upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
committerTomgamer <tomanhorak22@gmail.com>2026-11-22 16:32:05 +0100
commiteb35aed2e7e8ea1d4a11fd4e42ab80d853f05169 (patch)
tree22bd0e6fa6363235d1feedc1c9be678ab63bee4b
parent759a90c42e58886153f67dcd2d5d41c44face012 (diff)
parent4eb6155d3ac4f9d3fadb0d095c4ce13e76783615 (diff)
Merge origin/main into shader-309-wave64-lds-limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--.github/workflows/ci.yml7
-rw-r--r--CONTRIBUTING.md3
-rw-r--r--README.md2
-rw-r--r--docs/README.md7
-rw-r--r--docs/animation.md71
-rw-r--r--docs/audio.md27
-rw-r--r--docs/bvh.md25
-rw-r--r--docs/character_models.md33
-rw-r--r--docs/character_skeleton.md43
-rw-r--r--docs/d3d12_command_objects.md27
-rw-r--r--docs/d3d12_vulkan.md177
-rw-r--r--docs/descriptor_lookup_ada.md2
-rw-r--r--docs/descriptor_lookup_apple.md2
-rw-r--r--docs/design.md85
-rw-r--r--docs/embedded_shaders.md124
-rw-r--r--docs/fspx.md20
-rw-r--r--docs/i18n/README.md6
-rw-r--r--docs/i18n/ja/quickstart.md138
-rw-r--r--docs/i18n/pt-BR/quickstart.md18
-rw-r--r--docs/i18n/ru/quickstart.md157
-rw-r--r--docs/i18n/zh-CN/quickstart.md29
-rw-r--r--docs/mission_logic.md57
-rw-r--r--docs/models.md53
-rw-r--r--docs/pipeline_check.md38
-rw-r--r--docs/psin.md15
-rw-r--r--docs/rbf0.md8
-rw-r--r--docs/rpf.md7
-rw-r--r--docs/runtime_imports.md40
-rw-r--r--docs/saves.md7
-rw-r--r--docs/shader_validation.md131
-rw-r--r--docs/testing.md8
-rw-r--r--docs/world_names.md4
-rw-r--r--make_game.py45
-rw-r--r--runtime/CMakeLists.txt120
-rw-r--r--runtime/README.md8
-rw-r--r--runtime/shims/d3d12_com.cpp63
-rw-r--r--runtime/shims/d3d12_com.h6
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp451
-rw-r--r--runtime/shims/d3d12_xs_device.cpp188
-rw-r--r--runtime/shims/d3d12_xs_device.h32
-rw-r--r--runtime/shims/dxgi_com.cpp71
-rw-r--r--runtime/shims/file_system.cpp4
-rw-r--r--runtime/shims/process.cpp40
-rw-r--r--runtime/shims/xgameruntime.cpp261
-rw-r--r--runtime/src/base_reservation.h151
-rw-r--r--runtime/src/command_list.h36
-rw-r--r--runtime/src/descriptor_table.h24
-rw-r--r--runtime/src/main.cpp5
-rw-r--r--runtime/src/pe_loader.cpp8
-rw-r--r--runtime/src/vulkan13_features.h127
-rw-r--r--runtime/src/vulkan_backend.h78
-rw-r--r--runtime/src/vulkan_bindless.h80
-rw-r--r--runtime/src/vulkan_present.h34
-rw-r--r--runtime/src/vulkan_replay.h231
-rw-r--r--runtime/src/xdxr_build.comp87
-rw-r--r--runtime/src/xdxr_build.h94
-rw-r--r--runtime/src/xdxr_build.inc7493
-rw-r--r--runtime/test/allocator_proxy_test.cpp382
-rw-r--r--runtime/test/bindless_sizing_test.cpp31
-rw-r--r--runtime/test/bink_audio_test.cpp2
-rw-r--r--runtime/test/check_d3d12_trace.py2
-rw-r--r--runtime/test/check_texture_readback_sync.cmake3
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake34
-rw-r--r--runtime/test/d3d12_buffer_uav_test.cpp699
-rw-r--r--runtime/test/d3d12_compute_test.cpp183
-rw-r--r--runtime/test/d3d12_copy_compare.h25
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp77
-rw-r--r--runtime/test/d3d12_draw_test.cpp3
-rw-r--r--runtime/test/d3d12_gcl8_test.cpp4
-rw-r--r--runtime/test/d3d12_m2_textured_test.cpp24
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp395
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp316
-rw-r--r--runtime/test/d3d12_present_test.cpp13
-rw-r--r--runtime/test/d3d12_translated_draw_test.cpp26
-rw-r--r--runtime/test/d3d12_typeless_rtv_test.cpp249
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp673
-rw-r--r--runtime/test/d3d12_xdxr_rt_test.cpp157
-rw-r--r--runtime/test/descriptor_table_test.cpp51
-rw-r--r--runtime/test/device_proxy_test.cpp41
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp227
-rw-r--r--runtime/test/file_system_test.cpp11
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp21
-rw-r--r--runtime/test/fsr_dispatch_test.cpp4
-rw-r--r--runtime/test/glsl/cs_user_data.comp14
-rw-r--r--runtime/test/process_cmdline_test.cpp70
-rw-r--r--runtime/test/shader_library_corpus_test.cpp159
-rw-r--r--runtime/test/shaders/build.py45
-rw-r--r--runtime/test/shaders/check.py84
-rw-r--r--runtime/test/shaders/cs_buf_counter.asm40
-rw-r--r--runtime/test/shaders/cs_buf_typed.asm63
-rw-r--r--runtime/test/shaders/cs_lds_b64_cmpst.asm132
-rw-r--r--runtime/test/shaders/cs_m4_fill.asm51
-rw-r--r--runtime/test/shaders/cs_m4_indirect.asm28
-rw-r--r--runtime/test/shaders/cs_tbuffer_store.asm275
-rw-r--r--runtime/test/shaders/ps_imgatomic.asm44
-rw-r--r--runtime/test/shaders/ps_m2_uoff.asm5
-rw-r--r--runtime/test/shaders/ps_mandelbrot.asm46
-rw-r--r--runtime/test/shaders/ps_scc_logic32.asm44
-rw-r--r--runtime/test/shaders/ps_scc_logic64.asm49
-rw-r--r--runtime/test/shaders/vs_w64_a_skip.asm45
-rw-r--r--runtime/test/shaders/vs_w64_b_ballot_atomic.asm42
-rw-r--r--runtime/test/shaders/vs_w64_b_readlane_uniform.asm33
-rw-r--r--runtime/test/shaders/vs_w64_b_waterfall.asm35
-rw-r--r--runtime/test/shaders/vs_w64_c_bcnt_export.asm23
-rw-r--r--runtime/test/shaders/vs_w64_c_lane_id.asm21
-rw-r--r--runtime/test/shaders/vs_w64_c_readlane.asm23
-rw-r--r--runtime/test/shaders/w64_graphics.py98
-rw-r--r--runtime/test/typeless_rtv_test.cpp24
-rw-r--r--runtime/test/vk_bc_zero_init_test.cpp388
-rw-r--r--runtime/test/vk_bindless_test.cpp181
-rw-r--r--runtime/test/vk_descriptor_bench.cpp42
-rw-r--r--runtime/test/vk_harness.cpp23
-rw-r--r--runtime/test/vk_overlapping_occlusion_test.cpp74
-rw-r--r--runtime/test/vk_pipeline_check.cpp335
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp62
-rw-r--r--runtime/test/vk_test_device.h84
-rw-r--r--runtime/test/vk_xdxr_build_test.cpp183
-rw-r--r--runtime/test/xgameruntime_test.cpp158
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp93
-rw-r--r--scripts/audit_shader4_regs.py2
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/run_gpu_tests.py44
-rw-r--r--scripts/run_wine_tests.py2
-rw-r--r--tests/semantic/README.md4
-rw-r--r--tests/semantic/fixtures/disasm/cs_tbuffer_store.s233
-rw-r--r--tests/semantic/regen_fixtures.py1
-rw-r--r--tests/semantic/spirv_mini_interp.py30
-rw-r--r--tests/semantic/spirv_wave_interp.py5
-rw-r--r--tests/semantic/test_alu_add_co_clamp.py183
-rw-r--r--tests/semantic/test_alu_cvt_flr_rpi.py74
-rw-r--r--tests/semantic/test_alu_dot4_i8.py138
-rw-r--r--tests/semantic/test_buffer_format_narrow_int.py257
-rw-r--r--tests/semantic/test_buffer_load_format.py41
-rw-r--r--tests/semantic/test_f16_interp_fallback.py46
-rw-r--r--tests/semantic/test_interp_merge_check.py73
-rw-r--r--tests/semantic/test_interp_p1lv_f16.py14
-rw-r--r--tests/semantic/test_mask_src_sgpr_const.py114
-rw-r--r--tests/semantic/test_scalar_noop_waitcnt.py636
-rw-r--r--tests/semantic/test_tbuffer_store.py86
-rw-r--r--tests/semantic/test_valu_fma_mix.py66
-rw-r--r--tests/semantic/test_valu_fract_f16.py703
-rw-r--r--tests/semantic/test_valu_permlane16.py814
-rw-r--r--tests/semantic/test_valu_rcp_fdiv.py824
-rw-r--r--tests/test_anim_rigs.py134
-rw-r--r--tests/test_awc_names.py15
-rw-r--r--tests/test_awc_opus.py81
-rw-r--r--tests/test_bink_names.py12
-rw-r--r--tests/test_build_runtime_fallback.py5
-rw-r--r--tests/test_ctest_registration.py32
-rw-r--r--tests/test_d16_format_probe.py222
-rw-r--r--tests/test_d3d12_xs_surface.py5
-rw-r--r--tests/test_docs_design_rows.py64
-rw-r--r--tests/test_docs_list_items.py72
-rw-r--r--tests/test_docs_repo_paths.py79
-rw-r--r--tests/test_feature_scan.py94
-rw-r--r--tests/test_fma_mix_probe.py11
-rw-r--r--tests/test_fspx_unpack.py38
-rw-r--r--tests/test_gamedata_index.py19
-rw-r--r--tests/test_glb_writer.py19
-rw-r--r--tests/test_hashdict.py26
-rw-r--r--tests/test_imhex_patterns.py256
-rw-r--r--tests/test_int_hw_probe.py126
-rw-r--r--tests/test_lds_fuzz.py60
-rw-r--r--tests/test_lds_fuzz_hw.py4
-rw-r--r--tests/test_make_game_assets_pools.py2
-rw-r--r--tests/test_make_game_preflight.py36
-rw-r--r--tests/test_manifest.py53
-rw-r--r--tests/test_mission_tables.py235
-rw-r--r--tests/test_opus_tags.py11
-rw-r--r--tests/test_pe_inspect.py28
-rw-r--r--tests/test_pe_shader_containers.py171
-rw-r--r--tests/test_psin_names.py18
-rw-r--r--tests/test_rdna2spirv_cli.py51
-rw-r--r--tests/test_rdna2spirv_merge.py180
-rw-r--r--tests/test_save_keys.py5
-rw-r--r--tests/test_shader_build_fallbacks.py124
-rw-r--r--tests/test_shader_carve.py30
-rw-r--r--tests/test_shader_checks.py27
-rw-r--r--tests/test_spirv_metal_set0_aliases.py386
-rw-r--r--tests/test_spirv_metal_set0_extra.py1043
-rw-r--r--tests/test_text_tables.py56
-rw-r--r--tests/test_text_write_line_endings.py88
-rw-r--r--tests/test_tool_startup.py72
-rw-r--r--tests/test_user_sgpr_census.py58
-rw-r--r--tests/test_viewer_streaming.cjs16
-rw-r--r--tests/test_vk_pipeline_check_index.py65
-rw-r--r--tests/test_vk_pipeline_check_isolate.py129
-rw-r--r--tests/test_vk_subgroup_info.py61
-rw-r--r--tests/test_wave64_graphics_scan.py9
-rw-r--r--tests/test_wave64_halves_fixtures.py35
-rw-r--r--tests/test_world_index.py16
-rw-r--r--tests/test_world_lights_paths.py10
-rw-r--r--tests/test_world_names.py2
-rw-r--r--tools/ab_control_flow.py4
-rw-r--r--tools/analyze_4240_full.py2
-rw-r--r--tools/anim_clips.py2
-rw-r--r--tools/anim_index.py4
-rw-r--r--tools/anim_rigs.py172
-rw-r--r--tools/awc_names.py7
-rw-r--r--tools/awc_opus.py43
-rw-r--r--tools/bink_index.py2
-rw-r--r--tools/bink_names.py4
-rw-r--r--tools/bvh_index.py2
-rw-r--r--tools/calibrated_texture.py3
-rw-r--r--tools/cf_diff.py2
-rw-r--r--tools/classify_carve.py2
-rw-r--r--tools/crosslane_fuzz.py8
-rw-r--r--tools/d16_format_probe.py341
-rw-r--r--tools/f16_trans_sweep.py2
-rw-r--r--tools/f32_fuzz.py4
-rw-r--r--tools/feature_scan.py231
-rw-r--r--tools/fma_mix_probe.py4
-rw-r--r--tools/fspx_unpack.py19
-rw-r--r--tools/fssm_unpack.py2
-rw-r--r--tools/gamedata_graph.py2
-rw-r--r--tools/gamedata_index.py10
-rw-r--r--tools/gamedata_maps.py2
-rw-r--r--tools/gamedata_xml.py2
-rw-r--r--tools/glb_writer.py13
-rw-r--r--tools/hashdict.py17
-rw-r--r--tools/hw_oracle/runner.py2
-rw-r--r--tools/image_fuzz.py4
-rw-r--r--tools/imhex/psin.hexpat193
-rw-r--r--tools/imhex/rbf0.hexpat96
-rw-r--r--tools/imhex/rpf9.hexpat32
-rw-r--r--tools/instance_lists.py2
-rw-r--r--tools/int_hw_probe.py743
-rw-r--r--tools/lds_fuzz.py24
-rw-r--r--tools/manifest.py36
-rw-r--r--tools/mem_diff.py2
-rw-r--r--tools/meshlet_page.py4
-rw-r--r--tools/mission_tables.py524
-rw-r--r--tools/navmesh_decode.py2
-rw-r--r--tools/navmesh_index.py2
-rw-r--r--tools/opus_tags.py7
-rw-r--r--tools/page_index.py2
-rw-r--r--tools/pe_inspect.py8
-rw-r--r--tools/pe_shader_containers.py272
-rw-r--r--tools/psin_names.py7
-rw-r--r--tools/rbf0_index.py2
-rw-r--r--tools/rdna2spirv.py422
-rw-r--r--tools/restofworld_index.py2
-rw-r--r--tools/rpf9_carve.py2
-rw-r--r--tools/rpf9_names.py2
-rw-r--r--tools/rpf_probe.py2
-rw-r--r--tools/salu_diff.py9
-rw-r--r--tools/save_keys.py4
-rw-r--r--tools/saves.py12
-rw-r--r--tools/shader_carve.py5
-rw-r--r--tools/shader_diff.py2
-rw-r--r--tools/shader_disasm.py2
-rw-r--r--tools/shader_profile.py2
-rw-r--r--tools/skin_streams.py2
-rw-r--r--tools/spirv_gs_to_compute.py2
-rw-r--r--tools/spirv_metal_set0.py56
-rw-r--r--tools/story_index.py2
-rw-r--r--tools/tex_export.py2
-rw-r--r--tools/tex_headers.py2
-rw-r--r--tools/text_tables.py85
-rw-r--r--tools/ttpf_assets.py4
-rw-r--r--tools/ttpf_mips.py2
-rw-r--r--tools/turing_atlas.py4
-rw-r--r--tools/user_sgpr_census.py33
-rw-r--r--tools/valu_fuzz.py4
-rw-r--r--tools/vertex_types.py2
-rw-r--r--tools/vk_subgroup_info.py25
-rw-r--r--tools/wave64_graphics_scan.py10
-rw-r--r--tools/world_census.py2
-rw-r--r--tools/world_index.py23
-rw-r--r--tools/world_lights_paths.py11
-rw-r--r--tools/world_names.py2
-rw-r--r--tools/xdxr_bvh.py10
-rw-r--r--viewer/index.html11
273 files changed, 25774 insertions, 4520 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0154733a0..46156fef9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,6 +45,13 @@ jobs:
45 } 45 }
46 "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT 46 "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT
47 exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status. 47 exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status.
48 # A docs-only diff still needs the tests that read those documents: the link checker walks every tracked
49 # Markdown file, and the i18n index checks docs/i18n/README.md. Both are standard library only.
50 - name: Check documentation when only documentation changed
51 if: steps.paths.outputs.docs-only == 'true'
52 run: |
53 python3 -I tests/test_docs_links.py
54 python3 -I tests/test_i18n_index.py
48 55
49 check: 56 check:
50 needs: change-scope 57 needs: change-scope
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6a0a332a8..400e1d0d8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,6 +27,9 @@ methods are still open.
27## Working on the code 27## Working on the code
28 28
29- Python tools run with `python -I` and use only the standard library unless a file says otherwise. 29- Python tools run with `python -I` and use only the standard library unless a file says otherwise.
30- A text file a tool writes (JSON, CSV, a manifest, an assembly listing) names its line ending: `open(path, "w",
31 encoding="utf-8", newline="\n")`, so the output is LF on Windows too and the same input gives the same bytes on every
32 platform. `tests/test_text_write_line_endings.py` fails for a writer that forgets it.
30- `tools/rpf9dump` needs the submodule: `git submodule update --init`. 33- `tools/rpf9dump` needs the submodule: `git submodule update --init`.
31- A new shader-translator rule goes into the contract table in `docs/design.md`, with how it was confirmed: a GPU 34- A new shader-translator rule goes into the contract table in `docs/design.md`, with how it was confirmed: a GPU
32 test, a Mesa/LLVM reference, or a count over the corpus. 35 test, a Mesa/LLVM reference, or a count over the corpus.
diff --git a/README.md b/README.md
index b0430195a..a487c847f 100644
--- a/README.md
+++ b/README.md
@@ -47,7 +47,7 @@ work on booting can start as soon as one is available to a developer.
47| Booting, story mode, anything playable | ❌ No | 47| Booting, story mode, anything playable | ❌ No |
48| Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works | 48| Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works |
49| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 | 49| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 |
50| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after the SPIR-V ID-bound fix. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate | 50| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after `dcd8ecf` fixed the SPIR-V ID bound; the intervening `dedd75c` run was 26,501. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate |
51| Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output | 51| Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output |
52| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | 52| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet |
53| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) | 53| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) |
diff --git a/docs/README.md b/docs/README.md
index 57b9540a3..cb4a79cb9 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -17,8 +17,8 @@ method, scope and caveats. No game data is included.
17 17
18| Document | Measured content | 18| Document | Measured content |
19|---|---| 19|---|---|
20| [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. |
20| [models.md](models.md) | 382,781 models (2.64 billion triangles, 0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children and 55,417 fragments; the re-count table is in models.md. | 21| [models.md](models.md) | 382,781 models (2.64 billion triangles, 0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children and 55,417 fragments; the re-count table is in models.md. |
21| [models.md](models.md) | 350,251 models at the `917e9b9` pin, including 159,486 drawable-dictionary children; the `e293917` re-count adds 3,203 rows outside `levels.rpf`, almost all recovered fragments; `levels.rpf` recovers 343,327 models (+29,327) but was not fully exported. The per-archive table is in models.md. |
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). | 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). |
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 reference TRS is not the 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 reference TRS is not the bind pose. |
24| [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. | 24| [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. |
@@ -46,8 +46,6 @@ method, scope and caveats. No game data is included.
46| Document | Measured content | 46| Document | Measured content |
47|---|---| 47|---|---|
48| [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. | 48| [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. |
49| [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. |
50| [audio.md](audio.md) | AWC banks: Opus, PCM and XMA2; lossless Ogg Opus repack and WAV paths. |
51| [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. | 49| [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. |
52| [awc_shorts.md](awc_shorts.md) | Export short streamed-music idents/stings by duration; stereo-aware, no re-encode. | 50| [awc_shorts.md](awc_shorts.md) | Export short streamed-music idents/stings by duration; stereo-aware, no re-encode. |
53| [audio_config.md](audio_config.md) | The music/radio record table: 1,589 records, exact durations, AWC stream ids; no start offsets. | 51| [audio_config.md](audio_config.md) | The music/radio record table: 1,589 records, exact durations, AWC stream ids; no start offsets. |
@@ -73,9 +71,10 @@ method, scope and caveats. No game data is included.
73| [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`. | 71| [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`. |
74| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | 72| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. |
75| [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`. | 73| [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`. |
74| [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; 42/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the four rules still missing. |
76| [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. | 75| [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. |
77| [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. | 76| [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. |
78 77
79## Other languages 78## Other languages
80 79
81Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`fr`, `pt-BR`, `zh-CN`, `pl-PL`, `tr`). 80Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`fr`, `pt-BR`, `zh-CN`, `pl-PL`, `tr`, `ru`, `ja`).
diff --git a/docs/animation.md b/docs/animation.md
index 8cf132bd3..7dc30c950 100644
--- a/docs/animation.md
+++ b/docs/animation.md
@@ -278,7 +278,8 @@ blob to its last byte and confirms the counts above: 9 descriptors, 28,962 eleme
278string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes 278string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes
279on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group` 279on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group`
280text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field 280text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field
281semantics and the rig-to-skeleton link remain unresolved. 281semantics remain unresolved. The `Dictionary` text names one of the four rig dictionaries and `Rig` is a key
282there; see [Rig dictionaries](#rig-dictionaries).
282 283
283Mapping to the name tables: 284Mapping to the name tables:
284 285
@@ -328,7 +329,8 @@ are in the same stream. It is not a rig → skeleton link for RBF0:
328- The four motionmatcher paths are not in the 2,298 `.clip`/`.anim`/`.motion` name-table paths. 329- The four motionmatcher paths are not in the 2,298 `.clip`/`.anim`/`.motion` name-table paths.
329 330
330So RBF0 gives rig-set → source → rig, and the motion matcher resources show how a clip can carry its own bone 331So RBF0 gives rig-set → source → rig, and the motion matcher resources show how a clip can carry its own bone
331table. The link from an RBF0 rig to that table is still missing; it is the main unresolved binding. 332table. The RBF0 rig itself resolves into a rig dictionary ([Rig dictionaries](#rig-dictionaries)); what it does not
333give is a whole skeleton for the clips.
332 334
333### Magics not found 335### Magics not found
334 336
@@ -380,7 +382,8 @@ as a clip dictionary; all 36 do, so no root is left unresolved. That recovery ru
380has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page 382has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page
381map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in 383map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in
382a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip 384a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip
383dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, not decoded here), and 385dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, [decoded
386below](#rig-dictionaries) by `tools/anim_rigs.py`), and
3841 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages 3871 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages
385(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those 388(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those
386streams are: zero-prefix 66,115, raw 20,845, name-table 273, skeleton-names 1. 389streams are: zero-prefix 66,115, raw 20,845, name-table 273, skeleton-names 1.
@@ -595,6 +598,68 @@ one of the 1,902 hashes anim.rpf refers to without having them.
595python -I tools/anim_clips.py <package>\pack\story000\story000.rpf <work>\story000-clips.json --jobs 20 598python -I tools/anim_clips.py <package>\pack\story000\story000.rpf <work>\story000-clips.json --jobs 20
596``` 599```
597 600
601## Rig dictionaries
602
603`tools/anim_rigs.py` reads the four `RIG` roots above (ASSET-20). Run on the 1.0.2.1 copy:
604
605```powershell
606python -I tools/anim_index.py <package>\anim.rpf <work>\anim-index.json --rigs <work>\rigs.json
607python -I tools/anim_rigs.py <package>\anim.rpf <work>\anim-rigs.json --rigs <work>\rigs.json
608```
609
610The output holds counts and one row per rig dictionary (offset, name, hash, entry count), no table items.
611
612**Layout.** The root is the clip dictionary's: `+0x38` atString name, `+0x48` atMap, `+0x68` `joaat32(name)` (4 of
6134), and at `+0x70` the bytes `RIG` and a version byte (2 in all four). Every map key has a zero high half (3,897 of
6143,897). Every map value has a pointer at `+0x20` to a **`RIG` block** (3,897 of 3,897): `RIG`, a version byte (2),
615a u32 length of what follows, then tables `{u32 kind hash; u32 size = 0xC + 8 × count; u32 count; u32 word}`, each
616followed by `count` 8-byte items `{u32 hash; u32 word}`, with other bytes between the tables. The other bytes and
617the item words are not mapped.
618
619**The four dictionaries are the four RBF0 sources.** Their names are the four source strings of the rig-set
620manager:
621
622| Name | Entries | Keys that are `joaat32` of an RBF0 rig |
623|---|---:|---:|
624| `canonical@legacy` | 22 | 16 |
625| `canonical@source` | 543 | 534 |
626| `generated@source` | 1,256 | 1,188 |
627| `pipelined@source` | 2,076 | 1,931 |
628
629These are the distinct-rig counts per source in [the RBF0 table above](#tail-rbf0-rig-set-manager). The other 228
630keys are not named by any RBF0 entry. **All 6,677 RBF0 entries resolve**: the entry's `Dictionary` text is the
631rig dictionary's name, and `joaat32(lowercase Rig path)` is a key in it (6,677 of 6,677; 0 in another dictionary,
6320 missing). So a rig set reaches its rigs' `RIG` blocks through rig-set → `{Dictionary, Rig}` → rig dictionary →
633key → `+0x20`.
634
635**Tables.** 6,606 tables are found in the 3,897 blocks. Four kind hashes hold all but 5 of them; the 5 are single
636hits whose "kind" is an f32 near 1.0 (`0x3f7f....`, `0x3f76....`) or a small integer, so they are float data that
637happens to fit the header rule. The kind names are not resolved:
638
639| Kind | Tables | Items | Items that are a clip track's bone hash |
640|---|---:|---:|---:|
641| `0x74d00508` | 2,642 | 13,210 | 0 |
642| `0x2316833f` | 2,437 | 118,853 | 91,559 |
643| `0xb688b77e` | 1,427 | 72,528 | 39,880 |
644| `0x5e25d3bf` | 95 | 4,416 | 0 |
645
646"A clip track's bone hash" means the hash is the bone of some track in the 191,042 decoded animations.
647
648**Rigs are not the clips' skeletons.** The clip side was measured with a local script over the same
649`anim_clips.py` parse: for each of the 52,752 clip dictionaries with bone tracks, the union of its
650`bonerotation`/`bonetranslation` bone hashes (mover track 0 left out).
651
652- Against the 596 hashed names of the shared humanoid skeleton ([character_skeleton.md](character_skeleton.md)),
653 44,359 dictionaries have at least 90% of their bones in it (16 have all of them).
654- Against the rigs (the items of the two bone-bearing kinds above), no rig set covers the clips of a humanoid
655 dictionary. Even the union over all the rigs of one rig set reaches 80% of a dictionary's bones for 11 of those
656 44,359. Only 4 dictionaries, all of objects, are covered completely by a rig set.
657
658So humanoid clips bind to the fragment skeleton, not to a `RIG` block. The rig tables look like per-rig bone or
659channel subsets (the RBF0 groups are `deformation`, `pose`, `identity`, `facial` and others); that reading is not
660measured. Still open in ASSET-20: the `0DRP` "2/3 packed clip streams" ([above](#packed-clip-streams)) and which
661model or skeleton each non-humanoid clip dictionary drives.
662
598## Readable, compressed and still opaque 663## Readable, compressed and still opaque
599 664
600- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers, 665- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers,
diff --git a/docs/audio.md b/docs/audio.md
index ffc6c66b4..d02f07d07 100644
--- a/docs/audio.md
+++ b/docs/audio.md
@@ -88,15 +88,23 @@ The exporters ignore the remaining bytes.
88| `5` | XMA2 | `.xma.wav`, RIFF XMA2; ffmpeg decodes it to PCM WAV | 88| `5` | XMA2 | `.xma.wav`, RIFF XMA2; ffmpeg decodes it to PCM WAV |
89 89
90Opus data is stored in 2048-byte blocks. Each block is a sequence of `[u16 length][packet]`; a zero length pads 90Opus data is stored in 2048-byte blocks. Each block is a sequence of `[u16 length][packet]`; a zero length pads
91the rest of the block. The first 312 decoded samples are the encoder's lookahead (libopus at 48 kHz); the AWC does 91the rest of the block. The first 312 decoded samples are the encoder's lookahead. Measured on 30 real streams from
92not store it, so the exporter writes that value as `OpusHead` pre-skip and sets the last page's granule to 92four banks: decoded with pre-skip 0, the 5% and 10% attack points are at 312 samples (median 312; the 10% point
93`pre-skip + declared samples`. Decoders then drop the priming and stop at the real end instead of the padded final 93ranges 278..868, none near 1920), so 312 is the exporter's default. The AWC does not store the value, so
94frame. `--pre-skip` overrides the 312 default for a stream encoded with a different lookahead. 94`--pre-skip` overrides it for a stream encoded with a different lookahead.
95
96The exporter writes that value as `OpusHead` pre-skip and emits the EOS page at the first packet that reaches
97`pre-skip + declared samples`; later packets are encoder padding and are dropped. Clamping only the last page
98would let its granule go backwards when the trim point falls before that page starts, and decoders would keep the
99excess: a 27-packet real-libopus fixture decoded 24,960 frames for 24,000 declared, while the reaching-packet
100form decodes exactly 24,000. An oversized `--pre-skip` is clamped to the stream length so the final granule never
101falls below it.
95 102
96The format tag's sample count is already in 48 kHz frames even when its rate field is 32 kHz, and `+0x0C` is the 103The format tag's sample count is already in 48 kHz frames even when its rate field is 32 kHz, and `+0x0C` is the
97per-channel frame count (equal to `+0` for mono and half of it for stereo in all 7,451 measured streams). The 104per-channel frame count (equal to `+0` for mono and half of it for stereo in all 7,451 measured streams, 0.5% of
98exporter uses `+0x0C` and falls back to `+0 / channels` when a block leaves it zero; it never scales either count 105the 1.6M-stream corpus). The exporter uses `+0x0C` only when it agrees with `+0` (`frames * channels == samples`)
99by the rate field, because scaling a 32 kHz stream by 48000/32000 leaves up to a frame of padding untrimmed. 106and otherwise falls back to `+0 / channels`, so a malformed block cannot silently truncate audio. It never scales
107either count by the rate field, because scaling a 32 kHz stream by 48000/32000 leaves padding untrimmed.
100 108
101Codec `5` is not handled by `tools/awc_opus.py`. `rpf9dump xma` writes it as RIFF XMA2, and ffmpeg does the decode. 109Codec `5` is not handled by `tools/awc_opus.py`. `rpf9dump xma` writes it as RIFF XMA2, and ffmpeg does the decode.
102 110
@@ -331,7 +339,10 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru
331 339
332## What has been checked 340## What has been checked
333 341
334- 300 random Opus streams decode with ffmpeg with no errors; their lengths match the declared sample counts. 342- 20 real Opus streams (6 at 48 kHz, 14 at 32 kHz) decode with ffmpeg to exactly their declared
343 per-channel frame counts after the EOS fix; 300 random streams decode with no errors. The earlier
344 "lengths match" check read the granule-derived duration, not decoded frames, so it did not catch
345 the backwards-EOS case.
335- All 1,818 XMA2 streams decode after `rpf9dump xma`. 346- All 1,818 XMA2 streams decode after `rpf9dump xma`.
336- A 4-channel streamed-music bank gives four 42.0 s mono channels with real levels and no decoder errors. 347- A 4-channel streamed-music bank gives four 42.0 s mono channels with real levels and no decoder errors.
337- A 1-channel streamed-music descriptor can carry stereo Opus packets; it exports as one stereo Ogg with the 348- A 1-channel streamed-music descriptor can carry stereo Opus packets; it exports as one stereo Ogg with the
diff --git a/docs/bvh.md b/docs/bvh.md
index 23e046221..3c6e99ecc 100644
--- a/docs/bvh.md
+++ b/docs/bvh.md
@@ -339,8 +339,9 @@ the destination buffer:
339 339
3401. one thread per triangle (TRI0 leaves, remap `0x09`) or per instance (128-byte records, the world-to-object 3401. one thread per triangle (TRI0 leaves, remap `0x09`) or per instance (128-byte records, the world-to-object
341 inverse, the BLAS root and identity-rotation flag); 341 inverse, the BLAS root and identity-rotation flag);
3422. a 30-bit Morton key of each box centre, then a stable radix sort: 8 passes of 4-bit digits, 24 dispatches 3422. a 30-bit Morton key of each box centre, then a stable sort: up to 1,024 keys in one workgroup's shared memory
343 whatever the count, with no padding to a power of two; 343 (one dispatch), more with a radix sort of 8 passes of 4-bit digits over 256-element tiles (24 dispatches
344 whatever the count, no padding to a power of two);
3443. BOX32 nodes, built level by level from four consecutive sorted children, with the parent table and each 3453. BOX32 nodes, built level by level from four consecutive sorted children, with the parent table and each
345 instance's `ParentNode`; 346 instance's `ParentNode`;
3464. the header. 3474. the header.
@@ -360,8 +361,24 @@ them the same way.
360scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as 361scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against brute force. `ctest` runs both as
361`xdxr_build` and `xdxr_build_check`. 362`xdxr_build` and `xdxr_build_check`.
362 363
363Not done yet: pairing triangles into TRI1 leaves, BOX16 nodes, updates, compaction and copies. A higher-quality 364**Updates** (D3D12 `PERFORM_UPDATE`) refit: the source structure is copied to the destination unless it is the
364build (SAH) would also come later. 365destination, the elements are rewritten at their slots, and each node's boxes are recomputed bottom-up from the
366children it already points to. The tree is kept, so a refit is valid for any motion and skips the Morton pass and
367the 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
368a build, but the tree traverses more slowly as the geometry moves away from where it was built.
369
370**Copies and postbuild info.** `CopyRaytracingAccelerationStructure` with `CLONE` or `COMPACT` copies the
371structure's bytes. The records are position-independent: node pointers count from the structure's start, and a TLAS
372names its BLASes by address, which a clone keeps. The size comes from the source header (`totalSizeIn64BNodes`), so
373a copy can follow a build in the same command list, and it is bounded by the destination resource. A build is
374already exactly its layout's size, so `COMPACTED_SIZE` and `CURRENT_SIZE` (from
375`EmitRaytracingAccelerationStructurePostbuildInfo` or the postbuild descs of a build) are both
376`totalSizeIn64BNodes * 64`, and compaction saves nothing. Serialization, deserialization and the tools-visualization
377mode are refused at replay as unsupported, not faked. In `LEONIDA_RT_AS=khr` mode the postbuild descs stay ignored,
378as before.
379
380Not done yet: pairing triangles into TRI1 leaves, BOX16 nodes, serialization. A higher-quality build (SAH) would also
381come later.
365 382
366```powershell 383```powershell
367python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force 384python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force
diff --git a/docs/character_models.md b/docs/character_models.md
index 1838a0522..e3b5eb575 100644
--- a/docs/character_models.md
+++ b/docs/character_models.md
@@ -45,7 +45,11 @@ The decoded export used by the previews contains 13 parts:
45 45
46Two caveats that matter for any render: 46Two caveats that matter for any render:
47 47
48- **`body` is not a base body.** The only Lucia full-body record in `packs.rpf` is the 48- **`body` is the shared player/cutscene body.** The only `lucia`-named full-body record in
49 `packs.rpf` is `cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full` (874- and 640-vertex rows;
50 1,748 / 1,816 decoded). Its `FragName` is byte-identical to `cs_monalisa` and `cs_mandy`, so it
51 is the shared player/cutscene body, not a unique high-detail mesh. Do not present it as a
52 high-detail hero body.
49- **`body` is not a base body.** The only `lucia`-named full-body record in `packs.rpf` is the 53- **`body` is not a base body.** The only `lucia`-named full-body record in `packs.rpf` is the
50 `cs_lucia_legacypedcs` clothed legacy ped. The decoded part is 1,748 vertices / 1,816 54 `cs_lucia_legacypedcs` clothed legacy ped. The decoded part is 1,748 vertices / 1,816
51 triangles, and the manifest lists 874- and 640-vertex rows of the same drawable. Do not present 55 triangles, and the manifest lists 874- and 640-vertex rows of the same drawable. Do not present
@@ -126,6 +130,26 @@ have **no albedo**, so a preview must render them as clay rather than invent a c
126 The blue in an earlier preview came from the authored `baseColorFactor` `(0.200, 0.270, 0.400)`, 130 The blue in an earlier preview came from the authored `baseColorFactor` `(0.200, 0.270, 0.400)`,
127 not from this atlas. 131 not from this atlas.
128 132
133## Bodies
134
135A geometry-first census — every `packs.rpf` drawable and fragment, all 50,802 `levels.rpf`
136fragments, 178,073 of 184,778 `levels.rpf` drawables (96.4%; the 6,705 above 3 MB were not
137decoded), all 4,195 `story000.rpf` drawables, and the `anim.rpf` rig dictionaries — found no
138Lucia or Mandy body. `story000.rpf` is mission map cells, not ped actors, and `anim.rpf`'s
139`LOD0_Body_Shapes_Female` is a rig program with no mesh.
140
141The only **nude** continuous human-skeleton meshes are a **generic female mannequin** in
142`levels.rpf`: `gmt_mannequin_proxy_f_01a` (15,488 vertices / 27,725 triangles, 95 bones,
1431.72 m, A-pose) and `gmt_mannequin_f_01b` (the same body posed mid-stride). It has no Lucia or
144Mandy name or texture link, and its rig is a clothing form, not the 596-bone ped skeleton (78
145of 95 bone names are shared, with mirrored limb pivots), so it is a base proxy for a
146reconstruction, not Lucia's body.
147
148The player and cutscene body is a separate shared **clothed** fragment,
149`cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full` (874 v), used by `cs_lucia`, `cs_monalisa`
150and `cs_mandy` (their `FragName` is identical). It is the body the game uses; it is low-poly and
151clothed, so it is not a high-detail nude body.
152
129## What is not decoded 153## What is not decoded
130 154
131- **Fragment children.** All 2,865 fragments export as the 25-vertex bounds cube described above. 155- **Fragment children.** All 2,865 fragments export as the 25-vertex bounds cube described above.
@@ -154,8 +178,11 @@ have **no albedo**, so a preview must render them as clay rather than invent a c
154 placeholders. Across all characters, 241 of 329 hair rows are 3-vertex placeholders, but 68 178 placeholders. Across all characters, 241 of 329 hair rows are 3-vertex placeholders, but 68
155 have more than 100 vertices, so real hair geometry does exist for some characters. A static 179 have more than 100 vertices, so real hair geometry does exist for some characters. A static
156 export of Lucia is bald by design, not by a missing decode. 180 export of Lucia is bald by design, not by a missing decode.
157- **`levels.rpf` names.** The archive has not been name-enumerated in this workspace; the negative 181- **`levels.rpf`.** The full archive was name-enumerated: 1,116,073 streams, 98.32% inflated,
158 for a Lucia body is scoped to the named `packs.rpf` records above. 182 235,814 named streams, 318,266 unique names. It contains no Lucia, Mandy, `player_story` or
183 `ambient_female` drawable; the Lucia and Mandy hits are props (photos, frames, luggage, a
184 curtain). The only human-skeleton meshes in `levels.rpf` are the generic mannequin pair in
185 **Bodies**.
159- **Bind pose and full skinning.** The delivered GLBs use identity inverse-bind matrices and do 186- **Bind pose and full skinning.** The delivered GLBs use identity inverse-bind matrices and do
160 not apply the 8-influence bone-palette skinning. Prior art places inverse bind matrices at the 187 not apply the 8-influence bone-palette skinning. Prior art places inverse bind matrices at the
161 skeleton header `+0x08`; that is not yet reproduced here, so the reference TRS remains the only 188 skeleton header `+0x08`; that is not yet reproduced here, so the reference TRS remains the only
diff --git a/docs/character_skeleton.md b/docs/character_skeleton.md
index db9e78b71..489a21c94 100644
--- a/docs/character_skeleton.md
+++ b/docs/character_skeleton.md
@@ -229,10 +229,53 @@ The name controls resolve `cs_kenton`, `u_f_o_rhonda`, `cs_monalisa` and `cs_luc
229not. The delivered `mandy/` preview export is therefore a clearly labelled `cs_monalisa` proxy, 229not. The delivered `mandy/` preview export is therefore a clearly labelled `cs_monalisa` proxy,
230not a verified Mandy model. 230not a verified Mandy model.
231 231
232Two further checks refine that negative. A missing `mandy` name is the common case, not an
233anomaly: of the 13 `KeyLento/Perschars/Peds/Unique` entries, two resolve cleanly by name
234(`kenton` -> `cs_kenton`, `rhonda` -> `u_f_o_rhonda`), one plausibly maps (`Bert` ->
235`hc_cs_herbert_watson`), and the other ten, including `Mandy`, have no name hit. Also, the
236package manifest lists 108 files and its `pack/` directory contains only `story000`,
237`core_restofworld`, `core_restofworld001`, `shared_minigame000` and their `_bvh4`/`_licenses`
238companions; there is no `psp_*` archive, so the `PSP_KeyLento_perschars_peds` pack named by the
239schedule is not present in this build. Mandy is therefore not disproven: her appearance is either
240a generic ped assembled at runtime or in a pack this package does not include.
241
232Caveats: `levels.rpf` was prefix-bounded at 4 MiB per inflated stream, raw RSC8 bodies and 242Caveats: `levels.rpf` was prefix-bounded at 4 MiB per inflated stream, raw RSC8 bodies and
233Bink/opaque regions were not decoded, and the encrypted RPF9 table of contents prevents a full 243Bink/opaque regions were not decoded, and the encrypted RPF9 table of contents prevents a full
234path enumeration (27 top-level entries remain). The evidence supports a shared ped-appearance 244path enumeration (27 top-level entries remain). The evidence supports a shared ped-appearance
235actor assembled from existing components, not a unique `mandy` resource. 245actor assembled from existing components, not a unique `mandy` resource.
246The mission binding is now measured. `COM_KBOS_NEIGHB` is the internal id of the "Pipework"
247mission: the replay table carries that `<MissionId>`, and the mission text names "Mandy's
248house", "Follow Mandy" and "Bert died". Five PSIN state tables in
249`pack/story000/story000_script.rpf` (`03fe4000`, `03fe8000`, `03feb000`, `03fee000`,
250`03ff0000`) contain both characters as entity link hashes: `0x03A885E6` (`Mandy`) and
251`0xE34ACBC8` (`Bert`); the schedule pack hash is `0x865F0DA9`
252(`PSP_KeyLento_perschars_peds`).
253
254The model binding is also decoded. `PERSCHARS_INFO` (`data.rpf@0x1AA5F000`, record 3499) maps
255`Name = 0x03A885E6` (`mandy`) to `ModelSetName = 0x03A885E6`; `CPedModelInfo__InitData`
256(`packs.rpf@0x11D1FF000`, record 1219) maps that link to `cs_mandy` (`0xD7C0CDFF`). `cs_mandy`
257is a live model id — a `story000.rpf` cutscene actor/voice table uses it — but there is **no
258named `cs_mandy` drawable**. Its 64-bit `ModelName` is `0x009B33B7D7C0CDFF`, and its `FragName`
259`0xC9888B65009B33B7` is byte-identical to `cs_lucia` and `cs_monalisa`: the shared female
260cutscene-ped fragment set. The realistic full-body in that family is `cs_lucia_legacypedcs`
261(874 v), so Mandy uses the same body as Lucia. Her nine-entry variation table has 18 u32 hashes;
26216 are unique to her, but none resolves to a shipped drawable or texture name.
263
264The entities linked to Mandy carry three different per-state archetype hashes
265(`0x18BB2550`, `0x73E83886`, `0x57DDFFC2`), which fits her outfit changing between states, not
266three models. None of those hashes resolves through the package name dictionary, any drawable
267or prop name pool, the `packs.rpf` PSOs, or a `0x7a` meta hash scan, so they are state/archetype
268ids, not model names. The archetype-to-component-set table is not in the readable archives;
269whether it is in the missing executable or an undecoded store is not established.
270
271`Mandy_FirstTingle`, `Mandy_ComingUp` and `Drug_Mandy_*` in `common.rpf` are MDMA drug effects,
272not the character. They are a red herring in any `mandy` name search.
273
274Caveats: the RPF9 table of contents is still not decoded; names come from carving and recovery
275(318,266 unique `levels.rpf` names, 24,034 `packs.rpf` names), and raw RSC8 bodies and
276Bink/opaque regions were not decoded. The evidence supports a shared ped-appearance actor: a
277`cs_mandy` model id, a body fragment shared with `cs_lucia` and `cs_monalisa`, and a variation
278table, not a unique `mandy` drawable.
236 279
237## Reproduction 280## Reproduction
238 281
diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md
index a55c3d964..93f0b39a0 100644
--- a/docs/d3d12_command_objects.md
+++ b/docs/d3d12_command_objects.md
@@ -371,9 +371,10 @@ vtable pointer of a public object.
371- **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)` 371- **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)`
372 with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the 372 with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the
373 root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1 373 root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1
374 at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy used to 374 at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy maps the
375 forward it to the PC method at the same index; it now refuses it (`E_NOTIMPL`). When it fails, the DLL takes 375 console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to `CreateComputePipelineState` (PC slot 11). On a
376 slot 62; its message for that failure calls the fallback "NewBE". 376 PC device that call fails (`E_FAIL`) because the code is not a PC shader, so the DLL falls back to slot 62; its message
377 for that failure calls the fallback "NewBE".
377- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC 378- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC
378 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns 379 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns
379 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a 380 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a
@@ -563,6 +564,26 @@ Queues and fences are wrapped the same way.
563 and a heap proxy given to a list's `SetDescriptorHeaps` reaches the real list unchanged. The command-list 564 and a heap proxy given to a list's `SetDescriptorHeaps` reaches the real list unchanged. The command-list
564 proxy of §3.5a adds the unwrap at both places. 565 proxy of §3.5a adds the unwrap at both places.
565 566
567Command allocators get the same kind of proxy: device slot 9 (`CreateCommandAllocator`) returns one.
568
569- **What is forwarded.** The public chain, 9 slots: the base chain and `Reset` at 8. A slot past it, up to the
570 end of a 64-slot table, is logged and refused, and a read past the table faults in its own guard region.
571 The console allocator's extra methods are not measured.
572- **Where a list takes it.** A list takes an allocator from the title in `CreateCommandList` and `Reset`, so
573 the proxy is safe only where the list side resolves it. Slot 9 therefore wraps an allocator only when it
574 answers `kLeonidaCommandAllocatorTag` (`d3d12_xs_device.h`). That is the Vulkan layer's own allocator, whose
575 `CommandAllocator::from()` resolves the proxy for both list calls.
576- **On the host runtime.** A PC runtime allocator comes back unwrapped, logged once, because the PC runtime's
577 lists would take a proxy for their own allocator. A command-list proxy that unwraps at `Reset` (§3.5a) is
578 what lets the host backend wrap allocators too.
579- **Residency.** An allocator is a pageable, so `MakeResident`/`Evict`/`SetResidencyPriority`/
580 `EnqueueMakeResident` unwrap allocator proxies like heap, queue and fence proxies.
581
582`allocator_proxy_test` checks this on the Vulkan device and on the host runtime, and the mock test checks it
583over allocators with and without the tag. On the Vulkan device it checks forwarding, the refused tail, the guard
584region, identity, and D3D12's allocator rules through the proxy, and runs a list created and `Reset` on the
585proxy whose copies go through the queue and fence proxies and are read back.
586
566Which of this is measured: the slot numbers and signatures are the SDK's (public). That the console 587Which of this is measured: the slot numbers and signatures are the SDK's (public). That the console
567keeps the public queue and fence slots, and device slots 8/32/36/75, is an assumption the package cannot 588keeps the public queue and fence slots, and device slots 8/32/36/75, is an assumption the package cannot
568test, as above. The proxies make a wrong assumption visible in the log; they do not prove it right. 589test, as above. The proxies make a wrong assumption visible in the log; they do not prove it right.
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index e96dcae72..d30229138 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -300,8 +300,6 @@ What is implemented (all of it testable without the game):
300 yet; 300 yet;
301 - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE2D`, `TEXTURE2DMS`, 301 - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE2D`, `TEXTURE2DMS`,
302 `TEXTURE2DARRAY` and `TEXTURE2DMSARRAY` (a slice range; 1D and 1D-array DSVs wait for 1D textures, D3D-63); 302 `TEXTURE2DARRAY` and `TEXTURE2DMSARRAY` (a slice range; 1D and 1D-array DSVs wait for 1D textures, D3D-63);
303 - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE2D`, `TEXTURE2DMS` and
304 `TEXTURE2DARRAY`;
305 - `CopyDescriptors` / `CopyDescriptorsSimple`. A descriptor is the bytes of its slot, so a copy is a byte copy: 303 - `CopyDescriptors` / `CopyDescriptorsSimple`. A descriptor is the bytes of its slot, so a copy is a byte copy:
306 the destination and source range lists are walked together, one descriptor at a time, and null size arrays 304 the destination and source range lists are walked together, one descriptor at a time, and null size arrays
307 mean one descriptor per range; 305 mean one descriptor per range;
@@ -380,7 +378,9 @@ What is implemented (all of it testable without the game):
380 | `CreateCommandQueue1`'s creator ID | ignored | 378 | `CreateCommandQueue1`'s creator ID | ignored |
381 379
382 `CreatePlacedResource1/2` wrap the placed path above; `2` carries the castable-format list. `CreateHeap1` 380 `CreatePlacedResource1/2` wrap the placed path above; `2` carries the castable-format list. `CreateHeap1`
383 remains a stub. 381 wraps `CreateHeap` and refuses a protected session. Both refuse, as the host does (RX 5700 and WARP, D3D-238),
382 an alignment other than 0, 64 KiB and 4 MiB, a heap type outside the enum, a custom heap without a CPU page
383 property and memory pool or a non-custom heap with either, and a heap with all three `DENY_*` flags.
384 - `CreateSampler2` as a wrapper over `CreateSampler` (D3D-28, part 2). Without flags it writes the same S#. 384 - `CreateSampler2` as a wrapper over `CreateSampler` (D3D-28, part 2). Without flags it writes the same S#.
385 `D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR` reads the union as integers. `(0,0,0,0)`, `(0,0,0,1)` and `(1,1,1,1)` 385 `D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR` reads the union as integers. `(0,0,0,0)`, `(0,0,0,1)` and `(1,1,1,1)`
386 take the S#'s transparent-black, opaque-black and opaque-white types. The S# has no separate integer types, 386 take the S#'s transparent-black, opaque-black and opaque-white types. The S# has no separate integer types,
@@ -477,7 +477,9 @@ side inwards:
477 477
478 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within 478 Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within
479 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be 479 `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be
480 supported. The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type 480 supported: past it, the device grows only where `vkGetDescriptorSetLayoutSupport` accepts the grown layout.
481 Intel's UHD 770 (101.7092) reports 6159 and accepts the full sizes, so it gets the same set as an RTX (D3D-219).
482 The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type
481 and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 483 and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793
482 descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and 484 descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and
483 `bindless_sizing_test` checks the rules on synthetic limits. 485 `bindless_sizing_test` checks the rules on synthetic limits.
@@ -496,9 +498,12 @@ side inwards:
496 - `flush()` also uploads the table to its buffer: device-local memory, written from a mapped staging copy when 498 - `flush()` also uploads the table to its buffer: device-local memory, written from a mapped staging copy when
497 the buffers are created (first use or growth) and with `vkCmdUpdateBuffer` for slot changes. Adding a key only 499 the buffers are created (first use or growth) and with `vkCmdUpdateBuffer` for slot changes. Adding a key only
498 puts a new entry in an empty slot, and the copy of an entry is not atomic; a running lookup that does not know 500 puts a new entry in an empty slot, and the copy of an entry is not atomic; a running lookup that does not know
499 the key cannot resolve to it, which is accepted. Erasing a key compacts its probe cluster, which moves other 501 the key cannot resolve to it, which is accepted. Erasing a key empties its slot and moves no other entry
500 keys' entries, and a table that has grown gets a new buffer behind binding 2: `flush_needs_idle()` says when a 502 (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is
501 flush would do either, and the device waits for the queue before flushing in that case. 503 uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that
504 has grown (a new buffer behind binding 2) change what running lookups see: `flush_needs_idle()` says when a
505 flush would do one of those, and the device waits for the queue before flushing in that case. Erasing used to
506 compact the probe cluster, which moved other keys and made every texture release wait for the whole GPU.
502- **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with 507- **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with
503 their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's 508 their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's
504 (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits 509 (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits
@@ -541,8 +546,9 @@ which has one array layer. `d3d12_descriptor_test` checks samples at four W coor
541volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_view_min_lod`, at or below 546volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_view_min_lod`, at or below
542`MostDetailedMip`, and above the last mip). 547`MostDetailedMip`, and above the last mip).
543 548
544Known gaps in the descriptor path: buffer shader-resource and unordered-access views and constant-buffer views 549Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views (the V# a shader would
545(the V# a shader would load for them; the structure is in `gfx10_descriptors.h`, the views are not written); 550load for them; the structure is in `gfx10_descriptors.h`, the views are not written; buffer UAVs of every kind are,
551section 3.4 "Buffer UAVs", `d3d12_m4_compute_test` and `d3d12_buffer_uav_test`);
5461D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless 5521D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless
547color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, 553color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`,
548`R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the 554`R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the
@@ -669,8 +675,9 @@ The compute path, end to end:
669 place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA; 675 place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA;
670 tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures are backed the same way with 676 tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures are backed the same way with
671 tile-multiple `GetResourceAllocationInfo`, `GetResourceTiling`, and host-matched `E_INVALIDARG` checks 677 tile-multiple `GetResourceAllocationInfo`, `GetResourceTiling`, and host-matched `E_INVALIDARG` checks
672 (D3D-191). `CreatePlacedResource2`'s castable-format list reaches the placed texture's image as the committed 678 (D3D-191). Multisampled 2D placed textures (`UNKNOWN` and `4x` tiled) share that backing with host-matched heap
673 path's does (D3D-90). 679 and offset alignment checks (`4 MiB` vs `64 KiB`, `D3D-222`). `CreatePlacedResource2`'s castable-format list
680 reaches the placed texture's image as the committed path's does (D3D-90).
674 681
675Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and 682Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and
676therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines, 683therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines,
@@ -1041,7 +1048,7 @@ The layer therefore owns the console VAs. It returns them from `ID3D12Resource::
1041| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. | 1048| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. |
1042| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. | 1049| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. |
1043| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. | 1050| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. |
1044| 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 gets its own `VkDeviceMemory` and a null VA, as in D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures share that backing and answer `GetResourceAllocationInfo` and `GetResourceTiling` (D3D-191). | 1051| 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 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. |
1045| 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. | 1052| 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. |
1046| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. | 1053| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. |
1047| 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). | 1054| 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). |
@@ -1145,6 +1152,38 @@ The layer's descriptor model:
1145 - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index; 1152 - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index;
1146 - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index; 1153 - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index;
1147 - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences. 1154 - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences.
1155- **Buffer UAVs.** `CreateUnorderedAccessView` on a buffer writes a V# in the first 16 bytes of the slot (the rest of
1156 the 32 bytes is zero): `BASE_ADDRESS` = the resource's GPU VA + `FirstElement` * the element size, and by view kind
1157 - *raw* (`R32_TYPELESS` + `RAW`): stride 0, `NUM_RECORDS` = bytes, `OOB_SELECT` 3 (raw);
1158 - *structured* (`UNKNOWN` + `StructureByteStride`): stride, `NUM_RECORDS` = records, `OOB_SELECT` 0;
1159 - *typed* (any other format the typed-UAV table has: `uav_clear.h` layouts that `gfx10_descriptors.h`'s
1160 `format_table` names with a code below 128): `FORMAT` = the `GFX10_FORMAT_*` code, stride = the element size in
1161 bytes, `NUM_RECORDS` = elements, `DST_SEL` = the format's own channel order (`format_swizzle`: R8 reads as
1162 (x, 0, 0, 1), B8G8R8A8 as (z, y, x, w)), `OOB_SELECT` 1 (structured: only the index is checked against
1163 `NUM_RECORDS`, `docs/buffer_bounds.md`). This is what `buffer_load_format_*` / `buffer_store_format_*` / the
1164 `buffer_atomic_*` of a translated `RWBuffer<T>` read; the translator decodes the element from the V#'s `FORMAT`
1165 at run time (`rdna2spirv.py` `FORMATS`) and bounds-checks the whole element against `NUM_RECORDS`. A format the
1166 layer cannot name (a typeless or 96-bit one, a compressed one, anything whose code is 128 or more, `R16G16_SNORM`
1167 and the other texture formats `vulkan_format` has no row for) leaves a null slot, logged once. Typed clears
1168 (`ClearUnorderedAccessViewUint/Float`) read the same V# back, so they work on these views and on game-built ones.
1169 - **UAV counters** (`pCounterResource` + `CounterOffsetInBytes`, structured views only). D3D12 keeps the counter in
1170 an application-visible buffer: there is no `CopyStructureCount` (that is D3D11); a game copies the counter with
1171 `CopyBufferRegion` from `pCounterResource` at `CounterOffsetInBytes` (this is "CopyStructureCount" in D3D12 and
1172 needs nothing from the layer), and resets it with `ClearUnorderedAccessViewUint` on a raw view of that word or a
1173 copy from an upload buffer. The layer refuses (null slot, logged once) a counter on a non-structured view, a
1174 counter resource that is not a buffer created with `ALLOW_UNORDERED_ACCESS`, an offset that is not a multiple of
1175 `D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT` (4096) or leaves no room for 4 bytes, and a non-zero offset with no counter
1176 resource, the combinations D3D12 documents as invalid. **Hypothesis for the console contract (not measured):** the
1177 shader gets the counter as a second V#, raw, 4 bytes (stride 0, `NUM_RECORDS` 4, `OOB_SELECT` 3) at address
1178 counter VA + offset, in **bytes 16..31 of the same descriptor slot**, which is otherwise unused for a buffer
1179 (a V# is 16 bytes in a 32-byte slot), and `AppendStructuredBuffer` / `ConsumeStructuredBuffer` compile to
1180 `buffer_atomic_add` / `buffer_atomic_sub` with `glc` on it, the returned old value (minus one for consume) being
1181 the record index. Why this guess: the translator has no `ds_append` / `ds_consume` / GDS path and the corpus scan
1182 (open-questions table below, row 10) found no GDS instruction, so a counter in memory is the only form left; where the
1183 counter V# sits (a second slot, a user SGPR pair, a spill) is open until a shader that uses one is traced
1184 (row 16 of the same table). `d3d12_buffer_uav_test` runs `cs_buf_counter.asm`, a hand-written shader of exactly that shape:
1185 256 lanes append, 128 consume, the counter reads 256 and then 128 through `CopyBufferRegion`, and the 256
1186 appended records are each present once. If the console puts the counter elsewhere, only `write_buffer_uav` moves.
1148- Unbounded descriptor ranges (`NumDescriptors = UINT_MAX`) have no end. Scan from the table handle to the end of 1187- Unbounded descriptor ranges (`NumDescriptors = UINT_MAX`) have no end. Scan from the table handle to the end of
1149 the bound heap, and cache parsed descriptors by key so unchanged slots cost nothing. **Open:** whether the game 1188 the bound heap, and cache parsed descriptors by key so unchanged slots cost nothing. **Open:** whether the game
1150 uses unbounded tables; the trace will show the root-signature ranges. 1189 uses unbounded tables; the trace will show the root-signature ranges.
@@ -1383,12 +1422,13 @@ The trace will enumerate them.
1383- `D3D12_FEATURE_LEVELS`: report the highest feature level the Vulkan device can satisfy (12_2 when mesh/RT 1422- `D3D12_FEATURE_LEVELS`: report the highest feature level the Vulkan device can satisfy (12_2 when mesh/RT
1384 features are present). 1423 features are present).
1385- `D3D12_FEATURE_SHADER_MODEL`: answer the shader model the layer can honour, not the driver's maximum. Nothing in 1424- `D3D12_FEATURE_SHADER_MODEL`: answer the shader model the layer can honour, not the driver's maximum. Nothing in
1386 the runtime compiles DXIL: the game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path 1425 the runtime compiles DXIL: the game's shaders arrive as SPIR-V from the offline translator, and the BVH
1387 (the BVH builder) is lowered to standard DXIL, whose baseline is 6.0. A request above it is clamped down to 6.0, 1426 builder's container also carries a console FSSM program that the same translator handles. A request above 6.0 is
1388 a request for 5.1 is answered with 5.1 (D3D12's own baseline, which a caller asking for the minimum expects), and a 1427 clamped down to 6.0, a request for 5.1 is answered with 5.1 (D3D12's own baseline, which a caller asking for the
1389 value below 5.1 is refused with `E_INVALIDARG`. Measured against the host PC runtime (616.86) on an RTX 5070: 1428 minimum expects), and a value below 5.1 is refused with `E_INVALIDARG`. Measured against the host PC runtime
1390 5.1-6.8 echo the request, 6.9 clamps to 6.8, and `0` is `E_INVALIDARG`; `0x5f` crashed the host runtime, which the 1429 (616.86) on an RTX 5070: 5.1-6.8 echo the request, 6.9 clamps to 6.8, and `0` is `E_INVALIDARG`; `0x5f` crashed
1391 test records in a comment rather than repeating. WARP answers a 5.1 request the same way. 1430 the host runtime, which the test records in a comment rather than repeating. WARP answers a 5.1 request the same
1431 way.
1392- `D3D12_FEATURE_ROOT_SIGNATURE`: 1.1, the version the proxy can always produce. A 1.2 blob is rewritten as 1.1 when 1432- `D3D12_FEATURE_ROOT_SIGNATURE`: 1.1, the version the proxy can always produce. A 1.2 blob is rewritten as 1.1 when
1393 the host's serializer stops at 1.1 and nothing is lost (`d3d12_xs_rootsig.cpp`), and Windows 10's `d3d12.dll` stops 1433 the host's serializer stops at 1.1 and nothing is lost (`d3d12_xs_rootsig.cpp`), and Windows 10's `d3d12.dll` stops
1394 there, so 1.1 is what the game can rely on everywhere. A higher request is clamped down like the shader model, and 1434 there, so 1.1 is what the game can rely on everywhere. A higher request is clamped down like the shader model, and
@@ -1428,8 +1468,9 @@ The trace will enumerate them.
1428 - `MIP` wherever the image can have more than one level. 1468 - `MIP` wherever the image can have more than one level.
1429 - `SHADER_GATHER` with `SHADER_SAMPLE` (not `A8_UNORM`, whose swizzled view isn't verified for gathers). 1469 - `SHADER_GATHER` with `SHADER_SAMPLE` (not `A8_UNORM`, whose swizzled view isn't verified for gathers).
1430 - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`), 1470 - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`),
1431 not a storage-image read. Typed buffer UAVs share the store side's gaps: the layer creates no buffer UAV 1471 not a storage-image read. Typed buffer UAVs: the layer now writes their V# (section 3.4, "Buffer UAVs"); the
1432 views yet, and `rdna2spirv.py` `FORMATS` decodes only some buffer formats (no SINT, 8/16-bit UINT, 10_11_11). 1472 gap left is `rdna2spirv.py` `FORMATS`, which decodes only some buffer formats (the 32-bit SINT ones, but no
1473 8/16-bit SINT/UINT other than the RGBA8 and RGBA16 UINT ones, and no 10_11_11).
1433 - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today 1474 - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today
1434 that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the 1475 that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the
1435 layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view. 1476 layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view.
@@ -2150,24 +2191,23 @@ own names use the `XDXR` prefix for Xbox's raytracing path:
2150 node format: node id = address >> 3 | type, box16/box32/triangle nodes, 256-byte base units. That is the format 2191 node format: node id = address >> 3 | type, box16/box32/triangle nodes, 256-byte base units. That is the format
2151 the runtime must produce for the game's compute traversal. 2192 the runtime must produce for the game's compute traversal.
2152 2193
2153**The builder's own shaders are a separate problem.** They are Xbox DXIL using `@xbox.*` intrinsics, not FSSM 2194**The builder's own shaders are console FSSM, not Xbox DXIL.** Each of the 52 containers carries an LLVM
2154RDNA2: prior art found 44 of the 53 call non-standard `@xbox.*` functions and fail the PC D3D12 shader compiler, 2195bitcode blob and an `XDAT`/`XBCH` record; the PC experiment below compiled the bitcode, but the console runtime
2155and 22 have been lowered to standard DXIL and accepted as pipelines on an RX 7800 XT. Thirty-one of the 53 use raw 2196executes the `XBCH` record. Measured from that record: 52/52 unpack to `FSSM`, 42 translate and all 42 pass
215664-bit addresses (global load/store/atomic and `s_load`), so lowering also needs an address-to-resource mapping. 2197`spirv-val` with the same translator the game's 26,503 shaders use; the 10 left need `global_atomic_fmax`/`fmin`,
2157The existing FSSM translator does not cover these shaders, and their results are not yet checked against a 2198`buffer_load_ushort` and `tbuffer_load_format_x` with format 8 ([embedded_shaders.md](embedded_shaders.md)). The
2158reference. If the game uses the builder, the layer needs a DXIL path (or a substitute builder); this is on the 2199raw 64-bit addresses are the corpus's existing raw-address path, not a separate lowering. Open: whether the game
2159critical path for the RT effects, not a footnote. 2200uses the builder at all (RT-5) and whether the translated programs match a reference on a GPU.
2160 2201
2161The design choice follows from that: **build AMD-format BVH data, not a `VkAccelerationStructureKHR`, unless the 2202The design choice follows from that: **build AMD-format BVH data, not a `VkAccelerationStructureKHR`, unless the
2162shaders are changed to `OpTraceRayKHR`.** The game's 64 RT compute shaders traverse the nodes themselves; a 2203shaders are changed to `OpTraceRayKHR`.** The game's 64 RT compute shaders traverse the nodes themselves; a
2163Vulkan AS would be invisible to them. Two paths: 2204Vulkan AS would be invisible to them. Two paths:
2164 2205
21651. If `XboxBvhBuilder` does the build with its own compute dispatches (the likely case, given it ships as a DLL 22061. If `XboxBvhBuilder` does the build with its own compute dispatches (the likely case, given it ships as a DLL
2166 with a device and command lists), the layer must translate and run its Xbox DXIL compute shaders — it cannot 2207 with a device and command lists), the layer must translate and run its compute shaders. The console programs
2167 feed DXIL to Vulkan directly. Buffers, UAVs, descriptors, barriers and indirect dispatch are necessary but not 2208 are `FSSM` and 41 of the 52 already pass `spirv-val`; the ten above still need their four rules. Buffers,
2168 sufficient; the 53 builder shaders need the DXIL path described above, and the 31 raw-address shaders need a 2209 UAVs, descriptors, barriers and indirect dispatch are necessary but not sufficient. The standard
2169 VA-to-resource mapping. The standard `BuildRaytracingAccelerationStructure` calls may never reach our command 2210 `BuildRaytracingAccelerationStructure` calls may never reach our command list.
2170 list.
21712. If the game calls `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure`, the layer must implement 22112. If the game calls `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure`, the layer must implement
2172 it. Produce the AMD node layout in the arena, with the same geometry/instance rules the translator assumes, 2212 it. Produce the AMD node layout in the arena, with the same geometry/instance rules the translator assumes,
2173 and make `GetRaytracingAccelerationStructurePrebuildInfo` return sizes for that layout. 2213 and make `GetRaytracingAccelerationStructurePrebuildInfo` return sizes for that layout.
@@ -2176,8 +2216,10 @@ Vulkan AS would be invisible to them. Two paths:
2176 the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure` 2216 the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure`
2177 and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure 2217 and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure
2178 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps 2218 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps
2179 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates rebuild 2219 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates refit
2180 the structure; compaction, copies, serialization and the Xbox batched/streaming builds are not implemented. The 2220 the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the
2221 postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). Serialization and the Xbox
2222 batched/streaming builds are not implemented. The
2181 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through 2223 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through
2182 the D3D12 API. 2224 the D3D12 API.
2183 2225
@@ -2417,10 +2459,10 @@ M0–M2 do not need the executable.
2417| **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below | 2459| **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below |
2418| **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | 2460| **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) |
2419| **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU), and texture formats other than R8G8B8A8_UNORM, mips and arrays through a PSO (the descriptor test covers views and sampling on a compute shader) | 2461| **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU), and texture formats other than R8G8B8A8_UNORM, mips and arrays through a PSO (the descriptor test covers views and sampling on a compute shader) |
2420| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | 2462| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable |
2421| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check | 2463| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker follows submission order, so the copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error; d3d12_queue_wait_test covers Wait-before-Signal without a resource), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game |
2422| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | 2464| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise |
2423| **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; Xbox DXIL path for the builder's 53 shaders (22 lowered so far) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the DXIL path or a substitute; no unknown XDXR call remains | 2465| **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (42 pass `spirv-val`, four rules left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains |
2424| **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; HDR, VRS, plane compose, alt-tab are open | 2466| **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; HDR, VRS, plane compose, alt-tab are open |
2425 2467
2426### 6.1 Minimum API set for the first frame 2468### 6.1 Minimum API set for the first frame
@@ -2474,7 +2516,7 @@ DLLs were executed against a PC D3D12 device through the Xbox-ABI proxy.
2474| 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. | 2516| 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. |
2475| 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. | 2517| 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. |
2476| 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. | 2518| 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. |
2477| 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. | 2519| 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)). |
2478 2520
2479### 7.1 What this confirms, corrects and narrows 2521### 7.1 What this confirms, corrects and narrows
2480 2522
@@ -2503,9 +2545,9 @@ DLLs were executed against a PC D3D12 device through the Xbox-ABI proxy.
2503 Xbox value and slot 76. 2545 Xbox value and slot 76.
2504- **Root signatures.** The `0x03000000` flags must be masked on a copy before the host serializer/deserializer. 2546- **Root signatures.** The `0x03000000` flags must be masked on a copy before the host serializer/deserializer.
2505 Our earlier "forward the blob to the host" was too simple; the PC serializer rejects the Xbox bits. 2547 Our earlier "forward the blob to the host" was too simple; the PC serializer rejects the Xbox bits.
2506- **BVH builder.** Its shaders are Xbox DXIL, not FSSM. "Run the builder's dispatches" therefore needs a DXIL 2548- **BVH builder.** Its console programs are `FSSM`; the bitcode in the same container is the representation the
2507 translation/lowering path plus an address-to-resource mapping for the raw-address shaders; the FSSM translator 2549 PC compiler consumed. "Run the builder's dispatches" therefore takes the same FSSM → SPIR-V path as the game,
2508 does not cover them. 2550 with four rules still missing ([embedded_shaders.md](embedded_shaders.md)).
2509 2551
2510**Narrows.** 2552**Narrows.**
2511 2553
@@ -2520,16 +2562,18 @@ DLLs were executed against a PC D3D12 device through the Xbox-ABI proxy.
2520- The `xgr` 48/398 and Xodus 152/396 coverage numbers show how large the long tail is. They do not change the 2562- The `xgr` 48/398 and Xodus 152/396 coverage numbers show how large the long tail is. They do not change the
2521 plan: implement what the game calls, in the order it calls it. 2563 plan: implement what the game calls, in the order it calls it.
2522 2564
2523### 7.2 The BVH builder's Xbox DXIL path 2565### 7.2 The BVH builder's shader path
2524 2566
2525The builder's 53 compute shaders are a second shader front end. They are Xbox DXIL with `@xbox.*` intrinsics that 2567The builder's 52 compute shaders are a second *corpus*, not a second shader front end. Each container carries an
2526map one-to-one to RDNA instructions (global load/store/atomic with 64-bit addresses, `s_load`, min/med/max, 2568LLVM bitcode blob and an `XDAT`/`XBCH` record; the bitcode is what the PC D3D12 compiler experiment consumed
2527bitfield insert, alignbyte, cndmask, packed f16 min/max and lane/wave operations). The standard PC DXIL compiler 2569(44 of 53 rejected, 22 lowered), while the console runtime executes the `XBCH` record. That record decompresses
2528rejects 44 of the 53; 22 have been lowered to standard DXIL and compile; the 31 that use raw 64-bit addresses also 2570to `FSSM`, the same container the game's own compute shaders use: 52/52 unpack, 42 translate and all 42 pass
2529need a table mapping those addresses to resources. This is separate from the FSSM RDNA2 translator, which covers 2571`spirv-val` with `tools/rdna2spirv.py`. The 10 left stop at `global_atomic_fmax`/`fmin` (6 programs),
2530the game's 26,503 shaders. A port that uses `XboxBvhBuilder` needs both: FSSM → SPIR-V for the game, and an Xbox 2572`buffer_load_ushort` (3) and `tbuffer_load_format_x` with format 8 (1); [embedded_shaders.md](embedded_shaders.md)
2531DXIL → standard DXIL → SPIR-V path (or a substitute builder) for the BVH helper. The prior art has compiled 2573lists them. The raw 64-bit addresses are the translator's existing raw-address path, so no address-to-resource
2532lowered shaders but has no reference output yet, so correctness is unverified. 2574table is needed on top. A port that runs `XboxBvhBuilder` therefore needs the FSSM translator plus four rules,
2575not a DXIL front end (a substitute builder remains the alternative).
2576Correctness is still unverified on a GPU and the call sites need the executable (RT-5).
2533 2577
2534### 7.3 Licence 2578### 7.3 Licence
2535 2579
@@ -2552,7 +2596,7 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2552 absent executable. 2596 absent executable.
2553- The prior art's measured Xbox ABI (section 7): 6 Xbox-specific static imports across the 16 DLLs, 2597- The prior art's measured Xbox ABI (section 7): 6 Xbox-specific static imports across the 16 DLLs,
2554 `D3D12XboxCreateDevice`, device slots 62/76, descriptor-heap start handles in RAX, root-signature flags 2598 `D3D12XboxCreateDevice`, device slots 62/76, descriptor-heap start handles in RAX, root-signature flags
2555 `0x03000000`, and the BVH builder's Xbox DXIL shaders. 2599 `0x03000000`, and the BVH builder's container format (a DXIL bitcode blob plus the console `XBCH` record).
2556 2600
2557### 8.2 Unknown / open questions 2601### 8.2 Unknown / open questions
2558 2602
@@ -2564,7 +2608,7 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2564| 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. | 2608| 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. |
2565| 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. | 2609| 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. |
2566| 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. | 2610| 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. |
2567| 7 | Does the game build acceleration structures through the standard D3D12 calls or through `XboxBvhBuilder`'s own compute path? | Log `BuildRaytracingAccelerationStructure`, `CopyRaytracingAccelerationStructure`, `Emit...PostbuildInfo`, and the builder's command-list method calls on the first RT frame. The builder's 53 shaders are Xbox DXIL; 44/53 fail the PC compiler and 22 have been lowered. If the builder path is used, the layer needs a DXIL plan. | 2611| 7 | Does the game build acceleration structures through the standard D3D12 calls or through `XboxBvhBuilder`'s own compute path? | Log `BuildRaytracingAccelerationStructure`, `CopyRaytracingAccelerationStructure`, `Emit...PostbuildInfo`, and the builder's command-list method calls on the first RT frame. The builder's container carries a DXIL bitcode blob and a console `XBCH` record; the record is `FSSM` and 42 of 52 programs pass `spirv-val` ([embedded_shaders.md](embedded_shaders.md)). If the builder path is used, translate the `XBCH` record rather than the bitcode. |
2568| 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). | 2612| 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). |
2569| 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. | 2613| 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. |
2570| 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. | 2614| 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. |
@@ -2573,11 +2617,12 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2573| 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. | 2617| 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. |
2574| 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`. | 2618| 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`. |
2575| 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). | 2619| 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). |
2576| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. | 2620| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1, disassembled with LLVM 21.1.8 for gfx1013; SHADER-65). **No append/consume counters:** none of the 445,394 PSV0 binding records is a structured UAV with a counter, and there is no `ds_append`/`ds_consume`/GDS instruction. Typed buffers are declared in 5,359 shaders as SRVs (17,328 records) and in 2,177 as UAVs (4,005). **MTBUF** (format in the instruction): 52,890 loads in 10,278 shaders, all in five formats the translator decodes (`16_16_SNORM` 24,881, `8_8_8_8_UNORM` 19,835, `8_8_8_8_UINT` 5,099, `2_10_10_10_UNORM` 2,648, `16_16_16_16_UINT` 427), and no MTBUF store. **MUBUF** `buffer_*_format_*` (format from V# word 3): 90,316 accesses (84,908 loads, 5,408 stores) in 11,591 shaders; word 3 comes from a scalar load in 88,924 of them, is computed in 1,390, and is a literal in 2 (FORMAT 0, INVALID, which reads 0 on the hardware and in the translator). So the shaders fix no MUBUF format: the descriptors the executable writes decide it. Still open: which formats those descriptors carry; the runtime can log a V# format outside `Gen.FORMATS` (those read 0 today) when the descriptor is created or copied. |
2621| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. **Runtime side done, console side open:** the layer writes typed buffer V#s and a counter V# (a hypothesis for where the shader finds it, section 3.4 "Buffer UAVs"); whether the game uses either is for the trace. |
2577| 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. | 2622| 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. |
2578| 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). | 2623| 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). |
2579| 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. Compare against the public flag enum and observe the game's behaviour with and without the mask. | 2624| 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. Compare against the public flag enum and observe the game's behaviour with and without the mask. |
2580| 20 | Which of the BVH builder's 53 Xbox DXIL shaders does the game actually use, and can the 31 raw-address shaders be lowered without a reference? | Dump the slot-62 compute PSOs on the first RT frame; lower and compile each; compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. | 2625| 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. |
2581| 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. | 2626| 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. |
2582 2627
2583## 9. Risks and non-goals 2628## 9. Risks and non-goals
@@ -2595,9 +2640,6 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2595 game's buffer working set may exceed `maxBufferSize` or PC VRAM. Host-visible arenas are slow; device-local 2640 game's buffer working set may exceed `maxBufferSize` or PC VRAM. Host-visible arenas are slow; device-local
2596 arenas need staging and careful upload/readback handling. This is the main performance risk. 2641 arenas need staging and careful upload/readback handling. This is the main performance risk.
2597- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); Intel, RTX 5070 Ti Laptop and AMD RDNA3 are measured in section 5.1; Apple numbers remain open via `vk_descriptor_bench`. 2642- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); Intel, RTX 5070 Ti Laptop and AMD RDNA3 are measured in section 5.1; Apple numbers remain open via `vk_descriptor_bench`.
2598- **Wave64.** On NVIDIA, wave64 shaders use the translator's 32-wide approximation; cross-half ops are approximate.
2599 AMD GPUs with 64-wide subgroups are exact. This is a known fidelity gap, not specific to the layer.
2600- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 616.56): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (`3.0–3.7 us/1M` net wave-uniform full sweeps, `17.2–28.9 us/1M` net divergent hits), whereas `HOST_VISIBLE | HOST_COHERENT` system memory drops 9.6x–28x on uniform full sweeps and 59x–755x on divergent lookups at 10k–100k entries, and linear probing's 8-probe limit doubles a 100k table to `80.00 MiB` (`4.8%` load). **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); AMD/Intel/Apple numbers remain open via `vk_descriptor_bench`.
2601- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (Windows driver, RADV on GFX10+) can require 2643- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (Windows driver, RADV on GFX10+) can require
2602 it for compute, mesh and pixel shaders, NVIDIA cannot (32 only). There, compute and mesh shaders translated with 2644 it for compute, mesh and pixel shaders, NVIDIA cannot (32 only). There, compute and mesh shaders translated with
2603 `--wave64-emulate` are exact; wave64 pixel, vertex and geometry shaders have no emulation and keep the 2645 `--wave64-emulate` are exact; wave64 pixel, vertex and geometry shaders have no emulation and keep the
@@ -2605,9 +2647,10 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc
2605 the layer. 2647 the layer.
2606- **Xbox tiling/DCC.** Slot 76 and layout `0x101` are known, but the tiled data layout, detile path and DCC remain 2648- **Xbox tiling/DCC.** Slot 76 and layout `0x101` are known, but the tiled data layout, detile path and DCC remain
2607 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step. 2649 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step.
2608- **BVH builder DXIL.** 44 of the builder's 53 Xbox DXIL shaders fail the PC compiler; 22 have been lowered to 2650- **BVH builder shaders.** The container's DXIL bitcode is Xbox DXIL that PC drivers reject; its console `XBCH`
2609 standard DXIL and compile, and 31 use raw 64-bit addresses. The lowered shaders have no reference output yet, and 2651 record is `FSSM`, and 41 of the 52 programs already pass `spirv-val` through the same translator as the game
2610 this is a separate front end from the FSSM translator. 2652 ([embedded_shaders.md](embedded_shaders.md)). The 10 left need four small rules. Translation is not execution:
2653 there is no GPU reference for any of the 52 yet.
2611- **Ray tracing.** The game's RT work includes 64 compute shaders that traverse AMD-format BVH nodes, and it ships 2654- **Ray tracing.** The game's RT work includes 64 compute shaders that traverse AMD-format BVH nodes, and it ships
2612 a BVH builder; a standard D3D12 AS path may also exist. If it is used, the layer must build AMD-format nodes, not 2655 a BVH builder; a standard D3D12 AS path may also exist. If it is used, the layer must build AMD-format nodes, not
2613 a Vulkan AS. 2656 a Vulkan AS.
@@ -2725,8 +2768,8 @@ on a PC device behind the Xbox-ABI proxy). Measured:
2725 `(desc, riid, out)`, so the first call returned `E_POINTER` and the constructor threw it. 2768 `(desc, riid, out)`, so the first call returned `E_POINTER` and the constructor threw it.
2726- With slot 62 read that way, on **WARP** the constructor returns after 62 ms: 17 root signatures (slot 16) and 53 2769- With slot 62 read that way, on **WARP** the constructor returns after 62 ms: 17 root signatures (slot 16) and 53
2727 compute PSOs (slot 62, 53 of 53 `S_OK`), CS bytecode 4–75 KB each. `~XboxBvhBuilder` returns and makes no device 2770 compute PSOs (slot 62, 53 of 53 `S_OK`), CS bytecode 4–75 KB each. `~XboxBvhBuilder` returns and makes no device
2728 call. Created is not the same as correct: the shaders are Xbox DXIL with `@xbox.*` intrinsics (section 7.2), and 2771 call. Created is not the same as correct: the container's DXIL bitcode is Xbox DXIL with `@xbox.*` intrinsics
2729 nothing has been dispatched yet. 2772 (section 7.2), its console `XBCH` record is `FSSM`, and nothing has been dispatched yet.
2730- **NVIDIA (RT-54).** On an RTX 3060 (616.64), an RTX 4090 (621.14) and an RTX 5070 Ti (621.24), all on Windows 11, 2773- **NVIDIA (RT-54).** On an RTX 3060 (616.64), an RTX 4090 (621.14) and an RTX 5070 Ti (621.24), all on Windows 11,
2731 the first 48 PSOs return `S_OK`, and the 49th (38,248 bytes) never does. Some runs return `E_OUTOFMEMORY` for it, 2774 the first 48 PSOs return `S_OK`, and the 49th (38,248 bytes) never does. Some runs return `E_OUTOFMEMORY` for it,
2732 which the constructor throws. Other runs end the process inside `nvwgf2umx.dll` with `0xC0000409`, after the 2775 which the constructor throws. Other runs end the process inside `nvwgf2umx.dll` with `0xC0000409`, after the
@@ -2734,7 +2777,7 @@ on a PC device behind the Xbox-ABI proxy). Measured:
2734 can't be caught. The D3D12 debug layer prints nothing first. 2777 can't be caught. The D3D12 debug layer prints nothing first.
2735 - **Cause: the input, not Leonida.** The proxy passes the bytecode through unchanged, so nothing is wrong in what 2778 - **Cause: the input, not Leonida.** The proxy passes the bytecode through unchanged, so nothing is wrong in what
2736 it forwards. The input is the problem: `LEONIDA_BVH_RECORD62=1 LEONIDA_BVH_DXIL=1` shows that every one of the 2779 it forwards. The input is the problem: `LEONIDA_BVH_RECORD62=1 LEONIDA_BVH_DXIL=1` shows that every one of the
2737 53 containers is signed, has the same 9 parts, and is shader model 6.5 / DXIL 1.5. But dxil.dll (Windows SDK 2780 53 PSO calls (52 distinct containers) is signed, has the same 9 parts, and is shader model 6.5 / DXIL 1.5. But dxil.dll (Windows SDK
2738 10.0.26100) rejects all 53 (`0x80aa0009`): the target triple is `dxil-ms-xb2` and the module carries 2781 10.0.26100) rejects all 53 (`0x80aa0009`): the target triple is `dxil-ms-xb2` and the module carries
2739 `xbox.compiler.options` metadata. Most also have Xbox-only externals (44 of 53), `extractvalue` on non-DXIL types 2782 `xbox.compiler.options` metadata. Most also have Xbox-only externals (44 of 53), `extractvalue` on non-DXIL types
2740 (16) or other disallowed instruction types (5). No PC driver has to accept this, and WARP happens to. 2783 (16) or other disallowed instruction types (5). No PC driver has to accept this, and WARP happens to.
@@ -2746,8 +2789,10 @@ on a PC device behind the Xbox-ABI proxy). Measured:
2746 So `bvh_builder_test` uses WARP whenever there is a hardware adapter, unless `LEONIDA_BVH_HARDWARE=1`, and it 2789 So `bvh_builder_test` uses WARP whenever there is a hardware adapter, unless `LEONIDA_BVH_HARDWARE=1`, and it
2747 prints the reason with the adapter's PCI vendor id. WARP creates all 53 PSOs, and the constructor and destructor 2790 prints the reason with the adapter's PCI vendor id. WARP creates all 53 PSOs, and the constructor and destructor
2748 return. 2791 return.
2749 - **The runtime itself still shouldn't hand Xbox DXIL to a PC driver.** These shaders need lowering to PC DXIL or a 2792 - **The runtime itself still shouldn't hand Xbox DXIL to a PC driver.** The same container carries the console
2750 translation of their own (section 7.2, M6) before they can run on hardware. 2793 `XBCH` record, which decompresses to `FSSM`; 41 of the 52 programs translate and pass `spirv-val` today
2794 ([embedded_shaders.md](embedded_shaders.md)). Translating that record is the path that avoids a DXIL lowering
2795 front end (section 7.2, M6); the bitcode is a second representation.
2751 2796
2752### A.3 `amd_fidelityfx_upscaler_xbox.dll` 2797### A.3 `amd_fidelityfx_upscaler_xbox.dll`
2753 2798
@@ -2820,7 +2865,7 @@ on a PC device behind the Xbox-ABI proxy). Measured:
2820 (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence: 2865 (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence:
2821 [d3d12_command_objects.md §3.5a](d3d12_command_objects.md). 2866 [d3d12_command_objects.md §3.5a](d3d12_command_objects.md).
2822 Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own 2867 Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own
2823 messages, not the PC method at that index; the proxy now refuses it. The dispatch stops where the PC runtime 2868 messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime
2824 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX` 2869 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX`
2825 payload with an RDNA2 program ([fspx.md](fspx.md)). 2870 payload with an RDNA2 program ([fspx.md](fspx.md)).
2826 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException` 2871 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException`
diff --git a/docs/descriptor_lookup_ada.md b/docs/descriptor_lookup_ada.md
index 490648e54..c5a6fced3 100644
--- a/docs/descriptor_lookup_ada.md
+++ b/docs/descriptor_lookup_ada.md
@@ -51,6 +51,8 @@ foreach ($memory in 'device', 'host', 'rebar') {
51} 51}
52``` 52```
53 53
54These commands predate `--warmup-ms` (TEST-277, default 300 ms of extra warm-up). With a current build add `--warmup-ms 0` to reproduce them as run.
55
54Device 0 was the RTX 4070 SUPER, the only Vulkan device. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The rounds used the same size orders and starting memory types as the M3 Max run. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each. Each round ran the other of device and host second, and ReBAR third. 56Device 0 was the RTX 4070 SUPER, the only Vulkan device. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The rounds used the same size orders and starting memory types as the M3 Max run. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each. Each round ran the other of device and host second, and ReBAR third.
55 57
56## System 58## System
diff --git a/docs/descriptor_lookup_apple.md b/docs/descriptor_lookup_apple.md
index dbc3c1f79..fad071ec6 100644
--- a/docs/descriptor_lookup_apple.md
+++ b/docs/descriptor_lookup_apple.md
@@ -43,4 +43,6 @@ for memory in device host; do
43done 43done
44``` 44```
45 45
46These commands predate `--warmup-ms` (TEST-277, default 300 ms of extra warm-up). With a current build add `--warmup-ms 0` to reproduce them as run.
47
46Device 0 was the M3 Max. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each. 48Device 0 was the M3 Max. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each.
diff --git a/docs/design.md b/docs/design.md
index d17183fc9..90adabdae 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -103,11 +103,11 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b
103| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `<work>\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | 103| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `<work>\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) |
104| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `<work>\textures\` | 104| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `<work>\textures\` |
105| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**, **55,417 fragments**, **89,887 bone-bound**, **2.64 billion triangles** [`2,636,248,990`], 1,805 embedded textures; 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,248 at `917e9b9` (159,483 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,533 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `<work>\assets\<archive>\models\` | 105| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**, **55,417 fragments**, **89,887 bone-bound**, **2.64 billion triangles** [`2,636,248,990`], 1,805 embedded textures; 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,248 at `917e9b9` (159,483 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,533 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `<work>\assets\<archive>\models\` |
106| Models | **Done: 350,251 models measured at the `917e9b9` pin** (the submodule pin is now `e293917`, which also pulls in upstream `v1.2` model-discovery PRs #8-#12 plus BCPack PR #7; the non-`levels.rpf` archives have been re-counted at `e293917`: 39,454 rows, +3,203, almost all recovered fragments; `levels.rpf` has a recovery count of 343,327 models (+29,327) but no full OBJ export). At `917e9b9`: `levels.rpf` 314,000, `story000` 7,460, `packs` 24,034, `data` 2,581, `shared_minigame000` 1,288, `core_restofworld` 885, `story000_restofworld` 3; 0 decode failures in the re-count. The `c3708fb` export was 190,792; the new entries are **159,486 drawable-dictionary children** (levels 130,225, packs 23,720, story 4,156, data 268, shared 317, core 797, story_restofworld 3) plus raw-tail/mixed-block pages. The standalone total is 190,765. Triangle totals were not re-run. Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `<work>\assets\<archive>\models\` | 106| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**; the other archives measure **4,686 fragments**, **30,343 bone-bound**, **126,301,454 triangles** and 512 embedded textures, while the `levels.rpf` fragments/bone-bound/triangles/embedded cells are **not independently reproduced** (no `levels.rpf` manifest; the count harness emits no such fields); 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,251 at `917e9b9` (159,486 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,530 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `<work>\assets\<archive>\models\` |
107| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` | 107| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` |
108| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\<name>\data\ttdb\**` (exported under `ttpf_pack\<pack>\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_<assetkey>`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` | 108| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\<name>\data\ttdb\**` (exported under `ttpf_pack\<pack>\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_<assetkey>`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` |
109| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `<work>\anim-index\` | 109| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `<work>\anim-index\` |
110| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`, so decoders drop the 312-sample libopus priming and stop at the declared end. Checked: 300 random streams decode with ffmpeg with no errors, lengths match the declared counts. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `<work>\assets\audio\ogg\<bank>\<stream id>.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `<work>\assets\audio\awc\` | 110| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`; the EOS page is emitted at the packet that reaches that target and later padding packets are dropped, so decoders stop at the declared end. Checked: 20 real streams at 48 and 32 kHz decode to exactly their declared counts; 300 random streams decode with ffmpeg with no errors. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `<work>\assets\audio\ogg\<bank>\<stream id>.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `<work>\assets\audio\awc\` |
111| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) | 111| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) |
112| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | 112| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) |
113| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) | 113| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) |
@@ -217,7 +217,6 @@ How the generated SPIR-V expects the runtime to work:
217| 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). | 217| 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). |
218| 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. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | 218| 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. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. |
219| 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 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), **not yet GPU-verified**. | 219| 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 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), **not yet GPU-verified**. |
220| 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. 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), **not yet GPU-verified**. |
221| `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). **Not GPU-verified** for the seven new kinds. | 220| `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). **Not GPU-verified** for the seven new kinds. |
222| 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. 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. | 221| 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. 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. |
223| 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"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | 222| 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"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. |
@@ -225,30 +224,25 @@ How the generated SPIR-V expects the runtime to work:
225| 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`). A source it does read prints as decoded (raw 0 is `s0`), so this can't hide a real difference. 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. | 224| 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`). A source it does read prints as decoded (raw 0 is `s0`), so this can't hide a real difference. 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. |
226| 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`). | 225| 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`). |
227| 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. 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_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, the float atomics, 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) 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.** | 226| 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. 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_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, the float atomics, 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) 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.** |
228| 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. 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`. 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). **Not GPU-verified.** |
229| 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.** | 227| 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.** |
230| 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. | 228| 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. |
231| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). 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). Not measured: `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; `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. | 229| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). 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). Not measured: `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. |
232| 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). | 230| 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). |
233| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). 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). Not measured: `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. | 231| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). 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). Not measured: `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. |
234| 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. | 232| 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. |
235| 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 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. 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. |
236| 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. | 233| 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. |
237| 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 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. 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). | 234| 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 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. 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). |
235| 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`. 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. |
236| 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. |
237| 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`. 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). |
238| 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`). | 238| 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`). |
239| 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. | 239| 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. |
240| 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). | 240| 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). |
241| 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.** | 241| 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.** |
242| 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. This assumes the pair is perspective-center, the only pair this layout models. 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. |
243| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `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 (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
244| 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. |
245| 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. |
246| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `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` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
247| 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). |
248| 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. | 242| 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. |
249| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `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 (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. | 243| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `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 (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. |
250| 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. | 244| 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. |
251| 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 (docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). | 245| 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"). |
252| `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. | 246| `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. |
253| 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 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, constants, rejected forms). **Not GPU-verified.** | 247| 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 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, constants, rejected forms). **Not GPU-verified.** |
254| `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. 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. | 248| `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. 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. |
@@ -264,20 +258,22 @@ How the generated SPIR-V expects the runtime to work:
264| 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. | 258| 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. |
265| 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. | 259| 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. |
266| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. 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` 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. | 260| Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. 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` 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. |
267| 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`, **not yet GPU-verified**. 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**. | 261| 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 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). **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. |
262| 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**. |
268| 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). | 263| 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). |
269| `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. | 264| `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. |
270| 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). | 265| 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). |
271| 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. | 266| 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. |
272| 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). | 267| 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). |
273| 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 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. 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. `tbuffer_store_format_*` is not translated. | 268| 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 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. 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. `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`. |
274| 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 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. | 269| 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 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. |
270| 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 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. 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. |
271| 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 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. 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. `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 and xyzw stores 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). |
272| 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 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. 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 and xyzw stores 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). |
275| `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. | 273| `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. |
276| Other additions | `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. 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). Those two 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. `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`). | 274| Other additions | `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. 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). Those two 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. `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`). |
277| `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), **not yet GPU-verified**. | 275| `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. |
278| 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. 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. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `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 (**assumption**: RADV only uses base 0). **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. 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. | 276| 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. 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. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `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 (**assumption**: RADV only uses base 0). **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. 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. |
279| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). |
280| 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. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. 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 (**assumption**: RADV only uses base 0). **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. |
281| 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). | 277| 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). |
282| Flat pixel inputs | 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. | 278| Flat pixel inputs | 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. |
283| 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` models only the p0 provoking vertex. 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 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. | 279| 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` models only the p0 provoking vertex. 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 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. |
@@ -288,9 +284,7 @@ How the generated SPIR-V expects the runtime to work:
288| 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 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. | 284| 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 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. |
289| 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. `--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`. 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). | 285| 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. `--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`. 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). |
290| `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). | 286| `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). |
291| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. |
292| `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. | 287| `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. |
293| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply with an exact zero result and a negative sign (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). The f16 multiplies are `OpFMul` on `float`, so all three go through the same path. MoltenVK's SPIRV-Cross turns a `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 and MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`, have the old helper. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` and `SignedZeroInfNanPreserve` (#664) do not help on MoltenVK, because the helper itself adds +0. 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` matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`. 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). Homebrew MoltenVK 1.4.2 gives the `aa217aeb` counts. |
294| 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. | 288| 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. |
295| 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). | 289| 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). |
296| 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. | 290| 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. |
@@ -300,35 +294,30 @@ How the generated SPIR-V expects the runtime to work:
300| 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. | 294| 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. |
301| 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`); **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)` (`FClamp`). | 295| 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`); **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)` (`FClamp`). |
302| 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 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"). | 296| 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 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"). |
297| 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; 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. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
303| 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. 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 `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 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. | 298| 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. 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 `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 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. |
304| 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). 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). 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. | 299| 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). 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). 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. |
305| 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. | 300| 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. |
306| 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; not ordered: scalar loads of memory the wave wrote, and sampling an image it 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. `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). | 301| 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. `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). |
307| 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. `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). |
308| 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), 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, the largest constant offset) 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 room left and LDS indices wrap with `OpUMod` instead of a mask (addresses below the need are unchanged); 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. A need that comes only from a constant ds offset is not counted against the cap: the translator adds 4 dwords of slack for the widest access, so an in-range `ds_write_b32` at offset 65,524 computes as 65,540 B, and an offset really past 64 KiB is out of range on hardware (reads 0, writes dropped); those keep the clipped 64 KiB array, as before. `%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 exactly 65,536 B, the exact-cap boundary, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, a constant offset computing as 65,540 B kept at 64 KiB, `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`. | 302| 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), 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, the largest constant offset) 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 room left and LDS indices wrap with `OpUMod` instead of a mask (addresses below the need are unchanged); 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. A need that comes only from a constant ds offset is not counted against the cap: the translator adds 4 dwords of slack for the widest access, so an in-range `ds_write_b32` at offset 65,524 computes as 65,540 B, and an offset really past 64 KiB is out of range on hardware (reads 0, writes dropped); those keep the clipped 64 KiB array, as before. `%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 exactly 65,536 B, the exact-cap boundary, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, a constant offset computing as 65,540 B kept at 64 KiB, `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`. |
309| 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). | 303| 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). |
310| 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), 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. | 304| 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), 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. |
311| 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. | 305| 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. |
312| 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. | 306| 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. |
313| 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. | 307| 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. |
308| 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`. Two modifiers were measured too and are Unsupported: `clamp` saturates `v_dot4_i32_i8` to a signed 32-bit value (the two overflowing sets), and `op_sel` 2 with `op_sel_hi` 5 exchanges the 16-bit halves of S1 before the products (5 sets; the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)). 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). With the rule 17 of the 29 programs translate and pass `spirv-val` (13 before). |
314| 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. 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. | 309| 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. 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. |
315| 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), 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`. 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. | 310| 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), 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`. 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. |
316| `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`. **Not GPU-verified.** | 311| `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). |
317| `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). **Not GPU-verified.** | 312| `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). **Not GPU-verified.** |
318| `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`, so the memory ends as a 64-bit exchange leaves it, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **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`). 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). **Not GPU-verified.** | 313| `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`, so the memory ends as a 64-bit exchange leaves it, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **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`). 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). **Not GPU-verified.** |
319| `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.** | 314| `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.** |
320| `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. | 315| `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. |
321| 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). **Not GPU-verified.** | 316| 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). |
322| 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. | 317| 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. |
323| 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. | 318| 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. |
324| Typed image loads | `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). 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). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. 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. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | 319| Typed image loads | `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). 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). 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. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
325| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. 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. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | 320| 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. |
326| Typed image loads | `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). 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). 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. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
327| Typed image loads | `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). 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). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. 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. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
328| Typed image loads | `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). 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). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. 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. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
329| 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. Out-of-range integer narrowing has the same limitation as typed image loads below. |
330| Typed image loads | `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). 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). 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. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
331| Typed image loads | `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). 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). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. 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. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. |
332| 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 (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). 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. | 321| 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 (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). 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. |
333| 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. 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. | 322| 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. 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. |
334| 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`. | 323| 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`. |
@@ -339,46 +328,60 @@ How the generated SPIR-V expects the runtime to work:
339| 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], 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](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`; **not GPU-verified, no corpus count**; the translated shaders were 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). **Not measured on RDNA2.** | 328| 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], 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](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`; **not GPU-verified, no corpus count**; the translated shaders were 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). **Not measured on RDNA2.** |
340| `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, 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. | 329| `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, 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. |
341| 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. | 330| 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. |
331| 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. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
332| `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). |
333| `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. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). |
334| `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 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. Not in the translated corpus. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
335| 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). |
336| `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); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. |
337| 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). |
342| `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). **Not GPU-verified.** | 338| `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). **Not GPU-verified.** |
343| 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`). **Not GPU-verified.** | 339| 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`). **Not GPU-verified.** |
344| 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.** | 340| 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.** |
345| `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. | 341| `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. |
346| 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. | 342| 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. |
347| 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` 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. Not covered here: SGPRs read as masks (#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`). | 343| 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` 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. Not covered here: SGPRs read as masks (#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`). |
344| 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). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
345| 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` 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 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). Not covered: 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`). |
348| 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.** | 346| 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.** |
349| 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. | 347| 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. |
350| 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). | 348| 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). |
351| 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. **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). **Not GPU-verified.** |
352| `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.** | 349| `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.** |
353| 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). **Not GPU-verified.** | 350| 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). **Not GPU-verified.** |
351| 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. **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). |
354| 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 round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. 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). Round to nearest even for these conversions is 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`). | 352| 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 round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. 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). Round to nearest even for these conversions is 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`). |
353| 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 round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. 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). 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`). |
355| 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`. | 354| 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`. |
356| `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); 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. **Not measured on hardware**: the kept half of the destination for the integer-result forms and the NaN result. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; not run on the shader corpus. | 355| `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. |
357| `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. **Not measured on hardware**: the denormal input and result handling (the f32 denormal mode is not modelled) and the NaN payload are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | 356| `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. **Not measured on hardware**: the denormal input and result handling (the f32 denormal mode is not modelled) and the NaN payload are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. |
358| `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`. **Not measured on hardware**: `clamp` on the multiply-add (the translator saturates after the full-width sum) and the kept half. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; not run on the shader corpus. | 357| `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. |
359| `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. `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. Source neg/abs apply to the float operand. `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 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. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`; not run on the shader corpus. | 358| `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. `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. Source neg/abs apply to the float operand. `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 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. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`; not run on the shader corpus. |
360| `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` 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`. **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`. | 359| `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` 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`. **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`. |
361| `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. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. | 360| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | `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. **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`. |
362| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `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). **Not GPU-verified.** | 361| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `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). **Not GPU-verified.** |
363| 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. `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings) in nearest-even mode, while the hardware rounds once: 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). | 362| 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. `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings) in nearest-even mode, while the hardware rounds once: 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). |
363| `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. 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. NaN gives 0, as `v_cvt_i32_f32` does. Source modifiers apply. `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). **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. |
364| 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. `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). |
365| 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. `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations). |
364| `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. | 366| `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. |
365| 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. **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. | 367| 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. **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. |
366| 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. 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..(29 − 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. Not combined with `--bary-fallback`'s geometry shader. | 368| 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. 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..(29 − 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. Not combined with `--bary-fallback`'s geometry shader. |
367| `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. | 369| `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. |
370| 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 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. 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. **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. |
371| `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)). |
368| 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. 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`. 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 GPU-verified**. | 372| 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. 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`. 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 GPU-verified**. |
369| 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 (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, 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` 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. 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). | 373| 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 (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 and verified by `tools/fma_mix_probe.py`; finding 7079901079): `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. `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` 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. 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). |
374| 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) round to nearest, which matches the default mode. `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, 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` 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. 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). |
375| 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 (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, 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` 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 is 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). 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). |
370| 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 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). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **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. | 376| 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 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). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **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. |
371| `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. | 377| `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. |
372| 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). 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`. | 378| 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). 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`. |
373| 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 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. **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. |
374| `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. **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.** | 379| `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. **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.** |
375| 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`/`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 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. 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. 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 wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. | 380| 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`/`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 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. 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. 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), 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 (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. |
376| 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 and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. 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. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), 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. | 381| 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 and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. 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. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), 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. |
377| 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_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, 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]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | 382| 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_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, 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]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. |
378| Wave64 mask ballot | `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` and `tests/semantic/test_scalar_alu_shifts.py`. | 383| Wave64 mask ballot | `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` and `tests/semantic/test_scalar_alu_shifts.py`. |
379| Wave64 mask ballot | `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`. 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`. |
380| 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)). | 384| 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)). |
381| 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); **not GPU-verified**. |
382| 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). | 385| 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). |
383| 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. | 386| 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. |
384 387
diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md
new file mode 100644
index 000000000..cfd316094
--- /dev/null
+++ b/docs/embedded_shaders.md
@@ -0,0 +1,124 @@
1# Shader containers embedded in the package's DLLs
2
3**Status: measured** on the 1.0.2.1 package. This note covers the shader programs that ship outside
4`shaders.rpf`: the DXBC containers inside the package's DLLs, what each one carries, and what the measurement
5changes for the ray-tracing and upscaling paths. No container, shader or payload is reproduced here; the tables
6hold counts, offsets, chunk names and module identifiers.
7
8## 1. Why they matter
9
10`make_game.py`'s `shaders` stage carves `shaders.rpf` only (`make_game.py`:655). Two DLLs in the same package
11carry compute programs of their own:
12
13* `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* `amd_fidelityfx_upscaler_xbox.dll`, the FidelityFX 4.1.1 upscaler. Its programs are the `ACCC`/`FSPX` format
16 covered in [fspx.md](fspx.md); this note only counts them.
17
18`tools/pe_shader_containers.py` scans a binary for DXBC containers, validates the chunk table, reads the `ILDN`
19module name and reports what each container carries. `--extract` writes the containers and an `index.json` the
20translator reads; extracted shaders are game data and must stay in the user's work folder.
21
22```sh
23python -I tools/pe_shader_containers.py <dll> --json <work>/containers.json --extract <work>/embedded/dxbc
24```
25
26## 2. Inventory
27
28The 16 DLLs and the package's root files were scanned. All the containers are in two DLLs:
29
30| image | containers | bytes | min / median / max | chunks |
31|---|---:|---:|---:|---|
32| `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| other 14 DLLs | 0 | 0 | — | — |
35
36The 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
38validator rejects it (the scan reports both counts).
39
40**Every one of the 52 containers carries two representations of its program:**
41
42* an LLVM bitcode blob in the `DXIL` chunk (`BC C0 DE`, 1,820 to 70,276 bytes), and
43* an `XDAT` directory with tag `0x0d` whose payload starts with `XBCH`: the console program. The same chunk also
44 holds tag `0x07` (a second `DXIL` program header) and tag `0x12` (a 16-byte hash). The `STAT` chunk holds a
45 second, different bitcode blob, not the same one.
46
47The bitcode is what a PC D3D12 compiler consumes; the runtime path is the `XBCH` record. The constructor passes
48the **whole container** to the compute-PSO call: at `0x180021330` it loads `DAT_180025700` with size `0x1134`
49(4,404 bytes, the size of container 0, `CopyAndCompactBVH`) and calls `FUN_18000c470`, whose vtable call at
50`+0x1f0` (slot 62) receives that pointer, its size and two zero words. `FUN_18001d400` adds two more PSOs,
51`XDXR PostBuildInfoQuery` (0x14a4 bytes) and `XDXR GetBVHCompactedSize`. `bvh_builder_test` measures **53** PSO
52creations during construction over the **52** containers ([d3d12_vulkan.md](d3d12_vulkan.md) A.2), so one
53container is created twice; which one is **Open**.
54
55## 3. The 52 modules
56
57The `ILDN` PDB path gives one module per container, all under
58`X:\americas\src\dev\rage\3rdparty\Microsoft\XboxBvhBuilder\Build\Release\Output\XboxBvhBuilder\` (Microsoft's
59component integrated into RAGE, not Rockstar shader code). Grouped by phase:
60
61| phase | modules |
62|---|---|
63| sort (11) | `BitonicPreSortCS`, `BitonicPreSort64CS`, `BitonicInnerSortCS`, `BitonicInnerSort64CS`, `BitonicOuterSortCS`, `BitonicOuterSort64CS`, `RadixCount`, `RadixAlloc`, `RadixReset`, `CalculateMortonCodes`, `CalculateMortonCodes64` |
64| prefix (7) | `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096` |
65| kdop (3) | `BuildKDOP`, `ResetKDOP`, `BuildApexPointMap` |
66| build (7) | `ConstructBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `SplitInstances`, `FindTreelets`, `RearrangeBVHs`, `RearrangeTriangles` |
67| refit (2) | `RefitBVH4`, `CopyForBVHUpdate` |
68| load (6) | `LoadTriangles`, `ReloadTriangles`, `LoadInstances`, `LoadProceduralGeometry`, `ReloadProcedurals`, `ResetToIndexBuffer` |
69| path tracing (6) | `PT_ConstructBVH4`, `PT_BeginPass`, `PT_LoadInstances`, `PT_WriteInstances`, `PT_WritePartitions`, `PT_WriteOfflinePartition` |
70| rehydration (3) | `Box16Rehydration`, `Box32Rehydration`, `LeafRehydration` |
71| headers/util (7) | `DecompressHeader`, `InitHeaders`, `InitPartitionedHeaders`, `GetBVHCompactedSize`, `CopyCounters`, `ResetCounterValues`, `CopyAndCompactBVH` |
72
73## 4. They are console FSSM, and the existing translator already takes them
74
75The `XBCH` record has the same shape as the game's own shaders: `XBCH` + stored/unpacked sizes + a zlib stream
76that expands to `FSSM` ([fssm_crosscheck.md](fssm_crosscheck.md)). On all 52 containers:
77
78| step | result |
79|---|---|
80| `tools/fssm_unpack.py` | **52/52** decompress to a valid `FSSM` blob (716 B to 101,320 B, median 2,200 B) |
81| `tools/shader_disasm.py --mcpu gfx1013` | **52/52** disassemble; 42 with no invalid word, 10 with invalid words in the code |
82| `tools/rdna2spirv.py` | **42** translate and pass `spirv-val` |
83
84The 10 untranslated programs stop at four rules:
85
86| module(s) | blocker |
87|---|---|
88| `BuildKDOP`, `LoadInstances`, `ReloadProcedurals`, `LoadProceduralGeometry`, `LoadTriangles` | `global_atomic_fmax` |
89| `PT_LoadInstances` | `global_atomic_fmin` |
90| `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles` | `buffer_load_ushort` |
91| `LeafRehydration` | `tbuffer_load_format_x GFX10_FORMAT_8_UINT` |
92
93Reproduction, after `--extract` above:
94
95```sh
96python -I tools/fssm_unpack.py <work>/embedded/dxbc
97python -I tools/shader_disasm.py <work>/embedded/dxbc/fssm --out <work>/embedded/dxbc/disasm --mcpu gfx1013
98python -I tools/rdna2spirv.py <work>/embedded/dxbc/disasm --out <work>/embedded/spirv
99```
100
101## 5. What this changes
102
103* **The RT builder does not need a DXIL path for the console code.** Its programs are RDNA2 `FSSM`, and 41 of
104 52 already pass `spirv-val` with the translator the project uses for the game's 26,503 shaders. The bitcode in
105 the same container is a second representation (the one the PC-compiler experiment measured); it is not what
106 the console runtime executes.
107* **The four missing rules are small and have real fixtures.** `global_atomic_fmax`/`fmin` cover 6 programs,
108 `buffer_load_ushort` 3 and `tbuffer_load_format_x` with format 8 one. They are ordinary translator rules, not
109 a new compiler backend.
110* **The rehydration programs are the ones closest to the shipped data.** `Box16Rehydration`,
111 `Box32Rehydration` and `LeafRehydration` are exactly the programs that would turn the dehydrated BVH packs
112 into runtime trees ([bvh.md](bvh.md) §3.1). Two of the four rules stand between them and translation.
113* **What is still open.** None of the 52 has been executed on a GPU; translation and `spirv-val` do not prove the
114 output. Which of them the game actually creates is a call-site question (RT-5). The module-to-pipeline order
115 above comes from `ILDN`, not from a runtime trace. The `STAT` bitcode and the `0x07 NOBC` record are not
116 explained.
117
118## 6. Tool and tests
119
120`tools/pe_shader_containers.py` is standard library only and reads the file, never runs it. It accepts a
121container only when the chunk table is sorted, 4-byte aligned, entirely inside the declared total and its last
122chunk ends exactly at that total; that is what rejects the FSR DLL's `DXBC` immediate. The synthetic tests in
123`tests/test_pe_shader_containers.py` build containers by hand (no game data) and cover the accepted layout, a
124bare magic, a truncated chunk, an `ACCC`/`FSPX` container, the `ILDN` name and the extraction index.
diff --git a/docs/fspx.md b/docs/fspx.md
index 7c9770f84..6d6c2f4eb 100644
--- a/docs/fspx.md
+++ b/docs/fspx.md
@@ -88,8 +88,11 @@ compute shader.
88 - `fspx_unpack.py --disasm` defaults to `gfx1030`. 88 - `fspx_unpack.py --disasm` defaults to `gfx1030`.
89- **What llvm-mc still rejects.** With `gfx1030`, 21 of the 29 decode with no invalid word. The other 89 words, in 8 89- **What llvm-mc still rejects.** With `gfx1030`, 21 of the 29 decode with no invalid word. The other 89 words, in 8
90 programs, are all VOP3P opcode 0x16 with `op_sel` 2 and `op_sel_hi` 5. That is the opcode of the 1,458 90 programs, are all VOP3P opcode 0x16 with `op_sel` 2 and `op_sel_hi` 5. That is the opcode of the 1,458
91 `v_dot4_i32_i8` that `llvm-mc` does decode, all of which have `op_sel` 0. What the hardware does with that `op_sel` 91 `v_dot4_i32_i8` that `llvm-mc` does decode, all of which have `op_sel` 0.
92 was not checked. 92 - Measured on RDNA2 hardware (gfx1036, through `tools/hw_oracle`, the instruction given as two raw words): with
93 `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source
94 exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves
95 here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`.
93 96
94## Kind 7: records 97## Kind 7: records
95 98
@@ -108,12 +111,13 @@ compute shader.
108 111
109With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs: 112With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs:
110 113
111- **13 translate and pass `spirv-val`.** They are the 16 programs that use no dot4 instruction, minus 3 that stop at 114- **17 translate and pass `spirv-val`.** 13 of them are the 16 programs that use no dot4 instruction, minus 3 that
112 `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. 115 stop at `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. The other 4 use dot4 (design.md, "Signed-byte
113- **The 13 programs that use dot4 do not translate yet.** The translator has neither dot4 form: 116 dot products").
114 - 10 stop at `v_dot4_i32_i8`; 117- **9 more programs that use dot4 do not translate yet.** The first thing each stops at:
115 - 2 stop earlier, at a reachable word `llvm-mc` does not decode (the VOP3P words above); 118 - 6 at an `s_buffer_load_dwordx8` or `_dwordx16` whose destination range ends in `vcc_lo, vcc_hi`;
116 - 1 stops earlier, at an `src_scc` operand. 119 - 2 at a reachable word `llvm-mc` does not decode (the VOP3P words above);
120 - 1 at an `src_scc` operand.
117 121
118## Unknown 122## Unknown
119 123
diff --git a/docs/i18n/README.md b/docs/i18n/README.md
index 78e8562c1..83138e71a 100644
--- a/docs/i18n/README.md
+++ b/docs/i18n/README.md
@@ -13,7 +13,9 @@ A language is added when a contributor volunteers to maintain it and keeps the s
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) | `e7584c52` | `@Urban225` |
16| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `d3841c0c` | `@Andretuta` | 16| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `003e7812` | `@Andretuta` |
17| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `e7584c5` | `@liang-kai-shui` | 17| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `003e7812` | `@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) | `c0ac5fd6` | `@Dom-in` |
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) | `f85582e` | `@emirhan-karaca` |
20| Русский (`ru`) | [`ru/quickstart.md`](ru/quickstart.md) | `a0acd33` | `@DmitryBykov-ISPO` |
21| 日本語 (`ja`) | [`ja/quickstart.md`](ja/quickstart.md) | `003e781` | `@bingll123` |
diff --git a/docs/i18n/ja/quickstart.md b/docs/i18n/ja/quickstart.md
new file mode 100644
index 000000000..0dfae7831
--- /dev/null
+++ b/docs/i18n/ja/quickstart.md
@@ -0,0 +1,138 @@
1# Leonida クイックスタート(`ja`)
2
3> [!NOTE]
4> 英語のドキュメント([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md)、
5> [`docs/README.md`](../../README.md))が**正式版**です。このページは安定したセットアップとビルド手順のみを
6> まとめたもので、commit `003e781` に同期しています。日々の進捗は [`README.md`](../../../README.md)
7> を参照してください。
8
9## Leonida とは
10
11Leonida は、Xbox Series 版 Grand Theft Auto VI を Windows 上でネイティブに動かすための**静的リコンパイル**
12プロジェクトです。Xbox Series の CPU は PC と同じ x86-64 なので、ゲームのコードはそのまま読み込まれて
13ネイティブに実行され、本体側のシステムソフトウェアは shim として再実装されます。本体用にコンパイル済みの
14RDNA2 GPU プログラムは Vulkan 向けの SPIR-V に翻訳され、モデル・テクスチャ・音声はあなたのパッケージから
15直接読み込まれます。これらはすべて**あなたの PC 上で、あなた自身のゲームのコピーから**行われます。
16
17> [!IMPORTANT]
18> このリポジトリにはゲーム、キー、実行ファイルは**含まれません**。入手方法も説明しません。自分用のコピーが
19> 必要で、そのファイルはあらかじめディスク上で読める状態になっている必要があります。ここには復号や保護の
20> 回避を行うものは何もありません。ビルドが生成するもの(翻訳されたシェーダー、抽出されたアセット、
21> runtime フォルダー、セーブデータ)はすべてあなたのゲームに由来し、あなたの PC に残ります。これらの
22> ファイルを共有しないでください([`CONTRIBUTING.md`](../../../CONTRIBUTING.md))。
23
24プロジェクトはまだ初期段階で、**ゲームはまだ起動しません**。
25
26## 前提条件
27
28- **自分用の Xbox Series パッケージ**(バージョン `1.0.2.1`)。`MicrosoftGame.Config` と `.rpf` アーカイブが
29 プレーンなファイルとして置かれているフォルダーが、ゲームフォルダーです。
30- **Windows 10/11 x64** と、作業ファイル用に約 **350 GB** の空き容量(`--work` で別ドライブに置けます)。
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)。
33- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as` / `spirv-val` 用)。
34- **AMDGPU target** を含む [LLVM 21+](https://github.com/llvm/llvm-project/releases)(`llvm-mc` 用)。
35 - Windows 版の公式 LLVM には AMDGPU target が**含まれていません**。
36 - Windows では、リポジトリのルートで次のコマンドを実行すると、AMDGPU target 付きのネイティブ `llvm-mc.exe` を
37 ビルドし(WSL 不要。`git` と下記の Visual Studio の C++ ツールが必要)、`LLVM_MC` を設定します:
38
39 ```powershell
40 powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1
41 ```
42 - または WSL に `llvm-21` を入れて、`LLVM_MC` にコマンド全体を設定します:
43 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`
44 ([docs/design.md](../../design.md#disassembling-shaders))。
45 - Linux では `PATH` に `llvm-mc` があれば十分です。
46- **Visual Studio 2022**(**C++ によるデスクトップ開発**)と **Windows SDK 10.0.26100 以降**。
47 `runtime` ステージで必要です(バージョン 1.2 の root signature を使い、古い SDK には宣言がないためです)。
48- [ffmpeg](https://ffmpeg.org/download.html) を `PATH` に(任意: XMA2 ストリームのデコード。`--wav` では必須)。
49
50## ビルド方法
51
52ポートはビルド済みで配布されているものではありません。**あなたの PC 上で、あなた自身のコピーから**ビルドします。
53
54### 簡単な方法(Windows)
55
561. 上記の前提条件をインストールします。
572. サブモジュール込みでリポジトリを取得します。
58
59 ```powershell
60 git clone --recursive https://github.com/ItsNotRexed/Leonida
61 ```
62
63 GitHub の "Download ZIP" では `third_party/rpf9-explorer` が含まれません。`git` があればビルドが自動で
64 取得し、なければ必要な操作を表示します。
653. **`Build.bat`** をダブルクリックします。
66
67すると、ゲームのコピーが自動で見つかります。ダウンロード、デスクトップ、ドキュメント(OneDrive など
68Windows が保存する場所を含む)、Games、ホームフォルダー、各ドライブの先頭から 2 階層までを探し、いくつかの
69ファイルサイズからバージョンを判定します(大きなファイルは読みません)。複数ある場合はどれを使うか確認し、
70見つからない場合はフォルダーの貼り付けを求めます。開始前に上記の前提条件と空き容量を確認し、足りないものを
71まとめて表示します。出力先は `Documents\Leonida` です。中断したビルドは続きから再開します。
72
73### コマンドライン(`make_game.py`)
74
75```powershell
76python -I make_game.py --find # この PC で見つかったコピーを一覧
77python -I make_game.py --pick # フォルダーダイアログでゲームフォルダーを選ぶ
78python -I make_game.py --check # コピーを確認するだけでビルドしない
79python -I make_game.py --check --full-check # すべてのファイルの SHA-256 も比較(低速)
80python -I make_game.py --game "D:\path\to\your\package" --out "D:\Games\Leonida" --work "E:\leonida-work"
81python -I make_game.py --stages shaders,assets # 一部のステージだけ
82python -I make_game.py --game "D:\path\to\your\package" --wav # Opus を PCM WAV にもデコード(大容量)
83python -I make_game.py --wave64-emulate off # auto(既定)、on、off のいずれか
84```
85
86ステージは `check` → `shaders` → `assets` → `runtime` → `pipelines` の順に実行されます。`pipelines` は
87翻訳済みの各シェーダーをあなたの GPU ドライバー上で生成してパイプラインキャッシュを保存するので、初回起動時の
88コンパイルが不要になります。最も時間がかかるのはシェーダーの翻訳で、`--jobs` 個のプロセスで実行されます
89(既定では CPU スレッド数の半分)。
90
91- **`--wave64-emulate`**: wave64 の compute / mesh シェーダーを、どのサブグループサイズでも正確になるように
92 翻訳するかどうかを決めます。NVIDIA と Intel の GPU は 32 レーンのサブグループなので必要です。既定の `auto` は
93 `vulkaninfo`(Vulkan SDK に含まれる)に問い合わせ、すべての GPU が 64 レーンのサブグループを報告しない場合、
94 または判定できない場合に有効にします。ただし runtime が使う GPU が、AMD の Windows ドライバーで wave64 を
95 ネイティブに実行できる RDNA2 のカードや iGPU の場合は、そのドライバーのシェーダーコンパイラーが
96 エミュレーションされた LDS コードでクラッシュするため(#857)、オフのままにします。設定は翻訳済みシェーダーの
97 隣に保存され、変更すると翻訳し直しになります。
98- **`--work`**: 中間ファイル用のフォルダーです。最低でも 350 GB 空いているドライブを指定してください。
99- **`--wav`**: 既定では無効です。16-bit PCM WAV は Ogg Opus より数倍大きいためです。
100- **Linux と Wine/Proton**: `make_game.py` は Linux でも動作します。ローダーは Windows プログラムなので
101 Wine または Proton で動きます。`runtime` ステージは Linux 上で clang-cl と lld-link(LLVM 19 以降)を使い、
102 [xwin](https://github.com/Jake-Shadle/xwin) が `XWIN_DIR` または `~/.local/share/xwin-sdk` に用意した
103 MSVC CRT と Windows SDK に対して `runtime/build/windows` へクロスビルドします
104 ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) に一度だけ実行する
105 `xwin` コマンドがあります)。これらがない場合、このステージは既定のステージから外れ、明示的に指定すると
106 何が足りないかを作業開始前に表示します。別の場所で作った Windows 版も使えます:
107
108 ```sh
109 python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows
110 ```
111
112 どちらの場合も `gta6rt.exe` と `gta6rt_tls_host.dll` を `--out` にコピーし、隣に `gta6rt.sh` を書き出します。
113 これは `gta6rt.exe` を `wine`、または `WINE` で指定した Wine(Proton なら `files/bin/wine`)で起動します。
114 Windows で同じオプションを指定すると、ビルドは省略されます。
115
116## よくある問題
117
118- **GitHub の "Download ZIP" を使った**: ZIP には `third_party/rpf9-explorer` サブモジュールが含まれません。
119 `git clone --recursive` を使うか、リポジトリのフォルダーで `git submodule update --init --recursive` を
120 実行してください。
121- **`llvm-mc` が `gfx1013` や AMDGPU を拒否する**: Windows 版の公式 LLVM を使っている可能性が高いです。
122 リポジトリのルートで `powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1` を実行するか、
123 `LLVM_MC` を WSL の `llvm-mc`(`llvm-21`)に向けてください。
124- **CMake が "needs the Windows SDK 10.0.26100 or newer" で止まる**、または MSVC が `Desc_1_2` は
125 `D3D12_VERSIONED_ROOT_SIGNATURE_DESC` のメンバーではないと報告する: Windows SDK を `10.0.26100` 以降に
126 更新し(Visual Studio Installer、または `winget install Microsoft.WindowsSDK.10.0.26100`)、
127 `runtime/build` を削除してから構成し直してください。
128- **`C:` ドライブの空きが足りない**: `--work "D:\leonida-work"` を指定して中間ファイルを別のドライブに置きます。
129- **Windows がビルド直後のテストプログラムの実行を拒否する**("An Application Control policy has blocked this
130 file"): Windows 11 のスマート アプリ コントロールです。
131 [docs/testing.md](../../testing.md#known-problems) を参照してください。
132
133## コントリビュートと GPU テスト
134
135- GPU テストの手順(ゲームファイル不要): [docs/testing.md](../../testing.md)。結果は
136 [#166](https://github.com/ItsNotRexed/Leonida/issues/166) に、GPU とドライバーごとに 1 コメントで投稿します。
137- コントリビュートのルール、ゲームデータを持ち込まない方針、作業の調整:
138 [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)。
diff --git a/docs/i18n/pt-BR/quickstart.md b/docs/i18n/pt-BR/quickstart.md
index 0d54af7b4..6964b8aee 100644
--- a/docs/i18n/pt-BR/quickstart.md
+++ b/docs/i18n/pt-BR/quickstart.md
@@ -3,7 +3,7 @@
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 `d3841c0c`). Para o status diário do projeto, consulte o 6> configuração e compilação (sincronizado com o commit `003e7812`). Para o status diário do projeto, consulte o
7> [`README.md`](../../../README.md). 7> [`README.md`](../../../README.md).
8 8
9## O que é o Leonida 9## O que é o Leonida
@@ -30,9 +30,14 @@ O projeto está em fase inicial: **o jogo ainda não dá boot**.
30- [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`).
31- [LLVM 21+](https://github.com/llvm/llvm-project/releases) com o **target AMDGPU** (`llvm-mc`): 31- [LLVM 21+](https://github.com/llvm/llvm-project/releases) com o **target AMDGPU** (`llvm-mc`):
32 - O binário oficial do LLVM para Windows **não** inclui o target AMDGPU. 32 - O binário oficial do LLVM para Windows **não** inclui o target AMDGPU.
33 - Para compilar um `llvm-mc.exe` nativo com AMDGPU, execute `.\scripts\build_llvm_mc.ps1` no PowerShell 33 - Para compilar um `llvm-mc.exe` nativo com AMDGPU, rode este comando a partir da raiz do repositório.
34 a partir da raiz do repositório. O script requer `git` e as ferramentas C++ do Visual Studio, configura 34
35 `LLVM_MC` para o seu usuário e pede que você abra um novo terminal para carregar a variável. 35 ```powershell
36 powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1
37 ```
38
39 O script requer `git` e as ferramentas C++ do Visual Studio, configura `LLVM_MC` para o seu usuário
40 e pede que você abra um novo terminal para carregar a variável.
36 - Se usar o WSL, instale `llvm-21` no Ubuntu e defina a variável na mesma sessão do PowerShell em que vai 41 - Se usar o WSL, instale `llvm-21` no Ubuntu e defina a variável na mesma sessão do PowerShell em que vai
37 executar `make_game.py`. 42 executar `make_game.py`.
38 43
@@ -80,7 +85,7 @@ Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runti
80## Problemas comuns 85## Problemas comuns
81 86
82- **Baixou pelo botão "Download ZIP" do GitHub**: o ZIP não inclui o submódulo `third_party/rpf9-explorer`. Use `git clone --recursive` ou execute `git submodule update --init --recursive` dentro da pasta do repositório. 87- **Baixou pelo botão "Download ZIP" do GitHub**: o ZIP não inclui o submódulo `third_party/rpf9-explorer`. Use `git clone --recursive` ou execute `git submodule update --init --recursive` dentro da pasta do repositório.
83- **`llvm-mc` recusa `gfx1013` / AMDGPU**: você provavelmente está com o instalador oficial do LLVM para Windows. Use `scripts\build_llvm_mc.ps1` ou aponte `LLVM_MC` para o `llvm-mc` do WSL (`llvm-21`). 88- **`llvm-mc` recusa `gfx1013` / AMDGPU**: você provavelmente está com o instalador oficial do LLVM para Windows. Siga um dos passos de configuração do LLVM acima.
84- **Erro de `D3D12_ROOT_SIGNATURE_DESC2` ao compilar o runtime**: atualize o Windows SDK para `10.0.26100` ou mais recente pelo Visual Studio Installer ou `winget install Microsoft.WindowsSDK.10.0.26100`, apague a pasta de build e reconfigure. 89- **Erro de `D3D12_ROOT_SIGNATURE_DESC2` ao compilar o runtime**: atualize o Windows SDK para `10.0.26100` ou mais recente pelo Visual Studio Installer ou `winget install Microsoft.WindowsSDK.10.0.26100`, apague a pasta de build e reconfigure.
85- **Falha por falta de espaço no drive `C:`**: passe `--work "D:\leonida-work"` para mover os arquivos temporários para outra partição. 90- **Falha por falta de espaço no drive `C:`**: passe `--work "D:\leonida-work"` para mover os arquivos temporários para outra partição.
86 91
@@ -91,7 +96,8 @@ Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runti
912. Rode os testes relevantes com entradas sintéticas. Por exemplo, para testar o verificador de manifestos, 962. Rode os testes relevantes com entradas sintéticas. Por exemplo, para testar o verificador de manifestos,
92 execute `python -I tests/test_manifest_verifier.py` na raiz do repositório. 97 execute `python -I tests/test_manifest_verifier.py` na raiz do repositório.
933. No PR, inclua o ID da tarefa, descreva o que testou e informe a GPU e o driver se rodou testes de GPU. 983. No PR, inclua o ID da tarefa, descreva o que testou e informe a GPU e o driver se rodou testes de GPU.
94 Indique se usou assistência de IA. Confira as regras em [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). 99 Confira as regras em [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). Se usou assistência de IA, indique
100 isso no PR, conforme [`AGENTS.md`](../../../AGENTS.md).
95 101
96O [guia de testes em GPU](../../testing.md) mostra como executar os testes sem arquivos do jogo. 102O [guia de testes em GPU](../../testing.md) mostra como executar os testes sem arquivos do jogo.
97Publique os resultados de GPU na [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). 103Publique os resultados de GPU na [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166).
diff --git a/docs/i18n/ru/quickstart.md b/docs/i18n/ru/quickstart.md
new file mode 100644
index 000000000..c22c09e79
--- /dev/null
+++ b/docs/i18n/ru/quickstart.md
@@ -0,0 +1,157 @@
1# Быстрый старт Leonida (`ru`)
2
3> [!NOTE]
4> Главный источник: английская документация ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)
5> и [`docs/README.md`](../../README.md)). Этот гайд покрывает только стабильные шаги установки и сборки
6> (сверен с коммитом `a0acd33`). Текущее состояние проекта меняется каждый день, его смотрите в
7> [`README.md`](../../../README.md).
8
9## Что такое Leonida
10
11Leonida это проект статической рекомпиляции Grand Theft Auto VI (Xbox Series): игра запускается нативно на
12Windows. Процессор консоли x86-64, как у ПК, поэтому код игры загружается и работает напрямую, а системное ПО
13консоли реализовано заново. Готовые GPU-программы RDNA2 переводятся в SPIR-V для Vulkan. Модели, текстуры и звук
14читаются из вашего пакета. Всё это происходит **на вашем ПК, из вашей копии игры**.
15
16> [!IMPORTANT]
17> В репозитории **нет ни игры, ни ключей, ни исполняемого файла**, и он не объясняет, где их взять. Нужна своя
18> копия, файлы которой уже читаются с диска. Ничто в проекте не расшифровывает данные и не обходит защиты. Всё,
19> что создаёт сборка (переведённые шейдеры, извлечённые ресурсы, рабочая папка и ваши сохранения), берётся из
20> вашей игры и **остаётся на вашем ПК**. Не выкладывайте эти файлы (см. [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)).
21
22Проект на раннем этапе: **игра пока не запускается**.
23
24## Что нужно
25
26- **Своя копия** пакета Xbox Series версии `1.0.2.1`: папка, где `MicrosoftGame.Config` и архивы `.rpf` лежат
27 обычными файлами.
28- **Windows 10/11 x64** и примерно **350 ГБ** свободного места под рабочие файлы. Их можно перенести на другой
29 диск через `--work`.
30- [Python 3.12+](https://www.python.org/downloads/) (при установке отметьте *«Add python.exe to PATH»*).
31- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
32- [Vulkan SDK](https://vulkan.lunarg.com/) для `spirv-as` и `spirv-val`.
33- [LLVM 21+](https://github.com/llvm/llvm-project/releases) с **целью AMDGPU** для `llvm-mc`:
34 - в официальной сборке LLVM для Windows цели AMDGPU нет;
35 - на Windows `scripts\build_llvm_mc.ps1` собирает свой `llvm-mc.exe` с этой целью (без WSL, нужны `git` и
36 инструменты C++ из Visual Studio ниже) и прописывает `LLVM_MC`; после этого откройте новый терминал, чтобы
37 переменная подхватилась;
38 - если ставите `llvm-21` в WSL, передайте `LLVM_MC` целой командой в той же сессии PowerShell, откуда
39 запускаете `make_game.py`:
40
41 ```powershell
42 $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'
43 ```
44
45 Подробности в [`docs/design.md`](../../design.md#disassembling-shaders);
46 - на Linux достаточно `llvm-mc` в `PATH`.
47- **Visual Studio 2022** с рабочей нагрузкой *«Разработка классических приложений на C++»* и **Windows SDK
48 `10.0.26100` или новее**: они нужны этапу `runtime`, который использует root signatures версии 1.2, а в старых
49 SDK их нет.
50- [ffmpeg](https://ffmpeg.org/download.html) в `PATH` *(по желанию: декодирует потоки XMA2, обязателен для `--wav`)*.
51
52## Как собрать
53
54### Простой способ (Windows)
55
561. Установите всё из списка выше.
572. Склонируйте проект **вместе с подмодулем**:
58 ```powershell
59 git clone --recursive https://github.com/ItsNotRexed/Leonida
60 ```
61 Кнопка «Download ZIP» на GitHub оставляет за бортом `third_party/rpf9-explorer`. Сборка подтянет его сама,
62 если установлен `git`, иначе скажет, что сделать.
633. Запустите **`Build.bat`** двойным щелчком.
64
65Скрипт сам находит копию игры: смотрит папки «Загрузки», рабочий стол, «Документы» (в том числе когда их хранит
66OneDrive), `Games`, домашнюю папку и корень каждого диска, на два уровня вглубь. Версию он определяет по
67размерам нескольких файлов, не читая больших данных. Если копий несколько, спросит, какую брать;
68если ни одной, попросит вставить путь к папке. Перед стартом он проверит, что всё из списка установлено и места
69хватает, и покажет все недостающие пункты разом. Результат пишется в `Documents\Leonida`. Прерванная
70сборка продолжается с того места, где встала.
71
72### Из терминала (`make_game.py`)
73
74```powershell
75python -I make_game.py --find # какие копии нашлись на этом ПК
76python -I make_game.py --pick # выбрать папку игры в диалоге
77python -I make_game.py --check # проверить копию, ничего не собирать
78python -I make_game.py --check --full-check # ещё и сравнить SHA-256 каждого файла (долго)
79python -I make_game.py --game "D:\путь\к\пакету" --out "D:\Games\Leonida" --work "E:\leonida-work"
80python -I make_game.py --stages shaders,assets # только часть этапов
81python -I make_game.py --game "D:\путь\к\пакету" --wav # ещё и Opus в PCM WAV (много места)
82python -I make_game.py --wave64-emulate off # auto (по умолчанию), on или off
83```
84
85Этапы идут в таком порядке: `check`, `shaders`, `assets`, `runtime`, `pipelines`. Последний создаёт все
86переведённые шейдеры на драйвере вашей видеокарты и сохраняет кеш конвейеров, чтобы при первой загрузке их не
87пришлось компилировать. Перевод шейдеров самый долгий: он выполняется в `--jobs` процессов (по умолчанию
88половина потоков процессора).
89
90- **`--wave64-emulate`**: переводить ли compute- и mesh-шейдеры wave64 так, чтобы они работали точно при любом
91 размере подгруппы (раздел «Wave64 emulation» в [`docs/design.md`](../../design.md)). У NVIDIA и Intel подгруппы
92 шириной 32, им это нужно. Режим `auto` спрашивает `vulkaninfo` из Vulkan SDK и включает эмуляцию в трёх
93 случаях: не все видеокарты сообщают подгруппы шириной 64, ответ получить не удалось, или карта для runtime не
94 умеет выполнять compute- и mesh-шейдеры на 64. Режим сохраняется рядом с переведёнными шейдерами, и его смена
95 запускает перевод заново. При `auto` рабочая папка, где эмуляция уже использовалась, держит её и дальше, даже
96 если текущая карта умеет wave64 нативно.
97- **`--work`**: выберите диск, где свободно хотя бы 350 ГБ.
98- **`--wav`**: по умолчанию выключен, потому что 16-битный PCM WAV в несколько раз больше Ogg Opus. Флаг
99 декодирует перепакованные потоки Ogg Opus в `work\assets\audio\wav` после этапа аудио; готовые WAV при
100 продолжении сборки пропускаются.
101
102Четыре запасных флага передаются переводчику так же, сохраняются рядом с шейдерами и запускают перевод заново
103при изменении: `--no-float-controls` (убрать `SignedZeroInfNanPreserve` для устройств, чья проверка конвейеров
104пропускает шейдер без `shaderSignedZeroInfNanPreserveFloat32`), `--bary-fallback` (читать сырые барицентрики из
105интерполированного входа, для устройств без `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback`
106(вносить смещения `image_sample*_o` в координату, для устройств без `VK_KHR_maintenance8`) и `--mesh-compute`
107(mesh-шейдеры как compute, для устройств без `VK_EXT_mesh_shader`). Каждый описан в
108[`docs/design.md`](../../design.md).
109
110### Linux и Wine/Proton
111
112`make_game.py` работает и на Linux. Загрузчик (`gta6rt.exe`) это программа для Windows, поэтому на Linux она
113идёт под Wine или Proton. Этап `runtime` на Linux кросс-собирается в `runtime/build/windows` через `clang-cl` и
114`lld-link`
115(LLVM 19+, но не 22.1.7 и не 22.1.8, см. [`docs/testing.md`](../../testing.md#known-problems)) против CRT от MSVC и
116Windows SDK, которые раскладывает [xwin](https://github.com/Jake-Shadle/xwin) в `XWIN_DIR` или
117`~/.local/share/xwin-sdk`. Разовый вызов `xwin` есть в
118[`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton). Если этих инструментов нет,
119этап выпадает из списка по умолчанию, а при явном запросе скрипт сразу перечислит, чего не хватает. Готовая
120сборка для Windows тоже подойдёт, например артефакт `runtime-windows` из CI:
121
122```sh
123python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows
124```
125
126В обоих случаях `gta6rt.exe` и `gta6rt_tls_host.dll` копируются в `--out`, а рядом пишется `gta6rt.sh`, который
127запускает `gta6rt.exe` через `wine` или через Wine из переменной `WINE` (для Proton это его `files/bin/wine`). На
128Windows этот же флаг пропускает сборку.
129
130## Частые проблемы
131
132- **Скачали ZIP с GitHub**: в архиве нет подмодуля `third_party/rpf9-explorer`. Используйте
133 `git clone --recursive` или выполните `git submodule update --init --recursive` в папке репозитория.
134- **`llvm-mc` не знает `gfx1013` или цель AMDGPU**: скорее всего установлен официальный LLVM для Windows.
135 Соберите свой через `scripts\build_llvm_mc.ps1` или укажите в `LLVM_MC` путь к `llvm-mc` из WSL (`llvm-21`).
136- **CMake пишет «needs the Windows SDK 10.0.26100 or newer»** или MSVC не находит `Desc_1_2` в
137 `D3D12_VERSIONED_ROOT_SIGNATURE_DESC`: поставьте Windows SDK `10.0.26100` или новее через Visual Studio
138 Installer либо `winget install Microsoft.WindowsSDK.10.0.26100`, удалите `runtime/build` и настройте заново.
139- **Кончилось место на `C:`**: передайте `--work "D:\leonida-work"`, чтобы рабочие файлы легли на другой диск.
140- **Windows не даёт запустить только что собранные тестовые программы** («An Application Control policy has
141 blocked this file»): так работает Smart App Control в Windows 11, подробности в
142 [`docs/testing.md`](../../testing.md#known-problems).
143
144## Как помочь и прогнать тесты на видеокарте
145
1461. Посмотрите открытые pull request и [issue координации][coord], чтобы не делать ту же работу дважды. Заявите
147 задачу строкой `claiming: <ID>` или одним предложением описания, если ID ещё нет.
1482. Прогоните нужные тесты на синтетических входных данных. Например, проверку манифеста:
149 `python -I tests/test_manifest_verifier.py` из корня репозитория.
1503. В pull request укажите ID задачи и то, что вы проверили, а если запускали тесты на видеокарте, ещё её модель и
151 версию драйвера. Отметьте, помогал ли вам ИИ. Все правила в [`CONTRIBUTING.md`](../../../CONTRIBUTING.md).
152
153[Руководство по тестам на видеокарте](../../testing.md) объясняет, как обойтись без файлов игры. Результаты
154складывают в [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166), по одному комментарию на карту и
155драйвер.
156
157[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/zh-CN/quickstart.md b/docs/i18n/zh-CN/quickstart.md
index c316e65da..3cf73de36 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 `e7584c5` 同步)。 5> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `003e7812` 同步)。
6> 项目每日进展请查看 [`README.md`](../../../README.md)。 6> 项目每日进展请查看 [`README.md`](../../../README.md)。
7 7
8## Leonida 是什么 8## Leonida 是什么
@@ -48,14 +48,16 @@ Leonida 是一个把 Xbox Series 版 Grand Theft Auto VI **静态重编译**到
48 48
493. 双击 **`Build.bat`**。 493. 双击 **`Build.bat`**。
50 50
51脚本会自动查找你的拷贝(Downloads、Desktop、Documents、Games、用户目录以及每个盘的根目录往下两层), 51脚本会自动查找你的拷贝(Downloads、Desktop、Documents(也包括 OneDrive 等 Windows 实际存放它的位置)、Games、
52检查前置条件和可用空间,结果写到 `Documents\Leonida`。构建中断后重新运行即可从断点继续。 52用户目录以及每个盘的根目录往下两层),检查前置条件和可用空间,结果写到 `Documents\Leonida`。构建中断后重新运行即可从断点继续。
53 53
54### 命令行(`make_game.py`) 54### 命令行(`make_game.py`)
55 55
56```powershell 56```powershell
57python -I make_game.py --find # 列出本机找到的拷贝 57python -I make_game.py --find # 列出本机找到的拷贝
58python -I make_game.py --pick # 在文件夹对话框里选择游戏目录
58python -I make_game.py --check # 校验游戏文件,不构建 59python -I make_game.py --check # 校验游戏文件,不构建
60python -I make_game.py --check --full-check # 另外比对每个文件的 SHA-256(较慢)
59python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work" 61python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work"
60python -I make_game.py --stages shaders,assets # 只跑指定阶段 62python -I make_game.py --stages shaders,assets # 只跑指定阶段
61python -I make_game.py --game "D:\path\to\package" --wav # 额外把 Ogg Opus 解码为 PCM WAV(很大) 63python -I make_game.py --game "D:\path\to\package" --wav # 额外把 Ogg Opus 解码为 PCM WAV(很大)
@@ -64,11 +66,26 @@ python -I make_game.py --wave64-emulate auto # auto(默认)、o
64 66
65阶段顺序:`check` → `shaders` → `assets` → `runtime` → `pipelines`。 67阶段顺序:`check` → `shaders` → `assets` → `runtime` → `pipelines`。
66 68
67- **`--wave64-emulate`**:在 32 lane 子组的 GPU(NVIDIA、Intel)上模拟 compute/mesh 的 wave64。 69- **`--wave64-emulate`**:决定是否把 wave64 compute/mesh 着色器翻译成在任意子组宽度下都精确的版本
68 默认 `auto` 会询问 `vulkaninfo`,需要时自动启用。 70 (见 [`docs/design.md`](../../design.md) 中 Wave64 emulation 一行)。NVIDIA 和 Intel GPU 是 32 lane 子组,
71 需要它。默认 `auto` 会询问 `vulkaninfo`(属于 Vulkan SDK),除非所有 GPU 都报告 64 宽子组、或无法判断,
72 都会启用;运行时实际使用的 GPU 无法以 64 宽运行 compute/mesh 时也会启用。有一个例外会让它保持关闭:当运行时的
73 GPU 是 RDNA2 独显或核显(RX 6000、Ryzen 6000/7000/9000 的核显)、使用 AMD Windows 驱动并原生运行 wave64 时
74 ——该驱动的着色器编译器在模拟 LDS 代码上会崩溃(#857);否则 Intel 核显搭配 RX 6000 卡时也会被启用。
75 该模式会保存在翻译后的着色器旁边,切换它会重新翻译。使用 `auto` 时,之前用过模拟的工作目录在后续翻译和重试中
76 会继续使用模拟,即使当前 GPU 支持原生 wave64;要用原生方式翻译,使用 `--wave64-emulate off`。
77- **四个 fallback 标志**:它们同样转发给翻译器、保存在翻译后的着色器旁边,切换会重新翻译:
78 `--no-float-controls`(去掉 `SignedZeroInfNanPreserve`,用于设备在缺少
79 `shaderSignedZeroInfNanPreserveFloat32` 时会跳过着色器;需要 PR #664 的翻译器标志)、
80 `--bary-fallback`(从插值输入读取原始重心坐标,用于没有 `VK_KHR_fragment_shader_barycentric` 的设备)、
81 `--texel-offset-fallback`(把 `image_sample*_o` 的偏移折叠进坐标,用于没有 `VK_KHR_maintenance8` 的设备)和
82 `--mesh-compute`(把 mesh 着色器当作 compute,用于没有 `VK_EXT_mesh_shader` 的设备)。每个标志的说明见
83 [`docs/design.md`](../../design.md)。
69- **`--work`**:建议指向至少有 350 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。 84- **`--work`**:建议指向至少有 350 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。
70- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和 85- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和
71 lld-link(LLVM 19+)把 loader 交叉编译到 `runtime/build/windows`,依赖 `XWIN_DIR` 或 86 lld-link(LLVM 19+,但 22.1.7 和 22.1.8 有已知问题,见 [docs/testing.md](../../testing.md#known-problems);
87 命令名用不带版本后缀的,或五个 LLVM 工具都用同一版本后缀,例如 `clang-cl-21`)把 loader 交叉编译到
88 `runtime/build/windows`,依赖 `XWIN_DIR` 或
72 `~/.local/share/xwin-sdk` 里的 MSVC CRT 和 Windows SDK 89 `~/.local/share/xwin-sdk` 里的 MSVC CRT 和 Windows SDK
73 ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) 有一次性 `xwin` 命令); 90 ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) 有一次性 `xwin` 命令);
74 缺少这些时该阶段不参与默认 stages,显式请求会先列出缺什么。 91 缺少这些时该阶段不参与默认 stages,显式请求会先列出缺什么。
diff --git a/docs/mission_logic.md b/docs/mission_logic.md
index 8f754556e..af6ac4a10 100644
--- a/docs/mission_logic.md
+++ b/docs/mission_logic.md
@@ -103,7 +103,56 @@ are no opcodes here, and no jump table. Two consequences for a runtime:
103 103
104## Mission identity 104## Mission identity
105 105
106The package's own text metadata carries a 145-entry mission table. Only **one** of those ids is provably 106The package's own text metadata carries a 145-entry mission table. Two of those ids now have a
107bound to one of these tables, so most outlines are unattributed. Joining ids to tables is an open problem; 107reproducible binding to one of these tables, so most outlines are still unattributed. Joining ids to
108a plain joaat of the ids does not appear in the program data (0 of 290 variants in 170.9 MB), so the join 108tables is an open problem; a plain joaat of the ids does not appear in the program data (0 of 290
109is not by name hash. 109variants in 170.9 MB), so the join is not by name hash.
110
111## Binding a mission id to its tables
112
113This binding does not join on the id. It uses a **character** as the bridge: the mission's own text names
114a person, a name dictionary turns that name into a 32-bit hash, and the same hash appears as the
115`linkHash` of pool elements in a state table.
116
1171. **Start from a name the mission text uses.** `COM_KBOS_NEIGHB` is the replay-table id for the mission
118 publicly catalogued as **Pipework** (Mandy's rent). The text table at `data.rpf` stream
119 `0x19957A0` contains the line "You brought the cops to Mandy's house" and the line "Bert died".
120 The stream carries no mission id; the id-to-text step rests on the public name and the cast, not an
121 archive key.
1222. **Resolve the character and its schedule.** `common.rpf` stream `0x4C270` lists
123 `KeyLento/Perschars/Peds/Unique/Mandy` and `.../Bert` under the pack `PSP_KeyLento_perschars_peds`.
124 SixNG's name dictionary, which is lower-case joaat, resolves the pack to `0x865F0DA9`, Mandy to
125 `0x03A885E6` and Bert to `0xE34ACBC8`.
1263. **Scan the PSINs for the link hash.** In the 64-byte element above, `linkHash` is the dword at byte
127 `+0x34`, not the archetype dword. Inflating the five `story000_script.rpf` streams at `0x3FE4000`,
128 `0x3FE8000`, `0x3FEB000`, `0x3FEE000` and `0x3FF0000` and searching for those two hashes finds 28
129 elements: 15 Mandy and 13 Bert. A scan of all 2,309 PSIN streams finds those 28 hits in exactly these
130 five files.
1314. **Read the element.** Its start is `linkHash - 52`. The first dword is the archetype/state hash
132 described above. It does not resolve in the name dictionary, and the same character takes three
133 values, so it is an archetype/state hash rather than a character model name.
134
135| stream | Mandy elements | Mandy archetype | Bert elements | Bert archetype |
136|---|---:|---|---:|---|
137| `0x3FE4000` | 5 | `0x18BB2550` | 5 | `0xA5A1E67D` |
138| `0x3FE8000` | 3 | `0x73E83886` | 3 | `0x780A05A5` |
139| `0x3FEB000` | 3 | `0x73E83886` | 4 | `0x780A05A5` |
140| `0x3FEE000` | 3 | `0x73E83886` | 0 | - |
141| `0x3FF0000` | 1 | `0x57DDFFC2` | 1 | `0xCBA48304` |
142
143Mandy has three distinct archetype values in this set and Bert three; none resolves in the name
144dictionary.
145
146The five tables are bound to `COM_KBOS_NEIGHB` through two people the mission's own text names, both
147present as link hashes in the same five streams. It is a binding by cast, not by id: the public
148`Pipework` name is the outside link between the id and the text, and a mission whose cast is not in the
149dictionary still has no bridge.
150
151It does **not** turn `0x18BB2550`, `0x73E83886`, `0x57DDFFC2`, `0xA5A1E67D`, `0x780A05A5` or
152`0xCBA48304` into model names. None resolves in the same dictionary, and the first dword changes per
153state; it is an archetype/state hash, not a Mandy or Bert drawable. The table that would name those
154archetypes is not in the readable archives.
155
156This is **one more binding, not a general solution**. The other 143 ids in the mission table remain
157unattributed unless a character, schedule or other stable name gives them a bridge; joining ids to
158tables is still an open problem.
diff --git a/docs/models.md b/docs/models.md
index 61b0e9f2b..90d31c1a8 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -2,12 +2,8 @@
2 2
3Measured state of `tools/rpf9dump models` on the Xbox Series 1.0.2.1 package, and the 3Measured state of `tools/rpf9dump models` on the Xbox Series 1.0.2.1 package, and the
4upstream `rpf9-explorer` fixes that close it. The fixes are merged upstream and the submodule is 4upstream `rpf9-explorer` fixes that close it. The fixes are merged upstream and the submodule is
5pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**2.64 billion 5pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**0 decode
6triangles**, **0 decode failures**), up from 350,248 at `917e9b9` and 190,792 at `c3708fb`. 6failures**), up from 350,251 at `917e9b9` and 190,792 at `c3708fb`.
7upstream `rpf9-explorer` fix that closes it. The fix is merged upstream and the submodule is
8pinned at `e293917` (the 350,251-model counts below were measured at `917e9b9`, before
9upstream `v1.2` PRs #8-#12 landed; the non-`levels.rpf` archives were then re-counted at
10`e293917`).
11 7
12Before the fix, the exporter did not reject any vertex or index layout in the tested archives. It 8Before the fix, the exporter did not reject any vertex or index layout in the tested archives. It
13dropped valid models in three validation paths, all in `third_party/rpf9-explorer` at commit 9dropped valid models in three validation paths, all in `third_party/rpf9-explorer` at commit
@@ -23,13 +19,11 @@ per entry), the TTPF compact/array/cubemap/volume layouts, and the external draw
23reader. Commits `917e9b9..e293917` add upstream `v1.2` model-discovery changes (PRs #8–#12: 19reader. Commits `917e9b9..e293917` add upstream `v1.2` model-discovery changes (PRs #8–#12:
24optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit 20optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit
25bone-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
26decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,533** 22decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,530**
27over `917e9b9`'s 350,248) and **2,636,248,990 triangles** with **0 decode failures**; the earlier 23over `917e9b9`'s 350,251) with **0 decode failures**; the `levels.rpf` fragment, bone-binding and
24triangle cells are not independently reproduced (see the table note), and the earlier
28`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
29measured state; it is not a competing patch. 26measured state; it is not a competing patch.
30decoding (PR #7). The 350,251-model counts below were measured at `917e9b9` and are kept as the
31control; the `e293917` re-count for the non-`levels.rpf` archives is in the table below. This page
32records both, and is not a competing patch.
33 27
34PR #1 reports 190,792 of 190,792 recognized candidates across the ten archives configured in 28PR #1 reports 190,792 of 190,792 recognized candidates across the ten archives configured in
35Leonida, including 169 previously rejected candidates (also verified after archive readback). A 29Leonida, including 169 previously rejected candidates (also verified after archive readback). A
@@ -63,18 +57,25 @@ effect of upstream `v1.2` PRs #8–#12:
63| `data.rpf` | 2,921 | **3,175** | 268 | 2,907 | 1,758 | 2,891 | 3,387,016 | 0 | +594 | 57| `data.rpf` | 2,921 | **3,175** | 268 | 2,907 | 1,758 | 2,891 | 3,387,016 | 0 | +594 |
64| `pack/shared_minigame000/...` | 1,058 | **1,294** | 317 | 977 | 10 | 18 | 16,843,903 | 0 | +6 | 58| `pack/shared_minigame000/...` | 1,058 | **1,294** | 317 | 977 | 10 | 18 | 16,843,903 | 0 | +6 |
65| `pack/core_restofworld/...` | 924 | **936** | 808 | 128 | 53 | 849 | 1,239,596 | 0 | +51 | 59| `pack/core_restofworld/...` | 924 | **936** | 808 | 128 | 53 | 849 | 1,239,596 | 0 | +51 |
66| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | +3 | 60| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | 0 |
67| `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 |
68| `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 |
69| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | 50,731 | 59,544 | 2,509,947,536 | 71 | +29,327 | 63| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | † | † | † | 71 | +29,327 |
70| `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 64| `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
71| `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 |
72| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **55,417** | **89,887** | **2,636,248,990** | **72** | **+32,533** | 66| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **†** | **†** | **†** | **72** | **+32,530** |
67
68† `levels.rpf` was counted with `count.exe recover --verify`, which reports candidates, models,
69dictionary children, standalone models, rejects and decode failures only: no `levels.rpf` manifest
70exists and the harness emits no fragment, bone-binding or triangle field. Those three `levels.rpf`
71cells, and the totals that would include them, are therefore **not independently reproduced**. The
72other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles.
73 73
74Every recovered entry was read back from its archive segments and decoded through 74Every recovered entry was read back from its archive segments and decoded through
75`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**, **4,090,898 meshes**, 75`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**. The other archives
76**2,468,402,149 vertices**, **2,636,248,990 triangles (2.64 billion)**, and **1,805 embedded 76measure **236,311 meshes**, **104,183,438 vertices**, **126,301,454 triangles** and **512 embedded
77textures**. 77textures**; the `levels.rpf` mesh/vertex/triangle/embedded cells are not independently reproduced
78(see the table note).
78 79
79What moved between `917e9b9` and `e293917`: 80What moved between `917e9b9` and `e293917`:
80 81
@@ -89,13 +90,13 @@ What moved between `917e9b9` and `e293917`:
89 `data.rpf` (75 → 0), `core_restofworld` (140 → 0), and `shared_minigame000` (18 → 0). Only one 90 `data.rpf` (75 → 0), `core_restofworld` (140 → 0), and `shared_minigame000` (18 → 0). Only one
90 texture-dictionary candidate remains across all ten archives (in `textures.rpf`; rejected cleanly, 91 texture-dictionary candidate remains across all ten archives (in `textures.rpf`; rejected cleanly,
91 and recovered by `Rpf9TextureRecovery`). 92 and recovered by `Rpf9TextureRecovery`).
92- **Probe caps and zero-radius drawables (+28 dictionary children plus capped standalones).** 93- **Probe caps and zero-radius drawables (+25 dictionary children plus capped standalones).**
93 Upstream [rpf9-explorer#11](https://github.com/breadbbbb/rpf9-explorer/pull/11) recovers the 29 94 Upstream [rpf9-explorer#11](https://github.com/breadbbbb/rpf9-explorer/pull/11) recovers the 29
94 previously capped candidates (+1 in `story000.rpf`, and +14 dictionary children plus capped 95 previously capped candidates (+1 in `story000.rpf`, and +14 dictionary children plus capped
95 standalones in `levels.rpf`). Upstream 96 standalones in `levels.rpf`). Upstream
96 [rpf9-explorer#12](https://github.com/breadbbbb/rpf9-explorer/pull/12) recovers all 11 zero-radius 97 [rpf9-explorer#12](https://github.com/breadbbbb/rpf9-explorer/pull/12) recovers all 11 zero-radius
97 dictionary children in `core_restofworld` (797 → 808) and 1 drawable dictionary (3 models) in 98 dictionary children in `core_restofworld` (797 → 808); `story000_restofworld.rpf` already
98 `story000_restofworld.rpf`, which previously recovered 0 models. 99 recovered its 3 models at `917e9b9`, so its delta is 0.
99- **Remaining 72 rejects (down from 1,282 at `917e9b9`).** Aside from the single texture-dictionary 100- **Remaining 72 rejects (down from 1,282 at `917e9b9`).** Aside from the single texture-dictionary
100 candidate in `textures.rpf`, all 71 remaining rejects are in `levels.rpf` (0 texture dictionaries, 101 candidate in `textures.rpf`, all 71 remaining rejects are in `levels.rpf` (0 texture dictionaries,
101 0 zlib checksum errors). Sampled headers are fragment candidates (`LooksLikeFragment == true`) 102 0 zlib checksum errors). Sampled headers are fragment candidates (`LooksLikeFragment == true`)
@@ -165,7 +166,7 @@ pages. `core_restofworld` recovers 873 of its 1,024 candidates (885 models); the
165models**, 130,225 dictionary children, 183,775 standalone. 1,037 candidates are rejected: the 166models**, 130,225 dictionary children, 183,775 standalone. 1,037 candidates are rejected: the
1661,009 in the last shard are texture dictionaries, not models, and 28 more in shards 1 to 7 are 1671,009 in the last shard are texture dictionaries, not models, and 28 more in shards 1 to 7 are
167models the probe caps reject (see [rejected candidates](#rejected-candidates-at-917e9b9)). The 168models the probe caps reject (see [rejected candidates](#rejected-candidates-at-917e9b9)). The
168`levels.rpf` full export was not re-run, so its triangle total is still the old measurement. 169`levels.rpf` full export was not re-run, so its triangle total is not re-run here.
169 170
170### Rejected candidates at `917e9b9` 171### Rejected candidates at `917e9b9`
171 172
@@ -248,11 +249,8 @@ The `packs.rpf` row is the pre-dictionary-root control: at `917e9b9` that archiv
24824,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above. 24924,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above.
249The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251, 250The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251,
250and the `e293917` re-count outside `levels.rpf` is 39,454. Triangle totals have not been re-run at 251and the `e293917` re-count outside `levels.rpf` is 39,454. Triangle totals have not been re-run at
251either new pin. 252either new pin; the `e293917` `levels.rpf` geometry cells are not independently reproduced (see
25224,034 models (26,585 at `e293917`), and the other archives' counts are in the tables above. The 253the table note above).
253rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,248.
254Triangle totals for that pin have not been re-run; the current `e293917` totals are in the
255full-archive table above.
256 254
257At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback 255At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback
258failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The 256failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The
@@ -505,7 +503,8 @@ own light bones).
5051. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream. 5031. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream.
5062. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`). 5042. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`).
5073. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781 5053. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781
508 models**, **2,636,248,990 triangles**, **0 decode failures**; table above). 506 models**, **0 decode failures**; table above; the `levels.rpf` geometry cells are not
507 independently reproduced).
5094. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1 5084. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1
510 texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted. 509 texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted.
5115. Keep issue #29 in sync with the `e293917` counts. 5105. Keep issue #29 in sync with the `e293917` counts.
diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md
index 51ae4281f..2066671bb 100644
--- a/docs/pipeline_check.md
+++ b/docs/pipeline_check.md
@@ -9,6 +9,8 @@ the Vulkan implementation, not that the shader results are correct. Value-level
9The checker exits nonzero if a module fails to load, a pipeline fails to compile, or the requested final 9The 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 10cache save fails. It still finishes checking the other entries and attempts the final save so the next run
11can reuse successful pipelines. Entries reported as skipped do not count as failures. 11can reuse successful pipelines. Entries reported as skipped do not count as failures.
12It also exits 2, before loading Vulkan, if `index.json` is missing, unreadable, empty or malformed, so a wrong
13directory can't pass as an empty corpus. A valid `{}` is an intentionally empty index.
12 14
13## Check user-defined interfaces between stages 15## Check user-defined interfaces between stages
14 16
@@ -138,6 +140,42 @@ The report above therefore states the limit and the skip count; a later run on a
138completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility 140completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility
139tool, not a pass: a skipped module has not been validated. 141tool, not a pass: a skipped module has not been validated.
140 142
143## Crash isolation (`--isolate`)
144
145A driver that dies while compiling one module (for example the RADV `SIGFPE` in
146[#1721](https://github.com/ItsNotRexed/Leonida/issues/1721)) ends the whole process, so the rest of the corpus
147used to need that module excluded by hand with `--start/--count`. With `--isolate` (POSIX only; on Windows it
148prints an error and exits with 2) the tool runs the check in child processes instead:
149
150```sh
151vk_pipeline_check <spirv dir> cache.bin --isolate [--isolate-batch 256] [--jobs N ...]
152```
153
154- The parent opens no Vulkan device. It runs this executable, one child at a time, over `--isolate-batch`
155 modules (default 256) of the same sorted, stage-filtered list, with the other options passed on (`--jobs` is
156 the thread count inside each child). `--stats` is refused: children would overwrite one file.
157- A child that is killed by a signal, or exits without finishing the pass after it started work, has its output
158 discarded and its batch is bisected (re-run in halves) down to the module that kills it. That module is printed as
159 `MODULE CRASH <name> (<stage>, driver crashed: SIGFPE)`, counted as a failed pipeline and listed at the end;
160 the other modules are checked as usual and counted once. If both halves of a crashed batch run clean (a crash
161 that needs several threads at once), the batch is reported as `MODULE CRASH [a, b) not reproduced ...` and
162 counts as a failure. A child that fails before it starts work (no device, bad arguments) stops the run
163 with exit status 1.
164- The pipeline cache: children run one after another and each seeds from and saves to the same `cache.bin`,
165 like the chunked runs above; the save is atomic, a crashed child saves nothing, so the file stays valid and
166 holds everything the finished children compiled. The parent prints its size at the end.
167- Exit status: 0 only if no module failed or crashed and the cache saved; 1 otherwise. The summary is
168 aggregated by the parent (modules, pipelines, skips, `--cache-feedback`); the per-stage wave and compile-time lines
169 of a normal run are not repeated. Output of a batch appears when its child finishes.
170- Each child loads the cache again, so a very large cache makes small batches slow; raise `--isolate-batch`.
171 There is no timeout: a hung compile still hangs.
172
173Test hook, not for normal use: `VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL]` makes the
174process raise `SIGNAL` (default `SIGFPE`; `SEGV`, `ABRT`, `KILL`, ... also accepted) just before the pipeline of a
175matching module is created. `tests/test_vk_pipeline_check_isolate.py` uses it with five hand-assembled compute
176shaders to check `--isolate` without a crashing driver; it skips when the tool isn't built or there is no
177Vulkan device.
178
141## Application pipeline-cache feedback 179## Application pipeline-cache feedback
142 180
143With `--cache-feedback`, the checker groups successful pipeline creations by translated shader stage 181With `--cache-feedback`, the checker groups successful pipeline creations by translated shader stage
diff --git a/docs/psin.md b/docs/psin.md
index 22ac8ab15..9999e89a9 100644
--- a/docs/psin.md
+++ b/docs/psin.md
@@ -467,6 +467,21 @@ section, truncated data, trailing bytes and the JSON CLI, and the `LSCH`/`LENM`
467a count that fits nothing and both schema checks. It uses synthetic headers and joaat hashes of invented names 467a count that fits nothing and both schema checks. It uses synthetic headers and joaat hashes of invented names
468only. 468only.
469 469
470### Viewing a container in ImHex
471
472[tools/imhex/psin.hexpat](../tools/imhex/psin.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex
473editor that lays out one container as this page describes it:
474- the header, the instance-data block table with its `pppppppp` end, and the blocks, as raw bytes;
475- the section chain;
476- the `LSCH` struct headers and members, and the `LENM` enums and values, with the header count found by the same
477 fill-exact rule as `psin_index.py`;
478- the `LSNS` block table and its opaque 16-byte records;
479- the `LRSC` `0DRP` version and root block, and the `CHKS` file size.
480
481A section that runs past the end of a truncated stream is shown as raw bytes. `tests/test_imhex_patterns.py` builds a
482synthetic container, checks it with `psin_index.py` and `psin_data.block_table`, and when ImHex is installed compares
483the pattern's output with both.
484
470## Limits 485## Limits
471 486
472- The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent 487- The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent
diff --git a/docs/rbf0.md b/docs/rbf0.md
index 5ccdb5a8a..3e6779cb3 100644
--- a/docs/rbf0.md
+++ b/docs/rbf0.md
@@ -468,8 +468,16 @@ python -I tools/rbf0_tree.py <work>\data-carve <work>\subtitle.json --root CMovi
468# Unit tests: synthetic headers and trees only 468# Unit tests: synthetic headers and trees only
469python -I tests/test_rbf0_index.py 469python -I tests/test_rbf0_index.py
470python -I tests/test_rbf0_tree.py 470python -I tests/test_rbf0_tree.py
471python -I tests/test_imhex_patterns.py
471``` 472```
472 473
474To look at one resource in a hex editor, open the inflated and joined resource (not the archive) in
475[ImHex](https://imhex.werwolv.net/) with [tools/imhex/rbf0.hexpat](../tools/imhex/rbf0.hexpat). The pattern follows
476the grammar in section 3, picks the 8- or 4-byte value width from the prologue, and stops where the root element
477closes. `tests/test_imhex_patterns.py` builds wide and narrow streams with every record type, checks them with
478`rbf0_index.parse_rbf0`, and when ImHex is installed (on `PATH`, in its default Windows folder, or named by
479`LEONIDA_IMHEX`) compares the pattern's output with the parser's.
480
473`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a 481`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a
474one-line error and exit code 2 before an index is written. 482one-line error and exit code 2 before an index is written.
475 483
diff --git a/docs/rpf.md b/docs/rpf.md
index 3f0865ab9..ffc6d34e2 100644
--- a/docs/rpf.md
+++ b/docs/rpf.md
@@ -69,6 +69,13 @@ both paths. It is used to check exported assets without keeping a second copy.
69of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It 69of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It
70does not decode a resource or need the TOC; see [resource_names.md](resource_names.md). 70does not decode a resource or need the TOC; see [resource_names.md](resource_names.md).
71 71
72### Viewing a header in ImHex
73
74[tools/imhex/rpf9.hexpat](../tools/imhex/rpf9.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex
75editor. It names the magic and the data offset at `+4`, shows the u32s at `+8` and `+12` unnamed, and shows the range
76from `+0x10` to the data offset (the rest of the header and the TOC) as one opaque byte array. It decodes nothing in
77that range. `python -I tests/test_imhex_patterns.py` runs it on a synthetic header when ImHex is installed.
78
72## Limits 79## Limits
73 80
74- The TOC is the hard boundary. File names, original paths and the exact file boundaries come from the TOC, 81- The TOC is the hard boundary. File names, original paths and the exact file boundaries come from the TOC,
diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md
index 6761ff227..b5d099062 100644
--- a/docs/runtime_imports.md
+++ b/docs/runtime_imports.md
@@ -41,21 +41,23 @@ All 16 DLLs in the package map at their preferred base `0x180000000` with no rel
41| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 3 | 54 | 0 | 0 | 41| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 3 | 54 | 0 | 0 |
42| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 5 | 81 | 0 | 0 | 42| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 5 | 81 | 0 | 0 |
43| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 4 | 18 | 0 | 0 | 43| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 4 | 18 | 0 | 0 |
44| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 7 | 191 | 0 | 0 | 44| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 10 | 188 | 0 | 0 |
45| `XCurl.dll` | 188,416 | `0x17b0` | 7 | 133 | 0 | 0 | 45| `XCurl.dll` | 188,416 | `0x17b0` | 8 | 132 | 0 | 0 |
46| `concrt140.dll` | 303,104 | `0x29160` | 1 | 102 | 0 | 0 | 46| `concrt140.dll` | 303,104 | `0x29160` | 1 | 102 | 0 | 0 |
47| `msvcp140.dll` | 577,536 | `0x525a0` | 5 | 182 | 0 | 0 | 47| `msvcp140.dll` | 577,536 | `0x525a0` | 9 | 178 | 0 | 0 |
48| `msvcp140_1.dll` | 36,864 | `0x15c0` | 1 | 32 | 0 | 0 | 48| `msvcp140_1.dll` | 36,864 | `0x15c0` | 1 | 32 | 0 | 0 |
49| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 1 | 95 | 0 | 0 | 49| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 1 | 95 | 0 | 0 |
50| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 3 | 61 | 0 | 0 | 50| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 3 | 61 | 0 | 0 |
51| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 1 | 23 | 0 | 0 | 51| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 1 | 23 | 0 | 0 |
52| `vccorlib140.dll` | 344,064 | `0x27e50` | 6 | 108 | 0 | 0 | 52| `vccorlib140.dll` | 344,064 | `0x27e50` | 6 | 108 | 0 | 0 |
53| `vcomp140.dll` | 86,016 | `0x6580` | 3 | 75 | 0 | 0 | 53| `vcomp140.dll` | 86,016 | `0x6580` | 7 | 71 | 0 | 0 |
54| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 | 54| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 |
55| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 | 55| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 |
56 56
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. 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.
58 58
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.
60
59The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in 61The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in
60[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): 62[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi):
61 63
@@ -139,10 +141,32 @@ pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name
139with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. 141with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged.
140 142
141`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK 143`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK
142version and mode once. `QueryApiImpl` logs each class and interface id it is asked for and returns `0x80070032`, the 144version and mode once. `QueryApiImpl` serves `XThreadingImpl` and `XErrorImpl` (below); for any other class it logs
143documented error for a class the runtime doesn't provide. The class method layouts are not known yet, so the first 145the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so
144boot with the executable lists the interfaces to implement next. `xgameruntime_test` drives this path through the 146the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through
145api-set binding `XCurl.dll` uses. 147the api-set binding `XCurl.dll` uses, and calls the two classes slot by slot.
148
149### Class layouts, measured
150
151Each `xgameruntime.lib` function the package's DLLs link is a thunk of the same shape: it calls a helper with the
152class id (passed as both the class and the interface id), which initializes the runtime once and calls
153`QueryApiImpl`; then it calls one vtable slot with `this` followed by the function's own arguments, and calls
154`Release` (slot 2). The helper treats `0x80040154` (class not registered) from `QueryApiImpl` specially: it turns it
155into `0x89240107` and calls an error hook; any other failure is returned as is.
156
157The slots below were read from the thunks statically linked into `libHttpClient.GDK.dll` and `XCurl.dll`
158(disassembled with `llvm-objdump`; no code was run, nothing else read). Every slot called matches, in argument
159count and width, the function at that position of xgameruntime-docs' "Layout" list after IUnknown's three slots:
160
161| Class | Slots called | Checked against the documented order |
162|---|---|---|
163| `XThreadingImpl` (`IXThreadingImpl`, 28 methods, slots 3-30) | 3-7 and 9-30 (`libHttpClient.GDK.dll`), 3, 5, 12, 16-18, 22, 29 (`XCurl.dll`) | e.g. 7 `XAsyncBegin` (5 args), 9 `XAsyncSchedule` (pointer, 32-bit), 10 `XAsyncComplete` (pointer, HRESULT, size), 12 `XTaskQueueCreate` (two 32-bit modes, pointer), 16 `XTaskQueueDispatch` (returns a byte), 19 `XTaskQueueSubmitDelayedCallback` (5 args), 22 `XTaskQueueTerminate` (pointer, bool, two pointers), 27 `XThreadSetTimeSensitive` (bool), 30 `XThreadIsTimeSensitive` (returns a byte). Slot 8 (`XAsyncBeginAlloc`, private) is never called; slot 28 (`XTaskQueueIsEmpty`, private) takes no arguments |
164| `XErrorImpl` (`IXErrorImpl`, slots 3-5) | 3 (`XCurl.dll`) | slot 3, the docs' `_unknown_`, takes an HRESULT and a pointer: `XErrorReport(HRESULT, const char*)` |
165| `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Not served yet |
166
167`XThreadingImpl` forwards each slot to `third_party/xtaskqueue`, the same implementation the named exports use;
168`XThreadSetTimeSensitive`/`XThreadIsTimeSensitive` keep a per-thread flag and the two private slots log once and
169answer 0. `XErrorImpl` logs each report and hands it to the callback `XErrorSetCallback` set.
146 170
147Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that 171Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that
148xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): 172xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read):
diff --git a/docs/saves.md b/docs/saves.md
index 48136dc7f..4f8fcaeef 100644
--- a/docs/saves.md
+++ b/docs/saves.md
@@ -101,12 +101,15 @@ to it holds the same save. The wrapper's header is the only place the autosave's
101 101
102## Importing into the runtime 102## Importing into the runtime
103 103
104`runtime/shims/xgameruntime_services.cpp` (#279) keeps `XGameSave` data in 104The offline XGameSave shim of the open #279 (`xgameruntime_services.cpp` there; **not on `main` yet**, where the
105`XGameSave*` imports have no implementation and get the loader's default answers, classified in
106`runtime/shims/registry.cpp`) keeps `XGameSave` data in
105`LEONIDA_SAVE_DIR\local-user\<container>\<blob>`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, with names 107`LEONIDA_SAVE_DIR\local-user\<container>\<blob>`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, with names
106%-encoded. `python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB]` writes payloads 108%-encoded. `python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB]` writes payloads
107in that layout with the same encoding, plus `import-manifest.json` (source, size, SHA-256). 109in that layout with the same encoding, plus `import-manifest.json` (source, size, SHA-256).
108 110
109Checked: four imported blobs (2 KB to 1.2 MB) read back byte-identical through the shim's `XGameSaveReadBlobData`. 111Checked with #279's shim: four imported blobs (2 KB to 1.2 MB) read back byte-identical through its
112`XGameSaveReadBlobData`.
110 113
111**VERIFY:** the title's real container and blob names. The default is container = slot name and blob = payload file 114**VERIFY:** the title's real container and blob names. The default is container = slot name and blob = payload file
112name, and `--map` overrides it. Confirm or fix them from the executable's `XGameSaveCreateContainer` and 115name, and `--map` overrides it. Confirm or fix them from the executable's `XGameSaveCreateContainer` and
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index fc7b3d5ac..97cf8309a 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -13,9 +13,11 @@ harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py`
13check that the module computes what the RDNA2 program computes. Those are different questions, and 13check that the module computes what the RDNA2 program computes. Those are different questions, and
14this repository already has cases where only the second question had a useful answer: 14this repository already has cases where only the second question had a useful answer:
15 15
16- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2), yet the SDWA source/destination 16- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2) at `43d4703`, after `dcd8ecf` fixed
17 selects were silently ignored until 2026-11-20. That passed validation for 3,826 of the 13,926 17 the ID-bound regression (#881); the intervening `dedd75c` run was 26,501, and `793b06f` before
18 translated shaders and produced wrong values (`docs/design.md`, "SDWA"). 18 #223's LLVM 23 source-field fix was 25,032. Yet the SDWA source/destination selects were silently
19 ignored until 2026-11-20: validation passed for 3,826 of the 13,926 shaders translated at the time
20 and produced wrong values (`docs/design.md`, "SDWA").
19- The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5` 21- The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5`
20 for a compressed pair, and the translated shader exported `(r, g, r, g)`. 22 for a compressed pair, and the translated shader exported `(r, g, r, g)`.
21- `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke 23- `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke
@@ -255,6 +257,34 @@ RDNA4 (Radeon RX 9070, gfx1201, driver 26.11.2, `rocm-sdk-core` 10.0.0 clang): 1
255500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With 257500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With
256`--oracle translator,hw`, 200 of 200 programs matched (seed 1). 258`--oracle translator,hw`, 200 of 200 programs matched (seed 1).
257 259
260#### RDNA2 integer rows (`tools/int_hw_probe.py`, SHADER-137)
261
262`tools/int_hw_probe.py` runs 87 hand-written cases across 19 integer groups (both wave32 and wave64) natively on
263an AMD GPU through `tools/hw_oracle` and compares every output word against `tools/rdna2spirv.py` +
264`tests/semantic/spirv_mini_interp.py` (with scalar ops run twice, SCC preset to 0 and 1, so SCC written vs kept is
265observed directly).
266
267Measured on an **AMD Radeon 680M (gfx1035, RDNA2)**, Windows 11 (`10.0.26300`), AMD driver `26.5.1`
268(`32.0.21043.7012`, `amdhip64_6.dll`), conda-forge `clang 22.1.8` + `lld 23.1.6` (`--oracle both --wave both`):
269**87 cases: 82 bit-exact matches, 5 known live translator divergences, 0 unexpected mismatches, 0 wave32/wave64
270differences** (plus `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`: 500/500 match).
271
272- **Matched RDNA2 silicon in both wave32 and wave64 (82/87):** `s_absdiff_i32`, `s_mul_hi_i32/u32`, `s_lshl1..4_add_u32`
273 (64-bit shift-out and add carry into SCC), `s_sext_i32_i8/i16`, `s_flbit_i32`, `s_cmov_b32`, `s_cmovk_i32`,
274 `s_pack_ll/lh/hh_b32_b16`, `s_bfe_u32/i32` past bit 31, `s_brev_b64`, `s_bfe_u64/i64`, `s_bitset0/1_b64`,
275 `s_flbit_i32_b64/i64`, `s_quadmask_b32/b64`, `s_bitreplicate_b64_b32`, all nine 64-bit scalar bitwise ops on scalar
276 data, `s_movrels_b32/b64`, `v_add/sub/subrev_nc_u32` / `v_add/sub_nc_i32` / `v_add/sub_nc_u16` with `clamp` and
277 `op_sel`, `v_mad_u64_u32` / `v_mad_i64_i32` (`sdst` bit 64 sign of exact 65-bit sum and inactive-EXEC masking),
278 `v_sad_u8`/`hi_u8`/`u16`/`u32`, `v_msad_u8`, `v_lerp_u8`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`, `v_mqsad_u32_u8`,
279 `v_mul_hi_u32_u24`/`i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_mad_u16`/`i16` (`clamp`, `op_sel`, untouched half
280 kept), `v_cvt_f16_u16/i16` and `v_cvt_u16/i16_f16` (`_e64` keeps high half; NaN → 0, ±inf saturates; note GFX10
281 does not accept `op_sel` on these opcodes), `v_cvt_i32_f32` (control: all ±qNaN/±sNaN → 0), and
282 `v_cvt_pknorm_i16/u16_f32` (±qNaN → 0, ±inf saturation, RNE ties at ±0.5).
283- **Translator divergences found on gfx1035:** five (VOP3 `clamp` on the six carry-out add/sub ops ignored;
284 `v_cvt_rpi_i32_f32` rounding `x + 0.5` in binary32; `v_cvt_flr/rpi_i32_f32` returning `0` for NaN instead of
285 saturating by its sign). All are fixed (#1831, #1856), so `KNOWN_DIVERGENCES` is empty and all 87 cases
286 match.
287
258Two assembler facts matter when writing edge cases: 288Two assembler facts matter when writing edge cases:
259 289
260- An integer token in a float-operand position uses AMD's inline-constant encoding for values 0..64 290- An integer token in a float-operand position uses AMD's inline-constant encoding for values 0..64
@@ -390,11 +420,20 @@ python -I tools/lds_fuzz.py --oracle hw --programs 50 --seed 1 --wave 32 --only
390 that lane is on"): gfx1150 returns 0 when the source lane is off in EXEC, as `ds_bpermute` does. The model now 420 that lane is on"): gfx1150 returns 0 when the source lane is off in EXEC, as `ds_bpermute` does. The model now
391 says that. 421 says that.
392- **Negative controls.** `--perturb NAME` judges the hardware against a deliberately wrong model (mismatches must 422- **Negative controls.** `--perturb NAME` judges the hardware against a deliberately wrong model (mismatches must
393 appear); `--negative-control` re-judges the words of the run with all 15 (`max_i32` unsigned, `min_u32` signed, 423 appear); `--negative-control` re-judges the words of the run with all 16 (`max_i32` unsigned, `min_u32` signed,
394 swapped `cmpst`, zero-extended `i8`/`i16`, d16 reads clearing the other half, `b16_d16_hi` shift, swapped 424 swapped `cmpst`, zero-extended `i8`/`i16`, d16 reads clearing the other half, `b16_d16_hi` shift, swapped
395 `write2`, `st64` unit, bpermute reading off lanes or crossing the wave64 halves, reversed quad permute, swapped 425 `write2`, `st64` unit, bpermute reading off lanes or crossing the wave64 halves, reversed quad permute, swapped
396 swizzle or/xor, permute writing no zero) and exits 1 if one goes unnoticed. `--minimize` drops ops while a 426 swizzle or/xor, permute writing no zero, permute lowest source winning a collision) and exits 1 if one goes
397 program still differs, `--keep DIR` writes the native kernel of each mismatch, `--only I,J` runs chosen indices. 427 unnoticed. `--minimize` drops ops while a program still differs, `--keep DIR` writes the native kernel of each
428 mismatch, `--only I,J` runs chosen indices.
429
430RDNA2 `ds_permute_b32` verification (`FUZZ-10`, `SHADER-133`): raw kernels on an AMD Radeon RX 6800 (`gfx1030`, wave32
431and wave64) confirm that only active lanes send, the highest active source lane wins a collision, active destination
432lanes nobody targets read `0`, inactive destinations keep their old values, and the two 32-lane halves stay separate
433in wave64. On an AMD Radeon RX 6700 XT (`gfx1031`, RADV Mesa 26.3.1), 3,600 translator runs with colliding
434`ds_permute_b32` multipliers (`mul` in `0..63`, seeds 1–3, 300 programs × wave32/wave64 native and `--emulate`)
435matched the model bit for bit (`0` mismatches), and inverting the collision winner or zero-fill rules produced
436mismatches in `39` and `56` of `200` seed-1 programs.
398 437
399Results on a Radeon 880M (gfx1150, RDNA3.5, driver 26.11.2, AMD clang 23.0.0git), `--oracle hw`: 438Results on a Radeon 880M (gfx1150, RDNA3.5, driver 26.11.2, AMD clang 23.0.0git), `--oracle hw`:
400 439
@@ -647,7 +686,7 @@ vscnt wait plus `s_dcache_inv`; vector accesses only need `s_waitcnt vmcnt(0)`.
647*Results on RDNA2 (gfx1036 integrated GPU, AMD Windows driver 32.0.21044.64, HIP backend, AMD clang 23.0.0git, `main` bb2e1842).* 686*Results on RDNA2 (gfx1036 integrated GPU, AMD Windows driver 32.0.21044.64, HIP backend, AMD clang 23.0.0git, `main` bb2e1842).*
648- **Hardware, same protocol** (seeds 101 to 105 x 2,000 programs x wave32 and native wave64 per family): **`f16` 20,000 of 20,000 and `mem` 20,000 of 20,000 match, 0 mismatches, 0 assembler rejections.** On a gfx1030, ROCm 6.2's clang 19 rejected 3,768 of 4,000 `f16` programs (#1365); clang 23 rejects none. 687- **Hardware, same protocol** (seeds 101 to 105 x 2,000 programs x wave32 and native wave64 per family): **`f16` 20,000 of 20,000 and `mem` 20,000 of 20,000 match, 0 mismatches, 0 assembler rejections.** On a gfx1030, ROCm 6.2's clang 19 rejected 3,768 of 4,000 `f16` programs (#1365); clang 23 rejects none.
649- **Negative controls**, in the order above: `f16` 992, 865, 826, 430, 280 and 879 caught; `mem` 514, 57, 354, 60, 37, 580, 214 and 89 caught. The unperturbed model gives 0 mismatches. 688- **Negative controls**, in the order above: `f16` 992, 865, 826, 430, 280 and 879 caught; `mem` 514, 57, 354, 60, 37, 580, 214 and 89 caught. The unperturbed model gives 0 mismatches.
650- **`translator,hw` at seed 3** (100 programs, the same GPU through the AMD Vulkan driver): `mem` 200 of 200 match, `f16` 199 of 200. The one difference, `s3_22_w64`, is a driver mismatch of the #1506 kind. The hardware and `tests/semantic/spirv_mini_interp` both give the model's value for it, and the same emulated SPIR-V matches on NVIDIA. 689- **`translator,hw` at seed 3** (100 programs, the same GPU through the AMD Vulkan driver): `mem` 200 of 200 match, `f16` 199 of 200. The one difference, `s3_22_w64`, is a driver mismatch of the #1506 kind. The hardware and `tests/semantic/spirv_mini_interp.py` both give the model's value for it, and the same emulated SPIR-V matches on NVIDIA.
651- **`v_pack_b32_f16` with signaling NaNs**, measured with hand-written raw kernels in both wave sizes and both IEEE modes. The inputs were five signaling-NaN halves, quiet NaNs, ±0, +inf and a denormal, in either half, with `op_sel` and with `neg`. 690- **`v_pack_b32_f16` with signaling NaNs**, measured with hand-written raw kernels in both wave sizes and both IEEE modes. The inputs were five signaling-NaN halves, quiet NaNs, ±0, +inf and a denormal, in either half, with `op_sel` and with `neg`.
652 - IEEE mode 1, the assembler's default: a signaling-NaN half is quieted. Bit 9 is set and the sign and payload are kept, as on gfx1150. 691 - IEEE mode 1, the assembler's default: a signaling-NaN half is quieted. Bit 9 is set and the sign and payload are kept, as on gfx1150.
653 - IEEE mode 0: the half is moved unchanged. 692 - IEEE mode 0: the half is moved unchanged.
@@ -948,6 +987,65 @@ reset in the kernel log.
948 inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks 987 inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks
949 exp2 of integers and wave32 = wave64. 988 exp2 of integers and wave32 = wave64.
950 989
990### d16 rounding of UNORM/SNORM buffer loads (`tools/d16_format_probe.py`, BUILD-161)
991
992`docs/design.md` ("d16 and f16 format narrowing") narrows the f16 of a typed d16 buffer load the way it narrows an
993image result: the exact binary32 decode, then integer round to nearest even (`Gen.f16_bits`). For buffer loads that
994rounding was inferred, not measured. The probe measures it on a GFX10 GPU (RDNA1/RDNA2) through the hardware
995oracle. Every value of UNORM8, SNORM8, UNORM10 (the x channel of format 50), UNORM16 and SNORM16 is loaded with
996`buffer_load_format_d16_x`, `tbuffer_load_format_d16_x` and, for the f32 stage alone, `buffer_load_format_x`. Each
997runs in wave32 and wave64.
998
999```
1000python -I tools/d16_format_probe.py --json d16.json # about 1,040 kernels of 1,024 threads; exit 77 without the oracle
1001python -I tools/d16_format_probe.py --self-test # the rules against docs/design.md's #489 counts, no GPU
1002```
1003
1004- **The kernels stage their own inputs.** Thread t stores the format bits of one value at dword t of the output
1005 buffer and waits for the store (`s_waitcnt_vscnt`). It then builds a GFX10 V# over the buffer: DST_SEL XYZW, the
1006 format, RESOURCE_LEVEL 1, OOB_SELECT 3, NUM_RECORDS the 4 KiB staged. It loads its element with `glc dlc` (past
1007 L0 and GL1) and stores the VGPR at dword 1024 + t. The host checks that every staged word reads back as written.
1008- **Rules compared**, each also with f16 denormal results flushed:
1009 - `f32_rte`, the translator's rule;
1010 - `f32_rtz`, which is `v_cvt_pkrtz_f16_f32` of the f32 decode, the #489 bug;
1011 - `rte` and `rtz`, which round the exact quotient once;
1012 - `mul_rte`, the f32 product v · f32(1/(2^n − 1)) rounded to nearest even.
1013- **What the formats can separate.** The 8- and 10-bit formats only separate nearest from toward zero: every other rule
1014 gives the same bits there. That covers 123 of the 256 UNORM8 values and 110 of the 256 SNORM8 values, the #489
1015 counts. Only four 16-bit values separate one rounding from two (`f32_rte` against `rte`): UNORM16 0xffaf and
1016 0xffef, SNORM16 0x7ff7 and 0x8009. The smallest UNORM16/SNORM16 values have quotients under 2^-14, so they show
1017 a flush of f16 denormals.
1018- **Controls:**
1019 - a 16_FLOAT d16 load must return its own bits (NaNs may be quieted);
1020 - `d16_x` must leave the high half of its VGPR as it was (`docs/design.md` measured this on gfx1036);
1021 - wave32 must equal wave64, and MUBUF must equal MTBUF.
1022
1023 A failed control is exit 2; a wave or MUBUF/MTBUF difference is exit 1. Which rule the hardware follows is
1024 reported, not judged.
1025
1026Measured on an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003, ROCm wheel clang), the whole sweep in 36 s:
1027
1028| Format | Values | d16 `rte` | d16 `f32_rte` | d16 `f32_rtz` | f32 `f32_rte` |
1029| --- | --- | --- | --- | --- | --- |
1030| UNORM8 | 256 | 256 | 256 | 133 | 256 |
1031| SNORM8 | 256 | 256 | 256 | 146 | 256 |
1032| UNORM10 | 1,024 | 1,024 | 1,024 | 514 | 1,024 |
1033| UNORM16 | 65,536 | 65,536 | 65,534 | 33,796 | 65,536 |
1034| SNORM16 | 65,536 | 65,536 | 65,534 | 34,820 | 65,536 |
1035
1036- The d16 result is the exact quotient rounded once to f16, to nearest even, with f16 denormals kept. The two
1037 UNORM16 and two SNORM16 values that separate one rounding from two all came out 1 ulp below the f32-first result:
1038 0xffaf gave 0x3bfd (not 0x3bfe), 0xffef gave 0x3bff (not 0x3c00), 0x7ff7 gave 0x3bff, and 0x8009 gave 0xbbff.
1039 The translator now follows this (`Gen.d16_norm_f16`, `docs/design.md` "d16 and f16 format narrowing").
1040- The f32 result (`buffer_load_format_x`) is the correctly rounded quotient for every value. The reciprocal multiply
1041 matched only 130 of 256 UNORM8 values and 65,024 of 65,536 UNORM16 values.
1042- 16_FLOAT came back with its own bits for all 65,536 encodings, NaNs included. The high half of the d16_x VGPR was
1043 kept. MUBUF matched MTBUF, and wave32 matched wave64, for every value.
1044
1045`tests/test_d16_format_probe.py` checks the rules against the #489 counts and the descriptor bits. It checks that
1046each value is staged once, and that the kernels assemble for gfx1031. A fake oracle plays the GPU to check the exit
1047codes. On a GFX10 GPU the test runs UNORM8 and checks the controls.
1048
951### `v_fma_mix*` f16 rounding in nearest mode (`tools/fma_mix_probe.py`) 1049### `v_fma_mix*` f16 rounding in nearest mode (`tools/fma_mix_probe.py`)
952 1050
953`docs/design.md` leaves one f16 question open. In round-to-nearest mode, does `v_fma_mixlo_f16` / `v_fma_mixhi_f16` 1051`docs/design.md` leaves one f16 question open. In round-to-nearest mode, does `v_fma_mixlo_f16` / `v_fma_mixhi_f16`
@@ -978,21 +1076,30 @@ side follows the same rule. Exit 1 means they differ, or a side follows neither
978is unavailable. 1076is unavailable.
979 1077
980`tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that 1078`tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that
981the translator follows the double rule today, and that the compute shader gives the pixel shader's words on the 1079the translator follows the single rounding rule, and that the compute shader gives the pixel shader's words on the
982interpreter. If the hardware rounds once, the fix is to use `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at 1080interpreter. Hardware measurement on AMD RDNA2 confirmed that the hardware rounds once, straight to f16, so the translator
983f32 then narrows exactly. With that change the translator gives the single-rounded word on all seven inputs. 1081uses `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at f32 then narrows exactly, giving the single-rounded word on
1082all seven discriminating inputs.
984 1083
985Results: 1084Results:
986 1085
987| GPU | Driver | `translator` | `vulkan` | `hw` | 1086| GPU | Driver | `translator` | `vulkan` | `hw` |
988|---|---|---|---|---| 1087|---|---|---|---|---|
989| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | double | double, 8 of 8 words | not AMD | 1088| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | single | single, 8 of 8 words | not AMD |
990| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | double | not run | **single**, 7 of 7 ties; control `0x4100` | 1089| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | single | single, 8 of 8 words | **single**, 7 of 7 ties; control `0x4100` |
991 1090
992RDNA2 rounds once. Every tie input gives the single-rounded word (A `0x3c01`, B `0x3c01`, C `0xbc01`, D `0x0001`, 1091RDNA2 rounds once. Every tie input gives the single-rounded word (A `0x3c01`, B `0x3c01`, C `0xbc01`, D `0x0001`,
993E `0x7bff`, F `0x3c01`, G `0x3c01`), so the translator is one f16 ulp off on exactly these inputs (SHADER-135; the 1092E `0x7bff`, F `0x3c01`, G `0x3c01`), so the translator is one f16 ulp off on exactly these inputs (SHADER-135; the
994translator is not changed here). On the RTX 5060, a translator copy changed to use 1093translator is not changed here). On the RTX 5060, a translator copy changed to use
995`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well. 1094`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well.
1095| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | single | single, 8 of 8 words | not AMD |
1096| AMD Radeon gfx1036 (RDNA2), Linux / Windows | | single | single, 8 of 8 words | single, 8 of 8 words |
1097
1098Measurement on AMD RDNA2 (gfx1036) confirmed single rounding across all 7 discriminating cases (finding 7079901079).
1099Using `fma_mix_odd` produces the exact hardware single-rounded words in both nearest-even and toward-zero modes.
1100E `0x7bff`, F `0x3c01`, G `0x3c01`), which the translator produces across all 7 discriminating cases via
1101`fma_mix_odd` in both nearest-even and toward-zero modes (SHADER-297). On Vulkan, using `fma_mix_odd` matches the
1102exact single-rounded hardware words for all inputs.
996 1103
997### f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2 (SHADER-135) 1104### f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2 (SHADER-135)
998 1105
diff --git a/docs/testing.md b/docs/testing.md
index e4e0755f2..0c187fdef 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -114,7 +114,7 @@ python -I runtime/test/shaders/build.py <out dir>
114python -I runtime/test/shaders/check.py <out dir> <folder with the test programs> 114python -I runtime/test/shaders/check.py <out dir> <folder with the test programs>
115``` 115```
116 116
117For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed; their overlay layers ignore `VK_LOADER_LAYERS_DISABLE=~implicit~` and can inject unsupported swapchain flags. 117For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems").
118 118
119## The Windows runtime on Linux, under Wine or Proton 119## The Windows runtime on Linux, under Wine or Proton
120 120
@@ -258,11 +258,11 @@ The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) r
258|---|---|---| 258|---|---|---|
259| 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 | 259| 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 |
260| 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~` | 260| 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~` |
261| 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: RivaTuner's `VK_LAYER_RTSS` adds `STORAGE` usage to it. On some setups it stays loaded even with `VK_LOADER_LAYERS_DISABLE=~implicit~` | Also set the layer's own switch: `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 |
262| 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~`. Note that third-party overlays (RivaTuner `VK_LAYER_RTSS` from MSI Afterburner, OBS `VK_LAYER_OBS_HOOK`) stay loaded under `~implicit~` and can add `VK_IMAGE_USAGE_STORAGE_BIT` to swapchains; set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` to disable them |
263| False validation failures in `xbox_present` or present tests (e.g. sRGB swapchain `STORAGE` messages) with MSI Afterburner or OBS running | Overlay Vulkan layers (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) remain active under `VK_LOADER_LAYERS_DISABLE=~implicit~` and inject `VK_IMAGE_USAGE_STORAGE_BIT` into swapchains | Set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` for validation runs |
264| 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. 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 | 261| 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. 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 |
262| 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 |
263| 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 |
265| `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 | 264| `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 |
265| 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. 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 |
266| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | 266| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer |
267| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | 267| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` |
268| `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 | 268| `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 |
diff --git a/docs/world_names.md b/docs/world_names.md
index 80f572583..bd0a83b0d 100644
--- a/docs/world_names.md
+++ b/docs/world_names.md
@@ -67,7 +67,9 @@ formula is proven by every resolved entry.
67 67
68The windows above use only names that were already exported locally. The names of almost all the other 68The windows above use only names that were already exported locally. The names of almost all the other
69archetypes are in `levels.rpf` itself: `tools/rpf9_names.py` lists the `name.#dr` and `name.#ft` strings of every 69archetypes are in `levels.rpf` itself: `tools/rpf9_names.py` lists the `name.#dr` and `name.#ft` strings of every
70stream, and with that list as the dictionary nearly every placement resolves. Whole `levels.rpf`, one 70stream. A full pass over the data area (76.15 GB, 5,255 s) inflates 1,116,073 zlib streams (98.32% of
71compressed bytes) and finds 235,814 named streams / 318,266 unique names (267,463 `.#dr`, 50,803 `.#ft`);
72with that list as the dictionary nearly every placement resolves. Whole `levels.rpf`, one
71`world_index.py --archetypes-out` run (23,532 placement maps and 1,670,435 entities: 3 maps and 7 entities fewer 73`world_index.py --archetypes-out` run (23,532 placement maps and 1,670,435 entities: 3 maps and 7 entities fewer
72than the census in [world.md](world.md#how-many-are-there), which also joins the raw continuation page that 3 74than the census in [world.md](world.md#how-many-are-there), which also joins the raw continuation page that 3
73placement maps use and `world_index.py` does not; 228,681 distinct `archetypeName` hashes, one 64-bit key per hash, no conflicting keys, 75placement maps use and `world_index.py` does not; 228,681 distinct `archetypeName` hashes, one 64-bit key per hash, no conflicting keys,
diff --git a/make_game.py b/make_game.py
index 397fad2cf..b7fc47c08 100644
--- a/make_game.py
+++ b/make_game.py
@@ -334,10 +334,33 @@ def choose_game() -> str:
334 print(" That folder isn't a supported version of the game. Try again.") 334 print(" That folder isn't a supported version of the game. Try again.")
335 335
336 336
337def icloud_documents() -> bool:
338 """macOS: whether iCloud Drive holds Desktop & Documents. With that sync on, ~/Documents lives in iCloud Drive,
339 which uploads what goes in it and may evict files from the disk ("Optimize Mac Storage"). The folder can stay in
340 iCloud Drive after the sync is turned off; leaving Documents alone then costs nothing."""
341 return sys.platform == "darwin" and os.path.isdir(
342 os.path.join(os.path.expanduser("~"), "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents"))
343
344
337def default_out() -> str: 345def default_out() -> str:
346 """Documents/Leonida, except on a Mac whose Documents iCloud syncs: the port and its work folder (hundreds of
347 GB made from the game) must stay on this computer, so they go to ~/Leonida there."""
348 if icloud_documents():
349 return os.path.join(os.path.expanduser("~"), "Leonida")
338 return os.path.join(os.path.expanduser("~"), "Documents", "Leonida") 350 return os.path.join(os.path.expanduser("~"), "Documents", "Leonida")
339 351
340 352
353def icloud_default_notes() -> list:
354 """The log lines when default_out() left iCloud-synced Documents: why, and where a build made before this change
355 is, so its resumable work folder isn't silently left behind."""
356 notes = ["iCloud syncs Documents on this Mac: building into ~/Leonida instead, so the game's files stay off iCloud"]
357 earlier = os.path.join(os.path.expanduser("~"), "Documents", "Leonida")
358 if os.path.isdir(earlier):
359 notes.append(f"an earlier build is in {earlier}: move it to {default_out()} to resume it there, "
360 f'or pass --out "{earlier}" to keep using it')
361 return notes
362
363
341# ---------------------------------------------------------------- preflight 364# ---------------------------------------------------------------- preflight
342MIN_FREE_GB = {"shaders": 30, "assets": 300} 365MIN_FREE_GB = {"shaders": 30, "assets": 300}
343 366
@@ -682,7 +705,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
682 drop(translated, shard_plan, disassembled) 705 drop(translated, shard_plan, disassembled)
683 clear_shader_disassembly(work, disasm) 706 clear_shader_disassembly(work, disasm)
684 py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs) 707 py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs)
685 with open(disassembled, "w", encoding="utf-8") as f: 708 with open(disassembled, "w", encoding="utf-8", newline="\n") as f:
686 f.write(signature + "\n") 709 f.write(signature + "\n")
687 # The translation also depends on the translator's own files, so their digest is kept beside it. A folder without 710 # The translation also depends on the translator's own files, so their digest is kept beside it. A folder without
688 # it (from before the file existed), with an unreadable one or with another one is translated again; carving, unpacking and 711 # it (from before the file existed), with an unreadable one or with another one is translated again; carving, unpacking and
@@ -726,11 +749,11 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate
726 # a stop at any point then leaves either no index (translated again) or an index with the right mode and 749 # a stop at any point then leaves either no index (translated again) or an index with the right mode and
727 # digest, never a guessed one. rdna2spirv.py --merge writes index.json last, after the stubs. 750 # digest, never a guessed one. rdna2spirv.py --merge writes index.json last, after the stubs.
728 os.makedirs(spirv, exist_ok=True) 751 os.makedirs(spirv, exist_ok=True)
729 with open(mode_file, "w", encoding="utf-8") as f: 752 with open(mode_file, "w", encoding="utf-8", newline="\n") as f:
730 f.write(want + "\n") 753 f.write(want + "\n")
731 with open(flags_file, "w", encoding="utf-8") as f: 754 with open(flags_file, "w", encoding="utf-8", newline="\n") as f:
732 f.write(want_flags + "\n") 755 f.write(want_flags + "\n")
733 with open(sources_file, "w", encoding="utf-8") as f: 756 with open(sources_file, "w", encoding="utf-8", newline="\n") as f:
734 f.write(sources + "\n") 757 f.write(sources + "\n")
735 translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) 758 translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks)
736 log("shaders: done") 759 log("shaders: done")
@@ -907,9 +930,9 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False,
907 # Parts from another --jobs would be merged in too, and parts from another mode, flags or translator are 930 # Parts from another --jobs would be merged in too, and parts from another mode, flags or translator are
908 # wrong. They go before the new plan is written: a stop in between must not leave old parts under a new plan. 931 # wrong. They go before the new plan is written: a stop in between must not leave old parts under a new plan.
909 for f in os.listdir(spirv): 932 for f in os.listdir(spirv):
910 if f.startswith("index.part") and f.endswith(".json"): 933 if (f.startswith("index.part") and f.endswith(".json")) or re.fullmatch(r"shard\d+\.json", f):
911 os.remove(os.path.join(spirv, f)) 934 os.remove(os.path.join(spirv, f))
912 with open(plan_path, "w", encoding="utf-8") as f: 935 with open(plan_path, "w", encoding="utf-8", newline="\n") as f:
913 json.dump(plan, f) 936 json.dump(plan, f)
914 todo = [i for i in range(jobs) if not os.path.isfile(os.path.join(spirv, f"index.part{i}.json"))] 937 todo = [i for i in range(jobs) if not os.path.isfile(os.path.join(spirv, f"index.part{i}.json"))]
915 if len(todo) < jobs: 938 if len(todo) < jobs:
@@ -1058,7 +1081,7 @@ def assets(game: str, work: str, wav: bool, jobs: int) -> None:
1058 1081
1059def mark(path: str, what: str) -> None: 1082def mark(path: str, what: str) -> None:
1060 """Write a step's completion marker; call it only after the step succeeded.""" 1083 """Write a step's completion marker; call it only after the step succeeded."""
1061 with open(path, "w", encoding="utf-8") as f: 1084 with open(path, "w", encoding="utf-8", newline="\n") as f:
1062 f.write(f"{what} finished\n") 1085 f.write(f"{what} finished\n")
1063 1086
1064 1087
@@ -1177,7 +1200,7 @@ def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs
1177 if not os.path.exists(os.path.join(out, os.path.basename(built))) or \ 1200 if not os.path.exists(os.path.join(out, os.path.basename(built))) or \
1178 not os.path.samefile(built, os.path.join(out, os.path.basename(built))): 1201 not os.path.samefile(built, os.path.join(out, os.path.basename(built))):
1179 shutil.copy2(built, out) 1202 shutil.copy2(built, out)
1180 with open(os.path.join(out, "game_path.txt"), "w", encoding="utf-8") as f: 1203 with open(os.path.join(out, "game_path.txt"), "w", encoding="utf-8", newline="\n") as f:
1181 f.write(os.path.abspath(game)) 1204 f.write(os.path.abspath(game))
1182 start = os.path.join(out, "gta6rt.exe") 1205 start = os.path.join(out, "gta6rt.exe")
1183 if os.name != "nt": 1206 if os.name != "nt":
@@ -1235,7 +1258,8 @@ def main() -> int:
1235 ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.") 1258 ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.")
1236 ap.add_argument("--game", help="your package folder (found automatically if left out)") 1259 ap.add_argument("--game", help="your package folder (found automatically if left out)")
1237 ap.add_argument("--pick", action="store_true", help="choose your package folder in a folder dialog") 1260 ap.add_argument("--pick", action="store_true", help="choose your package folder in a folder dialog")
1238 ap.add_argument("--out", help="folder for the finished port (default Documents/Leonida)") 1261 ap.add_argument("--out", help="folder for the finished port (default Documents/Leonida; ~/Leonida on a Mac "
1262 "whose Documents iCloud syncs)")
1239 ap.add_argument("--work", help="folder for intermediate files (hundreds of GB; default <out>/work)") 1263 ap.add_argument("--work", help="folder for intermediate files (hundreds of GB; default <out>/work)")
1240 ap.add_argument("--stages", help="comma list from: " + ",".join(STAGES)) 1264 ap.add_argument("--stages", help="comma list from: " + ",".join(STAGES))
1241 ap.add_argument("--check", action="store_true", help="only check the game files") 1265 ap.add_argument("--check", action="store_true", help="only check the game files")
@@ -1336,6 +1360,9 @@ def main() -> int:
1336 fallbacks = fallback_flags(a) if "shaders" in stages else () 1360 fallbacks = fallback_flags(a) if "shaders" in stages else ()
1337 preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated, 1361 preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated,
1338 fallbacks=fallbacks, jobs=a.jobs) 1362 fallbacks=fallbacks, jobs=a.jobs)
1363 if not a.out and icloud_documents():
1364 for note in icloud_default_notes():
1365 log(note)
1339 log(f"building into {out} (work files in {work})") 1366 log(f"building into {out} (work files in {work})")
1340 t0 = time.time() 1367 t0 = time.time()
1341 if "shaders" in stages: 1368 if "shaders" in stages:
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 6f135558a..01e188e47 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -394,10 +394,20 @@ if(BUILD_TESTING)
394 set_target_properties(tiny_game PROPERTIES 394 set_target_properties(tiny_game PROPERTIES
395 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 395 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
396 ) 396 )
397 # The same game with no .reloc, at the default EXE base, as RT-22 asks about the real one: it can only run at
398 # 0x140000000, which arm64 Wine on macOS uses for itself (src/base_reservation.h).
399 add_executable(tiny_game_fixed test/fixtures/tiny_game.cpp)
400 target_link_libraries(tiny_game_fixed PRIVATE xgameruntime_stub)
401 target_compile_definitions(tiny_game_fixed PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS)
402 target_compile_options(tiny_game_fixed PRIVATE /W4 /permissive- /utf-8 /EHsc)
403 target_link_options(tiny_game_fixed PRIVATE /FIXED /DYNAMICBASE:NO /BASE:0x140000000)
404 set_target_properties(tiny_game_fixed PROPERTIES
405 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
406 )
397 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) 407 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp)
398 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 408 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
399 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) 409 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8)
400 add_dependencies(tiny_game_exit_code_test gta6rt tiny_game) 410 add_dependencies(tiny_game_exit_code_test gta6rt tiny_game tiny_game_fixed)
401 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>") 411 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>")
402 412
403 # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and 413 # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and
@@ -499,6 +509,11 @@ if(BUILD_TESTING)
499 add_test(NAME descriptor_table COMMAND descriptor_table_test) 509 add_test(NAME descriptor_table COMMAND descriptor_table_test)
500 add_executable(shader_library_test test/shader_library_test.cpp) 510 add_executable(shader_library_test test/shader_library_test.cpp)
501 add_test(NAME shader_library COMMAND shader_library_test) 511 add_test(NAME shader_library COMMAND shader_library_test)
512 # Optional: skips unless LEONIDA_SHADERS names a translated work folder (<work>/shaders/spirv).
513 add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp)
514 add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test)
515 # Reads all 26,503 containers and modules: about 9 minutes from a hard disk.
516 set_tests_properties(shader_library_corpus PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600)
502 if(WIN32) 517 if(WIN32)
503 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. 518 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set.
504 add_executable(bink_decode_test 519 add_executable(bink_decode_test
@@ -595,6 +610,11 @@ if(BUILD_TESTING)
595 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42) 610 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42)
596 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test 611 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test
597 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>") 612 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>")
613 # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the
614 # game's exact exit code comes back through the relaunch.
615 add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $<TARGET_FILE:tiny_game_fixed> -- hello 42)
616 add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test
617 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game_fixed>")
598 # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed, 618 # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed,
599 # so a gta6rt that ignored the conflict would run it, print "running" and exit 0. 619 # so a gta6rt that ignored the conflict would run it, print "running" and exit 0.
600 foreach(modes "dry-run;run" "dry-run;init" "init;run") 620 foreach(modes "dry-run;run" "dry-run;init" "init;run")
@@ -677,6 +697,11 @@ if(TARGET Vulkan::Headers)
677 endif() 697 endif()
678 endforeach() 698 endforeach()
679 if(BUILD_TESTING) 699 if(BUILD_TESTING)
700 add_test(NAME vk_pipeline_check_cli COMMAND "${CMAKE_COMMAND}"
701 "-DTOOL=$<TARGET_FILE:vk_pipeline_check>"
702 "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input"
703 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}"
704 -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake")
680 add_test(NAME depth24_convert COMMAND depth24_convert_test) 705 add_test(NAME depth24_convert COMMAND depth24_convert_test)
681 set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) 706 set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77)
682 # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them. 707 # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them.
@@ -753,6 +778,19 @@ if(TARGET Vulkan::Headers)
753 if(BUILD_TESTING) 778 if(BUILD_TESTING)
754 add_test(NAME vk_device_pick COMMAND vk_device_pick_test) 779 add_test(NAME vk_device_pick COMMAND vk_device_pick_test)
755 endif() 780 endif()
781 # Committed BC* texture zero-initialization via vk.zero_buffer or vk.copy_scratch (D3D-220).
782 add_executable(vk_bc_zero_init_test test/vk_bc_zero_init_test.cpp)
783 target_link_libraries(vk_bc_zero_init_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
784 if(WIN32)
785 target_compile_definitions(vk_bc_zero_init_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
786 endif()
787 if(MSVC)
788 target_compile_options(vk_bc_zero_init_test PRIVATE /W4 /permissive- /utf-8)
789 endif()
790 if(BUILD_TESTING)
791 add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test)
792 set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77)
793 endif()
756 # CPU-only: the bindless set's array sizes from synthetic device limits. 794 # CPU-only: the bindless set's array sizes from synthetic device limits.
757 add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) 795 add_executable(bindless_sizing_test test/bindless_sizing_test.cpp)
758 target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) 796 target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers)
@@ -819,7 +857,7 @@ if(TARGET Vulkan::Headers)
819 ${_stubs_header} 857 ${_stubs_header}
820 ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 858 ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1
821 ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature 859 ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature
822 ID3D12PipelineState ID3D12CommandSignature 860 ID3D12PipelineState ID3D12CommandSignature ID3D12PipelineLibrary1
823 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} 861 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER}
824 COMMENT "Generating D3D12 COM stubs" 862 COMMENT "Generating D3D12 COM stubs"
825 VERBATIM) 863 VERBATIM)
@@ -961,6 +999,14 @@ if(TARGET Vulkan::Headers)
961 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8) 999 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8)
962 add_test(NAME queue_proxy COMMAND queue_proxy_test) 1000 add_test(NAME queue_proxy COMMAND queue_proxy_test)
963 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) 1001 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77)
1002 # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the
1003 # host runtime: forwarding, refused tail, guard region, lists and GPU copies on the proxy. 77: no device at all.
1004 add_executable(allocator_proxy_test test/allocator_proxy_test.cpp)
1005 target_link_libraries(allocator_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1006 target_compile_definitions(allocator_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1007 target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8)
1008 add_test(NAME allocator_proxy COMMAND allocator_proxy_test)
1009 set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77)
964 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. 1010 # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero.
965 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) 1011 add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp)
966 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1012 target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -1176,8 +1222,65 @@ if(TARGET Vulkan::Headers)
1176 target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) 1222 target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8)
1177 add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) 1223 add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test)
1178 set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77) 1224 set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77)
1225
1226 # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect
1227 # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results
1228 # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes
1229 # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the
1230 # test wraps in shader containers.
1231 set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders)
1232 set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm
1233 ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm)
1234 add_custom_command(
1235 OUTPUT ${LEONIDA_M4_FILES}
1236 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR}
1237 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1238 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1239 ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect
1240 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1241 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py
1242 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm
1243 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm
1244 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py
1245 COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test"
1246 VERBATIM)
1247 add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES})
1248 target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com)
1249 target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1250 LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}")
1251 target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8)
1252 add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test)
1253 set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77)
1254
1255 # Typed buffer UAVs and UAV counters: cs_buf_typed.asm writes typed views through V#s with a FORMAT, and
1256 # cs_buf_counter.asm appends to and consumes from a structured view whose counter is the second V# of its slot;
1257 # the test also compares typed-buffer and counter clears with the host runtime on the layer's adapter.
1258 set(LEONIDA_BUFFER_UAV_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/buffer_uav_shaders)
1259 set(LEONIDA_BUFFER_UAV_FILES ${LEONIDA_BUFFER_UAV_DIR}/spirv/index.json
1260 ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_typed.fssm
1261 ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_counter.fssm)
1262 add_custom_command(
1263 OUTPUT ${LEONIDA_BUFFER_UAV_FILES}
1264 COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BUFFER_UAV_DIR}
1265 COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}"
1266 $<TARGET_FILE:Python3::Interpreter> -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1267 ${LEONIDA_BUFFER_UAV_DIR} cs_buf_typed cs_buf_counter
1268 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py
1269 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py
1270 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_typed.asm
1271 ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_counter.asm
1272 ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py
1273 COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test"
1274 VERBATIM)
1275 add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES})
1276 target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com)
1277 target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1278 LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}")
1279 target_compile_options(d3d12_buffer_uav_test PRIVATE /W4 /permissive- /utf-8)
1280 add_test(NAME d3d12_buffer_uav COMMAND d3d12_buffer_uav_test)
1281 set_tests_properties(d3d12_buffer_uav PROPERTIES SKIP_RETURN_CODE 77)
1179 else() 1282 else()
1180 message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test and d3d12_m3_frame_test are not built") 1283 message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m3_frame_test, d3d12_m4_compute_test and d3d12_buffer_uav_test are not built")
1181 endif() 1284 endif()
1182 # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the 1285 # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the
1183 # host runtime and WARP; run explicitly on a Vulkan GPU. 1286 # host runtime and WARP; run explicitly on a Vulkan GPU.
@@ -1191,6 +1294,7 @@ if(TARGET Vulkan::Headers)
1191 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1294 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1192 target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8) 1295 target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8)
1193 add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test) 1296 add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test)
1297 set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77)
1194 set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77) 1298 set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77)
1195 set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) 1299 set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77)
1196 1300
@@ -1332,6 +1436,16 @@ if(TARGET Vulkan::Headers)
1332 target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) 1436 target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8)
1333 add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) 1437 add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test)
1334 set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) 1438 set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77)
1439 add_executable(d3d12_pipeline_library_test test/d3d12_pipeline_library_test.cpp
1440 ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS})
1441 target_link_libraries(d3d12_pipeline_library_test PRIVATE gta6rt_d3d12_com)
1442 target_compile_definitions(d3d12_pipeline_library_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1443 LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}"
1444 LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}"
1445 LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}")
1446 target_compile_options(d3d12_pipeline_library_test PRIVATE /W4 /permissive- /utf-8)
1447 add_test(NAME d3d12_pipeline_library COMMAND d3d12_pipeline_library_test)
1448 set_tests_properties(d3d12_pipeline_library PROPERTIES SKIP_RETURN_CODE 77)
1335 else() 1449 else()
1336 message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built") 1450 message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built")
1337 endif() 1451 endif()
diff --git a/runtime/README.md b/runtime/README.md
index 1375ced25..7060f4368 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -235,6 +235,14 @@ The PE-loader and Bink-decode tests that need the retail package are optional: w
235`LEONIDA_GAME_DIR` (and, for Bink, `LEONIDA_MOVIE`) is unset they print `SKIP` and exit 0. They read 235`LEONIDA_GAME_DIR` (and, for Bink, `LEONIDA_MOVIE`) is unset they print `SKIP` and exit 0. They read
236the files in place and never copy or commit game data. 236the files in place and never copy or commit game data.
237 237
238`shader_library_corpus_test` runs the D3D12 layer's shader lookup (`src/shader_library.h`) over a work folder
239that `make_game.py --stages shaders` built from your copy. With `LEONIDA_SHADERS=<work>/shaders/spirv` it takes
240every container in `<work>/shaders/dxbc` (or `LEONIDA_SHADER_DXBC`), inflates its FSSM program and looks it up
241under the stage its DXIL program header names. Each container has to find its own `index.json` entry and a
242readable `.spv`, every entry has to be reached, and in containers with more than one 0x0D payload no earlier
243payload may be the indexed program. Without `LEONIDA_SHADERS` it prints `SKIP` (CTest reports it as skipped).
244It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve.
245
238## Current limits 246## Current limits
239 247
240`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its 248`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 7e428735d..55c6f86a8 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -113,8 +113,9 @@ class CommandAllocator final
113 : public Child<CommandAllocator, ID3D12CommandAllocatorStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 113 : public Child<CommandAllocator, ID3D12CommandAllocatorStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
114 ID3D12CommandAllocator> { 114 ID3D12CommandAllocator> {
115public: 115public:
116 // {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10} 116 // {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}, public in d3d12_xs_device.h: the device proxy's slot 9 wraps an allocator
117 static constexpr GUID kTag{0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; 117 // in an Xbox-ABI allocator proxy only when it answers this tag, because from() below resolves such a proxy.
118 static constexpr GUID kTag = d3d12_xs::kLeonidaCommandAllocatorTag;
118 explicit CommandAllocator(D3D12_COMMAND_LIST_TYPE type) : type_(type) {} 119 explicit CommandAllocator(D3D12_COMMAND_LIST_TYPE type) : type_(type) {}
119 // Lists own their recorded commands, so there is nothing to free. As on the PC runtime (D3D-51, measured by 120 // Lists own their recorded commands, so there is nothing to free. As on the PC runtime (D3D-51, measured by
120 // d3d12_vulkan_device_test): E_FAIL while a list is recording into this allocator, and S_OK while its lists are 121 // d3d12_vulkan_device_test): E_FAIL while a list is recording into this allocator, and S_OK while its lists are
@@ -124,7 +125,12 @@ public:
124 // The one list that is recording into this allocator, or null. D3D12 allows one at a time. 125 // The one list that is recording into this allocator, or null. D3D12 allows one at a time.
125 const void* recording() const { return recording_; } 126 const void* recording() const { return recording_; }
126 void set_recording(const void* list) { recording_ = list; } 127 void set_recording(const void* list) { recording_ = list; }
127 static CommandAllocator* from(IUnknown* object) { return Child::from<CommandAllocator>(object); } 128 // An allocator proxy (the title's allocator from device slot 9) stands for the allocator behind it, so every
129 // list method that takes an allocator (CreateCommandList, Reset) resolves it here.
130 static CommandAllocator* from(IUnknown* object) {
131 if (ID3D12CommandAllocator* real = d3d12_xs::allocator_proxy_real_allocator(object)) object = real;
132 return Child::from<CommandAllocator>(object);
133 }
128 134
129private: 135private:
130 D3D12_COMMAND_LIST_TYPE type_; 136 D3D12_COMMAND_LIST_TYPE type_;
@@ -214,10 +220,14 @@ public:
214 bind_root(compute_, signature); 220 bind_root(compute_, signature);
215 } 221 }
216 void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override { 222 void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override {
223 d3d12_trace::record("ID3D12GraphicsCommandList::SetGraphicsRootSignature");
217 bind_root(graphics_, signature); 224 bind_root(graphics_, signature);
218 } 225 }
219 226
220 void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { set_pipeline(state); } 227 void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override {
228 d3d12_trace::record("ID3D12GraphicsCommandList::SetPipelineState");
229 set_pipeline(state);
230 }
221 231
222 // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs. 232 // The bound heaps matter to direct heap indexing, which is still open (section 3.4); tables carry their VAs.
223 void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {} 233 void STDMETHODCALLTYPE SetDescriptorHeaps(UINT, ID3D12DescriptorHeap* const*) override {}
@@ -591,12 +601,17 @@ public:
591 cmd.argument_offset = argument_buffer_offset; 601 cmd.argument_offset = argument_buffer_offset;
592 cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0; 602 cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0;
593 cmd.count_offset = count_buffer ? count_buffer_offset : 0; 603 cmd.count_offset = count_buffer ? count_buffer_offset : 0;
604 if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record
605 if (!compute_pipeline_ || !compute_.layout) return check(false);
606 cmd.pipeline = compute_pipeline_;
607 cmd.user_data = compute_.data;
608 }
594 check(list_.execute_indirect(cmd)); 609 check(list_.execute_indirect(cmd));
595 } 610 }
596 611
597 void STDMETHODCALLTYPE BuildRaytracingAccelerationStructure( 612 void STDMETHODCALLTYPE BuildRaytracingAccelerationStructure(
598 const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* desc, UINT, 613 const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* desc, UINT postbuild_count,
599 const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC*) override { 614 const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* postbuild) override {
600 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !desc) return check(false); 615 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !desc) return check(false);
601 const auto& in = desc->Inputs; 616 const auto& in = desc->Inputs;
602 leonida::BuildAccelerationStructure cmd{}; 617 leonida::BuildAccelerationStructure cmd{};
@@ -650,7 +665,38 @@ public:
650 cmd.triangles.push_back(t); 665 cmd.triangles.push_back(t);
651 } 666 }
652 } 667 }
653 check(list_.build_acceleration_structure(cmd)); 668 const std::uint64_t built = cmd.dst_va;
669 const bool recorded = list_.build_acceleration_structure(std::move(cmd));
670 check(recorded);
671 if (!recorded) return;
672 // The postbuild values of the structure just built, after it (D3D12 orders them after the build).
673 for (UINT i = 0; postbuild && i < postbuild_count; ++i) {
674 leonida::AccelerationStructurePostbuild info{};
675 info.dest_va = postbuild[i].DestBuffer;
676 info.type = static_cast<std::uint32_t>(postbuild[i].InfoType);
677 info.sources = {built};
678 const bool ok = list_.acceleration_structure_postbuild(std::move(info));
679 check(ok);
680 if (!ok) return;
681 }
682 }
683
684 void STDMETHODCALLTYPE EmitRaytracingAccelerationStructurePostbuildInfo(
685 const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* desc, UINT count,
686 const D3D12_GPU_VIRTUAL_ADDRESS* sources) override {
687 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !desc || !count || !sources) return check(false);
688 leonida::AccelerationStructurePostbuild info{};
689 info.dest_va = desc->DestBuffer;
690 info.type = static_cast<std::uint32_t>(desc->InfoType);
691 info.sources.assign(sources, sources + count);
692 check(list_.acceleration_structure_postbuild(std::move(info)));
693 }
694
695 void STDMETHODCALLTYPE CopyRaytracingAccelerationStructure(D3D12_GPU_VIRTUAL_ADDRESS dest,
696 D3D12_GPU_VIRTUAL_ADDRESS source,
697 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) override {
698 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
699 check(list_.copy_acceleration_structure({dest, source, static_cast<std::uint32_t>(mode)}));
654 } 700 }
655 701
656 static GraphicsCommandList* from(IUnknown* object) { return Child::from<GraphicsCommandList>(object); } 702 static GraphicsCommandList* from(IUnknown* object) { return Child::from<GraphicsCommandList>(object); }
@@ -1251,7 +1297,8 @@ HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator
1251 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; 1297 if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG;
1252 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). 1298 // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51).
1253 if (command_allocator->recording()) return E_INVALIDARG; 1299 if (command_allocator->recording()) return E_INVALIDARG;
1254 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE) 1300 if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE &&
1301 type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY)
1255 stub("create_command_list(non-direct type)"); 1302 stub("create_command_list(non-direct type)");
1256 auto* object = new GraphicsCommandList(type); // created open, as D3D12 does 1303 auto* object = new GraphicsCommandList(type); // created open, as D3D12 does
1257 object->record_into(command_allocator); 1304 object->record_into(command_allocator);
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 2e1f2d3c5..b3b397be0 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -273,6 +273,12 @@ inline constexpr UINT descriptor_size = 32;
273// ExecuteCommandLists returns void; this is what the last call on the queue did. 273// ExecuteCommandLists returns void; this is what the last call on the queue did.
274leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); 274leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue);
275 275
276// True when the current thread or process token has SeIncreaseBasePriorityPrivilege enabled (or the test override
277// forces it), which D3D12 requires for D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME.
278bool has_global_realtime_privilege();
279// Test override for has_global_realtime_privilege(): -1 queries the token (default), 0 forces denied, 1 forces granted.
280void set_global_realtime_privilege_override_for_test(int state);
281
276// The front/back stencil references last recorded by ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef on 282// The front/back stencil references last recorded by ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef on
277// `list`. The values are kept for the future pipeline path, which is what would apply them. False when `list` is 283// `list`. The values are kept for the future pipeline path, which is what would apply them. False when `list` is
278// not one of this module's command lists. 284// not one of this module's command lists.
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 5cb39d0d6..af7e7aa5c 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -15,15 +15,19 @@
15#include "d3d12_xs_device.h" 15#include "d3d12_xs_device.h"
16#include "dxgi_com.h" 16#include "dxgi_com.h"
17#include "../src/gfx10_descriptors.h" 17#include "../src/gfx10_descriptors.h"
18#include "../src/uav_clear.h"
18#include "../src/vulkan_bindless.h" 19#include "../src/vulkan_bindless.h"
19#include "../src/vulkan_memory.h" 20#include "../src/vulkan_memory.h"
20#include "../src/resource_tiling.h" 21#include "../src/resource_tiling.h"
21#include "../src/shader_library.h" 22#include "../src/shader_library.h"
22#include "../src/vulkan_present.h" 23#include "../src/vulkan_present.h"
23#include "../src/vulkan_device_filter.h" 24#include "../src/vulkan_device_filter.h"
25#include "../src/vulkan13_features.h"
24 26
25#include <vulkan/vulkan_win32.h> 27#include <vulkan/vulkan_win32.h>
26 28#ifdef _MSC_VER
29#pragma comment(lib, "advapi32.lib")
30#endif
27 31
28#include <algorithm> 32#include <algorithm>
29#include <atomic> 33#include <atomic>
@@ -59,6 +63,8 @@ static_assert(sizeof(leonida::TargetView) <= kDescriptorSize);
59constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0; 63constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0;
60constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; 64constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1;
61 65
66std::atomic<int> g_global_realtime_privilege_override{-1};
67
62void log_once(const char* what, int value) { 68void log_once(const char* what, int value) {
63 static std::mutex mutex; 69 static std::mutex mutex;
64 static std::set<std::pair<std::string, int>> seen; 70 static std::set<std::pair<std::string, int>> seen;
@@ -1060,6 +1066,21 @@ const char* heap_properties_refusal(const D3D12_HEAP_PROPERTIES& heap) {
1060 return nullptr; 1066 return nullptr;
1061} 1067}
1062 1068
1069// Why the host would refuse this CreateHeap/CreateHeap1 description, or null if these checks pass (D3D-238). A probe
1070// on an RX 5700 and WARP refuses an alignment other than 0, 64 KiB and 4 MiB, the heap properties above (a type of 0,
1071// a custom heap without a CPU page property), and a heap that denies buffers and both kinds of texture.
1072const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc) {
1073 if (!desc.SizeInBytes) return "zero size";
1074 if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT &&
1075 desc.Alignment != D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT)
1076 return "alignment (0, 64 KiB or 4 MiB)";
1077 if (const char* why = heap_properties_refusal(desc.Properties)) return why;
1078 constexpr UINT deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
1079 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
1080 if ((UINT(desc.Flags) & deny_all) == deny_all) return "heap flags denying every resource kind";
1081 return nullptr;
1082}
1083
1063// Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were 1084// Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were
1064// measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources 1085// measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources
1065// (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no 1086// (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no
@@ -1355,6 +1376,10 @@ public:
1355 binding.size = desc_.Width; 1376 binding.size = desc_.Width;
1356 binding.buffer = device_.arena.buffer; 1377 binding.buffer = device_.arena.buffer;
1357 binding.buffer_offset = va_; 1378 binding.buffer_offset = va_;
1379 binding.va = va_;
1380 binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK ||
1381 (heap_.Type == D3D12_HEAP_TYPE_CUSTOM &&
1382 heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK));
1358 device_.context->add_resource(id(), binding); 1383 device_.context->add_resource(id(), binding);
1359 return S_OK; 1384 return S_OK;
1360 } 1385 }
@@ -1460,8 +1485,9 @@ public:
1460 D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { 1485 D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override {
1461 D3D12_RESOURCE_DESC desc = desc_; 1486 D3D12_RESOURCE_DESC desc = desc_;
1462 if (!desc.Alignment) { 1487 if (!desc.Alignment) {
1463 desc.Alignment = desc.SampleDesc.Count > 1 ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT 1488 desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout))
1464 : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; 1489 ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT
1490 : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
1465 } 1491 }
1466 return desc; 1492 return desc;
1467 } 1493 }
@@ -1937,6 +1963,7 @@ public:
1937 bool reserved() const { return reserved_; } 1963 bool reserved() const { return reserved_; }
1938 VkDeviceSize offset() const { return offset_; } 1964 VkDeviceSize offset() const { return offset_; }
1939 UINT64 bytes() const { return desc_.SizeInBytes; } 1965 UINT64 bytes() const { return desc_.SizeInBytes; }
1966 UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; }
1940 const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } 1967 const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; }
1941 D3D12_HEAP_FLAGS flags() const { return desc_.Flags; } 1968 D3D12_HEAP_FLAGS flags() const { return desc_.Flags; }
1942 1969
@@ -2616,6 +2643,99 @@ struct TextureView {
2616 float min_lod = 0.0f; 2643 float min_lod = 0.0f;
2617}; 2644};
2618 2645
2646// In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific
2647// and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs
2648// and returns D3D12_ERROR_DRIVER_VERSION_MISMATCH for foreign or corrupt ones.
2649class PipelineLibrary final
2650 : public Child<PipelineLibrary, ID3D12PipelineLibrary1Stubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
2651 ID3D12PipelineLibrary, ID3D12PipelineLibrary1> {
2652public:
2653 // {6e2a9d41-7b5f-4c83-8e14-2a9d6f3c5b10}
2654 static constexpr GUID kTag{0x6e2a9d41, 0x7b5f, 0x4c83, {0x8e, 0x14, 0x2a, 0x9d, 0x6f, 0x3c, 0x5b, 0x10}};
2655
2656 struct Header {
2657 std::uint32_t magic;
2658 std::uint32_t version;
2659 std::uint32_t count;
2660 std::uint32_t reserved;
2661 };
2662 static constexpr std::uint32_t kMagic = 0x314C504Cu; // "LPL1"
2663 static constexpr std::uint32_t kVersion = 1;
2664
2665 ~PipelineLibrary() override {
2666 std::lock_guard lock(mutex_);
2667 for (auto& [name, pso] : entries_)
2668 if (pso) pso->Release();
2669 entries_.clear();
2670 }
2671
2672 static bool valid_blob(const void* data, SIZE_T size) {
2673 if (!data || size < sizeof(Header)) return false;
2674 Header h{};
2675 std::memcpy(&h, data, sizeof(h));
2676 return h.magic == kMagic && h.version == kVersion && h.reserved == 0;
2677 }
2678
2679 HRESULT STDMETHODCALLTYPE StorePipeline(LPCWSTR name, ID3D12PipelineState* pipeline) override {
2680 if (!name || !*name || !pipeline) return E_INVALIDARG;
2681 if (!PipelineState::from<PipelineState>(pipeline)) return E_INVALIDARG;
2682 std::lock_guard lock(mutex_);
2683 auto [it, inserted] = entries_.emplace(name, pipeline);
2684 if (!inserted) return E_INVALIDARG;
2685 pipeline->AddRef();
2686 return S_OK;
2687 }
2688
2689 HRESULT STDMETHODCALLTYPE LoadGraphicsPipeline(LPCWSTR name, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
2690 REFIID riid, void** out) override {
2691 if (!out) return E_POINTER;
2692 *out = nullptr;
2693 if (!name || !*name || !desc) return E_INVALIDARG;
2694 return load_entry(name, false, true, riid, out);
2695 }
2696
2697 HRESULT STDMETHODCALLTYPE LoadComputePipeline(LPCWSTR name, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
2698 REFIID riid, void** out) override {
2699 if (!out) return E_POINTER;
2700 *out = nullptr;
2701 if (!name || !*name || !desc) return E_INVALIDARG;
2702 return load_entry(name, true, false, riid, out);
2703 }
2704
2705 HRESULT STDMETHODCALLTYPE LoadPipeline(LPCWSTR name, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
2706 REFIID riid, void** out) override {
2707 if (!out) return E_POINTER;
2708 *out = nullptr;
2709 if (!name || !*name || !desc || !desc->SizeInBytes || !desc->pPipelineStateSubobjectStream) return E_INVALIDARG;
2710 return load_entry(name, false, false, riid, out);
2711 }
2712
2713 SIZE_T STDMETHODCALLTYPE GetSerializedSize() override { return sizeof(Header); }
2714
2715 HRESULT STDMETHODCALLTYPE Serialize(void* data, SIZE_T size) override {
2716 if (!data || size < sizeof(Header)) return E_INVALIDARG;
2717 std::lock_guard lock(mutex_);
2718 const Header h{kMagic, kVersion, static_cast<std::uint32_t>(entries_.size()), 0};
2719 std::memcpy(data, &h, sizeof(h));
2720 return S_OK;
2721 }
2722
2723private:
2724 HRESULT load_entry(LPCWSTR name, bool require_compute, bool require_graphics, REFIID riid, void** out) {
2725 std::lock_guard lock(mutex_);
2726 const auto it = entries_.find(name);
2727 if (it == entries_.end()) return E_INVALIDARG;
2728 PipelineState* ps = PipelineState::from<PipelineState>(it->second);
2729 if (!ps) return E_INVALIDARG;
2730 if (require_compute && !ps->compute()) return E_INVALIDARG;
2731 if (require_graphics && !ps->graphics()) return E_INVALIDARG;
2732 return it->second->QueryInterface(riid, out);
2733 }
2734
2735 std::mutex mutex_;
2736 std::unordered_map<std::wstring, ID3D12PipelineState*> entries_;
2737};
2738
2619// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. 2739// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read.
2620// False (with a log) for a view set 0 cannot show yet. 2740// False (with a log) for a view set 0 cannot show yet.
2621bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { 2741bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) {
@@ -2646,7 +2766,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
2646 const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : 2766 const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D :
2647 view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : 2767 view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D :
2648 D3D12_RESOURCE_DIMENSION_TEXTURE2D; 2768 D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2649 if (desc.Dimension != dimension || (line && desc.DepthOrArraySize != 1) || msaa != (desc.SampleDesc.Count > 1)) { 2769 if (desc.Dimension != dimension || (line && view.layer_count != 1) || msaa != (desc.SampleDesc.Count > 1)) {
2650 log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); 2770 log_once("view type incompatible with texture dimension or sample count; view type", int(view.type));
2651 return false; 2771 return false;
2652 } 2772 }
@@ -3094,7 +3214,19 @@ public:
3094 get_properties(state_.info.physical, &properties); 3214 get_properties(state_.info.physical, &properties);
3095 features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT), 3215 features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT),
3096 state_.ms_fallback_samples(VK_FORMAT_R32_SINT)}; 3216 state_.ms_fallback_samples(VK_FORMAT_R32_SINT)};
3097 if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed)) 3217 // Past maxPerSetDescriptors, ask the driver about the grown layout (D3D-219: Intel's Xe-LP reports 6159).
3218 const auto layout_support = reinterpret_cast<PFN_vkGetDescriptorSetLayoutSupport>(
3219 get_device(state_.info.device, "vkGetDescriptorSetLayoutSupport"));
3220 std::function<bool(const leonida::BindlessFeatures&)> layout_supported;
3221 if (layout_support)
3222 layout_supported = [&](const leonida::BindlessFeatures& candidate) {
3223 const leonida::bindless::SetLayout layout(candidate);
3224 VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT};
3225 layout_support(state_.info.device, &layout.info, &support);
3226 return support.supported == VK_TRUE;
3227 };
3228 if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed,
3229 layout_supported))
3098 std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default " 3230 std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default "
3099 "sizes; it holds less\n"); 3231 "sizes; it holds less\n");
3100 } 3232 }
@@ -3379,8 +3511,8 @@ public:
3379 log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type); 3511 log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type);
3380 return d3d12_trace::result(method, E_INVALIDARG); 3512 return d3d12_trace::result(method, E_INVALIDARG);
3381 } 3513 }
3382 // Global realtime priority needs a privilege the host grants only on request; without it, this answer. 3514 // Global realtime priority needs SeIncreaseBasePriorityPrivilege enabled in the token; without it, this answer.
3383 if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) { 3515 if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME && !has_global_realtime_privilege()) {
3384 log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type); 3516 log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type);
3385 return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED); 3517 return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED);
3386 } 3518 }
@@ -3513,7 +3645,7 @@ public:
3513 auto& vk = state_.context->vk; 3645 auto& vk = state_.context->vk;
3514 if (desc && state_.context->xdxr_acceleration_structures()) { 3646 if (desc && state_.context->xdxr_acceleration_structures()) {
3515 // XDXR records: the layout depends only on the triangle or instance count (xdxr_build.h), so the sizes 3647 // XDXR records: the layout depends only on the triangle or instance count (xdxr_build.h), so the sizes
3516 // are exact. An update rebuilds the structure, so it needs the same scratch. 3648 // are exact. An update refits (no sort); the build's scratch size covers it.
3517 leonida::BuildAccelerationStructure build{}; 3649 leonida::BuildAccelerationStructure build{};
3518 build.is_tlas = desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; 3650 build.is_tlas = desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;
3519 if (build.is_tlas) { 3651 if (build.is_tlas) {
@@ -3676,7 +3808,7 @@ public:
3676 return hand_out(signature, riid, out); 3808 return hand_out(signature, riid, out);
3677 } 3809 }
3678 3810
3679 // PC slot 11; the Xbox ABI reaches it through device slot 62 (the proxy forwards). 3811 // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards).
3680 HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, 3812 HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid,
3681 void** out) override { 3813 void** out) override {
3682 if (!out) return E_POINTER; 3814 if (!out) return E_POINTER;
@@ -3705,6 +3837,19 @@ public:
3705 return hand_out(pipeline, riid, out); 3837 return hand_out(pipeline, riid, out);
3706 } 3838 }
3707 3839
3840 // Device1: in-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4).
3841 HRESULT STDMETHODCALLTYPE CreatePipelineLibrary(const void* blob, SIZE_T size, REFIID riid, void** out) override {
3842 constexpr auto method = "ID3D12Device1::CreatePipelineLibrary";
3843 if (out) *out = nullptr;
3844 if (size > 0 && !blob) return d3d12_trace::result(method, E_INVALIDARG);
3845 if (size > 0 && !PipelineLibrary::valid_blob(blob, size))
3846 return d3d12_trace::result(method, D3D12_ERROR_DRIVER_VERSION_MISMATCH);
3847 if (!out) return d3d12_trace::result(method, S_FALSE);
3848 auto* lib = new PipelineLibrary();
3849 lib->attach_device(identity());
3850 return d3d12_trace::result(method, hand_out(lib, riid, out));
3851 }
3852
3708 UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { 3853 UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override {
3709 return kDescriptorSize; 3854 return kDescriptorSize;
3710 } 3855 }
@@ -3763,13 +3908,16 @@ public:
3763 r->allows_view_format(vulkan_format(requested, false).format)); 3908 r->allows_view_format(vulkan_format(requested, false).format));
3764 if (typeless_rgba8 || (requested != rd.Format && listed && 3909 if (typeless_rgba8 || (requested != rd.Format && listed &&
3765 rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM)) { 3910 rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM)) {
3766 const bool plain = desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D; 3911 const bool msaa = rd.SampleDesc.Count > 1;
3767 const bool array = desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; 3912 const bool plain = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D;
3913 const bool array = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
3914 const bool ms = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS;
3915 const bool ms_array = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
3768 const UINT plane = plain ? desc->Texture2D.PlaneSlice : 3916 const UINT plane = plain ? desc->Texture2D.PlaneSlice :
3769 array ? desc->Texture2DArray.PlaneSlice : 0; 3917 array ? desc->Texture2DArray.PlaneSlice : 0;
3770 // Subtraction keeps malformed layer ranges from overflowing during validation. 3918 // Subtraction keeps malformed layer ranges from overflowing during validation.
3771 if ((!plain && !array) || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || 3919 if ((!plain && !array && !ms && !ms_array) || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D ||
3772 rd.SampleDesc.Count != 1 || plane || !view.resource || view.mip >= rd.MipLevels || 3920 plane || !view.resource || view.mip >= rd.MipLevels ||
3773 !view.layer_count || view.first_layer >= rd.DepthOrArraySize || 3921 !view.layer_count || view.first_layer >= rd.DepthOrArraySize ||
3774 view.layer_count > rd.DepthOrArraySize - view.first_layer || 3922 view.layer_count > rd.DepthOrArraySize - view.first_layer ||
3775 !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { 3923 !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
@@ -3862,6 +4010,24 @@ public:
3862 std::size_t(count) * kDescriptorSize); 4010 std::size_t(count) * kDescriptorSize);
3863 } 4011 }
3864 4012
4013 // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest).
4014 // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0).
4015 void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
4016 D3D12_CPU_DESCRIPTOR_HANDLE destination) override {
4017 d3d12_trace::record("ID3D12Device::CreateConstantBufferView");
4018 if (!destination.ptr) return;
4019 std::memset(reinterpret_cast<void*>(destination.ptr), 0, kDescriptorSize);
4020 if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return;
4021 leonida::gfx10::Buffer buffer{};
4022 buffer.address = desc->BufferLocation;
4023 buffer.stride = 0;
4024 buffer.num_records = desc->SizeInBytes;
4025 buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT);
4026 buffer.oob_select = leonida::gfx10::OobSelect::raw;
4027 const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer);
4028 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
4029 }
4030
3865 // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight 4031 // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight
3866 // dwords through its descriptor table and finds the image by them. A slot left as zeros is a null descriptor: 4032 // dwords through its descriptor table and finds the image by them. A slot left as zeros is a null descriptor:
3867 // nothing is registered for it, so the shader gets the fallback image. Buffer views are not implemented. 4033 // nothing is registered for it, so the shader gets the fallback image. Buffer views are not implemented.
@@ -3885,9 +4051,10 @@ public:
3885 TextureView view{}; 4051 TextureView view{};
3886 if (!desc) { 4052 if (!desc) {
3887 const bool array = r->desc().DepthOrArraySize > 1; 4053 const bool array = r->desc().DepthOrArraySize > 1;
3888 if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) 4054 if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) {
3889 view.type = ImageType::image_1d; 4055 view.type = ImageType::image_1d;
3890 else if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) 4056 view.layer_count = 1;
4057 } else if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D)
3891 view.type = ImageType::image_3d; 4058 view.type = ImageType::image_3d;
3892 else if (r->desc().SampleDesc.Count > 1) 4059 else if (r->desc().SampleDesc.Count > 1)
3893 view.type = array ? ImageType::image_2d_msaa_array : ImageType::image_2d_msaa; 4060 view.type = array ? ImageType::image_2d_msaa_array : ImageType::image_2d_msaa;
@@ -3901,6 +4068,7 @@ public:
3901 view.type = ImageType::image_1d; 4068 view.type = ImageType::image_1d;
3902 view.first_mip = desc->Texture1D.MostDetailedMip; 4069 view.first_mip = desc->Texture1D.MostDetailedMip;
3903 view.mip_count = desc->Texture1D.MipLevels; 4070 view.mip_count = desc->Texture1D.MipLevels;
4071 view.layer_count = 1;
3904 view.min_lod = desc->Texture1D.ResourceMinLODClamp; 4072 view.min_lod = desc->Texture1D.ResourceMinLODClamp;
3905 break; 4073 break;
3906 case D3D12_SRV_DIMENSION_TEXTURE3D: 4074 case D3D12_SRV_DIMENSION_TEXTURE3D:
@@ -3957,6 +4125,95 @@ public:
3957 write_image_descriptor(*r, view, destination, false); 4125 write_image_descriptor(*r, view, destination, false);
3958 } 4126 }
3959 4127
4128 // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords
4129 // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format
4130 // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count,
4131 // a typed one (any other format) is the format's GFX10_FORMAT code with the element size as the stride and an
4132 // element count: the V# a buffer_load_format / buffer_store_format / buffer_atomic reads (OOB_SELECT 1, so the
4133 // index is checked against NUM_RECORDS, docs/buffer_bounds.md). A slot left as zeros is a null descriptor.
4134 // A UAV counter (docs section 3.4, "UAV counters") is a second, raw V# of 4 bytes in the slot's upper 16 bytes: the
4135 // counter resource's address plus CounterOffsetInBytes. Append and consume are atomics a shader does on it.
4136 void write_buffer_uav(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
4137 D3D12_CPU_DESCRIPTOR_HANDLE destination) {
4138 namespace g = leonida::gfx10;
4139 const D3D12_RESOURCE_DESC& rd = Resource::from<Resource>(resource)->desc();
4140 if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
4141 log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags));
4142 return;
4143 }
4144 if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
4145 log_once("unordered-access view of a buffer needs a buffer view description; dimension",
4146 desc ? int(desc->ViewDimension) : -1);
4147 return;
4148 }
4149 const D3D12_BUFFER_UAV& view = desc->Buffer;
4150 const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN;
4151 const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW);
4152 const bool typed = !structured && !raw;
4153 std::uint32_t format_code = 0, element_bytes = 0;
4154 g::Swizzle channels = g::identity_swizzle;
4155 if (typed) {
4156 // D3D12: a typed view has no RAW flag; its format is one of the typed-UAV formats the layer can name.
4157 const Format mapped = vulkan_format(desc->Format, false);
4158 const auto* layout = mapped.format != VK_FORMAT_UNDEFINED && !mapped.typeless && !mapped.rgb96 &&
4159 !(view.Flags & D3D12_BUFFER_UAV_FLAG_RAW)
4160 ? leonida::uav_clear::layout(mapped.format)
4161 : nullptr;
4162 format_code = layout ? g::format_from_vulkan(mapped.format) : 0;
4163 if (!format_code || format_code >= 128) { // the V#'s FORMAT is 7 bits
4164 log_once("typed buffer unordered-access view format not supported; format", int(desc->Format));
4165 return;
4166 }
4167 element_bytes = layout->bytes;
4168 channels = g::format_swizzle(mapped.format);
4169 }
4170 const UINT64 unit = structured ? view.StructureByteStride : typed ? element_bytes : 4;
4171 if (!unit || unit > 0x3fff || view.FirstElement > rd.Width / unit ||
4172 (UINT64(view.FirstElement) + view.NumElements) > rd.Width / unit ||
4173 UINT64(view.NumElements) * (structured || typed ? 1 : 4) > ~0u) {
4174 log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements",
4175 int(view.NumElements));
4176 return;
4177 }
4178 // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte
4179 // aligned with room for its 4 bytes; with no counter resource the offset is 0.
4180 if (counter || view.CounterOffsetInBytes) {
4181 const Resource* c = counter ? Resource::from<Resource>(counter) : nullptr;
4182 const bool valid = c && !c->image() && structured &&
4183 (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) &&
4184 !(view.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) &&
4185 UINT64(view.CounterOffsetInBytes) + 4 <= c->desc().Width;
4186 if (!valid) {
4187 log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered "
4188 "access, a 4096-aligned offset inside it); offset",
4189 int(view.CounterOffsetInBytes));
4190 return;
4191 }
4192 }
4193 const UINT64 va = resource->GetGPUVirtualAddress();
4194 const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0;
4195 if (!va || (counter && !counter_va)) return;
4196 g::Buffer buffer{};
4197 buffer.address = va + view.FirstElement * unit;
4198 buffer.stride = structured || typed ? std::uint32_t(unit) : 0;
4199 buffer.num_records = std::uint32_t(structured || typed ? view.NumElements : UINT64(view.NumElements) * 4);
4200 buffer.format = format_code;
4201 buffer.swizzle = channels;
4202 buffer.oob_select = typed ? g::OobSelect::structured
4203 : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw;
4204 const g::BufferWords words = g::encode(buffer);
4205 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
4206 if (counter) {
4207 g::Buffer counter_buffer{};
4208 counter_buffer.address = counter_va + view.CounterOffsetInBytes;
4209 counter_buffer.num_records = 4;
4210 counter_buffer.oob_select = g::OobSelect::raw;
4211 const g::BufferWords counter_words = g::encode(counter_buffer);
4212 std::memcpy(reinterpret_cast<char*>(destination.ptr) + sizeof(words), counter_words.data(),
4213 sizeof(counter_words));
4214 }
4215 }
4216
3960 // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. 4217 // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image.
3961 void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, 4218 void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter,
3962 const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, 4219 const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
@@ -3969,7 +4226,11 @@ public:
3969 if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); 4226 if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)");
3970 return; 4227 return;
3971 } 4228 }
3972 if (!r->image() || counter) return stub("ID3D12Device::CreateUnorderedAccessView(buffer)"); 4229 if (!r->image()) return write_buffer_uav(resource, counter, desc, destination);
4230 if (counter) {
4231 log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension));
4232 return;
4233 }
3973 if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { 4234 if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
3974 log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", 4235 log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags",
3975 int(r->desc().Flags)); 4236 int(r->desc().Flags));
@@ -4005,6 +4266,7 @@ public:
4005 return; 4266 return;
4006 } 4267 }
4007 write_image_descriptor(*r, view, destination, true); 4268 write_image_descriptor(*r, view, destination, true);
4269 state_.context->note_storage_image(r->id());
4008 } 4270 }
4009 4271
4010 // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords. 4272 // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords.
@@ -4238,7 +4500,11 @@ public:
4238 // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. 4500 // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it.
4239 HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override { 4501 HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override {
4240 if (out) *out = nullptr; 4502 if (out) *out = nullptr;
4241 if (!desc || !desc->SizeInBytes) return E_INVALIDARG; 4503 if (!desc) return E_INVALIDARG;
4504 if (const char* why = heap_desc_refusal(*desc)) {
4505 log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type));
4506 return E_INVALIDARG;
4507 }
4242 if (!state_.arena.mapped) { 4508 if (!state_.arena.mapped) {
4243 log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", 4509 log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:",
4244 int(desc->SizeInBytes / 1024)); 4510 int(desc->SizeInBytes / 1024));
@@ -4258,6 +4524,18 @@ public:
4258 return hand_out(heap, riid, out); 4524 return hand_out(heap, riid, out);
4259 } 4525 }
4260 4526
4527 // Device4: CreateHeap with a protected session, which is refused as CreateCommittedResource1 refuses one. The host
4528 // gives the same answers as CreateHeap for the D3D-238 descriptions.
4529 HRESULT STDMETHODCALLTYPE CreateHeap1(const D3D12_HEAP_DESC* desc, ID3D12ProtectedResourceSession* session,
4530 REFIID riid, void** out) override {
4531 if (out) *out = nullptr;
4532 if (session) {
4533 log_once("protected resource session refused (not supported) by CreateHeap1", 1);
4534 return E_INVALIDARG;
4535 }
4536 return CreateHeap(desc, riid, out);
4537 }
4538
4261 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, 4539 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset,
4262 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES, 4540 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
4263 const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override { 4541 const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override {
@@ -4310,26 +4588,35 @@ public:
4310 return E_INVALIDARG; 4588 return E_INVALIDARG;
4311 } 4589 }
4312 const bool tiled = is_tiled_layout(desc->Layout); 4590 const bool tiled = is_tiled_layout(desc->Layout);
4591 const bool msaa = desc->SampleDesc.Count > 1;
4313 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 4592 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
4593 if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG;
4314 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; 4594 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG;
4315 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG; 4595 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG;
4316 } else if (heap_offset >= heap->bytes()) { 4596 } else {
4317 return E_INVALIDARG;
4318 }
4319 if (tiled) {
4320 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || 4597 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD ||
4321 heap->properties().Type == D3D12_HEAP_TYPE_READBACK) 4598 heap->properties().Type == D3D12_HEAP_TYPE_READBACK)
4322 return E_INVALIDARG; 4599 return E_INVALIDARG;
4323 if (desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && 4600 const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
4324 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) 4601 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
4325 return E_INVALIDARG; 4602 if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG;
4326 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(*desc); 4603 if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG;
4327 if (alloc.SizeInBytes == UINT64_MAX || alloc.SizeInBytes > heap->bytes() || 4604 if (tiled || msaa) {
4328 heap_offset > heap->bytes() - alloc.SizeInBytes) 4605 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
4606 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D)
4607 return E_INVALIDARG;
4608 if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG;
4609 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(*desc);
4610 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment ||
4611 heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() ||
4612 heap_offset > heap->bytes() - alloc.SizeInBytes)
4613 return E_INVALIDARG;
4614 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
4615 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
4616 int(desc->Dimension));
4617 }
4618 } else if (heap_offset >= heap->bytes()) {
4329 return E_INVALIDARG; 4619 return E_INVALIDARG;
4330 if (static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
4331 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
4332 int(desc->Dimension));
4333 } 4620 }
4334 } 4621 }
4335 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image. 4622 // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image.
@@ -4341,8 +4628,6 @@ public:
4341 hr = resource->create_placed_buffer(); 4628 hr = resource->create_placed_buffer();
4342 } else if (!tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { 4629 } else if (!tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) {
4343 log_once("placed resource dimension not supported:", int(desc->Dimension)); 4630 log_once("placed resource dimension not supported:", int(desc->Dimension));
4344 } else if (desc->SampleDesc.Count > 1) {
4345 log_once("multisampled placed resource not supported; samples", int(desc->SampleDesc.Count));
4346 } else { 4631 } else {
4347 hr = S_OK; 4632 hr = S_OK;
4348 const Format format = state_.texture_format(*desc); 4633 const Format format = state_.texture_format(*desc);
@@ -5109,21 +5394,19 @@ private:
5109 D3D12_RESOURCE_DESC resolved = desc; 5394 D3D12_RESOURCE_DESC resolved = desc;
5110 if (!resolved.MipLevels) resolved.MipLevels = full; 5395 if (!resolved.MipLevels) resolved.MipLevels = full;
5111 if (resolved.MipLevels > full) return kInvalidAllocation; 5396 if (resolved.MipLevels > full) return kInvalidAllocation;
5112 if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || 5397 const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
5398 if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || !(desc.Flags & attachment) ||
5399 (desc.Flags & attachment) == attachment ||
5113 (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) 5400 (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)))
5114 return kInvalidAllocation; 5401 return kInvalidAllocation;
5115 // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth. 5402 // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth.
5116 const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
5117 if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) || 5403 if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) ||
5118 (volume && depth_stencil)) 5404 (volume && depth_stencil))
5119 return kInvalidAllocation; 5405 return kInvalidAllocation;
5120 const bool tiled = is_tiled_layout(desc.Layout); 5406 const bool tiled = is_tiled_layout(desc.Layout);
5121 if (tiled) { 5407 if (tiled) {
5122 if (one_d) return kInvalidAllocation; 5408 if (one_d || (samples > 1 && samples != 4)) return kInvalidAllocation;
5123 if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation; 5409 if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation;
5124 // Tiled MSAA is 4x single-mip 2D attachment only (measured on RTX 5070 Ti and WARP).
5125 if (samples > 1 && (samples != 4 || !(desc.Flags & attachment) || (desc.Flags & attachment) == attachment))
5126 return kInvalidAllocation;
5127 } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) { 5410 } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) {
5128 log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); 5411 log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout);
5129 } 5412 }
@@ -5186,12 +5469,10 @@ private:
5186 if (!image_descriptor(resource, view, image)) return; 5469 if (!image_descriptor(resource, view, image)) return;
5187 const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); 5470 const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image);
5188 const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), 5471 const bool registered = state_.bind_image(words, image, resource.image(), resource.format(),
5189 resource.aspects(), storage, false, 5472 resource.aspects(), storage, resource.has_view_format_list(),
5190 resource.r9g9b9e5_as_r32_uint()); 5473 resource.r9g9b9e5_as_r32_uint());
5191 if (leonida::gfx10::multisampled(image.type) && !registered) return; 5474 if (leonida::gfx10::multisampled(image.type) && !registered) return;
5192 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 5475 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
5193 state_.bind_image(words, image, resource.image(), resource.format(), resource.aspects(), storage,
5194 resource.has_view_format_list(), resource.r9g9b9e5_as_r32_uint());
5195 } 5476 }
5196 5477
5197 // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on 5478 // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on
@@ -5741,7 +6022,8 @@ HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out) {
5741 i.queue_family, riid, out); 6022 i.queue_family, riid, out);
5742} 6023}
5743 6024
5744// Creates its own Vulkan 1.3 instance and device. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. 6025// Creates its own Vulkan instance and a Vulkan 1.3 device, or a 1.2 device with VK_KHR_dynamic_rendering and
6026// VK_KHR_synchronization2 (vulkan13_features.h). LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation.
5745HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { 6027HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5746 if (!out) return E_POINTER; 6028 if (!out) return E_POINTER;
5747 *out = nullptr; 6029 *out = nullptr;
@@ -5854,22 +6136,21 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5854 bool chosen_bc = false; 6136 bool chosen_bc = false;
5855 VkPhysicalDeviceFeatures chosen_features{}; 6137 VkPhysicalDeviceFeatures chosen_features{};
5856 VkPhysicalDeviceVulkan12Features chosen12{}; 6138 VkPhysicalDeviceVulkan12Features chosen12{};
5857 VkPhysicalDeviceVulkan13Features chosen13{};
5858 bool chosen_draw_params = false; 6139 bool chosen_draw_params = false;
6140 leonida::Vulkan13Features v13, candidate13;
5859 for (VkPhysicalDevice candidate : physicals) { 6141 for (VkPhysicalDevice candidate : physicals) {
5860 VkPhysicalDeviceProperties props{}; 6142 VkPhysicalDeviceProperties props{};
5861 vkGetPhysicalDeviceProperties(candidate, &props); 6143 vkGetPhysicalDeviceProperties(candidate, &props);
5862 if (props.apiVersion < VK_API_VERSION_1_3 || !leonida::vulkan_device_wanted(props.deviceName)) continue; 6144 if (!leonida::vulkan_device_wanted(props.deviceName)) continue;
5863 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 6145 candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties);
5864 VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &f13}; 6146 if (!candidate13.usable()) continue;
6147 VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
5865 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f11}; 6148 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f11};
5866 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; 6149 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12};
5867 vkGetPhysicalDeviceFeatures2(candidate, &features); 6150 vkGetPhysicalDeviceFeatures2(candidate, &features);
5868 const bool bc = features.features.textureCompressionBC; 6151 const bool bc = features.features.textureCompressionBC;
5869 const bool draw_params = f11.shaderDrawParameters; 6152 const bool draw_params = f11.shaderDrawParameters;
5870 if (!f13.dynamicRendering || !f13.synchronization2 || !f12.timelineSemaphore || 6153 if (!f12.timelineSemaphore || !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue;
5871 !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress)
5872 continue;
5873 std::uint32_t family_count = 0; 6154 std::uint32_t family_count = 0;
5874 vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); 6155 vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr);
5875 std::vector<VkQueueFamilyProperties> families(family_count); 6156 std::vector<VkQueueFamilyProperties> families(family_count);
@@ -5883,18 +6164,22 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5883 chosen_bc = bc; 6164 chosen_bc = bc;
5884 chosen_features = features.features; 6165 chosen_features = features.features;
5885 chosen12 = f12; 6166 chosen12 = f12;
5886 chosen13 = f13;
5887 chosen_draw_params = draw_params; 6167 chosen_draw_params = draw_params;
6168 v13.choose(candidate13);
5888 } 6169 }
5889 break; 6170 break;
5890 } 6171 }
5891 } 6172 }
5892 if (!info.physical) 6173 if (!info.physical)
5893 return fail(leonida::vulkan_device_filter().empty() 6174 return fail(leonida::vulkan_device_filter().empty()
5894 ? "no Vulkan 1.3 GPU with dynamicRendering, synchronization2, timelineSemaphore and " 6175 ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with "
5895 "separateDepthStencilLayouts" 6176 "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts"
5896 : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 with dynamicRendering, synchronization2, " 6177 : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and "
5897 "timelineSemaphore and separateDepthStencilLayouts"); 6178 "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and "
6179 "separateDepthStencilLayouts");
6180 if (!v13.core)
6181 std::fprintf(stderr, "[rt] d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR "
6182 "extensions\n");
5898 6183
5899 // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional 6184 // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional
5900 // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). 6185 // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS).
@@ -5964,17 +6249,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
5964 ext_chain = &enable_conditional; 6249 ext_chain = &enable_conditional;
5965 } 6250 }
5966 6251
5967 VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, ext_chain};
5968 enable13.dynamicRendering = VK_TRUE;
5969 enable13.synchronization2 = VK_TRUE;
5970 // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). 6252 // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h).
5971 enable13.subgroupSizeControl = chosen13.subgroupSizeControl; 6253 leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control,
5972 enable13.computeFullSubgroups = chosen13.computeFullSubgroups; 6254 v13.compute_full_subgroups, info.subgroup);
5973 leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, chosen13.subgroupSizeControl,
5974 chosen13.computeFullSubgroups, info.subgroup);
5975 // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the 6255 // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the
5976 // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). 6256 // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs).
5977 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 6257 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
6258 v13.enable(ext_chain)};
5978 enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; 6259 enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE;
5979 if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); 6260 if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n");
5980 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; 6261 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11};
@@ -6047,8 +6328,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6047 vkGetPhysicalDeviceFeatures2(info.physical, &query); 6328 vkGetPhysicalDeviceFeatures2(info.physical, &query);
6048 info.image_view_min_lod = min_lod.minLod == VK_TRUE; 6329 info.image_view_min_lod = min_lod.minLod == VK_TRUE;
6049 if (info.image_view_min_lod) { 6330 if (info.image_view_min_lod) {
6050 min_lod.pNext = enable13.pNext; 6331 min_lod.pNext = *v13.next();
6051 enable13.pNext = &min_lod; 6332 *v13.next() = &min_lod;
6052 } 6333 }
6053 } 6334 }
6054 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; 6335 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT};
@@ -6059,8 +6340,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6059 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; 6340 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME;
6060 info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy; 6341 info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy;
6061 if (info.host_image_copy) { 6342 if (info.host_image_copy) {
6062 host_copy.pNext = enable13.pNext; // after the conditional rendering features, if any 6343 host_copy.pNext = *v13.next(); // after the conditional rendering features, if any
6063 enable13.pNext = &host_copy; 6344 *v13.next() = &host_copy;
6064 } else { 6345 } else {
6065 std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); 6346 std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n");
6066 } 6347 }
@@ -6077,8 +6358,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6077 vkGetPhysicalDeviceFeatures2(info.physical, &query); 6358 vkGetPhysicalDeviceFeatures2(info.physical, &query);
6078 info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE; 6359 info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE;
6079 if (info.shader_fma) { 6360 if (info.shader_fma) {
6080 shader_fma.pNext = enable13.pNext; 6361 shader_fma.pNext = *v13.next();
6081 enable13.pNext = &shader_fma; 6362 *v13.next() = &shader_fma;
6082 } 6363 }
6083 } 6364 }
6084#endif 6365#endif
@@ -6113,9 +6394,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6113 // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent): 6394 // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent):
6114 // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name 6395 // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name
6115 // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature. 6396 // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature.
6397 const char* swapchain_m1_name = nullptr;
6398#if defined(VK_KHR_swapchain_maintenance1)
6116 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{ 6399 VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{
6117 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR}; 6400 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR};
6118 const char* swapchain_m1_name = nullptr;
6119 if (has_swapchain && instance_has_surface) { 6401 if (has_swapchain && instance_has_surface) {
6120 const auto device_has = [&](const char* name) { 6402 const auto device_has = [&](const char* name) {
6121 return std::any_of(extensions.begin(), extensions.end(), 6403 return std::any_of(extensions.begin(), extensions.end(),
@@ -6129,13 +6411,14 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6129 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; 6411 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1};
6130 vkGetPhysicalDeviceFeatures2(info.physical, &query); 6412 vkGetPhysicalDeviceFeatures2(info.physical, &query);
6131 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { 6413 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) {
6132 swapchain_m1.pNext = enable13.pNext; 6414 swapchain_m1.pNext = *v13.next();
6133 enable13.pNext = &swapchain_m1; 6415 *v13.next() = &swapchain_m1;
6134 } else { 6416 } else {
6135 swapchain_m1_name = nullptr; 6417 swapchain_m1_name = nullptr;
6136 } 6418 }
6137 } 6419 }
6138 } 6420 }
6421#endif
6139 info.swapchain_maintenance1 = swapchain_m1_name != nullptr; 6422 info.swapchain_maintenance1 = swapchain_m1_name != nullptr;
6140 6423
6141 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; 6424 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12};
@@ -6143,6 +6426,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6143 device_info.pQueueCreateInfos = &queue_info; 6426 device_info.pQueueCreateInfos = &queue_info;
6144 device_info.pEnabledFeatures = &enable; 6427 device_info.pEnabledFeatures = &enable;
6145 std::vector<const char*> device_extensions; 6428 std::vector<const char*> device_extensions;
6429 v13.add_extensions(device_extensions);
6146 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 6430 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
6147 if (info.conditional_rendering) device_extensions.push_back(conditional_extension); 6431 if (info.conditional_rendering) device_extensions.push_back(conditional_extension);
6148 if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); 6432 if (info.host_image_copy) device_extensions.push_back(host_image_copy_name);
@@ -6196,4 +6480,29 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6196 return hand_out(device, riid, out); 6480 return hand_out(device, riid, out);
6197} 6481}
6198 6482
6483bool has_global_realtime_privilege() {
6484 const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed);
6485 if (override_state >= 0) return override_state != 0;
6486 HANDLE token = nullptr;
6487 if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token) &&
6488 !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
6489 return false;
6490 LUID luid{};
6491 BOOL enabled = FALSE;
6492 if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) {
6493 PRIVILEGE_SET set{};
6494 set.PrivilegeCount = 1;
6495 set.Control = PRIVILEGE_SET_ALL_NECESSARY;
6496 set.Privilege[0].Luid = luid;
6497 set.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;
6498 if (!PrivilegeCheck(token, &set, &enabled)) enabled = FALSE;
6499 }
6500 CloseHandle(token);
6501 return enabled != FALSE;
6502}
6503
6504void set_global_realtime_privilege_override_for_test(int state) {
6505 g_global_realtime_privilege_override.store(state, std::memory_order_relaxed);
6506}
6507
6199} // namespace rt::d3d12 6508} // namespace rt::d3d12
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 57cd292c7..65a4f3995 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -388,18 +388,29 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII
388// 388//
389// QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when 389// QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when
390// the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to 390// the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to
391// the title. Leonida's own code reaches the real object through queue_proxy_real_queue / fence_proxy_real_fence. 391// the title. Leonida's own code reaches the real object through queue_proxy_real_queue / fence_proxy_real_fence /
392// allocator_proxy_real_allocator.
393//
394// Command allocators (device slot 9) are the third kind: their public chain is 9 slots (Reset at 8). Slot 9 wraps
395// only an allocator that answers kLeonidaCommandAllocatorTag, because a list takes the title's allocator in
396// CreateCommandList and Reset and only the Vulkan layer's lists resolve a proxy there (CommandAllocator::from);
397// a PC runtime allocator is handed out unchanged until a command-list proxy unwraps it at Reset.
392 398
393enum class ChildKind { queue, fence }; 399enum class ChildKind { queue, fence, allocator };
394 400
395constexpr unsigned kQueueSlots = 128; // the table: 19 public slots plus a refused tail 401constexpr unsigned kQueueSlots = 128; // the table: 19 public slots plus a refused tail
396constexpr unsigned kFenceSlots = 64; // the table: 12 public slots plus a refused tail 402constexpr unsigned kFenceSlots = 64; // the table: 12 public slots plus a refused tail
397constexpr unsigned kQueuePublicSlots = 19; // ID3D12CommandQueue 403constexpr unsigned kQueuePublicSlots = 19; // ID3D12CommandQueue
398constexpr unsigned kFencePublicSlots = 11; // ID3D12Fence 404constexpr unsigned kFencePublicSlots = 11; // ID3D12Fence
399constexpr unsigned kFence1PublicSlots = 12; // ID3D12Fence1 405constexpr unsigned kFence1PublicSlots = 12; // ID3D12Fence1
406constexpr unsigned kAllocatorSlots = 64; // the table: 9 public slots plus a refused tail
407constexpr unsigned kAllocatorPublicSlots = 9; // ID3D12CommandAllocator: the base chain and Reset (slot 8)
400constexpr SIZE_T kTableRegion = 64 * 1024; // one allocation granule: the table page plus 15 never-committed pages 408constexpr SIZE_T kTableRegion = 64 * 1024; // one allocation granule: the table page plus 15 never-committed pages
401static_assert(kQueueSlots > kQueuePublicSlots && kFenceSlots > kFence1PublicSlots, "the tables need a tail"); 409static_assert(kQueueSlots > kQueuePublicSlots && kFenceSlots > kFence1PublicSlots &&
402static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) <= 4096, 410 kAllocatorSlots > kAllocatorPublicSlots,
411 "the tables need a tail");
412static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) <= 4096 &&
413 kAllocatorSlots * sizeof(void*) <= 4096,
403 "a table must fit in the first page of its reservation"); 414 "a table must fit in the first page of its reservation");
404 415
405constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) 416constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64)
@@ -415,7 +426,9 @@ struct ChildProxy {
415 426
416template <ChildKind K> 427template <ChildKind K>
417struct ChildStats { 428struct ChildStats {
418 static constexpr unsigned kSlots = K == ChildKind::queue ? kQueueSlots : kFenceSlots; 429 static constexpr unsigned kSlots = K == ChildKind::queue ? kQueueSlots
430 : K == ChildKind::fence ? kFenceSlots
431 : kAllocatorSlots;
419 static inline std::atomic<std::uint64_t> hits[kSlots]; 432 static inline std::atomic<std::uint64_t> hits[kSlots];
420 static inline std::atomic<bool> first[kSlots]; 433 static inline std::atomic<bool> first[kSlots];
421 static inline std::atomic<bool> beyond_warned[kSlots]; 434 static inline std::atomic<bool> beyond_warned[kSlots];
@@ -426,7 +439,7 @@ struct ChildStats {
426 439
427template <ChildKind K> 440template <ChildKind K>
428constexpr const char* child_kind_name() { 441constexpr const char* child_kind_name() {
429 return K == ChildKind::queue ? "queue" : "fence"; 442 return K == ChildKind::queue ? "queue" : K == ChildKind::fence ? "fence" : "allocator";
430} 443}
431 444
432template <ChildKind K> 445template <ChildKind K>
@@ -441,8 +454,10 @@ const char* child_public_name(unsigned slot) {
441 if (slot < 8) return object[slot]; 454 if (slot < 8) return object[slot];
442 if constexpr (K == ChildKind::queue) { 455 if constexpr (K == ChildKind::queue) {
443 if (slot < kQueuePublicSlots) return queue[slot - 8]; 456 if (slot < kQueuePublicSlots) return queue[slot - 8];
444 } else { 457 } else if constexpr (K == ChildKind::fence) {
445 if (slot < kFence1PublicSlots) return fence[slot - 8]; 458 if (slot < kFence1PublicSlots) return fence[slot - 8];
459 } else {
460 if (slot == 8) return "Reset";
446 } 461 }
447 return nullptr; 462 return nullptr;
448} 463}
@@ -454,7 +469,9 @@ template <ChildKind K>
454const char* child_trace_name(unsigned slot) { 469const char* child_trace_name(unsigned slot) {
455 static const auto names = [] { 470 static const auto names = [] {
456 static char storage[ChildStats<K>::kSlots][64]; 471 static char storage[ChildStats<K>::kSlots][64];
457 const char* iface = K == ChildKind::queue ? "XboxID3D12CommandQueue" : "XboxID3D12Fence"; 472 const char* iface = K == ChildKind::queue ? "XboxID3D12CommandQueue"
473 : K == ChildKind::fence ? "XboxID3D12Fence"
474 : "XboxID3D12CommandAllocator";
458 for (unsigned s = 0; s < ChildStats<K>::kSlots; ++s) { 475 for (unsigned s = 0; s < ChildStats<K>::kSlots; ++s) {
459 const char* method = child_public_name<K>(s); 476 const char* method = child_public_name<K>(s);
460 if (method) 477 if (method)
@@ -528,8 +545,10 @@ bool is_child_iid(const IID& iid) {
528 return true; 545 return true;
529 if constexpr (K == ChildKind::queue) { 546 if constexpr (K == ChildKind::queue) {
530 return IsEqualIID(iid, __uuidof(ID3D12CommandQueue)); 547 return IsEqualIID(iid, __uuidof(ID3D12CommandQueue));
531 } else { 548 } else if constexpr (K == ChildKind::fence) {
532 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || IsEqualIID(iid, __uuidof(ID3D12Fence1)); 549 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || IsEqualIID(iid, __uuidof(ID3D12Fence1));
550 } else {
551 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator));
533 } 552 }
534} 553}
535 554
@@ -608,7 +627,8 @@ IUnknown* proxy_real_object(const void* object) {
608 void* const vtable = *reinterpret_cast<void* const*>(object); 627 void* const vtable = *reinterpret_cast<void* const*>(object);
609 if (vtable == reinterpret_cast<void*>(get_heap_vtable())) return static_cast<const HeapProxy*>(object)->real; 628 if (vtable == reinterpret_cast<void*>(get_heap_vtable())) return static_cast<const HeapProxy*>(object)->real;
610 if (vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::queue>()) || 629 if (vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::queue>()) ||
611 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::fence>())) 630 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::fence>()) ||
631 vtable == reinterpret_cast<void*>(get_child_vtable<ChildKind::allocator>()))
612 return static_cast<const ChildProxy*>(object)->real; 632 return static_cast<const ChildProxy*>(object)->real;
613 return nullptr; 633 return nullptr;
614} 634}
@@ -685,6 +705,7 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) {
685 const auto address = static_cast<std::uintptr_t>(record->ExceptionInformation[1]); 705 const auto address = static_cast<std::uintptr_t>(record->ExceptionInformation[1]);
686 report_table_overrun<ChildKind::queue>(address); 706 report_table_overrun<ChildKind::queue>(address);
687 report_table_overrun<ChildKind::fence>(address); 707 report_table_overrun<ChildKind::fence>(address);
708 report_table_overrun<ChildKind::allocator>(address);
688 } 709 }
689 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash 710 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash
690} 711}
@@ -803,8 +824,10 @@ HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void
803 proxy->real_vtable = *reinterpret_cast<void***>(created); 824 proxy->real_vtable = *reinterpret_cast<void***>(created);
804 if constexpr (K == ChildKind::queue) { 825 if constexpr (K == ChildKind::queue) {
805 proxy->slot_count = kQueuePublicSlots; 826 proxy->slot_count = kQueuePublicSlots;
806 } else { 827 } else if constexpr (K == ChildKind::fence) {
807 proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots; 828 proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots;
829 } else {
830 proxy->slot_count = kAllocatorPublicSlots;
808 } 831 }
809 proxy->refs.store(1, std::memory_order_relaxed); 832 proxy->refs.store(1, std::memory_order_relaxed);
810 proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice 833 proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice
@@ -894,6 +917,43 @@ HRESULT proxy_create_fence(DeviceProxy* self, std::uint64_t initial_value, std::
894 return wrap_child<ChildKind::fence>(static_cast<IUnknown*>(created), self, riid, out); 917 return wrap_child<ChildKind::fence>(static_cast<IUnknown*>(created), self, riid, out);
895} 918}
896 919
920// True when `allocator` is one whose consumers resolve allocator proxies: Leonida's own Vulkan-layer allocator,
921// whose lists (CreateCommandList, Reset) find the real allocator through allocator_proxy_real_allocator. A PC
922// runtime allocator does not answer the tag, and its lists would take a proxy for their own allocator.
923bool resolves_allocator_proxies(IUnknown* allocator) {
924 void* found = nullptr;
925 if (FAILED(allocator->QueryInterface(kLeonidaCommandAllocatorTag, &found)) || !found) return false;
926 static_cast<IUnknown*>(found)->Release(); // the implementation pointer starts with its IUnknown chain
927 return true;
928}
929
930// Device slot 9: CreateCommandAllocator(type, riid, out). An allocator proxy where the list side resolves it (see
931// resolves_allocator_proxies); any other allocator goes back unchanged, logged once, so the host runtime's lists
932// never see a proxy. Null output and null IID as slot 8.
933HRESULT proxy_create_command_allocator(DeviceProxy* self, std::uint64_t type, const IID* riid, void** out) {
934 note_slot(9);
935 if (out) *out = nullptr; // as slot 8
936 if (!riid) return E_POINTER;
937 const auto list_type = static_cast<D3D12_COMMAND_LIST_TYPE>(static_cast<std::uint32_t>(type));
938#pragma warning(suppress : 6387) // the caller's null output, on purpose (see slot 8)
939 if (!out) return self->real->CreateCommandAllocator(list_type, *riid, nullptr);
940 void* created = nullptr;
941 const HRESULT hr = self->real->CreateCommandAllocator(list_type, __uuidof(ID3D12CommandAllocator), &created);
942 if (FAILED(hr)) return hr;
943 if (!created) return E_FAIL;
944 auto* allocator = static_cast<IUnknown*>(created);
945 if (!resolves_allocator_proxies(allocator)) {
946 static std::atomic<bool> logged{false};
947 if (!logged.exchange(true, std::memory_order_relaxed))
948 std::fprintf(stderr, "[rt] d3d12_xs: allocators of this device are not wrapped: its command lists "
949 "cannot resolve an allocator proxy\n");
950 const HRESULT asked = allocator->QueryInterface(*riid, out);
951 allocator->Release();
952 return asked;
953 }
954 return wrap_child<ChildKind::allocator>(allocator, self, riid, out);
955}
956
897// Device slot 32: OpenSharedHandle(handle, riid, out). The object is opened as asked; when it is a fence (whatever 957// Device slot 32: OpenSharedHandle(handle, riid, out). The object is opened as asked; when it is a fence (whatever
898// interface was asked for, IUnknown included) the title gets a fence proxy, anything else (heaps, resources) is 958// interface was asked for, IUnknown included) the title gets a fence proxy, anything else (heaps, resources) is
899// returned unchanged. 959// returned unchanged.
@@ -981,6 +1041,61 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU
981 return self->real->CreateComputePipelineState(desc, *riid, out); 1041 return self->real->CreateComputePipelineState(desc, *riid, out);
982} 1042}
983 1043
1044// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named
1045// DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc
1046// passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md):
1047// kind 0 (dispatch state) at +0x08/+0x10, kind 1 at +0x18/+0x20, kind 6 (the RDNA2 program) at +0x28/+0x30, and
1048// kind 7 (records) at +0x38/+0x40. Translates the console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC
1049// with CS bytecode pointing at kind 6 and routes it to CreateComputePipelineState on the PC device (slot 11), which
1050// on the Vulkan device resolves through the translator. The PC slot 67 is CreateProtectedResourceSession1.
1051HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const void* desc,
1052 const IID* riid, void** out) {
1053 note_slot(67);
1054 if (!out) return E_POINTER;
1055 *out = nullptr;
1056 if (!desc) return E_INVALIDARG;
1057 if (!riid) return E_POINTER;
1058
1059 // FSPX description layout (docs/fspx.md §How the DLL reads it):
1060 struct XboxNativeComputePipelineStateDesc {
1061 ID3D12RootSignature* root_signature; // +0x00
1062 const void* kind0; // +0x08: dispatch state
1063 std::uint64_t kind0_size; // +0x10: 28 bytes
1064 const void* kind1; // +0x18: unknown
1065 std::uint64_t kind1_size; // +0x20: 20 bytes
1066 const void* kind6; // +0x28: RDNA2 program code
1067 std::uint64_t kind6_size; // +0x30: program size in bytes
1068 const void* kind7; // +0x38: resource/hash records
1069 std::uint64_t kind7_size; // +0x40: records size in bytes
1070 };
1071 const auto* xbox_desc = static_cast<const XboxNativeComputePipelineStateDesc*>(desc);
1072
1073 if (xbox_desc->kind0 || xbox_desc->kind0_size || xbox_desc->kind1 || xbox_desc->kind1_size ||
1074 xbox_desc->kind7 || xbox_desc->kind7_size) {
1075 static std::atomic<bool> logged{false};
1076 if (!logged.exchange(true, std::memory_order_relaxed)) {
1077 std::fprintf(stderr,
1078 "[rt] d3d12_xs: slot 67 FSPX metadata: kind0 0x%llx (%llu B), kind1 0x%llx (%llu B), kind7 0x%llx (%llu B)\n",
1079 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind0)),
1080 static_cast<unsigned long long>(xbox_desc->kind0_size),
1081 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind1)),
1082 static_cast<unsigned long long>(xbox_desc->kind1_size),
1083 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(xbox_desc->kind7)),
1084 static_cast<unsigned long long>(xbox_desc->kind7_size));
1085 }
1086 }
1087
1088 D3D12_COMPUTE_PIPELINE_STATE_DESC pc_desc{};
1089 pc_desc.pRootSignature = xbox_desc->root_signature;
1090 pc_desc.CS.pShaderBytecode = xbox_desc->kind6;
1091 pc_desc.CS.BytecodeLength = static_cast<SIZE_T>(xbox_desc->kind6_size);
1092 pc_desc.NodeMask = 0;
1093 pc_desc.CachedPSO = {nullptr, 0};
1094 pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
1095
1096 return self->real->CreateComputePipelineState(&pc_desc, *riid, out);
1097}
1098
984HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, 1099HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties,
985 D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, 1100 D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc,
986 D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, 1101 D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value,
@@ -1024,6 +1139,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1024 } else if constexpr (Slot == 8) { 1139 } else if constexpr (Slot == 8) {
1025 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1), 1140 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1),
1026 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3))); 1141 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3)));
1142 } else if constexpr (Slot == 9) {
1143 return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast<const IID*>(a2),
1144 reinterpret_cast<void**>(a3)));
1027 } else if constexpr (Slot == 36) { 1145 } else if constexpr (Slot == 36) {
1028 return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast<const IID*>(a3), 1146 return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast<const IID*>(a3),
1029 reinterpret_cast<void**>(a4))); 1147 reinterpret_cast<void**>(a4)));
@@ -1044,18 +1162,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1044 self, reinterpret_cast<const D3D12_COMPUTE_PIPELINE_STATE_DESC*>(a1), a2, a3, 1162 self, reinterpret_cast<const D3D12_COMPUTE_PIPELINE_STATE_DESC*>(a1), a2, a3,
1045 reinterpret_cast<const IID*>(a4), reinterpret_cast<void**>(a5))); 1163 reinterpret_cast<const IID*>(a4), reinterpret_cast<void**>(a5)));
1046 } else if constexpr (Slot == 67) { 1164 } else if constexpr (Slot == 67) {
1047 // Measured in amd_fidelityfx_upscaler_xbox.dll (call at RVA 0x56d9): (desc, riid, out), named 1165 return hr_to_u64(proxy_create_compute_pipeline_from_native_code(
1048 // DeserializeComputePipelineStateX in the DLL's own messages. The desc is the root signature at +0x00, then 1166 self, reinterpret_cast<const void*>(a1), reinterpret_cast<const IID*>(a2),
1049 // pointer/size pairs for the shader's FSPX entries, with the native RDNA2 program at +0x28 (docs/fspx.md); 1167 reinterpret_cast<void**>(a3)));
1050 // the DLL falls back to slot 62 when it fails. The PC device's slot 67 is CreateProtectedResourceSession1, a
1051 // different method, so it is refused here, not forwarded.
1052 note_slot(67);
1053 static std::atomic<bool> logged{false};
1054 if (!logged.exchange(true, std::memory_order_relaxed))
1055 std::fprintf(stderr,
1056 "[rt] d3d12_xs: device slot 67 (Xbox DeserializeComputePipelineStateX) -> E_NOTIMPL\n");
1057 if (a3) *reinterpret_cast<void**>(a3) = nullptr;
1058 return hr_to_u64(E_NOTIMPL);
1059 } else if constexpr (Slot == 76) { 1168 } else if constexpr (Slot == 76) {
1060 return hr_to_u64(proxy_create_resource( 1169 return hr_to_u64(proxy_create_resource(
1061 self, reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(a1), 1170 self, reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(a1),
@@ -1186,13 +1295,19 @@ ID3D12Device* device_proxy_real_device(const void* device) {
1186} 1295}
1187 1296
1188bool device_slot_overridden(unsigned slot) { 1297bool device_slot_overridden(unsigned slot) {
1189 return slot <= 2 || slot == 8 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || 1298 return slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 ||
1190 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || 1299 slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 ||
1191 slot == 75 || slot == 76; 1300 slot == 75 || slot == 76;
1192} 1301}
1193 1302
1194bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } 1303bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); }
1195bool is_fence_proxy(const void* fence) { return is_child_proxy<ChildKind::fence>(fence); } 1304bool is_fence_proxy(const void* fence) { return is_child_proxy<ChildKind::fence>(fence); }
1305bool is_allocator_proxy(const void* allocator) { return is_child_proxy<ChildKind::allocator>(allocator); }
1306
1307ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator) {
1308 if (!is_allocator_proxy(allocator)) return nullptr;
1309 return reinterpret_cast<ID3D12CommandAllocator*>(static_cast<const ChildProxy*>(allocator)->real);
1310}
1196 1311
1197ID3D12CommandQueue* queue_proxy_real_queue(const void* queue) { 1312ID3D12CommandQueue* queue_proxy_real_queue(const void* queue) {
1198 if (!is_queue_proxy(queue)) return nullptr; 1313 if (!is_queue_proxy(queue)) return nullptr;
@@ -1214,9 +1329,13 @@ unsigned fence_proxy_slot_count(const void* fence) {
1214 1329
1215unsigned queue_proxy_table_size() { return kQueueSlots; } 1330unsigned queue_proxy_table_size() { return kQueueSlots; }
1216unsigned fence_proxy_table_size() { return kFenceSlots; } 1331unsigned fence_proxy_table_size() { return kFenceSlots; }
1332unsigned allocator_proxy_table_size() { return kAllocatorSlots; }
1333unsigned allocator_proxy_slot_count(const void* allocator) {
1334 return is_allocator_proxy(allocator) ? static_cast<const ChildProxy*>(allocator)->slot_count : 0;
1335}
1217 1336
1218unsigned long command_object_proxy_ref_count(const void* object) { 1337unsigned long command_object_proxy_ref_count(const void* object) {
1219 if (!is_queue_proxy(object) && !is_fence_proxy(object)) return 0; 1338 if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0;
1220 return static_cast<const ChildProxy*>(object)->refs.load(std::memory_order_relaxed); 1339 return static_cast<const ChildProxy*>(object)->refs.load(std::memory_order_relaxed);
1221} 1340}
1222 1341
@@ -1251,8 +1370,24 @@ std::uint64_t fence_table_overruns() {
1251bool command_object_tables_guarded() { 1370bool command_object_tables_guarded() {
1252 get_child_vtable<ChildKind::queue>(); 1371 get_child_vtable<ChildKind::queue>();
1253 get_child_vtable<ChildKind::fence>(); 1372 get_child_vtable<ChildKind::fence>();
1373 get_child_vtable<ChildKind::allocator>();
1254 return ChildStats<ChildKind::queue>::table_end.load(std::memory_order_acquire) && 1374 return ChildStats<ChildKind::queue>::table_end.load(std::memory_order_acquire) &&
1255 ChildStats<ChildKind::fence>::table_end.load(std::memory_order_acquire); 1375 ChildStats<ChildKind::fence>::table_end.load(std::memory_order_acquire) &&
1376 ChildStats<ChildKind::allocator>::table_end.load(std::memory_order_acquire);
1377}
1378
1379std::uint64_t allocator_slot_hits(unsigned slot) {
1380 using S = ChildStats<ChildKind::allocator>;
1381 return slot < S::kSlots ? S::hits[slot].load(std::memory_order_relaxed) : 0;
1382}
1383
1384bool allocator_slot_first_call_seen(unsigned slot) {
1385 using S = ChildStats<ChildKind::allocator>;
1386 return slot < S::kSlots && S::first[slot].load(std::memory_order_relaxed);
1387}
1388
1389std::uint64_t allocator_table_overruns() {
1390 return ChildStats<ChildKind::allocator>::overruns.load(std::memory_order_relaxed);
1256} 1391}
1257 1392
1258bool heap_slot_overridden(unsigned slot) { 1393bool heap_slot_overridden(unsigned slot) {
@@ -1292,6 +1427,7 @@ void reset_device_proxy_stats() {
1292 } 1427 }
1293 reset_child_stats<ChildKind::queue>(); 1428 reset_child_stats<ChildKind::queue>();
1294 reset_child_stats<ChildKind::fence>(); 1429 reset_child_stats<ChildKind::fence>();
1430 reset_child_stats<ChildKind::allocator>();
1295} 1431}
1296 1432
1297} // namespace rt::d3d12_xs 1433} // namespace rt::d3d12_xs
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 510560516..12ac5a78f 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -3,6 +3,9 @@
3// Measured Xbox device deviations used here (vtable indices, x64): 3// Measured Xbox device deviations used here (vtable indices, x64):
4// slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) 4// slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown)
5// before the IID. The PC slot 62 is CreateStateObject. 5// before the IID. The PC slot 62 is CreateStateObject.
6// slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc
7// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards
8// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1.
6// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. 9// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored.
7// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device 10// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device
8// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. 11// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged.
@@ -57,8 +60,9 @@ unsigned device_proxy_slot_count(const void* device);
57ID3D12Device* device_proxy_real_device(const void* device); 60ID3D12Device* device_proxy_real_device(const void* device);
58 61
59// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 62// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
60// proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67 and 76. 63// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 62, 67
61// Slots 9 and 10 are intentionally false; the handle conversion is on the heap proxy. 64// and 76. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap proxy, and device
65// slot 9 is CreateCommandAllocator, which the proxy handles for the allocator proxy.
62bool device_slot_overridden(unsigned slot); 66bool device_slot_overridden(unsigned slot);
63 67
64// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object 68// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object
@@ -72,7 +76,7 @@ unsigned queue_proxy_slot_count(const void* queue);
72unsigned fence_proxy_slot_count(const void* fence); 76unsigned fence_proxy_slot_count(const void* fence);
73unsigned queue_proxy_table_size(); 77unsigned queue_proxy_table_size();
74unsigned fence_proxy_table_size(); 78unsigned fence_proxy_table_size();
75// Live references on a queue or fence proxy (0 for anything else). Test helper. 79// Live references on a queue, fence or allocator proxy (0 for anything else). Test helper.
76unsigned long command_object_proxy_ref_count(const void* object); 80unsigned long command_object_proxy_ref_count(const void* object);
77// Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. 81// Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies.
78std::uint64_t queue_slot_hits(unsigned slot); 82std::uint64_t queue_slot_hits(unsigned slot);
@@ -82,8 +86,28 @@ bool fence_slot_first_call_seen(unsigned slot);
82// Vtable reads past a queue or fence proxy table that faulted in its guard region (counted by the fault logger). 86// Vtable reads past a queue or fence proxy table that faulted in its guard region (counted by the fault logger).
83std::uint64_t queue_table_overruns(); 87std::uint64_t queue_table_overruns();
84std::uint64_t fence_table_overruns(); 88std::uint64_t fence_table_overruns();
85// True when both tables sit in front of their guard region (false only if the reservation failed). 89// True when the queue, fence and allocator tables sit in front of their guard regions (false only if a reservation
90// or the fault logger failed).
86bool command_object_tables_guarded(); 91bool command_object_tables_guarded();
92
93// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a
94// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the
95// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not
96// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's
97// own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime
98// allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a
99// command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too.
100// {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}: the Vulkan layer's CommandAllocator answers it with its implementation.
101inline constexpr GUID kLeonidaCommandAllocatorTag{
102 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}};
103bool is_allocator_proxy(const void* allocator);
104// The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy.
105ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator);
106unsigned allocator_proxy_slot_count(const void* allocator);
107unsigned allocator_proxy_table_size();
108std::uint64_t allocator_slot_hits(unsigned slot);
109bool allocator_slot_first_call_seen(unsigned slot);
110std::uint64_t allocator_table_overruns();
87// Heap slots 0-2, 7 (GetDevice -> device proxy) and 9/10 (handle conversion). 111// Heap slots 0-2, 7 (GetDevice -> device proxy) and 9/10 (handle conversion).
88bool heap_slot_overridden(unsigned slot); 112bool heap_slot_overridden(unsigned slot);
89 113
diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp
index 17449fefc..caf09cee7 100644
--- a/runtime/shims/dxgi_com.cpp
+++ b/runtime/shims/dxgi_com.cpp
@@ -22,12 +22,14 @@ void stub(const char* method) {
22 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method); 22 if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method);
23} 23}
24 24
25bool valid_flip_buffer_count(UINT count) {
26 return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
27}
28
25VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) { 29VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) {
26 switch (fmt) { 30 switch (fmt) {
27 case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM; 31 case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
28 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
29 case DXGI_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM; 32 case DXGI_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM;
30 case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return VK_FORMAT_R8G8B8A8_SRGB;
31 case DXGI_FORMAT_R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; 33 case DXGI_FORMAT_R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
32 case DXGI_FORMAT_R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT; 34 case DXGI_FORMAT_R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT;
33 default: return VK_FORMAT_UNDEFINED; 35 default: return VK_FORMAT_UNDEFINED;
@@ -122,20 +124,14 @@ public:
122 if (parent_) parent_->Release(); 124 if (parent_) parent_->Release();
123 } 125 }
124 126
125 bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc) { 127 bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc, VkFormat vk_fmt) {
126 hwnd_ = hwnd; 128 hwnd_ = hwnd;
127 flags_ = desc.Flags; 129 flags_ = desc.Flags;
128 const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u}); 130 const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u});
129 const std::uint32_t w = size.width; 131 const std::uint32_t w = size.width;
130 const std::uint32_t h = size.height; 132 const std::uint32_t h = size.height;
131 const std::uint32_t count = desc.BufferCount ? desc.BufferCount : 2u;
132 VkFormat vk_fmt = VK_FORMAT_UNDEFINED;
133 if (desc.Format != DXGI_FORMAT_UNKNOWN) {
134 vk_fmt = dxgi_to_vk_format(desc.Format);
135 if (vk_fmt == VK_FORMAT_UNDEFINED) return false;
136 }
137 const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; 133 const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
138 if (!swapchain_.create(hwnd, w, h, vk_fmt, count, allow_tearing)) return false; 134 if (!swapchain_.create(hwnd, w, h, vk_fmt, desc.BufferCount, allow_tearing)) return false;
139 if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) { 135 if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) {
140 // DXGI: waitable swapchains default to maximum frame latency 1. 136 // DXGI: waitable swapchains default to maximum frame latency 1.
141 max_frame_latency_.store(1, std::memory_order_relaxed); 137 max_frame_latency_.store(1, std::memory_order_relaxed);
@@ -234,11 +230,15 @@ public:
234 } 230 }
235 231
236 HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags) override { 232 HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags) override {
233 if (count != 0 && !valid_flip_buffer_count(count)) return E_INVALIDARG;
237 VkFormat vk_fmt = VK_FORMAT_UNDEFINED; 234 VkFormat vk_fmt = VK_FORMAT_UNDEFINED;
238 if (fmt != DXGI_FORMAT_UNKNOWN) { 235 if (fmt != DXGI_FORMAT_UNKNOWN) {
239 vk_fmt = dxgi_to_vk_format(fmt); 236 vk_fmt = dxgi_to_vk_format(fmt);
240 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_UNSUPPORTED; 237 if (vk_fmt == VK_FORMAT_UNDEFINED) return E_INVALIDARG;
241 } 238 }
239 constexpr UINT creation_only_flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT |
240 DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
241 if ((flags & creation_only_flags) != (flags_ & creation_only_flags)) return E_INVALIDARG;
242 // DXGI refuses to resize while the app still holds a back buffer reference. 242 // DXGI refuses to resize while the app still holds a back buffer reference.
243 for (auto* bb : buffers_) 243 for (auto* bb : buffers_)
244 if (bb->held_by_app()) return DXGI_ERROR_INVALID_CALL; 244 if (bb->held_by_app()) return DXGI_ERROR_INVALID_CALL;
@@ -246,8 +246,7 @@ public:
246 const VkExtent2D size = size_or_client(width, height, swapchain_.extent()); 246 const VkExtent2D size = size_or_client(width, height, swapchain_.extent());
247 const std::uint32_t w = size.width; 247 const std::uint32_t w = size.width;
248 const std::uint32_t h = size.height; 248 const std::uint32_t h = size.height;
249 const UINT waitable_bit = flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 249 const UINT next_flags = flags ? flags : flags_;
250 const UINT next_flags = (flags ? flags : flags_) | waitable_bit;
251 const bool allow_tearing = (next_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; 250 const bool allow_tearing = (next_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
252 if (!swapchain_.resize(w, h, vk_fmt, count, allow_tearing)) return E_FAIL; 251 if (!swapchain_.resize(w, h, vk_fmt, count, allow_tearing)) return E_FAIL;
253 statistics_disjoint_.store(true, std::memory_order_relaxed); 252 statistics_disjoint_.store(true, std::memory_order_relaxed);
@@ -782,24 +781,57 @@ public:
782 if (!out) return E_POINTER; 781 if (!out) return E_POINTER;
783 *out = nullptr; 782 *out = nullptr;
784 if (!hwnd || !desc) return E_INVALIDARG; 783 if (!hwnd || !desc) return E_INVALIDARG;
784 if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL;
785 const VkFormat vk_fmt = dxgi_to_vk_format(desc->Format);
786 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL;
785 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); 787 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_);
786 if (!sc->init(hwnd, *desc)) { 788 if (!sc->init(hwnd, *desc, vk_fmt)) {
787 sc->Release(); 789 sc->Release();
788 return E_FAIL; 790 return E_FAIL;
789 } 791 }
790 *out = static_cast<IDXGISwapChain1*>(sc); 792 *out = static_cast<IDXGISwapChain1*>(sc);
791 return S_OK; 793 return S_OK;
792 } 794 }
793 HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(IUnknown*, IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, 795 HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(IUnknown* device, IUnknown* window,
794 IDXGIOutput*, IDXGISwapChain1**) override { 796 const DXGI_SWAP_CHAIN_DESC1* desc,
795 return E_NOTIMPL; 797 IDXGIOutput* restrict_to_output,
798 IDXGISwapChain1** out) override {
799 if (!out) return E_POINTER;
800 *out = nullptr;
801 if (!device || !window || !desc) return E_INVALIDARG;
802 // UWP / Game Core Scarlett titles present to an ICoreWindow. Extract the underlying
803 // Win32 HWND via ICoreWindowInterop.
804 static constexpr GUID kIID_ICoreWindowInterop = {
805 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
806 struct ICoreWindowInterop : public IUnknown {
807 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) = 0;
808 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char value) = 0;
809 };
810 ICoreWindowInterop* interop = nullptr;
811 if (FAILED(window->QueryInterface(kIID_ICoreWindowInterop, reinterpret_cast<void**>(&interop))) || !interop) {
812 return DXGI_ERROR_INVALID_CALL;
813 }
814 HWND hwnd = nullptr;
815 const HRESULT hr = interop->get_WindowHandle(&hwnd);
816 interop->Release();
817 if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL;
818 return CreateSwapChainForHwnd(device, hwnd, desc, nullptr, restrict_to_output, out);
796 } 819 }
797 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; } 820 HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; }
798 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } 821 HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; }
799 HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; } 822 HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; }
800 void STDMETHODCALLTYPE UnregisterStereoStatus(DWORD) override {} 823 void STDMETHODCALLTYPE UnregisterStereoStatus(DWORD) override {}
801 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } 824 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(HWND hwnd, UINT msg, DWORD* cookie) override {
802 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(HANDLE, DWORD*) override { return E_NOTIMPL; } 825 (void)msg;
826 if (!hwnd || !cookie) return DXGI_ERROR_INVALID_CALL;
827 *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed);
828 return S_OK;
829 }
830 HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(HANDLE event, DWORD* cookie) override {
831 if (!event || !cookie) return DXGI_ERROR_INVALID_CALL;
832 *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed);
833 return S_OK;
834 }
803 void STDMETHODCALLTYPE UnregisterOcclusionStatus(DWORD) override {} 835 void STDMETHODCALLTYPE UnregisterOcclusionStatus(DWORD) override {}
804 HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, IDXGIOutput*, 836 HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, IDXGIOutput*,
805 IDXGISwapChain1**) override { 837 IDXGISwapChain1**) override {
@@ -885,6 +917,7 @@ private:
885 HWND assoc_hwnd_ = nullptr; 917 HWND assoc_hwnd_ = nullptr;
886 mutable std::once_flag tearing_once_; 918 mutable std::once_flag tearing_once_;
887 bool tearing_supported_ = false; 919 bool tearing_supported_ = false;
920 std::atomic<DWORD> next_occlusion_cookie_{1};
888}; 921};
889 922
890} // namespace 923} // namespace
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index 38c3194fe..f0ae08811 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -142,7 +142,9 @@ std::filesystem::path marker(const std::filesystem::path& overlay, const std::ve
142bool deleted(const std::filesystem::path& overlay, const std::vector<std::wstring>& parts) { 142bool deleted(const std::filesystem::path& overlay, const std::vector<std::wstring>& parts) {
143 if (overlay.empty() || parts.empty()) return false; 143 if (overlay.empty() || parts.empty()) return false;
144 std::error_code ec; 144 std::error_code ec;
145 return std::filesystem::exists(marker(overlay, parts), ec); 145 // Only regular files are deletion markers; parent directories inside .gta6rt-deleted/ exist only to hold markers
146 // for nested deleted files and must not hide the corresponding ancestor directories in the package.
147 return std::filesystem::is_regular_file(marker(overlay, parts), ec);
146} 148}
147 149
148Target read_target(const std::wstring& path) { 150Target read_target(const std::wstring& path) {
diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp
index c0070782f..d3f76a684 100644
--- a/runtime/shims/process.cpp
+++ b/runtime/shims/process.cpp
@@ -9,6 +9,10 @@
9// process-wide atexit table also holds gta6rt's own). 9// process-wide atexit table also holds gta6rt's own).
10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and 10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and
11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. 11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here.
12// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a
13// title can import them by: kernel32.dll (the classic import libraries), kernelbase.dll, and the API sets that the
14// umbrella libraries a GDK title links (OneCore_apiset.lib, mincore.lib) bind them to. The retail package's own DLLs
15// import ExitProcess from api-ms-win-core-processthreads-l1-1-0.dll.
12#include <windows.h> 16#include <windows.h>
13 17
14#include <atomic> 18#include <atomic>
@@ -16,6 +20,7 @@
16#include <cstdlib> 20#include <cstdlib>
17#include <cstring> 21#include <cstring>
18#include <string> 22#include <string>
23#include <type_traits>
19#include <vector> 24#include <vector>
20 25
21#include "process_shim.h" 26#include "process_shim.h"
@@ -107,6 +112,24 @@ wchar_t** __cdecl game_p_wcmdln_storage() {
107 return &p; 112 return &p;
108} 113}
109 114
115// What the UCRT's _get_narrow/_get_wide_winmain_command_line return, and the CRT's WinMain startup passes as
116// lpCmdLine: the command line after the program name and the blanks that follow it. The program name ends at the
117// first character up to ' ' outside quotes, the UCRT's own scan. The comparison is unsigned, so a non-ASCII byte of
118// the narrow line is part of the name; a DBCS trail byte is never '"' or a blank, so it needs no lead-byte step.
119template <typename C>
120C* after_program_name(C* p) {
121 using U = std::make_unsigned_t<C>;
122 bool quoted = false;
123 while (U(*p) > U(' ') || (*p && quoted)) {
124 if (*p == C('"')) quoted = !quoted;
125 ++p;
126 }
127 while (*p && U(*p) <= U(' ')) ++p;
128 return p;
129}
130char* __cdecl game_get_narrow_winmain_command_line() { return after_program_name(g_cmdline.data()); }
131wchar_t* __cdecl game_get_wide_winmain_command_line() { return after_program_name(g_wcmdline.data()); }
132
110// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) 133// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo)
111int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { 134int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) {
112 *argc = g_argc; 135 *argc = g_argc;
@@ -197,7 +220,13 @@ using namespace rt::process;
197 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_argv)}, \ 220 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
198 {dll, "_configure_wide_argv", reinterpret_cast<void*>(&game_configure_argv)}, \ 221 {dll, "_configure_wide_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
199 {dll, "__p__acmdln", reinterpret_cast<void*>(&game_p_acmdln_storage)}, \ 222 {dll, "__p__acmdln", reinterpret_cast<void*>(&game_p_acmdln_storage)}, \
200 {dll, "__p__wcmdln", reinterpret_cast<void*>(&game_p_wcmdln_storage)} 223 {dll, "__p__wcmdln", reinterpret_cast<void*>(&game_p_wcmdln_storage)}, \
224 {dll, "_get_narrow_winmain_command_line", reinterpret_cast<void*>(&game_get_narrow_winmain_command_line)}, \
225 {dll, "_get_wide_winmain_command_line", reinterpret_cast<void*>(&game_get_wide_winmain_command_line)}
226#define EXIT_PROCESS(dll) {dll, "ExitProcess", reinterpret_cast<void*>(&game_exit_process)}
227#define COMMAND_LINE(dll) \
228 {dll, "GetCommandLineA", reinterpret_cast<void*>(&game_get_command_line_a)}, \
229 {dll, "GetCommandLineW", reinterpret_cast<void*>(&game_get_command_line_w)}
201} // namespace 230} // namespace
202 231
203SHIM_TABLE(process, 232SHIM_TABLE(process,
@@ -209,7 +238,10 @@ SHIM_TABLE(process,
209 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)}, 238 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)},
210 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)}, 239 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)},
211 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)}, 240 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)},
212 {"kernel32.dll", "ExitProcess", reinterpret_cast<void*>(&game_exit_process)}, 241 EXIT_PROCESS("kernel32.dll"),
213 {"kernel32.dll", "GetCommandLineA", reinterpret_cast<void*>(&game_get_command_line_a)}, 242 EXIT_PROCESS("kernelbase.dll"),
214 {"kernel32.dll", "GetCommandLineW", reinterpret_cast<void*>(&game_get_command_line_w)}, 243 EXIT_PROCESS("api-ms-win-core-processthreads-l1-1-0.dll"),
244 COMMAND_LINE("kernel32.dll"),
245 COMMAND_LINE("kernelbase.dll"),
246 COMMAND_LINE("api-ms-win-core-processenvironment-l1-1-0.dll"),
215); 247);
diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp
index 8135589b9..46aec5af7 100644
--- a/runtime/shims/xgameruntime.cpp
+++ b/runtime/shims/xgameruntime.cpp
@@ -16,6 +16,7 @@
16#include <cstdio> 16#include <cstdio>
17#include <cstdlib> 17#include <cstdlib>
18#include <cstring> 18#include <cstring>
19#include <iterator>
19 20
20#include <XAsync.h> 21#include <XAsync.h>
21#include <XAsyncProvider.h> 22#include <XAsyncProvider.h>
@@ -35,9 +36,9 @@ std::atomic<int> g_runtime_refs{0};
35// "xgameruntime.dll" and GetProcAddress these five names (measured in the package's libHttpClient.GDK.dll and 36// "xgameruntime.dll" and GetProcAddress these five names (measured in the package's libHttpClient.GDK.dll and
36// XCurl.dll, docs/runtime_imports.md). Signatures, the options struct and the error for an unknown class follow 37// XCurl.dll, docs/runtime_imports.md). Signatures, the options struct and the error for an unknown class follow
37// xodus-gaming/xgameruntime-docs (GPL-3.0; facts only, nothing copied): InitializeApiImplEx2 is the one 38// xodus-gaming/xgameruntime-docs (GPL-3.0; facts only, nothing copied): InitializeApiImplEx2 is the one
38// XGameRuntimeInitialize[WithOptions] calls, and QueryApiImpl hands out the runtime's COM classes. The classes' 39// XGameRuntimeInitialize[WithOptions] calls, and QueryApiImpl hands out the runtime's COM classes. XThreadingImpl and
39// method layouts are not known yet, so QueryApiImpl logs each class and interface id it is asked for and refuses 40// XErrorImpl are served (their layouts are measured, below); for any other class QueryApiImpl logs the class and
40// them; the first boot with the executable then lists the interfaces to implement. 41// interface id and refuses it, so the first boot with the executable lists the interfaces to implement next.
41 42
42struct ApiImplOptions { // InitializeApiImplEx2's fourth argument 43struct ApiImplOptions { // InitializeApiImplEx2's fourth argument
43 uint32_t unknown; // documented as always 1 44 uint32_t unknown; // documented as always 1
@@ -85,8 +86,149 @@ void print_guid(char (&out)[40], const GUID* g) {
85 g->Data4[6], g->Data4[7]); 86 g->Data4[6], g->Data4[7]);
86} 87}
87 88
89// ---- The runtime classes QueryApiImpl hands out ----
90//
91// xgameruntime.lib's thunk for each function asks QueryApiImpl for the class (passing the class id as the interface
92// id too), calls one slot of the object's vtable with the function's own arguments after `this`, and Releases it.
93// The slot order is xgameruntime-docs' "Layout" list after IUnknown's three slots, and it is measured: the thunks
94// statically linked into the package's libHttpClient.GDK.dll and XCurl.dll (disassembled, their code not run)
95// call IXThreadingImpl slots 3-7 and 9-30, each with the argument shape of the documented function in that
96// position (XAsyncBegin's five arguments at slot 7, XTaskQueueCreate's two modes and a handle pointer at 12,
97// XTaskQueueTerminate's bool at 22, XThreadSetTimeSensitive's bool at 27, ...), and IXErrorImpl slot 3 with an
98// HRESULT and a pointer. docs/runtime_imports.md has the table. Each function is served by the implementation the
99// named export already uses (third_party/xtaskqueue), so the two ways in behave the same.
100
101constexpr GUID kThreadingClass = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
102constexpr GUID kErrorClass = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}};
103
104// A function's arguments after `this`, forwarded unchanged (x64 has one calling convention).
105// Specialised on the function's exact type, so a noexcept function matches only one form.
106template <auto F, class T = decltype(F)> struct Method;
107template <auto F, class R, class... A> struct Method<F, R (*)(A...)> {
108 static R STDMETHODCALLTYPE call(void*, A... a) { return F(a...); }
109};
110template <auto F, class R, class... A> struct Method<F, R (*)(A...) noexcept> {
111 static R STDMETHODCALLTYPE call(void*, A... a) noexcept { return F(a...); }
112};
113
114constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
115
116// The runtime's objects are process-wide singletons: AddRef/Release count but never free.
117struct RuntimeObject {
118 const void* const* vtable;
119 const GUID* class_id;
120 std::atomic<long> refs{1};
121};
122
123HRESULT STDMETHODCALLTYPE object_query_interface(void* self, REFIID iid, void** out) {
124 if (!out) return E_POINTER;
125 auto* o = static_cast<RuntimeObject*>(self);
126 if (iid == kIUnknown || iid == *o->class_id) {
127 o->refs.fetch_add(1);
128 *out = self;
129 return S_OK;
130 }
131 *out = nullptr;
132 return E_NOINTERFACE;
133}
134ULONG STDMETHODCALLTYPE object_add_ref(void* self) { return static_cast<ULONG>(static_cast<RuntimeObject*>(self)->refs.fetch_add(1) + 1); }
135ULONG STDMETHODCALLTYPE object_release(void* self) {
136 long prev = static_cast<RuntimeObject*>(self)->refs.load();
137 while (prev > 1 && !static_cast<RuntimeObject*>(self)->refs.compare_exchange_weak(prev, prev - 1)) {}
138 return static_cast<ULONG>(prev > 1 ? prev - 1 : 1); // the singleton's own reference stays
139}
140
141// A private slot whose signature isn't public: logged once, answers 0 (S_OK / false / nothing to do).
142template <int Slot> uint64_t STDMETHODCALLTYPE private_slot(void*) {
143 static std::atomic<bool> s_logged{false};
144 if (!s_logged.exchange(true))
145 std::fprintf(stderr, "[rt] xgameruntime: XThreadingImpl private slot %d called; answering 0\n", Slot);
146 return 0;
147}
148
149// XThreadSetTimeSensitive / XThreadIsTimeSensitive / XThreadAssertNotTimeSensitive. The flag is per thread, as in
150// the GDK; nothing is enforced offline (a time-sensitive thread may still block).
151thread_local bool t_time_sensitive = false;
152HRESULT STDMETHODCALLTYPE thread_set_time_sensitive(void*, bool value) {
153 t_time_sensitive = value;
154 return S_OK;
155}
156void STDMETHODCALLTYPE thread_assert_not_time_sensitive(void*) {}
157bool STDMETHODCALLTYPE thread_is_time_sensitive(void*) { return t_time_sensitive; }
158
159#define XM(fn) reinterpret_cast<const void*>(&Method<&fn>::call)
160const void* const kThreadingVtable[] = {
161 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
162 reinterpret_cast<const void*>(&object_release),
163 XM(XAsyncGetStatus), // 3
164 XM(XAsyncGetResultSize), // 4
165 XM(XAsyncCancel), // 5
166 XM(XAsyncRun), // 6
167 XM(XAsyncBegin), // 7
168 reinterpret_cast<const void*>(&private_slot<8>), // 8 XAsyncBeginAlloc (private, not called by the package)
169 XM(XAsyncSchedule), // 9
170 XM(XAsyncComplete), // 10
171 XM(XAsyncGetResult), // 11
172 XM(XTaskQueueCreate), // 12
173 XM(XTaskQueueCreateComposite), // 13
174 XM(XTaskQueueGetPort), // 14
175 XM(XTaskQueueDuplicateHandle), // 15
176 XM(XTaskQueueDispatch), // 16
177 XM(XTaskQueueCloseHandle), // 17
178 XM(XTaskQueueSubmitCallback), // 18
179 XM(XTaskQueueSubmitDelayedCallback), // 19
180 XM(XTaskQueueRegisterWaiter), // 20
181 XM(XTaskQueueUnregisterWaiter), // 21
182 XM(XTaskQueueTerminate), // 22
183 XM(XTaskQueueRegisterMonitor), // 23
184 XM(XTaskQueueUnregisterMonitor), // 24
185 XM(XTaskQueueGetCurrentProcessTaskQueue), // 25
186 XM(XTaskQueueSetCurrentProcessTaskQueue), // 26
187 reinterpret_cast<const void*>(&thread_set_time_sensitive), // 27
188 reinterpret_cast<const void*>(&private_slot<28>), // 28 XTaskQueueIsEmpty (private; no arguments)
189 reinterpret_cast<const void*>(&thread_assert_not_time_sensitive), // 29
190 reinterpret_cast<const void*>(&thread_is_time_sensitive), // 30
191};
192#undef XM
193static_assert(std::size(kThreadingVtable) == 31, "IUnknown + IXThreadingImpl's 28 methods");
194
195// IXErrorImpl: XErrorReport(HRESULT, const char*) at slot 3 (the docs' "_unknown_"; XCurl calls it with an HRESULT
196// and a string), XErrorSetCallback(XErrorCallback*, void*) and XErrorSetOptions(options, options). Offline, a report
197// is logged and handed to the callback the title set, if any.
198using XErrorCallback = bool(CALLBACK*)(HRESULT hr, const char* message, void* context);
199std::atomic<XErrorCallback> g_error_callback{nullptr};
200std::atomic<void*> g_error_context{nullptr};
201
202void STDMETHODCALLTYPE error_report(void*, HRESULT hr, const char* message) {
203 static std::atomic<int> s_logged{0};
204 if (s_logged.fetch_add(1) < 64)
205 std::fprintf(stderr, "[rt] xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast<unsigned long>(hr),
206 message ? message : "(null)");
207 if (XErrorCallback cb = g_error_callback.load()) cb(hr, message, g_error_context.load());
208}
209void STDMETHODCALLTYPE error_set_callback(void*, XErrorCallback callback, void* context) {
210 g_error_context = context;
211 g_error_callback = callback;
212}
213HRESULT STDMETHODCALLTYPE error_set_options(void*, uint32_t, uint32_t) { return S_OK; }
214
215const void* const kErrorVtable[] = {
216 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
217 reinterpret_cast<const void*>(&object_release),
218 reinterpret_cast<const void*>(&error_report), // 3
219 reinterpret_cast<const void*>(&error_set_callback), // 4
220 reinterpret_cast<const void*>(&error_set_options), // 5
221};
222
223RuntimeObject g_threading{kThreadingVtable, &kThreadingClass};
224RuntimeObject g_error{kErrorVtable, &kErrorClass};
225
88HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) { 226HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) {
89 if (out) *out = nullptr; 227 if (out) *out = nullptr;
228 if (class_id && out) {
229 for (RuntimeObject* o : {&g_threading, &g_error})
230 if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out);
231 }
90 char cls[40], iid[40]; 232 char cls[40], iid[40];
91 print_guid(cls, class_id); 233 print_guid(cls, class_id);
92 print_guid(iid, &interface_id); 234 print_guid(iid, &interface_id);
@@ -156,6 +298,115 @@ uint64_t __stdcall XSystemGetAppMemoryUsage() {
156 return 0; 298 return 0;
157} 299}
158 300
301// XVersion: 4-part version structure from GDK XGameRuntimeTypes.h (8 bytes)
302struct XVersion {
303 union {
304 struct {
305 uint16_t major;
306 uint16_t minor;
307 uint16_t build;
308 uint16_t revision;
309 };
310 uint64_t Value;
311 };
312};
313static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes");
314
315// XSystemAnalyticsInfo: hardware and OS version telemetry (144 bytes)
316struct XSystemAnalyticsInfo {
317 XVersion osVersion;
318 XVersion hostingOsVersion;
319 char family[64];
320 char form[64];
321};
322static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes");
323
324// XSystemAnalyticsInfo XSystemGetAnalyticsInfo()
325// Returned by value per Microsoft GDK specification.
326XSystemAnalyticsInfo __stdcall XSystemGetAnalyticsInfo() {
327 XSystemAnalyticsInfo info{};
328 info.osVersion = {10, 0, 22000, 0};
329 info.hostingOsVersion = {10, 0, 22000, 0};
330 std::strncpy(info.family, "Xbox", sizeof(info.family) - 1);
331
332 const uint32_t dt = XSystemGetDeviceType();
333 if (dt == static_cast<uint32_t>(XSystemDeviceType::XboxScarlettLockhart)) {
334 std::strncpy(info.form, "Xbox Series S", sizeof(info.form) - 1);
335 } else {
336 std::strncpy(info.form, "Xbox Series X", sizeof(info.form) - 1);
337 }
338
339 char form_override[64];
340 const DWORD n = GetEnvironmentVariableA("LEONIDA_ANALYTICS_FORM", form_override, sizeof(form_override));
341 if (n > 0 && n < sizeof(form_override)) {
342 std::strncpy(info.form, form_override, sizeof(info.form) - 1);
343 }
344 return info;
345}
346
347// ---- XPackage ----
348
349constexpr size_t XPACKAGE_IDENTIFIER_MAX_LENGTH = 33;
350constexpr char kDefaultPackageIdentifier[XPACKAGE_IDENTIFIER_MAX_LENGTH] = "LeonidaPackageIdentifier00000000";
351static_assert(sizeof(kDefaultPackageIdentifier) == XPACKAGE_IDENTIFIER_MAX_LENGTH,
352 "default package identifier must match XPACKAGE_IDENTIFIER_MAX_LENGTH");
353
354// HRESULT XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer).
355// Retrieves the package identifier string for the current process.
356HRESULT __stdcall XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer) {
357 if (!buffer || bufferSize == 0) return E_INVALIDARG;
358
359 char id[XPACKAGE_IDENTIFIER_MAX_LENGTH] = {};
360 const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGE_ID", id, sizeof(id));
361 const char* selected = (n > 0 && n < sizeof(id)) ? id : kDefaultPackageIdentifier;
362 const size_t len = std::strlen(selected);
363
364 if (bufferSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
365 std::memcpy(buffer, selected, len + 1);
366 return S_OK;
367}
368
369// HRESULT XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path).
370// Retrieves the installed filesystem path for the mounted package.
371// Reads LEONIDA_GAME_DIR when set, otherwise falls back to the current module's directory.
372HRESULT __stdcall XPackageGetMountPath(void* /*mount*/, size_t pathSize, char* path) {
373 if (!path || pathSize == 0) return E_INVALIDARG;
374
375 char buf[MAX_PATH] = {};
376 const DWORD n = GetEnvironmentVariableA("LEONIDA_GAME_DIR", buf, sizeof(buf));
377 if (n == 0 || n >= sizeof(buf)) {
378 const DWORD mod_len = GetModuleFileNameA(nullptr, buf, sizeof(buf));
379 if (mod_len > 0 && mod_len < sizeof(buf)) {
380 char* slash = std::strrchr(buf, '\\');
381 char* fslash = std::strrchr(buf, '/');
382 char* last = slash > fslash ? slash : fslash;
383 if (last) {
384 *last = '\0';
385 } else {
386 return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
387 }
388 } else {
389 return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
390 }
391 }
392
393 const size_t len = std::strlen(buf);
394 if (pathSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
395 std::memcpy(path, buf, len + 1);
396 return S_OK;
397}
398
399// bool XPackageIsPackagedProcess().
400// Returns true on Xbox Series console. LEONIDA_PACKAGED=0 overrides it.
401bool __stdcall XPackageIsPackagedProcess() {
402 char s[16];
403 const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGED", s, sizeof(s));
404 if (n > 0 && n < sizeof(s)) {
405 if (std::atoi(s) == 0) return false;
406 }
407 return true;
408}
409
159#define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast<void*>(&name)} 410#define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast<void*>(&name)}
160 411
161} // namespace 412} // namespace
@@ -173,6 +424,10 @@ SHIM_TABLE(xgameruntime,
173 XGR(XSystemGetConsoleId), 424 XGR(XSystemGetConsoleId),
174 XGR(XSystemGetAppMemoryUsageLimit), 425 XGR(XSystemGetAppMemoryUsageLimit),
175 XGR(XSystemGetAppMemoryUsage), 426 XGR(XSystemGetAppMemoryUsage),
427 XGR(XSystemGetAnalyticsInfo),
428 XGR(XPackageGetCurrentProcessPackageIdentifier),
429 XGR(XPackageGetMountPath),
430 XGR(XPackageIsPackagedProcess),
176 // XTaskQueue (third_party/xtaskqueue) 431 // XTaskQueue (third_party/xtaskqueue)
177 XGR(XTaskQueueCreate), 432 XGR(XTaskQueueCreate),
178 XGR(XTaskQueueCreateComposite), 433 XGR(XTaskQueueCreateComposite),
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h
new file mode 100644
index 000000000..bf4946895
--- /dev/null
+++ b/runtime/src/base_reservation.h
@@ -0,0 +1,151 @@
1#pragma once
2
3// Keeping a relocation-less game image's preferred range free until the loader maps it there.
4//
5// An EXE without a .reloc directory can only run at its ImageBase (0x140000000 by default). Windows and x86-64 Wine
6// leave that range alone, but arm64 Wine on macOS (CrossOver's arm64 bottles, whose x86-64 code runs under FEX) puts
7// its own start-up allocations at 0x100000000 and up, over that range, before gta6rt's first line runs. So gta6rt
8// starts itself again, suspended, reserves [ImageBase, ImageBase + SizeOfImage) in that child before any of its code
9// runs, and resumes it; the child's loader then commits the image inside the reservation (commit_reserved), so
10// nothing else can take the range in between. The child is told by LEONIDA_BASE_RESERVED=<base>:<size> (hex), which
11// also stops it from starting itself again. Measured on CrossOver Preview 20260821 (arm64 bottle, M2 Max): in a
12// suspended child 0x140000000-0x170000000 is free and reservable; macOS maps its own regions above that (the arm64
13// shared region starts at 0x180000000), so a range there can't be had either way.
14//
15// Nothing changes where the range is free at start-up (Windows, x86-64 Wine) or where the image has relocations.
16
17#include <windows.h>
18
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cwchar>
23#include <filesystem>
24#include <fstream>
25#include <optional>
26#include <string>
27#include <vector>
28
29namespace rt::base_reservation {
30
31inline constexpr wchar_t kVariable[] = L"LEONIDA_BASE_RESERVED";
32
33struct Range {
34 std::uint64_t base = 0;
35 std::uint64_t size = 0;
36};
37
38// The range this process was started with (LEONIDA_BASE_RESERVED), if any.
39inline std::optional<Range> inherited() {
40 wchar_t value[64] = {};
41 const DWORD length = GetEnvironmentVariableW(kVariable, value, 64);
42 if (!length || length >= 64) return std::nullopt;
43 Range r{};
44 if (std::swscanf(value, L"%llx:%llx", reinterpret_cast<unsigned long long*>(&r.base),
45 reinterpret_cast<unsigned long long*>(&r.size)) != 2 ||
46 !r.size)
47 return std::nullopt;
48 return r;
49}
50
51// Commits [base, base + size) for the loader when it lies inside the reservation this process was started with and
52// that reservation is still in place; returns null otherwise (the caller then allocates as usual). The reservation
53// is the allocation, so VirtualFree(base, 0, MEM_RELEASE) frees it as it frees any image.
54inline void* commit_reserved(std::uint64_t base, std::uint64_t size) {
55 const auto r = inherited();
56 if (!r || base != r->base || size > r->size) return nullptr;
57 MEMORY_BASIC_INFORMATION info{};
58 if (!VirtualQuery(reinterpret_cast<void*>(base), &info, sizeof info) || info.State != MEM_RESERVE ||
59 reinterpret_cast<std::uint64_t>(info.AllocationBase) != base)
60 return nullptr;
61 return VirtualAlloc(reinterpret_cast<void*>(base), static_cast<SIZE_T>(size), MEM_COMMIT, PAGE_READWRITE);
62}
63
64// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt
65// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself).
66inline std::optional<Range> needed(const std::filesystem::path& image) {
67 std::ifstream file(image, std::ios::binary);
68 IMAGE_DOS_HEADER dos{};
69 if (!file.read(reinterpret_cast<char*>(&dos), sizeof dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < 0)
70 return std::nullopt;
71 IMAGE_NT_HEADERS64 nt{};
72 if (!file.seekg(dos.e_lfanew) || !file.read(reinterpret_cast<char*>(&nt), sizeof nt) ||
73 nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC ||
74 !nt.OptionalHeader.SizeOfImage)
75 return std::nullopt;
76 const auto& oh = nt.OptionalHeader;
77 if (oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC &&
78 oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size)
79 return std::nullopt; // relocatable: the loader moves it if the base is taken
80 const Range r{oh.ImageBase, (static_cast<std::uint64_t>(oh.SizeOfImage) + 0xffff) & ~std::uint64_t{0xffff}};
81 for (std::uint64_t at = r.base; at < r.base + r.size;) {
82 MEMORY_BASIC_INFORMATION info{};
83 if (!VirtualQuery(reinterpret_cast<void*>(at), &info, sizeof info)) return r;
84 if (info.State != MEM_FREE) return r;
85 at = reinterpret_cast<std::uint64_t>(info.BaseAddress) + info.RegionSize;
86 }
87 return std::nullopt;
88}
89
90// Runs this program again with the same command line, suspended, reserves `r` in the new process, resumes it and
91// returns its exit code. On failure prints why and returns 1 (the child, if any, is ended unrun).
92inline int relaunch(const Range& r) {
93 wchar_t self[MAX_PATH * 4] = {};
94 if (!GetModuleFileNameW(nullptr, self, MAX_PATH * 4)) {
95 std::fprintf(stderr, "error: GetModuleFileName failed (%lu)\n", GetLastError());
96 return 1;
97 }
98 wchar_t marker[64];
99 std::swprintf(marker, 64, L"%llx:%llx", static_cast<unsigned long long>(r.base),
100 static_cast<unsigned long long>(r.size));
101 // Inherited by the child: it tells it to commit inside the reservation and not to relaunch again.
102 if (!SetEnvironmentVariableW(kVariable, marker)) {
103 std::fprintf(stderr, "error: setting %ls failed (%lu)\n", kVariable, GetLastError());
104 return 1;
105 }
106 std::wstring command_line = GetCommandLineW();
107 STARTUPINFOW startup{sizeof startup};
108 startup.dwFlags = STARTF_USESTDHANDLES;
109 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
110 startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
111 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
112 for (HANDLE h : {startup.hStdInput, startup.hStdOutput, startup.hStdError})
113 if (h && h != INVALID_HANDLE_VALUE) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
114 PROCESS_INFORMATION process{};
115 std::fflush(stdout);
116 std::fflush(stderr);
117 if (!CreateProcessW(self, command_line.data(), nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr,
118 &startup, &process)) {
119 std::fprintf(stderr, "error: starting gta6rt again to reserve the image range failed (%lu)\n", GetLastError());
120 return 1;
121 }
122 const auto abandon = [&process] { // the child never ran: end it and release its handles
123 TerminateProcess(process.hProcess, 1);
124 CloseHandle(process.hThread);
125 CloseHandle(process.hProcess);
126 };
127 if (!VirtualAllocEx(process.hProcess, reinterpret_cast<void*>(r.base), static_cast<SIZE_T>(r.size), MEM_RESERVE,
128 PAGE_NOACCESS)) {
129 const DWORD error = GetLastError();
130 abandon();
131 std::fprintf(stderr,
132 "error: the image has no relocations and its range %#llx-%#llx is taken, also in a new "
133 "process (VirtualAllocEx %lu)\n",
134 static_cast<unsigned long long>(r.base), static_cast<unsigned long long>(r.base + r.size), error);
135 return 1;
136 }
137 if (ResumeThread(process.hThread) == static_cast<DWORD>(-1)) { // still suspended: the wait would never end
138 const DWORD error = GetLastError();
139 abandon();
140 std::fprintf(stderr, "error: resuming the relaunched gta6rt failed (%lu)\n", error);
141 return 1;
142 }
143 WaitForSingleObject(process.hProcess, INFINITE);
144 DWORD code = 1;
145 GetExitCodeProcess(process.hProcess, &code);
146 CloseHandle(process.hThread);
147 CloseHandle(process.hProcess);
148 return static_cast<int>(code);
149}
150
151} // namespace rt::base_reservation
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 9c74994e1..07520c2e3 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -565,6 +565,11 @@ struct ExecuteIndirect {
565 std::uint64_t argument_offset = 0; 565 std::uint64_t argument_offset = 0;
566 ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount 566 ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount
567 std::uint64_t count_offset = 0; 567 std::uint64_t count_offset = 0;
568 // kind == dispatch: the compute pipeline and root arguments in effect, as Dispatch records them, so the dispatches
569 // run that pipeline with those arguments whatever the command buffer had bound. A pipeline of 0 leaves the binding
570 // as it is.
571 std::uintptr_t pipeline = 0;
572 std::array<std::uint32_t, 32> user_data{};
568}; 573};
569 574
570// Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). 575// Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure).
@@ -594,11 +599,29 @@ struct BuildAccelerationStructure {
594 std::vector<RtTriangleGeometry> triangles; 599 std::vector<RtTriangleGeometry> triangles;
595}; 600};
596 601
602// CopyRaytracingAccelerationStructure. `mode` is D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE; replay supports
603// CLONE (0) and COMPACT (1) for XDXR structures.
604struct CopyAccelerationStructure {
605 std::uint64_t dst_va = 0;
606 std::uint64_t src_va = 0;
607 std::uint32_t mode = 0;
608};
609
610// EmitRaytracingAccelerationStructurePostbuildInfo, and each postbuild desc of BuildRaytracingAccelerationStructure:
611// one value per source, consecutively from `dest_va`. `type` is D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE;
612// replay supports COMPACTED_SIZE (0) and CURRENT_SIZE (3), 8 bytes each.
613struct AccelerationStructurePostbuild {
614 std::uint64_t dest_va = 0;
615 std::uint32_t type = 0;
616 std::vector<std::uint64_t> sources;
617};
618
597using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, 619using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier,
598 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, 620 TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture,
599 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource, 621 CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource,
600 WriteImmediate, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker, 622 WriteImmediate, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker,
601 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw>; 623 ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure,
624 AccelerationStructurePostbuild>;
602 625
603class CommandList { 626class CommandList {
604public: 627public:
@@ -809,6 +832,17 @@ public:
809 if (!build.dst_va || !build.scratch_va) return false; 832 if (!build.dst_va || !build.scratch_va) return false;
810 return append(std::move(build)); 833 return append(std::move(build));
811 } 834 }
835 // D3D12: acceleration structures are 256-byte aligned, postbuild destinations 8-byte aligned.
836 bool copy_acceleration_structure(CopyAccelerationStructure copy) {
837 if (!copy.dst_va || !copy.src_va || copy.dst_va % 256 || copy.src_va % 256) return false;
838 return append(copy);
839 }
840 bool acceleration_structure_postbuild(AccelerationStructurePostbuild info) {
841 if (!info.dest_va || info.dest_va % 8 || info.sources.empty()) return false;
842 for (const auto va : info.sources)
843 if (!va || va % 256) return false;
844 return append(std::move(info));
845 }
812 bool close() { 846 bool close() {
813 if (closed_) return false; 847 if (closed_) return false;
814 closed_ = true; 848 closed_ = true;
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index 59f96fd4f..2b5b111f7 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -129,7 +129,10 @@ public:
129 } 129 }
130 130
131 // Erases a key from the table. Returns true if the key was found and erased, false otherwise. 131 // Erases a key from the table. Returns true if the key was found and erased, false otherwise.
132 // Backward-shifts downstream entries in the probe cluster so probe chains remain intact and compact. 132 // Only the key's own slot changes (it becomes empty): no other entry moves. Every lookup, here and in the
133 // shaders (rdna2spirv.py desc_probe), compares all kDescriptorProbes slots and never stops at an empty one, so
134 // a hole breaks no probe chain and inserts reuse it. Keeping the other entries in place is what lets the GPU
135 // copy of the table take an erase while shaders still probe it (BindlessSet::flush_needs_idle).
133 bool erase(const std::uint32_t key[8]) { 136 bool erase(const std::uint32_t key[8]) {
134 std::lock_guard lock(mutex_); 137 std::lock_guard lock(mutex_);
135 return erase_locked(key); 138 return erase_locked(key);
@@ -321,24 +324,9 @@ private:
321 } 324 }
322 if (!found) return false; 325 if (!found) return false;
323 326
324 // Backward-shift entries in the probe cluster to maintain probe chains 327 // No backward shift: see erase().
325 std::uint32_t i = found_slot; 328 entries_[found_slot] = DescriptorEntry{};
326 std::uint32_t j = i;
327 mark(found_slot); 329 mark(found_slot);
328 while (true) {
329 j = (j + 1) & mask_;
330 if (entries_[j].pad != kSlotOccupiedMarker) break;
331 const std::uint32_t r = hash_descriptor_key(entries_[j].key);
332 const std::uint32_t dist_r_to_i = (i - r) & mask_;
333 const std::uint32_t dist_r_to_j = (j - r) & mask_;
334 if (dist_r_to_i < dist_r_to_j && dist_r_to_i < kDescriptorProbes) {
335 entries_[i] = entries_[j];
336 mark(i);
337 i = j;
338 }
339 }
340 entries_[i] = DescriptorEntry{};
341 mark(i);
342 --occupied_count_; 330 --occupied_count_;
343 return true; 331 return true;
344 } 332 }
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 7d3491653..560f68349 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -23,6 +23,7 @@
23#include <string> 23#include <string>
24#include <vector> 24#include <vector>
25 25
26#include "base_reservation.h"
26#include "pe_loader.h" 27#include "pe_loader.h"
27#include "../shims/d3d12_trace.h" 28#include "../shims/d3d12_trace.h"
28#include "../shims/file_system.h" 29#include "../shims/file_system.h"
@@ -73,6 +74,10 @@ int wmain(int argc, wchar_t** argv) {
73 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. 74 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point.
74 if (dry_run + init + run != 1) return usage(); 75 if (dry_run + init + run != 1) return usage();
75 if (game_dir.empty()) game_dir = image.parent_path(); 76 if (game_dir.empty()) game_dir = image.parent_path();
77 // An image without relocations whose range this process already uses (arm64 Wine on macOS) runs in a new
78 // process that has the range reserved from the start (base_reservation.h); that process does not do this again.
79 if (!rt::base_reservation::inherited())
80 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range);
76 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. 81 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package.
77 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 82 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
78 rt::fs::configure(game_dir, overlay_dir); 83 rt::fs::configure(game_dir, overlay_dir);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 1ab9c7801..387051756 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -14,6 +14,7 @@
14#include <vector> 14#include <vector>
15 15
16#include "../shims/shims.h" 16#include "../shims/shims.h"
17#include "base_reservation.h"
17 18
18namespace rt { 19namespace rt {
19 20
@@ -506,8 +507,11 @@ Module& Loader::map_image(const std::filesystem::path& path) {
506 by_name_[lower(m->name)] = m; 507 by_name_[lower(m->name)] = m;
507 order_.push_back(m); 508 order_.push_back(m);
508 509
509 m->base = static_cast<uint8_t*>( 510 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.
510 VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 511 m->base = static_cast<uint8_t*>(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage));
512 if (!m->base)
513 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
514 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
511 if (!m->base) { 515 if (!m->base) {
512 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 516 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
513 if (!relocs.Size) 517 if (!relocs.Size)
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
new file mode 100644
index 000000000..2057d953b
--- /dev/null
+++ b/runtime/src/vulkan13_features.h
@@ -0,0 +1,127 @@
1#pragma once
2
3// dynamicRendering and synchronization2, the two Vulkan 1.3 features the D3D12 layer needs, on a Vulkan 1.3 device
4// or on a Vulkan 1.2 device through VK_KHR_dynamic_rendering and VK_KHR_synchronization2. CrossOver's MoltenVK on
5// macOS is such a 1.2 device (1.2.10: Vulkan 1.2 with both extensions); the extension structs, functions and
6// behaviour are the core ones under another name, so the rest of the layer does not see the difference.
7//
8// leonida::Vulkan13Features v13;
9// v13.query(physical, props.apiVersion, get_features2, enumerate_extensions); // per candidate
10// if (!v13.usable()) continue;
11// enable12.pNext = v13.enable(chain); // chain: what came after VkPhysicalDeviceVulkan13Features
12// ... v13.next() is where later feature structs go (it used to be enable13.pNext)
13// v13.add_extensions(device_extensions);
14// fn = leonida::device_proc_or_khr(get_device_proc, device, "vkCmdPipelineBarrier2");
15
16#include <vulkan/vulkan.h>
17
18#include <cstdint>
19#include <cstring>
20#include <string>
21#include <vector>
22
23namespace leonida {
24
25class Vulkan13Features {
26public:
27 Vulkan13Features() = default;
28 Vulkan13Features(const Vulkan13Features&) = delete; // enable() links pointers into this object
29 Vulkan13Features& operator=(const Vulkan13Features&) = delete;
30
31 bool core = false; // a Vulkan 1.3 device: the features are core
32 bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering
33 bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2
34 // Optional 1.3 core features, enabled where supported; on a 1.2 device they stay off (no required subgroup size).
35 bool subgroup_size_control = false;
36 bool compute_full_subgroups = false;
37
38 bool usable() const { return dynamic_rendering && synchronization2; }
39
40 // Fills the flags above for one physical device. A device older than 1.2 never qualifies.
41 void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2,
42 PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) {
43 core = api_version >= VK_API_VERSION_1_3;
44 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
45 if (!features2) return;
46 if (core) {
47 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
48 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13};
49 features2(physical, &query);
50 dynamic_rendering = f13.dynamicRendering == VK_TRUE;
51 synchronization2 = f13.synchronization2 == VK_TRUE;
52 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
53 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
54 return;
55 }
56 if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return;
57 std::uint32_t count = 0;
58 enumerate_extensions(physical, nullptr, &count, nullptr);
59 std::vector<VkExtensionProperties> extensions(count);
60 enumerate_extensions(physical, nullptr, &count, extensions.data());
61 bool has_dynamic_rendering = false, has_synchronization2 = false;
62 for (const auto& e : extensions) {
63 has_dynamic_rendering |= std::strcmp(e.extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0;
64 has_synchronization2 |= std::strcmp(e.extensionName, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0;
65 }
66 if (!has_dynamic_rendering || !has_synchronization2) return;
67 VkPhysicalDeviceSynchronization2FeaturesKHR sync2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR};
68 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering{
69 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, &sync2};
70 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &rendering};
71 features2(physical, &query);
72 dynamic_rendering = rendering.dynamicRendering == VK_TRUE;
73 synchronization2 = sync2.synchronization2 == VK_TRUE;
74 }
75
76 // Copies the flags of the device query() chose (a later query() for another candidate overwrites them).
77 void choose(const Vulkan13Features& from) {
78 core = from.core;
79 dynamic_rendering = from.dynamic_rendering;
80 synchronization2 = from.synchronization2;
81 subgroup_size_control = from.subgroup_size_control;
82 compute_full_subgroups = from.compute_full_subgroups;
83 }
84
85 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features'
86 // pNext. Call once, after query() or choose().
87 void* enable(void* chain) {
88 if (core) {
89 enable13_.pNext = chain;
90 enable13_.dynamicRendering = VK_TRUE;
91 enable13_.synchronization2 = VK_TRUE;
92 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE;
93 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE;
94 return &enable13_;
95 }
96 sync2_.pNext = chain;
97 sync2_.synchronization2 = VK_TRUE;
98 rendering_.pNext = &sync2_;
99 rendering_.dynamicRendering = VK_TRUE;
100 return &rendering_;
101 }
102
103 // Where a feature struct goes to follow these: insert with `s.pNext = *next(); *next() = &s;`.
104 void** next() { return core ? &enable13_.pNext : &sync2_.pNext; }
105
106 // The device extensions a 1.2 device needs for both features; none on 1.3.
107 void add_extensions(std::vector<const char*>& extensions) const {
108 if (core) return;
109 extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME);
110 extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
111 }
112
113private:
114 VkPhysicalDeviceVulkan13Features enable13_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
115 VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR};
116 VkPhysicalDeviceSynchronization2FeaturesKHR sync2_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR};
117};
118
119// A device function by its core name, or by its KHR name where the core one is null: a Vulkan 1.2 device returns
120// null for Vulkan 1.3 core names (vkCmdPipelineBarrier2, vkCmdBeginRendering, ...) and serves the enabled
121// extension's vkCmdPipelineBarrier2KHR and the like, which have the same signatures.
122inline PFN_vkVoidFunction device_proc_or_khr(PFN_vkGetDeviceProcAddr get, VkDevice device, const char* name) {
123 if (const PFN_vkVoidFunction function = get(device, name)) return function;
124 return get(device, (std::string(name) + "KHR").c_str());
125}
126
127} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 73232109e..8683ae2de 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -3,7 +3,8 @@
3// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, 3// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker,
4// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in 4// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in
5// shims/d3d12_com.cpp are thin wrappers over these. Needs Vulkan 1.2 timeline semaphores; rectangle clears and 5// shims/d3d12_com.cpp are thin wrappers over these. Needs Vulkan 1.2 timeline semaphores; rectangle clears and
6// enhanced barriers need the Vulkan 1.3 functions (dynamicRendering, synchronization2) to be enabled. 6// enhanced barriers need the Vulkan 1.3 functions (dynamicRendering, synchronization2) to be enabled, as core
7// features or through their KHR extensions on a 1.2 device (vulkan13_features.h).
7 8
8#ifndef VK_NO_PROTOTYPES 9#ifndef VK_NO_PROTOTYPES
9#define VK_NO_PROTOTYPES 10#define VK_NO_PROTOTYPES
@@ -12,6 +13,7 @@
12#include "occlusion_sum_spirv.h" 13#include "occlusion_sum_spirv.h"
13#include "retire_tickets.h" 14#include "retire_tickets.h"
14#include "statistics_sum_spirv.h" 15#include "statistics_sum_spirv.h"
16#include "vulkan13_features.h"
15#include "vulkan_depth24.h" 17#include "vulkan_depth24.h"
16#include "vulkan_scratch.h" 18#include "vulkan_scratch.h"
17#include "vulkan_replay.h" 19#include "vulkan_replay.h"
@@ -27,6 +29,7 @@
27#include <map> 29#include <map>
28#include <memory> 30#include <memory>
29#include <mutex> 31#include <mutex>
32#include <unordered_set>
30#include <shared_mutex> 33#include <shared_mutex>
31#include <span> 34#include <span>
32#include <thread> 35#include <thread>
@@ -84,7 +87,7 @@ struct VulkanDeviceFunctions {
84 // extension is not enabled, and the query functions are optional (a list that uses queries without them is 87 // extension is not enabled, and the query functions are optional (a list that uses queries without them is
85 // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. 88 // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results.
86 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { 89 bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) {
87#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name)); 90#define LEONIDA_VK_LOAD(name) name = reinterpret_cast<PFN_##name>(leonida::device_proc_or_khr(get, device, #name));
88 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) 91 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD)
89#undef LEONIDA_VK_LOAD 92#undef LEONIDA_VK_LOAD
90 return vkCreateCommandPool && vkDestroyCommandPool && vkAllocateCommandBuffers && vkResetCommandBuffer && 93 return vkCreateCommandPool && vkDestroyCommandPool && vkAllocateCommandBuffers && vkResetCommandBuffer &&
@@ -732,15 +735,26 @@ public:
732 const std::uint64_t base = replay_.heap_base; 735 const std::uint64_t base = replay_.heap_base;
733 XdxrLayout layout; 736 XdxrLayout layout;
734 layout.compute(xdxr_elements(b), b.is_tlas); 737 layout.compute(xdxr_elements(b), b.is_tlas);
738 // PERFORM_UPDATE refits the source (the destination itself when no source is given, as D3D12
739 // allows for an in-place update); a full build otherwise.
740 const std::uint64_t from = b.update ? base + (b.src_va ? b.src_va : b.dst_va) : 0;
735 if (b.is_tlas) { 741 if (b.is_tlas) {
736 xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va, 742 xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va,
737 base + b.scratch_va, base); 743 base + b.scratch_va, base, from);
738 } else { 744 } else {
739 std::vector<XdxrTriangles> geometries; 745 std::vector<XdxrTriangles> geometries;
740 xdxr_inputs(b, &geometries, base); 746 xdxr_inputs(b, &geometries, base);
741 xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va); 747 xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va, from);
742 } 748 }
743 }; 749 };
750 replay_.xdxr_copy = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t bytes) {
751 const std::uint64_t base = replay_.heap_base;
752 xdxr_->record_copy(cb, base + src, base + dst, bytes);
753 };
754 replay_.xdxr_postbuild = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dest) {
755 const std::uint64_t base = replay_.heap_base;
756 xdxr_->record_postbuild(cb, base + src, base + dest);
757 };
744 } else { 758 } else {
745 xdxr_.reset(); 759 xdxr_.reset();
746 } 760 }
@@ -814,6 +828,15 @@ public:
814 } 828 }
815 } 829 }
816 830
831 // An image that got a storage (unordered-access) view. A shader can write it before any command names it, so the
832 // layer would not know it was used and the first barrier or copy that does would zero-fill it (vulkan_replay.h,
833 // initialize). The next submission therefore moves each such image to GENERAL, the layout its descriptor names,
834 // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is.
835 void note_storage_image(ResourceId id) {
836 std::lock_guard lock(storage_mutex_);
837 storage_pending_.insert(id);
838 }
839
817 void remove_resource(ResourceId id) { 840 void remove_resource(ResourceId id) {
818 VkImage img = VK_NULL_HANDLE; 841 VkImage img = VK_NULL_HANDLE;
819 { 842 {
@@ -1119,6 +1142,14 @@ private:
1119 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 1142 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
1120 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 1143 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
1121 LayoutTracker tracker_; 1144 LayoutTracker tracker_;
1145 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only
1146 std::unordered_set<ResourceId> storage_pending_;
1147 // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter
1148 // that says which one: every other queue's next submission waits for it, so no queue uses such an image before
1149 // the zero-fill that put it in GENERAL has run.
1150 VkSemaphore storage_init_semaphore_ = VK_NULL_HANDLE;
1151 std::uint64_t storage_init_value_ = 0;
1152 std::uint64_t storage_init_version_ = 0;
1122 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; 1153 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_;
1123 std::function<bool(VkCommandBuffer)> bindless_prepare_; 1154 std::function<bool(VkCommandBuffer)> bindless_prepare_;
1124 std::unique_ptr<Depth24Converter> depth24_; 1155 std::unique_ptr<Depth24Converter> depth24_;
@@ -1434,6 +1465,33 @@ public:
1434 return ReplayResult::unsupported; 1465 return ReplayResult::unsupported;
1435 } 1466 }
1436 auto next_tracker = context_.tracker_; 1467 auto next_tracker = context_.tracker_;
1468 // Images with a UAV view are moved to GENERAL (zeroed) by the first submission that can use a shader on them:
1469 // not a copy queue (its family may not clear images), and one whose lists dispatch or draw.
1470 bool runs_shaders = false;
1471 for (const CommandList* list : lists)
1472 for (const auto& command : list->commands())
1473 runs_shaders |= std::holds_alternative<Dispatch>(command) || std::holds_alternative<Draw>(command) ||
1474 std::holds_alternative<ExecuteIndirect>(command);
1475 std::vector<ResourceId> storage_images;
1476 {
1477 std::lock_guard lock(context_.storage_mutex_);
1478 if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ &&
1479 context_.storage_init_version_ != storage_init_seen_) {
1480 waits_.push_back(context_.storage_init_semaphore_);
1481 wait_values_.push_back(context_.storage_init_value_);
1482 storage_init_seen_ = context_.storage_init_version_;
1483 }
1484 if (kind_ != QueueKind::copy && runs_shaders)
1485 storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end());
1486 if (!storage_images.empty()) context_.storage_pending_.clear();
1487 }
1488 for (const ResourceId id : storage_images) {
1489 const ResourceBinding* image = context_.resolve(id);
1490 if (!image || !image->image) continue;
1491 const VkImageSubresourceRange range{image->aspects, 0, image->mip_levels, 0, image->array_layers};
1492 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED);
1493 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker);
1494 }
1437 bool wrote_readback = false; 1495 bool wrote_readback = false;
1438 VkPipelineStageFlags2 readback_stages = 0; 1496 VkPipelineStageFlags2 readback_stages = 0;
1439 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 1497 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
@@ -1476,6 +1534,17 @@ public:
1476 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1534 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1477 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 1535 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
1478 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1536 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
1537 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission
1538 std::lock_guard lock(context_.storage_mutex_);
1539 context_.storage_pending_.insert(storage_images.begin(), storage_images.end());
1540 }
1541 if (submitted && !storage_images.empty()) {
1542 std::lock_guard lock(context_.storage_mutex_);
1543 context_.storage_init_semaphore_ = progress_;
1544 context_.storage_init_value_ = submitted_;
1545 ++context_.storage_init_version_;
1546 storage_init_seen_ = context_.storage_init_version_;
1547 }
1479 if (submitted) { 1548 if (submitted) {
1480 context_.tracker_ = std::move(next_tracker); 1549 context_.tracker_ = std::move(next_tracker);
1481 slot->predicate = std::move(batch); 1550 slot->predicate = std::move(batch);
@@ -1627,6 +1696,7 @@ private:
1627 std::uint64_t submitted_ = 0; 1696 std::uint64_t submitted_ = 0;
1628 std::vector<CommandSlot> buffers_; 1697 std::vector<CommandSlot> buffers_;
1629 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 1698 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
1699 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
1630 std::vector<VkSemaphore> waits_; 1700 std::vector<VkSemaphore> waits_;
1631 std::vector<std::uint64_t> wait_values_; 1701 std::vector<std::uint64_t> wait_values_;
1632 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 1702 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index c599eb7c2..5f484bf16 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -47,6 +47,7 @@
47#include <array> 47#include <array>
48#include <cstdint> 48#include <cstdint>
49#include <cstring> 49#include <cstring>
50#include <functional>
50#include <unordered_map> 51#include <unordered_map>
51#include <vector> 52#include <vector>
52 53
@@ -162,6 +163,35 @@ constexpr std::uint32_t r32ui_binding(ImageDimension dimension) {
162 return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; 163 return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding;
163} 164}
164 165
166// Set 0's descriptor set layout at features' counts: what create_layout creates and what size_bindings'
167// layout_supported asks vkGetDescriptorSetLayoutSupport about. It points into itself, so it is not copied.
168struct SetLayout {
169 std::array<VkDescriptorSetLayoutBinding, binding_count> entries{};
170 std::array<VkDescriptorBindingFlags, binding_count> flags{};
171 VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{
172 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO};
173 VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
174
175 explicit SetLayout(const BindlessFeatures& features) {
176 std::uint32_t count = 0;
177 for (std::uint32_t b = 0; b < binding_count; ++b) {
178 if (!binding_enabled(b, features)) continue;
179 entries[count] = {b, bindings[b].type, features.counts[b], VK_SHADER_STAGE_ALL, nullptr};
180 flags[count] = (features.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) |
181 (features.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0);
182 ++count;
183 }
184 flags_info.bindingCount = count;
185 flags_info.pBindingFlags = flags.data();
186 info.pNext = &flags_info;
187 info.flags = features.update_after_bind ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0;
188 info.bindingCount = count;
189 info.pBindings = entries.data();
190 }
191 SetLayout(const SetLayout&) = delete;
192 SetLayout& operator=(const SetLayout&) = delete;
193};
194
165// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then 195// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then
166// 3-6 MiB (93793 descriptors on an RTX 5070). 196// 3-6 MiB (93793 descriptors on an RTX 5070).
167inline constexpr std::uint32_t max_2d_images = 65536; 197inline constexpr std::uint32_t max_2d_images = 65536;
@@ -183,10 +213,14 @@ inline constexpr std::uint32_t growth_headroom = 64;
183// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. 213// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1.
184// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a 214// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a
185// storage view an index past the sampled array. The other bindings keep their default counts. 215// storage view an index past the sampled array. The other bindings keep their default counts.
216// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument:
217// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports
218// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors.
186// Sets features.counts; returns false when a count is below its default because the device's limits are. 219// Sets features.counts; returns false when a count is below its default because the device's limits are.
187inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, 220inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits,
188 const VkPhysicalDeviceVulkan11Properties& v11, 221 const VkPhysicalDeviceVulkan11Properties& v11,
189 const VkPhysicalDeviceVulkan12Properties& v12) { 222 const VkPhysicalDeviceVulkan12Properties& v12,
223 const std::function<bool(const BindlessFeatures&)>& layout_supported = {}) {
190 const bool uab = features.update_after_bind; 224 const bool uab = features.update_after_bind;
191 const std::uint32_t sampled_limit = 225 const std::uint32_t sampled_limit =
192 uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, 226 uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages,
@@ -233,7 +267,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi
233 const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; }; 267 const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; };
234 const std::uint64_t all = sampled + sampler + stored + buffers; 268 const std::uint64_t all = sampled + sampler + stored + buffers;
235 return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) && 269 return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) &&
236 within(sampled + stored + buffers, resource_limit) && all <= pool_limit && all <= set_limit; 270 within(sampled + stored + buffers, resource_limit) && all <= pool_limit &&
271 (all <= set_limit || (layout_supported && layout_supported(features)));
237 }; 272 };
238 // Raises n to the largest value up to `high` that fits; leaves it where it is when none does. 273 // Raises n to the largest value up to `high` that fits; leaves it where it is when none does.
239 const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) { 274 const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) {
@@ -400,19 +435,21 @@ public:
400 result == DescriptorTable::InsertResult::added_with_relocation; 435 result == DescriptorTable::InsertResult::added_with_relocation;
401 return true; 436 return true;
402 } 437 }
403 // Erasing compacts the key's probe cluster, so other keys' entries may change slots. 438 // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle.
439 // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires.
404 bool erase_key(const DescriptorKey& key) { 440 bool erase_key(const DescriptorKey& key) {
405 if (!table_.erase(key)) return false; 441 if (!table_.erase(key)) return false;
406 table_dirty_ = existing_entries_changed_ = true; 442 table_dirty_ = true;
407 return true; 443 return true;
408 } 444 }
409 const DescriptorTable& table() const { return table_; } 445 const DescriptorTable& table() const { return table_; }
410 446
411 // True when the next flush() will change entries a running shader may be probing, or replace the table's 447 // True when the next flush() will change entries a running shader may be probing (a live key's index replaced
412 // buffer: the caller then flushes only once no command buffer that uses the set is still executing. Without 448 // or a live key moved by a relocating insert), or replace the table's buffer: the caller then flushes only once
413 // it the flush only adds entries, and the copy of an entry is not atomic: a shader probing a different key 449 // no command buffer that uses the set is still executing. Without it the flush only adds entries or empties the
414 // could in principle see a torn entry that matches it, which is accepted as vanishingly unlikely because the 450 // slots of erased keys, and the copy of an entry is not atomic: a shader probing a different key could in
415 // added key is new (there is no live key equal to it). 451 // principle see a torn entry that matches it, which is accepted as vanishingly unlikely because the added or
452 // erased key is not live (no running work uses it).
416 bool flush_needs_idle() const { 453 bool flush_needs_idle() const {
417 return table_dirty_ && (existing_entries_changed_ || force_full_upload_ || 454 return table_dirty_ && (existing_entries_changed_ || force_full_upload_ ||
418 table_.size_bytes() > table_buffers_.table.size); 455 table_.size_bytes() > table_buffers_.table.size);
@@ -532,27 +569,12 @@ private:
532 } 569 }
533 570
534 bool create_layout() { 571 bool create_layout() {
535 std::array<VkDescriptorSetLayoutBinding, bindless::bindings.size()> entries{}; 572 const bindless::SetLayout layout(features_);
536 std::array<VkDescriptorBindingFlags, bindless::bindings.size()> flags{}; 573 const std::uint32_t count = layout.info.bindingCount;
537 std::array<VkDescriptorPoolSize, bindless::bindings.size()> sizes{}; 574 std::array<VkDescriptorPoolSize, bindless::bindings.size()> sizes{};
538 std::uint32_t count = 0; 575 for (std::uint32_t i = 0; i < count; ++i)
539 for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { 576 sizes[i] = {layout.entries[i].descriptorType, layout.entries[i].descriptorCount};
540 if (!bindless::binding_enabled(b, features_)) continue; 577 if (vk_.vkCreateDescriptorSetLayout(device_, &layout.info, nullptr, &layout_) != VK_SUCCESS) return false;
541 entries[count] = {b, bindless::bindings[b].type, features_.counts[b], VK_SHADER_STAGE_ALL, nullptr};
542 flags[count] = (features_.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) |
543 (features_.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0);
544 sizes[count] = {bindless::bindings[b].type, features_.counts[b]};
545 ++count;
546 }
547 VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{
548 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO};
549 flags_info.bindingCount = count;
550 flags_info.pBindingFlags = flags.data();
551 VkDescriptorSetLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, &flags_info};
552 layout_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0;
553 layout_info.bindingCount = count;
554 layout_info.pBindings = entries.data();
555 if (vk_.vkCreateDescriptorSetLayout(device_, &layout_info, nullptr, &layout_) != VK_SUCCESS) return false;
556 578
557 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; 579 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
558 pool_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0; 580 pool_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0;
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 35f1cb556..d9f53baa5 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -35,7 +35,6 @@
35#include <cstring> 35#include <cstring>
36#include <functional> 36#include <functional>
37#include <map> 37#include <map>
38#include <optional>
39#include <vector> 38#include <vector>
40 39
41namespace leonida { 40namespace leonida {
@@ -271,25 +270,34 @@ public:
271 270
272 bool recorded = false; 271 bool recorded = false;
273 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
274 std::optional<LayoutTracker> next_tracker; 273 bool rollback_source = false;
274 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
275 if (binding) { 275 if (binding) {
276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
277 // Release resource_mutex_ before vkQueueSubmit while keeping tracker_mutex_ held so layout updates 277 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
278 // commit in submission order and roll back if vkQueueSubmit fails. 278 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
279 std::shared_lock resource_lock(context_.resource_mutex_); 279 std::shared_lock resource_lock(context_.resource_mutex_);
280 const ResourceBinding* current = context_.resolve(source); 280 const ResourceBinding* current = context_.resolve(source);
281 if (current && current->image && current->aspects == VK_IMAGE_ASPECT_COLOR_BIT) { 281 if (current && current->image && current->aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
282 tracker_lock.lock(); 282 tracker_lock.lock();
283 next_tracker.emplace(context_.tracker_); 283 rollback_source = context_.tracker_.tracked(source);
284 record(frame.commands, *current, source, image, source_rect, *next_tracker); 284 if (rollback_source) prev_layout = context_.tracker_.layout(source, 0);
285 record(frame.commands, *current, source, image, source_rect);
285 recorded = true; 286 recorded = true;
286 } 287 }
287 } else { 288 } else {
288 record_blank(frame.commands, image); 289 record_blank(frame.commands, image);
289 recorded = true; 290 recorded = true;
290 } 291 }
292 const auto rollback = [&] {
293 if (rollback_source)
294 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
295 };
291 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 296 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
292 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) return stop(reset); 297 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
298 rollback();
299 return stop(reset);
300 }
293 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; 301 const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
294 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 302 VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO};
295 submit_info.waitSemaphoreCount = 1; 303 submit_info.waitSemaphoreCount = 1;
@@ -322,10 +330,12 @@ public:
322 { 330 {
323 std::lock_guard lock(context_.submit_mutex()); 331 std::lock_guard lock(context_.submit_mutex());
324 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); 332 submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done);
333 if (submitted != VK_SUCCESS) rollback();
334 // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission
335 // order without holding tracker_mutex_ across vkQueuePresentKHR.
336 if (tracker_lock.owns_lock()) tracker_lock.unlock();
325 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); 337 if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present);
326 } 338 }
327 if (submitted == VK_SUCCESS && next_tracker) context_.tracker_ = std::move(*next_tracker);
328 if (tracker_lock.owns_lock()) tracker_lock.unlock();
329 if (submitted != VK_SUCCESS) return give_back(frame, submitted); 339 if (submitted != VK_SUCCESS) return give_back(frame, submitted);
330 ++frame_index_; 340 ++frame_index_;
331 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain 341 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain
@@ -401,7 +411,7 @@ private:
401 } 411 }
402 412
403 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, 413 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image,
404 const PresentRect* source_rect, LayoutTracker& tracker) { 414 const PresentRect* source_rect) {
405 auto& vk = context_.vk; 415 auto& vk = context_.vk;
406 const ReplayFunctions& fn = context_.replay_; 416 const ReplayFunctions& fn = context_.replay_;
407 vk.vkResetCommandBuffer(commands, 0); 417 vk.vkResetCommandBuffer(commands, 0);
@@ -414,8 +424,8 @@ private:
414 // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is 424 // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is
415 // zero-filled first, as any committed resource is. 425 // zero-filled first, as any committed resource is.
416 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); 426 const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL);
417 auto pieces = detail::current(&tracker, source, range, common); 427 auto pieces = detail::current(&context_.tracker_, source, range, common);
418 detail::initialize(fn, commands, binding, source, pieces, common, &tracker); 428 detail::initialize(fn, commands, binding, source, pieces, common, &context_.tracker_);
419 for (const auto& piece : pieces) 429 for (const auto& piece : pieces)
420 detail::image_barrier(fn, commands, binding, piece.range, piece.layout, 430 detail::image_barrier(fn, commands, binding, piece.range, piece.layout,
421 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, 431 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT,
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 887c95b72..2a37f58f5 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -788,6 +788,10 @@ struct ReplayFunctions {
788 // cannot read while the list is prepared, `xdxr_record` records the build. 788 // cannot read while the list is prepared, `xdxr_record` records the build.
789 std::function<bool(const BuildAccelerationStructure&)> xdxr_check; 789 std::function<bool(const BuildAccelerationStructure&)> xdxr_check;
790 std::function<void(VkCommandBuffer, const BuildAccelerationStructure&)> xdxr_record; 790 std::function<void(VkCommandBuffer, const BuildAccelerationStructure&)> xdxr_record;
791 // CopyRaytracingAccelerationStructure (CLONE, COMPACT) of XDXR structures: `bytes` is the room the destination
792 // resource has; and one postbuild value (COMPACTED_SIZE, CURRENT_SIZE) of the structure at `src` to `dest`.
793 std::function<void(VkCommandBuffer, std::uint64_t src_va, std::uint64_t dst_va, std::uint64_t bytes)> xdxr_copy;
794 std::function<void(VkCommandBuffer, std::uint64_t src_va, std::uint64_t dest_va)> xdxr_postbuild;
791 std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure; 795 std::function<VkAccelerationStructureKHR(std::uint64_t)> resolve_acceleration_structure;
792 // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. 796 // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command.
793 std::function<bool(VkBuffer, VkDeviceSize, PredicateCapture&)> prepare_predicate; 797 std::function<bool(VkBuffer, VkDeviceSize, PredicateCapture&)> prepare_predicate;
@@ -903,6 +907,7 @@ struct Prepared {
903 VkExtent2D area{}; 907 VkExtent2D area{};
904 std::uint32_t layers = 1; // the fewest layers any bound attachment view has 908 std::uint32_t layers = 1; // the fewest layers any bound attachment view has
905 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; 909 VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE;
910 std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write
906 VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; 911 VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE;
907}; 912};
908 913
@@ -972,7 +977,7 @@ inline VkFormat color_view_format(const ResourceBinding& resource, const TargetV
972 } 977 }
973 if (!resource.rgba8_typeless && !resource.castable_view_formats) 978 if (!resource.rgba8_typeless && !resource.castable_view_formats)
974 return format == resource.format ? format : VK_FORMAT_UNDEFINED; 979 return format == resource.format ? format : VK_FORMAT_UNDEFINED;
975 if (resource.format != VK_FORMAT_R8G8B8A8_UNORM || resource.volume || resource.depth != 1 || resource.samples != 1) 980 if (resource.format != VK_FORMAT_R8G8B8A8_UNORM || resource.volume || resource.depth != 1)
976 return VK_FORMAT_UNDEFINED; 981 return VK_FORMAT_UNDEFINED;
977 return format; 982 return format;
978} 983}
@@ -1058,20 +1063,180 @@ inline std::vector<LayoutPiece> current(const LayoutTracker* tracker, ResourceId
1058 return out; 1063 return out;
1059} 1064}
1060 1065
1066// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page
1067// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids
1068// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set
1069// (D3D-220).
1070inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer,
1071 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1072 VkImageLayout dst_layout) {
1073 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1074 if (fmt.block <= 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1075 const std::uint32_t mip_begin = range.baseMipLevel;
1076 const std::uint32_t mip_end =
1077 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels
1078 : std::min(resource.mip_levels, mip_begin + range.levelCount);
1079 const std::uint32_t layer_begin = range.baseArrayLayer;
1080 const std::uint32_t layer_end =
1081 range.layerCount == VK_REMAINING_ARRAY_LAYERS ? resource.array_layers
1082 : std::min(resource.array_layers, layer_begin + range.layerCount);
1083 if (mip_begin >= mip_end || layer_begin >= layer_end) return true;
1084
1085 constexpr VkDeviceSize kMaxChunk = 64u * 1024u;
1086 const std::uint32_t layer_count = layer_end - layer_begin;
1087 VkDeviceSize needed = 0;
1088 for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) {
1089 const VkExtent2D ext = mip_extent(resource, mip);
1090 const std::uint64_t bx = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block;
1091 const std::uint64_t by = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block;
1092 const std::uint64_t mip_d = std::max(1u, resource.depth >> mip);
1093 const std::uint64_t slice_bytes = bx * by * fmt.bytes;
1094 if (slice_bytes >= kMaxChunk || mip_d > kMaxChunk / slice_bytes ||
1095 layer_count > kMaxChunk / (slice_bytes * mip_d)) {
1096 needed = kMaxChunk;
1097 break;
1098 }
1099 needed = std::max<VkDeviceSize>(needed, slice_bytes * mip_d * layer_count);
1100 }
1101 if (!needed) return true;
1102
1103 VkBuffer zero_buf = VK_NULL_HANDLE;
1104 VkDeviceSize zero_off = 0;
1105 VkDeviceSize zero_cap = 0;
1106 if (vk.zero_buffer && vk.zero_size >= fmt.bytes) {
1107 const VkDeviceSize align = fmt.bytes;
1108 const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align;
1109 if (vk.zero_size >= pad + fmt.bytes) {
1110 zero_buf = vk.zero_buffer;
1111 zero_off = vk.zero_offset + pad;
1112 zero_cap = vk.zero_size - pad;
1113 }
1114 }
1115 if (!zero_buf && vk.copy_scratch && vk.fill_buffer) {
1116 // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer).
1117 const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes;
1118 VkBuffer scratch = VK_NULL_HANDLE;
1119 VkDeviceSize offset = 0;
1120 if (vk.copy_scratch(fill_bytes, scratch, offset)) {
1121 const VkDeviceSize align = fmt.bytes;
1122 const VkDeviceSize pad = (align - (offset % align)) % align;
1123 if (fill_bytes >= pad + fmt.bytes) {
1124 vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0);
1125 memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1126 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1127 zero_buf = scratch;
1128 zero_off = offset + pad;
1129 zero_cap = fill_bytes - pad;
1130 }
1131 }
1132 }
1133 if (!zero_buf || zero_cap < fmt.bytes) return false;
1134
1135 std::vector<VkBufferImageCopy> regions;
1136 for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) {
1137 const VkExtent2D ext = mip_extent(resource, mip);
1138 const std::uint32_t mip_d = std::max(1u, resource.depth >> mip);
1139 const std::uint64_t bx_total = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block;
1140 const std::uint64_t by_total = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block;
1141 const std::uint64_t slice_bytes = bx_total * by_total * fmt.bytes;
1142 if (slice_bytes && slice_bytes <= zero_cap && mip_d <= zero_cap / slice_bytes &&
1143 layer_count <= zero_cap / (slice_bytes * mip_d)) {
1144 VkBufferImageCopy r{};
1145 r.bufferOffset = zero_off;
1146 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count};
1147 r.imageExtent = {ext.width, ext.height, mip_d};
1148 regions.push_back(r);
1149 continue;
1150 }
1151 const std::uint64_t row_bytes = bx_total * fmt.bytes;
1152 for (std::uint32_t layer = layer_begin; layer < layer_end; ++layer) {
1153 if (slice_bytes <= zero_cap) {
1154 const std::uint32_t slices_per_copy =
1155 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(mip_d, zero_cap / slice_bytes)));
1156 for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) {
1157 VkBufferImageCopy r{};
1158 r.bufferOffset = zero_off;
1159 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1160 r.imageOffset = {0, 0, std::int32_t(z)};
1161 r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)};
1162 regions.push_back(r);
1163 }
1164 } else if (row_bytes <= zero_cap) {
1165 const std::uint32_t rows_per_copy =
1166 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(by_total, zero_cap / row_bytes)));
1167 for (std::uint32_t z = 0; z < mip_d; ++z) {
1168 for (std::uint64_t y_blk = 0; y_blk < by_total; y_blk += rows_per_copy) {
1169 const std::uint32_t oy = std::uint32_t(y_blk * fmt.block);
1170 const std::uint32_t eh = std::min<std::uint32_t>(rows_per_copy * fmt.block, ext.height - oy);
1171 VkBufferImageCopy r{};
1172 r.bufferOffset = zero_off;
1173 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1174 r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)};
1175 r.imageExtent = {ext.width, eh, 1};
1176 regions.push_back(r);
1177 }
1178 }
1179 } else {
1180 const std::uint32_t cols_per_copy =
1181 std::max<std::uint32_t>(1u, std::uint32_t(std::min<std::uint64_t>(bx_total, zero_cap / fmt.bytes)));
1182 for (std::uint32_t z = 0; z < mip_d; ++z) {
1183 for (std::uint64_t y_blk = 0; y_blk < by_total; ++y_blk) {
1184 const std::uint32_t oy = std::uint32_t(y_blk * fmt.block);
1185 const std::uint32_t eh = std::min<std::uint32_t>(fmt.block, ext.height - oy);
1186 for (std::uint64_t x_blk = 0; x_blk < bx_total; x_blk += cols_per_copy) {
1187 const std::uint32_t ox = std::uint32_t(x_blk * fmt.block);
1188 const std::uint32_t ew =
1189 std::min<std::uint32_t>(cols_per_copy * fmt.block, ext.width - ox);
1190 VkBufferImageCopy r{};
1191 r.bufferOffset = zero_off;
1192 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1};
1193 r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)};
1194 r.imageExtent = {ew, eh, 1};
1195 regions.push_back(r);
1196 }
1197 }
1198 }
1199 }
1200 }
1201 }
1202 if (!regions.empty())
1203 vk.copy_buffer_to_image(command_buffer, zero_buf, resource.image, dst_layout,
1204 std::uint32_t(regions.size()), regions.data());
1205 return true;
1206}
1207
1061// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed, 1208// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed,
1062// so each such piece is cleared to zero (colour 0, depth 0, stencil 0) and moved to `layout`, the layout the 1209// so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats
1063// operation about to run expects, before that operation; with not_zeroed, or a block-compressed format (which 1210// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run
1064// Vulkan cannot clear), it is only moved. The tracker records it. 1211// expects; with not_zeroed, it is only moved. The tracker records it.
1065inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, 1212inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource,
1066 ResourceId id, std::vector<LayoutPiece>& pieces, VkImageLayout layout, LayoutTracker* tracker) { 1213 ResourceId id, std::vector<LayoutPiece>& pieces, VkImageLayout layout, LayoutTracker* tracker) {
1067 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; 1214 constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
1068 for (auto& piece : pieces) { 1215 for (auto& piece : pieces) {
1069 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1216 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1070 // Vulkan cannot clear block-compressed images; those start undefined (applications upload them first). 1217 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1071 const bool compressed = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT).block > 1; 1218 const bool compressed = fmt.block > 1;
1072 if (resource.not_zeroed || compressed) { 1219 if (resource.not_zeroed) {
1073 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1220 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1074 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1221 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1222 } else if (compressed) {
1223 const bool can_zero =
1224 vk.copy_buffer_to_image &&
1225 ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer));
1226 if (can_zero) {
1227 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1228 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
1229 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
1230 VK_PIPELINE_STAGE_TRANSFER_BIT);
1231 const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst);
1232 image_barrier(vk, command_buffer, resource, piece.range, dst, layout,
1233 zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0,
1234 zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory,
1235 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1236 } else {
1237 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1238 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1239 }
1075 } else { 1240 } else {
1076 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); 1241 const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1077 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, 1242 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0,
@@ -2232,6 +2397,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2232 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) 2397 (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect))
2233 return ReplayResult::unsupported; 2398 return ReplayResult::unsupported;
2234 } 2399 }
2400 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded
2401 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported;
2402 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline);
2403 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource;
2404 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
2405 p.pipeline = *pipeline;
2406 }
2235 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 2407 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
2236 if (vk.xdxr_check) { 2408 if (vk.xdxr_check) {
2237 if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; 2409 if (!vk.xdxr_check(*build)) return ReplayResult::unsupported;
@@ -2245,6 +2417,29 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2245 if (!p.accel_src) return ReplayResult::unresolved_resource; 2417 if (!p.accel_src) return ReplayResult::unresolved_resource;
2246 } 2418 }
2247 } 2419 }
2420 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) {
2421 // XDXR only (a KHR copy needs VkAccelerationStructureKHR handles and vkCmdCopyAccelerationStructureKHR);
2422 // the destination's room bounds the copy, as the size is only known to the GPU.
2423 if (!vk.xdxr_copy || !vk.buffer_at || copy->mode > 1) return ReplayResult::unsupported;
2424 std::uint64_t room = ~std::uint64_t(0);
2425 VkBuffer buffer = VK_NULL_HANDLE;
2426 VkDeviceSize offset = 0;
2427 if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource;
2428 std::uint64_t source = ~std::uint64_t(0);
2429 if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource;
2430 p.xdxr_bytes = std::min(room, source);
2431 } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command)) {
2432 // The KHR path never wrote postbuild values; it keeps skipping them rather than failing the list.
2433 if (!vk.xdxr_postbuild) {
2434 p.skip = true;
2435 } else {
2436 if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return ReplayResult::unsupported;
2437 std::uint64_t room = 8 * info->sources.size();
2438 VkBuffer buffer = VK_NULL_HANDLE;
2439 VkDeviceSize offset = 0;
2440 if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource;
2441 if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy;
2442 }
2248 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) { 2443 } else if (const auto* dispatch = std::get_if<Dispatch>(&command)) {
2249 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) 2444 if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline)
2250 return ReplayResult::unsupported; 2445 return ReplayResult::unsupported;
@@ -2953,14 +3148,32 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2953 } else if (ind->kind == IndirectKind::draw_indexed) { 3148 } else if (ind->kind == IndirectKind::draw_indexed) {
2954 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); 3149 vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride);
2955 } else if (ind->kind == IndirectKind::dispatch) { 3150 } else if (ind->kind == IndirectKind::dispatch) {
3151 if (ind->pipeline) {
3152 ShaderUserData data{};
3153 std::copy(ind->user_data.begin(), ind->user_data.end(), data.s);
3154 data.heap_base = vk.heap_base;
3155 data.code_base = p.pipeline.code_base;
3156 vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline);
3157 if (p.pipeline.bindless_set)
3158 vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0,
3159 1, &p.pipeline.bindless_set, 0, nullptr);
3160 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data),
3161 &data);
3162 }
2956 for (std::uint32_t k = 0; k < ind->max_count; ++k) { 3163 for (std::uint32_t k = 0; k < ind->max_count; ++k) {
2957 vk.dispatch_indirect(command_buffer, p.binding.buffer, 3164 vk.dispatch_indirect(command_buffer, p.binding.buffer,
2958 arguments + VkDeviceSize(k) * ind->stride); 3165 arguments + VkDeviceSize(k) * ind->stride);
2959 } 3166 }
2960 } 3167 }
2961 } 3168 }
2962 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command); build && vk.xdxr_record) { 3169 } else if (const auto* xdxr_build = std::get_if<BuildAccelerationStructure>(&command);
2963 vk.xdxr_record(command_buffer, *build); 3170 xdxr_build && vk.xdxr_record) {
3171 vk.xdxr_record(command_buffer, *xdxr_build);
3172 } else if (const auto* copy = std::get_if<CopyAccelerationStructure>(&command)) {
3173 vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes);
3174 } else if (const auto* info = std::get_if<AccelerationStructurePostbuild>(&command); info && !p.skip) {
3175 for (std::size_t i = 0; i < info->sources.size(); ++i)
3176 vk.xdxr_postbuild(command_buffer, info->sources[i], info->dest_va + 8 * i);
2964 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 3177 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
2965 // The build's addresses are console VAs into the GPU address arena (heap_base is its device address). 3178 // The build's addresses are console VAs into the GPU address arena (heap_base is its device address).
2966 // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. 3179 // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page.
diff --git a/runtime/src/xdxr_build.comp b/runtime/src/xdxr_build.comp
index 7b5b9d034..908006897 100644
--- a/runtime/src/xdxr_build.comp
+++ b/runtime/src/xdxr_build.comp
@@ -13,8 +13,22 @@
13// MODE_RADIX_* a stable LSD radix sort of the keys with their element indices: 8 passes of 4-bit digits, each 13// MODE_RADIX_* a stable LSD radix sort of the keys with their element indices: 8 passes of 4-bit digits, each
14// a count per tile of RADIX_TILE elements, one exclusive scan, and a scatter (24 dispatches in all, 14// a count per tile of RADIX_TILE elements, one exclusive scan, and a scatter (24 dispatches in all,
15// whatever the count; shared memory only, no subgroup operations) 15// whatever the count; shared memory only, no subgroup operations)
16// MODE_SMALL_SORT up to SMALL_SORT_MAX keys: one workgroup sorts them in shared memory (bitonic, ties by element
17// index, so the order is the stable one), in one dispatch instead of the radix sort's 24, whose
18// fixed latency dominated small builds
16// MODE_LEVEL one thread per BOX32 node of one level: four consecutive entries of the level below 19// MODE_LEVEL one thread per BOX32 node of one level: four consecutive entries of the level below
17// MODE_HEADER one thread: the 64-byte header 20// MODE_HEADER one thread: the 64-byte header
21// An update (D3D12 PERFORM_UPDATE: same topology, new positions or transforms) refits instead: MODE_COPY copies the
22// source structure to the destination when they differ, MODE_TRIANGLES / MODE_INSTANCES rewrite the elements at their
23// slots, MODE_LEVEL with arg2 = 1 recomputes each node's boxes from the children it already points to (the tree's
24// grouping is kept, so there is no Morton pass and no sort), and MODE_HEADER rewrites the bounds.
25// MODE_COPY one thread per word: count words from src0 to dst
26// MODE_COPY_AS CopyRaytracingAccelerationStructure CLONE / COMPACT: the source structure's size comes from its
27// header (totalSizeIn64BNodes), so the copy can follow a build in the same list; at most count
28// words. The records are position-independent (node pointers count from the structure's start, and
29// a TLAS names its BLASes by address), so the bytes are the copy.
30// MODE_POSTBUILD one thread: the 8-byte COMPACTED_SIZE or CURRENT_SIZE of the structure at src0, at dst. A build
31// is already exactly its layout's size, so both are totalSizeIn64BNodes * 64.
18// The tree groups four consecutive children per node in Morton order, level by level, so its shape depends only on 32// The tree groups four consecutive children per node in Morton order, level by level, so its shape depends only on
19// the element count and the layout (xdxr_build.h XdxrLayout) is known when the command is recorded. 33// the element count and the layout (xdxr_build.h XdxrLayout) is known when the command is recorded.
20// 34//
@@ -31,9 +45,11 @@ layout(local_size_x = 64) in;
31layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; 45layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; };
32 46
33const uint MODE_INIT = 0u, MODE_TRIANGLES = 1u, MODE_INSTANCES = 2u, MODE_MORTON = 3u, MODE_LEVEL = 5u, 47const uint MODE_INIT = 0u, MODE_TRIANGLES = 1u, MODE_INSTANCES = 2u, MODE_MORTON = 3u, MODE_LEVEL = 5u,
34 MODE_HEADER = 6u, MODE_RADIX_COUNT = 7u, MODE_RADIX_SCAN = 8u, MODE_RADIX_SCATTER = 9u; 48 MODE_HEADER = 6u, MODE_RADIX_COUNT = 7u, MODE_RADIX_SCAN = 8u, MODE_RADIX_SCATTER = 9u,
49 MODE_SMALL_SORT = 10u, MODE_COPY = 11u, MODE_COPY_AS = 12u, MODE_POSTBUILD = 13u;
50const uint SMALL_SORT_MAX = 1024u; // xdxr_build.h XdxrLayout::small_sort_max
35const uint RADIX_BITS = 4u, RADIX_BINS = 16u, RADIX_PASSES = 8u; 51const uint RADIX_BITS = 4u, RADIX_BINS = 16u, RADIX_PASSES = 8u;
36const uint RADIX_TILE = 2048u; // elements per workgroup in count and scatter: 32 chunks of 64 52const uint RADIX_TILE = 256u; // elements per workgroup in count and scatter: 4 chunks of 64
37const uint INVALID = 0xffffffffu; 53const uint INVALID = 0xffffffffu;
38const uint TRI0 = 0u, BOX32 = 5u, INSTANCE = 6u; 54const uint TRI0 = 0u, BOX32 = 5u, INSTANCE = 6u;
39const uint REMAP_IDENTITY = 0x09u; 55const uint REMAP_IDENTITY = 0x09u;
@@ -53,7 +69,7 @@ layout(push_constant) uniform Push {
53 uint arg0; // triangles: vertex stride; level: entries in the level below 69 uint arg0; // triangles: vertex stride; level: entries in the level below
54 uint arg1; // triangles: 0 = R32G32B32_FLOAT, 1 = R32G32_FLOAT; level: first node of the level below, 70 uint arg1; // triangles: 0 = R32G32B32_FLOAT, 1 = R32G32_FLOAT; level: first node of the level below,
55 // or INVALID when the level below is the elements 71 // or INVALID when the level below is the elements
56 uint arg2; // triangles: index type (0 none, 1 u16, 2 u32); level: 1 for the root level 72 uint arg2; // triangles: index type (0 none, 1 u16, 2 u32); level: 1 = refit the existing node
57 uint geometry; // triangles: geometry index << 8 | D3D12_RAYTRACING_GEOMETRY_FLAGS 73 uint geometry; // triangles: geometry index << 8 | D3D12_RAYTRACING_GEOMETRY_FLAGS
58 uint elements; // element count N 74 uint elements; // element count N
59 uint sort_size; // N: the keys sorted (one per element) 75 uint sort_size; // N: the keys sorted (one per element)
@@ -254,6 +270,41 @@ void morton(uint i) {
254 store(pc.scratch, keys_off() + 4u * i, key); 270 store(pc.scratch, keys_off() + 4u * i, key);
255 store(pc.scratch, vals_off() + 4u * i, i); 271 store(pc.scratch, vals_off() + 4u * i, i);
256} 272}
273// ---- MODE_SMALL_SORT ----
274// 8 KiB, with the radix arrays below about 12.5 KiB: under the 16 KiB every Vulkan device must allow.
275shared uint small_keys[SMALL_SORT_MAX];
276shared uint small_vals[SMALL_SORT_MAX];
277
278void small_sort(uint t) {
279 uint n = pc.sort_size, p = 1u;
280 while (p < n) p <<= 1;
281 for (uint i = t; i < p; i += 64u) {
282 small_keys[i] = i < n ? load(pc.scratch, keys_off() + 4u * i) : INVALID;
283 small_vals[i] = i < n ? load(pc.scratch, vals_off() + 4u * i) : INVALID;
284 }
285 barrier();
286 for (uint k = 2u; k <= p; k <<= 1) {
287 for (uint j = k >> 1; j > 0u; j >>= 1) {
288 for (uint i = t; i < p; i += 64u) {
289 uint l = i ^ j;
290 if (l > i) {
291 uint ki = small_keys[i], kl = small_keys[l], vi = small_vals[i], vl = small_vals[l];
292 bool greater = ki > kl || (ki == kl && vi > vl);
293 if (greater == ((i & k) == 0u)) {
294 small_keys[i] = kl; small_keys[l] = ki;
295 small_vals[i] = vl; small_vals[l] = vi;
296 }
297 }
298 }
299 barrier();
300 }
301 }
302 for (uint i = t; i < n; i += 64u) {
303 store(pc.scratch, keys_off() + 4u * i, small_keys[i]);
304 store(pc.scratch, vals_off() + 4u * i, small_vals[i]);
305 }
306}
307
257// ---- MODE_RADIX_* ---- 308// ---- MODE_RADIX_* ----
258shared uint radix_hist[RADIX_BINS]; 309shared uint radix_hist[RADIX_BINS];
259shared uint radix_rank[RADIX_BINS][64]; 310shared uint radix_rank[RADIX_BINS][64];
@@ -341,7 +392,22 @@ void build_node(uint n) {
341 uint entry = 4u * n + c; 392 uint entry = 4u * n + c;
342 uint child = INVALID; 393 uint child = INVALID;
343 vec3 lo = vec3(uintBitsToFloat(0x7f800000u)), hi = -lo; // min > max: the box test misses it 394 vec3 lo = vec3(uintBitsToFloat(0x7f800000u)), hi = -lo; // min > max: the box test misses it
344 if (entry < pc.arg0) { 395 if (pc.arg2 == 1u) {
396 // refit: the child this node already has; its new box is in scratch (an element's from MODE_TRIANGLES /
397 // MODE_INSTANCES, a node's from the level below)
398 child = load(pc.dst, o + 4u * c);
399 if (child != INVALID) {
400 uint at = ptr_unit(child) * 64u;
401 if ((child & 7u) == BOX32) {
402 load_box(pc.elements + (at - pc.nodes_off) / 128u, lo, hi);
403 } else {
404 uint e = (at - pc.elements_off) / element_size();
405 load_box(e, lo, hi);
406 if (pc.tlas != 0u) store(pc.dst, pc.elements_off + 128u * e + 116u, me);
407 }
408 if (!box_empty(lo, hi)) { ulo = min(ulo, lo); uhi = max(uhi, hi); }
409 }
410 } else if (entry < pc.arg0) {
345 if (pc.arg1 == INVALID) { 411 if (pc.arg1 == INVALID) {
346 uint e = load(pc.scratch, vals_off() + 4u * entry); 412 uint e = load(pc.scratch, vals_off() + 4u * entry);
347 child = element_ptr(e); 413 child = element_ptr(e);
@@ -389,12 +455,23 @@ void main() {
389 if (pc.mode == MODE_RADIX_COUNT) { radix_count(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } 455 if (pc.mode == MODE_RADIX_COUNT) { radix_count(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; }
390 if (pc.mode == MODE_RADIX_SCAN) { radix_scan(gl_LocalInvocationID.x); return; } 456 if (pc.mode == MODE_RADIX_SCAN) { radix_scan(gl_LocalInvocationID.x); return; }
391 if (pc.mode == MODE_RADIX_SCATTER) { radix_scatter(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } 457 if (pc.mode == MODE_RADIX_SCATTER) { radix_scatter(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; }
458 if (pc.mode == MODE_SMALL_SORT) { small_sort(gl_LocalInvocationID.x); return; }
392 if (pc.mode == MODE_HEADER) { 459 if (pc.mode == MODE_HEADER) {
393 if (i == 0u) build_header(); 460 if (i == 0u) build_header();
394 return; 461 return;
395 } 462 }
396 if (i >= pc.count) return; 463 if (i >= pc.count) return;
397 if (pc.mode == MODE_INIT) { 464 if (pc.mode == MODE_POSTBUILD) {
465 if (i == 0u) { store(pc.dst, 0u, load(pc.src0, 4u) * 64u); store(pc.dst, 4u, 0u); }
466 return;
467 }
468 if (pc.mode == MODE_COPY_AS) {
469 if (4u * i < load(pc.src0, 4u) * 64u) store(pc.dst, 4u * i, load(pc.src0, 4u * i));
470 return;
471 }
472 if (pc.mode == MODE_COPY) {
473 store(pc.dst, 4u * i, load(pc.src0, 4u * i));
474 } else if (pc.mode == MODE_INIT) {
398 store(pc.dst, pc.parents_off + 4u * i, INVALID); 475 store(pc.dst, pc.parents_off + 4u * i, INVALID);
399 if (i < 3u) { store(pc.scratch, 4u * i, INVALID); store(pc.scratch, 12u + 4u * i, 0u); } 476 if (i < 3u) { store(pc.scratch, 4u * i, INVALID); store(pc.scratch, 12u + 4u * i, 0u); }
400 } else if (pc.mode == MODE_TRIANGLES) { 477 } else if (pc.mode == MODE_TRIANGLES) {
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h
index 32ee111cb..6930078a4 100644
--- a/runtime/src/xdxr_build.h
+++ b/runtime/src/xdxr_build.h
@@ -15,6 +15,7 @@
15// device addresses are wider (llvmpipe's are host pointers), the layer must present a narrower window and a bias. 15// device addresses are wider (llvmpipe's are host pointers), the layer must present a narrower window and a bias.
16#pragma once 16#pragma once
17 17
18#include <algorithm>
18#include <cstddef> 19#include <cstddef>
19#include <cstdint> 20#include <cstdint>
20#include <vector> 21#include <vector>
@@ -41,9 +42,10 @@ struct XdxrLayout {
41 std::uint32_t size = 0; // result data size in bytes, a multiple of 64 42 std::uint32_t size = 0; // result data size in bytes, a multiple of 64
42 std::uint32_t parent_entries = 0; // one per 64-byte unit from elements_off on 43 std::uint32_t parent_entries = 0; // one per 64-byte unit from elements_off on
43 std::uint32_t sort_size = 0; // keys the radix sort orders: one per element 44 std::uint32_t sort_size = 0; // keys the radix sort orders: one per element
44 static constexpr std::uint32_t radix_tile = 2048; // xdxr_build.comp RADIX_TILE 45 static constexpr std::uint32_t radix_tile = 256; // xdxr_build.comp RADIX_TILE
45 static constexpr std::uint32_t radix_bins = 16; 46 static constexpr std::uint32_t radix_bins = 16;
46 static constexpr std::uint32_t radix_passes = 8; 47 static constexpr std::uint32_t radix_passes = 8;
48 static constexpr std::uint32_t small_sort_max = 1024; // xdxr_build.comp SMALL_SORT_MAX: one-workgroup sort
47 std::uint64_t scratch = 0; // scratch bytes 49 std::uint64_t scratch = 0; // scratch bytes
48 50
49 // False when the count would overflow the 32-bit offsets of the format. 51 // False when the count would overflow the 32-bit offsets of the format.
@@ -108,11 +110,16 @@ public:
108 110
109 // Records a bottom-level build into `dst` (layout.size bytes) using `scratch` (layout.scratch bytes). `layout` 111 // Records a bottom-level build into `dst` (layout.size bytes) using `scratch` (layout.scratch bytes). `layout`
110 // must come from compute() with the sum of the geometries' triangle counts. 112 // must come from compute() with the sum of the geometries' triangle counts.
113 //
114 // With `update_from` set, an update (D3D12 PERFORM_UPDATE) instead: the structure at `update_from` (the
115 // destination itself, or another one, which is copied first) was built from the same topology, and is refitted
116 // to the new positions. Its tree is kept and only its boxes change, which is valid for any motion and costs no
117 // sort, though a refitted tree traverses more slowly as the geometry moves away from where it was built.
111 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, 118 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries,
112 std::uint64_t dst, std::uint64_t scratch) { 119 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0) {
113 if (!loaded_ || layout.tlas) return false; 120 if (!loaded_ || layout.tlas) return false;
114 Push p = base(layout, dst, scratch); 121 Push p = base(layout, dst, scratch);
115 begin(cb, layout, p); 122 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
116 std::uint32_t first = 0; 123 std::uint32_t first = 0;
117 for (std::size_t g = 0; g < geometries.size(); ++g) { 124 for (std::size_t g = 0; g < geometries.size(); ++g) {
118 const auto& geo = geometries[g]; 125 const auto& geo = geometries[g];
@@ -132,17 +139,18 @@ public:
132 first += geo.triangle_count; 139 first += geo.triangle_count;
133 } 140 }
134 if (first != layout.elements) return false; 141 if (first != layout.elements) return false;
135 finish(cb, layout, p); 142 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
136 return true; 143 return true;
137 } 144 }
138 145
139 // Records a top-level build from `count` D3D12_RAYTRACING_INSTANCE_DESCs at `instances`. 146 // Records a top-level build from `count` D3D12_RAYTRACING_INSTANCE_DESCs at `instances`.
147 // `update_from`: as for record_blas; the instances may move, and name other BLASes.
140 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, 148 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst,
141 std::uint64_t scratch, std::uint64_t bias = 0) { 149 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) {
142 if (!loaded_ || !layout.tlas) return false; 150 if (!loaded_ || !layout.tlas) return false;
143 Push p = base(layout, dst, scratch); 151 Push p = base(layout, dst, scratch);
144 p.bias = split(bias); 152 p.bias = split(bias);
145 begin(cb, layout, p); 153 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
146 if (layout.elements) { 154 if (layout.elements) {
147 Push t = p; 155 Push t = p;
148 t.mode = mode_instances; 156 t.mode = mode_instances;
@@ -150,14 +158,48 @@ public:
150 t.src0 = split(instances); 158 t.src0 = split(instances);
151 dispatch(cb, t, t.count); 159 dispatch(cb, t, t.count);
152 } 160 }
153 finish(cb, layout, p); 161 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
162 return true;
163 }
164
165 // CopyRaytracingAccelerationStructure CLONE or COMPACT: the structure at `src` to `dst`, as many bytes as its
166 // header says, at most `max_bytes` (the room the destination has). The structures are position-independent.
167 bool record_copy(VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t max_bytes) {
168 if (!loaded_ || !src || !dst || max_bytes < XdxrLayout::header_size) return false;
169 if (src == dst) return true;
170 vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
171 Push p{};
172 p.mode = mode_copy_as;
173 p.src0 = split(src);
174 p.dst = split(dst);
175 p.count = std::uint32_t(std::min<std::uint64_t>(max_bytes, 0xffffffffull) / 4);
176 dispatch(cb, p, p.count, false);
177 return true;
178 }
179
180 // One postbuild value (COMPACTED_SIZE or CURRENT_SIZE, the same for these builds): 8 bytes at `dst` for the
181 // structure at `src`. A barrier first: a build or copy recorded just before writes the header it reads.
182 bool record_postbuild(VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst) {
183 if (!loaded_ || !src || !dst) return false;
184 VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT,
185 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
186 vk_.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1,
187 &b, 0, nullptr, 0, nullptr);
188 vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
189 Push p{};
190 p.mode = mode_postbuild;
191 p.src0 = split(src);
192 p.dst = split(dst);
193 p.count = 1;
194 dispatch(cb, p, 1, false);
154 return true; 195 return true;
155 } 196 }
156 197
157private: 198private:
158 enum : std::uint32_t { 199 enum : std::uint32_t {
159 mode_init = 0, mode_triangles = 1, mode_instances = 2, mode_morton = 3, mode_level = 5, mode_header = 6, 200 mode_init = 0, mode_triangles = 1, mode_instances = 2, mode_morton = 3, mode_level = 5, mode_header = 6,
160 mode_radix_count = 7, mode_radix_scan = 8, mode_radix_scatter = 9 201 mode_radix_count = 7, mode_radix_scan = 8, mode_radix_scatter = 9, mode_small_sort = 10, mode_copy = 11,
202 mode_copy_as = 12, mode_postbuild = 13
161 }; 203 };
162 struct Addr { std::uint32_t lo = 0, hi = 0; }; 204 struct Addr { std::uint32_t lo = 0, hi = 0; };
163 struct Push { // xdxr_build.comp `Push`, std430 push-constant layout 205 struct Push { // xdxr_build.comp `Push`, std430 push-constant layout
@@ -191,6 +233,36 @@ private:
191 dispatch(cb, init, init.count); 233 dispatch(cb, init, init.count);
192 } 234 }
193 235
236 // An update: the source's tree is copied unless it is the destination. Its parent table stays as it is, so there
237 // is no MODE_INIT.
238 void refit_begin(VkCommandBuffer cb, const XdxrLayout& l, const Push& p, std::uint64_t source) {
239 vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
240 const std::uint64_t dst = std::uint64_t(p.dst.hi) << 32 | p.dst.lo;
241 if (source == dst) return;
242 Push c = p;
243 c.mode = mode_copy;
244 c.count = l.size / 4;
245 c.src0 = split(source);
246 dispatch(cb, c, c.count);
247 }
248
249 // Boxes bottom-up through the existing nodes, then the header (its bounds change; nothing else does).
250 void refit_finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) {
251 for (std::size_t level = 0; level < l.level_counts.size(); ++level) {
252 Push n = p;
253 n.mode = mode_level;
254 n.count = l.level_counts[level];
255 n.first = l.level_first[level];
256 n.arg2 = 1; // refit: read each node's children from the node
257 dispatch(cb, n, n.count);
258 }
259 Push h = p;
260 h.mode = mode_header;
261 h.count = 1;
262 h.first = l.root();
263 dispatch(cb, h, 1, false);
264 }
265
194 void finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) { 266 void finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) {
195 Push m = p; 267 Push m = p;
196 m.mode = mode_morton; 268 m.mode = mode_morton;
@@ -198,7 +270,11 @@ private:
198 dispatch(cb, m, m.count); 270 dispatch(cb, m, m.count);
199 // stable LSD radix sort, 4 bits a pass; an even pass count leaves the result where the keys started 271 // stable LSD radix sort, 4 bits a pass; an even pass count leaves the result where the keys started
200 static_assert(XdxrLayout::radix_passes % 2 == 0, "the sorted keys must end in the first buffer"); 272 static_assert(XdxrLayout::radix_passes % 2 == 0, "the sorted keys must end in the first buffer");
201 if (l.sort_size > 1) { 273 if (l.sort_size > 1 && l.sort_size <= XdxrLayout::small_sort_max) {
274 Push s = p;
275 s.mode = mode_small_sort;
276 dispatch(cb, s, 64); // one workgroup, shared memory
277 } else if (l.sort_size > 1) {
202 for (std::uint32_t pass = 0; pass < XdxrLayout::radix_passes; ++pass) { 278 for (std::uint32_t pass = 0; pass < XdxrLayout::radix_passes; ++pass) {
203 Push s = p; 279 Push s = p;
204 s.first = pass; 280 s.first = pass;
diff --git a/runtime/src/xdxr_build.inc b/runtime/src/xdxr_build.inc
index 8a43b04cd..bbc1bb888 100644
--- a/runtime/src/xdxr_build.inc
+++ b/runtime/src/xdxr_build.inc
@@ -1,3441 +1,4092 @@
1{0x07230203,0x00010500,0x000d000b,0x00002b73, 1{0x07230203,0x00010500,0x000d000b,0x000032b4,
20x00000000,0x00020011,0x00000001,0x00020011, 20x00000000,0x00020011,0x00000001,0x00020011,
30x000014e3,0x0006000b,0x00000001,0x4c534c47, 30x000014e3,0x0006000b,0x00000001,0x4c534c47,
40x6474732e,0x3035342e,0x00000000,0x0003000e, 40x6474732e,0x3035342e,0x00000000,0x0003000e,
50x000014e4,0x00000001,0x000d000f,0x00000005, 50x000014e4,0x00000001,0x000f000f,0x00000005,
60x00000004,0x6e69616d,0x00000000,0x000000f9, 60x00000004,0x6e69616d,0x00000000,0x000000fc,
70x000006d4,0x00000740,0x00000789,0x000007e2, 70x000006af,0x000006c4,0x000007a3,0x0000080d,
80x000009e6,0x000009f0,0x000009f1,0x00060010, 80x00000856,0x000008af,0x00000b0e,0x00000b17,
90x00000004,0x00000011,0x00000040,0x00000001, 90x00000b18,0x00060010,0x00000004,0x00000011,
100x00000001,0x00040047,0x00000015,0x00000006, 100x00000040,0x00000001,0x00000001,0x00040047,
110x00000004,0x00030047,0x00000016,0x00000002, 110x00000015,0x00000006,0x00000004,0x00030047,
120x00050048,0x00000016,0x00000000,0x00000023, 120x00000016,0x00000002,0x00050048,0x00000016,
130x00000000,0x00030047,0x000000f7,0x00000002, 130x00000000,0x00000023,0x00000000,0x00030047,
140x00050048,0x000000f7,0x00000000,0x00000023, 140x000000fa,0x00000002,0x00050048,0x000000fa,
150x00000000,0x00050048,0x000000f7,0x00000001, 150x00000000,0x00000023,0x00000000,0x00050048,
160x00000023,0x00000008,0x00050048,0x000000f7, 160x000000fa,0x00000001,0x00000023,0x00000008,
170x00000002,0x00000023,0x00000010,0x00050048, 170x00050048,0x000000fa,0x00000002,0x00000023,
180x000000f7,0x00000003,0x00000023,0x00000018, 180x00000010,0x00050048,0x000000fa,0x00000003,
190x00050048,0x000000f7,0x00000004,0x00000023, 190x00000023,0x00000018,0x00050048,0x000000fa,
200x00000020,0x00050048,0x000000f7,0x00000005, 200x00000004,0x00000023,0x00000020,0x00050048,
210x00000023,0x00000028,0x00050048,0x000000f7, 210x000000fa,0x00000005,0x00000023,0x00000028,
220x00000006,0x00000023,0x00000030,0x00050048, 220x00050048,0x000000fa,0x00000006,0x00000023,
230x000000f7,0x00000007,0x00000023,0x00000034, 230x00000030,0x00050048,0x000000fa,0x00000007,
240x00050048,0x000000f7,0x00000008,0x00000023, 240x00000023,0x00000034,0x00050048,0x000000fa,
250x00000038,0x00050048,0x000000f7,0x00000009, 250x00000008,0x00000023,0x00000038,0x00050048,
260x00000023,0x0000003c,0x00050048,0x000000f7, 260x000000fa,0x00000009,0x00000023,0x0000003c,
270x0000000a,0x00000023,0x00000040,0x00050048, 270x00050048,0x000000fa,0x0000000a,0x00000023,
280x000000f7,0x0000000b,0x00000023,0x00000044, 280x00000040,0x00050048,0x000000fa,0x0000000b,
290x00050048,0x000000f7,0x0000000c,0x00000023, 290x00000023,0x00000044,0x00050048,0x000000fa,
300x00000048,0x00050048,0x000000f7,0x0000000d, 300x0000000c,0x00000023,0x00000048,0x00050048,
310x00000023,0x0000004c,0x00050048,0x000000f7, 310x000000fa,0x0000000d,0x00000023,0x0000004c,
320x0000000e,0x00000023,0x00000050,0x00050048, 320x00050048,0x000000fa,0x0000000e,0x00000023,
330x000000f7,0x0000000f,0x00000023,0x00000054, 330x00000050,0x00050048,0x000000fa,0x0000000f,
340x00050048,0x000000f7,0x00000010,0x00000023, 340x00000023,0x00000054,0x00050048,0x000000fa,
350x00000058,0x00050048,0x000000f7,0x00000011, 350x00000010,0x00000023,0x00000058,0x00050048,
360x00000023,0x0000005c,0x00050048,0x000000f7, 360x000000fa,0x00000011,0x00000023,0x0000005c,
370x00000012,0x00000023,0x00000060,0x00050048, 370x00050048,0x000000fa,0x00000012,0x00000023,
380x000000f7,0x00000013,0x00000023,0x00000064, 380x00000060,0x00050048,0x000000fa,0x00000013,
390x00040047,0x000009e6,0x0000000b,0x0000001c, 390x00000023,0x00000064,0x00040047,0x00000b0e,
400x00040047,0x000009f0,0x0000000b,0x0000001a, 400x0000000b,0x0000001c,0x00040047,0x00000b17,
410x00040047,0x000009f1,0x0000000b,0x0000001b, 410x0000000b,0x0000001a,0x00040047,0x00000b18,
420x00040047,0x00000a6c,0x0000000b,0x00000019, 420x0000000b,0x0000001b,0x00040047,0x00000bf1,
430x00020013,0x00000002,0x00030021,0x00000003, 430x0000000b,0x00000019,0x00020013,0x00000002,
440x00000002,0x00040015,0x00000006,0x00000020, 440x00030021,0x00000003,0x00000002,0x00040015,
450x00000000,0x00040017,0x00000007,0x00000006, 450x00000006,0x00000020,0x00000000,0x00040017,
460x00000002,0x00040020,0x00000009,0x00000007, 460x00000007,0x00000006,0x00000002,0x00040020,
470x00000006,0x00030027,0x00000014,0x000014e5, 470x00000009,0x00000007,0x00000006,0x00030027,
480x0003001d,0x00000015,0x00000006,0x0003001e, 480x00000014,0x000014e5,0x0003001d,0x00000015,
490x00000016,0x00000015,0x00040020,0x00000014, 490x00000006,0x0003001e,0x00000016,0x00000015,
500x000014e5,0x00000016,0x00030016,0x00000027, 500x00040020,0x00000014,0x000014e5,0x00000016,
510x00000020,0x00040020,0x00000028,0x00000007, 510x00030016,0x00000027,0x00000020,0x00040020,
520x00000027,0x00020014,0x0000002f,0x00040017, 520x00000028,0x00000007,0x00000027,0x00020014,
530x0000004b,0x00000027,0x00000003,0x00040020, 530x0000002f,0x00040017,0x0000004b,0x00000027,
540x0000004c,0x00000007,0x0000004b,0x0004002b, 540x00000003,0x00040020,0x0000004c,0x00000007,
550x00000006,0x000000a3,0x00000000,0x0004001e, 550x0000004b,0x0004002b,0x00000006,0x000000a6,
560x000000a8,0x00000006,0x00000006,0x0004002b, 560x00000000,0x0004001e,0x000000ab,0x00000006,
570x00000006,0x000000ad,0x00000001,0x00040015, 570x00000006,0x0004002b,0x00000006,0x000000b0,
580x000000d6,0x00000020,0x00000001,0x0004002b, 580x00000001,0x00040015,0x000000d9,0x00000020,
590x000000d6,0x000000d7,0x00000000,0x00040020, 590x00000001,0x0004002b,0x000000d9,0x000000da,
600x000000d8,0x000014e5,0x00000006,0x0016001e, 600x00000000,0x00040020,0x000000db,0x000014e5,
610x000000f7,0x00000007,0x00000007,0x00000007, 610x00000006,0x0016001e,0x000000fa,0x00000007,
620x00000007,0x00000007,0x00000007,0x00000006, 620x00000007,0x00000007,0x00000007,0x00000007,
630x00000007,0x00000006,0x00000006,0x00000006,
630x00000006,0x00000006,0x00000006,0x00000006, 640x00000006,0x00000006,0x00000006,0x00000006,
640x00000006,0x00000006,0x00000006,0x00000006, 650x00000006,0x00000006,0x00000006,0x00000006,
650x00000006,0x00000006,0x00000006,0x00000006, 660x00000006,0x00000006,0x00000006,0x00040020,
660x00000006,0x00040020,0x000000f8,0x00000009, 670x000000fb,0x00000009,0x000000fa,0x0004003b,
670x000000f7,0x0004003b,0x000000f8,0x000000f9, 680x000000fb,0x000000fc,0x00000009,0x0004002b,
680x00000009,0x0004002b,0x000000d6,0x000000fa, 690x000000d9,0x000000fd,0x0000000e,0x00040020,
690x0000000e,0x00040020,0x000000fb,0x00000009, 700x000000fe,0x00000009,0x00000006,0x0004002b,
700x00000006,0x0004002b,0x00000006,0x000000fe, 710x00000006,0x00000101,0x00000100,0x0004002b,
710x00000800,0x0004002b,0x00000006,0x00000104, 720x00000006,0x00000107,0x00000040,0x0004002b,
720x00000040,0x0004002b,0x00000006,0x00000107, 730x00000006,0x0000010a,0x00000004,0x0004002b,
730x00000004,0x0004002b,0x00000006,0x0000010e, 740x00000006,0x00000111,0x00000008,0x0004002b,
740x00000008,0x0004002b,0x00000006,0x00000115, 750x00000006,0x00000118,0x0000000c,0x0004002b,
750x0000000c,0x0004002b,0x00000006,0x0000011c, 760x00000006,0x0000011f,0x00000010,0x0004002b,
760x00000010,0x0004002b,0x00000006,0x0000012d, 770x00000006,0x00000130,0x80000000,0x0004002b,
770x80000000,0x0004002b,0x00000006,0x00000142, 780x00000006,0x00000145,0x7fffffff,0x0004002b,
780x7fffffff,0x0004002b,0x00000006,0x0000014d, 790x00000006,0x00000150,0x00000018,0x0004002b,
790x00000018,0x0004002b,0x000000d6,0x00000151, 800x000000d9,0x00000154,0x00000001,0x00040020,
800x00000001,0x00040020,0x00000153,0x00000009, 810x00000156,0x00000009,0x00000007,0x0004002b,
810x00000007,0x0004002b,0x00000006,0x0000016d, 820x00000006,0x00000170,0x00000002,0x0004002b,
820x00000002,0x0004002b,0x00000006,0x00000186, 830x00000006,0x00000189,0x00000014,0x0004002b,
830x00000014,0x0004002b,0x00000027,0x000001ea, 840x00000027,0x000001ed,0x3f000000,0x0004002b,
840x3f000000,0x0004002b,0x000000d6,0x00000202, 850x000000d9,0x00000205,0x00000002,0x0004002b,
850x00000002,0x0004002b,0x000000d6,0x0000020a, 860x000000d9,0x0000020d,0x00000003,0x0004002b,
860x00000003,0x0004002b,0x000000d6,0x00000212, 870x000000d9,0x00000215,0x00000004,0x0004002b,
870x00000004,0x0004002b,0x000000d6,0x0000021a, 880x000000d9,0x0000021d,0x00000005,0x0004002b,
880x00000005,0x0004002b,0x000000d6,0x00000221, 890x000000d9,0x00000224,0x00000013,0x0004002b,
890x00000013,0x0004002b,0x00000006,0x00000225, 900x00000006,0x00000228,0x00000080,0x0004002b,
900x00000080,0x0004002b,0x000000d6,0x00000229, 910x000000d9,0x0000022c,0x0000000f,0x0004002b,
910x0000000f,0x0004002b,0x000000d6,0x00000230, 920x000000d9,0x00000233,0x00000006,0x0004002b,
920x00000006,0x0004002b,0x00000006,0x00000236, 930x00000006,0x00000239,0x00000006,0x0004002b,
930x00000006,0x0004002b,0x000000d6,0x0000023b, 940x000000d9,0x0000023e,0x00000010,0x0004002b,
940x00000010,0x0004002b,0x00000006,0x00000243, 950x00000006,0x00000246,0x00000005,0x0004002b,
950x00000005,0x0004002b,0x000000d6,0x0000024d, 960x000000d9,0x00000250,0x00000009,0x0004002b,
960x00000009,0x0004002b,0x000000d6,0x00000263, 970x000000d9,0x00000266,0x0000000a,0x0004002b,
970x0000000a,0x0004002b,0x00000027,0x0000026a, 980x00000027,0x0000026d,0x00000000,0x0004002b,
980x00000000,0x0004002b,0x000000d6,0x00000278, 990x000000d9,0x0000027b,0x0000000b,0x0004002b,
990x0000000b,0x0004002b,0x00000006,0x000002a0, 1000x00000006,0x000002a3,0x0000ffff,0x0004002b,
1000x0000ffff,0x0004002b,0x00000006,0x000002b4, 1010x00000006,0x000002b7,0x00000003,0x00040017,
1010x00000003,0x00040017,0x000002b9,0x00000027, 1020x000002bc,0x00000027,0x00000004,0x0004001c,
1020x00000004,0x0004001c,0x000002f3,0x0000004b, 1030x000002f6,0x0000004b,0x000002b7,0x00040020,
1030x000002b4,0x00040020,0x000002f4,0x00000007, 1040x000002f7,0x00000007,0x000002f6,0x0004002b,
1040x000002f3,0x0004002b,0x000000d6,0x00000305, 1050x000000d9,0x00000308,0x00000008,0x0004002b,
1050x00000008,0x0004002b,0x00000006,0x00000344, 1060x00000006,0x00000347,0x00000024,0x0004002b,
1060x00000024,0x0004002b,0x00000006,0x0000034f, 1070x00000006,0x00000352,0x00000028,0x0004002b,
1070x00000028,0x0004002b,0x00000006,0x0000035a, 1080x00000006,0x0000035d,0x0000002c,0x0004002b,
1080x0000002c,0x0004002b,0x00000006,0x00000365, 1090x00000006,0x00000368,0x00000030,0x0004002b,
1090x00000030,0x0004002b,0x000000d6,0x00000367, 1100x000000d9,0x0000036a,0x0000000c,0x0004002b,
1100x0000000c,0x0004002b,0x00000006,0x00000371, 1110x00000006,0x00000374,0x00000034,0x0004002b,
1110x00000034,0x0004002b,0x00000006,0x0000037b, 1120x00000006,0x0000037e,0x00000038,0x0004002b,
1120x00000038,0x0004002b,0x00000006,0x0000037d, 1130x00000006,0x00000380,0xffffffff,0x0004002b,
1130xffffffff,0x0004002b,0x00000006,0x00000385, 1140x00000006,0x00000388,0x0000003c,0x0004002b,
1140x0000003c,0x0004002b,0x00000006,0x00000387, 1150x00000006,0x0000038a,0x00000009,0x00040017,
1150x00000009,0x00040017,0x00000392,0x0000002f, 1160x00000395,0x0000002f,0x00000003,0x0004001c,
1160x00000003,0x0004001c,0x000003d6,0x00000027, 1170x000003d9,0x00000027,0x00000118,0x00040020,
1170x00000115,0x00040020,0x000003d7,0x00000007, 1180x000003da,0x00000007,0x000003d9,0x0004002b,
1180x000003d6,0x0004002b,0x00000006,0x00000460, 1190x00000006,0x00000463,0x0000001c,0x0004002b,
1190x0000001c,0x0004002b,0x00000006,0x00000466, 1200x00000006,0x00000469,0x00000020,0x0004002b,
1200x00000020,0x0004002b,0x000000d6,0x0000047b, 1210x000000d9,0x0000047e,0x00000018,0x0004002b,
1210x00000018,0x0004002b,0x000000d6,0x000004d5, 1220x000000d9,0x000004d8,0x00000007,0x0004002b,
1220x00000007,0x0004002b,0x00000027,0x000004f9, 1230x00000027,0x000004fc,0x3f800000,0x0004002b,
1230x3f800000,0x0004002b,0x00000006,0x0000052e, 1240x00000006,0x00000531,0x3fffffff,0x00040018,
1240x3fffffff,0x00040018,0x00000548,0x0000004b, 1250x0000054b,0x0000004b,0x00000003,0x00040020,
1250x00000003,0x00040020,0x00000549,0x00000007, 1260x0000054c,0x00000007,0x0000054b,0x0006002c,
1260x00000548,0x0006002c,0x0000004b,0x0000056d, 1270x0000004b,0x00000570,0x0000026d,0x0000026d,
1270x0000026a,0x0000026a,0x0000026a,0x0006002c, 1280x0000026d,0x0006002c,0x0000054b,0x00000571,
1280x00000548,0x0000056e,0x0000056d,0x0000056d, 1290x00000570,0x00000570,0x00000570,0x0004002b,
1290x0000056d,0x0004002b,0x00000006,0x00000594, 1300x00000006,0x00000597,0x00000044,0x0004002b,
1300x00000044,0x0004002b,0x00000006,0x000005a3, 1310x00000006,0x000005a6,0x00000048,0x0004002b,
1310x00000048,0x0004002b,0x00000006,0x000005b2, 1320x00000006,0x000005b5,0x0000004c,0x0004002b,
1320x0000004c,0x0004002b,0x00000006,0x000005c3, 1330x00000006,0x000005c6,0x00000070,0x0004002b,
1330x00000070,0x0004002b,0x00000006,0x000005cd, 1340x00000006,0x000005d0,0x00000074,0x0004002b,
1340x00000074,0x0004002b,0x00000006,0x000005d6, 1350x00000006,0x000005d9,0x00000078,0x0004002b,
1350x00000078,0x0004002b,0x00000006,0x000005df, 1360x00000006,0x000005e2,0x0000007c,0x0004002b,
1360x0000007c,0x0004002b,0x00000006,0x000005fb, 1370x00000006,0x000005fe,0x000003ff,0x0004002b,
1370x000003ff,0x0004002b,0x00000006,0x00000602, 1380x00000006,0x00000605,0x030000ff,0x0004002b,
1380x030000ff,0x0004002b,0x00000006,0x00000608, 1390x00000006,0x0000060b,0x0300f00f,0x0004002b,
1390x0300f00f,0x0004002b,0x00000006,0x0000060e, 1400x00000006,0x00000611,0x030c30c3,0x0004002b,
1400x030c30c3,0x0004002b,0x00000006,0x00000614, 1410x00000006,0x00000617,0x09249249,0x0004002b,
1410x09249249,0x0004002b,0x00000027,0x00000657, 1420x00000027,0x0000065a,0x0da24260,0x0006002c,
1420x0da24260,0x0006002c,0x0000004b,0x00000658, 1430x0000004b,0x0000065b,0x0000065a,0x0000065a,
1430x00000657,0x00000657,0x00000657,0x00040017, 1440x0000065a,0x00040017,0x0000065d,0x00000006,
1440x0000065a,0x00000006,0x00000003,0x0004002b, 1450x00000003,0x0004002b,0x00000027,0x0000066b,
1450x00000027,0x00000668,0x447fc000,0x0004002b, 1460x447fc000,0x0004002b,0x00000006,0x000006ac,
1460x00000006,0x000006ca,0x0000000f,0x0004001c, 1470x00000400,0x0004001c,0x000006ad,0x00000006,
1470x000006d2,0x00000006,0x0000011c,0x00040020, 1480x000006ac,0x00040020,0x000006ae,0x00000004,
1480x000006d3,0x00000004,0x000006d2,0x0004003b, 1490x000006ad,0x0004003b,0x000006ae,0x000006af,
1490x000006d3,0x000006d4,0x00000004,0x00040020, 1500x00000004,0x00040020,0x000006c2,0x00000004,
1500x000006d6,0x00000004,0x00000006,0x0004002b, 1510x00000006,0x0004003b,0x000006ae,0x000006c4,
1510x00000006,0x000006d8,0x00000108,0x0004002b, 1520x00000004,0x0004002b,0x00000006,0x000006da,
1520x00000006,0x00000717,0x0000003f,0x0004001c, 1530x00000108,0x0004002b,0x00000006,0x00000799,
1530x0000073e,0x00000006,0x00000104,0x00040020, 1540x0000000f,0x0004001c,0x000007a1,0x00000006,
1540x0000073f,0x00000004,0x0000073e,0x0004003b, 1550x0000011f,0x00040020,0x000007a2,0x00000004,
1550x0000073f,0x00000740,0x00000004,0x0004003b, 1560x000007a1,0x0004003b,0x000007a2,0x000007a3,
1560x000006d3,0x00000789,0x00000004,0x0004001c, 1570x00000004,0x0004002b,0x00000006,0x000007e4,
1570x000007e0,0x0000073e,0x0000011c,0x00040020, 1580x0000003f,0x0004001c,0x0000080b,0x00000006,
1580x000007e1,0x00000004,0x000007e0,0x0004003b, 1590x00000107,0x00040020,0x0000080c,0x00000004,
1590x000007e1,0x000007e2,0x00000004,0x00040020, 1600x0000080b,0x0004003b,0x0000080c,0x0000080d,
1600x000007fe,0x00000007,0x000006d2,0x0004002b, 1610x00000004,0x0004003b,0x000007a2,0x00000856,
1610x000000d6,0x00000850,0x0000003f,0x0004002b, 1620x00000004,0x0004001c,0x000008ad,0x0000080b,
1620x000000d6,0x000008bc,0x0000000d,0x0004002b, 1630x0000011f,0x00040020,0x000008ae,0x00000004,
1630x000000d6,0x000008c7,0x00000011,0x0004002b, 1640x000008ad,0x0004003b,0x000008ae,0x000008af,
1640x000000d6,0x0000096f,0x00000012,0x00040020, 1650x00000004,0x00040020,0x000008cb,0x00000007,
1650x000009e5,0x00000001,0x0000065a,0x0004003b, 1660x000007a1,0x0004002b,0x000000d9,0x0000091d,
1660x000009e5,0x000009e6,0x00000001,0x00040020, 1670x0000003f,0x0004002b,0x00000006,0x00000967,
1670x000009e7,0x00000001,0x00000006,0x0004002b, 1680x00000007,0x0004002b,0x000000d9,0x0000096c,
1680x00000006,0x000009ec,0x00000007,0x0004003b, 1690x0000000d,0x0004002b,0x000000d9,0x000009ef,
1690x000009e5,0x000009f0,0x00000001,0x0004003b, 1700x00000011,0x0004002b,0x000000d9,0x00000a97,
1700x000009e5,0x000009f1,0x00000001,0x0006002c, 1710x00000012,0x00040020,0x00000b0d,0x00000001,
1710x0000065a,0x00000a6c,0x00000104,0x000000ad, 1720x0000065d,0x0004003b,0x00000b0d,0x00000b0e,
1720x000000ad,0x0006002c,0x0000004b,0x00002b61, 1730x00000001,0x00040020,0x00000b0f,0x00000001,
1730x000004f9,0x000004f9,0x000004f9,0x0004002b, 1740x00000006,0x0004003b,0x00000b0d,0x00000b17,
1740x00000027,0x00002b63,0x7f800000,0x0006002c, 1750x00000001,0x0004003b,0x00000b0d,0x00000b18,
1750x0000004b,0x00002b64,0x00002b63,0x00002b63, 1760x00000001,0x0004002b,0x00000006,0x00000b3a,
1760x00002b63,0x0004002b,0x00000027,0x00002b65, 1770x0000000a,0x0004002b,0x00000006,0x00000b57,
1770xff800000,0x0006002c,0x0000004b,0x00002b66, 1780x0000000d,0x0004002b,0x00000006,0x00000b94,
1780x00002b65,0x00002b65,0x00002b65,0x0004002b, 1790x0000000b,0x0006002c,0x0000065d,0x00000bf1,
1790x00000006,0x00002b67,0x000007ff,0x00050036, 1800x00000107,0x000000b0,0x000000b0,0x0006002c,
1800x00000002,0x00000004,0x00000000,0x00000003, 1810x0000004b,0x000032a2,0x000004fc,0x000004fc,
1810x000200f8,0x00000005,0x0004003b,0x000003d7, 1820x000004fc,0x0004002b,0x00000027,0x000032a4,
1820x00001884,0x00000007,0x0004003b,0x00000549, 1830x7f800000,0x0006002c,0x0000004b,0x000032a5,
1830x000018c5,0x00000007,0x0004003b,0x0000004c, 1840x000032a4,0x000032a4,0x000032a4,0x0004002b,
1840x000018c8,0x00000007,0x0004003b,0x0000004c, 1850x00000027,0x000032a6,0xff800000,0x0006002c,
1850x00001424,0x00000007,0x0004003b,0x000002f4, 1860x0000004b,0x000032a7,0x000032a6,0x000032a6,
1860x00001239,0x00000007,0x0004003b,0x000007fe, 1870x000032a6,0x0004002b,0x00000006,0x000032a8,
1870x00000c2a,0x00000007,0x000300f7,0x00000a6e, 1880x000000ff,0x00050036,0x00000002,0x00000004,
1880x00000000,0x000300fb,0x000000a3,0x00000a6f, 1890x00000000,0x00000003,0x000200f8,0x00000005,
1890x000200f8,0x00000a6f,0x00050041,0x000009e7, 1900x0004003b,0x000003da,0x00001c65,0x00000007,
1900x000009e8,0x000009e6,0x000000a3,0x0004003d, 1910x0004003b,0x0000054c,0x00001ca6,0x00000007,
1910x00000006,0x000009e9,0x000009e8,0x00050041, 1920x0004003b,0x0000004c,0x00001ca9,0x00000007,
1920x000000fb,0x000009ea,0x000000f9,0x00000230, 1930x0004003b,0x0000004c,0x00001805,0x00000007,
1930x0004003d,0x00000006,0x000009eb,0x000009ea, 1940x0004003b,0x000002f7,0x0000161a,0x00000007,
1940x000500aa,0x0000002f,0x000009ed,0x000009eb, 1950x0004003b,0x000008cb,0x00000daf,0x00000007,
1950x000009ec,0x000300f7,0x000009ef,0x00000000, 1960x000300f7,0x00000bf3,0x00000000,0x000300fb,
1960x000400fa,0x000009ed,0x000009ee,0x000009ef, 1970x000000a6,0x00000bf4,0x000200f8,0x00000bf4,
1970x000200f8,0x000009ee,0x00050041,0x000009e7, 1980x00050041,0x00000b0f,0x00000b10,0x00000b0e,
1980x000009f3,0x000009f0,0x000000a3,0x0004003d, 1990x000000a6,0x0004003d,0x00000006,0x00000b11,
1990x00000006,0x000009f4,0x000009f3,0x00050041, 2000x00000b10,0x00050041,0x000000fe,0x00000b12,
2000x000009e7,0x000009f6,0x000009f1,0x000000a3, 2010x000000fc,0x00000233,0x0004003d,0x00000006,
2010x0004003d,0x00000006,0x000009f7,0x000009f6, 2020x00000b13,0x00000b12,0x000500aa,0x0000002f,
2020x000500b0,0x0000002f,0x00000a8b,0x000009f7, 2030x00000b14,0x00000b13,0x00000967,0x000300f7,
2030x0000011c,0x000300f7,0x00000a8f,0x00000000, 2040x00000b16,0x00000000,0x000400fa,0x00000b14,
2040x000400fa,0x00000a8b,0x00000a8c,0x00000a8f, 2050x00000b15,0x00000b16,0x000200f8,0x00000b15,
2050x000200f8,0x00000a8c,0x00050041,0x000006d6, 2060x00050041,0x00000b0f,0x00000b1a,0x00000b17,
2060x00000a8e,0x000006d4,0x000009f7,0x0003003e, 2070x000000a6,0x0004003d,0x00000006,0x00000b1b,
2070x00000a8e,0x000000a3,0x000200f9,0x00000a8f, 2080x00000b1a,0x00050041,0x00000b0f,0x00000b1d,
2080x000200f8,0x00000a8f,0x000400e0,0x0000016d, 2090x00000b18,0x000000a6,0x0004003d,0x00000006,
2090x0000016d,0x000006d8,0x00050084,0x00000006, 2100x00000b1e,0x00000b1d,0x000500b0,0x0000002f,
2100x00000a91,0x000009f4,0x000000fe,0x00050080, 2110x00000c10,0x00000b1e,0x0000011f,0x000300f7,
2110x00000006,0x00000a93,0x00000a91,0x000000fe, 2120x00000c14,0x00000000,0x000400fa,0x00000c10,
2120x00050041,0x000000fb,0x00000a94,0x000000f9, 2130x00000c11,0x00000c14,0x000200f8,0x00000c11,
2130x000000fa,0x0004003d,0x00000006,0x00000a95, 2140x00050041,0x000006c2,0x00000c13,0x000007a3,
2140x00000a94,0x0007000c,0x00000006,0x00000a96, 2150x00000b1e,0x0003003e,0x00000c13,0x000000a6,
2150x00000001,0x00000026,0x00000a93,0x00000a95, 2160x000200f9,0x00000c14,0x000200f8,0x00000c14,
2160x00050080,0x00000006,0x00000a99,0x00000a91, 2170x000400e0,0x00000170,0x00000170,0x000006da,
2170x000009f7,0x000200f9,0x00000a9a,0x000200f8, 2180x00050084,0x00000006,0x00000c16,0x00000b1b,
2180x00000a9a,0x000700f5,0x00000006,0x00002b52, 2190x00000101,0x00050080,0x00000006,0x00000c18,
2190x00000a99,0x00000a8f,0x00000aac,0x00000aaa, 2200x00000c16,0x00000101,0x00050041,0x000000fe,
2200x000500b0,0x0000002f,0x00000a9e,0x00002b52, 2210x00000c19,0x000000fc,0x000000fd,0x0004003d,
2210x00000a96,0x000400f6,0x00000aad,0x00000aaa, 2220x00000006,0x00000c1a,0x00000c19,0x0007000c,
2220x00000000,0x000400fa,0x00000a9e,0x00000a9f, 2230x00000006,0x00000c1b,0x00000001,0x00000026,
2230x00000aad,0x000200f8,0x00000a9f,0x00050041, 2240x00000c18,0x00000c1a,0x00050080,0x00000006,
2240x000000fb,0x00000ac3,0x000000f9,0x00000305, 2250x00000c1e,0x00000c16,0x00000b1e,0x000200f9,
2250x0004003d,0x00000006,0x00000ac4,0x00000ac3, 2260x00000c1f,0x000200f8,0x00000c1f,0x000700f5,
2260x000500c7,0x00000006,0x00000ac5,0x00000ac4, 2270x00000006,0x00003283,0x00000c1e,0x00000c14,
2270x000000ad,0x000500aa,0x0000002f,0x00000ac6, 2280x00000c31,0x00000c2f,0x000500b0,0x0000002f,
2280x00000ac5,0x000000a3,0x000300f7,0x00000acb, 2290x00000c23,0x00003283,0x00000c1b,0x000400f6,
2290x00000000,0x000400fa,0x00000ac6,0x00000ac7, 2300x00000c32,0x00000c2f,0x00000000,0x000400fa,
2300x00000ac9,0x000200f8,0x00000ac7,0x000200f9, 2310x00000c23,0x00000c24,0x00000c32,0x000200f8,
2310x00000acb,0x000200f8,0x00000ac9,0x00050084, 2320x00000c24,0x00050041,0x000000fe,0x00000c48,
2320x00000006,0x00000ad3,0x0000010e,0x00000a95, 2330x000000fc,0x00000308,0x0004003d,0x00000006,
2330x00050080,0x00000006,0x00000ad4,0x00000104, 2340x00000c49,0x00000c48,0x000500c7,0x00000006,
2340x00000ad3,0x000200f9,0x00000acb,0x000200f8, 2350x00000c4a,0x00000c49,0x000000b0,0x000500aa,
2350x00000acb,0x000700f5,0x00000006,0x00002b53, 2360x0000002f,0x00000c4b,0x00000c4a,0x000000a6,
2360x00000104,0x00000ac7,0x00000ad4,0x00000ac9, 2370x000300f7,0x00000c50,0x00000000,0x000400fa,
2370x00050084,0x00000006,0x00000aa2,0x00000107, 2380x00000c4b,0x00000c4c,0x00000c4e,0x000200f8,
2380x00002b52,0x00050080,0x00000006,0x00000aa3, 2390x00000c4c,0x000200f9,0x00000c50,0x000200f8,
2390x00002b53,0x00000aa2,0x00050041,0x00000153, 2400x00000c4e,0x00050084,0x00000006,0x00000c58,
2400x00000aa4,0x000000f9,0x00000151,0x0004003d, 2410x00000111,0x00000c1a,0x00050080,0x00000006,
2410x00000007,0x00000aa5,0x00000aa4,0x00050051, 2420x00000c59,0x00000107,0x00000c58,0x000200f9,
2420x00000006,0x00000aeb,0x00000aa5,0x00000000, 2430x00000c50,0x000200f8,0x00000c50,0x000700f5,
2430x00050095,0x000000a8,0x00000aed,0x00000aeb, 2440x00000006,0x00003284,0x00000107,0x00000c4c,
2440x00000aa3,0x00050051,0x00000006,0x00000aee, 2450x00000c59,0x00000c4e,0x00050084,0x00000006,
2450x00000aed,0x00000001,0x00050051,0x00000006, 2460x00000c27,0x0000010a,0x00003283,0x00050080,
2460x00000aef,0x00000aed,0x00000000,0x00050051, 2470x00000006,0x00000c28,0x00003284,0x00000c27,
2470x00000006,0x00000af2,0x00000aa5,0x00000001, 2480x00050041,0x00000156,0x00000c29,0x000000fc,
2480x00050080,0x00000006,0x00000af4,0x00000af2, 2490x00000154,0x0004003d,0x00000007,0x00000c2a,
2490x00000aee,0x00050050,0x00000007,0x00000af5, 2500x00000c29,0x00050051,0x00000006,0x00000c70,
2500x00000aef,0x00000af4,0x0004007c,0x00000014, 2510x00000c2a,0x00000000,0x00050095,0x000000ab,
2510x00000ae5,0x00000af5,0x00060041,0x000000d8, 2520x00000c72,0x00000c70,0x00000c28,0x00050051,
2520x00000adc,0x00000ae5,0x000000d7,0x000000d7, 2530x00000006,0x00000c73,0x00000c72,0x00000001,
2530x0006003d,0x00000006,0x00000add,0x00000adc, 2540x00050051,0x00000006,0x00000c74,0x00000c72,
2550x00000000,0x00050051,0x00000006,0x00000c77,
2560x00000c2a,0x00000001,0x00050080,0x00000006,
2570x00000c79,0x00000c77,0x00000c73,0x00050050,
2580x00000007,0x00000c7a,0x00000c74,0x00000c79,
2590x0004007c,0x00000014,0x00000c6a,0x00000c7a,
2600x00060041,0x000000db,0x00000c61,0x00000c6a,
2610x000000da,0x000000da,0x0006003d,0x00000006,
2620x00000c62,0x00000c61,0x00000002,0x00000004,
2630x00050084,0x00000006,0x00000c80,0x0000010a,
2640x00000c49,0x000500c2,0x00000006,0x00000c81,
2650x00000c62,0x00000c80,0x000500c7,0x00000006,
2660x00000c82,0x00000c81,0x00000799,0x00050041,
2670x000006c2,0x00000c2d,0x000007a3,0x00000c82,
2680x000700ea,0x00000006,0x00000c2e,0x00000c2d,
2690x000000b0,0x000000a6,0x000000b0,0x000200f9,
2700x00000c2f,0x000200f8,0x00000c2f,0x00050080,
2710x00000006,0x00000c31,0x00003283,0x00000107,
2720x000200f9,0x00000c1f,0x000200f8,0x00000c32,
2730x000400e0,0x00000170,0x00000170,0x000006da,
2740x000300f7,0x00000c44,0x00000000,0x000400fa,
2750x00000c10,0x00000c35,0x00000c44,0x000200f8,
2760x00000c35,0x00050084,0x00000006,0x00000c87,
2770x0000011f,0x00000c1a,0x00050080,0x00000006,
2780x00000c88,0x00000107,0x00000c87,0x00050080,
2790x00000006,0x00000c8e,0x00000c1a,0x000032a8,
2800x00050086,0x00000006,0x00000c8f,0x00000c8e,
2810x00000101,0x00050084,0x00000006,0x00000c39,
2820x00000b1e,0x00000c8f,0x00050080,0x00000006,
2830x00000c3b,0x00000c39,0x00000b1b,0x00050084,
2840x00000006,0x00000c3c,0x0000010a,0x00000c3b,
2850x00050080,0x00000006,0x00000c3d,0x00000c88,
2860x00000c3c,0x00050041,0x00000156,0x00000c3f,
2870x000000fc,0x00000154,0x0004003d,0x00000007,
2880x00000c40,0x00000c3f,0x00050041,0x000006c2,
2890x00000c41,0x000007a3,0x00000b1e,0x0004003d,
2900x00000006,0x00000c42,0x00000c41,0x00050051,
2910x00000006,0x00000ca5,0x00000c40,0x00000000,
2920x00050095,0x000000ab,0x00000ca7,0x00000ca5,
2930x00000c3d,0x00050051,0x00000006,0x00000ca8,
2940x00000ca7,0x00000001,0x00050051,0x00000006,
2950x00000ca9,0x00000ca7,0x00000000,0x00050051,
2960x00000006,0x00000cac,0x00000c40,0x00000001,
2970x00050080,0x00000006,0x00000cae,0x00000cac,
2980x00000ca8,0x00050050,0x00000007,0x00000caf,
2990x00000ca9,0x00000cae,0x0004007c,0x00000014,
3000x00000c9f,0x00000caf,0x00060041,0x000000db,
3010x00000c97,0x00000c9f,0x000000da,0x000000da,
3020x0005003e,0x00000c97,0x00000c42,0x00000002,
3030x00000004,0x000200f9,0x00000c44,0x000200f8,
3040x00000c44,0x000200f9,0x00000bf3,0x000200f8,
3050x00000b16,0x000500aa,0x0000002f,0x00000b23,
3060x00000b13,0x00000111,0x000300f7,0x00000b25,
3070x00000000,0x000400fa,0x00000b23,0x00000b24,
3080x00000b25,0x000200f8,0x00000b24,0x00050041,
3090x00000b0f,0x00000b27,0x00000b18,0x000000a6,
3100x0004003d,0x00000006,0x00000b28,0x00000b27,
3110x00050041,0x000000fe,0x00000d22,0x000000fc,
3120x000000fd,0x0004003d,0x00000006,0x00000d23,
3130x00000d22,0x00050080,0x00000006,0x00000d25,
3140x00000d23,0x000032a8,0x00050086,0x00000006,
3150x00000d26,0x00000d25,0x00000101,0x00050084,
3160x00000006,0x00000cc5,0x0000011f,0x00000d26,
3170x00050080,0x00000006,0x00000cc7,0x00000cc5,
3180x000007e4,0x00050086,0x00000006,0x00000cc8,
3190x00000cc7,0x00000107,0x00050084,0x00000006,
3200x00000ccb,0x00000b28,0x00000cc8,0x0007000c,
3210x00000006,0x00000ccd,0x00000001,0x00000026,
3220x00000ccb,0x00000cc5,0x00050080,0x00000006,
3230x00000cd0,0x00000ccd,0x00000cc8,0x0007000c,
3240x00000006,0x00000cd2,0x00000001,0x00000026,
3250x00000cd0,0x00000cc5,0x000200f9,0x00000cd4,
3260x000200f8,0x00000cd4,0x000700f5,0x00000006,
3270x0000327e,0x000000a6,0x00000b24,0x00000ce2,
3280x00000cd9,0x000700f5,0x00000006,0x0000327d,
3290x00000ccd,0x00000b24,0x00000ce5,0x00000cd9,
3300x000500b0,0x0000002f,0x00000cd8,0x0000327d,
3310x00000cd2,0x000400f6,0x00000ce6,0x00000cd9,
3320x00000000,0x000400fa,0x00000cd8,0x00000cd9,
3330x00000ce6,0x000200f8,0x00000cd9,0x00050084,
3340x00000006,0x00000d2b,0x0000011f,0x00000d23,
3350x00050080,0x00000006,0x00000d2c,0x00000107,
3360x00000d2b,0x00050084,0x00000006,0x00000cdc,
3370x0000010a,0x0000327d,0x00050080,0x00000006,
3380x00000cdd,0x00000d2c,0x00000cdc,0x00050041,
3390x00000156,0x00000cde,0x000000fc,0x00000154,
3400x0004003d,0x00000007,0x00000cdf,0x00000cde,
3410x00050051,0x00000006,0x00000d43,0x00000cdf,
3420x00000000,0x00050095,0x000000ab,0x00000d45,
3430x00000d43,0x00000cdd,0x00050051,0x00000006,
3440x00000d46,0x00000d45,0x00000001,0x00050051,
3450x00000006,0x00000d47,0x00000d45,0x00000000,
3460x00050051,0x00000006,0x00000d4a,0x00000cdf,
3470x00000001,0x00050080,0x00000006,0x00000d4c,
3480x00000d4a,0x00000d46,0x00050050,0x00000007,
3490x00000d4d,0x00000d47,0x00000d4c,0x0004007c,
3500x00000014,0x00000d3d,0x00000d4d,0x00060041,
3510x000000db,0x00000d34,0x00000d3d,0x000000da,
3520x000000da,0x0006003d,0x00000006,0x00000d35,
3530x00000d34,0x00000002,0x00000004,0x00050080,
3540x00000006,0x00000ce2,0x0000327e,0x00000d35,
3550x00050080,0x00000006,0x00000ce5,0x0000327d,
3560x00000154,0x000200f9,0x00000cd4,0x000200f8,
3570x00000ce6,0x00050041,0x000006c2,0x00000ce9,
3580x0000080d,0x00000b28,0x0003003e,0x00000ce9,
3590x0000327e,0x000400e0,0x00000170,0x00000170,
3600x000006da,0x000500aa,0x0000002f,0x00000ceb,
3610x00000b28,0x000000a6,0x000300f7,0x00000cff,
3620x00000000,0x000400fa,0x00000ceb,0x00000cec,
3630x00000cff,0x000200f8,0x00000cec,0x000200f9,
3640x00000ced,0x000200f8,0x00000ced,0x000700f5,
3650x00000006,0x00003282,0x000000a6,0x00000cec,
3660x00000cfa,0x00000cf1,0x000700f5,0x00000006,
3670x0000327f,0x000000a6,0x00000cec,0x00000cfd,
3680x00000cf1,0x000500b0,0x0000002f,0x00000cf0,
3690x0000327f,0x00000107,0x000400f6,0x00000cfe,
3700x00000cf1,0x00000000,0x000400fa,0x00000cf0,
3710x00000cf1,0x00000cfe,0x000200f8,0x00000cf1,
3720x00050041,0x000006c2,0x00000cf3,0x0000080d,
3730x0000327f,0x0004003d,0x00000006,0x00000cf4,
3740x00000cf3,0x0003003e,0x00000cf3,0x00003282,
3750x00050080,0x00000006,0x00000cfa,0x00003282,
3760x00000cf4,0x00050080,0x00000006,0x00000cfd,
3770x0000327f,0x00000154,0x000200f9,0x00000ced,
3780x000200f8,0x00000cfe,0x000200f9,0x00000cff,
3790x000200f8,0x00000cff,0x000400e0,0x00000170,
3800x00000170,0x000006da,0x0004003d,0x00000006,
3810x00000d02,0x00000ce9,0x000200f9,0x00000d04,
3820x000200f8,0x00000d04,0x000700f5,0x00000006,
3830x00003281,0x00000d02,0x00000cff,0x00000d1b,
3840x00000d09,0x000700f5,0x00000006,0x00003280,
3850x00000ccd,0x00000cff,0x00000d1e,0x00000d09,
3860x000500b0,0x0000002f,0x00000d08,0x00003280,
3870x00000cd2,0x000400f6,0x00000d1f,0x00000d09,
3880x00000000,0x000400fa,0x00000d08,0x00000d09,
3890x00000d1f,0x000200f8,0x00000d09,0x00050084,
3900x00000006,0x00000d52,0x0000011f,0x00000d23,
3910x00050080,0x00000006,0x00000d53,0x00000107,
3920x00000d52,0x00050084,0x00000006,0x00000d0c,
3930x0000010a,0x00003280,0x00050080,0x00000006,
3940x00000d0d,0x00000d53,0x00000d0c,0x00050041,
3950x00000156,0x00000d0e,0x000000fc,0x00000154,
3960x0004003d,0x00000007,0x00000d0f,0x00000d0e,
3970x00050051,0x00000006,0x00000d6a,0x00000d0f,
3980x00000000,0x00050095,0x000000ab,0x00000d6c,
3990x00000d6a,0x00000d0d,0x00050051,0x00000006,
4000x00000d6d,0x00000d6c,0x00000001,0x00050051,
4010x00000006,0x00000d6e,0x00000d6c,0x00000000,
4020x00050051,0x00000006,0x00000d71,0x00000d0f,
4030x00000001,0x00050080,0x00000006,0x00000d73,
4040x00000d71,0x00000d6d,0x00050050,0x00000007,
4050x00000d74,0x00000d6e,0x00000d73,0x0004007c,
4060x00000014,0x00000d64,0x00000d74,0x00060041,
4070x000000db,0x00000d5b,0x00000d64,0x000000da,
4080x000000da,0x0006003d,0x00000006,0x00000d5c,
4090x00000d5b,0x00000002,0x00000004,0x0005003e,
4100x00000d5b,0x00003281,0x00000002,0x00000004,
4110x00050080,0x00000006,0x00000d1b,0x00003281,
4120x00000d5c,0x00050080,0x00000006,0x00000d1e,
4130x00003280,0x00000154,0x000200f9,0x00000d04,
4140x000200f8,0x00000d1f,0x000200f9,0x00000bf3,
4150x000200f8,0x00000b25,0x000500aa,0x0000002f,
4160x00000b2d,0x00000b13,0x0000038a,0x000300f7,
4170x00000b2f,0x00000000,0x000400fa,0x00000b2d,
4180x00000b2e,0x00000b2f,0x000200f8,0x00000b2e,
4190x00050041,0x00000b0f,0x00000b31,0x00000b17,
4200x000000a6,0x0004003d,0x00000006,0x00000b32,
4210x00000b31,0x00050041,0x00000b0f,0x00000b34,
4220x00000b18,0x000000a6,0x0004003d,0x00000006,
4230x00000b35,0x00000b34,0x000500b0,0x0000002f,
4240x00000dbb,0x00000b35,0x0000011f,0x000300f7,
4250x00000dca,0x00000000,0x000400fa,0x00000dbb,
4260x00000dbc,0x00000dca,0x000200f8,0x00000dbc,
4270x00050041,0x000000fe,0x00000e6c,0x000000fc,
4280x000000fd,0x0004003d,0x00000006,0x00000e6d,
4290x00000e6c,0x00050084,0x00000006,0x00000e6e,
4300x0000011f,0x00000e6d,0x00050080,0x00000006,
4310x00000e6f,0x00000107,0x00000e6e,0x00050080,
4320x00000006,0x00000e75,0x00000e6d,0x000032a8,
4330x00050086,0x00000006,0x00000e76,0x00000e75,
4340x00000101,0x00050084,0x00000006,0x00000dc1,
4350x00000b35,0x00000e76,0x00050080,0x00000006,
4360x00000dc3,0x00000dc1,0x00000b32,0x00050084,
4370x00000006,0x00000dc4,0x0000010a,0x00000dc3,
4380x00050080,0x00000006,0x00000dc5,0x00000e6f,
4390x00000dc4,0x00050041,0x00000156,0x00000dc6,
4400x000000fc,0x00000154,0x0004003d,0x00000007,
4410x00000dc7,0x00000dc6,0x00050051,0x00000006,
4420x00000e8d,0x00000dc7,0x00000000,0x00050095,
4430x000000ab,0x00000e8f,0x00000e8d,0x00000dc5,
4440x00050051,0x00000006,0x00000e90,0x00000e8f,
4450x00000001,0x00050051,0x00000006,0x00000e91,
4460x00000e8f,0x00000000,0x00050051,0x00000006,
4470x00000e94,0x00000dc7,0x00000001,0x00050080,
4480x00000006,0x00000e96,0x00000e94,0x00000e90,
4490x00050050,0x00000007,0x00000e97,0x00000e91,
4500x00000e96,0x0004007c,0x00000014,0x00000e87,
4510x00000e97,0x00060041,0x000000db,0x00000e7e,
4520x00000e87,0x000000da,0x000000da,0x0006003d,
4530x00000006,0x00000e7f,0x00000e7e,0x00000002,
4540x00000004,0x00050041,0x000006c2,0x00000dc9,
4550x00000856,0x00000b35,0x0003003e,0x00000dc9,
4560x00000e7f,0x000200f9,0x00000dca,0x000200f8,
4570x00000dca,0x00050084,0x00000006,0x00000dcc,
4580x00000b32,0x00000101,0x00050080,0x00000006,
4590x00000dce,0x00000dcc,0x00000101,0x00050041,
4600x000000fe,0x00000dcf,0x000000fc,0x000000fd,
4610x0004003d,0x00000006,0x00000dd0,0x00000dcf,
4620x0007000c,0x00000006,0x00000dd1,0x00000001,
4630x00000026,0x00000dce,0x00000dd0,0x000200f9,
4640x00000dd3,0x000200f8,0x00000dd3,0x000700f5,
4650x00000006,0x00003264,0x00000dcc,0x00000dca,
4660x00000e68,0x00000e66,0x000500b0,0x0000002f,
4670x00000dd7,0x00003264,0x00000dd1,0x000400f6,
4680x00000e69,0x00000e66,0x00000000,0x000400fa,
4690x00000dd7,0x00000dd8,0x00000e69,0x000200f8,
4700x00000dd8,0x00050080,0x00000006,0x00000ddb,
4710x00003264,0x00000b35,0x000500b0,0x0000002f,
4720x00000dde,0x00000ddb,0x00000dd1,0x000300f7,
4730x00000de9,0x00000000,0x000400fa,0x00000dde,
4740x00000de0,0x00000de8,0x000200f8,0x00000de0,
4750x00050041,0x000000fe,0x00000e9b,0x000000fc,
4760x00000308,0x0004003d,0x00000006,0x00000e9c,
4770x00000e9b,0x000500c7,0x00000006,0x00000e9d,
4780x00000e9c,0x000000b0,0x000500aa,0x0000002f,
4790x00000e9e,0x00000e9d,0x000000a6,0x000300f7,
4800x00000ea3,0x00000000,0x000400fa,0x00000e9e,
4810x00000e9f,0x00000ea1,0x000200f8,0x00000e9f,
4820x000200f9,0x00000ea3,0x000200f8,0x00000ea1,
4830x00050084,0x00000006,0x00000eab,0x00000111,
4840x00000dd0,0x00050080,0x00000006,0x00000eac,
4850x00000107,0x00000eab,0x000200f9,0x00000ea3,
4860x000200f8,0x00000ea3,0x000700f5,0x00000006,
4870x00003265,0x00000107,0x00000e9f,0x00000eac,
4880x00000ea1,0x00050084,0x00000006,0x00000de3,
4890x0000010a,0x00000ddb,0x00050080,0x00000006,
4900x00000de4,0x00003265,0x00000de3,0x00050041,
4910x00000156,0x00000de5,0x000000fc,0x00000154,
4920x0004003d,0x00000007,0x00000de6,0x00000de5,
4930x00050051,0x00000006,0x00000ec3,0x00000de6,
4940x00000000,0x00050095,0x000000ab,0x00000ec5,
4950x00000ec3,0x00000de4,0x00050051,0x00000006,
4960x00000ec6,0x00000ec5,0x00000001,0x00050051,
4970x00000006,0x00000ec7,0x00000ec5,0x00000000,
4980x00050051,0x00000006,0x00000eca,0x00000de6,
4990x00000001,0x00050080,0x00000006,0x00000ecc,
5000x00000eca,0x00000ec6,0x00050050,0x00000007,
5010x00000ecd,0x00000ec7,0x00000ecc,0x0004007c,
5020x00000014,0x00000ebd,0x00000ecd,0x00060041,
5030x000000db,0x00000eb4,0x00000ebd,0x000000da,
5040x000000da,0x0006003d,0x00000006,0x00000eb5,
5050x00000eb4,0x00000002,0x00000004,0x000200f9,
5060x00000de9,0x000200f8,0x00000de8,0x000200f9,
5070x00000de9,0x000200f8,0x00000de9,0x000700f5,
5080x00000006,0x00003266,0x00000eb5,0x00000ea3,
5090x000000a6,0x00000de8,0x000300f7,0x00000df5,
5100x00000000,0x000400fa,0x00000dde,0x00000dec,
5110x00000df4,0x000200f8,0x00000dec,0x00050041,
5120x000000fe,0x00000ed1,0x000000fc,0x00000308,
5130x0004003d,0x00000006,0x00000ed2,0x00000ed1,
5140x000500c7,0x00000006,0x00000ed3,0x00000ed2,
5150x000000b0,0x000500aa,0x0000002f,0x00000ed4,
5160x00000ed3,0x000000a6,0x000300f7,0x00000ed9,
5170x00000000,0x000400fa,0x00000ed4,0x00000ed5,
5180x00000ed7,0x000200f8,0x00000ed5,0x00050084,
5190x00000006,0x00000edf,0x0000010a,0x00000dd0,
5200x00050080,0x00000006,0x00000ee0,0x00000107,
5210x00000edf,0x000200f9,0x00000ed9,0x000200f8,
5220x00000ed7,0x00050084,0x00000006,0x00000ee5,
5230x00000118,0x00000dd0,0x00050080,0x00000006,
5240x00000ee6,0x00000107,0x00000ee5,0x000200f9,
5250x00000ed9,0x000200f8,0x00000ed9,0x000700f5,
5260x00000006,0x00003267,0x00000ee0,0x00000ed5,
5270x00000ee6,0x00000ed7,0x00050084,0x00000006,
5280x00000def,0x0000010a,0x00000ddb,0x00050080,
5290x00000006,0x00000df0,0x00003267,0x00000def,
5300x00050041,0x00000156,0x00000df1,0x000000fc,
5310x00000154,0x0004003d,0x00000007,0x00000df2,
5320x00000df1,0x00050051,0x00000006,0x00000efd,
5330x00000df2,0x00000000,0x00050095,0x000000ab,
5340x00000eff,0x00000efd,0x00000df0,0x00050051,
5350x00000006,0x00000f00,0x00000eff,0x00000001,
5360x00050051,0x00000006,0x00000f01,0x00000eff,
5370x00000000,0x00050051,0x00000006,0x00000f04,
5380x00000df2,0x00000001,0x00050080,0x00000006,
5390x00000f06,0x00000f04,0x00000f00,0x00050050,
5400x00000007,0x00000f07,0x00000f01,0x00000f06,
5410x0004007c,0x00000014,0x00000ef7,0x00000f07,
5420x00060041,0x000000db,0x00000eee,0x00000ef7,
5430x000000da,0x000000da,0x0006003d,0x00000006,
5440x00000eef,0x00000eee,0x00000002,0x00000004,
5450x000200f9,0x00000df5,0x000200f8,0x00000df4,
5460x000200f9,0x00000df5,0x000200f8,0x00000df5,
5470x000700f5,0x00000006,0x00003268,0x00000eef,
5480x00000ed9,0x000000a6,0x00000df4,0x00050041,
5490x000000fe,0x00000f0b,0x000000fc,0x00000308,
5500x0004003d,0x00000006,0x00000f0c,0x00000f0b,
5510x00050084,0x00000006,0x00000f0d,0x0000010a,
5520x00000f0c,0x000500c2,0x00000006,0x00000f0e,
5530x00003266,0x00000f0d,0x000500c7,0x00000006,
5540x00000f0f,0x00000f0e,0x00000799,0x000200f9,
5550x00000df9,0x000200f8,0x00000df9,0x000700f5,
5560x00000006,0x00003269,0x000000a6,0x00000df5,
5570x00000e09,0x00000dfd,0x000500b0,0x0000002f,
5580x00000dfc,0x00003269,0x0000011f,0x000400f6,
5590x00000e0a,0x00000dfd,0x00000000,0x000400fa,
5600x00000dfc,0x00000dfd,0x00000e0a,0x000200f8,
5610x00000dfd,0x000500aa,0x0000002f,0x00000e03,
5620x00003269,0x00000f0f,0x000500a7,0x0000002f,
5630x00000e04,0x00000dde,0x00000e03,0x000600a9,
5640x00000006,0x00000e05,0x00000e04,0x000000b0,
5650x000000a6,0x00060041,0x000006c2,0x00000e06,
5660x000008af,0x00003269,0x00000b35,0x0003003e,
5670x00000e06,0x00000e05,0x00050080,0x00000006,
5680x00000e09,0x00003269,0x00000154,0x000200f9,
5690x00000df9,0x000200f8,0x00000e0a,0x000400e0,
5700x00000170,0x00000170,0x000006da,0x000200f9,
5710x00000e0b,0x000200f8,0x00000e0b,0x000700f5,
5720x00000006,0x0000326a,0x000000b0,0x00000e0a,
5730x00000e3c,0x00000e3a,0x000500b0,0x0000002f,
5740x00000e0e,0x0000326a,0x00000107,0x000400f6,
5750x00000e3d,0x00000e3a,0x00000000,0x000400fa,
5760x00000e0e,0x00000e0f,0x00000e3d,0x000200f8,
5770x00000e0f,0x000200f9,0x00000e10,0x000200f8,
5780x00000e10,0x000700f5,0x00000006,0x00003277,
5790x000000a6,0x00000e0f,0x00000e26,0x00000e24,
5800x000500b0,0x0000002f,0x00000e13,0x00003277,
5810x0000011f,0x000400f6,0x00000e27,0x00000e24,
5820x00000000,0x000400fa,0x00000e13,0x00000e14,
5830x00000e27,0x000200f8,0x00000e14,0x000500ae,
5840x0000002f,0x00000e18,0x00000b35,0x0000326a,
5850x000300f7,0x00000e21,0x00000000,0x000400fa,
5860x00000e18,0x00000e19,0x00000e20,0x000200f8,
5870x00000e19,0x00050082,0x00000006,0x00000e1d,
5880x00000b35,0x0000326a,0x00060041,0x000006c2,
5890x00000e1e,0x000008af,0x00003277,0x00000e1d,
5900x0004003d,0x00000006,0x00000e1f,0x00000e1e,
5910x000200f9,0x00000e21,0x000200f8,0x00000e20,
5920x000200f9,0x00000e21,0x000200f8,0x00000e21,
5930x000700f5,0x00000006,0x0000327b,0x00000e1f,
5940x00000e19,0x000000a6,0x00000e20,0x00050041,
5950x00000009,0x00000e23,0x00000daf,0x00003277,
5960x0003003e,0x00000e23,0x0000327b,0x000200f9,
5970x00000e24,0x000200f8,0x00000e24,0x00050080,
5980x00000006,0x00000e26,0x00003277,0x00000154,
5990x000200f9,0x00000e10,0x000200f8,0x00000e27,
6000x000400e0,0x00000170,0x00000170,0x000006da,
6010x000200f9,0x00000e28,0x000200f8,0x00000e28,
6020x000700f5,0x00000006,0x00003278,0x000000a6,
6030x00000e27,0x00000e38,0x00000e2c,0x000500b0,
6040x0000002f,0x00000e2b,0x00003278,0x0000011f,
6050x000400f6,0x00000e39,0x00000e2c,0x00000000,
6060x000400fa,0x00000e2b,0x00000e2c,0x00000e39,
6070x000200f8,0x00000e2c,0x00050041,0x00000009,
6080x00000e30,0x00000daf,0x00003278,0x0004003d,
6090x00000006,0x00000e31,0x00000e30,0x00060041,
6100x000006c2,0x00000e32,0x000008af,0x00003278,
6110x00000b35,0x0004003d,0x00000006,0x00000e33,
6120x00000e32,0x00050080,0x00000006,0x00000e34,
6130x00000e33,0x00000e31,0x0003003e,0x00000e32,
6140x00000e34,0x00050080,0x00000006,0x00000e38,
6150x00003278,0x00000154,0x000200f9,0x00000e28,
6160x000200f8,0x00000e39,0x000400e0,0x00000170,
6170x00000170,0x000006da,0x000200f9,0x00000e3a,
6180x000200f8,0x00000e3a,0x000500c4,0x00000006,
6190x00000e3c,0x0000326a,0x00000154,0x000200f9,
6200x00000e0b,0x000200f8,0x00000e3d,0x000300f7,
6210x00000e59,0x00000000,0x000400fa,0x00000dde,
6220x00000e3f,0x00000e59,0x000200f8,0x00000e3f,
6230x00050041,0x000006c2,0x00000e41,0x00000856,
6240x00000f0f,0x0004003d,0x00000006,0x00000e42,
6250x00000e41,0x00060041,0x000006c2,0x00000e45,
6260x000008af,0x00000f0f,0x00000b35,0x0004003d,
6270x00000006,0x00000e46,0x00000e45,0x00050080,
6280x00000006,0x00000e47,0x00000e42,0x00000e46,
6290x00050082,0x00000006,0x00000e48,0x00000e47,
6300x000000b0,0x000500c7,0x00000006,0x00000f15,
6310x00000f0c,0x000000b0,0x000500aa,0x0000002f,
6320x00000f16,0x00000f15,0x000000a6,0x000300f7,
6330x00000f1b,0x00000000,0x000400fa,0x00000f16,
6340x00000f17,0x00000f19,0x000200f8,0x00000f17,
6350x00050084,0x00000006,0x00000f21,0x00000111,
6360x00000dd0,0x00050080,0x00000006,0x00000f22,
6370x00000107,0x00000f21,0x000200f9,0x00000f1b,
6380x000200f8,0x00000f19,0x000200f9,0x00000f1b,
6390x000200f8,0x00000f1b,0x000700f5,0x00000006,
6400x0000326b,0x00000f22,0x00000f17,0x00000107,
6410x00000f19,0x00050084,0x00000006,0x00000e4b,
6420x0000010a,0x00000e48,0x00050080,0x00000006,
6430x00000e4c,0x0000326b,0x00000e4b,0x00050041,
6440x00000156,0x00000e4d,0x000000fc,0x00000154,
6450x0004003d,0x00000007,0x00000e4e,0x00000e4d,
6460x00050051,0x00000006,0x00000f3a,0x00000e4e,
6470x00000000,0x00050095,0x000000ab,0x00000f3c,
6480x00000f3a,0x00000e4c,0x00050051,0x00000006,
6490x00000f3d,0x00000f3c,0x00000001,0x00050051,
6500x00000006,0x00000f3e,0x00000f3c,0x00000000,
6510x00050051,0x00000006,0x00000f41,0x00000e4e,
6520x00000001,0x00050080,0x00000006,0x00000f43,
6530x00000f41,0x00000f3d,0x00050050,0x00000007,
6540x00000f44,0x00000f3e,0x00000f43,0x0004007c,
6550x00000014,0x00000f34,0x00000f44,0x00060041,
6560x000000db,0x00000f2c,0x00000f34,0x000000da,
6570x000000da,0x0005003e,0x00000f2c,0x00003266,
6580x00000002,0x00000004,0x000300f7,0x00000f50,
6590x00000000,0x000400fa,0x00000f16,0x00000f4c,
6600x00000f4e,0x000200f8,0x00000f4c,0x00050084,
6610x00000006,0x00000f56,0x00000118,0x00000dd0,
6620x00050080,0x00000006,0x00000f57,0x00000107,
6630x00000f56,0x000200f9,0x00000f50,0x000200f8,
6640x00000f4e,0x00050084,0x00000006,0x00000f5c,
6650x0000010a,0x00000dd0,0x00050080,0x00000006,
6660x00000f5d,0x00000107,0x00000f5c,0x000200f9,
6670x00000f50,0x000200f8,0x00000f50,0x000700f5,
6680x00000006,0x0000326c,0x00000f57,0x00000f4c,
6690x00000f5d,0x00000f4e,0x00050080,0x00000006,
6700x00000e54,0x0000326c,0x00000e4b,0x00050095,
6710x000000ab,0x00000f75,0x00000f3a,0x00000e54,
6720x00050051,0x00000006,0x00000f76,0x00000f75,
6730x00000001,0x00050051,0x00000006,0x00000f77,
6740x00000f75,0x00000000,0x00050080,0x00000006,
6750x00000f7c,0x00000f41,0x00000f76,0x00050050,
6760x00000007,0x00000f7d,0x00000f77,0x00000f7c,
6770x0004007c,0x00000014,0x00000f6d,0x00000f7d,
6780x00060041,0x000000db,0x00000f65,0x00000f6d,
6790x000000da,0x000000da,0x0005003e,0x00000f65,
6800x00003268,0x00000002,0x00000004,0x000200f9,
6810x00000e59,0x000200f8,0x00000e59,0x000400e0,
6820x00000170,0x00000170,0x000006da,0x000300f7,
6830x00000e65,0x00000000,0x000400fa,0x00000dbb,
6840x00000e5c,0x00000e65,0x000200f8,0x00000e5c,
6850x00060041,0x000006c2,0x00000e5f,0x000008af,
6860x00000b35,0x0000091d,0x0004003d,0x00000006,
6870x00000e60,0x00000e5f,0x00050041,0x000006c2,
6880x00000e61,0x00000856,0x00000b35,0x0004003d,
6890x00000006,0x00000e62,0x00000e61,0x00050080,
6900x00000006,0x00000e63,0x00000e62,0x00000e60,
6910x0003003e,0x00000e61,0x00000e63,0x000200f9,
6920x00000e65,0x000200f8,0x00000e65,0x000400e0,
6930x00000170,0x00000170,0x000006da,0x000200f9,
6940x00000e66,0x000200f8,0x00000e66,0x00050080,
6950x00000006,0x00000e68,0x00003264,0x00000107,
6960x000200f9,0x00000dd3,0x000200f8,0x00000e69,
6970x000200f9,0x00000bf3,0x000200f8,0x00000b2f,
6980x000500aa,0x0000002f,0x00000b3b,0x00000b13,
6990x00000b3a,0x000300f7,0x00000b3d,0x00000000,
7000x000400fa,0x00000b3b,0x00000b3c,0x00000b3d,
7010x000200f8,0x00000b3c,0x00050041,0x00000b0f,
7020x00000b3f,0x00000b18,0x000000a6,0x0004003d,
7030x00000006,0x00000b40,0x00000b3f,0x00050041,
7040x000000fe,0x00000f98,0x000000fc,0x000000fd,
7050x0004003d,0x00000006,0x00000f99,0x00000f98,
7060x000200f9,0x00000f9a,0x000200f8,0x00000f9a,
7070x000700f5,0x00000006,0x0000324f,0x000000b0,
7080x00000b3c,0x00000fa1,0x00000f9f,0x000500b0,
7090x0000002f,0x00000f9e,0x0000324f,0x00000f99,
7100x000400f6,0x00000fa3,0x00000f9f,0x00000000,
7110x000400fa,0x00000f9e,0x00000f9f,0x00000fa3,
7120x000200f8,0x00000f9f,0x000500c4,0x00000006,
7130x00000fa1,0x0000324f,0x00000154,0x000200f9,
7140x00000f9a,0x000200f8,0x00000fa3,0x000200f9,
7150x00000fa5,0x000200f8,0x00000fa5,0x000700f5,
7160x00000006,0x00003250,0x00000b40,0x00000fa3,
7170x00000fcd,0x00000fcb,0x000500b0,0x0000002f,
7180x00000fa9,0x00003250,0x0000324f,0x000400f6,
7190x00000fce,0x00000fcb,0x00000000,0x000400fa,
7200x00000fa9,0x00000faa,0x00000fce,0x000200f8,
7210x00000faa,0x000500b0,0x0000002f,0x00000fae,
7220x00003250,0x00000f99,0x000300f7,0x00000fb8,
7230x00000000,0x000400fa,0x00000fae,0x00000faf,
7240x00000fb7,0x000200f8,0x00000faf,0x00050084,
7250x00000006,0x00000fb2,0x0000010a,0x00003250,
7260x00050080,0x00000006,0x00000fb3,0x00000107,
7270x00000fb2,0x00050041,0x00000156,0x00000fb4,
7280x000000fc,0x00000154,0x0004003d,0x00000007,
7290x00000fb5,0x00000fb4,0x00050051,0x00000006,
7300x0000105c,0x00000fb5,0x00000000,0x00050095,
7310x000000ab,0x0000105e,0x0000105c,0x00000fb3,
7320x00050051,0x00000006,0x0000105f,0x0000105e,
7330x00000001,0x00050051,0x00000006,0x00001060,
7340x0000105e,0x00000000,0x00050051,0x00000006,
7350x00001063,0x00000fb5,0x00000001,0x00050080,
7360x00000006,0x00001065,0x00001063,0x0000105f,
7370x00050050,0x00000007,0x00001066,0x00001060,
7380x00001065,0x0004007c,0x00000014,0x00001056,
7390x00001066,0x00060041,0x000000db,0x0000104d,
7400x00001056,0x000000da,0x000000da,0x0006003d,
7410x00000006,0x0000104e,0x0000104d,0x00000002,
7420x00000004,0x000200f9,0x00000fb8,0x000200f8,
7430x00000fb7,0x000200f9,0x00000fb8,0x000200f8,
7440x00000fb8,0x000700f5,0x00000006,0x00003260,
7450x0000104e,0x00000faf,0x00000380,0x00000fb7,
7460x00050041,0x000006c2,0x00000fba,0x000006af,
7470x00003250,0x0003003e,0x00000fba,0x00003260,
7480x000300f7,0x00000fc8,0x00000000,0x000400fa,
7490x00000fae,0x00000fbf,0x00000fc7,0x000200f8,
7500x00000fbf,0x00050084,0x00000006,0x0000106b,
7510x0000010a,0x00000f99,0x00050080,0x00000006,
7520x0000106c,0x00000107,0x0000106b,0x00050084,
7530x00000006,0x00000fc2,0x0000010a,0x00003250,
7540x00050080,0x00000006,0x00000fc3,0x0000106c,
7550x00000fc2,0x00050041,0x00000156,0x00000fc4,
7560x000000fc,0x00000154,0x0004003d,0x00000007,
7570x00000fc5,0x00000fc4,0x00050051,0x00000006,
7580x00001083,0x00000fc5,0x00000000,0x00050095,
7590x000000ab,0x00001085,0x00001083,0x00000fc3,
7600x00050051,0x00000006,0x00001086,0x00001085,
7610x00000001,0x00050051,0x00000006,0x00001087,
7620x00001085,0x00000000,0x00050051,0x00000006,
7630x0000108a,0x00000fc5,0x00000001,0x00050080,
7640x00000006,0x0000108c,0x0000108a,0x00001086,
7650x00050050,0x00000007,0x0000108d,0x00001087,
7660x0000108c,0x0004007c,0x00000014,0x0000107d,
7670x0000108d,0x00060041,0x000000db,0x00001074,
7680x0000107d,0x000000da,0x000000da,0x0006003d,
7690x00000006,0x00001075,0x00001074,0x00000002,
7700x00000004,0x000200f9,0x00000fc8,0x000200f8,
7710x00000fc7,0x000200f9,0x00000fc8,0x000200f8,
7720x00000fc8,0x000700f5,0x00000006,0x00003262,
7730x00001075,0x00000fbf,0x00000380,0x00000fc7,
7740x00050041,0x000006c2,0x00000fca,0x000006c4,
7750x00003250,0x0003003e,0x00000fca,0x00003262,
7760x000200f9,0x00000fcb,0x000200f8,0x00000fcb,
7770x00050080,0x00000006,0x00000fcd,0x00003250,
7780x00000107,0x000200f9,0x00000fa5,0x000200f8,
7790x00000fce,0x000400e0,0x00000170,0x00000170,
7800x000006da,0x000200f9,0x00000fcf,0x000200f8,
7810x00000fcf,0x000700f5,0x00000006,0x00003252,
7820x00000170,0x00000fce,0x00001023,0x00001021,
7830x000500b2,0x0000002f,0x00000fd3,0x00003252,
7840x0000324f,0x000400f6,0x00001024,0x00001021,
7850x00000000,0x000400fa,0x00000fd3,0x00000fd4,
7860x00001024,0x000200f8,0x00000fd4,0x000500c2,
7870x00000006,0x00000fd6,0x00003252,0x00000154,
7880x000200f9,0x00000fd7,0x000200f8,0x00000fd7,
7890x000700f5,0x00000006,0x00003255,0x00000fd6,
7900x00000fd4,0x0000101f,0x0000101d,0x000500ac,
7910x0000002f,0x00000fda,0x00003255,0x000000a6,
7920x000400f6,0x00001020,0x0000101d,0x00000000,
7930x000400fa,0x00000fda,0x00000fdb,0x00001020,
7940x000200f8,0x00000fdb,0x000200f9,0x00000fdd,
7950x000200f8,0x00000fdd,0x000700f5,0x00000006,
7960x00003257,0x00000b40,0x00000fdb,0x0000101b,
7970x00001019,0x000500b0,0x0000002f,0x00000fe1,
7980x00003257,0x0000324f,0x000400f6,0x0000101c,
7990x00001019,0x00000000,0x000400fa,0x00000fe1,
8000x00000fe2,0x0000101c,0x000200f8,0x00000fe2,
8010x000500c6,0x00000006,0x00000fe5,0x00003257,
8020x00003255,0x000500ac,0x0000002f,0x00000fe8,
8030x00000fe5,0x00003257,0x000300f7,0x00001018,
8040x00000000,0x000400fa,0x00000fe8,0x00000fe9,
8050x00001018,0x000200f8,0x00000fe9,0x00050041,
8060x000006c2,0x00000feb,0x000006af,0x00003257,
8070x0004003d,0x00000006,0x00000fec,0x00000feb,
8080x00050041,0x000006c2,0x00000fee,0x000006af,
8090x00000fe5,0x0004003d,0x00000006,0x00000fef,
8100x00000fee,0x00050041,0x000006c2,0x00000ff1,
8110x000006c4,0x00003257,0x0004003d,0x00000006,
8120x00000ff2,0x00000ff1,0x00050041,0x000006c2,
8130x00000ff4,0x000006c4,0x00000fe5,0x0004003d,
8140x00000006,0x00000ff5,0x00000ff4,0x000500ac,
8150x0000002f,0x00000ff8,0x00000fec,0x00000fef,
8160x000400a8,0x0000002f,0x00000ff9,0x00000ff8,
8170x000300f7,0x00001002,0x00000000,0x000400fa,
8180x00000ff9,0x00000ffa,0x00001002,0x000200f8,
8190x00000ffa,0x000500aa,0x0000002f,0x00000ffd,
8200x00000fec,0x00000fef,0x000500ac,0x0000002f,
8210x00001000,0x00000ff2,0x00000ff5,0x000500a7,
8220x0000002f,0x00001001,0x00000ffd,0x00001000,
8230x000200f9,0x00001002,0x000200f8,0x00001002,
8240x000700f5,0x0000002f,0x00001003,0x00000ff8,
8250x00000fe9,0x00001001,0x00000ffa,0x000500c7,
8260x00000006,0x00001007,0x00003257,0x00003252,
8270x000500aa,0x0000002f,0x00001008,0x00001007,
8280x000000a6,0x000500a4,0x0000002f,0x00001009,
8290x00001003,0x00001008,0x000300f7,0x00001017,
8300x00000000,0x000400fa,0x00001009,0x0000100a,
8310x00001017,0x000200f8,0x0000100a,0x0003003e,
8320x00000feb,0x00000fef,0x0003003e,0x00000fee,
8330x00000fec,0x0003003e,0x00000ff1,0x00000ff5,
8340x0003003e,0x00000ff4,0x00000ff2,0x000200f9,
8350x00001017,0x000200f8,0x00001017,0x000200f9,
8360x00001018,0x000200f8,0x00001018,0x000200f9,
8370x00001019,0x000200f8,0x00001019,0x00050080,
8380x00000006,0x0000101b,0x00003257,0x00000107,
8390x000200f9,0x00000fdd,0x000200f8,0x0000101c,
8400x000400e0,0x00000170,0x00000170,0x000006da,
8410x000200f9,0x0000101d,0x000200f8,0x0000101d,
8420x000500c2,0x00000006,0x0000101f,0x00003255,
8430x00000154,0x000200f9,0x00000fd7,0x000200f8,
8440x00001020,0x000200f9,0x00001021,0x000200f8,
8450x00001021,0x000500c4,0x00000006,0x00001023,
8460x00003252,0x00000154,0x000200f9,0x00000fcf,
8470x000200f8,0x00001024,0x000200f9,0x00001026,
8480x000200f8,0x00001026,0x000700f5,0x00000006,
8490x00003254,0x00000b40,0x00001024,0x00001042,
8500x0000102b,0x000500b0,0x0000002f,0x0000102a,
8510x00003254,0x00000f99,0x000400f6,0x00001043,
8520x0000102b,0x00000000,0x000400fa,0x0000102a,
8530x0000102b,0x00001043,0x000200f8,0x0000102b,
8540x00050084,0x00000006,0x0000102e,0x0000010a,
8550x00003254,0x00050080,0x00000006,0x0000102f,
8560x00000107,0x0000102e,0x00050041,0x00000156,
8570x00001031,0x000000fc,0x00000154,0x0004003d,
8580x00000007,0x00001032,0x00001031,0x00050041,
8590x000006c2,0x00001033,0x000006af,0x00003254,
8600x0004003d,0x00000006,0x00001034,0x00001033,
8610x00050051,0x00000006,0x000010a5,0x00001032,
8620x00000000,0x00050095,0x000000ab,0x000010a7,
8630x000010a5,0x0000102f,0x00050051,0x00000006,
8640x000010a8,0x000010a7,0x00000001,0x00050051,
8650x00000006,0x000010a9,0x000010a7,0x00000000,
8660x00050051,0x00000006,0x000010ac,0x00001032,
8670x00000001,0x00050080,0x00000006,0x000010ae,
8680x000010ac,0x000010a8,0x00050050,0x00000007,
8690x000010af,0x000010a9,0x000010ae,0x0004007c,
8700x00000014,0x0000109f,0x000010af,0x00060041,
8710x000000db,0x00001097,0x0000109f,0x000000da,
8720x000000da,0x0005003e,0x00001097,0x00001034,
2540x00000002,0x00000004,0x00050084,0x00000006, 8730x00000002,0x00000004,0x00050084,0x00000006,
2550x00000afb,0x00000107,0x00000ac4,0x000500c2, 8740x000010b4,0x0000010a,0x00000f99,0x00050080,
2560x00000006,0x00000afc,0x00000add,0x00000afb, 8750x00000006,0x000010b5,0x00000107,0x000010b4,
2570x000500c7,0x00000006,0x00000afd,0x00000afc, 8760x00050080,0x00000006,0x00001039,0x000010b5,
2580x000006ca,0x00050041,0x000006d6,0x00000aa8, 8770x0000102e,0x00050041,0x000006c2,0x0000103d,
2590x000006d4,0x00000afd,0x000700ea,0x00000006, 8780x000006c4,0x00003254,0x0004003d,0x00000006,
2600x00000aa9,0x00000aa8,0x000000ad,0x000000a3, 8790x0000103e,0x0000103d,0x00050095,0x000000ab,
2610x000000ad,0x000200f9,0x00000aaa,0x000200f8, 8800x000010cd,0x000010a5,0x00001039,0x00050051,
2620x00000aaa,0x00050080,0x00000006,0x00000aac, 8810x00000006,0x000010ce,0x000010cd,0x00000001,
2630x00002b52,0x00000104,0x000200f9,0x00000a9a, 8820x00050051,0x00000006,0x000010cf,0x000010cd,
2640x000200f8,0x00000aad,0x000400e0,0x0000016d, 8830x00000000,0x00050080,0x00000006,0x000010d4,
2650x0000016d,0x000006d8,0x000300f7,0x00000abf, 8840x000010ac,0x000010ce,0x00050050,0x00000007,
2660x00000000,0x000400fa,0x00000a8b,0x00000ab0, 8850x000010d5,0x000010cf,0x000010d4,0x0004007c,
2670x00000abf,0x000200f8,0x00000ab0,0x00050084, 8860x00000014,0x000010c5,0x000010d5,0x00060041,
2680x00000006,0x00000b02,0x0000011c,0x00000a95, 8870x000000db,0x000010bd,0x000010c5,0x000000da,
2690x00050080,0x00000006,0x00000b03,0x00000104, 8880x000000da,0x0005003e,0x000010bd,0x0000103e,
2700x00000b02,0x00050080,0x00000006,0x00000b09,
2710x00000a95,0x00002b67,0x00050086,0x00000006,
2720x00000b0a,0x00000b09,0x000000fe,0x00050084,
2730x00000006,0x00000ab4,0x000009f7,0x00000b0a,
2740x00050080,0x00000006,0x00000ab6,0x00000ab4,
2750x000009f4,0x00050084,0x00000006,0x00000ab7,
2760x00000107,0x00000ab6,0x00050080,0x00000006,
2770x00000ab8,0x00000b03,0x00000ab7,0x00050041,
2780x00000153,0x00000aba,0x000000f9,0x00000151,
2790x0004003d,0x00000007,0x00000abb,0x00000aba,
2800x00050041,0x000006d6,0x00000abc,0x000006d4,
2810x000009f7,0x0004003d,0x00000006,0x00000abd,
2820x00000abc,0x00050051,0x00000006,0x00000b20,
2830x00000abb,0x00000000,0x00050095,0x000000a8,
2840x00000b22,0x00000b20,0x00000ab8,0x00050051,
2850x00000006,0x00000b23,0x00000b22,0x00000001,
2860x00050051,0x00000006,0x00000b24,0x00000b22,
2870x00000000,0x00050051,0x00000006,0x00000b27,
2880x00000abb,0x00000001,0x00050080,0x00000006,
2890x00000b29,0x00000b27,0x00000b23,0x00050050,
2900x00000007,0x00000b2a,0x00000b24,0x00000b29,
2910x0004007c,0x00000014,0x00000b1a,0x00000b2a,
2920x00060041,0x000000d8,0x00000b12,0x00000b1a,
2930x000000d7,0x000000d7,0x0005003e,0x00000b12,
2940x00000abd,0x00000002,0x00000004,0x000200f9,
2950x00000abf,0x000200f8,0x00000abf,0x000200f9,
2960x00000a6e,0x000200f8,0x000009ef,0x000500aa,
2970x0000002f,0x000009fc,0x000009eb,0x0000010e,
2980x000300f7,0x000009fe,0x00000000,0x000400fa,
2990x000009fc,0x000009fd,0x000009fe,0x000200f8,
3000x000009fd,0x00050041,0x000009e7,0x00000a00,
3010x000009f1,0x000000a3,0x0004003d,0x00000006,
3020x00000a01,0x00000a00,0x00050041,0x000000fb,
3030x00000b9d,0x000000f9,0x000000fa,0x0004003d,
3040x00000006,0x00000b9e,0x00000b9d,0x00050080,
3050x00000006,0x00000ba0,0x00000b9e,0x00002b67,
3060x00050086,0x00000006,0x00000ba1,0x00000ba0,
3070x000000fe,0x00050084,0x00000006,0x00000b40,
3080x0000011c,0x00000ba1,0x00050080,0x00000006,
3090x00000b42,0x00000b40,0x00000717,0x00050086,
3100x00000006,0x00000b43,0x00000b42,0x00000104,
3110x00050084,0x00000006,0x00000b46,0x00000a01,
3120x00000b43,0x0007000c,0x00000006,0x00000b48,
3130x00000001,0x00000026,0x00000b46,0x00000b40,
3140x00050080,0x00000006,0x00000b4b,0x00000b48,
3150x00000b43,0x0007000c,0x00000006,0x00000b4d,
3160x00000001,0x00000026,0x00000b4b,0x00000b40,
3170x000200f9,0x00000b4f,0x000200f8,0x00000b4f,
3180x000700f5,0x00000006,0x00002b4d,0x000000a3,
3190x000009fd,0x00000b5d,0x00000b54,0x000700f5,
3200x00000006,0x00002b4c,0x00000b48,0x000009fd,
3210x00000b60,0x00000b54,0x000500b0,0x0000002f,
3220x00000b53,0x00002b4c,0x00000b4d,0x000400f6,
3230x00000b61,0x00000b54,0x00000000,0x000400fa,
3240x00000b53,0x00000b54,0x00000b61,0x000200f8,
3250x00000b54,0x00050084,0x00000006,0x00000ba6,
3260x0000011c,0x00000b9e,0x00050080,0x00000006,
3270x00000ba7,0x00000104,0x00000ba6,0x00050084,
3280x00000006,0x00000b57,0x00000107,0x00002b4c,
3290x00050080,0x00000006,0x00000b58,0x00000ba7,
3300x00000b57,0x00050041,0x00000153,0x00000b59,
3310x000000f9,0x00000151,0x0004003d,0x00000007,
3320x00000b5a,0x00000b59,0x00050051,0x00000006,
3330x00000bbe,0x00000b5a,0x00000000,0x00050095,
3340x000000a8,0x00000bc0,0x00000bbe,0x00000b58,
3350x00050051,0x00000006,0x00000bc1,0x00000bc0,
3360x00000001,0x00050051,0x00000006,0x00000bc2,
3370x00000bc0,0x00000000,0x00050051,0x00000006,
3380x00000bc5,0x00000b5a,0x00000001,0x00050080,
3390x00000006,0x00000bc7,0x00000bc5,0x00000bc1,
3400x00050050,0x00000007,0x00000bc8,0x00000bc2,
3410x00000bc7,0x0004007c,0x00000014,0x00000bb8,
3420x00000bc8,0x00060041,0x000000d8,0x00000baf,
3430x00000bb8,0x000000d7,0x000000d7,0x0006003d,
3440x00000006,0x00000bb0,0x00000baf,0x00000002,
3450x00000004,0x00050080,0x00000006,0x00000b5d,
3460x00002b4d,0x00000bb0,0x00050080,0x00000006,
3470x00000b60,0x00002b4c,0x00000151,0x000200f9,
3480x00000b4f,0x000200f8,0x00000b61,0x00050041,
3490x000006d6,0x00000b64,0x00000740,0x00000a01,
3500x0003003e,0x00000b64,0x00002b4d,0x000400e0,
3510x0000016d,0x0000016d,0x000006d8,0x000500aa,
3520x0000002f,0x00000b66,0x00000a01,0x000000a3,
3530x000300f7,0x00000b7a,0x00000000,0x000400fa,
3540x00000b66,0x00000b67,0x00000b7a,0x000200f8,
3550x00000b67,0x000200f9,0x00000b68,0x000200f8,
3560x00000b68,0x000700f5,0x00000006,0x00002b51,
3570x000000a3,0x00000b67,0x00000b75,0x00000b6c,
3580x000700f5,0x00000006,0x00002b4e,0x000000a3,
3590x00000b67,0x00000b78,0x00000b6c,0x000500b0,
3600x0000002f,0x00000b6b,0x00002b4e,0x00000104,
3610x000400f6,0x00000b79,0x00000b6c,0x00000000,
3620x000400fa,0x00000b6b,0x00000b6c,0x00000b79,
3630x000200f8,0x00000b6c,0x00050041,0x000006d6,
3640x00000b6e,0x00000740,0x00002b4e,0x0004003d,
3650x00000006,0x00000b6f,0x00000b6e,0x0003003e,
3660x00000b6e,0x00002b51,0x00050080,0x00000006,
3670x00000b75,0x00002b51,0x00000b6f,0x00050080,
3680x00000006,0x00000b78,0x00002b4e,0x00000151,
3690x000200f9,0x00000b68,0x000200f8,0x00000b79,
3700x000200f9,0x00000b7a,0x000200f8,0x00000b7a,
3710x000400e0,0x0000016d,0x0000016d,0x000006d8,
3720x0004003d,0x00000006,0x00000b7d,0x00000b64,
3730x000200f9,0x00000b7f,0x000200f8,0x00000b7f,
3740x000700f5,0x00000006,0x00002b50,0x00000b7d,
3750x00000b7a,0x00000b96,0x00000b84,0x000700f5,
3760x00000006,0x00002b4f,0x00000b48,0x00000b7a,
3770x00000b99,0x00000b84,0x000500b0,0x0000002f,
3780x00000b83,0x00002b4f,0x00000b4d,0x000400f6,
3790x00000b9a,0x00000b84,0x00000000,0x000400fa,
3800x00000b83,0x00000b84,0x00000b9a,0x000200f8,
3810x00000b84,0x00050084,0x00000006,0x00000bcd,
3820x0000011c,0x00000b9e,0x00050080,0x00000006,
3830x00000bce,0x00000104,0x00000bcd,0x00050084,
3840x00000006,0x00000b87,0x00000107,0x00002b4f,
3850x00050080,0x00000006,0x00000b88,0x00000bce,
3860x00000b87,0x00050041,0x00000153,0x00000b89,
3870x000000f9,0x00000151,0x0004003d,0x00000007,
3880x00000b8a,0x00000b89,0x00050051,0x00000006,
3890x00000be5,0x00000b8a,0x00000000,0x00050095,
3900x000000a8,0x00000be7,0x00000be5,0x00000b88,
3910x00050051,0x00000006,0x00000be8,0x00000be7,
3920x00000001,0x00050051,0x00000006,0x00000be9,
3930x00000be7,0x00000000,0x00050051,0x00000006,
3940x00000bec,0x00000b8a,0x00000001,0x00050080,
3950x00000006,0x00000bee,0x00000bec,0x00000be8,
3960x00050050,0x00000007,0x00000bef,0x00000be9,
3970x00000bee,0x0004007c,0x00000014,0x00000bdf,
3980x00000bef,0x00060041,0x000000d8,0x00000bd6,
3990x00000bdf,0x000000d7,0x000000d7,0x0006003d,
4000x00000006,0x00000bd7,0x00000bd6,0x00000002,
4010x00000004,0x0005003e,0x00000bd6,0x00002b50,
4020x00000002,0x00000004,0x00050080,0x00000006,
4030x00000b96,0x00002b50,0x00000bd7,0x00050080,
4040x00000006,0x00000b99,0x00002b4f,0x00000151,
4050x000200f9,0x00000b7f,0x000200f8,0x00000b9a,
4060x000200f9,0x00000a6e,0x000200f8,0x000009fe,
4070x000500aa,0x0000002f,0x00000a06,0x000009eb,
4080x00000387,0x000300f7,0x00000a08,0x00000000,
4090x000400fa,0x00000a06,0x00000a07,0x00000a08,
4100x000200f8,0x00000a07,0x00050041,0x000009e7,
4110x00000a0a,0x000009f0,0x000000a3,0x0004003d,
4120x00000006,0x00000a0b,0x00000a0a,0x00050041,
4130x000009e7,0x00000a0d,0x000009f1,0x000000a3,
4140x0004003d,0x00000006,0x00000a0e,0x00000a0d,
4150x000500b0,0x0000002f,0x00000c36,0x00000a0e,
4160x0000011c,0x000300f7,0x00000c45,0x00000000,
4170x000400fa,0x00000c36,0x00000c37,0x00000c45,
4180x000200f8,0x00000c37,0x00050041,0x000000fb,
4190x00000ce7,0x000000f9,0x000000fa,0x0004003d,
4200x00000006,0x00000ce8,0x00000ce7,0x00050084,
4210x00000006,0x00000ce9,0x0000011c,0x00000ce8,
4220x00050080,0x00000006,0x00000cea,0x00000104,
4230x00000ce9,0x00050080,0x00000006,0x00000cf0,
4240x00000ce8,0x00002b67,0x00050086,0x00000006,
4250x00000cf1,0x00000cf0,0x000000fe,0x00050084,
4260x00000006,0x00000c3c,0x00000a0e,0x00000cf1,
4270x00050080,0x00000006,0x00000c3e,0x00000c3c,
4280x00000a0b,0x00050084,0x00000006,0x00000c3f,
4290x00000107,0x00000c3e,0x00050080,0x00000006,
4300x00000c40,0x00000cea,0x00000c3f,0x00050041,
4310x00000153,0x00000c41,0x000000f9,0x00000151,
4320x0004003d,0x00000007,0x00000c42,0x00000c41,
4330x00050051,0x00000006,0x00000d08,0x00000c42,
4340x00000000,0x00050095,0x000000a8,0x00000d0a,
4350x00000d08,0x00000c40,0x00050051,0x00000006,
4360x00000d0b,0x00000d0a,0x00000001,0x00050051,
4370x00000006,0x00000d0c,0x00000d0a,0x00000000,
4380x00050051,0x00000006,0x00000d0f,0x00000c42,
4390x00000001,0x00050080,0x00000006,0x00000d11,
4400x00000d0f,0x00000d0b,0x00050050,0x00000007,
4410x00000d12,0x00000d0c,0x00000d11,0x0004007c,
4420x00000014,0x00000d02,0x00000d12,0x00060041,
4430x000000d8,0x00000cf9,0x00000d02,0x000000d7,
4440x000000d7,0x0006003d,0x00000006,0x00000cfa,
4450x00000cf9,0x00000002,0x00000004,0x00050041,
4460x000006d6,0x00000c44,0x00000789,0x00000a0e,
4470x0003003e,0x00000c44,0x00000cfa,0x000200f9,
4480x00000c45,0x000200f8,0x00000c45,0x00050084,
4490x00000006,0x00000c47,0x00000a0b,0x000000fe,
4500x00050080,0x00000006,0x00000c49,0x00000c47,
4510x000000fe,0x00050041,0x000000fb,0x00000c4a,
4520x000000f9,0x000000fa,0x0004003d,0x00000006,
4530x00000c4b,0x00000c4a,0x0007000c,0x00000006,
4540x00000c4c,0x00000001,0x00000026,0x00000c49,
4550x00000c4b,0x000200f9,0x00000c4e,0x000200f8,
4560x00000c4e,0x000700f5,0x00000006,0x00002b33,
4570x00000c47,0x00000c45,0x00000ce3,0x00000ce1,
4580x000500b0,0x0000002f,0x00000c52,0x00002b33,
4590x00000c4c,0x000400f6,0x00000ce4,0x00000ce1,
4600x00000000,0x000400fa,0x00000c52,0x00000c53,
4610x00000ce4,0x000200f8,0x00000c53,0x00050080,
4620x00000006,0x00000c56,0x00002b33,0x00000a0e,
4630x000500b0,0x0000002f,0x00000c59,0x00000c56,
4640x00000c4c,0x000300f7,0x00000c64,0x00000000,
4650x000400fa,0x00000c59,0x00000c5b,0x00000c63,
4660x000200f8,0x00000c5b,0x00050041,0x000000fb,
4670x00000d16,0x000000f9,0x00000305,0x0004003d,
4680x00000006,0x00000d17,0x00000d16,0x000500c7,
4690x00000006,0x00000d18,0x00000d17,0x000000ad,
4700x000500aa,0x0000002f,0x00000d19,0x00000d18,
4710x000000a3,0x000300f7,0x00000d1e,0x00000000,
4720x000400fa,0x00000d19,0x00000d1a,0x00000d1c,
4730x000200f8,0x00000d1a,0x000200f9,0x00000d1e,
4740x000200f8,0x00000d1c,0x00050084,0x00000006,
4750x00000d26,0x0000010e,0x00000c4b,0x00050080,
4760x00000006,0x00000d27,0x00000104,0x00000d26,
4770x000200f9,0x00000d1e,0x000200f8,0x00000d1e,
4780x000700f5,0x00000006,0x00002b34,0x00000104,
4790x00000d1a,0x00000d27,0x00000d1c,0x00050084,
4800x00000006,0x00000c5e,0x00000107,0x00000c56,
4810x00050080,0x00000006,0x00000c5f,0x00002b34,
4820x00000c5e,0x00050041,0x00000153,0x00000c60,
4830x000000f9,0x00000151,0x0004003d,0x00000007,
4840x00000c61,0x00000c60,0x00050051,0x00000006,
4850x00000d3e,0x00000c61,0x00000000,0x00050095,
4860x000000a8,0x00000d40,0x00000d3e,0x00000c5f,
4870x00050051,0x00000006,0x00000d41,0x00000d40,
4880x00000001,0x00050051,0x00000006,0x00000d42,
4890x00000d40,0x00000000,0x00050051,0x00000006,
4900x00000d45,0x00000c61,0x00000001,0x00050080,
4910x00000006,0x00000d47,0x00000d45,0x00000d41,
4920x00050050,0x00000007,0x00000d48,0x00000d42,
4930x00000d47,0x0004007c,0x00000014,0x00000d38,
4940x00000d48,0x00060041,0x000000d8,0x00000d2f,
4950x00000d38,0x000000d7,0x000000d7,0x0006003d,
4960x00000006,0x00000d30,0x00000d2f,0x00000002,
4970x00000004,0x000200f9,0x00000c64,0x000200f8,
4980x00000c63,0x000200f9,0x00000c64,0x000200f8,
4990x00000c64,0x000700f5,0x00000006,0x00002b35,
5000x00000d30,0x00000d1e,0x000000a3,0x00000c63,
5010x000300f7,0x00000c70,0x00000000,0x000400fa,
5020x00000c59,0x00000c67,0x00000c6f,0x000200f8,
5030x00000c67,0x00050041,0x000000fb,0x00000d4c,
5040x000000f9,0x00000305,0x0004003d,0x00000006,
5050x00000d4d,0x00000d4c,0x000500c7,0x00000006,
5060x00000d4e,0x00000d4d,0x000000ad,0x000500aa,
5070x0000002f,0x00000d4f,0x00000d4e,0x000000a3,
5080x000300f7,0x00000d54,0x00000000,0x000400fa,
5090x00000d4f,0x00000d50,0x00000d52,0x000200f8,
5100x00000d50,0x00050084,0x00000006,0x00000d5a,
5110x00000107,0x00000c4b,0x00050080,0x00000006,
5120x00000d5b,0x00000104,0x00000d5a,0x000200f9,
5130x00000d54,0x000200f8,0x00000d52,0x00050084,
5140x00000006,0x00000d60,0x00000115,0x00000c4b,
5150x00050080,0x00000006,0x00000d61,0x00000104,
5160x00000d60,0x000200f9,0x00000d54,0x000200f8,
5170x00000d54,0x000700f5,0x00000006,0x00002b36,
5180x00000d5b,0x00000d50,0x00000d61,0x00000d52,
5190x00050084,0x00000006,0x00000c6a,0x00000107,
5200x00000c56,0x00050080,0x00000006,0x00000c6b,
5210x00002b36,0x00000c6a,0x00050041,0x00000153,
5220x00000c6c,0x000000f9,0x00000151,0x0004003d,
5230x00000007,0x00000c6d,0x00000c6c,0x00050051,
5240x00000006,0x00000d78,0x00000c6d,0x00000000,
5250x00050095,0x000000a8,0x00000d7a,0x00000d78,
5260x00000c6b,0x00050051,0x00000006,0x00000d7b,
5270x00000d7a,0x00000001,0x00050051,0x00000006,
5280x00000d7c,0x00000d7a,0x00000000,0x00050051,
5290x00000006,0x00000d7f,0x00000c6d,0x00000001,
5300x00050080,0x00000006,0x00000d81,0x00000d7f,
5310x00000d7b,0x00050050,0x00000007,0x00000d82,
5320x00000d7c,0x00000d81,0x0004007c,0x00000014,
5330x00000d72,0x00000d82,0x00060041,0x000000d8,
5340x00000d69,0x00000d72,0x000000d7,0x000000d7,
5350x0006003d,0x00000006,0x00000d6a,0x00000d69,
5360x00000002,0x00000004,0x000200f9,0x00000c70,
5370x000200f8,0x00000c6f,0x000200f9,0x00000c70,
5380x000200f8,0x00000c70,0x000700f5,0x00000006,
5390x00002b37,0x00000d6a,0x00000d54,0x000000a3,
5400x00000c6f,0x00050041,0x000000fb,0x00000d86,
5410x000000f9,0x00000305,0x0004003d,0x00000006,
5420x00000d87,0x00000d86,0x00050084,0x00000006,
5430x00000d88,0x00000107,0x00000d87,0x000500c2,
5440x00000006,0x00000d89,0x00002b35,0x00000d88,
5450x000500c7,0x00000006,0x00000d8a,0x00000d89,
5460x000006ca,0x000200f9,0x00000c74,0x000200f8,
5470x00000c74,0x000700f5,0x00000006,0x00002b38,
5480x000000a3,0x00000c70,0x00000c84,0x00000c78,
5490x000500b0,0x0000002f,0x00000c77,0x00002b38,
5500x0000011c,0x000400f6,0x00000c85,0x00000c78,
5510x00000000,0x000400fa,0x00000c77,0x00000c78,
5520x00000c85,0x000200f8,0x00000c78,0x000500aa,
5530x0000002f,0x00000c7e,0x00002b38,0x00000d8a,
5540x000500a7,0x0000002f,0x00000c7f,0x00000c59,
5550x00000c7e,0x000600a9,0x00000006,0x00000c80,
5560x00000c7f,0x000000ad,0x000000a3,0x00060041,
5570x000006d6,0x00000c81,0x000007e2,0x00002b38,
5580x00000a0e,0x0003003e,0x00000c81,0x00000c80,
5590x00050080,0x00000006,0x00000c84,0x00002b38,
5600x00000151,0x000200f9,0x00000c74,0x000200f8,
5610x00000c85,0x000400e0,0x0000016d,0x0000016d,
5620x000006d8,0x000200f9,0x00000c86,0x000200f8,
5630x00000c86,0x000700f5,0x00000006,0x00002b39,
5640x000000ad,0x00000c85,0x00000cb7,0x00000cb5,
5650x000500b0,0x0000002f,0x00000c89,0x00002b39,
5660x00000104,0x000400f6,0x00000cb8,0x00000cb5,
5670x00000000,0x000400fa,0x00000c89,0x00000c8a,
5680x00000cb8,0x000200f8,0x00000c8a,0x000200f9,
5690x00000c8b,0x000200f8,0x00000c8b,0x000700f5,
5700x00000006,0x00002b46,0x000000a3,0x00000c8a,
5710x00000ca1,0x00000c9f,0x000500b0,0x0000002f,
5720x00000c8e,0x00002b46,0x0000011c,0x000400f6,
5730x00000ca2,0x00000c9f,0x00000000,0x000400fa,
5740x00000c8e,0x00000c8f,0x00000ca2,0x000200f8,
5750x00000c8f,0x000500ae,0x0000002f,0x00000c93,
5760x00000a0e,0x00002b39,0x000300f7,0x00000c9c,
5770x00000000,0x000400fa,0x00000c93,0x00000c94,
5780x00000c9b,0x000200f8,0x00000c94,0x00050082,
5790x00000006,0x00000c98,0x00000a0e,0x00002b39,
5800x00060041,0x000006d6,0x00000c99,0x000007e2,
5810x00002b46,0x00000c98,0x0004003d,0x00000006,
5820x00000c9a,0x00000c99,0x000200f9,0x00000c9c,
5830x000200f8,0x00000c9b,0x000200f9,0x00000c9c,
5840x000200f8,0x00000c9c,0x000700f5,0x00000006,
5850x00002b4a,0x00000c9a,0x00000c94,0x000000a3,
5860x00000c9b,0x00050041,0x00000009,0x00000c9e,
5870x00000c2a,0x00002b46,0x0003003e,0x00000c9e,
5880x00002b4a,0x000200f9,0x00000c9f,0x000200f8,
5890x00000c9f,0x00050080,0x00000006,0x00000ca1,
5900x00002b46,0x00000151,0x000200f9,0x00000c8b,
5910x000200f8,0x00000ca2,0x000400e0,0x0000016d,
5920x0000016d,0x000006d8,0x000200f9,0x00000ca3,
5930x000200f8,0x00000ca3,0x000700f5,0x00000006,
5940x00002b47,0x000000a3,0x00000ca2,0x00000cb3,
5950x00000ca7,0x000500b0,0x0000002f,0x00000ca6,
5960x00002b47,0x0000011c,0x000400f6,0x00000cb4,
5970x00000ca7,0x00000000,0x000400fa,0x00000ca6,
5980x00000ca7,0x00000cb4,0x000200f8,0x00000ca7,
5990x00050041,0x00000009,0x00000cab,0x00000c2a,
6000x00002b47,0x0004003d,0x00000006,0x00000cac,
6010x00000cab,0x00060041,0x000006d6,0x00000cad,
6020x000007e2,0x00002b47,0x00000a0e,0x0004003d,
6030x00000006,0x00000cae,0x00000cad,0x00050080,
6040x00000006,0x00000caf,0x00000cae,0x00000cac,
6050x0003003e,0x00000cad,0x00000caf,0x00050080,
6060x00000006,0x00000cb3,0x00002b47,0x00000151,
6070x000200f9,0x00000ca3,0x000200f8,0x00000cb4,
6080x000400e0,0x0000016d,0x0000016d,0x000006d8,
6090x000200f9,0x00000cb5,0x000200f8,0x00000cb5,
6100x000500c4,0x00000006,0x00000cb7,0x00002b39,
6110x00000151,0x000200f9,0x00000c86,0x000200f8,
6120x00000cb8,0x000300f7,0x00000cd4,0x00000000,
6130x000400fa,0x00000c59,0x00000cba,0x00000cd4,
6140x000200f8,0x00000cba,0x00050041,0x000006d6,
6150x00000cbc,0x00000789,0x00000d8a,0x0004003d,
6160x00000006,0x00000cbd,0x00000cbc,0x00060041,
6170x000006d6,0x00000cc0,0x000007e2,0x00000d8a,
6180x00000a0e,0x0004003d,0x00000006,0x00000cc1,
6190x00000cc0,0x00050080,0x00000006,0x00000cc2,
6200x00000cbd,0x00000cc1,0x00050082,0x00000006,
6210x00000cc3,0x00000cc2,0x000000ad,0x000500c7,
6220x00000006,0x00000d90,0x00000d87,0x000000ad,
6230x000500aa,0x0000002f,0x00000d91,0x00000d90,
6240x000000a3,0x000300f7,0x00000d96,0x00000000,
6250x000400fa,0x00000d91,0x00000d92,0x00000d94,
6260x000200f8,0x00000d92,0x00050084,0x00000006,
6270x00000d9c,0x0000010e,0x00000c4b,0x00050080,
6280x00000006,0x00000d9d,0x00000104,0x00000d9c,
6290x000200f9,0x00000d96,0x000200f8,0x00000d94,
6300x000200f9,0x00000d96,0x000200f8,0x00000d96,
6310x000700f5,0x00000006,0x00002b3a,0x00000d9d,
6320x00000d92,0x00000104,0x00000d94,0x00050084,
6330x00000006,0x00000cc6,0x00000107,0x00000cc3,
6340x00050080,0x00000006,0x00000cc7,0x00002b3a,
6350x00000cc6,0x00050041,0x00000153,0x00000cc8,
6360x000000f9,0x00000151,0x0004003d,0x00000007,
6370x00000cc9,0x00000cc8,0x00050051,0x00000006,
6380x00000db5,0x00000cc9,0x00000000,0x00050095,
6390x000000a8,0x00000db7,0x00000db5,0x00000cc7,
6400x00050051,0x00000006,0x00000db8,0x00000db7,
6410x00000001,0x00050051,0x00000006,0x00000db9,
6420x00000db7,0x00000000,0x00050051,0x00000006,
6430x00000dbc,0x00000cc9,0x00000001,0x00050080,
6440x00000006,0x00000dbe,0x00000dbc,0x00000db8,
6450x00050050,0x00000007,0x00000dbf,0x00000db9,
6460x00000dbe,0x0004007c,0x00000014,0x00000daf,
6470x00000dbf,0x00060041,0x000000d8,0x00000da7,
6480x00000daf,0x000000d7,0x000000d7,0x0005003e,
6490x00000da7,0x00002b35,0x00000002,0x00000004,
6500x000300f7,0x00000dcb,0x00000000,0x000400fa,
6510x00000d91,0x00000dc7,0x00000dc9,0x000200f8,
6520x00000dc7,0x00050084,0x00000006,0x00000dd1,
6530x00000115,0x00000c4b,0x00050080,0x00000006,
6540x00000dd2,0x00000104,0x00000dd1,0x000200f9,
6550x00000dcb,0x000200f8,0x00000dc9,0x00050084,
6560x00000006,0x00000dd7,0x00000107,0x00000c4b,
6570x00050080,0x00000006,0x00000dd8,0x00000104,
6580x00000dd7,0x000200f9,0x00000dcb,0x000200f8,
6590x00000dcb,0x000700f5,0x00000006,0x00002b3b,
6600x00000dd2,0x00000dc7,0x00000dd8,0x00000dc9,
6610x00050080,0x00000006,0x00000ccf,0x00002b3b,
6620x00000cc6,0x00050095,0x000000a8,0x00000df0,
6630x00000db5,0x00000ccf,0x00050051,0x00000006,
6640x00000df1,0x00000df0,0x00000001,0x00050051,
6650x00000006,0x00000df2,0x00000df0,0x00000000,
6660x00050080,0x00000006,0x00000df7,0x00000dbc,
6670x00000df1,0x00050050,0x00000007,0x00000df8,
6680x00000df2,0x00000df7,0x0004007c,0x00000014,
6690x00000de8,0x00000df8,0x00060041,0x000000d8,
6700x00000de0,0x00000de8,0x000000d7,0x000000d7,
6710x0005003e,0x00000de0,0x00002b37,0x00000002,
6720x00000004,0x000200f9,0x00000cd4,0x000200f8,
6730x00000cd4,0x000400e0,0x0000016d,0x0000016d,
6740x000006d8,0x000300f7,0x00000ce0,0x00000000,
6750x000400fa,0x00000c36,0x00000cd7,0x00000ce0,
6760x000200f8,0x00000cd7,0x00060041,0x000006d6,
6770x00000cda,0x000007e2,0x00000a0e,0x00000850,
6780x0004003d,0x00000006,0x00000cdb,0x00000cda,
6790x00050041,0x000006d6,0x00000cdc,0x00000789,
6800x00000a0e,0x0004003d,0x00000006,0x00000cdd,
6810x00000cdc,0x00050080,0x00000006,0x00000cde,
6820x00000cdd,0x00000cdb,0x0003003e,0x00000cdc,
6830x00000cde,0x000200f9,0x00000ce0,0x000200f8,
6840x00000ce0,0x000400e0,0x0000016d,0x0000016d,
6850x000006d8,0x000200f9,0x00000ce1,0x000200f8,
6860x00000ce1,0x00050080,0x00000006,0x00000ce3,
6870x00002b33,0x00000104,0x000200f9,0x00000c4e,
6880x000200f8,0x00000ce4,0x000200f9,0x00000a6e,
6890x000200f8,0x00000a08,0x000500aa,0x0000002f,
6900x00000a13,0x000009eb,0x00000236,0x000300f7,
6910x00000a15,0x00000000,0x000400fa,0x00000a13,
6920x00000a14,0x00000a15,0x000200f8,0x00000a14,
6930x000500aa,0x0000002f,0x00000a17,0x000009e9,
6940x000000a3,0x000300f7,0x00000a19,0x00000000,
6950x000400fa,0x00000a17,0x00000a18,0x00000a19,
6960x000200f8,0x00000a18,0x00050041,0x000000fb,
6970x00000e31,0x000000f9,0x00000305,0x0004003d,
6980x00000006,0x00000e32,0x00000e31,0x00050041,
6990x000000fb,0x00000e33,0x000000f9,0x000008bc,
7000x0004003d,0x00000006,0x00000e34,0x00000e33,
7010x00050080,0x00000006,0x00000e36,0x00000e34,
7020x00000e32,0x00050041,0x000000fb,0x00000ec7,
7030x000000f9,0x000000fa,0x0004003d,0x00000006,
7040x00000ec8,0x00000ec7,0x00050084,0x00000006,
7050x00000ec9,0x0000011c,0x00000ec8,0x00050080,
7060x00000006,0x00000eca,0x00000104,0x00000ec9,
7070x00050080,0x00000006,0x00000ed0,0x00000ec8,
7080x00002b67,0x00050086,0x00000006,0x00000ed1,
7090x00000ed0,0x000000fe,0x00050084,0x00000006,
7100x00000ec3,0x00000104,0x00000ed1,0x00050080,
7110x00000006,0x00000ec4,0x00000eca,0x00000ec3,
7120x00050084,0x00000006,0x00000e98,0x0000014d,
7130x00000e36,0x00050080,0x00000006,0x00000e99,
7140x00000ec4,0x00000e98,0x00050041,0x00000153,
7150x00000e9a,0x000000f9,0x00000151,0x0004003d,
7160x00000007,0x00000e9b,0x00000e9a,0x00050051,
7170x00000006,0x00000ee8,0x00000e9b,0x00000000,
7180x00050095,0x000000a8,0x00000eea,0x00000ee8,
7190x00000e99,0x00050051,0x00000006,0x00000eeb,
7200x00000eea,0x00000001,0x00050051,0x00000006,
7210x00000eec,0x00000eea,0x00000000,0x00050051,
7220x00000006,0x00000eef,0x00000e9b,0x00000001,
7230x00050080,0x00000006,0x00000ef1,0x00000eef,
7240x00000eeb,0x00050050,0x00000007,0x00000ef2,
7250x00000eec,0x00000ef1,0x0004007c,0x00000014,
7260x00000ee2,0x00000ef2,0x00060041,0x000000d8,
7270x00000ed9,0x00000ee2,0x000000d7,0x000000d7,
7280x0006003d,0x00000006,0x00000eda,0x00000ed9,
7290x00000002,0x00000004,0x00050080,0x00000006,
7300x00000ea0,0x00000e99,0x00000107,0x00050095,
7310x000000a8,0x00000f0b,0x00000ee8,0x00000ea0,
7320x00050051,0x00000006,0x00000f0c,0x00000f0b,
7330x00000001,0x00050051,0x00000006,0x00000f0d,
7340x00000f0b,0x00000000,0x00050080,0x00000006,
7350x00000f12,0x00000eef,0x00000f0c,0x00050050,
7360x00000007,0x00000f13,0x00000f0d,0x00000f12,
7370x0004007c,0x00000014,0x00000f03,0x00000f13,
7380x00060041,0x000000d8,0x00000efa,0x00000f03,
7390x000000d7,0x000000d7,0x0006003d,0x00000006,
7400x00000efb,0x00000efa,0x00000002,0x00000004,
7410x00050080,0x00000006,0x00000ea6,0x00000e99,
7420x0000010e,0x00050095,0x000000a8,0x00000f2c,
7430x00000ee8,0x00000ea6,0x00050051,0x00000006,
7440x00000f2d,0x00000f2c,0x00000001,0x00050051,
7450x00000006,0x00000f2e,0x00000f2c,0x00000000,
7460x00050080,0x00000006,0x00000f33,0x00000eef,
7470x00000f2d,0x00050050,0x00000007,0x00000f34,
7480x00000f2e,0x00000f33,0x0004007c,0x00000014,
7490x00000f24,0x00000f34,0x00060041,0x000000d8,
7500x00000f1b,0x00000f24,0x000000d7,0x000000d7,
7510x0006003d,0x00000006,0x00000f1c,0x00000f1b,
7520x00000002,0x00000004,0x00050080,0x00000006,
7530x00000ead,0x00000e99,0x00000115,0x00050095,
7540x000000a8,0x00000f4d,0x00000ee8,0x00000ead,
7550x00050051,0x00000006,0x00000f4e,0x00000f4d,
7560x00000001,0x00050051,0x00000006,0x00000f4f,
7570x00000f4d,0x00000000,0x00050080,0x00000006,
7580x00000f54,0x00000eef,0x00000f4e,0x00050050,
7590x00000007,0x00000f55,0x00000f4f,0x00000f54,
7600x0004007c,0x00000014,0x00000f45,0x00000f55,
7610x00060041,0x000000d8,0x00000f3c,0x00000f45,
7620x000000d7,0x000000d7,0x0006003d,0x00000006,
7630x00000f3d,0x00000f3c,0x00000002,0x00000004,
7640x00050080,0x00000006,0x00000eb3,0x00000e99,
7650x0000011c,0x00050095,0x000000a8,0x00000f6e,
7660x00000ee8,0x00000eb3,0x00050051,0x00000006,
7670x00000f6f,0x00000f6e,0x00000001,0x00050051,
7680x00000006,0x00000f70,0x00000f6e,0x00000000,
7690x00050080,0x00000006,0x00000f75,0x00000eef,
7700x00000f6f,0x00050050,0x00000007,0x00000f76,
7710x00000f70,0x00000f75,0x0004007c,0x00000014,
7720x00000f66,0x00000f76,0x00060041,0x000000d8,
7730x00000f5d,0x00000f66,0x000000d7,0x000000d7,
7740x0006003d,0x00000006,0x00000f5e,0x00000f5d,
7750x00000002,0x00000004,0x00050080,0x00000006,
7760x00000eb9,0x00000e99,0x00000186,0x00050095,
7770x000000a8,0x00000f8f,0x00000ee8,0x00000eb9,
7780x00050051,0x00000006,0x00000f90,0x00000f8f,
7790x00000001,0x00050051,0x00000006,0x00000f91,
7800x00000f8f,0x00000000,0x00050080,0x00000006,
7810x00000f96,0x00000eef,0x00000f90,0x00050050,
7820x00000007,0x00000f97,0x00000f91,0x00000f96,
7830x0004007c,0x00000014,0x00000f87,0x00000f97,
7840x00060041,0x000000d8,0x00000f7e,0x00000f87,
7850x000000d7,0x000000d7,0x0006003d,0x00000006,
7860x00000f7f,0x00000f7e,0x00000002,0x00000004,
7870x00050041,0x000000fb,0x00000e3a,0x000000f9,
7880x00000221,0x0004003d,0x00000006,0x00000e3b,
7890x00000e3a,0x000500ab,0x0000002f,0x00000e3c,
7900x00000e3b,0x000000a3,0x000600a9,0x00000006,
7910x00000e3d,0x00000e3c,0x000000a3,0x0000012d,
7920x000500c5,0x00000006,0x00000e3e,0x00000e3d,
7930x00000236,0x00050041,0x00000153,0x00000e3f,
7940x000000f9,0x000000d7,0x0004003d,0x00000007,
7950x00000e40,0x00000e3f,0x00050051,0x00000006,
7960x00000fad,0x00000e40,0x00000000,0x00050095,
7970x000000a8,0x00000faf,0x00000fad,0x000000a3,
7980x00050051,0x00000006,0x00000fb0,0x00000faf,
7990x00000001,0x00050051,0x00000006,0x00000fb1,
8000x00000faf,0x00000000,0x00050051,0x00000006,
8010x00000fb4,0x00000e40,0x00000001,0x00050080,
8020x00000006,0x00000fb6,0x00000fb4,0x00000fb0,
8030x00050050,0x00000007,0x00000fb7,0x00000fb1,
8040x00000fb6,0x0004007c,0x00000014,0x00000fa7,
8050x00000fb7,0x00060041,0x000000d8,0x00000f9f,
8060x00000fa7,0x000000d7,0x000000d7,0x0005003e,
8070x00000f9f,0x00000e3e,0x00000002,0x00000004,
8080x00050041,0x000000fb,0x00000e42,0x000000f9,
8090x0000096f,0x0004003d,0x00000006,0x00000e43,
8100x00000e42,0x00050086,0x00000006,0x00000e44,
8110x00000e43,0x00000104,0x00050095,0x000000a8,
8120x00000fcf,0x00000fad,0x00000107,0x00050051,
8130x00000006,0x00000fd0,0x00000fcf,0x00000001,
8140x00050051,0x00000006,0x00000fd1,0x00000fcf,
8150x00000000,0x00050080,0x00000006,0x00000fd6,
8160x00000fb4,0x00000fd0,0x00050050,0x00000007,
8170x00000fd7,0x00000fd1,0x00000fd6,0x0004007c,
8180x00000014,0x00000fc7,0x00000fd7,0x00060041,
8190x000000d8,0x00000fbf,0x00000fc7,0x000000d7,
8200x000000d7,0x0005003e,0x00000fbf,0x00000e44,
8210x00000002,0x00000004,0x00050095,0x000000a8,
8220x00000fef,0x00000fad,0x0000010e,0x00050051,
8230x00000006,0x00000ff0,0x00000fef,0x00000001,
8240x00050051,0x00000006,0x00000ff1,0x00000fef,
8250x00000000,0x00050080,0x00000006,0x00000ff6,
8260x00000fb4,0x00000ff0,0x00050050,0x00000007,
8270x00000ff7,0x00000ff1,0x00000ff6,0x0004007c,
8280x00000014,0x00000fe7,0x00000ff7,0x00060041,
8290x000000d8,0x00000fdf,0x00000fe7,0x000000d7,
8300x000000d7,0x0005003e,0x00000fdf,0x000000a3,
8310x00000002,0x00000004,0x00050095,0x000000a8,
8320x0000100f,0x00000fad,0x00000115,0x00050051,
8330x00000006,0x00001010,0x0000100f,0x00000001,
8340x00050051,0x00000006,0x00001011,0x0000100f,
8350x00000000,0x00050080,0x00000006,0x00001016,
8360x00000fb4,0x00001010,0x00050050,0x00000007,
8370x00001017,0x00001011,0x00001016,0x0004007c,
8380x00000014,0x00001007,0x00001017,0x00060041,
8390x000000d8,0x00000fff,0x00001007,0x000000d7,
8400x000000d7,0x0005003e,0x00000fff,0x00000e34,
8410x00000002,0x00000004,0x00050095,0x000000a8,
8420x00001038,0x00000fad,0x0000011c,0x00050051,
8430x00000006,0x00001039,0x00001038,0x00000001,
8440x00050051,0x00000006,0x0000103a,0x00001038,
8450x00000000,0x00050080,0x00000006,0x0000103f,
8460x00000fb4,0x00001039,0x00050050,0x00000007,
8470x00001040,0x0000103a,0x0000103f,0x0004007c,
8480x00000014,0x00001030,0x00001040,0x00060041,
8490x000000d8,0x00001028,0x00001030,0x000000d7,
8500x000000d7,0x0005003e,0x00001028,0x00000eda,
8510x00000002,0x00000004,0x00050095,0x000000a8,
8520x00001061,0x00000fad,0x00000186,0x00050051,
8530x00000006,0x00001062,0x00001061,0x00000001,
8540x00050051,0x00000006,0x00001063,0x00001061,
8550x00000000,0x00050080,0x00000006,0x00001068,
8560x00000fb4,0x00001062,0x00050050,0x00000007,
8570x00001069,0x00001063,0x00001068,0x0004007c,
8580x00000014,0x00001059,0x00001069,0x00060041,
8590x000000d8,0x00001051,0x00001059,0x000000d7,
8600x000000d7,0x0005003e,0x00001051,0x00000efb,
8610x00000002,0x00000004,0x00050095,0x000000a8,
8620x0000108a,0x00000fad,0x0000014d,0x00050051,
8630x00000006,0x0000108b,0x0000108a,0x00000001,
8640x00050051,0x00000006,0x0000108c,0x0000108a,
8650x00000000,0x00050080,0x00000006,0x00001091,
8660x00000fb4,0x0000108b,0x00050050,0x00000007,
8670x00001092,0x0000108c,0x00001091,0x0004007c,
8680x00000014,0x00001082,0x00001092,0x00060041,
8690x000000d8,0x0000107a,0x00001082,0x000000d7,
8700x000000d7,0x0005003e,0x0000107a,0x00000f1c,
8710x00000002,0x00000004,0x00050095,0x000000a8,
8720x000010b3,0x00000fad,0x00000460,0x00050051,
8730x00000006,0x000010b4,0x000010b3,0x00000001,
8740x00050051,0x00000006,0x000010b5,0x000010b3,
8750x00000000,0x00050080,0x00000006,0x000010ba,
8760x00000fb4,0x000010b4,0x00050050,0x00000007,
8770x000010bb,0x000010b5,0x000010ba,0x0004007c,
8780x00000014,0x000010ab,0x000010bb,0x00060041,
8790x000000d8,0x000010a3,0x000010ab,0x000000d7,
8800x000000d7,0x0005003e,0x000010a3,0x00000f3d,
8810x00000002,0x00000004,0x00050095,0x000000a8,
8820x000010dc,0x00000fad,0x00000466,0x00050051,
8830x00000006,0x000010dd,0x000010dc,0x00000001,
8840x00050051,0x00000006,0x000010de,0x000010dc,
8850x00000000,0x00050080,0x00000006,0x000010e3,
8860x00000fb4,0x000010dd,0x00050050,0x00000007,
8870x000010e4,0x000010de,0x000010e3,0x0004007c,
8880x00000014,0x000010d4,0x000010e4,0x00060041,
8890x000000d8,0x000010cc,0x000010d4,0x000000d7,
8900x000000d7,0x0005003e,0x000010cc,0x00000f5e,
8910x00000002,0x00000004,0x00050095,0x000000a8,
8920x00001105,0x00000fad,0x00000344,0x00050051,
8930x00000006,0x00001106,0x00001105,0x00000001,
8940x00050051,0x00000006,0x00001107,0x00001105,
8950x00000000,0x00050080,0x00000006,0x0000110c,
8960x00000fb4,0x00001106,0x00050050,0x00000007,
8970x0000110d,0x00001107,0x0000110c,0x0004007c,
8980x00000014,0x000010fd,0x0000110d,0x00060041,
8990x000000d8,0x000010f5,0x000010fd,0x000000d7,
9000x000000d7,0x0005003e,0x000010f5,0x00000f7f,
9010x00000002,0x00000004,0x00050041,0x000000fb,
9020x00000e70,0x000000f9,0x0000023b,0x0004003d,
9030x00000006,0x00000e71,0x00000e70,0x00050095,
9040x000000a8,0x00001125,0x00000fad,0x0000034f,
9050x00050051,0x00000006,0x00001126,0x00001125,
9060x00000001,0x00050051,0x00000006,0x00001127,
9070x00001125,0x00000000,0x00050080,0x00000006,
9080x0000112c,0x00000fb4,0x00001126,0x00050050,
9090x00000007,0x0000112d,0x00001127,0x0000112c,
9100x0004007c,0x00000014,0x0000111d,0x0000112d,
9110x00060041,0x000000d8,0x00001115,0x0000111d,
9120x000000d7,0x000000d7,0x0005003e,0x00001115,
9130x00000e71,0x00000002,0x00000004,0x00050095,
9140x000000a8,0x00001145,0x00000fad,0x0000035a,
9150x00050051,0x00000006,0x00001146,0x00001145,
9160x00000001,0x00050051,0x00000006,0x00001147,
9170x00001145,0x00000000,0x00050080,0x00000006,
9180x0000114c,0x00000fb4,0x00001146,0x00050050,
9190x00000007,0x0000114d,0x00001147,0x0000114c,
9200x0004007c,0x00000014,0x0000113d,0x0000114d,
9210x00060041,0x000000d8,0x00001135,0x0000113d,
9220x000000d7,0x000000d7,0x0005003e,0x00001135,
9230x000000a3,0x00000002,0x00000004,0x00050084,
9240x00000006,0x00001153,0x00000e32,0x00000225,
9250x00050080,0x00000006,0x00001154,0x00000e71,
9260x00001153,0x000500c2,0x00000006,0x00001155,
9270x00001154,0x00000230,0x000500c4,0x00000006,
9280x00001156,0x00001155,0x0000020a,0x000500c5,
9290x00000006,0x00001157,0x00001156,0x00000243,
9300x00050095,0x000000a8,0x0000116f,0x00000fad,
9310x00000365,0x00050051,0x00000006,0x00001170,
9320x0000116f,0x00000001,0x00050051,0x00000006,
9330x00001171,0x0000116f,0x00000000,0x00050080,
9340x00000006,0x00001176,0x00000fb4,0x00001170,
9350x00050050,0x00000007,0x00001177,0x00001171,
9360x00001176,0x0004007c,0x00000014,0x00001167,
9370x00001177,0x00060041,0x000000d8,0x0000115f,
9380x00001167,0x000000d7,0x000000d7,0x0005003e,
9390x0000115f,0x00001157,0x00000002,0x00000004,
9400x00050041,0x000000fb,0x00000e7d,0x000000f9,
9410x00000229,0x0004003d,0x00000006,0x00000e7e,
9420x00000e7d,0x00050095,0x000000a8,0x0000118f,
9430x00000fad,0x00000371,0x00050051,0x00000006,
9440x00001190,0x0000118f,0x00000001,0x00050051,
9450x00000006,0x00001191,0x0000118f,0x00000000,
9460x00050080,0x00000006,0x00001196,0x00000fb4,
9470x00001190,0x00050050,0x00000007,0x00001197,
9480x00001191,0x00001196,0x0004007c,0x00000014,
9490x00001187,0x00001197,0x00060041,0x000000d8,
9500x0000117f,0x00001187,0x000000d7,0x000000d7,
9510x0005003e,0x0000117f,0x00000e7e,0x00000002,
9520x00000004,0x00050041,0x000000fb,0x00000e82,
9530x000000f9,0x000008c7,0x0004003d,0x00000006,
9540x00000e83,0x00000e82,0x00050095,0x000000a8,
9550x000011af,0x00000fad,0x0000037b,0x00050051,
9560x00000006,0x000011b0,0x000011af,0x00000001,
9570x00050051,0x00000006,0x000011b1,0x000011af,
9580x00000000,0x00050080,0x00000006,0x000011b6,
9590x00000fb4,0x000011b0,0x00050050,0x00000007,
9600x000011b7,0x000011b1,0x000011b6,0x0004007c,
9610x00000014,0x000011a7,0x000011b7,0x00060041,
9620x000000d8,0x0000119f,0x000011a7,0x000000d7,
9630x000000d7,0x0005003e,0x0000119f,0x00000e83,
9640x00000002,0x00000004,0x00050095,0x000000a8,
9650x000011cf,0x00000fad,0x00000385,0x00050051,
9660x00000006,0x000011d0,0x000011cf,0x00000001,
9670x00050051,0x00000006,0x000011d1,0x000011cf,
9680x00000000,0x00050080,0x00000006,0x000011d6,
9690x00000fb4,0x000011d0,0x00050050,0x00000007,
9700x000011d7,0x000011d1,0x000011d6,0x0004007c,
9710x00000014,0x000011c7,0x000011d7,0x00060041,
9720x000000d8,0x000011bf,0x000011c7,0x000000d7,
9730x000000d7,0x0005003e,0x000011bf,0x000000a3,
9740x00000002,0x00000004,0x000200f9,0x00000a19,
9750x000200f8,0x00000a19,0x000200f9,0x00000a6e,
9760x000200f8,0x00000a15,0x00050041,0x000000fb,
9770x00000a1d,0x000000f9,0x000004d5,0x0004003d,
9780x00000006,0x00000a1e,0x00000a1d,0x000500ae,
9790x0000002f,0x00000a1f,0x000009e9,0x00000a1e,
9800x000300f7,0x00000a21,0x00000000,0x000400fa,
9810x00000a1f,0x00000a20,0x00000a21,0x000200f8,
9820x00000a20,0x000200f9,0x00000a6e,0x000200f8,
9830x00000a21,0x000500aa,0x0000002f,0x00000a25,
9840x000009eb,0x000000a3,0x000300f7,0x00000a27,
9850x00000000,0x000400fa,0x00000a25,0x00000a26,
9860x00000a48,0x000200f8,0x00000a26,0x00050041,
9870x000000fb,0x00000a28,0x000000f9,0x000008c7,
9880x0004003d,0x00000006,0x00000a29,0x00000a28,
9890x00050084,0x00000006,0x00000a2b,0x00000107,
9900x000009e9,0x00050080,0x00000006,0x00000a2c,
9910x00000a29,0x00000a2b,0x00050041,0x00000153,
9920x00000a2e,0x000000f9,0x000000d7,0x0004003d,
9930x00000007,0x00000a2f,0x00000a2e,0x00050051,
9940x00000006,0x000011ed,0x00000a2f,0x00000000,
9950x00050095,0x000000a8,0x000011ef,0x000011ed,
9960x00000a2c,0x00050051,0x00000006,0x000011f0,
9970x000011ef,0x00000001,0x00050051,0x00000006,
9980x000011f1,0x000011ef,0x00000000,0x00050051,
9990x00000006,0x000011f4,0x00000a2f,0x00000001,
10000x00050080,0x00000006,0x000011f6,0x000011f4,
10010x000011f0,0x00050050,0x00000007,0x000011f7,
10020x000011f1,0x000011f6,0x0004007c,0x00000014,
10030x000011e7,0x000011f7,0x00060041,0x000000d8,
10040x000011df,0x000011e7,0x000000d7,0x000000d7,
10050x0005003e,0x000011df,0x0000037d,0x00000002,
10060x00000004,0x000500b0,0x0000002f,0x00000a34,
10070x000009e9,0x000002b4,0x000300f7,0x00000a36,
10080x00000000,0x000400fa,0x00000a34,0x00000a35,
10090x00000a36,0x000200f8,0x00000a35,0x00050041,
10100x00000153,0x00000a3a,0x000000f9,0x00000151,
10110x0004003d,0x00000007,0x00000a3b,0x00000a3a,
10120x00050051,0x00000006,0x0000120d,0x00000a3b,
10130x00000000,0x00050095,0x000000a8,0x0000120f,
10140x0000120d,0x00000a2b,0x00050051,0x00000006,
10150x00001210,0x0000120f,0x00000001,0x00050051,
10160x00000006,0x00001211,0x0000120f,0x00000000,
10170x00050051,0x00000006,0x00001214,0x00000a3b,
10180x00000001,0x00050080,0x00000006,0x00001216,
10190x00001214,0x00001210,0x00050050,0x00000007,
10200x00001217,0x00001211,0x00001216,0x0004007c,
10210x00000014,0x00001207,0x00001217,0x00060041,
10220x000000d8,0x000011ff,0x00001207,0x000000d7,
10230x000000d7,0x0005003e,0x000011ff,0x0000037d,
10240x00000002,0x00000004,0x00050080,0x00000006, 8890x00000002,0x00000004,0x00050080,0x00000006,
10250x00000a41,0x00000115,0x00000a2b,0x00050095, 8900x00001042,0x00003254,0x00000107,0x000200f9,
10260x000000a8,0x0000122f,0x0000120d,0x00000a41, 8910x00001026,0x000200f8,0x00001043,0x000200f9,
10270x00050051,0x00000006,0x00001230,0x0000122f, 8920x00000bf3,0x000200f8,0x00000b3d,0x000500aa,
10280x00000001,0x00050051,0x00000006,0x00001231, 8930x0000002f,0x00000b45,0x00000b13,0x00000239,
10290x0000122f,0x00000000,0x00050080,0x00000006, 8940x000300f7,0x00000b47,0x00000000,0x000400fa,
10300x00001236,0x00001214,0x00001230,0x00050050, 8950x00000b45,0x00000b46,0x00000b47,0x000200f8,
10310x00000007,0x00001237,0x00001231,0x00001236, 8960x00000b46,0x000500aa,0x0000002f,0x00000b49,
10320x0004007c,0x00000014,0x00001227,0x00001237, 8970x00000b11,0x000000a6,0x000300f7,0x00000b4b,
10330x00060041,0x000000d8,0x0000121f,0x00001227, 8980x00000000,0x000400fa,0x00000b49,0x00000b4a,
10340x000000d7,0x000000d7,0x0005003e,0x0000121f, 8990x00000b4b,0x000200f8,0x00000b4a,0x00050041,
10350x000000a3,0x00000002,0x00000004,0x000200f9, 9000x000000fe,0x0000110e,0x000000fc,0x00000308,
10360x00000a36,0x000200f8,0x00000a36,0x000200f9, 9010x0004003d,0x00000006,0x0000110f,0x0000110e,
10370x00000a27,0x000200f8,0x00000a48,0x000500aa, 9020x00050041,0x000000fe,0x00001110,0x000000fc,
10380x0000002f,0x00000a4b,0x000009eb,0x000000ad, 9030x0000096c,0x0004003d,0x00000006,0x00001111,
10390x000300f7,0x00000a4d,0x00000000,0x000400fa, 9040x00001110,0x00050080,0x00000006,0x00001113,
10400x00000a4b,0x00000a4c,0x00000a51,0x000200f8, 9050x00001111,0x0000110f,0x00050041,0x000000fe,
10410x00000a4c,0x000200f9,0x00001267,0x000200f8, 9060x000011a4,0x000000fc,0x000000fd,0x0004003d,
10420x00001267,0x000700f5,0x00000006,0x00002b1e, 9070x00000006,0x000011a5,0x000011a4,0x00050084,
10430x000000a3,0x00000a4c,0x00001277,0x00001275, 9080x00000006,0x000011a6,0x0000011f,0x000011a5,
10440x000500b0,0x0000002f,0x0000126a,0x00002b1e, 9090x00050080,0x00000006,0x000011a7,0x00000107,
10450x000002b4,0x000400f6,0x00001278,0x00001275, 9100x000011a6,0x00050080,0x00000006,0x000011ad,
10460x00000000,0x000400fa,0x0000126a,0x0000126b, 9110x000011a5,0x000032a8,0x00050086,0x00000006,
10470x00001278,0x000200f8,0x0000126b,0x00050084, 9120x000011ae,0x000011ad,0x00000101,0x00050084,
10480x00000006,0x0000126e,0x000002b4,0x000009e9, 9130x00000006,0x000011a0,0x00000107,0x000011ae,
10490x00050080,0x00000006,0x00001270,0x0000126e, 9140x00050080,0x00000006,0x000011a1,0x000011a7,
10500x00002b1e,0x000300f7,0x00001335,0x00000000, 9150x000011a0,0x00050084,0x00000006,0x00001175,
10510x000300fb,0x000000a3,0x00001313,0x000200f8, 9160x00000150,0x00001113,0x00050080,0x00000006,
10520x00001313,0x00050041,0x000000fb,0x00001314, 9170x00001176,0x000011a1,0x00001175,0x00050041,
10530x000000f9,0x00000278,0x0004003d,0x00000006, 9180x00000156,0x00001177,0x000000fc,0x00000154,
10540x00001315,0x00001314,0x000500aa,0x0000002f, 9190x0004003d,0x00000007,0x00001178,0x00001177,
10550x00001316,0x00001315,0x000000a3,0x000300f7, 9200x00050051,0x00000006,0x000011c5,0x00001178,
10560x00001319,0x00000000,0x000400fa,0x00001316, 9210x00000000,0x00050095,0x000000ab,0x000011c7,
10570x00001317,0x00001319,0x000200f8,0x00001317, 9220x000011c5,0x00001176,0x00050051,0x00000006,
10580x000200f9,0x00001335,0x000200f8,0x00001319, 9230x000011c8,0x000011c7,0x00000001,0x00050051,
10590x000500aa,0x0000002f,0x0000131c,0x00001315, 9240x00000006,0x000011c9,0x000011c7,0x00000000,
10600x0000016d,0x000300f7,0x00001323,0x00000000, 9250x00050051,0x00000006,0x000011cc,0x00001178,
10610x000400fa,0x0000131c,0x0000131d,0x00001323, 9260x00000001,0x00050080,0x00000006,0x000011ce,
10620x000200f8,0x0000131d,0x00050084,0x00000006, 9270x000011cc,0x000011c8,0x00050050,0x00000007,
10630x0000131f,0x00000107,0x00001270,0x00050041, 9280x000011cf,0x000011c9,0x000011ce,0x0004007c,
10640x00000153,0x00001320,0x000000f9,0x0000020a, 9290x00000014,0x000011bf,0x000011cf,0x00060041,
10650x0004003d,0x00000007,0x00001321,0x00001320, 9300x000000db,0x000011b6,0x000011bf,0x000000da,
10660x00050051,0x00000006,0x0000134d,0x00001321, 9310x000000da,0x0006003d,0x00000006,0x000011b7,
10670x00000000,0x00050095,0x000000a8,0x0000134f, 9320x000011b6,0x00000002,0x00000004,0x00050080,
10680x0000134d,0x0000131f,0x00050051,0x00000006, 9330x00000006,0x0000117d,0x00001176,0x0000010a,
10690x00001350,0x0000134f,0x00000001,0x00050051, 9340x00050095,0x000000ab,0x000011e8,0x000011c5,
10700x00000006,0x00001351,0x0000134f,0x00000000, 9350x0000117d,0x00050051,0x00000006,0x000011e9,
10710x00050051,0x00000006,0x00001354,0x00001321, 9360x000011e8,0x00000001,0x00050051,0x00000006,
10720x00000001,0x00050080,0x00000006,0x00001356, 9370x000011ea,0x000011e8,0x00000000,0x00050080,
10730x00001354,0x00001350,0x00050050,0x00000007, 9380x00000006,0x000011ef,0x000011cc,0x000011e9,
10740x00001357,0x00001351,0x00001356,0x0004007c, 9390x00050050,0x00000007,0x000011f0,0x000011ea,
10750x00000014,0x00001347,0x00001357,0x00060041, 9400x000011ef,0x0004007c,0x00000014,0x000011e0,
10760x000000d8,0x0000133e,0x00001347,0x000000d7, 9410x000011f0,0x00060041,0x000000db,0x000011d7,
10770x000000d7,0x0006003d,0x00000006,0x0000133f, 9420x000011e0,0x000000da,0x000000da,0x0006003d,
10780x0000133e,0x00000002,0x00000004,0x000200f9, 9430x00000006,0x000011d8,0x000011d7,0x00000002,
10790x00001335,0x000200f8,0x00001323,0x000500c2, 9440x00000004,0x00050080,0x00000006,0x00001183,
10800x00000006,0x00001325,0x00001270,0x00000151, 9450x00001176,0x00000111,0x00050095,0x000000ab,
10810x00050084,0x00000006,0x00001326,0x00000107, 9460x00001209,0x000011c5,0x00001183,0x00050051,
10820x00001325,0x00050041,0x00000153,0x00001327, 9470x00000006,0x0000120a,0x00001209,0x00000001,
10830x000000f9,0x0000020a,0x0004003d,0x00000007, 9480x00050051,0x00000006,0x0000120b,0x00001209,
10840x00001328,0x00001327,0x00050051,0x00000006, 9490x00000000,0x00050080,0x00000006,0x00001210,
10850x0000136e,0x00001328,0x00000000,0x00050095, 9500x000011cc,0x0000120a,0x00050050,0x00000007,
10860x000000a8,0x00001370,0x0000136e,0x00001326, 9510x00001211,0x0000120b,0x00001210,0x0004007c,
10870x00050051,0x00000006,0x00001371,0x00001370, 9520x00000014,0x00001201,0x00001211,0x00060041,
10880x00000001,0x00050051,0x00000006,0x00001372, 9530x000000db,0x000011f8,0x00001201,0x000000da,
10890x00001370,0x00000000,0x00050051,0x00000006, 9540x000000da,0x0006003d,0x00000006,0x000011f9,
10900x00001375,0x00001328,0x00000001,0x00050080, 9550x000011f8,0x00000002,0x00000004,0x00050080,
10910x00000006,0x00001377,0x00001375,0x00001371, 9560x00000006,0x0000118a,0x00001176,0x00000118,
10920x00050050,0x00000007,0x00001378,0x00001372, 9570x00050095,0x000000ab,0x0000122a,0x000011c5,
10930x00001377,0x0004007c,0x00000014,0x00001368, 9580x0000118a,0x00050051,0x00000006,0x0000122b,
10940x00001378,0x00060041,0x000000d8,0x0000135f, 9590x0000122a,0x00000001,0x00050051,0x00000006,
10950x00001368,0x000000d7,0x000000d7,0x0006003d, 9600x0000122c,0x0000122a,0x00000000,0x00050080,
10960x00000006,0x00001360,0x0000135f,0x00000002, 9610x00000006,0x00001231,0x000011cc,0x0000122b,
10970x00000004,0x000500c7,0x00000006,0x0000132b, 9620x00050050,0x00000007,0x00001232,0x0000122c,
10980x00001270,0x000000ad,0x000500ab,0x0000002f, 9630x00001231,0x0004007c,0x00000014,0x00001222,
10990x0000132c,0x0000132b,0x000000a3,0x000300f7, 9640x00001232,0x00060041,0x000000db,0x00001219,
11000x00001333,0x00000000,0x000400fa,0x0000132c, 9650x00001222,0x000000da,0x000000da,0x0006003d,
11010x0000132d,0x00001330,0x000200f8,0x0000132d, 9660x00000006,0x0000121a,0x00001219,0x00000002,
11020x000500c2,0x00000006,0x0000132f,0x00001360, 9670x00000004,0x00050080,0x00000006,0x00001190,
11030x0000023b,0x000200f9,0x00001333,0x000200f8, 9680x00001176,0x0000011f,0x00050095,0x000000ab,
11040x00001330,0x000500c7,0x00000006,0x00001332, 9690x0000124b,0x000011c5,0x00001190,0x00050051,
11050x00001360,0x000002a0,0x000200f9,0x00001333, 9700x00000006,0x0000124c,0x0000124b,0x00000001,
11060x000200f8,0x00001333,0x000700f5,0x00000006, 9710x00050051,0x00000006,0x0000124d,0x0000124b,
11070x00002b28,0x0000132f,0x0000132d,0x00001332, 9720x00000000,0x00050080,0x00000006,0x00001252,
11080x00001330,0x000200f9,0x00001335,0x000200f8, 9730x000011cc,0x0000124c,0x00050050,0x00000007,
11090x00001335,0x000900f5,0x00000006,0x00002b29, 9740x00001253,0x0000124d,0x00001252,0x0004007c,
11100x00001270,0x00001317,0x0000133f,0x0000131d, 9750x00000014,0x00001243,0x00001253,0x00060041,
11110x00002b28,0x00001333,0x00050041,0x000000fb, 9760x000000db,0x0000123a,0x00001243,0x000000da,
11120x00001389,0x000000f9,0x0000024d,0x0004003d, 9770x000000da,0x0006003d,0x00000006,0x0000123b,
11130x00000006,0x0000138a,0x00001389,0x00050084, 9780x0000123a,0x00000002,0x00000004,0x00050080,
11140x00000006,0x0000138b,0x00002b29,0x0000138a, 9790x00000006,0x00001196,0x00001176,0x00000189,
11150x00050041,0x00000153,0x0000138c,0x000000f9, 9800x00050095,0x000000ab,0x0000126c,0x000011c5,
11160x00000202,0x0004003d,0x00000007,0x0000138d, 9810x00001196,0x00050051,0x00000006,0x0000126d,
11170x0000138c,0x00050051,0x00000006,0x000013a8, 9820x0000126c,0x00000001,0x00050051,0x00000006,
11180x0000138d,0x00000000,0x00050095,0x000000a8, 9830x0000126e,0x0000126c,0x00000000,0x00050080,
11190x000013aa,0x000013a8,0x0000138b,0x00050051, 9840x00000006,0x00001273,0x000011cc,0x0000126d,
11200x00000006,0x000013ab,0x000013aa,0x00000001, 9850x00050050,0x00000007,0x00001274,0x0000126e,
11210x00050051,0x00000006,0x000013ac,0x000013aa, 9860x00001273,0x0004007c,0x00000014,0x00001264,
11220x00000000,0x00050051,0x00000006,0x000013af, 9870x00001274,0x00060041,0x000000db,0x0000125b,
11230x0000138d,0x00000001,0x00050080,0x00000006, 9880x00001264,0x000000da,0x000000da,0x0006003d,
11240x000013b1,0x000013af,0x000013ab,0x00050095, 9890x00000006,0x0000125c,0x0000125b,0x00000002,
11250x000000a8,0x000013cb,0x000013ac,0x000000a3, 9900x00000004,0x00050041,0x000000fe,0x00001117,
11260x00050051,0x00000006,0x000013cc,0x000013cb, 9910x000000fc,0x00000224,0x0004003d,0x00000006,
11270x00000001,0x00050051,0x00000006,0x000013cd, 9920x00001118,0x00001117,0x000500ab,0x0000002f,
11280x000013cb,0x00000000,0x00050080,0x00000006, 9930x00001119,0x00001118,0x000000a6,0x000600a9,
11290x000013d2,0x000013b1,0x000013cc,0x00050050, 9940x00000006,0x0000111a,0x00001119,0x000000a6,
11300x00000007,0x000013d3,0x000013cd,0x000013d2, 9950x00000130,0x000500c5,0x00000006,0x0000111b,
11310x0004007c,0x00000014,0x000013c3,0x000013d3, 9960x0000111a,0x00000239,0x00050041,0x00000156,
11320x00060041,0x000000d8,0x000013ba,0x000013c3, 9970x0000111c,0x000000fc,0x000000da,0x0004003d,
11330x000000d7,0x000000d7,0x0006003d,0x00000006, 9980x00000007,0x0000111d,0x0000111c,0x00050051,
11340x000013bb,0x000013ba,0x00000002,0x00000004, 9990x00000006,0x0000128a,0x0000111d,0x00000000,
11350x0004007c,0x00000027,0x00001391,0x000013bb, 10000x00050095,0x000000ab,0x0000128c,0x0000128a,
11360x00050095,0x000000a8,0x000013ec,0x000013ac, 10010x000000a6,0x00050051,0x00000006,0x0000128d,
11370x00000107,0x00050051,0x00000006,0x000013ed, 10020x0000128c,0x00000001,0x00050051,0x00000006,
11380x000013ec,0x00000001,0x00050051,0x00000006, 10030x0000128e,0x0000128c,0x00000000,0x00050051,
11390x000013ee,0x000013ec,0x00000000,0x00050080, 10040x00000006,0x00001291,0x0000111d,0x00000001,
11400x00000006,0x000013f3,0x000013b1,0x000013ed, 10050x00050080,0x00000006,0x00001293,0x00001291,
11410x00050050,0x00000007,0x000013f4,0x000013ee, 10060x0000128d,0x00050050,0x00000007,0x00001294,
11420x000013f3,0x0004007c,0x00000014,0x000013e4, 10070x0000128e,0x00001293,0x0004007c,0x00000014,
11430x000013f4,0x00060041,0x000000d8,0x000013db, 10080x00001284,0x00001294,0x00060041,0x000000db,
11440x000013e4,0x000000d7,0x000000d7,0x0006003d, 10090x0000127c,0x00001284,0x000000da,0x000000da,
11450x00000006,0x000013dc,0x000013db,0x00000002, 10100x0005003e,0x0000127c,0x0000111b,0x00000002,
11460x00000004,0x0004007c,0x00000027,0x00001394, 10110x00000004,0x00050041,0x000000fe,0x0000111f,
11470x000013dc,0x00050041,0x000000fb,0x00001395, 10120x000000fc,0x00000a97,0x0004003d,0x00000006,
11480x000000f9,0x00000263,0x0004003d,0x00000006, 10130x00001120,0x0000111f,0x00050086,0x00000006,
11490x00001396,0x00001395,0x000500aa,0x0000002f, 10140x00001121,0x00001120,0x00000107,0x00050095,
11500x00001397,0x00001396,0x000000ad,0x000300f7, 10150x000000ab,0x000012ac,0x0000128a,0x0000010a,
11510x0000139d,0x00000000,0x000400fa,0x00001397, 10160x00050051,0x00000006,0x000012ad,0x000012ac,
11520x00001398,0x00001399,0x000200f8,0x00001398, 10170x00000001,0x00050051,0x00000006,0x000012ae,
11530x000200f9,0x0000139d,0x000200f8,0x00001399, 10180x000012ac,0x00000000,0x00050080,0x00000006,
11540x00050095,0x000000a8,0x0000140d,0x000013ac, 10190x000012b3,0x00001291,0x000012ad,0x00050050,
11550x0000010e,0x00050051,0x00000006,0x0000140e, 10200x00000007,0x000012b4,0x000012ae,0x000012b3,
11560x0000140d,0x00000001,0x00050051,0x00000006, 10210x0004007c,0x00000014,0x000012a4,0x000012b4,
11570x0000140f,0x0000140d,0x00000000,0x00050080, 10220x00060041,0x000000db,0x0000129c,0x000012a4,
11580x00000006,0x00001414,0x000013b1,0x0000140e, 10230x000000da,0x000000da,0x0005003e,0x0000129c,
11590x00050050,0x00000007,0x00001415,0x0000140f, 10240x00001121,0x00000002,0x00000004,0x00050095,
11600x00001414,0x0004007c,0x00000014,0x00001405, 10250x000000ab,0x000012cc,0x0000128a,0x00000111,
11610x00001415,0x00060041,0x000000d8,0x000013fc, 10260x00050051,0x00000006,0x000012cd,0x000012cc,
11620x00001405,0x000000d7,0x000000d7,0x0006003d, 10270x00000001,0x00050051,0x00000006,0x000012ce,
11630x00000006,0x000013fd,0x000013fc,0x00000002, 10280x000012cc,0x00000000,0x00050080,0x00000006,
11640x00000004,0x0004007c,0x00000027,0x0000139c, 10290x000012d3,0x00001291,0x000012cd,0x00050050,
11650x000013fd,0x000200f9,0x0000139d,0x000200f8, 10300x00000007,0x000012d4,0x000012ce,0x000012d3,
11660x0000139d,0x000700f5,0x00000027,0x00002b2a, 10310x0004007c,0x00000014,0x000012c4,0x000012d4,
11670x0000026a,0x00001398,0x0000139c,0x00001399, 10320x00060041,0x000000db,0x000012bc,0x000012c4,
11680x00060050,0x0000004b,0x000013a2,0x00001391, 10330x000000da,0x000000da,0x0005003e,0x000012bc,
11690x00001394,0x00002b2a,0x000300f7,0x0000145b, 10340x000000a6,0x00000002,0x00000004,0x00050095,
11700x00000000,0x000300fb,0x000000a3,0x00001427, 10350x000000ab,0x000012ec,0x0000128a,0x00000118,
11710x000200f8,0x00001427,0x00050041,0x00000153, 10360x00050051,0x00000006,0x000012ed,0x000012ec,
11720x00001428,0x000000f9,0x00000212,0x0004003d, 10370x00000001,0x00050051,0x00000006,0x000012ee,
11730x00000007,0x00001429,0x00001428,0x00050051, 10380x000012ec,0x00000000,0x00050080,0x00000006,
11740x00000006,0x00001460,0x00001429,0x00000000, 10390x000012f3,0x00001291,0x000012ed,0x00050050,
11750x000500aa,0x0000002f,0x00001461,0x00001460, 10400x00000007,0x000012f4,0x000012ee,0x000012f3,
11760x000000a3,0x000300f7,0x00001466,0x00000000, 10410x0004007c,0x00000014,0x000012e4,0x000012f4,
11770x000400fa,0x00001461,0x00001462,0x00001466, 10420x00060041,0x000000db,0x000012dc,0x000012e4,
11780x000200f8,0x00001462,0x00050051,0x00000006, 10430x000000da,0x000000da,0x0005003e,0x000012dc,
11790x00001464,0x00001429,0x00000001,0x000500aa, 10440x00001111,0x00000002,0x00000004,0x00050095,
11800x0000002f,0x00001465,0x00001464,0x000000a3, 10450x000000ab,0x00001315,0x0000128a,0x0000011f,
11810x000200f9,0x00001466,0x000200f8,0x00001466, 10460x00050051,0x00000006,0x00001316,0x00001315,
11820x000700f5,0x0000002f,0x00001467,0x00001461, 10470x00000001,0x00050051,0x00000006,0x00001317,
11830x00001427,0x00001465,0x00001462,0x000300f7, 10480x00001315,0x00000000,0x00050080,0x00000006,
11840x0000142d,0x00000000,0x000400fa,0x00001467, 10490x0000131c,0x00001291,0x00001316,0x00050050,
11850x0000142b,0x0000142d,0x000200f8,0x0000142b, 10500x00000007,0x0000131d,0x00001317,0x0000131c,
11860x000200f9,0x0000145b,0x000200f8,0x0000142d, 10510x0004007c,0x00000014,0x0000130d,0x0000131d,
11870x000200f9,0x0000142e,0x000200f8,0x0000142e, 10520x00060041,0x000000db,0x00001305,0x0000130d,
11880x000700f5,0x00000006,0x00002b2b,0x000000a3, 10530x000000da,0x000000da,0x0005003e,0x00001305,
11890x0000142d,0x00001458,0x00001432,0x000500b0, 10540x000011b7,0x00000002,0x00000004,0x00050095,
11900x0000002f,0x00001431,0x00002b2b,0x000002b4, 10550x000000ab,0x0000133e,0x0000128a,0x00000189,
11910x000400f6,0x00001459,0x00001432,0x00000000, 10560x00050051,0x00000006,0x0000133f,0x0000133e,
11920x000400fa,0x00001431,0x00001432,0x00001459, 10570x00000001,0x00050051,0x00000006,0x00001340,
11930x000200f8,0x00001432,0x00050084,0x00000006, 10580x0000133e,0x00000000,0x00050080,0x00000006,
11940x00001434,0x0000011c,0x00002b2b,0x00050095, 10590x00001345,0x00001291,0x0000133f,0x00050050,
11950x000000a8,0x00001480,0x00001460,0x00001434, 10600x00000007,0x00001346,0x00001340,0x00001345,
11960x00050051,0x00000006,0x00001481,0x00001480, 10610x0004007c,0x00000014,0x00001336,0x00001346,
11970x00000001,0x00050051,0x00000006,0x00001482, 10620x00060041,0x000000db,0x0000132e,0x00001336,
11980x00001480,0x00000000,0x00050051,0x00000006, 10630x000000da,0x000000da,0x0005003e,0x0000132e,
11990x00001485,0x00001429,0x00000001,0x00050080, 10640x000011d8,0x00000002,0x00000004,0x00050095,
12000x00000006,0x00001487,0x00001485,0x00001481, 10650x000000ab,0x00001367,0x0000128a,0x00000150,
12010x00050050,0x00000007,0x00001488,0x00001482, 10660x00050051,0x00000006,0x00001368,0x00001367,
12020x00001487,0x0004007c,0x00000014,0x00001478, 10670x00000001,0x00050051,0x00000006,0x00001369,
12030x00001488,0x00060041,0x000000d8,0x0000146f, 10680x00001367,0x00000000,0x00050080,0x00000006,
12040x00001478,0x000000d7,0x000000d7,0x0006003d, 10690x0000136e,0x00001291,0x00001368,0x00050050,
12050x00000006,0x00001470,0x0000146f,0x00000002, 10700x00000007,0x0000136f,0x00001369,0x0000136e,
12060x00000004,0x0004007c,0x00000027,0x00001439, 10710x0004007c,0x00000014,0x0000135f,0x0000136f,
12070x00001470,0x00050080,0x00000006,0x0000143b, 10720x00060041,0x000000db,0x00001357,0x0000135f,
12080x00001434,0x00000107,0x00050095,0x000000a8, 10730x000000da,0x000000da,0x0005003e,0x00001357,
12090x000014a1,0x00001460,0x0000143b,0x00050051, 10740x000011f9,0x00000002,0x00000004,0x00050095,
12100x00000006,0x000014a2,0x000014a1,0x00000001, 10750x000000ab,0x00001390,0x0000128a,0x00000463,
12110x00050051,0x00000006,0x000014a3,0x000014a1, 10760x00050051,0x00000006,0x00001391,0x00001390,
12120x00000000,0x00050080,0x00000006,0x000014a8, 10770x00000001,0x00050051,0x00000006,0x00001392,
12130x00001485,0x000014a2,0x00050050,0x00000007, 10780x00001390,0x00000000,0x00050080,0x00000006,
12140x000014a9,0x000014a3,0x000014a8,0x0004007c, 10790x00001397,0x00001291,0x00001391,0x00050050,
12150x00000014,0x00001499,0x000014a9,0x00060041, 10800x00000007,0x00001398,0x00001392,0x00001397,
12160x000000d8,0x00001490,0x00001499,0x000000d7, 10810x0004007c,0x00000014,0x00001388,0x00001398,
12170x000000d7,0x0006003d,0x00000006,0x00001491, 10820x00060041,0x000000db,0x00001380,0x00001388,
12180x00001490,0x00000002,0x00000004,0x0004007c, 10830x000000da,0x000000da,0x0005003e,0x00001380,
12190x00000027,0x0000143f,0x00001491,0x00050080, 10840x0000121a,0x00000002,0x00000004,0x00050095,
12200x00000006,0x00001441,0x00001434,0x0000010e, 10850x000000ab,0x000013b9,0x0000128a,0x00000469,
12210x00050095,0x000000a8,0x000014c2,0x00001460, 10860x00050051,0x00000006,0x000013ba,0x000013b9,
12220x00001441,0x00050051,0x00000006,0x000014c3, 10870x00000001,0x00050051,0x00000006,0x000013bb,
12230x000014c2,0x00000001,0x00050051,0x00000006, 10880x000013b9,0x00000000,0x00050080,0x00000006,
12240x000014c4,0x000014c2,0x00000000,0x00050080, 10890x000013c0,0x00001291,0x000013ba,0x00050050,
12250x00000006,0x000014c9,0x00001485,0x000014c3, 10900x00000007,0x000013c1,0x000013bb,0x000013c0,
12260x00050050,0x00000007,0x000014ca,0x000014c4, 10910x0004007c,0x00000014,0x000013b1,0x000013c1,
12270x000014c9,0x0004007c,0x00000014,0x000014ba, 10920x00060041,0x000000db,0x000013a9,0x000013b1,
12280x000014ca,0x00060041,0x000000d8,0x000014b1, 10930x000000da,0x000000da,0x0005003e,0x000013a9,
12290x000014ba,0x000000d7,0x000000d7,0x0006003d, 10940x0000123b,0x00000002,0x00000004,0x00050095,
12300x00000006,0x000014b2,0x000014b1,0x00000002, 10950x000000ab,0x000013e2,0x0000128a,0x00000347,
12310x00000004,0x0004007c,0x00000027,0x00001445, 10960x00050051,0x00000006,0x000013e3,0x000013e2,
12320x000014b2,0x00050080,0x00000006,0x00001447, 10970x00000001,0x00050051,0x00000006,0x000013e4,
12330x00001434,0x00000115,0x00050095,0x000000a8, 10980x000013e2,0x00000000,0x00050080,0x00000006,
12340x000014e3,0x00001460,0x00001447,0x00050051, 10990x000013e9,0x00001291,0x000013e3,0x00050050,
12350x00000006,0x000014e4,0x000014e3,0x00000001, 11000x00000007,0x000013ea,0x000013e4,0x000013e9,
12360x00050051,0x00000006,0x000014e5,0x000014e3, 11010x0004007c,0x00000014,0x000013da,0x000013ea,
12370x00000000,0x00050080,0x00000006,0x000014ea, 11020x00060041,0x000000db,0x000013d2,0x000013da,
12380x00001485,0x000014e4,0x00050050,0x00000007, 11030x000000da,0x000000da,0x0005003e,0x000013d2,
12390x000014eb,0x000014e5,0x000014ea,0x0004007c, 11040x0000125c,0x00000002,0x00000004,0x00050041,
12400x00000014,0x000014db,0x000014eb,0x00060041, 11050x000000fe,0x0000114d,0x000000fc,0x0000023e,
12410x000000d8,0x000014d2,0x000014db,0x000000d7, 11060x0004003d,0x00000006,0x0000114e,0x0000114d,
12420x000000d7,0x0006003d,0x00000006,0x000014d3, 11070x00050095,0x000000ab,0x00001402,0x0000128a,
12430x000014d2,0x00000002,0x00000004,0x0004007c, 11080x00000352,0x00050051,0x00000006,0x00001403,
12440x00000027,0x0000144b,0x000014d3,0x00070050, 11090x00001402,0x00000001,0x00050051,0x00000006,
12450x000002b9,0x0000144c,0x00001439,0x0000143f, 11100x00001404,0x00001402,0x00000000,0x00050080,
12460x00001445,0x0000144b,0x0008004f,0x0000004b, 11110x00000006,0x00001409,0x00001291,0x00001403,
12470x0000144f,0x0000144c,0x0000144c,0x00000000, 11120x00050050,0x00000007,0x0000140a,0x00001404,
12480x00000001,0x00000002,0x00050094,0x00000027, 11130x00001409,0x0004007c,0x00000014,0x000013fa,
12490x00001451,0x0000144f,0x000013a2,0x00050081, 11140x0000140a,0x00060041,0x000000db,0x000013f2,
12500x00000027,0x00001454,0x00001451,0x0000144b, 11150x000013fa,0x000000da,0x000000da,0x0005003e,
12510x00050041,0x00000028,0x00001455,0x00001424, 11160x000013f2,0x0000114e,0x00000002,0x00000004,
12520x00002b2b,0x0003003e,0x00001455,0x00001454, 11170x00050095,0x000000ab,0x00001422,0x0000128a,
12530x00050080,0x00000006,0x00001458,0x00002b2b, 11180x0000035d,0x00050051,0x00000006,0x00001423,
12540x00000151,0x000200f9,0x0000142e,0x000200f8, 11190x00001422,0x00000001,0x00050051,0x00000006,
12550x00001459,0x0004003d,0x0000004b,0x0000145a, 11200x00001424,0x00001422,0x00000000,0x00050080,
12560x00001424,0x000200f9,0x0000145b,0x000200f8, 11210x00000006,0x00001429,0x00001291,0x00001423,
12570x0000145b,0x000700f5,0x0000004b,0x00002b2c, 11220x00050050,0x00000007,0x0000142a,0x00001424,
12580x000013a2,0x0000142b,0x0000145a,0x00001459, 11230x00001429,0x0004007c,0x00000014,0x0000141a,
12590x00050041,0x0000004c,0x00001274,0x00001239, 11240x0000142a,0x00060041,0x000000db,0x00001412,
12600x00002b1e,0x0003003e,0x00001274,0x00002b2c, 11250x0000141a,0x000000da,0x000000da,0x0005003e,
12610x000200f9,0x00001275,0x000200f8,0x00001275, 11260x00001412,0x000000a6,0x00000002,0x00000004,
12620x00050080,0x00000006,0x00001277,0x00002b1e, 11270x00050084,0x00000006,0x00001430,0x0000110f,
12630x00000151,0x000200f9,0x00001267,0x000200f8, 11280x00000228,0x00050080,0x00000006,0x00001431,
12640x00001278,0x00050041,0x000000fb,0x00001279, 11290x0000114e,0x00001430,0x000500c2,0x00000006,
12650x000000f9,0x00000305,0x0004003d,0x00000006, 11300x00001432,0x00001431,0x00000233,0x000500c4,
12660x0000127a,0x00001279,0x00050080,0x00000006, 11310x00000006,0x00001433,0x00001432,0x0000020d,
12670x0000127c,0x0000127a,0x000009e9,0x00050041, 11320x000500c5,0x00000006,0x00001434,0x00001433,
12680x000000fb,0x0000127d,0x000000f9,0x00000229, 11330x00000246,0x00050095,0x000000ab,0x0000144c,
12690x0004003d,0x00000006,0x0000127e,0x0000127d, 11340x0000128a,0x00000368,0x00050051,0x00000006,
12700x00050084,0x00000006,0x00001280,0x00000104, 11350x0000144d,0x0000144c,0x00000001,0x00050051,
12710x0000127c,0x00050080,0x00000006,0x00001281, 11360x00000006,0x0000144e,0x0000144c,0x00000000,
12720x0000127e,0x00001280,0x000200f9,0x00001282, 11370x00050080,0x00000006,0x00001453,0x00001291,
12730x000200f8,0x00001282,0x000700f5,0x00000006, 11380x0000144d,0x00050050,0x00000007,0x00001454,
12740x00002b1f,0x000000a3,0x00001278,0x000012a9, 11390x0000144e,0x00001453,0x0004007c,0x00000014,
12750x00001286,0x000500b0,0x0000002f,0x00001285, 11400x00001444,0x00001454,0x00060041,0x000000db,
12760x00002b1f,0x000002b4,0x000400f6,0x000012aa, 11410x0000143c,0x00001444,0x000000da,0x000000da,
12770x00001286,0x00000000,0x000400fa,0x00001285, 11420x0005003e,0x0000143c,0x00001434,0x00000002,
12780x00001286,0x000012aa,0x000200f8,0x00001286, 11430x00000004,0x00050041,0x000000fe,0x0000115a,
12790x00050084,0x00000006,0x00001289,0x00000115, 11440x000000fc,0x0000022c,0x0004003d,0x00000006,
12800x00002b1f,0x00050080,0x00000006,0x0000128a, 11450x0000115b,0x0000115a,0x00050095,0x000000ab,
12810x00001281,0x00001289,0x00050041,0x00000153, 11460x0000146c,0x0000128a,0x00000374,0x00050051,
12820x0000128c,0x000000f9,0x000000d7,0x0004003d, 11470x00000006,0x0000146d,0x0000146c,0x00000001,
12830x00000007,0x0000128d,0x0000128c,0x00060041, 11480x00050051,0x00000006,0x0000146e,0x0000146c,
12840x00000028,0x0000128e,0x00001239,0x00002b1f, 11490x00000000,0x00050080,0x00000006,0x00001473,
12850x000000a3,0x0004003d,0x00000027,0x0000128f, 11500x00001291,0x0000146d,0x00050050,0x00000007,
12860x0000128e,0x0004007c,0x00000006,0x000014f1, 11510x00001474,0x0000146e,0x00001473,0x0004007c,
12870x0000128f,0x00050051,0x00000006,0x0000150a, 11520x00000014,0x00001464,0x00001474,0x00060041,
12880x0000128d,0x00000000,0x00050095,0x000000a8, 11530x000000db,0x0000145c,0x00001464,0x000000da,
12890x0000150c,0x0000150a,0x0000128a,0x00050051, 11540x000000da,0x0005003e,0x0000145c,0x0000115b,
12900x00000006,0x0000150d,0x0000150c,0x00000001, 11550x00000002,0x00000004,0x00050041,0x000000fe,
12910x00050051,0x00000006,0x0000150e,0x0000150c, 11560x0000115f,0x000000fc,0x000009ef,0x0004003d,
12920x00000000,0x00050051,0x00000006,0x00001511, 11570x00000006,0x00001160,0x0000115f,0x00050095,
12930x0000128d,0x00000001,0x00050080,0x00000006, 11580x000000ab,0x0000148c,0x0000128a,0x0000037e,
12940x00001513,0x00001511,0x0000150d,0x00050050, 11590x00050051,0x00000006,0x0000148d,0x0000148c,
12950x00000007,0x00001514,0x0000150e,0x00001513, 11600x00000001,0x00050051,0x00000006,0x0000148e,
12960x0004007c,0x00000014,0x00001504,0x00001514, 11610x0000148c,0x00000000,0x00050080,0x00000006,
12970x00060041,0x000000d8,0x000014fc,0x00001504, 11620x00001493,0x00001291,0x0000148d,0x00050050,
12980x000000d7,0x000000d7,0x0005003e,0x000014fc, 11630x00000007,0x00001494,0x0000148e,0x00001493,
12990x000014f1,0x00000002,0x00000004,0x00050080, 11640x0004007c,0x00000014,0x00001484,0x00001494,
13000x00000006,0x00001295,0x0000128a,0x00000107, 11650x00060041,0x000000db,0x0000147c,0x00001484,
13010x00060041,0x00000028,0x00001299,0x00001239, 11660x000000da,0x000000da,0x0005003e,0x0000147c,
13020x00002b1f,0x000000ad,0x0004003d,0x00000027, 11670x00001160,0x00000002,0x00000004,0x00050095,
13030x0000129a,0x00001299,0x0004007c,0x00000006, 11680x000000ab,0x000014ac,0x0000128a,0x00000388,
13040x0000151a,0x0000129a,0x00050095,0x000000a8, 11690x00050051,0x00000006,0x000014ad,0x000014ac,
13050x00001535,0x0000150a,0x00001295,0x00050051, 11700x00000001,0x00050051,0x00000006,0x000014ae,
13060x00000006,0x00001536,0x00001535,0x00000001, 11710x000014ac,0x00000000,0x00050080,0x00000006,
13070x00050051,0x00000006,0x00001537,0x00001535, 11720x000014b3,0x00001291,0x000014ad,0x00050050,
13080x00000000,0x00050080,0x00000006,0x0000153c, 11730x00000007,0x000014b4,0x000014ae,0x000014b3,
13090x00001511,0x00001536,0x00050050,0x00000007, 11740x0004007c,0x00000014,0x000014a4,0x000014b4,
13100x0000153d,0x00001537,0x0000153c,0x0004007c, 11750x00060041,0x000000db,0x0000149c,0x000014a4,
13110x00000014,0x0000152d,0x0000153d,0x00060041, 11760x000000da,0x000000da,0x0005003e,0x0000149c,
13120x000000d8,0x00001525,0x0000152d,0x000000d7, 11770x000000a6,0x00000002,0x00000004,0x000200f9,
13130x000000d7,0x0005003e,0x00001525,0x0000151a, 11780x00000b4b,0x000200f8,0x00000b4b,0x000200f9,
13140x00000002,0x00000004,0x00050080,0x00000006, 11790x00000bf3,0x000200f8,0x00000b47,0x00050041,
13150x000012a0,0x0000128a,0x0000010e,0x00060041, 11800x000000fe,0x00000b4f,0x000000fc,0x000004d8,
13160x00000028,0x000012a4,0x00001239,0x00002b1f, 11810x0004003d,0x00000006,0x00000b50,0x00000b4f,
13170x0000016d,0x0004003d,0x00000027,0x000012a5, 11820x000500ae,0x0000002f,0x00000b51,0x00000b11,
13180x000012a4,0x0004007c,0x00000006,0x00001543, 11830x00000b50,0x000300f7,0x00000b53,0x00000000,
13190x000012a5,0x00050095,0x000000a8,0x0000155e, 11840x000400fa,0x00000b51,0x00000b52,0x00000b53,
13200x0000150a,0x000012a0,0x00050051,0x00000006, 11850x000200f8,0x00000b52,0x000200f9,0x00000bf3,
13210x0000155f,0x0000155e,0x00000001,0x00050051, 11860x000200f8,0x00000b53,0x000500aa,0x0000002f,
13220x00000006,0x00001560,0x0000155e,0x00000000, 11870x00000b58,0x00000b13,0x00000b57,0x000300f7,
13230x00050080,0x00000006,0x00001565,0x00001511, 11880x00000b5a,0x00000000,0x000400fa,0x00000b58,
13240x0000155f,0x00050050,0x00000007,0x00001566, 11890x00000b59,0x00000b5a,0x000200f8,0x00000b59,
13250x00001560,0x00001565,0x0004007c,0x00000014, 11900x000500aa,0x0000002f,0x00000b5c,0x00000b11,
13260x00001556,0x00001566,0x00060041,0x000000d8, 11910x000000a6,0x000300f7,0x00000b5e,0x00000000,
13270x0000154e,0x00001556,0x000000d7,0x000000d7, 11920x000400fa,0x00000b5c,0x00000b5d,0x00000b5e,
13280x0005003e,0x0000154e,0x00001543,0x00000002, 11930x000200f8,0x00000b5d,0x00050041,0x00000156,
13290x00000004,0x00050080,0x00000006,0x000012a9, 11940x00000b60,0x000000fc,0x00000205,0x0004003d,
13300x00002b1f,0x00000151,0x000200f9,0x00001282, 11950x00000007,0x00000b61,0x00000b60,0x00050051,
13310x000200f8,0x000012aa,0x00050080,0x00000006, 11960x00000006,0x000014cb,0x00000b61,0x00000000,
13320x000012ac,0x00001281,0x00000344,0x00050041, 11970x00050095,0x000000ab,0x000014cd,0x000014cb,
13330x00000153,0x000012ad,0x000000f9,0x000000d7, 11980x0000010a,0x00050051,0x00000006,0x000014ce,
13340x0004003d,0x00000007,0x000012ae,0x000012ad, 11990x000014cd,0x00000001,0x00050051,0x00000006,
13350x00060041,0x00000028,0x000012af,0x00001239, 12000x000014cf,0x000014cd,0x00000000,0x00050051,
13360x00000202,0x000000a3,0x0004003d,0x00000027, 12010x00000006,0x000014d2,0x00000b61,0x00000001,
13370x000012b0,0x000012af,0x0004007c,0x00000006, 12020x00050080,0x00000006,0x000014d4,0x000014d2,
13380x0000156c,0x000012b0,0x00050051,0x00000006, 12030x000014ce,0x00050050,0x00000007,0x000014d5,
13390x00001585,0x000012ae,0x00000000,0x00050095, 12040x000014cf,0x000014d4,0x0004007c,0x00000014,
13400x000000a8,0x00001587,0x00001585,0x000012ac, 12050x000014c5,0x000014d5,0x00060041,0x000000db,
13410x00050051,0x00000006,0x00001588,0x00001587, 12060x000014bc,0x000014c5,0x000000da,0x000000da,
13420x00000001,0x00050051,0x00000006,0x00001589, 12070x0006003d,0x00000006,0x000014bd,0x000014bc,
13430x00001587,0x00000000,0x00050051,0x00000006, 12080x00000002,0x00000004,0x00050084,0x00000006,
13440x0000158c,0x000012ae,0x00000001,0x00050080, 12090x00000b64,0x000014bd,0x00000107,0x00050041,
13450x00000006,0x0000158e,0x0000158c,0x00001588, 12100x00000156,0x00000b66,0x000000fc,0x000000da,
13460x00050050,0x00000007,0x0000158f,0x00001589, 12110x0004003d,0x00000007,0x00000b67,0x00000b66,
13470x0000158e,0x0004007c,0x00000014,0x0000157f, 12120x00050051,0x00000006,0x000014eb,0x00000b67,
13480x0000158f,0x00060041,0x000000d8,0x00001577, 12130x00000000,0x00050095,0x000000ab,0x000014ed,
13490x0000157f,0x000000d7,0x000000d7,0x0005003e, 12140x000014eb,0x000000a6,0x00050051,0x00000006,
13500x00001577,0x0000156c,0x00000002,0x00000004, 12150x000014ee,0x000014ed,0x00000001,0x00050051,
13510x00050080,0x00000006,0x000012b3,0x00001281, 12160x00000006,0x000014ef,0x000014ed,0x00000000,
13520x0000034f,0x00060041,0x00000028,0x000012b6, 12170x00050051,0x00000006,0x000014f2,0x00000b67,
13530x00001239,0x00000202,0x000000ad,0x0004003d, 12180x00000001,0x00050080,0x00000006,0x000014f4,
13540x00000027,0x000012b7,0x000012b6,0x0004007c, 12190x000014f2,0x000014ee,0x00050050,0x00000007,
13550x00000006,0x00001595,0x000012b7,0x00050095, 12200x000014f5,0x000014ef,0x000014f4,0x0004007c,
13560x000000a8,0x000015b0,0x00001585,0x000012b3, 12210x00000014,0x000014e5,0x000014f5,0x00060041,
13570x00050051,0x00000006,0x000015b1,0x000015b0, 12220x000000db,0x000014dd,0x000014e5,0x000000da,
13580x00000001,0x00050051,0x00000006,0x000015b2, 12230x000000da,0x0005003e,0x000014dd,0x00000b64,
13590x000015b0,0x00000000,0x00050080,0x00000006, 12240x00000002,0x00000004,0x00050095,0x000000ab,
13600x000015b7,0x0000158c,0x000015b1,0x00050050, 12250x0000150d,0x000014eb,0x0000010a,0x00050051,
13610x00000007,0x000015b8,0x000015b2,0x000015b7, 12260x00000006,0x0000150e,0x0000150d,0x00000001,
13620x0004007c,0x00000014,0x000015a8,0x000015b8, 12270x00050051,0x00000006,0x0000150f,0x0000150d,
13630x00060041,0x000000d8,0x000015a0,0x000015a8, 12280x00000000,0x00050080,0x00000006,0x00001514,
13640x000000d7,0x000000d7,0x0005003e,0x000015a0, 12290x000014f2,0x0000150e,0x00050050,0x00000007,
13650x00001595,0x00000002,0x00000004,0x00050080, 12300x00001515,0x0000150f,0x00001514,0x0004007c,
13660x00000006,0x000012ba,0x00001281,0x0000035a, 12310x00000014,0x00001505,0x00001515,0x00060041,
13670x00060041,0x00000028,0x000012bd,0x00001239, 12320x000000db,0x000014fd,0x00001505,0x000000da,
13680x00000202,0x0000016d,0x0004003d,0x00000027, 12330x000000da,0x0005003e,0x000014fd,0x000000a6,
13690x000012be,0x000012bd,0x0004007c,0x00000006, 12340x00000002,0x00000004,0x000200f9,0x00000b5e,
13700x000015be,0x000012be,0x00050095,0x000000a8, 12350x000200f8,0x00000b5e,0x000200f9,0x00000bf3,
13710x000015d9,0x00001585,0x000012ba,0x00050051, 12360x000200f8,0x00000b5a,0x000500aa,0x0000002f,
13720x00000006,0x000015da,0x000015d9,0x00000001, 12370x00000b74,0x00000b13,0x00000118,0x000300f7,
13730x00050051,0x00000006,0x000015db,0x000015d9, 12380x00000b76,0x00000000,0x000400fa,0x00000b74,
13740x00000000,0x00050080,0x00000006,0x000015e0, 12390x00000b75,0x00000b76,0x000200f8,0x00000b75,
13750x0000158c,0x000015da,0x00050050,0x00000007, 12400x00050084,0x00000006,0x00000b78,0x0000010a,
13760x000015e1,0x000015db,0x000015e0,0x0004007c, 12410x00000b11,0x00050041,0x00000156,0x00000b7a,
13770x00000014,0x000015d1,0x000015e1,0x00060041, 12420x000000fc,0x00000205,0x0004003d,0x00000007,
13780x000000d8,0x000015c9,0x000015d1,0x000000d7, 12430x00000b7b,0x00000b7a,0x00050051,0x00000006,
13790x000000d7,0x0005003e,0x000015c9,0x000015be, 12440x0000152c,0x00000b7b,0x00000000,0x00050095,
13800x00000002,0x00000004,0x00050080,0x00000006, 12450x000000ab,0x0000152e,0x0000152c,0x0000010a,
13810x000012c1,0x00001281,0x00000365,0x00050041, 12460x00050051,0x00000006,0x0000152f,0x0000152e,
13820x000000fb,0x000012c4,0x000000f9,0x00000367, 12470x00000001,0x00050051,0x00000006,0x00001530,
13830x0004003d,0x00000006,0x000012c5,0x000012c4, 12480x0000152e,0x00000000,0x00050051,0x00000006,
13840x00050095,0x000000a8,0x000015f9,0x00001585, 12490x00001533,0x00000b7b,0x00000001,0x00050080,
13850x000012c1,0x00050051,0x00000006,0x000015fa, 12500x00000006,0x00001535,0x00001533,0x0000152f,
13860x000015f9,0x00000001,0x00050051,0x00000006, 12510x00050050,0x00000007,0x00001536,0x00001530,
13870x000015fb,0x000015f9,0x00000000,0x00050080, 12520x00001535,0x0004007c,0x00000014,0x00001526,
13880x00000006,0x00001600,0x0000158c,0x000015fa, 12530x00001536,0x00060041,0x000000db,0x0000151d,
13890x00050050,0x00000007,0x00001601,0x000015fb, 12540x00001526,0x000000da,0x000000da,0x0006003d,
13900x00001600,0x0004007c,0x00000014,0x000015f1, 12550x00000006,0x0000151e,0x0000151d,0x00000002,
13910x00001601,0x00060041,0x000000d8,0x000015e9, 12560x00000004,0x00050084,0x00000006,0x00000b7e,
13920x000015f1,0x000000d7,0x000000d7,0x0005003e, 12570x0000151e,0x00000107,0x000500b0,0x0000002f,
13930x000015e9,0x000012c5,0x00000002,0x00000004, 12580x00000b7f,0x00000b78,0x00000b7e,0x000300f7,
13940x00050080,0x00000006,0x000012c8,0x00001281, 12590x00000b81,0x00000000,0x000400fa,0x00000b7f,
13950x00000371,0x00050095,0x000000a8,0x00001619, 12600x00000b80,0x00000b81,0x000200f8,0x00000b80,
13960x00001585,0x000012c8,0x00050051,0x00000006, 12610x00050095,0x000000ab,0x0000154f,0x0000152c,
13970x0000161a,0x00001619,0x00000001,0x00050051, 12620x00000b78,0x00050051,0x00000006,0x00001550,
13980x00000006,0x0000161b,0x00001619,0x00000000, 12630x0000154f,0x00000001,0x00050051,0x00000006,
13990x00050080,0x00000006,0x00001620,0x0000158c, 12640x00001551,0x0000154f,0x00000000,0x00050080,
14000x0000161a,0x00050050,0x00000007,0x00001621, 12650x00000006,0x00001556,0x00001533,0x00001550,
14010x0000161b,0x00001620,0x0004007c,0x00000014, 12660x00050050,0x00000007,0x00001557,0x00001551,
14020x00001611,0x00001621,0x00060041,0x000000d8, 12670x00001556,0x0004007c,0x00000014,0x00001547,
14030x00001609,0x00001611,0x000000d7,0x000000d7, 12680x00001557,0x00060041,0x000000db,0x0000153e,
14040x0005003e,0x00001609,0x000009e9,0x00000002, 12690x00001547,0x000000da,0x000000da,0x0006003d,
14050x00000004,0x00050080,0x00000006,0x000012ce, 12700x00000006,0x0000153f,0x0000153e,0x00000002,
14060x00001281,0x0000037b,0x00050095,0x000000a8, 12710x00000004,0x00050041,0x00000156,0x00000b8c,
14070x00001639,0x00001585,0x000012ce,0x00050051, 12720x000000fc,0x000000da,0x0004003d,0x00000007,
14080x00000006,0x0000163a,0x00001639,0x00000001, 12730x00000b8d,0x00000b8c,0x00050051,0x00000006,
14090x00050051,0x00000006,0x0000163b,0x00001639, 12740x0000156d,0x00000b8d,0x00000000,0x00050095,
14100x00000000,0x00050080,0x00000006,0x00001640, 12750x000000ab,0x0000156f,0x0000156d,0x00000b78,
14110x0000158c,0x0000163a,0x00050050,0x00000007, 12760x00050051,0x00000006,0x00001570,0x0000156f,
14120x00001641,0x0000163b,0x00001640,0x0004007c, 12770x00000001,0x00050051,0x00000006,0x00001571,
14130x00000014,0x00001631,0x00001641,0x00060041, 12780x0000156f,0x00000000,0x00050051,0x00000006,
14140x000000d8,0x00001629,0x00001631,0x000000d7, 12790x00001574,0x00000b8d,0x00000001,0x00050080,
14150x000000d7,0x0005003e,0x00001629,0x0000037d, 12800x00000006,0x00001576,0x00001574,0x00001570,
14160x00000002,0x00000004,0x00050080,0x00000006, 12810x00050050,0x00000007,0x00001577,0x00001571,
14170x000012d3,0x00001281,0x00000385,0x00050095, 12820x00001576,0x0004007c,0x00000014,0x00001567,
14180x000000a8,0x00001659,0x00001585,0x000012d3, 12830x00001577,0x00060041,0x000000db,0x0000155f,
14190x00050051,0x00000006,0x0000165a,0x00001659, 12840x00001567,0x000000da,0x000000da,0x0005003e,
14200x00000001,0x00050051,0x00000006,0x0000165b, 12850x0000155f,0x0000153f,0x00000002,0x00000004,
14210x00001659,0x00000000,0x00050080,0x00000006, 12860x000200f9,0x00000b81,0x000200f8,0x00000b81,
14220x00001660,0x0000158c,0x0000165a,0x00050050, 12870x000200f9,0x00000bf3,0x000200f8,0x00000b76,
14230x00000007,0x00001661,0x0000165b,0x00001660, 12880x000500aa,0x0000002f,0x00000b95,0x00000b13,
14240x0004007c,0x00000014,0x00001651,0x00001661, 12890x00000b94,0x000300f7,0x00000b97,0x00000000,
14250x00060041,0x000000d8,0x00001649,0x00001651, 12900x000400fa,0x00000b95,0x00000b96,0x00000ba7,
14260x000000d7,0x000000d7,0x0005003e,0x00001649, 12910x000200f8,0x00000b96,0x00050084,0x00000006,
14270x00000387,0x00000002,0x00000004,0x00050041, 12920x00000b99,0x0000010a,0x00000b11,0x00050041,
14280x0000004c,0x000012d7,0x00001239,0x000000d7, 12930x00000156,0x00000b9d,0x000000fc,0x00000205,
14290x0004003d,0x0000004b,0x000012d8,0x000012d7, 12940x0004003d,0x00000007,0x00000b9e,0x00000b9d,
14300x0004009c,0x00000392,0x000012d9,0x000012d8, 12950x00050051,0x00000006,0x0000158e,0x00000b9e,
14310x0004009a,0x0000002f,0x000012da,0x000012d9, 12960x00000000,0x00050095,0x000000ab,0x00001590,
14320x000400a8,0x0000002f,0x000012db,0x000012da, 12970x0000158e,0x00000b99,0x00050051,0x00000006,
14330x000300f7,0x000012e1,0x00000000,0x000400fa, 12980x00001591,0x00001590,0x00000001,0x00050051,
14340x000012db,0x000012dc,0x000012e1,0x000200f8, 12990x00000006,0x00001592,0x00001590,0x00000000,
14350x000012dc,0x00050041,0x0000004c,0x000012dd, 13000x00050051,0x00000006,0x00001595,0x00000b9e,
14360x00001239,0x00000151,0x0004003d,0x0000004b, 13010x00000001,0x00050080,0x00000006,0x00001597,
14370x000012de,0x000012dd,0x0004009c,0x00000392, 13020x00001595,0x00001591,0x00050050,0x00000007,
14380x000012df,0x000012de,0x0004009a,0x0000002f, 13030x00001598,0x00001592,0x00001597,0x0004007c,
14390x000012e0,0x000012df,0x000200f9,0x000012e1, 13040x00000014,0x00001588,0x00001598,0x00060041,
14400x000200f8,0x000012e1,0x000700f5,0x0000002f, 13050x000000db,0x0000157f,0x00001588,0x000000da,
14410x000012e2,0x000012da,0x000012aa,0x000012e0, 13060x000000da,0x0006003d,0x00000006,0x00001580,
14420x000012dc,0x000400a8,0x0000002f,0x000012e3, 13070x0000157f,0x00000002,0x00000004,0x00050041,
14430x000012e2,0x000300f7,0x000012e9,0x00000000, 13080x00000156,0x00000ba2,0x000000fc,0x000000da,
14440x000400fa,0x000012e3,0x000012e4,0x000012e9, 13090x0004003d,0x00000007,0x00000ba3,0x00000ba2,
14450x000200f8,0x000012e4,0x00050041,0x0000004c, 13100x00050051,0x00000006,0x000015ae,0x00000ba3,
14460x000012e5,0x00001239,0x00000202,0x0004003d, 13110x00000000,0x00050095,0x000000ab,0x000015b0,
14470x0000004b,0x000012e6,0x000012e5,0x0004009c, 13120x000015ae,0x00000b99,0x00050051,0x00000006,
14480x00000392,0x000012e7,0x000012e6,0x0004009a, 13130x000015b1,0x000015b0,0x00000001,0x00050051,
14490x0000002f,0x000012e8,0x000012e7,0x000200f9, 13140x00000006,0x000015b2,0x000015b0,0x00000000,
14500x000012e9,0x000200f8,0x000012e9,0x000700f5, 13150x00050051,0x00000006,0x000015b5,0x00000ba3,
14510x0000002f,0x000012ea,0x000012e2,0x000012e1, 13160x00000001,0x00050080,0x00000006,0x000015b7,
14520x000012e8,0x000012e4,0x0004003d,0x0000004b, 13170x000015b5,0x000015b1,0x00050050,0x00000007,
14530x000012ec,0x000012d7,0x00050041,0x0000004c, 13180x000015b8,0x000015b2,0x000015b7,0x0004007c,
14540x000012ed,0x00001239,0x00000151,0x0004003d, 13190x00000014,0x000015a8,0x000015b8,0x00060041,
14550x0000004b,0x000012ee,0x000012ed,0x0007000c, 13200x000000db,0x000015a0,0x000015a8,0x000000da,
14560x0000004b,0x000012ef,0x00000001,0x00000025, 13210x000000da,0x0005003e,0x000015a0,0x00001580,
14570x000012ec,0x000012ee,0x00050041,0x0000004c, 13220x00000002,0x00000004,0x000200f9,0x00000b97,
14580x000012f0,0x00001239,0x00000202,0x0004003d, 13230x000200f8,0x00000ba7,0x000500aa,0x0000002f,
14590x0000004b,0x000012f1,0x000012f0,0x0007000c, 13240x00000baa,0x00000b13,0x000000a6,0x000300f7,
14600x0000004b,0x000012f2,0x00000001,0x00000025, 13250x00000bac,0x00000000,0x000400fa,0x00000baa,
14610x000012ef,0x000012f1,0x0004003d,0x0000004b, 13260x00000bab,0x00000bcd,0x000200f8,0x00000bab,
14620x000012f4,0x000012d7,0x0004003d,0x0000004b, 13270x00050041,0x000000fe,0x00000bad,0x000000fc,
14630x000012f6,0x000012ed,0x0007000c,0x0000004b, 13280x000009ef,0x0004003d,0x00000006,0x00000bae,
14640x000012f7,0x00000001,0x00000028,0x000012f4, 13290x00000bad,0x00050084,0x00000006,0x00000bb0,
14650x000012f6,0x0004003d,0x0000004b,0x000012f9, 13300x0000010a,0x00000b11,0x00050080,0x00000006,
14660x000012f0,0x0007000c,0x0000004b,0x000012fa, 13310x00000bb1,0x00000bae,0x00000bb0,0x00050041,
14670x00000001,0x00000028,0x000012f7,0x000012f9, 13320x00000156,0x00000bb3,0x000000fc,0x000000da,
14680x00060050,0x00000392,0x00002b68,0x000012ea, 13330x0004003d,0x00000007,0x00000bb4,0x00000bb3,
14690x000012ea,0x000012ea,0x000600a9,0x0000004b, 13340x00050051,0x00000006,0x000015ce,0x00000bb4,
14700x00002b69,0x00002b68,0x00002b66,0x000012fa, 13350x00000000,0x00050095,0x000000ab,0x000015d0,
14710x000600a9,0x0000004b,0x00002b6b,0x00002b68, 13360x000015ce,0x00000bb1,0x00050051,0x00000006,
14720x00002b64,0x000012f2,0x00050041,0x000000fb, 13370x000015d1,0x000015d0,0x00000001,0x00050051,
14730x000016ab,0x000000f9,0x000000fa,0x0004003d, 13380x00000006,0x000015d2,0x000015d0,0x00000000,
14740x00000006,0x000016ac,0x000016ab,0x00050084, 13390x00050051,0x00000006,0x000015d5,0x00000bb4,
14750x00000006,0x000016ad,0x0000011c,0x000016ac, 13400x00000001,0x00050080,0x00000006,0x000015d7,
14760x00050080,0x00000006,0x000016ae,0x00000104, 13410x000015d5,0x000015d1,0x00050050,0x00000007,
14770x000016ad,0x00050080,0x00000006,0x000016b4, 13420x000015d8,0x000015d2,0x000015d7,0x0004007c,
14780x000016ac,0x00002b67,0x00050086,0x00000006, 13430x00000014,0x000015c8,0x000015d8,0x00060041,
14790x000016b5,0x000016b4,0x000000fe,0x00050084, 13440x000000db,0x000015c0,0x000015c8,0x000000da,
14800x00000006,0x000016a7,0x00000104,0x000016b5, 13450x000000da,0x0005003e,0x000015c0,0x00000380,
14810x00050080,0x00000006,0x000016a8,0x000016ae, 13460x00000002,0x00000004,0x000500b0,0x0000002f,
14820x000016a7,0x00050084,0x00000006,0x00001678, 13470x00000bb9,0x00000b11,0x000002b7,0x000300f7,
14830x0000014d,0x0000127c,0x00050080,0x00000006, 13480x00000bbb,0x00000000,0x000400fa,0x00000bb9,
14840x00001679,0x000016a8,0x00001678,0x00050041, 13490x00000bba,0x00000bbb,0x000200f8,0x00000bba,
14850x00000153,0x0000167a,0x000000f9,0x00000151, 13500x00050041,0x00000156,0x00000bbf,0x000000fc,
14860x0004003d,0x00000007,0x0000167b,0x0000167a, 13510x00000154,0x0004003d,0x00000007,0x00000bc0,
14870x00050051,0x00000027,0x0000167e,0x00002b6b, 13520x00000bbf,0x00050051,0x00000006,0x000015ee,
14880x00000000,0x0004007c,0x00000006,0x000016bb, 13530x00000bc0,0x00000000,0x00050095,0x000000ab,
14890x0000167e,0x00050051,0x00000006,0x000016d4, 13540x000015f0,0x000015ee,0x00000bb0,0x00050051,
14900x0000167b,0x00000000,0x00050095,0x000000a8, 13550x00000006,0x000015f1,0x000015f0,0x00000001,
14910x000016d6,0x000016d4,0x00001679,0x00050051, 13560x00050051,0x00000006,0x000015f2,0x000015f0,
14920x00000006,0x000016d7,0x000016d6,0x00000001, 13570x00000000,0x00050051,0x00000006,0x000015f5,
14930x00050051,0x00000006,0x000016d8,0x000016d6, 13580x00000bc0,0x00000001,0x00050080,0x00000006,
14940x00000000,0x00050051,0x00000006,0x000016db, 13590x000015f7,0x000015f5,0x000015f1,0x00050050,
14950x0000167b,0x00000001,0x00050080,0x00000006, 13600x00000007,0x000015f8,0x000015f2,0x000015f7,
14960x000016dd,0x000016db,0x000016d7,0x00050050, 13610x0004007c,0x00000014,0x000015e8,0x000015f8,
14970x00000007,0x000016de,0x000016d8,0x000016dd, 13620x00060041,0x000000db,0x000015e0,0x000015e8,
14980x0004007c,0x00000014,0x000016ce,0x000016de, 13630x000000da,0x000000da,0x0005003e,0x000015e0,
14990x00060041,0x000000d8,0x000016c6,0x000016ce, 13640x00000380,0x00000002,0x00000004,0x00050080,
15000x000000d7,0x000000d7,0x0005003e,0x000016c6, 13650x00000006,0x00000bc6,0x00000118,0x00000bb0,
15010x000016bb,0x00000002,0x00000004,0x00050080, 13660x00050095,0x000000ab,0x00001610,0x000015ee,
15020x00000006,0x00001681,0x00001679,0x00000107, 13670x00000bc6,0x00050051,0x00000006,0x00001611,
15030x00050051,0x00000027,0x00001685,0x00002b6b, 13680x00001610,0x00000001,0x00050051,0x00000006,
15040x00000001,0x0004007c,0x00000006,0x000016e4, 13690x00001612,0x00001610,0x00000000,0x00050080,
15050x00001685,0x00050095,0x000000a8,0x000016ff, 13700x00000006,0x00001617,0x000015f5,0x00001611,
15060x000016d4,0x00001681,0x00050051,0x00000006, 13710x00050050,0x00000007,0x00001618,0x00001612,
15070x00001700,0x000016ff,0x00000001,0x00050051, 13720x00001617,0x0004007c,0x00000014,0x00001608,
15080x00000006,0x00001701,0x000016ff,0x00000000, 13730x00001618,0x00060041,0x000000db,0x00001600,
15090x00050080,0x00000006,0x00001706,0x000016db, 13740x00001608,0x000000da,0x000000da,0x0005003e,
15100x00001700,0x00050050,0x00000007,0x00001707, 13750x00001600,0x000000a6,0x00000002,0x00000004,
15110x00001701,0x00001706,0x0004007c,0x00000014, 13760x000200f9,0x00000bbb,0x000200f8,0x00000bbb,
15120x000016f7,0x00001707,0x00060041,0x000000d8, 13770x000200f9,0x00000bac,0x000200f8,0x00000bcd,
15130x000016ef,0x000016f7,0x000000d7,0x000000d7, 13780x000500aa,0x0000002f,0x00000bd0,0x00000b13,
15140x0005003e,0x000016ef,0x000016e4,0x00000002, 13790x000000b0,0x000300f7,0x00000bd2,0x00000000,
15150x00000004,0x00050080,0x00000006,0x00001688, 13800x000400fa,0x00000bd0,0x00000bd1,0x00000bd6,
15160x00001679,0x0000010e,0x00050051,0x00000027, 13810x000200f8,0x00000bd1,0x000200f9,0x00001648,
15170x0000168c,0x00002b6b,0x00000002,0x0004007c, 13820x000200f8,0x00001648,0x000700f5,0x00000006,
15180x00000006,0x0000170d,0x0000168c,0x00050095, 13830x0000323a,0x000000a6,0x00000bd1,0x00001658,
15190x000000a8,0x00001728,0x000016d4,0x00001688, 13840x00001656,0x000500b0,0x0000002f,0x0000164b,
15200x00050051,0x00000006,0x00001729,0x00001728, 13850x0000323a,0x000002b7,0x000400f6,0x00001659,
15210x00000001,0x00050051,0x00000006,0x0000172a, 13860x00001656,0x00000000,0x000400fa,0x0000164b,
15220x00001728,0x00000000,0x00050080,0x00000006, 13870x0000164c,0x00001659,0x000200f8,0x0000164c,
15230x0000172f,0x000016db,0x00001729,0x00050050, 13880x00050084,0x00000006,0x0000164f,0x000002b7,
15240x00000007,0x00001730,0x0000172a,0x0000172f, 13890x00000b11,0x00050080,0x00000006,0x00001651,
15250x0004007c,0x00000014,0x00001720,0x00001730, 13900x0000164f,0x0000323a,0x000300f7,0x00001716,
15260x00060041,0x000000d8,0x00001718,0x00001720, 13910x00000000,0x000300fb,0x000000a6,0x000016f4,
15270x000000d7,0x000000d7,0x0005003e,0x00001718, 13920x000200f8,0x000016f4,0x00050041,0x000000fe,
15280x0000170d,0x00000002,0x00000004,0x00050080, 13930x000016f5,0x000000fc,0x0000027b,0x0004003d,
15290x00000006,0x0000168f,0x00001679,0x00000115, 13940x00000006,0x000016f6,0x000016f5,0x000500aa,
15300x00050051,0x00000027,0x00001693,0x00002b69, 13950x0000002f,0x000016f7,0x000016f6,0x000000a6,
15310x00000000,0x0004007c,0x00000006,0x00001736, 13960x000300f7,0x000016fa,0x00000000,0x000400fa,
15320x00001693,0x00050095,0x000000a8,0x00001751, 13970x000016f7,0x000016f8,0x000016fa,0x000200f8,
15330x000016d4,0x0000168f,0x00050051,0x00000006, 13980x000016f8,0x000200f9,0x00001716,0x000200f8,
15340x00001752,0x00001751,0x00000001,0x00050051, 13990x000016fa,0x000500aa,0x0000002f,0x000016fd,
15350x00000006,0x00001753,0x00001751,0x00000000, 14000x000016f6,0x00000170,0x000300f7,0x00001704,
15360x00050080,0x00000006,0x00001758,0x000016db, 14010x00000000,0x000400fa,0x000016fd,0x000016fe,
14020x00001704,0x000200f8,0x000016fe,0x00050084,
14030x00000006,0x00001700,0x0000010a,0x00001651,
14040x00050041,0x00000156,0x00001701,0x000000fc,
14050x0000020d,0x0004003d,0x00000007,0x00001702,
14060x00001701,0x00050051,0x00000006,0x0000172e,
14070x00001702,0x00000000,0x00050095,0x000000ab,
14080x00001730,0x0000172e,0x00001700,0x00050051,
14090x00000006,0x00001731,0x00001730,0x00000001,
14100x00050051,0x00000006,0x00001732,0x00001730,
14110x00000000,0x00050051,0x00000006,0x00001735,
14120x00001702,0x00000001,0x00050080,0x00000006,
14130x00001737,0x00001735,0x00001731,0x00050050,
14140x00000007,0x00001738,0x00001732,0x00001737,
14150x0004007c,0x00000014,0x00001728,0x00001738,
14160x00060041,0x000000db,0x0000171f,0x00001728,
14170x000000da,0x000000da,0x0006003d,0x00000006,
14180x00001720,0x0000171f,0x00000002,0x00000004,
14190x000200f9,0x00001716,0x000200f8,0x00001704,
14200x000500c2,0x00000006,0x00001706,0x00001651,
14210x00000154,0x00050084,0x00000006,0x00001707,
14220x0000010a,0x00001706,0x00050041,0x00000156,
14230x00001708,0x000000fc,0x0000020d,0x0004003d,
14240x00000007,0x00001709,0x00001708,0x00050051,
14250x00000006,0x0000174f,0x00001709,0x00000000,
14260x00050095,0x000000ab,0x00001751,0x0000174f,
14270x00001707,0x00050051,0x00000006,0x00001752,
14280x00001751,0x00000001,0x00050051,0x00000006,
14290x00001753,0x00001751,0x00000000,0x00050051,
14300x00000006,0x00001756,0x00001709,0x00000001,
14310x00050080,0x00000006,0x00001758,0x00001756,
15370x00001752,0x00050050,0x00000007,0x00001759, 14320x00001752,0x00050050,0x00000007,0x00001759,
15380x00001753,0x00001758,0x0004007c,0x00000014, 14330x00001753,0x00001758,0x0004007c,0x00000014,
15390x00001749,0x00001759,0x00060041,0x000000d8, 14340x00001749,0x00001759,0x00060041,0x000000db,
15400x00001741,0x00001749,0x000000d7,0x000000d7, 14350x00001740,0x00001749,0x000000da,0x000000da,
15410x0005003e,0x00001741,0x00001736,0x00000002, 14360x0006003d,0x00000006,0x00001741,0x00001740,
15420x00000004,0x00050080,0x00000006,0x00001696, 14370x00000002,0x00000004,0x000500c7,0x00000006,
15430x00001679,0x0000011c,0x00050051,0x00000027, 14380x0000170c,0x00001651,0x000000b0,0x000500ab,
15440x0000169a,0x00002b69,0x00000001,0x0004007c, 14390x0000002f,0x0000170d,0x0000170c,0x000000a6,
15450x00000006,0x0000175f,0x0000169a,0x00050095, 14400x000300f7,0x00001714,0x00000000,0x000400fa,
15460x000000a8,0x0000177a,0x000016d4,0x00001696, 14410x0000170d,0x0000170e,0x00001711,0x000200f8,
15470x00050051,0x00000006,0x0000177b,0x0000177a, 14420x0000170e,0x000500c2,0x00000006,0x00001710,
15480x00000001,0x00050051,0x00000006,0x0000177c, 14430x00001741,0x0000023e,0x000200f9,0x00001714,
15490x0000177a,0x00000000,0x00050080,0x00000006, 14440x000200f8,0x00001711,0x000500c7,0x00000006,
15500x00001781,0x000016db,0x0000177b,0x00050050, 14450x00001713,0x00001741,0x000002a3,0x000200f9,
15510x00000007,0x00001782,0x0000177c,0x00001781, 14460x00001714,0x000200f8,0x00001714,0x000700f5,
15520x0004007c,0x00000014,0x00001772,0x00001782, 14470x00000006,0x00003244,0x00001710,0x0000170e,
15530x00060041,0x000000d8,0x0000176a,0x00001772, 14480x00001713,0x00001711,0x000200f9,0x00001716,
15540x000000d7,0x000000d7,0x0005003e,0x0000176a, 14490x000200f8,0x00001716,0x000900f5,0x00000006,
15550x0000175f,0x00000002,0x00000004,0x00050080, 14500x00003245,0x00001651,0x000016f8,0x00001720,
15560x00000006,0x0000169d,0x00001679,0x00000186, 14510x000016fe,0x00003244,0x00001714,0x00050041,
15570x00050051,0x00000027,0x000016a1,0x00002b69, 14520x000000fe,0x0000176a,0x000000fc,0x00000250,
15580x00000002,0x0004007c,0x00000006,0x00001788, 14530x0004003d,0x00000006,0x0000176b,0x0000176a,
15590x000016a1,0x00050095,0x000000a8,0x000017a3, 14540x00050084,0x00000006,0x0000176c,0x00003245,
15600x000016d4,0x0000169d,0x00050051,0x00000006, 14550x0000176b,0x00050041,0x00000156,0x0000176d,
15610x000017a4,0x000017a3,0x00000001,0x00050051, 14560x000000fc,0x00000205,0x0004003d,0x00000007,
15620x00000006,0x000017a5,0x000017a3,0x00000000, 14570x0000176e,0x0000176d,0x00050051,0x00000006,
15630x00050080,0x00000006,0x000017aa,0x000016db, 14580x00001789,0x0000176e,0x00000000,0x00050095,
15640x000017a4,0x00050050,0x00000007,0x000017ab, 14590x000000ab,0x0000178b,0x00001789,0x0000176c,
15650x000017a5,0x000017aa,0x0004007c,0x00000014, 14600x00050051,0x00000006,0x0000178c,0x0000178b,
15660x0000179b,0x000017ab,0x00060041,0x000000d8, 14610x00000001,0x00050051,0x00000006,0x0000178d,
15670x00001793,0x0000179b,0x000000d7,0x000000d7, 14620x0000178b,0x00000000,0x00050051,0x00000006,
15680x0005003e,0x00001793,0x00001788,0x00000002, 14630x00001790,0x0000176e,0x00000001,0x00050080,
15690x00000004,0x000300f7,0x000017eb,0x00000000, 14640x00000006,0x00001792,0x00001790,0x0000178c,
15700x000300fb,0x000000a3,0x000017ba,0x000200f8, 14650x00050095,0x000000ab,0x000017ac,0x0000178d,
15710x000017ba,0x000500bc,0x0000002f,0x000017f2, 14660x000000a6,0x00050051,0x00000006,0x000017ad,
15720x0000167e,0x00001693,0x000300f7,0x000017f9, 14670x000017ac,0x00000001,0x00050051,0x00000006,
15730x00000000,0x000400fa,0x000017f2,0x000017f3, 14680x000017ae,0x000017ac,0x00000000,0x00050080,
15740x000017f9,0x000200f8,0x000017f3,0x000500bc, 14690x00000006,0x000017b3,0x00001792,0x000017ad,
15750x0000002f,0x000017f8,0x00001685,0x0000169a, 14700x00050050,0x00000007,0x000017b4,0x000017ae,
15760x000200f9,0x000017f9,0x000200f8,0x000017f9, 14710x000017b3,0x0004007c,0x00000014,0x000017a4,
15770x000700f5,0x0000002f,0x000017fa,0x000017f2, 14720x000017b4,0x00060041,0x000000db,0x0000179b,
15780x000017ba,0x000017f8,0x000017f3,0x000300f7, 14730x000017a4,0x000000da,0x000000da,0x0006003d,
15790x00001801,0x00000000,0x000400fa,0x000017fa, 14740x00000006,0x0000179c,0x0000179b,0x00000002,
15800x000017fb,0x00001801,0x000200f8,0x000017fb, 14750x00000004,0x0004007c,0x00000027,0x00001772,
15810x000500bc,0x0000002f,0x00001800,0x0000168c, 14760x0000179c,0x00050095,0x000000ab,0x000017cd,
15820x000016a1,0x000200f9,0x00001801,0x000200f8, 14770x0000178d,0x0000010a,0x00050051,0x00000006,
15830x00001801,0x000700f5,0x0000002f,0x00001802, 14780x000017ce,0x000017cd,0x00000001,0x00050051,
15840x000017fa,0x000017f9,0x00001800,0x000017fb, 14790x00000006,0x000017cf,0x000017cd,0x00000000,
15850x000400a8,0x0000002f,0x00001803,0x00001802, 14800x00050080,0x00000006,0x000017d4,0x00001792,
15860x000300f7,0x000017bf,0x00000000,0x000400fa, 14810x000017ce,0x00050050,0x00000007,0x000017d5,
15870x00001803,0x000017be,0x000017bf,0x000200f8, 14820x000017cf,0x000017d4,0x0004007c,0x00000014,
15880x000017be,0x000200f9,0x000017eb,0x000200f8, 14830x000017c5,0x000017d5,0x00060041,0x000000db,
15890x000017bf,0x00050081,0x0000004b,0x000017c2, 14840x000017bc,0x000017c5,0x000000da,0x000000da,
15900x00002b6b,0x00002b69,0x0005008e,0x0000004b, 14850x0006003d,0x00000006,0x000017bd,0x000017bc,
15910x000017c3,0x000017c2,0x000001ea,0x00050095,
15920x000000a8,0x00001813,0x000016d4,0x000000a3,
15930x00050051,0x00000006,0x00001814,0x00001813,
15940x00000001,0x00050051,0x00000006,0x00001815,
15950x00001813,0x00000000,0x00050080,0x00000006,
15960x0000181a,0x000016db,0x00001814,0x00050050,
15970x00000007,0x0000181b,0x00001815,0x0000181a,
15980x0004007c,0x00000014,0x0000180b,0x0000181b,
15990x00060041,0x000000d8,0x000017c8,0x0000180b,
16000x000000d7,0x000000d7,0x00050051,0x00000027,
16010x000017ca,0x000017c3,0x00000000,0x0004007c,
16020x00000006,0x00001821,0x000017ca,0x000500c7,
16030x00000006,0x00001823,0x00001821,0x0000012d,
16040x000500ab,0x0000002f,0x00001824,0x00001823,
16050x000000a3,0x000300f7,0x0000182b,0x00000000,
16060x000400fa,0x00001824,0x00001825,0x00001828,
16070x000200f8,0x00001825,0x000400c8,0x00000006,
16080x00001827,0x00001821,0x000200f9,0x0000182b,
16090x000200f8,0x00001828,0x000500c5,0x00000006,
16100x0000182a,0x00001821,0x0000012d,0x000200f9,
16110x0000182b,0x000200f8,0x0000182b,0x000700f5,
16120x00000006,0x00002b22,0x00001827,0x00001825,
16130x0000182a,0x00001828,0x000700ed,0x00000006,
16140x000017cc,0x000017c8,0x000000ad,0x000000a3,
16150x00002b22,0x00060041,0x000000d8,0x000017ce,
16160x0000180b,0x000000d7,0x00000151,0x00050051,
16170x00000027,0x000017d0,0x000017c3,0x00000001,
16180x0004007c,0x00000006,0x00001832,0x000017d0,
16190x000500c7,0x00000006,0x00001834,0x00001832,
16200x0000012d,0x000500ab,0x0000002f,0x00001835,
16210x00001834,0x000000a3,0x000300f7,0x0000183c,
16220x00000000,0x000400fa,0x00001835,0x00001836,
16230x00001839,0x000200f8,0x00001836,0x000400c8,
16240x00000006,0x00001838,0x00001832,0x000200f9,
16250x0000183c,0x000200f8,0x00001839,0x000500c5,
16260x00000006,0x0000183b,0x00001832,0x0000012d,
16270x000200f9,0x0000183c,0x000200f8,0x0000183c,
16280x000700f5,0x00000006,0x00002b23,0x00001838,
16290x00001836,0x0000183b,0x00001839,0x000700ed,
16300x00000006,0x000017d2,0x000017ce,0x000000ad,
16310x000000a3,0x00002b23,0x00060041,0x000000d8,
16320x000017d4,0x0000180b,0x000000d7,0x00000202,
16330x00050051,0x00000027,0x000017d6,0x000017c3,
16340x00000002,0x0004007c,0x00000006,0x00001843,
16350x000017d6,0x000500c7,0x00000006,0x00001845,
16360x00001843,0x0000012d,0x000500ab,0x0000002f,
16370x00001846,0x00001845,0x000000a3,0x000300f7,
16380x0000184d,0x00000000,0x000400fa,0x00001846,
16390x00001847,0x0000184a,0x000200f8,0x00001847,
16400x000400c8,0x00000006,0x00001849,0x00001843,
16410x000200f9,0x0000184d,0x000200f8,0x0000184a,
16420x000500c5,0x00000006,0x0000184c,0x00001843,
16430x0000012d,0x000200f9,0x0000184d,0x000200f8,
16440x0000184d,0x000700f5,0x00000006,0x00002b24,
16450x00001849,0x00001847,0x0000184c,0x0000184a,
16460x000700ed,0x00000006,0x000017d8,0x000017d4,
16470x000000ad,0x000000a3,0x00002b24,0x00060041,
16480x000000d8,0x000017da,0x0000180b,0x000000d7,
16490x0000020a,0x000300f7,0x0000185e,0x00000000,
16500x000400fa,0x00001824,0x00001858,0x0000185b,
16510x000200f8,0x00001858,0x000400c8,0x00000006,
16520x0000185a,0x00001821,0x000200f9,0x0000185e,
16530x000200f8,0x0000185b,0x000500c5,0x00000006,
16540x0000185d,0x00001821,0x0000012d,0x000200f9,
16550x0000185e,0x000200f8,0x0000185e,0x000700f5,
16560x00000006,0x00002b25,0x0000185a,0x00001858,
16570x0000185d,0x0000185b,0x000700ef,0x00000006,
16580x000017de,0x000017da,0x000000ad,0x000000a3,
16590x00002b25,0x00060041,0x000000d8,0x000017e0,
16600x0000180b,0x000000d7,0x00000212,0x000300f7,
16610x0000186f,0x00000000,0x000400fa,0x00001835,
16620x00001869,0x0000186c,0x000200f8,0x00001869,
16630x000400c8,0x00000006,0x0000186b,0x00001832,
16640x000200f9,0x0000186f,0x000200f8,0x0000186c,
16650x000500c5,0x00000006,0x0000186e,0x00001832,
16660x0000012d,0x000200f9,0x0000186f,0x000200f8,
16670x0000186f,0x000700f5,0x00000006,0x00002b26,
16680x0000186b,0x00001869,0x0000186e,0x0000186c,
16690x000700ef,0x00000006,0x000017e4,0x000017e0,
16700x000000ad,0x000000a3,0x00002b26,0x00060041,
16710x000000d8,0x000017e6,0x0000180b,0x000000d7,
16720x0000021a,0x000300f7,0x00001880,0x00000000,
16730x000400fa,0x00001846,0x0000187a,0x0000187d,
16740x000200f8,0x0000187a,0x000400c8,0x00000006,
16750x0000187c,0x00001843,0x000200f9,0x00001880,
16760x000200f8,0x0000187d,0x000500c5,0x00000006,
16770x0000187f,0x00001843,0x0000012d,0x000200f9,
16780x00001880,0x000200f8,0x00001880,0x000700f5,
16790x00000006,0x00002b27,0x0000187c,0x0000187a,
16800x0000187f,0x0000187d,0x000700ef,0x00000006,
16810x000017ea,0x000017e6,0x000000ad,0x000000a3,
16820x00002b27,0x000200f9,0x000017eb,0x000200f8,
16830x000017eb,0x000200f9,0x00000a4d,0x000200f8,
16840x00000a51,0x000500aa,0x0000002f,0x00000a54,
16850x000009eb,0x0000016d,0x000300f7,0x00000a56,
16860x00000000,0x000400fa,0x00000a54,0x00000a55,
16870x00000a5a,0x000200f8,0x00000a55,0x00050084,
16880x00000006,0x000018e9,0x00000104,0x000009e9,
16890x000200f9,0x000018ea,0x000200f8,0x000018ea,
16900x000700f5,0x00000006,0x00002ad4,0x000000a3,
16910x00000a55,0x000018fb,0x000018ee,0x000500b0,
16920x0000002f,0x000018ed,0x00002ad4,0x00000115,
16930x000400f6,0x000018fc,0x000018ee,0x00000000,
16940x000400fa,0x000018ed,0x000018ee,0x000018fc,
16950x000200f8,0x000018ee,0x00050084,0x00000006,
16960x000018f2,0x00000107,0x00002ad4,0x00050080,
16970x00000006,0x000018f3,0x000018e9,0x000018f2,
16980x00050041,0x00000153,0x000018f4,0x000000f9,
16990x00000202,0x0004003d,0x00000007,0x000018f5,
17000x000018f4,0x00050051,0x00000006,0x00001ab6,
17010x000018f5,0x00000000,0x00050095,0x000000a8,
17020x00001ab8,0x00001ab6,0x000018f3,0x00050051,
17030x00000006,0x00001ab9,0x00001ab8,0x00000001,
17040x00050051,0x00000006,0x00001aba,0x00001ab8,
17050x00000000,0x00050051,0x00000006,0x00001abd,
17060x000018f5,0x00000001,0x00050080,0x00000006,
17070x00001abf,0x00001abd,0x00001ab9,0x00050050,
17080x00000007,0x00001ac0,0x00001aba,0x00001abf,
17090x0004007c,0x00000014,0x00001ab0,0x00001ac0,
17100x00060041,0x000000d8,0x00001aa7,0x00001ab0,
17110x000000d7,0x000000d7,0x0006003d,0x00000006,
17120x00001aa8,0x00001aa7,0x00000002,0x00000004,
17130x0004007c,0x00000027,0x000018f7,0x00001aa8,
17140x00050041,0x00000028,0x000018f8,0x00001884,
17150x00002ad4,0x0003003e,0x000018f8,0x000018f7,
17160x00050080,0x00000006,0x000018fb,0x00002ad4,
17170x00000151,0x000200f9,0x000018ea,0x000200f8,
17180x000018fc,0x00050080,0x00000006,0x000018fe,
17190x000018e9,0x00000365,0x00050041,0x00000153,
17200x000018ff,0x000000f9,0x00000202,0x0004003d,
17210x00000007,0x00001900,0x000018ff,0x00050051,
17220x00000006,0x00001ad7,0x00001900,0x00000000,
17230x00050095,0x000000a8,0x00001ad9,0x00001ad7,
17240x000018fe,0x00050051,0x00000006,0x00001ada,
17250x00001ad9,0x00000001,0x00050051,0x00000006,
17260x00001adb,0x00001ad9,0x00000000,0x00050051,
17270x00000006,0x00001ade,0x00001900,0x00000001,
17280x00050080,0x00000006,0x00001ae0,0x00001ade,
17290x00001ada,0x00050050,0x00000007,0x00001ae1,
17300x00001adb,0x00001ae0,0x0004007c,0x00000014,
17310x00001ad1,0x00001ae1,0x00060041,0x000000d8,
17320x00001ac8,0x00001ad1,0x000000d7,0x000000d7,
17330x0006003d,0x00000006,0x00001ac9,0x00001ac8,
17340x00000002,0x00000004,0x00050080,0x00000006,
17350x00001903,0x000018e9,0x00000371,0x00050095,
17360x000000a8,0x00001afa,0x00001ad7,0x00001903,
17370x00050051,0x00000006,0x00001afb,0x00001afa,
17380x00000001,0x00050051,0x00000006,0x00001afc,
17390x00001afa,0x00000000,0x00050080,0x00000006,
17400x00001b01,0x00001ade,0x00001afb,0x00050050,
17410x00000007,0x00001b02,0x00001afc,0x00001b01,
17420x0004007c,0x00000014,0x00001af2,0x00001b02,
17430x00060041,0x000000d8,0x00001ae9,0x00001af2,
17440x000000d7,0x000000d7,0x0006003d,0x00000006,
17450x00001aea,0x00001ae9,0x00000002,0x00000004,
17460x00050080,0x00000006,0x00001908,0x000018e9,
17470x0000037b,0x00050095,0x000000a8,0x00001b1b,
17480x00001ad7,0x00001908,0x00050051,0x00000006,
17490x00001b1c,0x00001b1b,0x00000001,0x00050051,
17500x00000006,0x00001b1d,0x00001b1b,0x00000000,
17510x00050080,0x00000006,0x00001b22,0x00001ade,
17520x00001b1c,0x00050050,0x00000007,0x00001b23,
17530x00001b1d,0x00001b22,0x0004007c,0x00000014,
17540x00001b13,0x00001b23,0x00060041,0x000000d8,
17550x00001b0a,0x00001b13,0x000000d7,0x000000d7,
17560x0006003d,0x00000006,0x00001b0b,0x00001b0a,
17570x00000002,0x00000004,0x00050080,0x00000006,
17580x0000190d,0x000018e9,0x00000385,0x00050095,
17590x000000a8,0x00001b3c,0x00001ad7,0x0000190d,
17600x00050051,0x00000006,0x00001b3d,0x00001b3c,
17610x00000001,0x00050051,0x00000006,0x00001b3e,
17620x00001b3c,0x00000000,0x00050080,0x00000006,
17630x00001b43,0x00001ade,0x00001b3d,0x00050050,
17640x00000007,0x00001b44,0x00001b3e,0x00001b43,
17650x0004007c,0x00000014,0x00001b34,0x00001b44,
17660x00060041,0x000000d8,0x00001b2b,0x00001b34,
17670x000000d7,0x000000d7,0x0006003d,0x00000006,
17680x00001b2c,0x00001b2b,0x00000002,0x00000004,
17690x00050041,0x000000fb,0x00001912,0x000000f9,
17700x00000229,0x0004003d,0x00000006,0x00001913,
17710x00001912,0x00050084,0x00000006,0x00001915,
17720x00000225,0x000009e9,0x00050080,0x00000006,
17730x00001916,0x00001913,0x00001915,0x000200f9,
17740x00001917,0x000200f8,0x00001917,0x000700f5,
17750x00000006,0x00002ad5,0x000000a3,0x000018fc,
17760x00001928,0x0000191b,0x000500b0,0x0000002f,
17770x0000191a,0x00002ad5,0x00000115,0x000400f6,
17780x00001929,0x0000191b,0x00000000,0x000400fa,
17790x0000191a,0x0000191b,0x00001929,0x000200f8,
17800x0000191b,0x00050084,0x00000006,0x0000191e,
17810x00000107,0x00002ad5,0x00050080,0x00000006,
17820x0000191f,0x00001916,0x0000191e,0x00050041,
17830x00000153,0x00001921,0x000000f9,0x000000d7,
17840x0004003d,0x00000007,0x00001922,0x00001921,
17850x00050041,0x00000028,0x00001923,0x00001884,
17860x00002ad5,0x0004003d,0x00000027,0x00001924,
17870x00001923,0x0004007c,0x00000006,0x00001b4a,
17880x00001924,0x00050051,0x00000006,0x00001b63,
17890x00001922,0x00000000,0x00050095,0x000000a8,
17900x00001b65,0x00001b63,0x0000191f,0x00050051,
17910x00000006,0x00001b66,0x00001b65,0x00000001,
17920x00050051,0x00000006,0x00001b67,0x00001b65,
17930x00000000,0x00050051,0x00000006,0x00001b6a,
17940x00001922,0x00000001,0x00050080,0x00000006,
17950x00001b6c,0x00001b6a,0x00001b66,0x00050050,
17960x00000007,0x00001b6d,0x00001b67,0x00001b6c,
17970x0004007c,0x00000014,0x00001b5d,0x00001b6d,
17980x00060041,0x000000d8,0x00001b55,0x00001b5d,
17990x000000d7,0x000000d7,0x0005003e,0x00001b55,
18000x00001b4a,0x00000002,0x00000004,0x00050080,
18010x00000006,0x00001928,0x00002ad5,0x00000151,
18020x000200f9,0x00001917,0x000200f8,0x00001929,
18030x00050080,0x00000006,0x0000192b,0x00001916,
18040x00000365,0x00050041,0x00000153,0x0000192c,
18050x000000f9,0x000000d7,0x0004003d,0x00000007,
18060x0000192d,0x0000192c,0x00050051,0x00000006,
18070x00001b83,0x0000192d,0x00000000,0x00050095,
18080x000000a8,0x00001b85,0x00001b83,0x0000192b,
18090x00050051,0x00000006,0x00001b86,0x00001b85,
18100x00000001,0x00050051,0x00000006,0x00001b87,
18110x00001b85,0x00000000,0x00050051,0x00000006,
18120x00001b8a,0x0000192d,0x00000001,0x00050080,
18130x00000006,0x00001b8c,0x00001b8a,0x00001b86,
18140x00050050,0x00000007,0x00001b8d,0x00001b87,
18150x00001b8c,0x0004007c,0x00000014,0x00001b7d,
18160x00001b8d,0x00060041,0x000000d8,0x00001b75,
18170x00001b7d,0x000000d7,0x000000d7,0x0005003e,
18180x00001b75,0x00001ac9,0x00000002,0x00000004,
18190x00050080,0x00000006,0x00001931,0x00001916,
18200x00000371,0x00050095,0x000000a8,0x00001ba5,
18210x00001b83,0x00001931,0x00050051,0x00000006,
18220x00001ba6,0x00001ba5,0x00000001,0x00050051,
18230x00000006,0x00001ba7,0x00001ba5,0x00000000,
18240x00050080,0x00000006,0x00001bac,0x00001b8a,
18250x00001ba6,0x00050050,0x00000007,0x00001bad,
18260x00001ba7,0x00001bac,0x0004007c,0x00000014,
18270x00001b9d,0x00001bad,0x00060041,0x000000d8,
18280x00001b95,0x00001b9d,0x000000d7,0x000000d7,
18290x0005003e,0x00001b95,0x00001aea,0x00000002,
18300x00000004,0x000500aa,0x0000002f,0x00001bb2,
18310x00001b0b,0x000000a3,0x000300f7,0x00001bb7,
18320x00000000,0x000400fa,0x00001bb2,0x00001bb3,
18330x00001bb7,0x000200f8,0x00001bb3,0x000500aa,
18340x0000002f,0x00001bb6,0x00001b2c,0x000000a3,
18350x000200f9,0x00001bb7,0x000200f8,0x00001bb7,
18360x000700f5,0x0000002f,0x00001bb8,0x00001bb2,
18370x00001929,0x00001bb6,0x00001bb3,0x000400a8,
18380x0000002f,0x0000193c,0x00001bb8,0x000300f7,
18390x000019d2,0x00000000,0x000400fa,0x0000193c,
18400x0000193d,0x000019d2,0x000200f8,0x0000193d,
18410x00050041,0x00000153,0x0000193f,0x000000f9,
18420x0000021a,0x0004003d,0x00000007,0x00001940,
18430x0000193f,0x00050051,0x00000006,0x00001bc0,
18440x00001940,0x00000000,0x00050095,0x000000a8,
18450x00001bc1,0x00001b0b,0x00001bc0,0x00050051,
18460x00000006,0x00001bc2,0x00001bc1,0x00000001,
18470x00050051,0x00000006,0x00001bc3,0x00001bc1,
18480x00000000,0x00050051,0x00000006,0x00001bc8,
18490x00001940,0x00000001,0x00050080,0x00000006,
18500x00001bc9,0x00001b2c,0x00001bc8,0x00050080,
18510x00000006,0x00001bcb,0x00001bc9,0x00001bc2,
18520x00050095,0x000000a8,0x00001be5,0x00001bc3,
18530x00000365,0x00050051,0x00000006,0x00001be6,
18540x00001be5,0x00000001,0x00050051,0x00000006,
18550x00001be7,0x00001be5,0x00000000,0x00050080,
18560x00000006,0x00001bec,0x00001bcb,0x00001be6,
18570x00050050,0x00000007,0x00001bed,0x00001be7,
18580x00001bec,0x0004007c,0x00000014,0x00001bdd,
18590x00001bed,0x00060041,0x000000d8,0x00001bd4,
18600x00001bdd,0x000000d7,0x000000d7,0x0006003d,
18610x00000006,0x00001bd5,0x00001bd4,0x00000002,
18620x00000004,0x00050095,0x000000a8,0x00001c06,
18630x00001bc3,0x0000011c,0x00050051,0x00000006,
18640x00001c07,0x00001c06,0x00000001,0x00050051,
18650x00000006,0x00001c08,0x00001c06,0x00000000,
18660x00050080,0x00000006,0x00001c0d,0x00001bcb,
18670x00001c07,0x00050050,0x00000007,0x00001c0e,
18680x00001c08,0x00001c0d,0x0004007c,0x00000014,
18690x00001bfe,0x00001c0e,0x00060041,0x000000d8,
18700x00001bf5,0x00001bfe,0x000000d7,0x000000d7,
18710x0006003d,0x00000006,0x00001bf6,0x00001bf5,
18720x00000002,0x00000004,0x0004007c,0x00000027, 14860x00000002,0x00000004,0x0004007c,0x00000027,
18730x00001946,0x00001bf6,0x00050095,0x000000a8, 14870x00001775,0x000017bd,0x00050041,0x000000fe,
18740x00001c27,0x00001bc3,0x00000186,0x00050051, 14880x00001776,0x000000fc,0x00000266,0x0004003d,
18750x00000006,0x00001c28,0x00001c27,0x00000001, 14890x00000006,0x00001777,0x00001776,0x000500aa,
18760x00050051,0x00000006,0x00001c29,0x00001c27, 14900x0000002f,0x00001778,0x00001777,0x000000b0,
18770x00000000,0x00050080,0x00000006,0x00001c2e, 14910x000300f7,0x0000177e,0x00000000,0x000400fa,
18780x00001bcb,0x00001c28,0x00050050,0x00000007, 14920x00001778,0x00001779,0x0000177a,0x000200f8,
18790x00001c2f,0x00001c29,0x00001c2e,0x0004007c, 14930x00001779,0x000200f9,0x0000177e,0x000200f8,
18800x00000014,0x00001c1f,0x00001c2f,0x00060041, 14940x0000177a,0x00050095,0x000000ab,0x000017ee,
18810x000000d8,0x00001c16,0x00001c1f,0x000000d7, 14950x0000178d,0x00000111,0x00050051,0x00000006,
18820x000000d7,0x0006003d,0x00000006,0x00001c17, 14960x000017ef,0x000017ee,0x00000001,0x00050051,
18830x00001c16,0x00000002,0x00000004,0x0004007c, 14970x00000006,0x000017f0,0x000017ee,0x00000000,
18840x00000027,0x00001949,0x00001c17,0x00050095, 14980x00050080,0x00000006,0x000017f5,0x00001792,
18850x000000a8,0x00001c48,0x00001bc3,0x0000014d, 14990x000017ef,0x00050050,0x00000007,0x000017f6,
18860x00050051,0x00000006,0x00001c49,0x00001c48, 15000x000017f0,0x000017f5,0x0004007c,0x00000014,
18870x00000001,0x00050051,0x00000006,0x00001c4a, 15010x000017e6,0x000017f6,0x00060041,0x000000db,
18880x00001c48,0x00000000,0x00050080,0x00000006, 15020x000017dd,0x000017e6,0x000000da,0x000000da,
18890x00001c4f,0x00001bcb,0x00001c49,0x00050050, 15030x0006003d,0x00000006,0x000017de,0x000017dd,
18900x00000007,0x00001c50,0x00001c4a,0x00001c4f,
18910x0004007c,0x00000014,0x00001c40,0x00001c50,
18920x00060041,0x000000d8,0x00001c37,0x00001c40,
18930x000000d7,0x000000d7,0x0006003d,0x00000006,
18940x00001c38,0x00001c37,0x00000002,0x00000004,
18950x0004007c,0x00000027,0x0000194c,0x00001c38,
18960x00050095,0x000000a8,0x00001c69,0x00001bc3,
18970x00000460,0x00050051,0x00000006,0x00001c6a,
18980x00001c69,0x00000001,0x00050051,0x00000006,
18990x00001c6b,0x00001c69,0x00000000,0x00050080,
19000x00000006,0x00001c70,0x00001bcb,0x00001c6a,
19010x00050050,0x00000007,0x00001c71,0x00001c6b,
19020x00001c70,0x0004007c,0x00000014,0x00001c61,
19030x00001c71,0x00060041,0x000000d8,0x00001c58,
19040x00001c61,0x000000d7,0x000000d7,0x0006003d,
19050x00000006,0x00001c59,0x00001c58,0x00000002,
19060x00000004,0x0004007c,0x00000027,0x00001950,
19070x00001c59,0x00050095,0x000000a8,0x00001c8a,
19080x00001bc3,0x00000466,0x00050051,0x00000006,
19090x00001c8b,0x00001c8a,0x00000001,0x00050051,
19100x00000006,0x00001c8c,0x00001c8a,0x00000000,
19110x00050080,0x00000006,0x00001c91,0x00001bcb,
19120x00001c8b,0x00050050,0x00000007,0x00001c92,
19130x00001c8c,0x00001c91,0x0004007c,0x00000014,
19140x00001c82,0x00001c92,0x00060041,0x000000d8,
19150x00001c79,0x00001c82,0x000000d7,0x000000d7,
19160x0006003d,0x00000006,0x00001c7a,0x00001c79,
19170x00000002,0x00000004,0x0004007c,0x00000027, 15040x00000002,0x00000004,0x0004007c,0x00000027,
19180x00001953,0x00001c7a,0x00050095,0x000000a8, 15050x0000177d,0x000017de,0x000200f9,0x0000177e,
19190x00001cab,0x00001bc3,0x00000344,0x00050051, 15060x000200f8,0x0000177e,0x000700f5,0x00000027,
19200x00000006,0x00001cac,0x00001cab,0x00000001, 15070x00003246,0x0000026d,0x00001779,0x0000177d,
19210x00050051,0x00000006,0x00001cad,0x00001cab, 15080x0000177a,0x00060050,0x0000004b,0x00001783,
19220x00000000,0x00050080,0x00000006,0x00001cb2, 15090x00001772,0x00001775,0x00003246,0x000300f7,
19230x00001bcb,0x00001cac,0x00050050,0x00000007, 15100x0000183c,0x00000000,0x000300fb,0x000000a6,
19240x00001cb3,0x00001cad,0x00001cb2,0x0004007c, 15110x00001808,0x000200f8,0x00001808,0x00050041,
19250x00000014,0x00001ca3,0x00001cb3,0x00060041, 15120x00000156,0x00001809,0x000000fc,0x00000215,
19260x000000d8,0x00001c9a,0x00001ca3,0x000000d7, 15130x0004003d,0x00000007,0x0000180a,0x00001809,
19270x000000d7,0x0006003d,0x00000006,0x00001c9b, 15140x00050051,0x00000006,0x00001841,0x0000180a,
19280x00001c9a,0x00000002,0x00000004,0x0004007c, 15150x00000000,0x000500aa,0x0000002f,0x00001842,
19290x00000027,0x00001956,0x00001c9b,0x000500bc, 15160x00001841,0x000000a6,0x000300f7,0x00001847,
19300x0000002f,0x00001cba,0x00001946,0x00001950, 15170x00000000,0x000400fa,0x00001842,0x00001843,
19310x000300f7,0x00001cc1,0x00000000,0x000400fa, 15180x00001847,0x000200f8,0x00001843,0x00050051,
19320x00001cba,0x00001cbb,0x00001cc1,0x000200f8, 15190x00000006,0x00001845,0x0000180a,0x00000001,
19330x00001cbb,0x000500bc,0x0000002f,0x00001cc0, 15200x000500aa,0x0000002f,0x00001846,0x00001845,
19340x00001949,0x00001953,0x000200f9,0x00001cc1, 15210x000000a6,0x000200f9,0x00001847,0x000200f8,
19350x000200f8,0x00001cc1,0x000700f5,0x0000002f, 15220x00001847,0x000700f5,0x0000002f,0x00001848,
19360x00001cc2,0x00001cba,0x0000193d,0x00001cc0, 15230x00001842,0x00001808,0x00001846,0x00001843,
19370x00001cbb,0x000300f7,0x00001cc9,0x00000000, 15240x000300f7,0x0000180e,0x00000000,0x000400fa,
19380x000400fa,0x00001cc2,0x00001cc3,0x00001cc9, 15250x00001848,0x0000180c,0x0000180e,0x000200f8,
19390x000200f8,0x00001cc3,0x000500bc,0x0000002f, 15260x0000180c,0x000200f9,0x0000183c,0x000200f8,
19400x00001cc8,0x0000194c,0x00001956,0x000200f9, 15270x0000180e,0x000200f9,0x0000180f,0x000200f8,
19410x00001cc9,0x000200f8,0x00001cc9,0x000700f5, 15280x0000180f,0x000700f5,0x00000006,0x00003247,
19420x0000002f,0x00001cca,0x00001cc2,0x00001cc1, 15290x000000a6,0x0000180e,0x00001839,0x00001813,
19430x00001cc8,0x00001cc3,0x000300f7,0x00001960, 15300x000500b0,0x0000002f,0x00001812,0x00003247,
19440x00000000,0x000400fa,0x00001cca,0x0000195c, 15310x000002b7,0x000400f6,0x0000183a,0x00001813,
19450x00001960,0x000200f8,0x0000195c,0x000500c2, 15320x00000000,0x000400fa,0x00001812,0x00001813,
19460x00000006,0x0000195e,0x00001ac9,0x0000047b, 15330x0000183a,0x000200f8,0x00001813,0x00050084,
19470x000500ab,0x0000002f,0x0000195f,0x0000195e, 15340x00000006,0x00001815,0x0000011f,0x00003247,
19480x000000a3,0x000200f9,0x00001960,0x000200f8, 15350x00050095,0x000000ab,0x00001861,0x00001841,
19490x00001960,0x000700f5,0x0000002f,0x00001961, 15360x00001815,0x00050051,0x00000006,0x00001862,
19500x00001cca,0x00001cc9,0x0000195f,0x0000195c, 15370x00001861,0x00000001,0x00050051,0x00000006,
19510x000300f7,0x000019d1,0x00000000,0x000400fa, 15380x00001863,0x00001861,0x00000000,0x00050051,
19520x00001961,0x00001962,0x000019d1,0x000200f8, 15390x00000006,0x00001866,0x0000180a,0x00000001,
19530x00001962,0x000200f9,0x00001963,0x000200f8, 15400x00050080,0x00000006,0x00001868,0x00001866,
19540x00001963,0x000700f5,0x0000004b,0x00002b0b, 15410x00001862,0x00050050,0x00000007,0x00001869,
19550x00002b66,0x00001962,0x000019cc,0x00001967, 15420x00001863,0x00001868,0x0004007c,0x00000014,
19560x000700f5,0x0000004b,0x00002af9,0x00002b64, 15430x00001859,0x00001869,0x00060041,0x000000db,
19570x00001962,0x000019c9,0x00001967,0x000700f5, 15440x00001850,0x00001859,0x000000da,0x000000da,
19580x00000006,0x00002ad6,0x000000a3,0x00001962, 15450x0006003d,0x00000006,0x00001851,0x00001850,
19590x000019cf,0x00001967,0x000500b0,0x0000002f, 15460x00000002,0x00000004,0x0004007c,0x00000027,
19600x00001966,0x00002ad6,0x0000010e,0x000400f6, 15470x0000181a,0x00001851,0x00050080,0x00000006,
19610x000019d0,0x00001967,0x00000000,0x000400fa, 15480x0000181c,0x00001815,0x0000010a,0x00050095,
19620x00001966,0x00001967,0x000019d0,0x000200f8, 15490x000000ab,0x00001882,0x00001841,0x0000181c,
19630x00001967,0x000500c7,0x00000006,0x00001969, 15500x00050051,0x00000006,0x00001883,0x00001882,
19640x00002ad6,0x000000ad,0x000500ab,0x0000002f, 15510x00000001,0x00050051,0x00000006,0x00001884,
19650x0000196a,0x00001969,0x000000a3,0x000600a9, 15520x00001882,0x00000000,0x00050080,0x00000006,
19660x00000027,0x00002b6c,0x0000196a,0x00001950, 15530x00001889,0x00001866,0x00001883,0x00050050,
19670x00001946,0x000500c7,0x00000006,0x00001974, 15540x00000007,0x0000188a,0x00001884,0x00001889,
19680x00002ad6,0x0000016d,0x000500ab,0x0000002f, 15550x0004007c,0x00000014,0x0000187a,0x0000188a,
19690x00001975,0x00001974,0x000000a3,0x000600a9, 15560x00060041,0x000000db,0x00001871,0x0000187a,
19700x00000027,0x00002b6d,0x00001975,0x00001953, 15570x000000da,0x000000da,0x0006003d,0x00000006,
19710x00001949,0x000500c7,0x00000006,0x0000197f, 15580x00001872,0x00001871,0x00000002,0x00000004,
19720x00002ad6,0x00000107,0x000500ab,0x0000002f, 15590x0004007c,0x00000027,0x00001820,0x00001872,
19730x00001980,0x0000197f,0x000000a3,0x000600a9, 15600x00050080,0x00000006,0x00001822,0x00001815,
19740x00000027,0x00002b6e,0x00001980,0x00001956, 15610x00000111,0x00050095,0x000000ab,0x000018a3,
19750x0000194c,0x00050041,0x00000028,0x0000198a, 15620x00001841,0x00001822,0x00050051,0x00000006,
19760x00001884,0x000000d7,0x0004003d,0x00000027, 15630x000018a4,0x000018a3,0x00000001,0x00050051,
19770x0000198b,0x0000198a,0x00050085,0x00000027, 15640x00000006,0x000018a5,0x000018a3,0x00000000,
19780x0000198e,0x0000198b,0x00002b6c,0x00050041, 15650x00050080,0x00000006,0x000018aa,0x00001866,
19790x00000028,0x0000198f,0x00001884,0x00000151, 15660x000018a4,0x00050050,0x00000007,0x000018ab,
19800x0004003d,0x00000027,0x00001990,0x0000198f, 15670x000018a5,0x000018aa,0x0004007c,0x00000014,
19810x00050085,0x00000027,0x00001993,0x00001990, 15680x0000189b,0x000018ab,0x00060041,0x000000db,
19820x00002b6d,0x00050081,0x00000027,0x00001994, 15690x00001892,0x0000189b,0x000000da,0x000000da,
19830x0000198e,0x00001993,0x00050041,0x00000028, 15700x0006003d,0x00000006,0x00001893,0x00001892,
19840x00001995,0x00001884,0x00000202,0x0004003d, 15710x00000002,0x00000004,0x0004007c,0x00000027,
19850x00000027,0x00001996,0x00001995,0x00050085, 15720x00001826,0x00001893,0x00050080,0x00000006,
19860x00000027,0x00001999,0x00001996,0x00002b6e, 15730x00001828,0x00001815,0x00000118,0x00050095,
19870x00050081,0x00000027,0x0000199a,0x00001994, 15740x000000ab,0x000018c4,0x00001841,0x00001828,
19880x00001999,0x00050041,0x00000028,0x0000199b, 15750x00050051,0x00000006,0x000018c5,0x000018c4,
19890x00001884,0x0000020a,0x0004003d,0x00000027, 15760x00000001,0x00050051,0x00000006,0x000018c6,
19900x0000199c,0x0000199b,0x00050081,0x00000027, 15770x000018c4,0x00000000,0x00050080,0x00000006,
19910x0000199d,0x0000199a,0x0000199c,0x00050041, 15780x000018cb,0x00001866,0x000018c5,0x00050050,
19920x00000028,0x0000199e,0x00001884,0x00000212, 15790x00000007,0x000018cc,0x000018c6,0x000018cb,
19930x0004003d,0x00000027,0x0000199f,0x0000199e, 15800x0004007c,0x00000014,0x000018bc,0x000018cc,
19940x00050085,0x00000027,0x000019a2,0x0000199f, 15810x00060041,0x000000db,0x000018b3,0x000018bc,
19950x00002b6c,0x00050041,0x00000028,0x000019a3, 15820x000000da,0x000000da,0x0006003d,0x00000006,
19960x00001884,0x0000021a,0x0004003d,0x00000027, 15830x000018b4,0x000018b3,0x00000002,0x00000004,
19970x000019a4,0x000019a3,0x00050085,0x00000027, 15840x0004007c,0x00000027,0x0000182c,0x000018b4,
19980x000019a7,0x000019a4,0x00002b6d,0x00050081, 15850x00070050,0x000002bc,0x0000182d,0x0000181a,
19990x00000027,0x000019a8,0x000019a2,0x000019a7, 15860x00001820,0x00001826,0x0000182c,0x0008004f,
20000x00050041,0x00000028,0x000019a9,0x00001884, 15870x0000004b,0x00001830,0x0000182d,0x0000182d,
20010x00000230,0x0004003d,0x00000027,0x000019aa, 15880x00000000,0x00000001,0x00000002,0x00050094,
20020x000019a9,0x00050085,0x00000027,0x000019ad, 15890x00000027,0x00001832,0x00001830,0x00001783,
20030x000019aa,0x00002b6e,0x00050081,0x00000027, 15900x00050081,0x00000027,0x00001835,0x00001832,
20040x000019ae,0x000019a8,0x000019ad,0x00050041, 15910x0000182c,0x00050041,0x00000028,0x00001836,
20050x00000028,0x000019af,0x00001884,0x000004d5, 15920x00001805,0x00003247,0x0003003e,0x00001836,
20060x0004003d,0x00000027,0x000019b0,0x000019af, 15930x00001835,0x00050080,0x00000006,0x00001839,
20070x00050081,0x00000027,0x000019b1,0x000019ae, 15940x00003247,0x00000154,0x000200f9,0x0000180f,
20080x000019b0,0x00050041,0x00000028,0x000019b2, 15950x000200f8,0x0000183a,0x0004003d,0x0000004b,
20090x00001884,0x00000305,0x0004003d,0x00000027, 15960x0000183b,0x00001805,0x000200f9,0x0000183c,
20100x000019b3,0x000019b2,0x00050085,0x00000027, 15970x000200f8,0x0000183c,0x000700f5,0x0000004b,
20110x000019b6,0x000019b3,0x00002b6c,0x00050041, 15980x00003248,0x00001783,0x0000180c,0x0000183b,
20120x00000028,0x000019b7,0x00001884,0x0000024d, 15990x0000183a,0x00050041,0x0000004c,0x00001655,
20130x0004003d,0x00000027,0x000019b8,0x000019b7, 16000x0000161a,0x0000323a,0x0003003e,0x00001655,
20140x00050085,0x00000027,0x000019bb,0x000019b8, 16010x00003248,0x000200f9,0x00001656,0x000200f8,
20150x00002b6d,0x00050081,0x00000027,0x000019bc, 16020x00001656,0x00050080,0x00000006,0x00001658,
20160x000019b6,0x000019bb,0x00050041,0x00000028, 16030x0000323a,0x00000154,0x000200f9,0x00001648,
20170x000019bd,0x00001884,0x00000263,0x0004003d, 16040x000200f8,0x00001659,0x00050041,0x000000fe,
20180x00000027,0x000019be,0x000019bd,0x00050085, 16050x0000165a,0x000000fc,0x00000308,0x0004003d,
20190x00000027,0x000019c1,0x000019be,0x00002b6e, 16060x00000006,0x0000165b,0x0000165a,0x00050080,
20200x00050081,0x00000027,0x000019c2,0x000019bc, 16070x00000006,0x0000165d,0x0000165b,0x00000b11,
20210x000019c1,0x00050041,0x00000028,0x000019c3, 16080x00050041,0x000000fe,0x0000165e,0x000000fc,
20220x00001884,0x00000278,0x0004003d,0x00000027, 16090x0000022c,0x0004003d,0x00000006,0x0000165f,
20230x000019c4,0x000019c3,0x00050081,0x00000027, 16100x0000165e,0x00050084,0x00000006,0x00001661,
20240x000019c5,0x000019c2,0x000019c4,0x00060050, 16110x00000107,0x0000165d,0x00050080,0x00000006,
20250x0000004b,0x000019c6,0x0000199d,0x000019b1, 16120x00001662,0x0000165f,0x00001661,0x000200f9,
20260x000019c5,0x0007000c,0x0000004b,0x000019c9, 16130x00001663,0x000200f8,0x00001663,0x000700f5,
20270x00000001,0x00000025,0x00002af9,0x000019c6, 16140x00000006,0x0000323b,0x000000a6,0x00001659,
20280x0007000c,0x0000004b,0x000019cc,0x00000001, 16150x0000168a,0x00001667,0x000500b0,0x0000002f,
20290x00000028,0x00002b0b,0x000019c6,0x00050080, 16160x00001666,0x0000323b,0x000002b7,0x000400f6,
20300x00000006,0x000019cf,0x00002ad6,0x00000151, 16170x0000168b,0x00001667,0x00000000,0x000400fa,
20310x000200f9,0x00001963,0x000200f8,0x000019d0, 16180x00001666,0x00001667,0x0000168b,0x000200f8,
20320x000200f9,0x000019d1,0x000200f8,0x000019d1, 16190x00001667,0x00050084,0x00000006,0x0000166a,
20330x000700f5,0x0000004b,0x00002b07,0x00002b66, 16200x00000118,0x0000323b,0x00050080,0x00000006,
20340x00001960,0x00002b0b,0x000019d0,0x000700f5, 16210x0000166b,0x00001662,0x0000166a,0x00050041,
20350x0000004b,0x00002af5,0x00002b64,0x00001960, 16220x00000156,0x0000166d,0x000000fc,0x000000da,
20360x00002af9,0x000019d0,0x000200f9,0x000019d2, 16230x0004003d,0x00000007,0x0000166e,0x0000166d,
20370x000200f8,0x000019d2,0x000700f5,0x0000004b, 16240x00060041,0x00000028,0x0000166f,0x0000161a,
20380x00002b05,0x00002b66,0x00001bb7,0x00002b07, 16250x0000323b,0x000000a6,0x0004003d,0x00000027,
20390x000019d1,0x000700f5,0x0000004b,0x00002af3, 16260x00001670,0x0000166f,0x0004007c,0x00000006,
20400x00002b64,0x00001bb7,0x00002af5,0x000019d1, 16270x000018d2,0x00001670,0x00050051,0x00000006,
20410x000700f5,0x00000006,0x00002adf,0x0000037d, 16280x000018eb,0x0000166e,0x00000000,0x00050095,
20420x00001bb7,0x00001bd5,0x000019d1,0x00050041, 16290x000000ab,0x000018ed,0x000018eb,0x0000166b,
20430x00000028,0x000019d3,0x00001884,0x000000d7, 16300x00050051,0x00000006,0x000018ee,0x000018ed,
20440x0004003d,0x00000027,0x000019d4,0x000019d3, 16310x00000001,0x00050051,0x00000006,0x000018ef,
20450x000500b4,0x0000002f,0x000019d5,0x000019d4, 16320x000018ed,0x00000000,0x00050051,0x00000006,
20460x000004f9,0x000300f7,0x000019da,0x00000000, 16330x000018f2,0x0000166e,0x00000001,0x00050080,
20470x000400fa,0x000019d5,0x000019d6,0x000019da, 16340x00000006,0x000018f4,0x000018f2,0x000018ee,
20480x000200f8,0x000019d6,0x00050041,0x00000028, 16350x00050050,0x00000007,0x000018f5,0x000018ef,
20490x000019d7,0x00001884,0x00000151,0x0004003d, 16360x000018f4,0x0004007c,0x00000014,0x000018e5,
20500x00000027,0x000019d8,0x000019d7,0x000500b4, 16370x000018f5,0x00060041,0x000000db,0x000018dd,
20510x0000002f,0x000019d9,0x000019d8,0x0000026a, 16380x000018e5,0x000000da,0x000000da,0x0005003e,
20520x000200f9,0x000019da,0x000200f8,0x000019da, 16390x000018dd,0x000018d2,0x00000002,0x00000004,
20530x000700f5,0x0000002f,0x000019db,0x000019d5, 16400x00050080,0x00000006,0x00001676,0x0000166b,
20540x000019d2,0x000019d9,0x000019d6,0x000300f7, 16410x0000010a,0x00060041,0x00000028,0x0000167a,
20550x000019e0,0x00000000,0x000400fa,0x000019db, 16420x0000161a,0x0000323b,0x000000b0,0x0004003d,
20560x000019dc,0x000019e0,0x000200f8,0x000019dc, 16430x00000027,0x0000167b,0x0000167a,0x0004007c,
20570x00050041,0x00000028,0x000019dd,0x00001884, 16440x00000006,0x000018fb,0x0000167b,0x00050095,
20580x00000202,0x0004003d,0x00000027,0x000019de, 16450x000000ab,0x00001916,0x000018eb,0x00001676,
20590x000019dd,0x000500b4,0x0000002f,0x000019df, 16460x00050051,0x00000006,0x00001917,0x00001916,
20600x000019de,0x0000026a,0x000200f9,0x000019e0, 16470x00000001,0x00050051,0x00000006,0x00001918,
20610x000200f8,0x000019e0,0x000700f5,0x0000002f, 16480x00001916,0x00000000,0x00050080,0x00000006,
20620x000019e1,0x000019db,0x000019da,0x000019df, 16490x0000191d,0x000018f2,0x00001917,0x00050050,
20630x000019dc,0x000300f7,0x000019e6,0x00000000, 16500x00000007,0x0000191e,0x00001918,0x0000191d,
20640x000400fa,0x000019e1,0x000019e2,0x000019e6, 16510x0004007c,0x00000014,0x0000190e,0x0000191e,
20650x000200f8,0x000019e2,0x00050041,0x00000028, 16520x00060041,0x000000db,0x00001906,0x0000190e,
20660x000019e3,0x00001884,0x00000212,0x0004003d, 16530x000000da,0x000000da,0x0005003e,0x00001906,
20670x00000027,0x000019e4,0x000019e3,0x000500b4, 16540x000018fb,0x00000002,0x00000004,0x00050080,
20680x0000002f,0x000019e5,0x000019e4,0x0000026a, 16550x00000006,0x00001681,0x0000166b,0x00000111,
20690x000200f9,0x000019e6,0x000200f8,0x000019e6, 16560x00060041,0x00000028,0x00001685,0x0000161a,
20700x000700f5,0x0000002f,0x000019e7,0x000019e1, 16570x0000323b,0x00000170,0x0004003d,0x00000027,
20710x000019e0,0x000019e5,0x000019e2,0x000300f7, 16580x00001686,0x00001685,0x0004007c,0x00000006,
20720x000019ec,0x00000000,0x000400fa,0x000019e7, 16590x00001924,0x00001686,0x00050095,0x000000ab,
20730x000019e8,0x000019ec,0x000200f8,0x000019e8, 16600x0000193f,0x000018eb,0x00001681,0x00050051,
20740x00050041,0x00000028,0x000019e9,0x00001884, 16610x00000006,0x00001940,0x0000193f,0x00000001,
20750x0000021a,0x0004003d,0x00000027,0x000019ea, 16620x00050051,0x00000006,0x00001941,0x0000193f,
20760x000019e9,0x000500b4,0x0000002f,0x000019eb, 16630x00000000,0x00050080,0x00000006,0x00001946,
20770x000019ea,0x000004f9,0x000200f9,0x000019ec, 16640x000018f2,0x00001940,0x00050050,0x00000007,
20780x000200f8,0x000019ec,0x000700f5,0x0000002f, 16650x00001947,0x00001941,0x00001946,0x0004007c,
20790x000019ed,0x000019e7,0x000019e6,0x000019eb, 16660x00000014,0x00001937,0x00001947,0x00060041,
20800x000019e8,0x000300f7,0x000019f2,0x00000000, 16670x000000db,0x0000192f,0x00001937,0x000000da,
20810x000400fa,0x000019ed,0x000019ee,0x000019f2, 16680x000000da,0x0005003e,0x0000192f,0x00001924,
20820x000200f8,0x000019ee,0x00050041,0x00000028,
20830x000019ef,0x00001884,0x00000230,0x0004003d,
20840x00000027,0x000019f0,0x000019ef,0x000500b4,
20850x0000002f,0x000019f1,0x000019f0,0x0000026a,
20860x000200f9,0x000019f2,0x000200f8,0x000019f2,
20870x000700f5,0x0000002f,0x000019f3,0x000019ed,
20880x000019ec,0x000019f1,0x000019ee,0x000300f7,
20890x000019f8,0x00000000,0x000400fa,0x000019f3,
20900x000019f4,0x000019f8,0x000200f8,0x000019f4,
20910x00050041,0x00000028,0x000019f5,0x00001884,
20920x00000305,0x0004003d,0x00000027,0x000019f6,
20930x000019f5,0x000500b4,0x0000002f,0x000019f7,
20940x000019f6,0x0000026a,0x000200f9,0x000019f8,
20950x000200f8,0x000019f8,0x000700f5,0x0000002f,
20960x000019f9,0x000019f3,0x000019f2,0x000019f7,
20970x000019f4,0x000300f7,0x000019fe,0x00000000,
20980x000400fa,0x000019f9,0x000019fa,0x000019fe,
20990x000200f8,0x000019fa,0x00050041,0x00000028,
21000x000019fb,0x00001884,0x0000024d,0x0004003d,
21010x00000027,0x000019fc,0x000019fb,0x000500b4,
21020x0000002f,0x000019fd,0x000019fc,0x0000026a,
21030x000200f9,0x000019fe,0x000200f8,0x000019fe,
21040x000700f5,0x0000002f,0x000019ff,0x000019f9,
21050x000019f8,0x000019fd,0x000019fa,0x000300f7,
21060x00001a04,0x00000000,0x000400fa,0x000019ff,
21070x00001a00,0x00001a04,0x000200f8,0x00001a00,
21080x00050041,0x00000028,0x00001a01,0x00001884,
21090x00000263,0x0004003d,0x00000027,0x00001a02,
21100x00001a01,0x000500b4,0x0000002f,0x00001a03,
21110x00001a02,0x000004f9,0x000200f9,0x00001a04,
21120x000200f8,0x00001a04,0x000700f5,0x0000002f,
21130x00001a05,0x000019ff,0x000019fe,0x00001a03,
21140x00001a00,0x00050080,0x00000006,0x00001a07,
21150x00001916,0x0000037b,0x000500c7,0x00000006,
21160x00001a09,0x00002adf,0x0000052e,0x000600a9,
21170x00000006,0x00001a0b,0x00001a05,0x0000012d,
21180x000000a3,0x000500c5,0x00000006,0x00001a0c,
21190x00001a09,0x00001a0b,0x00050095,0x000000a8,
21200x00001ce3,0x00001b83,0x00001a07,0x00050051,
21210x00000006,0x00001ce4,0x00001ce3,0x00000001,
21220x00050051,0x00000006,0x00001ce5,0x00001ce3,
21230x00000000,0x00050080,0x00000006,0x00001cea,
21240x00001b8a,0x00001ce4,0x00050050,0x00000007,
21250x00001ceb,0x00001ce5,0x00001cea,0x0004007c,
21260x00000014,0x00001cdb,0x00001ceb,0x00060041,
21270x000000d8,0x00001cd3,0x00001cdb,0x000000d7,
21280x000000d7,0x0005003e,0x00001cd3,0x00001a0c,
21290x00000002,0x00000004,0x00050080,0x00000006,
21300x00001a11,0x00001916,0x00000385,0x000500c2,
21310x00000006,0x00001a14,0x00001b0b,0x00000305,
21320x000500c4,0x00000006,0x00001a17,0x00001b2c,
21330x0000047b,0x000500c5,0x00000006,0x00001a18,
21340x00001a14,0x00001a17,0x00050095,0x000000a8,
21350x00001d03,0x00001b83,0x00001a11,0x00050051,
21360x00000006,0x00001d04,0x00001d03,0x00000001,
21370x00050051,0x00000006,0x00001d05,0x00001d03,
21380x00000000,0x00050080,0x00000006,0x00001d0a,
21390x00001b8a,0x00001d04,0x00050050,0x00000007,
21400x00001d0b,0x00001d05,0x00001d0a,0x0004007c,
21410x00000014,0x00001cfb,0x00001d0b,0x00060041,
21420x000000d8,0x00001cf3,0x00001cfb,0x000000d7,
21430x000000d7,0x0005003e,0x00001cf3,0x00001a18,
21440x00000002,0x00000004,0x0004003d,0x00000027,
21450x00001a1d,0x000019d3,0x00050041,0x00000028,
21460x00001a1e,0x00001884,0x00000212,0x0004003d,
21470x00000027,0x00001a1f,0x00001a1e,0x00050041,
21480x00000028,0x00001a20,0x00001884,0x00000305,
21490x0004003d,0x00000027,0x00001a21,0x00001a20,
21500x00050041,0x00000028,0x00001a22,0x00001884,
21510x00000151,0x0004003d,0x00000027,0x00001a23,
21520x00001a22,0x00050041,0x00000028,0x00001a24,
21530x00001884,0x0000021a,0x0004003d,0x00000027,
21540x00001a25,0x00001a24,0x00050041,0x00000028,
21550x00001a26,0x00001884,0x0000024d,0x0004003d,
21560x00000027,0x00001a27,0x00001a26,0x00050041,
21570x00000028,0x00001a28,0x00001884,0x00000202,
21580x0004003d,0x00000027,0x00001a29,0x00001a28,
21590x00050041,0x00000028,0x00001a2a,0x00001884,
21600x00000230,0x0004003d,0x00000027,0x00001a2b,
21610x00001a2a,0x00050041,0x00000028,0x00001a2c,
21620x00001884,0x00000263,0x0004003d,0x00000027,
21630x00001a2d,0x00001a2c,0x00060050,0x0000004b,
21640x00001a2e,0x00001a1d,0x00001a1f,0x00001a21,
21650x00060050,0x0000004b,0x00001a2f,0x00001a23,
21660x00001a25,0x00001a27,0x00060050,0x0000004b,
21670x00001a30,0x00001a29,0x00001a2b,0x00001a2d,
21680x00060050,0x00000548,0x00001a31,0x00001a2e,
21690x00001a2f,0x00001a30,0x0006000c,0x00000027,
21700x00001a33,0x00000001,0x00000021,0x00001a31,
21710x000500b7,0x0000002f,0x00001a35,0x00001a33,
21720x0000026a,0x000300f7,0x00001a3a,0x00000000,
21730x000400fa,0x00001a35,0x00001a36,0x00001a39,
21740x000200f8,0x00001a36,0x0006000c,0x00000548,
21750x00001a38,0x00000001,0x00000022,0x00001a31,
21760x000200f9,0x00001a3a,0x000200f8,0x00001a39,
21770x000200f9,0x00001a3a,0x000200f8,0x00001a3a,
21780x000700f5,0x00000548,0x00002ae6,0x00001a38,
21790x00001a36,0x0000056e,0x00001a39,0x0003003e,
21800x000018c5,0x00002ae6,0x00050041,0x00000028,
21810x00001a3c,0x00001884,0x0000020a,0x0004003d,
21820x00000027,0x00001a3d,0x00001a3c,0x00050041,
21830x00000028,0x00001a3e,0x00001884,0x000004d5,
21840x0004003d,0x00000027,0x00001a3f,0x00001a3e,
21850x00050041,0x00000028,0x00001a40,0x00001884,
21860x00000278,0x0004003d,0x00000027,0x00001a41,
21870x00001a40,0x00060050,0x0000004b,0x00001a42,
21880x00001a3d,0x00001a3f,0x00001a41,0x00050091,
21890x0000004b,0x00001a45,0x00002ae6,0x00001a42,
21900x0004007f,0x0000004b,0x00001a46,0x00001a45,
21910x0003003e,0x000018c8,0x00001a46,0x000200f9,
21920x00001a47,0x000200f8,0x00001a47,0x000700f5,
21930x00000006,0x00002ae7,0x000000a3,0x00001a3a,
21940x00001a7a,0x00001a4b,0x000500b0,0x0000002f,
21950x00001a4a,0x00002ae7,0x000002b4,0x000400f6,
21960x00001a7b,0x00001a4b,0x00000000,0x000400fa,
21970x00001a4a,0x00001a4b,0x00001a7b,0x000200f8,
21980x00001a4b,0x00050080,0x00000006,0x00001a4d,
21990x00001916,0x00000104,0x00050084,0x00000006,
22000x00001a4f,0x0000011c,0x00002ae7,0x00050080,
22010x00000006,0x00001a50,0x00001a4d,0x00001a4f,
22020x00060041,0x00000028,0x00001a54,0x000018c5,
22030x000000d7,0x00002ae7,0x0004003d,0x00000027,
22040x00001a55,0x00001a54,0x0004007c,0x00000006,
22050x00001d11,0x00001a55,0x00050095,0x000000a8,
22060x00001d2c,0x00001b83,0x00001a50,0x00050051,
22070x00000006,0x00001d2d,0x00001d2c,0x00000001,
22080x00050051,0x00000006,0x00001d2e,0x00001d2c,
22090x00000000,0x00050080,0x00000006,0x00001d33,
22100x00001b8a,0x00001d2d,0x00050050,0x00000007,
22110x00001d34,0x00001d2e,0x00001d33,0x0004007c,
22120x00000014,0x00001d24,0x00001d34,0x00060041,
22130x000000d8,0x00001d1c,0x00001d24,0x000000d7,
22140x000000d7,0x0005003e,0x00001d1c,0x00001d11,
22150x00000002,0x00000004,0x00050080,0x00000006, 16690x00000002,0x00000004,0x00050080,0x00000006,
22160x00001a58,0x00001916,0x00000594,0x00050080, 16700x0000168a,0x0000323b,0x00000154,0x000200f9,
22170x00000006,0x00001a5b,0x00001a58,0x00001a4f, 16710x00001663,0x000200f8,0x0000168b,0x00050080,
22180x00060041,0x00000028,0x00001a5f,0x000018c5, 16720x00000006,0x0000168d,0x00001662,0x00000347,
22190x00000151,0x00002ae7,0x0004003d,0x00000027, 16730x00050041,0x00000156,0x0000168e,0x000000fc,
22200x00001a60,0x00001a5f,0x0004007c,0x00000006, 16740x000000da,0x0004003d,0x00000007,0x0000168f,
22210x00001d3a,0x00001a60,0x00050095,0x000000a8, 16750x0000168e,0x00060041,0x00000028,0x00001690,
22220x00001d55,0x00001b83,0x00001a5b,0x00050051, 16760x0000161a,0x00000205,0x000000a6,0x0004003d,
22230x00000006,0x00001d56,0x00001d55,0x00000001, 16770x00000027,0x00001691,0x00001690,0x0004007c,
22240x00050051,0x00000006,0x00001d57,0x00001d55, 16780x00000006,0x0000194d,0x00001691,0x00050051,
22250x00000000,0x00050080,0x00000006,0x00001d5c, 16790x00000006,0x00001966,0x0000168f,0x00000000,
22260x00001b8a,0x00001d56,0x00050050,0x00000007, 16800x00050095,0x000000ab,0x00001968,0x00001966,
22270x00001d5d,0x00001d57,0x00001d5c,0x0004007c, 16810x0000168d,0x00050051,0x00000006,0x00001969,
22280x00000014,0x00001d4d,0x00001d5d,0x00060041, 16820x00001968,0x00000001,0x00050051,0x00000006,
22290x000000d8,0x00001d45,0x00001d4d,0x000000d7, 16830x0000196a,0x00001968,0x00000000,0x00050051,
22300x000000d7,0x0005003e,0x00001d45,0x00001d3a, 16840x00000006,0x0000196d,0x0000168f,0x00000001,
16850x00050080,0x00000006,0x0000196f,0x0000196d,
16860x00001969,0x00050050,0x00000007,0x00001970,
16870x0000196a,0x0000196f,0x0004007c,0x00000014,
16880x00001960,0x00001970,0x00060041,0x000000db,
16890x00001958,0x00001960,0x000000da,0x000000da,
16900x0005003e,0x00001958,0x0000194d,0x00000002,
16910x00000004,0x00050080,0x00000006,0x00001694,
16920x00001662,0x00000352,0x00060041,0x00000028,
16930x00001697,0x0000161a,0x00000205,0x000000b0,
16940x0004003d,0x00000027,0x00001698,0x00001697,
16950x0004007c,0x00000006,0x00001976,0x00001698,
16960x00050095,0x000000ab,0x00001991,0x00001966,
16970x00001694,0x00050051,0x00000006,0x00001992,
16980x00001991,0x00000001,0x00050051,0x00000006,
16990x00001993,0x00001991,0x00000000,0x00050080,
17000x00000006,0x00001998,0x0000196d,0x00001992,
17010x00050050,0x00000007,0x00001999,0x00001993,
17020x00001998,0x0004007c,0x00000014,0x00001989,
17030x00001999,0x00060041,0x000000db,0x00001981,
17040x00001989,0x000000da,0x000000da,0x0005003e,
17050x00001981,0x00001976,0x00000002,0x00000004,
17060x00050080,0x00000006,0x0000169b,0x00001662,
17070x0000035d,0x00060041,0x00000028,0x0000169e,
17080x0000161a,0x00000205,0x00000170,0x0004003d,
17090x00000027,0x0000169f,0x0000169e,0x0004007c,
17100x00000006,0x0000199f,0x0000169f,0x00050095,
17110x000000ab,0x000019ba,0x00001966,0x0000169b,
17120x00050051,0x00000006,0x000019bb,0x000019ba,
17130x00000001,0x00050051,0x00000006,0x000019bc,
17140x000019ba,0x00000000,0x00050080,0x00000006,
17150x000019c1,0x0000196d,0x000019bb,0x00050050,
17160x00000007,0x000019c2,0x000019bc,0x000019c1,
17170x0004007c,0x00000014,0x000019b2,0x000019c2,
17180x00060041,0x000000db,0x000019aa,0x000019b2,
17190x000000da,0x000000da,0x0005003e,0x000019aa,
17200x0000199f,0x00000002,0x00000004,0x00050080,
17210x00000006,0x000016a2,0x00001662,0x00000368,
17220x00050041,0x000000fe,0x000016a5,0x000000fc,
17230x0000036a,0x0004003d,0x00000006,0x000016a6,
17240x000016a5,0x00050095,0x000000ab,0x000019da,
17250x00001966,0x000016a2,0x00050051,0x00000006,
17260x000019db,0x000019da,0x00000001,0x00050051,
17270x00000006,0x000019dc,0x000019da,0x00000000,
17280x00050080,0x00000006,0x000019e1,0x0000196d,
17290x000019db,0x00050050,0x00000007,0x000019e2,
17300x000019dc,0x000019e1,0x0004007c,0x00000014,
17310x000019d2,0x000019e2,0x00060041,0x000000db,
17320x000019ca,0x000019d2,0x000000da,0x000000da,
17330x0005003e,0x000019ca,0x000016a6,0x00000002,
17340x00000004,0x00050080,0x00000006,0x000016a9,
17350x00001662,0x00000374,0x00050095,0x000000ab,
17360x000019fa,0x00001966,0x000016a9,0x00050051,
17370x00000006,0x000019fb,0x000019fa,0x00000001,
17380x00050051,0x00000006,0x000019fc,0x000019fa,
17390x00000000,0x00050080,0x00000006,0x00001a01,
17400x0000196d,0x000019fb,0x00050050,0x00000007,
17410x00001a02,0x000019fc,0x00001a01,0x0004007c,
17420x00000014,0x000019f2,0x00001a02,0x00060041,
17430x000000db,0x000019ea,0x000019f2,0x000000da,
17440x000000da,0x0005003e,0x000019ea,0x00000b11,
22310x00000002,0x00000004,0x00050080,0x00000006, 17450x00000002,0x00000004,0x00050080,0x00000006,
22320x00001a63,0x00001916,0x000005a3,0x00050080, 17460x000016af,0x00001662,0x0000037e,0x00050095,
22330x00000006,0x00001a66,0x00001a63,0x00001a4f, 17470x000000ab,0x00001a1a,0x00001966,0x000016af,
22340x00060041,0x00000028,0x00001a6a,0x000018c5, 17480x00050051,0x00000006,0x00001a1b,0x00001a1a,
22350x00000202,0x00002ae7,0x0004003d,0x00000027, 17490x00000001,0x00050051,0x00000006,0x00001a1c,
22360x00001a6b,0x00001a6a,0x0004007c,0x00000006, 17500x00001a1a,0x00000000,0x00050080,0x00000006,
22370x00001d63,0x00001a6b,0x00050095,0x000000a8, 17510x00001a21,0x0000196d,0x00001a1b,0x00050050,
22380x00001d7e,0x00001b83,0x00001a66,0x00050051, 17520x00000007,0x00001a22,0x00001a1c,0x00001a21,
22390x00000006,0x00001d7f,0x00001d7e,0x00000001, 17530x0004007c,0x00000014,0x00001a12,0x00001a22,
22400x00050051,0x00000006,0x00001d80,0x00001d7e, 17540x00060041,0x000000db,0x00001a0a,0x00001a12,
22410x00000000,0x00050080,0x00000006,0x00001d85, 17550x000000da,0x000000da,0x0005003e,0x00001a0a,
22420x00001b8a,0x00001d7f,0x00050050,0x00000007, 17560x00000380,0x00000002,0x00000004,0x00050080,
22430x00001d86,0x00001d80,0x00001d85,0x0004007c, 17570x00000006,0x000016b4,0x00001662,0x00000388,
22440x00000014,0x00001d76,0x00001d86,0x00060041, 17580x00050095,0x000000ab,0x00001a3a,0x00001966,
22450x000000d8,0x00001d6e,0x00001d76,0x000000d7, 17590x000016b4,0x00050051,0x00000006,0x00001a3b,
22460x000000d7,0x0005003e,0x00001d6e,0x00001d63, 17600x00001a3a,0x00000001,0x00050051,0x00000006,
17610x00001a3c,0x00001a3a,0x00000000,0x00050080,
17620x00000006,0x00001a41,0x0000196d,0x00001a3b,
17630x00050050,0x00000007,0x00001a42,0x00001a3c,
17640x00001a41,0x0004007c,0x00000014,0x00001a32,
17650x00001a42,0x00060041,0x000000db,0x00001a2a,
17660x00001a32,0x000000da,0x000000da,0x0005003e,
17670x00001a2a,0x0000038a,0x00000002,0x00000004,
17680x00050041,0x0000004c,0x000016b8,0x0000161a,
17690x000000da,0x0004003d,0x0000004b,0x000016b9,
17700x000016b8,0x0004009c,0x00000395,0x000016ba,
17710x000016b9,0x0004009a,0x0000002f,0x000016bb,
17720x000016ba,0x000400a8,0x0000002f,0x000016bc,
17730x000016bb,0x000300f7,0x000016c2,0x00000000,
17740x000400fa,0x000016bc,0x000016bd,0x000016c2,
17750x000200f8,0x000016bd,0x00050041,0x0000004c,
17760x000016be,0x0000161a,0x00000154,0x0004003d,
17770x0000004b,0x000016bf,0x000016be,0x0004009c,
17780x00000395,0x000016c0,0x000016bf,0x0004009a,
17790x0000002f,0x000016c1,0x000016c0,0x000200f9,
17800x000016c2,0x000200f8,0x000016c2,0x000700f5,
17810x0000002f,0x000016c3,0x000016bb,0x0000168b,
17820x000016c1,0x000016bd,0x000400a8,0x0000002f,
17830x000016c4,0x000016c3,0x000300f7,0x000016ca,
17840x00000000,0x000400fa,0x000016c4,0x000016c5,
17850x000016ca,0x000200f8,0x000016c5,0x00050041,
17860x0000004c,0x000016c6,0x0000161a,0x00000205,
17870x0004003d,0x0000004b,0x000016c7,0x000016c6,
17880x0004009c,0x00000395,0x000016c8,0x000016c7,
17890x0004009a,0x0000002f,0x000016c9,0x000016c8,
17900x000200f9,0x000016ca,0x000200f8,0x000016ca,
17910x000700f5,0x0000002f,0x000016cb,0x000016c3,
17920x000016c2,0x000016c9,0x000016c5,0x0004003d,
17930x0000004b,0x000016cd,0x000016b8,0x00050041,
17940x0000004c,0x000016ce,0x0000161a,0x00000154,
17950x0004003d,0x0000004b,0x000016cf,0x000016ce,
17960x0007000c,0x0000004b,0x000016d0,0x00000001,
17970x00000025,0x000016cd,0x000016cf,0x00050041,
17980x0000004c,0x000016d1,0x0000161a,0x00000205,
17990x0004003d,0x0000004b,0x000016d2,0x000016d1,
18000x0007000c,0x0000004b,0x000016d3,0x00000001,
18010x00000025,0x000016d0,0x000016d2,0x0004003d,
18020x0000004b,0x000016d5,0x000016b8,0x0004003d,
18030x0000004b,0x000016d7,0x000016ce,0x0007000c,
18040x0000004b,0x000016d8,0x00000001,0x00000028,
18050x000016d5,0x000016d7,0x0004003d,0x0000004b,
18060x000016da,0x000016d1,0x0007000c,0x0000004b,
18070x000016db,0x00000001,0x00000028,0x000016d8,
18080x000016da,0x00060050,0x00000395,0x000032a9,
18090x000016cb,0x000016cb,0x000016cb,0x000600a9,
18100x0000004b,0x000032aa,0x000032a9,0x000032a7,
18110x000016db,0x000600a9,0x0000004b,0x000032ac,
18120x000032a9,0x000032a5,0x000016d3,0x00050041,
18130x000000fe,0x00001a8c,0x000000fc,0x000000fd,
18140x0004003d,0x00000006,0x00001a8d,0x00001a8c,
18150x00050084,0x00000006,0x00001a8e,0x0000011f,
18160x00001a8d,0x00050080,0x00000006,0x00001a8f,
18170x00000107,0x00001a8e,0x00050080,0x00000006,
18180x00001a95,0x00001a8d,0x000032a8,0x00050086,
18190x00000006,0x00001a96,0x00001a95,0x00000101,
18200x00050084,0x00000006,0x00001a88,0x00000107,
18210x00001a96,0x00050080,0x00000006,0x00001a89,
18220x00001a8f,0x00001a88,0x00050084,0x00000006,
18230x00001a59,0x00000150,0x0000165d,0x00050080,
18240x00000006,0x00001a5a,0x00001a89,0x00001a59,
18250x00050041,0x00000156,0x00001a5b,0x000000fc,
18260x00000154,0x0004003d,0x00000007,0x00001a5c,
18270x00001a5b,0x00050051,0x00000027,0x00001a5f,
18280x000032ac,0x00000000,0x0004007c,0x00000006,
18290x00001a9c,0x00001a5f,0x00050051,0x00000006,
18300x00001ab5,0x00001a5c,0x00000000,0x00050095,
18310x000000ab,0x00001ab7,0x00001ab5,0x00001a5a,
18320x00050051,0x00000006,0x00001ab8,0x00001ab7,
18330x00000001,0x00050051,0x00000006,0x00001ab9,
18340x00001ab7,0x00000000,0x00050051,0x00000006,
18350x00001abc,0x00001a5c,0x00000001,0x00050080,
18360x00000006,0x00001abe,0x00001abc,0x00001ab8,
18370x00050050,0x00000007,0x00001abf,0x00001ab9,
18380x00001abe,0x0004007c,0x00000014,0x00001aaf,
18390x00001abf,0x00060041,0x000000db,0x00001aa7,
18400x00001aaf,0x000000da,0x000000da,0x0005003e,
18410x00001aa7,0x00001a9c,0x00000002,0x00000004,
18420x00050080,0x00000006,0x00001a62,0x00001a5a,
18430x0000010a,0x00050051,0x00000027,0x00001a66,
18440x000032ac,0x00000001,0x0004007c,0x00000006,
18450x00001ac5,0x00001a66,0x00050095,0x000000ab,
18460x00001ae0,0x00001ab5,0x00001a62,0x00050051,
18470x00000006,0x00001ae1,0x00001ae0,0x00000001,
18480x00050051,0x00000006,0x00001ae2,0x00001ae0,
18490x00000000,0x00050080,0x00000006,0x00001ae7,
18500x00001abc,0x00001ae1,0x00050050,0x00000007,
18510x00001ae8,0x00001ae2,0x00001ae7,0x0004007c,
18520x00000014,0x00001ad8,0x00001ae8,0x00060041,
18530x000000db,0x00001ad0,0x00001ad8,0x000000da,
18540x000000da,0x0005003e,0x00001ad0,0x00001ac5,
22470x00000002,0x00000004,0x00050080,0x00000006, 18550x00000002,0x00000004,0x00050080,0x00000006,
22480x00001a6e,0x00001916,0x000005b2,0x00050080, 18560x00001a69,0x00001a5a,0x00000111,0x00050051,
22490x00000006,0x00001a71,0x00001a6e,0x00001a4f, 18570x00000027,0x00001a6d,0x000032ac,0x00000002,
22500x00050041,0x00000028,0x00001a75,0x000018c8, 18580x0004007c,0x00000006,0x00001aee,0x00001a6d,
22510x00002ae7,0x0004003d,0x00000027,0x00001a76, 18590x00050095,0x000000ab,0x00001b09,0x00001ab5,
22520x00001a75,0x0004007c,0x00000006,0x00001d8c, 18600x00001a69,0x00050051,0x00000006,0x00001b0a,
22530x00001a76,0x00050095,0x000000a8,0x00001da7, 18610x00001b09,0x00000001,0x00050051,0x00000006,
22540x00001b83,0x00001a71,0x00050051,0x00000006, 18620x00001b0b,0x00001b09,0x00000000,0x00050080,
22550x00001da8,0x00001da7,0x00000001,0x00050051, 18630x00000006,0x00001b10,0x00001abc,0x00001b0a,
22560x00000006,0x00001da9,0x00001da7,0x00000000, 18640x00050050,0x00000007,0x00001b11,0x00001b0b,
22570x00050080,0x00000006,0x00001dae,0x00001b8a, 18650x00001b10,0x0004007c,0x00000014,0x00001b01,
22580x00001da8,0x00050050,0x00000007,0x00001daf, 18660x00001b11,0x00060041,0x000000db,0x00001af9,
22590x00001da9,0x00001dae,0x0004007c,0x00000014, 18670x00001b01,0x000000da,0x000000da,0x0005003e,
22600x00001d9f,0x00001daf,0x00060041,0x000000d8, 18680x00001af9,0x00001aee,0x00000002,0x00000004,
22610x00001d97,0x00001d9f,0x000000d7,0x000000d7, 18690x00050080,0x00000006,0x00001a70,0x00001a5a,
22620x0005003e,0x00001d97,0x00001d8c,0x00000002, 18700x00000118,0x00050051,0x00000027,0x00001a74,
22630x00000004,0x00050080,0x00000006,0x00001a7a, 18710x000032aa,0x00000000,0x0004007c,0x00000006,
22640x00002ae7,0x00000151,0x000200f9,0x00001a47, 18720x00001b17,0x00001a74,0x00050095,0x000000ab,
22650x000200f8,0x00001a7b,0x00050080,0x00000006, 18730x00001b32,0x00001ab5,0x00001a70,0x00050051,
22660x00001a7d,0x00001916,0x000005c3,0x00050095, 18740x00000006,0x00001b33,0x00001b32,0x00000001,
22670x000000a8,0x00001dc7,0x00001b83,0x00001a7d, 18750x00050051,0x00000006,0x00001b34,0x00001b32,
22680x00050051,0x00000006,0x00001dc8,0x00001dc7, 18760x00000000,0x00050080,0x00000006,0x00001b39,
22690x00000001,0x00050051,0x00000006,0x00001dc9, 18770x00001abc,0x00001b33,0x00050050,0x00000007,
22700x00001dc7,0x00000000,0x00050080,0x00000006, 18780x00001b3a,0x00001b34,0x00001b39,0x0004007c,
22710x00001dce,0x00001b8a,0x00001dc8,0x00050050, 18790x00000014,0x00001b2a,0x00001b3a,0x00060041,
22720x00000007,0x00001dcf,0x00001dc9,0x00001dce, 18800x000000db,0x00001b22,0x00001b2a,0x000000da,
22730x0004007c,0x00000014,0x00001dbf,0x00001dcf, 18810x000000da,0x0005003e,0x00001b22,0x00001b17,
22740x00060041,0x000000d8,0x00001db7,0x00001dbf,
22750x000000d7,0x000000d7,0x0005003e,0x00001db7,
22760x000009e9,0x00000002,0x00000004,0x00050080,
22770x00000006,0x00001a83,0x00001916,0x000005cd,
22780x00050095,0x000000a8,0x00001de7,0x00001b83,
22790x00001a83,0x00050051,0x00000006,0x00001de8,
22800x00001de7,0x00000001,0x00050051,0x00000006,
22810x00001de9,0x00001de7,0x00000000,0x00050080,
22820x00000006,0x00001dee,0x00001b8a,0x00001de8,
22830x00050050,0x00000007,0x00001def,0x00001de9,
22840x00001dee,0x0004007c,0x00000014,0x00001ddf,
22850x00001def,0x00060041,0x000000d8,0x00001dd7,
22860x00001ddf,0x000000d7,0x000000d7,0x0005003e,
22870x00001dd7,0x0000037d,0x00000002,0x00000004,
22880x00050080,0x00000006,0x00001a88,0x00001916,
22890x000005d6,0x00050095,0x000000a8,0x00001e07,
22900x00001b83,0x00001a88,0x00050051,0x00000006,
22910x00001e08,0x00001e07,0x00000001,0x00050051,
22920x00000006,0x00001e09,0x00001e07,0x00000000,
22930x00050080,0x00000006,0x00001e0e,0x00001b8a,
22940x00001e08,0x00050050,0x00000007,0x00001e0f,
22950x00001e09,0x00001e0e,0x0004007c,0x00000014,
22960x00001dff,0x00001e0f,0x00060041,0x000000d8,
22970x00001df7,0x00001dff,0x000000d7,0x000000d7,
22980x0005003e,0x00001df7,0x000000a3,0x00000002,
22990x00000004,0x00050080,0x00000006,0x00001a8d,
23000x00001916,0x000005df,0x00050095,0x000000a8,
23010x00001e27,0x00001b83,0x00001a8d,0x00050051,
23020x00000006,0x00001e28,0x00001e27,0x00000001,
23030x00050051,0x00000006,0x00001e29,0x00001e27,
23040x00000000,0x00050080,0x00000006,0x00001e2e,
23050x00001b8a,0x00001e28,0x00050050,0x00000007,
23060x00001e2f,0x00001e29,0x00001e2e,0x0004007c,
23070x00000014,0x00001e1f,0x00001e2f,0x00060041,
23080x000000d8,0x00001e17,0x00001e1f,0x000000d7,
23090x000000d7,0x0005003e,0x00001e17,0x000000a3,
23100x00000002,0x00000004,0x000500b4,0x0000002f,
23110x00001a92,0x00001a33,0x0000026a,0x00060050,
23120x00000392,0x00002b6f,0x00001a92,0x00001a92,
23130x00001a92,0x000600a9,0x0000004b,0x00002b70,
23140x00002b6f,0x00002b66,0x00002b05,0x000600a9,
23150x0000004b,0x00002b72,0x00002b6f,0x00002b64,
23160x00002af3,0x00050041,0x000000fb,0x00001e79,
23170x000000f9,0x000000fa,0x0004003d,0x00000006,
23180x00001e7a,0x00001e79,0x00050084,0x00000006,
23190x00001e7b,0x0000011c,0x00001e7a,0x00050080,
23200x00000006,0x00001e7c,0x00000104,0x00001e7b,
23210x00050080,0x00000006,0x00001e82,0x00001e7a,
23220x00002b67,0x00050086,0x00000006,0x00001e83,
23230x00001e82,0x000000fe,0x00050084,0x00000006,
23240x00001e75,0x00000104,0x00001e83,0x00050080,
23250x00000006,0x00001e76,0x00001e7c,0x00001e75,
23260x00050084,0x00000006,0x00001e46,0x0000014d,
23270x000009e9,0x00050080,0x00000006,0x00001e47,
23280x00001e76,0x00001e46,0x00050041,0x00000153,
23290x00001e48,0x000000f9,0x00000151,0x0004003d,
23300x00000007,0x00001e49,0x00001e48,0x00050051,
23310x00000027,0x00001e4c,0x00002b72,0x00000000,
23320x0004007c,0x00000006,0x00001e89,0x00001e4c,
23330x00050051,0x00000006,0x00001ea2,0x00001e49,
23340x00000000,0x00050095,0x000000a8,0x00001ea4,
23350x00001ea2,0x00001e47,0x00050051,0x00000006,
23360x00001ea5,0x00001ea4,0x00000001,0x00050051,
23370x00000006,0x00001ea6,0x00001ea4,0x00000000,
23380x00050051,0x00000006,0x00001ea9,0x00001e49,
23390x00000001,0x00050080,0x00000006,0x00001eab,
23400x00001ea9,0x00001ea5,0x00050050,0x00000007,
23410x00001eac,0x00001ea6,0x00001eab,0x0004007c,
23420x00000014,0x00001e9c,0x00001eac,0x00060041,
23430x000000d8,0x00001e94,0x00001e9c,0x000000d7,
23440x000000d7,0x0005003e,0x00001e94,0x00001e89,
23450x00000002,0x00000004,0x00050080,0x00000006, 18820x00000002,0x00000004,0x00050080,0x00000006,
23460x00001e4f,0x00001e47,0x00000107,0x00050051, 18830x00001a77,0x00001a5a,0x0000011f,0x00050051,
23470x00000027,0x00001e53,0x00002b72,0x00000001, 18840x00000027,0x00001a7b,0x000032aa,0x00000001,
23480x0004007c,0x00000006,0x00001eb2,0x00001e53, 18850x0004007c,0x00000006,0x00001b40,0x00001a7b,
23490x00050095,0x000000a8,0x00001ecd,0x00001ea2, 18860x00050095,0x000000ab,0x00001b5b,0x00001ab5,
23500x00001e4f,0x00050051,0x00000006,0x00001ece, 18870x00001a77,0x00050051,0x00000006,0x00001b5c,
23510x00001ecd,0x00000001,0x00050051,0x00000006, 18880x00001b5b,0x00000001,0x00050051,0x00000006,
23520x00001ecf,0x00001ecd,0x00000000,0x00050080, 18890x00001b5d,0x00001b5b,0x00000000,0x00050080,
23530x00000006,0x00001ed4,0x00001ea9,0x00001ece, 18900x00000006,0x00001b62,0x00001abc,0x00001b5c,
23540x00050050,0x00000007,0x00001ed5,0x00001ecf, 18910x00050050,0x00000007,0x00001b63,0x00001b5d,
23550x00001ed4,0x0004007c,0x00000014,0x00001ec5, 18920x00001b62,0x0004007c,0x00000014,0x00001b53,
23560x00001ed5,0x00060041,0x000000d8,0x00001ebd, 18930x00001b63,0x00060041,0x000000db,0x00001b4b,
23570x00001ec5,0x000000d7,0x000000d7,0x0005003e, 18940x00001b53,0x000000da,0x000000da,0x0005003e,
23580x00001ebd,0x00001eb2,0x00000002,0x00000004, 18950x00001b4b,0x00001b40,0x00000002,0x00000004,
23590x00050080,0x00000006,0x00001e56,0x00001e47, 18960x00050080,0x00000006,0x00001a7e,0x00001a5a,
23600x0000010e,0x00050051,0x00000027,0x00001e5a, 18970x00000189,0x00050051,0x00000027,0x00001a82,
23610x00002b72,0x00000002,0x0004007c,0x00000006, 18980x000032aa,0x00000002,0x0004007c,0x00000006,
23620x00001edb,0x00001e5a,0x00050095,0x000000a8, 18990x00001b69,0x00001a82,0x00050095,0x000000ab,
23630x00001ef6,0x00001ea2,0x00001e56,0x00050051, 19000x00001b84,0x00001ab5,0x00001a7e,0x00050051,
23640x00000006,0x00001ef7,0x00001ef6,0x00000001, 19010x00000006,0x00001b85,0x00001b84,0x00000001,
23650x00050051,0x00000006,0x00001ef8,0x00001ef6, 19020x00050051,0x00000006,0x00001b86,0x00001b84,
23660x00000000,0x00050080,0x00000006,0x00001efd, 19030x00000000,0x00050080,0x00000006,0x00001b8b,
23670x00001ea9,0x00001ef7,0x00050050,0x00000007, 19040x00001abc,0x00001b85,0x00050050,0x00000007,
23680x00001efe,0x00001ef8,0x00001efd,0x0004007c, 19050x00001b8c,0x00001b86,0x00001b8b,0x0004007c,
23690x00000014,0x00001eee,0x00001efe,0x00060041, 19060x00000014,0x00001b7c,0x00001b8c,0x00060041,
23700x000000d8,0x00001ee6,0x00001eee,0x000000d7, 19070x000000db,0x00001b74,0x00001b7c,0x000000da,
23710x000000d7,0x0005003e,0x00001ee6,0x00001edb, 19080x000000da,0x0005003e,0x00001b74,0x00001b69,
19090x00000002,0x00000004,0x000300f7,0x00001bcc,
19100x00000000,0x000300fb,0x000000a6,0x00001b9b,
19110x000200f8,0x00001b9b,0x000500bc,0x0000002f,
19120x00001bd3,0x00001a5f,0x00001a74,0x000300f7,
19130x00001bda,0x00000000,0x000400fa,0x00001bd3,
19140x00001bd4,0x00001bda,0x000200f8,0x00001bd4,
19150x000500bc,0x0000002f,0x00001bd9,0x00001a66,
19160x00001a7b,0x000200f9,0x00001bda,0x000200f8,
19170x00001bda,0x000700f5,0x0000002f,0x00001bdb,
19180x00001bd3,0x00001b9b,0x00001bd9,0x00001bd4,
19190x000300f7,0x00001be2,0x00000000,0x000400fa,
19200x00001bdb,0x00001bdc,0x00001be2,0x000200f8,
19210x00001bdc,0x000500bc,0x0000002f,0x00001be1,
19220x00001a6d,0x00001a82,0x000200f9,0x00001be2,
19230x000200f8,0x00001be2,0x000700f5,0x0000002f,
19240x00001be3,0x00001bdb,0x00001bda,0x00001be1,
19250x00001bdc,0x000400a8,0x0000002f,0x00001be4,
19260x00001be3,0x000300f7,0x00001ba0,0x00000000,
19270x000400fa,0x00001be4,0x00001b9f,0x00001ba0,
19280x000200f8,0x00001b9f,0x000200f9,0x00001bcc,
19290x000200f8,0x00001ba0,0x00050081,0x0000004b,
19300x00001ba3,0x000032ac,0x000032aa,0x0005008e,
19310x0000004b,0x00001ba4,0x00001ba3,0x000001ed,
19320x00050095,0x000000ab,0x00001bf4,0x00001ab5,
19330x000000a6,0x00050051,0x00000006,0x00001bf5,
19340x00001bf4,0x00000001,0x00050051,0x00000006,
19350x00001bf6,0x00001bf4,0x00000000,0x00050080,
19360x00000006,0x00001bfb,0x00001abc,0x00001bf5,
19370x00050050,0x00000007,0x00001bfc,0x00001bf6,
19380x00001bfb,0x0004007c,0x00000014,0x00001bec,
19390x00001bfc,0x00060041,0x000000db,0x00001ba9,
19400x00001bec,0x000000da,0x000000da,0x00050051,
19410x00000027,0x00001bab,0x00001ba4,0x00000000,
19420x0004007c,0x00000006,0x00001c02,0x00001bab,
19430x000500c7,0x00000006,0x00001c04,0x00001c02,
19440x00000130,0x000500ab,0x0000002f,0x00001c05,
19450x00001c04,0x000000a6,0x000300f7,0x00001c0c,
19460x00000000,0x000400fa,0x00001c05,0x00001c06,
19470x00001c09,0x000200f8,0x00001c06,0x000400c8,
19480x00000006,0x00001c08,0x00001c02,0x000200f9,
19490x00001c0c,0x000200f8,0x00001c09,0x000500c5,
19500x00000006,0x00001c0b,0x00001c02,0x00000130,
19510x000200f9,0x00001c0c,0x000200f8,0x00001c0c,
19520x000700f5,0x00000006,0x0000323e,0x00001c08,
19530x00001c06,0x00001c0b,0x00001c09,0x000700ed,
19540x00000006,0x00001bad,0x00001ba9,0x000000b0,
19550x000000a6,0x0000323e,0x00060041,0x000000db,
19560x00001baf,0x00001bec,0x000000da,0x00000154,
19570x00050051,0x00000027,0x00001bb1,0x00001ba4,
19580x00000001,0x0004007c,0x00000006,0x00001c13,
19590x00001bb1,0x000500c7,0x00000006,0x00001c15,
19600x00001c13,0x00000130,0x000500ab,0x0000002f,
19610x00001c16,0x00001c15,0x000000a6,0x000300f7,
19620x00001c1d,0x00000000,0x000400fa,0x00001c16,
19630x00001c17,0x00001c1a,0x000200f8,0x00001c17,
19640x000400c8,0x00000006,0x00001c19,0x00001c13,
19650x000200f9,0x00001c1d,0x000200f8,0x00001c1a,
19660x000500c5,0x00000006,0x00001c1c,0x00001c13,
19670x00000130,0x000200f9,0x00001c1d,0x000200f8,
19680x00001c1d,0x000700f5,0x00000006,0x0000323f,
19690x00001c19,0x00001c17,0x00001c1c,0x00001c1a,
19700x000700ed,0x00000006,0x00001bb3,0x00001baf,
19710x000000b0,0x000000a6,0x0000323f,0x00060041,
19720x000000db,0x00001bb5,0x00001bec,0x000000da,
19730x00000205,0x00050051,0x00000027,0x00001bb7,
19740x00001ba4,0x00000002,0x0004007c,0x00000006,
19750x00001c24,0x00001bb7,0x000500c7,0x00000006,
19760x00001c26,0x00001c24,0x00000130,0x000500ab,
19770x0000002f,0x00001c27,0x00001c26,0x000000a6,
19780x000300f7,0x00001c2e,0x00000000,0x000400fa,
19790x00001c27,0x00001c28,0x00001c2b,0x000200f8,
19800x00001c28,0x000400c8,0x00000006,0x00001c2a,
19810x00001c24,0x000200f9,0x00001c2e,0x000200f8,
19820x00001c2b,0x000500c5,0x00000006,0x00001c2d,
19830x00001c24,0x00000130,0x000200f9,0x00001c2e,
19840x000200f8,0x00001c2e,0x000700f5,0x00000006,
19850x00003240,0x00001c2a,0x00001c28,0x00001c2d,
19860x00001c2b,0x000700ed,0x00000006,0x00001bb9,
19870x00001bb5,0x000000b0,0x000000a6,0x00003240,
19880x00060041,0x000000db,0x00001bbb,0x00001bec,
19890x000000da,0x0000020d,0x000300f7,0x00001c3f,
19900x00000000,0x000400fa,0x00001c05,0x00001c39,
19910x00001c3c,0x000200f8,0x00001c39,0x000400c8,
19920x00000006,0x00001c3b,0x00001c02,0x000200f9,
19930x00001c3f,0x000200f8,0x00001c3c,0x000500c5,
19940x00000006,0x00001c3e,0x00001c02,0x00000130,
19950x000200f9,0x00001c3f,0x000200f8,0x00001c3f,
19960x000700f5,0x00000006,0x00003241,0x00001c3b,
19970x00001c39,0x00001c3e,0x00001c3c,0x000700ef,
19980x00000006,0x00001bbf,0x00001bbb,0x000000b0,
19990x000000a6,0x00003241,0x00060041,0x000000db,
20000x00001bc1,0x00001bec,0x000000da,0x00000215,
20010x000300f7,0x00001c50,0x00000000,0x000400fa,
20020x00001c16,0x00001c4a,0x00001c4d,0x000200f8,
20030x00001c4a,0x000400c8,0x00000006,0x00001c4c,
20040x00001c13,0x000200f9,0x00001c50,0x000200f8,
20050x00001c4d,0x000500c5,0x00000006,0x00001c4f,
20060x00001c13,0x00000130,0x000200f9,0x00001c50,
20070x000200f8,0x00001c50,0x000700f5,0x00000006,
20080x00003242,0x00001c4c,0x00001c4a,0x00001c4f,
20090x00001c4d,0x000700ef,0x00000006,0x00001bc5,
20100x00001bc1,0x000000b0,0x000000a6,0x00003242,
20110x00060041,0x000000db,0x00001bc7,0x00001bec,
20120x000000da,0x0000021d,0x000300f7,0x00001c61,
20130x00000000,0x000400fa,0x00001c27,0x00001c5b,
20140x00001c5e,0x000200f8,0x00001c5b,0x000400c8,
20150x00000006,0x00001c5d,0x00001c24,0x000200f9,
20160x00001c61,0x000200f8,0x00001c5e,0x000500c5,
20170x00000006,0x00001c60,0x00001c24,0x00000130,
20180x000200f9,0x00001c61,0x000200f8,0x00001c61,
20190x000700f5,0x00000006,0x00003243,0x00001c5d,
20200x00001c5b,0x00001c60,0x00001c5e,0x000700ef,
20210x00000006,0x00001bcb,0x00001bc7,0x000000b0,
20220x000000a6,0x00003243,0x000200f9,0x00001bcc,
20230x000200f8,0x00001bcc,0x000200f9,0x00000bd2,
20240x000200f8,0x00000bd6,0x000500aa,0x0000002f,
20250x00000bd9,0x00000b13,0x00000170,0x000300f7,
20260x00000bdb,0x00000000,0x000400fa,0x00000bd9,
20270x00000bda,0x00000bdf,0x000200f8,0x00000bda,
20280x00050084,0x00000006,0x00001cca,0x00000107,
20290x00000b11,0x000200f9,0x00001ccb,0x000200f8,
20300x00001ccb,0x000700f5,0x00000006,0x000031f0,
20310x000000a6,0x00000bda,0x00001cdc,0x00001ccf,
20320x000500b0,0x0000002f,0x00001cce,0x000031f0,
20330x00000118,0x000400f6,0x00001cdd,0x00001ccf,
20340x00000000,0x000400fa,0x00001cce,0x00001ccf,
20350x00001cdd,0x000200f8,0x00001ccf,0x00050084,
20360x00000006,0x00001cd3,0x0000010a,0x000031f0,
20370x00050080,0x00000006,0x00001cd4,0x00001cca,
20380x00001cd3,0x00050041,0x00000156,0x00001cd5,
20390x000000fc,0x00000205,0x0004003d,0x00000007,
20400x00001cd6,0x00001cd5,0x00050051,0x00000006,
20410x00001e97,0x00001cd6,0x00000000,0x00050095,
20420x000000ab,0x00001e99,0x00001e97,0x00001cd4,
20430x00050051,0x00000006,0x00001e9a,0x00001e99,
20440x00000001,0x00050051,0x00000006,0x00001e9b,
20450x00001e99,0x00000000,0x00050051,0x00000006,
20460x00001e9e,0x00001cd6,0x00000001,0x00050080,
20470x00000006,0x00001ea0,0x00001e9e,0x00001e9a,
20480x00050050,0x00000007,0x00001ea1,0x00001e9b,
20490x00001ea0,0x0004007c,0x00000014,0x00001e91,
20500x00001ea1,0x00060041,0x000000db,0x00001e88,
20510x00001e91,0x000000da,0x000000da,0x0006003d,
20520x00000006,0x00001e89,0x00001e88,0x00000002,
20530x00000004,0x0004007c,0x00000027,0x00001cd8,
20540x00001e89,0x00050041,0x00000028,0x00001cd9,
20550x00001c65,0x000031f0,0x0003003e,0x00001cd9,
20560x00001cd8,0x00050080,0x00000006,0x00001cdc,
20570x000031f0,0x00000154,0x000200f9,0x00001ccb,
20580x000200f8,0x00001cdd,0x00050080,0x00000006,
20590x00001cdf,0x00001cca,0x00000368,0x00050041,
20600x00000156,0x00001ce0,0x000000fc,0x00000205,
20610x0004003d,0x00000007,0x00001ce1,0x00001ce0,
20620x00050051,0x00000006,0x00001eb8,0x00001ce1,
20630x00000000,0x00050095,0x000000ab,0x00001eba,
20640x00001eb8,0x00001cdf,0x00050051,0x00000006,
20650x00001ebb,0x00001eba,0x00000001,0x00050051,
20660x00000006,0x00001ebc,0x00001eba,0x00000000,
20670x00050051,0x00000006,0x00001ebf,0x00001ce1,
20680x00000001,0x00050080,0x00000006,0x00001ec1,
20690x00001ebf,0x00001ebb,0x00050050,0x00000007,
20700x00001ec2,0x00001ebc,0x00001ec1,0x0004007c,
20710x00000014,0x00001eb2,0x00001ec2,0x00060041,
20720x000000db,0x00001ea9,0x00001eb2,0x000000da,
20730x000000da,0x0006003d,0x00000006,0x00001eaa,
20740x00001ea9,0x00000002,0x00000004,0x00050080,
20750x00000006,0x00001ce4,0x00001cca,0x00000374,
20760x00050095,0x000000ab,0x00001edb,0x00001eb8,
20770x00001ce4,0x00050051,0x00000006,0x00001edc,
20780x00001edb,0x00000001,0x00050051,0x00000006,
20790x00001edd,0x00001edb,0x00000000,0x00050080,
20800x00000006,0x00001ee2,0x00001ebf,0x00001edc,
20810x00050050,0x00000007,0x00001ee3,0x00001edd,
20820x00001ee2,0x0004007c,0x00000014,0x00001ed3,
20830x00001ee3,0x00060041,0x000000db,0x00001eca,
20840x00001ed3,0x000000da,0x000000da,0x0006003d,
20850x00000006,0x00001ecb,0x00001eca,0x00000002,
20860x00000004,0x00050080,0x00000006,0x00001ce9,
20870x00001cca,0x0000037e,0x00050095,0x000000ab,
20880x00001efc,0x00001eb8,0x00001ce9,0x00050051,
20890x00000006,0x00001efd,0x00001efc,0x00000001,
20900x00050051,0x00000006,0x00001efe,0x00001efc,
20910x00000000,0x00050080,0x00000006,0x00001f03,
20920x00001ebf,0x00001efd,0x00050050,0x00000007,
20930x00001f04,0x00001efe,0x00001f03,0x0004007c,
20940x00000014,0x00001ef4,0x00001f04,0x00060041,
20950x000000db,0x00001eeb,0x00001ef4,0x000000da,
20960x000000da,0x0006003d,0x00000006,0x00001eec,
20970x00001eeb,0x00000002,0x00000004,0x00050080,
20980x00000006,0x00001cee,0x00001cca,0x00000388,
20990x00050095,0x000000ab,0x00001f1d,0x00001eb8,
21000x00001cee,0x00050051,0x00000006,0x00001f1e,
21010x00001f1d,0x00000001,0x00050051,0x00000006,
21020x00001f1f,0x00001f1d,0x00000000,0x00050080,
21030x00000006,0x00001f24,0x00001ebf,0x00001f1e,
21040x00050050,0x00000007,0x00001f25,0x00001f1f,
21050x00001f24,0x0004007c,0x00000014,0x00001f15,
21060x00001f25,0x00060041,0x000000db,0x00001f0c,
21070x00001f15,0x000000da,0x000000da,0x0006003d,
21080x00000006,0x00001f0d,0x00001f0c,0x00000002,
21090x00000004,0x00050041,0x000000fe,0x00001cf3,
21100x000000fc,0x0000022c,0x0004003d,0x00000006,
21110x00001cf4,0x00001cf3,0x00050084,0x00000006,
21120x00001cf6,0x00000228,0x00000b11,0x00050080,
21130x00000006,0x00001cf7,0x00001cf4,0x00001cf6,
21140x000200f9,0x00001cf8,0x000200f8,0x00001cf8,
21150x000700f5,0x00000006,0x000031f1,0x000000a6,
21160x00001cdd,0x00001d09,0x00001cfc,0x000500b0,
21170x0000002f,0x00001cfb,0x000031f1,0x00000118,
21180x000400f6,0x00001d0a,0x00001cfc,0x00000000,
21190x000400fa,0x00001cfb,0x00001cfc,0x00001d0a,
21200x000200f8,0x00001cfc,0x00050084,0x00000006,
21210x00001cff,0x0000010a,0x000031f1,0x00050080,
21220x00000006,0x00001d00,0x00001cf7,0x00001cff,
21230x00050041,0x00000156,0x00001d02,0x000000fc,
21240x000000da,0x0004003d,0x00000007,0x00001d03,
21250x00001d02,0x00050041,0x00000028,0x00001d04,
21260x00001c65,0x000031f1,0x0004003d,0x00000027,
21270x00001d05,0x00001d04,0x0004007c,0x00000006,
21280x00001f2b,0x00001d05,0x00050051,0x00000006,
21290x00001f44,0x00001d03,0x00000000,0x00050095,
21300x000000ab,0x00001f46,0x00001f44,0x00001d00,
21310x00050051,0x00000006,0x00001f47,0x00001f46,
21320x00000001,0x00050051,0x00000006,0x00001f48,
21330x00001f46,0x00000000,0x00050051,0x00000006,
21340x00001f4b,0x00001d03,0x00000001,0x00050080,
21350x00000006,0x00001f4d,0x00001f4b,0x00001f47,
21360x00050050,0x00000007,0x00001f4e,0x00001f48,
21370x00001f4d,0x0004007c,0x00000014,0x00001f3e,
21380x00001f4e,0x00060041,0x000000db,0x00001f36,
21390x00001f3e,0x000000da,0x000000da,0x0005003e,
21400x00001f36,0x00001f2b,0x00000002,0x00000004,
21410x00050080,0x00000006,0x00001d09,0x000031f1,
21420x00000154,0x000200f9,0x00001cf8,0x000200f8,
21430x00001d0a,0x00050080,0x00000006,0x00001d0c,
21440x00001cf7,0x00000368,0x00050041,0x00000156,
21450x00001d0d,0x000000fc,0x000000da,0x0004003d,
21460x00000007,0x00001d0e,0x00001d0d,0x00050051,
21470x00000006,0x00001f64,0x00001d0e,0x00000000,
21480x00050095,0x000000ab,0x00001f66,0x00001f64,
21490x00001d0c,0x00050051,0x00000006,0x00001f67,
21500x00001f66,0x00000001,0x00050051,0x00000006,
21510x00001f68,0x00001f66,0x00000000,0x00050051,
21520x00000006,0x00001f6b,0x00001d0e,0x00000001,
21530x00050080,0x00000006,0x00001f6d,0x00001f6b,
21540x00001f67,0x00050050,0x00000007,0x00001f6e,
21550x00001f68,0x00001f6d,0x0004007c,0x00000014,
21560x00001f5e,0x00001f6e,0x00060041,0x000000db,
21570x00001f56,0x00001f5e,0x000000da,0x000000da,
21580x0005003e,0x00001f56,0x00001eaa,0x00000002,
21590x00000004,0x00050080,0x00000006,0x00001d12,
21600x00001cf7,0x00000374,0x00050095,0x000000ab,
21610x00001f86,0x00001f64,0x00001d12,0x00050051,
21620x00000006,0x00001f87,0x00001f86,0x00000001,
21630x00050051,0x00000006,0x00001f88,0x00001f86,
21640x00000000,0x00050080,0x00000006,0x00001f8d,
21650x00001f6b,0x00001f87,0x00050050,0x00000007,
21660x00001f8e,0x00001f88,0x00001f8d,0x0004007c,
21670x00000014,0x00001f7e,0x00001f8e,0x00060041,
21680x000000db,0x00001f76,0x00001f7e,0x000000da,
21690x000000da,0x0005003e,0x00001f76,0x00001ecb,
21700x00000002,0x00000004,0x000500aa,0x0000002f,
21710x00001f93,0x00001eec,0x000000a6,0x000300f7,
21720x00001f98,0x00000000,0x000400fa,0x00001f93,
21730x00001f94,0x00001f98,0x000200f8,0x00001f94,
21740x000500aa,0x0000002f,0x00001f97,0x00001f0d,
21750x000000a6,0x000200f9,0x00001f98,0x000200f8,
21760x00001f98,0x000700f5,0x0000002f,0x00001f99,
21770x00001f93,0x00001d0a,0x00001f97,0x00001f94,
21780x000400a8,0x0000002f,0x00001d1d,0x00001f99,
21790x000300f7,0x00001db3,0x00000000,0x000400fa,
21800x00001d1d,0x00001d1e,0x00001db3,0x000200f8,
21810x00001d1e,0x00050041,0x00000156,0x00001d20,
21820x000000fc,0x0000021d,0x0004003d,0x00000007,
21830x00001d21,0x00001d20,0x00050051,0x00000006,
21840x00001fa1,0x00001d21,0x00000000,0x00050095,
21850x000000ab,0x00001fa2,0x00001eec,0x00001fa1,
21860x00050051,0x00000006,0x00001fa3,0x00001fa2,
21870x00000001,0x00050051,0x00000006,0x00001fa4,
21880x00001fa2,0x00000000,0x00050051,0x00000006,
21890x00001fa9,0x00001d21,0x00000001,0x00050080,
21900x00000006,0x00001faa,0x00001f0d,0x00001fa9,
21910x00050080,0x00000006,0x00001fac,0x00001faa,
21920x00001fa3,0x00050095,0x000000ab,0x00001fc6,
21930x00001fa4,0x00000368,0x00050051,0x00000006,
21940x00001fc7,0x00001fc6,0x00000001,0x00050051,
21950x00000006,0x00001fc8,0x00001fc6,0x00000000,
21960x00050080,0x00000006,0x00001fcd,0x00001fac,
21970x00001fc7,0x00050050,0x00000007,0x00001fce,
21980x00001fc8,0x00001fcd,0x0004007c,0x00000014,
21990x00001fbe,0x00001fce,0x00060041,0x000000db,
22000x00001fb5,0x00001fbe,0x000000da,0x000000da,
22010x0006003d,0x00000006,0x00001fb6,0x00001fb5,
22020x00000002,0x00000004,0x00050095,0x000000ab,
22030x00001fe7,0x00001fa4,0x0000011f,0x00050051,
22040x00000006,0x00001fe8,0x00001fe7,0x00000001,
22050x00050051,0x00000006,0x00001fe9,0x00001fe7,
22060x00000000,0x00050080,0x00000006,0x00001fee,
22070x00001fac,0x00001fe8,0x00050050,0x00000007,
22080x00001fef,0x00001fe9,0x00001fee,0x0004007c,
22090x00000014,0x00001fdf,0x00001fef,0x00060041,
22100x000000db,0x00001fd6,0x00001fdf,0x000000da,
22110x000000da,0x0006003d,0x00000006,0x00001fd7,
22120x00001fd6,0x00000002,0x00000004,0x0004007c,
22130x00000027,0x00001d27,0x00001fd7,0x00050095,
22140x000000ab,0x00002008,0x00001fa4,0x00000189,
22150x00050051,0x00000006,0x00002009,0x00002008,
22160x00000001,0x00050051,0x00000006,0x0000200a,
22170x00002008,0x00000000,0x00050080,0x00000006,
22180x0000200f,0x00001fac,0x00002009,0x00050050,
22190x00000007,0x00002010,0x0000200a,0x0000200f,
22200x0004007c,0x00000014,0x00002000,0x00002010,
22210x00060041,0x000000db,0x00001ff7,0x00002000,
22220x000000da,0x000000da,0x0006003d,0x00000006,
22230x00001ff8,0x00001ff7,0x00000002,0x00000004,
22240x0004007c,0x00000027,0x00001d2a,0x00001ff8,
22250x00050095,0x000000ab,0x00002029,0x00001fa4,
22260x00000150,0x00050051,0x00000006,0x0000202a,
22270x00002029,0x00000001,0x00050051,0x00000006,
22280x0000202b,0x00002029,0x00000000,0x00050080,
22290x00000006,0x00002030,0x00001fac,0x0000202a,
22300x00050050,0x00000007,0x00002031,0x0000202b,
22310x00002030,0x0004007c,0x00000014,0x00002021,
22320x00002031,0x00060041,0x000000db,0x00002018,
22330x00002021,0x000000da,0x000000da,0x0006003d,
22340x00000006,0x00002019,0x00002018,0x00000002,
22350x00000004,0x0004007c,0x00000027,0x00001d2d,
22360x00002019,0x00050095,0x000000ab,0x0000204a,
22370x00001fa4,0x00000463,0x00050051,0x00000006,
22380x0000204b,0x0000204a,0x00000001,0x00050051,
22390x00000006,0x0000204c,0x0000204a,0x00000000,
22400x00050080,0x00000006,0x00002051,0x00001fac,
22410x0000204b,0x00050050,0x00000007,0x00002052,
22420x0000204c,0x00002051,0x0004007c,0x00000014,
22430x00002042,0x00002052,0x00060041,0x000000db,
22440x00002039,0x00002042,0x000000da,0x000000da,
22450x0006003d,0x00000006,0x0000203a,0x00002039,
22460x00000002,0x00000004,0x0004007c,0x00000027,
22470x00001d31,0x0000203a,0x00050095,0x000000ab,
22480x0000206b,0x00001fa4,0x00000469,0x00050051,
22490x00000006,0x0000206c,0x0000206b,0x00000001,
22500x00050051,0x00000006,0x0000206d,0x0000206b,
22510x00000000,0x00050080,0x00000006,0x00002072,
22520x00001fac,0x0000206c,0x00050050,0x00000007,
22530x00002073,0x0000206d,0x00002072,0x0004007c,
22540x00000014,0x00002063,0x00002073,0x00060041,
22550x000000db,0x0000205a,0x00002063,0x000000da,
22560x000000da,0x0006003d,0x00000006,0x0000205b,
22570x0000205a,0x00000002,0x00000004,0x0004007c,
22580x00000027,0x00001d34,0x0000205b,0x00050095,
22590x000000ab,0x0000208c,0x00001fa4,0x00000347,
22600x00050051,0x00000006,0x0000208d,0x0000208c,
22610x00000001,0x00050051,0x00000006,0x0000208e,
22620x0000208c,0x00000000,0x00050080,0x00000006,
22630x00002093,0x00001fac,0x0000208d,0x00050050,
22640x00000007,0x00002094,0x0000208e,0x00002093,
22650x0004007c,0x00000014,0x00002084,0x00002094,
22660x00060041,0x000000db,0x0000207b,0x00002084,
22670x000000da,0x000000da,0x0006003d,0x00000006,
22680x0000207c,0x0000207b,0x00000002,0x00000004,
22690x0004007c,0x00000027,0x00001d37,0x0000207c,
22700x000500bc,0x0000002f,0x0000209b,0x00001d27,
22710x00001d31,0x000300f7,0x000020a2,0x00000000,
22720x000400fa,0x0000209b,0x0000209c,0x000020a2,
22730x000200f8,0x0000209c,0x000500bc,0x0000002f,
22740x000020a1,0x00001d2a,0x00001d34,0x000200f9,
22750x000020a2,0x000200f8,0x000020a2,0x000700f5,
22760x0000002f,0x000020a3,0x0000209b,0x00001d1e,
22770x000020a1,0x0000209c,0x000300f7,0x000020aa,
22780x00000000,0x000400fa,0x000020a3,0x000020a4,
22790x000020aa,0x000200f8,0x000020a4,0x000500bc,
22800x0000002f,0x000020a9,0x00001d2d,0x00001d37,
22810x000200f9,0x000020aa,0x000200f8,0x000020aa,
22820x000700f5,0x0000002f,0x000020ab,0x000020a3,
22830x000020a2,0x000020a9,0x000020a4,0x000300f7,
22840x00001d41,0x00000000,0x000400fa,0x000020ab,
22850x00001d3d,0x00001d41,0x000200f8,0x00001d3d,
22860x000500c2,0x00000006,0x00001d3f,0x00001eaa,
22870x0000047e,0x000500ab,0x0000002f,0x00001d40,
22880x00001d3f,0x000000a6,0x000200f9,0x00001d41,
22890x000200f8,0x00001d41,0x000700f5,0x0000002f,
22900x00001d42,0x000020ab,0x000020aa,0x00001d40,
22910x00001d3d,0x000300f7,0x00001db2,0x00000000,
22920x000400fa,0x00001d42,0x00001d43,0x00001db2,
22930x000200f8,0x00001d43,0x000200f9,0x00001d44,
22940x000200f8,0x00001d44,0x000700f5,0x0000004b,
22950x00003227,0x000032a7,0x00001d43,0x00001dad,
22960x00001d48,0x000700f5,0x0000004b,0x00003215,
22970x000032a5,0x00001d43,0x00001daa,0x00001d48,
22980x000700f5,0x00000006,0x000031f2,0x000000a6,
22990x00001d43,0x00001db0,0x00001d48,0x000500b0,
23000x0000002f,0x00001d47,0x000031f2,0x00000111,
23010x000400f6,0x00001db1,0x00001d48,0x00000000,
23020x000400fa,0x00001d47,0x00001d48,0x00001db1,
23030x000200f8,0x00001d48,0x000500c7,0x00000006,
23040x00001d4a,0x000031f2,0x000000b0,0x000500ab,
23050x0000002f,0x00001d4b,0x00001d4a,0x000000a6,
23060x000600a9,0x00000027,0x000032ad,0x00001d4b,
23070x00001d31,0x00001d27,0x000500c7,0x00000006,
23080x00001d55,0x000031f2,0x00000170,0x000500ab,
23090x0000002f,0x00001d56,0x00001d55,0x000000a6,
23100x000600a9,0x00000027,0x000032ae,0x00001d56,
23110x00001d34,0x00001d2a,0x000500c7,0x00000006,
23120x00001d60,0x000031f2,0x0000010a,0x000500ab,
23130x0000002f,0x00001d61,0x00001d60,0x000000a6,
23140x000600a9,0x00000027,0x000032af,0x00001d61,
23150x00001d37,0x00001d2d,0x00050041,0x00000028,
23160x00001d6b,0x00001c65,0x000000da,0x0004003d,
23170x00000027,0x00001d6c,0x00001d6b,0x00050085,
23180x00000027,0x00001d6f,0x00001d6c,0x000032ad,
23190x00050041,0x00000028,0x00001d70,0x00001c65,
23200x00000154,0x0004003d,0x00000027,0x00001d71,
23210x00001d70,0x00050085,0x00000027,0x00001d74,
23220x00001d71,0x000032ae,0x00050081,0x00000027,
23230x00001d75,0x00001d6f,0x00001d74,0x00050041,
23240x00000028,0x00001d76,0x00001c65,0x00000205,
23250x0004003d,0x00000027,0x00001d77,0x00001d76,
23260x00050085,0x00000027,0x00001d7a,0x00001d77,
23270x000032af,0x00050081,0x00000027,0x00001d7b,
23280x00001d75,0x00001d7a,0x00050041,0x00000028,
23290x00001d7c,0x00001c65,0x0000020d,0x0004003d,
23300x00000027,0x00001d7d,0x00001d7c,0x00050081,
23310x00000027,0x00001d7e,0x00001d7b,0x00001d7d,
23320x00050041,0x00000028,0x00001d7f,0x00001c65,
23330x00000215,0x0004003d,0x00000027,0x00001d80,
23340x00001d7f,0x00050085,0x00000027,0x00001d83,
23350x00001d80,0x000032ad,0x00050041,0x00000028,
23360x00001d84,0x00001c65,0x0000021d,0x0004003d,
23370x00000027,0x00001d85,0x00001d84,0x00050085,
23380x00000027,0x00001d88,0x00001d85,0x000032ae,
23390x00050081,0x00000027,0x00001d89,0x00001d83,
23400x00001d88,0x00050041,0x00000028,0x00001d8a,
23410x00001c65,0x00000233,0x0004003d,0x00000027,
23420x00001d8b,0x00001d8a,0x00050085,0x00000027,
23430x00001d8e,0x00001d8b,0x000032af,0x00050081,
23440x00000027,0x00001d8f,0x00001d89,0x00001d8e,
23450x00050041,0x00000028,0x00001d90,0x00001c65,
23460x000004d8,0x0004003d,0x00000027,0x00001d91,
23470x00001d90,0x00050081,0x00000027,0x00001d92,
23480x00001d8f,0x00001d91,0x00050041,0x00000028,
23490x00001d93,0x00001c65,0x00000308,0x0004003d,
23500x00000027,0x00001d94,0x00001d93,0x00050085,
23510x00000027,0x00001d97,0x00001d94,0x000032ad,
23520x00050041,0x00000028,0x00001d98,0x00001c65,
23530x00000250,0x0004003d,0x00000027,0x00001d99,
23540x00001d98,0x00050085,0x00000027,0x00001d9c,
23550x00001d99,0x000032ae,0x00050081,0x00000027,
23560x00001d9d,0x00001d97,0x00001d9c,0x00050041,
23570x00000028,0x00001d9e,0x00001c65,0x00000266,
23580x0004003d,0x00000027,0x00001d9f,0x00001d9e,
23590x00050085,0x00000027,0x00001da2,0x00001d9f,
23600x000032af,0x00050081,0x00000027,0x00001da3,
23610x00001d9d,0x00001da2,0x00050041,0x00000028,
23620x00001da4,0x00001c65,0x0000027b,0x0004003d,
23630x00000027,0x00001da5,0x00001da4,0x00050081,
23640x00000027,0x00001da6,0x00001da3,0x00001da5,
23650x00060050,0x0000004b,0x00001da7,0x00001d7e,
23660x00001d92,0x00001da6,0x0007000c,0x0000004b,
23670x00001daa,0x00000001,0x00000025,0x00003215,
23680x00001da7,0x0007000c,0x0000004b,0x00001dad,
23690x00000001,0x00000028,0x00003227,0x00001da7,
23700x00050080,0x00000006,0x00001db0,0x000031f2,
23710x00000154,0x000200f9,0x00001d44,0x000200f8,
23720x00001db1,0x000200f9,0x00001db2,0x000200f8,
23730x00001db2,0x000700f5,0x0000004b,0x00003223,
23740x000032a7,0x00001d41,0x00003227,0x00001db1,
23750x000700f5,0x0000004b,0x00003211,0x000032a5,
23760x00001d41,0x00003215,0x00001db1,0x000200f9,
23770x00001db3,0x000200f8,0x00001db3,0x000700f5,
23780x0000004b,0x00003221,0x000032a7,0x00001f98,
23790x00003223,0x00001db2,0x000700f5,0x0000004b,
23800x0000320f,0x000032a5,0x00001f98,0x00003211,
23810x00001db2,0x000700f5,0x00000006,0x000031fb,
23820x00000380,0x00001f98,0x00001fb6,0x00001db2,
23830x00050041,0x00000028,0x00001db4,0x00001c65,
23840x000000da,0x0004003d,0x00000027,0x00001db5,
23850x00001db4,0x000500b4,0x0000002f,0x00001db6,
23860x00001db5,0x000004fc,0x000300f7,0x00001dbb,
23870x00000000,0x000400fa,0x00001db6,0x00001db7,
23880x00001dbb,0x000200f8,0x00001db7,0x00050041,
23890x00000028,0x00001db8,0x00001c65,0x00000154,
23900x0004003d,0x00000027,0x00001db9,0x00001db8,
23910x000500b4,0x0000002f,0x00001dba,0x00001db9,
23920x0000026d,0x000200f9,0x00001dbb,0x000200f8,
23930x00001dbb,0x000700f5,0x0000002f,0x00001dbc,
23940x00001db6,0x00001db3,0x00001dba,0x00001db7,
23950x000300f7,0x00001dc1,0x00000000,0x000400fa,
23960x00001dbc,0x00001dbd,0x00001dc1,0x000200f8,
23970x00001dbd,0x00050041,0x00000028,0x00001dbe,
23980x00001c65,0x00000205,0x0004003d,0x00000027,
23990x00001dbf,0x00001dbe,0x000500b4,0x0000002f,
24000x00001dc0,0x00001dbf,0x0000026d,0x000200f9,
24010x00001dc1,0x000200f8,0x00001dc1,0x000700f5,
24020x0000002f,0x00001dc2,0x00001dbc,0x00001dbb,
24030x00001dc0,0x00001dbd,0x000300f7,0x00001dc7,
24040x00000000,0x000400fa,0x00001dc2,0x00001dc3,
24050x00001dc7,0x000200f8,0x00001dc3,0x00050041,
24060x00000028,0x00001dc4,0x00001c65,0x00000215,
24070x0004003d,0x00000027,0x00001dc5,0x00001dc4,
24080x000500b4,0x0000002f,0x00001dc6,0x00001dc5,
24090x0000026d,0x000200f9,0x00001dc7,0x000200f8,
24100x00001dc7,0x000700f5,0x0000002f,0x00001dc8,
24110x00001dc2,0x00001dc1,0x00001dc6,0x00001dc3,
24120x000300f7,0x00001dcd,0x00000000,0x000400fa,
24130x00001dc8,0x00001dc9,0x00001dcd,0x000200f8,
24140x00001dc9,0x00050041,0x00000028,0x00001dca,
24150x00001c65,0x0000021d,0x0004003d,0x00000027,
24160x00001dcb,0x00001dca,0x000500b4,0x0000002f,
24170x00001dcc,0x00001dcb,0x000004fc,0x000200f9,
24180x00001dcd,0x000200f8,0x00001dcd,0x000700f5,
24190x0000002f,0x00001dce,0x00001dc8,0x00001dc7,
24200x00001dcc,0x00001dc9,0x000300f7,0x00001dd3,
24210x00000000,0x000400fa,0x00001dce,0x00001dcf,
24220x00001dd3,0x000200f8,0x00001dcf,0x00050041,
24230x00000028,0x00001dd0,0x00001c65,0x00000233,
24240x0004003d,0x00000027,0x00001dd1,0x00001dd0,
24250x000500b4,0x0000002f,0x00001dd2,0x00001dd1,
24260x0000026d,0x000200f9,0x00001dd3,0x000200f8,
24270x00001dd3,0x000700f5,0x0000002f,0x00001dd4,
24280x00001dce,0x00001dcd,0x00001dd2,0x00001dcf,
24290x000300f7,0x00001dd9,0x00000000,0x000400fa,
24300x00001dd4,0x00001dd5,0x00001dd9,0x000200f8,
24310x00001dd5,0x00050041,0x00000028,0x00001dd6,
24320x00001c65,0x00000308,0x0004003d,0x00000027,
24330x00001dd7,0x00001dd6,0x000500b4,0x0000002f,
24340x00001dd8,0x00001dd7,0x0000026d,0x000200f9,
24350x00001dd9,0x000200f8,0x00001dd9,0x000700f5,
24360x0000002f,0x00001dda,0x00001dd4,0x00001dd3,
24370x00001dd8,0x00001dd5,0x000300f7,0x00001ddf,
24380x00000000,0x000400fa,0x00001dda,0x00001ddb,
24390x00001ddf,0x000200f8,0x00001ddb,0x00050041,
24400x00000028,0x00001ddc,0x00001c65,0x00000250,
24410x0004003d,0x00000027,0x00001ddd,0x00001ddc,
24420x000500b4,0x0000002f,0x00001dde,0x00001ddd,
24430x0000026d,0x000200f9,0x00001ddf,0x000200f8,
24440x00001ddf,0x000700f5,0x0000002f,0x00001de0,
24450x00001dda,0x00001dd9,0x00001dde,0x00001ddb,
24460x000300f7,0x00001de5,0x00000000,0x000400fa,
24470x00001de0,0x00001de1,0x00001de5,0x000200f8,
24480x00001de1,0x00050041,0x00000028,0x00001de2,
24490x00001c65,0x00000266,0x0004003d,0x00000027,
24500x00001de3,0x00001de2,0x000500b4,0x0000002f,
24510x00001de4,0x00001de3,0x000004fc,0x000200f9,
24520x00001de5,0x000200f8,0x00001de5,0x000700f5,
24530x0000002f,0x00001de6,0x00001de0,0x00001ddf,
24540x00001de4,0x00001de1,0x00050080,0x00000006,
24550x00001de8,0x00001cf7,0x0000037e,0x000500c7,
24560x00000006,0x00001dea,0x000031fb,0x00000531,
24570x000600a9,0x00000006,0x00001dec,0x00001de6,
24580x00000130,0x000000a6,0x000500c5,0x00000006,
24590x00001ded,0x00001dea,0x00001dec,0x00050095,
24600x000000ab,0x000020c4,0x00001f64,0x00001de8,
24610x00050051,0x00000006,0x000020c5,0x000020c4,
24620x00000001,0x00050051,0x00000006,0x000020c6,
24630x000020c4,0x00000000,0x00050080,0x00000006,
24640x000020cb,0x00001f6b,0x000020c5,0x00050050,
24650x00000007,0x000020cc,0x000020c6,0x000020cb,
24660x0004007c,0x00000014,0x000020bc,0x000020cc,
24670x00060041,0x000000db,0x000020b4,0x000020bc,
24680x000000da,0x000000da,0x0005003e,0x000020b4,
24690x00001ded,0x00000002,0x00000004,0x00050080,
24700x00000006,0x00001df2,0x00001cf7,0x00000388,
24710x000500c2,0x00000006,0x00001df5,0x00001eec,
24720x00000308,0x000500c4,0x00000006,0x00001df8,
24730x00001f0d,0x0000047e,0x000500c5,0x00000006,
24740x00001df9,0x00001df5,0x00001df8,0x00050095,
24750x000000ab,0x000020e4,0x00001f64,0x00001df2,
24760x00050051,0x00000006,0x000020e5,0x000020e4,
24770x00000001,0x00050051,0x00000006,0x000020e6,
24780x000020e4,0x00000000,0x00050080,0x00000006,
24790x000020eb,0x00001f6b,0x000020e5,0x00050050,
24800x00000007,0x000020ec,0x000020e6,0x000020eb,
24810x0004007c,0x00000014,0x000020dc,0x000020ec,
24820x00060041,0x000000db,0x000020d4,0x000020dc,
24830x000000da,0x000000da,0x0005003e,0x000020d4,
24840x00001df9,0x00000002,0x00000004,0x0004003d,
24850x00000027,0x00001dfe,0x00001db4,0x00050041,
24860x00000028,0x00001dff,0x00001c65,0x00000215,
24870x0004003d,0x00000027,0x00001e00,0x00001dff,
24880x00050041,0x00000028,0x00001e01,0x00001c65,
24890x00000308,0x0004003d,0x00000027,0x00001e02,
24900x00001e01,0x00050041,0x00000028,0x00001e03,
24910x00001c65,0x00000154,0x0004003d,0x00000027,
24920x00001e04,0x00001e03,0x00050041,0x00000028,
24930x00001e05,0x00001c65,0x0000021d,0x0004003d,
24940x00000027,0x00001e06,0x00001e05,0x00050041,
24950x00000028,0x00001e07,0x00001c65,0x00000250,
24960x0004003d,0x00000027,0x00001e08,0x00001e07,
24970x00050041,0x00000028,0x00001e09,0x00001c65,
24980x00000205,0x0004003d,0x00000027,0x00001e0a,
24990x00001e09,0x00050041,0x00000028,0x00001e0b,
25000x00001c65,0x00000233,0x0004003d,0x00000027,
25010x00001e0c,0x00001e0b,0x00050041,0x00000028,
25020x00001e0d,0x00001c65,0x00000266,0x0004003d,
25030x00000027,0x00001e0e,0x00001e0d,0x00060050,
25040x0000004b,0x00001e0f,0x00001dfe,0x00001e00,
25050x00001e02,0x00060050,0x0000004b,0x00001e10,
25060x00001e04,0x00001e06,0x00001e08,0x00060050,
25070x0000004b,0x00001e11,0x00001e0a,0x00001e0c,
25080x00001e0e,0x00060050,0x0000054b,0x00001e12,
25090x00001e0f,0x00001e10,0x00001e11,0x0006000c,
25100x00000027,0x00001e14,0x00000001,0x00000021,
25110x00001e12,0x000500b7,0x0000002f,0x00001e16,
25120x00001e14,0x0000026d,0x000300f7,0x00001e1b,
25130x00000000,0x000400fa,0x00001e16,0x00001e17,
25140x00001e1a,0x000200f8,0x00001e17,0x0006000c,
25150x0000054b,0x00001e19,0x00000001,0x00000022,
25160x00001e12,0x000200f9,0x00001e1b,0x000200f8,
25170x00001e1a,0x000200f9,0x00001e1b,0x000200f8,
25180x00001e1b,0x000700f5,0x0000054b,0x00003202,
25190x00001e19,0x00001e17,0x00000571,0x00001e1a,
25200x0003003e,0x00001ca6,0x00003202,0x00050041,
25210x00000028,0x00001e1d,0x00001c65,0x0000020d,
25220x0004003d,0x00000027,0x00001e1e,0x00001e1d,
25230x00050041,0x00000028,0x00001e1f,0x00001c65,
25240x000004d8,0x0004003d,0x00000027,0x00001e20,
25250x00001e1f,0x00050041,0x00000028,0x00001e21,
25260x00001c65,0x0000027b,0x0004003d,0x00000027,
25270x00001e22,0x00001e21,0x00060050,0x0000004b,
25280x00001e23,0x00001e1e,0x00001e20,0x00001e22,
25290x00050091,0x0000004b,0x00001e26,0x00003202,
25300x00001e23,0x0004007f,0x0000004b,0x00001e27,
25310x00001e26,0x0003003e,0x00001ca9,0x00001e27,
25320x000200f9,0x00001e28,0x000200f8,0x00001e28,
25330x000700f5,0x00000006,0x00003203,0x000000a6,
25340x00001e1b,0x00001e5b,0x00001e2c,0x000500b0,
25350x0000002f,0x00001e2b,0x00003203,0x000002b7,
25360x000400f6,0x00001e5c,0x00001e2c,0x00000000,
25370x000400fa,0x00001e2b,0x00001e2c,0x00001e5c,
25380x000200f8,0x00001e2c,0x00050080,0x00000006,
25390x00001e2e,0x00001cf7,0x00000107,0x00050084,
25400x00000006,0x00001e30,0x0000011f,0x00003203,
25410x00050080,0x00000006,0x00001e31,0x00001e2e,
25420x00001e30,0x00060041,0x00000028,0x00001e35,
25430x00001ca6,0x000000da,0x00003203,0x0004003d,
25440x00000027,0x00001e36,0x00001e35,0x0004007c,
25450x00000006,0x000020f2,0x00001e36,0x00050095,
25460x000000ab,0x0000210d,0x00001f64,0x00001e31,
25470x00050051,0x00000006,0x0000210e,0x0000210d,
25480x00000001,0x00050051,0x00000006,0x0000210f,
25490x0000210d,0x00000000,0x00050080,0x00000006,
25500x00002114,0x00001f6b,0x0000210e,0x00050050,
25510x00000007,0x00002115,0x0000210f,0x00002114,
25520x0004007c,0x00000014,0x00002105,0x00002115,
25530x00060041,0x000000db,0x000020fd,0x00002105,
25540x000000da,0x000000da,0x0005003e,0x000020fd,
25550x000020f2,0x00000002,0x00000004,0x00050080,
25560x00000006,0x00001e39,0x00001cf7,0x00000597,
25570x00050080,0x00000006,0x00001e3c,0x00001e39,
25580x00001e30,0x00060041,0x00000028,0x00001e40,
25590x00001ca6,0x00000154,0x00003203,0x0004003d,
25600x00000027,0x00001e41,0x00001e40,0x0004007c,
25610x00000006,0x0000211b,0x00001e41,0x00050095,
25620x000000ab,0x00002136,0x00001f64,0x00001e3c,
25630x00050051,0x00000006,0x00002137,0x00002136,
25640x00000001,0x00050051,0x00000006,0x00002138,
25650x00002136,0x00000000,0x00050080,0x00000006,
25660x0000213d,0x00001f6b,0x00002137,0x00050050,
25670x00000007,0x0000213e,0x00002138,0x0000213d,
25680x0004007c,0x00000014,0x0000212e,0x0000213e,
25690x00060041,0x000000db,0x00002126,0x0000212e,
25700x000000da,0x000000da,0x0005003e,0x00002126,
25710x0000211b,0x00000002,0x00000004,0x00050080,
25720x00000006,0x00001e44,0x00001cf7,0x000005a6,
25730x00050080,0x00000006,0x00001e47,0x00001e44,
25740x00001e30,0x00060041,0x00000028,0x00001e4b,
25750x00001ca6,0x00000205,0x00003203,0x0004003d,
25760x00000027,0x00001e4c,0x00001e4b,0x0004007c,
25770x00000006,0x00002144,0x00001e4c,0x00050095,
25780x000000ab,0x0000215f,0x00001f64,0x00001e47,
25790x00050051,0x00000006,0x00002160,0x0000215f,
25800x00000001,0x00050051,0x00000006,0x00002161,
25810x0000215f,0x00000000,0x00050080,0x00000006,
25820x00002166,0x00001f6b,0x00002160,0x00050050,
25830x00000007,0x00002167,0x00002161,0x00002166,
25840x0004007c,0x00000014,0x00002157,0x00002167,
25850x00060041,0x000000db,0x0000214f,0x00002157,
25860x000000da,0x000000da,0x0005003e,0x0000214f,
25870x00002144,0x00000002,0x00000004,0x00050080,
25880x00000006,0x00001e4f,0x00001cf7,0x000005b5,
25890x00050080,0x00000006,0x00001e52,0x00001e4f,
25900x00001e30,0x00050041,0x00000028,0x00001e56,
25910x00001ca9,0x00003203,0x0004003d,0x00000027,
25920x00001e57,0x00001e56,0x0004007c,0x00000006,
25930x0000216d,0x00001e57,0x00050095,0x000000ab,
25940x00002188,0x00001f64,0x00001e52,0x00050051,
25950x00000006,0x00002189,0x00002188,0x00000001,
25960x00050051,0x00000006,0x0000218a,0x00002188,
25970x00000000,0x00050080,0x00000006,0x0000218f,
25980x00001f6b,0x00002189,0x00050050,0x00000007,
25990x00002190,0x0000218a,0x0000218f,0x0004007c,
26000x00000014,0x00002180,0x00002190,0x00060041,
26010x000000db,0x00002178,0x00002180,0x000000da,
26020x000000da,0x0005003e,0x00002178,0x0000216d,
23720x00000002,0x00000004,0x00050080,0x00000006, 26030x00000002,0x00000004,0x00050080,0x00000006,
23730x00001e5d,0x00001e47,0x00000115,0x00050051, 26040x00001e5b,0x00003203,0x00000154,0x000200f9,
23740x00000027,0x00001e61,0x00002b70,0x00000000, 26050x00001e28,0x000200f8,0x00001e5c,0x00050080,
23750x0004007c,0x00000006,0x00001f04,0x00001e61, 26060x00000006,0x00001e5e,0x00001cf7,0x000005c6,
23760x00050095,0x000000a8,0x00001f1f,0x00001ea2, 26070x00050095,0x000000ab,0x000021a8,0x00001f64,
23770x00001e5d,0x00050051,0x00000006,0x00001f20, 26080x00001e5e,0x00050051,0x00000006,0x000021a9,
23780x00001f1f,0x00000001,0x00050051,0x00000006, 26090x000021a8,0x00000001,0x00050051,0x00000006,
23790x00001f21,0x00001f1f,0x00000000,0x00050080, 26100x000021aa,0x000021a8,0x00000000,0x00050080,
23800x00000006,0x00001f26,0x00001ea9,0x00001f20, 26110x00000006,0x000021af,0x00001f6b,0x000021a9,
23810x00050050,0x00000007,0x00001f27,0x00001f21, 26120x00050050,0x00000007,0x000021b0,0x000021aa,
23820x00001f26,0x0004007c,0x00000014,0x00001f17, 26130x000021af,0x0004007c,0x00000014,0x000021a0,
23830x00001f27,0x00060041,0x000000d8,0x00001f0f, 26140x000021b0,0x00060041,0x000000db,0x00002198,
23840x00001f17,0x000000d7,0x000000d7,0x0005003e, 26150x000021a0,0x000000da,0x000000da,0x0005003e,
23850x00001f0f,0x00001f04,0x00000002,0x00000004, 26160x00002198,0x00000b11,0x00000002,0x00000004,
23860x00050080,0x00000006,0x00001e64,0x00001e47, 26170x00050080,0x00000006,0x00001e64,0x00001cf7,
23870x0000011c,0x00050051,0x00000027,0x00001e68, 26180x000005d0,0x00050095,0x000000ab,0x000021c8,
23880x00002b70,0x00000001,0x0004007c,0x00000006, 26190x00001f64,0x00001e64,0x00050051,0x00000006,
23890x00001f2d,0x00001e68,0x00050095,0x000000a8, 26200x000021c9,0x000021c8,0x00000001,0x00050051,
23900x00001f48,0x00001ea2,0x00001e64,0x00050051, 26210x00000006,0x000021ca,0x000021c8,0x00000000,
23910x00000006,0x00001f49,0x00001f48,0x00000001, 26220x00050080,0x00000006,0x000021cf,0x00001f6b,
23920x00050051,0x00000006,0x00001f4a,0x00001f48, 26230x000021c9,0x00050050,0x00000007,0x000021d0,
23930x00000000,0x00050080,0x00000006,0x00001f4f, 26240x000021ca,0x000021cf,0x0004007c,0x00000014,
23940x00001ea9,0x00001f49,0x00050050,0x00000007, 26250x000021c0,0x000021d0,0x00060041,0x000000db,
23950x00001f50,0x00001f4a,0x00001f4f,0x0004007c, 26260x000021b8,0x000021c0,0x000000da,0x000000da,
23960x00000014,0x00001f40,0x00001f50,0x00060041, 26270x0005003e,0x000021b8,0x00000380,0x00000002,
23970x000000d8,0x00001f38,0x00001f40,0x000000d7, 26280x00000004,0x00050080,0x00000006,0x00001e69,
23980x000000d7,0x0005003e,0x00001f38,0x00001f2d, 26290x00001cf7,0x000005d9,0x00050095,0x000000ab,
26300x000021e8,0x00001f64,0x00001e69,0x00050051,
26310x00000006,0x000021e9,0x000021e8,0x00000001,
26320x00050051,0x00000006,0x000021ea,0x000021e8,
26330x00000000,0x00050080,0x00000006,0x000021ef,
26340x00001f6b,0x000021e9,0x00050050,0x00000007,
26350x000021f0,0x000021ea,0x000021ef,0x0004007c,
26360x00000014,0x000021e0,0x000021f0,0x00060041,
26370x000000db,0x000021d8,0x000021e0,0x000000da,
26380x000000da,0x0005003e,0x000021d8,0x000000a6,
23990x00000002,0x00000004,0x00050080,0x00000006, 26390x00000002,0x00000004,0x00050080,0x00000006,
24000x00001e6b,0x00001e47,0x00000186,0x00050051, 26400x00001e6e,0x00001cf7,0x000005e2,0x00050095,
24010x00000027,0x00001e6f,0x00002b70,0x00000002, 26410x000000ab,0x00002208,0x00001f64,0x00001e6e,
24020x0004007c,0x00000006,0x00001f56,0x00001e6f, 26420x00050051,0x00000006,0x00002209,0x00002208,
24030x00050095,0x000000a8,0x00001f71,0x00001ea2, 26430x00000001,0x00050051,0x00000006,0x0000220a,
24040x00001e6b,0x00050051,0x00000006,0x00001f72, 26440x00002208,0x00000000,0x00050080,0x00000006,
24050x00001f71,0x00000001,0x00050051,0x00000006, 26450x0000220f,0x00001f6b,0x00002209,0x00050050,
24060x00001f73,0x00001f71,0x00000000,0x00050080, 26460x00000007,0x00002210,0x0000220a,0x0000220f,
24070x00000006,0x00001f78,0x00001ea9,0x00001f72, 26470x0004007c,0x00000014,0x00002200,0x00002210,
24080x00050050,0x00000007,0x00001f79,0x00001f73, 26480x00060041,0x000000db,0x000021f8,0x00002200,
24090x00001f78,0x0004007c,0x00000014,0x00001f69, 26490x000000da,0x000000da,0x0005003e,0x000021f8,
24100x00001f79,0x00060041,0x000000d8,0x00001f61, 26500x000000a6,0x00000002,0x00000004,0x000500b4,
24110x00001f69,0x000000d7,0x000000d7,0x0005003e, 26510x0000002f,0x00001e73,0x00001e14,0x0000026d,
24120x00001f61,0x00001f56,0x00000002,0x00000004, 26520x00060050,0x00000395,0x000032b0,0x00001e73,
24130x000300f7,0x00001fb9,0x00000000,0x000300fb, 26530x00001e73,0x00001e73,0x000600a9,0x0000004b,
24140x000000a3,0x00001f88,0x000200f8,0x00001f88, 26540x000032b1,0x000032b0,0x000032a7,0x00003221,
24150x000500bc,0x0000002f,0x00001fc0,0x00001e4c, 26550x000600a9,0x0000004b,0x000032b3,0x000032b0,
24160x00001e61,0x000300f7,0x00001fc7,0x00000000, 26560x000032a5,0x0000320f,0x00050041,0x000000fe,
24170x000400fa,0x00001fc0,0x00001fc1,0x00001fc7, 26570x0000225a,0x000000fc,0x000000fd,0x0004003d,
24180x000200f8,0x00001fc1,0x000500bc,0x0000002f, 26580x00000006,0x0000225b,0x0000225a,0x00050084,
24190x00001fc6,0x00001e53,0x00001e68,0x000200f9, 26590x00000006,0x0000225c,0x0000011f,0x0000225b,
24200x00001fc7,0x000200f8,0x00001fc7,0x000700f5, 26600x00050080,0x00000006,0x0000225d,0x00000107,
24210x0000002f,0x00001fc8,0x00001fc0,0x00001f88, 26610x0000225c,0x00050080,0x00000006,0x00002263,
24220x00001fc6,0x00001fc1,0x000300f7,0x00001fcf, 26620x0000225b,0x000032a8,0x00050086,0x00000006,
24230x00000000,0x000400fa,0x00001fc8,0x00001fc9, 26630x00002264,0x00002263,0x00000101,0x00050084,
24240x00001fcf,0x000200f8,0x00001fc9,0x000500bc, 26640x00000006,0x00002256,0x00000107,0x00002264,
24250x0000002f,0x00001fce,0x00001e5a,0x00001e6f, 26650x00050080,0x00000006,0x00002257,0x0000225d,
24260x000200f9,0x00001fcf,0x000200f8,0x00001fcf, 26660x00002256,0x00050084,0x00000006,0x00002227,
24270x000700f5,0x0000002f,0x00001fd0,0x00001fc8, 26670x00000150,0x00000b11,0x00050080,0x00000006,
24280x00001fc7,0x00001fce,0x00001fc9,0x000400a8, 26680x00002228,0x00002257,0x00002227,0x00050041,
24290x0000002f,0x00001fd1,0x00001fd0,0x000300f7, 26690x00000156,0x00002229,0x000000fc,0x00000154,
24300x00001f8d,0x00000000,0x000400fa,0x00001fd1, 26700x0004003d,0x00000007,0x0000222a,0x00002229,
24310x00001f8c,0x00001f8d,0x000200f8,0x00001f8c, 26710x00050051,0x00000027,0x0000222d,0x000032b3,
24320x000200f9,0x00001fb9,0x000200f8,0x00001f8d, 26720x00000000,0x0004007c,0x00000006,0x0000226a,
24330x00050081,0x0000004b,0x00001f90,0x00002b72, 26730x0000222d,0x00050051,0x00000006,0x00002283,
24340x00002b70,0x0005008e,0x0000004b,0x00001f91, 26740x0000222a,0x00000000,0x00050095,0x000000ab,
24350x00001f90,0x000001ea,0x00050095,0x000000a8, 26750x00002285,0x00002283,0x00002228,0x00050051,
24360x00001fe1,0x00001ea2,0x000000a3,0x00050051, 26760x00000006,0x00002286,0x00002285,0x00000001,
24370x00000006,0x00001fe2,0x00001fe1,0x00000001, 26770x00050051,0x00000006,0x00002287,0x00002285,
24380x00050051,0x00000006,0x00001fe3,0x00001fe1, 26780x00000000,0x00050051,0x00000006,0x0000228a,
24390x00000000,0x00050080,0x00000006,0x00001fe8, 26790x0000222a,0x00000001,0x00050080,0x00000006,
24400x00001ea9,0x00001fe2,0x00050050,0x00000007, 26800x0000228c,0x0000228a,0x00002286,0x00050050,
24410x00001fe9,0x00001fe3,0x00001fe8,0x0004007c, 26810x00000007,0x0000228d,0x00002287,0x0000228c,
24420x00000014,0x00001fd9,0x00001fe9,0x00060041, 26820x0004007c,0x00000014,0x0000227d,0x0000228d,
24430x000000d8,0x00001f96,0x00001fd9,0x000000d7, 26830x00060041,0x000000db,0x00002275,0x0000227d,
24440x000000d7,0x00050051,0x00000027,0x00001f98, 26840x000000da,0x000000da,0x0005003e,0x00002275,
24450x00001f91,0x00000000,0x0004007c,0x00000006, 26850x0000226a,0x00000002,0x00000004,0x00050080,
24460x00001fef,0x00001f98,0x000500c7,0x00000006, 26860x00000006,0x00002230,0x00002228,0x0000010a,
24470x00001ff1,0x00001fef,0x0000012d,0x000500ab, 26870x00050051,0x00000027,0x00002234,0x000032b3,
24480x0000002f,0x00001ff2,0x00001ff1,0x000000a3, 26880x00000001,0x0004007c,0x00000006,0x00002293,
24490x000300f7,0x00001ff9,0x00000000,0x000400fa, 26890x00002234,0x00050095,0x000000ab,0x000022ae,
24500x00001ff2,0x00001ff3,0x00001ff6,0x000200f8, 26900x00002283,0x00002230,0x00050051,0x00000006,
24510x00001ff3,0x000400c8,0x00000006,0x00001ff5, 26910x000022af,0x000022ae,0x00000001,0x00050051,
24520x00001fef,0x000200f9,0x00001ff9,0x000200f8, 26920x00000006,0x000022b0,0x000022ae,0x00000000,
24530x00001ff6,0x000500c5,0x00000006,0x00001ff8, 26930x00050080,0x00000006,0x000022b5,0x0000228a,
24540x00001fef,0x0000012d,0x000200f9,0x00001ff9, 26940x000022af,0x00050050,0x00000007,0x000022b6,
24550x000200f8,0x00001ff9,0x000700f5,0x00000006, 26950x000022b0,0x000022b5,0x0004007c,0x00000014,
24560x00002b0c,0x00001ff5,0x00001ff3,0x00001ff8, 26960x000022a6,0x000022b6,0x00060041,0x000000db,
24570x00001ff6,0x000700ed,0x00000006,0x00001f9a, 26970x0000229e,0x000022a6,0x000000da,0x000000da,
24580x00001f96,0x000000ad,0x000000a3,0x00002b0c, 26980x0005003e,0x0000229e,0x00002293,0x00000002,
24590x00060041,0x000000d8,0x00001f9c,0x00001fd9, 26990x00000004,0x00050080,0x00000006,0x00002237,
24600x000000d7,0x00000151,0x00050051,0x00000027, 27000x00002228,0x00000111,0x00050051,0x00000027,
24610x00001f9e,0x00001f91,0x00000001,0x0004007c, 27010x0000223b,0x000032b3,0x00000002,0x0004007c,
24620x00000006,0x00002000,0x00001f9e,0x000500c7, 27020x00000006,0x000022bc,0x0000223b,0x00050095,
24630x00000006,0x00002002,0x00002000,0x0000012d, 27030x000000ab,0x000022d7,0x00002283,0x00002237,
24640x000500ab,0x0000002f,0x00002003,0x00002002, 27040x00050051,0x00000006,0x000022d8,0x000022d7,
24650x000000a3,0x000300f7,0x0000200a,0x00000000, 27050x00000001,0x00050051,0x00000006,0x000022d9,
24660x000400fa,0x00002003,0x00002004,0x00002007, 27060x000022d7,0x00000000,0x00050080,0x00000006,
24670x000200f8,0x00002004,0x000400c8,0x00000006, 27070x000022de,0x0000228a,0x000022d8,0x00050050,
24680x00002006,0x00002000,0x000200f9,0x0000200a, 27080x00000007,0x000022df,0x000022d9,0x000022de,
24690x000200f8,0x00002007,0x000500c5,0x00000006, 27090x0004007c,0x00000014,0x000022cf,0x000022df,
24700x00002009,0x00002000,0x0000012d,0x000200f9, 27100x00060041,0x000000db,0x000022c7,0x000022cf,
24710x0000200a,0x000200f8,0x0000200a,0x000700f5, 27110x000000da,0x000000da,0x0005003e,0x000022c7,
24720x00000006,0x00002b0d,0x00002006,0x00002004, 27120x000022bc,0x00000002,0x00000004,0x00050080,
24730x00002009,0x00002007,0x000700ed,0x00000006, 27130x00000006,0x0000223e,0x00002228,0x00000118,
24740x00001fa0,0x00001f9c,0x000000ad,0x000000a3, 27140x00050051,0x00000027,0x00002242,0x000032b1,
24750x00002b0d,0x00060041,0x000000d8,0x00001fa2, 27150x00000000,0x0004007c,0x00000006,0x000022e5,
24760x00001fd9,0x000000d7,0x00000202,0x00050051, 27160x00002242,0x00050095,0x000000ab,0x00002300,
24770x00000027,0x00001fa4,0x00001f91,0x00000002, 27170x00002283,0x0000223e,0x00050051,0x00000006,
24780x0004007c,0x00000006,0x00002011,0x00001fa4, 27180x00002301,0x00002300,0x00000001,0x00050051,
24790x000500c7,0x00000006,0x00002013,0x00002011, 27190x00000006,0x00002302,0x00002300,0x00000000,
24800x0000012d,0x000500ab,0x0000002f,0x00002014, 27200x00050080,0x00000006,0x00002307,0x0000228a,
24810x00002013,0x000000a3,0x000300f7,0x0000201b, 27210x00002301,0x00050050,0x00000007,0x00002308,
24820x00000000,0x000400fa,0x00002014,0x00002015, 27220x00002302,0x00002307,0x0004007c,0x00000014,
24830x00002018,0x000200f8,0x00002015,0x000400c8, 27230x000022f8,0x00002308,0x00060041,0x000000db,
24840x00000006,0x00002017,0x00002011,0x000200f9, 27240x000022f0,0x000022f8,0x000000da,0x000000da,
24850x0000201b,0x000200f8,0x00002018,0x000500c5, 27250x0005003e,0x000022f0,0x000022e5,0x00000002,
24860x00000006,0x0000201a,0x00002011,0x0000012d, 27260x00000004,0x00050080,0x00000006,0x00002245,
24870x000200f9,0x0000201b,0x000200f8,0x0000201b, 27270x00002228,0x0000011f,0x00050051,0x00000027,
24880x000700f5,0x00000006,0x00002b0e,0x00002017, 27280x00002249,0x000032b1,0x00000001,0x0004007c,
24890x00002015,0x0000201a,0x00002018,0x000700ed, 27290x00000006,0x0000230e,0x00002249,0x00050095,
24900x00000006,0x00001fa6,0x00001fa2,0x000000ad, 27300x000000ab,0x00002329,0x00002283,0x00002245,
24910x000000a3,0x00002b0e,0x00060041,0x000000d8, 27310x00050051,0x00000006,0x0000232a,0x00002329,
24920x00001fa8,0x00001fd9,0x000000d7,0x0000020a, 27320x00000001,0x00050051,0x00000006,0x0000232b,
24930x000300f7,0x0000202c,0x00000000,0x000400fa, 27330x00002329,0x00000000,0x00050080,0x00000006,
24940x00001ff2,0x00002026,0x00002029,0x000200f8, 27340x00002330,0x0000228a,0x0000232a,0x00050050,
24950x00002026,0x000400c8,0x00000006,0x00002028, 27350x00000007,0x00002331,0x0000232b,0x00002330,
24960x00001fef,0x000200f9,0x0000202c,0x000200f8, 27360x0004007c,0x00000014,0x00002321,0x00002331,
24970x00002029,0x000500c5,0x00000006,0x0000202b, 27370x00060041,0x000000db,0x00002319,0x00002321,
24980x00001fef,0x0000012d,0x000200f9,0x0000202c, 27380x000000da,0x000000da,0x0005003e,0x00002319,
24990x000200f8,0x0000202c,0x000700f5,0x00000006, 27390x0000230e,0x00000002,0x00000004,0x00050080,
25000x00002b0f,0x00002028,0x00002026,0x0000202b, 27400x00000006,0x0000224c,0x00002228,0x00000189,
25010x00002029,0x000700ef,0x00000006,0x00001fac, 27410x00050051,0x00000027,0x00002250,0x000032b1,
25020x00001fa8,0x000000ad,0x000000a3,0x00002b0f, 27420x00000002,0x0004007c,0x00000006,0x00002337,
25030x00060041,0x000000d8,0x00001fae,0x00001fd9, 27430x00002250,0x00050095,0x000000ab,0x00002352,
25040x000000d7,0x00000212,0x000300f7,0x0000203d, 27440x00002283,0x0000224c,0x00050051,0x00000006,
25050x00000000,0x000400fa,0x00002003,0x00002037, 27450x00002353,0x00002352,0x00000001,0x00050051,
25060x0000203a,0x000200f8,0x00002037,0x000400c8, 27460x00000006,0x00002354,0x00002352,0x00000000,
25070x00000006,0x00002039,0x00002000,0x000200f9, 27470x00050080,0x00000006,0x00002359,0x0000228a,
25080x0000203d,0x000200f8,0x0000203a,0x000500c5, 27480x00002353,0x00050050,0x00000007,0x0000235a,
25090x00000006,0x0000203c,0x00002000,0x0000012d, 27490x00002354,0x00002359,0x0004007c,0x00000014,
25100x000200f9,0x0000203d,0x000200f8,0x0000203d, 27500x0000234a,0x0000235a,0x00060041,0x000000db,
25110x000700f5,0x00000006,0x00002b10,0x00002039, 27510x00002342,0x0000234a,0x000000da,0x000000da,
25120x00002037,0x0000203c,0x0000203a,0x000700ef, 27520x0005003e,0x00002342,0x00002337,0x00000002,
25130x00000006,0x00001fb2,0x00001fae,0x000000ad, 27530x00000004,0x000300f7,0x0000239a,0x00000000,
25140x000000a3,0x00002b10,0x00060041,0x000000d8, 27540x000300fb,0x000000a6,0x00002369,0x000200f8,
25150x00001fb4,0x00001fd9,0x000000d7,0x0000021a, 27550x00002369,0x000500bc,0x0000002f,0x000023a1,
25160x000300f7,0x0000204e,0x00000000,0x000400fa, 27560x0000222d,0x00002242,0x000300f7,0x000023a8,
25170x00002014,0x00002048,0x0000204b,0x000200f8, 27570x00000000,0x000400fa,0x000023a1,0x000023a2,
25180x00002048,0x000400c8,0x00000006,0x0000204a, 27580x000023a8,0x000200f8,0x000023a2,0x000500bc,
25190x00002011,0x000200f9,0x0000204e,0x000200f8, 27590x0000002f,0x000023a7,0x00002234,0x00002249,
25200x0000204b,0x000500c5,0x00000006,0x0000204d, 27600x000200f9,0x000023a8,0x000200f8,0x000023a8,
25210x00002011,0x0000012d,0x000200f9,0x0000204e, 27610x000700f5,0x0000002f,0x000023a9,0x000023a1,
25220x000200f8,0x0000204e,0x000700f5,0x00000006, 27620x00002369,0x000023a7,0x000023a2,0x000300f7,
25230x00002b11,0x0000204a,0x00002048,0x0000204d, 27630x000023b0,0x00000000,0x000400fa,0x000023a9,
25240x0000204b,0x000700ef,0x00000006,0x00001fb8, 27640x000023aa,0x000023b0,0x000200f8,0x000023aa,
25250x00001fb4,0x000000ad,0x000000a3,0x00002b11, 27650x000500bc,0x0000002f,0x000023af,0x0000223b,
25260x000200f9,0x00001fb9,0x000200f8,0x00001fb9, 27660x00002250,0x000200f9,0x000023b0,0x000200f8,
25270x000200f9,0x00000a56,0x000200f8,0x00000a5a, 27670x000023b0,0x000700f5,0x0000002f,0x000023b1,
25280x000500aa,0x0000002f,0x00000a5d,0x000009eb, 27680x000023a9,0x000023a8,0x000023af,0x000023aa,
25290x000002b4,0x000300f7,0x00000a5f,0x00000000, 27690x000400a8,0x0000002f,0x000023b2,0x000023b1,
25300x000400fa,0x00000a5d,0x00000a5e,0x00000a63, 27700x000300f7,0x0000236e,0x00000000,0x000400fa,
25310x000200f8,0x00000a5e,0x00050041,0x000000fb, 27710x000023b2,0x0000236d,0x0000236e,0x000200f8,
25320x00002103,0x000000f9,0x000000fa,0x0004003d, 27720x0000236d,0x000200f9,0x0000239a,0x000200f8,
25330x00000006,0x00002104,0x00002103,0x00050084, 27730x0000236e,0x00050081,0x0000004b,0x00002371,
25340x00000006,0x00002105,0x0000011c,0x00002104, 27740x000032b3,0x000032b1,0x0005008e,0x0000004b,
25350x00050080,0x00000006,0x00002106,0x00000104, 27750x00002372,0x00002371,0x000001ed,0x00050095,
25360x00002105,0x00050080,0x00000006,0x0000210c, 27760x000000ab,0x000023c2,0x00002283,0x000000a6,
25370x00002104,0x00002b67,0x00050086,0x00000006, 27770x00050051,0x00000006,0x000023c3,0x000023c2,
25380x0000210d,0x0000210c,0x000000fe,0x00050084, 27780x00000001,0x00050051,0x00000006,0x000023c4,
25390x00000006,0x000020ff,0x00000104,0x0000210d, 27790x000023c2,0x00000000,0x00050080,0x00000006,
25400x00050080,0x00000006,0x00002100,0x00002106, 27800x000023c9,0x0000228a,0x000023c3,0x00050050,
25410x000020ff,0x00050084,0x00000006,0x000020d4, 27810x00000007,0x000023ca,0x000023c4,0x000023c9,
25420x0000014d,0x000009e9,0x00050080,0x00000006, 27820x0004007c,0x00000014,0x000023ba,0x000023ca,
25430x000020d5,0x00002100,0x000020d4,0x00050041, 27830x00060041,0x000000db,0x00002377,0x000023ba,
25440x00000153,0x000020d6,0x000000f9,0x00000151, 27840x000000da,0x000000da,0x00050051,0x00000027,
25450x0004003d,0x00000007,0x000020d7,0x000020d6, 27850x00002379,0x00002372,0x00000000,0x0004007c,
25460x00050051,0x00000006,0x00002124,0x000020d7, 27860x00000006,0x000023d0,0x00002379,0x000500c7,
25470x00000000,0x00050095,0x000000a8,0x00002126, 27870x00000006,0x000023d2,0x000023d0,0x00000130,
25480x00002124,0x000020d5,0x00050051,0x00000006, 27880x000500ab,0x0000002f,0x000023d3,0x000023d2,
25490x00002127,0x00002126,0x00000001,0x00050051, 27890x000000a6,0x000300f7,0x000023da,0x00000000,
25500x00000006,0x00002128,0x00002126,0x00000000, 27900x000400fa,0x000023d3,0x000023d4,0x000023d7,
25510x00050051,0x00000006,0x0000212b,0x000020d7, 27910x000200f8,0x000023d4,0x000400c8,0x00000006,
25520x00000001,0x00050080,0x00000006,0x0000212d, 27920x000023d6,0x000023d0,0x000200f9,0x000023da,
25530x0000212b,0x00002127,0x00050050,0x00000007, 27930x000200f8,0x000023d7,0x000500c5,0x00000006,
25540x0000212e,0x00002128,0x0000212d,0x0004007c, 27940x000023d9,0x000023d0,0x00000130,0x000200f9,
25550x00000014,0x0000211e,0x0000212e,0x00060041, 27950x000023da,0x000200f8,0x000023da,0x000700f5,
25560x000000d8,0x00002115,0x0000211e,0x000000d7, 27960x00000006,0x00003228,0x000023d6,0x000023d4,
25570x000000d7,0x0006003d,0x00000006,0x00002116, 27970x000023d9,0x000023d7,0x000700ed,0x00000006,
25580x00002115,0x00000002,0x00000004,0x0004007c, 27980x0000237b,0x00002377,0x000000b0,0x000000a6,
25590x00000027,0x000020da,0x00002116,0x00050080, 27990x00003228,0x00060041,0x000000db,0x0000237d,
25600x00000006,0x000020dc,0x000020d5,0x00000107, 28000x000023ba,0x000000da,0x00000154,0x00050051,
25610x00050095,0x000000a8,0x00002147,0x00002124, 28010x00000027,0x0000237f,0x00002372,0x00000001,
25620x000020dc,0x00050051,0x00000006,0x00002148, 28020x0004007c,0x00000006,0x000023e1,0x0000237f,
25630x00002147,0x00000001,0x00050051,0x00000006, 28030x000500c7,0x00000006,0x000023e3,0x000023e1,
25640x00002149,0x00002147,0x00000000,0x00050080, 28040x00000130,0x000500ab,0x0000002f,0x000023e4,
25650x00000006,0x0000214e,0x0000212b,0x00002148, 28050x000023e3,0x000000a6,0x000300f7,0x000023eb,
25660x00050050,0x00000007,0x0000214f,0x00002149, 28060x00000000,0x000400fa,0x000023e4,0x000023e5,
25670x0000214e,0x0004007c,0x00000014,0x0000213f, 28070x000023e8,0x000200f8,0x000023e5,0x000400c8,
25680x0000214f,0x00060041,0x000000d8,0x00002136, 28080x00000006,0x000023e7,0x000023e1,0x000200f9,
25690x0000213f,0x000000d7,0x000000d7,0x0006003d, 28090x000023eb,0x000200f8,0x000023e8,0x000500c5,
25700x00000006,0x00002137,0x00002136,0x00000002, 28100x00000006,0x000023ea,0x000023e1,0x00000130,
25710x00000004,0x0004007c,0x00000027,0x000020e0, 28110x000200f9,0x000023eb,0x000200f8,0x000023eb,
25720x00002137,0x00050080,0x00000006,0x000020e2, 28120x000700f5,0x00000006,0x00003229,0x000023e7,
25730x000020d5,0x0000010e,0x00050095,0x000000a8, 28130x000023e5,0x000023ea,0x000023e8,0x000700ed,
25740x00002168,0x00002124,0x000020e2,0x00050051, 28140x00000006,0x00002381,0x0000237d,0x000000b0,
25750x00000006,0x00002169,0x00002168,0x00000001, 28150x000000a6,0x00003229,0x00060041,0x000000db,
25760x00050051,0x00000006,0x0000216a,0x00002168, 28160x00002383,0x000023ba,0x000000da,0x00000205,
25770x00000000,0x00050080,0x00000006,0x0000216f, 28170x00050051,0x00000027,0x00002385,0x00002372,
25780x0000212b,0x00002169,0x00050050,0x00000007, 28180x00000002,0x0004007c,0x00000006,0x000023f2,
25790x00002170,0x0000216a,0x0000216f,0x0004007c, 28190x00002385,0x000500c7,0x00000006,0x000023f4,
25800x00000014,0x00002160,0x00002170,0x00060041, 28200x000023f2,0x00000130,0x000500ab,0x0000002f,
25810x000000d8,0x00002157,0x00002160,0x000000d7, 28210x000023f5,0x000023f4,0x000000a6,0x000300f7,
25820x000000d7,0x0006003d,0x00000006,0x00002158, 28220x000023fc,0x00000000,0x000400fa,0x000023f5,
25830x00002157,0x00000002,0x00000004,0x0004007c, 28230x000023f6,0x000023f9,0x000200f8,0x000023f6,
25840x00000027,0x000020e6,0x00002158,0x00060050, 28240x000400c8,0x00000006,0x000023f8,0x000023f2,
25850x0000004b,0x000020e7,0x000020da,0x000020e0, 28250x000200f9,0x000023fc,0x000200f8,0x000023f9,
25860x000020e6,0x00050080,0x00000006,0x000020e9, 28260x000500c5,0x00000006,0x000023fb,0x000023f2,
25870x000020d5,0x00000115,0x00050095,0x000000a8, 28270x00000130,0x000200f9,0x000023fc,0x000200f8,
25880x00002189,0x00002124,0x000020e9,0x00050051, 28280x000023fc,0x000700f5,0x00000006,0x0000322a,
25890x00000006,0x0000218a,0x00002189,0x00000001, 28290x000023f8,0x000023f6,0x000023fb,0x000023f9,
25900x00050051,0x00000006,0x0000218b,0x00002189, 28300x000700ed,0x00000006,0x00002387,0x00002383,
25910x00000000,0x00050080,0x00000006,0x00002190, 28310x000000b0,0x000000a6,0x0000322a,0x00060041,
25920x0000212b,0x0000218a,0x00050050,0x00000007, 28320x000000db,0x00002389,0x000023ba,0x000000da,
25930x00002191,0x0000218b,0x00002190,0x0004007c, 28330x0000020d,0x000300f7,0x0000240d,0x00000000,
25940x00000014,0x00002181,0x00002191,0x00060041, 28340x000400fa,0x000023d3,0x00002407,0x0000240a,
25950x000000d8,0x00002178,0x00002181,0x000000d7, 28350x000200f8,0x00002407,0x000400c8,0x00000006,
25960x000000d7,0x0006003d,0x00000006,0x00002179, 28360x00002409,0x000023d0,0x000200f9,0x0000240d,
25970x00002178,0x00000002,0x00000004,0x0004007c, 28370x000200f8,0x0000240a,0x000500c5,0x00000006,
25980x00000027,0x000020ed,0x00002179,0x00050080, 28380x0000240c,0x000023d0,0x00000130,0x000200f9,
25990x00000006,0x000020ef,0x000020d5,0x0000011c, 28390x0000240d,0x000200f8,0x0000240d,0x000700f5,
26000x00050095,0x000000a8,0x000021aa,0x00002124, 28400x00000006,0x0000322b,0x00002409,0x00002407,
26010x000020ef,0x00050051,0x00000006,0x000021ab, 28410x0000240c,0x0000240a,0x000700ef,0x00000006,
26020x000021aa,0x00000001,0x00050051,0x00000006, 28420x0000238d,0x00002389,0x000000b0,0x000000a6,
26030x000021ac,0x000021aa,0x00000000,0x00050080, 28430x0000322b,0x00060041,0x000000db,0x0000238f,
26040x00000006,0x000021b1,0x0000212b,0x000021ab, 28440x000023ba,0x000000da,0x00000215,0x000300f7,
26050x00050050,0x00000007,0x000021b2,0x000021ac, 28450x0000241e,0x00000000,0x000400fa,0x000023e4,
26060x000021b1,0x0004007c,0x00000014,0x000021a2, 28460x00002418,0x0000241b,0x000200f8,0x00002418,
26070x000021b2,0x00060041,0x000000d8,0x00002199, 28470x000400c8,0x00000006,0x0000241a,0x000023e1,
26080x000021a2,0x000000d7,0x000000d7,0x0006003d, 28480x000200f9,0x0000241e,0x000200f8,0x0000241b,
26090x00000006,0x0000219a,0x00002199,0x00000002, 28490x000500c5,0x00000006,0x0000241d,0x000023e1,
26100x00000004,0x0004007c,0x00000027,0x000020f3, 28500x00000130,0x000200f9,0x0000241e,0x000200f8,
26110x0000219a,0x00050080,0x00000006,0x000020f5, 28510x0000241e,0x000700f5,0x00000006,0x0000322c,
26120x000020d5,0x00000186,0x00050095,0x000000a8, 28520x0000241a,0x00002418,0x0000241d,0x0000241b,
26130x000021cb,0x00002124,0x000020f5,0x00050051, 28530x000700ef,0x00000006,0x00002393,0x0000238f,
26140x00000006,0x000021cc,0x000021cb,0x00000001, 28540x000000b0,0x000000a6,0x0000322c,0x00060041,
26150x00050051,0x00000006,0x000021cd,0x000021cb, 28550x000000db,0x00002395,0x000023ba,0x000000da,
26160x00000000,0x00050080,0x00000006,0x000021d2, 28560x0000021d,0x000300f7,0x0000242f,0x00000000,
26170x0000212b,0x000021cc,0x00050050,0x00000007, 28570x000400fa,0x000023f5,0x00002429,0x0000242c,
26180x000021d3,0x000021cd,0x000021d2,0x0004007c, 28580x000200f8,0x00002429,0x000400c8,0x00000006,
26190x00000014,0x000021c3,0x000021d3,0x00060041, 28590x0000242b,0x000023f2,0x000200f9,0x0000242f,
26200x000000d8,0x000021ba,0x000021c3,0x000000d7, 28600x000200f8,0x0000242c,0x000500c5,0x00000006,
26210x000000d7,0x0006003d,0x00000006,0x000021bb, 28610x0000242e,0x000023f2,0x00000130,0x000200f9,
26220x000021ba,0x00000002,0x00000004,0x0004007c, 28620x0000242f,0x000200f8,0x0000242f,0x000700f5,
26230x00000027,0x000020f9,0x000021bb,0x00060050, 28630x00000006,0x0000322d,0x0000242b,0x00002429,
26240x0000004b,0x000020fa,0x000020ed,0x000020f3, 28640x0000242e,0x0000242c,0x000700ef,0x00000006,
26250x000020f9,0x000500bc,0x0000002f,0x000021da, 28650x00002399,0x00002395,0x000000b0,0x000000a6,
26260x000020da,0x000020ed,0x000300f7,0x000021e1, 28660x0000322d,0x000200f9,0x0000239a,0x000200f8,
26270x00000000,0x000400fa,0x000021da,0x000021db, 28670x0000239a,0x000200f9,0x00000bdb,0x000200f8,
26280x000021e1,0x000200f8,0x000021db,0x000500bc, 28680x00000bdf,0x000500aa,0x0000002f,0x00000be2,
26290x0000002f,0x000021e0,0x000020e0,0x000020f3, 28690x00000b13,0x000002b7,0x000300f7,0x00000be4,
26300x000200f9,0x000021e1,0x000200f8,0x000021e1, 28700x00000000,0x000400fa,0x00000be2,0x00000be3,
26310x000700f5,0x0000002f,0x000021e2,0x000021da, 28710x00000be8,0x000200f8,0x00000be3,0x00050041,
26320x00000a5e,0x000021e0,0x000021db,0x000300f7, 28720x000000fe,0x000024e4,0x000000fc,0x000000fd,
26330x000021e9,0x00000000,0x000400fa,0x000021e2, 28730x0004003d,0x00000006,0x000024e5,0x000024e4,
26340x000021e3,0x000021e9,0x000200f8,0x000021e3, 28740x00050084,0x00000006,0x000024e6,0x0000011f,
26350x000500bc,0x0000002f,0x000021e8,0x000020e6, 28750x000024e5,0x00050080,0x00000006,0x000024e7,
26360x000020f9,0x000200f9,0x000021e9,0x000200f8, 28760x00000107,0x000024e6,0x00050080,0x00000006,
26370x000021e9,0x000700f5,0x0000002f,0x000021ea, 28770x000024ed,0x000024e5,0x000032a8,0x00050086,
26380x000021e2,0x000021e1,0x000021e8,0x000021e3, 28780x00000006,0x000024ee,0x000024ed,0x00000101,
26390x000300f7,0x000020b3,0x00000000,0x000400fa, 28790x00050084,0x00000006,0x000024e0,0x00000107,
26400x000021ea,0x00002077,0x000020b3,0x000200f8, 28800x000024ee,0x00050080,0x00000006,0x000024e1,
26410x00002077,0x00050095,0x000000a8,0x000021fb, 28810x000024e7,0x000024e0,0x00050084,0x00000006,
26420x00002124,0x000000a3,0x00050051,0x00000006, 28820x000024b5,0x00000150,0x00000b11,0x00050080,
26430x000021fc,0x000021fb,0x00000001,0x00050051, 28830x00000006,0x000024b6,0x000024e1,0x000024b5,
26440x00000006,0x000021fd,0x000021fb,0x00000000, 28840x00050041,0x00000156,0x000024b7,0x000000fc,
26450x00050080,0x00000006,0x00002202,0x0000212b, 28850x00000154,0x0004003d,0x00000007,0x000024b8,
26460x000021fc,0x00050050,0x00000007,0x00002203, 28860x000024b7,0x00050051,0x00000006,0x00002505,
26470x000021fd,0x00002202,0x0004007c,0x00000014, 28870x000024b8,0x00000000,0x00050095,0x000000ab,
26480x000021f3,0x00002203,0x00060041,0x000000d8, 28880x00002507,0x00002505,0x000024b6,0x00050051,
26490x0000207c,0x000021f3,0x000000d7,0x000000d7, 28890x00000006,0x00002508,0x00002507,0x00000001,
26500x0006003d,0x00000006,0x0000207d,0x0000207c, 28900x00050051,0x00000006,0x00002509,0x00002507,
28910x00000000,0x00050051,0x00000006,0x0000250c,
28920x000024b8,0x00000001,0x00050080,0x00000006,
28930x0000250e,0x0000250c,0x00002508,0x00050050,
28940x00000007,0x0000250f,0x00002509,0x0000250e,
28950x0004007c,0x00000014,0x000024ff,0x0000250f,
28960x00060041,0x000000db,0x000024f6,0x000024ff,
28970x000000da,0x000000da,0x0006003d,0x00000006,
28980x000024f7,0x000024f6,0x00000002,0x00000004,
28990x0004007c,0x00000027,0x000024bb,0x000024f7,
29000x00050080,0x00000006,0x000024bd,0x000024b6,
29010x0000010a,0x00050095,0x000000ab,0x00002528,
29020x00002505,0x000024bd,0x00050051,0x00000006,
29030x00002529,0x00002528,0x00000001,0x00050051,
29040x00000006,0x0000252a,0x00002528,0x00000000,
29050x00050080,0x00000006,0x0000252f,0x0000250c,
29060x00002529,0x00050050,0x00000007,0x00002530,
29070x0000252a,0x0000252f,0x0004007c,0x00000014,
29080x00002520,0x00002530,0x00060041,0x000000db,
29090x00002517,0x00002520,0x000000da,0x000000da,
29100x0006003d,0x00000006,0x00002518,0x00002517,
29110x00000002,0x00000004,0x0004007c,0x00000027,
29120x000024c1,0x00002518,0x00050080,0x00000006,
29130x000024c3,0x000024b6,0x00000111,0x00050095,
29140x000000ab,0x00002549,0x00002505,0x000024c3,
29150x00050051,0x00000006,0x0000254a,0x00002549,
29160x00000001,0x00050051,0x00000006,0x0000254b,
29170x00002549,0x00000000,0x00050080,0x00000006,
29180x00002550,0x0000250c,0x0000254a,0x00050050,
29190x00000007,0x00002551,0x0000254b,0x00002550,
29200x0004007c,0x00000014,0x00002541,0x00002551,
29210x00060041,0x000000db,0x00002538,0x00002541,
29220x000000da,0x000000da,0x0006003d,0x00000006,
29230x00002539,0x00002538,0x00000002,0x00000004,
29240x0004007c,0x00000027,0x000024c7,0x00002539,
29250x00060050,0x0000004b,0x000024c8,0x000024bb,
29260x000024c1,0x000024c7,0x00050080,0x00000006,
29270x000024ca,0x000024b6,0x00000118,0x00050095,
29280x000000ab,0x0000256a,0x00002505,0x000024ca,
29290x00050051,0x00000006,0x0000256b,0x0000256a,
29300x00000001,0x00050051,0x00000006,0x0000256c,
29310x0000256a,0x00000000,0x00050080,0x00000006,
29320x00002571,0x0000250c,0x0000256b,0x00050050,
29330x00000007,0x00002572,0x0000256c,0x00002571,
29340x0004007c,0x00000014,0x00002562,0x00002572,
29350x00060041,0x000000db,0x00002559,0x00002562,
29360x000000da,0x000000da,0x0006003d,0x00000006,
29370x0000255a,0x00002559,0x00000002,0x00000004,
29380x0004007c,0x00000027,0x000024ce,0x0000255a,
29390x00050080,0x00000006,0x000024d0,0x000024b6,
29400x0000011f,0x00050095,0x000000ab,0x0000258b,
29410x00002505,0x000024d0,0x00050051,0x00000006,
29420x0000258c,0x0000258b,0x00000001,0x00050051,
29430x00000006,0x0000258d,0x0000258b,0x00000000,
29440x00050080,0x00000006,0x00002592,0x0000250c,
29450x0000258c,0x00050050,0x00000007,0x00002593,
29460x0000258d,0x00002592,0x0004007c,0x00000014,
29470x00002583,0x00002593,0x00060041,0x000000db,
29480x0000257a,0x00002583,0x000000da,0x000000da,
29490x0006003d,0x00000006,0x0000257b,0x0000257a,
29500x00000002,0x00000004,0x0004007c,0x00000027,
29510x000024d4,0x0000257b,0x00050080,0x00000006,
29520x000024d6,0x000024b6,0x00000189,0x00050095,
29530x000000ab,0x000025ac,0x00002505,0x000024d6,
29540x00050051,0x00000006,0x000025ad,0x000025ac,
29550x00000001,0x00050051,0x00000006,0x000025ae,
29560x000025ac,0x00000000,0x00050080,0x00000006,
29570x000025b3,0x0000250c,0x000025ad,0x00050050,
29580x00000007,0x000025b4,0x000025ae,0x000025b3,
29590x0004007c,0x00000014,0x000025a4,0x000025b4,
29600x00060041,0x000000db,0x0000259b,0x000025a4,
29610x000000da,0x000000da,0x0006003d,0x00000006,
29620x0000259c,0x0000259b,0x00000002,0x00000004,
29630x0004007c,0x00000027,0x000024da,0x0000259c,
29640x00060050,0x0000004b,0x000024db,0x000024ce,
29650x000024d4,0x000024da,0x000500bc,0x0000002f,
29660x000025bb,0x000024bb,0x000024ce,0x000300f7,
29670x000025c2,0x00000000,0x000400fa,0x000025bb,
29680x000025bc,0x000025c2,0x000200f8,0x000025bc,
29690x000500bc,0x0000002f,0x000025c1,0x000024c1,
29700x000024d4,0x000200f9,0x000025c2,0x000200f8,
29710x000025c2,0x000700f5,0x0000002f,0x000025c3,
29720x000025bb,0x00000be3,0x000025c1,0x000025bc,
29730x000300f7,0x000025ca,0x00000000,0x000400fa,
29740x000025c3,0x000025c4,0x000025ca,0x000200f8,
29750x000025c4,0x000500bc,0x0000002f,0x000025c9,
29760x000024c7,0x000024da,0x000200f9,0x000025ca,
29770x000200f8,0x000025ca,0x000700f5,0x0000002f,
29780x000025cb,0x000025c3,0x000025c2,0x000025c9,
29790x000025c4,0x000300f7,0x00002494,0x00000000,
29800x000400fa,0x000025cb,0x00002458,0x00002494,
29810x000200f8,0x00002458,0x00050095,0x000000ab,
29820x000025dc,0x00002505,0x000000a6,0x00050051,
29830x00000006,0x000025dd,0x000025dc,0x00000001,
29840x00050051,0x00000006,0x000025de,0x000025dc,
29850x00000000,0x00050080,0x00000006,0x000025e3,
29860x0000250c,0x000025dd,0x00050050,0x00000007,
29870x000025e4,0x000025de,0x000025e3,0x0004007c,
29880x00000014,0x000025d4,0x000025e4,0x00060041,
29890x000000db,0x0000245d,0x000025d4,0x000000da,
29900x000000da,0x0006003d,0x00000006,0x0000245e,
29910x0000245d,0x00000002,0x00000004,0x000500c7,
29920x00000006,0x000025e9,0x0000245e,0x00000130,
29930x000500ab,0x0000002f,0x000025ea,0x000025e9,
29940x000000a6,0x000300f7,0x000025f1,0x00000000,
29950x000400fa,0x000025ea,0x000025eb,0x000025ee,
29960x000200f8,0x000025eb,0x000500c7,0x00000006,
29970x000025ed,0x0000245e,0x00000145,0x000200f9,
29980x000025f1,0x000200f8,0x000025ee,0x000400c8,
29990x00000006,0x000025f0,0x0000245e,0x000200f9,
30000x000025f1,0x000200f8,0x000025f1,0x000700f5,
30010x00000006,0x000031e7,0x000025ed,0x000025eb,
30020x000025f0,0x000025ee,0x0004007c,0x00000027,
30030x000025f3,0x000031e7,0x00060041,0x000000db,
30040x00002461,0x000025d4,0x000000da,0x00000154,
30050x0006003d,0x00000006,0x00002462,0x00002461,
30060x00000002,0x00000004,0x000500c7,0x00000006,
30070x000025f8,0x00002462,0x00000130,0x000500ab,
30080x0000002f,0x000025f9,0x000025f8,0x000000a6,
30090x000300f7,0x00002600,0x00000000,0x000400fa,
30100x000025f9,0x000025fa,0x000025fd,0x000200f8,
30110x000025fa,0x000500c7,0x00000006,0x000025fc,
30120x00002462,0x00000145,0x000200f9,0x00002600,
30130x000200f8,0x000025fd,0x000400c8,0x00000006,
30140x000025ff,0x00002462,0x000200f9,0x00002600,
30150x000200f8,0x00002600,0x000700f5,0x00000006,
30160x000031e8,0x000025fc,0x000025fa,0x000025ff,
30170x000025fd,0x0004007c,0x00000027,0x00002602,
30180x000031e8,0x00060041,0x000000db,0x00002465,
30190x000025d4,0x000000da,0x00000205,0x0006003d,
30200x00000006,0x00002466,0x00002465,0x00000002,
30210x00000004,0x000500c7,0x00000006,0x00002607,
30220x00002466,0x00000130,0x000500ab,0x0000002f,
30230x00002608,0x00002607,0x000000a6,0x000300f7,
30240x0000260f,0x00000000,0x000400fa,0x00002608,
30250x00002609,0x0000260c,0x000200f8,0x00002609,
30260x000500c7,0x00000006,0x0000260b,0x00002466,
30270x00000145,0x000200f9,0x0000260f,0x000200f8,
30280x0000260c,0x000400c8,0x00000006,0x0000260e,
30290x00002466,0x000200f9,0x0000260f,0x000200f8,
30300x0000260f,0x000700f5,0x00000006,0x000031e9,
30310x0000260b,0x00002609,0x0000260e,0x0000260c,
30320x0004007c,0x00000027,0x00002611,0x000031e9,
30330x00060050,0x0000004b,0x00002468,0x000025f3,
30340x00002602,0x00002611,0x00060041,0x000000db,
30350x0000246a,0x000025d4,0x000000da,0x0000020d,
30360x0006003d,0x00000006,0x0000246b,0x0000246a,
26510x00000002,0x00000004,0x000500c7,0x00000006, 30370x00000002,0x00000004,0x000500c7,0x00000006,
26520x00002208,0x0000207d,0x0000012d,0x000500ab, 30380x00002616,0x0000246b,0x00000130,0x000500ab,
26530x0000002f,0x00002209,0x00002208,0x000000a3, 30390x0000002f,0x00002617,0x00002616,0x000000a6,
26540x000300f7,0x00002210,0x00000000,0x000400fa, 30400x000300f7,0x0000261e,0x00000000,0x000400fa,
26550x00002209,0x0000220a,0x0000220d,0x000200f8, 30410x00002617,0x00002618,0x0000261b,0x000200f8,
26560x0000220a,0x000500c7,0x00000006,0x0000220c, 30420x00002618,0x000500c7,0x00000006,0x0000261a,
26570x0000207d,0x00000142,0x000200f9,0x00002210, 30430x0000246b,0x00000145,0x000200f9,0x0000261e,
26580x000200f8,0x0000220d,0x000400c8,0x00000006, 30440x000200f8,0x0000261b,0x000400c8,0x00000006,
26590x0000220f,0x0000207d,0x000200f9,0x00002210, 30450x0000261d,0x0000246b,0x000200f9,0x0000261e,
26600x000200f8,0x00002210,0x000700f5,0x00000006, 30460x000200f8,0x0000261e,0x000700f5,0x00000006,
26610x00002acb,0x0000220c,0x0000220a,0x0000220f, 30470x000031ea,0x0000261a,0x00002618,0x0000261d,
26620x0000220d,0x0004007c,0x00000027,0x00002212, 30480x0000261b,0x0004007c,0x00000027,0x00002620,
26630x00002acb,0x00060041,0x000000d8,0x00002080, 30490x000031ea,0x00060041,0x000000db,0x0000246e,
26640x000021f3,0x000000d7,0x00000151,0x0006003d, 30500x000025d4,0x000000da,0x00000215,0x0006003d,
26650x00000006,0x00002081,0x00002080,0x00000002, 30510x00000006,0x0000246f,0x0000246e,0x00000002,
26660x00000004,0x000500c7,0x00000006,0x00002217, 30520x00000004,0x000500c7,0x00000006,0x00002625,
26670x00002081,0x0000012d,0x000500ab,0x0000002f, 30530x0000246f,0x00000130,0x000500ab,0x0000002f,
26680x00002218,0x00002217,0x000000a3,0x000300f7, 30540x00002626,0x00002625,0x000000a6,0x000300f7,
26690x0000221f,0x00000000,0x000400fa,0x00002218, 30550x0000262d,0x00000000,0x000400fa,0x00002626,
26700x00002219,0x0000221c,0x000200f8,0x00002219, 30560x00002627,0x0000262a,0x000200f8,0x00002627,
26710x000500c7,0x00000006,0x0000221b,0x00002081, 30570x000500c7,0x00000006,0x00002629,0x0000246f,
26720x00000142,0x000200f9,0x0000221f,0x000200f8, 30580x00000145,0x000200f9,0x0000262d,0x000200f8,
26730x0000221c,0x000400c8,0x00000006,0x0000221e, 30590x0000262a,0x000400c8,0x00000006,0x0000262c,
26740x00002081,0x000200f9,0x0000221f,0x000200f8, 30600x0000246f,0x000200f9,0x0000262d,0x000200f8,
26750x0000221f,0x000700f5,0x00000006,0x00002acc, 30610x0000262d,0x000700f5,0x00000006,0x000031eb,
26760x0000221b,0x00002219,0x0000221e,0x0000221c, 30620x00002629,0x00002627,0x0000262c,0x0000262a,
26770x0004007c,0x00000027,0x00002221,0x00002acc, 30630x0004007c,0x00000027,0x0000262f,0x000031eb,
26780x00060041,0x000000d8,0x00002084,0x000021f3, 30640x00060041,0x000000db,0x00002472,0x000025d4,
26790x000000d7,0x00000202,0x0006003d,0x00000006, 30650x000000da,0x0000021d,0x0006003d,0x00000006,
26800x00002085,0x00002084,0x00000002,0x00000004, 30660x00002473,0x00002472,0x00000002,0x00000004,
26810x000500c7,0x00000006,0x00002226,0x00002085, 30670x000500c7,0x00000006,0x00002634,0x00002473,
26820x0000012d,0x000500ab,0x0000002f,0x00002227, 30680x00000130,0x000500ab,0x0000002f,0x00002635,
26830x00002226,0x000000a3,0x000300f7,0x0000222e, 30690x00002634,0x000000a6,0x000300f7,0x0000263c,
26840x00000000,0x000400fa,0x00002227,0x00002228, 30700x00000000,0x000400fa,0x00002635,0x00002636,
26850x0000222b,0x000200f8,0x00002228,0x000500c7, 30710x00002639,0x000200f8,0x00002636,0x000500c7,
26860x00000006,0x0000222a,0x00002085,0x00000142, 30720x00000006,0x00002638,0x00002473,0x00000145,
26870x000200f9,0x0000222e,0x000200f8,0x0000222b, 30730x000200f9,0x0000263c,0x000200f8,0x00002639,
26880x000400c8,0x00000006,0x0000222d,0x00002085, 30740x000400c8,0x00000006,0x0000263b,0x00002473,
26890x000200f9,0x0000222e,0x000200f8,0x0000222e, 30750x000200f9,0x0000263c,0x000200f8,0x0000263c,
26900x000700f5,0x00000006,0x00002acd,0x0000222a, 30760x000700f5,0x00000006,0x000031ec,0x00002638,
26910x00002228,0x0000222d,0x0000222b,0x0004007c, 30770x00002636,0x0000263b,0x00002639,0x0004007c,
26920x00000027,0x00002230,0x00002acd,0x00060050, 30780x00000027,0x0000263e,0x000031ec,0x00060050,
26930x0000004b,0x00002087,0x00002212,0x00002221, 30790x0000004b,0x00002475,0x00002620,0x0000262f,
26940x00002230,0x00060041,0x000000d8,0x00002089, 30800x0000263e,0x00050083,0x0000004b,0x00002478,
26950x000021f3,0x000000d7,0x0000020a,0x0006003d, 30810x00002475,0x00002468,0x0007000c,0x0000004b,
26960x00000006,0x0000208a,0x00002089,0x00000002, 30820x00002479,0x00000001,0x00000028,0x00002478,
26970x00000004,0x000500c7,0x00000006,0x00002235, 30830x0000065b,0x00050081,0x0000004b,0x0000247c,
26980x0000208a,0x0000012d,0x000500ab,0x0000002f, 30840x000024c8,0x000024db,0x0005008e,0x0000004b,
26990x00002236,0x00002235,0x000000a3,0x000300f7, 30850x0000247d,0x0000247c,0x000001ed,0x00050083,
27000x0000223d,0x00000000,0x000400fa,0x00002236, 30860x0000004b,0x0000247f,0x0000247d,0x00002468,
27010x00002237,0x0000223a,0x000200f8,0x00002237, 30870x00050088,0x0000004b,0x00002481,0x0000247f,
27020x000500c7,0x00000006,0x00002239,0x0000208a, 30880x00002479,0x0008000c,0x0000004b,0x00002484,
27030x00000142,0x000200f9,0x0000223d,0x000200f8, 30890x00000001,0x0000002b,0x00002481,0x00000570,
27040x0000223a,0x000400c8,0x00000006,0x0000223c, 30900x000032a2,0x0005008e,0x0000004b,0x00002485,
27050x0000208a,0x000200f9,0x0000223d,0x000200f8, 30910x00002484,0x0000066b,0x0004006d,0x0000065d,
27060x0000223d,0x000700f5,0x00000006,0x00002ace, 30920x00002486,0x00002485,0x00050051,0x00000006,
27070x00002239,0x00002237,0x0000223c,0x0000223a, 30930x00002488,0x00002486,0x00000000,0x000500c7,
27080x0004007c,0x00000027,0x0000223f,0x00002ace, 30940x00000006,0x00002642,0x00002488,0x000005fe,
27090x00060041,0x000000d8,0x0000208d,0x000021f3, 30950x000500c4,0x00000006,0x00002645,0x00002642,
27100x000000d7,0x00000212,0x0006003d,0x00000006, 30960x0000023e,0x000500c5,0x00000006,0x00002646,
27110x0000208e,0x0000208d,0x00000002,0x00000004, 30970x00002642,0x00002645,0x000500c7,0x00000006,
27120x000500c7,0x00000006,0x00002244,0x0000208e, 30980x00002647,0x00002646,0x00000605,0x000500c4,
27130x0000012d,0x000500ab,0x0000002f,0x00002245, 30990x00000006,0x0000264a,0x00002647,0x00000308,
27140x00002244,0x000000a3,0x000300f7,0x0000224c, 31000x000500c5,0x00000006,0x0000264b,0x00002647,
27150x00000000,0x000400fa,0x00002245,0x00002246, 31010x0000264a,0x000500c7,0x00000006,0x0000264c,
27160x00002249,0x000200f8,0x00002246,0x000500c7, 31020x0000264b,0x0000060b,0x000500c4,0x00000006,
27170x00000006,0x00002248,0x0000208e,0x00000142, 31030x0000264f,0x0000264c,0x00000215,0x000500c5,
27180x000200f9,0x0000224c,0x000200f8,0x00002249, 31040x00000006,0x00002650,0x0000264c,0x0000264f,
27190x000400c8,0x00000006,0x0000224b,0x0000208e, 31050x000500c7,0x00000006,0x00002651,0x00002650,
27200x000200f9,0x0000224c,0x000200f8,0x0000224c, 31060x00000611,0x000500c4,0x00000006,0x00002654,
27210x000700f5,0x00000006,0x00002acf,0x00002248, 31070x00002651,0x00000205,0x000500c5,0x00000006,
27220x00002246,0x0000224b,0x00002249,0x0004007c, 31080x00002655,0x00002651,0x00002654,0x000500c7,
27230x00000027,0x0000224e,0x00002acf,0x00060041, 31090x00000006,0x00002656,0x00002655,0x00000617,
27240x000000d8,0x00002091,0x000021f3,0x000000d7, 31100x000500c4,0x00000006,0x0000248a,0x00002656,
27250x0000021a,0x0006003d,0x00000006,0x00002092, 31110x00000205,0x00050051,0x00000006,0x0000248c,
27260x00002091,0x00000002,0x00000004,0x000500c7, 31120x00002486,0x00000001,0x000500c7,0x00000006,
27270x00000006,0x00002253,0x00002092,0x0000012d, 31130x0000265b,0x0000248c,0x000005fe,0x000500c4,
27280x000500ab,0x0000002f,0x00002254,0x00002253, 31140x00000006,0x0000265e,0x0000265b,0x0000023e,
27290x000000a3,0x000300f7,0x0000225b,0x00000000, 31150x000500c5,0x00000006,0x0000265f,0x0000265b,
27300x000400fa,0x00002254,0x00002255,0x00002258, 31160x0000265e,0x000500c7,0x00000006,0x00002660,
27310x000200f8,0x00002255,0x000500c7,0x00000006, 31170x0000265f,0x00000605,0x000500c4,0x00000006,
27320x00002257,0x00002092,0x00000142,0x000200f9, 31180x00002663,0x00002660,0x00000308,0x000500c5,
27330x0000225b,0x000200f8,0x00002258,0x000400c8, 31190x00000006,0x00002664,0x00002660,0x00002663,
27340x00000006,0x0000225a,0x00002092,0x000200f9, 31200x000500c7,0x00000006,0x00002665,0x00002664,
27350x0000225b,0x000200f8,0x0000225b,0x000700f5, 31210x0000060b,0x000500c4,0x00000006,0x00002668,
27360x00000006,0x00002ad0,0x00002257,0x00002255, 31220x00002665,0x00000215,0x000500c5,0x00000006,
27370x0000225a,0x00002258,0x0004007c,0x00000027, 31230x00002669,0x00002665,0x00002668,0x000500c7,
27380x0000225d,0x00002ad0,0x00060050,0x0000004b, 31240x00000006,0x0000266a,0x00002669,0x00000611,
27390x00002094,0x0000223f,0x0000224e,0x0000225d, 31250x000500c4,0x00000006,0x0000266d,0x0000266a,
27400x00050083,0x0000004b,0x00002097,0x00002094, 31260x00000205,0x000500c5,0x00000006,0x0000266e,
27410x00002087,0x0007000c,0x0000004b,0x00002098, 31270x0000266a,0x0000266d,0x000500c7,0x00000006,
27420x00000001,0x00000028,0x00002097,0x00000658, 31280x0000266f,0x0000266e,0x00000617,0x000500c4,
27430x00050081,0x0000004b,0x0000209b,0x000020e7, 31290x00000006,0x0000248e,0x0000266f,0x00000154,
27440x000020fa,0x0005008e,0x0000004b,0x0000209c, 31300x000500c5,0x00000006,0x0000248f,0x0000248a,
27450x0000209b,0x000001ea,0x00050083,0x0000004b, 31310x0000248e,0x00050051,0x00000006,0x00002491,
27460x0000209e,0x0000209c,0x00002087,0x00050088, 31320x00002486,0x00000002,0x000500c7,0x00000006,
27470x0000004b,0x000020a0,0x0000209e,0x00002098, 31330x00002674,0x00002491,0x000005fe,0x000500c4,
27480x0008000c,0x0000004b,0x000020a3,0x00000001, 31340x00000006,0x00002677,0x00002674,0x0000023e,
27490x0000002b,0x000020a0,0x0000056d,0x00002b61, 31350x000500c5,0x00000006,0x00002678,0x00002674,
27500x0005008e,0x0000004b,0x000020a4,0x000020a3, 31360x00002677,0x000500c7,0x00000006,0x00002679,
27510x00000668,0x0004006d,0x0000065a,0x000020a5, 31370x00002678,0x00000605,0x000500c4,0x00000006,
27520x000020a4,0x00050051,0x00000006,0x000020a7, 31380x0000267c,0x00002679,0x00000308,0x000500c5,
27530x000020a5,0x00000000,0x000500c7,0x00000006, 31390x00000006,0x0000267d,0x00002679,0x0000267c,
27540x00002261,0x000020a7,0x000005fb,0x000500c4, 31400x000500c7,0x00000006,0x0000267e,0x0000267d,
27550x00000006,0x00002264,0x00002261,0x0000023b, 31410x0000060b,0x000500c4,0x00000006,0x00002681,
27560x000500c5,0x00000006,0x00002265,0x00002261, 31420x0000267e,0x00000215,0x000500c5,0x00000006,
27570x00002264,0x000500c7,0x00000006,0x00002266, 31430x00002682,0x0000267e,0x00002681,0x000500c7,
27580x00002265,0x00000602,0x000500c4,0x00000006, 31440x00000006,0x00002683,0x00002682,0x00000611,
27590x00002269,0x00002266,0x00000305,0x000500c5, 31450x000500c4,0x00000006,0x00002686,0x00002683,
27600x00000006,0x0000226a,0x00002266,0x00002269, 31460x00000205,0x000500c5,0x00000006,0x00002687,
27610x000500c7,0x00000006,0x0000226b,0x0000226a, 31470x00002683,0x00002686,0x000500c7,0x00000006,
27620x00000608,0x000500c4,0x00000006,0x0000226e, 31480x00002688,0x00002687,0x00000617,0x000500c5,
27630x0000226b,0x00000212,0x000500c5,0x00000006, 31490x00000006,0x00002493,0x0000248f,0x00002688,
27640x0000226f,0x0000226b,0x0000226e,0x000500c7, 31500x000200f9,0x00002494,0x000200f8,0x00002494,
27650x00000006,0x00002270,0x0000226f,0x0000060e, 31510x000700f5,0x00000006,0x000031ed,0x00000531,
27660x000500c4,0x00000006,0x00002273,0x00002270, 31520x000025ca,0x00002493,0x0000263c,0x00050084,
27670x00000202,0x000500c5,0x00000006,0x00002274, 31530x00000006,0x00002497,0x0000010a,0x00000b11,
27680x00002270,0x00002273,0x000500c7,0x00000006, 31540x00050080,0x00000006,0x00002498,0x00000107,
27690x00002275,0x00002274,0x00000614,0x000500c4, 31550x00002497,0x00050095,0x000000ab,0x000026a3,
27700x00000006,0x000020a9,0x00002275,0x00000202, 31560x00002505,0x00002498,0x00050051,0x00000006,
27710x00050051,0x00000006,0x000020ab,0x000020a5, 31570x000026a4,0x000026a3,0x00000001,0x00050051,
27720x00000001,0x000500c7,0x00000006,0x0000227a, 31580x00000006,0x000026a5,0x000026a3,0x00000000,
27730x000020ab,0x000005fb,0x000500c4,0x00000006, 31590x00050080,0x00000006,0x000026aa,0x0000250c,
27740x0000227d,0x0000227a,0x0000023b,0x000500c5, 31600x000026a4,0x00050050,0x00000007,0x000026ab,
27750x00000006,0x0000227e,0x0000227a,0x0000227d, 31610x000026a5,0x000026aa,0x0004007c,0x00000014,
27760x000500c7,0x00000006,0x0000227f,0x0000227e, 31620x0000269b,0x000026ab,0x00060041,0x000000db,
27770x00000602,0x000500c4,0x00000006,0x00002282, 31630x00002693,0x0000269b,0x000000da,0x000000da,
27780x0000227f,0x00000305,0x000500c5,0x00000006, 31640x0005003e,0x00002693,0x000031ed,0x00000002,
27790x00002283,0x0000227f,0x00002282,0x000500c7, 31650x00000004,0x00050084,0x00000006,0x000026b0,
27800x00000006,0x00002284,0x00002283,0x00000608, 31660x0000010a,0x000024e5,0x00050080,0x00000006,
27810x000500c4,0x00000006,0x00002287,0x00002284, 31670x000026b1,0x00000107,0x000026b0,0x00050080,
27820x00000212,0x000500c5,0x00000006,0x00002288, 31680x00000006,0x000024a0,0x000026b1,0x00002497,
27830x00002284,0x00002287,0x000500c7,0x00000006, 31690x00050095,0x000000ab,0x000026c9,0x00002505,
27840x00002289,0x00002288,0x0000060e,0x000500c4, 31700x000024a0,0x00050051,0x00000006,0x000026ca,
27850x00000006,0x0000228c,0x00002289,0x00000202, 31710x000026c9,0x00000001,0x00050051,0x00000006,
27860x000500c5,0x00000006,0x0000228d,0x00002289, 31720x000026cb,0x000026c9,0x00000000,0x00050080,
27870x0000228c,0x000500c7,0x00000006,0x0000228e, 31730x00000006,0x000026d0,0x0000250c,0x000026ca,
27880x0000228d,0x00000614,0x000500c4,0x00000006, 31740x00050050,0x00000007,0x000026d1,0x000026cb,
27890x000020ad,0x0000228e,0x00000151,0x000500c5, 31750x000026d0,0x0004007c,0x00000014,0x000026c1,
27900x00000006,0x000020ae,0x000020a9,0x000020ad, 31760x000026d1,0x00060041,0x000000db,0x000026b9,
27910x00050051,0x00000006,0x000020b0,0x000020a5, 31770x000026c1,0x000000da,0x000000da,0x0005003e,
27920x00000002,0x000500c7,0x00000006,0x00002293, 31780x000026b9,0x00000b11,0x00000002,0x00000004,
27930x000020b0,0x000005fb,0x000500c4,0x00000006, 31790x000200f9,0x00000be4,0x000200f8,0x00000be8,
27940x00002296,0x00002293,0x0000023b,0x000500c5, 31800x000500aa,0x0000002f,0x00000beb,0x00000b13,
27950x00000006,0x00002297,0x00002293,0x00002296, 31810x00000246,0x000300f7,0x00000bed,0x00000000,
27960x000500c7,0x00000006,0x00002298,0x00002297, 31820x000400fa,0x00000beb,0x00000bec,0x00000bed,
27970x00000602,0x000500c4,0x00000006,0x0000229b, 31830x000200f8,0x00000bec,0x00050041,0x000000fe,
27980x00002298,0x00000305,0x000500c5,0x00000006, 31840x00002720,0x000000fc,0x00000308,0x0004003d,
27990x0000229c,0x00002298,0x0000229b,0x000500c7, 31850x00000006,0x00002721,0x00002720,0x00050080,
28000x00000006,0x0000229d,0x0000229c,0x00000608, 31860x00000006,0x00002723,0x00002721,0x00000b11,
28010x000500c4,0x00000006,0x000022a0,0x0000229d, 31870x00050041,0x000000fe,0x00002829,0x000000fc,
28020x00000212,0x000500c5,0x00000006,0x000022a1, 31880x0000023e,0x0004003d,0x00000006,0x0000282a,
28030x0000229d,0x000022a0,0x000500c7,0x00000006, 31890x00002829,0x00050084,0x00000006,0x0000282c,
28040x000022a2,0x000022a1,0x0000060e,0x000500c4, 31900x00002723,0x00000228,0x00050080,0x00000006,
28050x00000006,0x000022a5,0x000022a2,0x00000202, 31910x0000282d,0x0000282a,0x0000282c,0x000500c2,
28060x000500c5,0x00000006,0x000022a6,0x000022a2, 31920x00000006,0x0000282e,0x0000282d,0x00000233,
28070x000022a5,0x000500c7,0x00000006,0x000022a7, 31930x000500c4,0x00000006,0x0000282f,0x0000282e,
28080x000022a6,0x00000614,0x000500c5,0x00000006, 31940x0000020d,0x000500c5,0x00000006,0x00002830,
28090x000020b2,0x000020ae,0x000022a7,0x000200f9, 31950x0000282f,0x00000246,0x000200f9,0x0000272f,
28100x000020b3,0x000200f8,0x000020b3,0x000700f5, 31960x000200f8,0x0000272f,0x000700f5,0x0000004b,
28110x00000006,0x00002ad1,0x0000052e,0x000021e9, 31970x000031a2,0x000032a7,0x00000bec,0x0000328b,
28120x000020b2,0x0000225b,0x00050084,0x00000006, 31980x0000280b,0x000700f5,0x0000004b,0x000031a0,
28130x000020b6,0x00000107,0x000009e9,0x00050080, 31990x000032a5,0x00000bec,0x00003286,0x0000280b,
28140x00000006,0x000020b7,0x00000104,0x000020b6, 32000x000700f5,0x00000006,0x0000319d,0x000000a6,
28150x00050095,0x000000a8,0x000022c2,0x00002124, 32010x00000bec,0x0000280d,0x0000280b,0x000500b0,
28160x000020b7,0x00050051,0x00000006,0x000022c3, 32020x0000002f,0x00002732,0x0000319d,0x0000010a,
28170x000022c2,0x00000001,0x00050051,0x00000006, 32030x000400f6,0x0000280e,0x0000280b,0x00000000,
28180x000022c4,0x000022c2,0x00000000,0x00050080, 32040x000400fa,0x00002732,0x00002733,0x0000280e,
28190x00000006,0x000022c9,0x0000212b,0x000022c3, 32050x000200f8,0x00002733,0x00050084,0x00000006,
28200x00050050,0x00000007,0x000022ca,0x000022c4, 32060x00002735,0x0000010a,0x00000b11,0x00050080,
28210x000022c9,0x0004007c,0x00000014,0x000022ba, 32070x00000006,0x00002737,0x00002735,0x0000319d,
28220x000022ca,0x00060041,0x000000d8,0x000022b2, 32080x00050041,0x000000fe,0x0000273c,0x000000fc,
28230x000022ba,0x000000d7,0x000000d7,0x0005003e, 32090x0000027b,0x0004003d,0x00000006,0x0000273d,
28240x000022b2,0x00002ad1,0x00000002,0x00000004, 32100x0000273c,0x000500aa,0x0000002f,0x0000273e,
28250x00050084,0x00000006,0x000022cf,0x00000107, 32110x0000273d,0x000000b0,0x000300f7,0x000027d4,
28260x00002104,0x00050080,0x00000006,0x000022d0, 32120x00000000,0x000400fa,0x0000273e,0x0000273f,
28270x00000104,0x000022cf,0x00050080,0x00000006, 32130x00002784,0x000200f8,0x0000273f,0x00050084,
28280x000020bf,0x000022d0,0x000020b6,0x00050095, 32140x00000006,0x00002742,0x0000010a,0x0000319d,
28290x000000a8,0x000022e8,0x00002124,0x000020bf, 32150x00050080,0x00000006,0x00002743,0x0000282d,
28300x00050051,0x00000006,0x000022e9,0x000022e8, 32160x00002742,0x00050041,0x00000156,0x00002744,
28310x00000001,0x00050051,0x00000006,0x000022ea, 32170x000000fc,0x000000da,0x0004003d,0x00000007,
28320x000022e8,0x00000000,0x00050080,0x00000006, 32180x00002745,0x00002744,0x00050051,0x00000006,
28330x000022ef,0x0000212b,0x000022e9,0x00050050, 32190x00002847,0x00002745,0x00000000,0x00050095,
28340x00000007,0x000022f0,0x000022ea,0x000022ef, 32200x000000ab,0x00002849,0x00002847,0x00002743,
28350x0004007c,0x00000014,0x000022e0,0x000022f0, 32210x00050051,0x00000006,0x0000284a,0x00002849,
28360x00060041,0x000000d8,0x000022d8,0x000022e0, 32220x00000001,0x00050051,0x00000006,0x0000284b,
28370x000000d7,0x000000d7,0x0005003e,0x000022d8, 32230x00002849,0x00000000,0x00050051,0x00000006,
28380x000009e9,0x00000002,0x00000004,0x000200f9, 32240x0000284e,0x00002745,0x00000001,0x00050080,
28390x00000a5f,0x000200f8,0x00000a63,0x000500aa, 32250x00000006,0x00002850,0x0000284e,0x0000284a,
28400x0000002f,0x00000a66,0x000009eb,0x00000243, 32260x00050050,0x00000007,0x00002851,0x0000284b,
28410x000300f7,0x00000a68,0x00000000,0x000400fa, 32270x00002850,0x0004007c,0x00000014,0x00002841,
28420x00000a66,0x00000a67,0x00000a68,0x000200f8, 32280x00002851,0x00060041,0x000000db,0x00002838,
28430x00000a67,0x00050041,0x000000fb,0x0000232f, 32290x00002841,0x000000da,0x000000da,0x0006003d,
28440x000000f9,0x00000305,0x0004003d,0x00000006, 32300x00000006,0x00002839,0x00002838,0x00000002,
28450x00002330,0x0000232f,0x00050080,0x00000006, 32310x00000004,0x000500ab,0x0000002f,0x00002748,
28460x00002332,0x00002330,0x000009e9,0x00050041, 32320x00002839,0x00000380,0x000300f7,0x00002783,
28470x000000fb,0x000023ee,0x000000f9,0x0000023b, 32330x00000000,0x000400fa,0x00002748,0x00002749,
28480x0004003d,0x00000006,0x000023ef,0x000023ee, 32340x00002783,0x000200f8,0x00002749,0x000500c2,
28490x00050084,0x00000006,0x000023f1,0x00002332, 32350x00000006,0x00002855,0x00002839,0x0000020d,
28500x00000225,0x00050080,0x00000006,0x000023f2, 32360x00050084,0x00000006,0x0000274c,0x00002855,
28510x000023ef,0x000023f1,0x000500c2,0x00000006, 32370x00000107,0x000500c7,0x00000006,0x0000274e,
28520x000023f3,0x000023f2,0x00000230,0x000500c4, 32380x00002839,0x00000967,0x000500aa,0x0000002f,
28530x00000006,0x000023f4,0x000023f3,0x0000020a, 32390x0000274f,0x0000274e,0x00000246,0x000300f7,
28540x000500c5,0x00000006,0x000023f5,0x000023f4, 32400x00002776,0x00000000,0x000400fa,0x0000274f,
28550x00000243,0x000200f9,0x0000233e,0x000200f8, 32410x00002750,0x0000275c,0x000200f8,0x00002750,
28560x0000233e,0x000700f5,0x0000004b,0x00002aaa, 32420x00050041,0x000000fe,0x00002751,0x000000fc,
28570x00002b66,0x00000a67,0x00002b57,0x000023d0, 32430x0000096c,0x0004003d,0x00000006,0x00002752,
28580x000700f5,0x0000004b,0x00002aa8,0x00002b64, 32440x00002751,0x00050082,0x00000006,0x00002756,
28590x00000a67,0x00002b55,0x000023d0,0x000700f5, 32450x0000274c,0x0000282a,0x00050086,0x00000006,
28600x00000006,0x00002aa5,0x000000a3,0x00000a67, 32460x00002757,0x00002756,0x00000228,0x00050080,
28610x000023d2,0x000023d0,0x000500b0,0x0000002f, 32470x00000006,0x00002758,0x00002752,0x00002757,
28620x00002341,0x00002aa5,0x00000107,0x000400f6, 32480x00050041,0x000000fe,0x00002895,0x000000fc,
28630x000023d3,0x000023d0,0x00000000,0x000400fa, 32490x000000fd,0x0004003d,0x00000006,0x00002896,
28640x00002341,0x00002342,0x000023d3,0x000200f8, 32500x00002895,0x00050084,0x00000006,0x00002897,
28650x00002342,0x00050084,0x00000006,0x00002344, 32510x0000011f,0x00002896,0x00050080,0x00000006,
28660x00000107,0x000009e9,0x00050080,0x00000006, 32520x00002898,0x00000107,0x00002897,0x00050080,
28670x00002346,0x00002344,0x00002aa5,0x00050041, 32530x00000006,0x0000289e,0x00002896,0x000032a8,
28680x000000fb,0x0000234c,0x000000f9,0x0000024d, 32540x00050086,0x00000006,0x0000289f,0x0000289e,
28690x0004003d,0x00000006,0x0000234d,0x0000234c, 32550x00000101,0x00050084,0x00000006,0x00002891,
28700x000500b0,0x0000002f,0x0000234e,0x00002346, 32560x00000107,0x0000289f,0x00050080,0x00000006,
28710x0000234d,0x000300f7,0x00002399,0x00000000, 32570x00002892,0x00002898,0x00002891,0x00050084,
28720x000400fa,0x0000234e,0x0000234f,0x00002399, 32580x00000006,0x00002866,0x00000150,0x00002758,
28730x000200f8,0x0000234f,0x00050041,0x000000fb, 32590x00050080,0x00000006,0x00002867,0x00002892,
28740x00002350,0x000000f9,0x00000263,0x0004003d, 32600x00002866,0x00050041,0x00000156,0x00002868,
28750x00000006,0x00002351,0x00002350,0x000500aa, 32610x000000fc,0x00000154,0x0004003d,0x00000007,
28760x0000002f,0x00002352,0x00002351,0x0000037d, 32620x00002869,0x00002868,0x00050051,0x00000006,
28770x000300f7,0x0000237e,0x00000000,0x000400fa, 32630x000028b6,0x00002869,0x00000000,0x00050095,
28780x00002352,0x00002353,0x00002370,0x000200f8, 32640x000000ab,0x000028b8,0x000028b6,0x00002867,
28790x00002353,0x00050041,0x000000fb,0x000023f8, 32650x00050051,0x00000006,0x000028b9,0x000028b8,
28800x000000f9,0x000000fa,0x0004003d,0x00000006, 32660x00000001,0x00050051,0x00000006,0x000028ba,
28810x000023f9,0x000023f8,0x00050084,0x00000006, 32670x000028b8,0x00000000,0x00050051,0x00000006,
28820x000023fa,0x00000107,0x000023f9,0x00050080, 32680x000028bd,0x00002869,0x00000001,0x00050080,
28830x00000006,0x000023fb,0x00000104,0x000023fa, 32690x00000006,0x000028bf,0x000028bd,0x000028b9,
28840x00050084,0x00000006,0x00002356,0x00000107, 32700x00050050,0x00000007,0x000028c0,0x000028ba,
28850x00002346,0x00050080,0x00000006,0x00002357, 32710x000028bf,0x0004007c,0x00000014,0x000028b0,
28860x000023fb,0x00002356,0x00050041,0x00000153, 32720x000028c0,0x00060041,0x000000db,0x000028a7,
28870x00002358,0x000000f9,0x00000151,0x0004003d, 32730x000028b0,0x000000da,0x000000da,0x0006003d,
28880x00000007,0x00002359,0x00002358,0x00050051, 32740x00000006,0x000028a8,0x000028a7,0x00000002,
28890x00000006,0x00002412,0x00002359,0x00000000, 32750x00000004,0x0004007c,0x00000027,0x0000286c,
28900x00050095,0x000000a8,0x00002414,0x00002412, 32760x000028a8,0x00050080,0x00000006,0x0000286e,
28910x00002357,0x00050051,0x00000006,0x00002415, 32770x00002867,0x0000010a,0x00050095,0x000000ab,
28920x00002414,0x00000001,0x00050051,0x00000006, 32780x000028d9,0x000028b6,0x0000286e,0x00050051,
28930x00002416,0x00002414,0x00000000,0x00050051, 32790x00000006,0x000028da,0x000028d9,0x00000001,
28940x00000006,0x00002419,0x00002359,0x00000001, 32800x00050051,0x00000006,0x000028db,0x000028d9,
28950x00050080,0x00000006,0x0000241b,0x00002419, 32810x00000000,0x00050080,0x00000006,0x000028e0,
28960x00002415,0x00050050,0x00000007,0x0000241c, 32820x000028bd,0x000028da,0x00050050,0x00000007,
28970x00002416,0x0000241b,0x0004007c,0x00000014, 32830x000028e1,0x000028db,0x000028e0,0x0004007c,
28980x0000240c,0x0000241c,0x00060041,0x000000d8, 32840x00000014,0x000028d1,0x000028e1,0x00060041,
28990x00002403,0x0000240c,0x000000d7,0x000000d7, 32850x000000db,0x000028c8,0x000028d1,0x000000da,
29000x0006003d,0x00000006,0x00002404,0x00002403, 32860x000000da,0x0006003d,0x00000006,0x000028c9,
29010x00000002,0x00000004,0x00050041,0x000000fb, 32870x000028c8,0x00000002,0x00000004,0x0004007c,
29020x0000241f,0x000000f9,0x00000229,0x0004003d, 32880x00000027,0x00002872,0x000028c9,0x00050080,
29030x00000006,0x00002420,0x0000241f,0x00050041, 32890x00000006,0x00002874,0x00002867,0x00000111,
29040x000000fb,0x0000242e,0x000000f9,0x00000221, 32900x00050095,0x000000ab,0x000028fa,0x000028b6,
29050x0004003d,0x00000006,0x0000242f,0x0000242e, 32910x00002874,0x00050051,0x00000006,0x000028fb,
29060x000500ab,0x0000002f,0x00002430,0x0000242f, 32920x000028fa,0x00000001,0x00050051,0x00000006,
29070x000000a3,0x000600a9,0x00000006,0x00002431, 32930x000028fc,0x000028fa,0x00000000,0x00050080,
29080x00002430,0x00000225,0x00000104,0x00050084, 32940x00000006,0x00002901,0x000028bd,0x000028fb,
29090x00000006,0x00002423,0x00002404,0x00002431, 32950x00050050,0x00000007,0x00002902,0x000028fc,
29100x00050080,0x00000006,0x00002424,0x00002420, 32960x00002901,0x0004007c,0x00000014,0x000028f2,
29110x00002423,0x000500c2,0x00000006,0x00002425, 32970x00002902,0x00060041,0x000000db,0x000028e9,
29120x00002424,0x00000230,0x000500c4,0x00000006, 32980x000028f2,0x000000da,0x000000da,0x0006003d,
29130x00002426,0x00002425,0x0000020a,0x000600a9, 32990x00000006,0x000028ea,0x000028e9,0x00000002,
29140x00000006,0x0000242a,0x00002430,0x00000236, 33000x00000004,0x0004007c,0x00000027,0x00002878,
29150x000000a3,0x000500c5,0x00000006,0x0000242b, 33010x000028ea,0x00060050,0x0000004b,0x00002879,
29160x00002426,0x0000242a,0x00050084,0x00000006, 33020x0000286c,0x00002872,0x00002878,0x00050080,
29170x00002473,0x0000011c,0x000023f9,0x00050080, 33030x00000006,0x0000287b,0x00002867,0x00000118,
29180x00000006,0x00002474,0x00000104,0x00002473, 33040x00050095,0x000000ab,0x0000291b,0x000028b6,
29190x00050080,0x00000006,0x0000247a,0x000023f9, 33050x0000287b,0x00050051,0x00000006,0x0000291c,
29200x00002b67,0x00050086,0x00000006,0x0000247b, 33060x0000291b,0x00000001,0x00050051,0x00000006,
29210x0000247a,0x000000fe,0x00050084,0x00000006, 33070x0000291d,0x0000291b,0x00000000,0x00050080,
29220x0000246d,0x00000104,0x0000247b,0x00050080, 33080x00000006,0x00002922,0x000028bd,0x0000291c,
29230x00000006,0x0000246e,0x00002474,0x0000246d, 33090x00050050,0x00000007,0x00002923,0x0000291d,
29240x00050084,0x00000006,0x00002442,0x0000014d, 33100x00002922,0x0004007c,0x00000014,0x00002913,
29250x00002404,0x00050080,0x00000006,0x00002443, 33110x00002923,0x00060041,0x000000db,0x0000290a,
29260x0000246e,0x00002442,0x00050095,0x000000a8, 33120x00002913,0x000000da,0x000000da,0x0006003d,
29270x00002494,0x00002412,0x00002443,0x00050051, 33130x00000006,0x0000290b,0x0000290a,0x00000002,
29280x00000006,0x00002495,0x00002494,0x00000001, 33140x00000004,0x0004007c,0x00000027,0x0000287f,
29290x00050051,0x00000006,0x00002496,0x00002494, 33150x0000290b,0x00050080,0x00000006,0x00002881,
29300x00000000,0x00050080,0x00000006,0x0000249b, 33160x00002867,0x0000011f,0x00050095,0x000000ab,
29310x00002419,0x00002495,0x00050050,0x00000007, 33170x0000293c,0x000028b6,0x00002881,0x00050051,
29320x0000249c,0x00002496,0x0000249b,0x0004007c, 33180x00000006,0x0000293d,0x0000293c,0x00000001,
29330x00000014,0x0000248c,0x0000249c,0x00060041, 33190x00050051,0x00000006,0x0000293e,0x0000293c,
29340x000000d8,0x00002483,0x0000248c,0x000000d7, 33200x00000000,0x00050080,0x00000006,0x00002943,
29350x000000d7,0x0006003d,0x00000006,0x00002484, 33210x000028bd,0x0000293d,0x00050050,0x00000007,
29360x00002483,0x00000002,0x00000004,0x0004007c, 33220x00002944,0x0000293e,0x00002943,0x0004007c,
29370x00000027,0x00002448,0x00002484,0x00050080, 33230x00000014,0x00002934,0x00002944,0x00060041,
29380x00000006,0x0000244a,0x00002443,0x00000107, 33240x000000db,0x0000292b,0x00002934,0x000000da,
29390x00050095,0x000000a8,0x000024b5,0x00002412, 33250x000000da,0x0006003d,0x00000006,0x0000292c,
29400x0000244a,0x00050051,0x00000006,0x000024b6, 33260x0000292b,0x00000002,0x00000004,0x0004007c,
29410x000024b5,0x00000001,0x00050051,0x00000006, 33270x00000027,0x00002885,0x0000292c,0x00050080,
29420x000024b7,0x000024b5,0x00000000,0x00050080, 33280x00000006,0x00002887,0x00002867,0x00000189,
29430x00000006,0x000024bc,0x00002419,0x000024b6, 33290x00050095,0x000000ab,0x0000295d,0x000028b6,
29440x00050050,0x00000007,0x000024bd,0x000024b7, 33300x00002887,0x00050051,0x00000006,0x0000295e,
29450x000024bc,0x0004007c,0x00000014,0x000024ad, 33310x0000295d,0x00000001,0x00050051,0x00000006,
29460x000024bd,0x00060041,0x000000d8,0x000024a4, 33320x0000295f,0x0000295d,0x00000000,0x00050080,
29470x000024ad,0x000000d7,0x000000d7,0x0006003d, 33330x00000006,0x00002964,0x000028bd,0x0000295e,
29480x00000006,0x000024a5,0x000024a4,0x00000002, 33340x00050050,0x00000007,0x00002965,0x0000295f,
29490x00000004,0x0004007c,0x00000027,0x0000244e, 33350x00002964,0x0004007c,0x00000014,0x00002955,
29500x000024a5,0x00050080,0x00000006,0x00002450, 33360x00002965,0x00060041,0x000000db,0x0000294c,
29510x00002443,0x0000010e,0x00050095,0x000000a8, 33370x00002955,0x000000da,0x000000da,0x0006003d,
29520x000024d6,0x00002412,0x00002450,0x00050051, 33380x00000006,0x0000294d,0x0000294c,0x00000002,
29530x00000006,0x000024d7,0x000024d6,0x00000001, 33390x00000004,0x0004007c,0x00000027,0x0000288b,
29540x00050051,0x00000006,0x000024d8,0x000024d6, 33400x0000294d,0x00060050,0x0000004b,0x0000288c,
29550x00000000,0x00050080,0x00000006,0x000024dd, 33410x0000287f,0x00002885,0x0000288b,0x000200f9,
29560x00002419,0x000024d7,0x00050050,0x00000007, 33420x00002776,0x000200f8,0x0000275c,0x00050041,
29570x000024de,0x000024d8,0x000024dd,0x0004007c, 33430x000000fe,0x0000275e,0x000000fc,0x0000022c,
29580x00000014,0x000024ce,0x000024de,0x00060041, 33440x0004003d,0x00000006,0x0000275f,0x0000275e,
29590x000000d8,0x000024c5,0x000024ce,0x000000d7, 33450x00050082,0x00000006,0x00002760,0x0000274c,
29600x000000d7,0x0006003d,0x00000006,0x000024c6, 33460x0000275f,0x00050041,0x000000fe,0x00002968,
29610x000024c5,0x00000002,0x00000004,0x0004007c, 33470x000000fc,0x00000224,0x0004003d,0x00000006,
29620x00000027,0x00002454,0x000024c6,0x00060050, 33480x00002969,0x00002968,0x000500ab,0x0000002f,
29630x0000004b,0x00002455,0x00002448,0x0000244e, 33490x0000296a,0x00002969,0x000000a6,0x000600a9,
29640x00002454,0x00050080,0x00000006,0x00002457, 33500x00000006,0x0000296b,0x0000296a,0x00000228,
29650x00002443,0x00000115,0x00050095,0x000000a8, 33510x00000107,0x00050086,0x00000006,0x00002762,
29660x000024f7,0x00002412,0x00002457,0x00050051, 33520x00002760,0x0000296b,0x00050041,0x000000fe,
29670x00000006,0x000024f8,0x000024f7,0x00000001, 33530x000029ab,0x000000fc,0x000000fd,0x0004003d,
29680x00050051,0x00000006,0x000024f9,0x000024f7, 33540x00000006,0x000029ac,0x000029ab,0x00050084,
29690x00000000,0x00050080,0x00000006,0x000024fe, 33550x00000006,0x000029ad,0x0000011f,0x000029ac,
29700x00002419,0x000024f8,0x00050050,0x00000007, 33560x00050080,0x00000006,0x000029ae,0x00000107,
29710x000024ff,0x000024f9,0x000024fe,0x0004007c, 33570x000029ad,0x00050080,0x00000006,0x000029b4,
29720x00000014,0x000024ef,0x000024ff,0x00060041, 33580x000029ac,0x000032a8,0x00050086,0x00000006,
29730x000000d8,0x000024e6,0x000024ef,0x000000d7, 33590x000029b5,0x000029b4,0x00000101,0x00050084,
29740x000000d7,0x0006003d,0x00000006,0x000024e7, 33600x00000006,0x000029a7,0x00000107,0x000029b5,
29750x000024e6,0x00000002,0x00000004,0x0004007c, 33610x00050080,0x00000006,0x000029a8,0x000029ae,
29760x00000027,0x0000245b,0x000024e7,0x00050080, 33620x000029a7,0x00050084,0x00000006,0x0000297c,
29770x00000006,0x0000245d,0x00002443,0x0000011c, 33630x00000150,0x00002762,0x00050080,0x00000006,
29780x00050095,0x000000a8,0x00002518,0x00002412, 33640x0000297d,0x000029a8,0x0000297c,0x00050041,
29790x0000245d,0x00050051,0x00000006,0x00002519, 33650x00000156,0x0000297e,0x000000fc,0x00000154,
29800x00002518,0x00000001,0x00050051,0x00000006, 33660x0004003d,0x00000007,0x0000297f,0x0000297e,
29810x0000251a,0x00002518,0x00000000,0x00050080, 33670x00050051,0x00000006,0x000029cc,0x0000297f,
29820x00000006,0x0000251f,0x00002419,0x00002519, 33680x00000000,0x00050095,0x000000ab,0x000029ce,
29830x00050050,0x00000007,0x00002520,0x0000251a, 33690x000029cc,0x0000297d,0x00050051,0x00000006,
29840x0000251f,0x0004007c,0x00000014,0x00002510, 33700x000029cf,0x000029ce,0x00000001,0x00050051,
29850x00002520,0x00060041,0x000000d8,0x00002507, 33710x00000006,0x000029d0,0x000029ce,0x00000000,
29860x00002510,0x000000d7,0x000000d7,0x0006003d, 33720x00050051,0x00000006,0x000029d3,0x0000297f,
29870x00000006,0x00002508,0x00002507,0x00000002, 33730x00000001,0x00050080,0x00000006,0x000029d5,
29880x00000004,0x0004007c,0x00000027,0x00002461, 33740x000029d3,0x000029cf,0x00050050,0x00000007,
29890x00002508,0x00050080,0x00000006,0x00002463, 33750x000029d6,0x000029d0,0x000029d5,0x0004007c,
29900x00002443,0x00000186,0x00050095,0x000000a8, 33760x00000014,0x000029c6,0x000029d6,0x00060041,
29910x00002539,0x00002412,0x00002463,0x00050051, 33770x000000db,0x000029bd,0x000029c6,0x000000da,
29920x00000006,0x0000253a,0x00002539,0x00000001, 33780x000000da,0x0006003d,0x00000006,0x000029be,
29930x00050051,0x00000006,0x0000253b,0x00002539, 33790x000029bd,0x00000002,0x00000004,0x0004007c,
29940x00000000,0x00050080,0x00000006,0x00002540, 33800x00000027,0x00002982,0x000029be,0x00050080,
29950x00002419,0x0000253a,0x00050050,0x00000007, 33810x00000006,0x00002984,0x0000297d,0x0000010a,
29960x00002541,0x0000253b,0x00002540,0x0004007c, 33820x00050095,0x000000ab,0x000029ef,0x000029cc,
29970x00000014,0x00002531,0x00002541,0x00060041, 33830x00002984,0x00050051,0x00000006,0x000029f0,
29980x000000d8,0x00002528,0x00002531,0x000000d7, 33840x000029ef,0x00000001,0x00050051,0x00000006,
29990x000000d7,0x0006003d,0x00000006,0x00002529, 33850x000029f1,0x000029ef,0x00000000,0x00050080,
30000x00002528,0x00000002,0x00000004,0x0004007c, 33860x00000006,0x000029f6,0x000029d3,0x000029f0,
30010x00000027,0x00002467,0x00002529,0x00060050, 33870x00050050,0x00000007,0x000029f7,0x000029f1,
30020x0000004b,0x00002468,0x0000245b,0x00002461, 33880x000029f6,0x0004007c,0x00000014,0x000029e7,
30030x00002467,0x000300f7,0x0000236f,0x00000000, 33890x000029f7,0x00060041,0x000000db,0x000029de,
30040x000400fa,0x00002430,0x00002364,0x0000236f, 33900x000029e7,0x000000da,0x000000da,0x0006003d,
30050x000200f8,0x00002364,0x00050084,0x00000006, 33910x00000006,0x000029df,0x000029de,0x00000002,
30060x00002368,0x00000225,0x00002404,0x00050080, 33920x00000004,0x0004007c,0x00000027,0x00002988,
30070x00000006,0x00002369,0x00002420,0x00002368, 33930x000029df,0x00050080,0x00000006,0x0000298a,
30080x00050080,0x00000006,0x0000236a,0x00002369, 33940x0000297d,0x00000111,0x00050095,0x000000ab,
30090x000005cd,0x00050041,0x00000153,0x0000236b, 33950x00002a10,0x000029cc,0x0000298a,0x00050051,
30100x000000f9,0x000000d7,0x0004003d,0x00000007, 33960x00000006,0x00002a11,0x00002a10,0x00000001,
30110x0000236c,0x0000236b,0x00050051,0x00000006, 33970x00050051,0x00000006,0x00002a12,0x00002a10,
30120x00002557,0x0000236c,0x00000000,0x00050095, 33980x00000000,0x00050080,0x00000006,0x00002a17,
30130x000000a8,0x00002559,0x00002557,0x0000236a, 33990x000029d3,0x00002a11,0x00050050,0x00000007,
30140x00050051,0x00000006,0x0000255a,0x00002559, 34000x00002a18,0x00002a12,0x00002a17,0x0004007c,
30150x00000001,0x00050051,0x00000006,0x0000255b, 34010x00000014,0x00002a08,0x00002a18,0x00060041,
30160x00002559,0x00000000,0x00050051,0x00000006, 34020x000000db,0x000029ff,0x00002a08,0x000000da,
30170x0000255e,0x0000236c,0x00000001,0x00050080, 34030x000000da,0x0006003d,0x00000006,0x00002a00,
30180x00000006,0x00002560,0x0000255e,0x0000255a, 34040x000029ff,0x00000002,0x00000004,0x0004007c,
30190x00050050,0x00000007,0x00002561,0x0000255b, 34050x00000027,0x0000298e,0x00002a00,0x00060050,
30200x00002560,0x0004007c,0x00000014,0x00002551, 34060x0000004b,0x0000298f,0x00002982,0x00002988,
30210x00002561,0x00060041,0x000000d8,0x00002549, 34070x0000298e,0x00050080,0x00000006,0x00002991,
30220x00002551,0x000000d7,0x000000d7,0x0005003e, 34080x0000297d,0x00000118,0x00050095,0x000000ab,
30230x00002549,0x000023f5,0x00000002,0x00000004, 34090x00002a31,0x000029cc,0x00002991,0x00050051,
30240x000200f9,0x0000236f,0x000200f8,0x0000236f, 34100x00000006,0x00002a32,0x00002a31,0x00000001,
30250x000200f9,0x0000237e,0x000200f8,0x00002370, 34110x00050051,0x00000006,0x00002a33,0x00002a31,
30260x00050080,0x00000006,0x00002374,0x00002351, 34120x00000000,0x00050080,0x00000006,0x00002a38,
30270x00002346,0x00050084,0x00000006,0x00002567, 34130x000029d3,0x00002a32,0x00050050,0x00000007,
30280x00002374,0x00000225,0x00050080,0x00000006, 34140x00002a39,0x00002a33,0x00002a38,0x0004007c,
30290x00002568,0x000023ef,0x00002567,0x000500c2, 34150x00000014,0x00002a29,0x00002a39,0x00060041,
30300x00000006,0x00002569,0x00002568,0x00000230, 34160x000000db,0x00002a20,0x00002a29,0x000000da,
30310x000500c4,0x00000006,0x0000256a,0x00002569, 34170x000000da,0x0006003d,0x00000006,0x00002a21,
30320x0000020a,0x000500c5,0x00000006,0x0000256b, 34180x00002a20,0x00000002,0x00000004,0x0004007c,
30330x0000256a,0x00000243,0x00050041,0x000000fb, 34190x00000027,0x00002995,0x00002a21,0x00050080,
30340x00002377,0x000000f9,0x000008bc,0x0004003d, 34200x00000006,0x00002997,0x0000297d,0x0000011f,
30350x00000006,0x00002378,0x00002377,0x00050080, 34210x00050095,0x000000ab,0x00002a52,0x000029cc,
30360x00000006,0x0000237a,0x00002378,0x00002374, 34220x00002997,0x00050051,0x00000006,0x00002a53,
30370x00050041,0x000000fb,0x000025ab,0x000000f9, 34230x00002a52,0x00000001,0x00050051,0x00000006,
30380x000000fa,0x0004003d,0x00000006,0x000025ac, 34240x00002a54,0x00002a52,0x00000000,0x00050080,
30390x000025ab,0x00050084,0x00000006,0x000025ad, 34250x00000006,0x00002a59,0x000029d3,0x00002a53,
30400x0000011c,0x000025ac,0x00050080,0x00000006, 34260x00050050,0x00000007,0x00002a5a,0x00002a54,
30410x000025ae,0x00000104,0x000025ad,0x00050080, 34270x00002a59,0x0004007c,0x00000014,0x00002a4a,
30420x00000006,0x000025b4,0x000025ac,0x00002b67, 34280x00002a5a,0x00060041,0x000000db,0x00002a41,
30430x00050086,0x00000006,0x000025b5,0x000025b4, 34290x00002a4a,0x000000da,0x000000da,0x0006003d,
30440x000000fe,0x00050084,0x00000006,0x000025a7, 34300x00000006,0x00002a42,0x00002a41,0x00000002,
30450x00000104,0x000025b5,0x00050080,0x00000006, 34310x00000004,0x0004007c,0x00000027,0x0000299b,
30460x000025a8,0x000025ae,0x000025a7,0x00050084, 34320x00002a42,0x00050080,0x00000006,0x0000299d,
30470x00000006,0x0000257c,0x0000014d,0x0000237a, 34330x0000297d,0x00000189,0x00050095,0x000000ab,
30480x00050080,0x00000006,0x0000257d,0x000025a8, 34340x00002a73,0x000029cc,0x0000299d,0x00050051,
30490x0000257c,0x00050041,0x00000153,0x0000257e, 34350x00000006,0x00002a74,0x00002a73,0x00000001,
30500x000000f9,0x00000151,0x0004003d,0x00000007, 34360x00050051,0x00000006,0x00002a75,0x00002a73,
30510x0000257f,0x0000257e,0x00050051,0x00000006, 34370x00000000,0x00050080,0x00000006,0x00002a7a,
30520x000025cc,0x0000257f,0x00000000,0x00050095, 34380x000029d3,0x00002a74,0x00050050,0x00000007,
30530x000000a8,0x000025ce,0x000025cc,0x0000257d, 34390x00002a7b,0x00002a75,0x00002a7a,0x0004007c,
30540x00050051,0x00000006,0x000025cf,0x000025ce, 34400x00000014,0x00002a6b,0x00002a7b,0x00060041,
30550x00000001,0x00050051,0x00000006,0x000025d0, 34410x000000db,0x00002a62,0x00002a6b,0x000000da,
30560x000025ce,0x00000000,0x00050051,0x00000006, 34420x000000da,0x0006003d,0x00000006,0x00002a63,
30570x000025d3,0x0000257f,0x00000001,0x00050080, 34430x00002a62,0x00000002,0x00000004,0x0004007c,
30580x00000006,0x000025d5,0x000025d3,0x000025cf, 34440x00000027,0x000029a1,0x00002a63,0x00060050,
30590x00050050,0x00000007,0x000025d6,0x000025d0, 34450x0000004b,0x000029a2,0x00002995,0x0000299b,
30600x000025d5,0x0004007c,0x00000014,0x000025c6, 34460x000029a1,0x000300f7,0x00002775,0x00000000,
30610x000025d6,0x00060041,0x000000d8,0x000025bd, 34470x000400fa,0x0000296a,0x0000276a,0x00002775,
30620x000025c6,0x000000d7,0x000000d7,0x0006003d, 34480x000200f8,0x0000276a,0x00050084,0x00000006,
30630x00000006,0x000025be,0x000025bd,0x00000002, 34490x0000276e,0x00000228,0x00002762,0x00050080,
30640x00000004,0x0004007c,0x00000027,0x00002582, 34500x00000006,0x0000276f,0x0000275f,0x0000276e,
30650x000025be,0x00050080,0x00000006,0x00002584, 34510x00050080,0x00000006,0x00002770,0x0000276f,
30660x0000257d,0x00000107,0x00050095,0x000000a8, 34520x000005d0,0x00050095,0x000000ab,0x00002a93,
30670x000025ef,0x000025cc,0x00002584,0x00050051, 34530x00002847,0x00002770,0x00050051,0x00000006,
30680x00000006,0x000025f0,0x000025ef,0x00000001, 34540x00002a94,0x00002a93,0x00000001,0x00050051,
30690x00050051,0x00000006,0x000025f1,0x000025ef, 34550x00000006,0x00002a95,0x00002a93,0x00000000,
30700x00000000,0x00050080,0x00000006,0x000025f6, 34560x00050080,0x00000006,0x00002a9a,0x0000284e,
30710x000025d3,0x000025f0,0x00050050,0x00000007, 34570x00002a94,0x00050050,0x00000007,0x00002a9b,
30720x000025f7,0x000025f1,0x000025f6,0x0004007c, 34580x00002a95,0x00002a9a,0x0004007c,0x00000014,
30730x00000014,0x000025e7,0x000025f7,0x00060041, 34590x00002a8b,0x00002a9b,0x00060041,0x000000db,
30740x000000d8,0x000025de,0x000025e7,0x000000d7, 34600x00002a83,0x00002a8b,0x000000da,0x000000da,
30750x000000d7,0x0006003d,0x00000006,0x000025df, 34610x0005003e,0x00002a83,0x00002830,0x00000002,
30760x000025de,0x00000002,0x00000004,0x0004007c, 34620x00000004,0x000200f9,0x00002775,0x000200f8,
30770x00000027,0x00002588,0x000025df,0x00050080, 34630x00002775,0x000200f9,0x00002776,0x000200f8,
30780x00000006,0x0000258a,0x0000257d,0x0000010e, 34640x00002776,0x000700f5,0x0000004b,0x000031b7,
30790x00050095,0x000000a8,0x00002610,0x000025cc, 34650x0000288c,0x00002750,0x000029a2,0x00002775,
30800x0000258a,0x00050051,0x00000006,0x00002611, 34660x000700f5,0x0000004b,0x000031b5,0x00002879,
30810x00002610,0x00000001,0x00050051,0x00000006, 34670x00002750,0x0000298f,0x00002775,0x00050051,
30820x00002612,0x00002610,0x00000000,0x00050080, 34680x00000027,0x00002a9f,0x000031b5,0x00000000,
30830x00000006,0x00002617,0x000025d3,0x00002611, 34690x00050051,0x00000027,0x00002aa1,0x000031b7,
30840x00050050,0x00000007,0x00002618,0x00002612, 34700x00000000,0x000500bc,0x0000002f,0x00002aa2,
30850x00002617,0x0004007c,0x00000014,0x00002608, 34710x00002a9f,0x00002aa1,0x000300f7,0x00002aa9,
30860x00002618,0x00060041,0x000000d8,0x000025ff, 34720x00000000,0x000400fa,0x00002aa2,0x00002aa3,
30870x00002608,0x000000d7,0x000000d7,0x0006003d, 34730x00002aa9,0x000200f8,0x00002aa3,0x00050051,
30880x00000006,0x00002600,0x000025ff,0x00000002, 34740x00000027,0x00002aa5,0x000031b5,0x00000001,
30890x00000004,0x0004007c,0x00000027,0x0000258e, 34750x00050051,0x00000027,0x00002aa7,0x000031b7,
30900x00002600,0x00060050,0x0000004b,0x0000258f, 34760x00000001,0x000500bc,0x0000002f,0x00002aa8,
30910x00002582,0x00002588,0x0000258e,0x00050080, 34770x00002aa5,0x00002aa7,0x000200f9,0x00002aa9,
30920x00000006,0x00002591,0x0000257d,0x00000115, 34780x000200f8,0x00002aa9,0x000700f5,0x0000002f,
30930x00050095,0x000000a8,0x00002631,0x000025cc, 34790x00002aaa,0x00002aa2,0x00002776,0x00002aa8,
30940x00002591,0x00050051,0x00000006,0x00002632, 34800x00002aa3,0x000300f7,0x00002ab1,0x00000000,
30950x00002631,0x00000001,0x00050051,0x00000006, 34810x000400fa,0x00002aaa,0x00002aab,0x00002ab1,
30960x00002633,0x00002631,0x00000000,0x00050080, 34820x000200f8,0x00002aab,0x00050051,0x00000027,
30970x00000006,0x00002638,0x000025d3,0x00002632, 34830x00002aad,0x000031b5,0x00000002,0x00050051,
30980x00050050,0x00000007,0x00002639,0x00002633, 34840x00000027,0x00002aaf,0x000031b7,0x00000002,
30990x00002638,0x0004007c,0x00000014,0x00002629, 34850x000500bc,0x0000002f,0x00002ab0,0x00002aad,
31000x00002639,0x00060041,0x000000d8,0x00002620, 34860x00002aaf,0x000200f9,0x00002ab1,0x000200f8,
31010x00002629,0x000000d7,0x000000d7,0x0006003d, 34870x00002ab1,0x000700f5,0x0000002f,0x00002ab2,
31020x00000006,0x00002621,0x00002620,0x00000002, 34880x00002aaa,0x00002aa9,0x00002ab0,0x00002aab,
31030x00000004,0x0004007c,0x00000027,0x00002595, 34890x000300f7,0x00002782,0x00000000,0x000400fa,
31040x00002621,0x00050080,0x00000006,0x00002597, 34900x00002ab2,0x0000277b,0x00002782,0x000200f8,
31050x0000257d,0x0000011c,0x00050095,0x000000a8, 34910x0000277b,0x0007000c,0x0000004b,0x0000277e,
31060x00002652,0x000025cc,0x00002597,0x00050051, 34920x00000001,0x00000025,0x000031a0,0x000031b5,
31070x00000006,0x00002653,0x00002652,0x00000001, 34930x0007000c,0x0000004b,0x00002781,0x00000001,
31080x00050051,0x00000006,0x00002654,0x00002652, 34940x00000028,0x000031a2,0x000031b7,0x000200f9,
31090x00000000,0x00050080,0x00000006,0x00002659, 34950x00002782,0x000200f8,0x00002782,0x000700f5,
31100x000025d3,0x00002653,0x00050050,0x00000007, 34960x0000004b,0x0000328d,0x000031a2,0x00002ab1,
31110x0000265a,0x00002654,0x00002659,0x0004007c, 34970x00002781,0x0000277b,0x000700f5,0x0000004b,
31120x00000014,0x0000264a,0x0000265a,0x00060041, 34980x00003288,0x000031a0,0x00002ab1,0x0000277e,
31130x000000d8,0x00002641,0x0000264a,0x000000d7, 34990x0000277b,0x000200f9,0x00002783,0x000200f8,
31140x000000d7,0x0006003d,0x00000006,0x00002642, 35000x00002783,0x000700f5,0x0000004b,0x0000328c,
31150x00002641,0x00000002,0x00000004,0x0004007c, 35010x000031a2,0x0000273f,0x0000328d,0x00002782,
31160x00000027,0x0000259b,0x00002642,0x00050080, 35020x000700f5,0x0000004b,0x00003287,0x000031a0,
31170x00000006,0x0000259d,0x0000257d,0x00000186, 35030x0000273f,0x00003288,0x00002782,0x000700f5,
31180x00050095,0x000000a8,0x00002673,0x000025cc, 35040x0000004b,0x000031e3,0x000032a7,0x0000273f,
31190x0000259d,0x00050051,0x00000006,0x00002674, 35050x000031b7,0x00002782,0x000700f5,0x0000004b,
31200x00002673,0x00000001,0x00050051,0x00000006, 35060x000031de,0x000032a5,0x0000273f,0x000031b5,
31210x00002675,0x00002673,0x00000000,0x00050080, 35070x00002782,0x000200f9,0x000027d4,0x000200f8,
31220x00000006,0x0000267a,0x000025d3,0x00002674, 35080x00002784,0x00050041,0x000000fe,0x00002786,
31230x00050050,0x00000007,0x0000267b,0x00002675, 35090x000000fc,0x00000250,0x0004003d,0x00000006,
31240x0000267a,0x0004007c,0x00000014,0x0000266b, 35100x00002787,0x00002786,0x000500b0,0x0000002f,
31250x0000267b,0x00060041,0x000000d8,0x00002662, 35110x00002788,0x00002737,0x00002787,0x000300f7,
31260x0000266b,0x000000d7,0x000000d7,0x0006003d, 35120x000027d3,0x00000000,0x000400fa,0x00002788,
31270x00000006,0x00002663,0x00002662,0x00000002, 35130x00002789,0x000027d3,0x000200f8,0x00002789,
31280x00000004,0x0004007c,0x00000027,0x000025a1, 35140x00050041,0x000000fe,0x0000278a,0x000000fc,
31290x00002663,0x00060050,0x0000004b,0x000025a2, 35150x00000266,0x0004003d,0x00000006,0x0000278b,
31300x00002595,0x0000259b,0x000025a1,0x000200f9, 35160x0000278a,0x000500aa,0x0000002f,0x0000278c,
31310x0000237e,0x000200f8,0x0000237e,0x000700f5, 35170x0000278b,0x00000380,0x000300f7,0x000027b8,
31320x0000004b,0x00002aaf,0x00002468,0x0000236f, 35180x00000000,0x000400fa,0x0000278c,0x0000278d,
31330x000025a2,0x00002370,0x000700f5,0x0000004b, 35190x000027aa,0x000200f8,0x0000278d,0x00050041,
31340x00002aad,0x00002455,0x0000236f,0x0000258f, 35200x000000fe,0x00002ab6,0x000000fc,0x000000fd,
31350x00002370,0x000700f5,0x00000006,0x00002aab, 35210x0004003d,0x00000006,0x00002ab7,0x00002ab6,
31360x0000242b,0x0000236f,0x0000256b,0x00002370, 35220x00050084,0x00000006,0x00002ab8,0x0000010a,
31370x00050041,0x000000fb,0x0000237f,0x000000f9, 35230x00002ab7,0x00050080,0x00000006,0x00002ab9,
31380x000008c7,0x0004003d,0x00000006,0x00002380, 35240x00000107,0x00002ab8,0x00050084,0x00000006,
31390x0000237f,0x000500c2,0x00000006,0x0000267f, 35250x00002790,0x0000010a,0x00002737,0x00050080,
31400x00002aab,0x0000020a,0x00050041,0x000000fb, 35260x00000006,0x00002791,0x00002ab9,0x00002790,
31410x00002383,0x000000f9,0x00000229,0x0004003d, 35270x00050041,0x00000156,0x00002792,0x000000fc,
31420x00000006,0x00002384,0x00002383,0x00050086, 35280x00000154,0x0004003d,0x00000007,0x00002793,
31430x00000006,0x00002385,0x00002384,0x00000104, 35290x00002792,0x00050051,0x00000006,0x00002ad0,
31440x00050082,0x00000006,0x00002386,0x0000267f, 35300x00002793,0x00000000,0x00050095,0x000000ab,
31450x00002385,0x00050084,0x00000006,0x00002387, 35310x00002ad2,0x00002ad0,0x00002791,0x00050051,
31460x00000107,0x00002386,0x00050080,0x00000006, 35320x00000006,0x00002ad3,0x00002ad2,0x00000001,
31470x00002388,0x00002380,0x00002387,0x00050041, 35330x00050051,0x00000006,0x00002ad4,0x00002ad2,
31480x00000153,0x00002389,0x000000f9,0x000000d7, 35340x00000000,0x00050051,0x00000006,0x00002ad7,
31490x0004003d,0x00000007,0x0000238a,0x00002389, 35350x00002793,0x00000001,0x00050080,0x00000006,
31500x00050051,0x00000006,0x00002695,0x0000238a, 35360x00002ad9,0x00002ad7,0x00002ad3,0x00050050,
31510x00000000,0x00050095,0x000000a8,0x00002697, 35370x00000007,0x00002ada,0x00002ad4,0x00002ad9,
31520x00002695,0x00002388,0x00050051,0x00000006, 35380x0004007c,0x00000014,0x00002aca,0x00002ada,
31530x00002698,0x00002697,0x00000001,0x00050051, 35390x00060041,0x000000db,0x00002ac1,0x00002aca,
31540x00000006,0x00002699,0x00002697,0x00000000, 35400x000000da,0x000000da,0x0006003d,0x00000006,
31550x00050051,0x00000006,0x0000269c,0x0000238a, 35410x00002ac2,0x00002ac1,0x00000002,0x00000004,
31560x00000001,0x00050080,0x00000006,0x0000269e, 35420x00050041,0x000000fe,0x00002add,0x000000fc,
31570x0000269c,0x00002698,0x00050050,0x00000007, 35430x0000022c,0x0004003d,0x00000006,0x00002ade,
31580x0000269f,0x00002699,0x0000269e,0x0004007c, 35440x00002add,0x00050041,0x000000fe,0x00002aec,
31590x00000014,0x0000268f,0x0000269f,0x00060041, 35450x000000fc,0x00000224,0x0004003d,0x00000006,
31600x000000d8,0x00002687,0x0000268f,0x000000d7, 35460x00002aed,0x00002aec,0x000500ab,0x0000002f,
31610x000000d7,0x0005003e,0x00002687,0x000023f5, 35470x00002aee,0x00002aed,0x000000a6,0x000600a9,
31620x00000002,0x00000004,0x00050051,0x00000027, 35480x00000006,0x00002aef,0x00002aee,0x00000228,
31630x000026a3,0x00002aad,0x00000000,0x00050051, 35490x00000107,0x00050084,0x00000006,0x00002ae1,
31640x00000027,0x000026a5,0x00002aaf,0x00000000, 35500x00002ac2,0x00002aef,0x00050080,0x00000006,
31650x000500bc,0x0000002f,0x000026a6,0x000026a3, 35510x00002ae2,0x00002ade,0x00002ae1,0x000500c2,
31660x000026a5,0x000300f7,0x000026ad,0x00000000, 35520x00000006,0x00002ae3,0x00002ae2,0x00000233,
31670x000400fa,0x000026a6,0x000026a7,0x000026ad, 35530x000500c4,0x00000006,0x00002ae4,0x00002ae3,
31680x000200f8,0x000026a7,0x00050051,0x00000027, 35540x0000020d,0x000600a9,0x00000006,0x00002ae8,
31690x000026a9,0x00002aad,0x00000001,0x00050051, 35550x00002aee,0x00000239,0x000000a6,0x000500c5,
31700x00000027,0x000026ab,0x00002aaf,0x00000001, 35560x00000006,0x00002ae9,0x00002ae4,0x00002ae8,
31710x000500bc,0x0000002f,0x000026ac,0x000026a9, 35570x00050084,0x00000006,0x00002b31,0x0000011f,
31720x000026ab,0x000200f9,0x000026ad,0x000200f8, 35580x00002ab7,0x00050080,0x00000006,0x00002b32,
31730x000026ad,0x000700f5,0x0000002f,0x000026ae, 35590x00000107,0x00002b31,0x00050080,0x00000006,
31740x000026a6,0x0000237e,0x000026ac,0x000026a7, 35600x00002b38,0x00002ab7,0x000032a8,0x00050086,
31750x000300f7,0x000026b5,0x00000000,0x000400fa, 35610x00000006,0x00002b39,0x00002b38,0x00000101,
31760x000026ae,0x000026af,0x000026b5,0x000200f8, 35620x00050084,0x00000006,0x00002b2b,0x00000107,
31770x000026af,0x00050051,0x00000027,0x000026b1, 35630x00002b39,0x00050080,0x00000006,0x00002b2c,
31780x00002aad,0x00000002,0x00050051,0x00000027, 35640x00002b32,0x00002b2b,0x00050084,0x00000006,
31790x000026b3,0x00002aaf,0x00000002,0x000500bc, 35650x00002b00,0x00000150,0x00002ac2,0x00050080,
31800x0000002f,0x000026b4,0x000026b1,0x000026b3, 35660x00000006,0x00002b01,0x00002b2c,0x00002b00,
31810x000200f9,0x000026b5,0x000200f8,0x000026b5, 35670x00050095,0x000000ab,0x00002b52,0x00002ad0,
31820x000700f5,0x0000002f,0x000026b6,0x000026ae, 35680x00002b01,0x00050051,0x00000006,0x00002b53,
31830x000026ad,0x000026b4,0x000026af,0x000300f7, 35690x00002b52,0x00000001,0x00050051,0x00000006,
31840x00002398,0x00000000,0x000400fa,0x000026b6, 35700x00002b54,0x00002b52,0x00000000,0x00050080,
31850x00002391,0x00002398,0x000200f8,0x00002391, 35710x00000006,0x00002b59,0x00002ad7,0x00002b53,
31860x0007000c,0x0000004b,0x00002394,0x00000001, 35720x00050050,0x00000007,0x00002b5a,0x00002b54,
31870x00000025,0x00002aa8,0x00002aad,0x0007000c, 35730x00002b59,0x0004007c,0x00000014,0x00002b4a,
31880x0000004b,0x00002397,0x00000001,0x00000028, 35740x00002b5a,0x00060041,0x000000db,0x00002b41,
31890x00002aaa,0x00002aaf,0x000200f9,0x00002398, 35750x00002b4a,0x000000da,0x000000da,0x0006003d,
31900x000200f8,0x00002398,0x000700f5,0x0000004b, 35760x00000006,0x00002b42,0x00002b41,0x00000002,
31910x00002b58,0x00002aaa,0x000026b5,0x00002397, 35770x00000004,0x0004007c,0x00000027,0x00002b06,
31920x00002391,0x000700f5,0x0000004b,0x00002b56, 35780x00002b42,0x00050080,0x00000006,0x00002b08,
31930x00002aa8,0x000026b5,0x00002394,0x00002391, 35790x00002b01,0x0000010a,0x00050095,0x000000ab,
31940x000200f9,0x00002399,0x000200f8,0x00002399, 35800x00002b73,0x00002ad0,0x00002b08,0x00050051,
31950x000700f5,0x0000004b,0x00002b57,0x00002aaa, 35810x00000006,0x00002b74,0x00002b73,0x00000001,
31960x00002342,0x00002b58,0x00002398,0x000700f5, 35820x00050051,0x00000006,0x00002b75,0x00002b73,
31970x0000004b,0x00002b55,0x00002aa8,0x00002342, 35830x00000000,0x00050080,0x00000006,0x00002b7a,
31980x00002b56,0x00002398,0x000700f5,0x0000004b, 35840x00002ad7,0x00002b74,0x00050050,0x00000007,
31990x00002ac9,0x00002b66,0x00002342,0x00002aaf, 35850x00002b7b,0x00002b75,0x00002b7a,0x0004007c,
32000x00002398,0x000700f5,0x0000004b,0x00002ac7, 35860x00000014,0x00002b6b,0x00002b7b,0x00060041,
32010x00002b64,0x00002342,0x00002aad,0x00002398, 35870x000000db,0x00002b62,0x00002b6b,0x000000da,
32020x000700f5,0x00000006,0x00002ac3,0x0000037d, 35880x000000da,0x0006003d,0x00000006,0x00002b63,
32030x00002342,0x00002aab,0x00002398,0x00050084, 35890x00002b62,0x00000002,0x00000004,0x0004007c,
32040x00000006,0x0000239c,0x00000107,0x00002aa5, 35900x00000027,0x00002b0c,0x00002b63,0x00050080,
32050x00050080,0x00000006,0x0000239d,0x000023f2, 35910x00000006,0x00002b0e,0x00002b01,0x00000111,
32060x0000239c,0x00050041,0x00000153,0x0000239e, 35920x00050095,0x000000ab,0x00002b94,0x00002ad0,
32070x000000f9,0x000000d7,0x0004003d,0x00000007, 35930x00002b0e,0x00050051,0x00000006,0x00002b95,
32080x0000239f,0x0000239e,0x00050051,0x00000006, 35940x00002b94,0x00000001,0x00050051,0x00000006,
32090x000026cd,0x0000239f,0x00000000,0x00050095, 35950x00002b96,0x00002b94,0x00000000,0x00050080,
32100x000000a8,0x000026cf,0x000026cd,0x0000239d, 35960x00000006,0x00002b9b,0x00002ad7,0x00002b95,
32110x00050051,0x00000006,0x000026d0,0x000026cf, 35970x00050050,0x00000007,0x00002b9c,0x00002b96,
32120x00000001,0x00050051,0x00000006,0x000026d1, 35980x00002b9b,0x0004007c,0x00000014,0x00002b8c,
32130x000026cf,0x00000000,0x00050051,0x00000006, 35990x00002b9c,0x00060041,0x000000db,0x00002b83,
32140x000026d4,0x0000239f,0x00000001,0x00050080, 36000x00002b8c,0x000000da,0x000000da,0x0006003d,
32150x00000006,0x000026d6,0x000026d4,0x000026d0, 36010x00000006,0x00002b84,0x00002b83,0x00000002,
32160x00050050,0x00000007,0x000026d7,0x000026d1, 36020x00000004,0x0004007c,0x00000027,0x00002b12,
32170x000026d6,0x0004007c,0x00000014,0x000026c7, 36030x00002b84,0x00060050,0x0000004b,0x00002b13,
32180x000026d7,0x00060041,0x000000d8,0x000026bf, 36040x00002b06,0x00002b0c,0x00002b12,0x00050080,
32190x000026c7,0x000000d7,0x000000d7,0x0005003e, 36050x00000006,0x00002b15,0x00002b01,0x00000118,
32200x000026bf,0x00002ac3,0x00000002,0x00000004, 36060x00050095,0x000000ab,0x00002bb5,0x00002ad0,
32210x00050080,0x00000006,0x000023a3,0x000023f2, 36070x00002b15,0x00050051,0x00000006,0x00002bb6,
32220x0000011c,0x00050084,0x00000006,0x000023a5, 36080x00002bb5,0x00000001,0x00050051,0x00000006,
32230x0000014d,0x00002aa5,0x00050080,0x00000006, 36090x00002bb7,0x00002bb5,0x00000000,0x00050080,
32240x000023a6,0x000023a3,0x000023a5,0x00050051, 36100x00000006,0x00002bbc,0x00002ad7,0x00002bb6,
32250x00000027,0x000023ab,0x00002ac7,0x00000000, 36110x00050050,0x00000007,0x00002bbd,0x00002bb7,
32260x0004007c,0x00000006,0x000026dd,0x000023ab, 36120x00002bbc,0x0004007c,0x00000014,0x00002bad,
32270x00050095,0x000000a8,0x000026f8,0x000026cd, 36130x00002bbd,0x00060041,0x000000db,0x00002ba4,
32280x000023a6,0x00050051,0x00000006,0x000026f9, 36140x00002bad,0x000000da,0x000000da,0x0006003d,
32290x000026f8,0x00000001,0x00050051,0x00000006, 36150x00000006,0x00002ba5,0x00002ba4,0x00000002,
32300x000026fa,0x000026f8,0x00000000,0x00050080, 36160x00000004,0x0004007c,0x00000027,0x00002b19,
32310x00000006,0x000026ff,0x000026d4,0x000026f9, 36170x00002ba5,0x00050080,0x00000006,0x00002b1b,
32320x00050050,0x00000007,0x00002700,0x000026fa, 36180x00002b01,0x0000011f,0x00050095,0x000000ab,
32330x000026ff,0x0004007c,0x00000014,0x000026f0, 36190x00002bd6,0x00002ad0,0x00002b1b,0x00050051,
32340x00002700,0x00060041,0x000000d8,0x000026e8, 36200x00000006,0x00002bd7,0x00002bd6,0x00000001,
32350x000026f0,0x000000d7,0x000000d7,0x0005003e, 36210x00050051,0x00000006,0x00002bd8,0x00002bd6,
32360x000026e8,0x000026dd,0x00000002,0x00000004, 36220x00000000,0x00050080,0x00000006,0x00002bdd,
32370x00050080,0x00000006,0x000023ae,0x000023a6, 36230x00002ad7,0x00002bd7,0x00050050,0x00000007,
32380x00000107,0x00050051,0x00000027,0x000023b2, 36240x00002bde,0x00002bd8,0x00002bdd,0x0004007c,
32390x00002ac7,0x00000001,0x0004007c,0x00000006, 36250x00000014,0x00002bce,0x00002bde,0x00060041,
32400x00002706,0x000023b2,0x00050095,0x000000a8, 36260x000000db,0x00002bc5,0x00002bce,0x000000da,
32410x00002721,0x000026cd,0x000023ae,0x00050051, 36270x000000da,0x0006003d,0x00000006,0x00002bc6,
32420x00000006,0x00002722,0x00002721,0x00000001, 36280x00002bc5,0x00000002,0x00000004,0x0004007c,
32430x00050051,0x00000006,0x00002723,0x00002721, 36290x00000027,0x00002b1f,0x00002bc6,0x00050080,
32440x00000000,0x00050080,0x00000006,0x00002728, 36300x00000006,0x00002b21,0x00002b01,0x00000189,
32450x000026d4,0x00002722,0x00050050,0x00000007, 36310x00050095,0x000000ab,0x00002bf7,0x00002ad0,
32460x00002729,0x00002723,0x00002728,0x0004007c, 36320x00002b21,0x00050051,0x00000006,0x00002bf8,
32470x00000014,0x00002719,0x00002729,0x00060041, 36330x00002bf7,0x00000001,0x00050051,0x00000006,
32480x000000d8,0x00002711,0x00002719,0x000000d7, 36340x00002bf9,0x00002bf7,0x00000000,0x00050080,
32490x000000d7,0x0005003e,0x00002711,0x00002706, 36350x00000006,0x00002bfe,0x00002ad7,0x00002bf8,
36360x00050050,0x00000007,0x00002bff,0x00002bf9,
36370x00002bfe,0x0004007c,0x00000014,0x00002bef,
36380x00002bff,0x00060041,0x000000db,0x00002be6,
36390x00002bef,0x000000da,0x000000da,0x0006003d,
36400x00000006,0x00002be7,0x00002be6,0x00000002,
36410x00000004,0x0004007c,0x00000027,0x00002b25,
36420x00002be7,0x00060050,0x0000004b,0x00002b26,
36430x00002b19,0x00002b1f,0x00002b25,0x000300f7,
36440x000027a9,0x00000000,0x000400fa,0x00002aee,
36450x0000279e,0x000027a9,0x000200f8,0x0000279e,
36460x00050084,0x00000006,0x000027a2,0x00000228,
36470x00002ac2,0x00050080,0x00000006,0x000027a3,
36480x00002ade,0x000027a2,0x00050080,0x00000006,
36490x000027a4,0x000027a3,0x000005d0,0x00050041,
36500x00000156,0x000027a5,0x000000fc,0x000000da,
36510x0004003d,0x00000007,0x000027a6,0x000027a5,
36520x00050051,0x00000006,0x00002c15,0x000027a6,
36530x00000000,0x00050095,0x000000ab,0x00002c17,
36540x00002c15,0x000027a4,0x00050051,0x00000006,
36550x00002c18,0x00002c17,0x00000001,0x00050051,
36560x00000006,0x00002c19,0x00002c17,0x00000000,
36570x00050051,0x00000006,0x00002c1c,0x000027a6,
36580x00000001,0x00050080,0x00000006,0x00002c1e,
36590x00002c1c,0x00002c18,0x00050050,0x00000007,
36600x00002c1f,0x00002c19,0x00002c1e,0x0004007c,
36610x00000014,0x00002c0f,0x00002c1f,0x00060041,
36620x000000db,0x00002c07,0x00002c0f,0x000000da,
36630x000000da,0x0005003e,0x00002c07,0x00002830,
36640x00000002,0x00000004,0x000200f9,0x000027a9,
36650x000200f8,0x000027a9,0x000200f9,0x000027b8,
36660x000200f8,0x000027aa,0x00050080,0x00000006,
36670x000027ae,0x0000278b,0x00002737,0x00050084,
36680x00000006,0x00002c25,0x000027ae,0x00000228,
36690x00050080,0x00000006,0x00002c26,0x0000282a,
36700x00002c25,0x000500c2,0x00000006,0x00002c27,
36710x00002c26,0x00000233,0x000500c4,0x00000006,
36720x00002c28,0x00002c27,0x0000020d,0x000500c5,
36730x00000006,0x00002c29,0x00002c28,0x00000246,
36740x00050041,0x000000fe,0x000027b1,0x000000fc,
36750x0000096c,0x0004003d,0x00000006,0x000027b2,
36760x000027b1,0x00050080,0x00000006,0x000027b4,
36770x000027b2,0x000027ae,0x00050041,0x000000fe,
36780x00002c69,0x000000fc,0x000000fd,0x0004003d,
36790x00000006,0x00002c6a,0x00002c69,0x00050084,
36800x00000006,0x00002c6b,0x0000011f,0x00002c6a,
36810x00050080,0x00000006,0x00002c6c,0x00000107,
36820x00002c6b,0x00050080,0x00000006,0x00002c72,
36830x00002c6a,0x000032a8,0x00050086,0x00000006,
36840x00002c73,0x00002c72,0x00000101,0x00050084,
36850x00000006,0x00002c65,0x00000107,0x00002c73,
36860x00050080,0x00000006,0x00002c66,0x00002c6c,
36870x00002c65,0x00050084,0x00000006,0x00002c3a,
36880x00000150,0x000027b4,0x00050080,0x00000006,
36890x00002c3b,0x00002c66,0x00002c3a,0x00050041,
36900x00000156,0x00002c3c,0x000000fc,0x00000154,
36910x0004003d,0x00000007,0x00002c3d,0x00002c3c,
36920x00050051,0x00000006,0x00002c8a,0x00002c3d,
36930x00000000,0x00050095,0x000000ab,0x00002c8c,
36940x00002c8a,0x00002c3b,0x00050051,0x00000006,
36950x00002c8d,0x00002c8c,0x00000001,0x00050051,
36960x00000006,0x00002c8e,0x00002c8c,0x00000000,
36970x00050051,0x00000006,0x00002c91,0x00002c3d,
36980x00000001,0x00050080,0x00000006,0x00002c93,
36990x00002c91,0x00002c8d,0x00050050,0x00000007,
37000x00002c94,0x00002c8e,0x00002c93,0x0004007c,
37010x00000014,0x00002c84,0x00002c94,0x00060041,
37020x000000db,0x00002c7b,0x00002c84,0x000000da,
37030x000000da,0x0006003d,0x00000006,0x00002c7c,
37040x00002c7b,0x00000002,0x00000004,0x0004007c,
37050x00000027,0x00002c40,0x00002c7c,0x00050080,
37060x00000006,0x00002c42,0x00002c3b,0x0000010a,
37070x00050095,0x000000ab,0x00002cad,0x00002c8a,
37080x00002c42,0x00050051,0x00000006,0x00002cae,
37090x00002cad,0x00000001,0x00050051,0x00000006,
37100x00002caf,0x00002cad,0x00000000,0x00050080,
37110x00000006,0x00002cb4,0x00002c91,0x00002cae,
37120x00050050,0x00000007,0x00002cb5,0x00002caf,
37130x00002cb4,0x0004007c,0x00000014,0x00002ca5,
37140x00002cb5,0x00060041,0x000000db,0x00002c9c,
37150x00002ca5,0x000000da,0x000000da,0x0006003d,
37160x00000006,0x00002c9d,0x00002c9c,0x00000002,
37170x00000004,0x0004007c,0x00000027,0x00002c46,
37180x00002c9d,0x00050080,0x00000006,0x00002c48,
37190x00002c3b,0x00000111,0x00050095,0x000000ab,
37200x00002cce,0x00002c8a,0x00002c48,0x00050051,
37210x00000006,0x00002ccf,0x00002cce,0x00000001,
37220x00050051,0x00000006,0x00002cd0,0x00002cce,
37230x00000000,0x00050080,0x00000006,0x00002cd5,
37240x00002c91,0x00002ccf,0x00050050,0x00000007,
37250x00002cd6,0x00002cd0,0x00002cd5,0x0004007c,
37260x00000014,0x00002cc6,0x00002cd6,0x00060041,
37270x000000db,0x00002cbd,0x00002cc6,0x000000da,
37280x000000da,0x0006003d,0x00000006,0x00002cbe,
37290x00002cbd,0x00000002,0x00000004,0x0004007c,
37300x00000027,0x00002c4c,0x00002cbe,0x00060050,
37310x0000004b,0x00002c4d,0x00002c40,0x00002c46,
37320x00002c4c,0x00050080,0x00000006,0x00002c4f,
37330x00002c3b,0x00000118,0x00050095,0x000000ab,
37340x00002cef,0x00002c8a,0x00002c4f,0x00050051,
37350x00000006,0x00002cf0,0x00002cef,0x00000001,
37360x00050051,0x00000006,0x00002cf1,0x00002cef,
37370x00000000,0x00050080,0x00000006,0x00002cf6,
37380x00002c91,0x00002cf0,0x00050050,0x00000007,
37390x00002cf7,0x00002cf1,0x00002cf6,0x0004007c,
37400x00000014,0x00002ce7,0x00002cf7,0x00060041,
37410x000000db,0x00002cde,0x00002ce7,0x000000da,
37420x000000da,0x0006003d,0x00000006,0x00002cdf,
37430x00002cde,0x00000002,0x00000004,0x0004007c,
37440x00000027,0x00002c53,0x00002cdf,0x00050080,
37450x00000006,0x00002c55,0x00002c3b,0x0000011f,
37460x00050095,0x000000ab,0x00002d10,0x00002c8a,
37470x00002c55,0x00050051,0x00000006,0x00002d11,
37480x00002d10,0x00000001,0x00050051,0x00000006,
37490x00002d12,0x00002d10,0x00000000,0x00050080,
37500x00000006,0x00002d17,0x00002c91,0x00002d11,
37510x00050050,0x00000007,0x00002d18,0x00002d12,
37520x00002d17,0x0004007c,0x00000014,0x00002d08,
37530x00002d18,0x00060041,0x000000db,0x00002cff,
37540x00002d08,0x000000da,0x000000da,0x0006003d,
37550x00000006,0x00002d00,0x00002cff,0x00000002,
37560x00000004,0x0004007c,0x00000027,0x00002c59,
37570x00002d00,0x00050080,0x00000006,0x00002c5b,
37580x00002c3b,0x00000189,0x00050095,0x000000ab,
37590x00002d31,0x00002c8a,0x00002c5b,0x00050051,
37600x00000006,0x00002d32,0x00002d31,0x00000001,
37610x00050051,0x00000006,0x00002d33,0x00002d31,
37620x00000000,0x00050080,0x00000006,0x00002d38,
37630x00002c91,0x00002d32,0x00050050,0x00000007,
37640x00002d39,0x00002d33,0x00002d38,0x0004007c,
37650x00000014,0x00002d29,0x00002d39,0x00060041,
37660x000000db,0x00002d20,0x00002d29,0x000000da,
37670x000000da,0x0006003d,0x00000006,0x00002d21,
37680x00002d20,0x00000002,0x00000004,0x0004007c,
37690x00000027,0x00002c5f,0x00002d21,0x00060050,
37700x0000004b,0x00002c60,0x00002c53,0x00002c59,
37710x00002c5f,0x000200f9,0x000027b8,0x000200f8,
37720x000027b8,0x000700f5,0x0000004b,0x000031a7,
37730x00002b26,0x000027a9,0x00002c60,0x000027aa,
37740x000700f5,0x0000004b,0x000031a5,0x00002b13,
37750x000027a9,0x00002c4d,0x000027aa,0x000700f5,
37760x00000006,0x000031a3,0x00002ae9,0x000027a9,
37770x00002c29,0x000027aa,0x00050041,0x000000fe,
37780x000027b9,0x000000fc,0x000009ef,0x0004003d,
37790x00000006,0x000027ba,0x000027b9,0x000500c2,
37800x00000006,0x00002d3d,0x000031a3,0x0000020d,
37810x00050041,0x000000fe,0x000027bd,0x000000fc,
37820x0000022c,0x0004003d,0x00000006,0x000027be,
37830x000027bd,0x00050086,0x00000006,0x000027bf,
37840x000027be,0x00000107,0x00050082,0x00000006,
37850x000027c0,0x00002d3d,0x000027bf,0x00050084,
37860x00000006,0x000027c1,0x0000010a,0x000027c0,
37870x00050080,0x00000006,0x000027c2,0x000027ba,
37880x000027c1,0x00050041,0x00000156,0x000027c3,
37890x000000fc,0x000000da,0x0004003d,0x00000007,
37900x000027c4,0x000027c3,0x00050051,0x00000006,
37910x00002d53,0x000027c4,0x00000000,0x00050095,
37920x000000ab,0x00002d55,0x00002d53,0x000027c2,
37930x00050051,0x00000006,0x00002d56,0x00002d55,
37940x00000001,0x00050051,0x00000006,0x00002d57,
37950x00002d55,0x00000000,0x00050051,0x00000006,
37960x00002d5a,0x000027c4,0x00000001,0x00050080,
37970x00000006,0x00002d5c,0x00002d5a,0x00002d56,
37980x00050050,0x00000007,0x00002d5d,0x00002d57,
37990x00002d5c,0x0004007c,0x00000014,0x00002d4d,
38000x00002d5d,0x00060041,0x000000db,0x00002d45,
38010x00002d4d,0x000000da,0x000000da,0x0005003e,
38020x00002d45,0x00002830,0x00000002,0x00000004,
38030x00050051,0x00000027,0x00002d61,0x000031a5,
38040x00000000,0x00050051,0x00000027,0x00002d63,
38050x000031a7,0x00000000,0x000500bc,0x0000002f,
38060x00002d64,0x00002d61,0x00002d63,0x000300f7,
38070x00002d6b,0x00000000,0x000400fa,0x00002d64,
38080x00002d65,0x00002d6b,0x000200f8,0x00002d65,
38090x00050051,0x00000027,0x00002d67,0x000031a5,
38100x00000001,0x00050051,0x00000027,0x00002d69,
38110x000031a7,0x00000001,0x000500bc,0x0000002f,
38120x00002d6a,0x00002d67,0x00002d69,0x000200f9,
38130x00002d6b,0x000200f8,0x00002d6b,0x000700f5,
38140x0000002f,0x00002d6c,0x00002d64,0x000027b8,
38150x00002d6a,0x00002d65,0x000300f7,0x00002d73,
38160x00000000,0x000400fa,0x00002d6c,0x00002d6d,
38170x00002d73,0x000200f8,0x00002d6d,0x00050051,
38180x00000027,0x00002d6f,0x000031a5,0x00000002,
38190x00050051,0x00000027,0x00002d71,0x000031a7,
38200x00000002,0x000500bc,0x0000002f,0x00002d72,
38210x00002d6f,0x00002d71,0x000200f9,0x00002d73,
38220x000200f8,0x00002d73,0x000700f5,0x0000002f,
38230x00002d74,0x00002d6c,0x00002d6b,0x00002d72,
38240x00002d6d,0x000300f7,0x000027d2,0x00000000,
38250x000400fa,0x00002d74,0x000027cb,0x000027d2,
38260x000200f8,0x000027cb,0x0007000c,0x0000004b,
38270x000027ce,0x00000001,0x00000025,0x000031a0,
38280x000031a5,0x0007000c,0x0000004b,0x000027d1,
38290x00000001,0x00000028,0x000031a2,0x000031a7,
38300x000200f9,0x000027d2,0x000200f8,0x000027d2,
38310x000700f5,0x0000004b,0x0000328f,0x000031a2,
38320x00002d73,0x000027d1,0x000027cb,0x000700f5,
38330x0000004b,0x0000328a,0x000031a0,0x00002d73,
38340x000027ce,0x000027cb,0x000200f9,0x000027d3,
38350x000200f8,0x000027d3,0x000700f5,0x0000004b,
38360x0000328e,0x000031a2,0x00002784,0x0000328f,
38370x000027d2,0x000700f5,0x0000004b,0x00003289,
38380x000031a0,0x00002784,0x0000328a,0x000027d2,
38390x000700f5,0x0000004b,0x000031e5,0x000032a7,
38400x00002784,0x000031a7,0x000027d2,0x000700f5,
38410x0000004b,0x000031e0,0x000032a5,0x00002784,
38420x000031a5,0x000027d2,0x000700f5,0x00000006,
38430x000031d9,0x00000380,0x00002784,0x000031a3,
38440x000027d2,0x000200f9,0x000027d4,0x000200f8,
38450x000027d4,0x000700f5,0x0000004b,0x0000328b,
38460x0000328c,0x00002783,0x0000328e,0x000027d3,
38470x000700f5,0x0000004b,0x00003286,0x00003287,
38480x00002783,0x00003289,0x000027d3,0x000700f5,
38490x0000004b,0x000031e2,0x000031e3,0x00002783,
38500x000031e5,0x000027d3,0x000700f5,0x0000004b,
38510x000031dd,0x000031de,0x00002783,0x000031e0,
38520x000027d3,0x000700f5,0x00000006,0x000031d2,
38530x00002839,0x00002783,0x000031d9,0x000027d3,
38540x00050084,0x00000006,0x000027d7,0x0000010a,
38550x0000319d,0x00050080,0x00000006,0x000027d8,
38560x0000282d,0x000027d7,0x00050041,0x00000156,
38570x000027d9,0x000000fc,0x000000da,0x0004003d,
38580x00000007,0x000027da,0x000027d9,0x00050051,
38590x00000006,0x00002d8b,0x000027da,0x00000000,
38600x00050095,0x000000ab,0x00002d8d,0x00002d8b,
38610x000027d8,0x00050051,0x00000006,0x00002d8e,
38620x00002d8d,0x00000001,0x00050051,0x00000006,
38630x00002d8f,0x00002d8d,0x00000000,0x00050051,
38640x00000006,0x00002d92,0x000027da,0x00000001,
38650x00050080,0x00000006,0x00002d94,0x00002d92,
38660x00002d8e,0x00050050,0x00000007,0x00002d95,
38670x00002d8f,0x00002d94,0x0004007c,0x00000014,
38680x00002d85,0x00002d95,0x00060041,0x000000db,
38690x00002d7d,0x00002d85,0x000000da,0x000000da,
38700x0005003e,0x00002d7d,0x000031d2,0x00000002,
38710x00000004,0x00050080,0x00000006,0x000027de,
38720x0000282d,0x0000011f,0x00050084,0x00000006,
38730x000027e0,0x00000150,0x0000319d,0x00050080,
38740x00000006,0x000027e1,0x000027de,0x000027e0,
38750x00050051,0x00000027,0x000027e6,0x000031dd,
38760x00000000,0x0004007c,0x00000006,0x00002d9b,
38770x000027e6,0x00050095,0x000000ab,0x00002db6,
38780x00002d8b,0x000027e1,0x00050051,0x00000006,
38790x00002db7,0x00002db6,0x00000001,0x00050051,
38800x00000006,0x00002db8,0x00002db6,0x00000000,
38810x00050080,0x00000006,0x00002dbd,0x00002d92,
38820x00002db7,0x00050050,0x00000007,0x00002dbe,
38830x00002db8,0x00002dbd,0x0004007c,0x00000014,
38840x00002dae,0x00002dbe,0x00060041,0x000000db,
38850x00002da6,0x00002dae,0x000000da,0x000000da,
38860x0005003e,0x00002da6,0x00002d9b,0x00000002,
38870x00000004,0x00050080,0x00000006,0x000027e9,
38880x000027e1,0x0000010a,0x00050051,0x00000027,
38890x000027ed,0x000031dd,0x00000001,0x0004007c,
38900x00000006,0x00002dc4,0x000027ed,0x00050095,
38910x000000ab,0x00002ddf,0x00002d8b,0x000027e9,
38920x00050051,0x00000006,0x00002de0,0x00002ddf,
38930x00000001,0x00050051,0x00000006,0x00002de1,
38940x00002ddf,0x00000000,0x00050080,0x00000006,
38950x00002de6,0x00002d92,0x00002de0,0x00050050,
38960x00000007,0x00002de7,0x00002de1,0x00002de6,
38970x0004007c,0x00000014,0x00002dd7,0x00002de7,
38980x00060041,0x000000db,0x00002dcf,0x00002dd7,
38990x000000da,0x000000da,0x0005003e,0x00002dcf,
39000x00002dc4,0x00000002,0x00000004,0x00050080,
39010x00000006,0x000027f0,0x000027e1,0x00000111,
39020x00050051,0x00000027,0x000027f4,0x000031dd,
39030x00000002,0x0004007c,0x00000006,0x00002ded,
39040x000027f4,0x00050095,0x000000ab,0x00002e08,
39050x00002d8b,0x000027f0,0x00050051,0x00000006,
39060x00002e09,0x00002e08,0x00000001,0x00050051,
39070x00000006,0x00002e0a,0x00002e08,0x00000000,
39080x00050080,0x00000006,0x00002e0f,0x00002d92,
39090x00002e09,0x00050050,0x00000007,0x00002e10,
39100x00002e0a,0x00002e0f,0x0004007c,0x00000014,
39110x00002e00,0x00002e10,0x00060041,0x000000db,
39120x00002df8,0x00002e00,0x000000da,0x000000da,
39130x0005003e,0x00002df8,0x00002ded,0x00000002,
39140x00000004,0x00050080,0x00000006,0x000027f7,
39150x000027e1,0x00000118,0x00050051,0x00000027,
39160x000027fb,0x000031e2,0x00000000,0x0004007c,
39170x00000006,0x00002e16,0x000027fb,0x00050095,
39180x000000ab,0x00002e31,0x00002d8b,0x000027f7,
39190x00050051,0x00000006,0x00002e32,0x00002e31,
39200x00000001,0x00050051,0x00000006,0x00002e33,
39210x00002e31,0x00000000,0x00050080,0x00000006,
39220x00002e38,0x00002d92,0x00002e32,0x00050050,
39230x00000007,0x00002e39,0x00002e33,0x00002e38,
39240x0004007c,0x00000014,0x00002e29,0x00002e39,
39250x00060041,0x000000db,0x00002e21,0x00002e29,
39260x000000da,0x000000da,0x0005003e,0x00002e21,
39270x00002e16,0x00000002,0x00000004,0x00050080,
39280x00000006,0x000027fe,0x000027e1,0x0000011f,
39290x00050051,0x00000027,0x00002802,0x000031e2,
39300x00000001,0x0004007c,0x00000006,0x00002e3f,
39310x00002802,0x00050095,0x000000ab,0x00002e5a,
39320x00002d8b,0x000027fe,0x00050051,0x00000006,
39330x00002e5b,0x00002e5a,0x00000001,0x00050051,
39340x00000006,0x00002e5c,0x00002e5a,0x00000000,
39350x00050080,0x00000006,0x00002e61,0x00002d92,
39360x00002e5b,0x00050050,0x00000007,0x00002e62,
39370x00002e5c,0x00002e61,0x0004007c,0x00000014,
39380x00002e52,0x00002e62,0x00060041,0x000000db,
39390x00002e4a,0x00002e52,0x000000da,0x000000da,
39400x0005003e,0x00002e4a,0x00002e3f,0x00000002,
39410x00000004,0x00050080,0x00000006,0x00002805,
39420x000027e1,0x00000189,0x00050051,0x00000027,
39430x00002809,0x000031e2,0x00000002,0x0004007c,
39440x00000006,0x00002e68,0x00002809,0x00050095,
39450x000000ab,0x00002e83,0x00002d8b,0x00002805,
39460x00050051,0x00000006,0x00002e84,0x00002e83,
39470x00000001,0x00050051,0x00000006,0x00002e85,
39480x00002e83,0x00000000,0x00050080,0x00000006,
39490x00002e8a,0x00002d92,0x00002e84,0x00050050,
39500x00000007,0x00002e8b,0x00002e85,0x00002e8a,
39510x0004007c,0x00000014,0x00002e7b,0x00002e8b,
39520x00060041,0x000000db,0x00002e73,0x00002e7b,
39530x000000da,0x000000da,0x0005003e,0x00002e73,
39540x00002e68,0x00000002,0x00000004,0x000200f9,
39550x0000280b,0x000200f8,0x0000280b,0x00050080,
39560x00000006,0x0000280d,0x0000319d,0x00000154,
39570x000200f9,0x0000272f,0x000200f8,0x0000280e,
39580x000200f9,0x0000280f,0x000200f8,0x0000280f,
39590x000700f5,0x00000006,0x0000319e,0x000000a6,
39600x0000280e,0x0000281e,0x00002813,0x000500b0,
39610x0000002f,0x00002812,0x0000319e,0x0000010a,
39620x000400f6,0x0000281f,0x00002813,0x00000000,
39630x000400fa,0x00002812,0x00002813,0x0000281f,
39640x000200f8,0x00002813,0x00050080,0x00000006,
39650x00002815,0x0000282d,0x000005c6,0x00050084,
39660x00000006,0x00002817,0x0000010a,0x0000319e,
39670x00050080,0x00000006,0x00002818,0x00002815,
39680x00002817,0x00050041,0x00000156,0x00002819,
39690x000000fc,0x000000da,0x0004003d,0x00000007,
39700x0000281a,0x00002819,0x00050051,0x00000006,
39710x00002ea1,0x0000281a,0x00000000,0x00050095,
39720x000000ab,0x00002ea3,0x00002ea1,0x00002818,
39730x00050051,0x00000006,0x00002ea4,0x00002ea3,
39740x00000001,0x00050051,0x00000006,0x00002ea5,
39750x00002ea3,0x00000000,0x00050051,0x00000006,
39760x00002ea8,0x0000281a,0x00000001,0x00050080,
39770x00000006,0x00002eaa,0x00002ea8,0x00002ea4,
39780x00050050,0x00000007,0x00002eab,0x00002ea5,
39790x00002eaa,0x0004007c,0x00000014,0x00002e9b,
39800x00002eab,0x00060041,0x000000db,0x00002e93,
39810x00002e9b,0x000000da,0x000000da,0x0005003e,
39820x00002e93,0x000000a6,0x00000002,0x00000004,
39830x00050080,0x00000006,0x0000281e,0x0000319e,
39840x00000154,0x000200f9,0x0000280f,0x000200f8,
39850x0000281f,0x00050041,0x000000fe,0x00002820,
39860x000000fc,0x0000096c,0x0004003d,0x00000006,
39870x00002821,0x00002820,0x00050080,0x00000006,
39880x00002823,0x00002821,0x00002723,0x00050041,
39890x000000fe,0x00002ef5,0x000000fc,0x000000fd,
39900x0004003d,0x00000006,0x00002ef6,0x00002ef5,
39910x00050084,0x00000006,0x00002ef7,0x0000011f,
39920x00002ef6,0x00050080,0x00000006,0x00002ef8,
39930x00000107,0x00002ef7,0x00050080,0x00000006,
39940x00002efe,0x00002ef6,0x000032a8,0x00050086,
39950x00000006,0x00002eff,0x00002efe,0x00000101,
39960x00050084,0x00000006,0x00002ef1,0x00000107,
39970x00002eff,0x00050080,0x00000006,0x00002ef2,
39980x00002ef8,0x00002ef1,0x00050084,0x00000006,
39990x00002ec2,0x00000150,0x00002823,0x00050080,
40000x00000006,0x00002ec3,0x00002ef2,0x00002ec2,
40010x00050041,0x00000156,0x00002ec4,0x000000fc,
40020x00000154,0x0004003d,0x00000007,0x00002ec5,
40030x00002ec4,0x00050051,0x00000027,0x00002ec8,
40040x000031a0,0x00000000,0x0004007c,0x00000006,
40050x00002f05,0x00002ec8,0x00050051,0x00000006,
40060x00002f1e,0x00002ec5,0x00000000,0x00050095,
40070x000000ab,0x00002f20,0x00002f1e,0x00002ec3,
40080x00050051,0x00000006,0x00002f21,0x00002f20,
40090x00000001,0x00050051,0x00000006,0x00002f22,
40100x00002f20,0x00000000,0x00050051,0x00000006,
40110x00002f25,0x00002ec5,0x00000001,0x00050080,
40120x00000006,0x00002f27,0x00002f25,0x00002f21,
40130x00050050,0x00000007,0x00002f28,0x00002f22,
40140x00002f27,0x0004007c,0x00000014,0x00002f18,
40150x00002f28,0x00060041,0x000000db,0x00002f10,
40160x00002f18,0x000000da,0x000000da,0x0005003e,
40170x00002f10,0x00002f05,0x00000002,0x00000004,
40180x00050080,0x00000006,0x00002ecb,0x00002ec3,
40190x0000010a,0x00050051,0x00000027,0x00002ecf,
40200x000031a0,0x00000001,0x0004007c,0x00000006,
40210x00002f2e,0x00002ecf,0x00050095,0x000000ab,
40220x00002f49,0x00002f1e,0x00002ecb,0x00050051,
40230x00000006,0x00002f4a,0x00002f49,0x00000001,
40240x00050051,0x00000006,0x00002f4b,0x00002f49,
40250x00000000,0x00050080,0x00000006,0x00002f50,
40260x00002f25,0x00002f4a,0x00050050,0x00000007,
40270x00002f51,0x00002f4b,0x00002f50,0x0004007c,
40280x00000014,0x00002f41,0x00002f51,0x00060041,
40290x000000db,0x00002f39,0x00002f41,0x000000da,
40300x000000da,0x0005003e,0x00002f39,0x00002f2e,
32500x00000002,0x00000004,0x00050080,0x00000006, 40310x00000002,0x00000004,0x00050080,0x00000006,
32510x000023b5,0x000023a6,0x0000010e,0x00050051, 40320x00002ed2,0x00002ec3,0x00000111,0x00050051,
32520x00000027,0x000023b9,0x00002ac7,0x00000002, 40330x00000027,0x00002ed6,0x000031a0,0x00000002,
32530x0004007c,0x00000006,0x0000272f,0x000023b9, 40340x0004007c,0x00000006,0x00002f57,0x00002ed6,
32540x00050095,0x000000a8,0x0000274a,0x000026cd, 40350x00050095,0x000000ab,0x00002f72,0x00002f1e,
32550x000023b5,0x00050051,0x00000006,0x0000274b, 40360x00002ed2,0x00050051,0x00000006,0x00002f73,
32560x0000274a,0x00000001,0x00050051,0x00000006, 40370x00002f72,0x00000001,0x00050051,0x00000006,
32570x0000274c,0x0000274a,0x00000000,0x00050080, 40380x00002f74,0x00002f72,0x00000000,0x00050080,
32580x00000006,0x00002751,0x000026d4,0x0000274b, 40390x00000006,0x00002f79,0x00002f25,0x00002f73,
32590x00050050,0x00000007,0x00002752,0x0000274c, 40400x00050050,0x00000007,0x00002f7a,0x00002f74,
32600x00002751,0x0004007c,0x00000014,0x00002742, 40410x00002f79,0x0004007c,0x00000014,0x00002f6a,
32610x00002752,0x00060041,0x000000d8,0x0000273a, 40420x00002f7a,0x00060041,0x000000db,0x00002f62,
32620x00002742,0x000000d7,0x000000d7,0x0005003e, 40430x00002f6a,0x000000da,0x000000da,0x0005003e,
32630x0000273a,0x0000272f,0x00000002,0x00000004, 40440x00002f62,0x00002f57,0x00000002,0x00000004,
32640x00050080,0x00000006,0x000023bc,0x000023a6, 40450x00050080,0x00000006,0x00002ed9,0x00002ec3,
32650x00000115,0x00050051,0x00000027,0x000023c0, 40460x00000118,0x00050051,0x00000027,0x00002edd,
32660x00002ac9,0x00000000,0x0004007c,0x00000006, 40470x000031a2,0x00000000,0x0004007c,0x00000006,
32670x00002758,0x000023c0,0x00050095,0x000000a8, 40480x00002f80,0x00002edd,0x00050095,0x000000ab,
32680x00002773,0x000026cd,0x000023bc,0x00050051, 40490x00002f9b,0x00002f1e,0x00002ed9,0x00050051,
32690x00000006,0x00002774,0x00002773,0x00000001, 40500x00000006,0x00002f9c,0x00002f9b,0x00000001,
32700x00050051,0x00000006,0x00002775,0x00002773, 40510x00050051,0x00000006,0x00002f9d,0x00002f9b,
32710x00000000,0x00050080,0x00000006,0x0000277a, 40520x00000000,0x00050080,0x00000006,0x00002fa2,
32720x000026d4,0x00002774,0x00050050,0x00000007, 40530x00002f25,0x00002f9c,0x00050050,0x00000007,
32730x0000277b,0x00002775,0x0000277a,0x0004007c, 40540x00002fa3,0x00002f9d,0x00002fa2,0x0004007c,
32740x00000014,0x0000276b,0x0000277b,0x00060041, 40550x00000014,0x00002f93,0x00002fa3,0x00060041,
32750x000000d8,0x00002763,0x0000276b,0x000000d7, 40560x000000db,0x00002f8b,0x00002f93,0x000000da,
32760x000000d7,0x0005003e,0x00002763,0x00002758, 40570x000000da,0x0005003e,0x00002f8b,0x00002f80,
32770x00000002,0x00000004,0x00050080,0x00000006, 40580x00000002,0x00000004,0x00050080,0x00000006,
32780x000023c3,0x000023a6,0x0000011c,0x00050051, 40590x00002ee0,0x00002ec3,0x0000011f,0x00050051,
32790x00000027,0x000023c7,0x00002ac9,0x00000001, 40600x00000027,0x00002ee4,0x000031a2,0x00000001,
32800x0004007c,0x00000006,0x00002781,0x000023c7, 40610x0004007c,0x00000006,0x00002fa9,0x00002ee4,
32810x00050095,0x000000a8,0x0000279c,0x000026cd, 40620x00050095,0x000000ab,0x00002fc4,0x00002f1e,
32820x000023c3,0x00050051,0x00000006,0x0000279d, 40630x00002ee0,0x00050051,0x00000006,0x00002fc5,
32830x0000279c,0x00000001,0x00050051,0x00000006, 40640x00002fc4,0x00000001,0x00050051,0x00000006,
32840x0000279e,0x0000279c,0x00000000,0x00050080, 40650x00002fc6,0x00002fc4,0x00000000,0x00050080,
32850x00000006,0x000027a3,0x000026d4,0x0000279d, 40660x00000006,0x00002fcb,0x00002f25,0x00002fc5,
32860x00050050,0x00000007,0x000027a4,0x0000279e, 40670x00050050,0x00000007,0x00002fcc,0x00002fc6,
32870x000027a3,0x0004007c,0x00000014,0x00002794, 40680x00002fcb,0x0004007c,0x00000014,0x00002fbc,
32880x000027a4,0x00060041,0x000000d8,0x0000278c, 40690x00002fcc,0x00060041,0x000000db,0x00002fb4,
32890x00002794,0x000000d7,0x000000d7,0x0005003e, 40700x00002fbc,0x000000da,0x000000da,0x0005003e,
32900x0000278c,0x00002781,0x00000002,0x00000004, 40710x00002fb4,0x00002fa9,0x00000002,0x00000004,
32910x00050080,0x00000006,0x000023ca,0x000023a6, 40720x00050080,0x00000006,0x00002ee7,0x00002ec3,
32920x00000186,0x00050051,0x00000027,0x000023ce, 40730x00000189,0x00050051,0x00000027,0x00002eeb,
32930x00002ac9,0x00000002,0x0004007c,0x00000006, 40740x000031a2,0x00000002,0x0004007c,0x00000006,
32940x000027aa,0x000023ce,0x00050095,0x000000a8, 40750x00002fd2,0x00002eeb,0x00050095,0x000000ab,
32950x000027c5,0x000026cd,0x000023ca,0x00050051, 40760x00002fed,0x00002f1e,0x00002ee7,0x00050051,
32960x00000006,0x000027c6,0x000027c5,0x00000001, 40770x00000006,0x00002fee,0x00002fed,0x00000001,
32970x00050051,0x00000006,0x000027c7,0x000027c5, 40780x00050051,0x00000006,0x00002fef,0x00002fed,
32980x00000000,0x00050080,0x00000006,0x000027cc, 40790x00000000,0x00050080,0x00000006,0x00002ff4,
32990x000026d4,0x000027c6,0x00050050,0x00000007, 40800x00002f25,0x00002fee,0x00050050,0x00000007,
33000x000027cd,0x000027c7,0x000027cc,0x0004007c, 40810x00002ff5,0x00002fef,0x00002ff4,0x0004007c,
33010x00000014,0x000027bd,0x000027cd,0x00060041, 40820x00000014,0x00002fe5,0x00002ff5,0x00060041,
33020x000000d8,0x000027b5,0x000027bd,0x000000d7, 40830x000000db,0x00002fdd,0x00002fe5,0x000000da,
33030x000000d7,0x0005003e,0x000027b5,0x000027aa, 40840x000000da,0x0005003e,0x00002fdd,0x00002fd2,
33040x00000002,0x00000004,0x000200f9,0x000023d0, 40850x00000002,0x00000004,0x000200f9,0x00000bed,
33050x000200f8,0x000023d0,0x00050080,0x00000006, 40860x000200f8,0x00000bed,0x000200f9,0x00000be4,
33060x000023d2,0x00002aa5,0x00000151,0x000200f9, 40870x000200f8,0x00000be4,0x000200f9,0x00000bdb,
33070x0000233e,0x000200f8,0x000023d3,0x000200f9, 40880x000200f8,0x00000bdb,0x000200f9,0x00000bd2,
33080x000023d4,0x000200f8,0x000023d4,0x000700f5, 40890x000200f8,0x00000bd2,0x000200f9,0x00000bac,
33090x00000006,0x00002aa6,0x000000a3,0x000023d3, 40900x000200f8,0x00000bac,0x000200f9,0x00000b97,
33100x000023e3,0x000023d8,0x000500b0,0x0000002f, 40910x000200f8,0x00000b97,0x000200f9,0x00000bf3,
33110x000023d7,0x00002aa6,0x00000107,0x000400f6, 40920x000200f8,0x00000bf3,0x000100fd,0x00010038}
33120x000023e4,0x000023d8,0x00000000,0x000400fa,
33130x000023d7,0x000023d8,0x000023e4,0x000200f8,
33140x000023d8,0x00050080,0x00000006,0x000023da,
33150x000023f2,0x000005c3,0x00050084,0x00000006,
33160x000023dc,0x00000107,0x00002aa6,0x00050080,
33170x00000006,0x000023dd,0x000023da,0x000023dc,
33180x00050041,0x00000153,0x000023de,0x000000f9,
33190x000000d7,0x0004003d,0x00000007,0x000023df,
33200x000023de,0x00050051,0x00000006,0x000027e3,
33210x000023df,0x00000000,0x00050095,0x000000a8,
33220x000027e5,0x000027e3,0x000023dd,0x00050051,
33230x00000006,0x000027e6,0x000027e5,0x00000001,
33240x00050051,0x00000006,0x000027e7,0x000027e5,
33250x00000000,0x00050051,0x00000006,0x000027ea,
33260x000023df,0x00000001,0x00050080,0x00000006,
33270x000027ec,0x000027ea,0x000027e6,0x00050050,
33280x00000007,0x000027ed,0x000027e7,0x000027ec,
33290x0004007c,0x00000014,0x000027dd,0x000027ed,
33300x00060041,0x000000d8,0x000027d5,0x000027dd,
33310x000000d7,0x000000d7,0x0005003e,0x000027d5,
33320x000000a3,0x00000002,0x00000004,0x00050080,
33330x00000006,0x000023e3,0x00002aa6,0x00000151,
33340x000200f9,0x000023d4,0x000200f8,0x000023e4,
33350x00050041,0x000000fb,0x000023e5,0x000000f9,
33360x000008bc,0x0004003d,0x00000006,0x000023e6,
33370x000023e5,0x00050080,0x00000006,0x000023e8,
33380x000023e6,0x00002332,0x00050041,0x000000fb,
33390x00002837,0x000000f9,0x000000fa,0x0004003d,
33400x00000006,0x00002838,0x00002837,0x00050084,
33410x00000006,0x00002839,0x0000011c,0x00002838,
33420x00050080,0x00000006,0x0000283a,0x00000104,
33430x00002839,0x00050080,0x00000006,0x00002840,
33440x00002838,0x00002b67,0x00050086,0x00000006,
33450x00002841,0x00002840,0x000000fe,0x00050084,
33460x00000006,0x00002833,0x00000104,0x00002841,
33470x00050080,0x00000006,0x00002834,0x0000283a,
33480x00002833,0x00050084,0x00000006,0x00002804,
33490x0000014d,0x000023e8,0x00050080,0x00000006,
33500x00002805,0x00002834,0x00002804,0x00050041,
33510x00000153,0x00002806,0x000000f9,0x00000151,
33520x0004003d,0x00000007,0x00002807,0x00002806,
33530x00050051,0x00000027,0x0000280a,0x00002aa8,
33540x00000000,0x0004007c,0x00000006,0x00002847,
33550x0000280a,0x00050051,0x00000006,0x00002860,
33560x00002807,0x00000000,0x00050095,0x000000a8,
33570x00002862,0x00002860,0x00002805,0x00050051,
33580x00000006,0x00002863,0x00002862,0x00000001,
33590x00050051,0x00000006,0x00002864,0x00002862,
33600x00000000,0x00050051,0x00000006,0x00002867,
33610x00002807,0x00000001,0x00050080,0x00000006,
33620x00002869,0x00002867,0x00002863,0x00050050,
33630x00000007,0x0000286a,0x00002864,0x00002869,
33640x0004007c,0x00000014,0x0000285a,0x0000286a,
33650x00060041,0x000000d8,0x00002852,0x0000285a,
33660x000000d7,0x000000d7,0x0005003e,0x00002852,
33670x00002847,0x00000002,0x00000004,0x00050080,
33680x00000006,0x0000280d,0x00002805,0x00000107,
33690x00050051,0x00000027,0x00002811,0x00002aa8,
33700x00000001,0x0004007c,0x00000006,0x00002870,
33710x00002811,0x00050095,0x000000a8,0x0000288b,
33720x00002860,0x0000280d,0x00050051,0x00000006,
33730x0000288c,0x0000288b,0x00000001,0x00050051,
33740x00000006,0x0000288d,0x0000288b,0x00000000,
33750x00050080,0x00000006,0x00002892,0x00002867,
33760x0000288c,0x00050050,0x00000007,0x00002893,
33770x0000288d,0x00002892,0x0004007c,0x00000014,
33780x00002883,0x00002893,0x00060041,0x000000d8,
33790x0000287b,0x00002883,0x000000d7,0x000000d7,
33800x0005003e,0x0000287b,0x00002870,0x00000002,
33810x00000004,0x00050080,0x00000006,0x00002814,
33820x00002805,0x0000010e,0x00050051,0x00000027,
33830x00002818,0x00002aa8,0x00000002,0x0004007c,
33840x00000006,0x00002899,0x00002818,0x00050095,
33850x000000a8,0x000028b4,0x00002860,0x00002814,
33860x00050051,0x00000006,0x000028b5,0x000028b4,
33870x00000001,0x00050051,0x00000006,0x000028b6,
33880x000028b4,0x00000000,0x00050080,0x00000006,
33890x000028bb,0x00002867,0x000028b5,0x00050050,
33900x00000007,0x000028bc,0x000028b6,0x000028bb,
33910x0004007c,0x00000014,0x000028ac,0x000028bc,
33920x00060041,0x000000d8,0x000028a4,0x000028ac,
33930x000000d7,0x000000d7,0x0005003e,0x000028a4,
33940x00002899,0x00000002,0x00000004,0x00050080,
33950x00000006,0x0000281b,0x00002805,0x00000115,
33960x00050051,0x00000027,0x0000281f,0x00002aaa,
33970x00000000,0x0004007c,0x00000006,0x000028c2,
33980x0000281f,0x00050095,0x000000a8,0x000028dd,
33990x00002860,0x0000281b,0x00050051,0x00000006,
34000x000028de,0x000028dd,0x00000001,0x00050051,
34010x00000006,0x000028df,0x000028dd,0x00000000,
34020x00050080,0x00000006,0x000028e4,0x00002867,
34030x000028de,0x00050050,0x00000007,0x000028e5,
34040x000028df,0x000028e4,0x0004007c,0x00000014,
34050x000028d5,0x000028e5,0x00060041,0x000000d8,
34060x000028cd,0x000028d5,0x000000d7,0x000000d7,
34070x0005003e,0x000028cd,0x000028c2,0x00000002,
34080x00000004,0x00050080,0x00000006,0x00002822,
34090x00002805,0x0000011c,0x00050051,0x00000027,
34100x00002826,0x00002aaa,0x00000001,0x0004007c,
34110x00000006,0x000028eb,0x00002826,0x00050095,
34120x000000a8,0x00002906,0x00002860,0x00002822,
34130x00050051,0x00000006,0x00002907,0x00002906,
34140x00000001,0x00050051,0x00000006,0x00002908,
34150x00002906,0x00000000,0x00050080,0x00000006,
34160x0000290d,0x00002867,0x00002907,0x00050050,
34170x00000007,0x0000290e,0x00002908,0x0000290d,
34180x0004007c,0x00000014,0x000028fe,0x0000290e,
34190x00060041,0x000000d8,0x000028f6,0x000028fe,
34200x000000d7,0x000000d7,0x0005003e,0x000028f6,
34210x000028eb,0x00000002,0x00000004,0x00050080,
34220x00000006,0x00002829,0x00002805,0x00000186,
34230x00050051,0x00000027,0x0000282d,0x00002aaa,
34240x00000002,0x0004007c,0x00000006,0x00002914,
34250x0000282d,0x00050095,0x000000a8,0x0000292f,
34260x00002860,0x00002829,0x00050051,0x00000006,
34270x00002930,0x0000292f,0x00000001,0x00050051,
34280x00000006,0x00002931,0x0000292f,0x00000000,
34290x00050080,0x00000006,0x00002936,0x00002867,
34300x00002930,0x00050050,0x00000007,0x00002937,
34310x00002931,0x00002936,0x0004007c,0x00000014,
34320x00002927,0x00002937,0x00060041,0x000000d8,
34330x0000291f,0x00002927,0x000000d7,0x000000d7,
34340x0005003e,0x0000291f,0x00002914,0x00000002,
34350x00000004,0x000200f9,0x00000a68,0x000200f8,
34360x00000a68,0x000200f9,0x00000a5f,0x000200f8,
34370x00000a5f,0x000200f9,0x00000a56,0x000200f8,
34380x00000a56,0x000200f9,0x00000a4d,0x000200f8,
34390x00000a4d,0x000200f9,0x00000a27,0x000200f8,
34400x00000a27,0x000200f9,0x00000a6e,0x000200f8,
34410x00000a6e,0x000100fd,0x00010038}
diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp
new file mode 100644
index 000000000..733e37cac
--- /dev/null
+++ b/runtime/test/allocator_proxy_test.cpp
@@ -0,0 +1,382 @@
1// Xbox-ABI command allocator proxies (d3d12_xs_device.h, device slot 9) behind the device proxy, on the Vulkan-backed
2// device and on the host PC runtime (WARP, and the first hardware adapter when there is one):
3// - Vulkan device: slot 9 wraps the allocator; the public chain (9 slots) is forwarded with the real allocator's
4// answers, every slot past it up to the end of the table is refused (E_NOTIMPL), and a read past the table faults
5// in the guard region and is counted;
6// - QueryInterface identity, GetDevice -> the device proxy, references and release orders;
7// - a command list created on the proxy and Reset on it (the Vulkan layer resolves the proxy), recording a buffer
8// copy that runs through the queue and fence proxies and is read back, twice, with the allocator Reset between;
9// and D3D12's allocator rules through the proxy (Reset while a list records: E_FAIL; a second list on a busy
10// allocator: E_INVALIDARG);
11// - MakeResident/Evict with an allocator proxy give the real allocator's HRESULT;
12// - host runtime: slot 9 hands out the PC allocator unwrapped (its lists could not resolve a proxy), and the same
13// copy works.
14// LEONIDA_VK_VALIDATION=1 runs the Vulkan device under VK_LAYER_KHRONOS_validation with synchronization validation;
15// any validation error fails the test. Exits 77 when neither a host D3D12 device nor a Vulkan device can be made.
16// No shaders, game data or Xbox DLLs.
17#include "vk_test_device.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_xs_device.h"
20
21#include <d3d12.h>
22#include <dxgi1_4.h>
23
24#include <cstdint>
25#include <cstdio>
26#include <cstring>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \
30} while (0)
31
32namespace {
33
34namespace xs = rt::d3d12_xs;
35
36template <class T>
37struct Ref {
38 T* p = nullptr;
39 Ref() = default;
40 Ref(const Ref&) = delete;
41 Ref& operator=(const Ref&) = delete;
42 ~Ref() { reset(); }
43 void reset() {
44 if (p) p->Release();
45 p = nullptr;
46 }
47 T* operator->() const { return p; }
48};
49
50struct Backend {
51 const char* label;
52 ID3D12Device* device; // the device proxy
53 ID3D12Device* real; // the device behind it (PC runtime or Vulkan layer)
54 bool vulkan;
55};
56
57using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
58 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
59 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t);
60
61// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks.
62HRESULT call_slot(void* object, unsigned slot) {
63 void** vtable = *reinterpret_cast<void***>(object);
64 return static_cast<HRESULT>(static_cast<std::uint32_t>(
65 reinterpret_cast<SlotFn>(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)));
66}
67
68ULONG_PTR g_fault_address = 0;
69
70int record_fault(EXCEPTION_POINTERS* info) {
71 g_fault_address = info->ExceptionRecord->NumberParameters >= 2 ? info->ExceptionRecord->ExceptionInformation[1] : 0;
72 return EXCEPTION_EXECUTE_HANDLER;
73}
74
75// The read in a function of its own: clang-cl's __try only catches a fault raised inside a call.
76__declspec(noinline) void* read_entry(void* const* vtable, unsigned slot) {
77 return *static_cast<void* const volatile*>(&vtable[slot]);
78}
79
80// Reads vtable[slot] the way a call through it does. The exception code, or 0 when the read worked.
81DWORD read_slot_guarded(void* const* vtable, unsigned slot) {
82 g_fault_address = 0;
83 __try {
84 void* volatile entry = read_entry(vtable, slot);
85 (void)entry;
86 return 0;
87 } __except (record_fault(GetExceptionInformation())) {
88 return GetExceptionCode();
89 }
90}
91
92int wait_for(const char* label, ID3D12Fence* fence, UINT64 value) {
93 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
94 EXPECT(event != nullptr);
95 const bool set = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 5000) == 0;
96 CloseHandle(event);
97 EXPECT(set && fence->GetCompletedValue() >= value);
98 return 0;
99}
100
101int make_buffer(const char* label, ID3D12Device* device, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state,
102 Ref<ID3D12Resource>& out) {
103 D3D12_HEAP_PROPERTIES heap{};
104 heap.Type = heap_type;
105 D3D12_RESOURCE_DESC desc{};
106 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
107 desc.Width = 256;
108 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
109 desc.SampleDesc.Count = 1;
110 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
111 EXPECT(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
112 IID_PPV_ARGS(&out.p))));
113 return 0;
114}
115
116// One recording on `list` (open, recording into the allocator): 256 bytes of `byte` copied from an upload buffer to a
117// readback buffer, executed through the queue proxy, finished through the fence proxy at `value`, then compared.
118int copy_round(const char* label, ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence,
119 ID3D12GraphicsCommandList* list, std::uint8_t byte, UINT64 value) {
120 Ref<ID3D12Resource> upload, readback;
121 if (make_buffer(label, device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, upload)) return 1;
122 if (make_buffer(label, device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return 1;
123 void* mapped = nullptr;
124 EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped)) && mapped);
125 std::memset(mapped, byte, 256);
126 upload->Unmap(0, nullptr);
127 list->CopyBufferRegion(readback.p, 0, upload.p, 0, 256);
128 EXPECT(SUCCEEDED(list->Close()));
129 ID3D12CommandList* lists[] = {list};
130 queue->ExecuteCommandLists(1, lists);
131 EXPECT(SUCCEEDED(queue->Signal(fence, value)));
132 if (wait_for(label, fence, value)) return 1;
133 const D3D12_RANGE read{0, 256};
134 EXPECT(SUCCEEDED(readback->Map(0, &read, &mapped)) && mapped);
135 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
136 int wrong = 0;
137 for (int i = 0; i < 256; ++i) wrong += bytes[i] != byte;
138 const D3D12_RANGE none{0, 0};
139 readback->Unmap(0, &none);
140 EXPECT(wrong == 0);
141 return 0;
142}
143
144// ---- 1. The proxy itself: slots, identity, guard (Vulkan device) ----
145
146int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) {
147 const char* label = b.label;
148 ID3D12CommandAllocator* real = xs::allocator_proxy_real_allocator(allocator);
149 EXPECT(real && static_cast<void*>(real) != static_cast<void*>(allocator));
150 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9);
151 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
152
153 // QueryInterface: the base chain and the allocator itself answer with the proxy; anything else is refused.
154 const IID modelled[] = {__uuidof(IUnknown), __uuidof(ID3D12Object), __uuidof(ID3D12DeviceChild),
155 __uuidof(ID3D12Pageable), __uuidof(ID3D12CommandAllocator)};
156 for (const IID& iid : modelled) {
157 void* same = nullptr;
158 EXPECT(SUCCEEDED(allocator->QueryInterface(iid, &same)) && same == allocator);
159 static_cast<IUnknown*>(same)->Release();
160 }
161 void* other = reinterpret_cast<void*>(1);
162 EXPECT(allocator->QueryInterface(__uuidof(ID3D12Fence), &other) == E_NOINTERFACE && !other);
163 other = reinterpret_cast<void*>(1); // the Vulkan layer's private tag: not modelled, the real object stays hidden
164 EXPECT(allocator->QueryInterface(xs::kLeonidaCommandAllocatorTag, &other) == E_NOINTERFACE && !other);
165 EXPECT(xs::command_object_proxy_ref_count(allocator) == 1);
166
167 ID3D12Device* owner = nullptr;
168 EXPECT(SUCCEEDED(allocator->GetDevice(IID_PPV_ARGS(&owner))) && owner == b.device);
169 owner->Release();
170 // Private data and SetName go to the real allocator; the proxy pointer round-trips as an interface.
171 EXPECT(SUCCEEDED(allocator->SetName(L"leonida allocator proxy")));
172 constexpr GUID key{0x2a6b8c41, 0x77d2, 0x4e19, {0x9c, 0x3a, 0x51, 0xe0, 0x8f, 0x24, 0x6d, 0x0b}};
173 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, allocator)));
174 IUnknown* back = nullptr;
175 UINT size = sizeof(back);
176 EXPECT(SUCCEEDED(allocator->GetPrivateData(key, &size, &back)) && back == allocator);
177 back->Release();
178 EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr)));
179
180 // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted.
181 const unsigned table = xs::allocator_proxy_table_size();
182 EXPECT(table == 64);
183 for (unsigned slot = 9; slot < table; ++slot) {
184 const std::uint64_t before = xs::allocator_slot_hits(slot);
185 EXPECT(call_slot(allocator, slot) == E_NOTIMPL);
186 EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot));
187 }
188
189 // Past the table: the vtable read itself faults in the guard region, at the slot's address, and is counted.
190 EXPECT(xs::command_object_tables_guarded());
191 void* const* vtable = *reinterpret_cast<void* const* const*>(allocator);
192 EXPECT(read_slot_guarded(vtable, table - 1) == 0);
193 for (unsigned slot : {table, table + 512, table + 7000}) {
194 const std::uint64_t before = xs::allocator_table_overruns();
195 EXPECT(read_slot_guarded(vtable, slot) == EXCEPTION_ACCESS_VIOLATION);
196 EXPECT(g_fault_address == reinterpret_cast<ULONG_PTR>(&vtable[slot]));
197 EXPECT(xs::allocator_table_overruns() == before + 1);
198 }
199 std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read "
200 "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1);
201 return 0;
202}
203
204// ---- 2. Lists on the allocator, GPU work, D3D12's allocator rules, residency ----
205
206int check_backend(const Backend& b) {
207 const char* label = b.label;
208 const unsigned long device_refs = xs::device_proxy_ref_count(b.device);
209 {
210 Ref<ID3D12CommandAllocator> allocator;
211 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
212 IID_PPV_ARGS(&allocator.p))));
213 // Vulkan layer: wrapped. Host runtime: its lists could not resolve a proxy, so the PC allocator comes back.
214 EXPECT(xs::is_allocator_proxy(allocator.p) == b.vulkan);
215 if (b.vulkan && check_proxy(b, allocator.p)) return 1;
216 // As IUnknown, and without an output (the device's own answer), as slot 8 does for queues.
217 Ref<IUnknown> as_unknown;
218 EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(IUnknown),
219 reinterpret_cast<void**>(&as_unknown.p))));
220 EXPECT(xs::is_allocator_proxy(as_unknown.p) == b.vulkan);
221#pragma warning(suppress : 6387) // the null output on purpose
222 EXPECT(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
223 nullptr) ==
224 b.real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
225 nullptr));
226 Ref<ID3D12Fence> not_an_allocator; // asked for an interface the allocator does not have
227 not_an_allocator.p = reinterpret_cast<ID3D12Fence*>(1);
228 const HRESULT wrong_iid = b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
229 IID_PPV_ARGS(&not_an_allocator.p));
230 const bool cleared = !not_an_allocator.p;
231 not_an_allocator.p = nullptr;
232 EXPECT(FAILED(wrong_iid) && cleared);
233
234 D3D12_COMMAND_QUEUE_DESC queue_desc{};
235 Ref<ID3D12CommandQueue> queue;
236 Ref<ID3D12Fence> fence;
237 EXPECT(SUCCEEDED(b.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
238 EXPECT(SUCCEEDED(b.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
239 EXPECT(xs::is_queue_proxy(queue.p) && xs::is_fence_proxy(fence.p));
240
241 // A list on the allocator: the Vulkan layer resolves the proxy in CreateCommandList.
242 Ref<ID3D12GraphicsCommandList> list;
243 EXPECT(SUCCEEDED(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
244 IID_PPV_ARGS(&list.p))));
245 // D3D12's rules, through the proxy: a recording list holds the allocator.
246 const std::uint64_t resets_before = xs::allocator_slot_hits(8);
247 EXPECT(allocator->Reset() == E_FAIL);
248 Ref<ID3D12GraphicsCommandList> second;
249 EXPECT(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
250 IID_PPV_ARGS(&second.p)) == E_INVALIDARG && !second.p);
251 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0x5a, 1)) return 1;
252
253 // Done on the GPU: the allocator resets through the proxy, and the list resets onto it (Reset resolves it).
254 EXPECT(SUCCEEDED(allocator->Reset()));
255 EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
256 if (copy_round(label, b.device, queue.p, fence.p, list.p, 0xa5, 2)) return 1;
257 // The two allocator Reset calls above went through slot 8 (list->Reset is the list's method, not this one).
258 if (b.vulkan) EXPECT(xs::allocator_slot_hits(8) == resets_before + 2);
259
260 // Residency: the real runtime gets the real allocator (an allocator is a pageable).
261 ID3D12Pageable* pageable = allocator.p;
262 ID3D12CommandAllocator* real_allocator =
263 b.vulkan ? xs::allocator_proxy_real_allocator(allocator.p) : allocator.p;
264 ID3D12Pageable* real_pageable = real_allocator;
265 EXPECT(b.device->MakeResident(1, &pageable) == b.real->MakeResident(1, &real_pageable));
266 EXPECT(b.device->Evict(1, &pageable) == b.real->Evict(1, &real_pageable));
267
268 // Release orders: the allocator first while its (closed) list still exists, then the list.
269 if (b.vulkan) EXPECT(xs::command_object_proxy_ref_count(allocator.p) == 1);
270 allocator.reset();
271 list.reset();
272 }
273 EXPECT(xs::device_proxy_ref_count(b.device) == device_refs); // nothing the proxies made kept the device
274 std::printf("%s: CreateCommandAllocator %s; a list created and Reset on it, two GPU copies through the queue and "
275 "fence proxies read back exactly; allocator rules and residency as on the real allocator\n", label,
276 b.vulkan ? "returns an allocator proxy" : "returns the PC allocator unwrapped");
277 return 0;
278}
279
280int run_host(IDXGIAdapter1* adapter, const char* label) {
281 ID3D12Device* real = nullptr;
282 if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) {
283 std::printf("%s: no D3D12 device, skipped\n", label);
284 return 77;
285 }
286 real->AddRef(); // the backend's own reference; the proxy takes the other
287 Ref<ID3D12Device> device;
288 if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device.p)))) {
289 real->Release();
290 real->Release();
291 std::fprintf(stderr, "%s: device proxy creation failed\n", label);
292 return 1;
293 }
294 const int result = check_backend(Backend{label, device.p, real, false});
295 device.reset();
296 if (result) return 1;
297 if (real->Release() != 0) {
298 std::fprintf(stderr, "%s: the PC device outlives its proxies\n", label);
299 return 1;
300 }
301 return 0;
302}
303
304} // namespace
305
306// A failure ends the process with a message on stderr, never in a dialog a test run would wait on.
307static void no_dialogs() {
308 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
309 SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
310}
311
312int main() {
313 no_dialogs();
314 std::setvbuf(stdout, nullptr, _IONBF, 0);
315 const char* label = "allocator_proxy_test";
316 int ran = 0;
317
318 // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the
319 // PC runtime the proxy is written against, so only Vulkan runs there.
320 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
321 Ref<IDXGIFactory4> factory;
322 if (wine) std::printf("host D3D12: under Wine, skipped\n");
323 if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) {
324 Ref<IDXGIAdapter1> warp;
325 if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) {
326 const int r = run_host(warp.p, "host WARP");
327 if (r == 1) return 1;
328 ran += r == 0;
329 }
330 for (UINT i = 0;; ++i) {
331 Ref<IDXGIAdapter1> adapter;
332 if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break;
333 DXGI_ADAPTER_DESC1 desc{};
334 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
335 char name[128] = {};
336 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr);
337 char host_label[160];
338 std::snprintf(host_label, sizeof(host_label), "host %s", name);
339 const int r = run_host(adapter.p, host_label);
340 if (r == 1) return 1;
341 ran += r == 0;
342 break;
343 }
344 }
345
346 // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan.
347 vktest::Device d;
348 if (d.create()) {
349 label = "Vulkan";
350 rt::d3d12::VulkanDeviceInfo info{};
351 info.get_instance_proc = d.instance_proc;
352 info.instance = d.instance;
353 info.physical = d.physical;
354 info.device = d.device;
355 info.queue = d.queue;
356 info.queue_family = d.family;
357 ID3D12Device* inner = nullptr;
358 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
359 inner->AddRef(); // the backend's own reference; the proxy takes the other
360 ID3D12Device* device = nullptr;
361 EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device))));
362 rt::d3d12::set_device_outer(inner, device);
363 const int result = check_backend(Backend{label, device, inner, true});
364 device->Release();
365 if (result) return 1;
366 EXPECT(inner->Release() == 0); // nothing the proxies made kept the layer's device alive
367 ++ran;
368 if (d.validation_errors()) {
369 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
370 return 1;
371 }
372 } else {
373 std::printf("Vulkan: no device, skipped\n");
374 }
375
376 if (!ran) {
377 std::printf("SKIP allocator_proxy_test: neither a host D3D12 device nor a Vulkan device\n");
378 return 77;
379 }
380 std::printf("allocator_proxy_test: %d backend(s) passed\n", ran);
381 return 0;
382}
diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp
index 469274d56..07715f01e 100644
--- a/runtime/test/bindless_sizing_test.cpp
+++ b/runtime/test/bindless_sizing_test.cpp
@@ -172,6 +172,37 @@ int main() {
172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096); 172 EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096);
173 } 173 }
174 174
175 // D3D-219: past maxPerSetDescriptors, growth follows layout_supported (vkGetDescriptorSetLayoutSupport), which
176 // is asked only above that limit. Intel's Xe-LP reports 6159 and supports the full sizes.
177 {
178 Device d = uniform(1048576, 1048576);
179 d.v11.maxPerSetDescriptors = 6159;
180 d.limits.maxSamplerAllocationCount = 4000;
181 unsigned asked = 0, asked_within = 0;
182 const auto all_supported = [&](const BindlessFeatures& candidate) {
183 ++asked;
184 asked_within += totals(candidate).all <= 6159;
185 return true;
186 };
187 BindlessFeatures f = with_ms(true);
188 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported));
189 EXPECT(asked > 0 && asked_within == 0);
190 EXPECT(count(f, D::dim_2d) == bindless::max_2d_images &&
191 f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers);
192 EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f));
193
194 // A driver that supports less: growth stops where it says no.
195 const auto up_to_20000 = [&](const BindlessFeatures& candidate) { return totals(candidate).all <= 20000; };
196 f = with_ms(true);
197 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, up_to_20000));
198 EXPECT(totals(f).all <= 20000 && totals(f).all > 6159 && count(f, D::dim_2d) > 4096);
199
200 // Without the callback, maxPerSetDescriptors still caps growth as before.
201 f = with_ms(true);
202 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12));
203 EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024));
204 }
205
175 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get. 206 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get.
176 EXPECT(BindlessFeatures{}.counts == defaults); 207 EXPECT(BindlessFeatures{}.counts == defaults);
177 std::printf("bindless sizing: synthetic limits gave the expected counts\n"); 208 std::printf("bindless sizing: synthetic limits gave the expected counts\n");
diff --git a/runtime/test/bink_audio_test.cpp b/runtime/test/bink_audio_test.cpp
index 2156e5eff..8616d9165 100644
--- a/runtime/test/bink_audio_test.cpp
+++ b/runtime/test/bink_audio_test.cpp
@@ -237,7 +237,7 @@ int main() {
237 header.flags[i]); 237 header.flags[i]);
238 if (!header.audio_tracks) { 238 if (!header.audio_tracks) {
239 std::printf("SKIP (movie has no audio tracks)\n"); 239 std::printf("SKIP (movie has no audio tracks)\n");
240 return 0; 240 return 77; // nothing was checked: a ctest SKIP (SKIP_RETURN_CODE 77), not a pass
241 } 241 }
242 242
243 try { 243 try {
diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py
index c32536464..d24e02058 100644
--- a/runtime/test/check_d3d12_trace.py
+++ b/runtime/test/check_d3d12_trace.py
@@ -50,6 +50,8 @@ def main():
50 ] 50 ]
51 else: 51 else:
52 expected = [ 52 expected = [
53 "ID3D12GraphicsCommandList::SetPipelineState called",
54 "ID3D12GraphicsCommandList::SetGraphicsRootSignature called",
53 "ID3D12GraphicsCommandList::SetMarker called", 55 "ID3D12GraphicsCommandList::SetMarker called",
54 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 56 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
55 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", 57 "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported",
diff --git a/runtime/test/check_texture_readback_sync.cmake b/runtime/test/check_texture_readback_sync.cmake
index f82156789..81ef3f24e 100644
--- a/runtime/test/check_texture_readback_sync.cmake
+++ b/runtime/test/check_texture_readback_sync.cmake
@@ -1,10 +1,11 @@
1# Run with -DTOOL=<vk_texture_test> -DSPIRV=<directory built by the GPU suite> 1# Run with -DTOOL=<vk_texture_test> -DSPIRV=<directory built by the GPU suite>
2# -DOUTPUT=<readback file> -P runtime/test/check_texture_readback_sync.cmake. 2# -DOUTPUT=<readback file> -P runtime/test/check_texture_readback_sync.cmake.
3# For a cross build, pass the configured emulator as "-DRUNNER=<emulator;args>".
3# Requires the Khronos validation layer and a device that supports the texture harness. 4# Requires the Khronos validation layer and a device that supports the texture harness.
4execute_process( 5execute_process(
5 COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation 6 COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation
6 VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT 7 VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT
7 "${TOOL}" cube "${OUTPUT}" 8 ${RUNNER} "${TOOL}" cube "${OUTPUT}"
8 WORKING_DIRECTORY "${SPIRV}" TIMEOUT 90 9 WORKING_DIRECTORY "${SPIRV}" TIMEOUT 90
9 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log) 10 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log)
10if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED" 11if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED"
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
new file mode 100644
index 000000000..8c98ba1eb
--- /dev/null
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -0,0 +1,34 @@
1file(MAKE_DIRECTORY "${TEST_DIR}")
2file(WRITE "${TEST_DIR}/index.json" "not JSON\n")
3
4# ${RUNNER} is CMAKE_CROSSCOMPILING_EMULATOR: CTest does not apply it to a script
5# test (the command is the host CMake), so the script runs the tool through it itself.
6function(check_invalid option)
7 execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" "${option}" ${ARGN}
8 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
9 if(NOT code STREQUAL "2" OR NOT log MATCHES "${option} requires a valid value")
10 message(FATAL_ERROR "${option} ${ARGN}: expected usage error, got ${code}\n${log}")
11 endif()
12endfunction()
13
14check_invalid(--count)
15check_invalid(--count --compute-only)
16check_invalid(--count 18446744073709551616)
17check_invalid(--jobs 4294967296)
18check_invalid(--start -1)
19check_invalid(--max-bytes 1MiB)
20check_invalid(--large-module-bytes -1)
21check_invalid(--slow nonsense)
22check_invalid(--slow nan)
23check_invalid(--slow -0.5)
24check_invalid(--stage --graphics-only)
25check_invalid(--stats)
26
27execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}"
28 --jobs 2 --start 3 --count 0 --max-bytes 0 --large-module-bytes 0
29 --slow 0.5 --stage cs --stats report.csv
30 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
31# The index parser names the file and where it stopped (#1847: "index.json: expected '{' at byte 0").
32if(NOT code STREQUAL "2" OR NOT log MATCHES "index.json: ")
33 message(FATAL_ERROR "Expected valid arguments to reach the malformed index, got ${code}\n${log}")
34endif()
diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp
new file mode 100644
index 000000000..cf936012a
--- /dev/null
+++ b/runtime/test/d3d12_buffer_uav_test.cpp
@@ -0,0 +1,699 @@
1// Typed buffer UAVs and UAV counters (docs/d3d12_vulkan.md section 3.4, "Buffer UAVs"), through the D3D12 API on the
2// proxy, with compute shaders that are translator output (test/shaders/cs_buf_typed.asm and cs_buf_counter.asm,
3// hand-written RDNA2), plus D3D12-only behaviour compared with the host runtime on the same adapter.
4//
5// Part 1, one DIRECT list: a compute root signature (four root constants and a table of six UAVs), two compute PSOs.
6// cs_buf_typed writes typed buffer views (R32_UINT with an atomic add, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from
7// FirstElement 16, R32G32B32A32_UINT, R32_SINT) and reads an R32_FLOAT view. Two views are shorter
8// than the dispatch (240 and 250 elements of 256): the V#'s NUM_RECORDS is the bound, so stores past
9// it leave the buffer's sentinel and loads past it give 0.
10// cs_buf_counter a structured UAV with a counter at CounterOffsetInBytes 4096 of another buffer: 256 lanes append
11// (buffer_atomic_add on the counter V# in the slot's upper half, store at the returned index), then
12// 128 lanes consume (buffer_atomic_sub, load the record just below). "CopyStructureCount" in D3D12
13// is CopyBufferRegion of the counter's 4 bytes into a buffer: read after the append (256) and after
14// the consume (128). Lane order is up to the GPU, so records are compared as sets.
15// Everything is compared with a CPU reference, word by word, error 0.
16// Part 2, the layer's device (no proxy) and the host runtime on the SAME adapter (LUID): typed buffer UAVs created with
17// CreateUnorderedAccessView and cleared with ClearUnorderedAccessViewUint / Float (thirteen formats, sub-ranges, an
18// element range ending off a word boundary), and a structured UAV with a counter: a clear of the structured view and
19// of the counter's own word through a raw view. The bytes read back are compared with the host's; with no host D3D12
20// the layer's are compared with the model of uav_clear.h.
21// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
22#include "vk_test_device.h"
23#include "d3d12_test_shaders.h"
24#include "d3d12_copy_compare.h"
25#include "../shims/d3d12_com.h"
26#include "../shims/d3d12_xs_device.h"
27#include "../src/gfx10_descriptors.h"
28#include "../src/shader_library.h"
29#include "../src/uav_clear.h"
30
31#include <algorithm>
32#include <array>
33#include <bit>
34#include <cmath>
35#include <cstring>
36
37#ifndef LEONIDA_TEST_BUFFER_UAV_DIR
38#error "LEONIDA_TEST_BUFFER_UAV_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)"
39#endif
40
41#define EXPECT(condition) do { \
42 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
43} while (0)
44
45using namespace d3d12test;
46using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
47namespace g = leonida::gfx10;
48namespace uc = leonida::uav_clear;
49
50namespace {
51
52std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
53 std::ifstream in(path, std::ios::binary);
54 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
55}
56
57constexpr UINT lanes = 256;
58constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193;
59constexpr std::uint32_t sentinel = 0xa5a5a5a5u;
60constexpr UINT out0_elements = 240, in4_elements = 250, out2_first = 16;
61constexpr UINT64 counter_offset = 4096, counter_buffer_bytes = 8192;
62constexpr UINT consumed = 128;
63
64// The buffers of part 1: sizes, in the order of their slices of the upload and of the readback buffer.
65enum Buf { out0, out1, out2, out3, in4, out5, records, counter, consumed_out, buffer_count };
66constexpr UINT64 sizes[buffer_count] = {lanes * 4, lanes * 8, (out2_first + lanes) * 4, lanes * 16, lanes * 4,
67 lanes * 4, lanes * 8, counter_buffer_bytes, consumed * 8};
68constexpr UINT64 slice(Buf which) {
69 UINT64 at = 0;
70 for (int i = 0; i < which; ++i) at += (sizes[i] + 255) / 256 * 256;
71 return at;
72}
73constexpr UINT64 total_bytes = slice(consumed_out) + (sizes[consumed_out] + 255) / 256 * 256;
74constexpr UINT64 count_after_append = total_bytes, count_after_consume = total_bytes + 4;
75constexpr UINT64 readback_bytes = total_bytes + 8;
76
77std::uint16_t half_bits(float value) { // exact for the values the reference uses (finite, in the normal range)
78 const std::uint32_t f = std::bit_cast<std::uint32_t>(value);
79 if (!(f & 0x7fffffffu)) return std::uint16_t(f >> 16);
80 const int exponent = int((f >> 23) & 0xff) - 127 + 15;
81 return std::uint16_t(((f >> 16) & 0x8000) | (exponent << 10) | ((f >> 13) & 0x3ff));
82}
83
84float input_value(UINT g) { return float(g) - 100.5f; }
85
86struct Reference {
87 std::vector<std::uint32_t> words[buffer_count];
88};
89
90Reference reference() {
91 Reference ref;
92 for (int i = 0; i < buffer_count; ++i) ref.words[i].assign(sizes[i] / 4, sentinel);
93 for (UINT g = 0; g < lanes; ++g) {
94 if (g < out0_elements) ref.words[out0][g] = (g * multiplier + seed) + g;
95 const float x = float(g);
96 ref.words[out1][g * 2] = half_bits(x) | std::uint32_t(half_bits(x + 0.5f)) << 16;
97 ref.words[out1][g * 2 + 1] = half_bits(-1.0f - x) | std::uint32_t(half_bits(0.25f)) << 16;
98 const std::uint32_t k = g & 255;
99 ref.words[out2][out2_first + g] = k | (255 - k) << 8 | 0xff000000u;
100 ref.words[out3][g * 4 + 0] = g;
101 ref.words[out3][g * 4 + 1] = g ^ 0xffff;
102 ref.words[out3][g * 4 + 2] = g * 7;
103 ref.words[out3][g * 4 + 3] = 0xa5;
104 ref.words[in4][g] = std::bit_cast<std::uint32_t>(input_value(g));
105 ref.words[out5][g] = g < in4_elements ? std::uint32_t(int(2.0f * input_value(g))) : 0;
106 }
107 return ref;
108}
109
110D3D12_RESOURCE_BARRIER uav_barrier(ID3D12Resource* resource) {
111 D3D12_RESOURCE_BARRIER b{};
112 b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
113 b.UAV.pResource = resource;
114 return b;
115}
116
117D3D12_UNORDERED_ACCESS_VIEW_DESC buffer_view(DXGI_FORMAT format, UINT64 first, UINT count, UINT stride,
118 UINT64 counter_at = 0, D3D12_BUFFER_UAV_FLAGS flags = D3D12_BUFFER_UAV_FLAG_NONE) {
119 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
120 view.Format = format;
121 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
122 view.Buffer = {first, count, stride, counter_at, flags};
123 return view;
124}
125
126// What a V# in a slot says, as the shader loads it.
127struct Vsharp {
128 std::uint64_t address;
129 std::uint32_t stride, records, format, oob;
130};
131Vsharp vsharp(const void* slot_pointer, unsigned dword = 0) {
132 std::uint32_t w[4];
133 std::memcpy(w, static_cast<const std::uint32_t*>(slot_pointer) + dword, sizeof(w));
134 return {(std::uint64_t(w[1] & 0xffff) << 32) | w[0], w[1] >> 16 & 0x3fff, w[2], w[3] >> 12 & 0x7f, w[3] >> 28 & 3};
135}
136
137// ---- part 1 -----------------------------------------------------------------------------------------------------
138
139int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsigned& words_checked) {
140 leonida::ShaderLibrary library;
141 EXPECT(library.load((root_dir / "spirv").string()));
142 const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); };
143 const auto typed_fssm = program("cs_buf_typed"), counter_fssm = program("cs_buf_counter");
144 EXPECT(typed_fssm.size() >= 0x150 && counter_fssm.size() >= 0x150 && typed_fssm != counter_fssm);
145 EXPECT(library.find("cs", leonida::sha256_hex(typed_fssm)) && library.find("cs", leonida::sha256_hex(counter_fssm)));
146 const auto typed_container = shader_container(typed_fssm), counter_container = shader_container(counter_fssm);
147
148 rt::d3d12::VulkanDeviceInfo info{};
149 info.get_instance_proc = d.instance_proc;
150 info.instance = d.instance;
151 info.physical = d.physical;
152 info.device = d.device;
153 info.queue = d.queue;
154 info.queue_family = d.family;
155 info.buffer_device_address = true;
156 info.bindless = d.bindless;
157 info.bindless_partially_bound = d.partially_bound;
158 info.image_view_min_lod = d.image_view_min_lod;
159 info.shader_dir = (root_dir / "spirv").string();
160 ID3D12Device* inner = nullptr;
161 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
162 Ref<ID3D12Device> device;
163 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
164 reinterpret_cast<void**>(&device.p))));
165 rt::d3d12::set_device_outer(inner, device.p);
166 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
167
168 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 6, 0, 0, 0};
169 D3D12_ROOT_PARAMETER params[2] = {};
170 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
171 params[0].Constants = {0, 0, 4};
172 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
173 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
174 params[1].DescriptorTable = {1, &uav_range};
175 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
176 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
177 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
178 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
179 const auto root_blob = serialize_root_signature(root_desc);
180 EXPECT(!root_blob.empty());
181 Ref<ID3D12RootSignature> root;
182 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
183 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
184 pso_desc.pRootSignature = root.p;
185 pso_desc.CS = {typed_container.data(), typed_container.size()};
186 Ref<ID3D12PipelineState> pso_typed, pso_counter;
187 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_typed.p))));
188 pso_desc.CS = {counter_container.data(), counter_container.size()};
189 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_counter.p))));
190
191 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
192 readback_heap{D3D12_HEAP_TYPE_READBACK};
193 Ref<ID3D12Resource> upload, readback, buf[buffer_count];
194 const auto create = [&](Ref<ID3D12Resource>& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
195 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
196 const auto desc = buffer_desc(bytes, flags);
197 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
198 IID_PPV_ARGS(&out.p)));
199 };
200 EXPECT(create(upload, upload_heap, total_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ));
201 EXPECT(create(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST));
202 for (int i = 0; i < buffer_count; ++i)
203 EXPECT(create(buf[i], default_heap, sizes[i], D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
204 D3D12_RESOURCE_STATE_COPY_DEST));
205 Reference want = reference();
206 {
207 std::uint8_t* mapped = nullptr;
208 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
209 for (UINT64 i = 0; i < total_bytes / 4; ++i) std::memcpy(mapped + i * 4, &sentinel, 4);
210 // The input buffer holds floats; the counter's own word starts at 0 (the rest of its buffer is sentinel).
211 std::memcpy(mapped + slice(in4), want.words[in4].data(), sizes[in4]);
212 std::memset(mapped + slice(counter) + counter_offset, 0, 4);
213 upload->Unmap(0, nullptr);
214 }
215
216 // The table: slots 0..5 typed views for cs_buf_typed; slot 6 a structured UAV with a counter, slot 7 a raw output
217 // for cs_buf_counter (its table starts at slot 6).
218 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 12,
219 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
220 Ref<ID3D12DescriptorHeap> heap;
221 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
222 const std::uint64_t cpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 9))(heap.p);
223 const std::uint64_t gpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p);
224 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
225 EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot
226 const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; };
227 const auto make = [&](UINT i, Buf which, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view, ID3D12Resource* counter_res = nullptr) {
228 device->CreateUnorderedAccessView(buf[which].p, counter_res, &view, handle(i));
229 };
230 make(0, out0, buffer_view(DXGI_FORMAT_R32_UINT, 0, out0_elements, 0));
231 make(1, out1, buffer_view(DXGI_FORMAT_R16G16B16A16_FLOAT, 0, lanes, 0));
232 make(2, out2, buffer_view(DXGI_FORMAT_R8G8B8A8_UNORM, out2_first, lanes, 0));
233 make(3, out3, buffer_view(DXGI_FORMAT_R32G32B32A32_UINT, 0, lanes, 0));
234 make(4, in4, buffer_view(DXGI_FORMAT_R32_FLOAT, 0, in4_elements, 0));
235 make(5, out5, buffer_view(DXGI_FORMAT_R32_SINT, 0, lanes, 0));
236 make(6, records, buffer_view(DXGI_FORMAT_UNKNOWN, 0, lanes, 8, counter_offset), buf[counter].p);
237 make(7, consumed_out, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, consumed * 2, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW));
238
239 // The V#s the shaders load: format code, element size as stride, element count, OOB_SELECT 1 (structured); the
240 // R8G8B8A8 view starts 16 elements in; the counter V# is raw (stride 0, 4 bytes, OOB_SELECT 3) in the slot's upper half.
241 const auto at = [&](UINT i) { return reinterpret_cast<const void*>(handle(i).ptr); };
242 const auto expect_typed = [&](UINT i, Buf which, UINT code, UINT bytes, UINT elements, UINT first) {
243 const Vsharp v = vsharp(at(i));
244 return v.address == buf[which]->GetGPUVirtualAddress() + UINT64(first) * bytes && v.stride == bytes &&
245 v.records == elements && v.format == code && v.oob == 1;
246 };
247 EXPECT(expect_typed(0, out0, 20, 4, out0_elements, 0)); // GFX10_FORMAT_32_UINT
248 EXPECT(expect_typed(1, out1, 71, 8, lanes, 0)); // 16_16_16_16_FLOAT
249 EXPECT(expect_typed(2, out2, 56, 4, lanes, out2_first)); // 8_8_8_8_UNORM
250 EXPECT(expect_typed(3, out3, 75, 16, lanes, 0)); // 32_32_32_32_UINT
251 EXPECT(expect_typed(4, in4, 22, 4, in4_elements, 0)); // 32_FLOAT
252 EXPECT(expect_typed(5, out5, 21, 4, lanes, 0)); // 32_SINT
253 {
254 const Vsharp v = vsharp(at(6)), c = vsharp(at(6), 4);
255 EXPECT(v.address == buf[records]->GetGPUVirtualAddress() && v.stride == 8 && v.records == lanes && v.format == 0 &&
256 v.oob == 0);
257 EXPECT(c.address == buf[counter]->GetGPUVirtualAddress() + counter_offset && c.stride == 0 && c.records == 4 &&
258 c.format == 0 && c.oob == 3);
259 const Vsharp r = vsharp(at(7));
260 EXPECT(r.address == buf[consumed_out]->GetGPUVirtualAddress() && r.stride == 0 && r.records == consumed * 8 &&
261 r.oob == 3);
262 // A view with no counter leaves the slot's upper half zero.
263 const Vsharp none = vsharp(at(7), 4);
264 EXPECT(!none.address && !none.records);
265 }
266
267 D3D12_COMMAND_QUEUE_DESC queue_desc{};
268 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
269 Ref<ID3D12CommandQueue> queue;
270 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
271 Ref<ID3D12CommandAllocator> allocator;
272 Ref<ID3D12GraphicsCommandList> list;
273 Ref<ID3D12Fence> fence;
274 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
275 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
276 IID_PPV_ARGS(&list.p))));
277 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
278
279 constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
280 for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(buf[i].p, 0, upload.p, slice(Buf(i)), sizes[i]);
281 D3D12_RESOURCE_BARRIER barriers[buffer_count];
282 for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, D3D12_RESOURCE_STATE_COPY_DEST, uav_state);
283 list->ResourceBarrier(buffer_count, barriers);
284 ID3D12DescriptorHeap* heaps[] = {heap.p};
285 list->SetDescriptorHeaps(1, heaps);
286 list->SetComputeRootSignature(root.p);
287 const auto constants = [&](std::uint32_t a, std::uint32_t b) {
288 const std::uint32_t values[4] = {a, b, 0, 0};
289 list->SetComputeRoot32BitConstants(0, 4, values, 0);
290 };
291 list->SetPipelineState(pso_typed.p);
292 constants(seed, multiplier);
293 list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu});
294 list->Dispatch(lanes / 64, 1, 1);
295 list->SetPipelineState(pso_counter.p);
296 constants(0, 0); // append
297 list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 6ull * step});
298 list->Dispatch(lanes / 64, 1, 1);
299 D3D12_RESOURCE_BARRIER sync[2] = {uav_barrier(buf[records].p), uav_barrier(buf[counter].p)};
300 list->ResourceBarrier(2, sync);
301 // CopyStructureCount: the counter's 4 bytes into a buffer, after the append.
302 D3D12_RESOURCE_BARRIER to_copy = transition(buf[counter].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE);
303 list->ResourceBarrier(1, &to_copy);
304 list->CopyBufferRegion(readback.p, count_after_append, buf[counter].p, counter_offset, 4);
305 D3D12_RESOURCE_BARRIER back = transition(buf[counter].p, D3D12_RESOURCE_STATE_COPY_SOURCE, uav_state);
306 list->ResourceBarrier(1, &back);
307 constants(1, 0); // consume
308 list->Dispatch(consumed / 64, 1, 1);
309 for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE);
310 list->ResourceBarrier(buffer_count, barriers);
311 for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(readback.p, slice(Buf(i)), buf[i].p, 0, sizes[i]);
312 list->CopyBufferRegion(readback.p, count_after_consume, buf[counter].p, counter_offset, 4);
313 EXPECT(list->Close() == S_OK);
314 ID3D12CommandList* lists[] = {list.p};
315 queue->ExecuteCommandLists(1, lists);
316 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
317 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
318 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
319 EXPECT(event != nullptr);
320 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, event)));
321 if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) {
322 std::fprintf(stderr, "the fence never reached 1\n");
323 return 1;
324 }
325 CloseHandle(event);
326
327 std::vector<std::uint8_t> got;
328 {
329 void* mapped = nullptr;
330 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
331 got.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + readback_bytes);
332 readback->Unmap(0, nullptr);
333 }
334 const auto word_at = [&](UINT64 offset) {
335 std::uint32_t value = 0;
336 std::memcpy(&value, got.data() + offset, 4);
337 return value;
338 };
339
340 unsigned mismatches = 0;
341 const auto compare = [&](const char* what, Buf which, const std::vector<std::uint32_t>& expected) {
342 unsigned bad = 0;
343 for (std::size_t i = 0; i < expected.size(); ++i) {
344 ++words_checked;
345 const std::uint32_t value = word_at(slice(which) + i * 4);
346 if (value == expected[i]) continue;
347 ++mismatches;
348 if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]);
349 }
350 if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size());
351 };
352 compare("R32_UINT store + atomic add (240 of 256 elements)", out0, want.words[out0]);
353 compare("R16G16B16A16_FLOAT store", out1, want.words[out1]);
354 compare("R8G8B8A8_UNORM store (FirstElement 16)", out2, want.words[out2]);
355 compare("R32G32B32A32_UINT store", out3, want.words[out3]);
356 compare("R32_FLOAT input untouched", in4, want.words[in4]);
357 compare("R32_FLOAT load -> R32_SINT store (250 of 256 loads in range)", out5, want.words[out5]);
358
359 // The counter: 256 after the append, 128 after the consume, and nothing else of its buffer touched.
360 ++words_checked;
361 if (word_at(count_after_append) != lanes) {
362 std::fprintf(stderr, "counter after the append: %u, want %u\n", word_at(count_after_append), lanes);
363 ++mismatches;
364 }
365 ++words_checked;
366 if (word_at(count_after_consume) != lanes - consumed) {
367 std::fprintf(stderr, "counter after the consume: %u, want %u\n", word_at(count_after_consume), lanes - consumed);
368 ++mismatches;
369 }
370 for (UINT64 i = 0; i < counter_buffer_bytes / 4; ++i) {
371 ++words_checked;
372 const std::uint32_t expected = i == counter_offset / 4 ? lanes - consumed : sentinel;
373 if (word_at(slice(counter) + i * 4) != expected && mismatches++ < 12)
374 std::fprintf(stderr, "counter buffer word %llu: got %08x want %08x\n", static_cast<unsigned long long>(i),
375 word_at(slice(counter) + i * 4), expected);
376 }
377 // The appended records: every g exactly once with its second field, in whatever order the lanes took the counter.
378 std::vector<std::array<std::uint32_t, 2>> appended, taken;
379 for (UINT i = 0; i < lanes; ++i)
380 appended.push_back({word_at(slice(records) + i * 8), word_at(slice(records) + i * 8 + 4)});
381 std::vector<std::array<std::uint32_t, 2>> sorted = appended;
382 std::sort(sorted.begin(), sorted.end());
383 for (UINT i = 0; i < lanes; ++i) {
384 ++words_checked;
385 if (sorted[i][0] != i || sorted[i][1] != i * 3 + 1) {
386 if (mismatches++ < 12)
387 std::fprintf(stderr, "appended record %u (sorted): { %u, %u }, want { %u, %u }\n", i, sorted[i][0],
388 sorted[i][1], i, i * 3 + 1);
389 }
390 }
391 // The consumed ones: the records at indices 128..255 (the counter went from 256 down to 128), each once.
392 for (UINT i = 0; i < consumed; ++i)
393 taken.push_back({word_at(slice(consumed_out) + i * 8), word_at(slice(consumed_out) + i * 8 + 4)});
394 std::vector<std::array<std::uint32_t, 2>> tail(appended.begin() + (lanes - consumed), appended.end());
395 std::sort(taken.begin(), taken.end());
396 std::sort(tail.begin(), tail.end());
397 for (UINT i = 0; i < consumed; ++i) {
398 ++words_checked;
399 if (taken[i] != tail[i] && mismatches++ < 12)
400 std::fprintf(stderr, "consumed record %u (sorted): { %u, %u }, want { %u, %u }\n", i, taken[i][0], taken[i][1],
401 tail[i][0], tail[i][1]);
402 }
403 EXPECT(!mismatches);
404
405 for (auto& b : buf) b.reset();
406 upload.reset(); readback.reset(); list.reset(); allocator.reset(); fence.reset(); queue.reset();
407 pso_typed.reset(); pso_counter.reset(); root.reset(); heap.reset();
408 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
409 return 0;
410}
411
412// ---- part 2 -----------------------------------------------------------------------------------------------------
413
414struct ClearCase {
415 DXGI_FORMAT format;
416 VkFormat vulkan; // for the model
417 bool is_float;
418 std::array<std::uint32_t, 4> values;
419 UINT64 byte_offset;
420 UINT elements;
421};
422std::uint32_t fb(float f) { return std::bit_cast<std::uint32_t>(f); }
423
424// Values in the domain D3D12 defines the same on every driver: no exact .5 ties in a float -> UNORM rounding (the RTX 5070's
425// D3D12 rounds 127.5 down, the layer and the spec's round-to-nearest up) and no integer wider than its channel (the low bits
426// are kept here, one vendor clamps).
427const ClearCase clear_cases[] = {
428 {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, false, {0x12345678, 0, 0, 0}, 0, 16},
429 {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, false, {0xfffffff0, 0, 0, 0}, 256, 8},
430 {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, true, {fb(1.5f), 0, 0, 0}, 512, 8},
431 {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, true, {fb(1.0f), fb(0.5f), fb(-2.0f), fb(0.25f)}, 768, 8},
432 {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, true, {fb(1.0f), fb(0.4f), fb(0.2f), fb(2.0f)}, 1024, 16},
433 {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, false, {0xf1, 2, 3, 0x80}, 1280, 16},
434 {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 1536, 4},
435 {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, true, {fb(0.25f), 0, 0, 0}, 1792, 16},
436 {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, true, {fb(0.2f), 0, 0, 0}, 2048, 21}, // ends off a word boundary
437 {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, true, {fb(0.25f), fb(0.4f), fb(0.75f), fb(1.0f)}, 2304, 8},
438 {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, true, {fb(1.0f), fb(2.0f), fb(0.5f), 0}, 2560, 8},
439 {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, true, {fb(1.5f), fb(-0.5f), 0, 0}, 2816, 8},
440 {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, false, {0xaa, 0xbb, 0, 0}, 3072, 10},
441};
442constexpr UINT64 api_data_bytes = 4096, api_records_bytes = 4096;
443constexpr UINT api_readback = api_data_bytes + api_records_bytes + counter_buffer_bytes;
444
445// The same scenario on `device`: bytes read back, or empty on failure. host: a real heap pair (a non-shader-visible one the
446// views are made in, a shader-visible one the clear's GPU handle comes from), as the PC runtime wants; the layer takes the
447// CPU handle and ignores the GPU one.
448bool run_api(ID3D12Device* device, bool host, std::vector<std::uint8_t>& out, std::vector<bool>& supported_by_host) {
449 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD},
450 readback_heap{D3D12_HEAP_TYPE_READBACK};
451 const auto create = [&](Ref<ID3D12Resource>& r, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
452 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
453 const auto desc = buffer_desc(bytes, flags);
454 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
455 IID_PPV_ARGS(&r.p)));
456 };
457 constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
458 Ref<ID3D12Resource> data, structured, counter_buffer, upload, readback;
459 if (!create(data, default_heap, api_data_bytes, uav_flag, D3D12_RESOURCE_STATE_UNORDERED_ACCESS) ||
460 !create(structured, default_heap, api_records_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) ||
461 !create(counter_buffer, default_heap, counter_buffer_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) ||
462 !create(upload, upload_heap, api_records_bytes + counter_buffer_bytes, D3D12_RESOURCE_FLAG_NONE,
463 D3D12_RESOURCE_STATE_GENERIC_READ) ||
464 !create(readback, readback_heap, api_readback, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST))
465 return std::fprintf(stderr, "resource creation failed\n"), false;
466 {
467 std::uint8_t* mapped = nullptr;
468 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
469 std::memset(mapped, 0x11, api_records_bytes + counter_buffer_bytes);
470 const std::uint32_t seven = 7;
471 std::memcpy(mapped + api_records_bytes + counter_offset, &seven, 4); // the counter's word
472 upload->Unmap(0, nullptr);
473 }
474 constexpr UINT slots = 24;
475 Ref<ID3D12DescriptorHeap> cpu_heap, gpu_heap;
476 D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
477 if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&cpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
478 if (host) {
479 desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
480 if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&gpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
481 }
482 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
483 const auto cpu = [&](UINT i) {
484 D3D12_CPU_DESCRIPTOR_HANDLE h = cpu_heap->GetCPUDescriptorHandleForHeapStart();
485 h.ptr += SIZE_T(i) * step;
486 return h;
487 };
488 const auto gpu = [&](UINT i) {
489 if (!host) return D3D12_GPU_DESCRIPTOR_HANDLE{0};
490 D3D12_GPU_DESCRIPTOR_HANDLE h = gpu_heap->GetGPUDescriptorHandleForHeapStart();
491 h.ptr += UINT64(i) * step;
492 return h;
493 };
494 UINT next_slot = 0;
495 const auto make = [&](ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view) {
496 const UINT i = next_slot++;
497 device->CreateUnorderedAccessView(resource, counter, &view, cpu(i));
498 if (host) {
499 D3D12_CPU_DESCRIPTOR_HANDLE visible = gpu_heap->GetCPUDescriptorHandleForHeapStart();
500 visible.ptr += SIZE_T(i) * step;
501 device->CopyDescriptorsSimple(1, visible, cpu(i), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
502 }
503 return i;
504 };
505
506 Ref<ID3D12CommandQueue> queue;
507 Ref<ID3D12CommandAllocator> allocator;
508 Ref<ID3D12GraphicsCommandList> list;
509 Ref<ID3D12Fence> fence;
510 const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
511 if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) ||
512 FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) ||
513 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p))) ||
514 FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
515 return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
516 ID3D12DescriptorHeap* heaps[] = {gpu_heap.p};
517 if (host) list->SetDescriptorHeaps(1, heaps);
518
519 const auto clear = [&](UINT slot_index, ID3D12Resource* resource, bool is_float, const std::array<std::uint32_t, 4>& v) {
520 if (is_float) {
521 const float f[4] = {std::bit_cast<float>(v[0]), std::bit_cast<float>(v[1]), std::bit_cast<float>(v[2]),
522 std::bit_cast<float>(v[3])};
523 list->ClearUnorderedAccessViewFloat(gpu(slot_index), cpu(slot_index), resource, f, 0, nullptr);
524 } else {
525 list->ClearUnorderedAccessViewUint(gpu(slot_index), cpu(slot_index), resource, v.data(), 0, nullptr);
526 }
527 const D3D12_RESOURCE_BARRIER barrier = uav_barrier(resource);
528 list->ResourceBarrier(1, &barrier);
529 };
530 // The whole buffer 0xcdcdcdcd through a raw view, then each case's elements through a typed view.
531 clear(make(data.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, api_data_bytes / 4, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)),
532 data.p, false, {0xcdcdcdcd, 0, 0, 0});
533 supported_by_host.assign(std::size(clear_cases), true);
534 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
535 const ClearCase& test = clear_cases[c];
536 if (host) {
537 D3D12_FEATURE_DATA_FORMAT_SUPPORT support{test.format};
538 supported_by_host[c] = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) &&
539 (support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE);
540 }
541 if (!supported_by_host[c]) continue;
542 const UINT size = uc::layout(test.vulkan)->bytes;
543 clear(make(data.p, nullptr, buffer_view(test.format, test.byte_offset / size, test.elements, 0)), data.p,
544 test.is_float, test.values);
545 }
546 // A structured view with a counter. The clear writes the records and leaves the counter (preset to 7) alone ...
547 list->CopyBufferRegion(structured.p, 0, upload.p, 0, api_records_bytes);
548 list->CopyBufferRegion(counter_buffer.p, 0, upload.p, api_records_bytes, counter_buffer_bytes);
549 D3D12_RESOURCE_BARRIER to_uav[2] = {transition(structured.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
550 transition(counter_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST,
551 D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
552 list->ResourceBarrier(2, to_uav);
553 clear(make(structured.p, counter_buffer.p, buffer_view(DXGI_FORMAT_UNKNOWN, 0, 256, 16, counter_offset)), structured.p,
554 false, {0xab, 0xcd, 0xef, 0x01});
555 // ... and a raw view of the counter's own word (element 1024) clears it, as a game resets its counter.
556 clear(make(counter_buffer.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, counter_offset / 4, 1, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)),
557 counter_buffer.p, false, {3, 0, 0, 0});
558 D3D12_RESOURCE_BARRIER to_copy[3] = {
559 transition(data.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
560 transition(structured.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
561 transition(counter_buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)};
562 list->ResourceBarrier(3, to_copy);
563 list->CopyBufferRegion(readback.p, 0, data.p, 0, api_data_bytes);
564 list->CopyBufferRegion(readback.p, api_data_bytes, structured.p, 0, api_records_bytes);
565 list->CopyBufferRegion(readback.p, api_data_bytes + api_records_bytes, counter_buffer.p, 0, counter_buffer_bytes);
566 if (const HRESULT hr = list->Close(); FAILED(hr)) return std::fprintf(stderr, "Close: %08lx\n", static_cast<unsigned long>(hr)), false;
567 ID3D12CommandList* lists[] = {list.p};
568 queue->ExecuteCommandLists(1, lists);
569 if (!host && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success)
570 return std::fprintf(stderr, "replay result %d\n", int(rt::d3d12::last_execute_result(queue.p))), false;
571 if (FAILED(queue->Signal(fence.p, 1))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
572 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
573 if (!event || FAILED(fence->SetEventOnCompletion(1, event)) || WaitForSingleObject(event, 20000) != WAIT_OBJECT_0)
574 return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
575 CloseHandle(event);
576 void* mapped = nullptr;
577 if (FAILED(readback->Map(0, nullptr, &mapped))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false;
578 out.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + api_readback);
579 readback->Unmap(0, nullptr);
580 return true;
581}
582
583// What D3D12 says the same sequence leaves, from uav_clear.h: the model for a run with no host runtime to compare with.
584std::vector<std::uint8_t> model(const std::vector<bool>& supported) {
585 std::vector<std::uint8_t> bytes(api_readback, 0x11);
586 std::fill(bytes.begin(), bytes.begin() + api_data_bytes, std::uint8_t(0xcd));
587 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
588 const ClearCase& test = clear_cases[c];
589 uc::Element e{};
590 if (!supported[c] || !uc::encode(test.vulkan, test.is_float, test.values, e)) continue;
591 for (UINT64 i = 0; i < UINT64(test.elements) * e.size; ++i) bytes[test.byte_offset + i] = e.bytes[i % e.size];
592 }
593 // A structured view clears every 32-bit word to the first value (D3D12 ignores the other three).
594 for (UINT64 i = 0; i < api_records_bytes; ++i) bytes[api_data_bytes + i] = i % 4 == 0 ? 0xab : 0;
595 const std::uint32_t three = 3;
596 std::memcpy(bytes.data() + api_data_bytes + api_records_bytes + counter_offset, &three, 4);
597 return bytes;
598}
599
600} // namespace
601
602int main() {
603 vktest::Device d;
604 const auto device_status = d.initialize();
605 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
606 if (device_status != vktest::DeviceStatus::ready) return 1;
607 if (!d.bindless) {
608 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
609 return 77;
610 }
611 const std::filesystem::path root_dir = LEONIDA_TEST_BUFFER_UAV_DIR;
612
613 unsigned words = 0;
614 if (const int status = run_shaders(d, root_dir, words)) return status;
615
616 // Part 2: the layer's device and the host's on the same adapter.
617 std::vector<std::uint8_t> ours, host_bytes;
618 std::vector<bool> supported;
619 {
620 rt::d3d12::VulkanDeviceInfo info{};
621 info.get_instance_proc = d.instance_proc;
622 info.instance = d.instance;
623 info.physical = d.physical;
624 info.device = d.device;
625 info.queue = d.queue;
626 info.queue_family = d.family;
627 info.buffer_device_address = true; // the V# holds the buffer's address
628 Ref<ID3D12Device> device;
629 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
630 EXPECT(run_api(device.p, false, ours, supported));
631 }
632 std::string host_name = "none";
633 bool compared = false;
634 {
635 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
636 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
637 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
638 copycmp::Ptr<ID3D12Device> host;
639 LUID luid{};
640 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
641 if (id.deviceLUIDValid && copycmp::try_create_host(host, host_name, &luid)) {
642 std::vector<bool> host_supported;
643 EXPECT(run_api(host.p, true, host_bytes, host_supported));
644 supported = host_supported;
645 compared = true;
646 }
647 }
648 if (!compared) {
649 std::printf("no host D3D12 device on the layer's adapter: the layer's bytes are compared with uav_clear.h\n");
650 host_bytes = model(supported);
651 host_name = "the uav_clear.h model";
652 } else {
653 // The layer ran every case; the host only those its adapter can store typed. Mask the others in both.
654 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
655 if (supported[c]) continue;
656 const ClearCase& test = clear_cases[c];
657 const UINT size = uc::layout(test.vulkan)->bytes;
658 std::fill_n(ours.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0));
659 std::fill_n(host_bytes.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0));
660 std::printf("host adapter has no typed UAV store for DXGI format %d: that case is not compared\n",
661 int(test.format));
662 }
663 }
664 EXPECT(ours.size() == api_readback && host_bytes.size() == api_readback);
665 unsigned differing = 0;
666 for (std::size_t i = 0; i < ours.size(); ++i) {
667 ++words;
668 if (ours[i] == host_bytes[i]) continue;
669 if (differing++ < 12) {
670 const char* where = i < api_data_bytes ? "typed clears" : i < api_data_bytes + api_records_bytes ? "structured clear with a counter" : "counter buffer";
671 std::fprintf(stderr, "%s byte %zu: layer %02x, %s %02x\n", where, i, ours[i], host_name.c_str(), host_bytes[i]);
672 }
673 }
674 if (differing) {
675 // Say which clear case the first differing byte belongs to.
676 for (std::size_t c = 0; c < std::size(clear_cases); ++c) {
677 const ClearCase& test = clear_cases[c];
678 const UINT size = uc::layout(test.vulkan)->bytes;
679 for (UINT64 i = 0; i < UINT64(test.elements) * size; ++i)
680 if (ours[test.byte_offset + i] != host_bytes[test.byte_offset + i]) {
681 std::fprintf(stderr, "case %zu (DXGI format %d) differs\n", c, int(test.format));
682 break;
683 }
684 }
685 std::fprintf(stderr, "%u bytes differ\n", differing);
686 return 1;
687 }
688 if (d.validation_errors()) {
689 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
690 return 1;
691 }
692 std::printf("Buffer UAVs: typed views (R32_UINT with an atomic, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from FirstElement 16, "
693 "R32G32B32A32_UINT, R32_FLOAT loads, R32_SINT) written by a translated compute shader with NUM_RECORDS "
694 "as the bound, and a structured UAV with a counter at offset 4096 appended to by 256 lanes and consumed "
695 "by 128 (counter 256 then 128 through CopyBufferRegion) matched the CPU reference; typed-buffer and "
696 "counter clears matched %s: %u values compared, error 0\n",
697 host_name.c_str(), words);
698 return 0;
699}
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index a2011d3c2..2d9dff03f 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -10,6 +10,7 @@
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h"
13#include "../src/shader_library.h" 14#include "../src/shader_library.h"
14#include "../shims/d3d12_xs_device.h" 15#include "../shims/d3d12_xs_device.h"
15 16
@@ -33,6 +34,8 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10
33// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). 34// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235).
34using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, 35using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
35 std::uint64_t, const IID*, void**); 36 std::uint64_t, const IID*, void**);
37// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out).
38using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**);
36using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); 39using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
37 40
38template<class T> 41template<class T>
@@ -169,6 +172,7 @@ int main() {
169 constexpr UINT elements = 64, bytes = elements * 4; 172 constexpr UINT elements = 64, bytes = elements * 4;
170 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; 173 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000};
171 std::vector<std::uint32_t> first(elements), second(elements); 174 std::vector<std::uint32_t> first(elements), second(elements);
175 std::vector<std::uint32_t> cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements);
172 { 176 {
173 rt::d3d12::VulkanDeviceInfo info{}; 177 rt::d3d12::VulkanDeviceInfo info{};
174 info.get_instance_proc = d.instance_proc; 178 info.get_instance_proc = d.instance_proc;
@@ -221,6 +225,40 @@ int main() {
221 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); 225 EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p);
222 pso_desc.CS = {container.data(), container.size()}; 226 pso_desc.CS = {container.data(), container.size()};
223 227
228 // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState.
229 struct XboxNativeComputeDesc {
230 ID3D12RootSignature* root_signature;
231 const void* kind0;
232 std::uint64_t kind0_size;
233 const void* kind1;
234 std::uint64_t kind1_size;
235 const void* kind6;
236 std::uint64_t kind6_size;
237 const void* kind7;
238 std::uint64_t kind7_size;
239 } native_desc{};
240 native_desc.root_signature = root.p;
241 native_desc.kind6 = fssm.data();
242 native_desc.kind6_size = fssm.size();
243 Ref<ID3D12PipelineState> pso67, unknown67;
244 EXPECT(SUCCEEDED(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
245 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&pso67.p))));
246 EXPECT(pso67.p != nullptr);
247 native_desc.kind6 = other.data();
248 native_desc.kind6_size = other.size();
249 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
250 device.p, &native_desc, &pso_iid, reinterpret_cast<void**>(&unknown67.p)) == E_INVALIDARG && !unknown67.p);
251 void* out_null = reinterpret_cast<void*>(0x1111);
252 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
253 device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null);
254 out_null = reinterpret_cast<void*>(0x1111);
255 native_desc.kind6 = fssm.data();
256 native_desc.kind6_size = fssm.size();
257 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
258 device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null);
259 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
260 device.p, &native_desc, &pso_iid, nullptr) == E_POINTER);
261
224 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so 262 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so
225 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). 263 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag).
226 { 264 {
@@ -344,7 +382,131 @@ int main() {
344 std::memcpy(first.data(), results, bytes); 382 std::memcpy(first.data(), results, bytes);
345 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes); 383 std::memcpy(second.data(), static_cast<const std::uint8_t*>(results) + bytes, bytes);
346 384
385 // CreateConstantBufferView: populate shader-visible descriptor heap slots with GFX10 V# descriptors for a
386 // 512-byte arena constant buffer (two 256-byte CBVs: A at +0, B at +256) and null CBVs.
387 {
388 const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
389 EXPECT(inc == 32);
390 const auto cb_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE);
391 Ref<ID3D12Resource> cb_upload, cb_default, cb_readback;
392 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
393 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
394 IID_PPV_ARGS(&cb_upload.p))));
395 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &cb_desc,
396 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
397 IID_PPV_ARGS(&cb_default.p))));
398 const auto cb_rb_desc = buffer_desc(4 * bytes, D3D12_RESOURCE_FLAG_NONE);
399 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &cb_rb_desc,
400 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
401 IID_PPV_ARGS(&cb_readback.p))));
402 void* cb_mapped = nullptr;
403 EXPECT(SUCCEEDED(cb_upload->Map(0, nullptr, &cb_mapped)));
404 auto* cb_words = static_cast<std::uint32_t*>(cb_mapped);
405 for (UINT i = 0; i < elements; ++i) {
406 cb_words[i] = 0x10000u + i;
407 cb_words[elements + i] = 0x20000u + i;
408 }
409 const D3D12_GPU_VIRTUAL_ADDRESS cb_va = cb_default->GetGPUVirtualAddress();
410 EXPECT(cb_va >= 0x10000 && cb_va < (1ull << 32));
411
412 const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; };
413 const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; };
414
415 // Pre-fill slot 3 with non-zero bytes to prove null CBV zeroes the entire 32-byte slot.
416 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0xA5, inc);
417 device->CreateConstantBufferView(nullptr, slot_cpu(3));
418 std::uint8_t zeros[32] = {};
419 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
420
421 // Zero BufferLocation or zero SizeInBytes also produces a zeroed null V#.
422 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_loc{0, 256};
423 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
424 device->CreateConstantBufferView(&zero_loc, slot_cpu(3));
425 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
426 const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_size{cb_va, 0};
427 std::memset(reinterpret_cast<void*>(slot_cpu(3).ptr), 0x5A, inc);
428 device->CreateConstantBufferView(&zero_size, slot_cpu(3));
429 EXPECT(std::memcmp(reinterpret_cast<const void*>(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0);
430
431 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_a{cb_va, 256};
432 const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_b{cb_va + 256, 256};
433 device->CreateConstantBufferView(&cbv_a, slot_cpu(1));
434 device->CreateConstantBufferView(&cbv_b, slot_cpu(2));
435
436 // Decode the written V# in slots 1 and 2 and verify every field + zeroed trailing 16 bytes.
437 for (const auto& [slot_idx, expected_va] :
438 {std::pair{1u, std::uint64_t(cb_va)}, std::pair{2u, std::uint64_t(cb_va + 256)}}) {
439 leonida::gfx10::BufferWords raw{};
440 std::memcpy(raw.data(), reinterpret_cast<const void*>(slot_cpu(slot_idx).ptr), sizeof(raw));
441 leonida::gfx10::Buffer decoded{};
442 EXPECT(leonida::gfx10::decode(raw, decoded));
443 EXPECT(decoded.address == expected_va);
444 EXPECT(decoded.stride == 0);
445 EXPECT(decoded.num_records == 256);
446 EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT));
447 EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle);
448 EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw);
449 EXPECT(std::memcmp(reinterpret_cast<const std::uint8_t*>(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0);
450 }
451
452 // Copy CBV data into the arena buffer, then run 4 dispatches:
453 // 1) CBV A at byte offset 0 (all 64 dwords in-bounds)
454 // 2) CBV A at byte offset 128 (dwords 0..31 in-bounds, dwords 32..63 OOB -> 0)
455 // 3) CBV B at byte offset 0 (negative control: all 64 dwords flip to 0x20000 + i)
456 // 4) Null CBV at byte offset 0 (negative control: all 64 dwords become 0)
457 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
458 list->CopyBufferRegion(cb_default.p, 0, cb_upload.p, 0, 512);
459 const D3D12_RESOURCE_BARRIER cb_ready[] = {
460 transition(cb_default.p, D3D12_RESOURCE_STATE_COPY_DEST,
461 D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER),
462 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
463 };
464 list->ResourceBarrier(2, cb_ready);
465 list->SetDescriptorHeaps(1, heaps);
466 list->SetComputeRootSignature(root.p);
467 list->SetComputeRootUnorderedAccessView(1, va_a);
468
469 const struct CbvDispatch {
470 UINT byte_offset;
471 UINT slot_idx;
472 UINT readback_offset;
473 } cbv_dispatches[] = {
474 {0, 1, 0 * bytes},
475 {128, 1, 1 * bytes},
476 {0, 2, 2 * bytes},
477 {0, 3, 3 * bytes},
478 };
479 for (const auto& d_cfg : cbv_dispatches) {
480 const std::uint32_t rc[2] = {d_cfg.byte_offset, 0}; // s1 == 0 selects CBV V# mode
481 list->SetComputeRoot32BitConstants(0, 2, rc, 0);
482 list->SetComputeRootDescriptorTable(2, slot_gpu(d_cfg.slot_idx));
483 list->Dispatch(1, 1, 1);
484 const auto to_src =
485 transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
486 list->ResourceBarrier(1, &to_src);
487 list->CopyBufferRegion(cb_readback.p, d_cfg.readback_offset, out_a.p, 0, bytes);
488 const auto to_uav =
489 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
490 list->ResourceBarrier(1, &to_uav);
491 }
492 EXPECT(list->Close() == S_OK);
493 queue->ExecuteCommandLists(1, lists);
494 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
495 EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)));
496 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr)));
497
498 void* cb_res = nullptr;
499 EXPECT(SUCCEEDED(cb_readback->Map(0, nullptr, &cb_res)));
500 const auto* src_bytes = static_cast<const std::uint8_t*>(cb_res);
501 std::memcpy(cbv_a_out.data(), src_bytes + 0 * bytes, bytes);
502 std::memcpy(cbv_oob_out.data(), src_bytes + 1 * bytes, bytes);
503 std::memcpy(cbv_b_out.data(), src_bytes + 2 * bytes, bytes);
504 std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes);
505 }
506
347 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); 507 for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset();
508 pso67.reset();
509 unknown67.reset();
348 pso.reset(); 510 pso.reset();
349 root.reset(); 511 root.reset();
350 heap.reset(); 512 heap.reset();
@@ -364,6 +526,27 @@ int main() {
364 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b); 526 std::fprintf(stderr, "element %u: got %u and %u, want %u and %u\n", i, first[i], second[i], a, b);
365 } 527 }
366 EXPECT(!mismatches); 528 EXPECT(!mismatches);
529 UINT cbv_b_diff = 0, cbv_null_diff = 0;
530 for (std::uint32_t i = 0; i < elements; ++i) {
531 const std::uint32_t want_a = 0x10000u + i;
532 const std::uint32_t want_oob = i < 32 ? (0x10000u + 32u + i) : 0u;
533 const std::uint32_t want_b = 0x20000u + i;
534 if (cbv_a_out[i] != want_a && mismatches++ < 4)
535 std::fprintf(stderr, "CBV A[%u]: got 0x%x want 0x%x\n", i, cbv_a_out[i], want_a);
536 if (cbv_oob_out[i] != want_oob && mismatches++ < 4)
537 std::fprintf(stderr, "CBV OOB[%u]: got 0x%x want 0x%x\n", i, cbv_oob_out[i], want_oob);
538 if (cbv_b_out[i] != want_b && mismatches++ < 4)
539 std::fprintf(stderr, "CBV B[%u]: got 0x%x want 0x%x\n", i, cbv_b_out[i], want_b);
540 if (cbv_null_out[i] != 0u && mismatches++ < 4)
541 std::fprintf(stderr, "CBV null[%u]: got 0x%x want 0\n", i, cbv_null_out[i]);
542 if (cbv_b_out[i] != cbv_a_out[i]) ++cbv_b_diff;
543 if (cbv_null_out[i] != cbv_a_out[i]) ++cbv_null_diff;
544 }
545 EXPECT(!mismatches);
546 EXPECT(cbv_b_diff == elements && cbv_null_diff == elements);
547 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at "
548 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n",
549 cbv_b_diff, elements, cbv_null_diff, elements);
367 if (d.validation_errors()) { 550 if (d.validation_errors()) {
368 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 551 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
369 return 1; 552 return 1;
diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h
index 3679ab754..3d4281a17 100644
--- a/runtime/test/d3d12_copy_compare.h
+++ b/runtime/test/d3d12_copy_compare.h
@@ -5,7 +5,8 @@
5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are 5// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are
6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match. 6// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match.
7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately). 7// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately).
8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the default adapter. 8// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the layer's own adapter when
9// the test has set layer_adapter(), else the default adapter.
9#pragma once 10#pragma once
10#include <windows.h> 11#include <windows.h>
11#include <d3d12.h> 12#include <d3d12.h>
@@ -18,6 +19,7 @@
18#include <cstdio> 19#include <cstdio>
19#include <cstring> 20#include <cstring>
20#include <functional> 21#include <functional>
22#include <optional>
21#include <string> 23#include <string>
22#include <vector> 24#include <vector>
23 25
@@ -110,12 +112,25 @@ inline bool try_create_host(Ptr<ID3D12Device>& host, std::string& name, const LU
110 return true; 112 return true;
111} 113}
112 114
113// A host device, or false when there is none (the comparisons are then skipped). When LEONIDA_HOST_ADAPTER names an 115// The adapter behind the layer's Vulkan device (VkPhysicalDeviceIDProperties::deviceLUID), for a test that knows it.
114// adapter that cannot be had, the run fails: a typo must not turn the comparisons into a silent pass. 116// On a PC with two GPUs D3D12's default adapter can be the other one, whose driver accepts other formats (an AMD
117// layer device accepts an R9G9B9E5 render target that the NVIDIA host refuses), so the comparison would be between
118// two GPUs instead of between the layer and the host runtime.
119inline std::optional<LUID>& layer_adapter() {
120 static std::optional<LUID> luid;
121 return luid;
122}
123
124// A host device, or false when there is none (the comparisons are then skipped). Without LEONIDA_HOST_ADAPTER it is
125// on the layer's own adapter when that is set and has a D3D12 device, else on the default adapter. When
126// LEONIDA_HOST_ADAPTER names an adapter that cannot be had, the run fails: a typo must not turn the comparisons into a
127// silent pass.
115inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) { 128inline bool create_host(Ptr<ID3D12Device>& host, std::string& name) {
116 if (try_create_host(host, name)) return true;
117 char want[128] = {}; 129 char want[128] = {};
118 if (GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0]) { 130 const bool named = GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && want[0];
131 if (!named && layer_adapter() && try_create_host(host, name, &*layer_adapter())) return true;
132 if (try_create_host(host, name)) return true;
133 if (named) {
119 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want); 134 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", want);
120 std::exit(1); 135 std::exit(1);
121 } 136 }
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 64ef24da6..13c10d043 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -698,6 +698,42 @@ int main() {
698 const auto null_at = [&](UINT i) { 698 const auto null_at = [&](UINT i) {
699 return std::all_of(view_bytes(i), view_bytes(i) + step, [](std::uint8_t byte) { return byte == 0; }); 699 return std::all_of(view_bytes(i), view_bytes(i) + step, [](std::uint8_t byte) { return byte == 0; });
700 }; 700 };
701 // An explicit D3D12_SRV_DIMENSION_TEXTURE1D view on a 1D texture array selects layer zero (like TEXTURE2D
702 // and TEXTURE2DMS on 2D arrays), while a default (nullptr) SRV on a 1D array remains a null descriptor.
703 {
704 auto line_array_desc = line_desc;
705 line_array_desc.DepthOrArraySize = 3;
706 Ref<ID3D12Resource> line_array;
707 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &line_array_desc,
708 D3D12_RESOURCE_STATE_COMMON, nullptr,
709 IID_PPV_ARGS(&line_array.p))));
710 D3D12_DESCRIPTOR_HEAP_DESC la_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2,
711 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
712 Ref<ID3D12DescriptorHeap> la_heap;
713 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&la_heap_desc, IID_PPV_ARGS(&la_heap.p))));
714 const std::uint64_t la_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(la_heap.p, 9))(la_heap.p);
715 const D3D12_CPU_DESCRIPTOR_HANDLE la_default{SIZE_T(la_cpu)}, la_slice0{SIZE_T(la_cpu + step)};
716 std::memset(reinterpret_cast<void*>(la_default.ptr), 0x77, step);
717 device->CreateShaderResourceView(line_array.p, nullptr, la_default);
718 EXPECT(std::all_of(reinterpret_cast<const std::uint8_t*>(la_default.ptr),
719 reinterpret_cast<const std::uint8_t*>(la_default.ptr) + step,
720 [](std::uint8_t byte) { return byte == 0; }));
721 D3D12_SHADER_RESOURCE_VIEW_DESC la_view{};
722 la_view.Format = DXGI_FORMAT_UNKNOWN;
723 la_view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
724 la_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
725 la_view.Texture1D = {1, 1, 0};
726 device->CreateShaderResourceView(line_array.p, &la_view, la_slice0);
727 g::ImageWords la_words{};
728 std::memcpy(la_words.data(), reinterpret_cast<const void*>(la_slice0.ptr), sizeof(la_words));
729 g::Image la_image{};
730 EXPECT(g::is_image(la_words) && g::decode(la_words, la_image) &&
731 la_image.type == g::ImageType::image_1d && la_image.first_mip == 1 && la_image.mip_count == 1 &&
732 la_image.first_layer == 0 && la_image.layer_count == 1);
733 std::uint32_t la_key[8]{};
734 std::memcpy(la_key, la_words.data(), sizeof(la_key));
735 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, la_key) != 0);
736 }
701 D3D12_RESOURCE_DESC ms_desc = texture_desc; 737 D3D12_RESOURCE_DESC ms_desc = texture_desc;
702 ms_desc.Width = ms_desc.Height = 4; 738 ms_desc.Width = ms_desc.Height = 4;
703 ms_desc.SampleDesc.Count = 4; 739 ms_desc.SampleDesc.Count = 4;
@@ -2166,6 +2202,47 @@ int main() {
2166#endif 2202#endif
2167 } 2203 }
2168 2204
2205 // Cross-family castable SRV: write_image_descriptor must pass resource.has_view_format_list() into a single
2206 // bind_image call so a listed R8G8B8A8_UINT -> R32_UINT view registers cleanly without a spurious first-pass
2207 // failure (and without double-binding every view).
2208 if (d.bindless) {
2209 Ref<ID3D12Device10> inner10;
2210 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&inner10.p))));
2211 D3D12_RESOURCE_DESC1 cast_desc{};
2212 cast_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2213 cast_desc.Width = 4;
2214 cast_desc.Height = 4;
2215 cast_desc.DepthOrArraySize = 1;
2216 cast_desc.MipLevels = 1;
2217 cast_desc.Format = DXGI_FORMAT_R8G8B8A8_UINT;
2218 cast_desc.SampleDesc = {1, 0};
2219 cast_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
2220 const DXGI_FORMAT cast_formats[] = {DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R32_UINT};
2221 Ref<ID3D12Resource> cast_tex;
2222 EXPECT(SUCCEEDED(inner10->CreateCommittedResource3(
2223 &default_heap, D3D12_HEAP_FLAG_NONE, &cast_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr,
2224 2, cast_formats, IID_PPV_ARGS(&cast_tex.p))));
2225 const D3D12_DESCRIPTOR_HEAP_DESC cast_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1,
2226 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
2227 Ref<ID3D12DescriptorHeap> cast_heap;
2228 EXPECT(SUCCEEDED(inner10->CreateDescriptorHeap(&cast_hd, IID_PPV_ARGS(&cast_heap.p))));
2229 const D3D12_CPU_DESCRIPTOR_HANDLE cast_slot = cast_heap->GetCPUDescriptorHandleForHeapStart();
2230 D3D12_SHADER_RESOURCE_VIEW_DESC cast_srv{};
2231 cast_srv.Format = DXGI_FORMAT_R32_UINT;
2232 cast_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2233 cast_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2234 cast_srv.Texture2D.MipLevels = 1;
2235 inner10->CreateShaderResourceView(cast_tex.p, &cast_srv, cast_slot);
2236 g::ImageWords cast_words{};
2237 std::memcpy(cast_words.data(), reinterpret_cast<const void*>(cast_slot.ptr), sizeof(cast_words));
2238 g::Image decoded{};
2239 EXPECT(g::decode(cast_words, decoded) && decoded.type == g::ImageType::image_2d);
2240 EXPECT(decoded.format == g::format_from_vulkan(VK_FORMAT_R32_UINT));
2241 std::uint32_t cast_key[8]{};
2242 std::memcpy(cast_key, cast_words.data(), sizeof(cast_key));
2243 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0);
2244 }
2245
2169 upload.reset(); 2246 upload.reset();
2170 array_texture.reset(); 2247 array_texture.reset();
2171 line.reset(); 2248 line.reset();
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 1c29d3822..12a1c71cf 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -630,7 +630,8 @@ int main() {
630 EXPECT(list->Close() == S_OK); 630 EXPECT(list->Close() == S_OK);
631 queue->ExecuteCommandLists(1, lists); 631 queue->ExecuteCommandLists(1, lists);
632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 632 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
633 EXPECT(SUCCEEDED(queue->Signal(fence.p, 4)) && SUCCEEDED(fence->SetEventOnCompletion(4, nullptr))); 633 // Above the strip passes' 20: a lower value is already reached, so the wait would return at once.
634 EXPECT(SUCCEEDED(queue->Signal(fence.p, 21)) && SUCCEEDED(fence->SetEventOnCompletion(21, nullptr)));
634 const auto* result = static_cast<const std::uint8_t*>(mapped); 635 const auto* result = static_cast<const std::uint8_t*>(mapped);
635 for (UINT row = 0; row < size; ++row) { 636 for (UINT row = 0; row < size; ++row) {
636 for (UINT col = 0; col < size; ++col) { 637 for (UINT col = 0; col < size; ++col) {
diff --git a/runtime/test/d3d12_gcl8_test.cpp b/runtime/test/d3d12_gcl8_test.cpp
index 5872a624f..8b0426e6c 100644
--- a/runtime/test/d3d12_gcl8_test.cpp
+++ b/runtime/test/d3d12_gcl8_test.cpp
@@ -36,6 +36,10 @@ int main(int argc, char** argv) {
36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); 36 EXPECT(SUCCEEDED(create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p)))); 37 EXPECT(SUCCEEDED(create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, IID_PPV_ARGS(&list7.p))));
38 38
39 // Null bindings exercise the public entry points without creating a pipeline or loading Vulkan.
40 list7.p->SetPipelineState(nullptr);
41 list7.p->SetGraphicsRootSignature(nullptr);
42
39 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held. 43 // AddRef through the GCL7 pointer gives the count this test expects while the QueryInterface reference is held.
40 const ULONG held = list7.p->AddRef(); 44 const ULONG held = list7.p->AddRef();
41 list7.p->Release(); 45 list7.p->Release();
diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp
index db8e9fd3f..8d13bf214 100644
--- a/runtime/test/d3d12_m2_textured_test.cpp
+++ b/runtime/test/d3d12_m2_textured_test.cpp
@@ -20,6 +20,7 @@
20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the 20// [1] POINT/WRAP. The left half takes the WRAP sampler (U + 1 wraps back: the gradient again), the right half the
21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The 21// CLAMP one (U + 1 clamps to the last column: each row is that row's right-edge texel of the reflected texture). The
22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection. 22// pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection.
23// The control also keeps one unbounded SRV table bound and selects its two entries by a root constant.
23// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
24#include "vk_test_device.h" 25#include "vk_test_device.h"
25#include "d3d12_test_shaders.h" 26#include "d3d12_test_shaders.h"
@@ -148,6 +149,22 @@ int main() {
148 pso_desc.SampleDesc.Count = 1; 149 pso_desc.SampleDesc.Count = 1;
149 Ref<ID3D12PipelineState> pso, uoff_pso; 150 Ref<ID3D12PipelineState> pso, uoff_pso;
150 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); 151 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
152 D3D12_DESCRIPTOR_RANGE indexed_range = srv_range;
153 indexed_range.NumDescriptors = UINT32_MAX;
154 D3D12_ROOT_PARAMETER indexed_params[3] = {params[0], params[1], {}};
155 indexed_params[0].DescriptorTable = {1, &indexed_range};
156 indexed_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
157 indexed_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
158 indexed_params[2].Constants = {0, 0, 2}; // s4 = SRV index, s5 = SRV stride in bytes
159 D3D12_VERSIONED_ROOT_SIGNATURE_DESC indexed_desc = root_desc;
160 indexed_desc.Desc_1_0.NumParameters = 3;
161 indexed_desc.Desc_1_0.pParameters = indexed_params;
162 const auto indexed_blob = serialize_root_signature(indexed_desc);
163 EXPECT(!indexed_blob.empty());
164 Ref<ID3D12RootSignature> indexed_root;
165 EXPECT(SUCCEEDED(device->CreateRootSignature(0, indexed_blob.data(), indexed_blob.size(),
166 IID_PPV_ARGS(&indexed_root.p))));
167 pso_desc.pRootSignature = indexed_root.p;
151 pso_desc.PS = {uoff_container.data(), uoff_container.size()}; 168 pso_desc.PS = {uoff_container.data(), uoff_container.size()};
152 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); 169 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p))));
153 170
@@ -350,8 +367,9 @@ int main() {
350 D3D12_RESOURCE_STATE_RENDER_TARGET); 367 D3D12_RESOURCE_STATE_RENDER_TARGET);
351 list2->ResourceBarrier(1, &back); 368 list2->ResourceBarrier(1, &back);
352 list2->ClearRenderTargetView(rtv, clear, 0, nullptr); 369 list2->ClearRenderTargetView(rtv, clear, 0, nullptr);
353 list2->SetGraphicsRootSignature(root.p); 370 list2->SetGraphicsRootSignature(indexed_root.p);
354 list2->SetDescriptorHeaps(2, heaps); 371 list2->SetDescriptorHeaps(2, heaps);
372 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu});
355 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 373 list2->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
356 list2->IASetIndexBuffer(&ibv); 374 list2->IASetIndexBuffer(&ibv);
357 list2->RSSetViewports(1, &viewport); 375 list2->RSSetViewports(1, &viewport);
@@ -359,7 +377,8 @@ int main() {
359 for (UINT half = 0; half < 2; ++half) { 377 for (UINT half = 0; half < 2; ++half) {
360 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; 378 const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)};
361 list2->RSSetScissorRects(1, &scissor); 379 list2->RSSetScissorRects(1, &scissor);
362 list2->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); 380 const UINT srv_args[] = {half, step};
381 list2->SetGraphicsRoot32BitConstants(2, 2, srv_args, 0);
363 list2->SetGraphicsRootDescriptorTable( 382 list2->SetGraphicsRootDescriptorTable(
364 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)}); 383 1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu + std::uint64_t(half == 0 ? sampler_step : 0)});
365 list2->DrawIndexedInstanced(6, 1, 0, 0, 0); 384 list2->DrawIndexedInstanced(6, 1, 0, 0, 0);
@@ -387,6 +406,7 @@ int main() {
387 uoff_pso.reset(); 406 uoff_pso.reset();
388 list2.reset(); 407 list2.reset();
389 allocator2.reset(); 408 allocator2.reset();
409 indexed_root.reset();
390 root.reset(); 410 root.reset();
391 srv_heap.reset(); 411 srv_heap.reset();
392 sampler_heap.reset(); 412 sampler_heap.reset();
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
new file mode 100644
index 000000000..bd3a555fd
--- /dev/null
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -0,0 +1,395 @@
1// Milestone M4, the synthetic part (docs/d3d12_vulkan.md section 6): a compute workload with the structure a game's asset
2// streaming and compute passes have, through the D3D12 API on the proxy, with compute shaders that are translator output
3// (test/shaders/cs_m4_fill.asm and cs_m4_indirect.asm, hand-written RDNA2).
4// Three queues' worth of work, each its own command list type:
5// COPY queue streams an input buffer: CopyBufferRegion from an UPLOAD buffer into a DEFAULT buffer that was created
6// in COMMON (promoted to COPY_DEST there), then Signal(copy fence, 1).
7// COMPUTE queue Wait(copy fence, 1), then one list: a barrier COMMON -> UNORDERED_ACCESS for the input, a compute root
8// signature (four root constants and a descriptor table of five UAVs: a structured buffer, a raw
9// buffer, an R32_UINT RWTexture2D, the raw input and a raw output), a compute PSO, and Dispatch with
10// four groups. That shader fills the structured buffer and the image from the input and writes the
11// arguments of the next dispatch into the raw buffer. Barriers (a transition of the argument buffer to
12// INDIRECT_ARGUMENT and UAV barriers on the buffer and the image) and ExecuteIndirect with a dispatch
13// command signature runs a second PSO whose group count is that buffer's first word: it reads the
14// structured buffer and the image back and writes the raw output. Everything then goes to COMMON and
15// the queue does Signal(compute fence, 1).
16// COPY queue Wait(compute fence, 1), a COPY list that copies the five results (four buffers and the image through
17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with
18// SetEventOnCompletion and an event.
19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are
20// real cross-queue semaphores); with one, they share it. Either way the three batches are submitted in dependency order.
21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the
22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the
23// first dispatch asked for ran).
24// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
25#include "vk_test_device.h"
26#include "d3d12_test_shaders.h"
27#include "../shims/d3d12_com.h"
28#include "../shims/d3d12_xs_device.h"
29#include "../src/shader_library.h"
30
31#include <array>
32#include <cstring>
33
34#ifndef LEONIDA_TEST_M4_DIR
35#error "LEONIDA_TEST_M4_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)"
36#endif
37
38#define EXPECT(condition) do { \
39 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
40} while (0)
41
42using namespace d3d12test;
43using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
44
45namespace {
46
47std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
48 std::ifstream in(path, std::ios::binary);
49 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
50}
51
52constexpr UINT records = 256; // fill: 4 groups of 64
53constexpr UINT second_groups = 3; // the indirect dispatch: 3 groups of 64
54constexpr UINT image_dim = 16; // 16 x 16 R32_UINT, one texel a record
55constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193;
56// The readback buffer: the structured buffer, the argument buffer's 16 bytes, the second output, the input, the image.
57constexpr UINT64 data_bytes = records * 16, args_bytes = 16, out2_bytes = second_groups * 64 * 8, in_bytes = records * 4;
58constexpr UINT64 offset_data = 0, offset_args = offset_data + data_bytes, offset_out2 = offset_args + args_bytes,
59 offset_in = offset_out2 + out2_bytes;
60constexpr UINT64 offset_image = (offset_in + in_bytes + 511) / 512 * 512;
61constexpr UINT image_pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
62constexpr UINT64 readback_bytes = offset_image + UINT64(image_dim) * image_pitch;
63
64std::uint32_t rotr(std::uint32_t v, unsigned n) { return (v >> n) | (v << (32 - n)); }
65std::uint32_t input_word(UINT g) { return (g + 1) * 0x9e3779b1u ^ (g << 7); }
66
67struct Reference {
68 std::vector<std::uint32_t> data, args, in, image, out2;
69};
70Reference reference() {
71 Reference ref;
72 ref.args = {second_groups, 1, 1, 0xc0de0001u};
73 ref.data.resize(records * 4);
74 ref.image.resize(image_dim * image_dim);
75 for (UINT g = 0; g < records; ++g) {
76 const std::uint32_t in = input_word(g);
77 ref.in.push_back(in);
78 ref.data[g * 4 + 0] = in + seed;
79 ref.data[g * 4 + 1] = g * multiplier;
80 ref.data[g * 4 + 2] = in ^ (g << 8);
81 ref.data[g * 4 + 3] = rotr(in, 13);
82 const UINT x = g & 15, y = g >> 4;
83 ref.image[y * image_dim + x] = in * 3 + x * 0x10001u + y;
84 }
85 for (UINT g = 0; g < second_groups * 64; ++g) {
86 const std::uint32_t t = ref.image[g]; // (g & 15, g >> 4) is texel g of the row-major image
87 ref.out2.push_back((ref.data[g * 4 + 0] + t) ^ ref.data[g * 4 + 3]);
88 ref.out2.push_back((ref.data[g * 4 + 2] ^ t) + ref.data[g * 4 + 1]);
89 }
90 return ref;
91}
92
93} // namespace
94
95int main() {
96 vktest::Device d;
97 d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two
98 const auto device_status = d.initialize();
99 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
100 if (device_status != vktest::DeviceStatus::ready) return 1;
101 if (!d.bindless) {
102 std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n");
103 return 77;
104 }
105
106 const std::filesystem::path root_dir = LEONIDA_TEST_M4_DIR;
107 leonida::ShaderLibrary library;
108 EXPECT(library.load((root_dir / "spirv").string()));
109 const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); };
110 const auto fill = program("cs_m4_fill"), indirect = program("cs_m4_indirect");
111 EXPECT(fill.size() >= 0x150 && indirect.size() >= 0x150 && fill != indirect);
112 EXPECT(library.find("cs", leonida::sha256_hex(fill)) && library.find("cs", leonida::sha256_hex(indirect)));
113 const auto fill_container = shader_container(fill), indirect_container = shader_container(indirect);
114
115 const bool distinct_queues = d.queues.size() >= 2;
116 Reference want = reference();
117 std::vector<std::uint8_t> got;
118 {
119 rt::d3d12::VulkanDeviceInfo info{};
120 info.get_instance_proc = d.instance_proc;
121 info.instance = d.instance;
122 info.physical = d.physical;
123 info.device = d.device;
124 info.queue = d.queue;
125 info.queue_family = d.family;
126 if (distinct_queues) info.command_queues = d.queues;
127 info.buffer_device_address = true;
128 info.bindless = d.bindless;
129 info.bindless_partially_bound = d.partially_bound;
130 info.image_view_min_lod = d.image_view_min_lod;
131 info.shader_dir = (root_dir / "spirv").string();
132 ID3D12Device* inner = nullptr;
133 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
134 Ref<ID3D12Device> device;
135 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
136 reinterpret_cast<void**>(&device.p))));
137 rt::d3d12::set_device_outer(inner, device.p);
138 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
139
140 // [0] four 32-bit constants (s0..s3), [1] a table of five UAVs (s[4:5]).
141 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 5, 0, 0, 0};
142 D3D12_ROOT_PARAMETER params[2] = {};
143 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
144 params[0].Constants = {0, 0, 4};
145 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
146 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
147 params[1].DescriptorTable = {1, &uav_range};
148 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
149 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
150 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
151 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
152 const auto root_blob = serialize_root_signature(root_desc);
153 EXPECT(!root_blob.empty());
154 Ref<ID3D12RootSignature> root;
155 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
156
157 D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{};
158 pso_desc.pRootSignature = root.p;
159 pso_desc.CS = {fill_container.data(), fill_container.size()};
160 Ref<ID3D12PipelineState> pso_fill, pso_indirect;
161 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_fill.p))));
162 pso_desc.CS = {indirect_container.data(), indirect_container.size()};
163 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p))));
164
165 D3D12_INDIRECT_ARGUMENT_DESC argument{};
166 argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
167 D3D12_COMMAND_SIGNATURE_DESC signature_desc{};
168 signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS);
169 signature_desc.NumArgumentDescs = 1;
170 signature_desc.pArgumentDescs = &argument;
171 Ref<ID3D12CommandSignature> signature;
172 EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p))));
173
174 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
175 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
176 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
177 constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
178 constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
179 constexpr auto common = D3D12_RESOURCE_STATE_COMMON;
180 Ref<ID3D12Resource> upload, input, data, args, out2, image, readback;
181 const auto create_buffer = [&](Ref<ID3D12Resource>& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes,
182 D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) {
183 const auto desc = buffer_desc(bytes, flags);
184 return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
185 IID_PPV_ARGS(&out.p)));
186 };
187 EXPECT(create_buffer(upload, upload_heap, in_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ));
188 EXPECT(create_buffer(input, default_heap, in_bytes, uav_flag, common));
189 EXPECT(create_buffer(data, default_heap, data_bytes, uav_flag, uav_state));
190 EXPECT(create_buffer(args, default_heap, 256, uav_flag, uav_state));
191 EXPECT(create_buffer(out2, default_heap, out2_bytes, uav_flag, uav_state));
192 EXPECT(create_buffer(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE,
193 D3D12_RESOURCE_STATE_COPY_DEST));
194 D3D12_RESOURCE_DESC image_desc{};
195 image_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
196 image_desc.Width = image_desc.Height = image_dim;
197 image_desc.DepthOrArraySize = 1;
198 image_desc.MipLevels = 1;
199 image_desc.Format = DXGI_FORMAT_R32_UINT;
200 image_desc.SampleDesc.Count = 1;
201 image_desc.Flags = uav_flag;
202 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &image_desc, uav_state,
203 nullptr, IID_PPV_ARGS(&image.p))));
204 {
205 std::uint32_t* mapped = nullptr;
206 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
207 for (UINT g = 0; g < records; ++g) mapped[g] = input_word(g);
208 upload->Unmap(0, nullptr);
209 }
210
211 // The table: slot 0 structured buffer (stride 16), 1 raw argument buffer, 2 image, 3 raw input, 4 raw output.
212 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5,
213 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
214 Ref<ID3D12DescriptorHeap> heap;
215 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
216 const std::uint64_t cpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 9))(heap.p);
217 const std::uint64_t gpu = reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p);
218 const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
219 EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot
220 const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; };
221 const auto buffer_view = [](DXGI_FORMAT format, UINT count, UINT stride, D3D12_BUFFER_UAV_FLAGS flags) {
222 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
223 view.Format = format;
224 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
225 view.Buffer = {0, count, stride, 0, flags};
226 return view;
227 };
228 auto view = buffer_view(DXGI_FORMAT_UNKNOWN, records, 16, D3D12_BUFFER_UAV_FLAG_NONE);
229 device->CreateUnorderedAccessView(data.p, nullptr, &view, handle(0));
230 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, 4, 0, D3D12_BUFFER_UAV_FLAG_RAW); // the 16 bytes of arguments
231 device->CreateUnorderedAccessView(args.p, nullptr, &view, handle(1));
232 D3D12_UNORDERED_ACCESS_VIEW_DESC image_view{};
233 image_view.Format = DXGI_FORMAT_R32_UINT;
234 image_view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
235 device->CreateUnorderedAccessView(image.p, nullptr, &image_view, handle(2));
236 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, records, 0, D3D12_BUFFER_UAV_FLAG_RAW);
237 device->CreateUnorderedAccessView(input.p, nullptr, &view, handle(3));
238 view = buffer_view(DXGI_FORMAT_R32_TYPELESS, UINT(out2_bytes / 4), 0, D3D12_BUFFER_UAV_FLAG_RAW);
239 device->CreateUnorderedAccessView(out2.p, nullptr, &view, handle(4));
240 // The V# of the structured view and the T# of the image view are what the shader loads from the table.
241 std::uint32_t v_data[4], v_args[4];
242 std::memcpy(v_data, reinterpret_cast<const void*>(handle(0).ptr), sizeof(v_data));
243 std::memcpy(v_args, reinterpret_cast<const void*>(handle(1).ptr), sizeof(v_args));
244 EXPECT(v_data[0] == std::uint32_t(data->GetGPUVirtualAddress()) && (v_data[1] >> 16 & 0x3fff) == 16 &&
245 v_data[2] == records);
246 EXPECT(v_args[0] == std::uint32_t(args->GetGPUVirtualAddress()) && (v_args[1] >> 16 & 0x3fff) == 0 &&
247 v_args[2] == 16);
248
249 D3D12_COMMAND_QUEUE_DESC queue_desc{};
250 Ref<ID3D12CommandQueue> copy_queue, compute_queue;
251 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
252 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&copy_queue.p))));
253 queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
254 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&compute_queue.p))));
255 Ref<ID3D12CommandAllocator> stream_alloc, compute_alloc, readback_alloc;
256 Ref<ID3D12GraphicsCommandList> stream_list, compute_list, readback_list;
257 Ref<ID3D12Fence> copy_fence, compute_fence;
258 const auto make_list = [&](D3D12_COMMAND_LIST_TYPE type, Ref<ID3D12CommandAllocator>& alloc,
259 Ref<ID3D12GraphicsCommandList>& list) {
260 return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&alloc.p))) &&
261 SUCCEEDED(device->CreateCommandList(0, type, alloc.p, nullptr, IID_PPV_ARGS(&list.p)));
262 };
263 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, stream_alloc, stream_list));
264 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, compute_alloc, compute_list));
265 EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, readback_alloc, readback_list));
266 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&copy_fence.p))));
267 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence.p))));
268
269 // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). This is the
270 // first submission after the UAV views were written, and a copy queue: it must not initialize the storage image
271 // (the compute queue does, in the submission that dispatches), or the data written later would be at risk.
272 stream_list->CopyBufferRegion(input.p, 0, upload.p, 0, in_bytes);
273 EXPECT(stream_list->Close() == S_OK);
274
275 D3D12_TEXTURE_COPY_LOCATION dst{}, src{};
276 dst.pResource = readback.p;
277 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
278 dst.PlacedFootprint = {offset_image, {DXGI_FORMAT_R32_UINT, image_dim, image_dim, 1, image_pitch}};
279 src.pResource = image.p;
280 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
281
282 // Compute list.
283 ID3D12DescriptorHeap* heaps[] = {heap.p};
284 D3D12_RESOURCE_BARRIER acquire = transition(input.p, common, uav_state);
285 compute_list->ResourceBarrier(1, &acquire);
286 compute_list->SetDescriptorHeaps(1, heaps);
287 compute_list->SetComputeRootSignature(root.p);
288 compute_list->SetPipelineState(pso_fill.p);
289 const std::uint32_t constants[4] = {seed, multiplier, second_groups, 0};
290 compute_list->SetComputeRoot32BitConstants(0, 4, constants, 0);
291 compute_list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu});
292 compute_list->Dispatch(records / 64, 1, 1);
293 D3D12_RESOURCE_BARRIER between[3] = {transition(args.p, uav_state, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
294 {}, {}};
295 for (int i : {1, 2}) {
296 between[i].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
297 between[i].UAV.pResource = i == 1 ? data.p : image.p;
298 }
299 compute_list->ResourceBarrier(3, between);
300 compute_list->SetPipelineState(pso_indirect.p); // the root arguments stay
301 compute_list->ExecuteIndirect(signature.p, 1, args.p, 0, nullptr, 0);
302 D3D12_RESOURCE_BARRIER release[5] = {transition(data.p, uav_state, common),
303 transition(args.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, common),
304 transition(out2.p, uav_state, common),
305 transition(input.p, uav_state, common),
306 transition(image.p, uav_state, common)};
307 compute_list->ResourceBarrier(5, release);
308 EXPECT(compute_list->Close() == S_OK);
309
310 // Copy list 2: the results to the readback buffer, once the compute queue is done.
311 readback_list->CopyBufferRegion(readback.p, offset_data, data.p, 0, data_bytes);
312 readback_list->CopyBufferRegion(readback.p, offset_args, args.p, 0, args_bytes);
313 readback_list->CopyBufferRegion(readback.p, offset_out2, out2.p, 0, out2_bytes);
314 readback_list->CopyBufferRegion(readback.p, offset_in, input.p, 0, in_bytes);
315 readback_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
316 EXPECT(readback_list->Close() == S_OK);
317
318 const auto execute = [&](ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list) {
319 ID3D12CommandList* lists[] = {list};
320 queue->ExecuteCommandLists(1, lists);
321 return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success;
322 };
323 const auto submit_copy = [&] {
324 return execute(copy_queue.p, stream_list.p) && SUCCEEDED(copy_queue->Signal(copy_fence.p, 1));
325 };
326 const auto submit_readback = [&] {
327 return SUCCEEDED(copy_queue->Wait(compute_fence.p, 1)) && execute(copy_queue.p, readback_list.p) &&
328 SUCCEEDED(copy_queue->Signal(copy_fence.p, 2));
329 };
330 const auto submit_compute = [&] {
331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) &&
332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1));
333 };
334 // In dependency order: the layer replays a list at ExecuteCommandLists and tracks every image's layout in that
335 // order, so a list that waits for another queue's signal has to be submitted after the list it waits for
336 // (the Wait-before-Signal order d3d12_queue_wait_test covers, without a resource handed over).
337 EXPECT(submit_copy() && submit_compute() && submit_readback());
338
339 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
340 EXPECT(event != nullptr);
341 EXPECT(SUCCEEDED(copy_fence->SetEventOnCompletion(2, event)));
342 if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) {
343 std::fprintf(stderr, "the copy fence never reached 2 (compute fence at %llu)\n",
344 static_cast<unsigned long long>(compute_fence->GetCompletedValue()));
345 return 1;
346 }
347 CloseHandle(event);
348 EXPECT(copy_fence->GetCompletedValue() >= 2 && compute_fence->GetCompletedValue() >= 1);
349
350 void* mapped = nullptr;
351 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
352 got.assign(static_cast<const std::uint8_t*>(mapped), static_cast<const std::uint8_t*>(mapped) + readback_bytes);
353 readback->Unmap(0, nullptr);
354
355 for (auto* r : {&upload, &input, &data, &args, &out2, &image, &readback}) r->reset();
356 stream_list.reset(); compute_list.reset(); readback_list.reset();
357 stream_alloc.reset(); compute_alloc.reset(); readback_alloc.reset();
358 copy_fence.reset(); compute_fence.reset();
359 signature.reset(); pso_fill.reset(); pso_indirect.reset(); root.reset(); heap.reset();
360 copy_queue.reset(); compute_queue.reset();
361 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
362 }
363
364 unsigned mismatches = 0, words = 0;
365 const auto compare = [&](const char* what, UINT64 offset, const std::vector<std::uint32_t>& expected, UINT pitch,
366 UINT row_words) {
367 unsigned bad = 0;
368 for (std::size_t i = 0; i < expected.size(); ++i) {
369 std::uint32_t value = 0;
370 const UINT64 at = offset + (pitch ? (i / row_words) * pitch + (i % row_words) * 4 : i * 4);
371 std::memcpy(&value, got.data() + at, 4);
372 ++words;
373 if (value == expected[i]) continue;
374 ++mismatches;
375 if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]);
376 }
377 if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size());
378 };
379 compare("input (copy queue round trip)", offset_in, want.in, 0, 0);
380 compare("structured buffer", offset_data, want.data, 0, 0);
381 compare("dispatch arguments", offset_args, want.args, 0, 0);
382 compare("image", offset_image, want.image, image_pitch, image_dim);
383 compare("indirect dispatch output", offset_out2, want.out2, 0, 0);
384 EXPECT(!mismatches);
385 if (d.validation_errors()) {
386 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
387 return 1;
388 }
389 std::printf("M4: a COPY queue streamed an input buffer in, a COMPUTE queue ran a compute PSO over a UAV table "
390 "(structured buffer, raw buffers, an R32_UINT storage image) and a second dispatch through "
391 "ExecuteIndirect from arguments the first wrote, and a COPY queue behind a cross-queue fence read the "
392 "results back (%s): %u words matched the CPU reference (error 0)\n",
393 distinct_queues ? "two VkQueues" : "one VkQueue", words);
394 return 0;
395}
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
new file mode 100644
index 000000000..cd7b411e5
--- /dev/null
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -0,0 +1,316 @@
1// Synthetic GPU test for ID3D12Device1::CreatePipelineLibrary and ID3D12PipelineLibrary / ID3D12PipelineLibrary1:
2// - empty library creation (0-byte blob), null-output capability check (S_FALSE), and invalid/foreign/corrupt
3// blob rejection (E_INVALIDARG for null pointer with non-zero size, D3D12_ERROR_DRIVER_VERSION_MISMATCH for
4// unrecognized or corrupt headers);
5// - StorePipeline (unique names, duplicate rejection, null/empty name rejection, null/foreign PSO rejection);
6// - LoadComputePipeline, LoadGraphicsPipeline, and ID3D12PipelineLibrary1::LoadPipeline (including cross-type
7// mismatch rejection when a compute PSO is requested through LoadGraphicsPipeline or vice versa);
8// - GetSerializedSize + Serialize round-trip into a second CreatePipelineLibrary;
9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1.
10// No game data.
11#include "vk_test_device.h"
12#include "d3d12_test_shaders.h"
13#include "../shims/d3d12_com.h"
14#include "../src/shader_library.h"
15
16#include <cstring>
17#include <filesystem>
18#include <fstream>
19#include <vector>
20
21#if !defined(LEONIDA_TEST_CS_SPV) || !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV)
22#error "LEONIDA_TEST_CS_SPV, LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must be defined"
23#endif
24
25#define EXPECT(condition) do { \
26 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
27} while (0)
28
29using namespace d3d12test;
30
31namespace {
32
33struct Vertex {
34 float x, y;
35 std::uint8_t r, g, b, a;
36};
37
38D3D12_RESOURCE_DESC tex2d_desc(UINT w, UINT h, DXGI_FORMAT fmt, D3D12_RESOURCE_FLAGS flags) {
39 D3D12_RESOURCE_DESC d{};
40 d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
41 d.Width = w;
42 d.Height = h;
43 d.DepthOrArraySize = 1;
44 d.MipLevels = 1;
45 d.Format = fmt;
46 d.SampleDesc = {1, 0};
47 d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
48 d.Flags = flags;
49 return d;
50}
51
52} // namespace
53
54int main() {
55 vktest::Device d;
56 const auto status = d.initialize();
57 if (status == vktest::DeviceStatus::unavailable) {
58 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
59 return 77;
60 }
61 EXPECT(status == vktest::DeviceStatus::ready);
62
63 const auto cs_prog = fssm_program({0x43532001, 0xbf810000});
64 const auto vs_prog = fssm_program({0x56532001, 0xbf810000});
65 const auto ps_prog = fssm_program({0x50532001, 0xbf810000});
66 const auto cs_dxbc = shader_container(cs_prog);
67 const auto vs_dxbc = shader_container(vs_prog);
68 const auto ps_dxbc = shader_container(ps_prog);
69
70 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test";
71 std::filesystem::create_directories(lib_dir);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, lib_dir / "cs.spv",
73 std::filesystem::copy_options::overwrite_existing);
74 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, lib_dir / "vs.spv",
75 std::filesystem::copy_options::overwrite_existing);
76 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, lib_dir / "ps.spv",
77 std::filesystem::copy_options::overwrite_existing);
78 {
79 std::ofstream idx(lib_dir / "index.json", std::ios::binary);
80 idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog)
81 << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n"
82 " \"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog)
83 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": ["
84 "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, "
85 "\"system_value\": 0, \"component_type\": \"float\"}, "
86 "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, "
87 "\"system_value\": 0, \"component_type\": \"float\"}]},\n"
88 " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_prog)
89 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}";
90 }
91
92 rt::d3d12::VulkanDeviceInfo info{};
93 info.get_instance_proc = d.instance_proc;
94 info.instance = d.instance;
95 info.physical = d.physical;
96 info.device = d.device;
97 info.queue = d.queue;
98 info.queue_family = d.family;
99 info.buffer_device_address = true;
100 info.shader_dir = lib_dir.string();
101
102 Ref<ID3D12Device1> device;
103 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
104
105 // 1. CreatePipelineLibrary creation, capability check (null output -> S_FALSE), and invalid/corrupt blobs.
106 {
107 EXPECT(device->CreatePipelineLibrary(nullptr, 0, __uuidof(ID3D12PipelineLibrary), nullptr) == S_FALSE);
108 Ref<ID3D12PipelineLibrary> bad;
109 EXPECT(device->CreatePipelineLibrary(nullptr, 16, IID_PPV_ARGS(&bad.p)) == E_INVALIDARG && !bad.p);
110 const std::uint32_t foreign[4] = {0xDEADBEEFu, 1u, 0u, 0u};
111 EXPECT(device->CreatePipelineLibrary(foreign, sizeof(foreign), IID_PPV_ARGS(&bad.p)) ==
112 D3D12_ERROR_DRIVER_VERSION_MISMATCH &&
113 !bad.p);
114 const std::uint8_t tiny[4] = {1, 2, 3, 4};
115 EXPECT(device->CreatePipelineLibrary(tiny, sizeof(tiny), IID_PPV_ARGS(&bad.p)) ==
116 D3D12_ERROR_DRIVER_VERSION_MISMATCH &&
117 !bad.p);
118 }
119
120 // 2. Build one compute PSO and one graphics PSO.
121 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0};
122 D3D12_ROOT_PARAMETER cs_params[3]{};
123 cs_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
124 cs_params[0].Constants = {0, 0, 1};
125 cs_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
126 cs_params[1].Descriptor = {0, 0};
127 cs_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
128 cs_params[2].DescriptorTable = {1, &uav_range};
129 D3D12_VERSIONED_ROOT_SIGNATURE_DESC cs_rs_desc{};
130 cs_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
131 cs_rs_desc.Desc_1_0 = {3, cs_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
132 const auto cs_rs_blob = serialize_root_signature(cs_rs_desc);
133 Ref<ID3D12RootSignature> cs_rs;
134 EXPECT(SUCCEEDED(device->CreateRootSignature(0, cs_rs_blob.data(), cs_rs_blob.size(), IID_PPV_ARGS(&cs_rs.p))));
135
136 D3D12_COMPUTE_PIPELINE_STATE_DESC cs_desc{};
137 cs_desc.pRootSignature = cs_rs.p;
138 cs_desc.CS = {cs_dxbc.data(), cs_dxbc.size()};
139 Ref<ID3D12PipelineState> cs_pso;
140 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&cs_desc, IID_PPV_ARGS(&cs_pso.p))));
141
142 D3D12_ROOT_PARAMETER gfx_params[2]{};
143 gfx_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
144 gfx_params[0].Constants = {0, 0, 2};
145 gfx_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
146 gfx_params[1].Descriptor = {1, 0};
147 D3D12_VERSIONED_ROOT_SIGNATURE_DESC gfx_rs_desc{};
148 gfx_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
149 gfx_rs_desc.Desc_1_0 = {2, gfx_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
150 const auto gfx_rs_blob = serialize_root_signature(gfx_rs_desc);
151 Ref<ID3D12RootSignature> gfx_rs;
152 EXPECT(SUCCEEDED(device->CreateRootSignature(0, gfx_rs_blob.data(), gfx_rs_blob.size(), IID_PPV_ARGS(&gfx_rs.p))));
153
154 const D3D12_INPUT_ELEMENT_DESC input_elems[2] = {
155 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
156 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT,
157 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
158 };
159 D3D12_GRAPHICS_PIPELINE_STATE_DESC gfx_desc{};
160 gfx_desc.pRootSignature = gfx_rs.p;
161 gfx_desc.VS = {vs_dxbc.data(), vs_dxbc.size()};
162 gfx_desc.PS = {ps_dxbc.data(), ps_dxbc.size()};
163 gfx_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
164 gfx_desc.SampleMask = 0xFFFFFFFFu;
165 gfx_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
166 gfx_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
167 gfx_desc.RasterizerState.DepthClipEnable = TRUE;
168 gfx_desc.InputLayout = {input_elems, 2};
169 gfx_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
170 gfx_desc.NumRenderTargets = 1;
171 gfx_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
172 gfx_desc.SampleDesc = {1, 0};
173 Ref<ID3D12PipelineState> gfx_pso;
174 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&gfx_desc, IID_PPV_ARGS(&gfx_pso.p))));
175
176 // 3. Store, load, cross-type rejection, and serialize round-trip.
177 Ref<ID3D12PipelineLibrary1> lib;
178 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(nullptr, 0, IID_PPV_ARGS(&lib.p))) && lib.p);
179 Ref<ID3D12Device> parent_dev;
180 EXPECT(SUCCEEDED(lib->GetDevice(IID_PPV_ARGS(&parent_dev.p))) && parent_dev.p);
181
182 EXPECT(lib->StorePipeline(nullptr, cs_pso.p) == E_INVALIDARG);
183 EXPECT(lib->StorePipeline(L"", cs_pso.p) == E_INVALIDARG);
184 EXPECT(lib->StorePipeline(L"cs", nullptr) == E_INVALIDARG);
185 EXPECT(SUCCEEDED(lib->StorePipeline(L"cs", cs_pso.p)));
186 EXPECT(lib->StorePipeline(L"cs", cs_pso.p) == E_INVALIDARG); // duplicate name
187 EXPECT(SUCCEEDED(lib->StorePipeline(L"gfx", gfx_pso.p)));
188
189 Ref<ID3D12PipelineState> loaded_cs, loaded_gfx, loaded_any, wrong;
190 EXPECT(lib->LoadComputePipeline(L"missing", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
191 EXPECT(lib->LoadComputePipeline(L"gfx", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
192 EXPECT(lib->LoadGraphicsPipeline(L"cs", &gfx_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
193 EXPECT(SUCCEEDED(lib->LoadComputePipeline(L"cs", &cs_desc, IID_PPV_ARGS(&loaded_cs.p))) && loaded_cs.p);
194 EXPECT(SUCCEEDED(lib->LoadGraphicsPipeline(L"gfx", &gfx_desc, IID_PPV_ARGS(&loaded_gfx.p))) && loaded_gfx.p);
195
196 std::uint32_t dummy_stream = 0;
197 D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(dummy_stream), &dummy_stream};
198 D3D12_PIPELINE_STATE_STREAM_DESC empty_stream{0, nullptr};
199 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
200 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p);
201
202 const SIZE_T blob_size = lib->GetSerializedSize();
203 EXPECT(blob_size >= 16);
204 std::vector<std::uint8_t> blob(blob_size);
205 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG);
206 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG);
207 EXPECT(SUCCEEDED(lib->Serialize(blob.data(), blob_size)));
208
209 Ref<ID3D12PipelineLibrary> reloaded;
210 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p);
211
212 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU.
213 Ref<ID3D12CommandQueue> queue;
214 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
215 EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
216 Ref<ID3D12CommandAllocator> alloc;
217 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))));
218 Ref<ID3D12GraphicsCommandList> list;
219 EXPECT(SUCCEEDED(
220 device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p))));
221 Ref<ID3D12Fence> fence;
222 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
223
224 constexpr UINT W = 16, H = 16;
225 const D3D12_HEAP_PROPERTIES hp_def{D3D12_HEAP_TYPE_DEFAULT};
226 const D3D12_HEAP_PROPERTIES hp_up{D3D12_HEAP_TYPE_UPLOAD};
227 const D3D12_HEAP_PROPERTIES hp_rb{D3D12_HEAP_TYPE_READBACK};
228 const auto rtd = tex2d_desc(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
229 const Vertex verts[4] = {
230 {-1.0f, 1.0f, 255, 0, 0, 255},
231 { 0.0f, 1.0f, 255, 0, 0, 255},
232 { 0.0f, 0.0f, 255, 0, 0, 255},
233 {-1.0f, 0.0f, 255, 0, 0, 255},
234 };
235 const std::uint16_t indices[6] = {0, 1, 2, 0, 2, 3};
236 const float tint[4] = {1.0f, 0.0f, 1.0f, 1.0f};
237 const auto vbd = buffer_desc(sizeof(verts));
238 const auto ibd = buffer_desc(sizeof(indices));
239 const auto cbd = buffer_desc(256);
240 Ref<ID3D12Resource> rt, vb, ib, cb, rb;
241 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_def, D3D12_HEAP_FLAG_NONE, &rtd,
242 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&rt.p))));
243 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &vbd,
244 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vb.p))));
245 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &ibd,
246 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&ib.p))));
247 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &cbd,
248 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&cb.p))));
249 void* p = nullptr;
250 EXPECT(SUCCEEDED(vb->Map(0, nullptr, &p)));
251 std::memcpy(p, verts, sizeof(verts));
252 vb->Unmap(0, nullptr);
253 EXPECT(SUCCEEDED(ib->Map(0, nullptr, &p)));
254 std::memcpy(p, indices, sizeof(indices));
255 ib->Unmap(0, nullptr);
256 EXPECT(SUCCEEDED(cb->Map(0, nullptr, &p)));
257 std::memcpy(p, tint, sizeof(tint));
258 cb->Unmap(0, nullptr);
259
260 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
261 UINT64 total_bytes = 0;
262 device->GetCopyableFootprints(&rtd, 0, 1, 0, &fp, nullptr, nullptr, &total_bytes);
263 const auto rbd = buffer_desc(total_bytes);
264 EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_rb, D3D12_HEAP_FLAG_NONE, &rbd,
265 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb.p))));
266
267 Ref<ID3D12DescriptorHeap> rtv_heap;
268 const D3D12_DESCRIPTOR_HEAP_DESC rhd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
269 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rhd, IID_PPV_ARGS(&rtv_heap.p))));
270 const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
271 device->CreateRenderTargetView(rt.p, nullptr, rtv);
272
273 const float blue[4] = {0.0f, 0.0f, 1.0f, 1.0f};
274 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
275 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
276 const D3D12_VIEWPORT vp{0, 0, float(W), float(H), 0.0f, 1.0f};
277 const D3D12_RECT sc{0, 0, LONG(W), LONG(H)};
278 list->RSSetViewports(1, &vp);
279 list->RSSetScissorRects(1, &sc);
280 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
281 const D3D12_VERTEX_BUFFER_VIEW vbv{vb->GetGPUVirtualAddress(), sizeof(verts), sizeof(Vertex)};
282 const D3D12_INDEX_BUFFER_VIEW ibv{ib->GetGPUVirtualAddress(), sizeof(indices), DXGI_FORMAT_R16_UINT};
283 list->IASetVertexBuffers(0, 1, &vbv);
284 list->IASetIndexBuffer(&ibv);
285 list->SetGraphicsRootSignature(gfx_rs.p);
286 const float offset[2] = {0.0f, 0.0f};
287 list->SetGraphicsRoot32BitConstants(0, 2, offset, 0);
288 list->SetGraphicsRootConstantBufferView(1, cb->GetGPUVirtualAddress());
289 list->SetPipelineState(loaded_gfx.p);
290 list->DrawIndexedInstanced(6, 1, 0, 0, 0);
291
292 const auto to_src = transition(rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
293 list->ResourceBarrier(1, &to_src);
294 D3D12_TEXTURE_COPY_LOCATION src_loc{rt.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}};
295 D3D12_TEXTURE_COPY_LOCATION dst_loc{rb.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
296 dst_loc.PlacedFootprint = fp;
297 list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr);
298 EXPECT(SUCCEEDED(list->Close()));
299 ID3D12CommandList* lists[] = {list.p};
300 queue->ExecuteCommandLists(1, lists);
301 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
302 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
303
304 EXPECT(SUCCEEDED(rb->Map(0, nullptr, &p)));
305 const auto* bytes = static_cast<const std::uint8_t*>(p);
306 std::uint32_t tl = 0, br = 0;
307 std::memcpy(&tl, bytes + 2 * fp.Footprint.RowPitch + 2 * 4, 4);
308 std::memcpy(&br, bytes + 12 * fp.Footprint.RowPitch + 12 * 4, 4);
309 EXPECT(tl == 0xFF0000FFu); // red quad drawn by PSO loaded from PipelineLibrary
310 EXPECT(br == 0xFFFF0000u); // blue background clear
311 rb->Unmap(0, nullptr);
312
313 EXPECT(d.validation_errors() == 0);
314 std::printf("d3d12_pipeline_library_test: ok\n");
315 return 0;
316}
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 8b28eb67a..f01fb902b 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -115,6 +115,8 @@ int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore fr
115bool fail_surface_formats = false; // armed: the next surface-format query fails before creation 115bool fail_surface_formats = false; // armed: the next surface-format query fails before creation
116bool observe_next_swapchain = false; 116bool observe_next_swapchain = false;
117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF) 117bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF)
118bool undefined_extent_queried = false;
119VkExtent2D last_swapchain_extent{};
118VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE; 120VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE;
119VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE; 121VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE;
120unsigned out_of_date = 0; // presents the real driver reported out of date 122unsigned out_of_date = 0; // presents the real driver reported out of date
@@ -170,6 +172,7 @@ VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice physical, VkSurf
170 172
171VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapchainCreateInfoKHR* info, 173VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapchainCreateInfoKHR* info,
172 const VkAllocationCallbacks* allocator, VkSwapchainKHR* out) { 174 const VkAllocationCallbacks* allocator, VkSwapchainKHR* out) {
175 if (info) last_swapchain_extent = info->imageExtent;
173 if (observe_next_swapchain) { 176 if (observe_next_swapchain) {
174 observed_old_swapchain = info->oldSwapchain; 177 observed_old_swapchain = info->oldSwapchain;
175 observe_next_swapchain = false; 178 observe_next_swapchain = false;
@@ -185,6 +188,7 @@ VKAPI_ATTR VkResult VKAPI_CALL get_surface_capabilities(VkPhysicalDevice physica
185 if (result == VK_SUCCESS && report_undefined_extent && caps) { 188 if (result == VK_SUCCESS && report_undefined_extent && caps) {
186 caps->currentExtent.width = 0xFFFFFFFF; 189 caps->currentExtent.width = 0xFFFFFFFF;
187 caps->currentExtent.height = 0xFFFFFFFF; 190 caps->currentExtent.height = 0xFFFFFFFF;
191 undefined_extent_queried = true;
188 } 192 }
189 return result; 193 return result;
190} 194}
@@ -409,9 +413,14 @@ int main() {
409 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); 413 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr)));
410 414
411 // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165): 415 // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165):
412 // the presenter queries the window client extent and clamps to surface bounds. 416 // switch vsync to 0 to force swapchain recreation, verifying that vkGetPhysicalDeviceSurfaceCapabilitiesKHR
417 // is reached while armed and that vkCreateSwapchainKHR receives the clamped client extent (400x300)
418 // instead of 0xFFFFFFFF.
413 driver::report_undefined_extent = true; 419 driver::report_undefined_extent = true;
414 EXPECT(frame(1)); 420 driver::undefined_extent_queried = false;
421 EXPECT(frame(0));
422 EXPECT(driver::undefined_extent_queried);
423 EXPECT(driver::last_swapchain_extent.width == 400 && driver::last_swapchain_extent.height == 300);
415 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); 424 EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300);
416 driver::report_undefined_extent = false; 425 driver::report_undefined_extent = false;
417 426
diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp
index 80bd911c1..c6b660dda 100644
--- a/runtime/test/d3d12_translated_draw_test.cpp
+++ b/runtime/test/d3d12_translated_draw_test.cpp
@@ -63,8 +63,8 @@ struct Vertex {
63}; 63};
64 64
65using Pixel = std::array<float, 4>; 65using Pixel = std::array<float, 4>;
66constexpr UINT extent = 64; 66constexpr UINT target_extent = 64;
67constexpr UINT pitch = extent * sizeof(Pixel); // 1024, a multiple of 256 67constexpr UINT pitch = target_extent * sizeof(Pixel); // 1024, a multiple of 256
68 68
69// A V# for the vertex records: stride 32, `records` records, format 32_32_32_32_FLOAT, identity swizzle. The 69// A V# for the vertex records: stride 32, `records` records, format 32_32_32_32_FLOAT, identity swizzle. The
70// out-of-range mode is structured (an index checked against num_records), which is what the hardware does with an 70// out-of-range mode is structured (an index checked against num_records), which is what the hardware does with an
@@ -113,7 +113,7 @@ int main() {
113 vertex(-1, 0, c2), vertex(-1, -1, c2), vertex(0, -1, c2)}; 113 vertex(-1, 0, c2), vertex(-1, -1, c2), vertex(0, -1, c2)};
114 static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 288); 114 static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 288);
115 115
116 std::vector<Pixel> pixels(extent * extent); 116 std::vector<Pixel> pixels(target_extent * target_extent);
117 { 117 {
118 rt::d3d12::VulkanDeviceInfo info{}; 118 rt::d3d12::VulkanDeviceInfo info{};
119 info.get_instance_proc = d.instance_proc; 119 info.get_instance_proc = d.instance_proc;
@@ -178,13 +178,13 @@ int main() {
178 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, 178 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
179 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, 179 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
180 IID_PPV_ARGS(&upload.p)))); 180 IID_PPV_ARGS(&upload.p))));
181 const auto readback_desc = buffer_desc(pitch * extent); 181 const auto readback_desc = buffer_desc(pitch * target_extent);
182 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, 182 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
183 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 183 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
184 IID_PPV_ARGS(&readback.p)))); 184 IID_PPV_ARGS(&readback.p))));
185 D3D12_RESOURCE_DESC rt_desc{}; 185 D3D12_RESOURCE_DESC rt_desc{};
186 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 186 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
187 rt_desc.Width = rt_desc.Height = extent; 187 rt_desc.Width = rt_desc.Height = target_extent;
188 rt_desc.DepthOrArraySize = 1; 188 rt_desc.DepthOrArraySize = 1;
189 rt_desc.MipLevels = 1; 189 rt_desc.MipLevels = 1;
190 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; 190 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
@@ -245,8 +245,8 @@ int main() {
245 ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; 245 ID3D12DescriptorHeap* heaps[] = {srv_heap.p};
246 list->SetDescriptorHeaps(1, heaps); 246 list->SetDescriptorHeaps(1, heaps);
247 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 247 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
248 const D3D12_VIEWPORT viewport{0, 0, float(extent), float(extent), 0, 1}; 248 const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1};
249 const D3D12_RECT scissor{0, 0, LONG(extent), LONG(extent)}; 249 const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)};
250 list->RSSetViewports(1, &viewport); 250 list->RSSetViewports(1, &viewport);
251 list->RSSetScissorRects(1, &scissor); 251 list->RSSetScissorRects(1, &scissor);
252 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); 252 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
@@ -271,7 +271,7 @@ int main() {
271 D3D12_TEXTURE_COPY_LOCATION dst{}; 271 D3D12_TEXTURE_COPY_LOCATION dst{};
272 dst.pResource = readback.p; 272 dst.pResource = readback.p;
273 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; 273 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
274 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, extent, extent, 1, pitch}}; 274 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}};
275 D3D12_TEXTURE_COPY_LOCATION src{}; 275 D3D12_TEXTURE_COPY_LOCATION src{};
276 src.pResource = target.p; 276 src.pResource = target.p;
277 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; 277 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
@@ -302,10 +302,10 @@ int main() {
302 const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f}; 302 const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f};
303 const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f}; 303 const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f};
304 unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0; 304 unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0;
305 for (UINT row = 0; row < extent; ++row) { 305 for (UINT row = 0; row < target_extent; ++row) {
306 for (UINT col = 0; col < extent; ++col) { 306 for (UINT col = 0; col < target_extent; ++col) {
307 const bool top = row < extent / 2, left = col < extent / 2; 307 const bool top = row < target_extent / 2, left = col < target_extent / 2;
308 const Pixel& got = pixels[row * extent + col]; 308 const Pixel& got = pixels[row * target_extent + col];
309 const auto bits_equal = [&](const Pixel& want) { return std::memcmp(&got, &want, sizeof(Pixel)) == 0; }; 309 const auto bits_equal = [&](const Pixel& want) { return std::memcmp(&got, &want, sizeof(Pixel)) == 0; };
310 const Pixel* want; 310 const Pixel* want;
311 if (top) { 311 if (top) {
@@ -340,6 +340,6 @@ int main() {
340 "pixels on the triangle's diagonal (%u its colour, %u the clear colour). User data from a descriptor " 340 "pixels on the triangle's diagonal (%u its colour, %u the clear colour). User data from a descriptor "
341 "table and root constants, V# vertex fetch from the arena, PS constants " 341 "table and root constants, V# vertex fetch from the arena, PS constants "
342 "through the code base\n", 342 "through the code base\n",
343 extent * extent - edge, extent * extent, edge, edge_triangle, edge_clear); 343 target_extent * target_extent - edge, target_extent * target_extent, edge, edge_triangle, edge_clear);
344 return 0; 344 return 0;
345} 345}
diff --git a/runtime/test/d3d12_typeless_rtv_test.cpp b/runtime/test/d3d12_typeless_rtv_test.cpp
index cc6054f85..d8b8d841e 100644
--- a/runtime/test/d3d12_typeless_rtv_test.cpp
+++ b/runtime/test/d3d12_typeless_rtv_test.cpp
@@ -213,19 +213,36 @@ bool clear_and_read(ID3D12Device* device, DXGI_FORMAT whole_format, DXGI_FORMAT
213 return true; 213 return true;
214} 214}
215bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view, 215bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view,
216 UINT16 mips = 1, UINT16 layers = 1) { 216 UINT16 mips = 1, UINT16 layers = 1, UINT samples = 1,
217 const DXGI_FORMAT* cast_list = nullptr, UINT32 cast_count = 0) {
217 Ref<ID3D12Resource> resource; 218 Ref<ID3D12Resource> resource;
218 D3D12_HEAP_PROPERTIES heap_properties{D3D12_HEAP_TYPE_DEFAULT}; 219 D3D12_HEAP_PROPERTIES heap_properties{D3D12_HEAP_TYPE_DEFAULT};
219 D3D12_RESOURCE_DESC texture{}; 220 if (cast_count) {
220 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 221 Ref<ID3D12Device10> device10;
221 texture.Width = texture.Height = 4; 222 CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p))));
222 texture.DepthOrArraySize = layers; 223 D3D12_RESOURCE_DESC1 tex1{};
223 texture.MipLevels = mips; 224 tex1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
224 texture.Format = resource_format; 225 tex1.Width = tex1.Height = 4;
225 texture.SampleDesc.Count = 1; 226 tex1.DepthOrArraySize = layers;
226 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; 227 tex1.MipLevels = mips;
227 CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, 228 tex1.Format = resource_format;
228 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&resource.p)))); 229 tex1.SampleDesc.Count = samples;
230 tex1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
231 CHECK(SUCCEEDED(device10->CreateCommittedResource3(&heap_properties, D3D12_HEAP_FLAG_NONE, &tex1,
232 D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, cast_count, cast_list,
233 IID_PPV_ARGS(&resource.p))));
234 } else {
235 D3D12_RESOURCE_DESC texture{};
236 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
237 texture.Width = texture.Height = 4;
238 texture.DepthOrArraySize = layers;
239 texture.MipLevels = mips;
240 texture.Format = resource_format;
241 texture.SampleDesc.Count = samples;
242 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
243 CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture,
244 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&resource.p))));
245 }
229 Ref<ID3D12DescriptorHeap> heap; 246 Ref<ID3D12DescriptorHeap> heap;
230 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; 247 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
231 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); 248 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p))));
@@ -237,7 +254,7 @@ bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12
237 const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); 254 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
238 // For the supported shape, overwrite a valid slot too: rejection must not leave its old RTV active. 255 // For the supported shape, overwrite a valid slot too: rejection must not leave its old RTV active.
239 D3D12_RENDER_TARGET_VIEW_DESC seed{}; 256 D3D12_RENDER_TARGET_VIEW_DESC seed{};
240 seed.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; 257 seed.ViewDimension = samples > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS : D3D12_RTV_DIMENSION_TEXTURE2D;
241 seed.Format = resource_format == DXGI_FORMAT_R8G8B8A8_TYPELESS ? DXGI_FORMAT_R8G8B8A8_UNORM : resource_format; 258 seed.Format = resource_format == DXGI_FORMAT_R8G8B8A8_TYPELESS ? DXGI_FORMAT_R8G8B8A8_UNORM : resource_format;
242 device->CreateRenderTargetView(resource.p, &seed, handle); 259 device->CreateRenderTargetView(resource.p, &seed, handle);
243 device->CreateRenderTargetView(resource.p, view, handle); 260 device->CreateRenderTargetView(resource.p, view, handle);
@@ -246,6 +263,150 @@ bool rejects_view(ID3D12Device* device, DXGI_FORMAT resource_format, const D3D12
246 CHECK(list->Close() == E_INVALIDARG); // The invalid list is never sent to the GPU. 263 CHECK(list->Close() == E_INVALIDARG); // The invalid list is never sent to the GPU.
247 return true; 264 return true;
248} 265}
266
267bool clear_and_read_msaa(ID3D12Device* device, DXGI_FORMAT resource_format,
268 const DXGI_FORMAT* cast_list, UINT32 cast_count,
269 DXGI_FORMAT whole_format, DXGI_FORMAT rect_format, bool partial,
270 bool array, UINT first_layer, UINT layer_count,
271 std::vector<unsigned char>& pixels) {
272 Ref<ID3D12CommandQueue> queue;
273 Ref<ID3D12CommandAllocator> allocator;
274 Ref<ID3D12GraphicsCommandList> list;
275 Ref<ID3D12Fence> fence;
276 D3D12_COMMAND_QUEUE_DESC queue_desc{};
277 CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
278 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
279 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
280 IID_PPV_ARGS(&list.p))));
281 CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
282
283 constexpr UINT width = 5, height = 3;
284 const UINT16 layers = array ? 4 : 1;
285 Ref<ID3D12Resource> msaa, resolved, readback;
286 D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
287 if (cast_count) {
288 Ref<ID3D12Device10> device10;
289 CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p))));
290 D3D12_RESOURCE_DESC1 tex1{};
291 tex1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
292 tex1.Width = width;
293 tex1.Height = height;
294 tex1.DepthOrArraySize = layers;
295 tex1.MipLevels = 1;
296 tex1.Format = resource_format;
297 tex1.SampleDesc.Count = 4;
298 tex1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
299 CHECK(SUCCEEDED(device10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &tex1,
300 D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, cast_count, cast_list,
301 IID_PPV_ARGS(&msaa.p))));
302 } else {
303 D3D12_RESOURCE_DESC tex{};
304 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
305 tex.Width = width;
306 tex.Height = height;
307 tex.DepthOrArraySize = layers;
308 tex.MipLevels = 1;
309 tex.Format = resource_format;
310 tex.SampleDesc.Count = 4;
311 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
312 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex,
313 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&msaa.p))));
314 }
315 D3D12_RESOURCE_DESC resolved_desc{};
316 resolved_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
317 resolved_desc.Width = width;
318 resolved_desc.Height = height;
319 resolved_desc.DepthOrArraySize = layers;
320 resolved_desc.MipLevels = 1;
321 resolved_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
322 resolved_desc.SampleDesc.Count = 1;
323 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &resolved_desc,
324 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr, IID_PPV_ARGS(&resolved.p))));
325
326 std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placed(layers);
327 UINT64 total = 0;
328 device->GetCopyableFootprints(&resolved_desc, 0, layers, 0, placed.data(), nullptr, nullptr, &total);
329 D3D12_RESOURCE_DESC buf{};
330 buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
331 buf.Width = total;
332 buf.Height = buf.SampleDesc.Count = 1;
333 buf.DepthOrArraySize = buf.MipLevels = 1;
334 buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
335 D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK};
336 CHECK(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &buf,
337 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p))));
338
339 Ref<ID3D12DescriptorHeap> rtv_heap;
340 const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
341 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap.p))));
342 const auto h0 = rtv_heap->GetCPUDescriptorHandleForHeapStart();
343 const D3D12_CPU_DESCRIPTOR_HANDLE h1{h0.ptr + device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)};
344
345 D3D12_RENDER_TARGET_VIEW_DESC view{};
346 view.ViewDimension = array ? D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY : D3D12_RTV_DIMENSION_TEXTURE2DMS;
347 if (array) {
348 view.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
349 for (UINT layer = 0; layer < layers; ++layer) {
350 view.Texture2DMSArray = {layer, 1};
351 device->CreateRenderTargetView(msaa.p, &view, h0);
352 const FLOAT seed[] = {FLOAT(layer + 1) * 0.1f, 0.2f, 0.3f, 1.0f};
353 list->ClearRenderTargetView(h0, seed, 0, nullptr);
354 }
355 view.Texture2DMSArray = {first_layer, layer_count};
356 }
357 view.Format = whole_format;
358 device->CreateRenderTargetView(msaa.p, &view, h0);
359 view.Format = rect_format;
360 device->CreateRenderTargetView(msaa.p, &view, h1);
361 const FLOAT full[4] = {0.25f, 0.5f, 0.75f, 0.25f};
362 const FLOAT part[4] = {0.0031308f, 0.18f, 0.5f, 0.75f};
363 list->ClearRenderTargetView(h0, full, 0, nullptr);
364 const D3D12_RECT rect{1, 1, 4, 3};
365 if (partial) list->ClearRenderTargetView(h1, part, 1, &rect);
366
367 D3D12_RESOURCE_BARRIER b{};
368 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
369 b.Transition = {msaa.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
370 D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE};
371 list->ResourceBarrier(1, &b);
372 for (UINT layer = 0; layer < layers; ++layer)
373 list->ResolveSubresource(resolved.p, layer, msaa.p, layer, DXGI_FORMAT_R8G8B8A8_UNORM);
374 b.Transition = {resolved.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
375 D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
376 list->ResourceBarrier(1, &b);
377 D3D12_TEXTURE_COPY_LOCATION src{}, dst{};
378 src.pResource = resolved.p;
379 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
380 dst.pResource = readback.p;
381 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
382 for (UINT layer = 0; layer < layers; ++layer) {
383 src.SubresourceIndex = layer;
384 dst.PlacedFootprint = placed[layer];
385 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
386 }
387 CHECK(SUCCEEDED(list->Close()));
388 ID3D12CommandList* lists[] = {list.p};
389 queue->ExecuteCommandLists(1, lists);
390 CHECK(SUCCEEDED(queue->Signal(fence.p, 1)));
391 Event event;
392 CHECK(event.handle);
393 CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle)));
394 CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
395 void* mapped = nullptr;
396 const D3D12_RANGE range{0, SIZE_T(total)};
397 CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped);
398 pixels.clear();
399 for (const auto& footprint : placed) {
400 const auto& f = footprint.Footprint;
401 for (UINT y = 0; y < f.Height; ++y) {
402 const auto* row = static_cast<unsigned char*>(mapped) + footprint.Offset + y * f.RowPitch;
403 pixels.insert(pixels.end(), row, row + f.Width * 4);
404 }
405 }
406 const D3D12_RANGE none{};
407 readback->Unmap(0, &none);
408 return true;
409}
249} // namespace 410} // namespace
250 411
251int main() { 412int main() {
@@ -452,8 +613,10 @@ int main() {
452 regressions, vk.conditional_rendering ? "enabled" : "unavailable (predicated cases skipped)"); 613 regressions, vk.conditional_rendering ? "enabled" : "unavailable (predicated cases skipped)");
453 if (mismatches) return 1; 614 if (mismatches) return 1;
454 const auto rejects = [&](DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view, 615 const auto rejects = [&](DXGI_FORMAT resource_format, const D3D12_RENDER_TARGET_VIEW_DESC* view,
455 UINT16 mips = 1, UINT16 layers = 1) { 616 UINT16 mips = 1, UINT16 layers = 1, UINT samples = 1,
456 if (!rejects_view(ours.p, resource_format, view, mips, layers)) return false; 617 const DXGI_FORMAT* cast_list = nullptr, UINT32 cast_count = 0) {
618 if (!rejects_view(ours.p, resource_format, view, mips, layers, samples, cast_list, cast_count))
619 return false;
457 ++rejected; 620 ++rejected;
458 return true; 621 return true;
459 }; 622 };
@@ -501,6 +664,64 @@ int main() {
501 invalid.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; 664 invalid.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
502 invalid.Texture2DArray = {1, 1, 2, 1}; 665 invalid.Texture2DArray = {1, 1, 2, 1};
503 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &invalid, 3, 4)) return 1; 666 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &invalid, 3, 4)) return 1;
667
668 // 4x MSAA typeless and castable RGBA8 RTVs (TEXTURE2DMS / TEXTURE2DMSARRAY) compared against WARP.
669 {
670 const DXGI_FORMAT srgb_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
671 const auto compare_msaa = [&](DXGI_FORMAT resource_format, const DXGI_FORMAT* cast_list,
672 UINT32 cast_count, DXGI_FORMAT full, DXGI_FORMAT rect, bool partial,
673 bool array, UINT first_layer, UINT layer_count) {
674 std::vector<unsigned char> actual, expected;
675 if (!clear_and_read_msaa(ours.p, resource_format, cast_list, cast_count, full, rect, partial, array,
676 first_layer, layer_count, actual) ||
677 !clear_and_read_msaa(host.p, resource_format, cast_list, cast_count, full, rect, partial, array,
678 first_layer, layer_count, expected))
679 return false;
680 ++comparisons;
681 if (actual.size() != expected.size()) return false;
682 for (std::size_t i = 0; i < actual.size(); ++i) {
683 if (std::abs(int(actual[i]) - int(expected[i])) > 1) {
684 std::fprintf(stderr, "MSAA RTV mismatch fmt %d full %d rect %d array %d byte %zu: ours %u WARP %u\n",
685 int(resource_format), int(full), int(rect), int(array), i, unsigned(actual[i]),
686 unsigned(expected[i]));
687 ++mismatches;
688 return false;
689 }
690 }
691 return true;
692 };
693 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
694 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false, false, 0, 1))
695 return 1;
696 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM,
697 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, true, false, 0, 1))
698 return 1;
699 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_TYPELESS, nullptr, 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
700 DXGI_FORMAT_R8G8B8A8_UNORM, true, true, 1, 2))
701 return 1;
702 Ref<ID3D12Device10> host10;
703 if (SUCCEEDED(host->QueryInterface(IID_PPV_ARGS(&host10.p)))) {
704 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_UNORM, srgb_list, 2, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
705 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false, false, 0, 1))
706 return 1;
707 if (!compare_msaa(DXGI_FORMAT_R8G8B8A8_UNORM, srgb_list, 2, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
708 DXGI_FORMAT_R8G8B8A8_UNORM, true, true, 1, 2))
709 return 1;
710 }
711 // MSAA vs 1x view-dimension mismatches, out-of-range MSAA array slices, and unlisted castable formats.
712 D3D12_RENDER_TARGET_VIEW_DESC bad_msaa{};
713 bad_msaa.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
714 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
715 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 1, 4)) return 1;
716 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
717 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 1, 1)) return 1;
718 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
719 bad_msaa.Texture2DMSArray = {3, 2};
720 if (!rejects(DXGI_FORMAT_R8G8B8A8_TYPELESS, &bad_msaa, 1, 4, 4)) return 1;
721 bad_msaa.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
722 bad_msaa.Format = DXGI_FORMAT_R8G8B8A8_UINT;
723 if (!rejects(DXGI_FORMAT_R8G8B8A8_UNORM, &bad_msaa, 1, 1, 4, srgb_list, 2)) return 1;
724 }
504 } 725 }
505 if (vk.validation_errors()) return 1; 726 if (vk.validation_errors()) return 1;
506 std::printf("typeless RTV: %u WARP readbacks matched, descriptor snapshots and format-cache order checked; %u unsupported/invalid views rejected\n", 727 std::printf("typeless RTV: %u WARP readbacks matched, descriptor snapshots and format-cache order checked; %u unsupported/invalid views rejected\n",
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 556ab1566..9d49740e0 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -324,8 +324,8 @@ int cpu_copies(ID3D12Device* device, bool bc, const char* path) {
324 return 0; 324 return 0;
325} 325}
326 326
327// The host PC runtime's D3D12 device to compare answers with: the default adapter, or the one LEONIDA_HOST_ADAPTER 327// The host PC runtime's D3D12 device to compare answers with: the layer's own adapter (set in main), else the default
328// names ("warp", or part of an adapter's name); false if there is none. 328// one, or the one LEONIDA_HOST_ADAPTER names ("warp", or part of an adapter's name); false if there is none.
329// Under Wine there is none (copycmp::create_host). 329// Under Wine there is none (copycmp::create_host).
330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) { 330bool create_host_device(Ref<ID3D12Device>& host, std::string* adapter_name = nullptr) {
331 copycmp::Ptr<ID3D12Device> device; 331 copycmp::Ptr<ID3D12Device> device;
@@ -785,6 +785,9 @@ int compare_allocation_info(ID3D12Device* ours) {
785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; 785 d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
786 return d; 786 return d;
787 }(), 0}, 787 }(), 0},
788 {"UNKNOWN 4x MSAA NONE (invalid)", with(texture_desc(256, 256, rgba8, none, 1), 0, 4), 0},
789 {"UNKNOWN 4x MSAA RT+DS (invalid)",
790 with(texture_desc(256, 256, rgba8, rt | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 1), 0, 4), 0},
788 }; 791 };
789 int mismatches = 0; 792 int mismatches = 0;
790 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a, 793 const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a,
@@ -797,6 +800,18 @@ int compare_allocation_info(ID3D12Device* ours) {
797 for (const Case& c : cases) { 800 for (const Case& c : cases) {
798 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc); 801 const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc);
799 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc); 802 const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc);
803 if (c.top_mip_bytes && b.SizeInBytes == UINT64_MAX && c.desc.SampleDesc.Count > 1 &&
804 c.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
805 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS ms{
806 c.desc.Format, c.desc.SampleDesc.Count, D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE, 0};
807 if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &ms, sizeof(ms))) &&
808 ms.NumQualityLevels == 0) {
809 if (a.SizeInBytes == UINT64_MAX || a.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)
810 mismatch(c.name, a, b);
811 std::printf("allocation info %s: host unsupported (NumQualityLevels=0), skipped\n", c.name);
812 continue;
813 }
814 }
800 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { 815 if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) {
801 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment)) 816 if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment))
802 mismatch(c.name, a, b); 817 mismatch(c.name, a, b);
@@ -1597,6 +1612,15 @@ int compare_feature_support(ID3D12Device* ours) {
1597 1612
1598// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back 1613// Same-adapter host D3D12 device matched by VkPhysicalDeviceIDProperties (LUID first, then PCI IDs), falling back
1599// to the default adapter. False if the host has no D3D12 device. 1614// to the default adapter. False if the host has no D3D12 device.
1615// D3D11.3 spec 3.2.3.8's ideal FLOAT -> SRGB encoding of c in [0, 1], before scaling to the format's maximum.
1616double ideal_srgb(double c) { return c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1.0 / 2.4) - 0.055; }
1617
1618// Both bytes within 0.6 ULP (on the integer side) of the ideal value: the tolerance spec 3.2.3.6 (FLOAT -> UNORM)
1619// and 3.2.3.8 (FLOAT -> SRGB) permit, so two drivers may give the codes either side of a near-tie.
1620bool within_06_ulp(std::uint8_t a, std::uint8_t b, double ideal) {
1621 return std::abs(double(a) - ideal) <= 0.6 && std::abs(double(b) - ideal) <= 0.6;
1622}
1623
1600bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical, 1624bool create_host_device_for_physical(VkInstance instance, VkPhysicalDevice physical,
1601 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host, 1625 PFN_vkGetInstanceProcAddr instance_proc, Ref<ID3D12Device>& host,
1602 std::string& adapter_name) { 1626 std::string& adapter_name) {
@@ -2205,6 +2229,32 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui
2205 return released(device->CreateFence(0, flags, riid, &out), &out); 2229 return released(device->CreateFence(0, flags, riid, &out), &out);
2206} 2230}
2207 2231
2232// A 64 KiB heap description for the CreateHeap/CreateHeap1 cases (D3D-238).
2233D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT},
2234 D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) {
2235 D3D12_HEAP_DESC desc{};
2236 desc.SizeInBytes = size;
2237 desc.Properties = properties;
2238 desc.Alignment = alignment;
2239 desc.Flags = flags;
2240 return desc;
2241}
2242
2243HRESULT heap_create(ID3D12Device* device, D3D12_HEAP_DESC desc) {
2244 void* out = nullptr;
2245 return released(device->CreateHeap(&desc, __uuidof(ID3D12Heap), &out), &out);
2246}
2247
2248// CreateHeap1 without a protected session; E_NOINTERFACE when the device has no ID3D12Device4.
2249HRESULT heap_create1(ID3D12Device* device, D3D12_HEAP_DESC desc) {
2250 ID3D12Device4* device4 = nullptr;
2251 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4)))) return E_NOINTERFACE;
2252 void* out = nullptr;
2253 const HRESULT hr = device4->CreateHeap1(&desc, nullptr, __uuidof(ID3D12Heap), &out);
2254 device4->Release();
2255 return released(hr, &out);
2256}
2257
2208// Map on a fresh committed resource; `range` is the read range, or null. 2258// Map on a fresh committed resource; `range` is the read range, or null.
2209HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state, 2259HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state,
2210 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) { 2260 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) {
@@ -2238,6 +2288,21 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2238 struct Case { 2288 struct Case {
2239 const char* name; 2289 const char* name;
2240 InvalidCase call; 2290 InvalidCase call;
2291 bool (*comparable)(ID3D12Device*) = nullptr;
2292 };
2293 const auto device10 = [](ID3D12Device* d) {
2294 Ref<ID3D12Device10> newer;
2295 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p)));
2296 };
2297 const auto not_elevated = [](ID3D12Device*) {
2298 HANDLE token = nullptr;
2299 TOKEN_ELEVATION elevation{};
2300 DWORD size = 0;
2301 const bool elevated = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
2302 GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) &&
2303 elevation.TokenIsElevated;
2304 if (token) CloseHandle(token);
2305 return !elevated;
2241 }; 2306 };
2242 static const Case cases[] = { 2307 static const Case cases[] = {
2243 // CreateCommittedResource: arguments. 2308 // CreateCommittedResource: arguments.
@@ -2315,7 +2380,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2315 }}, 2380 }},
2316 {"committed: upload buffer in COMMON", [](ID3D12Device* d) { 2381 {"committed: upload buffer in COMMON", [](ID3D12Device* d) {
2317 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2382 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2318 }}, 2383 }, +device10},
2319 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) { 2384 {"committed: upload buffer in COPY_DEST", [](ID3D12Device* d) {
2320 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST); 2385 return committed(d, {D3D12_HEAP_TYPE_UPLOAD}, buffer_desc(256), D3D12_RESOURCE_STATE_COPY_DEST);
2321 }}, 2386 }},
@@ -2441,7 +2506,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2441 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) { 2506 {"committed: BC1 6x6 top mip", [](ID3D12Device* d) {
2442 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2507 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2443 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE)); 2508 texture_desc(6, 6, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE));
2444 }}, 2509 }, host_supports_unaligned_block_textures},
2445 {"committed: render target and depth stencil", [](ID3D12Device* d) { 2510 {"committed: render target and depth stencil", [](ID3D12Device* d) {
2446 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, 2511 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
2447 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, 2512 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
@@ -2513,7 +2578,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2513 }}, 2578 }},
2514 {"committed: readback buffer in COMMON", [](ID3D12Device* d) { 2579 {"committed: readback buffer in COMMON", [](ID3D12Device* d) {
2515 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON); 2580 return committed(d, {D3D12_HEAP_TYPE_READBACK}, buffer_desc(256), D3D12_RESOURCE_STATE_COMMON);
2516 }}, 2581 }, +device10},
2517 {"committed: readback buffer with UAV", [](ID3D12Device* d) { 2582 {"committed: readback buffer with UAV", [](ID3D12Device* d) {
2518 auto desc = buffer_desc(256); 2583 auto desc = buffer_desc(256);
2519 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 2584 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
@@ -2673,7 +2738,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2673 }}, 2738 }},
2674 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) { 2739 {"committed: heap flag HARDWARE_PROTECTED on a texture", [](ID3D12Device* d) {
2675 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED); 2740 return with_heap_flags(d, rgba8(), D3D12_HEAP_FLAG_HARDWARE_PROTECTED);
2676 }}, 2741 }, +device10},
2677 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) { 2742 {"committed: heap flag ALLOW_WRITE_WATCH on a buffer", [](ID3D12Device* d) {
2678 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH); 2743 return with_heap_flags(d, buffer_desc(256), D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH);
2679 }}, 2744 }},
@@ -2728,7 +2793,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2728 auto desc = buffer_desc(256); 2793 auto desc = buffer_desc(256);
2729 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2794 desc.Flags = D3D12_RESOURCE_FLAGS(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2730 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2795 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2731 }}, 2796 }, +device10},
2732 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) { 2797 {"committed: resource flag 0x200 on a buffer", [](ID3D12Device* d) {
2733 auto desc = buffer_desc(256); 2798 auto desc = buffer_desc(256);
2734 desc.Flags = D3D12_RESOURCE_FLAGS(0x200); 2799 desc.Flags = D3D12_RESOURCE_FLAGS(0x200);
@@ -2756,15 +2821,15 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2756 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) { 2821 {"committed: resource flag RAYTRACING_ACCELERATION_STRUCTURE on a texture", [](ID3D12Device* d) {
2757 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE); 2822 auto desc = rgba8(D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE);
2758 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2823 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2759 }}, 2824 }, +device10},
2760 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) { 2825 {"committed: resource flag 0x400 on a buffer", [](ID3D12Device* d) {
2761 auto desc = buffer_desc(256); 2826 auto desc = buffer_desc(256);
2762 desc.Flags = D3D12_RESOURCE_FLAGS(0x400); 2827 desc.Flags = D3D12_RESOURCE_FLAGS(0x400);
2763 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc); 2828 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc);
2764 }}, 2829 }, +device10},
2765 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) { 2830 {"committed: resource flag 0x400 on a texture", [](ID3D12Device* d) {
2766 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400))); 2831 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAGS(0x400)));
2767 }}, 2832 }, +device10},
2768 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first. 2833 // A null output is a capability check; with invalid arguments too, the host's answer says which comes first.
2769 {"committed: heap type 99, null output", [](ID3D12Device* d) { 2834 {"committed: heap type 99, null output", [](ID3D12Device* d) {
2770 const H heap{D3D12_HEAP_TYPE(99)}; 2835 const H heap{D3D12_HEAP_TYPE(99)};
@@ -2779,6 +2844,42 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2779 return d->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 2844 return d->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON,
2780 nullptr, __uuidof(ID3D12Resource), nullptr); 2845 nullptr, __uuidof(ID3D12Resource), nullptr);
2781 }}, 2846 }},
2847 // CreateHeap and CreateHeap1 (D3D-238): the four descriptions the host refused on an RX 5700 and WARP, the
2848 // heap-property rules CreateCommittedResource shares. A refusal needs no arena; the valid neighbours do, so
2849 // compare_heap_neighbours compares them on the standalone device.
2850 {"heap: alignment 4096", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(4096)); }},
2851 {"heap1: alignment 4096", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(4096)); }},
2852 {"heap: custom heap, unknown page property", [](ID3D12Device* d) {
2853 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2854 D3D12_MEMORY_POOL_L0}));
2855 }},
2856 {"heap1: custom heap, unknown page property", [](ID3D12Device* d) {
2857 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2858 D3D12_MEMORY_POOL_L0}));
2859 }},
2860 {"heap: all three DENY flags", [](ID3D12Device* d) {
2861 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
2862 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
2863 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES));
2864 }},
2865 {"heap1: all three DENY flags", [](ID3D12Device* d) {
2866 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
2867 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
2868 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES));
2869 }},
2870 {"heap: type 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }},
2871 {"heap1: type 0", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }},
2872 {"heap: custom heap, unknown pool", [](ID3D12Device* d) {
2873 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
2874 D3D12_MEMORY_POOL_UNKNOWN}));
2875 }},
2876 {"heap: default heap with a CPU page property", [](ID3D12Device* d) {
2877 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK}));
2878 }},
2879 {"heap: default heap with a memory pool", [](ID3D12Device* d) {
2880 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
2881 D3D12_MEMORY_POOL_L0}));
2882 }},
2782 // CreateDescriptorHeap. A null description faults in the host runtime, so it is not compared. 2883 // CreateDescriptorHeap. A null description faults in the host runtime, so it is not compared.
2783 {"descriptor heap: null output", [](ID3D12Device* d) { 2884 {"descriptor heap: null output", [](ID3D12Device* d) {
2784 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4}; 2885 const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4};
@@ -2817,7 +2918,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2817 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) { 2918 {"descriptor heap: shader-visible 2049 samplers", [](ID3D12Device* d) {
2818 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049, 2919 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2049,
2819 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2920 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
2820 }}, 2921 }, +device10},
2821 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) { 2922 {"descriptor heap: shader-visible 2048 samplers", [](ID3D12Device* d) {
2822 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048, 2923 return descriptor_heap(d, {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2048,
2823 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}); 2924 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE});
@@ -2862,7 +2963,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2862 }}, 2963 }},
2863 {"command queue: global realtime priority", [](ID3D12Device* d) { 2964 {"command queue: global realtime priority", [](ID3D12Device* d) {
2864 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME}); 2965 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME});
2865 }}, 2966 }, +not_elevated},
2866 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 2967 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
2867 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 2968 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
2868 {"command queue: high priority", [](ID3D12Device* d) { 2969 {"command queue: high priority", [](ID3D12Device* d) {
@@ -2952,6 +3053,11 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2952 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); 3053 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
2953 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); 3054 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
2954 if (a == b) continue; 3055 if (a == b) continue;
3056 if (c.comparable && !c.comparable(host.p)) {
3057 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
3058 a, b);
3059 continue;
3060 }
2955 ++mismatches; 3061 ++mismatches;
2956 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); 3062 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
2957 } 3063 }
@@ -3009,6 +3115,59 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3009 return mismatches; 3115 return mismatches;
3010} 3116}
3011 3117
3118// D3D-238: the valid neighbours of the CreateHeap/CreateHeap1 refusals in compare_invalid_arguments, compared
3119// with the host on a device that has the GPU address arena (without it the layer answers every heap E_NOTIMPL).
3120int compare_heap_neighbours(ID3D12Device* ours) {
3121 Ref<ID3D12Device> host;
3122 if (!create_host_device(host)) return -1;
3123 struct Case {
3124 const char* name;
3125 InvalidCase call;
3126 };
3127 static const Case cases[] = {
3128 {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }},
3129 {"heap: alignment 64 KiB", [](ID3D12Device* d) {
3130 return heap_create(d, heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT));
3131 }},
3132 {"heap: alignment 4 MiB", [](ID3D12Device* d) {
3133 return heap_create(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
3134 {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE,
3135 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT));
3136 }},
3137 {"heap1: alignment 4 MiB", [](ID3D12Device* d) {
3138 return heap_create1(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
3139 {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE,
3140 D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT));
3141 }},
3142 {"heap: size 1000", [](ID3D12Device* d) {
3143 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000));
3144 }},
3145 {"heap: upload", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD})); }},
3146 {"heap: readback", [](ID3D12Device* d) {
3147 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK}));
3148 }},
3149 {"heap: custom write-combine L0", [](ID3D12Device* d) {
3150 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
3151 D3D12_MEMORY_POOL_L0}));
3152 }},
3153 {"heap1: custom write-combine L0", [](ID3D12Device* d) {
3154 return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
3155 D3D12_MEMORY_POOL_L0}));
3156 }},
3157 {"heap: ALLOW_ONLY_BUFFERS (two DENY flags)", [](ID3D12Device* d) {
3158 return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS));
3159 }},
3160 };
3161 int mismatches = 0;
3162 for (const Case& c : cases) {
3163 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
3164 if (a == b) continue;
3165 ++mismatches;
3166 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
3167 }
3168 return mismatches;
3169}
3170
3012} // namespace 3171} // namespace
3013 3172
3014int main() { 3173int main() {
@@ -3016,6 +3175,18 @@ int main() {
3016 const auto status = d.initialize(); 3175 const auto status = d.initialize();
3017 if (status == vktest::DeviceStatus::unavailable) return 77; 3176 if (status == vktest::DeviceStatus::unavailable) return 77;
3018 if (status == vktest::DeviceStatus::failed) return 1; 3177 if (status == vktest::DeviceStatus::failed) return 1;
3178 {
3179 // The host comparisons (create_host_device, the copies) run on the layer's own adapter, not D3D12's default
3180 // one, which on a PC with two GPUs can be the other GPU (copycmp::layer_adapter).
3181 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
3182 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
3183 d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties);
3184 if (id.deviceLUIDValid) {
3185 LUID luid{};
3186 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
3187 copycmp::layer_adapter() = luid;
3188 }
3189 }
3019 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); 3190 EXPECT(d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT));
3020 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0; 3191 VkSampleCountFlags depth_sample_counts = 0, color_sample_counts = 0;
3021 { 3192 {
@@ -3422,6 +3593,68 @@ int main() {
3422 std::printf("invalid arguments: no host D3D12 device to compare with, skipped\n"); 3593 std::printf("invalid arguments: no host D3D12 device to compare with, skipped\n");
3423 EXPECT(argument_mismatches <= 0); 3594 EXPECT(argument_mismatches <= 0);
3424 3595
3596 // D3D-236: CreateCommandQueue with D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME requires
3597 // SeIncreaseBasePriorityPrivilege enabled in the token, matching the Windows D3D12 runtime.
3598 {
3599 const D3D12_COMMAND_QUEUE_DESC rt_desc{
3600 D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME,
3601 D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
3602 struct RestoreOverride {
3603 ~RestoreOverride() { rt::d3d12::set_global_realtime_privilege_override_for_test(-1); }
3604 } restore_override;
3605
3606 rt::d3d12::set_global_realtime_privilege_override_for_test(0);
3607 EXPECT(!rt::d3d12::has_global_realtime_privilege());
3608 Ref<ID3D12CommandQueue> denied_q;
3609 EXPECT(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&denied_q.p)) == DXGI_ERROR_ACCESS_DENIED);
3610 EXPECT(!denied_q.p);
3611 EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) ==
3612 DXGI_ERROR_ACCESS_DENIED);
3613
3614 rt::d3d12::set_global_realtime_privilege_override_for_test(1);
3615 EXPECT(rt::d3d12::has_global_realtime_privilege());
3616 EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) == E_UNEXPECTED);
3617 Ref<ID3D12CommandQueue> granted_q;
3618 EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p);
3619 if (granted_q.p) {
3620 EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME);
3621 }
3622 granted_q.reset();
3623 rt::d3d12::set_global_realtime_privilege_override_for_test(-1);
3624
3625 // When the process token holds SeIncreaseBasePriorityPrivilege (e.g. an elevated session), toggle the
3626 // real token privilege and verify both states against the host D3D12 runtime.
3627 HANDLE token = nullptr;
3628 LUID luid{};
3629 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
3630 if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) {
3631 TOKEN_PRIVILEGES tp{}, prev{};
3632 DWORD prev_len = 0;
3633 tp.PrivilegeCount = 1;
3634 tp.Privileges[0].Luid = luid;
3635 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
3636 if (AdjustTokenPrivileges(token, FALSE, &tp, sizeof(prev), &prev, &prev_len) &&
3637 GetLastError() == ERROR_SUCCESS) {
3638 EXPECT(rt::d3d12::has_global_realtime_privilege());
3639 EXPECT(command_queue(device.p, rt_desc) == S_OK);
3640 Ref<ID3D12Device> host;
3641 if (create_host_device(host)) {
3642 EXPECT(command_queue(host.p, rt_desc) == S_OK);
3643 }
3644 tp.Privileges[0].Attributes = 0;
3645 if (AdjustTokenPrivileges(token, FALSE, &tp, 0, nullptr, nullptr) &&
3646 GetLastError() == ERROR_SUCCESS) {
3647 EXPECT(!rt::d3d12::has_global_realtime_privilege());
3648 EXPECT(command_queue(device.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
3649 if (host.p) EXPECT(command_queue(host.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
3650 }
3651 AdjustTokenPrivileges(token, FALSE, &prev, 0, nullptr, nullptr);
3652 }
3653 }
3654 CloseHandle(token);
3655 }
3656 }
3657
3425 const int depth_quality_mismatches = compare_depth_multisample_quality_levels(device.p, depth_sample_counts); 3658 const int depth_quality_mismatches = compare_depth_multisample_quality_levels(device.p, depth_sample_counts);
3426 if (depth_quality_mismatches < 0) 3659 if (depth_quality_mismatches < 0)
3427 std::printf("Depth/stencil MSAA quality queries: no host D3D12 device to compare with, skipped\n"); 3660 std::printf("Depth/stencil MSAA quality queries: no host D3D12 device to compare with, skipped\n");
@@ -4741,6 +4974,44 @@ int main() {
4741 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes))); 4974 EXPECT(SUCCEEDED(zeroes->Map(0, nullptr, &zero_bytes)));
4742 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64); 4975 report("placed buffer", 0, static_cast<std::uint8_t*>(zero_bytes), std::array<std::uint8_t, 64>{}.data(), 64);
4743 zeroes->Unmap(0, nullptr); 4976 zeroes->Unmap(0, nullptr);
4977
4978 // Placed buffers carry their console VA in VulkanContext (so VA-resolved commands like WriteBufferImmediate
4979 // find them) and placed readback buffers mark host_readable (so the submission flushes GPU writes to host).
4980 {
4981 D3D12_HEAP_DESC rb_heap_desc{};
4982 rb_heap_desc.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4983 rb_heap_desc.SizeInBytes = 65536;
4984 rb_heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
4985 Ref<ID3D12Heap> rb_heap;
4986 Ref<ID3D12Resource> placed_rb;
4987 EXPECT(SUCCEEDED(standalone->CreateHeap(&rb_heap_desc, IID_PPV_ARGS(&rb_heap.p))));
4988 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(rb_heap.p, 0, &placed_buffer,
4989 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
4990 IID_PPV_ARGS(&placed_rb.p))));
4991 Ref<ID3D12GraphicsCommandList2> placed_list2;
4992 EXPECT(SUCCEEDED(placed_list->QueryInterface(IID_PPV_ARGS(&placed_list2.p))));
4993 EXPECT(SUCCEEDED(placed_allocator->Reset()) && SUCCEEDED(placed_list->Reset(placed_allocator.p, nullptr)));
4994 const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER wp{placed_va + 16, 0xCAFEBABEu};
4995 const D3D12_WRITEBUFFERIMMEDIATE_MODE wm = D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT;
4996 placed_list2->WriteBufferImmediate(1, &wp, &wm);
4997 D3D12_RESOURCE_BARRIER b{};
4998 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
4999 b.Transition = {placed_a.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
5000 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
5001 placed_list->ResourceBarrier(1, &b);
5002 placed_list->CopyBufferRegion(placed_rb.p, 0, placed_a.p, 0, 64);
5003 EXPECT(SUCCEEDED(placed_list->Close()));
5004 queue->ExecuteCommandLists(1, placed_lists);
5005 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5006 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr)));
5007 void* rb_bytes = nullptr;
5008 EXPECT(SUCCEEDED(placed_rb->Map(0, nullptr, &rb_bytes)));
5009 std::uint32_t word = 0;
5010 std::memcpy(&word, static_cast<const std::uint8_t*>(rb_bytes) + 16, sizeof(word));
5011 EXPECT(word == 0xCAFEBABEu);
5012 placed_rb->Unmap(0, nullptr);
5013 }
5014
4744 // The heap owns the range: releasing it puts the next heap of that size back at the same place. 5015 // The heap owns the range: releasing it puts the next heap of that size back at the same place.
4745 placed_image.reset(); 5016 placed_image.reset();
4746 placed_b.reset(); 5017 placed_b.reset();
@@ -4762,6 +5033,52 @@ int main() {
4762 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; 5033 upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4763 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p)))); 5034 EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p))));
4764 5035
5036 // D3D-238: heap descriptions the host refuses (RX 5700 and WARP), from CreateHeap and CreateHeap1 alike, and
5037 // their valid neighbours. compare_invalid_arguments and compare_heap_neighbours check them against a host.
5038 {
5039 const D3D12_HEAP_FLAGS deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES |
5040 D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
5041 const D3D12_HEAP_DESC refused_heaps[] = {
5042 heap_desc_of(4096),
5043 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_L0}),
5044 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, deny_all),
5045 heap_desc_of(0, {D3D12_HEAP_TYPE(0)}),
5046 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
5047 D3D12_MEMORY_POOL_UNKNOWN}),
5048 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK}),
5049 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 0),
5050 };
5051 for (const D3D12_HEAP_DESC& hd : refused_heaps) {
5052 EXPECT(heap_create(standalone.p, hd) == E_INVALIDARG);
5053 EXPECT(heap_create1(standalone.p, hd) == E_INVALIDARG);
5054 }
5055 const D3D12_HEAP_DESC accepted_heaps[] = {
5056 heap_desc_of(0),
5057 heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT),
5058 heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, {D3D12_HEAP_TYPE_DEFAULT},
5059 D3D12_HEAP_FLAG_NONE, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT),
5060 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000),
5061 heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD}),
5062 heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK}),
5063 heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0}),
5064 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS),
5065 heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT},
5066 D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES),
5067 };
5068 for (const D3D12_HEAP_DESC& hd : accepted_heaps) {
5069 EXPECT(heap_create(standalone.p, hd) == S_OK);
5070 EXPECT(heap_create1(standalone.p, hd) == S_OK);
5071 }
5072 Ref<ID3D12Device4> device4;
5073 Ref<ID3D12Heap> unused;
5074 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&device4.p))));
5075 EXPECT(device4->CreateHeap1(&placed_heap_desc, nullptr, IID_PPV_ARGS(&unused.p)) == S_OK && unused.p);
5076 const int heap_mismatches = compare_heap_neighbours(standalone.p);
5077 if (heap_mismatches < 0)
5078 std::printf("CreateHeap valid neighbours: no host D3D12 device to compare with, skipped\n");
5079 EXPECT(heap_mismatches <= 0);
5080 }
5081
4765 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags, 5082 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags,
4766 UINT64 align = 0) { 5083 UINT64 align = 0) {
4767 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips); 5084 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
@@ -4846,13 +5163,6 @@ int main() {
4846 EXPECT(!fail.p); 5163 EXPECT(!fail.p);
4847 } 5164 }
4848 { 5165 {
4849 const D3D12_RESOURCE_DESC valid_4x = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4850 Ref<ID3D12Resource> fail;
4851 EXPECT(standalone->CreatePlacedResource(tiled_heap.p, 0, &valid_4x, D3D12_RESOURCE_STATE_COMMON, nullptr,
4852 IID_PPV_ARGS(&fail.p)) == E_NOTIMPL);
4853 EXPECT(!fail.p);
4854 }
4855 {
4856 Ref<ID3D12Resource> fail; 5166 Ref<ID3D12Resource> fail;
4857 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc, 5167 EXPECT(standalone->CreatePlacedResource(upload_placed_heap.p, 0, &tiled_rt_desc,
4858 D3D12_RESOURCE_STATE_COMMON, nullptr, 5168 D3D12_RESOURCE_STATE_COMMON, nullptr,
@@ -4900,7 +5210,7 @@ int main() {
4900 ID3D12CommandList* tiled_lists[] = {tiled_list.p}; 5210 ID3D12CommandList* tiled_lists[] = {tiled_list.p};
4901 queue->ExecuteCommandLists(1, tiled_lists); 5211 queue->ExecuteCommandLists(1, tiled_lists);
4902 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 5212 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
4903 EXPECT(SUCCEEDED(queue->Signal(fence.p, 7)) && SUCCEEDED(fence->SetEventOnCompletion(7, nullptr))); 5213 EXPECT(SUCCEEDED(queue->Signal(fence.p, 8)) && SUCCEEDED(fence->SetEventOnCompletion(8, nullptr)));
4904 void* tiled_bytes = nullptr; 5214 void* tiled_bytes = nullptr;
4905 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes))); 5215 EXPECT(SUCCEEDED(tiled_rb->Map(0, nullptr, &tiled_bytes)));
4906 const std::uint8_t want_rgba[4] = {64, 128, 191, 255}; 5216 const std::uint8_t want_rgba[4] = {64, 128, 191, 255};
@@ -4922,15 +5232,15 @@ int main() {
4922 tiled_3d_desc, 5232 tiled_3d_desc,
4923 }; 5233 };
4924 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) { 5234 for (int idx = 0; idx < int(std::size(host_cases)); ++idx) {
4925 const D3D12_RESOURCE_DESC& d = host_cases[idx]; 5235 const D3D12_RESOURCE_DESC& host_desc = host_cases[idx];
4926 if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && 5236 if (host_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D &&
4927 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3) 5237 host_opts.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_3)
4928 continue; 5238 continue;
4929 Ref<ID3D12Resource> our_r, host_r; 5239 Ref<ID3D12Resource> our_r, host_r;
4930 const HRESULT our_hr = standalone->CreatePlacedResource( 5240 const HRESULT our_hr = standalone->CreatePlacedResource(
4931 tiled_heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p)); 5241 tiled_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
4932 const HRESULT host_hr = host_dev->CreatePlacedResource( 5242 const HRESULT host_hr = host_dev->CreatePlacedResource(
4933 host_heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p)); 5243 host_heap.p, 0, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
4934 if (FAILED(host_hr)) continue; 5244 if (FAILED(host_hr)) continue;
4935 EXPECT(SUCCEEDED(our_hr)); 5245 EXPECT(SUCCEEDED(our_hr));
4936 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout); 5246 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
@@ -4948,6 +5258,259 @@ int main() {
4948 } 5258 }
4949 } 5259 }
4950 } 5260 }
5261
5262 // D3D-222: multisampled placed textures (UNKNOWN and 4x tiled).
5263 D3D12_HEAP_DESC msaa_heap_desc{};
5264 msaa_heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
5265 msaa_heap_desc.SizeInBytes = 16 * 1024 * 1024;
5266 msaa_heap_desc.Alignment = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT;
5267 Ref<ID3D12Heap> msaa_heap;
5268 EXPECT(SUCCEEDED(standalone->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&msaa_heap.p))));
5269 D3D12_HEAP_DESC deny_rt_desc = tiled_heap_desc;
5270 deny_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
5271 Ref<ID3D12Heap> deny_rt_heap;
5272 EXPECT(SUCCEEDED(standalone->CreateHeap(&deny_rt_desc, IID_PPV_ARGS(&deny_rt_heap.p))));
5273
5274 auto msaa_desc = [&](UINT w, UINT h, UINT samples, UINT64 align, D3D12_TEXTURE_LAYOUT layout,
5275 D3D12_RESOURCE_FLAGS flags, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM,
5276 UINT16 mips = 1) {
5277 D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips);
5278 d.Alignment = align;
5279 d.SampleDesc.Count = samples;
5280 d.Layout = layout;
5281 return d;
5282 };
5283 const D3D12_RESOURCE_DESC msaa_unk_rt_desc =
5284 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5285 const D3D12_RESOURCE_DESC msaa_unk_small_desc = msaa_desc(
5286 256, 256, 4, D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5287 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5288 const D3D12_RESOURCE_DESC msaa_unk_ds_desc =
5289 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
5290 DXGI_FORMAT_D32_FLOAT);
5291 const D3D12_RESOURCE_DESC msaa_tiled_rt_desc = tiled_2d_msaa(4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5292 D3D12_RESOURCE_DESC msaa_xbox_rt_desc = msaa_tiled_rt_desc;
5293 msaa_xbox_rt_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
5294
5295 Ref<ID3D12Resource> msaa_unk_rt, msaa_unk_small, msaa_unk_ds, msaa_tiled_rt, msaa_xbox_rt, msaa_cast_rt;
5296 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT,
5297 &msaa_unk_rt_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5298 IID_PPV_ARGS(&msaa_unk_rt.p))));
5299 EXPECT(msaa_unk_rt->GetGPUVirtualAddress() == 0);
5300 EXPECT(msaa_unk_rt->GetDesc().Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5301 EXPECT(msaa_unk_rt->GetDesc().SampleDesc.Count == 4);
5302 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_unk_small_desc,
5303 D3D12_RESOURCE_STATE_COMMON, nullptr,
5304 IID_PPV_ARGS(&msaa_unk_small.p))));
5305 EXPECT(msaa_unk_small->GetDesc().Alignment == D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT);
5306 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(msaa_heap.p, 8 * 1024 * 1024, &msaa_unk_ds_desc,
5307 D3D12_RESOURCE_STATE_COMMON, nullptr,
5308 IID_PPV_ARGS(&msaa_unk_ds.p))));
5309 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_tiled_rt_desc,
5310 D3D12_RESOURCE_STATE_COMMON, nullptr,
5311 IID_PPV_ARGS(&msaa_tiled_rt.p))));
5312 EXPECT(msaa_tiled_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5313 UINT msaa_tiles = 0;
5314 D3D12_TILE_SHAPE msaa_shape{};
5315 standalone->GetResourceTiling(msaa_tiled_rt.p, &msaa_tiles, nullptr, &msaa_shape, nullptr, 0, nullptr);
5316 EXPECT(msaa_tiles == 16 && msaa_shape.WidthInTexels == 64 && msaa_shape.HeightInTexels == 64);
5317 EXPECT(SUCCEEDED(standalone->CreatePlacedResource(tiled_heap.p, 65536, &msaa_xbox_rt_desc,
5318 D3D12_RESOURCE_STATE_COMMON, nullptr,
5319 IID_PPV_ARGS(&msaa_xbox_rt.p))));
5320 EXPECT(msaa_xbox_rt->GetDesc().Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
5321 EXPECT(static_cast<UINT>(msaa_xbox_rt->GetDesc().Layout) == 0x101);
5322
5323 {
5324 Ref<ID3D12Device10> standalone10;
5325 EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&standalone10.p))));
5326 D3D12_RESOURCE_DESC1 cast_msaa{};
5327 cast_msaa.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5328 cast_msaa.Width = 64;
5329 cast_msaa.Height = 64;
5330 cast_msaa.DepthOrArraySize = 1;
5331 cast_msaa.MipLevels = 1;
5332 cast_msaa.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS;
5333 cast_msaa.SampleDesc.Count = 4;
5334 cast_msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5335 const DXGI_FORMAT cast_list[] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB};
5336 EXPECT(SUCCEEDED(standalone10->CreatePlacedResource2(
5337 msaa_heap.p, 0, &cast_msaa, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, cast_list,
5338 IID_PPV_ARGS(&msaa_cast_rt.p))));
5339 }
5340
5341 // Refusals matching host D3D12 for MSAA placed resources.
5342 {
5343 struct BadMsaaCase {
5344 ID3D12Heap* heap;
5345 UINT64 offset;
5346 D3D12_RESOURCE_DESC desc;
5347 };
5348 D3D12_RESOURCE_DESC msaa_3d =
5349 msaa_desc(16, 16, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
5350 msaa_3d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5351 msaa_3d.DepthOrArraySize = 8;
5352 const BadMsaaCase bad_msaa[] = {
5353 // 4 MiB-aligned UNKNOWN MSAA fails on a 64 KiB heap (even at offset 0) and at misaligned offsets.
5354 {tiled_heap.p, 0, msaa_unk_rt_desc},
5355 {msaa_heap.p, 65536, msaa_unk_rt_desc},
5356 {msaa_heap.p, msaa_heap_desc.SizeInBytes - 65536, msaa_unk_small_desc},
5357 {upload_placed_heap.p, 0, msaa_unk_small_desc},
5358 {deny_rt_heap.p, 0, msaa_unk_small_desc},
5359 {deny_rt_heap.p, 0, tiled_rt_desc},
5360 {msaa_heap.p, 0,
5361 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE)},
5362 {msaa_heap.p, 0,
5363 msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN,
5364 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)},
5365 {msaa_heap.p, 0,
5366 msaa_desc(64, 64, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
5367 DXGI_FORMAT_R8G8B8A8_UNORM, 0)},
5368 {msaa_heap.p, 0, msaa_3d},
5369 };
5370 for (const BadMsaaCase& bad : bad_msaa) {
5371 Ref<ID3D12Resource> fail;
5372 EXPECT(standalone->CreatePlacedResource(bad.heap, bad.offset, &bad.desc, D3D12_RESOURCE_STATE_COMMON,
5373 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5374 EXPECT(!fail.p);
5375 }
5376 D3D12_HEAP_DESC only_rt_desc = tiled_heap_desc;
5377 only_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
5378 Ref<ID3D12Heap> only_rt_heap;
5379 EXPECT(SUCCEEDED(standalone->CreateHeap(&only_rt_desc, IID_PPV_ARGS(&only_rt_heap.p))));
5380 for (const D3D12_RESOURCE_DESC& bad_only_rt :
5381 {texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1),
5382 buffer_desc(4096)}) {
5383 Ref<ID3D12Resource> fail;
5384 EXPECT(standalone->CreatePlacedResource(only_rt_heap.p, 0, &bad_only_rt, D3D12_RESOURCE_STATE_COMMON,
5385 nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG);
5386 EXPECT(!fail.p);
5387 }
5388 }
5389
5390 // Clear placed 4x MSAA RTVs (UNKNOWN + tiled) and DSV, resolve, and read back to verify GPU execution.
5391 {
5392 const D3D12_RESOURCE_DESC resolved_desc =
5393 texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
5394 Ref<ID3D12Resource> msaa_resolved_unk, msaa_resolved_tiled;
5395 D3D12_HEAP_PROPERTIES def_hp{D3D12_HEAP_TYPE_DEFAULT};
5396 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5397 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5398 IID_PPV_ARGS(&msaa_resolved_unk.p))));
5399 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &resolved_desc,
5400 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
5401 IID_PPV_ARGS(&msaa_resolved_tiled.p))));
5402
5403 D3D12_DESCRIPTOR_HEAP_DESC msaa_rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5404 D3D12_DESCRIPTOR_HEAP_DESC msaa_dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
5405 Ref<ID3D12DescriptorHeap> msaa_rtv_heap, msaa_dsv_heap;
5406 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_rtv_hd, IID_PPV_ARGS(&msaa_rtv_heap.p))));
5407 EXPECT(SUCCEEDED(standalone->CreateDescriptorHeap(&msaa_dsv_hd, IID_PPV_ARGS(&msaa_dsv_heap.p))));
5408 const UINT rtv_step = standalone->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5409 const D3D12_CPU_DESCRIPTOR_HANDLE rtv0 = msaa_rtv_heap->GetCPUDescriptorHandleForHeapStart();
5410 const D3D12_CPU_DESCRIPTOR_HANDLE rtv1{rtv0.ptr + rtv_step};
5411 standalone->CreateRenderTargetView(msaa_unk_rt.p, nullptr, rtv0);
5412 standalone->CreateRenderTargetView(msaa_tiled_rt.p, nullptr, rtv1);
5413 standalone->CreateDepthStencilView(msaa_unk_ds.p, nullptr, msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart());
5414
5415 EXPECT(SUCCEEDED(tiled_alloc->Reset()) && SUCCEEDED(tiled_list->Reset(tiled_alloc.p, nullptr)));
5416 D3D12_RESOURCE_BARRIER barriers[] = {
5417 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5418 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET),
5419 transition(msaa_unk_ds.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE),
5420 };
5421 tiled_list->ResourceBarrier(3, barriers);
5422 tiled_list->ClearRenderTargetView(rtv0, tiled_color, 0, nullptr);
5423 tiled_list->ClearRenderTargetView(rtv1, tiled_color, 0, nullptr);
5424 tiled_list->ClearDepthStencilView(msaa_dsv_heap->GetCPUDescriptorHandleForHeapStart(),
5425 D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr);
5426 D3D12_RESOURCE_BARRIER to_resolve[] = {
5427 transition(msaa_unk_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5428 transition(msaa_tiled_rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE),
5429 };
5430 tiled_list->ResourceBarrier(2, to_resolve);
5431 tiled_list->ResolveSubresource(msaa_resolved_unk.p, 0, msaa_unk_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5432 tiled_list->ResolveSubresource(msaa_resolved_tiled.p, 0, msaa_tiled_rt.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
5433 D3D12_RESOURCE_BARRIER to_copy[] = {
5434 transition(msaa_resolved_unk.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5435 transition(msaa_resolved_tiled.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE),
5436 };
5437 tiled_list->ResourceBarrier(2, to_copy);
5438 Ref<ID3D12Resource> msaa_rb;
5439 const D3D12_RESOURCE_DESC msaa_rb_desc = buffer_desc(1024);
5440 EXPECT(SUCCEEDED(standalone->CreateCommittedResource(&rb_props, D3D12_HEAP_FLAG_NONE, &msaa_rb_desc,
5441 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
5442 IID_PPV_ARGS(&msaa_rb.p))));
5443 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp_unk{}, fp_tiled{};
5444 fp_unk.Offset = 0;
5445 fp_unk.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT};
5446 fp_tiled = fp_unk;
5447 fp_tiled.Offset = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
5448 const D3D12_TEXTURE_COPY_LOCATION dst_unk = footprint(msaa_rb.p, fp_unk);
5449 const D3D12_TEXTURE_COPY_LOCATION src_unk = subresource(msaa_resolved_unk.p, 0);
5450 const D3D12_TEXTURE_COPY_LOCATION dst_tiled = footprint(msaa_rb.p, fp_tiled);
5451 const D3D12_TEXTURE_COPY_LOCATION src_tiled = subresource(msaa_resolved_tiled.p, 0);
5452 tiled_list->CopyTextureRegion(&dst_unk, 0, 0, 0, &src_unk, &box);
5453 tiled_list->CopyTextureRegion(&dst_tiled, 0, 0, 0, &src_tiled, &box);
5454 EXPECT(SUCCEEDED(tiled_list->Close()));
5455 queue->ExecuteCommandLists(1, tiled_lists);
5456 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
5457 EXPECT(SUCCEEDED(queue->Signal(fence.p, 9)) && SUCCEEDED(fence->SetEventOnCompletion(9, nullptr)));
5458 void* msaa_bytes = nullptr;
5459 EXPECT(SUCCEEDED(msaa_rb->Map(0, nullptr, &msaa_bytes)));
5460 const auto* out_bytes = static_cast<const std::uint8_t*>(msaa_bytes);
5461 report("placed MSAA UNKNOWN RTV resolve", 0, out_bytes, want_rgba, 4);
5462 report("placed MSAA tiled RTV resolve", 0, out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4);
5463 EXPECT(std::memcmp(out_bytes, want_rgba, 4) == 0);
5464 EXPECT(std::memcmp(out_bytes + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, want_rgba, 4) == 0);
5465 msaa_rb->Unmap(0, nullptr);
5466 }
5467
5468 // Host parity for MSAA placed acceptance/refusals, layout, alignment, heap flags and tiled 4x shape.
5469 if (host_dev.p) {
5470 Ref<ID3D12Heap> host_heap64, host_heap4m;
5471 if (SUCCEEDED(host_dev->CreateHeap(&tiled_heap_desc, IID_PPV_ARGS(&host_heap64.p))) &&
5472 SUCCEEDED(host_dev->CreateHeap(&msaa_heap_desc, IID_PPV_ARGS(&host_heap4m.p)))) {
5473 struct MsaaParityCase {
5474 ID3D12Heap* our_heap;
5475 ID3D12Heap* host_heap;
5476 UINT64 offset;
5477 D3D12_RESOURCE_DESC desc;
5478 };
5479 const MsaaParityCase parity[] = {
5480 {tiled_heap.p, host_heap64.p, 0, msaa_unk_rt_desc},
5481 {msaa_heap.p, host_heap4m.p, 65536, msaa_unk_rt_desc},
5482 {msaa_heap.p, host_heap4m.p, 0, msaa_unk_rt_desc},
5483 {tiled_heap.p, host_heap64.p, 65536, msaa_unk_small_desc},
5484 {tiled_heap.p, host_heap64.p, 65536, msaa_tiled_rt_desc},
5485 };
5486 for (const MsaaParityCase& mc : parity) {
5487 Ref<ID3D12Resource> our_r, host_r;
5488 const HRESULT our_hr = standalone->CreatePlacedResource(
5489 mc.our_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&our_r.p));
5490 const HRESULT host_hr = host_dev->CreatePlacedResource(
5491 mc.host_heap, mc.offset, &mc.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&host_r.p));
5492 EXPECT(SUCCEEDED(our_hr) == SUCCEEDED(host_hr));
5493 if (FAILED(host_hr)) {
5494 EXPECT(our_hr == host_hr);
5495 continue;
5496 }
5497 EXPECT(our_r->GetDesc().Layout == host_r->GetDesc().Layout);
5498 EXPECT(our_r->GetDesc().Alignment == host_r->GetDesc().Alignment);
5499 EXPECT(our_r->GetDesc().SampleDesc.Count == host_r->GetDesc().SampleDesc.Count);
5500 D3D12_HEAP_PROPERTIES ohp{}, hhp{};
5501 EXPECT(SUCCEEDED(our_r->GetHeapProperties(&ohp, nullptr)) &&
5502 SUCCEEDED(host_r->GetHeapProperties(&hhp, nullptr)));
5503 EXPECT(ohp.Type == hhp.Type);
5504 if (mc.desc.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) {
5505 D3D12_TILE_SHAPE os{}, hs{};
5506 standalone->GetResourceTiling(our_r.p, nullptr, nullptr, &os, nullptr, 0, nullptr);
5507 host_dev->GetResourceTiling(host_r.p, nullptr, nullptr, &hs, nullptr, 0, nullptr);
5508 EXPECT(os.WidthInTexels == hs.WidthInTexels && os.HeightInTexels == hs.HeightInTexels &&
5509 os.DepthInTexels == hs.DepthInTexels);
5510 }
5511 }
5512 }
5513 }
4951 } 5514 }
4952 5515
4953 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as 5516 // D3D-90, the placed half of castable formats: CreatePlacedResource2 takes NumCastableFormats exactly as
@@ -5179,6 +5742,15 @@ int main() {
5179 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0); 5742 EXPECT(words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0);
5180 } 5743 }
5181 5744
5745 // The tolerance host_side applies, pinned here so every GPU checks it: its accept side only runs where the
5746 // host rounds differently (Intel's SRGB clear), so a change to it would otherwise stay green elsewhere.
5747 // One code either side of a near-tie is accepted; two codes, or a code past 0.6 ULP, are not.
5748 EXPECT(within_06_ulp(187, 188, ideal_srgb(0.5) * 255.0) && within_06_ulp(127, 128, 127.5));
5749 EXPECT(!within_06_ulp(186, 188, ideal_srgb(0.5) * 255.0) && !within_06_ulp(126, 128, 127.5));
5750 EXPECT(!within_06_ulp(224, 225, ideal_srgb(0.75) * 255.0) &&
5751 !within_06_ulp(136, 137, ideal_srgb(0.25) * 255.0));
5752 EXPECT(!within_06_ulp(254, 255, 255.0));
5753
5182 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise. 5754 // The host PC runtime's bytes and refusals: the default adapter when it can cast, WARP otherwise.
5183 bool compared = false; 5755 bool compared = false;
5184 const char* source = "no host"; 5756 const char* source = "no host";
@@ -5188,33 +5760,44 @@ int main() {
5188 if (!placed_cast_scenario(device10, false, host.data())) return false; 5760 if (!placed_cast_scenario(device10, false, host.data())) return false;
5189 if (!placed_cast_refusals(device10, host_refusals)) return false; 5761 if (!placed_cast_refusals(device10, host_refusals)) return false;
5190 unsigned differences = 0; 5762 unsigned differences = 0;
5191 // D3D12 does not pin float -> UNORM at a tie: the D3D11.3 functional spec (3.2.3.6 FLOAT -> UNORM) 5763 // D3D12 does not pin float -> UNORM or float -> SRGB to one code: the D3D11.3 functional spec
5192 // computes c * (2^n - 1) + 0.5 and drops the fraction, but permits a tolerance of 0.6 ULP on the integer 5764 // (3.2.3.6 FLOAT -> UNORM, 3.2.3.8 FLOAT -> SRGB) permits a tolerance of 0.6 ULP on the integer side, so
5193 // side, so a value exactly halfway between two codes (0.5 * 255 = 127.5) may map to either. WARP and AMD 5765 // a value near halfway between two codes may map to either. The plain clear's 0.5 * 255 = 127.5 is a
5194 // give the upper code; NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080 616.64, RTX 3090 5766 // tie: WARP and AMD give the upper code, NVIDIA's D3D12 driver and its Vulkan driver the lower (RTX 3080
5195 // 610.88 and RTX 5070 Laptop 617.42). On the layer's own adapter (same LUID) the comparison stays exact; 5767 // 616.64, RTX 3090 610.88 and RTX 5070 Laptop 617.42). The SRGB-cast clear's 0.5 encodes to 187.516:
5196 // against another adapter or WARP the plain clear accepts either code on a tie channel. 5768 // WARP and NVIDIA's Vulkan driver give 188, Intel's Vulkan driver 187 (UHD 770 101.7092), both within
5769 // 0.6 ULP. On the layer's own adapter (same LUID) the comparison stays exact; against another adapter
5770 // or WARP a byte may differ when both sides are within 0.6 ULP of the ideal value.
5197 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour 5771 const FLOAT clear_value[4] = {0.25f, 0.5f, 0.75f, 1.0f}; // placed_cast_scenario's clear colour
5198 unsigned tie_bytes_other_way = 0; 5772 const auto within_tolerance = [&](std::uint8_t ours_byte, std::uint8_t host_byte, double ideal) {
5773 return !same_adapter && within_06_ulp(ours_byte, host_byte, ideal);
5774 };
5775 unsigned plain_within = 0, srgb_within = 0;
5199 for (UINT row = 0; row < 4; ++row) 5776 for (UINT row = 0; row < 4; ++row)
5200 for (UINT i = 0; i < 16; ++i) { 5777 for (UINT i = 0; i < 16; ++i) {
5201 const UINT a = row * 256 + i, b = 1024 + row * 256 + i; 5778 const UINT a = row * 256 + i, b = 1024 + row * 256 + i;
5202 const double scaled = double(clear_value[i % 4]) * 255.0; 5779 const double c = clear_value[i % 4];
5203 const bool tie = !same_adapter && scaled - std::floor(scaled) == 0.5; 5780 const double plain_ideal = c * 255.0;
5204 if (tie && std::abs(int(ours[b]) - int(host[b])) == 1) { 5781 const double srgb_ideal = (i % 4 == 3 ? c : ideal_srgb(c)) * 255.0; // alpha stays linear
5205 ++tie_bytes_other_way; 5782 if (ours[b] != host[b]) {
5206 } else if (ours[b] != host[b] && differences++ < 8) { 5783 if (within_tolerance(ours[b], host[b], plain_ideal))
5207 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i, 5784 ++plain_within;
5208 ours[b], host[b]); 5785 else if (differences++ < 8)
5786 std::fprintf(stderr, "placed plain clear row %u byte %u: ours %02x, host %02x\n", row, i,
5787 ours[b], host[b]);
5788 }
5789 if (ours[a] != host[a]) {
5790 if (within_tolerance(ours[a], host[a], srgb_ideal))
5791 ++srgb_within;
5792 else if (differences++ < 8)
5793 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n",
5794 row, i, ours[a], host[a]);
5209 } 5795 }
5210 if (ours[a] != host[a] && differences++ < 8)
5211 std::fprintf(stderr, "placed SRGB-cast clear row %u byte %u: ours %02x, host %02x\n", row,
5212 i, ours[a], host[a]);
5213 } 5796 }
5214 if (tie_bytes_other_way) 5797 if (plain_within || srgb_within)
5215 std::printf("placed plain clear: the host rounds the exact .5 tie the other way in %u bytes (within " 5798 std::printf("placed clears: %u plain and %u SRGB-cast bytes differ from the host by one code, both "
5216 "the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6)\n", 5799 "within the 0.6 ULP tolerance of D3D11.3 spec 3.2.3.6 and 3.2.3.8\n",
5217 tie_bytes_other_way); 5800 plain_within, srgb_within);
5218 for (UINT i = 0; i < 3; ++i) 5801 for (UINT i = 0; i < 3; ++i)
5219 if (our_refusals[i] != host_refusals[i]) { 5802 if (our_refusals[i] != host_refusals[i]) {
5220 ++differences; 5803 ++differences;
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp
index 9499dbe0d..51f357fc1 100644
--- a/runtime/test/d3d12_xdxr_rt_test.cpp
+++ b/runtime/test/d3d12_xdxr_rt_test.cpp
@@ -2,7 +2,10 @@
2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an 2// 4.8, src/xdxr_build.h), the layout the game's translated traversal shaders read. A BLAS of two geometries (an
3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three 3// unindexed triangle soup, and an R16-indexed grid with a 16-byte stride and a 3x4 transform) and a TLAS of three
4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to 4// instances are built through the D3D12 API, sized by GetRaytracingAccelerationStructurePrebuildInfo, copied to
5// readback buffers and written to <out dir> as <case>.bin + <case>.json at their console GPU virtual addresses. 5// readback buffers and written to <out dir>; the BLAS is then updated in place (PERFORM_UPDATE) after its soup moves,
6// and written again as d3d12_blas_update; then its postbuild COMPACTED_SIZE and a TLAS rebuild's CURRENT_SIZE are
7// checked against the prebuild sizes, and the BLAS is compacted (CopyRaytracingAccelerationStructure COMPACT) into a
8// buffer of exactly that size, written as d3d12_blas_compacted as <case>.bin + <case>.json at their console GPU virtual addresses.
6// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest: 9// `python -I tools/xdxr_bvh.py check-build <out dir>` validates them and traces rays against brute force (ctest:
7// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files. 10// d3d12_xdxr_rt + d3d12_xdxr_rt_check). Exit 77 without a Vulkan device, or with LEONIDA_RT_AS=khr. No game files.
8#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -153,6 +156,7 @@ int main(int argc, char** argv) {
153 156
154 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; 157 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{};
155 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; 158 blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
159 blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; // updated below
156 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; 160 blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
157 blas_inputs.NumDescs = 2; 161 blas_inputs.NumDescs = 2;
158 blas_inputs.pGeometryDescs = geometries; 162 blas_inputs.pGeometryDescs = geometries;
@@ -239,7 +243,7 @@ int main(int argc, char** argv) {
239 ID3D12CommandList* lists[] = {list.p}; 243 ID3D12CommandList* lists[] = {list.p};
240 queue->ExecuteCommandLists(1, lists); 244 queue->ExecuteCommandLists(1, lists);
241 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal"); 245 if (FAILED(queue->Signal(fence.p, 1))) return fail("Signal");
242 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 246 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // reused for the update below
243 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) && 247 const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(1, event)) &&
244 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; 248 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
245 if (event) CloseHandle(event); 249 if (event) CloseHandle(event);
@@ -258,31 +262,35 @@ int main(int argc, char** argv) {
258 rb->Unmap(0, nullptr); 262 rb->Unmap(0, nullptr);
259 return ok; 263 return ok;
260 }; 264 };
261 std::string tris = "["; 265 // The BLAS's triangles as the reference sees them, for the soup's current positions.
262 bool first = true; 266 auto triangles_json = [&](const std::vector<float>& soup_now) {
263 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) { 267 std::string tris = "[";
264 tris += first ? "\n [" : ",\n ["; 268 bool first = true;
265 first = false; 269 auto add_tri = [&](const float v[3][3], int geometry, UINT primitive) {
266 for (int k = 0; k < 3; ++k) 270 tris += first ? "\n [" : ",\n [";
267 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]"; 271 first = false;
268 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]"; 272 for (int k = 0; k < 3; ++k)
269 }; 273 tris += (k ? ", [" : "[") + num(v[k][0]) + ", " + num(v[k][1]) + ", " + num(v[k][2]) + "]";
270 for (UINT t = 0; t < soup_tris; ++t) { 274 tris += ", " + std::to_string(geometry) + ", " + std::to_string(primitive) + "]";
271 float v[3][3]; 275 };
272 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup[9 * t + k]; 276 for (UINT t = 0; t < soup_tris; ++t) {
273 add_tri(v, 0, t); 277 float v[3][3];
274 } 278 for (int k = 0; k < 9; ++k) v[k / 3][k % 3] = soup_now[9 * t + k];
275 for (UINT t = 0; t < indices.size() / 3; ++t) { 279 add_tri(v, 0, t);
276 float v[3][3];
277 for (int k = 0; k < 3; ++k) {
278 const float* p = &grid[4 * indices[3 * t + k]];
279 for (int r = 0; r < 3; ++r)
280 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
281 transform[4 * r + 3];
282 } 280 }
283 add_tri(v, 1, t); 281 for (UINT t = 0; t < indices.size() / 3; ++t) {
284 } 282 float v[3][3];
285 tris += "]"; 283 for (int k = 0; k < 3; ++k) {
284 const float* p = &grid[4 * indices[3 * t + k]];
285 for (int r = 0; r < 3; ++r)
286 v[k][r] = transform[4 * r] * p[0] + transform[4 * r + 1] * p[1] + transform[4 * r + 2] * p[2] +
287 transform[4 * r + 3];
288 }
289 add_tri(v, 1, t);
290 }
291 return tris + "]";
292 };
293 const std::string tris = triangles_json(soup);
286 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas", 294 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas",
287 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + 295 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
288 ", \"triangles\": " + tris + "}\n")) 296 ", \"triangles\": " + tris + "}\n"))
@@ -298,6 +306,103 @@ int main(int argc, char** argv) {
298 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + 306 "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) +
299 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n")) 307 ", \"bias\": 0, \"blas\": [\"d3d12_blas\"], \"instances\": " + inst + "}\n"))
300 return fail("TLAS readback"); 308 return fail("TLAS readback");
309
310 // ---- PERFORM_UPDATE in place: the soup moves (every vertex), the grid stays; the BLAS is refitted ----
311 std::vector<float> moved = soup;
312 std::uniform_real_distribution<float> nudge(-1.0f, 1.0f);
313 for (std::size_t v = 0; v < moved.size(); v += 3) {
314 moved[v] = moved[v] * 1.3f + nudge(rng);
315 moved[v + 1] = moved[v + 1] * 0.7f + nudge(rng);
316 moved[v + 2] += nudge(rng);
317 }
318 if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) return fail("Map upload for the update");
319 std::memcpy(mapped + (soup_va - upload->GetGPUVirtualAddress()), moved.data(), std::size_t(soup_bytes));
320 upload->Unmap(0, nullptr);
321 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for the update");
322 build.Inputs = blas_inputs;
323 build.Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
324 build.DestAccelerationStructureData = blas->GetGPUVirtualAddress();
325 build.SourceAccelerationStructureData = blas->GetGPUVirtualAddress();
326 list->BuildRaytracingAccelerationStructure(&build, 0, nullptr);
327 list->ResourceBarrier(1, &barrier);
328 list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes);
329 if (FAILED(hr = list->Close())) return fail("Close (update)", hr);
330 queue->ExecuteCommandLists(1, lists);
331 if (FAILED(queue->Signal(fence.p, 2))) return fail("Signal (update)");
332 event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
333 const bool updated = event && SUCCEEDED(fence->SetEventOnCompletion(2, event)) &&
334 WaitForSingleObject(event, 10000) == WAIT_OBJECT_0;
335 if (event) CloseHandle(event);
336 if (!updated) return fail("the update did not complete");
337 if (!dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "d3d12_blas_update",
338 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
339 ", \"triangles\": " + triangles_json(moved) + "}\n"))
340 return fail("BLAS readback after the update");
341
342 // ---- postbuild info and compaction: EmitRaytracingAccelerationStructurePostbuildInfo for both structures, a
343 // TLAS rebuild with a CURRENT_SIZE postbuild desc, then COMPACT the BLAS into a buffer of exactly its size ----
344 auto submit = [&](UINT64 value) {
345 if (FAILED(list->Close())) return false;
346 queue->ExecuteCommandLists(1, lists);
347 if (FAILED(queue->Signal(fence.p, value))) return false;
348 HANDLE e = CreateEventW(nullptr, FALSE, FALSE, nullptr);
349 const bool ok = e && SUCCEEDED(fence->SetEventOnCompletion(value, e)) &&
350 WaitForSingleObject(e, 10000) == WAIT_OBJECT_0;
351 if (e) CloseHandle(e);
352 return ok;
353 };
354 Ref<ID3D12Resource> info, info_rb;
355 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, 24, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, info.put())) ||
356 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, 24, D3D12_RESOURCE_STATE_COPY_DEST,
357 D3D12_RESOURCE_FLAG_NONE, info_rb.put())))
358 return fail("postbuild buffers", hr);
359 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for postbuild");
360 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC compacted_desc{
361 info->GetGPUVirtualAddress(), D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE};
362 const D3D12_GPU_VIRTUAL_ADDRESS both[2] = {blas->GetGPUVirtualAddress(), tlas->GetGPUVirtualAddress()};
363 list->EmitRaytracingAccelerationStructurePostbuildInfo(&compacted_desc, 2, both);
364 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC current_desc{
365 info->GetGPUVirtualAddress() + 16, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE};
366 build = {};
367 build.Inputs = tlas_inputs;
368 build.DestAccelerationStructureData = tlas->GetGPUVirtualAddress();
369 build.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress();
370 list->BuildRaytracingAccelerationStructure(&build, 1, &current_desc);
371 list->ResourceBarrier(1, &barrier);
372 list->CopyBufferRegion(info_rb.p, 0, info.p, 0, 24);
373 if (!submit(3)) return fail("postbuild submission");
374 UINT64 sizes[3] = {};
375 {
376 void* p = nullptr;
377 if (FAILED(info_rb->Map(0, nullptr, &p))) return fail("Map postbuild");
378 std::memcpy(sizes, p, sizeof sizes);
379 info_rb->Unmap(0, nullptr);
380 }
381 // the builds are exactly their prebuild size, so the compacted size is that size
382 if (sizes[0] != blas_info.ResultDataMaxSizeInBytes || sizes[1] != tlas_info.ResultDataMaxSizeInBytes ||
383 sizes[2] != tlas_info.ResultDataMaxSizeInBytes) {
384 std::fprintf(stderr, "postbuild sizes %llu %llu %llu, prebuild %llu %llu\n",
385 static_cast<unsigned long long>(sizes[0]), static_cast<unsigned long long>(sizes[1]),
386 static_cast<unsigned long long>(sizes[2]),
387 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
388 static_cast<unsigned long long>(tlas_info.ResultDataMaxSizeInBytes));
389 return fail("postbuild sizes");
390 }
391 Ref<ID3D12Resource> compacted, compacted_rb;
392 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, sizes[0], as_state, uav, compacted.put())) ||
393 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, sizes[0], D3D12_RESOURCE_STATE_COPY_DEST,
394 D3D12_RESOURCE_FLAG_NONE, compacted_rb.put())))
395 return fail("compacted buffers", hr);
396 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for compaction");
397 list->CopyRaytracingAccelerationStructure(compacted->GetGPUVirtualAddress(), blas->GetGPUVirtualAddress(),
398 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT);
399 list->ResourceBarrier(1, &barrier);
400 list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, sizes[0]);
401 if (!submit(4)) return fail("compaction submission");
402 if (!dump(compacted_rb.p, sizes[0], "d3d12_blas_compacted",
403 "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) +
404 ", \"triangles\": " + triangles_json(moved) + "}\n"))
405 return fail("compacted BLAS readback");
301 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n", 406 std::printf("d3d12_xdxr_rt: BLAS %llu bytes (prebuild %llu), TLAS (prebuild %llu), written to %s\n",
302 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 407 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
303 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes), 408 static_cast<unsigned long long>(blas_info.ResultDataMaxSizeInBytes),
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
index a24a9c6e2..26fb39083 100644
--- a/runtime/test/descriptor_table_test.cpp
+++ b/runtime/test/descriptor_table_test.cpp
@@ -233,7 +233,7 @@ int test_clear_resets_table() {
233 return 0; 233 return 0;
234} 234}
235 235
236int test_erase_and_cluster_compact() { 236int test_erase_and_reinsert() {
237 DescriptorTable table(16); 237 DescriptorTable table(16);
238 238
239 const std::uint32_t k1[8] = {1, 10, 100, 1000, 2, 20, 200, 2000}; 239 const std::uint32_t k1[8] = {1, 10, 100, 1000, 2, 20, 200, 2000};
@@ -310,12 +310,12 @@ int test_change_tracking() {
310 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot); 310 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot);
311 EXPECT(table.read_slot(slot, read) && read[8] == 43); 311 EXPECT(table.read_slot(slot, read) && read[8] == 43);
312 312
313 // Erasing marks the slot it was in and the ones the cluster compaction moved. 313 // Erasing marks only the slot it was in: no other entry moves.
314 EXPECT(table.insert(k2, 7)); 314 EXPECT(table.insert(k2, 7));
315 table.take_changes(); 315 table.take_changes();
316 EXPECT(table.erase(k1)); 316 EXPECT(table.erase(k1));
317 changes = table.take_changes(); 317 changes = table.take_changes();
318 EXPECT(!changes.all && !changes.slots.empty() && changes.slots.front() == slot); 318 EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot);
319 319
320 // Growth changes the mask, so everything re-uploads. 320 // Growth changes the mask, so everything re-uploads.
321 const std::size_t before = table.capacity(); 321 const std::size_t before = table.capacity();
@@ -366,6 +366,48 @@ int test_relocation_marks_both_slots() {
366 return 0; 366 return 0;
367} 367}
368 368
369// Shaders keep probing the GPU copy of the table while an erase is uploaded without waiting for idle
370// (BindlessSet::flush_needs_idle), so an erase must leave every other key's slot exactly as it was.
371int test_erase_moves_no_other_entry() {
372 DescriptorTable table(64);
373 const std::uint32_t slots = std::uint32_t(table.capacity());
374 // Five keys with one home: they fill five consecutive slots, the cluster the old erase compacted.
375 std::array<DescriptorKey, 5> keys{};
376 for (std::uint32_t i = 0; i < keys.size(); ++i) {
377 auto& key = keys[i];
378 key[0] = i + 1;
379 while ((hash_descriptor_key(key) & (slots - 1)) != slots - 2) ++key[7]; // the cluster wraps the end
380 EXPECT(table.insert_or_update(key.data(), 200 + i) == DescriptorTable::InsertResult::added);
381 }
382 table.take_changes();
383 const auto before = table.build_gpu_buffer();
384
385 EXPECT(table.erase(keys[1].data()));
386 const DescriptorTable::Changes changes = table.take_changes();
387 EXPECT(!changes.all && changes.slots.size() == 1);
388 const std::uint32_t hole = changes.slots.front();
389 const auto after = table.build_gpu_buffer();
390 for (std::uint32_t s = 0; s < slots; ++s) {
391 const bool same = std::memcmp(&before[1 + s * 10], &after[1 + s * 10], 10 * sizeof(std::uint32_t)) == 0;
392 EXPECT(same == (s != hole));
393 }
394 for (std::uint32_t w = 0; w < 10; ++w) EXPECT(after[1 + hole * 10 + w] == 0); // an empty slot: a miss
395 for (std::uint32_t i = 0; i < keys.size(); ++i) EXPECT(table.lookup(keys[i]) == (i == 1 ? 0u : 200 + i));
396
397 // Keys past the hole are still found after more erases, and a new key of the same home reuses the hole.
398 EXPECT(table.erase(keys[0].data()));
399 EXPECT(table.lookup(keys[4]) == 204 && table.lookup(keys[3]) == 203);
400 DescriptorKey extra = keys[0];
401 extra[0] = 100;
402 while ((hash_descriptor_key(extra) & (slots - 1)) != slots - 2) ++extra[7];
403 table.take_changes();
404 EXPECT(table.insert_or_update(extra.data(), 300) == DescriptorTable::InsertResult::added);
405 const DescriptorTable::Changes reuse = table.take_changes();
406 EXPECT(reuse.slots.size() == 1 && reuse.slots.front() == slots - 2); // the first hole of the probe window
407 EXPECT(table.lookup(extra) == 300 && table.size() == 4);
408 return 0;
409}
410
369int main() { 411int main() {
370 EXPECT(test_fnv1a_hash_matches_contract() == 0); 412 EXPECT(test_fnv1a_hash_matches_contract() == 0);
371 EXPECT(test_ssharp_key_padding() == 0); 413 EXPECT(test_ssharp_key_padding() == 0);
@@ -376,9 +418,10 @@ int main() {
376 EXPECT(test_gpu_buffer_serialization() == 0); 418 EXPECT(test_gpu_buffer_serialization() == 0);
377 EXPECT(test_change_tracking() == 0); 419 EXPECT(test_change_tracking() == 0);
378 EXPECT(test_relocation_marks_both_slots() == 0); 420 EXPECT(test_relocation_marks_both_slots() == 0);
421 EXPECT(test_erase_moves_no_other_entry() == 0);
379 EXPECT(test_multithreaded_insert_and_lookup() == 0); 422 EXPECT(test_multithreaded_insert_and_lookup() == 0);
380 EXPECT(test_clear_resets_table() == 0); 423 EXPECT(test_clear_resets_table() == 0);
381 EXPECT(test_erase_and_cluster_compact() == 0); 424 EXPECT(test_erase_and_reinsert() == 0);
382 425
383 std::printf("descriptor_table_test: all tests passed (0 failures)\n"); 426 std::printf("descriptor_table_test: all tests passed (0 failures)\n");
384 return 0; 427 return 0;
diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp
index e414f155b..70cae9a89 100644
--- a/runtime/test/device_proxy_test.cpp
+++ b/runtime/test/device_proxy_test.cpp
@@ -151,19 +151,19 @@ int main() {
151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get()); 151 unsigned slots = rt::d3d12_xs::device_proxy_slot_count(device.Get());
152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots); 152 std::printf("proxy forwards %u PC vtable slots (ID3D12Device..Device14 max is 83)\n", slots);
153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable"); 153 check(slots >= 44, "proxy forwards at least the base ID3D12Device vtable");
154 check(!rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is forwarded (PC CreateCommandAllocator)"); 154 check(rt::d3d12_xs::device_slot_overridden(9), "device slot 9 is CreateCommandAllocator (allocator proxies)");
155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)"); 155 check(!rt::d3d12_xs::device_slot_overridden(10), "device slot 10 is forwarded (PC CreateGraphicsPipelineState)");
156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override"); 156 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override");
157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); 157 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override");
158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); 158 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override");
159 check(rt::d3d12_xs::device_slot_overridden(67), 159 check(rt::d3d12_xs::device_slot_overridden(67),
160 "device slot 67 is refused (console DeserializeComputePipelineStateX, " 160 "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)");
161 "not PC CreateProtectedResourceSession1)");
162 161
163 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get()); 162 void** proxy_vtbl = *reinterpret_cast<void***>(device.Get());
164 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr; 163 void** real_vtbl = real ? *reinterpret_cast<void***>(real) : nullptr;
165 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry"); 164 check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry");
166 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject"); 165 if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject");
166 if (slots > 67) check(proxy_vtbl[67] != real_vtbl[67], "slot 67 thunk differs from PC CreateProtectedResourceSession1");
167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3"); 167 if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3");
168 168
169 rt::d3d12_xs::reset_device_proxy_stats(); 169 rt::d3d12_xs::reset_device_proxy_stats();
@@ -278,6 +278,8 @@ int main() {
278 ComPtr<ID3D12CommandAllocator> allocator; 278 ComPtr<ID3D12CommandAllocator> allocator;
279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf())); 279 hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.GetAddressOf()));
280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator"); 280 check(SUCCEEDED(hr) && allocator != nullptr, "device slot 9 forwards CreateCommandAllocator");
281 // A PC runtime allocator is not wrapped: the PC runtime's lists could not resolve an allocator proxy.
282 check(!rt::d3d12_xs::is_allocator_proxy(allocator.Get()), "slot 9 hands out the PC allocator unwrapped");
281 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1"); 283 check(rt::d3d12_xs::device_slot_hits(9) == 1, "slot 9 hit counter is 1");
282 284
283 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR. 285 // Slot 76: buffer resource with the measured Xbox layout word 0x101; PC committed resources take ROW_MAJOR.
@@ -342,6 +344,31 @@ int main() {
342 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState"); 344 check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState");
343 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1"); 345 check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1");
344 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set"); 346 check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set");
347
348 // Slot 67: Xbox native compute pipeline creation. Maps the console descriptor (+0x00 root signature,
349 // +0x28 kind 6 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState.
350 struct XboxNativeComputeDesc {
351 ID3D12RootSignature* root_signature;
352 const void* kind0;
353 std::uint64_t kind0_size;
354 const void* kind1;
355 std::uint64_t kind1_size;
356 const void* kind6;
357 std::uint64_t kind6_size;
358 const void* kind7;
359 std::uint64_t kind7_size;
360 } xbox_desc{};
361 xbox_desc.root_signature = root_signature.Get();
362 xbox_desc.kind6 = bytecode->GetBufferPointer();
363 xbox_desc.kind6_size = bytecode->GetBufferSize();
364
365 using XboxCreateNativeComputePsoFn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
366 auto create_native_pso = reinterpret_cast<XboxCreateNativeComputePsoFn>(proxy_vtbl[67]);
367 ComPtr<ID3D12PipelineState> pso67;
368 hr = create_native_pso(device.Get(), &xbox_desc, &iid_pso, reinterpret_cast<void**>(pso67.GetAddressOf()));
369 check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState");
370 check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1");
371 check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set");
345 } 372 }
346 373
347 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, 374 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions,
@@ -357,6 +384,14 @@ int main() {
357 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{}; 384 D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{};
358 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out); 385 hr = reinterpret_cast<Slot62Fn>(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out);
359 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID"); 386 check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID");
387 using Slot67Fn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**);
388 proxy_out = reinterpret_cast<void*>(0x1111);
389 const IID iid_pso = __uuidof(ID3D12PipelineState);
390 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), nullptr, &iid_pso, &proxy_out);
391 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null description");
392 proxy_out = reinterpret_cast<void*>(0x1111);
393 hr = reinterpret_cast<Slot67Fn>(proxy_vtbl[67])(device.Get(), &root_desc, nullptr, &proxy_out);
394 check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null IID");
360 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, 395 using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
361 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, 396 const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
362 const D3D12_CLEAR_VALUE*, const IID*, void**); 397 const D3D12_CLEAR_VALUE*, const IID*, void**);
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index 3b23b3579..c22397d90 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -276,6 +276,18 @@ int main() {
276 scd.BufferCount = 2; 276 scd.BufferCount = 2;
277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; 277 scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
278 278
279 for (const UINT count : {0u, 1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
280 DXGI_SWAP_CHAIN_DESC1 invalid = scd;
281 invalid.BufferCount = count;
282 IDXGISwapChain1* rejected = nullptr;
283 const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd, &invalid, nullptr, nullptr, &rejected);
284 if (rejected) {
285 rejected->Release();
286 return fail("CreateSwapChainForHwnd returned a swapchain for an invalid buffer count");
287 }
288 if (hr != DXGI_ERROR_INVALID_CALL) return fail("CreateSwapChainForHwnd invalid buffer count HRESULT");
289 }
290
279 IDXGISwapChain1* sc1 = nullptr; 291 IDXGISwapChain1* sc1 = nullptr;
280 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1) 292 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd, &scd, nullptr, nullptr, &sc1)) || !sc1)
281 return fail("CreateSwapChainForHwnd"); 293 return fail("CreateSwapChainForHwnd");
@@ -421,12 +433,34 @@ int main() {
421 return 0; 433 return 0;
422 }; 434 };
423 435
436 // Invalid counts must leave the initial back buffers usable for the first frame.
437 {
438 DXGI_SWAP_CHAIN_DESC1 before_resize{};
439 if (FAILED(sc->GetDesc1(&before_resize))) return fail("GetDesc1 before invalid resizes");
440 const std::vector<UINT> node_masks(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, 1);
441 const std::vector<IUnknown*> present_queues(DXGI_MAX_SWAP_CHAIN_BUFFERS + 1, queue);
442 for (const UINT count : {1u, DXGI_MAX_SWAP_CHAIN_BUFFERS + 1u}) {
443 if (sc->ResizeBuffers(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0) != E_INVALIDARG)
444 return fail("ResizeBuffers invalid buffer count HRESULT");
445 if (sc->ResizeBuffers1(count, 64, 64, DXGI_FORMAT_UNKNOWN, 0, node_masks.data(), present_queues.data()) !=
446 E_INVALIDARG)
447 return fail("ResizeBuffers1 invalid buffer count HRESULT");
448 }
449 DXGI_SWAP_CHAIN_DESC1 after_resize{};
450 if (FAILED(sc->GetDesc1(&after_resize)) || after_resize.BufferCount != before_resize.BufferCount ||
451 after_resize.Width != before_resize.Width || after_resize.Height != before_resize.Height)
452 return fail("Invalid resize changed swapchain buffers");
453 }
454
424 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present. 455 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present.
425 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f}; 456 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f};
426 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1; 457 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1;
427 458
428 // Frame 2: ResizeBuffers to explicit 37x19 on the unchanged 128x128 HWND, clear to green, read back all 703 pixels, Present. 459 // Frame 2: ResizeBuffers to explicit 37x19 on the unchanged 128x128 HWND, clear to green, read back all 703 pixels, Present.
429 if (FAILED(sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers"); 460 if (FAILED(sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers");
461 DXGI_SWAP_CHAIN_DESC1 preserved_format{};
462 if (FAILED(sc->GetDesc1(&preserved_format)) || preserved_format.Format != scd.Format)
463 return fail("ResizeBuffers with DXGI_FORMAT_UNKNOWN changed the format");
430 const float green[4] = {0.0f, 1.0f, 0.0f, 1.0f}; 464 const float green[4] = {0.0f, 1.0f, 0.0f, 1.0f};
431 if (run_clear_readback_present(37, 19, green, 0, 255, 0) != 0) return 1; 465 if (run_clear_readback_present(37, 19, green, 0, 255, 0) != 0) return 1;
432 466
@@ -587,9 +621,28 @@ int main() {
587 return fail("GetRotation(nullptr) should return E_INVALIDARG"); 621 return fail("GetRotation(nullptr) should return E_INVALIDARG");
588 } 622 }
589 623
590 // Unsupported swapchain format must fail explicitly instead of silently downgrading to BGRA8. 624 constexpr DXGI_FORMAT invalid_formats[] = {
591 if (sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_R32_UINT, 0) != DXGI_ERROR_UNSUPPORTED) 625 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
592 return fail("ResizeBuffers should reject unsupported format DXGI_FORMAT_R32_UINT"); 626 DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R32_UINT,
627 };
628 {
629 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
630 if (FAILED(sc->GetDesc1(&before))) return fail("GetDesc1 before invalid formats");
631 const UINT node_masks[2] = {1, 1};
632 IUnknown* const present_queues[2] = {queue, queue};
633 for (DXGI_FORMAT format : invalid_formats) {
634 if (sc->ResizeBuffers(2, 64, 64, format, 0) != E_INVALIDARG ||
635 sc->ResizeBuffers1(2, 64, 64, format, 0, node_masks, present_queues) != E_INVALIDARG)
636 return fail("ResizeBuffers and ResizeBuffers1 should reject invalid flip-model formats");
637 }
638 if (FAILED(sc->GetDesc1(&after)) || after.Format != before.Format || after.BufferCount != before.BufferCount ||
639 after.Width != before.Width || after.Height != before.Height)
640 return fail("Invalid format changed the existing swapchain");
641 ID3D12Resource* buffer = nullptr;
642 if (FAILED(sc->GetBuffer(sc->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&buffer))) || !buffer)
643 return fail("GetBuffer after invalid swapchain formats");
644 buffer->Release();
645 }
593 646
594 // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back 647 // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back
595 // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing. 648 // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing.
@@ -747,6 +800,8 @@ int main() {
747 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at 800 // Zero width or height means the window's client area, in ResizeBuffers (the usual WM_SIZE call) and at
748 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size. 801 // creation; host DXGI: ResizeBuffers(0, 0, 0) after resizing the window gives the new client size.
749 { 802 {
803 DXGI_SWAP_CHAIN_DESC1 before_zero{};
804 if (FAILED(sc->GetDesc1(&before_zero))) return fail("GetDesc1 before zero-count resize");
750 RECT wr{0, 0, 300, 200}; 805 RECT wr{0, 0, 300, 200};
751 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); 806 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
752 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER); 807 SetWindowPos(hwnd, nullptr, 0, 0, wr.right - wr.left, wr.bottom - wr.top, SWP_NOMOVE | SWP_NOZORDER);
@@ -754,7 +809,8 @@ int main() {
754 GetClientRect(hwnd, &cr); 809 GetClientRect(hwnd, &cr);
755 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)"); 810 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers(0, 0, 0)");
756 DXGI_SWAP_CHAIN_DESC1 d{}; 811 DXGI_SWAP_CHAIN_DESC1 d{};
757 sc->GetDesc1(&d); 812 if (FAILED(sc->GetDesc1(&d)) || d.BufferCount != before_zero.BufferCount)
813 return fail("ResizeBuffers(0, 0, 0) changed the buffer count");
758 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) { 814 if (d.Width != UINT(cr.right) || d.Height != UINT(cr.bottom)) {
759 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height, 815 std::fprintf(stderr, "FAIL: ResizeBuffers(0, 0, 0) gave %ux%u, client area is %ldx%ld\n", d.Width, d.Height,
760 cr.right, cr.bottom); 816 cr.right, cr.bottom);
@@ -764,6 +820,21 @@ int main() {
764 HWND hwnd2 = create_test_window(200, 150); 820 HWND hwnd2 = create_test_window(200, 150);
765 if (!hwnd2) return fail("CreateWindowExW (second)"); 821 if (!hwnd2) return fail("CreateWindowExW (second)");
766 GetClientRect(hwnd2, &cr); 822 GetClientRect(hwnd2, &cr);
823 const auto rejects_creation_format = [&](DXGI_FORMAT format) {
824 DXGI_SWAP_CHAIN_DESC1 invalid = scd;
825 invalid.Format = format;
826 IDXGISwapChain1* rejected = nullptr;
827 const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd2, &invalid, nullptr, nullptr, &rejected);
828 if (rejected) {
829 rejected->Release();
830 return false;
831 }
832 return hr == DXGI_ERROR_INVALID_CALL;
833 };
834 if (!rejects_creation_format(DXGI_FORMAT_UNKNOWN))
835 return fail("CreateSwapChainForHwnd accepted DXGI_FORMAT_UNKNOWN");
836 for (DXGI_FORMAT format : invalid_formats)
837 if (!rejects_creation_format(format)) return fail("CreateSwapChainForHwnd invalid flip-model format");
767 DXGI_SWAP_CHAIN_DESC1 zd = scd; 838 DXGI_SWAP_CHAIN_DESC1 zd = scd;
768 zd.Width = 0; 839 zd.Width = 0;
769 zd.Height = 0; 840 zd.Height = 0;
@@ -794,11 +865,31 @@ int main() {
794 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG"); 865 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG");
795 factory5->Release(); 866 factory5->Release();
796 867
868 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
869 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
870 constexpr UINT both_flags = tearing_flag | waitable_flag;
871 const UINT node_masks[2] = {1, 1};
872 IUnknown* const present_queues[2] = {queue, queue};
873 const auto rejects_flag_change = [&](IDXGISwapChain3* chain, UINT flags) {
874 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
875 if (FAILED(chain->GetDesc1(&before))) return false;
876 const UINT width = before.Width + 1;
877 return chain->ResizeBuffers(0, width, before.Height, DXGI_FORMAT_UNKNOWN, flags) == E_INVALIDARG &&
878 chain->ResizeBuffers1(2, width, before.Height, DXGI_FORMAT_UNKNOWN, flags,
879 node_masks, present_queues) == E_INVALIDARG &&
880 SUCCEEDED(chain->GetDesc1(&after)) && after.Flags == before.Flags &&
881 after.BufferCount == before.BufferCount && after.Width == before.Width &&
882 after.Height == before.Height;
883 };
884
797 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected. 885 // Non-waitable, non-tearing swapchain: GetFrameLatencyWaitableObject is null and ALLOW_TEARING is rejected.
886 for (UINT flags : {waitable_flag, tearing_flag, both_flags})
887 if (!rejects_flag_change(sc, flags)) return fail("Resize accepted adding a creation-only flag");
798 if (sc->GetFrameLatencyWaitableObject() != nullptr) 888 if (sc->GetFrameLatencyWaitableObject() != nullptr)
799 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject"); 889 return fail("Non-waitable swapchain should return nullptr from GetFrameLatencyWaitableObject");
800 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL) 890 if (sc->Present(0, DXGI_PRESENT_ALLOW_TEARING) != DXGI_ERROR_INVALID_CALL)
801 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL"); 891 return fail("Present(ALLOW_TEARING) on non-tearing swapchain should return DXGI_ERROR_INVALID_CALL");
892 if (FAILED(sc->Present(0, 0))) return fail("Present after rejected resize on a plain swapchain");
802 893
803 HWND hwnd3 = create_test_window(128, 96); 894 HWND hwnd3 = create_test_window(128, 96);
804 if (!hwnd3) return fail("CreateWindowExW (third)"); 895 if (!hwnd3) return fail("CreateWindowExW (third)");
@@ -806,7 +897,7 @@ int main() {
806 wdesc.Width = 128; 897 wdesc.Width = 128;
807 wdesc.Height = 96; 898 wdesc.Height = 96;
808 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer 899 wdesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM; // also tests presenting an untouched offscreen backbuffer
809 wdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 900 wdesc.Flags = both_flags;
810 IDXGISwapChain1* wsc1 = nullptr; 901 IDXGISwapChain1* wsc1 = nullptr;
811 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1) 902 if (FAILED(factory->CreateSwapChainForHwnd(queue, hwnd3, &wdesc, nullptr, nullptr, &wsc1)) || !wsc1)
812 return fail("CreateSwapChainForHwnd (tearing + waitable)"); 903 return fail("CreateSwapChainForHwnd (tearing + waitable)");
@@ -814,6 +905,8 @@ int main() {
814 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)"); 905 if (FAILED(wsc1->QueryInterface(IID_PPV_ARGS(&wsc))) || !wsc) return fail("QI IDXGISwapChain3 (waitable)");
815 wsc1->Release(); 906 wsc1->Release();
816 907
908 for (UINT flags : {0u, waitable_flag, tearing_flag})
909 if (!rejects_flag_change(wsc, flags)) return fail("Resize accepted removing a creation-only flag");
817 DXGI_SWAP_CHAIN_DESC1 got_desc{}; 910 DXGI_SWAP_CHAIN_DESC1 got_desc{};
818 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags) 911 if (FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Flags != wdesc.Flags)
819 return fail("Waitable swapchain GetDesc1 did not preserve Flags"); 912 return fail("Waitable swapchain GetDesc1 did not preserve Flags");
@@ -836,11 +929,131 @@ int main() {
836 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint"); 929 if (!check_statistics_disjoint(wsc)) return fail("first statistics query after Present should be disjoint");
837 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0) 930 if (WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
838 return fail("Post-Present WaitForSingleObject on waitable swapchain failed"); 931 return fail("Post-Present WaitForSingleObject on waitable swapchain failed");
932 if (FAILED(wsc->ResizeBuffers(0, wdesc.Width + 1, wdesc.Height, DXGI_FORMAT_UNKNOWN, both_flags)) ||
933 FAILED(wsc->GetDesc1(&got_desc)) || got_desc.Width != wdesc.Width + 1 || got_desc.Flags != both_flags)
934 return fail("ResizeBuffers with matching creation flags failed");
935 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) ||
936 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
937 return fail("Present or wait after resizing the waitable swapchain failed");
839 CloseHandle(waitable); 938 CloseHandle(waitable);
840 wsc->Release(); 939 wsc->Release();
841 DestroyWindow(hwnd3); 940 DestroyWindow(hwnd3);
842 } 941 }
843 942
943 // CreateSwapChainForCoreWindow & Occlusion status registration
944 {
945 // 1. Parameter validation
946 IDXGISwapChain1* sc_dummy = nullptr;
947 if (factory->CreateSwapChainForCoreWindow(queue, nullptr, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
948 return fail("CreateSwapChainForCoreWindow(null window) should return E_INVALIDARG");
949 if (factory->CreateSwapChainForCoreWindow(nullptr, queue, &scd, nullptr, &sc_dummy) != E_INVALIDARG)
950 return fail("CreateSwapChainForCoreWindow(null device) should return E_INVALIDARG");
951 if (factory->CreateSwapChainForCoreWindow(queue, queue, nullptr, nullptr, &sc_dummy) != E_INVALIDARG)
952 return fail("CreateSwapChainForCoreWindow(null desc) should return E_INVALIDARG");
953 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, nullptr) != E_POINTER)
954 return fail("CreateSwapChainForCoreWindow(null out) should return E_POINTER");
955
956 // Non-CoreWindow IUnknown
957 if (factory->CreateSwapChainForCoreWindow(queue, queue, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL)
958 return fail("CreateSwapChainForCoreWindow with non-CoreWindow should return DXGI_ERROR_INVALID_CALL");
959
960 // 2. Mock ICoreWindow with ICoreWindowInterop
961 static constexpr GUID kIID_ICoreWindowInterop = {
962 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}};
963 struct MockCoreWindow final : public IUnknown {
964 HWND window_handle = nullptr;
965 std::atomic<ULONG> refs{1};
966
967 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
968 if (!out) return E_POINTER;
969 if (riid == IID_IUnknown || riid == kIID_ICoreWindowInterop) {
970 *out = this;
971 AddRef();
972 return S_OK;
973 }
974 *out = nullptr;
975 return E_NOINTERFACE;
976 }
977 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
978 ULONG STDMETHODCALLTYPE Release() override {
979 ULONG r = --refs;
980 if (!r) delete this;
981 return r;
982 }
983 virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) {
984 if (!hwnd) return E_POINTER;
985 *hwnd = window_handle;
986 return S_OK;
987 }
988 virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char) { return S_OK; }
989 };
990
991 auto* mock_cw = new MockCoreWindow();
992 // Null HWND in interop
993 if (factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &sc_dummy) != DXGI_ERROR_INVALID_CALL) {
994 mock_cw->Release();
995 return fail("CreateSwapChainForCoreWindow with null HWND should return DXGI_ERROR_INVALID_CALL");
996 }
997
998 // Valid HWND in mock CoreWindow
999 HWND hwnd4 = create_test_window(160, 120);
1000 if (!hwnd4) {
1001 mock_cw->Release();
1002 return fail("CreateWindowExW (fourth)");
1003 }
1004 mock_cw->window_handle = hwnd4;
1005 IDXGISwapChain1* cw_sc1 = nullptr;
1006 if (FAILED(factory->CreateSwapChainForCoreWindow(queue, mock_cw, &scd, nullptr, &cw_sc1)) || !cw_sc1) {
1007 mock_cw->Release();
1008 DestroyWindow(hwnd4);
1009 return fail("CreateSwapChainForCoreWindow with valid MockCoreWindow failed");
1010 }
1011 IDXGISwapChain3* cw_sc = nullptr;
1012 if (FAILED(cw_sc1->QueryInterface(IID_PPV_ARGS(&cw_sc))) || !cw_sc) {
1013 cw_sc1->Release();
1014 mock_cw->Release();
1015 DestroyWindow(hwnd4);
1016 return fail("QI IDXGISwapChain3 on CoreWindow swapchain failed");
1017 }
1018 cw_sc1->Release();
1019 DXGI_SWAP_CHAIN_DESC1 cw_desc{};
1020 if (FAILED(cw_sc->GetDesc1(&cw_desc)) || cw_desc.Width != scd.Width || cw_desc.Height != scd.Height) {
1021 cw_sc->Release();
1022 mock_cw->Release();
1023 DestroyWindow(hwnd4);
1024 return fail("GetDesc1 on CoreWindow swapchain mismatch");
1025 }
1026 if (FAILED(cw_sc->Present(0, 0))) {
1027 cw_sc->Release();
1028 mock_cw->Release();
1029 DestroyWindow(hwnd4);
1030 return fail("Present on CoreWindow swapchain failed");
1031 }
1032 cw_sc->Release();
1033 mock_cw->Release();
1034 DestroyWindow(hwnd4);
1035
1036 // 3. Occlusion status registration
1037 DWORD cookie1 = 0, cookie2 = 0;
1038 if (factory->RegisterOcclusionStatusWindow(nullptr, WM_USER, &cookie1) != DXGI_ERROR_INVALID_CALL)
1039 return fail("RegisterOcclusionStatusWindow(null hwnd) should return DXGI_ERROR_INVALID_CALL");
1040 if (factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, nullptr) != DXGI_ERROR_INVALID_CALL)
1041 return fail("RegisterOcclusionStatusWindow(null cookie) should return DXGI_ERROR_INVALID_CALL");
1042 if (FAILED(factory->RegisterOcclusionStatusWindow(hwnd, WM_USER, &cookie1)) || cookie1 == 0)
1043 return fail("RegisterOcclusionStatusWindow failed");
1044
1045 HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1046 if (factory->RegisterOcclusionStatusEvent(nullptr, &cookie2) != DXGI_ERROR_INVALID_CALL)
1047 return fail("RegisterOcclusionStatusEvent(null event) should return DXGI_ERROR_INVALID_CALL");
1048 if (factory->RegisterOcclusionStatusEvent(ev, nullptr) != DXGI_ERROR_INVALID_CALL)
1049 return fail("RegisterOcclusionStatusEvent(null cookie) should return DXGI_ERROR_INVALID_CALL");
1050 if (FAILED(factory->RegisterOcclusionStatusEvent(ev, &cookie2)) || cookie2 == 0 || cookie2 == cookie1)
1051 return fail("RegisterOcclusionStatusEvent failed or duplicated cookie");
1052 factory->UnregisterOcclusionStatus(cookie1);
1053 factory->UnregisterOcclusionStatus(cookie2);
1054 CloseHandle(ev);
1055 }
1056
844 rtv_heap->Release(); 1057 rtv_heap->Release();
845 sc->Release(); 1058 sc->Release();
846 fence->Release(); 1059 fence->Release();
@@ -860,7 +1073,7 @@ int main() {
860 return 1; 1073 return 1;
861 } 1074 }
862 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off"); 1075 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off");
863 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, GetBuffer+GetDesc, clear+readback, Present, " 1076 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, "
864 "ResizeBuffers; 0 validation errors)\n"); 1077 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n");
865 return 0; 1078 return 0;
866} 1079}
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index c33098d2a..1fcaf6710 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -99,7 +99,7 @@ int main() {
99 write_path(package / "data" / "hello.txt", "package"); 99 write_path(package / "data" / "hello.txt", "package");
100 write_path(package / "data" / "dup.txt", "package"); 100 write_path(package / "data" / "dup.txt", "package");
101 write_path(package / "data" / "bye.txt", "package"); 101 write_path(package / "data" / "bye.txt", "package");
102 std::filesystem::create_directories(package / "data" / "sub"); 102 write_path(package / "data" / "sub" / "nested.txt", "nested");
103 103
104 rt::fs::configure(package, overlay); 104 rt::fs::configure(package, overlay);
105 check(rt::fs::game_dir() == package, "configure() sets the game folder"); 105 check(rt::fs::game_dir() == package, "configure() sets the game folder");
@@ -249,6 +249,15 @@ int main() {
249 SetLastError(0); 249 SetLastError(0);
250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND, 250 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND"); 251 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND");
252
253 // Deleting a nested package file creates parent directories inside .gta6rt-deleted/; those marker parent
254 // directories must not hide the corresponding ancestor directories in the package.
255 check(delete_w(L"GAME:\\data\\sub\\nested.txt") != FALSE, "DeleteFileW accepts a nested package file");
256 const DWORD sub_attrs = attributes_w(L"GAME:\\data\\sub");
257 check(sub_attrs != INVALID_FILE_ATTRIBUTES && (sub_attrs & FILE_ATTRIBUTE_DIRECTORY) != 0,
258 "deleting a nested package file does not hide its parent folder");
259 check(contains(list(first_w, next_w, find_close, L"GAME:\\data\\*"), L"sub"),
260 "the parent folder stays listed after deleting a nested package file");
252 } 261 }
253 262
254 // Nothing leaves the package and the overlay. 263 // Nothing leaves the package and the overlay.
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index 780b10edb..291d3a5d7 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -51,10 +51,27 @@ int main() {
51 HRESULT hr = init(0, 0, 0x02, &options); 51 HRESULT hr = init(0, 0, 0x02, &options);
52 if (hr != S_OK) return fail("InitializeApiImplEx2", static_cast<unsigned long>(hr)); 52 if (hr != S_OK) return fail("InitializeApiImplEx2", static_cast<unsigned long>(hr));
53 53
54 // XThreadingImpl, the first class XCurl.dll references (docs/runtime_imports.md); not provided offline yet. 54 // XThreadingImpl, the first class XCurl.dll references (docs/runtime_imports.md), used as its thunks do: the
55 // class id as both ids, a slot with `this` first, then Release (slot 2). Slot 12 is XTaskQueueCreate, 17
56 // XTaskQueueCloseHandle.
55 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}; 57 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
58 void* obj = nullptr;
59 hr = query(&threading, threading, &obj);
60 if (hr != S_OK || !obj) return fail("QueryApiImpl hands out XThreadingImpl", static_cast<unsigned long>(hr));
61 void* const* vtable = *static_cast<void* const* const*>(obj);
62 using Create = HRESULT(STDMETHODCALLTYPE*)(void*, UINT32, UINT32, void**);
63 using Close = void(STDMETHODCALLTYPE*)(void*, void*);
64 using Release = ULONG(STDMETHODCALLTYPE*)(void*);
65 void* queue = nullptr;
66 hr = reinterpret_cast<Create>(vtable[12])(obj, 0, 0, &queue); // XTaskQueueDispatchMode::Manual twice
67 if (hr != S_OK || !queue) return fail("XThreadingImpl slot 12 (XTaskQueueCreate)", static_cast<unsigned long>(hr));
68 reinterpret_cast<Close>(vtable[17])(obj, queue);
69 reinterpret_cast<Release>(vtable[2])(obj);
70
71 // A class not served yet (XNetworkingImpl) is refused, with the out pointer cleared.
72 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
56 void* out = reinterpret_cast<void*>(1); 73 void* out = reinterpret_cast<void*>(1);
57 hr = query(&threading, threading, &out); 74 hr = query(&networking, networking, &out);
58 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 75 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
59 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr)); 76 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr));
60 hr = uninit(); 77 hr = uninit();
diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp
index 7affaee7a..9a66071ac 100644
--- a/runtime/test/fsr_dispatch_test.cpp
+++ b/runtime/test/fsr_dispatch_test.cpp
@@ -28,7 +28,7 @@
28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the 28// driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the
29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device 29// context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device
30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create 30// is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create
31// (slot 67 is console-only and refused; slot 62's code is not a PC shader). The INFO lines are the measurement; the 31// (slot 67 and 62 codes are not PC shaders). The INFO lines are the measurement; the
32// PASS/FAIL checks only cover what is known to work. 32// PASS/FAIL checks only cover what is known to work.
33#include <windows.h> 33#include <windows.h>
34 34
@@ -958,7 +958,7 @@ int main() {
958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " + 958 note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " +
959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr))); 959 std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast<uint32_t>(g_slot62_hr)));
960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted)); 960 if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted));
961 // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader); on the 961 // On a PC device both pipeline paths fail (neither slot 67's nor 62's code is a PC shader); on the
962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes 962 // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes
963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10, 963 // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10,
964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure. 964 // the same pointer it passes to SetPipelineState): a documented stop, not a test failure.
diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp
index a932cc086..82779ccb1 100644
--- a/runtime/test/glsl/cs_user_data.comp
+++ b/runtime/test/glsl/cs_user_data.comp
@@ -36,8 +36,20 @@ Words at(uvec2 va) {
36void main() { 36void main() {
37 const uint i = gl_GlobalInvocationID.x; 37 const uint i = gl_GlobalInvocationID.x;
38 Words table = at(uvec2(pc.s[4], pc.s[5])); 38 Words table = at(uvec2(pc.s[4], pc.s[5]));
39 Words result = at(uvec2(pc.s[2], pc.s[3]));
40 if (pc.s[1] == 0u) {
41 // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView.
42 const uint num_records = table.w[2];
43 const uint byte_off = pc.s[0] + i * 4u;
44 if (byte_off + 4u <= num_records) {
45 Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu));
46 result.w[i] = cbv.w[byte_off >> 2u];
47 } else {
48 result.w[i] = 0u;
49 }
50 return;
51 }
39 Words constants = at(uvec2(table.w[0], table.w[1])); 52 Words constants = at(uvec2(table.w[0], table.w[1]));
40 Words code = at(pc.code_base); 53 Words code = at(pc.code_base);
41 Words result = at(uvec2(pc.s[2], pc.s[3]));
42 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1]; 54 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1];
43} 55}
diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp
index 4c78835bb..8f35a8ef7 100644
--- a/runtime/test/process_cmdline_test.cpp
+++ b/runtime/test/process_cmdline_test.cpp
@@ -1,10 +1,14 @@
1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the 1// The process shim's command line round-trips: what GetCommandLineW says must parse with CommandLineToArgvW (the
2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what 2// documented rules the CRT's argv parser shares) back to the __wargv the shim hands out, and __wargv must hold what
3// main.cpp passed, whatever the system code page (RT-84). No game files. 3// main.cpp passed, whatever the system code page (RT-84). The WinMain line (lpCmdLine) is the game's too, and the
4// command line and ExitProcess are served under kernelbase.dll and the API-set names as well as kernel32.dll.
5// No game files.
4#include <windows.h> 6#include <windows.h>
5#include <shellapi.h> 7#include <shellapi.h>
6 8
7#include <cstdio> 9#include <cstdio>
10#include <cstring>
11#include <cwchar>
8#include <string> 12#include <string>
9#include <vector> 13#include <vector>
10 14
@@ -54,6 +58,60 @@ void check_non_ascii(const std::wstring& want, const char* what) {
54 ++failures; 58 ++failures;
55 } 59 }
56} 60}
61
62// An executable can import GetCommandLineA/W and ExitProcess from kernel32.dll, kernelbase.dll or the API set its
63// umbrella library names, and the loader matches the DLL name exactly: every name must hand out the same shim.
64void check_import_names() {
65 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processenvironment-l1-1-0.dll"})
66 for (const char* name : {"GetCommandLineA", "GetCommandLineW"}) {
67 void* fn = rt::shims::find(dll, name);
68 if (!fn || fn != rt::shims::find("kernel32.dll", name)) {
69 std::fprintf(stderr, "FAIL %s!%s is not the kernel32.dll shim\n", dll, name);
70 ++failures;
71 }
72 }
73 for (const char* dll : {"kernelbase.dll", "api-ms-win-core-processthreads-l1-1-0.dll"}) {
74 void* fn = rt::shims::find(dll, "ExitProcess");
75 if (!fn || fn != rt::shims::find("kernel32.dll", "ExitProcess")) {
76 std::fprintf(stderr, "FAIL %s!ExitProcess is not the kernel32.dll shim\n", dll);
77 ++failures;
78 }
79 }
80 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll", "ucrtbased.dll"})
81 for (const char* name : {"_get_narrow_winmain_command_line", "_get_wide_winmain_command_line"})
82 if (!rt::shims::find(dll, name)) {
83 std::fprintf(stderr, "FAIL %s!%s is not shimmed\n", dll, name);
84 ++failures;
85 }
86}
87
88// lpCmdLine as the CRT's WinMain startup gets it from _get_wide/_get_narrow_winmain_command_line: the game's command
89// line after the program name and the blanks that follow it (the narrow one in the ANSI code page).
90void check_winmain(const std::wstring& program, const std::vector<std::wstring>& args, const wchar_t* want,
91 const char* what) {
92 rt::process::set_command_line(program, args);
93 using Wide = wchar_t*(__cdecl*)();
94 using Narrow = char*(__cdecl*)();
95 for (const char* dll : {"api-ms-win-crt-runtime-l1-1-0.dll", "ucrtbase.dll"}) {
96 const auto wide_fn = reinterpret_cast<Wide>(rt::shims::find(dll, "_get_wide_winmain_command_line"));
97 const auto narrow_fn = reinterpret_cast<Narrow>(rt::shims::find(dll, "_get_narrow_winmain_command_line"));
98 if (!wide_fn || !narrow_fn) continue; // check_import_names has reported the missing shim
99 const wchar_t* wide = wide_fn();
100 const char* line = narrow_fn();
101 char expected[256] = {};
102 WideCharToMultiByte(CP_ACP, 0, want, -1, expected, sizeof(expected), nullptr, nullptr);
103 if (!wide || std::wcscmp(wide, want) != 0) {
104 std::fwprintf(stderr, L"FAIL %hs (%hs): the wide WinMain line is [%ls], want [%ls]\n", what, dll,
105 wide ? wide : L"(null)", want);
106 ++failures;
107 }
108 if (!line || std::strcmp(line, expected) != 0) {
109 std::fprintf(stderr, "FAIL %s (%s): the narrow WinMain line is [%s], want [%s]\n", what, dll,
110 line ? line : "(null)", expected);
111 ++failures;
112 }
113 }
114}
57} // namespace 115} // namespace
58 116
59int main() { 117int main() {
@@ -67,8 +125,16 @@ int main() {
67 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC. 125 // Greek, Cyrillic and CJK together: no single-byte code page holds all of them, so this covers every PC.
68 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page"); 126 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page");
69 127
128 check_import_names();
129 check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name");
130 check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space");
131 check_winmain(L"game.exe", {}, L"", "no arguments");
132 // A byte above 0x7f in the narrow program name is part of the name, not the end of it.
133 check_winmain(L"caf\u00e9.exe", {L"-x"}, L"-x", "a non-ASCII program name");
134
70 if (failures) return 1; 135 if (failures) return 1;
71 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u)\n", 136 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); "
137 "the WinMain line and the kernelbase/API-set names are the game's\n",
72 GetACP()); 138 GetACP());
73 return 0; 139 return 0;
74} 140}
diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp
new file mode 100644
index 000000000..6e3e6be94
--- /dev/null
+++ b/runtime/test/shader_library_corpus_test.cpp
@@ -0,0 +1,159 @@
1// The runtime's shader lookup (src/shader_library.h) over a translated corpus from the player's own copy.
2//
3// LEONIDA_SHADERS=<work>/shaders/spirv the translator's output (index.json and the .spv modules)
4// LEONIDA_SHADER_DXBC=<work>/shaders/dxbc optional; the carved DXBC containers, default <spirv>/../dxbc
5//
6// For every container the test does what d3d12_vulkan_device.cpp does with a PSO's bytecode: inflate the FSSM program
7// from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL
8// part's program header, not from index.json. Every container has to resolve to its own entry (the one named after
9// the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every index entry has to be reached by
10// a container. Containers with more than one 0x0D payload are counted, and their first payload must not stand in for
11// the last: that is the rule fssm_program follows, so a regression to the first payload fails here.
12//
13// Without LEONIDA_SHADERS it prints SKIP and exits 77 (SKIP_RETURN_CODE). It reads the work folder in place, writes
14// nothing, and prints counts; on a failure it names at most a few shaders, which stay on your machine.
15#include "../src/shader_library.h"
16
17#include <cstdio>
18#include <cstdlib>
19#include <filesystem>
20#include <fstream>
21#include <set>
22#include <string>
23#include <vector>
24
25namespace {
26
27namespace fs = std::filesystem;
28
29std::string env(const char* name) {
30 const char* value = std::getenv(name);
31 return value ? value : "";
32}
33
34std::vector<std::uint8_t> read_file(const fs::path& path) {
35 std::ifstream file(path, std::ios::binary);
36 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
37}
38
39std::uint32_t u32(std::span<const std::uint8_t> data, std::size_t at) {
40 if (at + 4 > data.size()) return 0;
41 std::uint32_t v;
42 std::memcpy(&v, data.data() + at, 4);
43 return v;
44}
45
46// The stage the DXIL program header names (DxilProgramHeader::ProgramVersion, kind in bits 31:16; D3D12's
47// D3D12_SHADER_VERSION_TYPE), in the translator's spelling. Empty for a kind the corpus has no translation for.
48std::string dxil_stage(std::span<const std::uint8_t> container) {
49 const auto dxil = leonida::dxbc_part(container, "DXIL");
50 if (dxil.size() < 4) return {};
51 switch (u32(dxil, 0) >> 16) {
52 case 0: return "ps";
53 case 1: return "vs";
54 case 2: return "gs";
55 case 5: return "cs";
56 case 13: return "ms";
57 default: return {};
58 }
59}
60
61// Every 0x0D (XBCH) payload of the container's XDAT table, in table order, inflated. fssm_program keeps the last.
62std::vector<std::vector<std::uint8_t>> all_programs(std::span<const std::uint8_t> container) {
63 std::vector<std::vector<std::uint8_t>> out;
64 const auto dxil = leonida::dxbc_part(container, "DXIL");
65 std::size_t xdat = 0;
66 while (xdat + 4 <= dxil.size() && std::memcmp(dxil.data() + xdat, "XDAT", 4) != 0) ++xdat;
67 const std::uint32_t count = u32(dxil, xdat + 4);
68 for (std::uint32_t i = 0; i < count; ++i) {
69 const std::size_t entry = xdat + 12 + 12 * std::size_t(i);
70 if (entry + 12 > dxil.size()) break;
71 const std::uint32_t tag = u32(dxil, entry), offset = u32(dxil, entry + 4), size = u32(dxil, entry + 8);
72 if (tag != 0x0d || size < 24 || std::size_t(offset) + size > dxil.size()) continue;
73 const auto blob = dxil.subspan(offset, size);
74 std::vector<std::uint8_t> program;
75 if (std::memcmp(blob.data(), "XBCH", 4) == 0 && leonida::zlib_inflate(blob.subspan(24), program, u32(blob, 16)))
76 out.push_back(std::move(program));
77 }
78 return out;
79}
80
81bool own_entry(const leonida::ShaderEntry& entry, const std::string& stem) {
82 return entry.name == stem || entry.name.rfind(stem + "~", 0) == 0;
83}
84
85} // namespace
86
87int main() {
88 const std::string spirv_dir = env("LEONIDA_SHADERS");
89 if (spirv_dir.empty()) {
90 std::printf("SKIP (no translated corpus: set LEONIDA_SHADERS to <work>/shaders/spirv)\n");
91 return 77;
92 }
93 std::string dxbc_dir = env("LEONIDA_SHADER_DXBC");
94 if (dxbc_dir.empty()) dxbc_dir = (fs::path(spirv_dir) / ".." / "dxbc").lexically_normal().string();
95
96 int failures = 0, named = 0;
97 const auto fail = [&](const std::string& what, const std::string& shader) {
98 ++failures;
99 if (named++ < 8) std::fprintf(stderr, "FAIL %s: %s\n", what.c_str(), shader.c_str());
100 };
101
102 leonida::ShaderLibrary library;
103 std::string error;
104 if (!library.load(spirv_dir, &error)) {
105 std::fprintf(stderr, "FAIL loading %s: %s\n", spirv_dir.c_str(), error.c_str());
106 return 1;
107 }
108 std::error_code ec;
109 if (!fs::is_directory(dxbc_dir, ec)) {
110 std::fprintf(stderr, "FAIL no DXBC folder %s (set LEONIDA_SHADER_DXBC)\n", dxbc_dir.c_str());
111 return 1;
112 }
113
114 std::size_t containers = 0, multi = 0;
115 std::set<std::string> reached;
116 for (const auto& item : fs::directory_iterator(dxbc_dir)) {
117 if (!item.is_regular_file() || item.path().extension() != ".dxbc") continue;
118 ++containers;
119 const std::string stem = item.path().stem().string();
120 const auto bytes = read_file(item.path());
121 const std::string stage = dxil_stage(bytes);
122 if (stage.empty()) {
123 fail("no shader stage in the DXIL program header", stem);
124 continue;
125 }
126 const auto program = leonida::fssm_program(bytes);
127 if (program.size() < 4 || std::memcmp(program.data(), "FSSM", 4) != 0) {
128 fail("no FSSM program", stem);
129 continue;
130 }
131 bool found = false;
132 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(program))) {
133 if (!own_entry(*entry, stem)) continue;
134 found = true;
135 reached.insert(entry->name);
136 if (library.spirv(*entry).empty()) fail("no SPIR-V module for", entry->name);
137 }
138 if (!found) fail("not found under its " + stage + " stage", stem);
139
140 // The 0x0D payloads that differ from the last: none of them may be what the index has for this container.
141 const auto programs = all_programs(bytes);
142 if (programs.empty() || programs.back() != program) fail("fssm_program is not the last 0x0D payload", stem);
143 bool differs = false;
144 for (std::size_t i = 0; i + 1 < programs.size(); ++i) {
145 if (programs[i] == program) continue;
146 differs = true;
147 for (const leonida::ShaderEntry* entry : library.candidates(stage, leonida::sha256_hex(programs[i])))
148 if (own_entry(*entry, stem)) fail("an earlier 0x0D payload is the indexed program", stem);
149 }
150 multi += differs;
151 }
152
153 if (containers == 0) fail("no .dxbc containers in", dxbc_dir);
154 if (reached.size() != library.size())
155 fail(std::to_string(library.size() - reached.size()) + " index entries reached by no container", spirv_dir);
156 std::printf("%zu containers, %zu index entries, %zu reached; %zu containers with more than one program; "
157 "%d failures\n", containers, library.size(), reached.size(), multi, failures);
158 return failures ? 1 : 0;
159}
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index c9796f244..7ec6608d6 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -20,6 +20,8 @@ With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fm
20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. 20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl.
21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and 21With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and
22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). 22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py).
23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR
24inputs, and check.py reports it as SKIP.
23""" 25"""
24import json 26import json
25import os 27import os
@@ -38,6 +40,8 @@ import mc_command # noqa: E402
38 40
39MC = mc_command.mc_command() 41MC = mc_command.mc_command()
40RSRC2, GROUP = 0x8088, (64, 1, 1) 42RSRC2, GROUP = 0x8088, (64, 1, 1)
43# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main).
44NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",)
41sys.path.insert(0, HERE) # this script is also run with python -I 45sys.path.insert(0, HERE) # this script is also run with python -I
42from compute_fixture import compute_header # noqa: E402 46from compute_fixture import compute_header # noqa: E402
43 47
@@ -58,8 +62,8 @@ def asm_mattr(path):
58CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} 62CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1}
59 63
60 64
61def asm_fssm(path): 65def asm_fssm_fields(path):
62 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" 66 """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them."""
63 at, words = None, [] 67 at, words = None, []
64 for ln in Path(path).read_text(encoding="utf-8").splitlines(): 68 for ln in Path(path).read_text(encoding="utf-8").splitlines():
65 s = ln.strip() 69 s = ln.strip()
@@ -71,11 +75,27 @@ def asm_fssm(path):
71 m = re.match(r";\s*fssm-data:\s*(.*)", s) 75 m = re.match(r";\s*fssm-data:\s*(.*)", s)
72 if m: 76 if m:
73 words += [int(w, 0) for w in m.group(1).split()] 77 words += [int(w, 0) for w in m.group(1).split()]
78 return at, words
79
80
81def asm_fssm(path):
82 """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None."""
83 at, words = asm_fssm_fields(path)
74 if at is None or not words or at < 4 or at % 4: 84 if at is None or not words or at < 4 or at % 4:
75 return None 85 return None
76 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words) 86 return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("<I", w) for w in words)
77 87
78 88
89def cs_fssm_extra(path):
90 """A compute shader's "fssm-at"/"fssm-data" words (at 0x148 or later, after compute_header's header), or None.
91 Two compute shaders with the same group size and RSRC2 would otherwise share one FSSM hash, which is what the
92 layer finds a PSO's shader by."""
93 at, words = asm_fssm_fields(path)
94 if at is None or not words or at < 0x148 or at % 4:
95 return None
96 return at, b"".join(struct.pack("<I", w) for w in words)
97
98
79def shader_source(name): 99def shader_source(name):
80 return "vs_clip" if name in CLIP_CASES else name 100 return "vs_clip" if name in CLIP_CASES else name
81 101
@@ -108,12 +128,16 @@ def translate_tests(work, names):
108 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") 128 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}")
109 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. 129 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first.
110 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 130 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
111 (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8") 131 (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8", newline="\n")
112 program = None if n.startswith("cs_") else asm_fssm(asm_path) 132 program = None if n.startswith("cs_") else asm_fssm(asm_path)
113 if program: # where the translator looks for a program to hash, as in the game's work folder 133 if program: # where the translator looks for a program to hash, as in the game's work folder
114 (fssm / (n + ".fssm")).write_bytes(program) 134 (fssm / (n + ".fssm")).write_bytes(program)
115 if n.startswith("cs_"): 135 if n.startswith("cs_"):
116 (fssm / (n + ".fssm")).write_bytes(compute_header(asm_path)) 136 program = bytes(compute_header(asm_path))
137 extra = cs_fssm_extra(asm_path)
138 if extra:
139 program += bytes(extra[0] - len(program)) + extra[1]
140 (fssm / (n + ".fssm")).write_bytes(program)
117 elif n in CLIP_CASES and n != "vs_clip_undeclared": 141 elif n in CLIP_CASES and n != "vs_clip_undeclared":
118 (work / (n + ".dxbc")).write_bytes(clip_container()) 142 (work / (n + ".dxbc")).write_bytes(clip_container())
119 else: 143 else:
@@ -149,6 +173,14 @@ def main():
149 if skipped: 173 if skipped:
150 print("not built (need a DXBC container with signatures):", ", ".join(skipped)) 174 print("not built (need a DXBC container with signatures):", ", ".join(skipped))
151 names = [n for n in names if n not in skipped] 175 names = [n for n in names if n not in skipped]
176 # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there,
177 # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch.
178 if os.environ.get("LEONIDA_BARY_FALLBACK") == "1" or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1":
179 per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS]
180 if per_vertex:
181 print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):",
182 ", ".join(per_vertex))
183 names = [n for n in names if n not in per_vertex]
152 if not names: 184 if not names:
153 return 0 185 return 0
154 out.mkdir(parents=True, exist_ok=True) 186 out.mkdir(parents=True, exist_ok=True)
@@ -168,13 +200,14 @@ def main():
168 published_index = spirv / index.name 200 published_index = spirv / index.name
169 combined = json.loads(published_index.read_text(encoding="utf-8")) if published_index.exists() else {} 201 combined = json.loads(published_index.read_text(encoding="utf-8")) if published_index.exists() else {}
170 combined.update(validated) 202 combined.update(validated)
171 index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8") 203 index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8", newline="\n")
172 for n in validated: 204 for n in validated:
173 for suffix in (".spv", ".spvasm"): 205 for suffix in (".spv", ".spvasm"):
174 artifact = built / (n + suffix) 206 artifact = built / (n + suffix)
175 artifact.replace(spirv / artifact.name) 207 artifact.replace(spirv / artifact.name)
176 sidecar = work / "fssm" / (n + ".fssm") 208 sidecar = work / "fssm" / (n + ".fssm")
177 if not n.startswith("cs_") and sidecar.is_file(): 209 published = not n.startswith("cs_") or cs_fssm_extra(os.path.join(HERE, n + ".asm"))
210 if published and sidecar.is_file():
178 (out / "fssm").mkdir(exist_ok=True) 211 (out / "fssm").mkdir(exist_ok=True)
179 sidecar.replace(out / "fssm" / sidecar.name) 212 sidecar.replace(out / "fssm" / sidecar.name)
180 index.replace(published_index) 213 index.replace(published_index)
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 2f2853175..3985f85e4 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -81,14 +81,14 @@ CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed001
81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", 81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute",
82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", 82 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32",
83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos") 84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst")
85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may 87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may
88# otherwise pick a narrower size and return different words (#774). 88# otherwise pick a narrower size and return different words (#774).
89WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} 89WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"}
90WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", 90WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const",
91 "cs_w32_mask_imm") 91 "cs_w32_mask_imm", "cs_lds_b64_cmpst")
92CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), 92CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
93 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), 93 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]),
94 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), 94 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]),
@@ -116,6 +116,9 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
116 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]), 116 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]),
117 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept 117 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept
118 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]), 118 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]),
119 # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header)
120 ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004,
121 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]),
119 # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31) 122 # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31)
120 ("cs_exec_const", [16, 8, 2, 16, 0, 16]), 123 ("cs_exec_const", [16, 8, 2, 16, 0, 16]),
121 # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L, 124 # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L,
@@ -188,6 +191,16 @@ FMT_XY_XYZ_WORDS = [
188 0x3F800000, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0x0000FFFF, 0xA5A50294, 0xA5A50298, 0xA5A5029C, 191 0x3F800000, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0x0000FFFF, 0xA5A50294, 0xA5A50298, 0xA5A5029C,
189 0x0003FF01, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0xA5A502B0, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC, 192 0x0003FF01, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0xA5A502B0, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC,
190 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC] 193 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC]
194# cs_tbuffer_store.asm: 13 tbuffer_store_format_* regions read back, as a Radeon 680M (gfx1035) gives them
195# natively. Layout and rules in the .asm header.
196TBUFFER_STORE_WORDS = [
197 0x3F800000, 0x40000000, 0x40400000, 0x40800000, 0x40003C00, 0x00000000, 0xA5A50218, 0xA5A5021C,
198 0x00030201, 0xA5A50224, 0xA5A50228, 0xA5A5022C, 0xA5A5FF30, 0xA5A50234, 0xA5A50238, 0xA5A5023C,
199 0x40000240, 0xA5A50244, 0xA5A50248, 0xA5A5024C, 0xD00003FF, 0xA5A50254, 0xA5A50258, 0xA5A5025C,
200 0x3F800000, 0x40000000, 0xA5A50268, 0xA5A5026C, 0x40003C00, 0xA5A50274, 0xA5A50278, 0xA5A5027C,
201 0xFF0080FF, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0xA5A50290, 0xA5A50294, 0xA5A50298, 0xA5A5029C,
202 0xA5A502FF, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0x3F800000, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC,
203 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC]
191# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds 204# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds
192# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement. 205# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement.
193GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 206GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4,
@@ -257,6 +270,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
257 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), 270 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000),
258 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000), 271 "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000),
259 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 272 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
273 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
274 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
260 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), 275 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000),
261 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), 276 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000),
262 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) 277 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers)
@@ -316,7 +331,8 @@ CLIP_TESTS = ("vs_clip", "vs_clip_param4", "vs_clip_undeclared")
316# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from 331# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from
317# the standalone run. Keep every pixel fixture in this tuple. 332# the standalone run. Keep every pixel fixture in this tuple.
318PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit", 333PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit",
319 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed")) 334 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed",
335 "ps_mandelbrot"))
320# Pixel fixtures drawn with another vertex shader than vs_ids. 336# Pixel fixtures drawn with another vertex shader than vs_ids.
321PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack", 337PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack",
322 "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"} 338 "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"}
@@ -465,6 +481,12 @@ def fmt_xy_xyz_test(tools, spirv, env=None):
465 return dump_test(tools, spirv, "cs_fmt_xy_xyz", FMT_XY_XYZ_WORDS + [0xEEEEEEEE] * 44, 192, env) 481 return dump_test(tools, spirv, "cs_fmt_xy_xyz", FMT_XY_XYZ_WORDS + [0xEEEEEEEE] * 44, 192, env)
466 482
467 483
484def tbuffer_store_test(tools, spirv, env=None):
485 """The 52 region words tbuffer_store_format_* leaves and the untouched words after them, up to the regions at
486 0x200. The heap needs 0x2d0 bytes, so it is 192 words."""
487 return dump_test(tools, spirv, "cs_tbuffer_store", TBUFFER_STORE_WORDS + [0xEEEEEEEE] * 76, 192, env)
488
489
468class Skip(str): 490class Skip(str):
469 """A result that is neither a pass nor a failure: the device can't run the test.""" 491 """A result that is neither a pass nor a failure: the device can't run the test."""
470 492
@@ -659,6 +681,8 @@ def cvt_f32_sat_test(tools, spirv):
659 for bits, unsigned, signed in CVT_F32_SAT_CASES: 681 for bits, unsigned, signed in CVT_F32_SAT_CASES:
660 problem = compute_test(tools, spirv, "cs_cvt_f32_sat", "1", "dump", expected_words=[unsigned, signed], 682 problem = compute_test(tools, spirv, "cs_cvt_f32_sat", "1", "dump", expected_words=[unsigned, signed],
661 env={"VKC_SGPRS": f"{bits:#010x}"}) 683 env={"VKC_SGPRS": f"{bits:#010x}"})
684 if problem is None or isinstance(problem, Skip):
685 return problem # the device can't run it as recorded (wave size not pinnable): the same for every input
662 if problem: 686 if problem:
663 wrong.append(f"{bits:#010x}: {problem}") 687 wrong.append(f"{bits:#010x}: {problem}")
664 return f"{len(wrong)} of {len(CVT_F32_SAT_CASES)} inputs wrong, first {wrong[0]}" if wrong else "" 688 return f"{len(wrong)} of {len(CVT_F32_SAT_CASES)} inputs wrong, first {wrong[0]}" if wrong else ""
@@ -707,9 +731,10 @@ def subgroup_size(spirv, name):
707 return None 731 return None
708 732
709 733
710def bindless_test(tools, spirv): 734def bindless_test(tools, spirv, pixel="ps_tex"):
711 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).""" 735 """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).
712 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_tex")] 736 ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel."""
737 shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)]
713 for path in shaders: 738 for path in shaders:
714 if not os.path.isfile(path): 739 if not os.path.isfile(path):
715 return f"missing {os.path.basename(path)}" 740 return f"missing {os.path.basename(path)}"
@@ -717,6 +742,9 @@ def bindless_test(tools, spirv):
717 if code == UNSUPPORTED: 742 if code == UNSUPPORTED:
718 m = re.search(r"unsupported: .*", out) 743 m = re.search(r"unsupported: .*", out)
719 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") 744 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
745 if pixel == "ps_imgatomic":
746 m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out)
747 return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3)
720 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) 748 m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out)
721 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) 749 return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3)
722 750
@@ -1098,6 +1126,46 @@ def wide_pixel_skip(name, out):
1098 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})") 1126 return Skip(f"SKIP (this device cannot require a {want}-wide fragment subgroup{seen})")
1099 1127
1100 1128
1129def f32(x):
1130 """x rounded to the nearest float32. One double add or multiply of two float32 values, then this, is the exact
1131 IEEE float32 result, so a model built from it matches the GPU bit for bit."""
1132 return struct.unpack("<f", struct.pack("<f", x))[0]
1133
1134
1135def mandelbrot_counts(w):
1136 """ps_mandelbrot.asm's iteration counts over a w x w frame, in the shader's order of float32 operations."""
1137 counts = []
1138 for y in range(w):
1139 cy = f32(f32(3.0 * f32((y + 0.5) / w)) - 1.5)
1140 for x in range(w):
1141 cx = f32(f32(3.0 * f32((x + 0.5) / w)) - 2.25)
1142 zx = zy = 0.0
1143 n = 0
1144 while n < 64:
1145 zx2, zy2 = f32(zx * zx), f32(zy * zy)
1146 if not 4.0 >= f32(zx2 + zy2):
1147 break
1148 xy = f32(zx * zy)
1149 zx, zy = f32(f32(zx2 - zy2) + cx), f32(f32(xy + xy) + cy)
1150 n += 1
1151 counts.append(n)
1152 return counts
1153
1154
1155def mandelbrot_problem(px):
1156 """ps_mandelbrot: channel 3 is the lane's iteration count. A lane that leaves EXEC too early or late, or a loop
1157 that ends on the wrong branch, changes counts; the colour channels are only for looking at the frame."""
1158 w = int(len(px) ** 0.5)
1159 if w * w != len(px):
1160 return f"{len(px)} pixels is not a square frame"
1161 want = mandelbrot_counts(w)
1162 wrong = [(i, p[3], e) for i, (p, e) in enumerate(zip(px, want)) if p[3] != e]
1163 if not wrong:
1164 return ""
1165 i, got, e = wrong[0]
1166 return f"{len(wrong)} of {len(px)} iteration counts differ, e.g. pixel ({i % w}, {i // w}) {got} instead of {e}"
1167
1168
1101def pixel_test(tools, spirv, name): 1169def pixel_test(tools, spirv, name):
1102 path = os.path.join(spirv, name + ".spv") 1170 path = os.path.join(spirv, name + ".spv")
1103 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): 1171 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES):
@@ -1164,6 +1232,8 @@ def pixel_test(tools, spirv, name):
1164 c = collections.Counter((a, b) for a, b, _, _ in px) 1232 c = collections.Counter((a, b) for a, b, _, _ in px)
1165 fine = c[(8, 1)] and c[(8, 0)] and c[(7, 0)] and set(c) <= {(8, 1), (8, 0), (7, 0)} 1233 fine = c[(8, 1)] and c[(8, 0)] and c[(7, 0)] and set(c) <= {(8, 1), (8, 0), (7, 0)}
1166 return "" if fine else f"(s5, bit) counts {dict(c)}" 1234 return "" if fine else f"(s5, bit) counts {dict(c)}"
1235 if name == "ps_mandelbrot":
1236 return mandelbrot_problem(px)
1167 return "no check written for this shader" 1237 return "no check written for this shader"
1168 1238
1169 1239
@@ -1217,6 +1287,7 @@ def main():
1217 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) 1287 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv)))
1218 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv))) 1288 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv)))
1219 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1289 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1290 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv)))
1220 for name, groups, want in GLOBAL_OFFSET: 1291 for name, groups, want in GLOBAL_OFFSET:
1221 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) 1292 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want)))
1222 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump", 1293 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump",
@@ -1254,6 +1325,7 @@ def main():
1254 results.append((name, texture_constant_test(tools, spirv, name))) 1325 results.append((name, texture_constant_test(tools, spirv, name)))
1255 results.append(("ps_tex", bindless_test(tools, spirv))) 1326 results.append(("ps_tex", bindless_test(tools, spirv)))
1256 results.append(("ps_ssharp", sampler_test(tools, spirv))) 1327 results.append(("ps_ssharp", sampler_test(tools, spirv)))
1328 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic")))
1257 for name in MIP_TEST_PASSES: 1329 for name in MIP_TEST_PASSES:
1258 results.append((name, texture_mip_test(tools, spirv, name))) 1330 results.append((name, texture_mip_test(tools, spirv, name)))
1259 for name in GRADIENT_TESTS: 1331 for name in GRADIENT_TESTS:
diff --git a/runtime/test/shaders/cs_buf_counter.asm b/runtime/test/shaders/cs_buf_counter.asm
new file mode 100644
index 000000000..9bbe84bea
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_counter.asm
@@ -0,0 +1,40 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x4e554f43 0x3d524554
5; UAV counters (D3D12 CreateUnorderedAccessView with pCounterResource): AppendStructuredBuffer and
6; ConsumeStructuredBuffer as hand-written RDNA2, the way docs/d3d12_vulkan.md section 3.4 describes the contract:
7; the counter is a second, raw 4-byte V# in the upper 16 bytes of the view's descriptor slot, and append and consume
8; are buffer atomics on it. Run: d3d12_buffer_uav_test (a compute PSO found by the SHA-256 of its synthetic FSSM header).
9; The branch skips the 10 dwords of the append path (checked with llvm-mc -show-encoding).
10; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs, TGID_X in s6:
11; s0 = mode: 0 append, 1 consume s[4:5] = console VA of the table's first slot (32 bytes a slot)
12; slot 0 (+0x00): V#, structured buffer, stride 8, 256 records; the counter V# in +0x10 (raw, 4 bytes)
13; slot 1 (+0x20): V#, raw buffer, 128 records of 8 bytes (written by consume)
14; g = 64 * group + lane
15; append: i = counter++ (buffer_atomic_add, glc returns the old value); record i = { g, g * 3 + 1 }
16; consume: i = --counter (the old value of buffer_atomic_sub, minus one); out[g] = record i
17s_load_dwordx8 s[8:15], s[4:5], 0x0
18s_load_dwordx4 s[16:19], s[4:5], 0x20
19s_lshl_b32 s7, s6, 6
20s_waitcnt lgkmcnt(0)
21v_add_nc_u32_e32 v1, s7, v0
22v_mov_b32_e32 v2, 1
23s_cmp_eq_u32 s0, 0
24s_cbranch_scc0 10
25buffer_atomic_add v2, off, s[12:15], 0 glc
26s_waitcnt vmcnt(0)
27v_mul_lo_u32 v6, v1, 3
28v_add_nc_u32_e32 v6, 1, v6
29v_mov_b32_e32 v5, v1
30buffer_store_dwordx2 v[5:6], v2, s[8:11], 0 idxen
31s_endpgm
32; consume:
33buffer_atomic_sub v2, off, s[12:15], 0 glc
34s_waitcnt vmcnt(0)
35v_add_nc_u32_e32 v2, -1, v2
36buffer_load_dwordx2 v[5:6], v2, s[8:11], 0 idxen
37s_waitcnt vmcnt(0)
38v_lshlrev_b32_e32 v7, 3, v1
39buffer_store_dwordx2 v[5:6], v7, s[16:19], 0 offen
40s_endpgm
diff --git a/runtime/test/shaders/cs_buf_typed.asm b/runtime/test/shaders/cs_buf_typed.asm
new file mode 100644
index 000000000..b101343e8
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_typed.asm
@@ -0,0 +1,63 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x44505954 0x3d424655
5; Typed buffer UAVs (D3D12 CreateUnorderedAccessView with a Format on a BUFFER view): hand-written RDNA2 the way a
6; translated `RWBuffer<T>` shader reads and writes them. Run: d3d12_buffer_uav_test (a compute PSO found by the
7; SHA-256 of its synthetic FSSM header, as for the other cs_ shaders).
8; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs. RSRC2 0x808c =
9; six user SGPRs and TGID_X, so the group index is s6:
10; s0 = seed s1 = multiplier s[4:5] = console VA of the table's first slot (a slot is 32 bytes, a V# in its first 16)
11; slot 0 (+0x00): V#, typed R32_UINT, 240 elements of a 256-element buffer (written, then atomically added to)
12; slot 1 (+0x20): V#, typed R16G16B16A16_FLOAT, 256 elements (written)
13; slot 2 (+0x40): V#, typed R8G8B8A8_UNORM, 256 elements from element 16 of the buffer (written)
14; slot 3 (+0x60): V#, typed R32G32B32A32_UINT, 256 elements (written)
15; slot 4 (+0x80): V#, typed R32_FLOAT, 250 elements of a 256-element buffer (read)
16; slot 5 (+0xa0): V#, typed R32_SINT, 256 elements (written)
17; g = 64 * group + lane, 0..255 (an index past a view's NUM_RECORDS is out of range: a load gives 0, a store or an
18; atomic touches nothing):
19; slot 0: element g = g * mul + seed, then += g
20; slot 1: element g = { f16(g), f16(g + 0.5), f16(-1 - g), f16(0.25) }
21; slot 2: element g = unorm8 { (g & 255) / 255, (255 - (g & 255)) / 255, 0, 1 }
22; slot 3: element g = { g, g ^ 0xffff, g * 7, 0xa5 }
23; slot 5: element g = (int)(2 * input[g]), input[g] = g - 100.5
24s_load_dwordx4 s[8:11], s[4:5], 0x0
25s_load_dwordx4 s[12:15], s[4:5], 0x20
26s_load_dwordx4 s[16:19], s[4:5], 0x40
27s_load_dwordx4 s[20:23], s[4:5], 0x60
28s_load_dwordx4 s[24:27], s[4:5], 0x80
29s_load_dwordx4 s[28:31], s[4:5], 0xa0
30s_lshl_b32 s7, s6, 6
31s_waitcnt lgkmcnt(0)
32v_add_nc_u32_e32 v1, s7, v0
33v_mul_lo_u32 v2, v1, s1
34v_add_nc_u32_e32 v2, s0, v2
35buffer_store_format_x v2, v1, s[8:11], 0 idxen
36v_mov_b32_e32 v3, v1
37buffer_atomic_add v3, v1, s[8:11], 0 idxen
38v_cvt_f32_u32_e32 v4, v1
39v_add_f32_e32 v5, 0.5, v4
40v_sub_f32_e32 v6, -1.0, v4
41v_mov_b32_e32 v7, 0x3e800000
42buffer_store_format_xyzw v[4:7], v1, s[12:15], 0 idxen
43v_and_b32_e32 v8, 255, v1
44v_cvt_f32_ubyte0_e32 v9, v8
45v_mov_b32_e32 v10, 0x3b808081
46v_mul_f32_e32 v11, v9, v10
47v_sub_nc_u32_e32 v12, 255, v8
48v_cvt_f32_ubyte0_e32 v12, v12
49v_mul_f32_e32 v12, v12, v10
50v_mov_b32_e32 v13, 0
51v_mov_b32_e32 v14, 1.0
52buffer_store_format_xyzw v[11:14], v1, s[16:19], 0 idxen
53v_mov_b32_e32 v15, v1
54v_xor_b32_e32 v16, 0xffff, v1
55v_mul_lo_u32 v17, v1, 7
56v_mov_b32_e32 v18, 0xa5
57buffer_store_format_xyzw v[15:18], v1, s[20:23], 0 idxen
58buffer_load_format_x v19, v1, s[24:27], 0 idxen
59s_waitcnt vmcnt(0)
60v_add_f32_e32 v19, v19, v19
61v_cvt_i32_f32_e32 v19, v19
62buffer_store_format_x v19, v1, s[28:31], 0 idxen
63s_endpgm
diff --git a/runtime/test/shaders/cs_lds_b64_cmpst.asm b/runtime/test/shaders/cs_lds_b64_cmpst.asm
new file mode 100644
index 000000000..0998d8576
--- /dev/null
+++ b/runtime/test/shaders/cs_lds_b64_cmpst.asm
@@ -0,0 +1,132 @@
1; GPU test for the two LDS families that docs/design.md lists as not GPU-verified:
2; ds_cmpst_b32 (the non-returning compare-and-store) and the b64 2-address forms
3; (ds_read2_b64 / ds_write2_b64 and their st64 variants).
4;
5; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words are
6; derived from the RDNA2 ISA's 2-address and DS_CMPST_B32 pseudocode:
7;
8; out[0..3] ds_write2_b64 then ds_read2_b64 at base 0x20, offset0:1 offset1:3,
9; writes A at 0x28 and B at 0x38 (unit 8), reads the same two elements:
10; A.lo A.hi B.lo B.hi
11; out[4] ds_read2st64_b64 at base 0x100, offset0:0 offset1:1 (unit 512):
12; XOR of the four dwords seeded at 0x100 and 0x300
13; out[5] ds_write2st64_b64 at base 0x100, offset0:0 offset1:1, then plain
14; ds_read_b32 at 0x100/0x104/0x300/0x304: XOR of the four dwords
15; out[6] ds_read2_b64 v[2:5], v2 at base 0x200 (vdst overlaps vaddr): the
16; second element's low dword, 0xBBBB000B, read before v2 is overwritten
17; out[7] ds_cmpst_b32 hit (mem 0x13572468 -> 0x2468ABCD) XOR the miss case's
18; unchanged word (0x11111111): 0x3579BADC
19;
20; Run: vk_compute_test cs_lds_b64_cmpst.spv 1 dump
21; -> out[0..7] = 0x11110001 0x22220002 0x33330003 0x44440004
22; 0xCCCC000C 0x44440004 0xBBBB000B 0x3579BADC
23; rsrc2: 0x40088
24; group: 32,1,1
25; mattr: +wavefrontsize32,-wavefrontsize64
26v_cmpx_eq_u32_e32 0, v0
27
28; --- ds_write2_b64 / ds_read2_b64, unit 8 bytes ---
29v_mov_b32_e32 v2, 0x20
30v_mov_b32_e32 v4, 0x11110001
31v_mov_b32_e32 v5, 0x22220002
32v_mov_b32_e32 v6, 0x33330003
33v_mov_b32_e32 v7, 0x44440004
34ds_write2_b64 v2, v[4:5], v[6:7] offset0:1 offset1:3
35s_waitcnt lgkmcnt(0)
36ds_read2_b64 v[10:13], v2 offset0:1 offset1:3
37s_waitcnt lgkmcnt(0)
38v_mov_b32_e32 v21, 0
39buffer_store_dword v10, v21, s[0:3], 0 offen
40v_mov_b32_e32 v21, 4
41buffer_store_dword v11, v21, s[0:3], 0 offen
42v_mov_b32_e32 v21, 8
43buffer_store_dword v12, v21, s[0:3], 0 offen
44v_mov_b32_e32 v21, 12
45buffer_store_dword v13, v21, s[0:3], 0 offen
46
47; --- ds_read2st64_b64, unit 512 bytes: seed 0x100 and 0x300 ---
48v_mov_b32_e32 v1, 0x100
49v_mov_b32_e32 v3, 0x55550005
50ds_write_b32 v1, v3
51v_mov_b32_e32 v1, 0x104
52v_mov_b32_e32 v3, 0x66660006
53ds_write_b32 v1, v3
54v_mov_b32_e32 v1, 0x300
55v_mov_b32_e32 v3, 0x77770007
56ds_write_b32 v1, v3
57v_mov_b32_e32 v1, 0x304
58v_mov_b32_e32 v3, 0x88880008
59ds_write_b32 v1, v3
60s_waitcnt lgkmcnt(0)
61v_mov_b32_e32 v2, 0x100
62ds_read2st64_b64 v[10:13], v2 offset0:0 offset1:1
63s_waitcnt lgkmcnt(0)
64v_xor_b32_e32 v14, v10, v11
65v_xor_b32_e32 v14, v14, v12
66v_xor_b32_e32 v14, v14, v13
67v_mov_b32_e32 v21, 16
68buffer_store_dword v14, v21, s[0:3], 0 offen
69
70; --- ds_write2st64_b64, unit 512 bytes: A at 0x100, B at 0x300 ---
71v_mov_b32_e32 v2, 0x100
72ds_write2st64_b64 v2, v[4:5], v[6:7] offset0:0 offset1:1
73s_waitcnt lgkmcnt(0)
74v_mov_b32_e32 v1, 0x100
75ds_read_b32 v10, v1
76v_mov_b32_e32 v1, 0x104
77ds_read_b32 v11, v1
78v_mov_b32_e32 v1, 0x300
79ds_read_b32 v12, v1
80v_mov_b32_e32 v1, 0x304
81ds_read_b32 v13, v1
82s_waitcnt lgkmcnt(0)
83v_xor_b32_e32 v15, v10, v11
84v_xor_b32_e32 v15, v15, v12
85v_xor_b32_e32 v15, v15, v13
86v_mov_b32_e32 v21, 20
87buffer_store_dword v15, v21, s[0:3], 0 offen
88
89; --- ds_read2_b64 with vdst overlapping vaddr: v[2:5] <- base v2 ---
90v_mov_b32_e32 v1, 0x200
91v_mov_b32_e32 v3, 0x99990009
92ds_write_b32 v1, v3
93v_mov_b32_e32 v1, 0x204
94v_mov_b32_e32 v3, 0xAAAA000A
95ds_write_b32 v1, v3
96v_mov_b32_e32 v1, 0x208
97v_mov_b32_e32 v3, 0xBBBB000B
98ds_write_b32 v1, v3
99v_mov_b32_e32 v1, 0x20C
100v_mov_b32_e32 v3, 0xCCCC000C
101ds_write_b32 v1, v3
102s_waitcnt lgkmcnt(0)
103v_mov_b32_e32 v2, 0x200
104ds_read2_b64 v[2:5], v2 offset0:0 offset1:1
105s_waitcnt lgkmcnt(0)
106v_mov_b32_e32 v21, 24
107buffer_store_dword v4, v21, s[0:3], 0 offen
108
109; --- ds_cmpst_b32: hit at 0x400, miss at 0x404 ---
110v_mov_b32_e32 v1, 0x400
111v_mov_b32_e32 v3, 0x13572468
112ds_write_b32 v1, v3
113v_mov_b32_e32 v1, 0x404
114v_mov_b32_e32 v3, 0x11111111
115ds_write_b32 v1, v3
116s_waitcnt lgkmcnt(0)
117v_mov_b32_e32 v1, 0x400
118v_mov_b32_e32 v3, 0x13572468
119v_mov_b32_e32 v4, 0x2468ABCD
120ds_cmpst_b32 v1, v3, v4
121s_waitcnt lgkmcnt(0)
122ds_read_b32 v10, v1
123v_mov_b32_e32 v1, 0x404
124v_mov_b32_e32 v3, 0
125v_mov_b32_e32 v4, 0xFFFFFFFF
126ds_cmpst_b32 v1, v3, v4
127s_waitcnt lgkmcnt(0)
128ds_read_b32 v11, v1
129v_xor_b32_e32 v16, v10, v11
130v_mov_b32_e32 v21, 28
131buffer_store_dword v16, v21, s[0:3], 0 offen
132s_endpgm
diff --git a/runtime/test/shaders/cs_m4_fill.asm b/runtime/test/shaders/cs_m4_fill.asm
new file mode 100644
index 000000000..1af46dac9
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_fill.asm
@@ -0,0 +1,51 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x4c4c4946 0x3d344d5f
5; M4 compute shader 1: fills a structured UAV buffer and a typed UAV image from a raw input buffer, and writes the
6; arguments of the next (indirect) dispatch. Run: d3d12_m4_compute_test (a compute PSO found by the SHA-256 of its
7; synthetic FSSM header, as for the other cs_ shaders).
8; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of five UAVs. RSRC2 0x808c =
9; six user SGPRs and TGID_X, so the group index is s6:
10; s0 = seed s1 = multiplier s2 = group count of the indirect dispatch s3 = unused
11; s[4:5] = console VA of the table's first slot. A slot is 32 bytes: a V# in its first 16 bytes or a T# in all 32.
12; slot 0 (+0x00): V#, structured buffer, stride 16, 256 records (written)
13; slot 1 (+0x20): V#, raw buffer, the arguments of the indirect dispatch (written)
14; slot 2 (+0x40): T#, 16x16 R32_UINT image (written)
15; slot 3 (+0x60): V#, raw buffer, 256 input words (read)
16; slot 4 (+0x80): V#, raw buffer, the second shader's output (not used here)
17; g = 64 * group + lane, 0..255: in = input[g]
18; record g = { in + seed, g * mul, in ^ (g << 8), rotr(in, 13) }
19; image(x = g & 15, y = g >> 4) = in * 3 + x * 0x10001 + y
20; g == 0 also writes the arguments { s2, 1, 1, 0xc0de0001 }
21s_load_dwordx4 s[8:11], s[4:5], 0x0
22s_load_dwordx4 s[12:15], s[4:5], 0x20
23s_load_dwordx8 s[16:23], s[4:5], 0x40
24s_load_dwordx4 s[24:27], s[4:5], 0x60
25s_lshl_b32 s7, s6, 6
26s_waitcnt lgkmcnt(0)
27v_add_nc_u32_e32 v1, s7, v0
28v_lshlrev_b32_e32 v2, 2, v1
29buffer_load_dword v3, v2, s[24:27], 0 offen
30s_waitcnt vmcnt(0)
31v_add_nc_u32_e32 v4, s0, v3
32v_mul_lo_u32 v5, v1, s1
33v_lshlrev_b32_e32 v6, 8, v1
34v_xor_b32_e32 v6, v3, v6
35v_alignbit_b32 v7, v3, v3, 13
36buffer_store_dwordx4 v[4:7], v1, s[8:11], 0 idxen
37v_and_b32_e32 v8, 15, v1
38v_lshrrev_b32_e32 v9, 4, v1
39v_mul_u32_u24_e32 v10, 0x10001, v8
40v_mul_lo_u32 v11, v3, 3
41v_add_nc_u32_e32 v10, v10, v11
42v_add_nc_u32_e32 v10, v10, v9
43image_store v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
44v_cmpx_eq_u32_e32 0, v1
45v_mov_b32_e32 v12, 0
46v_mov_b32_e32 v13, s2
47v_mov_b32_e32 v14, 1
48v_mov_b32_e32 v15, 1
49v_mov_b32_e32 v16, 0xc0de0001
50buffer_store_dwordx4 v[13:16], v12, s[12:15], 0 offen
51s_endpgm
diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm
new file mode 100644
index 000000000..8a23596bf
--- /dev/null
+++ b/runtime/test/shaders/cs_m4_indirect.asm
@@ -0,0 +1,28 @@
1; group: 64,1,1
2; rsrc2: 0x808c
3; fssm-at: 0x150
4; fssm-data: 0x44444e49 0x3d344d5f
5; M4 compute shader 2: runs under ExecuteIndirect with the arguments cs_m4_fill wrote ({ groups, 1, 1 }), reads the
6; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run:
7; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there):
8; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written)
9; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 }
10; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g
11s_load_dwordx4 s[8:11], s[4:5], 0x0
12s_load_dwordx8 s[16:23], s[4:5], 0x40
13s_load_dwordx4 s[12:15], s[4:5], 0x80
14s_lshl_b32 s7, s6, 6
15s_waitcnt lgkmcnt(0)
16v_add_nc_u32_e32 v1, s7, v0
17buffer_load_dwordx4 v[4:7], v1, s[8:11], 0 idxen
18v_and_b32_e32 v8, 15, v1
19v_lshrrev_b32_e32 v9, 4, v1
20image_load v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
21s_waitcnt vmcnt(0)
22v_add_nc_u32_e32 v11, v4, v10
23v_xor_b32_e32 v11, v11, v7
24v_xor_b32_e32 v12, v6, v10
25v_add_nc_u32_e32 v12, v12, v5
26v_lshlrev_b32_e32 v13, 3, v1
27buffer_store_dwordx2 v[11:12], v13, s[12:15], 0 offen
28s_endpgm
diff --git a/runtime/test/shaders/cs_tbuffer_store.asm b/runtime/test/shaders/cs_tbuffer_store.asm
new file mode 100644
index 000000000..a6e0e78e5
--- /dev/null
+++ b/runtime/test/shaders/cs_tbuffer_store.asm
@@ -0,0 +1,275 @@
1; tbuffer_store_format_* and its d16 forms. Every expected word was measured by running this body natively on a Radeon
2; 680M (gfx1035, RDNA2) through tools/hw_oracle's kernel wrapper, with s[0:3] set to the V# vk_compute_test passes;
3; wave32 and wave64 gave the same 52 words. One thread runs.
4; - The instruction's format replaces the V#'s, for the encoding, the element size and the bounds check alike. No
5; format modifier means GFX10's default, BUF_FMT_8_UNORM: one byte, its neighbours kept.
6; - A store writes its format's whole element: components the format has but the instruction doesn't give are 0
7; (xy into 16_16_16_16 leaves z = w = 0); components the format doesn't have are dropped (xyzw into 32_32 writes
8; x, y; into 32 only x).
9; - d16 data is two 16-bit values per VGPR, low half first.
10; - Bounds (OOB_SELECT 3): the instruction's element must end inside num_records. With NR 0x298, an xy store of a
11; 16-byte element at 0x290 writes nothing, though a V# that says 32_FLOAT has a 4-byte element; with NR 0x2a1, an
12; 8_UNORM byte at 0x2a0 is written, though the V#'s 16-byte element would not fit.
13; - A V# whose FORMAT is 0 (INVALID) disables the store, though the instruction brings its own format.
14; Store regions 0x200..0x2cf start as 0xa5a50000 | address; out[0..51] are the 13 regions read back, in source order.
15; Run: VKC_OUT_WORDS=192 VKC_DUMP=<file> vk_compute_test cs_tbuffer_store.spv 1 dump; check.py compares words 0..127 of
16; the dump with TBUFFER_STORE_WORDS and 76 untouched 0xeeeeeeee words.
17v_cmpx_eq_u32_e32 0, v0
18; the store regions 0x200..0x2cf hold 0xa5a50000 | their address
19v_mov_b32_e32 v1, 0xa5a50200
20v_mov_b32_e32 v2, 0xa5a50204
21v_mov_b32_e32 v3, 0xa5a50208
22v_mov_b32_e32 v4, 0xa5a5020c
23v_mov_b32_e32 v5, 0x200
24buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
25v_mov_b32_e32 v1, 0xa5a50210
26v_mov_b32_e32 v2, 0xa5a50214
27v_mov_b32_e32 v3, 0xa5a50218
28v_mov_b32_e32 v4, 0xa5a5021c
29v_mov_b32_e32 v5, 0x210
30buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
31v_mov_b32_e32 v1, 0xa5a50220
32v_mov_b32_e32 v2, 0xa5a50224
33v_mov_b32_e32 v3, 0xa5a50228
34v_mov_b32_e32 v4, 0xa5a5022c
35v_mov_b32_e32 v5, 0x220
36buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
37v_mov_b32_e32 v1, 0xa5a50230
38v_mov_b32_e32 v2, 0xa5a50234
39v_mov_b32_e32 v3, 0xa5a50238
40v_mov_b32_e32 v4, 0xa5a5023c
41v_mov_b32_e32 v5, 0x230
42buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
43v_mov_b32_e32 v1, 0xa5a50240
44v_mov_b32_e32 v2, 0xa5a50244
45v_mov_b32_e32 v3, 0xa5a50248
46v_mov_b32_e32 v4, 0xa5a5024c
47v_mov_b32_e32 v5, 0x240
48buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
49v_mov_b32_e32 v1, 0xa5a50250
50v_mov_b32_e32 v2, 0xa5a50254
51v_mov_b32_e32 v3, 0xa5a50258
52v_mov_b32_e32 v4, 0xa5a5025c
53v_mov_b32_e32 v5, 0x250
54buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
55v_mov_b32_e32 v1, 0xa5a50260
56v_mov_b32_e32 v2, 0xa5a50264
57v_mov_b32_e32 v3, 0xa5a50268
58v_mov_b32_e32 v4, 0xa5a5026c
59v_mov_b32_e32 v5, 0x260
60buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
61v_mov_b32_e32 v1, 0xa5a50270
62v_mov_b32_e32 v2, 0xa5a50274
63v_mov_b32_e32 v3, 0xa5a50278
64v_mov_b32_e32 v4, 0xa5a5027c
65v_mov_b32_e32 v5, 0x270
66buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
67v_mov_b32_e32 v1, 0xa5a50280
68v_mov_b32_e32 v2, 0xa5a50284
69v_mov_b32_e32 v3, 0xa5a50288
70v_mov_b32_e32 v4, 0xa5a5028c
71v_mov_b32_e32 v5, 0x280
72buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
73v_mov_b32_e32 v1, 0xa5a50290
74v_mov_b32_e32 v2, 0xa5a50294
75v_mov_b32_e32 v3, 0xa5a50298
76v_mov_b32_e32 v4, 0xa5a5029c
77v_mov_b32_e32 v5, 0x290
78buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
79v_mov_b32_e32 v1, 0xa5a502a0
80v_mov_b32_e32 v2, 0xa5a502a4
81v_mov_b32_e32 v3, 0xa5a502a8
82v_mov_b32_e32 v4, 0xa5a502ac
83v_mov_b32_e32 v5, 0x2a0
84buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
85v_mov_b32_e32 v1, 0xa5a502b0
86v_mov_b32_e32 v2, 0xa5a502b4
87v_mov_b32_e32 v3, 0xa5a502b8
88v_mov_b32_e32 v4, 0xa5a502bc
89v_mov_b32_e32 v5, 0x2b0
90buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
91v_mov_b32_e32 v1, 0xa5a502c0
92v_mov_b32_e32 v2, 0xa5a502c4
93v_mov_b32_e32 v3, 0xa5a502c8
94v_mov_b32_e32 v4, 0xa5a502cc
95v_mov_b32_e32 v5, 0x2c0
96buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
97s_waitcnt_vscnt null, 0x0
98s_mov_b32 s4, s0
99s_mov_b32 s5, s1
100; 0x200: tbuffer_store_format_xyzw, xyzw, 32_32_32_32_FLOAT over a V# that says 32_FLOAT: all four dwords
101v_mov_b32_e32 v20, 0x3f800000
102v_mov_b32_e32 v21, 0x40000000
103v_mov_b32_e32 v22, 0x40400000
104v_mov_b32_e32 v23, 0x40800000
105s_mov_b32 s6, 0xffffffff
106s_mov_b32 s7, 0x31016fac
107v_mov_b32_e32 v5, 0x200
108tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
109; 0x210: tbuffer_store_format_xy, xy, 16_16_16_16_FLOAT over a V# that says 32_32_32_32_FLOAT: the 8-byte element, z = w = 0
110v_mov_b32_e32 v20, 0x3f800000
111v_mov_b32_e32 v21, 0x40000000
112s_mov_b32 s6, 0xffffffff
113s_mov_b32 s7, 0x3104dfac
114v_mov_b32_e32 v5, 0x210
115tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen
116; 0x220: tbuffer_store_format_xyz, xyz, 8_8_8_8_UINT over a V# that says 32_FLOAT
117v_mov_b32_e32 v20, 0x1
118v_mov_b32_e32 v21, 0x2
119v_mov_b32_e32 v22, 0x3
120s_mov_b32 s6, 0xffffffff
121s_mov_b32 s7, 0x31016fac
122v_mov_b32_e32 v5, 0x220
123tbuffer_store_format_xyz v[20:22], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UINT] offen
124; 0x230: tbuffer_store_format_x, x, no format modifier (GFX10 default 8_UNORM) at byte 1, over a V# that says 32_32_32_32_FLOAT
125v_mov_b32_e32 v20, 0x3f800000
126s_mov_b32 s6, 0xffffffff
127s_mov_b32 s7, 0x3104dfac
128v_mov_b32_e32 v5, 0x231
129tbuffer_store_format_x v20, v5, s[4:7], 0 offen
130; 0x240: tbuffer_store_format_x, x, 16_FLOAT at byte 2 (the high half)
131v_mov_b32_e32 v20, 0x40000000
132s_mov_b32 s6, 0xffffffff
133s_mov_b32 s7, 0x31016fac
134v_mov_b32_e32 v5, 0x242
135tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_16_FLOAT] offen
136; 0x250: tbuffer_store_format_xyzw, xyzw, 2_10_10_10_UNORM (1.0, 0.0, 0.25, 1.0)
137v_mov_b32_e32 v20, 0x3f800000
138v_mov_b32_e32 v21, 0x0
139v_mov_b32_e32 v22, 0x3e800000
140v_mov_b32_e32 v23, 0x3f800000
141s_mov_b32 s6, 0xffffffff
142s_mov_b32 s7, 0x31016fac
143v_mov_b32_e32 v5, 0x250
144tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen
145; 0x260: tbuffer_store_format_xyzw, xyzw into 32_32_FLOAT: only x, y
146v_mov_b32_e32 v20, 0x3f800000
147v_mov_b32_e32 v21, 0x40000000
148v_mov_b32_e32 v22, 0x40400000
149v_mov_b32_e32 v23, 0x40800000
150s_mov_b32 s6, 0xffffffff
151s_mov_b32 s7, 0x3104dfac
152v_mov_b32_e32 v5, 0x260
153tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
154; 0x270: tbuffer_store_format_d16_xy, d16_xy, 16_16_FLOAT (packed 1.0, 2.0)
155v_mov_b32_e32 v20, 0x40003c00
156s_mov_b32 s6, 0xffffffff
157s_mov_b32 s7, 0x3104dfac
158v_mov_b32_e32 v5, 0x270
159tbuffer_store_format_d16_xy v20, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen
160; 0x280: tbuffer_store_format_d16_xyzw, d16_xyzw, 8_8_8_8_UNORM (packed 1.0, 0.5, 0.0, 1.0)
161v_mov_b32_e32 v20, 0x38003c00
162v_mov_b32_e32 v21, 0x3c000000
163s_mov_b32 s6, 0xffffffff
164s_mov_b32 s7, 0x31016fac
165v_mov_b32_e32 v5, 0x280
166tbuffer_store_format_d16_xyzw v[20:21], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen
167; 0x290: tbuffer_store_format_xy, xy, 32_32_32_32_FLOAT, NR 0x298 over a V# that says 32_FLOAT: x, y end at 0x298, the element at 0x2a0
168v_mov_b32_e32 v20, 0x3f800000
169v_mov_b32_e32 v21, 0x40000000
170s_mov_b32 s6, 0x298
171s_mov_b32 s7, 0x31016fac
172v_mov_b32_e32 v5, 0x290
173tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
174; 0x2a0: tbuffer_store_format_x, x, 8_UNORM, NR 0x2a1 over a V# that says 32_32_32_32_FLOAT: the byte fits, the V#'s element would not
175v_mov_b32_e32 v20, 0x3f800000
176s_mov_b32 s6, 0x2a1
177s_mov_b32 s7, 0x3104dfac
178v_mov_b32_e32 v5, 0x2a0
179tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_8_UNORM] offen
180; 0x2b0: tbuffer_store_format_xyzw, xyzw into 32_FLOAT (one channel) over a V# that says 32_32_32_32_FLOAT: only x
181v_mov_b32_e32 v20, 0x3f800000
182v_mov_b32_e32 v21, 0x40000000
183v_mov_b32_e32 v22, 0x40400000
184v_mov_b32_e32 v23, 0x40800000
185s_mov_b32 s6, 0xffffffff
186s_mov_b32 s7, 0x3104dfac
187v_mov_b32_e32 v5, 0x2b0
188tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_FLOAT] offen
189; 0x2c0: tbuffer_store_format_xy, xy, 32_32_FLOAT over a V# whose FORMAT is 0 (INVALID): nothing
190v_mov_b32_e32 v20, 0x3f800000
191v_mov_b32_e32 v21, 0x40000000
192s_mov_b32 s6, 0xffffffff
193s_mov_b32 s7, 0x31000fac
194v_mov_b32_e32 v5, 0x2c0
195tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
196s_waitcnt_vscnt null, 0x0
197; out[0..3]: the 16 bytes at 0x200
198v_mov_b32_e32 v5, 0x200
199buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
200s_waitcnt vmcnt(0)
201v_mov_b32_e32 v6, 0x0
202buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
203; out[4..7]: the 16 bytes at 0x210
204v_mov_b32_e32 v5, 0x210
205buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
206s_waitcnt vmcnt(0)
207v_mov_b32_e32 v6, 0x10
208buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
209; out[8..11]: the 16 bytes at 0x220
210v_mov_b32_e32 v5, 0x220
211buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
212s_waitcnt vmcnt(0)
213v_mov_b32_e32 v6, 0x20
214buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
215; out[12..15]: the 16 bytes at 0x230
216v_mov_b32_e32 v5, 0x230
217buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
218s_waitcnt vmcnt(0)
219v_mov_b32_e32 v6, 0x30
220buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
221; out[16..19]: the 16 bytes at 0x240
222v_mov_b32_e32 v5, 0x240
223buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
224s_waitcnt vmcnt(0)
225v_mov_b32_e32 v6, 0x40
226buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
227; out[20..23]: the 16 bytes at 0x250
228v_mov_b32_e32 v5, 0x250
229buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
230s_waitcnt vmcnt(0)
231v_mov_b32_e32 v6, 0x50
232buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
233; out[24..27]: the 16 bytes at 0x260
234v_mov_b32_e32 v5, 0x260
235buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
236s_waitcnt vmcnt(0)
237v_mov_b32_e32 v6, 0x60
238buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
239; out[28..31]: the 16 bytes at 0x270
240v_mov_b32_e32 v5, 0x270
241buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
242s_waitcnt vmcnt(0)
243v_mov_b32_e32 v6, 0x70
244buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
245; out[32..35]: the 16 bytes at 0x280
246v_mov_b32_e32 v5, 0x280
247buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
248s_waitcnt vmcnt(0)
249v_mov_b32_e32 v6, 0x80
250buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
251; out[36..39]: the 16 bytes at 0x290
252v_mov_b32_e32 v5, 0x290
253buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
254s_waitcnt vmcnt(0)
255v_mov_b32_e32 v6, 0x90
256buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
257; out[40..43]: the 16 bytes at 0x2a0
258v_mov_b32_e32 v5, 0x2a0
259buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
260s_waitcnt vmcnt(0)
261v_mov_b32_e32 v6, 0xa0
262buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
263; out[44..47]: the 16 bytes at 0x2b0
264v_mov_b32_e32 v5, 0x2b0
265buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
266s_waitcnt vmcnt(0)
267v_mov_b32_e32 v6, 0xb0
268buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
269; out[48..51]: the 16 bytes at 0x2c0
270v_mov_b32_e32 v5, 0x2c0
271buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
272s_waitcnt vmcnt(0)
273v_mov_b32_e32 v6, 0xc0
274buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
275s_endpgm
diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm
new file mode 100644
index 000000000..b8f888c13
--- /dev/null
+++ b/runtime/test/shaders/ps_imgatomic.asm
@@ -0,0 +1,44 @@
1; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders:
2; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0
3; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s:
4; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords:
5; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target),
6; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8
7; images:
8; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31),
9; umax3d[px & 3][ty >> 1][tx >> 1] = max(id) (a 4x4x4 image)
10; After its atomics, every odd px is discarded (v_cmpx). The atomics of a pixel that is discarded afterwards still
11; count, as on hardware: the expected values above are over all 4096 pixels. Even pixels export 1.0.
12; Run: vk_bindless_test vs_ids.spv ps_imgatomic.spv (images cleared to 0, umin to 0xffffffff; checked per texel)
13s_load_dwordx8 s[8:15], s[2:3], 0x0
14s_load_dwordx8 s[16:23], s[2:3], 0x20
15s_load_dwordx8 s[24:31], s[2:3], 0x40
16s_load_dwordx8 s[32:39], s[2:3], 0x60
17s_waitcnt lgkmcnt(0)
18v_interp_p1_f32_e32 v2, v0, attr0.x
19v_interp_p2_f32_e32 v2, v1, attr0.x
20v_interp_p1_f32_e32 v3, v0, attr0.y
21v_interp_p2_f32_e32 v3, v1, attr0.y
22v_mul_f32_e32 v2, 0x42800000, v2
23v_mul_f32_e32 v3, 0x42800000, v3
24v_cvt_u32_f32_e32 v4, v2
25v_cvt_u32_f32_e32 v5, v3
26v_lshlrev_b32_e32 v6, 6, v5
27v_add_nc_u32_e32 v6, v6, v4
28v_lshrrev_b32_e32 v7, 3, v4
29v_lshrrev_b32_e32 v8, 3, v5
30image_atomic_umax v6, v[7:8], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
31image_atomic_umin v6, v[7:8], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
32v_and_b32_e32 v9, 31, v6
33v_lshlrev_b32_e64 v9, v9, 1
34image_atomic_or v9, v[7:8], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
35v_lshrrev_b32_e32 v10, 1, v7
36v_lshrrev_b32_e32 v11, 1, v8
37v_and_b32_e32 v12, 3, v4
38image_atomic_umax v6, v[10:12], s[32:39] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
39s_waitcnt vmcnt(0)
40v_and_b32_e32 v13, 1, v4
41v_cmpx_eq_u32_e32 0, v13
42v_mov_b32_e32 v14, 1.0
43exp mrt0 v14, v14, v14, v14 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_m2_uoff.asm b/runtime/test/shaders/ps_m2_uoff.asm
index 7f1167944..1c96f50d5 100644
--- a/runtime/test/shaders/ps_m2_uoff.asm
+++ b/runtime/test/shaders/ps_m2_uoff.asm
@@ -2,9 +2,12 @@
2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one 2; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one
3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by 3; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by
4; @Vonsek (#1489). Run: d3d12_m2_textured_test. 4; @Vonsek (#1489). Run: d3d12_m2_textured_test.
5; The same unbounded SRV table stays bound across both draws. Root constants s4 and s5 hold
6; the descriptor index and byte stride, respectively.
5; fssm-at: 0x10 7; fssm-at: 0x10
6; fssm-data: 0x324d5350 0x4f465520 8; fssm-data: 0x324d5350 0x4f465520
7s_load_dwordx8 s[8:15], s[0:1], 0x0 9s_mul_i32 s20, s4, s5
10s_load_dwordx8 s[8:15], s[0:1], s20
8s_load_dwordx4 s[16:19], s[2:3], 0x0 11s_load_dwordx4 s[16:19], s[2:3], 0x0
9s_waitcnt lgkmcnt(0) 12s_waitcnt lgkmcnt(0)
10v_interp_p1_f32_e32 v2, v0, attr0.x 13v_interp_p1_f32_e32 v2, v0, attr0.x
diff --git a/runtime/test/shaders/ps_mandelbrot.asm b/runtime/test/shaders/ps_mandelbrot.asm
new file mode 100644
index 000000000..98c70f6cc
--- /dev/null
+++ b/runtime/test/shaders/ps_mandelbrot.asm
@@ -0,0 +1,46 @@
1; Mandelbrot set: a divergent backward loop with EXEC masking. Each lane iterates z = z^2 + c until |z|^2 > 4 or
2; 64 iterations, with c from attr0.xy (u, v 0..1 over the image) mapped to [-2.25, 0.75] x [-1.5, 1.5]. A lane that
3; escapes drops out of EXEC (s_and_b32 exec_lo, exec_lo, vcc_lo); s_cbranch_execz leaves the loop once every lane has
4; escaped, else the uniform counter s10 ends it after 64 rounds. EXEC is restored from s20 before the export.
5; Only v_mul/v_add/v_sub (no FMA), so a float32 model on the CPU gives the same counts.
6; Branch offsets are dwords from the next instruction: execz +9 forward to the restore, scc1 -15 back to the loop top.
7; Run: vk_harness vs_ids.spv ps_mandelbrot.spv out.raw
8; -> mrt0 = (sqrt(t), t*t, 4t(1-t), iteration count as raw bits) with t = count / 64
9v_interp_p1_f32_e32 v2, v0, attr0.x
10v_interp_p2_f32_e32 v2, v1, attr0.x
11v_interp_p1_f32_e32 v3, v0, attr0.y
12v_interp_p2_f32_e32 v3, v1, attr0.y
13v_mul_f32_e32 v4, 0x40400000, v2
14v_add_f32_e32 v4, 0xc0100000, v4
15v_mul_f32_e32 v5, 0x40400000, v3
16v_add_f32_e32 v5, 0xbfc00000, v5
17v_mov_b32_e32 v6, 0
18v_mov_b32_e32 v7, 0
19v_mov_b32_e32 v8, 0
20s_mov_b32 s10, 0
21s_mov_b32 s20, exec_lo
22v_mul_f32_e32 v9, v6, v6
23v_mul_f32_e32 v10, v7, v7
24v_add_f32_e32 v11, v9, v10
25v_cmp_ge_f32_e32 vcc_lo, 4.0, v11
26s_and_b32 exec_lo, exec_lo, vcc_lo
27s_cbranch_execz 9
28v_sub_f32_e32 v12, v9, v10
29v_mul_f32_e32 v13, v6, v7
30v_add_f32_e32 v13, v13, v13
31v_add_f32_e32 v6, v12, v4
32v_add_f32_e32 v7, v13, v5
33v_add_nc_u32_e32 v8, 1, v8
34s_add_u32 s10, s10, 1
35s_cmp_lt_u32 s10, 64
36s_cbranch_scc1 -15
37s_mov_b32 exec_lo, s20
38v_cvt_f32_u32_e32 v14, v8
39v_mul_f32_e32 v14, 0x3c800000, v14
40v_sqrt_f32_e32 v15, v14
41v_mul_f32_e32 v16, v14, v14
42v_sub_f32_e32 v17, 1.0, v14
43v_mul_f32_e32 v17, v14, v17
44v_mul_f32_e32 v17, 4.0, v17
45exp mrt0 v15, v16, v17, v8 done vm
46s_endpgm
diff --git a/runtime/test/shaders/ps_scc_logic32.asm b/runtime/test/shaders/ps_scc_logic32.asm
new file mode 100644
index 000000000..3b36f1362
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic32.asm
@@ -0,0 +1,44 @@
1; s_nand_b32, s_nor_b32, s_xnor_b32: D = ~(S0 op S1), SCC = (D != 0). Values by hand from the RDNA2 ISA SOP2 text.
2; s2 = 0xf0f0f0f0, s3 = 0xff00ff00: and = 0xf000f000, or = 0xfff0fff0, xor = 0x0ff00ff0.
3; Expected mrt0 bits: nand 0x0fff0fff, nor 0x000f000f, xnor 0xf00ff00f, and an SCC word, bit n = SCC after case n:
4; 0 nand(-1, -1) = 0 -> 0 1 nor(0, 0) = -1 -> 1 2 xnor(x, x) = -1 -> 1
5; 3 xnor(x, ~x) = 0 -> 0 4 nor(0xfffffff0, 0) = 0xf -> 1 5 nand(0x80000000, -1) = 0x7fffffff -> 1
6; so the SCC word is 0x36.
7s_mov_b32 s2, 0xf0f0f0f0
8s_mov_b32 s3, 0xff00ff00
9s_nand_b32 s4, s2, s3
10s_nor_b32 s5, s2, s3
11s_xnor_b32 s6, s2, s3
12s_mov_b32 s8, -1
13s_mov_b32 s9, 0
14s_mov_b32 s10, 0x0f0f0f0f
15s_mov_b32 s11, 0xfffffff0
16s_mov_b32 s12, 0x80000000
17s_nand_b32 s13, s8, s8
18s_cselect_b32 s20, 1, 0
19s_nor_b32 s13, s9, s9
20s_cselect_b32 s21, 1, 0
21s_xnor_b32 s13, s2, s2
22s_cselect_b32 s22, 1, 0
23s_xnor_b32 s13, s2, s10
24s_cselect_b32 s23, 1, 0
25s_nor_b32 s13, s11, s9
26s_cselect_b32 s24, 1, 0
27s_nand_b32 s13, s12, s8
28s_cselect_b32 s25, 1, 0
29s_lshl_b32 s21, s21, 1
30s_lshl_b32 s22, s22, 2
31s_lshl_b32 s23, s23, 3
32s_lshl_b32 s24, s24, 4
33s_lshl_b32 s25, s25, 5
34s_or_b32 s20, s20, s21
35s_or_b32 s20, s20, s22
36s_or_b32 s20, s20, s23
37s_or_b32 s20, s20, s24
38s_or_b32 s20, s20, s25
39v_mov_b32_e32 v0, s4
40v_mov_b32_e32 v1, s5
41v_mov_b32_e32 v2, s6
42v_mov_b32_e32 v3, s20
43exp mrt0 v0, v1, v2, v3 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_scc_logic64.asm b/runtime/test/shaders/ps_scc_logic64.asm
new file mode 100644
index 000000000..3ffb677ae
--- /dev/null
+++ b/runtime/test/shaders/ps_scc_logic64.asm
@@ -0,0 +1,49 @@
1; s_nand_b64, s_nor_b64, s_xnor_b64 on plain SGPR pairs: D = ~(S0 op S1), SCC = ((D.lo | D.hi) != 0). By hand from the RDNA2 ISA.
2; A = s[2:3] = (lo 0xf0f0f0f0, hi 0x0000ffff), B = s[4:5] = (lo 0xff00ff00, hi 0x00ff00ff).
3; Expected mrt0 bits: nand.lo 0x0fff0fff, nor.hi 0xff000000 (A.hi | B.hi = 0x00ffffff), xnor.hi 0xff0000ff (A.hi ^ B.hi = 0x00ffff00),
4; and an SCC word, bit n = SCC after case n (X = (-1, 0), Y = (0, -1)):
5; 0 nand(ones, ones) = 0 -> 0 1 nor(X, 0) = (0, -1), only the high dword set -> 1
6; 2 xnor(X, X) = all ones -> 1 3 xnor(X, Y) = 0 -> 0
7; 4 nor(Y, (0xfffffff0, 0)) = (0xf, 0), only the low dword set -> 1
8; so the SCC word is 0x16.
9s_mov_b32 s2, 0xf0f0f0f0
10s_mov_b32 s3, 0x0000ffff
11s_mov_b32 s4, 0xff00ff00
12s_mov_b32 s5, 0x00ff00ff
13s_nand_b64 s[6:7], s[2:3], s[4:5]
14s_nor_b64 s[8:9], s[2:3], s[4:5]
15s_xnor_b64 s[10:11], s[2:3], s[4:5]
16s_mov_b32 s12, -1
17s_mov_b32 s13, -1
18s_mov_b32 s14, -1
19s_mov_b32 s15, 0
20s_mov_b32 s16, 0
21s_mov_b32 s17, -1
22s_mov_b32 s18, 0
23s_mov_b32 s19, 0
24s_mov_b32 s24, 0xfffffff0
25s_mov_b32 s25, 0
26s_nand_b64 s[30:31], s[12:13], s[12:13]
27s_cselect_b32 s40, 1, 0
28s_nor_b64 s[30:31], s[14:15], s[18:19]
29s_cselect_b32 s41, 1, 0
30s_xnor_b64 s[30:31], s[14:15], s[14:15]
31s_cselect_b32 s42, 1, 0
32s_xnor_b64 s[30:31], s[14:15], s[16:17]
33s_cselect_b32 s43, 1, 0
34s_nor_b64 s[30:31], s[16:17], s[24:25]
35s_cselect_b32 s44, 1, 0
36s_lshl_b32 s41, s41, 1
37s_lshl_b32 s42, s42, 2
38s_lshl_b32 s43, s43, 3
39s_lshl_b32 s44, s44, 4
40s_or_b32 s40, s40, s41
41s_or_b32 s40, s40, s42
42s_or_b32 s40, s40, s43
43s_or_b32 s40, s40, s44
44v_mov_b32_e32 v0, s6
45v_mov_b32_e32 v1, s9
46v_mov_b32_e32 v2, s11
47v_mov_b32_e32 v3, s40
48exp mrt0 v0, v1, v2, v3 done vm
49s_endpgm
diff --git a/runtime/test/shaders/vs_w64_a_skip.asm b/runtime/test/shaders/vs_w64_a_skip.asm
new file mode 100644
index 000000000..dac0d885e
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_a_skip.asm
@@ -0,0 +1,45 @@
1; TEST-251 (SHADER-10 tier A, vertex stage): the skip regions and the loop of ps_w64_a_skip in a wave64 vertex shader,
2; without its whole-quad mask (vertex quads are lanes, not pixels). Vertex v (v0 = vertex index) has x = v & 63 and
3; y = v >> 6, so every word is a function of v and not of the lane the vertex landed on. It stores (r0, r1, r2, r3)
4; to its record at heap 0x1000 + 16 * v through the V# in s[0:3].
5; (1) a skip region behind s_cbranch_execz: only lanes with x % 4 == 1 run it. r0 = x % 4 == 1 ? 7 * y + x : 1000 + x.
6; (2) r1 = x % 4 == 1 (the VCC of (1), per lane).
7; (3) s_cbranch_vccz over a region that narrows EXEC to that VCC. r2 = 2000 + y + (y % 4 == 2 ? 9 : 0).
8; (4) a loop closed by s_cbranch_execnz, no scalar state carried. r3 = x % 4 + 1.
9; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
10; vs_w64_a_skip.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal records, and equal
11; to the expected words.
12; mattr: +wavefrontsize64,-wavefrontsize32
13v_and_b32_e32 v2, 63, v0
14v_lshrrev_b32_e32 v3, 6, v0
15s_mov_b64 s[10:11], exec
16v_add_nc_u32_e32 v6, 0x3e8, v2
17v_and_b32_e32 v4, 3, v2
18v_cmp_eq_u32_e32 vcc, 1, v4
19v_cndmask_b32_e64 v7, 0, 1, vcc
20s_and_saveexec_b64 s[12:13], vcc
21s_cbranch_execz 2
22v_mul_u32_u24_e32 v6, 7, v3
23v_add_nc_u32_e32 v6, v6, v2
24s_or_b64 exec, exec, s[12:13]
25v_and_b32_e32 v5, 3, v3
26v_add_nc_u32_e32 v8, 0x7d0, v3
27v_cmp_eq_u32_e32 vcc, 2, v5
28s_cbranch_vccz 3
29s_and_saveexec_b64 s[16:17], vcc
30v_add_nc_u32_e32 v8, 9, v8
31s_or_b64 exec, exec, s[16:17]
32v_add_nc_u32_e32 v10, 1, v4
33v_mov_b32_e32 v9, 0
34v_add_nc_u32_e32 v9, 1, v9
35v_cmp_lt_u32_e32 vcc, v9, v10
36s_and_b64 exec, exec, vcc
37s_cbranch_execnz -4
38s_mov_b64 exec, s[10:11]
39v_lshlrev_b32_e32 v12, 4, v0
40v_add_nc_u32_e32 v12, 0x1000, v12
41buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
42v_mov_b32_e32 v5, 0
43exp pos0 v5, v5, v5, v5 done
44exp param0 v5, v5, v5, v5
45s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_ballot_atomic.asm b/runtime/test/shaders/vs_w64_b_ballot_atomic.asm
new file mode 100644
index 000000000..f718c25f8
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_ballot_atomic.asm
@@ -0,0 +1,42 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): the wave-aggregated atomic of ps_w64_b_ballot_atomic in a wave64 vertex
2; shader. Vertex v (v0 = vertex index) has x = v & 63; vertices with x % 4 == 1 are the "wanted" lanes. EXEC = the
3; wanted lanes; n = s_bcnt1_i32_b64 exec; rank = v_mbcnt_lo/hi of EXEC; the lane of rank 0 does buffer_atomic_add of n
4; to the counter at heap offset 0 and gets the old value back; v_readfirstlane broadcasts it as the base; every wanted
5; vertex stores v + 1 at heap offset 0x100 + 4 * (base + rank). Whatever the wave size and the packing, every wanted
6; vertex gets a slot of its own and the counter ends at the number of wanted vertices (240 of 960); which vertex gets
7; which slot depends on the packing, so the slots are compared as a set. Its record at heap 0x1000 + 16 * v holds
8; (x % 4 == 1, 0, 0, 0).
9; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
10; vs_w64_b_ballot_atomic.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32.
11; mattr: +wavefrontsize64,-wavefrontsize32
12v_and_b32_e32 v2, 63, v0
13v_and_b32_e32 v4, 3, v2
14s_mov_b64 s[10:11], exec
15v_cmp_eq_u32_e32 vcc, 1, v4
16v_cndmask_b32_e64 v6, 0, 1, vcc
17s_and_saveexec_b64 s[12:13], vcc
18s_bcnt1_i32_b64 s6, exec
19v_mbcnt_lo_u32_b32 v10, exec_lo, 0
20v_mbcnt_hi_u32_b32 v10, exec_hi, v10
21v_cmp_eq_u32_e32 vcc, 0, v10
22s_and_saveexec_b64 s[14:15], vcc
23v_mov_b32_e32 v11, s6
24v_mov_b32_e32 v13, 0
25buffer_atomic_add v11, v13, s[0:3], 0 offen glc
26s_or_b64 exec, exec, s[14:15]
27v_readfirstlane_b32 s7, v11
28v_add_nc_u32_e32 v13, s7, v10
29v_lshlrev_b32_e32 v13, 2, v13
30v_add_nc_u32_e32 v14, 1, v0
31buffer_store_dword v14, v13, s[0:3], 0 offen offset:256
32s_mov_b64 exec, s[10:11]
33v_mov_b32_e32 v7, 0
34v_mov_b32_e32 v8, 0
35v_mov_b32_e32 v9, 0
36v_lshlrev_b32_e32 v12, 4, v0
37v_add_nc_u32_e32 v12, 0x1000, v12
38buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
39v_mov_b32_e32 v5, 0
40exp pos0 v5, v5, v5, v5 done
41exp param0 v5, v5, v5, v5
42s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_readlane_uniform.asm b/runtime/test/shaders/vs_w64_b_readlane_uniform.asm
new file mode 100644
index 000000000..0fb85008d
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_readlane_uniform.asm
@@ -0,0 +1,33 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): v_readfirstlane and v_readlane (lanes 40 and 63) of wave-uniform VGPRs
2; in a wave64 vertex shader, the vertex twin of ps_w64_b_readfirstlane and ps_w64_b_readlane_uniform. s4 is a user
3; SGPR (VKH_SGPRS sets it to 123), copied to a VGPR and read back; so is the constant 77. Every lane holds the same
4; value, so the scalar does not depend on which lane is read, on the wave size or on how many vertices a wave got.
5; Vertex v (v0 = vertex index) has x = v & 63. r0 = x + 123 (readfirstlane), r1 = 123 + 77 (readlane 40 and 63),
6; r2 = x + 123 (readlane 40), r3 = 77 * 2 + 123 (readfirstlane), stored to its record at heap 0x1000 + 16 * v
7; through the V# in s[0:3].
8; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000,123 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
9; vs_w64_b_readlane_uniform.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal, and
10; equal to the expected words.
11; mattr: +wavefrontsize64,-wavefrontsize32
12v_and_b32_e32 v2, 63, v0
13s_mov_b64 s[10:11], exec
14v_mov_b32_e32 v5, s4
15v_mov_b32_e32 v4, 77
16v_readfirstlane_b32 s20, v5
17v_add_nc_u32_e32 v6, s20, v2
18v_readlane_b32 s21, v5, 40
19v_readlane_b32 s22, v4, 63
20s_add_u32 s23, s21, s22
21v_mov_b32_e32 v7, s23
22v_add_nc_u32_e32 v8, s21, v2
23v_readfirstlane_b32 s24, v4
24s_lshl_b32 s24, s24, 1
25s_add_u32 s24, s24, s20
26v_mov_b32_e32 v9, s24
27v_lshlrev_b32_e32 v12, 4, v0
28v_add_nc_u32_e32 v12, 0x1000, v12
29buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
30v_mov_b32_e32 v5, 0
31exp pos0 v5, v5, v5, v5 done
32exp param0 v5, v5, v5, v5
33s_endpgm
diff --git a/runtime/test/shaders/vs_w64_b_waterfall.asm b/runtime/test/shaders/vs_w64_b_waterfall.asm
new file mode 100644
index 000000000..814259842
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_b_waterfall.asm
@@ -0,0 +1,35 @@
1; TEST-251 (SHADER-10 tier B, vertex stage): the waterfall loop of ps_w64_b_waterfall in a wave64 vertex shader.
2; Vertex v (v0 = vertex index) has x = v & 63, y = v >> 6 and the key a = x % 4 + 4 * (y % 4). The loop takes
3; v_readfirstlane of the key, runs the lanes holding it (v_cmp_eq, s_and_saveexec), retires them (s_xor exec) and
4; repeats while lanes are left (s_cbranch_execnz); the scalar is used only inside the body. It runs once per distinct
5; key of the wave or of the 32-lane subgroup, and every vertex ends with r0 = 17 * a + x, r1 = a, r2 = r3 = 0, stored
6; to its record at heap 0x1000 + 16 * v through the V# in s[0:3].
7; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
8; vs_w64_b_waterfall.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: equal, and equal to
9; the expected words.
10; mattr: +wavefrontsize64,-wavefrontsize32
11v_and_b32_e32 v2, 63, v0
12v_lshrrev_b32_e32 v3, 6, v0
13v_and_b32_e32 v4, 3, v2
14v_and_b32_e32 v5, 3, v3
15v_lshl_add_u32 v4, v5, 2, v4
16v_mov_b32_e32 v6, 0
17s_mov_b64 s[10:11], exec
18v_readfirstlane_b32 s20, v4
19v_cmp_eq_u32_e32 vcc, s20, v4
20s_and_saveexec_b64 s[12:13], vcc
21s_mul_i32 s21, s20, 17
22v_add_nc_u32_e32 v6, s21, v2
23s_xor_b64 exec, exec, s[12:13]
24s_cbranch_execnz -7
25s_mov_b64 exec, s[10:11]
26v_mov_b32_e32 v7, v4
27v_mov_b32_e32 v8, 0
28v_mov_b32_e32 v9, 0
29v_lshlrev_b32_e32 v12, 4, v0
30v_add_nc_u32_e32 v12, 0x1000, v12
31buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
32v_mov_b32_e32 v5, 0
33exp pos0 v5, v5, v5, v5 done
34exp param0 v5, v5, v5, v5
35s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_bcnt_export.asm b/runtime/test/shaders/vs_w64_c_bcnt_export.asm
new file mode 100644
index 000000000..84dd9bf53
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_bcnt_export.asm
@@ -0,0 +1,23 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): a lane count used as data. Vertex v (v0 = vertex index) has x = v & 63;
2; s_bcnt1_i32_b64 counts the lanes of its wave with x % 4 == 1, which depends on the wave size and on how many
3; vertices the driver put in the wave. r0 = that count (partition dependent), r1 = x % 4 == 1, r2 = r3 = 0, stored to
4; its record at heap 0x1000 + 16 * v through the V# in s[0:3].
5; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
6; vs_w64_c_bcnt_export.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r0
7; differs.
8; mattr: +wavefrontsize64,-wavefrontsize32
9v_and_b32_e32 v2, 63, v0
10v_and_b32_e32 v4, 3, v2
11v_cmp_eq_u32_e32 vcc, 1, v4
12s_bcnt1_i32_b64 s6, vcc
13v_mov_b32_e32 v6, s6
14v_cndmask_b32_e64 v7, 0, 1, vcc
15v_mov_b32_e32 v8, 0
16v_mov_b32_e32 v9, 0
17v_lshlrev_b32_e32 v12, 4, v0
18v_add_nc_u32_e32 v12, 0x1000, v12
19buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
20v_mov_b32_e32 v5, 0
21exp pos0 v5, v5, v5, v5 done
22exp param0 v5, v5, v5, v5
23s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_lane_id.asm b/runtime/test/shaders/vs_w64_c_lane_id.asm
new file mode 100644
index 000000000..c69850333
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_lane_id.asm
@@ -0,0 +1,21 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): the raw lane number (v_mbcnt_lo/hi of -1) used as data. Each vertex v
2; (v0 = vertex index) stores (lane id, lane id & 31, v, 0) to its record at heap 0x1000 + 16 * v through the V# in
3; s[0:3]. In a wave64 VS some vertices get lanes 32..63; in a wave32 VS none do, so r0 and r1 depend on how the driver
4; packed the vertices into waves and r2 does not. w64_graphics.py also uses it as its probe: the largest r0 shows the
5; wave size the driver picked (63 by default on RADV GFX12, 31 with RADV_PERFTEST=gewave32).
6; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
7; vs_w64_c_lane_id.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32 (the triangles have
8; zero area, so nothing is drawn).
9; mattr: +wavefrontsize64,-wavefrontsize32
10v_mbcnt_lo_u32_b32 v6, -1, 0
11v_mbcnt_hi_u32_b32 v6, -1, v6
12v_and_b32_e32 v7, 31, v6
13v_mov_b32_e32 v8, v0
14v_mov_b32_e32 v9, 0
15v_lshlrev_b32_e32 v12, 4, v0
16v_add_nc_u32_e32 v12, 0x1000, v12
17buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
18v_mov_b32_e32 v5, 0
19exp pos0 v5, v5, v5, v5 done
20exp param0 v5, v5, v5, v5
21s_endpgm
diff --git a/runtime/test/shaders/vs_w64_c_readlane.asm b/runtime/test/shaders/vs_w64_c_readlane.asm
new file mode 100644
index 000000000..d472b1ee5
--- /dev/null
+++ b/runtime/test/shaders/vs_w64_c_readlane.asm
@@ -0,0 +1,23 @@
1; TEST-251 (SHADER-10 tier C, vertex stage): v_readlane of a varying value (the vertex index) at lanes 40 and 7. In a
2; wave64 VS every lane gets the vertex in hardware lane 40 (or 7) of its wave; in a wave32 VS lane 40 wraps or is
3; undefined and lane 7 is the vertex of another wave. Vertex v (v0 = vertex index): r0 = readlane 40, r1 = v,
4; r2 = readlane 7 (both partition dependent), r3 = 0, stored to its record at heap 0x1000 + 16 * v through the V# in
5; s[0:3].
6; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness
7; vs_w64_c_readlane.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r2 differs.
8; mattr: +wavefrontsize64,-wavefrontsize32
9s_mov_b64 s[10:11], exec
10v_mov_b32_e32 v4, v0
11v_readlane_b32 s6, v4, 40
12v_readlane_b32 s7, v4, 7
13v_mov_b32_e32 v6, s6
14v_mov_b32_e32 v7, v4
15v_mov_b32_e32 v8, s7
16v_mov_b32_e32 v9, 0
17v_lshlrev_b32_e32 v12, 4, v0
18v_add_nc_u32_e32 v12, 0x1000, v12
19buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen
20v_mov_b32_e32 v5, 0
21exp pos0 v5, v5, v5, v5 done
22exp param0 v5, v5, v5, v5
23s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index 91424af99..6e281d4b4 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -1,5 +1,5 @@
1"""SHADER-10 GPU checks: wave64 pixel shaders on 32-lane subgroups (docs/design.md, "Wave64 graphics: partition 1"""SHADER-10 GPU checks: wave64 pixel and vertex shaders on 32-lane subgroups (docs/design.md, "Wave64 graphics:
2invariance"). 2partition invariance").
3 3
4 python3 -I runtime/test/shaders/w64_graphics.py <build dir with spirv/> [tools dir] [name ...] 4 python3 -I runtime/test/shaders/w64_graphics.py <build dir with spirv/> [tools dir] [name ...]
5 5
@@ -16,6 +16,13 @@ A device that can require only one size (NVIDIA: 32 only) cannot run the compari
16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a 16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a
17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require 17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require
18it, and W64G_REF=<dir> compares every run of the other device with those files (equal for A and B, different for C). 18it, and W64G_REF=<dir> compares every run of the other device with those files (equal for A and B, different for C).
19
20The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes
21come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+).
22Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id
23doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs
2462 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of
25the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index.
19""" 26"""
20import os 27import os
21import struct 28import struct
@@ -106,6 +113,25 @@ def _c_execz_sgpr(i):
106 return (7 if _on(i) else None, _on(i), 0, 0) # r0 = s5: 7 only where the active side ran 113 return (7 if _on(i) else None, _on(i), 0, 0) # r0 = s5: 7 only where the active side ran
107 114
108 115
116# vs_w64_* fixtures: i is the vertex index, x = i % 64 and y = i // 64 as for a pixel.
117def _vs_a_skip(i):
118 x, y = _x(i), _y(i)
119 return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 == 1), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1)
120
121
122def _vs_b_readlane_uniform(i):
123 return (_x(i) + 123, 200, _x(i) + 123, 277)
124
125
126def _vs_c_lane_id(i):
127 return (None, None, i, 0) # r0, r1 = the lane the vertex got
128
129
130VS_ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"}
131VS_VERTICES = 960 # 15 rows of 64 vertices: several waves at either size, and partial ones
132VS_RECORDS = 0x1000 // 4 # heap word of vertex 0's record (4 words per vertex); below it, the atomic's counter and slots
133
134
109# name -> (tier, expected words per pixel (None = not fixed), environment of the draw) 135# name -> (tier, expected words per pixel (None = not fixed), environment of the draw)
110FIXTURES = { 136FIXTURES = {
111 "ps_w64_a_skip": ("A", _a_skip, {}), 137 "ps_w64_a_skip": ("A", _a_skip, {}),
@@ -122,13 +148,70 @@ FIXTURES = {
122 "ps_w64_c_vote_else": ("C", _c_vote_else, {}), 148 "ps_w64_c_vote_else": ("C", _c_vote_else, {}),
123 "ps_w64_c_scc_vote": ("C", _c_scc_vote, {}), 149 "ps_w64_c_scc_vote": ("C", _c_scc_vote, {}),
124 "ps_w64_c_execz_sgpr": ("C", _c_execz_sgpr, {}), 150 "ps_w64_c_execz_sgpr": ("C", _c_execz_sgpr, {}),
151 "vs_w64_a_skip": ("A", _vs_a_skip, VS_ENV),
152 "vs_w64_b_waterfall": ("B", _b_waterfall, VS_ENV),
153 "vs_w64_b_readlane_uniform": ("B", _vs_b_readlane_uniform, dict(VS_ENV, VKH_SGPRS=VS_ENV["VKH_SGPRS"] + ",123")),
154 "vs_w64_b_ballot_atomic": ("B", _b_ballot, VS_ENV),
155 "vs_w64_c_bcnt_export": ("C", _c_bcnt, VS_ENV),
156 "vs_w64_c_readlane": ("C", _c_readlane, VS_ENV),
157 "vs_w64_c_lane_id": ("C", _vs_c_lane_id, VS_ENV),
125} 158}
126 159
160VS_PROBE = "vs_w64_c_lane_id"
161_vs_applied = {}
162
163
164def _radv_perftest(size):
165 """RADV_PERFTEST for a vertex draw at `size`. Vulkan cannot require a vertex subgroup size (requiredSubgroupSizeStages
166 has no VERTEX on RADV or on the AMD driver), but RADV runs the VS/GS (NGG) stage as wave32 with gewave32 and as
167 wave64 without it on GFX10+. Other drivers ignore the variable; the probe then finds no change."""
168 flags = [f for f in os.environ.get("RADV_PERFTEST", "").split(",") if f and f != "gewave32"]
169 return ",".join(flags + ["gewave32"] * (size == 32))
170
171
172def _vs_wave_size(tools, spirv, size, tmp):
173 """Whether a vertex draw at `size` really ran at that wave size: the largest lane id of VS_PROBE is 32..63 in a
174 wave64 VS and below 32 in a wave32 one. Size 32 also needs size 64 to work, so that the two draws differ."""
175 if size not in _vs_applied:
176 def top(s):
177 words = _draw_vs(tools, spirv, VS_PROBE, s, tmp)[0]
178 return None if words is None else max(w[0] for w in words)
179 lane64, lane32 = top(64), top(32)
180 _vs_applied[64] = lane64 is not None and 32 <= lane64 < 64
181 _vs_applied[32] = _vs_applied[64] and lane32 is not None and lane32 < 32
182 return _vs_applied[size]
183
184
185def _draw_vs(tools, spirv, name, size, tmp):
186 """(records, heap) of one vertex draw at `size` (None: as the environment says), or (None, message)."""
187 env = dict(os.environ, **FIXTURES[name][2])
188 if size:
189 env["RADV_PERFTEST"] = _radv_perftest(size)
190 raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap"
191 env.update(VKH_VERTICES=str(VS_VERTICES), VKH_HEAP_DUMP=str(heap))
192 env.pop("VKH_SUBGROUP_SIZE", None)
193 # The triangles have zero area, so no pixel is drawn and any fragment shader does.
194 cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, name + ".spv"),
195 os.path.join(spirv, "ps_w64_a_skip.spv"), str(raw)]
196 r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120)
197 out = r.stdout + r.stderr
198 if r.returncode == UNSUPPORTED:
199 return None, "unsupported: " + out.strip().splitlines()[-1]
200 if r.returncode or not heap.is_file():
201 return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}"
202 words = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes()))
203 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(VS_VERTICES)], words
204
127 205
128def draw(tools, spirv, name, size, tmp): 206def draw(tools, spirv, name, size, tmp):
129 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size 207 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size
130 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message.""" 208 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message."""
131 tier, expect, extra = FIXTURES[name] 209 tier, expect, extra = FIXTURES[name]
210 if name.startswith("vs_"):
211 words, heap = _draw_vs(tools, spirv, name, size, tmp)
212 if words is None:
213 return None, heap, None
214 return words, heap, _vs_wave_size(tools, spirv, size, tmp) if size else None
132 env = dict(os.environ, **extra) 215 env = dict(os.environ, **extra)
133 env.pop("VKH_SUBGROUP_SIZE", None) 216 env.pop("VKH_SUBGROUP_SIZE", None)
134 if size: 217 if size:
@@ -168,15 +251,16 @@ def expected_problem(name, words, heap):
168 if wrong: 251 if wrong:
169 i, w, want = wrong[0] 252 i, w, want = wrong[0]
170 return f"{len(wrong)} of {len(words)} pixels differ from the derived words, first ({_x(i)},{_y(i)}): got {w}, want {want}" 253 return f"{len(wrong)} of {len(words)} pixels differ from the derived words, first ({_x(i)},{_y(i)}): got {w}, want {want}"
171 if name == "ps_w64_b_ballot_atomic": 254 if name.endswith("_b_ballot_atomic"):
172 want = sorted(_y(i) * W + _x(i) + 1 for i in range(W * H) if _x(i) % 4 == 1) 255 want = sorted(i + 1 for i in range(len(words)) if _x(i) % 4 == 1)
173 n = len(want) 256 n = len(want)
174 if heap[0] != n: 257 if heap[0] != n:
175 return f"counter is {heap[0]}, want {n}" 258 return f"counter is {heap[0]}, want {n}"
176 slots = heap[64:64 + n] 259 slots = heap[64:64 + n]
177 if sorted(slots) != want: 260 if sorted(slots) != want:
178 return f"slot words are not the {n} wanted pixel numbers once each ({len(set(slots))} distinct)" 261 return f"slot words are not the {n} wanted pixel numbers once each ({len(set(slots))} distinct)"
179 if any(heap[64 + n:]) or any(heap[1:64]): 262 end = VS_RECORDS if name.startswith("vs_") else len(heap) # the vertex records follow the slots
263 if any(heap[64 + n:end]) or any(heap[1:64]):
180 return "words outside the counter and the slots were written" 264 return "words outside the counter and the slots were written"
181 return "" 265 return ""
182 266
@@ -184,7 +268,7 @@ def expected_problem(name, words, heap):
184def comparable(name, words, heap): 268def comparable(name, words, heap):
185 """What two draws of the same fixture must share when the shader is partition invariant.""" 269 """What two draws of the same fixture must share when the shader is partition invariant."""
186 stable = [tuple(0 if g is None else v for g, v in zip(FIXTURES[name][1](i), w)) for i, w in enumerate(words)] 270 stable = [tuple(0 if g is None else v for g, v in zip(FIXTURES[name][1](i), w)) for i, w in enumerate(words)]
187 if name == "ps_w64_b_ballot_atomic": 271 if name.endswith("_b_ballot_atomic"):
188 return stable, sorted(heap[64:64 + heap[0]]), heap[0] 272 return stable, sorted(heap[64:64 + heap[0]]), heap[0]
189 return stable, None, None 273 return stable, None, None
190 274
@@ -240,7 +324,7 @@ def check(tools, spirv, name):
240 if not partition_dependent(name, ref_words, words): 324 if not partition_dependent(name, ref_words, words):
241 return "tier C but the run equals the 64-lane reference: the detector is wrong" 325 return "tier C but the run equals the 64-lane reference: the detector is wrong"
242 compared = True 326 compared = True
243 elif name != "ps_w64_b_ballot_atomic" and comparable(name, ref_words, None) != comparable(name, words, None): 327 elif not name.endswith("_b_ballot_atomic") and comparable(name, ref_words, None) != comparable(name, words, None):
244 return "the run differs from the 64-lane reference" 328 return "the run differs from the 64-lane reference"
245 if tier == "C" and not compared: 329 if tier == "C" and not compared:
246 return Skip("SKIP (tier C needs a device that can require both 64 and 32, or W64G_REF)") 330 return Skip("SKIP (tier C needs a device that can require both 64 and 32, or W64G_REF)")
diff --git a/runtime/test/typeless_rtv_test.cpp b/runtime/test/typeless_rtv_test.cpp
index be935c123..87fa46acb 100644
--- a/runtime/test/typeless_rtv_test.cpp
+++ b/runtime/test/typeless_rtv_test.cpp
@@ -262,9 +262,27 @@ int main() {
262 EXPECT(rejects(wrong, {1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, ReplayResult::invalid_subresource)); 262 EXPECT(rejects(wrong, {1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, ReplayResult::invalid_subresource));
263 wrong = binding; wrong.volume = true; 263 wrong = binding; wrong.volume = true;
264 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb})); 264 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb}));
265 wrong = binding; wrong.samples = 4; 265 {
266 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_uint})); 266 auto msaa = binding; msaa.samples = 4;
267 checks += 8; 267 for (const auto [format, expected] : formats) {
268 CommandList ms_list;
269 EXPECT(ms_list.clear_render_target({1, 0, 0, 1, format}, color) && ms_list.close());
270 EXPECT(run(ms_list, msaa, vk) == ReplayResult::success);
271 const bool attachment = format != ColorViewFormat::rgba8_unorm;
272 EXPECT(image_clears == (attachment ? 0u : 1u) && attachment_clears == (attachment ? 1u : 0u));
273 EXPECT(!attachment || (requested_format == expected && rendering_layers == 1));
274 ++checks;
275 }
276 auto msaa_layered = layered; msaa_layered.mip_levels = 1; msaa_layered.samples = 4;
277 CommandList ms_layer_list;
278 EXPECT(ms_layer_list.clear_render_target({1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, color) &&
279 ms_layer_list.close());
280 EXPECT(run(ms_layer_list, msaa_layered, vk) == ReplayResult::success);
281 EXPECT(attachment_clears == 1 && requested_format == VK_FORMAT_R8G8B8A8_SRGB);
282 EXPECT(requested_range.baseArrayLayer == 1 && requested_range.layerCount == 2 && rendering_layers == 2);
283 ++checks;
284 }
285 checks += 7;
268 CommandList list; 286 CommandList list;
269 EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color) && list.close()); 287 EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color) && list.close());
270 auto unavailable = vk; unavailable.begin_rendering = nullptr; 288 auto unavailable = vk; unavailable.begin_rendering = nullptr;
diff --git a/runtime/test/vk_bc_zero_init_test.cpp b/runtime/test/vk_bc_zero_init_test.cpp
new file mode 100644
index 000000000..6edc36fcb
--- /dev/null
+++ b/runtime/test/vk_bc_zero_init_test.cpp
@@ -0,0 +1,388 @@
1// Committed block-compressed (BC*) texture zero-initialization regression (D3D-220, #1725):
2// D3D12 committed textures start zeroed unless D3D12_HEAP_FLAG_CREATE_NOT_ZEROED is set. Vulkan forbids
3// vkCmdClearColorImage on BC formats, so detail::initialize() must zero-fill them via vkCmdCopyBufferToImage
4// from either the device zero page (vk.zero_buffer) or a zeroed transfer-scratch chunk (vk.copy_scratch).
5//
6// Cases (all on explicitly poisoned 0x5A backing memory when host-visible, plus default device memory):
7// 1. Path A (vk.zero_buffer): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4) — untouched blocks are 0x00.
8// 2. Path A (vk.zero_buffer): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips — mip 1 untouched block (bytes 56..63) is 0x00.
9// 3. Path A (tiny 32-byte vk.zero_buffer): 32x32 BC7 image tiled in multiple row/column chunks — all 1024 bytes are 0x00.
10// 4. Path B (enable_copy_scratch, no zero_buffer — matches d3d12_copy_xfmt): both D3D-220 cases match bit for bit.
11// 5. not_zeroed = true (CREATE_NOT_ZEROED): zero-fill is skipped.
12// Skips with exit code 77 when no Vulkan 1.3 device with textureCompressionBC is available. No game data.
13#include "vk_test_device.h"
14#include "../src/vulkan_backend.h"
15
16#include <algorithm>
17#include <cstdint>
18#include <cstdio>
19#include <cstring>
20#include <vector>
21
22#define EXPECT(condition) do { \
23 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
24} while (0)
25
26namespace {
27
28struct OwnedImage {
29 VkDevice device = VK_NULL_HANDLE;
30 PFN_vkDestroyImage destroy_image = nullptr;
31 PFN_vkFreeMemory free_memory = nullptr;
32 VkImage image = VK_NULL_HANDLE;
33 VkDeviceMemory memory = VK_NULL_HANDLE;
34 bool poisoned = false;
35
36 ~OwnedImage() {
37 if (image && destroy_image) destroy_image(device, image, nullptr);
38 if (memory && free_memory) free_memory(device, memory, nullptr);
39 }
40 OwnedImage(const OwnedImage&) = delete;
41 OwnedImage& operator=(const OwnedImage&) = delete;
42 OwnedImage() = default;
43};
44
45bool create_image(const vktest::Device& d, VkFormat format, std::uint32_t width, std::uint32_t height,
46 std::uint32_t mips, VkBuffer poison_buf, OwnedImage& out) {
47 out.device = d.device;
48 out.destroy_image = d.fn<PFN_vkDestroyImage>("vkDestroyImage");
49 out.free_memory = d.fn<PFN_vkFreeMemory>("vkFreeMemory");
50
51 VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
52 info.imageType = VK_IMAGE_TYPE_2D;
53 info.format = format;
54 info.extent = {width, height, 1};
55 info.mipLevels = mips;
56 info.arrayLayers = 1;
57 info.samples = VK_SAMPLE_COUNT_1_BIT;
58 info.tiling = VK_IMAGE_TILING_OPTIMAL;
59 info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
60 if (d.fn<PFN_vkCreateImage>("vkCreateImage")(d.device, &info, nullptr, &out.image) != VK_SUCCESS) return false;
61
62 VkMemoryRequirements req{};
63 d.fn<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(d.device, out.image, &req);
64 VkPhysicalDeviceMemoryProperties mp{};
65 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
66
67 std::uint32_t type = UINT32_MAX;
68 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
69 if (!(req.memoryTypeBits & (1u << i))) continue;
70 if (type == UINT32_MAX) type = i;
71 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
72 type = i;
73 break;
74 }
75 }
76 if (type == UINT32_MAX) return false;
77
78 VkMemoryAllocateInfo alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
79 alloc.allocationSize = req.size;
80 alloc.memoryTypeIndex = type;
81 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &alloc, nullptr, &out.memory) != VK_SUCCESS)
82 return false;
83 if (d.fn<PFN_vkBindImageMemory>("vkBindImageMemory")(d.device, out.image, out.memory, 0) != VK_SUCCESS)
84 return false;
85
86 // Pre-fill every mip on the GPU with 0x5A so stale recycled VRAM is modeled deterministically on every GPU
87 // (discrete and integrated alike), before registering the image in LayoutTracker as UNDEFINED.
88 if (poison_buf) {
89 const bool ok = const_cast<vktest::Device&>(d).run([&](VkCommandBuffer cb) {
90 VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
91 to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
92 to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
93 to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
94 to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
95 to_dst.image = out.image;
96 to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1};
97 d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
98 VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
99 nullptr, 1, &to_dst);
100 std::vector<VkBufferImageCopy> regions;
101 for (std::uint32_t m = 0; m < mips; ++m) {
102 VkBufferImageCopy r{};
103 r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, m, 0, 1};
104 r.imageExtent = {std::max(1u, width >> m), std::max(1u, height >> m), 1};
105 regions.push_back(r);
106 }
107 d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage")(
108 cb, poison_buf, out.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, std::uint32_t(regions.size()),
109 regions.data());
110 return true;
111 });
112 if (!ok) return false;
113 out.poisoned = true;
114 }
115 return true;
116}
117
118VkDeviceMemory allocate_device_local(const vktest::Device& d, const VkMemoryRequirements& req) {
119 VkPhysicalDeviceMemoryProperties mp{};
120 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp);
121 std::uint32_t chosen = UINT32_MAX;
122 for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) {
123 if (!(req.memoryTypeBits & (1u << i))) continue;
124 if (chosen == UINT32_MAX) chosen = i;
125 if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
126 chosen = i;
127 break;
128 }
129 }
130 if (chosen == UINT32_MAX) return VK_NULL_HANDLE;
131 VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
132 info.allocationSize = req.size;
133 info.memoryTypeIndex = chosen;
134 VkDeviceMemory mem = VK_NULL_HANDLE;
135 if (d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &info, nullptr, &mem) != VK_SUCCESS)
136 return VK_NULL_HANDLE;
137 return mem;
138}
139
140// Runs the two D3D-220 partial uncompressed -> BC1 copies on a given context/queue:
141// (a) CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)
142// (b) CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips
143int run_d3d220_cases(const vktest::Device& d, leonida::VulkanContext& ctx, leonida::VulkanQueue& q,
144 VkBuffer poison_buf, VkBuffer up_buf, void* up_ptr, VkBuffer rb_buf, void* rb_ptr,
145 const char* label) {
146 using namespace leonida;
147
148 auto* up = static_cast<std::uint8_t*>(up_ptr);
149 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
150 for (std::size_t i = 0; i < 4096; ++i) up[i] = static_cast<std::uint8_t>(i * 7 + 3);
151
152 // Case (a): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4).
153 // Destination has 4x4 BC1 blocks (8 bytes/block). Only blocks (2,1), (3,1), (2,2), (3,2) are written;
154 // the other 12 blocks (including block (0,0) at byte 0) must be 0x00.
155 {
156 OwnedImage src_img, dst_img;
157 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 2, 2, 1, VK_NULL_HANDLE, src_img));
158 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, dst_img));
159
160 ResourceBinding src_rb{};
161 src_rb.image = src_img.image;
162 src_rb.format = VK_FORMAT_R32G32_UINT;
163 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
164 src_rb.width = 2; src_rb.height = 2; src_rb.mip_levels = 1; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
165
166 ResourceBinding dst_rb{};
167 dst_rb.image = dst_img.image;
168 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
169 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
170 dst_rb.width = 16; dst_rb.height = 16; dst_rb.mip_levels = 1; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
171
172 ctx.add_resource(10, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
173 ctx.add_resource(11, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
174 std::memset(rb, 0xCD, 4096);
175
176 CommandList list;
177 CopyLocation up_loc{1, true, 0, 0, 2, 2, 1, 256};
178 CopyLocation src_loc{10, false, 0, 0, 0, 0, 0, 0};
179 CopyLocation dst_loc{11, false, 0, 0, 0, 0, 0, 0};
180 CopyLocation rb_loc{2, true, 0, 0, 16, 16, 1, 256};
181 EXPECT(list.copy_texture({src_loc, 0, 0, 0, up_loc, false, {}}));
182 EXPECT(list.transition({10, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
183 EXPECT(list.copy_texture({dst_loc, 8, 4, 0, src_loc, false, {}}));
184 EXPECT(list.transition({11, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
185 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, dst_loc, false, {}}));
186 EXPECT(list.close());
187
188 const CommandList* ptr = &list;
189 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
190 EXPECT(q.idle());
191
192 // Check every 8-byte block across the 4x4 block grid (row pitch 256).
193 for (std::uint32_t by = 0; by < 4; ++by) {
194 for (std::uint32_t bx = 0; bx < 4; ++bx) {
195 const std::uint8_t* got = rb + std::size_t(by) * 256 + std::size_t(bx) * 8;
196 if (bx >= 2 && bx < 4 && by >= 1 && by < 3) {
197 const std::uint8_t* want = up + std::size_t(by - 1) * 256 + std::size_t(bx - 2) * 8;
198 EXPECT(std::memcmp(got, want, 8) == 0);
199 } else {
200 for (int k = 0; k < 8; ++k) EXPECT(got[k] == 0x00);
201 }
202 }
203 }
204 ctx.remove_resource(10);
205 ctx.remove_resource(11);
206 }
207
208 // Case (b): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips.
209 // Mip 0: 3x2 -> 12x8 (3x2 = 6 blocks written).
210 // Mip 1: 1x1 -> 6x4 (2x1 = 2 blocks; block 0 is written, block 1 at bytes 8..15 of mip 1 is untouched -> 0x00).
211 {
212 OwnedImage src_img, dst_img;
213 EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 3, 2, 2, VK_NULL_HANDLE, src_img));
214 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 12, 8, 2, poison_buf, dst_img));
215
216 ResourceBinding src_rb{};
217 src_rb.image = src_img.image;
218 src_rb.format = VK_FORMAT_R32G32_UINT;
219 src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
220 src_rb.width = 3; src_rb.height = 2; src_rb.mip_levels = 2; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1;
221
222 ResourceBinding dst_rb{};
223 dst_rb.image = dst_img.image;
224 dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
225 dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
226 dst_rb.width = 12; dst_rb.height = 8; dst_rb.mip_levels = 2; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1;
227
228 ctx.add_resource(12, src_rb, VK_IMAGE_LAYOUT_UNDEFINED);
229 ctx.add_resource(13, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED);
230 std::memset(rb, 0xCD, 4096);
231
232 // Upload mip 0 at offset 0 (2 rows * 256 = 512 bytes) and mip 1 at offset 512 (1 row * 256).
233 CommandList list;
234 CopyLocation up0{1, true, 0, 0, 3, 2, 1, 256};
235 CopyLocation up1{1, true, 0, 512, 1, 1, 1, 256};
236 CopyLocation src0{12, false, 0, 0, 0, 0, 0, 0};
237 CopyLocation src1{12, false, 1, 0, 0, 0, 0, 0};
238 CopyLocation dst0{13, false, 0, 0, 0, 0, 0, 0};
239 CopyLocation dst1{13, false, 1, 0, 0, 0, 0, 0};
240 CopyLocation rb0{2, true, 0, 0, 12, 8, 1, 256};
241 CopyLocation rb1{2, true, 0, 512, 6, 4, 1, 256};
242 EXPECT(list.copy_texture({src0, 0, 0, 0, up0, false, {}}));
243 EXPECT(list.copy_texture({src1, 0, 0, 0, up1, false, {}}));
244 EXPECT(list.transition({12, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
245 EXPECT(list.copy_resource({13, 12}));
246 EXPECT(list.transition({13, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
247 EXPECT(list.copy_texture({rb0, 0, 0, 0, dst0, false, {}}));
248 EXPECT(list.copy_texture({rb1, 0, 0, 0, dst1, false, {}}));
249 EXPECT(list.close());
250
251 const CommandList* ptr = &list;
252 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
253 EXPECT(q.idle());
254
255 // Mip 0: 2 rows of 3 blocks (24 bytes per row).
256 EXPECT(std::memcmp(rb + 0, up + 0, 24) == 0);
257 EXPECT(std::memcmp(rb + 256, up + 256, 24) == 0);
258 // Mip 1: block 0 (bytes 0..7) matches up + 512; untouched block 1 (bytes 8..15) must be 0x00.
259 EXPECT(std::memcmp(rb + 512, up + 512, 8) == 0);
260 for (int k = 8; k < 16; ++k) EXPECT(rb[512 + k] == 0x00);
261
262 ctx.remove_resource(12);
263 ctx.remove_resource(13);
264 }
265
266 (void)up_buf;
267 (void)rb_buf;
268 std::printf("bc zero-init (%s): partial CopyTextureRegion and 2-mip CopyResource ok\n", label);
269 return 0;
270}
271
272} // namespace
273
274int main() {
275 using namespace leonida;
276
277 vktest::Device d;
278 if (!d.create(false) || !d.bc) {
279 std::fprintf(stderr, "vk_bc_zero_init_test: no Vulkan 1.3 device with BC support, skipped\n");
280 return 77;
281 }
282
283 void* up_ptr = nullptr;
284 void* rb_ptr = nullptr;
285 void* zero_ptr = nullptr;
286 void* poison_ptr = nullptr;
287 const VkBuffer up_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_ptr);
288 const VkBuffer rb_buf = d.buffer(8192, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_ptr);
289 const VkBuffer zero_buf = d.buffer(65536, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &zero_ptr);
290 const VkBuffer poison_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &poison_ptr);
291 EXPECT(up_buf && rb_buf && zero_buf && poison_buf);
292 std::memset(zero_ptr, 0, 65536);
293 std::memset(poison_ptr, 0x5A, 4096);
294
295 ResourceBinding up_rb{};
296 up_rb.buffer = up_buf;
297 up_rb.size = 4096;
298 ResourceBinding rb_rb{};
299 rb_rb.buffer = rb_buf;
300 rb_rb.size = 8192;
301 rb_rb.host_readable = true;
302
303 // Path A: device arena zero page (vk.zero_buffer).
304 {
305 VulkanContext ctx(d.device_proc, d.device, true);
306 EXPECT(ctx.loaded());
307 ctx.set_zero_page(zero_buf, 0, 65536);
308 ctx.add_resource(1, up_rb);
309 ctx.add_resource(2, rb_rb);
310 VulkanQueue q(ctx, d.queue, d.family);
311 EXPECT(q.ok());
312 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "zero_buffer") == 0);
313
314 // Multi-tile chunking: shrink zero_page to 32 bytes (2 BC7 blocks) and zero-init a 32x32 BC7 image (64 blocks).
315 ctx.set_zero_page(zero_buf, 16, 32);
316 OwnedImage bc7_img;
317 EXPECT(create_image(d, VK_FORMAT_BC7_UNORM_BLOCK, 32, 32, 1, poison_buf, bc7_img));
318 ResourceBinding bc7_rb{};
319 bc7_rb.image = bc7_img.image;
320 bc7_rb.format = VK_FORMAT_BC7_UNORM_BLOCK;
321 bc7_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
322 bc7_rb.width = 32; bc7_rb.height = 32; bc7_rb.mip_levels = 1; bc7_rb.array_layers = 1; bc7_rb.depth = 1; bc7_rb.samples = 1;
323 ctx.add_resource(20, bc7_rb, VK_IMAGE_LAYOUT_UNDEFINED);
324 std::memset(rb_ptr, 0xCD, 8192);
325
326 CommandList list;
327 EXPECT(list.transition({20, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
328 CopyLocation bc7_loc{20, false, 0, 0, 0, 0, 0, 0};
329 CopyLocation rb_loc{2, true, 0, 0, 32, 32, 1, 256};
330 EXPECT(list.copy_texture({rb_loc, 0, 0, 0, bc7_loc, false, {}}));
331 EXPECT(list.close());
332 const CommandList* ptr = &list;
333 EXPECT(q.execute({&ptr, 1}) == ReplayResult::success);
334 EXPECT(q.idle());
335
336 auto* rb = static_cast<std::uint8_t*>(rb_ptr);
337 for (std::uint32_t row = 0; row < 8; ++row)
338 for (std::uint32_t x = 0; x < 8 * 16; ++x)
339 EXPECT(rb[row * 256 + x] == 0x00);
340 ctx.remove_resource(20);
341 std::printf("bc zero-init (tiny 32-byte zero_buffer chunking on 32x32 BC7): ok\n");
342
343 // CREATE_NOT_ZEROED (not_zeroed = true) must skip zero-fill.
344 ctx.set_zero_page(zero_buf, 0, 65536);
345 OwnedImage nz_img;
346 EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, nz_img));
347 EXPECT(nz_img.poisoned);
348 ResourceBinding nz_rb{};
349 nz_rb.image = nz_img.image;
350 nz_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
351 nz_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
352 nz_rb.width = 16; nz_rb.height = 16; nz_rb.mip_levels = 1; nz_rb.array_layers = 1; nz_rb.depth = 1; nz_rb.samples = 1;
353 nz_rb.not_zeroed = true;
354 ctx.add_resource(21, nz_rb, VK_IMAGE_LAYOUT_UNDEFINED);
355 std::memset(rb_ptr, 0xCD, 8192);
356
357 CommandList nz_list;
358 EXPECT(nz_list.transition({21, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source}));
359 CopyLocation nz_loc{21, false, 0, 0, 0, 0, 0, 0};
360 CopyLocation nz_rb_loc{2, true, 0, 0, 16, 16, 1, 256};
361 EXPECT(nz_list.copy_texture({nz_rb_loc, 0, 0, 0, nz_loc, false, {}}));
362 EXPECT(nz_list.close());
363 const CommandList* nz_ptr = &nz_list;
364 EXPECT(q.execute({&nz_ptr, 1}) == ReplayResult::success);
365 EXPECT(q.idle());
366 EXPECT(rb[0] == 0x5A);
367 ctx.remove_resource(21);
368 std::printf("bc zero-init (not_zeroed = true skips zero-fill): ok\n");
369 }
370
371 // Path B: copy_scratch + vkCmdFillBuffer fallback (no zero_buffer, matching d3d12_copy_xfmt without BDA).
372 {
373 VulkanContext ctx(d.device_proc, d.device, true);
374 EXPECT(ctx.loaded());
375 ctx.enable_copy_scratch(d.device_proc, [&](const VkMemoryRequirements& req) {
376 return allocate_device_local(d, req);
377 });
378 ctx.add_resource(1, up_rb);
379 ctx.add_resource(2, rb_rb);
380 VulkanQueue q(ctx, d.queue, d.family);
381 EXPECT(q.ok());
382 EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "copy_scratch") == 0);
383 }
384
385 EXPECT(d.validation_errors() == 0);
386 std::printf("vk_bc_zero_init_test: ok\n");
387 return 0;
388}
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 73ac39013..041f6f648 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -24,6 +24,7 @@
24#include "vk_shader_fma.h" 24#include "vk_shader_fma.h"
25#include "../src/vulkan_bindless.h" 25#include "../src/vulkan_bindless.h"
26 26
27#include <algorithm>
27#include <array> 28#include <array>
28#include <cmath> 29#include <cmath>
29#include <cstdio> 30#include <cstdio>
@@ -105,7 +106,7 @@ std::uint32_t probe_depth(std::span<const std::uint32_t> table, const Descriptor
105 106
106int main(int argc, char** argv) { 107int main(int argc, char** argv) {
107 if (argc < 3) { 108 if (argc < 3) {
108 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv>\n"); 109 std::fprintf(stderr, "usage: vk_bindless_test <vs_ids.spv> <ps_tex.spv | ps_imgatomic.spv>\n");
109 return 2; 110 return 2;
110 } 111 }
111 // A bad readback in a single channel must still fail when all three others match. 112 // A bad readback in a single channel must still fail when all three others match.
@@ -225,6 +226,15 @@ int main(int argc, char** argv) {
225 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; 226 VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12};
226 enable.features.shaderInt64 = VK_TRUE; 227 enable.features.shaderInt64 = VK_TRUE;
227 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; 228 enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
229 // ps_imgatomic: image atomics in a pixel shader need fragment stores and atomics.
230 const bool atomic_mode = std::strstr(argv[2], "imgatomic") != nullptr;
231 if (atomic_mode) {
232 if (!have.features.fragmentStoresAndAtomics) {
233 std::printf("unsupported: fragmentStoresAndAtomics (image atomics in a pixel shader)\n");
234 return unsupported;
235 }
236 enable.features.fragmentStoresAndAtomics = VK_TRUE;
237 }
228 238
229 std::uint32_t qn = 0; 239 std::uint32_t qn = 0;
230 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); 240 vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
@@ -260,7 +270,7 @@ int main(int argc, char** argv) {
260 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); 270 LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout);
261 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); 271 LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass);
262 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); 272 LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer);
263 LD(vkFreeMemory); LD(vkDestroyDevice); 273 LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage);
264 VkQueue queue = VK_NULL_HANDLE; 274 VkQueue queue = VK_NULL_HANDLE;
265 vkGetDeviceQueue(dev, qi, 0, &queue); 275 vkGetDeviceQueue(dev, qi, 0, &queue);
266 VkPhysicalDeviceMemoryProperties mp; 276 VkPhysicalDeviceMemoryProperties mp;
@@ -663,6 +673,171 @@ int main(int argc, char** argv) {
663 const std::uint32_t sampler_index = set.add_sampler(nearest); 673 const std::uint32_t sampler_index = set.add_sampler(nearest);
664 EXPECT(decoy_sampler == 1 && sampler_index == 2); 674 EXPECT(decoy_sampler == 1 && sampler_index == 2);
665 675
676 if (atomic_mode) {
677 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from
678 // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd
679 // pixels are discarded after their atomics, which still count.
680 constexpr std::uint32_t atomic_va = 1024, AW = 8, A3 = 4;
681 const std::array<DescriptorKey, 4> keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8},
682 {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8},
683 {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8},
684 {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}};
685 for (std::uint32_t k = 0; k < 4; ++k)
686 std::memcpy(static_cast<char*>(heap_map) + atomic_va + 32 * k, keys[k].data(), 32);
687 const VkImageUsageFlags atomic_usage =
688 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
689 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
690 VkImage images[4];
691 VkImageView views[4];
692 for (int k = 0; k < 3; ++k) CHECK(make_image(VK_FORMAT_R32_UINT, AW, AW, atomic_usage, &images[k], &views[k]));
693 { // the 3D image
694 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
695 ii.imageType = VK_IMAGE_TYPE_3D;
696 ii.format = VK_FORMAT_R32_UINT;
697 ii.extent = {A3, A3, A3};
698 ii.mipLevels = 1;
699 ii.arrayLayers = 1;
700 ii.samples = VK_SAMPLE_COUNT_1_BIT;
701 ii.usage = atomic_usage;
702 CHECK(vkCreateImage(dev, &ii, nullptr, &images[3]));
703 VkMemoryRequirements mr;
704 vkGetImageMemoryRequirements(dev, images[3], &mr);
705 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
706 ai.allocationSize = mr.size;
707 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
708 VkDeviceMemory m;
709 CHECK(vkAllocateMemory(dev, &ai, nullptr, &m));
710 allocations.push_back(m);
711 CHECK(vkBindImageMemory(dev, images[3], m, 0));
712 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
713 vi.image = images[3];
714 vi.viewType = VK_IMAGE_VIEW_TYPE_3D;
715 vi.format = VK_FORMAT_R32_UINT;
716 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
717 CHECK(vkCreateImageView(dev, &vi, nullptr, &views[3]));
718 }
719 std::uint32_t indices[4];
720 for (int k = 0; k < 4; ++k) {
721 StorageViews storage;
722 storage.as_uint = views[k];
723 storage.r32ui = views[k];
724 indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k],
725 VK_IMAGE_LAYOUT_GENERAL, storage);
726 EXPECT(indices[k] != 0);
727 EXPECT(set.insert_key(keys[k], indices[k]));
728 }
729 EXPECT(flush());
730
731 // Clear: umax and or start at 0, umin at all ones; then GENERAL for the shader's atomics.
732 CHECK(vkResetCommandBuffer(cmd, 0));
733 CHECK(vkBeginCommandBuffer(cmd, &begin));
734 if (!set.fallbacks_ready()) set.record_fallback_init(cmd);
735 for (int k = 0; k < 4; ++k) {
736 VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
737 b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
738 b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
739 b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
740 b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
741 b.image = images[k];
742 b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
743 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
744 nullptr, 0, nullptr, 1, &b);
745 VkClearColorValue value{};
746 for (auto& c : value.uint32) c = k == 1 ? 0xFFFFFFFFu : 0u;
747 vkCmdClearColorImage(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, &value, 1, &b.subresourceRange);
748 b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
749 b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
750 b.oldLayout = b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
751 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0,
752 nullptr, 0, nullptr, 1, &b);
753 }
754 CHECK(submit());
755
756 // The draw, then the images and the render target read back.
757 const VkDeviceSize image_bytes = 3 * AW * AW * 4 + A3 * A3 * A3 * 4;
758 VkBuffer atomic_readback;
759 void* atomic_map;
760 CHECK(make_buffer(image_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &atomic_readback, &atomic_map));
761 CHECK(vkResetCommandBuffer(cmd, 0));
762 CHECK(vkBeginCommandBuffer(cmd, &begin));
763 VkClearValue clear{};
764 for (float& channel : clear.color.float32) channel = 0.25f;
765 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
766 rbi.renderPass = pass;
767 rbi.framebuffer = framebuffer;
768 rbi.renderArea = scissor;
769 rbi.clearValueCount = 1;
770 rbi.pClearValues = &clear;
771 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
772 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
773 const VkDescriptorSet bound = set.set();
774 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr);
775 std::uint32_t block[36] = {};
776 block[2] = atomic_va;
777 block[32] = std::uint32_t(heap_base);
778 block[33] = std::uint32_t(heap_base >> 32);
779 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
780 sizeof(block), block);
781 vkCmdDraw(cmd, 3, 1, 0, 0);
782 vkCmdEndRenderPass(cmd);
783 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
784 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
785 after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
786 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after,
787 0, nullptr, 0, nullptr);
788 VkDeviceSize offset = 0;
789 for (int k = 0; k < 4; ++k) {
790 VkBufferImageCopy rc{};
791 rc.bufferOffset = offset;
792 rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
793 rc.imageExtent = k == 3 ? VkExtent3D{A3, A3, A3} : VkExtent3D{AW, AW, 1};
794 vkCmdCopyImageToBuffer(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, atomic_readback, 1, &rc);
795 offset += k == 3 ? A3 * A3 * A3 * 4 : AW * AW * 4;
796 }
797 VkBufferImageCopy tc{};
798 tc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
799 tc.imageExtent = {W, H, 1};
800 vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &tc);
801 CHECK(submit());
802
803 // The model: every pixel's atomics, discarded or not.
804 std::vector<std::uint32_t> want(3 * AW * AW + A3 * A3 * A3, 0);
805 for (std::uint32_t t = 0; t < AW * AW; ++t) want[AW * AW + t] = 0xFFFFFFFFu;
806 for (std::uint32_t py = 0; py < H; ++py)
807 for (std::uint32_t px = 0; px < W; ++px) {
808 const std::uint32_t id = px + 64 * py, t = (py >> 3) * AW + (px >> 3);
809 want[t] = std::max(want[t], id);
810 want[AW * AW + t] = std::min(want[AW * AW + t], id);
811 want[2 * AW * AW + t] |= 1u << (id & 31);
812 const std::uint32_t v = ((px & 3) * A3 + (py >> 4)) * A3 + (px >> 4);
813 want[3 * AW * AW + v] = std::max(want[3 * AW * AW + v], id);
814 }
815 const auto* got = static_cast<const std::uint32_t*>(atomic_map);
816 const char* names[] = {"2D umax", "2D umin", "2D or", "3D umax"};
817 unsigned wrong = 0;
818 for (std::size_t i = 0; i < want.size(); ++i) {
819 if (got[i] == want[i]) continue;
820 const int k = i < 3 * AW * AW ? int(i / (AW * AW)) : 3;
821 if (wrong++ < 8)
822 std::printf(" %s texel %zu: got 0x%08x, want 0x%08x\n", names[k],
823 k == 3 ? i - 3 * AW * AW : i % (AW * AW), got[i], want[i]);
824 }
825 const float* rt = static_cast<const float*>(readback_map);
826 unsigned bad_rt = 0;
827 for (std::uint32_t py = 0; py < H; ++py)
828 for (std::uint32_t px = 0; px < W; ++px)
829 bad_rt += rt[(py * W + px) * 4] != ((px & 1) ? 0.25f : 1.0f);
830 std::printf("ps_imgatomic: %u of %zu texels wrong (2D umax/umin/or 8x8 each, 3D umax 4x4x4); "
831 "%u of %u render-target pixels wrong (odd columns discarded)\n",
832 wrong, want.size(), bad_rt, W * H);
833 vkDeviceWaitIdle(dev);
834 if (g_validation_errors) {
835 std::printf("ps_imgatomic: %u validation errors\n", g_validation_errors);
836 return 1;
837 }
838 return wrong || bad_rt ? 1 : 0;
839 }
840
666 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed 841 // A view that comes and goes before the set is flushed is never written: a texture created and destroyed
667 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view 842 // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view
668 // would be a validation error. 843 // would be a validation error.
@@ -727,7 +902,7 @@ int main(int argc, char** argv) {
727 // 2. Without its key the T# is a miss: index 0, the fallback image of zeros. 902 // 2. Without its key the T# is a miss: index 0, the fallback image of zeros.
728 const float zeros[4] = {0, 0, 0, 0}; 903 const float zeros[4] = {0, 0, 0, 0};
729 EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp)); 904 EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp));
730 EXPECT(set.flush_needs_idle()); // erasing may move the keys behind it; nothing is running here 905 EXPECT(!set.flush_needs_idle()); // erasing empties its slot only: the three keys ahead stay where they are
731 EXPECT(flush() && !set.flush_needs_idle()); 906 EXPECT(flush() && !set.flush_needs_idle());
732 CHECK(draw()); 907 CHECK(draw());
733 compare("2 miss", zeros); 908 compare("2 miss", zeros);
diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp
index 07be76abb..5f5e721c8 100644
--- a/runtime/test/vk_descriptor_bench.cpp
+++ b/runtime/test/vk_descriptor_bench.cpp
@@ -7,7 +7,7 @@
7// dispatch against CPU DescriptorTable::lookup() before timing. 7// dispatch against CPU DescriptorTable::lookup() before timing.
8// 8//
9// Usage: 9// Usage:
10// vk_descriptor_bench [--sizes 1000,10000,100000] [--groups 4096] [--iters 64] [--reps 25] [--warmup 5] 10// vk_descriptor_bench [--sizes 1000,10000,100000] [--groups 4096] [--iters 64] [--reps 25] [--warmup 5] [--warmup-ms 300]
11// [--memory all|device|host|rebar] [--device N] [--list-devices] [--quick] [--csv] 11// [--memory all|device|host|rebar] [--device N] [--list-devices] [--quick] [--csv]
12// [--dump-spv PREFIX] [--self-test] 12// [--dump-spv PREFIX] [--self-test]
13// LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation; any validation error fails the run. 13// LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation; any validation error fails the run.
@@ -969,6 +969,7 @@ struct Options {
969 std::uint32_t reps = 25u; 969 std::uint32_t reps = 25u;
970 std::uint32_t warmup = 5u; 970 std::uint32_t warmup = 5u;
971 double max_dispatch_ms = 120.0; 971 double max_dispatch_ms = 120.0;
972 double warmup_ms = 300.0; // keep running the timed dispatch until this much time has passed (0 = off)
972 std::optional<std::uint32_t> device_index; 973 std::optional<std::uint32_t> device_index;
973 MemoryFilter mem_filter = MemoryFilter::All; 974 MemoryFilter mem_filter = MemoryFilter::All;
974 bool list_devices = false; 975 bool list_devices = false;
@@ -985,6 +986,8 @@ void print_usage() {
985 " --iters N lookups per invocation per dispatch (default: 64)\n" 986 " --iters N lookups per invocation per dispatch (default: 64)\n"
986 " --reps N timed repetitions per scenario (default: 25)\n" 987 " --reps N timed repetitions per scenario (default: 25)\n"
987 " --warmup N warmup dispatches before timing (default: 5)\n" 988 " --warmup N warmup dispatches before timing (default: 5)\n"
989 " --warmup-ms F then keep dispatching until F ms have passed, so the GPU clocks are up before the\n"
990 " first timed run, 0=off (default: 300; --quick turns it off)\n"
988 " --max-dispatch-ms F auto-scale slow dispatches to avoid OS TDR, 0=off (default: 120)\n" 991 " --max-dispatch-ms F auto-scale slow dispatches to avoid OS TDR, 0=off (default: 120)\n"
989 " --memory MODE all|device|host|rebar (default: all)\n" 992 " --memory MODE all|device|host|rebar (default: all)\n"
990 " --device N select physical device index from --list-devices\n" 993 " --device N select physical device index from --list-devices\n"
@@ -1031,6 +1034,7 @@ bool parse_args(int argc, const char* const* argv, Options& opt, bool& show_help
1031 opt.groups = 16u; 1034 opt.groups = 16u;
1032 opt.iters = 4u; 1035 opt.iters = 4u;
1033 opt.warmup = 1u; 1036 opt.warmup = 1u;
1037 opt.warmup_ms = 0.0;
1034 opt.reps = 3u; 1038 opt.reps = 3u;
1035 } else if (arg == "--groups") { 1039 } else if (arg == "--groups") {
1036 const char* v = nullptr; 1040 const char* v = nullptr;
@@ -1051,6 +1055,13 @@ bool parse_args(int argc, const char* const* argv, Options& opt, bool& show_help
1051 const double val = std::strtod(v, &end); 1055 const double val = std::strtod(v, &end);
1052 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false; 1056 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false;
1053 opt.max_dispatch_ms = val; 1057 opt.max_dispatch_ms = val;
1058 } else if (arg == "--warmup-ms") {
1059 const char* v = nullptr;
1060 if (!need_val(v)) return false;
1061 char* end = nullptr;
1062 const double val = std::strtod(v, &end);
1063 if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false;
1064 opt.warmup_ms = val;
1054 } else if (arg == "--device") { 1065 } else if (arg == "--device") {
1055 const char* v = nullptr; 1066 const char* v = nullptr;
1056 std::uint32_t idx = 0u; 1067 std::uint32_t idx = 0u;
@@ -1164,6 +1175,19 @@ int run_self_test() {
1164 return 1; 1175 return 1;
1165 } 1176 }
1166 1177
1178 {
1179 const char* const ok_args[] = {"vk_descriptor_bench", "--warmup-ms", "0"};
1180 const char* const bad_args[] = {"vk_descriptor_bench", "--warmup-ms", "-1"};
1181 const char* const quick_args[] = {"vk_descriptor_bench", "--quick"};
1182 Options o_ok, o_bad, o_quick, o_default;
1183 bool h = false;
1184 if (o_default.warmup_ms != 300.0 || !parse_args(3, ok_args, o_ok, h) || o_ok.warmup_ms != 0.0 ||
1185 parse_args(3, bad_args, o_bad, h) || !parse_args(2, quick_args, o_quick, h) || o_quick.warmup_ms != 0.0) {
1186 std::fprintf(stderr, "self-test: --warmup-ms parsing or its default is wrong\n");
1187 return 1;
1188 }
1189 }
1190
1167 const struct { 1191 const struct {
1168 const char* name; 1192 const char* name;
1169 ShaderKind kind; 1193 ShaderKind kind;
@@ -2134,6 +2158,22 @@ int main(int argc, char** argv) {
2134 } 2158 }
2135 } 2159 }
2136 2160
2161 // A handful of dispatches is not enough to bring the clocks up on every GPU: with --warmup 5 an idle
2162 // RX 7600 measured the first placement ~1.8x slower than with --warmup 200, and the RTX 4050 ~1.3x
2163 // (TEST-277). Keep running the command that is about to be timed for --warmup-ms.
2164 if (opt.warmup_ms > 0.0) {
2165 const auto w0 = std::chrono::steady_clock::now();
2166 for (;;) {
2167 if (!submit_and_wait(bench_cmd)) {
2168 cleanup_all(keys_buf, map_buf);
2169 return 1;
2170 }
2171 const double spent =
2172 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
2173 if (spent >= opt.warmup_ms) break;
2174 }
2175 }
2176
2137 std::vector<double> samples_ms; 2177 std::vector<double> samples_ms;
2138 samples_ms.reserve(eff_reps); 2178 samples_ms.reserve(eff_reps);
2139 for (std::uint32_t r = 0; r < eff_reps; ++r) { 2179 for (std::uint32_t r = 0; r < eff_reps; ++r) {
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index f7f86fa51..360a20fa7 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -240,6 +240,17 @@ int main(int argc, char** argv) {
240 return 2; 240 return 2;
241 } 241 }
242 } 242 }
243 // Translated shaders declare a 144-byte push-constant block (user SGPRs, heap base, code base; see VKH_SGPRS /
244 // VKH_HEAP); --mesh-compute modules and their vertex shaders add the output address (152 bytes). A device with
245 // fewer bytes (128, the Vulkan minimum, as on some Intel Arc drivers and AMD's Windows driver for RDNA2 iGPUs)
246 // cannot take that range: declaring it anyway is invalid, and there a shader reading past the limit crashed or
247 // hung the device. 77, as vk_texture_test and vk_bindless_test: a device limit, not a wrong result (D3D-14).
248 const uint32_t pc_bytes = mesh_compute ? 152u : 144u;
249 if (props.limits.maxPushConstantsSize < pc_bytes) {
250 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes,
251 props.limits.maxPushConstantsSize);
252 return 77;
253 }
243 // VKH_MESH=1: the first shader is a mesh shader (VK_EXT_mesh_shader), drawn with vkCmdDrawMeshTasksEXT(1,1,1). 254 // VKH_MESH=1: the first shader is a mesh shader (VK_EXT_mesh_shader), drawn with vkCmdDrawMeshTasksEXT(1,1,1).
244 const bool mesh = !mesh_compute && (group_readback || std::getenv("VKH_MESH") != nullptr); 255 const bool mesh = !mesh_compute && (group_readback || std::getenv("VKH_MESH") != nullptr);
245 VkPhysicalDeviceMeshShaderFeaturesEXT meshf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 256 VkPhysicalDeviceMeshShaderFeaturesEXT meshf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
@@ -454,12 +465,11 @@ int main(int argc, char** argv) {
454 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; 465 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF;
455 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; 466 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
456 cb.attachmentCount = 1; cb.pAttachments = &cba; 467 cb.attachmentCount = 1; cb.pAttachments = &cba;
457 // Translated shaders declare a 144-byte push-constant block (user SGPRs, heap base, code base; see VKH_SGPRS / 468 // The push-constant block (pc_bytes, checked against the device limit above).
458 // VKH_HEAP); --mesh-compute modules and their vertex shaders add the output address (152 bytes).
459 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) | 469 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) |
460 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) | 470 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) |
461 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0); 471 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0);
462 VkPushConstantRange pcr{pcs, 0, mesh_compute ? 152u : 144u}; 472 VkPushConstantRange pcr{pcs, 0, pc_bytes};
463 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 473 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
464 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 474 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
465 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 475 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
@@ -564,7 +574,6 @@ int main(int argc, char** argv) {
564 std::memcpy(pc, shifts, sizeof(shifts)); 574 std::memcpy(pc, shifts, sizeof(shifts));
565 } 575 }
566 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants")); 576 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"));
567 const uint32_t pc_bytes = mesh_compute ? 152u : 144u;
568 if (mesh_compute) { 577 if (mesh_compute) {
569 // The mesh shader as compute, then make its stores visible to the vertex shader's reads. 578 // The mesh shader as compute, then make its stores visible to the vertex shader's reads.
570 LOADD(vkCmdDispatch); LOADD(vkCmdPipelineBarrier); 579 LOADD(vkCmdDispatch); LOADD(vkCmdPipelineBarrier);
@@ -591,7 +600,11 @@ int main(int argc, char** argv) {
591 } 600 }
592 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); 601 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
593 push(cmd, pl, pcs, 0, pc_bytes, pc); 602 push(cmd, pl, pcs, 0, pc_bytes, pc);
594 if (mesh_compute) 603 // VKH_VERTICES=<n>: draw n vertices instead of one triangle, so a vertex shader fills whole waves (TEST-251).
604 const char* vertices_env = std::getenv("VKH_VERTICES");
605 if (const unsigned vertices = vertices_env ? unsigned(std::strtoul(vertices_env, nullptr, 10)) : 0; vertices && !mesh)
606 vkCmdDraw(cmd, vertices, 1, 0, 0);
607 else if (mesh_compute)
595 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0); 608 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0);
596 else if (mesh) 609 else if (mesh)
597 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]); 610 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]);
diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp
index cc9372feb..2a510d33a 100644
--- a/runtime/test/vk_overlapping_occlusion_test.cpp
+++ b/runtime/test/vk_overlapping_occlusion_test.cpp
@@ -135,13 +135,14 @@ struct Draws {
135 std::vector<std::uint32_t> extents; 135 std::vector<std::uint32_t> extents;
136 std::size_t next = 0; 136 std::size_t next = 0;
137 bool overflow = false; 137 bool overflow = false;
138 bool every = false; // --bisect: one 1x1 draw before every end, no schedule 138 bool every = false; // --bisect: one 1x1 draw before every end, no schedule
139 bool no_draw = false; // --bisect --no-draw: no draws at all, every query stays empty
139}; 140};
140Draws* draws = nullptr; 141Draws* draws = nullptr;
141 142
142VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) { 143VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) {
143 if (draws->every) { 144 if (draws->every) {
144 draws->fixture.draw(cb, 1); 145 if (!draws->no_draw) draws->fixture.draw(cb, 1);
145 } else if (draws->next == draws->extents.size()) { 146 } else if (draws->next == draws->extents.size()) {
146 draws->overflow = true; 147 draws->overflow = true;
147 } else if (const auto extent = draws->extents[draws->next++]) { 148 } else if (const auto extent = draws->extents[draws->next++]) {
@@ -159,9 +160,13 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice device, const
159// submission is waited for before the next, so the last "running" line before a hang or a lost device names the 160// submission is waited for before the next, so the last "running" line before a hang or a lost device names the
160// pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named 161// pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named
161// phases run only those, in the order below. Only completion is checked, not values. 162// phases run only those, in the order below. Only completion is checked, not values.
163// Two switches separate the draw from the resolve: --no-draw leaves every query empty (no rendering scope inside
164// it), --no-resolve records the queries but never copies or sums their results.
162struct Bisect { 165struct Bisect {
163 bool enabled = false; 166 bool enabled = false;
164 bool gated = false; 167 bool gated = false;
168 bool no_draw = false;
169 bool no_resolve = false;
165 std::vector<std::string> phases; 170 std::vector<std::string> phases;
166 bool wants(const char* name) const { 171 bool wants(const char* name) const {
167 return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end(); 172 return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end();
@@ -184,8 +189,9 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
184 schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); 189 schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1);
185 // The statistics lists below: a split query (two segments), two unsplit references and a second split query. 190 // The statistics lists below: a split query (two segments), two unsplit references and a second split query.
186 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5}); 191 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5});
187 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0}); 192 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1});
188 schedule.every = bisect.enabled; 193 schedule.every = bisect.enabled;
194 schedule.no_draw = bisect.no_draw;
189 draws = &schedule; 195 draws = &schedule;
190 VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering); 196 VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering);
191 EXPECT(context.loaded()); 197 EXPECT(context.loaded());
@@ -236,30 +242,37 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
236 if (!bisect.wants(name)) return nullptr; 242 if (!bisect.wants(name)) return nullptr;
237 return &lists.emplace_back(name, CommandList{}).second; 243 return &lists.emplace_back(name, CommandList{}).second;
238 }; 244 };
245 const auto resolve = [&](CommandList* l, const ResolveQueries& r) {
246 return bisect.no_resolve || l->resolve_queries(r);
247 };
239 if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active 248 if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active
240 EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0})); 249 EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0}));
241 EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); 250 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1}));
242 EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 24})); 251 EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 24}));
252 }
253 if (auto* l = add("active")) { // a resolve inside one active query, without an overlap
254 EXPECT(l->begin_query({a, occ, 0}) && l->end_query({a, occ, 0}) && l->begin_query({a, occ, 3}));
255 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3}));
243 } 256 }
244 if (auto* l = add("nested")) { // the same index in two heaps, one inside the other 257 if (auto* l = add("nested")) { // the same index in two heaps, one inside the other
245 EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2})); 258 EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2}));
246 EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2})); 259 EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2}));
247 EXPECT(l->resolve_queries({a, occ, 2, 1, dst_id, 40}) && l->resolve_queries({b, occ, 2, 1, dst_id, 48})); 260 EXPECT(resolve(l, {a, occ, 2, 1, dst_id, 40}) && resolve(l, {b, occ, 2, 1, dst_id, 48}));
248 } 261 }
249 if (auto* l = add("unwritten")) { // a query never begun: zero fill 262 if (auto* l = add("unwritten")) { // a query never begun: zero fill
250 EXPECT(l->resolve_queries({b, occ, 0, 1, dst_id, 56})); 263 EXPECT(resolve(l, {b, occ, 0, 1, dst_id, 56}));
251 } 264 }
252 if (auto* l = add("binary")) { // the binary-occlusion compute resolve 265 if (auto* l = add("binary")) { // the binary-occlusion compute resolve
253 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); 266 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3}));
254 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); 267 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64}));
255 } 268 }
256 if (d.conditional_rendering) { 269 if (d.conditional_rendering) {
257 if (auto* l = add("predicated")) { // both compute resolves under a false predicate 270 if (auto* l = add("predicated")) { // both compute resolves under a false predicate
258 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); 271 EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3}));
259 EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero})); 272 EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero}));
260 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); 273 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64}));
261 EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 72})); 274 EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 72}));
262 EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 80})); 275 EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 80}));
263 EXPECT(copy_control.record(*l)); 276 EXPECT(copy_control.record(*l));
264 } 277 }
265 } 278 }
@@ -267,14 +280,24 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
267 EXPECT(l->begin_query({a, occ, 3})); 280 EXPECT(l->begin_query({a, occ, 3}));
268 for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0})); 281 for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0}));
269 EXPECT(l->end_query({a, occ, 3})); 282 EXPECT(l->end_query({a, occ, 3}));
270 EXPECT(l->resolve_queries({a, occ, 3, 1, dst_id, 88}) && l->resolve_queries({b, occ, 0, 1, dst_id, 96})); 283 EXPECT(resolve(l, {a, occ, 3, 1, dst_id, 88}) && resolve(l, {b, occ, 0, 1, dst_id, 96}));
271 } 284 }
272 if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved 285 if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved
273 for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}}) 286 for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}})
274 EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index})); 287 EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index}));
275 EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 112})); 288 EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 112}));
276 } 289 }
277 EXPECT(!lists.empty()); 290 EXPECT(!lists.empty());
291 std::printf("bisect:%s%s%s\n", bisect.gated ? " gated" : " ungated", bisect.no_draw ? " no-draw" : " draws",
292 bisect.no_resolve ? " no-resolve" : " resolves");
293 // After a TDR, AMD's Windows driver lets vkQueueWaitIdle succeed (#1540); every timeline semaphore then reads
294 // UINT64_MAX, so the gate's value is checked as well as what the context has seen.
295 const auto get_value = d.fn<PFN_vkGetSemaphoreCounterValue>("vkGetSemaphoreCounterValue");
296 const auto lost = [&] {
297 std::uint64_t value = 0;
298 return context.is_device_lost() || get_value(d.device, gate.semaphore(), &value) != VK_SUCCESS ||
299 value == UINT64_MAX;
300 };
278 if (bisect.gated) queue.wait(gate.semaphore(), 1); 301 if (bisect.gated) queue.wait(gate.semaphore(), 1);
279 for (auto& [name, list] : lists) { 302 for (auto& [name, list] : lists) {
280 EXPECT(list.close()); 303 EXPECT(list.close());
@@ -286,15 +309,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
286 std::printf("%s: execute returned %d\n", name, int(result)); 309 std::printf("%s: execute returned %d\n", name, int(result));
287 return 1; 310 return 1;
288 } 311 }
289 if (!bisect.gated && !queue.idle()) { 312 if (!bisect.gated && (!queue.idle() || lost())) {
290 std::printf("%s: vkQueueWaitIdle failed (device lost?)\n", name); 313 std::printf("%s: device lost\n", name);
291 return 1; 314 return 1;
292 } 315 }
293 } 316 }
294 if (bisect.gated) { 317 if (bisect.gated) {
295 EXPECT(gate.signal(1)); 318 EXPECT(gate.signal(1));
296 if (!queue.idle()) { 319 if (!queue.idle() || lost()) {
297 std::printf("gated: vkQueueWaitIdle failed (device lost?)\n"); 320 std::printf("gated: device lost\n");
298 return 1; 321 return 1;
299 } 322 }
300 } 323 }
@@ -414,13 +437,22 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
414 EXPECT(replace.close()); 437 EXPECT(replace.close());
415 const CommandList* fourth[] = {&replace}; 438 const CommandList* fourth[] = {&replace};
416 EXPECT(queue.execute(fourth) == ReplayResult::success); 439 EXPECT(queue.execute(fourth) == ReplayResult::success);
440
441 // A resolve inside one active query, with no overlap.
442 CommandList single;
443 EXPECT(single.begin_query({a, occ, 3}));
444 EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128}));
445 EXPECT(single.end_query({a, occ, 3}));
446 EXPECT(single.close());
447 const CommandList* fifth[] = {&single};
448 EXPECT(queue.execute(fifth) == ReplayResult::success);
417 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size()); 449 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size());
418 EXPECT(gate.signal(1)); 450 EXPECT(gate.signal(1));
419 EXPECT(queue.idle()); 451 EXPECT(queue.idle());
420 452
421 std::map<VkDeviceSize, std::uint64_t> expected = { 453 std::map<VkDeviceSize, std::uint64_t> expected = {
422 {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1}, 454 {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1},
423 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, 455 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4},
424 }; 456 };
425 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query 457 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query
426 for (VkDeviceSize offset = 0; offset < size; offset += 8) { 458 for (VkDeviceSize offset = 0; offset < size; offset += 8) {
@@ -460,7 +492,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
460 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7))); 492 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7)));
461 } 493 }
462 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " 494 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; "
463 "offsets and gated overwrites exact\n", 495 "resolve inside an active query 4; offsets and gated overwrites exact\n",
464 2 * bursts + 1); 496 2 * bursts + 1);
465 EXPECT(copy_control.check()); 497 EXPECT(copy_control.check());
466 return 0; 498 return 0;
@@ -468,13 +500,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
468 500
469} // namespace 501} // namespace
470 502
471// vk_overlapping_occlusion_test <vert.spv> <frag.spv> [--bisect [--gated] [phase...]] 503// vk_overlapping_occlusion_test <vert.spv> <frag.spv> [--bisect [--gated] [--no-draw] [--no-resolve] [phase...]]
472int main(int argc, char** argv) { 504int main(int argc, char** argv) {
473 EXPECT(argc >= 3); 505 EXPECT(argc >= 3);
474 Bisect bisect; 506 Bisect bisect;
475 for (int i = 3; i < argc; ++i) { 507 for (int i = 3; i < argc; ++i) {
476 if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true; 508 if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true;
477 else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true; 509 else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true;
510 else if (std::strcmp(argv[i], "--no-draw") == 0) bisect.no_draw = true;
511 else if (std::strcmp(argv[i], "--no-resolve") == 0) bisect.no_resolve = true;
478 else bisect.phases.emplace_back(argv[i]); 512 else bisect.phases.emplace_back(argv[i]);
479 } 513 }
480 EXPECT(argc == 3 || bisect.enabled); 514 EXPECT(argc == 3 || bisect.enabled);
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index bdefac894..f11cc37ff 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -22,6 +22,12 @@
22// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and 22// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and
23// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a 23// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a
24// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. 24// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count.
25// --isolate (POSIX only) check in child processes, --isolate-batch modules at a time (default 256), so a module
26// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass
27// goes on. A crashed batch is bisected to the module. Children run one after the other and share
28// cache.bin. Not compatible with --stats.
29// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL] raises SIGNAL (default SIGFPE)
30// just before the pipeline of a matching module is created. Only for testing --isolate.
25#include "vulkan_loader.h" 31#include "vulkan_loader.h"
26#include "vk_device_pick.h" 32#include "vk_device_pick.h"
27#include "pipeline_cache_file.h" 33#include "pipeline_cache_file.h"
@@ -32,7 +38,10 @@
32#include <cctype> 38#include <cctype>
33#include <charconv> 39#include <charconv>
34#include <chrono> 40#include <chrono>
41#include <cmath>
35#include <condition_variable> 42#include <condition_variable>
43#include <csignal>
44#include <cstdlib>
36#include <cstdio> 45#include <cstdio>
37#include <cstring> 46#include <cstring>
38#include <fstream> 47#include <fstream>
@@ -48,6 +57,13 @@
48#include <utility> 57#include <utility>
49#include <vector> 58#include <vector>
50 59
60#ifndef _WIN32
61#include <sys/wait.h>
62#include <unistd.h>
63#include <cerrno>
64#include <filesystem>
65#endif
66
51static PFN_vkGetInstanceProcAddr gipa; 67static PFN_vkGetInstanceProcAddr gipa;
52 68
53struct VertexInputMeta { 69struct VertexInputMeta {
@@ -275,11 +291,13 @@ struct JsonParser {
275 291
276std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) { 292std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) {
277 std::ifstream f(path, std::ios::binary); 293 std::ifstream f(path, std::ios::binary);
278 std::string s((std::istreambuf_iterator<char>(f)), {});
279 std::map<std::string, ShaderMeta> out; 294 std::map<std::string, ShaderMeta> out;
295 if (!f) { err = "cannot open the file"; return out; } // a missing index must not read as an empty corpus
296 std::string s((std::istreambuf_iterator<char>(f)), {});
297 if (f.bad()) { err = "read error"; return out; }
280 JsonParser p{s, 0}; 298 JsonParser p{s, 0};
281 p.ws(); 299 p.ws();
282 if (p.i >= s.size()) return out; 300 if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; }
283 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; } 301 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; }
284 while (!p.error && p.i < s.size()) { 302 while (!p.error && p.i < s.size()) {
285 if (p.consume('}')) return out; 303 if (p.consume('}')) return out;
@@ -375,6 +393,116 @@ static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1);
375static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT | 393static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT |
376 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0); 394 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0);
377 395
396// Test hook (see the header): VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL].
397struct SimulatedCrash {
398 bool enabled = false;
399 std::string pattern;
400 int sig = SIGFPE;
401};
402
403int signal_from_name(std::string n) {
404 for (char& c : n) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
405 if (n.rfind("SIG", 0) == 0) n = n.substr(3);
406 if (n == "FPE") return SIGFPE;
407 if (n == "SEGV") return SIGSEGV;
408 if (n == "ABRT") return SIGABRT;
409 if (n == "ILL") return SIGILL;
410 if (n == "TERM") return SIGTERM;
411#ifndef _WIN32
412 if (n == "BUS") return SIGBUS;
413 if (n == "KILL") return SIGKILL;
414#endif
415 return 0;
416}
417
418SimulatedCrash read_simulated_crash() {
419 SimulatedCrash c;
420 const char* env = std::getenv("VK_PIPELINE_CHECK_SIMULATE_CRASH");
421 if (!env || !*env) return c;
422 std::string v = env;
423 const size_t colon = v.rfind(':');
424 if (colon != std::string::npos) {
425 if (const int sig = signal_from_name(v.substr(colon + 1))) {
426 c.sig = sig;
427 v.resize(colon);
428 }
429 }
430 c.enabled = true;
431 c.pattern = v;
432 return c;
433}
434
435#ifndef _WIN32
436std::string signal_label(int sig) {
437 switch (sig) {
438 case SIGFPE: return "SIGFPE";
439 case SIGSEGV: return "SIGSEGV";
440 case SIGABRT: return "SIGABRT";
441 case SIGILL: return "SIGILL";
442 case SIGBUS: return "SIGBUS";
443 case SIGKILL: return "SIGKILL";
444 case SIGTERM: return "SIGTERM";
445 default: return "signal " + std::to_string(sig);
446 }
447}
448
449// --isolate: one child run of this executable over [start, start + count) of the stage-filtered list.
450struct ChildRun {
451 bool ready = false; // reached the work loop (ISO-READY): Vulkan and the cache were set up
452 bool done = false; // finished the pass and saved the cache (ISO-DONE)
453 bool cache_ok = true;
454 int sig = 0; // killed by this signal
455 int status = 0; // exit status when it exited
456 std::string out; // its stdout
457};
458
459ChildRun run_child(const std::string& exe, const std::string& dir, const std::vector<std::string>& pass,
460 const std::string& cache_path, size_t start, size_t count) {
461 ChildRun r;
462 std::vector<std::string> args = {exe, dir};
463 if (!cache_path.empty()) args.push_back(cache_path);
464 for (const auto& a : pass) args.push_back(a);
465 args.insert(args.end(), {"--isolate-child", "--start", std::to_string(start), "--count", std::to_string(count)});
466 std::vector<char*> argv;
467 for (auto& a : args) argv.push_back(a.data());
468 argv.push_back(nullptr);
469 int fds[2];
470 if (pipe(fds) != 0) { r.status = 127; return r; }
471 std::fflush(nullptr);
472 const pid_t pid = fork();
473 if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return r; }
474 if (pid == 0) {
475 dup2(fds[1], 1);
476 close(fds[0]); close(fds[1]);
477 execv(exe.c_str(), argv.data());
478 _exit(127);
479 }
480 close(fds[1]);
481 char buf[4096];
482 for (;;) {
483 const ssize_t n = read(fds[0], buf, sizeof buf);
484 if (n > 0) r.out.append(buf, size_t(n));
485 else if (n < 0 && errno == EINTR) continue;
486 else break;
487 }
488 close(fds[0]);
489 int st = 0;
490 while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
491 if (WIFSIGNALED(st)) r.sig = WTERMSIG(st);
492 else r.status = WIFEXITED(st) ? WEXITSTATUS(st) : 1;
493 size_t pos = 0;
494 while (pos < r.out.size()) {
495 size_t e = r.out.find('\n', pos);
496 if (e == std::string::npos) e = r.out.size();
497 const std::string_view line(r.out.data() + pos, e - pos);
498 if (line == "ISO-READY") r.ready = true;
499 else if (line.rfind("ISO-DONE", 0) == 0) { r.done = true; r.cache_ok = line.find("cache_ok=0") == std::string_view::npos; }
500 pos = e + 1;
501 }
502 return r;
503}
504#endif
505
378} // namespace 506} // namespace
379 507
380int main(int argc, char** argv) { 508int main(int argc, char** argv) {
@@ -382,7 +510,7 @@ int main(int argc, char** argv) {
382 std::fprintf(stderr, 510 std::fprintf(stderr,
383 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " 511 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
384 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " 512 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
385 "[--stats FILE] [--cache-feedback]\n"); 513 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]]\n");
386 return 2; 514 return 2;
387 } 515 }
388 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen 516 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
@@ -392,40 +520,67 @@ int main(int argc, char** argv) {
392 size_t large_module_bytes = 4 * 1024 * 1024; 520 size_t large_module_bytes = 4 * 1024 * 1024;
393 double slow = 30.0; 521 double slow = 30.0;
394 std::string stage_filter = "all"; 522 std::string stage_filter = "all";
395 bool cache_feedback = false; 523 bool cache_feedback = false, isolate = false, iso_child = false;
524 size_t isolate_batch = 256;
396 for (int i = 2; i < argc; i++) { 525 for (int i = 2; i < argc; i++) {
397 std::string a = argv[i]; 526 std::string a = argv[i];
398 auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; 527 auto value = [&]() -> std::string_view {
399 if (a == "--jobs") jobs = std::max(1u, uint32_t(std::stoul(val()))); 528 if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
400 else if (a == "--start") start = std::stoull(val()); 529 return argv[++i];
401 else if (a == "--count") count = std::stoull(val()); 530 };
402 else if (a == "--slow") slow = std::stod(val()); 531 auto number = [&](auto& dest) {
403 else if (a == "--stage") stage_filter = val(); 532 const auto text = value();
533 if (text.empty()) return false;
534 const auto end = text.data() + text.size();
535 const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
536 return ec == std::errc{} && ptr == end;
537 };
538 bool valid = true;
539 if (a == "--jobs") {
540 valid = number(jobs);
541 jobs = std::max(1u, jobs);
542 } else if (a == "--start") valid = number(start);
543 else if (a == "--count") valid = number(count);
544 else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
545 else if (a == "--stage") valid = !(stage_filter = value()).empty();
404 else if (a == "--compute-only") stage_filter = "cs"; 546 else if (a == "--compute-only") stage_filter = "cs";
405 else if (a == "--graphics-only") stage_filter = "graphics"; 547 else if (a == "--graphics-only") stage_filter = "graphics";
406 else if (a == "--max-bytes") max_bytes = std::stoull(val()); 548 else if (a == "--max-bytes") valid = number(max_bytes);
407 else if (a == "--large-module-bytes") { 549 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
408 const std::string_view value = i + 1 < argc ? argv[++i] : ""; 550 else if (a == "--stats") valid = !(stats_path = value()).empty();
409 const auto end = value.data() + value.size();
410 const auto [ptr, ec] = std::from_chars(value.data(), end, large_module_bytes);
411 if (ec != std::errc{} || ptr != end) {
412 std::fprintf(stderr, "--large-module-bytes requires a non-negative byte count\n");
413 return 2;
414 }
415 }
416 else if (a == "--stats") stats_path = val();
417 else if (a == "--cache-feedback") cache_feedback = true; 551 else if (a == "--cache-feedback") cache_feedback = true;
552 else if (a == "--isolate") isolate = true;
553 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs
554 else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch
555 valid = number(isolate_batch);
556 isolate_batch = std::max<size_t>(1, isolate_batch);
557 }
418 else cache_path = a; 558 else cache_path = a;
559 if (!valid) {
560 std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
561 return 2;
562 }
419 } 563 }
420 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { 564 if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") {
421 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str()); 565 std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
422 return 2; 566 return 2;
423 } 567 }
424 568
569 if (isolate && !stats_path.empty()) {
570 std::fprintf(stderr, "--isolate cannot be combined with --stats\n");
571 return 2;
572 }
573#ifdef _WIN32
574 if (isolate) {
575 std::fprintf(stderr, "--isolate is not supported on Windows (it needs fork/waitpid); run without it\n");
576 return 2;
577 }
578#endif
579
425 std::string index_err; 580 std::string index_err;
426 auto index = read_index(dir + "/index.json", index_err); 581 auto index = read_index(dir + "/index.json", index_err);
427 if (!index_err.empty()) { 582 if (!index_err.empty()) {
428 std::fprintf(stderr, "error: malformed JSON in %s/index.json: %s\n", dir.c_str(), index_err.c_str()); 583 std::fprintf(stderr, "error: cannot use %s/index.json: %s\n", dir.c_str(), index_err.c_str());
429 return 2; 584 return 2;
430 } 585 }
431 std::fprintf(stderr, "%zu shaders in index\n", index.size()); 586 std::fprintf(stderr, "%zu shaders in index\n", index.size());
@@ -441,6 +596,115 @@ int main(int argc, char** argv) {
441 const auto [lo, hi] = shader_slice(all.size(), start, count); 596 const auto [lo, hi] = shader_slice(all.size(), start, count);
442 const std::vector<Item> work(all.begin() + lo, all.begin() + hi); 597 const std::vector<Item> work(all.begin() + lo, all.begin() + hi);
443 598
599#ifndef _WIN32
600 if (isolate) {
601 // Parent: no Vulkan here. Run the check in child processes, one at a time, in batches of --isolate-batch
602 // modules. A child that dies mid-batch has its output discarded and the batch is bisected until the one
603 // module that kills the driver is found; the clean sub-runs partition the rest, so nothing is counted twice.
604 std::string exe = argv[0];
605 std::error_code ec;
606 if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string();
607 std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter,
608 "--max-bytes", std::to_string(max_bytes),
609 "--large-module-bytes", std::to_string(large_module_bytes)};
610 if (cache_feedback) pass.push_back("--cache-feedback");
611 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
612 std::map<std::string, Agg> agg;
613 std::vector<std::string> crashes;
614 bool cache_ok = true, setup_failed = false;
615 size_t unreproduced = 0;
616 const auto t_iso = std::chrono::steady_clock::now();
617 std::fprintf(stderr, "isolating %zu shaders [%zu, %zu) (stage=%s) in child processes, %zu per batch\n",
618 work.size(), lo, hi, stage_filter.c_str(), isolate_batch);
619 auto commit = [&](const ChildRun& r) {
620 size_t pos = 0;
621 while (pos < r.out.size()) {
622 size_t e = r.out.find('\n', pos);
623 if (e == std::string::npos) e = r.out.size();
624 const std::string line = r.out.substr(pos, e - pos);
625 pos = e + 1;
626 // The parent prints one cache line at the end instead of one per child.
627 if (line == "ISO-READY" || line.rfind("ISO-DONE", 0) == 0 || line.rfind("pipeline cache: ", 0) == 0) continue;
628 if (line.rfind("ISO-RESULT ", 0) == 0) {
629 char st[16];
630 unsigned v[9] = {};
631 if (std::sscanf(line.c_str(), "ISO-RESULT %15s %u %u %u %u %u %u %u %u %u", st, v, v + 1, v + 2, v + 3,
632 v + 4, v + 5, v + 6, v + 7, v + 8) == 10) {
633 Agg& a = agg[st];
634 a.mod_ok += v[0]; a.mod_bad += v[1]; a.pipe_ok += v[2]; a.pipe_bad += v[3]; a.pipe_skip += v[4];
635 a.big += v[5]; a.fb[0] += v[6]; a.fb[1] += v[7]; a.fb[2] += v[8];
636 }
637 continue;
638 }
639 std::printf("%s\n", line.c_str());
640 }
641 std::fflush(stdout);
642 if (!r.cache_ok) cache_ok = false;
643 };
644 // Returns the number of failures recorded for [s, s + n): crashed modules, or 1 for a crash that vanished.
645 auto bisect = [&](auto&& self, size_t s, size_t n) -> size_t {
646 if (setup_failed) return 0;
647 const ChildRun r = run_child(exe, dir, pass, cache_path, s, n);
648 if (r.done) { commit(r); return 0; }
649 if (!r.ready) { // died or exited before the work loop: not a module's fault
650 std::fputs(r.out.c_str(), stdout);
651 if (r.sig) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal_label(r.sig).c_str());
652 else std::fprintf(stderr, "error: a child process failed during setup (exit status %d)\n", r.status);
653 setup_failed = true;
654 return 0;
655 }
656 const std::string why = r.sig ? "driver crashed: " + signal_label(r.sig)
657 : "driver exited with status " + std::to_string(r.status);
658 if (n == 1) {
659 const std::string& name = *all[s].first;
660 const std::string& st = all[s].second->stage;
661 std::printf("MODULE CRASH %s (%s, %s)\n", name.c_str(), st.c_str(), why.c_str());
662 std::fflush(stdout);
663 crashes.push_back(name + " (" + st + ", " + why + ")");
664 agg[st].pipe_bad++;
665 agg[st].crashed++;
666 return 1;
667 }
668 std::fprintf(stderr, "child over [%zu, %zu) died (%s); bisecting\n", s, s + n, why.c_str());
669 const size_t half = n / 2;
670 size_t found = self(self, s, half);
671 found += self(self, s + half, n - half);
672 if (found == 0 && !setup_failed) {
673 std::printf("MODULE CRASH [%zu, %zu) not reproduced when split (%s); counted as failed\n", s, s + n, why.c_str());
674 ++unreproduced;
675 return 1;
676 }
677 return found;
678 };
679 for (size_t s = lo; s < hi && !setup_failed; s += isolate_batch) bisect(bisect, s, std::min(isolate_batch, hi - s));
680 if (setup_failed) return 1;
681 bool failed = !crashes.empty() || unreproduced || !cache_ok;
682 for (const auto& [st, a] : agg) {
683 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), a.mod_ok, a.mod_bad);
684 std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", st.c_str(), a.pipe_ok, a.pipe_bad, a.pipe_skip);
685 if (a.crashed) std::printf(" %s crashed the driver: %u (counted as failed)\n", st.c_str(), a.crashed);
686 if (cache_feedback)
687 std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", st.c_str(), a.fb[0], a.fb[1], a.fb[2]);
688 if (a.mod_bad || a.pipe_bad) failed = true;
689 }
690 uint32_t big_total = 0;
691 for (const auto& [st, a] : agg) big_total += a.big;
692 if (big_total) std::printf("big modules skipped: %u (limit %zu bytes)\n", big_total, max_bytes);
693 if (!crashes.empty()) {
694 std::printf("modules that crashed the driver: %zu\n", crashes.size());
695 for (const auto& c : crashes) std::printf(" %s\n", c.c_str());
696 }
697 if (unreproduced) std::printf("crashes not reproduced after splitting: %zu\n", unreproduced);
698 if (!cache_path.empty()) {
699 const auto sz = std::filesystem::file_size(cache_path, ec);
700 if (!ec) std::printf("pipeline cache: %ju bytes -> %s\n", static_cast<uintmax_t>(sz), cache_path.c_str());
701 }
702 std::printf("wall time: %.1fs (isolated)\n",
703 std::chrono::duration<double>(std::chrono::steady_clock::now() - t_iso).count());
704 return failed ? 1 : 0;
705 }
706#endif
707
444 // Scan selected shaders to request only the optional extensions they actually use. 708 // Scan selected shaders to request only the optional extensions they actually use.
445 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false; 709 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false;
446 for (auto& [_, meta] : work) { 710 for (auto& [_, meta] : work) {
@@ -783,6 +1047,15 @@ int main(int argc, char** argv) {
783 if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed()); 1047 if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed());
784 }; 1048 };
785 1049
1050 const SimulatedCrash sim_crash = read_simulated_crash();
1051 auto maybe_simulate_crash = [&](const std::string& name) { // test hook, see the header
1052 if (sim_crash.enabled && name.find(sim_crash.pattern) != std::string::npos) {
1053 std::fprintf(stderr, "simulating signal %d before the pipeline of %s\n", sim_crash.sig, name.c_str());
1054 std::fflush(nullptr);
1055 std::raise(sim_crash.sig);
1056 }
1057 };
1058
786 auto worker = [&] { 1059 auto worker = [&] {
787 for (size_t k; (k = next++) < work.size();) { 1060 for (size_t k; (k = next++) < work.size();) {
788 const std::string& name = *work[k].first; 1061 const std::string& name = *work[k].first;
@@ -846,6 +1119,7 @@ int main(int argc, char** argv) {
846 const auto t0 = std::chrono::steady_clock::now(); 1119 const auto t0 = std::chrono::steady_clock::now();
847 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1120 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
848 VkPipeline p = VK_NULL_HANDLE; 1121 VkPipeline p = VK_NULL_HANDLE;
1122 maybe_simulate_crash(name);
849 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); 1123 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p);
850 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); 1124 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
851 if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p); 1125 if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p);
@@ -1015,6 +1289,7 @@ int main(int argc, char** argv) {
1015 const auto t0 = std::chrono::steady_clock::now(); 1289 const auto t0 = std::chrono::steady_clock::now();
1016 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1290 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
1017 VkPipeline p = VK_NULL_HANDLE; 1291 VkPipeline p = VK_NULL_HANDLE;
1292 maybe_simulate_crash(name);
1018 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); 1293 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p);
1019 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); 1294 const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1020 if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p); 1295 if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p);
@@ -1032,6 +1307,8 @@ int main(int argc, char** argv) {
1032 } 1307 }
1033 } 1308 }
1034 }; 1309 };
1310 if (iso_child) std::printf("ISO-READY\n");
1311 std::fflush(stdout);
1035 std::vector<std::thread> pool; 1312 std::vector<std::thread> pool;
1036 for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker); 1313 for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker);
1037 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes. 1314 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes.
@@ -1070,6 +1347,20 @@ int main(int argc, char** argv) {
1070 for (auto& [st, _] : modules_bad) all_stages.insert(st); 1347 for (auto& [st, _] : modules_bad) all_stages.insert(st);
1071 for (auto& [st, _] : stats) all_stages.insert(st); 1348 for (auto& [st, _] : stats) all_stages.insert(st);
1072 1349
1350 if (iso_child) { // --isolate child: machine-readable counts; the parent prints the summary
1351 for (const auto& st : all_stages) {
1352 const StageStats* s = stats.count(st) ? &stats[st] : nullptr;
1353 uint32_t big = big_skipped.count(st) ? big_skipped[st] : 0;
1354 std::printf("ISO-RESULT %s %u %u %u %u %u %u %u %u %u\n", st.c_str(), modules_ok[st], modules_bad[st],
1355 s ? s->pipes_ok : 0u, s ? s->pipes_bad : 0u, s ? s->pipes_skipped : 0u, big,
1356 s ? s->feedback[0] : 0u, s ? s->feedback[1] : 0u, s ? s->feedback[2] : 0u);
1357 }
1358 const bool saved = save_cache(true);
1359 std::printf("ISO-DONE cache_ok=%d\n", saved ? 1 : 0);
1360 std::fflush(stdout);
1361 return saved ? 0 : 1;
1362 }
1363
1073 bool check_failed = false; 1364 bool check_failed = false;
1074 for (const auto& st : all_stages) { 1365 for (const auto& st : all_stages) {
1075 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]); 1366 std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]);
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 3748aeec7..8f5c7d7d0 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -19,10 +19,14 @@
19#include "../src/vulkan_present.h" 19#include "../src/vulkan_present.h"
20 20
21#include <atomic> 21#include <atomic>
22#include <chrono>
22#include <cmath> 23#include <cmath>
24#include <condition_variable>
23#include <cstdint> 25#include <cstdint>
24#include <cstdio> 26#include <cstdio>
25#include <cstdlib> 27#include <cstdlib>
28#include <functional>
29#include <mutex>
26#include <string_view> 30#include <string_view>
27#include <thread> 31#include <thread>
28#include <vector> 32#include <vector>
@@ -49,10 +53,12 @@ namespace driver {
49PFN_vkGetInstanceProcAddr real_get_instance = nullptr; 53PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
50PFN_vkGetDeviceProcAddr real_get_device = nullptr; 54PFN_vkGetDeviceProcAddr real_get_device = nullptr;
51PFN_vkQueueSubmit real_submit = nullptr; 55PFN_vkQueueSubmit real_submit = nullptr;
56PFN_vkQueuePresentKHR real_present = nullptr;
52PFN_vkCmdPipelineBarrier real_barrier = nullptr; 57PFN_vkCmdPipelineBarrier real_barrier = nullptr;
53PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 58PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
54 59
55std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 60std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
61std::function<void()> on_next_present;
56std::atomic<bool> observe_capture{false}; 62std::atomic<bool> observe_capture{false};
57std::atomic<bool> saw_capture_waw{false}; 63std::atomic<bool> saw_capture_waw{false};
58std::atomic<std::uint32_t> capture_copies{0}; 64std::atomic<std::uint32_t> capture_copies{0};
@@ -65,6 +71,15 @@ VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count,
65 return real_submit(queue, count, submits, fence); 71 return real_submit(queue, count, submits, fence);
66} 72}
67 73
74VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) {
75 if (on_next_present) {
76 auto cb = std::move(on_next_present);
77 on_next_present = {};
78 cb();
79 }
80 return real_present(queue, info);
81}
82
68VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, 83VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
69 VkPipelineStageFlags dst_stage, VkDependencyFlags flags, 84 VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
70 std::uint32_t mem_count, const VkMemoryBarrier* mem, 85 std::uint32_t mem_count, const VkMemoryBarrier* mem,
@@ -100,6 +115,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage
100VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { 115VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
101 const std::string_view n = name; 116 const std::string_view n = name;
102 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 117 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
118 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
103 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier); 119 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier);
104 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer); 120 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
105 return real_get_device(device, name); 121 return real_get_device(device, name);
@@ -114,6 +130,7 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
114 real_get_instance = instance_proc; 130 real_get_instance = instance_proc;
115 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 131 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
116 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 132 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
133 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
117 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier")); 134 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
118 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer")); 135 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
119} 136}
@@ -193,15 +210,52 @@ int main() {
193 EXPECT(presenter.ok()); 210 EXPECT(presenter.ok());
194 EXPECT(presenter.enable_capture()); 211 EXPECT(presenter.enable_capture());
195 212
196 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker. 213 // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback
214 // even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR.
215 for (ResourceId extra = 1000; extra < 1512; ++extra)
216 context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
197 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 217 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
198 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); 218 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
199 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY); 219 EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY);
200 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); 220 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
201 221 EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
202 // Next present succeeds, runs the deferred zero-fill, and commits GENERAL. 222
203 EXPECT(presenter.present(1, true) == VK_SUCCESS); 223 // Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before
224 // vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation.
225 std::mutex sync_mutex;
226 std::condition_variable sync_cv;
227 bool reader_started = false;
228 bool read_done = false;
229 VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED;
230 bool unblocked_during_present = false;
231 std::thread reader;
232 driver::on_next_present = [&] {
233 reader = std::thread([&] {
234 {
235 std::lock_guard lk(sync_mutex);
236 reader_started = true;
237 }
238 sync_cv.notify_all();
239 const VkImageLayout layout = context.layout(1, 0);
240 {
241 std::lock_guard lk(sync_mutex);
242 seen_during_present = layout;
243 read_done = true;
244 }
245 sync_cv.notify_all();
246 });
247 std::unique_lock lk(sync_mutex);
248 const bool started = sync_cv.wait_for(lk, std::chrono::seconds(2), [&] { return reader_started; });
249 unblocked_during_present =
250 started && sync_cv.wait_for(lk, std::chrono::milliseconds(500), [&] { return read_done; });
251 };
252 const VkResult present_rc = presenter.present(1, true);
253 if (reader.joinable()) reader.join();
254 EXPECT(present_rc == VK_SUCCESS);
255 EXPECT(unblocked_during_present);
256 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
204 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); 257 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
258 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
205 std::vector<std::uint8_t> pixels; 259 std::vector<std::uint8_t> pixels;
206 VkExtent2D ext{}; 260 VkExtent2D ext{};
207 VkFormat fmt = VK_FORMAT_UNDEFINED; 261 VkFormat fmt = VK_FORMAT_UNDEFINED;
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 635a3107b..1e54a9487 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -1,10 +1,12 @@
1// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device with dynamicRendering, synchronization2, 1// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and
2// timelineSemaphore and separateDepthStencilLayouts, images, buffers and one-shot submissions. 2// VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and
3// separateDepthStencilLayouts, images, buffers and one-shot submissions.
3// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors. 4// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors.
4#pragma once 5#pragma once
5 6
6#include "vulkan_loader.h" 7#include "vulkan_loader.h"
7#include "../src/vulkan_device_filter.h" 8#include "../src/vulkan_device_filter.h"
9#include "../src/vulkan13_features.h"
8#include "vk_device_pick.h" 10#include "vk_device_pick.h"
9#include "../src/subgroup_size.h" 11#include "../src/subgroup_size.h"
10 12
@@ -82,6 +84,12 @@ public:
82 VkDevice device = VK_NULL_HANDLE; 84 VkDevice device = VK_NULL_HANDLE;
83 VkQueue queue = VK_NULL_HANDLE; 85 VkQueue queue = VK_NULL_HANDLE;
84 std::uint32_t family = 0; 86 std::uint32_t family = 0;
87 // Set before initialize(): how many queues of `family` to create (fewer if the family has fewer). `queues` holds the
88 // handles; queues[0] == queue. A test that wants distinct VkQueues for its D3D12 queues passes them on as
89 // VulkanDeviceInfo::command_queues when there is more than one.
90 std::uint32_t queue_count_wanted = 1;
91 std::uint32_t family_queue_count = 1; // the family's queueCount, known after the device is chosen
92 std::vector<VkQueue> queues;
85 bool validation = false; 93 bool validation = false;
86 bool bc = false; // textureCompressionBC enabled 94 bool bc = false; // textureCompressionBC enabled
87 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` 95 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device`
@@ -134,9 +142,10 @@ public:
134 reinterpret_cast<PFN_vkDestroyInstance>(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr); 142 reinterpret_cast<PFN_vkDestroyInstance>(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr);
135 } 143 }
136 144
145 // A Vulkan 1.3 function falls back to its KHR name on a 1.2 device.
137 template<typename F> 146 template<typename F>
138 F fn(const char* name) const { 147 F fn(const char* name) const {
139 return reinterpret_cast<F>(device_proc(device, name)); 148 return reinterpret_cast<F>(leonida::device_proc_or_khr(device_proc, device, name));
140 } 149 }
141 150
142 template<typename F> 151 template<typename F>
@@ -263,10 +272,16 @@ public:
263 if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result); 272 if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result);
264 VkPhysicalDeviceProperties chosen{}; 273 VkPhysicalDeviceProperties chosen{};
265 int best_rank = -1; 274 int best_rank = -1;
275 const auto features2_of = instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2");
276 const auto device_extensions_of =
277 instance_fn<PFN_vkEnumerateDeviceExtensionProperties>("vkEnumerateDeviceExtensionProperties");
278 leonida::Vulkan13Features candidate13;
266 for (auto candidate : devices) { 279 for (auto candidate : devices) {
267 VkPhysicalDeviceProperties props{}; 280 VkPhysicalDeviceProperties props{};
268 properties_of(candidate, &props); 281 properties_of(candidate, &props);
269 if (props.apiVersion < VK_API_VERSION_1_3 || !leonida::vulkan_device_wanted(props.deviceName)) continue; 282 if (!leonida::vulkan_device_wanted(props.deviceName)) continue;
283 candidate13.query(candidate, props.apiVersion, features2_of, device_extensions_of);
284 if (!candidate13.usable()) continue;
270 std::uint32_t family_count = 0; 285 std::uint32_t family_count = 0;
271 families_of(candidate, &family_count, nullptr); 286 families_of(candidate, &family_count, nullptr);
272 std::vector<VkQueueFamilyProperties> families(family_count); 287 std::vector<VkQueueFamilyProperties> families(family_count);
@@ -277,8 +292,10 @@ public:
277 rank > best_rank) { 292 rank > best_rank) {
278 physical = candidate; 293 physical = candidate;
279 family = i; 294 family = i;
295 family_queue_count = families[i].queueCount;
280 chosen = props; 296 chosen = props;
281 best_rank = rank; 297 best_rank = rank;
298 v13_.choose(candidate13);
282 } 299 }
283 break; 300 break;
284 } 301 }
@@ -286,22 +303,25 @@ public:
286 if (!physical) { 303 if (!physical) {
287 if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) { 304 if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) {
288 // A filter that matches nothing fails the test instead of skipping it. 305 // A filter that matches nothing fails the test instead of skipping it.
289 std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device with a graphics queue matches\n", 306 std::fprintf(stderr,
307 "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and "
308 "VK_KHR_synchronization2) with a graphics queue matches\n",
290 filter.c_str()); 309 filter.c_str());
291 return DeviceStatus::failed; 310 return DeviceStatus::failed;
292 } 311 }
293 std::fprintf(stderr, "no Vulkan 1.3 device with a graphics queue\n"); 312 std::fprintf(stderr, "no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and "
313 "VK_KHR_synchronization2) with a graphics queue\n");
294 return DeviceStatus::unavailable; 314 return DeviceStatus::unavailable;
295 } 315 }
296 std::printf("device: %s%s\n", chosen.deviceName, validation ? " (validation on)" : ""); 316 std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)",
317 validation ? " (validation on)" : "");
297 318
298 VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 319 VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
299 VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &features13};
300 VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; 320 VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11};
301 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; 321 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12};
302 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &features); 322 features2_of(physical, &features);
303 if (!features13.dynamicRendering || !features13.synchronization2 || !features12.timelineSemaphore || 323 if (!features12.timelineSemaphore || !features12.separateDepthStencilLayouts ||
304 !features12.separateDepthStencilLayouts || !features12.bufferDeviceAddress) { 324 !features12.bufferDeviceAddress) {
305 std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or " 325 std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or "
306 "separateDepthStencilLayouts\n"); 326 "separateDepthStencilLayouts\n");
307 return DeviceStatus::unavailable; 327 return DeviceStatus::unavailable;
@@ -327,14 +347,8 @@ public:
327 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; 347 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT};
328 enable_conditional.conditionalRendering = VK_TRUE; 348 enable_conditional.conditionalRendering = VK_TRUE;
329 349
330 VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
331 conditional_rendering ? &enable_conditional : nullptr};
332 enable13.dynamicRendering = VK_TRUE;
333 enable13.synchronization2 = VK_TRUE;
334 enable13.subgroupSizeControl = features13.subgroupSizeControl;
335 enable13.computeFullSubgroups = features13.computeFullSubgroups;
336 leonida::query_subgroup_size_caps(instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2"), 350 leonida::query_subgroup_size_caps(instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2"),
337 physical, features13.subgroupSizeControl, features13.computeFullSubgroups, 351 physical, v13_.subgroup_size_control, v13_.compute_full_subgroups,
338 subgroup); 352 subgroup);
339 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " 353 std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, "
340 "computeFullSubgroups %s\n", 354 "computeFullSubgroups %s\n",
@@ -342,7 +356,8 @@ public:
342 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off"); 356 subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off");
343 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 357 // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436
344 // (zero-based VS ids) is in; harmless before. 358 // (zero-based VS ids) is in; harmless before.
345 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &enable13}; 359 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
360 v13_.enable(conditional_rendering ? &enable_conditional : nullptr)};
346 enable11.shaderDrawParameters = features11.shaderDrawParameters; 361 enable11.shaderDrawParameters = features11.shaderDrawParameters;
347 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; 362 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11};
348 enable12.timelineSemaphore = VK_TRUE; 363 enable12.timelineSemaphore = VK_TRUE;
@@ -369,11 +384,11 @@ public:
369 enable12.samplerFilterMinmax = sampler_filter_minmax; 384 enable12.samplerFilterMinmax = sampler_filter_minmax;
370 enable12.bufferDeviceAddress = VK_TRUE; 385 enable12.bufferDeviceAddress = VK_TRUE;
371 386
372 const float priority = 1.0f; 387 const std::vector<float> priority(std::max(1u, std::min(queue_count_wanted, family_queue_count)), 1.0f);
373 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 388 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
374 queue_info.queueFamilyIndex = family; 389 queue_info.queueFamilyIndex = family;
375 queue_info.queueCount = 1; 390 queue_info.queueCount = std::max(1u, std::min(queue_count_wanted, family_queue_count));
376 queue_info.pQueuePriorities = &priority; 391 queue_info.pQueuePriorities = priority.data();
377 VkPhysicalDeviceFeatures enable{}; 392 VkPhysicalDeviceFeatures enable{};
378 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 393 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
379 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) 394 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
@@ -399,8 +414,8 @@ public:
399 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 414 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
400 image_view_min_lod = min_lod.minLod == VK_TRUE; 415 image_view_min_lod = min_lod.minLod == VK_TRUE;
401 if (image_view_min_lod) { 416 if (image_view_min_lod) {
402 min_lod.pNext = enable13.pNext; 417 min_lod.pNext = *v13_.next();
403 enable13.pNext = &min_lod; 418 *v13_.next() = &min_lod;
404 } 419 }
405 } 420 }
406 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{ 421 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{
@@ -413,8 +428,8 @@ public:
413 } 428 }
414 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; 429 const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME;
415 if (host_image_copy) { 430 if (host_image_copy) {
416 host_copy.pNext = enable13.pNext; // after the conditional rendering features, if any 431 host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any
417 enable13.pNext = &host_copy; 432 *v13_.next() = &host_copy;
418 } 433 }
419 434
420#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME 435#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
@@ -427,8 +442,8 @@ public:
427 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 442 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
428 shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE; 443 shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE;
429 if (shader_fma) { 444 if (shader_fma) {
430 fma_features.pNext = enable13.pNext; 445 fma_features.pNext = *v13_.next();
431 enable13.pNext = &fma_features; 446 *v13_.next() = &fma_features;
432 } 447 }
433 } 448 }
434#endif 449#endif
@@ -442,6 +457,7 @@ public:
442 device_info.pEnabledFeatures = &enable; 457 device_info.pEnabledFeatures = &enable;
443 enabled = enable; 458 enabled = enable;
444 std::vector<const char*> device_extensions; 459 std::vector<const char*> device_extensions;
460 v13_.add_extensions(device_extensions);
445 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 461 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
446 if (conditional_rendering) device_extensions.push_back(conditional_extension); 462 if (conditional_rendering) device_extensions.push_back(conditional_extension);
447 if (host_image_copy) device_extensions.push_back(host_image_copy_name); 463 if (host_image_copy) device_extensions.push_back(host_image_copy_name);
@@ -462,8 +478,8 @@ public:
462 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; 478 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1};
463 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 479 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
464 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { 480 if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) {
465 swapchain_m1.pNext = enable13.pNext; 481 swapchain_m1.pNext = *v13_.next();
466 enable13.pNext = &swapchain_m1; 482 *v13_.next() = &swapchain_m1;
467 device_extensions.push_back(name); 483 device_extensions.push_back(name);
468 swapchain_maintenance1 = true; 484 swapchain_maintenance1 = true;
469 } 485 }
@@ -478,7 +494,10 @@ public:
478 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 494 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
479 if (result != VK_SUCCESS) return failure("vkCreateDevice", result); 495 if (result != VK_SUCCESS) return failure("vkCreateDevice", result);
480 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr"); 496 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
481 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, 0, &queue); 497 queues.resize(queue_info.queueCount);
498 for (std::uint32_t i = 0; i < queue_info.queueCount; ++i)
499 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, i, &queues[i]);
500 queue = queues[0];
482 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical, 501 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical,
483 &memory_); 502 &memory_);
484 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; 503 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
@@ -628,6 +647,7 @@ private:
628 VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE; 647 VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE;
629 VkCommandPool pool_ = VK_NULL_HANDLE; 648 VkCommandPool pool_ = VK_NULL_HANDLE;
630 VkPhysicalDeviceMemoryProperties memory_{}; 649 VkPhysicalDeviceMemoryProperties memory_{};
650 leonida::Vulkan13Features v13_; // the chosen device's dynamicRendering/synchronization2 path
631 std::vector<std::pair<VkImage, VkDeviceMemory>> images_; 651 std::vector<std::pair<VkImage, VkDeviceMemory>> images_;
632 std::vector<std::pair<VkBuffer, VkDeviceMemory>> buffers_; 652 std::vector<std::pair<VkBuffer, VkDeviceMemory>> buffers_;
633}; 653};
diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp
index 136f49f68..1f4686869 100644
--- a/runtime/test/vk_xdxr_build_test.cpp
+++ b/runtime/test/vk_xdxr_build_test.cpp
@@ -6,10 +6,12 @@
6// 6//
7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride; 7// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride;
8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no 8// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no
9// triangles; 5000 triangles (three radix-sort tiles); and a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS). 9// triangles; 5000 triangles (many radix-sort tiles); updates (refits) in place and into another buffer; clones and a
10// compaction (CopyRaytracingAccelerationStructure) with the postbuild size; a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS).
10// Exit 77 when there is no Vulkan device with bufferDeviceAddress. 11// Exit 77 when there is no Vulkan device with bufferDeviceAddress.
11// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of 12// `vk_xdxr_build_test <out dir> <triangles>` instead times BLAS builds of that many random triangles (wall clock of
12// one submission each, after one warm-up; result and scratch in device-local memory) and writes nothing. 13// one submission each, after one warm-up; result and scratch in device-local memory), then in-place updates
14// (refits) of the same structure, and writes nothing.
13#include "vk_test_device.h" 15#include "vk_test_device.h"
14#include "../src/xdxr_build.h" 16#include "../src/xdxr_build.h"
15 17
@@ -117,9 +119,12 @@ struct Built {
117 std::vector<Tri> tris; 119 std::vector<Tri> tris;
118}; 120};
119 121
122// With `moved` (the same geometries with new vertex positions) the BLAS is then updated: refitted in place, or with
123// `into_other` into a second buffer, in which case the untouched source is written too, as <name>_source.
120int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, 124int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name,
121 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0) { 125 const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0,
122 std::vector<Buffer> keep; 126 const std::vector<Geometry>* moved = nullptr, bool into_other = false) {
127 std::vector<Buffer> keep, vertex_buffers;
123 std::vector<XdxrTriangles> descs; 128 std::vector<XdxrTriangles> descs;
124 std::uint32_t total = 0; 129 std::uint32_t total = 0;
125 for (std::size_t g = 0; g < geometries.size(); ++g) { 130 for (std::size_t g = 0; g < geometries.size(); ++g) {
@@ -134,6 +139,7 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
134 d.triangle_count = geo.triangle_count; 139 d.triangle_count = geo.triangle_count;
135 d.flags = 1; 140 d.flags = 1;
136 keep.push_back(v); 141 keep.push_back(v);
142 vertex_buffers.push_back(v);
137 if (!geo.indices.empty()) { 143 if (!geo.indices.empty()) {
138 Buffer ib = make(gpu, geo.indices.size() * 4); 144 Buffer ib = make(gpu, geo.indices.size() * 4);
139 EXPECT(ib.buffer); 145 EXPECT(ib.buffer);
@@ -170,13 +176,41 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir
170 return recorded; 176 return recorded;
171 })); 177 }));
172 built.address = base; 178 built.address = base;
173 const auto* bytes = static_cast<const char*>(dst.map) + (base - dst.address); 179 auto dump = [&](const std::string& case_name, const Buffer& buffer, std::uint64_t at, const std::vector<Tri>& tris) {
174 EXPECT(write_file(dir + "/" + name + ".bin", bytes, layout.size)); 180 const auto* bytes = static_cast<const char*>(buffer.map) + (at - buffer.address);
175 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(base) + 181 const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
176 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) + 182 (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) +
177 ", \"triangles\": " + tris_json(built.tris) + "}\n"; 183 ", \"triangles\": " + tris_json(tris) + "}\n";
178 EXPECT(write_file(dir + "/" + name + ".json", json.data(), json.size())); 184 return write_file(dir + "/" + case_name + ".bin", bytes, layout.size) &&
179 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes); 185 write_file(dir + "/" + case_name + ".json", json.data(), json.size());
186 };
187 if (!moved) {
188 EXPECT(dump(name, dst, base, built.tris));
189 std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes);
190 return 0;
191 }
192 // the update: new positions in the same vertex buffers, then a refit of the structure just built
193 EXPECT(moved->size() == geometries.size());
194 std::vector<Tri> moved_tris;
195 for (std::size_t g = 0; g < moved->size(); ++g) {
196 EXPECT((*moved)[g].vertex_data.size() == geometries[g].vertex_data.size());
197 std::memcpy(vertex_buffers[g].map, (*moved)[g].vertex_data.data(), (*moved)[g].vertex_data.size() * 4);
198 expand((*moved)[g], std::uint32_t(g), moved_tris);
199 }
200 Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{};
201 const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base;
202 EXPECT(!into_other || other.buffer);
203 EXPECT(gpu.run([&](VkCommandBuffer cb) {
204 recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base);
205 barrier_to_host(gpu, cb);
206 return recorded;
207 }));
208 if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source
209 EXPECT(dump(name, into_other ? other : dst, target, moved_tris));
210 built.tris = moved_tris;
211 built.address = target;
212 std::printf("%s: %u triangles refitted %s, %u bytes\n", name.c_str(), total,
213 into_other ? "into another buffer" : "in place", layout.size);
180 return 0; 214 return 0;
181} 215}
182 216
@@ -234,8 +268,17 @@ int main(int argc, char** argv) {
234 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 268 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
235 if (rep) best = std::min(best, ms); 269 if (rep) best = std::min(best, ms);
236 } 270 }
237 std::printf("%u triangles: %.2f ms (best of 3), result %u bytes, scratch %llu bytes, sort size %u\n", n, best, 271 double refit = 1e30; // an update of the structure just built, in place
238 layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size); 272 for (int rep = 0; rep < 4; ++rep) {
273 const auto t0 = std::chrono::steady_clock::now();
274 EXPECT(gpu.run([&](VkCommandBuffer cb) {
275 return builder.record_blas(cb, layout, {d}, dst.address, scratch.address, dst.address);
276 }));
277 const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
278 if (rep) refit = std::min(refit, ms);
279 }
280 std::printf("%u triangles: %.2f ms (best of 3), refit %.2f ms, result %u bytes, scratch %llu bytes, sort size %u\n",
281 n, best, refit, layout.size, static_cast<unsigned long long>(layout.scratch), layout.sort_size);
239 return 0; 282 return 0;
240 } 283 }
241 284
@@ -287,10 +330,33 @@ int main(int argc, char** argv) {
287 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive 330 b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive
288 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; 331 if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1;
289 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; 332 if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1;
290 // three radix-sort tiles of 2048, the last one partial (fewer rays: the reference's brute force is slow) 333 // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow)
291 Built tiles; 334 Built tiles;
292 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; 335 if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1;
293 336
337 // Updates. Every triangle moves (its own offset, and a stretch), so each box changes; the tree is kept.
338 auto move = [&](Geometry g, float amount) {
339 std::uniform_real_distribution<float> d(-amount, amount);
340 const std::uint32_t floats = g.stride / 4;
341 for (std::size_t v = 0; v + 2 < g.vertex_data.size(); v += floats) {
342 const float dx = d(rng), dy = d(rng);
343 g.vertex_data[v] = g.vertex_data[v] * 1.25f + dx;
344 g.vertex_data[v + 1] = g.vertex_data[v + 1] * 0.8f + dy;
345 if (!g.xy) g.vertex_data[v + 2] += d(rng);
346 }
347 return g;
348 };
349 {
350 Built refitted;
351 const Geometry big = soup(3000); // the radix-sort path
352 const std::vector<Geometry> after = {move(big, 1.5f)};
353 if (build_blas(gpu, builder, dir, "blas_refit_in_place", {big}, refitted, 300, &after)) return 1;
354 Built copied;
355 const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path
356 const std::vector<Geometry> after_grid = {move(g, 0.3f)};
357 if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1;
358 }
359
294 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address 360 // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address
295 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers). 361 // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers).
296 // The instances hold application-style addresses, device address - bias, as the layer's address window does. 362 // The instances hold application-style addresses, device address - bias, as the layer's address window does.
@@ -338,6 +404,95 @@ int main(int argc, char** argv) {
338 } 404 }
339 json += "]}\n"; 405 json += "]}\n";
340 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size())); 406 EXPECT(write_file(dir + "/tlas.json", json.data(), json.size()));
407
408 // The TLAS updated in place: every instance moves and turns; the masked and the BLAS-less ones stay so.
409 Inst moved_insts[sizeof insts / sizeof insts[0]];
410 std::memcpy(moved_insts, insts, sizeof insts);
411 const float c2 = std::cos(1.9f), s2 = std::sin(1.9f);
412 const float turned[12] = {c2, 0, s2, 4, 0, 1, 0, -3, -s2, 0, c2, 2};
413 std::memcpy(moved_insts[0].m, turned, sizeof turned);
414 moved_insts[1].m[3] -= 7;
415 moved_insts[1].m[7] += 5;
416 moved_insts[2].m[11] -= 4;
417 for (std::uint32_t i = 0; i < count; ++i) std::memcpy(static_cast<char*>(descs.map) + 64 * i, moved_insts[i].m, 48);
418 EXPECT(gpu.run([&](VkCommandBuffer cb) {
419 recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias, base);
420 barrier_to_host(gpu, cb);
421 return recorded;
422 }));
423 EXPECT(write_file(dir + "/tlas_refit.bin", static_cast<const char*>(dst.map) + (base - dst.address), layout.size));
424 std::string json2 = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " +
425 std::to_string(bias) + ", \"blas\": [\"blas_random\", \"blas_grid_u16_stride16\"], \"instances\": [";
426 for (std::uint32_t i = 0; i < count; ++i) {
427 json2 += i ? ", {" : "{";
428 json2 += "\"transform\": [";
429 for (int k = 0; k < 12; ++k) json2 += (k ? ", " : "") + num(moved_insts[i].m[k]);
430 json2 += "], \"mask\": " + std::to_string(moved_insts[i].id_mask >> 24) + ", \"blas\": " +
431 std::to_string(moved_insts[i].which) + "}";
432 }
433 json2 += "]}\n";
434 EXPECT(write_file(dir + "/tlas_refit.json", json2.data(), json2.size()));
435
436 // CopyRaytracingAccelerationStructure: a clone of blas_random, its COMPACTED_SIZE (postbuild), a compaction into
437 // a buffer of exactly that size, and a clone of the refitted TLAS. The copies are position-independent.
438 {
439 XdxrLayout blas_layout;
440 EXPECT(blas_layout.compute(1000, false));
441 Buffer clone = make(gpu, blas_layout.size + 256), info = make(gpu, 16);
442 EXPECT(clone.buffer && info.buffer);
443 const std::uint64_t clone_at = (clone.address + 255) & ~std::uint64_t(255);
444 std::memset(info.map, 0xab, 16);
445 EXPECT(gpu.run([&](VkCommandBuffer cb) {
446 const bool ok = builder.record_copy(cb, random.address, clone_at, blas_layout.size) &&
447 builder.record_postbuild(cb, random.address, info.address) &&
448 builder.record_postbuild(cb, clone_at, info.address + 8);
449 barrier_to_host(gpu, cb);
450 return ok;
451 }));
452 std::uint64_t compacted = 0, clone_size = 0;
453 std::memcpy(&compacted, info.map, 8);
454 std::memcpy(&clone_size, static_cast<char*>(info.map) + 8, 8);
455 EXPECT(compacted == blas_layout.size); // a build is exactly its layout's size
456 EXPECT(clone_size == compacted);
457 auto dump_blas = [&](const std::string& name, const Buffer& b, std::uint64_t at, std::size_t bytes) {
458 const std::string j = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) +
459 ", \"triangles\": " + tris_json(random.tris) + "}\n";
460 return write_file(dir + "/" + name + ".bin", static_cast<const char*>(b.map) + (at - b.address), bytes) &&
461 write_file(dir + "/" + name + ".json", j.data(), j.size());
462 };
463 EXPECT(dump_blas("blas_clone", clone, clone_at, blas_layout.size));
464 // COMPACT into exactly the compacted size; a guard word after it must survive
465 Buffer packed = make(gpu, std::size_t(compacted) + 256 + 4);
466 EXPECT(packed.buffer);
467 const std::uint64_t packed_at = (packed.address + 255) & ~std::uint64_t(255);
468 const std::uint32_t guard = 0x600dc0deu;
469 std::memcpy(static_cast<char*>(packed.map) + (packed_at - packed.address) + compacted, &guard, 4);
470 EXPECT(gpu.run([&](VkCommandBuffer cb) {
471 const bool ok = builder.record_copy(cb, clone_at, packed_at, compacted + 4); // more room than needed
472 barrier_to_host(gpu, cb);
473 return ok;
474 }));
475 std::uint32_t after = 0;
476 std::memcpy(&after, static_cast<char*>(packed.map) + (packed_at - packed.address) + compacted, 4);
477 EXPECT(after == guard); // the copy stops at the source's own size
478 EXPECT(dump_blas("blas_compacted", packed, packed_at, std::size_t(compacted)));
479
480 Buffer tclone = make(gpu, layout.size + 256);
481 EXPECT(tclone.buffer);
482 const std::uint64_t tclone_at = (tclone.address + 255) & ~std::uint64_t(255);
483 EXPECT(gpu.run([&](VkCommandBuffer cb) {
484 const bool ok = builder.record_copy(cb, base, tclone_at, layout.size);
485 barrier_to_host(gpu, cb);
486 return ok;
487 }));
488 EXPECT(write_file(dir + "/tlas_refit_clone.bin", static_cast<const char*>(tclone.map) + (tclone_at - tclone.address),
489 layout.size));
490 std::string json3 = json2;
491 json3.replace(json3.find(std::to_string(base)), std::to_string(base).size(), std::to_string(tclone_at));
492 EXPECT(write_file(dir + "/tlas_refit_clone.json", json3.data(), json3.size()));
493 std::printf("copies: blas_clone, blas_compacted (%llu bytes), tlas_refit_clone\n",
494 static_cast<unsigned long long>(compacted));
495 }
341 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size); 496 std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size);
342 return 0; 497 return 0;
343} 498}
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index ac36f40d9..8f5057662 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -51,8 +51,36 @@ using AsyncCompleteFn = void(__stdcall*)(XAsyncBlock*, HRESULT, size_t);
51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*); 51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*);
52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*); 52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*);
53 53
54struct XVersion {
55 union {
56 struct {
57 uint16_t major;
58 uint16_t minor;
59 uint16_t build;
60 uint16_t revision;
61 };
62 uint64_t Value;
63 };
64};
65static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes per GDK spec");
66
67struct XSystemAnalyticsInfo {
68 XVersion osVersion;
69 XVersion hostingOsVersion;
70 char family[64];
71 char form[64];
72};
73static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes per GDK spec");
74
75using AnalyticsInfoFn = XSystemAnalyticsInfo(__stdcall*)();
76using PackageIdentifierFn = HRESULT(__stdcall*)(size_t, char*);
77using PackageMountPathFn = HRESULT(__stdcall*)(void*, size_t, char*);
78using PackagedProcessFn = bool(__stdcall*)();
79
54const char* const kNames[] = { 80const char* const kNames[] = {
55 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId", 81 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId",
82 "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackageIdentifier", "XPackageGetMountPath",
83 "XPackageIsPackagedProcess",
56 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle", 84 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle",
57 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback", 85 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback",
58 "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter", 86 "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter",
@@ -182,6 +210,89 @@ void check_run_time_load() {
182 void* out = reinterpret_cast<void*>(1); 210 void* out = reinterpret_cast<void*>(1);
183 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr, 211 check(query(&some_class, some_class, &out) == static_cast<HRESULT>(0x80070032) && out == nullptr,
184 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); 212 "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer");
213
214 // XThreadingImpl and XErrorImpl, driven the way xgameruntime.lib's thunks in the package's DLLs do: QueryApiImpl
215 // with the class id as both ids, one vtable slot with `this` first, then Release (slot 2).
216 const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
217 const GUID error_cls = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}};
218 using Fn = void*;
219 auto slot = [](void* obj, int index) { return (*static_cast<Fn* const*>(obj))[index]; };
220 auto release = [&](void* obj) { reinterpret_cast<ULONG(STDMETHODCALLTYPE*)(void*)>(slot(obj, 2))(obj); };
221 auto get = [&](const GUID& cls) {
222 void* p = nullptr;
223 return query(&cls, cls, &p) == S_OK ? p : nullptr;
224 };
225 void* t = get(threading);
226 check(t != nullptr, "QueryApiImpl hands out XThreadingImpl for its class id");
227 if (t) {
228 void* again = get(threading);
229 check(again == t, "XThreadingImpl is one process-wide object");
230 release(again);
231 XTaskQueueHandle queue = nullptr;
232 using Create = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueDispatchMode, XTaskQueueDispatchMode,
233 XTaskQueueHandle*);
234 check(reinterpret_cast<Create>(slot(t, 12))(t, XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual,
235 &queue) == S_OK && queue,
236 "slot 12 is XTaskQueueCreate");
237 static std::atomic<int> s_ran{0};
238 using Submit = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, void*,
239 XTaskQueueCallback*);
240 XTaskQueueCallback* cb = [](void* ctx, bool canceled) {
241 if (!canceled) static_cast<std::atomic<int>*>(ctx)->fetch_add(1);
242 };
243 check(reinterpret_cast<Submit>(slot(t, 18))(t, queue, XTaskQueuePort::Work, &s_ran, cb) == S_OK,
244 "slot 18 is XTaskQueueSubmitCallback");
245 using Dispatch = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, uint32_t);
246 check(reinterpret_cast<Dispatch>(slot(t, 16))(t, queue, XTaskQueuePort::Work, 0) && s_ran.load() == 1,
247 "slot 16 is XTaskQueueDispatch: the callback ran on the work port");
248 XTaskQueueHandle dup = nullptr;
249 using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueueHandle*);
250 check(reinterpret_cast<Dup>(slot(t, 15))(t, queue, &dup) == S_OK && dup,
251 "slot 15 is XTaskQueueDuplicateHandle");
252 using Close = void(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle);
253 reinterpret_cast<Close>(slot(t, 17))(t, dup);
254 reinterpret_cast<Close>(slot(t, 17))(t, queue);
255 using SetSensitive = HRESULT(STDMETHODCALLTYPE*)(void*, bool);
256 using IsSensitive = bool(STDMETHODCALLTYPE*)(void*);
257 check(reinterpret_cast<SetSensitive>(slot(t, 27))(t, true) == S_OK &&
258 reinterpret_cast<IsSensitive>(slot(t, 30))(t) &&
259 reinterpret_cast<SetSensitive>(slot(t, 27))(t, false) == S_OK &&
260 !reinterpret_cast<IsSensitive>(slot(t, 30))(t),
261 "slots 27 and 30 set and read this thread's time-sensitive flag");
262 void* unk = nullptr;
263 const GUID iunknown = {0, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}};
264 using QI = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
265 check(reinterpret_cast<QI>(slot(t, 0))(t, iunknown, &unk) == S_OK && unk == t &&
266 reinterpret_cast<QI>(slot(t, 0))(t, error_cls, &unk) == E_NOINTERFACE && !unk,
267 "QueryInterface answers IUnknown and the class id, not another class");
268 release(t);
269 release(t);
270 }
271 void* e = get(error_cls);
272 check(e != nullptr, "QueryApiImpl hands out XErrorImpl for its class id");
273 if (e) {
274 struct Seen {
275 HRESULT hr;
276 char msg[32];
277 } seen{};
278 using Callback = bool(CALLBACK*)(HRESULT, const char*, void*);
279 Callback on_error = [](HRESULT hr, const char* msg, void* ctx) {
280 auto* s = static_cast<Seen*>(ctx);
281 s->hr = hr;
282 strncpy_s(s->msg, msg ? msg : "", _TRUNCATE);
283 return true;
284 };
285 using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*);
286 using Report = void(STDMETHODCALLTYPE*)(void*, HRESULT, const char*);
287 reinterpret_cast<SetCallback>(slot(e, 4))(e, on_error, &seen);
288 reinterpret_cast<Report>(slot(e, 3))(e, E_FAIL, "offline test");
289 check(seen.hr == E_FAIL && std::strcmp(seen.msg, "offline test") == 0,
290 "slot 3 is XErrorReport and reaches the callback slot 4 (XErrorSetCallback) set");
291 reinterpret_cast<SetCallback>(slot(e, 4))(e, nullptr, nullptr);
292 using SetOptions = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t);
293 check(reinterpret_cast<SetOptions>(slot(e, 5))(e, 0, 0) == S_OK, "slot 5 is XErrorSetOptions");
294 release(e);
295 }
185 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 296 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
186 297
187 HMODULE k32 = load_w(L"kernel32.dll"); 298 HMODULE k32 = load_w(L"kernel32.dll");
@@ -229,6 +340,53 @@ int main() {
229 check(console_id(sizeof(id), id, &used) == S_OK && used == 39 && std::strlen(id) == 38, 340 check(console_id(sizeof(id), id, &used) == S_OK && used == 39 && std::strlen(id) == 38,
230 "XSystemGetConsoleId fills 39 bytes (38 characters and the terminator)"); 341 "XSystemGetConsoleId fills 39 bytes (38 characters and the terminator)");
231 342
343 auto analytics_info = get<AnalyticsInfoFn>("XSystemGetAnalyticsInfo");
344 XSystemAnalyticsInfo info = analytics_info();
345 check(info.osVersion.major == 10 && info.osVersion.minor == 0 && info.osVersion.build == 22000 &&
346 info.osVersion.revision == 0,
347 "XSystemGetAnalyticsInfo returns osVersion 10.0.22000.0");
348 check(info.hostingOsVersion.major == 10 && info.hostingOsVersion.minor == 0 &&
349 info.hostingOsVersion.build == 22000 && info.hostingOsVersion.revision == 0,
350 "XSystemGetAnalyticsInfo returns hostingOsVersion 10.0.22000.0");
351 check(std::strcmp(info.family, "Xbox") == 0, "XSystemGetAnalyticsInfo returns family 'Xbox'");
352 check(std::strcmp(info.form, "Xbox Series X") == 0, "XSystemGetAnalyticsInfo returns form 'Xbox Series X'");
353
354 auto package_id = get<PackageIdentifierFn>("XPackageGetCurrentProcessPackageIdentifier");
355 check(package_id(0, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects null buffer and size 0");
356 char pkg_id[64] = {};
357 check(package_id(0, pkg_id) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects size 0 with buffer");
358 check(package_id(10, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackageIdentifier rejects null pointer with size");
359 check(package_id(16, pkg_id) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
360 "XPackageGetCurrentProcessPackageIdentifier rejects insufficient buffer");
361 check(package_id(sizeof(pkg_id), pkg_id) == S_OK && std::strlen(pkg_id) == 32,
362 "XPackageGetCurrentProcessPackageIdentifier fills 33-byte package identifier");
363
364 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", "CustomTestPackageId_123456789012");
365 check(package_id(sizeof(pkg_id), pkg_id) == S_OK &&
366 std::strcmp(pkg_id, "CustomTestPackageId_123456789012") == 0,
367 "XPackageGetCurrentProcessPackageIdentifier respects LEONIDA_PACKAGE_ID override");
368 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", nullptr);
369
370 auto mount_path = get<PackageMountPathFn>("XPackageGetMountPath");
371 check(mount_path(nullptr, 0, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null buffer and size 0");
372 char mnt_path[MAX_PATH] = {};
373 check(mount_path(nullptr, 0, mnt_path) == E_INVALIDARG, "XPackageGetMountPath rejects size 0 with buffer");
374 check(mount_path(nullptr, 10, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null pointer with size");
375
376 SetEnvironmentVariableA("LEONIDA_GAME_DIR", "C:\\LeonidaGameDir");
377 check(mount_path(nullptr, 5, mnt_path) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
378 "XPackageGetMountPath rejects insufficient buffer");
379 check(mount_path(nullptr, sizeof(mnt_path), mnt_path) == S_OK &&
380 std::strcmp(mnt_path, "C:\\LeonidaGameDir") == 0,
381 "XPackageGetMountPath returns configured game directory");
382 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr);
383
384 auto is_packaged = get<PackagedProcessFn>("XPackageIsPackagedProcess");
385 check(is_packaged() == true, "XPackageIsPackagedProcess returns true by default");
386 SetEnvironmentVariableA("LEONIDA_PACKAGED", "0");
387 check(is_packaged() == false, "XPackageIsPackagedProcess respects LEONIDA_PACKAGED=0 override");
388 SetEnvironmentVariableA("LEONIDA_PACKAGED", nullptr);
389
232 // Work on the thread pool, completions dispatched by the "game loop" on this thread. 390 // Work on the thread pool, completions dispatched by the "game loop" on this thread.
233 auto create = get<QueueCreateFn>("XTaskQueueCreate"); 391 auto create = get<QueueCreateFn>("XTaskQueueCreate");
234 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle"); 392 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle");
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 429261e98..f115b6655 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -70,7 +70,7 @@ namespace xs = rt::d3d12_xs;
70 70
71// ---- Mocks ---- 71// ---- Mocks ----
72 72
73enum class Kind { device, queue, fence, resource }; 73enum class Kind { device, queue, fence, resource, allocator };
74 74
75constexpr unsigned kMockSlots = 128; 75constexpr unsigned kMockSlots = 128;
76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens 76constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens
@@ -84,6 +84,7 @@ struct Mock {
84 long refs; 84 long refs;
85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) 85 int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only)
86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do 86 bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do
87 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
87 bool create_null; // device: creation returns create_result with no object 88 bool create_null; // device: creation returns create_result with no object
88 HRESULT create_result; // device: what creation returns (S_OK makes the object) 89 HRESULT create_result; // device: what creation returns (S_OK makes the object)
89 Mock* last_child; // device: the object its last creation or open made 90 Mock* last_child; // device: the object its last creation or open made
@@ -126,6 +127,9 @@ bool mock_has(const Mock* m, REFIID iid) {
126 case Kind::fence: 127 case Kind::fence:
127 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); 128 return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1)));
128 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); 129 case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource));
130 case Kind::allocator:
131 return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) ||
132 (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag));
129 default: return false; 133 default: return false;
130 } 134 }
131} 135}
@@ -148,6 +152,7 @@ HRESULT mock_create(Mock* device, Kind kind, std::uint64_t riid, std::uint64_t o
148 if (device->create_null || FAILED(device->create_result)) return device->create_result; 152 if (device->create_null || FAILED(device->create_result)) return device->create_result;
149 Mock* child = new_mock(kind); 153 Mock* child = new_mock(kind);
150 child->fence1 = device->fence1; 154 child->fence1 = device->fence1;
155 child->allocator_tag = device->allocator_tag;
151 device->last_child = child; 156 device->last_child = child;
152 return mock_query(child, reinterpret_cast<const IID*>(riid), out); 157 return mock_query(child, reinterpret_cast<const IID*>(riid), out);
153} 158}
@@ -163,6 +168,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
163 if (m->kind == Kind::device) { 168 if (m->kind == Kind::device) {
164 switch (slot) { 169 switch (slot) {
165 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue 170 case 8: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue
171 case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator
166 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 172 case 75: return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1
167 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence 173 case 36: return static_cast<std::uint32_t>(mock_create(m, Kind::fence, a3, a4)); // CreateFence
168 case 32: // OpenSharedHandle 174 case 32: // OpenSharedHandle
@@ -248,10 +254,11 @@ const IID kDevice1Iid = __uuidof(ID3D12Device1);
248const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; 254const D3D12_COMMAND_QUEUE_DESC kQueueDesc{};
249 255
250// A device proxy over a new mock device. The proxy takes the mock's one reference. 256// A device proxy over a new mock device. The proxy takes the mock's one reference.
251void* make_device(Mock*& mock, int level, bool fence1) { 257void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true) {
252 mock = new_mock(Kind::device); 258 mock = new_mock(Kind::device);
253 mock->device_level = level; 259 mock->device_level = level;
254 mock->fence1 = fence1; 260 mock->fence1 = fence1;
261 mock->allocator_tag = allocator_tag;
255 mock->refs = 1; 262 mock->refs = 1;
256 void* device = nullptr; 263 void* device = nullptr;
257 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device))) 264 if (FAILED(xs::create_device_proxy(reinterpret_cast<ID3D12Device*>(mock), __uuidof(ID3D12Device), &device)))
@@ -563,7 +570,85 @@ int check_alloc_failures() {
563 return 0; 570 return 0;
564} 571}
565 572
566// ---- 6. The refused tail and the guard region ---- 573// ---- 6. Command allocators (device slot 9) ----
574
575int check_allocators() {
576 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
577 // An allocator that answers Leonida's tag (its lists resolve a proxy) comes back wrapped.
578 {
579 Mock* mock = nullptr;
580 void* device = make_device(mock, 9, true, true);
581 EXPECT(device);
582 const unsigned long device_refs = xs::device_proxy_ref_count(device);
583 void* allocator = nullptr;
584 EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK);
585 Mock* const real = mock->last_child;
586 EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real));
587 EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1);
588 EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1);
589 // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused.
590 EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1);
591 for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot)
592 EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0);
593 // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces.
594 void* found = reinterpret_cast<void*>(1);
595 EXPECT(hr_of(raw(allocator, 0, word(&xs::kLeonidaCommandAllocatorTag), word(&found))) == E_NOINTERFACE &&
596 !found);
597 EXPECT(hr_of(raw(allocator, 0, word(&allocator_iid), word(&found))) == S_OK && found == allocator);
598 EXPECT(release(found) == 1);
599 // An allocator is a pageable: MakeResident gives the real runtime the real allocator.
600 const std::uint64_t objects[1] = {word(allocator)};
601 EXPECT(hr_of(raw(device, 34, 1, word(objects))) == S_OK && mock->array[34][0] == word(real));
602 EXPECT(release(allocator) == 0 && real->refs == 0);
603 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
604 // Null IID, null output, a failing or empty creation, an IID the allocator lacks.
605 void* out = reinterpret_cast<void*>(1);
606 EXPECT(hr_of(raw(device, 9, 0, 0, word(&out))) == E_POINTER && !out);
607 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), 0)) == S_FALSE); // the device's own answer
608 mock->create_result = E_OUTOFMEMORY;
609 out = reinterpret_cast<void*>(1);
610 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_OUTOFMEMORY && !out);
611 mock->create_result = S_OK;
612 mock->create_null = true;
613 out = reinterpret_cast<void*>(1);
614 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out))) == E_FAIL && !out);
615 mock->create_null = false;
616 const IID fence_iid = __uuidof(ID3D12Fence);
617 out = reinterpret_cast<void*>(1);
618 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
619 EXPECT(mock->last_child->refs == 0);
620 // A refused allocation for the proxy: E_OUTOFMEMORY, and the real allocator is released.
621 g_fail_news = 1;
622 out = reinterpret_cast<void*>(1);
623 const HRESULT starved = hr_of(raw(device, 9, 0, word(&allocator_iid), word(&out)));
624 g_fail_news = 0;
625 EXPECT(starved == E_OUTOFMEMORY && !out && mock->last_child->refs == 0);
626 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
627 EXPECT(release(device) == 0 && mock->refs == 0);
628 }
629 // An allocator without the tag (a PC runtime allocator, whose lists could not resolve a proxy) comes back as it
630 // is, as the interface asked for.
631 {
632 Mock* mock = nullptr;
633 void* device = make_device(mock, 9, true, false);
634 EXPECT(device);
635 void* allocator = nullptr;
636 EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK);
637 EXPECT(allocator == mock->last_child && !xs::is_allocator_proxy(allocator) && mock->last_child->refs == 1);
638 Mock* const real = mock->last_child;
639 EXPECT(release(allocator) == 0 && real->refs == 0);
640 const IID fence_iid = __uuidof(ID3D12Fence);
641 void* out = reinterpret_cast<void*>(1);
642 EXPECT(hr_of(raw(device, 9, 0, word(&fence_iid), word(&out))) == E_NOINTERFACE && !out);
643 EXPECT(mock->last_child->refs == 0);
644 EXPECT(release(device) == 0 && mock->refs == 0);
645 }
646 std::printf("%s: allocators answering Leonida's tag are wrapped (Reset forwarded, tail refused, residency "
647 "unwrapped, references balanced); others come back unwrapped; failures leave no reference\n", g_label);
648 return 0;
649}
650
651// ---- 7. The refused tail and the guard region ----
567 652
568int check_tail(bool want_guarded) { 653int check_tail(bool want_guarded) {
569 Mock* mock = nullptr; 654 Mock* mock = nullptr;
@@ -686,7 +771,7 @@ int main(int argc, char** argv) {
686 if (argc == 2) return run_fault_mode(argv[1]); 771 if (argc == 2) return run_fault_mode(argv[1]);
687 if (argc != 1) return 2; 772 if (argc != 1) return 2;
688 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || 773 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() ||
689 check_alloc_failures()) 774 check_alloc_failures() || check_allocators())
690 return 1; 775 return 1;
691 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 776 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
692 return 0; 777 return 0;
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py
index ac22c856c..6a6c449de 100644
--- a/scripts/audit_shader4_regs.py
+++ b/scripts/audit_shader4_regs.py
@@ -371,7 +371,7 @@ def main(argv=None):
371 if a.json_out: 371 if a.json_out:
372 try: 372 try:
373 os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) 373 os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True)
374 with open(a.json_out, "w", encoding="utf-8") as f: 374 with open(a.json_out, "w", encoding="utf-8", newline="\n") as f:
375 json.dump(rep, f, indent=2) 375 json.dump(rep, f, indent=2)
376 f.write("\n") 376 f.write("\n")
377 except OSError as e: 377 except OSError as e:
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index e71bcfe27..b251a281c 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -1,4 +1,4 @@
1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores. 1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores.
2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. 2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly.
3# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or 3# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or
4# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it. 4# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it.
@@ -58,8 +58,10 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
58} 58}
59 59
60# A .cmd file avoids cmd.exe's quote stripping on paths with spaces. 60# A .cmd file avoids cmd.exe's quote stripping on paths with spaces.
61# Switch to UTF-8 (CP 65001) before invoking CMake/Ninja/cl.exe so non-English MSVC /showIncludes prefixes
62# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP.
61$bat = Join-Path $out "_build.cmd" 63$bat = Join-Path $out "_build.cmd"
62"@echo off`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat 64"@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat
63 65
64$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 66$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru
65$null = $p.Handle # keeps the exit code readable after WaitForExit 67$null = $p.Handle # keeps the exit code readable after WaitForExit
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 7209c364c..025504fb8 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,7 +25,7 @@ sys.path.insert(0, os.path.join(ROOT, "tools"))
25import mc_command # noqa: E402 25import mc_command # noqa: E402
26sys.path.insert(0, SHADER_DIR) 26sys.path.insert(0, SHADER_DIR)
27from build import CLIP_CASES, clip_container, shader_source 27from build import CLIP_CASES, clip_container, shader_source
28from check import Skip, clip_test, fmt_1010102_test, fmt_sint32_test, fmt_xy_xyz_test 28from check import Skip, clip_test, fmt_1010102_test, fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test
29from compute_fixture import compute_header 29from compute_fixture import compute_header
30from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 30from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
31from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, 31from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
@@ -38,7 +38,7 @@ from check import gpu_test_timeout, timed_out # per-program time limit (LEONID
38from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS 38from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS
39from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, 39from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip,
40 vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 40 vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
41from check import PIXEL_VERTEX, interp_f16_high_problem, ij_computed_problem # pixel producers and checks 41from check import PIXEL_VERTEX, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks
42from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries 42from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries
43from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide 43from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide
44 44
@@ -115,7 +115,7 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None:
115 continue 115 continue
116 if ln.startswith("\t"): 116 if ln.startswith("\t"):
117 lines.append(ln) 117 lines.append(ln)
118 with open(s_path, "w", encoding="utf-8") as f: 118 with open(s_path, "w", encoding="utf-8", newline="\n") as f:
119 f.write("\n".join(lines) + "\n") 119 f.write("\n".join(lines) + "\n")
120 120
121 121
@@ -542,13 +542,15 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool,
542OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", 542OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test",
543 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", 543 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test",
544 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", 544 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test",
545 "ps_m3_post": "d3d12_m3_frame_test"} 545 "ps_m3_post": "d3d12_m3_frame_test",
546 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
547 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test"}
546 548
547 549
548# Shaders a selected test draws with, built even when the filter leaves them out (#192). 550# Shaders a selected test draws with, built even when the filter leaves them out (#192).
549DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", 551DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm",
550 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", 552 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm",
551 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", 553 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm",
552 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", 554 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm",
553 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", 555 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm",
554 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", 556 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm",
@@ -839,6 +841,10 @@ def run_suite(a, work: str) -> int:
839 # TEST-185: xy/xyz format loads and stores, words measured natively on a Radeon 680M (the .asm header) 841 # TEST-185: xy/xyz format loads and stores, words measured natively on a Radeon 680M (the .asm header)
840 problem = fmt_xy_xyz_test(a.build, spirv_dir, cs_env) 842 problem = fmt_xy_xyz_test(a.build, spirv_dir, cs_env)
841 results.append((name, not problem, problem or "128/128 dumped words exact")) 843 results.append((name, not problem, problem or "128/128 dumped words exact"))
844 elif name == "cs_tbuffer_store":
845 # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header)
846 problem = tbuffer_store_test(a.build, spirv_dir, cs_env)
847 results.append((name, not problem, problem or "128/128 dumped words exact"))
842 elif name == "cs_global_neg_offset": 848 elif name == "cs_global_neg_offset":
843 # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte 849 # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte
844 # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement. 850 # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement.
@@ -879,7 +885,7 @@ def run_suite(a, work: str) -> int:
879 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", 885 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load",
880 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", 886 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent",
881 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_barrier_early_end", 887 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_barrier_early_end",
882 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64"): 888 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_lds_b64_cmpst"):
883 cs_dump_wants = { 889 cs_dump_wants = {
884 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], 890 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000],
885 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone 891 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone
@@ -901,6 +907,9 @@ def run_suite(a, work: str) -> int:
901 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], 907 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE],
902 # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) 908 # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header)
903 "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], 909 "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234],
910 # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header)
911 "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004,
912 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC],
904 # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant 913 # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant
905 "cs_exec_const": [16, 8, 2, 16, 0, 16], 914 "cs_exec_const": [16, 8, 2, 16, 0, 16],
906 # constant lane masks: lane L takes bit L (cs_w32_mask_imm.asm / cs_w64_mask_imm.asm headers) 915 # constant lane masks: lane L takes bit L (cs_w32_mask_imm.asm / cs_w64_mask_imm.asm headers)
@@ -969,7 +978,8 @@ def run_suite(a, work: str) -> int:
969 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", 978 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop",
970 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", 979 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops",
971 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_sincos", 980 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_sincos",
972 "cs_exec_const", "cs_w32_mask_imm", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 981 "cs_lds_b64_cmpst", "cs_exec_const", "cs_w32_mask_imm",
982 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
973 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial 983 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial
974 if partial and not emulated: 984 if partial and not emulated:
975 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") 985 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64")
@@ -981,7 +991,8 @@ def run_suite(a, work: str) -> int:
981 ok, detail = None, str(skip) 991 ok, detail = None, str(skip)
982 else: 992 else:
983 ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, 993 ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated,
984 hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16")) 994 hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16",
995 "cs_lds_b64_cmpst"))
985 results.append((name, ok, detail)) 996 results.append((name, ok, detail))
986 elif name == "cs_imgstore": 997 elif name == "cs_imgstore":
987 rc, msg = run_cmd([vk_store, spv]) 998 rc, msg = run_cmd([vk_store, spv])
@@ -1042,10 +1053,12 @@ def run_suite(a, work: str) -> int:
1042 else: 1053 else:
1043 results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else 1054 results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else
1044 f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}")) 1055 f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}"))
1045 elif name == "ps_tex": 1056 elif name in ("ps_tex", "ps_imgatomic"):
1046 # A texture through the descriptor hash table and the bindless set. vk_bindless_test compares the 1057 # A texture through the descriptor hash table and the bindless set (ps_tex), or image atomics in a pixel
1047 # pixels itself, and exits 77 where the device lacks a feature the set or the shader needs. 1058 # shader through the set's r32ui storage arrays (ps_imgatomic, drawn with vs_ids). vk_bindless_test
1048 rc, msg = run_cmd([vk_bindless, vs_tri, spv]) 1059 # compares the result itself, and exits 77 where the device lacks a feature the set or shader needs.
1060 vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_imgatomic" else vs_tri
1061 rc, msg = run_cmd([vk_bindless, vs, spv])
1049 lines = msg.splitlines() 1062 lines = msg.splitlines()
1050 if rc == 77: 1063 if rc == 77:
1051 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device") 1064 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device")
@@ -1110,6 +1123,8 @@ def run_suite(a, work: str) -> int:
1110 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) 1123 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header)
1111 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000), 1124 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000),
1112 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 1125 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
1126 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
1127 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
1113 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), 1128 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000),
1114 "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 1129 "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64
1115 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) 1130 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers)
@@ -1168,6 +1183,11 @@ def run_suite(a, work: str) -> int:
1168 with open(raw, "rb") as source: 1183 with open(raw, "rb") as source:
1169 problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read()))) 1184 problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read())))
1170 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" 1185 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6"
1186 elif name == "ps_mandelbrot":
1187 with open(raw, "rb") as source:
1188 px = list(struct.iter_unpack("<4I", source.read()))
1189 problem = mandelbrot_problem(px)
1190 ok, detail = not problem, problem or f"{len(px)}/{len(px)} iteration counts match the float32 model"
1171 else: 1191 else:
1172 ok, detail = False, "no checker defined" 1192 ok, detail = False, "no checker defined"
1173 results.append((name, ok, detail)) 1193 results.append((name, ok, detail))
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index b55ea9b91..0a02525e5 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -251,7 +251,7 @@ def main() -> int:
251 if args.summary: 251 if args.summary:
252 try: 252 try:
253 _make_parent(args.summary) 253 _make_parent(args.summary)
254 with open(args.summary, "a", encoding="utf-8") as f: 254 with open(args.summary, "a", encoding="utf-8", newline="\n") as f:
255 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") 255 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n")
256 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") 256 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n")
257 f.write("| Test | Result | Required |\n|---|---|---|\n") 257 f.write("| Test | Result | Required |\n|---|---|---|\n")
diff --git a/tests/semantic/README.md b/tests/semantic/README.md
index 65b741083..5244ec9b3 100644
--- a/tests/semantic/README.md
+++ b/tests/semantic/README.md
@@ -35,6 +35,10 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader):
35 RDNA2 ISA's swizzled buffer_offset and its OOB_SELECT 3 rule (docs/design.md Swizzled buffer addressing): the 35 RDNA2 ISA's swizzled buffer_offset and its OOB_SELECT 3 rule (docs/design.md Swizzled buffer addressing): the
36 exact addresses loaded and stored for dword, multi-dword and typed accesses, each with a literal and a run-time 36 exact addresses loaded and stored for dword, multi-dword and typed accesses, each with a literal and a run-time
37 V#, and the GPU fixture `cs_buf_swizzle` on 64 threads. 37 V#, and the GPU fixture `cs_buf_swizzle` on 64 threads.
38- `test_tbuffer_store.py` runs the GPU test `cs_tbuffer_store` (13 `tbuffer_store_format_*` stores through V#s
39 whose format differs from the instruction's, or is 0) and asserts the 52 words `check.py` expects, measured natively on a
40 Radeon 680M; also the default `BUF_FMT_8_UNORM` byte, a format without an encoder staying `Unsupported`, and the
41 store's data VGPRs counting as reads.
38- `test_scalar_mem_smem.py` runs the code `Gen.scalar_load` emits with its own small evaluator (64-bit 42- `test_scalar_mem_smem.py` runs the code `Gen.scalar_load` emits with its own small evaluator (64-bit
39 addresses, forward selection constructs) and asserts the SGPR values and the addresses read, including the 43 addresses, forward selection constructs) and asserts the SGPR values and the addresses read, including the
40 measured SMEM truncation, `s_buffer_load` `NUM_RECORDS` bound and signed `s_load` immediate. 44 measured SMEM truncation, `s_buffer_load` `NUM_RECORDS` bound and signed `s_load` immediate.
diff --git a/tests/semantic/fixtures/disasm/cs_tbuffer_store.s b/tests/semantic/fixtures/disasm/cs_tbuffer_store.s
new file mode 100644
index 000000000..9f52a7b82
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/cs_tbuffer_store.s
@@ -0,0 +1,233 @@
1; cs_tbuffer_store test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_tbuffer_store.asm
2 v_cmpx_eq_u32_e32 0, v0
3 v_mov_b32_e32 v1, 0xa5a50200
4 v_mov_b32_e32 v2, 0xa5a50204
5 v_mov_b32_e32 v3, 0xa5a50208
6 v_mov_b32_e32 v4, 0xa5a5020c
7 v_mov_b32_e32 v5, 0x200
8 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
9 v_mov_b32_e32 v1, 0xa5a50210
10 v_mov_b32_e32 v2, 0xa5a50214
11 v_mov_b32_e32 v3, 0xa5a50218
12 v_mov_b32_e32 v4, 0xa5a5021c
13 v_mov_b32_e32 v5, 0x210
14 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
15 v_mov_b32_e32 v1, 0xa5a50220
16 v_mov_b32_e32 v2, 0xa5a50224
17 v_mov_b32_e32 v3, 0xa5a50228
18 v_mov_b32_e32 v4, 0xa5a5022c
19 v_mov_b32_e32 v5, 0x220
20 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
21 v_mov_b32_e32 v1, 0xa5a50230
22 v_mov_b32_e32 v2, 0xa5a50234
23 v_mov_b32_e32 v3, 0xa5a50238
24 v_mov_b32_e32 v4, 0xa5a5023c
25 v_mov_b32_e32 v5, 0x230
26 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
27 v_mov_b32_e32 v1, 0xa5a50240
28 v_mov_b32_e32 v2, 0xa5a50244
29 v_mov_b32_e32 v3, 0xa5a50248
30 v_mov_b32_e32 v4, 0xa5a5024c
31 v_mov_b32_e32 v5, 0x240
32 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
33 v_mov_b32_e32 v1, 0xa5a50250
34 v_mov_b32_e32 v2, 0xa5a50254
35 v_mov_b32_e32 v3, 0xa5a50258
36 v_mov_b32_e32 v4, 0xa5a5025c
37 v_mov_b32_e32 v5, 0x250
38 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
39 v_mov_b32_e32 v1, 0xa5a50260
40 v_mov_b32_e32 v2, 0xa5a50264
41 v_mov_b32_e32 v3, 0xa5a50268
42 v_mov_b32_e32 v4, 0xa5a5026c
43 v_mov_b32_e32 v5, 0x260
44 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
45 v_mov_b32_e32 v1, 0xa5a50270
46 v_mov_b32_e32 v2, 0xa5a50274
47 v_mov_b32_e32 v3, 0xa5a50278
48 v_mov_b32_e32 v4, 0xa5a5027c
49 v_mov_b32_e32 v5, 0x270
50 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
51 v_mov_b32_e32 v1, 0xa5a50280
52 v_mov_b32_e32 v2, 0xa5a50284
53 v_mov_b32_e32 v3, 0xa5a50288
54 v_mov_b32_e32 v4, 0xa5a5028c
55 v_mov_b32_e32 v5, 0x280
56 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
57 v_mov_b32_e32 v1, 0xa5a50290
58 v_mov_b32_e32 v2, 0xa5a50294
59 v_mov_b32_e32 v3, 0xa5a50298
60 v_mov_b32_e32 v4, 0xa5a5029c
61 v_mov_b32_e32 v5, 0x290
62 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
63 v_mov_b32_e32 v1, 0xa5a502a0
64 v_mov_b32_e32 v2, 0xa5a502a4
65 v_mov_b32_e32 v3, 0xa5a502a8
66 v_mov_b32_e32 v4, 0xa5a502ac
67 v_mov_b32_e32 v5, 0x2a0
68 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
69 v_mov_b32_e32 v1, 0xa5a502b0
70 v_mov_b32_e32 v2, 0xa5a502b4
71 v_mov_b32_e32 v3, 0xa5a502b8
72 v_mov_b32_e32 v4, 0xa5a502bc
73 v_mov_b32_e32 v5, 0x2b0
74 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
75 v_mov_b32_e32 v1, 0xa5a502c0
76 v_mov_b32_e32 v2, 0xa5a502c4
77 v_mov_b32_e32 v3, 0xa5a502c8
78 v_mov_b32_e32 v4, 0xa5a502cc
79 v_mov_b32_e32 v5, 0x2c0
80 buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
81 s_waitcnt_vscnt null, 0x0
82 s_mov_b32 s4, s0
83 s_mov_b32 s5, s1
84 v_mov_b32_e32 v20, 0x3f800000
85 v_mov_b32_e32 v21, 0x40000000
86 v_mov_b32_e32 v22, 0x40400000
87 v_mov_b32_e32 v23, 0x40800000
88 s_mov_b32 s6, 0xffffffff
89 s_mov_b32 s7, 0x31016fac
90 v_mov_b32_e32 v5, 0x200
91 tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
92 v_mov_b32_e32 v20, 0x3f800000
93 v_mov_b32_e32 v21, 0x40000000
94 s_mov_b32 s6, 0xffffffff
95 s_mov_b32 s7, 0x3104dfac
96 v_mov_b32_e32 v5, 0x210
97 tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen
98 v_mov_b32_e32 v20, 0x1
99 v_mov_b32_e32 v21, 0x2
100 v_mov_b32_e32 v22, 0x3
101 s_mov_b32 s6, 0xffffffff
102 s_mov_b32 s7, 0x31016fac
103 v_mov_b32_e32 v5, 0x220
104 tbuffer_store_format_xyz v[20:22], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UINT] offen
105 v_mov_b32_e32 v20, 0x3f800000
106 s_mov_b32 s6, 0xffffffff
107 s_mov_b32 s7, 0x3104dfac
108 v_mov_b32_e32 v5, 0x231
109 tbuffer_store_format_x v20, v5, s[4:7], 0 offen
110 v_mov_b32_e32 v20, 0x40000000
111 s_mov_b32 s6, 0xffffffff
112 s_mov_b32 s7, 0x31016fac
113 v_mov_b32_e32 v5, 0x242
114 tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_16_FLOAT] offen
115 v_mov_b32_e32 v20, 0x3f800000
116 v_mov_b32_e32 v21, 0x0
117 v_mov_b32_e32 v22, 0x3e800000
118 v_mov_b32_e32 v23, 0x3f800000
119 s_mov_b32 s6, 0xffffffff
120 s_mov_b32 s7, 0x31016fac
121 v_mov_b32_e32 v5, 0x250
122 tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen
123 v_mov_b32_e32 v20, 0x3f800000
124 v_mov_b32_e32 v21, 0x40000000
125 v_mov_b32_e32 v22, 0x40400000
126 v_mov_b32_e32 v23, 0x40800000
127 s_mov_b32 s6, 0xffffffff
128 s_mov_b32 s7, 0x3104dfac
129 v_mov_b32_e32 v5, 0x260
130 tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
131 v_mov_b32_e32 v20, 0x40003c00
132 s_mov_b32 s6, 0xffffffff
133 s_mov_b32 s7, 0x3104dfac
134 v_mov_b32_e32 v5, 0x270
135 tbuffer_store_format_d16_xy v20, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen
136 v_mov_b32_e32 v20, 0x38003c00
137 v_mov_b32_e32 v21, 0x3c000000
138 s_mov_b32 s6, 0xffffffff
139 s_mov_b32 s7, 0x31016fac
140 v_mov_b32_e32 v5, 0x280
141 tbuffer_store_format_d16_xyzw v[20:21], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen
142 v_mov_b32_e32 v20, 0x3f800000
143 v_mov_b32_e32 v21, 0x40000000
144 s_mov_b32 s6, 0x298
145 s_mov_b32 s7, 0x31016fac
146 v_mov_b32_e32 v5, 0x290
147 tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen
148 v_mov_b32_e32 v20, 0x3f800000
149 s_mov_b32 s6, 0x2a1
150 s_mov_b32 s7, 0x3104dfac
151 v_mov_b32_e32 v5, 0x2a0
152 tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_8_UNORM] offen
153 v_mov_b32_e32 v20, 0x3f800000
154 v_mov_b32_e32 v21, 0x40000000
155 v_mov_b32_e32 v22, 0x40400000
156 v_mov_b32_e32 v23, 0x40800000
157 s_mov_b32 s6, 0xffffffff
158 s_mov_b32 s7, 0x3104dfac
159 v_mov_b32_e32 v5, 0x2b0
160 tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_FLOAT] offen
161 v_mov_b32_e32 v20, 0x3f800000
162 v_mov_b32_e32 v21, 0x40000000
163 s_mov_b32 s6, 0xffffffff
164 s_mov_b32 s7, 0x31000fac
165 v_mov_b32_e32 v5, 0x2c0
166 tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen
167 s_waitcnt_vscnt null, 0x0
168 v_mov_b32_e32 v5, 0x200
169 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
170 s_waitcnt vmcnt(0)
171 v_mov_b32_e32 v6, 0x0
172 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
173 v_mov_b32_e32 v5, 0x210
174 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
175 s_waitcnt vmcnt(0)
176 v_mov_b32_e32 v6, 0x10
177 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
178 v_mov_b32_e32 v5, 0x220
179 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
180 s_waitcnt vmcnt(0)
181 v_mov_b32_e32 v6, 0x20
182 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
183 v_mov_b32_e32 v5, 0x230
184 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
185 s_waitcnt vmcnt(0)
186 v_mov_b32_e32 v6, 0x30
187 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
188 v_mov_b32_e32 v5, 0x240
189 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
190 s_waitcnt vmcnt(0)
191 v_mov_b32_e32 v6, 0x40
192 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
193 v_mov_b32_e32 v5, 0x250
194 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
195 s_waitcnt vmcnt(0)
196 v_mov_b32_e32 v6, 0x50
197 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
198 v_mov_b32_e32 v5, 0x260
199 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
200 s_waitcnt vmcnt(0)
201 v_mov_b32_e32 v6, 0x60
202 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
203 v_mov_b32_e32 v5, 0x270
204 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
205 s_waitcnt vmcnt(0)
206 v_mov_b32_e32 v6, 0x70
207 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
208 v_mov_b32_e32 v5, 0x280
209 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
210 s_waitcnt vmcnt(0)
211 v_mov_b32_e32 v6, 0x80
212 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
213 v_mov_b32_e32 v5, 0x290
214 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
215 s_waitcnt vmcnt(0)
216 v_mov_b32_e32 v6, 0x90
217 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
218 v_mov_b32_e32 v5, 0x2a0
219 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
220 s_waitcnt vmcnt(0)
221 v_mov_b32_e32 v6, 0xa0
222 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
223 v_mov_b32_e32 v5, 0x2b0
224 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
225 s_waitcnt vmcnt(0)
226 v_mov_b32_e32 v6, 0xb0
227 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
228 v_mov_b32_e32 v5, 0x2c0
229 buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen
230 s_waitcnt vmcnt(0)
231 v_mov_b32_e32 v6, 0xc0
232 buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen
233 s_endpgm
diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py
index a7c9cb696..28a6fa232 100644
--- a/tests/semantic/regen_fixtures.py
+++ b/tests/semantic/regen_fixtures.py
@@ -26,6 +26,7 @@ SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_bu
26 "ps_f32_mods", "ps_f64_mods", "ps_sff_imm", "cs_w32_lds_u8_d16", "cs_w32_lane_wrap", "ps_bary", 26 "ps_f32_mods", "ps_f64_mods", "ps_sff_imm", "cs_w32_lds_u8_d16", "cs_w32_lane_wrap", "ps_bary",
27 "cs_oob_select", "cs_oob_tail", "cs_w32_mask_imm", "cs_w64_mask_imm", 27 "cs_oob_select", "cs_oob_tail", "cs_w32_mask_imm", "cs_w64_mask_imm",
28 "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) 28 "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py)
29 "cs_tbuffer_store", # tbuffer_store_format_*, words measured natively on a Radeon 680M
29 # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only 30 # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only
30 "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", 31 "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods",
31 "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260) 32 "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260)
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py
index b288e42f7..3afc81c69 100644
--- a/tests/semantic/spirv_mini_interp.py
+++ b/tests/semantic/spirv_mini_interp.py
@@ -43,13 +43,29 @@ class InvalidModule(AssertionError):
43 43
44 44
45def check_structure(body): 45def check_structure(body):
46 """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, 46 """spirv-val's merge, phi and Function-variable rules (SPIR-V 2.16.1-2): OpSelectionMerge must be the second-to-last instruction of its block,
47 directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or 47 directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or
48 OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an 48 OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an
49 instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every 49 instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every
50 driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function.""" 50 driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function."""
51 follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), 51 follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"),
52 "OpLoopMerge": ("OpBranch", "OpBranchConditional")} 52 "OpLoopMerge": ("OpBranch", "OpBranchConditional")}
53 # OpPhi must come first in its block: only OpLabel or other OpPhi before it (SPIR-V 2.16.2, "OpPhi ... must be
54 # the first instructions of a block"). A phi emitted after an instruction of the merge block is rejected by
55 # spirv-val, and every translator path that merges a guarded load (OpPhi of the loaded and the kept value)
56 # depends on the order.
57 # Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1).
58 prev, blocks = None, 0
59 for _, op, a, line in body:
60 if op == "OpPhi" and prev not in ("OpLabel", "OpPhi"):
61 raise InvalidModule(f"{line!r} follows {prev or 'the start of the function'}, not OpLabel or OpPhi")
62 if op == "OpFunction":
63 blocks = 0
64 elif op == "OpLabel":
65 blocks += 1
66 elif op == "OpVariable" and a[1:2] == ["Function"] and blocks > 1:
67 raise InvalidModule(f"{line!r} is a Function variable outside the function's first block")
68 prev = op
53 for k, (_, op, _, line) in enumerate(body): 69 for k, (_, op, _, line) in enumerate(body):
54 if op in follow: 70 if op in follow:
55 nxt = body[k + 1][1] if k + 1 < len(body) else None 71 nxt = body[k + 1][1] if k + 1 < len(body) else None
@@ -867,18 +883,6 @@ def _invocation(text, inputs, push_constants, memory, step=False):
867 values[res] = fma_f32(x, y, z) 883 values[res] = fma_f32(x, y, z)
868 elif op == "OpFNegate": 884 elif op == "OpFNegate":
869 values[res] = f32(-val(a[1])) 885 values[res] = f32(-val(a[1]))
870 elif op == "OpFDiv":
871 x, y = val(a[1]), val(a[2])
872 if not (isinstance(x, float) and isinstance(y, float)):
873 raise UnsupportedConstruct("OpFDiv on non-float")
874 if y == 0.0:
875 raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)")
876 if math.isinf(x) and math.isinf(y):
877 values[res] = math.nan
878 elif math.isnan(x) or math.isnan(y):
879 values[res] = math.nan
880 else:
881 values[res] = f32(x / y) # x/inf is a signed zero, as in Python
882 elif op == "OpQuantizeToF16": 886 elif op == "OpQuantizeToF16":
883 # Single-instruction f32 -> f16 -> f32 round to nearest, with the 887 # Single-instruction f32 -> f16 -> f32 round to nearest, with the
884 # SPIR-V subnormal rule: a magnitude too small for a normal f16 888 # SPIR-V subnormal rule: a magnitude too small for a normal f16
diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py
index a3adf6544..0331c7b37 100644
--- a/tests/semantic/spirv_wave_interp.py
+++ b/tests/semantic/spirv_wave_interp.py
@@ -160,7 +160,12 @@ class _Module:
160 raise UnsupportedConstruct(f"{op} before the first label") 160 raise UnsupportedConstruct(f"{op} before the first label")
161 if res and a and op != "OpStore": 161 if res and a and op != "OpStore":
162 self.id_type[res] = a[0] 162 self.id_type[res] = a[0]
163 if op == "OpVariable" and a[1:2] == ["Function"] and len(self.blocks) > 1:
164 raise InvalidModule(f"{line!r} is a Function variable outside the function's first block")
163 if op == "OpPhi": 165 if op == "OpPhi":
166 if cur.body:
167 raise InvalidModule(f"{line!r} follows a non-phi instruction of its block (spirv-val: "
168 "OpPhi must come first)")
164 cur.phis.append((res, a)) 169 cur.phis.append((res, a))
165 elif op in ("OpSelectionMerge", "OpLoopMerge"): 170 elif op in ("OpSelectionMerge", "OpLoopMerge"):
166 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) 171 cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None)
diff --git a/tests/semantic/test_alu_add_co_clamp.py b/tests/semantic/test_alu_add_co_clamp.py
new file mode 100644
index 000000000..b39b8b26e
--- /dev/null
+++ b/tests/semantic/test_alu_add_co_clamp.py
@@ -0,0 +1,183 @@
1"""Semantic interpreter tests for VOP3 clamp on RDNA2 carry-out u32 add/sub ops.
2
3Covers all six carry-out forms: v_add_co_u32, v_sub_co_u32, v_subrev_co_u32, v_add_co_ci_u32, v_sub_co_ci_u32,
4and v_subrev_co_ci_u32. With VOP3 `clamp`, RDNA2 hardware (measured natively on gfx1035 and gfx1036, wave32 &
5wave64) saturates D to 0xFFFFFFFF on add carry or 0 on sub borrow while still writing the real carry/borrow bit
6into sdst (0 for inactive EXEC lanes). Without `clamp`, D wraps at 32 bits. No game files.
7"""
8import os
9import random
10import struct
11import sys
12import tempfile
13import unittest
14import warnings
15
16HERE = os.path.dirname(os.path.abspath(__file__))
17ROOT = os.path.dirname(os.path.dirname(HERE))
18TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
19
20sys.dont_write_bytecode = True
21sys.path.insert(0, TOOLS_DIR)
22sys.path.insert(0, HERE)
23
24import rdna2spirv # noqa: E402
25import spirv_mini_interp as si # noqa: E402
26
27M32 = 0xFFFFFFFF
28STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
29
30CO_OPS = ("v_add_co_u32", "v_sub_co_u32", "v_subrev_co_u32")
31CO_CI_OPS = ("v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32")
32EDGE_PAIRS = (
33 (0, 0),
34 (0, 1),
35 (1, 0),
36 (5, 10),
37 (10, 5),
38 (5, 4),
39 (0xFFFFFFFF, 0),
40 (0, 0xFFFFFFFF),
41 (0xFFFFFFFF, 1),
42 (0xFFFFFFFF, 0xFFFFFFFF),
43 (0x80000000, 0x80000000),
44 (0x7FFFFFFF, 0x80000000),
45)
46
47_TMP_DIR = None
48_SRC_PATH = None
49
50
51def setUpModule():
52 global _TMP_DIR, _SRC_PATH
53 _TMP_DIR = tempfile.TemporaryDirectory()
54 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
55 os.mkdir(disasm_dir)
56 _SRC_PATH = os.path.join(disasm_dir, "ps_add_co_clamp.s")
57 with open(os.path.join(_TMP_DIR.name, "ps_add_co_clamp.dxbc"), "wb") as f:
58 f.write(STUB_DXBC)
59
60
61def tearDownModule():
62 global _TMP_DIR
63 if _TMP_DIR is not None:
64 _TMP_DIR.cleanup()
65 _TMP_DIR = None
66
67
68def ref(op: str, x: int, y: int, cin: int, clamp: bool) -> tuple[int, int]:
69 x, y = x & M32, y & M32
70 if op.startswith("v_subrev_co"):
71 x, y = y, x
72 sub = "sub" in op
73 c = (1 if cin else 0) if op.endswith("ci_u32") else 0
74 if sub:
75 full = x - y - c
76 carry = 1 if full < 0 else 0
77 res = 0 if (clamp and carry) else (full & M32)
78 else:
79 full = x + y + c
80 carry = 1 if full > M32 else 0
81 res = M32 if (clamp and carry) else (full & M32)
82 return res, carry
83
84
85def run_case(op: str, x: int, y: int, cin: int, clamp: bool, cd: str = "vcc_lo") -> tuple[int, int]:
86 if _TMP_DIR is None:
87 setUpModule()
88 mod = " clamp" if clamp else ""
89 lines = [
90 f"v_mov_b32 v1, {x:#x}",
91 f"v_mov_b32 v2, {y:#x}",
92 f"s_mov_b32 vcc_lo, {-1 if cin else 0}",
93 ]
94 if op.endswith("ci_u32"):
95 lines.append(f"{op}_e64 v0, {cd}, v1, v2, vcc_lo{mod}")
96 else:
97 lines.append(f"{op} v0, {cd}, v1, v2{mod}")
98 if cd == "null":
99 lines.append("v_mov_b32 v7, 0")
100 else:
101 lines.append(f"v_cndmask_b32_e64 v7, 0, 1, {cd}")
102 lines += [
103 "v_and_b32 v5, 0xffff, v0",
104 "v_lshrrev_b32 v6, 16, v0",
105 "v_or_b32 v5, 0x40000000, v5",
106 "v_or_b32 v6, 0x40000000, v6",
107 "v_or_b32 v7, 0x40000000, v7",
108 ]
109 asm = "; test_add_co_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n"
110 with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f:
111 f.write(asm)
112 with warnings.catch_warnings():
113 warnings.simplefilter("ignore", ResourceWarning)
114 spv = rdna2spirv.translate(_SRC_PATH)
115 lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3]
116 assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000 and cword >> 16 == 0x4000, (hex(lo), hex(hi), hex(cword))
117 return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16), cword & 1
118
119
120class AddCoClampTests(unittest.TestCase):
121 def test_edge_pairs_all_six_ops(self):
122 for op in CO_OPS:
123 for clamp in (False, True):
124 for x, y in EDGE_PAIRS:
125 self.assertEqual(run_case(op, x, y, 0, clamp), ref(op, x, y, 0, clamp),
126 (op, hex(x), hex(y), clamp))
127 for op in CO_CI_OPS:
128 for clamp in (False, True):
129 for cin in (0, 1):
130 for x, y in EDGE_PAIRS:
131 self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp),
132 (op, hex(x), hex(y), cin, clamp))
133
134 def test_null_and_sgpr_carry_dests(self):
135 for op in ("v_add_co_u32", "v_sub_co_u32", "v_add_co_ci_u32", "v_sub_co_ci_u32"):
136 x, y, cin = (0xFFFFFFFF, 1, 1) if "add" in op else (0, 1, 1)
137 want_d, want_c = ref(op, x, y, cin, True)
138 got_d, _ = run_case(op, x, y, cin, True, cd="null")
139 self.assertEqual(got_d, want_d, (op, "null"))
140 self.assertEqual(run_case(op, x, y, cin, True, cd="s12"), (want_d, want_c), (op, "s12"))
141
142 def test_inactive_exec_lane(self):
143 if _TMP_DIR is None:
144 setUpModule()
145 lines = [
146 "v_mov_b32 v0, 0x12345678",
147 "v_mov_b32 v1, 0xffffffff",
148 "v_mov_b32 v2, 0xffffffff",
149 "s_mov_b32 vcc_lo, -1",
150 "s_mov_b32 s10, exec_lo",
151 "s_mov_b32 exec_lo, 0",
152 "v_add_co_u32 v0, vcc_lo, v1, v2 clamp",
153 "s_mov_b32 exec_lo, s10",
154 "v_cndmask_b32_e64 v7, 0, 1, vcc_lo",
155 "v_and_b32 v5, 0xffff, v0",
156 "v_lshrrev_b32 v6, 16, v0",
157 "v_or_b32 v5, 0x40000000, v5",
158 "v_or_b32 v6, 0x40000000, v6",
159 "v_or_b32 v7, 0x40000000, v7",
160 ]
161 asm = "; test_inactive\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n"
162 with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f:
163 f.write(asm)
164 with warnings.catch_warnings():
165 warnings.simplefilter("ignore", ResourceWarning)
166 spv = rdna2spirv.translate(_SRC_PATH)
167 lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3]
168 self.assertEqual((lo & 0xFFFF) | ((hi & 0xFFFF) << 16), 0x12345678)
169 self.assertEqual(cword & 1, 0)
170
171 def test_seeded_random(self):
172 rng = random.Random(20261122)
173 for op in CO_OPS + CO_CI_OPS:
174 for _ in range(12):
175 x, y = rng.randrange(1 << 32), rng.randrange(1 << 32)
176 cin = rng.randrange(2)
177 for clamp in (False, True):
178 self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp),
179 (op, hex(x), hex(y), cin, clamp))
180
181
182if __name__ == "__main__":
183 unittest.main()
diff --git a/tests/semantic/test_alu_cvt_flr_rpi.py b/tests/semantic/test_alu_cvt_flr_rpi.py
index f31e82d99..eb9239af8 100644
--- a/tests/semantic/test_alu_cvt_flr_rpi.py
+++ b/tests/semantic/test_alu_cvt_flr_rpi.py
@@ -1,13 +1,16 @@
1"""Semantic interpreter tests for RDNA2 v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32. 1"""Semantic interpreter tests for RDNA2 v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32.
2 2
3RDNA ISA pseudocode: v_cvt_flr_i32_f32 is f32_to_i32(floor(S0)), v_cvt_rpi_i32_f32 is f32_to_i32(floor(S0 + 0.5)), 3Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64): v_cvt_flr_i32_f32 is sat_i32(floor(S0)), and
4with the + 0.5 rounded in binary32 like any f32 add. f32_to_i32 saturates as v_cvt_i32_f32 does (#300): at or past 4v_cvt_rpi_i32_f32 is sat_i32(floor(S0 + 0.5)) computed **exactly** (without binary32 rounding of S0 + 0.5, so
5+-2^31, and +-inf, it gives INT_MAX / INT_MIN; NaN gives 0. Each case translates a synthetic pixel shader with 50x3EFFFFFF = 0.49999997 gives 0, 0x4B000001 gives 0x00800001, and 0x4B7FFFFF gives 0x00FFFFFF). Values at or past
6tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python 6+-2^31, +-inf, and NaNs all saturate by the sign bit of the operand (+ -> 0x7FFFFFFF, - -> 0x80000000), unlike
7reference. Denormal inputs are left out (the float mode that would flush them is not modelled). The result leaves 7v_cvt_i32_f32 which returns 0 for NaN. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs
8through exp as two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a 8it in tests/semantic/spirv_mini_interp.py and compares the result with an exact plain-Python reference. Denormal
9float round trip could change. 9inputs are left out (the float mode that would flush them is not modelled). The result leaves through exp as two
1016-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could
11change.
10""" 12"""
13from fractions import Fraction
11import math 14import math
12import os 15import os
13import random 16import random
@@ -32,38 +35,34 @@ M32 = 0xFFFFFFFF
32STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) 35STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
33 36
34 37
35def u2f(u: int) -> float:
36 return struct.unpack("<f", struct.pack("<I", u & M32))[0]
37
38
39def f32(x: float) -> float:
40 try:
41 return struct.unpack("<f", struct.pack("<f", x))[0]
42 except OverflowError:
43 return math.copysign(math.inf, x)
44
45
46def f32_to_i32(x: float) -> int:
47 if math.isnan(x):
48 return 0
49 if x >= 2.0 ** 31:
50 return 0x7FFFFFFF
51 if x < -(2.0 ** 31):
52 return 0x80000000
53 return int(x) & M32
54
55
56def ref(op: str, u: int) -> int: 38def ref(op: str, u: int) -> int:
57 x = u2f(u) 39 u &= M32
40 sign = (u >> 31) & 1
41 exp = (u >> 23) & 0xFF
42 mant = u & 0x7FFFFF
43 if exp == 0xFF:
44 return 0x80000000 if sign else 0x7FFFFFFF
45 if exp == 0:
46 x = Fraction(mant, 1 << 149)
47 else:
48 x = Fraction((1 << 23) | mant) * (Fraction(2) ** (exp - 150))
49 if sign:
50 x = -x
58 if op == "v_cvt_rpi_i32_f32": 51 if op == "v_cvt_rpi_i32_f32":
59 x = f32(x + 0.5) # exact in double, then one rounding to binary32 52 x += Fraction(1, 2)
60 return f32_to_i32(math.floor(x) if math.isfinite(x) else x) 53 iv = math.floor(x)
54 if iv >= (1 << 31):
55 return 0x7FFFFFFF
56 if iv < -(1 << 31):
57 return 0x80000000
58 return iv & M32
61 59
62 60
63OPS = ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32") 61OPS = ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32")
64VALUES = [0x00000000, 0x80000000, 0x3F000000, 0xBF000000, 0x3EFFFFFF, 0xBEFFFFFF, 0x3FC00000, 0xBFC00000, 62VALUES = [0x00000000, 0x80000000, 0x3F000000, 0xBF000000, 0x3EFFFFFF, 0xBEFFFFFF, 0xBF000001, 0x3FC00000, 0xBFC00000,
65 0x40200000, 0xC0200000, 0x3F7FFFFF, 0x4B000001, 0xCB000001, 0x4EFFFFFF, 0xCEFFFFFF, 0x4F000000, 63 0x40200000, 0xC0200000, 0x3F7FFFFF, 0x4AFFFFFF, 0x4B000000, 0x4B000001, 0x4B7FFFFF, 0xCB000001, 0x4EFFFFFF,
66 0xCF000000, 0xCF000001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7F800001] 64 0xCEFFFFFF, 0x4F000000, 0xCF000000, 0xCF000001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000,
65 0xFFC00000, 0x7F800001, 0xFF800001]
67 66
68_TMP_DIR = None 67_TMP_DIR = None
69_SRC_PATH = None 68_SRC_PATH = None
@@ -112,9 +111,12 @@ class CvtFlrRpiTests(unittest.TestCase):
112 self.assertEqual(ref("v_cvt_flr_i32_f32", 0xC0200000), (-3) & M32) # floor(-2.5) 111 self.assertEqual(ref("v_cvt_flr_i32_f32", 0xC0200000), (-3) & M32) # floor(-2.5)
113 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0xC0200000), (-2) & M32) # floor(-2.5 + 0.5) 112 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0xC0200000), (-2) & M32) # floor(-2.5 + 0.5)
114 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x40200000), 3) # 2.5 rounds up 113 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x40200000), 3) # 2.5 rounds up
115 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x3EFFFFFF), 1) # 0.49999997 + 0.5 rounds to 1.0 114 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x3EFFFFFF), 0) # 0.49999997 -> exact floor(x+0.5) = 0
115 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B000001), 0x00800001) # 8388609.0 -> exact, not 8388610
116 self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B7FFFFF), 0x00FFFFFF) # 16777215.0 -> exact, not 16777216
116 self.assertEqual(ref("v_cvt_flr_i32_f32", 0xCF000001), 0x80000000) # below -2^31: saturated 117 self.assertEqual(ref("v_cvt_flr_i32_f32", 0xCF000001), 0x80000000) # below -2^31: saturated
117 self.assertEqual(ref("v_cvt_flr_i32_f32", 0x7FC00000), 0) # NaN 118 self.assertEqual(ref("v_cvt_flr_i32_f32", 0x7FC00000), 0x7FFFFFFF) # +NaN saturates to INT_MAX
119 self.assertEqual(ref("v_cvt_flr_i32_f32", 0xFFC00000), 0x80000000) # -NaN saturates to INT_MIN
118 120
119 def test_edge_values(self): 121 def test_edge_values(self):
120 for op in OPS: 122 for op in OPS:
diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py
new file mode 100644
index 000000000..ff60a8508
--- /dev/null
+++ b/tests/semantic/test_alu_dot4_i8.py
@@ -0,0 +1,138 @@
1"""v_dot4_i32_i8 and v_dot4c_i32_i8: the dot product of the signed bytes of two dwords, plus an addend.
2
3ISA rule (RDNA2): D = S0.b0*S1.b0 + S0.b1*S1.b1 + S0.b2*S1.b2 + S0.b3*S1.b3 + addend, every byte sign-extended, the
4sum kept modulo 2^32. The addend is the third source for v_dot4_i32_i8 (VOP3P) and the old value of the destination
5for v_dot4c_i32_i8 (VOP2). The 29 FSPX programs of the package's upscaler DLL (docs/fspx.md) use the pair 27,271
6times.
7
8The expected words below were measured on RDNA2 hardware (gfx1036, the integrated GPU of a Ryzen 9 7950X3D, through
9tools/hw_oracle): each case ran `v_dot4_i32_i8 v8, v1, v2, v3`, `v_dot4c_i32_i8 v10, v1, v2` with v10 holding the
10addend, and the same with the two sources swapped. All three gave the word in the table, which the plain-Python
11reference `ref` reproduces. With `clamp` the hardware saturates v_dot4_i32_i8 to a signed 32-bit value
12(0x7fffffff and 0x80000000 in the two overflowing cases); the translator refuses that form.
13
14op_sel. The plain instruction has op_sel 0 and op_sel_hi 7. 89 words in 8 of those programs are v_dot4_i32_i8 with
15op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words
16(0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot
17product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit
18ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can
19carry it.
20
21 python -m unittest discover -s tests/semantic -p test_alu_dot4_i8.py
22"""
23import os
24import sys
25import unittest
26
27HERE = os.path.dirname(os.path.abspath(__file__))
28if HERE not in sys.path:
29 sys.path.insert(0, HERE)
30
31import support # noqa: E402
32
33rdna2spirv = support.rdna2spirv
34
35# (S0, S1, addend, result measured on gfx1036)
36MEASURED = [
37 (0x01020304, 0x05060708, 0x00000000, 0x00000046), # 4*8 + 3*7 + 2*6 + 1*5 = 70
38 (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # 70 + 1000
39 (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # 127*-1 + 1*-128 + -128*127 + -1*127 = -16638
40 (0xFF80017F, 0x7F7F80FF, 0x00010000, 0x0000BF02),
41 (0x80808080, 0x80808080, 0x00000000, 0x00010000), # 4 * (-128 * -128)
42 (0x80808080, 0x7F7F7F7F, 0x00000005, 0xFFFF0205), # 4 * (-128 * 127) + 5
43 (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x8000FC03), # wraps upward: no saturation without clamp
44 (0x80808080, 0x7F7F7F7F, 0x80000000, 0x7FFF0200), # wraps downward
45 (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003), # 4 * (-1 * -1) - 1
46 (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF),
47]
48
49
50# (S0, S1, addend, result measured on gfx1036 with op_sel 2 and op_sel_hi 5)
51MEASURED_OP_SEL = [
52 (0x04030201, 0x08070605, 0x00000000, 62), # the plain form gives 70
53 (0x04030201, 0x08070605, 0x000003E8, 1062),
54 (0x7F01FE80, 0x02FD7F81, 0x00000000, 16382), # the plain form gives 16253
55 (0x11223344, 0x55667788, 0x00010000, 74750), # the plain form gives 68358
56 (0xFFFFFFFF, 0x01020304, 0x00000007, 0xFFFFFFFD), # every byte of S0 the same: the order cannot show
57]
58
59
60def ref(a, b, addend):
61 def s8(x):
62 return x - 256 if x & 0x80 else x
63 total = sum(s8((a >> (8 * i)) & 0xFF) * s8((b >> (8 * i)) & 0xFF) for i in range(4))
64 return (total + addend) & 0xFFFFFFFF
65
66
67def ref_op_sel(a, b, addend):
68 """op_sel 2, op_sel_hi 5: the low half of the product reads the high half of S1 and the high half its low half."""
69 return ref(a, (b & 0xFFFF) << 16 | b >> 16, addend)
70
71
72def program(a, b, addend):
73 """mrt0 = (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4c_i32_i8 with the sources swapped, v_dot4_i32_i8 with the
74 sources and the addend taken from SGPRs and a literal, as the shaders do)."""
75 return [
76 f"v_mov_b32_e32 v1, 0x{a:08x}",
77 f"v_mov_b32_e32 v2, 0x{b:08x}",
78 f"v_mov_b32_e32 v3, 0x{addend:08x}",
79 f"s_mov_b32 s4, 0x{addend:08x}",
80 "v_dot4_i32_i8 v8, v1, v2, v3",
81 f"v_mov_b32_e32 v9, 0x{addend:08x}",
82 "v_dot4c_i32_i8 v9, v1, v2",
83 f"v_mov_b32_e32 v10, 0x{addend:08x}",
84 "v_dot4c_i32_i8 v10, v2, v1",
85 f"v_dot4_i32_i8 v11, v1, 0x{b:08x}, s4",
86 "exp mrt0 v8, v9, v10, v11 done vm",
87 "s_endpgm",
88 ]
89
90
91class Dot4I8(unittest.TestCase):
92 def test_the_reference_reproduces_the_hardware_words(self):
93 for a, b, addend, measured in MEASURED:
94 self.assertEqual(ref(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}")
95
96 def test_both_forms_give_the_hardware_words(self):
97 for a, b, addend, measured in MEASURED:
98 with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"):
99 spv = support.translate_lines("ps_dot4_i8", program(a, b, addend))
100 self.assertEqual(support.mrt0_words(spv), [measured] * 4)
101
102 def test_the_accumulating_form_reads_its_destination(self):
103 # v9 is never written before v_dot4c reads it: the old value is then the register's initial 0, not garbage
104 # from an expression that dropped the addend. 70 is the dot product alone.
105 lines = ["v_mov_b32_e32 v1, 0x01020304", "v_mov_b32_e32 v2, 0x05060708", "v_dot4c_i32_i8 v9, v1, v2",
106 "v_dot4c_i32_i8 v9, v1, v2", "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"]
107 self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4c_twice", lines)), [140] * 4)
108
109 def test_the_bytes_are_signed(self):
110 # 0xff * 0x01: -1 as a signed byte, 255 as an unsigned one.
111 lines = ["v_mov_b32_e32 v1, 0x000000ff", "v_mov_b32_e32 v2, 0x00000001", "v_mov_b32_e32 v3, 0",
112 "v_dot4_i32_i8 v8, v1, v2, v3", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
113 self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_signed", lines)), [0xFFFFFFFF] * 4)
114
115 def test_the_op_sel_reference_reproduces_the_hardware_words(self):
116 for a, b, addend, measured in MEASURED_OP_SEL:
117 self.assertEqual(ref_op_sel(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}")
118 # The table can tell the two readings apart: the plain rule gives another word in four of the five cases.
119 self.assertEqual(sum(ref(a, b, c) != m for a, b, c, m in MEASURED_OP_SEL), 4)
120
121 def test_op_sel_is_refused(self):
122 lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0",
123 "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]",
124 "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
125 with self.assertRaises(rdna2spirv.Unsupported) as refused:
126 support.translate_lines("ps_dot4_op_sel", lines)
127 self.assertEqual(str(refused.exception), "v_dot4_i32_i8 op_sel")
128
129 def test_clamp_is_refused(self):
130 lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0",
131 "v_dot4_i32_i8 v8, v1, v2, v3 clamp", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"]
132 with self.assertRaises(rdna2spirv.Unsupported) as refused:
133 support.translate_lines("ps_dot4_clamp", lines)
134 self.assertEqual(str(refused.exception), "v_dot4_i32_i8 clamp")
135
136
137if __name__ == "__main__":
138 unittest.main()
diff --git a/tests/semantic/test_buffer_format_narrow_int.py b/tests/semantic/test_buffer_format_narrow_int.py
new file mode 100644
index 000000000..0b1fbd15b
--- /dev/null
+++ b/tests/semantic/test_buffer_format_narrow_int.py
@@ -0,0 +1,257 @@
1"""Narrow integer typed-buffer formats (8/16-bit UINT and SINT) in tools/rdna2spirv.py, against words measured natively.
2
3Every expected word below was read back from an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD
4driver, through tools/hw_oracle with AMD clang 23 from rocm-sdk-core 10.0.0), in wave32 and wave64 alike, with the
5same V# and instruction the translated shader gets here:
6
7- loads: `buffer_load_format_xyzw` and `_d16_xyzw` from four source dwords (SOURCE) with DST_SEL XYZW and X011. UINT
8 zero-extends and SINT sign-extends each channel; missing channels repeat the format's own (c mod n); DST_SEL 1 is
9 integer 1; d16 packs each result as a 16-bit integer.
10- stores: `buffer_store_format_x/xy/xyzw` of four value sets into a buffer filled with 0xDEAD0000, with the V#
11 selectors the runtime gives each format (gfx10_descriptors.h: X001, XY01, XYZW). UINT saturates to the channel
12 (unsigned), SINT clamps the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1]; a 1-2 byte element keeps the rest
13 of its dword.
14
15Formats 27, 60 and 69 (16_16_UINT, 8_8_8_8_UINT, 16_16_16_16_UINT) were decoded before; they are the control.
16"""
17from __future__ import annotations
18
19import os
20import struct
21import sys
22import tempfile
23import unittest
24import warnings
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27ROOT = os.path.dirname(os.path.dirname(HERE))
28sys.dont_write_bytecode = True
29sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
30sys.path.insert(0, HERE)
31
32import rdna2spirv # noqa: E402
33import spirv_mini_interp as si # noqa: E402
34
35STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
36BASE = 0x1000
37SOURCE = (0x7F01FF80, 0x8000FFFF, 0x12345678, 0x9ABCDEF0)
38SEL_XYZW, SEL_X011 = 4 | 5 << 3 | 6 << 6 | 7 << 9, 4 | 0 << 3 | 1 << 6 | 1 << 9
39RUNTIME_SEL = {1: 4 | 0 << 3 | 0 << 6 | 1 << 9, 2: 4 | 5 << 3 | 0 << 6 | 1 << 9, 4: SEL_XYZW}
40CHANNELS = {5: 1, 6: 1, 11: 1, 12: 1, 18: 2, 19: 2, 27: 2, 28: 2, 60: 4, 61: 4, 69: 4, 70: 4}
41VALUES = {"big": (300, 0xFFFFFF38, 0x7FFFFFFF, 0x80000000), "edge": (0x7F, 0x80, 0xFFFFFF80, 0xFFFFFF7F),
42 "edge16": (0x7FFF, 0x8000, 0xFFFF8000, 0xFFFF7FFF), "small": (5, 0xFFFFFFFF, 0, 0x101)}
43
44LOADS = { # format: (xyzw with DST_SEL XYZW, xyzw with DST_SEL X011, d16_xyzw's two registers)
45 5: ((0x00000080, 0x00000080, 0x00000080, 0x00000080), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00800080, 0x00800080)), # 8_UINT
46 6: ((0xffffff80, 0xffffff80, 0xffffff80, 0xffffff80), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 8_SINT
47 11: ((0x0000ff80, 0x0000ff80, 0x0000ff80, 0x0000ff80), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 16_UINT
48 12: ((0xffffff80, 0xffffff80, 0xffffff80, 0xffffff80), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xff80ff80, 0xff80ff80)), # 16_SINT
49 18: ((0x00000080, 0x000000ff, 0x00000080, 0x000000ff), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00ff0080, 0x00ff0080)), # 8_8_UINT
50 19: ((0xffffff80, 0xffffffff, 0xffffff80, 0xffffffff), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xffffff80, 0xffffff80)), # 8_8_SINT
51 27: ((0x0000ff80, 0x00007f01, 0x0000ff80, 0x00007f01), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x7f01ff80)), # 16_16_UINT
52 28: ((0xffffff80, 0x00007f01, 0xffffff80, 0x00007f01), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x7f01ff80)), # 16_16_SINT
53 60: ((0x00000080, 0x000000ff, 0x00000001, 0x0000007f), (0x00000080, 0x00000000, 0x00000001, 0x00000001), (0x00ff0080, 0x007f0001)), # 8_8_8_8_UINT
54 61: ((0xffffff80, 0xffffffff, 0x00000001, 0x0000007f), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0xffffff80, 0x007f0001)), # 8_8_8_8_SINT
55 69: ((0x0000ff80, 0x00007f01, 0x0000ffff, 0x00008000), (0x0000ff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x8000ffff)), # 16_16_16_16_UINT
56 70: ((0xffffff80, 0x00007f01, 0xffffffff, 0xffff8000), (0xffffff80, 0x00000000, 0x00000001, 0x00000001), (0x7f01ff80, 0x8000ffff)), # 16_16_16_16_SINT
57}
58STORES = { # (format, value set, components): the two dwords at the element, 0xDEAD0000 before the store
59 (5, 'big', 1): (0xdead00ff, 0xdead0000), # 8_UINT
60 (5, 'big', 2): (0xdead00ff, 0xdead0000), # 8_UINT
61 (5, 'big', 4): (0xdead00ff, 0xdead0000), # 8_UINT
62 (5, 'edge', 1): (0xdead007f, 0xdead0000), # 8_UINT
63 (5, 'edge', 2): (0xdead007f, 0xdead0000), # 8_UINT
64 (5, 'edge', 4): (0xdead007f, 0xdead0000), # 8_UINT
65 (5, 'edge16', 1): (0xdead00ff, 0xdead0000), # 8_UINT
66 (5, 'edge16', 2): (0xdead00ff, 0xdead0000), # 8_UINT
67 (5, 'edge16', 4): (0xdead00ff, 0xdead0000), # 8_UINT
68 (5, 'small', 1): (0xdead0005, 0xdead0000), # 8_UINT
69 (5, 'small', 2): (0xdead0005, 0xdead0000), # 8_UINT
70 (5, 'small', 4): (0xdead0005, 0xdead0000), # 8_UINT
71 (6, 'big', 1): (0xdead007f, 0xdead0000), # 8_SINT
72 (6, 'big', 2): (0xdead007f, 0xdead0000), # 8_SINT
73 (6, 'big', 4): (0xdead007f, 0xdead0000), # 8_SINT
74 (6, 'edge', 1): (0xdead007f, 0xdead0000), # 8_SINT
75 (6, 'edge', 2): (0xdead007f, 0xdead0000), # 8_SINT
76 (6, 'edge', 4): (0xdead007f, 0xdead0000), # 8_SINT
77 (6, 'edge16', 1): (0xdead007f, 0xdead0000), # 8_SINT
78 (6, 'edge16', 2): (0xdead007f, 0xdead0000), # 8_SINT
79 (6, 'edge16', 4): (0xdead007f, 0xdead0000), # 8_SINT
80 (6, 'small', 1): (0xdead0005, 0xdead0000), # 8_SINT
81 (6, 'small', 2): (0xdead0005, 0xdead0000), # 8_SINT
82 (6, 'small', 4): (0xdead0005, 0xdead0000), # 8_SINT
83 (11, 'big', 1): (0xdead012c, 0xdead0000), # 16_UINT
84 (11, 'big', 2): (0xdead012c, 0xdead0000), # 16_UINT
85 (11, 'big', 4): (0xdead012c, 0xdead0000), # 16_UINT
86 (11, 'edge', 1): (0xdead007f, 0xdead0000), # 16_UINT
87 (11, 'edge', 2): (0xdead007f, 0xdead0000), # 16_UINT
88 (11, 'edge', 4): (0xdead007f, 0xdead0000), # 16_UINT
89 (11, 'edge16', 1): (0xdead7fff, 0xdead0000), # 16_UINT
90 (11, 'edge16', 2): (0xdead7fff, 0xdead0000), # 16_UINT
91 (11, 'edge16', 4): (0xdead7fff, 0xdead0000), # 16_UINT
92 (11, 'small', 1): (0xdead0005, 0xdead0000), # 16_UINT
93 (11, 'small', 2): (0xdead0005, 0xdead0000), # 16_UINT
94 (11, 'small', 4): (0xdead0005, 0xdead0000), # 16_UINT
95 (12, 'big', 1): (0xdead012c, 0xdead0000), # 16_SINT
96 (12, 'big', 2): (0xdead012c, 0xdead0000), # 16_SINT
97 (12, 'big', 4): (0xdead012c, 0xdead0000), # 16_SINT
98 (12, 'edge', 1): (0xdead007f, 0xdead0000), # 16_SINT
99 (12, 'edge', 2): (0xdead007f, 0xdead0000), # 16_SINT
100 (12, 'edge', 4): (0xdead007f, 0xdead0000), # 16_SINT
101 (12, 'edge16', 1): (0xdead7fff, 0xdead0000), # 16_SINT
102 (12, 'edge16', 2): (0xdead7fff, 0xdead0000), # 16_SINT
103 (12, 'edge16', 4): (0xdead7fff, 0xdead0000), # 16_SINT
104 (12, 'small', 1): (0xdead0005, 0xdead0000), # 16_SINT
105 (12, 'small', 2): (0xdead0005, 0xdead0000), # 16_SINT
106 (12, 'small', 4): (0xdead0005, 0xdead0000), # 16_SINT
107 (18, 'big', 1): (0xdead00ff, 0xdead0000), # 8_8_UINT
108 (18, 'big', 2): (0xdeadffff, 0xdead0000), # 8_8_UINT
109 (18, 'big', 4): (0xdeadffff, 0xdead0000), # 8_8_UINT
110 (18, 'edge', 1): (0xdead007f, 0xdead0000), # 8_8_UINT
111 (18, 'edge', 2): (0xdead807f, 0xdead0000), # 8_8_UINT
112 (18, 'edge', 4): (0xdead807f, 0xdead0000), # 8_8_UINT
113 (18, 'edge16', 1): (0xdead00ff, 0xdead0000), # 8_8_UINT
114 (18, 'edge16', 2): (0xdeadffff, 0xdead0000), # 8_8_UINT
115 (18, 'edge16', 4): (0xdeadffff, 0xdead0000), # 8_8_UINT
116 (18, 'small', 1): (0xdead0005, 0xdead0000), # 8_8_UINT
117 (18, 'small', 2): (0xdeadff05, 0xdead0000), # 8_8_UINT
118 (18, 'small', 4): (0xdeadff05, 0xdead0000), # 8_8_UINT
119 (19, 'big', 1): (0xdead007f, 0xdead0000), # 8_8_SINT
120 (19, 'big', 2): (0xdead807f, 0xdead0000), # 8_8_SINT
121 (19, 'big', 4): (0xdead807f, 0xdead0000), # 8_8_SINT
122 (19, 'edge', 1): (0xdead007f, 0xdead0000), # 8_8_SINT
123 (19, 'edge', 2): (0xdead7f7f, 0xdead0000), # 8_8_SINT
124 (19, 'edge', 4): (0xdead7f7f, 0xdead0000), # 8_8_SINT
125 (19, 'edge16', 1): (0xdead007f, 0xdead0000), # 8_8_SINT
126 (19, 'edge16', 2): (0xdead7f7f, 0xdead0000), # 8_8_SINT
127 (19, 'edge16', 4): (0xdead7f7f, 0xdead0000), # 8_8_SINT
128 (19, 'small', 1): (0xdead0005, 0xdead0000), # 8_8_SINT
129 (19, 'small', 2): (0xdeadff05, 0xdead0000), # 8_8_SINT
130 (19, 'small', 4): (0xdeadff05, 0xdead0000), # 8_8_SINT
131 (27, 'big', 1): (0x0000012c, 0xdead0000), # 16_16_UINT
132 (27, 'big', 2): (0xffff012c, 0xdead0000), # 16_16_UINT
133 (27, 'big', 4): (0xffff012c, 0xdead0000), # 16_16_UINT
134 (27, 'edge', 1): (0x0000007f, 0xdead0000), # 16_16_UINT
135 (27, 'edge', 2): (0x0080007f, 0xdead0000), # 16_16_UINT
136 (27, 'edge', 4): (0x0080007f, 0xdead0000), # 16_16_UINT
137 (27, 'edge16', 1): (0x00007fff, 0xdead0000), # 16_16_UINT
138 (27, 'edge16', 2): (0x80007fff, 0xdead0000), # 16_16_UINT
139 (27, 'edge16', 4): (0x80007fff, 0xdead0000), # 16_16_UINT
140 (27, 'small', 1): (0x00000005, 0xdead0000), # 16_16_UINT
141 (27, 'small', 2): (0xffff0005, 0xdead0000), # 16_16_UINT
142 (27, 'small', 4): (0xffff0005, 0xdead0000), # 16_16_UINT
143 (28, 'big', 1): (0x0000012c, 0xdead0000), # 16_16_SINT
144 (28, 'big', 2): (0xff38012c, 0xdead0000), # 16_16_SINT
145 (28, 'big', 4): (0xff38012c, 0xdead0000), # 16_16_SINT
146 (28, 'edge', 1): (0x0000007f, 0xdead0000), # 16_16_SINT
147 (28, 'edge', 2): (0x0080007f, 0xdead0000), # 16_16_SINT
148 (28, 'edge', 4): (0x0080007f, 0xdead0000), # 16_16_SINT
149 (28, 'edge16', 1): (0x00007fff, 0xdead0000), # 16_16_SINT
150 (28, 'edge16', 2): (0x7fff7fff, 0xdead0000), # 16_16_SINT
151 (28, 'edge16', 4): (0x7fff7fff, 0xdead0000), # 16_16_SINT
152 (28, 'small', 1): (0x00000005, 0xdead0000), # 16_16_SINT
153 (28, 'small', 2): (0xffff0005, 0xdead0000), # 16_16_SINT
154 (28, 'small', 4): (0xffff0005, 0xdead0000), # 16_16_SINT
155 (60, 'big', 1): (0x000000ff, 0xdead0000), # 8_8_8_8_UINT
156 (60, 'big', 2): (0x0000ffff, 0xdead0000), # 8_8_8_8_UINT
157 (60, 'big', 4): (0xffffffff, 0xdead0000), # 8_8_8_8_UINT
158 (60, 'edge', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_UINT
159 (60, 'edge', 2): (0x0000807f, 0xdead0000), # 8_8_8_8_UINT
160 (60, 'edge', 4): (0xffff807f, 0xdead0000), # 8_8_8_8_UINT
161 (60, 'edge16', 1): (0x000000ff, 0xdead0000), # 8_8_8_8_UINT
162 (60, 'edge16', 2): (0x0000ffff, 0xdead0000), # 8_8_8_8_UINT
163 (60, 'edge16', 4): (0xffffffff, 0xdead0000), # 8_8_8_8_UINT
164 (60, 'small', 1): (0x00000005, 0xdead0000), # 8_8_8_8_UINT
165 (60, 'small', 2): (0x0000ff05, 0xdead0000), # 8_8_8_8_UINT
166 (60, 'small', 4): (0xff00ff05, 0xdead0000), # 8_8_8_8_UINT
167 (61, 'big', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT
168 (61, 'big', 2): (0x0000807f, 0xdead0000), # 8_8_8_8_SINT
169 (61, 'big', 4): (0x807f807f, 0xdead0000), # 8_8_8_8_SINT
170 (61, 'edge', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT
171 (61, 'edge', 2): (0x00007f7f, 0xdead0000), # 8_8_8_8_SINT
172 (61, 'edge', 4): (0x80807f7f, 0xdead0000), # 8_8_8_8_SINT
173 (61, 'edge16', 1): (0x0000007f, 0xdead0000), # 8_8_8_8_SINT
174 (61, 'edge16', 2): (0x00007f7f, 0xdead0000), # 8_8_8_8_SINT
175 (61, 'edge16', 4): (0x80807f7f, 0xdead0000), # 8_8_8_8_SINT
176 (61, 'small', 1): (0x00000005, 0xdead0000), # 8_8_8_8_SINT
177 (61, 'small', 2): (0x0000ff05, 0xdead0000), # 8_8_8_8_SINT
178 (61, 'small', 4): (0x7f00ff05, 0xdead0000), # 8_8_8_8_SINT
179 (69, 'big', 1): (0x0000012c, 0x00000000), # 16_16_16_16_UINT
180 (69, 'big', 2): (0xffff012c, 0x00000000), # 16_16_16_16_UINT
181 (69, 'big', 4): (0xffff012c, 0xffffffff), # 16_16_16_16_UINT
182 (69, 'edge', 1): (0x0000007f, 0x00000000), # 16_16_16_16_UINT
183 (69, 'edge', 2): (0x0080007f, 0x00000000), # 16_16_16_16_UINT
184 (69, 'edge', 4): (0x0080007f, 0xffffffff), # 16_16_16_16_UINT
185 (69, 'edge16', 1): (0x00007fff, 0x00000000), # 16_16_16_16_UINT
186 (69, 'edge16', 2): (0x80007fff, 0x00000000), # 16_16_16_16_UINT
187 (69, 'edge16', 4): (0x80007fff, 0xffffffff), # 16_16_16_16_UINT
188 (69, 'small', 1): (0x00000005, 0x00000000), # 16_16_16_16_UINT
189 (69, 'small', 2): (0xffff0005, 0x00000000), # 16_16_16_16_UINT
190 (69, 'small', 4): (0xffff0005, 0x01010000), # 16_16_16_16_UINT
191 (70, 'big', 1): (0x0000012c, 0x00000000), # 16_16_16_16_SINT
192 (70, 'big', 2): (0xff38012c, 0x00000000), # 16_16_16_16_SINT
193 (70, 'big', 4): (0xff38012c, 0x80007fff), # 16_16_16_16_SINT
194 (70, 'edge', 1): (0x0000007f, 0x00000000), # 16_16_16_16_SINT
195 (70, 'edge', 2): (0x0080007f, 0x00000000), # 16_16_16_16_SINT
196 (70, 'edge', 4): (0x0080007f, 0xff7fff80), # 16_16_16_16_SINT
197 (70, 'edge16', 1): (0x00007fff, 0x00000000), # 16_16_16_16_SINT
198 (70, 'edge16', 2): (0x7fff7fff, 0x00000000), # 16_16_16_16_SINT
199 (70, 'edge16', 4): (0x7fff7fff, 0x80008000), # 16_16_16_16_SINT
200 (70, 'small', 1): (0x00000005, 0x00000000), # 16_16_16_16_SINT
201 (70, 'small', 2): (0xffff0005, 0x00000000), # 16_16_16_16_SINT
202 (70, 'small', 4): (0xffff0005, 0x01010000), # 16_16_16_16_SINT
203}
204
205
206def run(fmt: int, body: str, dst_sel: int, memory: dict) -> tuple:
207 """Translate a pixel shader whose V# (s[0:3], raw, 256 bytes) points at BASE with this format and selectors."""
208 with tempfile.TemporaryDirectory() as tmp:
209 os.mkdir(os.path.join(tmp, "disasm"))
210 src = os.path.join(tmp, "disasm", "ps_narrow_int.s")
211 with open(os.path.join(tmp, "ps_narrow_int.dxbc"), "wb") as f:
212 f.write(STUB_DXBC)
213 with open(src, "w", encoding="utf-8") as f:
214 f.write("; test_buffer_format_narrow_int\n"
215 f"\ts_mov_b32 s0, {BASE:#x}\n\ts_mov_b32 s1, 0\n\ts_mov_b32 s2, 0x100\n"
216 f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 1 << 24 | 3 << 28:#x}\n\tv_mov_b32 v1, 0\n" + body)
217 with warnings.catch_warnings():
218 warnings.simplefilter("ignore", ResourceWarning)
219 spv = rdna2spirv.translate(src)
220 return si.run_fragment(spv, memory=memory)["%out_mrt0"]
221
222
223def load(fmt: int, dst_sel: int, d16: bool = False) -> tuple:
224 regs, dst = ("v[2:3]", "v2, v3, v2, v3") if d16 else ("v[2:5]", "v2, v3, v4, v5")
225 body = (f"\tbuffer_load_format_{'d16_' if d16 else ''}xyzw {regs}, v1, s[0:3], 0 offen\n"
226 f"\ts_waitcnt vmcnt(0)\n\texp mrt0 {dst} done vm\n\ts_endpgm\n")
227 return run(fmt, body, dst_sel, {BASE + 4 * i: w for i, w in enumerate(SOURCE)})
228
229
230def store(fmt: int, values: tuple, n: int, channels: int) -> tuple:
231 memory = {BASE: 0xDEAD0000, BASE + 4: 0xDEAD0000}
232 movs = "".join(f"\tv_mov_b32 v{2 + i}, {v:#x}\n" for i, v in enumerate(values[:n]))
233 regs = "v2" if n == 1 else f"v[2:{1 + n}]"
234 body = (movs + f"\tbuffer_store_format_{'xyzw'[:n]} {regs}, v1, s[0:3], 0 offen\n"
235 "\texp mrt0 v2, v2, v2, v2 done vm\n\ts_endpgm\n")
236 run(fmt, body, RUNTIME_SEL[channels], memory)
237 return memory[BASE], memory[BASE + 4]
238
239
240class NarrowIntegerLoads(unittest.TestCase):
241 def test_measured_words(self):
242 for fmt, (xyzw, x011, d16) in LOADS.items():
243 with self.subTest(fmt=fmt):
244 self.assertEqual(load(fmt, SEL_XYZW), xyzw, "DST_SEL XYZW")
245 self.assertEqual(load(fmt, SEL_X011), x011, "DST_SEL X011: 0 and integer 1")
246 self.assertEqual(load(fmt, SEL_XYZW, d16=True)[:2], d16, "d16")
247
248
249class NarrowIntegerStores(unittest.TestCase):
250 def test_measured_words(self):
251 for (fmt, values, n), want in STORES.items():
252 with self.subTest(fmt=fmt, values=values, n=n):
253 self.assertEqual(store(fmt, VALUES[values], n, CHANNELS[fmt]), want)
254
255
256if __name__ == "__main__":
257 unittest.main()
diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py
index c5cf73a70..30f32bb31 100644
--- a/tests/semantic/test_buffer_load_format.py
+++ b/tests/semantic/test_buffer_load_format.py
@@ -33,6 +33,7 @@ MEMORY = {BASE: 0x11223344, BASE + 4: 0xDEADBEEF, BASE + 8: 0xCAFEF00D, BASE + 1
33# V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS 33# V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS
34FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13 34FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13
35FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56 35FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56
36FMT_UNORM16, FMT_SNORM16, FMT_UNORM16X2 = 7, 8, 23
36DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 37DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9
37# DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1 38# DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1
38DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9 39DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9
@@ -150,9 +151,9 @@ class D16DestinationHalves(unittest.TestCase):
150 151
151 152
152class D16NormalizedRounding(unittest.TestCase): 153class D16NormalizedRounding(unittest.TestCase):
153 """d16 narrows a normalized value to f16 with round to nearest even, like the d16 image results (#489; inferred 154 """d16 narrows a normalized value to f16 with round to nearest even (#489; measured for typed buffer loads on an
154 for the hardware, not measured). These bytes are among the about half of unorm8 values where round toward zero, 155 RX 6700, BUILD-161). These bytes are among the about half of unorm8 values where round toward zero, which
155 which PackHalf2x16 becomes on AMD drivers, gives 1 ulp less.""" 156 PackHalf2x16 becomes on AMD drivers, gives 1 ulp less."""
156 157
157 def test_unorm8_x(self): 158 def test_unorm8_x(self):
158 # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero 159 # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero
@@ -163,6 +164,40 @@ class D16NormalizedRounding(unittest.TestCase):
163 self.assertEqual(load_format(FMT_UNORM8X4, 4, 4, d16=True)[:2], (0x39F63B7F, 0x3AF7396D)) 164 self.assertEqual(load_format(FMT_UNORM8X4, 4, 4, d16=True)[:2], (0x39F63B7F, 0x3AF7396D))
164 165
165 166
167class D16NormalizedRoundsOnce(unittest.TestCase):
168 """BUILD-161, measured on an RX 6700 (gfx1031) with tools/d16_format_probe.py: d16 rounds the exact UNORM/SNORM
169 quotient once, straight to f16. The f32 decode followed by f16_bits rounds twice, which is 1 ulp high where the
170 f32 lands exactly on an f16 halfway point: UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009."""
171
172 def d16_x(self, fmt, half, op="buffer_load_format", mods=""):
173 return load_format(fmt, 0, 1, memory={BASE: half}, d16=True, op=op, mods=mods)[0]
174
175 def test_unorm16_and_snorm16_halfway_values(self):
176 for fmt, half, want in ((FMT_UNORM16, 0xFFEF, 0x3BFF), (FMT_UNORM16, 0xFFAF, 0x3BFD),
177 (FMT_SNORM16, 0x7FF7, 0x3BFF), (FMT_SNORM16, 0x8009, 0xBBFF)):
178 with self.subTest(fmt=fmt, half=hex(half)):
179 self.assertEqual(self.d16_x(fmt, half), 0x12340000 | want)
180
181 def test_mtbuf_takes_the_same_rule(self):
182 self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEF, "tbuffer_load_format", " format:[BUF_FMT_16_UNORM]"),
183 0x12343BFF)
184 self.assertEqual(self.d16_x(FMT_SNORM16, 0x8009, "tbuffer_load_format", " format:[BUF_FMT_16_SNORM]"),
185 0x1234BBFF)
186
187 def test_neighbours_and_the_f32_result_are_unchanged(self):
188 self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEE), 0x12343BFF) # 65518/65535: not a halfway f32
189 self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFFF), 0x12343C00)
190 self.assertEqual(load_format(FMT_UNORM16, 0, 1, memory={BASE: 0xFFEF})[0], 0x3F7FF000)
191
192 def test_a_float_format_on_the_halfway_value_still_ties_to_even(self):
193 self.assertEqual(self.d16_x(FMT_F32, 0x3F7FF000), 0x12343C00)
194 self.assertEqual(self.d16_x(FMT_F32, 0xBF7FB000), 0x1234BBFE)
195
196 def test_both_halves_of_a_pair(self):
197 got = load_format(FMT_UNORM16X2, 0, 2, memory={BASE: 0xFFAF << 16 | 0xFFEF}, d16=True)[0]
198 self.assertEqual(got, 0x3BFD3BFF)
199
200
166class CrossingDwordBoundary(unittest.TestCase): 201class CrossingDwordBoundary(unittest.TestCase):
167 """An element that starts mid-dword must read the following dwords, not re-read dword 0. 202 """An element that starts mid-dword must read the following dwords, not re-read dword 0.
168 203
diff --git a/tests/semantic/test_f16_interp_fallback.py b/tests/semantic/test_f16_interp_fallback.py
index 5565252ea..3eb9c8b5d 100644
--- a/tests/semantic/test_f16_interp_fallback.py
+++ b/tests/semantic/test_f16_interp_fallback.py
@@ -3,8 +3,9 @@
3By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and 3By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and
4weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration 4weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration
5is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two 5is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two
6f16 halves decoded to f32, low halves at location 29 - 2N and high halves at 30 - 2N, and the PS reads them as ordinary 6f16 halves decoded to f32, low halves at location 28 - 2N and high halves at 29 - 2N, and the PS reads them as ordinary
7smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: 7smooth inputs (the top is 29: MoltenVK's maxVertexOutputComponents, 124, counts gl_Position; SHADER-291).
8Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here:
8* the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the 9* the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the
9 per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read 10 per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read
10 unchanged; 11 unchanged;
@@ -15,6 +16,7 @@ smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(
15The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates 16The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates
16with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). 17with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK).
17""" 18"""
19import re
18import struct 20import struct
19import unittest 21import unittest
20 22
@@ -82,11 +84,11 @@ class FallbackPixelShader(unittest.TestCase):
82 self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) 84 self.assertNotIn("fragmentShaderBarycentric", self.meta["features"])
83 85
84 def test_decoded_half_inputs(self): 86 def test_decoded_half_inputs(self):
85 self.assertIn("OpDecorate %in_f16h0_0 Location 29", self.spv) 87 self.assertIn("OpDecorate %in_f16h0_0 Location 28", self.spv)
86 self.assertIn("OpDecorate %in_f16h0_1 Location 30", self.spv) 88 self.assertIn("OpDecorate %in_f16h0_1 Location 29", self.spv)
87 self.assertNotIn("%in_f16h0_0 Flat", self.spv) 89 self.assertNotIn("%in_f16h0_0 Flat", self.spv)
88 self.assertEqual(self.meta["f16_halves"], {"0": [29, 30]}) 90 self.assertEqual(self.meta["f16_halves"], {"0": [28, 29]})
89 self.assertEqual(self.meta["inputs"], [0, 1, 29, 30]) 91 self.assertEqual(self.meta["inputs"], [0, 1, 28, 29])
90 92
91 def test_values(self): 93 def test_values(self):
92 words = support.mrt0_words(self.spv, inputs=self.inputs()) 94 words = support.mrt0_words(self.spv, inputs=self.inputs())
@@ -102,9 +104,9 @@ class FallbackPixelShader(unittest.TestCase):
102 self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) 104 self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"])
103 105
104 def test_location_clash_is_rejected(self): 106 def test_location_clash_is_rejected(self):
105 """attr29 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" 107 """attr28 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data."""
106 clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", 108 clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2",
107 "v_interp_p1_f32_e32 v3, v0, attr29.x", "v_interp_p2_f32_e32 v3, v1, attr29.x", 109 "v_interp_p1_f32_e32 v3, v0, attr28.x", "v_interp_p2_f32_e32 v3, v1, attr28.x",
108 "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] 110 "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"]
109 with self.assertRaises(rdna2spirv.Unsupported): 111 with self.assertRaises(rdna2spirv.Unsupported):
110 translate("ps_f16_clash", clash) 112 translate("ps_f16_clash", clash)
@@ -119,10 +121,10 @@ class FallbackPixelShader(unittest.TestCase):
119class FallbackVertexShader(unittest.TestCase): 121class FallbackVertexShader(unittest.TestCase):
120 def test_exports_decoded_halves(self): 122 def test_exports_decoded_halves(self):
121 spv, meta = translate("vs_f16_fallback", VS.splitlines()) 123 spv, meta = translate("vs_f16_fallback", VS.splitlines())
122 for n, lo, hi in ((0, 29, 30), (1, 27, 28)): 124 for n, lo, hi in ((0, 28, 29), (1, 26, 27)):
123 self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) 125 self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv)
124 self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) 126 self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv)
125 self.assertEqual(meta["f16_halves"], {"0": [29, 30], "1": [27, 28]}) 127 self.assertEqual(meta["f16_halves"], {"0": [28, 29], "1": [26, 27]})
126 for vid in range(3): 128 for vid in range(3):
127 out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) 129 out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0})
128 u, v = float((vid << 1) & 2), float(vid & 2) 130 u, v = float((vid << 1) & 2), float(vid & 2)
@@ -137,13 +139,31 @@ class FallbackVertexShader(unittest.TestCase):
137 self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) 139 self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)])
138 140
139 def test_halves_never_overlap_the_shaders_params(self): 141 def test_halves_never_overlap_the_shaders_params(self):
140 """param29 occupies location 29, so param0's halves (29, 30) are left out; nothing else moves.""" 142 """param28 occupies location 28, so param0's halves (28, 29) are left out; nothing else moves."""
141 spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", 143 spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done",
142 "exp param0 v1, v1, v1, v1", "exp param29 v1, v1, v1, v1", 144 "exp param0 v1, v1, v1, v1", "exp param28 v1, v1, v1, v1",
143 "s_endpgm"]) 145 "s_endpgm"])
144 self.assertNotIn("%out_f16h0", spv) 146 self.assertNotIn("%out_f16h0", spv)
145 self.assertNotIn("f16_halves", meta) 147 self.assertNotIn("f16_halves", meta)
146 self.assertIn("OpDecorate %out_param29 Location 29", spv) 148 self.assertIn("OpDecorate %out_param28 Location 28", spv)
149
150 def test_halves_fit_just_above_the_shaders_params(self):
151 """param27 ends at location 27, so param0's halves still fit at 28 and 29."""
152 spv, meta = translate("vs_f16_near", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done",
153 "exp param0 v1, v1, v1, v1", "exp param27 v1, v1, v1, v1",
154 "s_endpgm"])
155 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
156 self.assertIn("OpDecorate %out_param27 Location 27", spv)
157
158 def test_top_half_fits_moltenvk_output_budget(self):
159 """SHADER-291: MoltenVK reports maxVertexOutputComponents = 124, and Metal and the validation layer count
160 gl_Position's 4 in it (VUID-RuntimeSpirv-Location-06272), so the highest location a VS writes must be 29."""
161 top = rdna2spirv.f16_half_location(0, 1)
162 self.assertEqual(top, 29)
163 self.assertLessEqual((top + 1) * 4 + 4, 124)
164 spv, _ = translate("vs_f16_fallback", VS.splitlines())
165 locations = [int(m) for m in re.findall(r"OpDecorate %out\S+ Location (\d+)", spv)]
166 self.assertEqual(max(locations), top)
147 167
148 def test_off_by_default(self): 168 def test_off_by_default(self):
149 spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) 169 spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False)
diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py
index 382955f5f..22156da60 100644
--- a/tests/semantic/test_interp_merge_check.py
+++ b/tests/semantic/test_interp_merge_check.py
@@ -1,4 +1,4 @@
1"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule. 1"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge or phi rule.
2 2
3OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / 3OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch /
4OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an 4OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an
@@ -74,5 +74,76 @@ class MergeRule(unittest.TestCase):
74 si.check_structure([ok[0]]) 74 si.check_structure([ok[0]])
75 75
76 76
77CS_LINES = ["v_mov_b32_e32 v1, 0x40", "global_load_dword v2, v1, s[0:1]", "s_waitcnt vmcnt(0)",
78 "v_mov_b32_e32 v3, 0", "buffer_store_dword v2, v3, s[0:3], 0 offen", "s_endpgm"]
79
80
81def cs_spv():
82 from test_salu64_bitwise_data import translate_cs
83 text = translate_cs(CS_LINES)
84 assert " = OpPhi " in text
85 return text
86
87
88def run_cs(text):
89 mem = {0x40: 0x1234}
90 si.run_workgroup(text, 1, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
91 push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 32, memory=mem)
92 return mem
93
94
95class PhiRule(unittest.TestCase):
96 """OpPhi must be the first instructions of its block: only OpLabel or OpPhi before it (SPIR-V 2.16.2)."""
97
98 def test_translated_module_runs(self):
99 self.assertEqual(run_cs(cs_spv())[0], 0x1234)
100
101 def test_phi_after_another_instruction(self):
102 lines = cs_spv().splitlines()
103 k = next(i for i, ln in enumerate(lines) if " = OpPhi " in ln)
104 lines[k], lines[k + 1] = lines[k + 1], lines[k] # the phi now follows a non-phi instruction
105 bad = "\n".join(lines) + "\n"
106 with self.assertRaisesRegex(si.InvalidModule, "OpPhi"):
107 run_cs(bad)
108
109 def test_rule_directly(self):
110 lab = (None, "OpLabel", [], "%b = OpLabel")
111 phi = ("%p", "OpPhi", [], "%p = OpPhi %uint %a %x %c %y")
112 add = ("%q", "OpIAdd", [], "%q = OpIAdd %uint %a %a")
113 si.check_structure([lab, phi, phi, add])
114 with self.assertRaisesRegex(si.InvalidModule, "OpPhi"):
115 si.check_structure([lab, add, phi])
116 with self.assertRaisesRegex(wi.InvalidModule, "OpPhi"):
117 wi.run_wave("OpFunction %void None %f\n%b = OpLabel\n%q = OpIAdd %uint %a %a\n"
118 "%p = OpPhi %uint %a %x %c %y\nOpReturn\nOpFunctionEnd\n", wave=32)
119
120
121class FunctionVariableRule(unittest.TestCase):
122 """A Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1)."""
123
124 def test_rule_directly(self):
125 lab = (None, "OpLabel", [], "%b = OpLabel")
126 var = ("%v", "OpVariable", ["%_ptr_Function_uint", "Function"], "%v = OpVariable %_ptr_Function_uint Function")
127 br = (None, "OpBranch", ["%c"], "OpBranch %c")
128 si.check_structure([lab, var, br, lab])
129 with self.assertRaisesRegex(si.InvalidModule, "first block"):
130 si.check_structure([lab, br, lab, var])
131 # a new function starts counting again
132 fn = ("%f", "OpFunction", [], "%f = OpFunction %void None %t")
133 si.check_structure([fn, lab, br, lab, fn, lab, var])
134
135 def test_translated_module_with_a_variable_moved(self):
136 lines = cs_spv().splitlines()
137 k = next(i for i, ln in enumerate(lines) if " OpVariable " in ln and " Function" in ln)
138 var = lines.pop(k)
139 last_label = max(i for i, ln in enumerate(lines) if ln.strip().endswith("= OpLabel"))
140 lines.insert(last_label + 1, var)
141 bad = "\n".join(lines) + "\n"
142 with self.assertRaisesRegex(si.InvalidModule, "first block"):
143 run_cs(bad)
144 with self.assertRaisesRegex(wi.InvalidModule, "first block"):
145 wi.run_wave(bad, wave=32)
146
147
77if __name__ == "__main__": 148if __name__ == "__main__":
78 unittest.main() 149 unittest.main()
diff --git a/tests/semantic/test_interp_p1lv_f16.py b/tests/semantic/test_interp_p1lv_f16.py
index b50e280dd..0ddf9bd74 100644
--- a/tests/semantic/test_interp_p1lv_f16.py
+++ b/tests/semantic/test_interp_p1lv_f16.py
@@ -259,11 +259,11 @@ class InterpP1lvF16HalvesFallbackTests(unittest.TestCase):
259 self.assertNotIn("BaryCoordKHR", spv) 259 self.assertNotIn("BaryCoordKHR", spv)
260 self.assertNotIn("FragmentBarycentricKHR", spv) 260 self.assertNotIn("FragmentBarycentricKHR", spv)
261 self.assertNotIn("fragmentShaderBarycentric", meta["features"]) 261 self.assertNotIn("fragmentShaderBarycentric", meta["features"])
262 self.assertIn("OpDecorate %in_f16h0_0 Location 29", spv) 262 self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv)
263 self.assertIn("OpDecorate %in_f16h0_1 Location 30", spv) 263 self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv)
264 self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv) 264 self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv)
265 self.assertEqual(meta["f16_halves"], {"0": [29, 30]}) 265 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
266 self.assertEqual(meta["inputs"], [29, 30]) 266 self.assertEqual(meta["inputs"], [28, 29])
267 267
268 inputs = { 268 inputs = {
269 "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32) 269 "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32)
@@ -372,9 +372,9 @@ class InterpF16BaryFallbackTests(unittest.TestCase):
372 spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR, 372 spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR,
373 dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True) 373 dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True)
374 self.assertNotIn("PerVertexKHR", spv) 374 self.assertNotIn("PerVertexKHR", spv)
375 self.assertIn("OpDecorate %in_f16h0_0 Location 29", spv) 375 self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv)
376 self.assertIn("OpDecorate %in_f16h0_1 Location 30", spv) 376 self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv)
377 self.assertEqual(meta["f16_halves"], {"0": [29, 30]}) 377 self.assertEqual(meta["f16_halves"], {"0": [28, 29]})
378 378
379 379
380class InterpF16GuardsAndRejectionsTests(unittest.TestCase): 380class InterpF16GuardsAndRejectionsTests(unittest.TestCase):
diff --git a/tests/semantic/test_mask_src_sgpr_const.py b/tests/semantic/test_mask_src_sgpr_const.py
new file mode 100644
index 000000000..ddeaff21f
--- /dev/null
+++ b/tests/semantic/test_mask_src_sgpr_const.py
@@ -0,0 +1,114 @@
1"""A constant lane mask that reaches a mask consumer through an SGPR: lane L takes bit L of the constant.
2
3`s_mov_b32 s20, 0x3ffffc00; s_and_saveexec_b32 s6, s20` leaves lanes 10..29 active on hardware. Gen.mask_src read the
4SGPR's raw value, which is the same non-zero constant in every invocation, so every lane stayed on (found writing
5#1771's GPU test; the immediate form `s_and_saveexec_b32 s6, 0x3ffffc00` was already right). Each case runs a
6translated pixel shader in tests/semantic/spirv_wave_interp.py as one wave and compares every lane with the
7immediate form and with the bits of the constant. Masks built by compares still work (they hold 0 / ~0 per lane).
8Standard library only; no GPU, no game files.
9"""
10import os
11import sys
12import unittest
13
14HERE = os.path.dirname(os.path.abspath(__file__))
15sys.dont_write_bytecode = True
16sys.path.insert(0, HERE)
17
18from test_salu64_bitwise_data import run_ps_wave # noqa: E402 (also puts tools/ on sys.path)
19
20EPILOGUE = ["v_mov_b32 v0, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0"]
21
22
23def active_lanes(lines, wave):
24 """Lanes whose v1 ends as 0x22: the ones the mask under test left active."""
25 outs, _ = run_ps_wave(["v_mov_b32 v1, 0x11"] + lines + ["v_mov_b32 v1, 0x22", f"s_mov_b{wave} exec, -1"] +
26 EPILOGUE, wave=wave)
27 return [lane for lane in range(wave) if outs[lane][1] == 0x22]
28
29
30def bits(v, wave):
31 return [lane for lane in range(wave) if v >> lane & 1]
32
33
34class SgprConstantMask(unittest.TestCase):
35 def test_saveexec_wave32(self):
36 for c in (0x3FFFFC00, 0x00000001, 0x80000000, 0x0000FF00, 0x55555555):
37 with self.subTest(c=hex(c)):
38 via_sgpr = active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_saveexec_b32 s6, s20"], 32)
39 via_imm = active_lanes([f"s_and_saveexec_b32 s6, {c:#x}"], 32)
40 self.assertEqual(via_sgpr, bits(c, 32))
41 self.assertEqual(via_sgpr, via_imm)
42
43 def test_exec_write_and_cndmask(self):
44 c = 0x0F0F00FF
45 self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_b32 exec_lo, exec_lo, s20"], 32), bits(c, 32))
46 outs, _ = run_ps_wave([f"s_mov_b32 s20, {c:#x}", "v_cndmask_b32_e64 v1, 0, 1, s20"] + EPILOGUE, wave=32)
47 self.assertEqual([lane for lane in range(32) if outs[lane][1] == 1], bits(c, 32))
48
49 def test_sop2_with_a_constant_and_exec(self):
50 # 32-bit bitwise SOP2 on EXEC with a constant, inline or in an SGPR (both were taken whole before).
51 c, full = 0x0F0F00FF, 0xFFFFFFFF # EXEC starts with every lane on
52 for kind, want in (("and", full & c), ("andn2", full & ~c), ("or", full | c), ("xor", full ^ c)):
53 for src in (f"{c:#x}", "s20"):
54 with self.subTest(op=kind, src=src):
55 lines = [f"s_mov_b32 s20, {c:#x}", f"s_{kind}_b32 exec_lo, exec_lo, {src}"]
56 self.assertEqual(active_lanes(lines, 32), bits(want & full, 32))
57
58 def test_exec_lo_from_an_sgpr_constant(self):
59 c = 0x00FF00F0
60 self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_mov_b32 exec_lo, s20"], 32), bits(c, 32))
61
62 def test_wave64_pair_takes_each_half_from_its_own_sgpr(self):
63 lo, hi = 0x0000FFFF, 0xF0000000
64 lanes = active_lanes([f"s_mov_b32 s20, {lo:#x}", f"s_mov_b32 s21, {hi:#x}",
65 "s_and_saveexec_b64 s[6:7], s[20:21]"], 64)
66 self.assertEqual(lanes, bits(lo | hi << 32, 64))
67
68 def test_masks_from_compares_still_work(self):
69 lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmp_gt_u32_e64 s20, 12, v4", "s_and_saveexec_b32 s6, s20"]
70 self.assertEqual(active_lanes(lines, 32), list(range(12)))
71 lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4", "v_cmp_lt_u32_e64 s[20:21], 40, v4",
72 "s_and_saveexec_b64 s[6:7], s[20:21]"]
73 self.assertEqual(active_lanes(lines, 64), list(range(41, 64)))
74
75
76class MaskAndConstantIntoAnSgpr(unittest.TestCase):
77 """@Pierre-Kookis's case on #1792 (GPU-reproduced on AMD RDNA2 and an RTX 4070 Ti SUPER): an SOP2 of EXEC with a
78 constant into a plain SGPR is data, and s_bcnt1 counts the wave's bits. The first version of this fix put each
79 lane's bit there and got 32 / 0 instead of 1 / 8."""
80
81 def test_s_and_of_exec_with_a_constant_counts_the_wave_bits(self):
82 import struct
83 import tempfile
84 import warnings
85 import spirv_mini_interp as si
86 from support import STUB_DXBC, rdna2spirv
87 lines = ["s_and_b32 s20, exec_lo, 1", "s_bcnt1_i32_b32 s21, s20", "s_and_b32 s22, exec_lo, 0xff00",
88 "s_bcnt1_i32_b32 s23, s22", "v_lshlrev_b32 v3, 3, v0", "v_mov_b32_e32 v1, s21",
89 "buffer_store_dword v1, v3, s[0:3], 0 offen", "v_add_nc_u32 v3, 4, v3", "v_mov_b32_e32 v1, s23",
90 "buffer_store_dword v1, v3, s[0:3], 0 offen", "s_endpgm"]
91 with tempfile.TemporaryDirectory() as tmp:
92 os.mkdir(os.path.join(tmp, "disasm"))
93 os.mkdir(os.path.join(tmp, "fssm"))
94 with open(os.path.join(tmp, "cs_bcnt.dxbc"), "wb") as f:
95 f.write(STUB_DXBC)
96 hdr = bytearray(0x148)
97 struct.pack_into("<4I", hdr, 0x138, 0x88, 32, 1, 1)
98 with open(os.path.join(tmp, "fssm", "cs_bcnt.fssm"), "wb") as f:
99 f.write(hdr)
100 src = os.path.join(tmp, "disasm", "cs_bcnt.s")
101 with open(src, "w", encoding="utf-8") as f:
102 f.write("; cs_bcnt\n" + "".join(f"\t{ln}\n" for ln in lines))
103 with warnings.catch_warnings():
104 warnings.simplefilter("ignore", ResourceWarning)
105 spv = rdna2spirv.translate(src)
106 mem = si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0),
107 "%sg_lane": i},
108 push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={})
109 for lane in range(32):
110 self.assertEqual((mem[8 * lane], mem[8 * lane + 4]), (1, 8), f"lane {lane}")
111
112
113if __name__ == "__main__":
114 unittest.main()
diff --git a/tests/semantic/test_scalar_noop_waitcnt.py b/tests/semantic/test_scalar_noop_waitcnt.py
new file mode 100644
index 000000000..67b805220
--- /dev/null
+++ b/tests/semantic/test_scalar_noop_waitcnt.py
@@ -0,0 +1,636 @@
1"""Semantic and translation tests for RDNA2 scalar no-op, hint, waitcnt, and mode instructions.
2
3Covers the 11 named scalar instructions and their syntax variants in tools/shader_ir.py and tools/rdna2spirv.py:
4 * In rdna2spirv.NOOPS (emits no SPIR-V instructions, preserves VGPRs, SGPRs, VCC, SCC, and EXEC):
5 s_clause, s_delay_alu (RDNA3 hint kept in NOOPS), s_inst_prefetch, s_setprio, s_sleep,
6 s_waitcnt_depctr, s_waitcnt_expcnt, s_waitcnt_lgkmcnt, s_waitcnt_vmcnt,
7 plus the sibling wait/no-op forms s_waitcnt, s_waitcnt_vscnt, s_nop, and v_nop.
8 * Refused mode mnemonics in rdna2spirv._insn:
9 s_denorm_mode and s_round_mode raise Unsupported ("MODE is modelled through s_setreg only");
10 valid MODE.FP_ROUND[3:2] writes go through s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0|3,
11 which updates %mode_r16 only and leaves VGPRs, SGPRs, VCC, SCC, and EXEC intact, while
12 non-MODE s_setreg* writes emit nothing and other MODE writes stay Unsupported.
13
14Standard library only (runs with python -I); hand-written RDNA2 listings, no GPU or game data.
15"""
16from __future__ import annotations
17
18import gc
19import os
20import struct
21import sys
22import tempfile
23import unittest
24import warnings
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27ROOT = os.path.dirname(os.path.dirname(HERE))
28TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
29
30sys.dont_write_bytecode = True
31for _p in (HERE, TOOLS_DIR):
32 if _p not in sys.path:
33 sys.path.insert(0, _p)
34
35import rdna2spirv # noqa: E402
36import shader_ir # noqa: E402
37import spirv_mini_interp as si # noqa: E402
38
39M32 = 0xFFFFFFFF
40STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
41# Raw buffer V# (OOB_SELECT 3, stride 0): any dword offset is in bounds in spirv_mini_interp.
42VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
43
44# Handled scalar no-op/hint/waitcnt instructions and explicit syntax variants accepted by shader_ir.py.
45SCALAR_NOOP_VARIANTS = [
46 "s_clause 0x1",
47 "s_clause 0",
48 "s_clause 15",
49 "s_delay_alu 0",
50 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
51 "s_delay_alu instid0(VALU_DEP_2)",
52 "s_inst_prefetch 0x0",
53 "s_inst_prefetch 0x1",
54 "s_inst_prefetch -1",
55 "s_setprio 0x0",
56 "s_setprio 0x2",
57 "s_setprio 3",
58 "s_sleep 0x0",
59 "s_sleep 0x1",
60 "s_sleep 7",
61 "s_waitcnt_depctr 0xffe3",
62 "s_waitcnt_depctr 0x0",
63 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
64 "s_waitcnt_depctr depctr_hold_cnt(0) depctr_sa_sdst(0) depctr_va_vdst(0)",
65 "s_waitcnt_expcnt null, 0x0",
66 "s_waitcnt_expcnt null, 0x7",
67 "s_waitcnt_expcnt 0x0",
68 "s_waitcnt_lgkmcnt null, 0x0",
69 "s_waitcnt_lgkmcnt null, 0x3f",
70 "s_waitcnt_lgkmcnt 0x0",
71 "s_waitcnt_vmcnt null, 0x0",
72 "s_waitcnt_vmcnt null, 0x3f",
73 "s_waitcnt_vmcnt 0x0",
74 # Sibling wait/no-op and non-MODE setreg forms handled alongside them in NOOPS / mode_write.
75 "s_waitcnt vmcnt(0)",
76 "s_waitcnt expcnt(0)",
77 "s_waitcnt lgkmcnt(0)",
78 "s_waitcnt vmcnt(1) lgkmcnt(2)",
79 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
80 "s_waitcnt 0",
81 "s_waitcnt_vscnt null, 0x0",
82 "s_waitcnt_vscnt vscnt(0)",
83 "s_nop 0",
84 "s_nop 0x7",
85 "v_nop",
86 "v_nop_e32",
87 "v_nop_e64",
88 "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO, 0, 32), 0",
89 "s_setreg_b32 hwreg(HW_REG_IB_STS), s2",
90]
91
92# Representative instruction per handled mnemonic from the 9-op scalar NOOPS group + s_waitcnt / s_nop.
93REPRESENTATIVE_NOOPS = [
94 "s_clause 0x1",
95 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
96 "s_inst_prefetch 0x0",
97 "s_setprio 0x2",
98 "s_sleep 0x1",
99 "s_waitcnt_depctr 0xffe3",
100 "s_waitcnt_expcnt null, 0x0",
101 "s_waitcnt_lgkmcnt null, 0x0",
102 "s_waitcnt_vmcnt null, 0x0",
103 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
104 "s_waitcnt_vscnt null, 0x0",
105 "s_nop 0",
106]
107
108REFUSED_MODE_VARIANTS = [
109 "s_denorm_mode 0x3",
110 "s_denorm_mode 0",
111 "s_round_mode 0x3",
112 "s_round_mode 0",
113]
114
115MODELLED_MODE_VARIANTS = [
116 ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", "%c0"),
117 ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", "%c3"),
118]
119
120_TMP_DIR: tempfile.TemporaryDirectory | None = None
121
122
123def setUpModule() -> None:
124 global _TMP_DIR
125 _TMP_DIR = tempfile.TemporaryDirectory()
126 os.mkdir(os.path.join(_TMP_DIR.name, "disasm"))
127 os.mkdir(os.path.join(_TMP_DIR.name, "fssm"))
128
129
130def tearDownModule() -> None:
131 global _TMP_DIR
132 if _TMP_DIR is not None:
133 gc.collect()
134 _TMP_DIR.cleanup()
135 _TMP_DIR = None
136
137
138def _ensure_dir() -> str:
139 if _TMP_DIR is None:
140 setUpModule()
141 assert _TMP_DIR is not None
142 return _TMP_DIR.name
143
144
145def make_fssm(threads: int, user_sgprs: int = 4) -> bytes:
146 """Synthetic compute FSSM header: user_sgprs USER_SGPRs, TGID_X_EN=0, TIDIG_COMP_CNT=0, size=(threads,1,1)."""
147 blob = bytearray(0x148)
148 rsrc2 = (user_sgprs & 31) << 1
149 struct.pack_into("<4I", blob, 0x138, rsrc2, threads, 1, 1)
150 return bytes(blob)
151
152
153def translate_ps(name: str, lines: list[str]) -> str:
154 root = _ensure_dir()
155 src = os.path.join(root, "disasm", name + ".s")
156 with open(src, "w", encoding="utf-8", newline="\n") as f:
157 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines))
158 with open(os.path.join(root, name + ".dxbc"), "wb") as f:
159 f.write(STUB_DXBC)
160 with warnings.catch_warnings():
161 warnings.simplefilter("ignore", ResourceWarning)
162 return rdna2spirv.translate(src)
163
164
165def translate_cs(name: str, lines: list[str], threads: int) -> str:
166 root = _ensure_dir()
167 src = os.path.join(root, "disasm", name + ".s")
168 with open(src, "w", encoding="utf-8", newline="\n") as f:
169 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines))
170 with open(os.path.join(root, name + ".dxbc"), "wb") as f:
171 f.write(STUB_DXBC)
172 with open(os.path.join(root, "fssm", name + ".fssm"), "wb") as f:
173 f.write(make_fssm(threads))
174 with warnings.catch_warnings():
175 warnings.simplefilter("ignore", ResourceWarning)
176 return rdna2spirv.translate(src)
177
178
179def ps_program(middle: list[str], *, scc_one: bool = True, vcc_one: bool = True,
180 exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> list[str]:
181 """Synthetic PS testing VGPRs, SGPRs, SCC, VCC, and EXEC across interleaved arithmetic and `middle`."""
182 s_rhs = 5 if scc_one else 0
183 s_lhs = 0xFFFFFFFF if scc_one else 0x12340000
184 cmp_val = (0x11112222 + add_k) & M32 if vcc_one else 0x00000000
185 return [
186 "v_mov_b32 v0, 0x11112222",
187 "v_mov_b32 v1, 0x33334444",
188 "v_mov_b32 v2, 0x55556666",
189 "v_mov_b32 v3, 0x77778888",
190 f"s_mov_b32 s2, {s_lhs:#x}",
191 f"s_mov_b32 s3, {s_rhs:#x}",
192 "s_add_u32 s4, s2, s3", # SCC = 1 iff s_lhs + s_rhs overflows 32 bits
193 f"v_add_nc_u32 v0, v0, {add_k:#x}",
194 f"v_cmp_eq_u32 vcc_lo, v0, {cmp_val:#x}", # VCC = 1 iff vcc_one
195 f"s_mov_b32 exec_lo, {exec_lo:#x}",
196 *middle,
197 "s_cselect_b32 s5, 0x10000001, 0x20000002", # reads SCC
198 "s_add_u32 s6, s4, s5", # reads SGPR s4 and selected s5
199 "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", # reads VCC (and VGPR v1 when VCC=1)
200 "v_add_nc_u32 v2, v2, s6", # reads EXEC, VGPR v2, SGPR s6
201 "exp mrt0 v0, v1, v2, v3 done vm",
202 "s_endpgm",
203 ]
204
205
206def expected_ps_mrt0(*, scc_one: bool = True, vcc_one: bool = True,
207 exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> tuple[int, int, int, int]:
208 """Plain-Python reference for ps_program()."""
209 active = bool(exec_lo & 1)
210 s_lhs = 0xFFFFFFFF if scc_one else 0x12340000
211 s_rhs = 5 if scc_one else 0
212 s4 = (s_lhs + s_rhs) & M32
213 scc = (s_lhs + s_rhs) > M32
214 v0 = ((0x11112222 + add_k) & M32) # executed while EXEC=1 initially
215 vcc = vcc_one # evaluated while EXEC=1 initially
216 s5 = 0x10000001 if scc else 0x20000002
217 s6 = (s4 + s5) & M32
218 v1 = (0x33334444 if vcc else 0x99990000) if active else 0x33334444
219 v2 = ((0x55556666 + s6) & M32) if active else 0x55556666
220 v3 = 0x77778888
221 if not active:
222 return (0, 0, 0, 0)
223 return (v0, v1, v2, v3)
224
225
226def cs_program(middle: list[str], *, wave64: bool, scc_one: bool = True,
227 exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[str]:
228 """Synthetic wave32/wave64 CS checking VGPRs, SGPRs, SCC, VCC, and EXEC across all lanes."""
229 s_lhs = 0xFFFFFFFF if scc_one else 0x10203040
230 s_rhs = 3 if scc_one else 1
231 if wave64:
232 lane_setup = [
233 "s_mov_b64 exec, -1",
234 "v_mbcnt_lo_u32_b32 v0, -1, 0",
235 "v_mbcnt_hi_u32_b32 v0, -1, v0",
236 ]
237 vcc_cmp = "v_cmp_eq_u32 vcc, v4, 0"
238 set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}", f"s_mov_b32 exec_hi, {exec_hi:#x}"]
239 reset_exec = "s_mov_b64 exec, -1"
240 vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc"
241 else:
242 lane_setup = [] # v0 is seeded directly from LocalInvocationId.x
243 vcc_cmp = "v_cmp_eq_u32 vcc_lo, v4, 0"
244 set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}"]
245 reset_exec = "s_mov_b32 exec_lo, -1"
246 vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc_lo"
247
248 return [
249 *lane_setup,
250 "v_mov_b32 v1, v0",
251 "v_add_nc_u32 v1, v1, 10",
252 "v_mov_b32 v2, 0x77770000",
253 "v_add_nc_u32 v2, v2, v0",
254 "v_mov_b32 v3, 0x1000",
255 "v_and_b32 v4, v0, 1",
256 vcc_cmp, # even lanes: VCC = 1; odd lanes: VCC = 0
257 "s_mov_b32 s8, 0x01020304",
258 "s_mov_b32 s9, 0x55667788",
259 f"s_mov_b32 s10, {s_lhs:#x}",
260 f"s_add_u32 s11, s10, {s_rhs:#x}", # SCC = 1 iff scc_one
261 *set_exec,
262 *middle,
263 "v_add_nc_u32 v1, v1, 0x100", # updates v1 only in lanes where EXEC=1
264 "s_cselect_b32 s12, 0x10000, 0x20000", # reads SCC
265 reset_exec,
266 vcc_cnd, # reads VCC across all lanes (even keeps v2, odd gets 0x99990000)
267 "v_add_nc_u32 v3, v3, s8", # reads SGPR s8
268 "v_add_nc_u32 v3, v3, s12", # reads s12 (SCC outcome)
269 "v_add_nc_u32 v3, v3, s11", # reads s11 (s_add_u32 sum)
270 "v_mov_b32 v4, s9", # reads SGPR s9
271 "v_lshlrev_b32 v5, 4, v0", # byte offset = 16 * lane
272 "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen",
273 "s_endpgm",
274 ]
275
276
277def expected_cs_words(lanes: int, *, scc_one: bool = True,
278 exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[tuple[int, int, int, int]]:
279 """Plain-Python reference for cs_program()."""
280 s_lhs = 0xFFFFFFFF if scc_one else 0x10203040
281 s_rhs = 3 if scc_one else 1
282 s11 = (s_lhs + s_rhs) & M32
283 s12 = 0x10000 if ((s_lhs + s_rhs) > M32) else 0x20000
284 exec_mask = (exec_hi << 32) | exec_lo
285 out = []
286 for lane in range(lanes):
287 active = bool((exec_mask >> lane) & 1)
288 w0 = (lane + 10 + (0x100 if active else 0)) & M32
289 w1 = (0x77770000 + lane) if (lane % 2 == 0) else 0x99990000
290 w2 = (0x1000 + 0x01020304 + s12 + s11) & M32
291 w3 = 0x55667788
292 out.append((w0, w1, w2, w3))
293 return out
294
295
296def run_cs(spv: str, lanes: int) -> list[tuple[int, int, int, int]]:
297 mem = si.run_workgroup(
298 spv, lanes, lanes,
299 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
300 push_constants=VSHARP + [0] * 28,
301 memory={},
302 )
303 return [tuple(mem[16 * lane + 4 * c] for c in range(4)) for lane in range(lanes)]
304
305
306class ScalarNoopWaitcntParsingTests(unittest.TestCase):
307 """Exact syntax and operand parsing in tools/shader_ir.py for all 11 scalar ops and variants."""
308
309 def test_parse_all_scalar_noop_waitcnt_and_mode_forms(self):
310 cases = [
311 ("s_clause 0x1", "s_clause", [{"k": "imm", "v": 1}]),
312 ("s_delay_alu 0", "s_delay_alu", [{"k": "imm", "v": 0}]),
313 (
314 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
315 "s_delay_alu",
316 [{"k": "special", "t": "instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)"}],
317 ),
318 ("s_denorm_mode 0x3", "s_denorm_mode", [{"k": "imm", "v": 3}]),
319 ("s_inst_prefetch 0x0", "s_inst_prefetch", [{"k": "imm", "v": 0}]),
320 ("s_inst_prefetch -1", "s_inst_prefetch", [{"k": "imm", "v": -1}]),
321 ("s_round_mode 0x3", "s_round_mode", [{"k": "imm", "v": 3}]),
322 ("s_setprio 0x2", "s_setprio", [{"k": "imm", "v": 2}]),
323 ("s_sleep 0x1", "s_sleep", [{"k": "imm", "v": 1}]),
324 ("s_waitcnt_depctr 0xffe3", "s_waitcnt_depctr", [{"k": "imm", "v": 0xFFE3}]),
325 (
326 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
327 "s_waitcnt_depctr",
328 [{"k": "special", "t": "depctr_vm_vsrc(0)"}, {"k": "special", "t": "depctr_va_sdst(0)"}],
329 ),
330 (
331 "s_waitcnt_expcnt null, 0x0",
332 "s_waitcnt_expcnt",
333 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
334 ),
335 (
336 "s_waitcnt_lgkmcnt null, 0x3f",
337 "s_waitcnt_lgkmcnt",
338 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0x3F}],
339 ),
340 (
341 "s_waitcnt_vmcnt null, 0x0",
342 "s_waitcnt_vmcnt",
343 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
344 ),
345 (
346 "s_waitcnt_vscnt null, 0x0",
347 "s_waitcnt_vscnt",
348 [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}],
349 ),
350 ("s_waitcnt vmcnt(0)", "s_waitcnt", [{"k": "special", "t": "vmcnt(0)"}]),
351 ("s_waitcnt expcnt(0)", "s_waitcnt", [{"k": "special", "t": "expcnt(0)"}]),
352 ("s_waitcnt lgkmcnt(0)", "s_waitcnt", [{"k": "special", "t": "lgkmcnt(0)"}]),
353 (
354 "s_waitcnt vmcnt(1) lgkmcnt(2)",
355 "s_waitcnt",
356 [{"k": "special", "t": "vmcnt(1)"}, {"k": "special", "t": "lgkmcnt(2)"}],
357 ),
358 (
359 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
360 "s_waitcnt",
361 [{"k": "special", "t": "vmcnt(0) expcnt(0) lgkmcnt(0)"}],
362 ),
363 ("s_waitcnt 0", "s_waitcnt", [{"k": "imm", "v": 0}]),
364 (
365 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3",
366 "s_setreg_imm32_b32",
367 [{"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, {"k": "imm", "v": 3}],
368 ),
369 ("s_nop 0", "s_nop", [{"k": "imm", "v": 0}]),
370 ("v_nop", "v_nop", []),
371 ]
372 for text, want_op, want_args in cases:
373 with self.subTest(line=text):
374 parsed = shader_ir.parse_line("\t" + text)
375 self.assertIsNotNone(parsed)
376 self.assertEqual(parsed["op"], want_op)
377 self.assertEqual(parsed["args"], want_args)
378 self.assertEqual(parsed["mods"], [])
379 self.assertTrue(all(arg["k"] != "raw" for arg in parsed["args"]))
380
381
382class PixelShaderNoopWaitcntTests(unittest.TestCase):
383 """PS translation and spirv_mini_interp execution across all handled NOOPS and waitcnt variants."""
384
385 def test_variants_emit_no_extra_spirv_and_preserve_state_active_scc1_vcc1(self):
386 baseline = translate_ps("ps_noop_base_11", ps_program([], scc_one=True, vcc_one=True))
387 want = expected_ps_mrt0(scc_one=True, vcc_one=True)
388 self.assertEqual(want, (0x11112232, 0x33334444, 0x6555666B, 0x77778888))
389 self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
390 self.assertNotIn("OpControlBarrier", baseline)
391 self.assertNotIn("OpMemoryBarrier", baseline)
392
393 for variant in SCALAR_NOOP_VARIANTS:
394 with self.subTest(insn=variant):
395 spv = translate_ps("ps_noop_var", ps_program([variant], scc_one=True, vcc_one=True))
396 self.assertEqual(spv, baseline, f"{variant} emitted unexpected SPIR-V operations")
397 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
398
399 def test_variants_preserve_scc0_and_vcc0(self):
400 baseline = translate_ps("ps_noop_base_00", ps_program([], scc_one=False, vcc_one=False))
401 want = expected_ps_mrt0(scc_one=False, vcc_one=False)
402 self.assertEqual(want, (0x11112232, 0x99990000, 0x87896668, 0x77778888))
403 self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
404
405 for variant in SCALAR_NOOP_VARIANTS:
406 with self.subTest(insn=variant):
407 spv = translate_ps("ps_noop_var00", ps_program([variant], scc_one=False, vcc_one=False))
408 self.assertEqual(spv, baseline)
409 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
410
411 def test_interleaved_across_every_arithmetic_step(self):
412 base_lines = ps_program([], scc_one=True, vcc_one=True)
413 baseline = translate_ps("ps_interleave_base", base_lines)
414 want = expected_ps_mrt0(scc_one=True, vcc_one=True)
415 interleaved = [
416 "v_mov_b32 v0, 0x11112222",
417 "v_mov_b32 v1, 0x33334444",
418 "v_mov_b32 v2, 0x55556666",
419 "v_mov_b32 v3, 0x77778888",
420 "s_clause 0x1",
421 "s_mov_b32 s2, 0xffffffff",
422 "s_mov_b32 s3, 5",
423 "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)",
424 "s_add_u32 s4, s2, s3",
425 "s_inst_prefetch 0x0",
426 "s_setprio 0x2",
427 "v_add_nc_u32 v0, v0, 0x10",
428 "s_sleep 0x1",
429 "v_cmp_eq_u32 vcc_lo, v0, 0x11112232",
430 "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)",
431 "s_mov_b32 exec_lo, 0xaaaa5555",
432 "s_waitcnt_expcnt null, 0x0",
433 "s_waitcnt_lgkmcnt null, 0x0",
434 "s_waitcnt_vmcnt null, 0x0",
435 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)",
436 "s_waitcnt_vscnt null, 0x0",
437 "s_nop 0",
438 "v_nop",
439 "s_cselect_b32 s5, 0x10000001, 0x20000002",
440 "s_add_u32 s6, s4, s5",
441 "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo",
442 "v_add_nc_u32 v2, v2, s6",
443 "exp mrt0 v0, v1, v2, v3 done vm",
444 "s_endpgm",
445 ]
446 spv = translate_ps("ps_interleave", interleaved)
447 self.assertEqual(spv, baseline)
448 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want)
449
450 def test_inactive_exec_stays_zero_for_vgpr_writes_and_exports(self):
451 # Part 1: EXEC=0 around all handled no-ops blocks VGPR writes, then restoring EXEC exports intact values.
452 base_vgpr = [
453 "v_mov_b32 v0, 0x10000001",
454 "v_mov_b32 v1, 0x20000002",
455 "v_mov_b32 v2, 0x30000003",
456 "v_mov_b32 v3, 0x40000004",
457 "s_mov_b32 exec_lo, 0",
458 "v_add_nc_u32 v2, v2, 0x1234",
459 "v_mov_b32 v3, 0xdeadbeef",
460 "s_mov_b32 exec_lo, -1",
461 "exp mrt0 v0, v1, v2, v3 done vm",
462 "s_endpgm",
463 ]
464 with_noops = base_vgpr[:5] + REPRESENTATIVE_NOOPS + base_vgpr[5:]
465 spv_base = translate_ps("ps_exec0_vgpr_base", base_vgpr)
466 spv_noops = translate_ps("ps_exec0_vgpr_noops", with_noops)
467 self.assertEqual(spv_noops, spv_base)
468 self.assertEqual(tuple(si.run_fragment(spv_noops, inputs={"%sg_lane": 0})["%out_mrt0"]),
469 (0x10000001, 0x20000002, 0x30000003, 0x40000004))
470
471 # Part 2: EXEC=0 across all handled no-ops keeps the lane inactive through end of shader (OpKill -> {}).
472 base_exp = [
473 "v_mov_b32 v0, 0x10000001",
474 "v_mov_b32 v1, 0x20000002",
475 "v_mov_b32 v2, 0x30000003",
476 "v_mov_b32 v3, 0x40000004",
477 "exp mrt0 v0, v1, v2, v3 vm",
478 "s_mov_b32 exec_lo, 0xaaaa5554",
479 "v_mov_b32 v0, 0xbad00000",
480 "exp mrt0 v0, v0, v0, v0 done vm",
481 "s_endpgm",
482 ]
483 spv_exp_base = translate_ps("ps_exec0_exp_base", base_exp)
484 spv_exp_noops = translate_ps("ps_exec0_exp_noops", base_exp[:6] + REPRESENTATIVE_NOOPS + base_exp[6:])
485 self.assertEqual(spv_exp_noops, spv_exp_base)
486 self.assertEqual(si.run_fragment(spv_exp_noops, inputs={"%sg_lane": 0}), {})
487
488
489class ComputeShaderNoopWaitcntTests(unittest.TestCase):
490 """FSSM compute shader translation and multi-lane execution (wave32 & wave64)."""
491
492 def test_wave32_each_and_all_preserve_registers_vcc_scc_and_exec(self):
493 for scc_one in (True, False):
494 baseline = translate_cs("cs_w32_base", cs_program([], wave64=False, scc_one=scc_one), threads=32)
495 want = expected_cs_words(32, scc_one=scc_one)
496 self.assertEqual(run_cs(baseline, 32), want)
497 self.assertNotIn("OpControlBarrier", baseline)
498 self.assertNotIn("OpMemoryBarrier", baseline)
499
500 for variant in SCALAR_NOOP_VARIANTS:
501 with self.subTest(scc_one=scc_one, insn=variant):
502 spv = translate_cs("cs_w32_var", cs_program([variant], wave64=False, scc_one=scc_one), threads=32)
503 self.assertEqual(spv, baseline)
504 self.assertEqual(run_cs(spv, 32), want)
505
506 spv_all = translate_cs("cs_w32_all", cs_program(REPRESENTATIVE_NOOPS, wave64=False, scc_one=scc_one),
507 threads=32)
508 self.assertEqual(spv_all, baseline)
509 self.assertEqual(run_cs(spv_all, 32), want)
510
511 def test_wave64_preserves_state_across_all_64_lanes(self):
512 for scc_one in (True, False):
513 baseline = translate_cs("cs_w64_base", cs_program([], wave64=True, scc_one=scc_one), threads=64)
514 want = expected_cs_words(64, scc_one=scc_one)
515 self.assertEqual(run_cs(baseline, 64), want)
516 self.assertNotIn("OpControlBarrier", baseline)
517 self.assertNotIn("OpMemoryBarrier", baseline)
518
519 with self.subTest(scc_one=scc_one):
520 spv_all = translate_cs("cs_w64_all", cs_program(REPRESENTATIVE_NOOPS, wave64=True, scc_one=scc_one),
521 threads=64)
522 self.assertEqual(spv_all, baseline)
523 self.assertEqual(run_cs(spv_all, 64), want)
524
525
526class ModeInstructionsTests(unittest.TestCase):
527 """Tests for s_denorm_mode, s_round_mode, and s_setreg* hardware MODE writes."""
528
529 def test_s_denorm_mode_and_s_round_mode_stay_unsupported(self):
530 for insn in REFUSED_MODE_VARIANTS:
531 op = insn.split()[0]
532 with self.subTest(stage="ps", insn=insn):
533 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
534 translate_ps("ps_refused_mode", ps_program([insn]))
535 self.assertIn(op, str(ctx.exception))
536 self.assertIn("s_setreg", str(ctx.exception))
537
538 with self.subTest(stage="cs", insn=insn):
539 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
540 translate_cs("cs_refused_mode", cs_program([insn], wave64=False), threads=32)
541 self.assertIn(op, str(ctx.exception))
542 self.assertIn("s_setreg", str(ctx.exception))
543
544 def test_s_setreg_mode_fp_round_emits_only_mode_r16_and_preserves_state(self):
545 ps_base = translate_ps("ps_mode_base", ps_program([]))
546 want_ps = expected_ps_mrt0()
547 cs_base = translate_cs("cs_mode_base", cs_program([], wave64=False), threads=32)
548 want_cs = expected_cs_words(32)
549
550 for insn, mode_const in MODELLED_MODE_VARIANTS:
551 with self.subTest(stage="ps", insn=insn):
552 spv = translate_ps("ps_mode_setreg", ps_program([insn]))
553 self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv)
554 self.assertIn(f"OpStore %mode_r16 {mode_const}", spv)
555 self.assertNotIn("OpControlBarrier", spv)
556 # Removing the two mode lines recovers the exact baseline SPIR-V (modulo unused %c3 if added).
557 self.assertEqual(spv.count("OpStore %mode_r16"), 1)
558 self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps)
559 self.assertEqual(tuple(si.run_fragment(ps_base, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps)
560
561 with self.subTest(stage="cs", insn=insn):
562 spv = translate_cs("cs_mode_setreg", cs_program([insn], wave64=False), threads=32)
563 self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv)
564 self.assertIn(f"OpStore %mode_r16 {mode_const}", spv)
565 self.assertEqual(run_cs(spv, 32), want_cs)
566 self.assertEqual(run_cs(cs_base, 32), want_cs)
567
568 def test_unmodelled_s_setreg_mode_forms_raise_unsupported(self):
569 bad_mode_writes = [
570 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3",
571 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15",
572 "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0",
573 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1",
574 "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 2",
575 "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s2",
576 ]
577 for insn in bad_mode_writes:
578 with self.subTest(insn=insn):
579 with self.assertRaises(rdna2spirv.Unsupported):
580 translate_ps("ps_bad_mode", ps_program([insn]))
581
582
583class NegativeControlTests(unittest.TestCase):
584 """Negative controls: sabotaging arithmetic or using unknown mnemonics must be detected."""
585
586 def test_sabotaging_arithmetic_around_noop_waitcnt_changes_output(self):
587 good_spv = translate_ps("ps_neg_good", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"]))
588 good_out = si.run_fragment(good_spv, inputs={"%sg_lane": 0})
589 self.assertEqual(tuple(good_out["%out_mrt0"]), expected_ps_mrt0(scc_one=True, vcc_one=True))
590
591 # Assembly-level sabotage around the waitcnt/clause instructions:
592 sabotaged_cases = [
593 ("SCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], scc_one=False)),
594 ("VCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], vcc_one=False)),
595 ("v_add_nc_u32 addend changed", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], add_k=0x20)),
596 ("EXEC bit 0 cleared", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], exec_lo=0xAAAA5554)),
597 ]
598 for label, bad_lines in sabotaged_cases:
599 with self.subTest(sabotage=label):
600 bad_spv = translate_ps("ps_neg_bad", bad_lines)
601 bad_out = si.run_fragment(bad_spv, inputs={"%sg_lane": 0})
602 self.assertNotEqual(bad_out, good_out)
603
604 # SPIR-V-level sabotage on the translated output around the no-op/waitcnt block:
605 for old, new, label in (
606 ("OpIAdd %uint", "OpISub %uint", "v_add_nc_u32/s_add_u32 turned into OpISub"),
607 ("OpIEqual %bool", "OpINotEqual %bool", "v_cmp_eq_u32 inverted"),
608 ):
609 with self.subTest(spirv_sabotage=label):
610 self.assertIn(old, good_spv)
611 mutated = good_spv.replace(old, new)
612 self.assertNotEqual(si.run_fragment(mutated, inputs={"%sg_lane": 0}), good_out)
613
614 # CS multi-lane negative control:
615 cs_good = translate_cs("cs_neg_good", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], wave64=False),
616 threads=32)
617 cs_good_words = run_cs(cs_good, 32)
618 cs_bad = translate_cs("cs_neg_bad", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"],
619 wave64=False, scc_one=False), threads=32)
620 self.assertNotEqual(run_cs(cs_bad, 32), cs_good_words)
621
622 def test_unknown_waitcnt_and_noop_mnemonics_fail_with_unsupported(self):
623 for bogus in ("s_bogus_waitcnt 0x0", "s_bogus_waitcnt", "s_bogus_noop 0"):
624 with self.subTest(stage="ps", insn=bogus):
625 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
626 translate_ps("ps_bogus", ps_program([bogus]))
627 self.assertIn(bogus.split()[0], str(ctx.exception))
628
629 with self.subTest(stage="cs", insn=bogus):
630 with self.assertRaises(rdna2spirv.Unsupported) as ctx:
631 translate_cs("cs_bogus", cs_program([bogus], wave64=False), threads=32)
632 self.assertIn(bogus.split()[0], str(ctx.exception))
633
634
635if __name__ == "__main__":
636 unittest.main()
diff --git a/tests/semantic/test_tbuffer_store.py b/tests/semantic/test_tbuffer_store.py
new file mode 100644
index 000000000..890c68d5d
--- /dev/null
+++ b/tests/semantic/test_tbuffer_store.py
@@ -0,0 +1,86 @@
1"""tbuffer_store_format_* (MTBUF stores with the instruction's own format) through the translator and the interpreter.
2
3cs_tbuffer_store.asm stores into 13 sentinel-filled regions through V#s whose FORMAT differs from the instruction's,
4then reads every region back into out[0..51]. check.py's TBUFFER_STORE_WORDS holds the words a Radeon 680M (gfx1035)
5gives natively; the rules are in the .asm header. Here the translated fixture runs on the CPU and must give the same
6words, so the GPU test, the hardware and the translation are kept in step.
7"""
8import os
9import struct
10import sys
11import unittest
12
13HERE = os.path.dirname(os.path.abspath(__file__))
14ROOT = os.path.dirname(os.path.dirname(HERE))
15sys.path.insert(0, HERE)
16sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders"))
17sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
18
19import check # noqa: E402 (runtime/test/shaders/check.py; importing it runs nothing)
20import rdna2spirv # noqa: E402
21import support # noqa: E402
22
23
24def fssm(rsrc2, group):
25 """The compute-shader header words the translator reads: COMPUTE_PGM_RSRC2 and the thread-group size."""
26 header = bytearray(0x148)
27 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
28 return bytes(header)
29
30
31# 4 user SGPRs (the output V#), workgroup id in s4, 64x1x1 threads: the header build.py gives the GPU tests.
32CS_FSSM = fssm(0x8088, (64, 1, 1))
33# The output V# vk_compute_test passes in s[0:3]: base 0, num_records 0xffffffff, 32_FLOAT, OOB_SELECT 3.
34OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
35
36
37def run(spv):
38 memory = {}
39 outputs = support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)},
40 push_constants=OUT_VSHARP + [0] * 28, memory=memory)
41 return outputs, memory
42
43
44class TbufferStoreFixture(unittest.TestCase):
45 def test_words_match_the_native_measurement(self):
46 outputs, memory = run(support.translate_fixture("cs_tbuffer_store", fssm=CS_FSSM))
47 self.assertEqual(outputs, {})
48 want = check.TBUFFER_STORE_WORDS
49 got = [memory.get(4 * i, 0) for i in range(len(want))]
50 for i, (g, w) in enumerate(zip(got, want)):
51 with self.subTest(out=i, region=hex(0x200 + 16 * (i // 4))):
52 self.assertEqual(f"{g:#010x}", f"{w:#010x}")
53 # The regions themselves hold the same words, and nothing lands between out[] and the regions.
54 self.assertEqual([memory.get(0x200 + 4 * i, 0) for i in range(len(want))], want)
55 self.assertEqual(sorted(a for a in memory if len(want) * 4 <= a < 0x200), [])
56
57
58class TbufferStoreTranslation(unittest.TestCase):
59 def store(self, fmt_mod):
60 return support.translate_lines("cs_tbuf_one", [
61 "v_mov_b32_e32 v20, 1.0", "v_mov_b32_e32 v5, 0x200",
62 f"tbuffer_store_format_x v20, v5, s[0:3], 0{fmt_mod} offen", "s_endpgm"], fssm=CS_FSSM)
63
64 def test_format_outside_formats_is_unsupported(self):
65 # BUF_FMT_8_USCALED is a GFX10 format the FORMATS table has no encoder for: reported, never guessed.
66 # (BUF_FMT_8_UINT was the example until #1871 added the measured 8/16-bit UINT/SINT formats.)
67 with self.assertRaises(rdna2spirv.Unsupported):
68 self.store(" format:[BUF_FMT_8_USCALED]")
69
70 def test_default_format_is_one_unorm_byte(self):
71 # No modifier is GFX10's default, BUF_FMT_8_UNORM: 1.0 is 0xff in the low byte, the other three kept.
72 spv = self.store("")
73 memory = {0x200: 0x11223344}
74 support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)},
75 push_constants=OUT_VSHARP + [0] * 28, memory=memory)
76 self.assertEqual(f"{memory[0x200]:#010x}", "0x112233ff")
77
78 def test_data_vgprs_are_read(self):
79 # read_before_write_vgprs: a store's vdata is a source, as for buffer_store.
80 import shader_ir
81 ins = shader_ir.parse_line("\ttbuffer_store_format_xy v[7:8], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen")
82 self.assertEqual(sorted(rdna2spirv.read_before_write_vgprs([ins])), [5, 7, 8])
83
84
85if __name__ == "__main__":
86 unittest.main()
diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py
index 1d0730fe3..6c2a39cc6 100644
--- a/tests/semantic/test_valu_fma_mix.py
+++ b/tests/semantic/test_valu_fma_mix.py
@@ -212,6 +212,25 @@ class FmaMixF16Tests(unittest.TestCase):
212 got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) 212 got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old)
213 self.assertEqual(got, pack_h(1.5, 3.5)) 213 self.assertEqual(got, pack_h(1.5, 3.5))
214 214
215 def test_single_rounding_discriminating_cases(self):
216 # Discriminating test cases A through G from tools/fma_mix_probe.py where
217 # hardware single rounding gives 1 ulp difference from double rounding.
218 # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00
219 got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD)
220 self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01)
221
222 # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02
223 got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD)
224 self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF))
225
226 # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00
227 got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD)
228 self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01)
229
230 # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02
231 got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD)
232 self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01)
233
215 234
216class NegativeControls(unittest.TestCase): 235class NegativeControls(unittest.TestCase):
217 """Sabotaging the translated SPIR-V must change the observed output.""" 236 """Sabotaging the translated SPIR-V must change the observed output."""
@@ -226,5 +245,52 @@ class NegativeControls(unittest.TestCase):
226 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) 245 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good)
227 246
228 247
248class FmaMixF32DenormalOperandTests(unittest.TestCase):
249 """SHADER-298: an f32 operand of v_fma_mix* that is denormal reads as a zero of its sign (the game's MODE has
250 denorm_mode_32 = 0), measured on gfx1036 by @Sanonymous01 for 0x00000001, 0x807fffff and the integer inline
251 constants 1 and 64. The result is not flushed here (not measured), so 0 * y + denormal keeps the denormal only
252 when the denormal is not an operand, which cannot happen; the checks below use operands only."""
253
254 BIG = f2u(1.0e30)
255 ZERO = 0x00000000
256 NEG_ZERO = 0x80000000
257
258 def test_denormal_multiplicand_reads_as_zero(self):
259 # 1.4e-45 * 1e30 = 1.4e-15 if the denormal is kept; 0 if it is flushed.
260 for d in (0x00000001, 0x007FFFFF):
261 with self.subTest(denormal=hex(d), slot="src0"):
262 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.ZERO), 0x00000000)
263 with self.subTest(denormal=hex(d), slot="src1"):
264 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.BIG, d, self.ZERO), 0x00000000)
265
266 def test_negative_denormal_reads_as_negative_zero(self):
267 # (-0) * 1e30 + (-0) = -0; a kept denormal would give -1.1e-8-ish tiny non-zero.
268 for d in (0x80000001, 0x807FFFFF):
269 with self.subTest(denormal=hex(d)):
270 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.NEG_ZERO), 0x80000000)
271
272 def test_denormal_addend_reads_as_zero(self):
273 # 0 * y + denormal: the denormal addend is flushed, so the result is +0 (kept it would be the denormal).
274 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.ZERO, self.BIG, 0x00000001), 0x00000000)
275
276 def test_integer_inline_constants_are_denormal_f32_operands(self):
277 # `1` and `64` in an f32 operand slot are the words 0x00000001 and 0x00000040: denormal, flushed to +0.
278 for const in ("1", "64"):
279 with self.subTest(const=const):
280 self.assertEqual(run(f"v_fma_mix_f32 v0, {const}, v2, v3", self.ZERO, self.BIG, self.ZERO), 0x00000000)
281
282 def test_normal_operands_are_untouched(self):
283 a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75)
284 self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c), f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0))))
285 smallest_normal = 0x00800000 # 2**-126 is the first value that is not flushed
286 got = run("v_fma_mix_f32 v0, v1, v2, v3", smallest_normal, f2u(1.0), self.ZERO)
287 self.assertEqual(got, smallest_normal)
288
289 def test_the_flush_reaches_the_f16_result(self):
290 # 1.4e-45 * 3e37 = 4.2e-8 rounds to the f16 subnormal 0x0001 if the denormal is kept, and is 0 flushed.
291 got = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x00000001, f2u(3.0e37), self.ZERO, old=0xAAAA0000)
292 self.assertEqual(got, 0xAAAA0000)
293
294
229if __name__ == "__main__": 295if __name__ == "__main__":
230 unittest.main() 296 unittest.main()
diff --git a/tests/semantic/test_valu_fract_f16.py b/tests/semantic/test_valu_fract_f16.py
new file mode 100644
index 000000000..aabad97c6
--- /dev/null
+++ b/tests/semantic/test_valu_fract_f16.py
@@ -0,0 +1,703 @@
1"""End-to-end semantic value tests for RDNA2 v_fract_f16 (S0.f16 - floor(S0.f16)).
2
3Covers v_fract_f16 executed end-to-end through tools/rdna2spirv.py and
4tests/semantic/spirv_mini_interp.py against an independent Fraction-based
5IEEE-754 binary16 `x - floor(x)` oracle:
6 - Positive & negative finite non-integers, including tiny negatives and
7 negative subnormals (-0.0001, -1e-5, -2**-12, -2**-24) whose exact
8 x - floor(x) rounds to 1.0 in binary16 and maps to 0x3bff (the largest
9 binary16 strictly below 1.0), plus the adjacent 0x3bfe / 0x3bff edge.
10 - Exact integers (0.0, 1.0, -1.0, 65504.0, -65504.0 -> +0.0) and -0.0 -> +0.0.
11 - +-inf and qNaN/sNaN behavior (GLSL.std.450 Fract returns NaN; fract_below_one
12 uses OpFOrdEqual + OpSelect so NaN survives into f16_bits -> qNaN).
13 - _e32, _e64, and bare mnemonics, keeping the untouched 16-bit half of dst.
14 - Runtime memory inputs via s_buffer_load_dwordx4 alongside immediate inputs.
15 - All 4 op_sel:[src,dst] combinations ([0,0], [1,0], [0,1], [1,1]).
16 - VOP3 source modifiers (-v1, |v1|, -|v1|) and output modifiers
17 (clamp, mul:2, mul:4, div:2, mul:2 clamp, mul:4 clamp).
18 - Inline f16 constants (0.5, -0.5, 1.0, -1.0), SGPR sources, destination
19 aliasing (v0, v0), single-lane and multi-lane EXEC masking, and SPIR-V
20 sabotage negative controls (Fract -> Trunc / Floor).
21
22Note: Under VOP3 `clamp`, GLSL.std.450 FClamp on NaN is undefined in SPIR-V
23and spirv_mini_interp.py raises UnsupportedConstruct (documented in
24docs/design.md), so `clamp` value tests use finite inputs. Standard library
25only; hand-written RDNA2 disassembly listings only; zero game data.
26"""
27from fractions import Fraction
28import gc
29import itertools
30import math
31import os
32import re
33import struct
34import sys
35import tempfile
36import unittest
37import warnings
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40ROOT = os.path.dirname(os.path.dirname(HERE))
41TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
42
43sys.dont_write_bytecode = True
44if TOOLS_DIR not in sys.path:
45 sys.path.insert(0, TOOLS_DIR)
46if HERE not in sys.path:
47 sys.path.insert(0, HERE)
48
49import rdna2spirv # noqa: E402
50import spirv_mini_interp as si # noqa: E402
51
52STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
53OLD = 0xBEEF1234
54PUSH_ADDR = [0x1000, 0, 32, 0] + [0] * 28
55VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC]
56HEAP_FILL = 0xEEEEEEEE
57
58# Representative binary16 encodings (cross-checked in OracleTests).
59H_POS_ZERO = 0x0000 # +0.0
60H_NEG_ZERO = 0x8000 # -0.0
61H_SUB_MIN = 0x0001 # +2^-24 (~5.96e-8)
62H_NEG_SUB_MIN = 0x8001 # -2^-24
63H_SUB_1E5 = 0x00A8 # +1e-5 rounded to f16 subnormal (~1.001e-5)
64H_NEG_SUB_1E5 = 0x80A8 # -1e-5 rounded to f16 subnormal (~-1.001e-5)
65H_SUB_MAX = 0x03FF # +1023 * 2^-24 (largest +subnormal)
66H_NEG_SUB_MAX = 0x83FF # -1023 * 2^-24 (largest-magnitude -subnormal)
67H_NORM_MIN = 0x0400 # +2^-14 (smallest +normal)
68H_NEG_NORM_MIN = 0x8400 # -2^-14
69H_1E4 = 0x068E # +0.0001 rounded to f16 (~1.000166e-4)
70H_NEG_1E4 = 0x868E # -0.0001 rounded to f16 (~-1.000166e-4)
71H_2PM13 = 0x0800 # +2^-13
72H_NEG_2PM13 = 0x8800 # -2^-13
73H_NEG_2PM12_M = 0x8BFF # -(2^-12 - 2^-23): just above -2^-12
74H_NEG_2PM12 = 0x8C00 # -2^-12: exact tie between 0x3bff and 0x3c00
75H_NEG_2PM12_P = 0x8C01 # -(2^-12 + 2^-22): strictly closer to 0x3bff
76H_NEG_3P2M13 = 0x8E00 # -3 * 2^-13: strictly closer to 0x3bff
77H_NEG_2PM11 = 0x9000 # -2^-11: 1 - 2^-11 = 0x3bff exact
78H_NEG_3P2M12 = 0x9200 # -3 * 2^-12: exact tie between 0x3bfe (even) and 0x3bff (odd) -> 0x3bfe
79H_NEG_2PM10 = 0x9400 # -2^-10: 1 - 2^-10 = 0x3bfe exact
80H_0P125 = 0x3000 # 0.125
81H_0P25 = 0x3400 # 0.25
82H_NEG_0P25 = 0xB400 # -0.25
83H_0P375 = 0x3600 # 0.375
84H_0P5 = 0x3800 # 0.5
85H_NEG_0P5 = 0xB800 # -0.5
86H_0P75 = 0x3A00 # 0.75
87H_NEG_0P75 = 0xBA00 # -0.75
88H_NEAR_ONE = 0x3BFF # 1 - 2^-11 (largest f16 < 1.0)
89H_1P0 = 0x3C00 # 1.0
90H_NEG_1P0 = 0xBC00 # -1.0
91H_1P25 = 0x3D00 # 1.25
92H_NEG_1P25 = 0xBD00 # -1.25
93H_1P5 = 0x3E00 # 1.5
94H_NEG_1P5 = 0xBE00 # -1.5
95H_1P75 = 0x3F00 # 1.75
96H_NEG_1P75 = 0xBF00 # -1.75
97H_2P0 = 0x4000 # 2.0
98H_NEG_2P0 = 0xC000 # -2.0
99H_2P5 = 0x4100 # 2.5
100H_NEG_2P5 = 0xC100 # -2.5
101H_3P0 = 0x4200 # 3.0
102H_NEG_3P0 = 0xC200 # -3.0
103H_3P75 = 0x4380 # 3.75
104H_NEG_3P75 = 0xC380 # -3.75
105H_1023P5 = 0x63FF # 1023.5
106H_NEG_1023P5 = 0xE3FF # -1023.5
107H_1024 = 0x6400 # 1024.0
108H_NEG_1024 = 0xE400 # -1024.0
109H_MAX = 0x7BFF # 65504.0
110H_NEG_MAX = 0xFBFF # -65504.0
111H_POS_INF = 0x7C00 # +inf
112H_NEG_INF = 0xFC00 # -inf
113H_QNAN = 0x7E01 # +qNaN
114H_NEG_QNAN = 0xFE01 # -qNaN
115H_SNAN = 0x7C01 # +sNaN
116H_NEG_SNAN = 0xFC01 # -sNaN
117
118
119# -----------------------------------------------------------------------------
120# Independent Fraction-Based IEEE-754 Binary16 Oracle
121# -----------------------------------------------------------------------------
122
123def h16_is_finite(h: int) -> bool:
124 return ((h >> 10) & 0x1F) != 0x1F
125
126
127def h16_is_nan(h: int) -> bool:
128 return (h & 0x7FFF) > 0x7C00
129
130
131def h16_is_inf(h: int) -> bool:
132 return (h & 0x7FFF) == 0x7C00
133
134
135def h16_to_fraction(h: int) -> Fraction:
136 """Decode finite IEEE-754 binary16 bit pattern ``h`` into an exact Fraction."""
137 h &= 0xFFFF
138 exp = (h >> 10) & 0x1F
139 if exp == 0x1F:
140 raise ValueError(f"non-finite binary16 {h:#06x}")
141 sign = -1 if (h >> 15) else 1
142 mant = h & 0x3FF
143 if exp == 0:
144 return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 24)
145 return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25))
146
147
148def fraction_to_h16(q: Fraction) -> int:
149 """Round an exact Fraction to IEEE-754 binary16 (nearest, ties to even)."""
150 if q == 0:
151 return H_POS_ZERO
152 sgn = 0x8000 if q < 0 else 0
153 a = abs(q)
154 e = max(a.numerator.bit_length() - a.denominator.bit_length(), -14)
155 if e > -14 and Fraction(2) ** e > a:
156 e -= 1
157 m = a / (Fraction(2) ** (e - 10))
158 n = m.numerator // m.denominator
159 rem = m - n
160 if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)):
161 n += 1
162 if e == -14 and n < 1024:
163 return sgn | n
164 if n >= 2048:
165 n >>= 1
166 e += 1
167 if e > 15:
168 return sgn | H_POS_INF
169 return sgn | ((e + 15) << 10) | (n - 1024)
170
171
172def exact_fract_fraction(h: int) -> Fraction | None:
173 """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN."""
174 if not h16_is_finite(h):
175 return None
176 q = h16_to_fraction(h)
177 return q - math.floor(q)
178
179
180def oracle_fract_f16(
181 h: int,
182 *,
183 abs_: bool = False,
184 neg: bool = False,
185 mul: int = 1,
186 div: int = 1,
187 clamp: bool = False,
188) -> int | None:
189 """Independent binary16 reference for v_fract_f16, returning 16-bit int or None for NaN.
190
191 Models RDNA2 source modifiers (abs before neg), exact ``x - floor(x)``,
192 the hardware/translator 0x3c00 -> 0x3bff clamp when no output multiplier is
193 present, and VOP3 output scaling (mul/div) + [0, 1] clamp before narrowing.
194 """
195 h &= 0xFFFF
196 if abs_:
197 h &= 0x7FFF
198 if neg:
199 h ^= 0x8000
200 r = exact_fract_fraction(h)
201 if r is None:
202 return None
203 if mul == 1 and div == 1:
204 res = fraction_to_h16(r)
205 return H_NEAR_ONE if res == H_1P0 else res
206 scaled = r * Fraction(mul, div)
207 if clamp:
208 scaled = min(max(scaled, Fraction(0)), Fraction(1))
209 return fraction_to_h16(scaled)
210
211
212def merge_half(old: int, half: int, dst_hi: int) -> int:
213 h = half & 0xFFFF
214 return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h)
215
216
217# -----------------------------------------------------------------------------
218# Translation & Execution Helpers
219# -----------------------------------------------------------------------------
220
221_TMP_DIR = None
222_PS_PATH = None
223_CS_PATH = None
224_CS_FSSM = None
225
226
227def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes:
228 header = bytearray(0x148)
229 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
230 return bytes(header)
231
232
233def setUpModule():
234 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
235 _TMP_DIR = tempfile.TemporaryDirectory()
236 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
237 fssm_dir = os.path.join(_TMP_DIR.name, "fssm")
238 os.mkdir(disasm_dir)
239 os.mkdir(fssm_dir)
240 _PS_PATH = os.path.join(disasm_dir, "ps_fract_f16.s")
241 _CS_PATH = os.path.join(disasm_dir, "cs_fract_f16.s")
242 _CS_FSSM = os.path.join(fssm_dir, "cs_fract_f16.fssm")
243 with open(os.path.join(_TMP_DIR.name, "ps_fract_f16.dxbc"), "wb") as f:
244 f.write(STUB_DXBC)
245
246
247def tearDownModule():
248 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
249 if _TMP_DIR is not None:
250 gc.collect()
251 _TMP_DIR.cleanup()
252 _TMP_DIR = None
253 _PS_PATH = None
254 _CS_PATH = None
255 _CS_FSSM = None
256
257
258def translate_ps(lines: list[str]) -> str:
259 if _TMP_DIR is None:
260 setUpModule()
261 asm = (
262 "; test_valu_fract_f16\n"
263 + "".join(f"\t{ln}\n" for ln in lines)
264 + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n"
265 )
266 with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f:
267 f.write(asm)
268 with warnings.catch_warnings():
269 warnings.simplefilter("ignore", ResourceWarning)
270 spv = rdna2spirv.translate(_PS_PATH)
271 gc.collect()
272 return spv
273
274
275def run_ps(lines: list[str], *, push_constants=None, memory=None) -> int:
276 out = si.run_fragment(translate_ps(lines), push_constants=push_constants, memory=memory)
277 return out["%out_mrt0"][0]
278
279
280def run_op(line: str, v1: int = 0, *, old: int = OLD, s4: int = 0) -> int:
281 return run_ps([
282 f"s_mov_b32 s4, {s4:#x}",
283 f"v_mov_b32 v1, {v1:#x}",
284 f"v_mov_b32 v0, {old:#x}",
285 line,
286 ])
287
288
289def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None:
290 if _TMP_DIR is None:
291 setUpModule()
292 # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x).
293 with open(_CS_FSSM, "wb") as f:
294 f.write(_make_fssm(0x0088, (group_size, 1, 1)))
295 asm = "; test_cs_valu_fract_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
296 with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f:
297 f.write(asm)
298 with warnings.catch_warnings():
299 warnings.simplefilter("ignore", ResourceWarning)
300 spv = rdna2spirv.translate(_CS_PATH)
301 gc.collect()
302 si.run_workgroup(
303 spv,
304 group_size,
305 32,
306 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)},
307 push_constants=VSHARP_CS + [0] * 28,
308 memory=memory,
309 )
310
311
312class _Heap(dict):
313 def get(self, key, default=None):
314 return super().get(key, HEAP_FILL)
315
316
317# -----------------------------------------------------------------------------
318# Oracle Self-Tests
319# -----------------------------------------------------------------------------
320
321class OracleTests(unittest.TestCase):
322 """Cross-checks the independent Fraction binary16 oracle against IEEE-754 encodings."""
323
324 def test_exhaustive_binary16_decode_and_roundtrip(self):
325 for h in range(0x10000):
326 if not h16_is_finite(h):
327 self.assertIsNone(exact_fract_fraction(h))
328 self.assertIsNone(oracle_fract_f16(h))
329 continue
330 q = h16_to_fraction(h)
331 expected_float = struct.unpack("<e", struct.pack("<H", h))[0]
332 self.assertEqual(q, Fraction(expected_float))
333 want = H_POS_ZERO if h == H_NEG_ZERO else h
334 self.assertEqual(fraction_to_h16(q), want)
335
336 def test_hand_worked_fract_f16_rows(self):
337 rows = [
338 (H_POS_ZERO, H_POS_ZERO),
339 (H_NEG_ZERO, H_POS_ZERO),
340 (H_0P25, H_0P25),
341 (H_1P25, H_0P25),
342 (H_3P75, H_0P75),
343 (H_NEG_0P25, H_0P75),
344 (H_NEG_1P25, H_0P75),
345 (H_NEG_0P5, H_0P5),
346 (H_NEG_0P75, H_0P25),
347 (H_1P0, H_POS_ZERO),
348 (H_NEG_1P0, H_POS_ZERO),
349 (H_MAX, H_POS_ZERO),
350 (H_NEG_MAX, H_POS_ZERO),
351 (H_NEG_2PM10, 0x3BFE),
352 (H_NEG_3P2M12, 0x3BFE),
353 (H_NEG_2PM11, H_NEAR_ONE),
354 (H_NEG_3P2M13, H_NEAR_ONE),
355 (H_NEG_2PM12_P, H_NEAR_ONE),
356 (H_NEG_2PM12, H_NEAR_ONE),
357 (H_NEG_2PM12_M, H_NEAR_ONE),
358 (H_NEG_2PM13, H_NEAR_ONE),
359 (H_NEG_1E4, H_NEAR_ONE),
360 (H_NEG_SUB_1E5, H_NEAR_ONE),
361 (H_NEG_SUB_MAX, H_NEAR_ONE),
362 (H_NEG_SUB_MIN, H_NEAR_ONE),
363 (H_SUB_MIN, H_SUB_MIN),
364 (H_SUB_1E5, H_SUB_1E5),
365 (H_1E4, H_1E4),
366 ]
367 for h, want in rows:
368 with self.subTest(h=hex(h)):
369 self.assertEqual(oracle_fract_f16(h), want)
370 # Verify decimal conversions match our binary16 constants.
371 self.assertEqual(struct.unpack("<H", struct.pack("<e", -0.0001))[0], H_NEG_1E4)
372 self.assertEqual(struct.unpack("<H", struct.pack("<e", -1e-5))[0], H_NEG_SUB_1E5)
373 self.assertEqual(struct.unpack("<H", struct.pack("<e", 3.75))[0], H_3P75)
374
375
376# -----------------------------------------------------------------------------
377# End-to-End Execution Tests
378# -----------------------------------------------------------------------------
379
380class FractF16ExecutionTests(unittest.TestCase):
381 def test_finite_values_across_e32_e64_and_bare(self):
382 samples = [
383 H_POS_ZERO, H_NEG_ZERO,
384 H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_1E5, H_NEG_SUB_1E5,
385 H_SUB_MAX, H_NEG_SUB_MAX, H_NORM_MIN, H_NEG_NORM_MIN,
386 H_1E4, H_NEG_1E4, H_2PM13, H_NEG_2PM13,
387 H_NEG_2PM12_M, H_NEG_2PM12, H_NEG_2PM12_P, H_NEG_3P2M13,
388 H_NEG_2PM11, H_NEG_3P2M12, H_NEG_2PM10,
389 H_0P125, H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75,
390 H_NEAR_ONE,
391 H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75,
392 H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, H_3P75, H_NEG_3P75,
393 H_1023P5, H_NEG_1023P5, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX,
394 ]
395 for suffix in ("_e32", "_e64", ""):
396 for h in samples:
397 v1 = 0x55550000 | h
398 want = merge_half(OLD, oracle_fract_f16(h), 0)
399 with self.subTest(form="v_fract_f16" + suffix, h=hex(h)):
400 self.assertEqual(run_op(f"v_fract_f16{suffix} v0, v1", v1), want)
401
402 def test_tiny_negatives_and_subnormals_near_one_boundary(self):
403 # Crosses the exact binary16 rounding transition: -2^-10 and -3*2^-12 give 0x3bfe;
404 # -2^-11 .. -2^-24 (including -0.0001 and -1e-5) give 0x3bff (never 0x3c00 = 1.0).
405 cases = [
406 (H_NEG_2PM10, 0x3BFE),
407 (H_NEG_3P2M12, 0x3BFE),
408 (H_NEG_2PM11, H_NEAR_ONE),
409 (H_NEG_3P2M13, H_NEAR_ONE),
410 (H_NEG_2PM12_P, H_NEAR_ONE),
411 (H_NEG_2PM12, H_NEAR_ONE),
412 (H_NEG_2PM12_M, H_NEAR_ONE),
413 (H_NEG_2PM13, H_NEAR_ONE),
414 (H_NEG_1E4, H_NEAR_ONE),
415 (H_NEG_SUB_1E5, H_NEAR_ONE),
416 (H_NEG_SUB_MAX, H_NEAR_ONE),
417 (H_NEG_SUB_MIN, H_NEAR_ONE),
418 ]
419 for h, want in cases:
420 with self.subTest(h=hex(h)):
421 self.assertEqual(oracle_fract_f16(h), want)
422 self.assertEqual(run_op("v_fract_f16_e32 v0, v1", 0xCAFE0000 | h), merge_half(OLD, want, 0))
423 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 op_sel:[0,1]", 0xCAFE0000 | h),
424 merge_half(OLD, want, 1))
425
426 def test_exact_integers_and_signed_zero_give_positive_zero(self):
427 # GLSL.std.450 Fract(-0.0) in spirv_mini_interp returns +0.0 (copysign == +1), matching hardware.
428 self.assertEqual(si._fract(-0.0), 0.0)
429 self.assertEqual(math.copysign(1.0, si._fract(-0.0)), 1.0)
430 for h in (H_POS_ZERO, H_NEG_ZERO, H_1P0, H_NEG_1P0, H_2P0, H_NEG_2P0,
431 H_3P0, H_NEG_3P0, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX):
432 with self.subTest(h=hex(h)):
433 got = run_op("v_fract_f16_e32 v0, v1", 0xABCD0000 | h)
434 self.assertEqual(got, merge_half(OLD, H_POS_ZERO, 0))
435 self.assertNotEqual(got & 0xFFFF, H_NEG_ZERO)
436 got_hi = run_op("v_fract_f16_e64 v0, v1 op_sel:[1,1]", (h << 16) | 0x1111)
437 self.assertEqual(got_hi, merge_half(OLD, H_POS_ZERO, 1))
438
439 def test_runtime_memory_inputs_via_s_buffer_load(self):
440 # Loaded at runtime through s_buffer_load_dwordx4 so constant folding cannot bypass Fract.
441 lanes_lo = [H_NEG_1E4, H_NEG_SUB_1E5, H_NEG_ZERO, H_3P75]
442 lanes_hi = [H_NEG_MAX, H_NEG_0P25, H_1P25, H_POS_INF]
443 packed = [(hi << 16) | lo for lo, hi in zip(lanes_lo, lanes_hi)]
444 mem = {0x1000 + 4 * i: w for i, w in enumerate(packed)}
445 for idx, (lo, hi) in enumerate(zip(lanes_lo, lanes_hi)):
446 reg = f"v{idx + 1}"
447 lines_head = [
448 "s_buffer_load_dwordx4 s[4:7], s[0:3], 0",
449 "s_waitcnt lgkmcnt(0)",
450 "v_mov_b32_e32 v1, s4",
451 "v_mov_b32_e32 v2, s5",
452 "v_mov_b32_e32 v3, s6",
453 "v_mov_b32_e32 v4, s7",
454 f"v_mov_b32_e32 v0, {OLD:#x}",
455 ]
456 got_lo = run_ps(lines_head + [f"v_fract_f16_e32 v0, {reg}"], push_constants=PUSH_ADDR, memory=mem)
457 self.assertEqual(got_lo, merge_half(OLD, oracle_fract_f16(lo), 0))
458 got_hi = run_ps(lines_head + [f"v_fract_f16_e64 v0, {reg} op_sel:[1,1]"],
459 push_constants=PUSH_ADDR, memory=mem)
460 want_hi = oracle_fract_f16(hi)
461 if want_hi is None:
462 self.assertEqual(got_hi & 0xFFFF, OLD & 0xFFFF)
463 self.assertTrue(h16_is_nan(got_hi >> 16), hex(got_hi))
464 else:
465 self.assertEqual(got_hi, merge_half(OLD, want_hi, 1))
466
467 def test_inf_and_nan_produce_nan_and_preserve_untouched_half(self):
468 # Verify spirv_mini_interp Fract on +-inf/NaN and translator's OpFOrdEqual guard.
469 self.assertTrue(math.isnan(si._fract(float("inf"))))
470 self.assertTrue(math.isnan(si._fract(float("-inf"))))
471 self.assertTrue(math.isnan(si._fract(float("nan"))))
472
473 for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_NEG_QNAN, H_SNAN, H_NEG_SNAN):
474 for suffix in ("_e32", "_e64", ""):
475 with self.subTest(h=hex(h), form=suffix or "bare"):
476 got = run_op(f"v_fract_f16{suffix} v0, v1", 0xCAFE0000 | h)
477 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
478 self.assertTrue(h16_is_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}")
479 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
480 v1 = ((h << 16) | H_0P25) if src_hi else ((H_0P25 << 16) | h)
481 with self.subTest(h=hex(h), src_hi=src_hi, dst_hi=dst_hi):
482 got = run_op(f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]", v1)
483 if dst_hi:
484 self.assertEqual(got & 0xFFFF, OLD & 0xFFFF)
485 self.assertTrue(h16_is_nan(got >> 16), hex(got))
486 else:
487 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
488 self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got))
489
490 def test_op_sel_all_four_combinations(self):
491 pairs = [
492 (H_NEG_1P25, H_0P25), # hi: 0.75, lo: 0.25
493 (H_NEG_SUB_1E5, H_3P75), # hi: 0x3bff, lo: 0.75
494 ]
495 for hi, lo in pairs:
496 v1 = (hi << 16) | lo
497 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
498 h_in = hi if src_hi else lo
499 line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]"
500 with self.subTest(line=line, v1=hex(v1)):
501 self.assertEqual(run_op(line, v1), merge_half(OLD, oracle_fract_f16(h_in), dst_hi))
502
503 def test_vop3_source_modifiers(self):
504 cases = [
505 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_NEG_1P25 << 16) | H_0P25, H_0P25, False, True, 0),
506 ("v_fract_f16_e64 v0, -v1 op_sel:[1,1]", (H_NEG_0P25 << 16) | H_1P25, H_NEG_0P25, False, True, 1),
507 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_0P25 << 16) | H_2PM13, H_2PM13, False, True, 0),
508 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_POS_ZERO, H_POS_ZERO, False, True, 0),
509 ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_1P0, H_1P0, False, True, 0),
510 ("v_fract_f16_e64 v0, |v1| op_sel:[1,1]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, False, 1),
511 ("v_fract_f16_e64 v0, |v1| op_sel:[1,0]", (H_NEG_2PM13 << 16) | H_0P5, H_NEG_2PM13, True, False, 0),
512 ("v_fract_f16_e64 v0, -|v1| op_sel:[1,0]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, True, 0),
513 ("v_fract_f16_e64 v0, -|v1| op_sel:[0,1]", (H_0P5 << 16) | H_3P75, H_3P75, True, True, 1),
514 ("v_fract_f16_e64 v0, -|v1| op_sel:[0,0]", H_2PM13, H_2PM13, True, True, 0),
515 ]
516 for line, v1, h_in, abs_, neg, dst_hi in cases:
517 with self.subTest(line=line, v1=hex(v1)):
518 want = oracle_fract_f16(h_in, abs_=abs_, neg=neg)
519 self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi))
520
521 # Source modifiers on inf/NaN preserve NaN output and keep untouched half.
522 for mod in ("-v1", "|v1|", "-|v1|"):
523 for h in (H_POS_INF, H_NEG_INF, H_QNAN):
524 with self.subTest(mod=mod, h=hex(h)):
525 got = run_op(f"v_fract_f16_e64 v0, {mod}", (H_0P25 << 16) | h)
526 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
527 self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got))
528
529 def test_vop3_output_modifiers(self):
530 # (asm_suffix, input_h, dst_hi, kwargs_for_oracle)
531 cases = [
532 # clamp without omod keeps [0, 1) and preserves 0x3c00 -> 0x3bff
533 ("clamp", H_0P75, 0, dict(clamp=True)),
534 ("clamp", H_NEG_0P25, 0, dict(clamp=True)),
535 ("clamp", H_NEG_2PM13, 0, dict(clamp=True)),
536 ("clamp", H_NEG_ZERO, 0, dict(clamp=True)),
537 # mul:2 / mul:4 / div:2 (true 1.0 stays 0x3c00 when omod is active)
538 ("mul:2", H_0P5, 0, dict(mul=2)),
539 ("mul:2", H_0P75, 0, dict(mul=2)),
540 ("mul:2", H_NEG_0P25, 0, dict(mul=2)),
541 ("mul:2", H_NEG_2PM13, 0, dict(mul=2)),
542 ("mul:4", H_0P25, 0, dict(mul=4)),
543 ("mul:4", H_0P5, 0, dict(mul=4)),
544 ("mul:4", H_NEG_1P25, 0, dict(mul=4)),
545 ("div:2", H_0P5, 0, dict(div=2)),
546 ("div:2", H_NEG_1P25, 0, dict(div=2)),
547 ("div:2", H_0P25, 0, dict(div=2)),
548 ("div:2", H_NEG_2PM13, 0, dict(div=2)),
549 # combined omod + clamp
550 ("mul:2 clamp", H_0P25, 0, dict(mul=2, clamp=True)),
551 ("mul:2 clamp", H_0P5, 0, dict(mul=2, clamp=True)),
552 ("mul:2 clamp", H_0P75, 0, dict(mul=2, clamp=True)),
553 ("mul:2 clamp", H_NEG_0P25, 0, dict(mul=2, clamp=True)),
554 ("mul:4 clamp", H_0P5, 0, dict(mul=4, clamp=True)),
555 ("op_sel:[1,1] mul:2 clamp", H_NEG_1P25, 1, dict(mul=2, clamp=True)),
556 ("op_sel:[1,1] mul:4 clamp", H_0P125, 1, dict(mul=4, clamp=True)),
557 ]
558 for suffix, h_in, dst_hi, kw in cases:
559 v1 = ((h_in << 16) | H_0P25) if "op_sel:[1,1]" in suffix else ((H_3P75 << 16) | h_in)
560 line = f"v_fract_f16_e64 v0, v1 {suffix}"
561 want = oracle_fract_f16(h_in, **kw)
562 with self.subTest(line=line, h_in=hex(h_in)):
563 self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi))
564
565 # Verify explicit exact values for the critical omod transitions.
566 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", H_0P5), merge_half(OLD, H_1P0, 0))
567 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2 clamp", H_0P75), merge_half(OLD, H_1P0, 0))
568 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:4", H_0P5), merge_half(OLD, H_2P0, 0))
569 self.assertEqual(run_op("v_fract_f16_e64 v0, v1 div:2", H_0P5), merge_half(OLD, H_0P25, 0))
570
571 def test_inline_f16_constants(self):
572 for lit, h in (("0.5", H_0P5), ("-0.5", H_NEG_0P5), ("1.0", H_1P0), ("-1.0", H_NEG_1P0)):
573 want = oracle_fract_f16(h)
574 for form in ("_e32", "_e64", ""):
575 with self.subTest(lit=lit, form=form or "bare"):
576 self.assertEqual(run_op(f"v_fract_f16{form} v0, {lit}"), merge_half(OLD, want, 0))
577 # op_sel:[0,1] writes the inline constant's fract into high half; low half preserved.
578 self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[0,1]"), merge_half(OLD, want, 1))
579 # Inline float constants place +0.0 in the high half (docs/design.md / src_h).
580 self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[1,0]"), merge_half(OLD, H_POS_ZERO, 0))
581
582 self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 mul:2"), merge_half(OLD, H_1P0, 0))
583 self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 div:2"), merge_half(OLD, H_0P25, 0))
584
585 def test_sgpr_sources_and_destination_aliasing(self):
586 s4 = (H_NEG_1P25 << 16) | H_0P25
587 self.assertEqual(run_op("v_fract_f16_e32 v0, s4", s4=s4), merge_half(OLD, H_0P25, 0))
588 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,0]", s4=s4), merge_half(OLD, H_0P25, 0))
589 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P75, 0))
590 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,1]", s4=s4), merge_half(OLD, H_0P25, 1))
591 self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P75, 1))
592 self.assertEqual(run_op("v_fract_f16_e64 v0, -s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P25, 0))
593 self.assertEqual(run_op("v_fract_f16_e64 v0, |s4| op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P25, 1))
594
595 # Destination aliasing: dst == src (v0, v0) keeps the untouched half of v0.
596 v0_init = (H_3P75 << 16) | H_NEG_0P25
597 self.assertEqual(
598 run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16_e32 v0, v0"]),
599 (H_3P75 << 16) | H_0P75,
600 )
601 self.assertEqual(
602 run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16 v0, v0"]),
603 (H_3P75 << 16) | H_0P75,
604 )
605 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
606 h_in = H_3P75 if src_hi else H_NEG_0P25
607 want_h = oracle_fract_f16(h_in)
608 with self.subTest(alias_op_sel=(src_hi, dst_hi)):
609 self.assertEqual(
610 run_ps([
611 f"v_mov_b32 v0, {v0_init:#x}",
612 f"v_fract_f16_e64 v0, v0 op_sel:[{src_hi},{dst_hi}]",
613 ]),
614 merge_half(v0_init, want_h, dst_hi),
615 )
616
617 def test_exec_masking_single_lane_and_workgroup(self):
618 # Single-lane pixel shader: inactive lane preserves pre-existing v0; re-enabling executes.
619 self.assertEqual(run_ps([
620 f"v_mov_b32 v1, {H_1P5:#x}",
621 f"v_mov_b32 v0, {OLD:#x}",
622 "s_mov_b32 exec_lo, 0",
623 "v_fract_f16_e32 v0, v1",
624 "v_fract_f16_e64 v0, v1 op_sel:[0,1]",
625 "s_mov_b32 exec_lo, 1",
626 ]), OLD)
627
628 self.assertEqual(run_ps([
629 f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}",
630 f"v_mov_b32 v0, {OLD:#x}",
631 "s_mov_b32 exec_lo, 0",
632 "v_fract_f16_e64 v0, v1 op_sel:[0,0]",
633 "v_fract_f16_e64 v0, v1 op_sel:[1,1]",
634 "s_mov_b32 exec_lo, 1",
635 "v_fract_f16_e64 v0, v1 op_sel:[1,0]",
636 ]), merge_half(OLD, H_0P75, 0))
637
638 # Multi-lane 8-thread compute shader: even lanes active, odd lanes masked off keep OLD.
639 lane_inputs = [
640 (H_NEG_1P25 << 16) | H_0P25,
641 (H_3P75 << 16) | H_NEG_0P25,
642 (H_NEG_SUB_1E5 << 16) | H_1P25,
643 (H_2P5 << 16) | H_NEG_1E4,
644 (H_NEG_ZERO << 16) | H_NEG_0P5,
645 (H_1P5 << 16) | H_NEG_MAX,
646 (H_NEG_MAX << 16) | H_NEG_2PM12,
647 (H_0P75 << 16) | H_3P75,
648 ]
649 lane_olds = [0xAA00BB00 + 0x00110001 * i for i in range(8)]
650 for dst_hi, op_line in (
651 (0, "v_fract_f16_e32 v2, v1"),
652 (1, "v_fract_f16_e64 v2, v1 op_sel:[1,1]"),
653 ):
654 mem = _Heap(
655 {0x100 + 4 * i: w for i, w in enumerate(lane_inputs)}
656 | {0x200 + 4 * i: w for i, w in enumerate(lane_olds)}
657 )
658 run_cs([
659 "v_lshlrev_b32_e32 v5, 2, v0",
660 "v_add_nc_u32_e32 v6, 0x100, v5",
661 "v_add_nc_u32_e32 v7, 0x200, v5",
662 "buffer_load_dword v1, v6, s[0:3], 0 offen",
663 "buffer_load_dword v2, v7, s[0:3], 0 offen",
664 "v_and_b32_e32 v3, 1, v0",
665 "v_cmp_eq_u32_e32 vcc_lo, 0, v3",
666 "s_and_saveexec_b32 s6, vcc_lo",
667 op_line,
668 "s_mov_b32 exec_lo, s6",
669 "buffer_store_dword v2, v5, s[0:3], 0 offen",
670 ], group_size=8, memory=mem)
671
672 got = [mem.get(4 * i) for i in range(8)]
673 want = []
674 for lane, (inp, old_w) in enumerate(zip(lane_inputs, lane_olds)):
675 if lane & 1:
676 want.append(old_w)
677 else:
678 h_in = (inp >> 16) if dst_hi else (inp & 0xFFFF)
679 want.append(merge_half(old_w, oracle_fract_f16(h_in), dst_hi))
680 with self.subTest(op_line=op_line):
681 self.assertEqual(got, want)
682
683 def test_negative_control_sabotaged_spirv(self):
684 # Input -1.25: true fract = 0.75 (0x3a00); Trunc gives -1.0 (0xbc00); Floor gives -2.0 (0xc000).
685 spv = translate_ps([
686 f"v_mov_b32 v1, {H_NEG_1P25:#x}",
687 f"v_mov_b32 v0, {OLD:#x}",
688 "v_fract_f16_e32 v0, v1",
689 ])
690 expected = merge_half(OLD, H_0P75, 0)
691 self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected)
692
693 for replacement, sabotaged_half in (("Trunc", H_NEG_1P0), ("Floor", H_NEG_2P0)):
694 sabotaged, n = re.subn(r"\bFract\b", replacement, spv, count=1)
695 self.assertEqual(n, 1)
696 got = si.run_fragment(sabotaged)["%out_mrt0"][0]
697 with self.subTest(replacement=replacement):
698 self.assertNotEqual(got, expected)
699 self.assertEqual(got, merge_half(OLD, sabotaged_half, 0))
700
701
702if __name__ == "__main__":
703 unittest.main()
diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py
new file mode 100644
index 000000000..3256b9d8d
--- /dev/null
+++ b/tests/semantic/test_valu_permlane16.py
@@ -0,0 +1,814 @@
1"""Semantic value and translation tests for RDNA2 cross-lane permutes:
2 v_permlane16_b32 D = vS[(l & ~15) | sel[l & 15]]
3 v_permlanex16_b32 D = vS[((l & ~15) ^ 16) | sel[l & 15]]
4
5where the 4-bit lane selector nibbles `sel[0..7]` come from `src1` (bits `[4*k+3 : 4*k]`) and
6`sel[8..15]` come from `src2` (bits `[4*(k-8)+3 : 4*(k-8)]`), applied independently inside each
732-lane row (`[0..15]` and `[16..31]`, and in wave64 `[32..47]` and `[48..63]`). Only lanes active
8in `EXEC` write `vD`; inactive destination lanes preserve their prior `vD`.
9
10Executed end-to-end through `tools/rdna2spirv.py` and `tests/semantic/spirv_mini_interp.py`
11(`run_workgroup`) across 32 lanes (wave32) and 64 lanes (wave64 on both one 64-wide subgroup and
12two 32-wide subgroups), as well as partial waves (20 and 40 lanes), and checked against
13hand-computed constants and an independent plain-Python RDNA2 ISA reference model. Standard library
14only; zero game data; hand-written RDNA2 disassembly listings only.
15
16Documented findings (observed in `tools/rdna2spirv.py`; no shared files modified):
17 1. `op_sel:[fi, bound_ctrl]` and inactive source lanes (`tools/rdna2spirv.py` lines 4608-4632):
18 In RDNA2 ISA (measured on RDNA2 gfx1036 and RDNA3.5 gfx1150; see `docs/shader_validation.md`
19 and `tools/crosslane_fuzz.py`), when a source lane is inactive in `EXEC` (`EXEC[src] == 0`):
20 - `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`): reads the inactive source lane's pre-existing `vS`.
21 - `fi=0, bound_ctrl=0` (`op_sel:[0,0]` or omitted): keeps the destination lane's prior `vD`.
22 - `fi=0, bound_ctrl=1` (`op_sel:[0,1]`): writes `0` to the destination lane.
23 `tools/rdna2spirv.py` lines 4608-4632 do not inspect `mods` (`op_sel:[fi, bound_ctrl]`) and emit
24 `self.g_shuffle(r, v, src)` unconditionally without checking the source lane's `%active` bit.
25 Therefore:
26 - When all accessed source lanes are active in `EXEC`, all four `op_sel` modes (`[0,0]`,
27 `[1,0]`, `[0,1]`, `[1,1]`) and omitted `op_sel` match the RDNA2 ISA.
28 - When a source lane is inactive in `EXEC` and `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`), the
29 translation matches the RDNA2 ISA (reading the inactive source lane's pre-existing `vS`).
30 - When a source lane is inactive in `EXEC` and `fi=0` (`op_sel:[0,0]`/omitted,
31 `op_sel:[0,1]`), the translator currently reads `vS[src]` instead of keeping `vD` or
32 writing `0`. Those inactive-source `fi=0` cases are tested in the plain-Python ISA
33 reference tests (`OracleTests`) and excluded from passing end-to-end assertions rather
34 than relaxing expected values; structural SPIR-V translation is verified in
35 `EmulationAndFindingTests`.
36 2. `--wave64-emulate` (`tools/rdna2spirv.py` lines 2671-2810, 2890-2895, 4608-4632):
37 With `WAVE64_EMULATE = True`, wave64 compute/mesh shaders lower `g_shuffle` and `sub_lane`
38 through `%x_buf` Workgroup-memory exchanges, `OpControlBarrier`, and a round loop (`OpLoopMerge`
39 with a backward branch). `tests/semantic/spirv_mini_interp.py` rejects `Workgroup` barriers and
40 non-forward branches (`UnsupportedConstruct`), so `--wave64-emulate` is covered by translation
41 and structural SPIR-V invariants here (and rejected cleanly by `run_workgroup`).
42 3. Wave64 native on two 32-wide subgroups (`subgroup_size = 32`):
43 Because `v_permlane16_b32` and `v_permlanex16_b32` never cross the 32-lane row boundary
44 (`0..31` vs `32..63`), both instructions stay exact across all 64 lanes even on two 32-wide
45 subgroups without `--wave64-emulate`.
46"""
47import gc
48import os
49import re
50import struct
51import sys
52import tempfile
53import unittest
54import warnings
55
56HERE = os.path.dirname(os.path.abspath(__file__))
57ROOT = os.path.dirname(os.path.dirname(HERE))
58TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
59
60sys.dont_write_bytecode = True
61if TOOLS_DIR not in sys.path:
62 sys.path.insert(0, TOOLS_DIR)
63if HERE not in sys.path:
64 sys.path.insert(0, HERE)
65
66import rdna2spirv # noqa: E402
67import spirv_mini_interp as si # noqa: E402
68
69MASK32 = 0xFFFFFFFF
70ALL32 = 0xFFFFFFFF
71ALL64 = 0xFFFFFFFFFFFFFFFF
72OLD_SENTINEL = 0xCAFE0000
73HEAP_FILL = 0xEEEEEEEE
74# V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3).
75VSHARP = [0, 0, 0x10000, 0x31016FAC]
76INPUT_BASE = 0x8000
77
78ID_S1 = 0x76543210
79ID_S2 = 0xFEDCBA98
80REV8_S1 = 0x01234567
81REV8_S2 = 0x89ABCDEF
82REV16_S1 = 0x89ABCDEF
83REV16_S2 = 0x01234567
84PAIR_SWAP_S1 = 0x10325476
85PAIR_SWAP_S2 = 0x98BADCFE
86ASYM_S1 = 0x3A0F5C91
87ASYM_S2 = 0xE27B48D6
88
89
90def ref_permlane(x16: bool, src_vals: list[int], dst_old: list[int], s1: int, s2: int,
91 exec_mask: int, fi: int = 0, bound_ctrl: int = 0) -> list[int]:
92 """Independent RDNA2 ISA reference model for v_permlane16_b32 / v_permlanex16_b32."""
93 lanes = len(src_vals)
94 assert len(dst_old) == lanes and lanes in (32, 64)
95 out = []
96 for lane in range(lanes):
97 if not ((exec_mask >> lane) & 1):
98 out.append(dst_old[lane] & MASK32)
99 continue
100 within = lane & 15
101 sel_word = s2 if within >= 8 else s1
102 nib = (sel_word >> (4 * (lane & 7))) & 0xF
103 half = lane & ~15
104 row = (half ^ 16) if x16 else half
105 src_lane = row | nib
106 if ((exec_mask >> src_lane) & 1) or fi:
107 out.append(src_vals[src_lane] & MASK32)
108 elif bound_ctrl:
109 out.append(0)
110 else:
111 out.append(dst_old[lane] & MASK32)
112 return out
113
114
115class _Heap(dict):
116 def get(self, key, default=None):
117 return super().get(key, HEAP_FILL)
118
119
120_TMP_DIR = None
121_DISASM_DIR = None
122_FSSM_DIR = None
123
124
125def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes:
126 header = bytearray(0x148)
127 struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1)
128 return bytes(header)
129
130
131def setUpModule():
132 global _TMP_DIR, _DISASM_DIR, _FSSM_DIR
133 _TMP_DIR = tempfile.TemporaryDirectory()
134 _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm")
135 _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm")
136 os.mkdir(_DISASM_DIR)
137 os.mkdir(_FSSM_DIR)
138
139
140def tearDownModule():
141 global _TMP_DIR, _DISASM_DIR, _FSSM_DIR
142 if _TMP_DIR is not None:
143 gc.collect()
144 _TMP_DIR.cleanup()
145 _TMP_DIR = None
146 _DISASM_DIR = None
147 _FSSM_DIR = None
148
149
150def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]:
151 assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}"
152 if _TMP_DIR is None:
153 setUpModule()
154 with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f:
155 f.write(_make_fssm(threads))
156 src_path = os.path.join(_DISASM_DIR, name + ".s")
157 asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
158 with open(src_path, "w", encoding="utf-8", newline="") as f:
159 f.write(asm)
160 old_emu = rdna2spirv.WAVE64_EMULATE
161 rdna2spirv.WAVE64_EMULATE = emulate
162 try:
163 with warnings.catch_warnings():
164 warnings.simplefilter("ignore", ResourceWarning)
165 spv = rdna2spirv.translate(src_path)
166 gen = rdna2spirv.translate.last_gen
167 gc.collect()
168 finally:
169 rdna2spirv.WAVE64_EMULATE = old_emu
170 return spv, gen
171
172
173def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int,
174 init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]:
175 """Translate and run a compute shader; return `threads * out_slots` 32-bit output words."""
176 spv, _ = translate_cs(name, lines, threads, emulate=False)
177 mem = _Heap()
178 if init_inputs is not None:
179 for i, val in enumerate(init_inputs):
180 mem[INPUT_BASE + 4 * i] = val & MASK32
181 si.run_workgroup(
182 spv, threads, subgroup_size,
183 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size},
184 push_constants=VSHARP + [0] * 28,
185 memory=mem,
186 )
187 out_bytes = 4 * threads * out_slots
188 stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes))
189 if stray:
190 raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}")
191 return [mem.get(4 * k) for k in range(threads * out_slots)]
192
193
194def exec_mask_lines(mask: int, wave: int) -> list[str]:
195 lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"]
196 if wave == 64:
197 lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}")
198 return lines
199
200
201def restore_exec_lines(wave: int) -> list[str]:
202 return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"]
203
204
205def store_slots_lines(regs: list[str], threads: int) -> list[str]:
206 """Emit buffer_store_dword for each VGPR in `regs` at `4 * (slot * threads + v0)`."""
207 lines = ["v_lshlrev_b32_e32 v21, 2, v0"]
208 for slot, reg in enumerate(regs):
209 if slot == 0:
210 lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen")
211 else:
212 lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}")
213 return lines
214
215
216class OracleTests(unittest.TestCase):
217 """Cross-check hand-worked constants and ISA semantics against ref_permlane."""
218
219 def test_hand_worked_identity_and_half_swap(self):
220 vals32 = [100 + l for l in range(32)]
221 old32 = [OLD_SENTINEL | l for l in range(32)]
222 # v_permlane16_b32 identity leaves all 32 lanes unchanged.
223 self.assertEqual(ref_permlane(False, vals32, old32, ID_S1, ID_S2, ALL32), vals32)
224 # v_permlanex16_b32 swaps [0..15] and [16..31].
225 self.assertEqual(
226 ref_permlane(True, vals32, old32, ID_S1, ID_S2, ALL32),
227 [100 + (l ^ 16) for l in range(32)],
228 )
229
230 # Wave64 swaps within each 32-lane row: [0..15]<->[16..31] and [32..47]<->[48..63].
231 vals64 = [500 + l for l in range(64)]
232 old64 = [OLD_SENTINEL | l for l in range(64)]
233 got64 = ref_permlane(True, vals64, old64, ID_S1, ID_S2, ALL64)
234 self.assertEqual((got64[0], got64[15], got64[16], got64[31]), (516, 531, 500, 515))
235 self.assertEqual((got64[32], got64[47], got64[48], got64[63]), (548, 563, 532, 547))
236
237 def test_hand_worked_nibble_patterns_and_exec_opsel_rules(self):
238 vals32 = [1000 + l for l in range(32)]
239 old32 = [OLD_SENTINEL | l for l in range(32)]
240
241 # Broadcast 0 from s1 (lanes 0..7) and 15 from s2 (lanes 8..15).
242 got_bcast = ref_permlane(False, vals32, old32, 0x00000000, 0xFFFFFFFF, ALL32)
243 self.assertEqual(got_bcast[0:8], [1000] * 8)
244 self.assertEqual(got_bcast[8:16], [1015] * 8)
245 self.assertEqual(got_bcast[16:24], [1016] * 8)
246 self.assertEqual(got_bcast[24:32], [1031] * 8)
247
248 # Full 16-lane reversal: s1=0x89abcdef (lanes 0..7 -> 15..8), s2=0x01234567 (lanes 8..15 -> 7..0).
249 got_rev16 = ref_permlane(False, vals32, old32, REV16_S1, REV16_S2, ALL32)
250 self.assertEqual(got_rev16[0:16], [1000 + (15 - l) for l in range(16)])
251 self.assertEqual(got_rev16[16:32], [1016 + (15 - l) for l in range(16)])
252
253 # Sub-half 8-lane reversal: s1=0x01234567 (0..7 -> 7..0), s2=0x89abcdef (8..15 -> 15..8).
254 got_rev8 = ref_permlane(True, vals32, old32, REV8_S1, REV8_S2, ALL32)
255 self.assertEqual(got_rev8[0:8], [1016 + (7 - l) for l in range(8)])
256 self.assertEqual(got_rev8[8:16], [1016 + (15 - l) for l in range(8)])
257
258 # op_sel:[fi, bound_ctrl] when lane 0 is INACTIVE in EXEC (0xFFFFFFFE):
259 # lanes 1..15 broadcast local lane 0 (inactive in half 0!), lanes 16..31 broadcast local lane 16 (active!).
260 exec_no_0 = ALL32 ^ 1
261 # fi=0, bound_ctrl=0 -> lanes 1..15 keep old32, lane 0 keeps old32[0], lanes 16..31 read 1016.
262 r00 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=0)
263 self.assertEqual(r00[0], old32[0])
264 self.assertEqual(r00[1:16], old32[1:16])
265 self.assertEqual(r00[16:32], [1016] * 16)
266
267 # fi=0, bound_ctrl=1 -> lanes 1..15 write 0, lane 0 keeps old32[0], lanes 16..31 read 1016.
268 r01 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=1)
269 self.assertEqual(r01[0], old32[0])
270 self.assertEqual(r01[1:16], [0] * 15)
271 self.assertEqual(r01[16:32], [1016] * 16)
272
273 # fi=1, bound_ctrl=0 or 1 -> lanes 1..15 read inactive lane 0's vals32[0], lane 0 keeps old32[0].
274 for bc in (0, 1):
275 r1x = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=1, bound_ctrl=bc)
276 self.assertEqual(r1x[0], old32[0])
277 self.assertEqual(r1x[1:16], [1000] * 15)
278 self.assertEqual(r1x[16:32], [1016] * 16)
279
280
281class Wave32ExecutionTests(unittest.TestCase):
282 """End-to-end 32-lane execution for v_permlane16_b32 and v_permlanex16_b32."""
283
284 def _run_batch(self, specs: list[tuple[bool, int, int, str, str]], init_vals: list[int],
285 old_vals: list[int], exec_mask: int = ALL32) -> list[list[int]]:
286 """Run a list of (x16, s1, s2, src_form, extra_mods) batched into one shader."""
287 lines = [
288 "v_lshlrev_b32_e32 v20, 2, v0",
289 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
290 "buffer_load_dword v1, v20, s[0:3], 0 offen",
291 ]
292 regs = []
293 for idx, _ in enumerate(specs):
294 dst = f"v{2 + idx}"
295 regs.append(dst)
296 lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0")
297 lines.extend(exec_mask_lines(exec_mask, 32))
298 for idx, (x16, s1, s2, src_expr, extra) in enumerate(specs):
299 dst = f"v{2 + idx}"
300 op = "v_permlanex16_b32" if x16 else "v_permlane16_b32"
301 if src_expr == "sgpr":
302 lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}",
303 f"{op} {dst}, v1, s4, s5{extra}"]
304 elif src_expr == "lit_sgpr":
305 lines += [f"s_mov_b32 s5, {s2:#x}", f"{op} {dst}, v1, {s1:#x}, s5{extra}"]
306 elif src_expr == "sgpr_lit":
307 lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, {s2:#x}{extra}"]
308 elif src_expr == "inline":
309 lines.append(f"{op} {dst}, v1, {s1}, {s2}{extra}")
310 elif src_expr == "same_sgpr":
311 assert s1 == s2
312 lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, s4{extra}"]
313 elif src_expr == "e64_sgpr":
314 lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}",
315 f"{op}_e64 {dst}, v1, s4, s5{extra}"]
316 else:
317 raise ValueError(src_expr)
318 lines.extend(restore_exec_lines(32))
319 lines.extend(store_slots_lines(regs, 32))
320 flat = run_cs("cs_w32_permlane_batch", lines, 32, 32, init_inputs=init_vals, out_slots=len(specs))
321 return [flat[slot * 32:(slot + 1) * 32] for slot in range(len(specs))]
322
323 def test_half_isolation_vs_cross_half_swap_and_nibble_selectors(self):
324 init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)]
325 old_vals = [OLD_SENTINEL | l for l in range(32)]
326 specs = [
327 # Identity (SGPR+SGPR, literal+SGPR, SGPR+literal, _e64)
328 (False, ID_S1, ID_S2, "sgpr", ""),
329 (True, ID_S1, ID_S2, "sgpr", ""),
330 (False, ID_S1, ID_S2, "lit_sgpr", ""),
331 (True, ID_S1, ID_S2, "sgpr_lit", ""),
332 (True, ID_S1, ID_S2, "e64_sgpr", ""),
333 # Broadcasts with inline constants (0, -1, 15, -16) and same-SGPR
334 (False, 0, 0, "inline", ""),
335 (True, 0, 0, "inline", ""),
336 (False, -1, -1, "inline", ""),
337 (True, 0, -1, "inline", ""),
338 (False, -16, 15, "inline", ""), # -16 = 0xfffffff0, 15 = 0x0000000f
339 (True, 0x55555555, 0x55555555, "same_sgpr", ""),
340 # 8-lane reversal vs full 16-lane reversal
341 (False, REV8_S1, REV8_S2, "sgpr", ""),
342 (True, REV8_S1, REV8_S2, "sgpr", ""),
343 (False, REV16_S1, REV16_S2, "sgpr", ""),
344 (True, REV16_S1, REV16_S2, "sgpr", ""),
345 # Pairwise swap & asymmetric non-bijective permutation
346 (False, PAIR_SWAP_S1, PAIR_SWAP_S2, "sgpr", ""),
347 (True, ASYM_S1, ASYM_S2, "sgpr", ""),
348 ]
349 results = self._run_batch(specs, init_vals, old_vals)
350 for idx, (x16, s1, s2, form, _) in enumerate(specs):
351 s1_u = s1 & MASK32
352 s2_u = s2 & MASK32
353 want = ref_permlane(x16, init_vals, old_vals, s1_u, s2_u, ALL32)
354 with self.subTest(idx=idx, x16=x16, form=form, s1=hex(s1_u), s2=hex(s2_u)):
355 self.assertEqual(results[idx], want)
356
357 # Spot-check half-staying vs half-swapping explicitly:
358 self.assertEqual(results[0], init_vals)
359 self.assertEqual(results[1], init_vals[16:32] + init_vals[0:16])
360
361 def test_all_16_nibble_broadcasts_for_both_ops(self):
362 init_vals = [0x9000 + l * 17 for l in range(32)]
363 old_vals = [OLD_SENTINEL | l for l in range(32)]
364 specs = []
365 for nib in range(16):
366 sel = 0x11111111 * nib
367 specs.append((False, sel, sel, "same_sgpr", ""))
368 specs.append((True, sel, sel, "same_sgpr", ""))
369 # Batch 16 specs at a time to stay well within VGPR file (v2..v17).
370 for base in (0, 16):
371 chunk = specs[base:base + 16]
372 results = self._run_batch(chunk, init_vals, old_vals)
373 for idx, (x16, s1, s2, _, _) in enumerate(chunk):
374 want = ref_permlane(x16, init_vals, old_vals, s1, s2, ALL32)
375 with self.subTest(x16=x16, nib=s1 & 0xF):
376 self.assertEqual(results[idx], want)
377
378 def test_butterfly_32lane_sum_reduction(self):
379 # Real compiler idiom: xor 1, 2, 4, 8 via v_permlane16_b32 then xor 16 via v_permlanex16_b32.
380 init_vals = [3 * l + 5 for l in range(32)]
381 expected_sum = sum(init_vals)
382 got = run_cs("cs_w32_permlane_butterfly", [
383 "v_lshlrev_b32_e32 v20, 2, v0",
384 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
385 "buffer_load_dword v1, v20, s[0:3], 0 offen",
386 # xor 1: s1=0x67452301, s2=0xefcdab89
387 "s_mov_b32 s5, 0xefcdab89",
388 "v_permlane16_b32 v2, v1, 0x67452301, s5",
389 "v_add_nc_u32_e32 v1, v1, v2",
390 # xor 2: s1=0x54761032, s2=0xdcfe98ba
391 "s_mov_b32 s5, 0xdcfe98ba",
392 "v_permlane16_b32 v2, v1, 0x54761032, s5",
393 "v_add_nc_u32_e32 v1, v1, v2",
394 # xor 4: s1=0x32107654, s2=0xba98fedc
395 "s_mov_b32 s5, 0xba98fedc",
396 "v_permlane16_b32 v2, v1, 0x32107654, s5",
397 "v_add_nc_u32_e32 v1, v1, v2",
398 # xor 8: s1=0xfedcba98, s2=0x76543210
399 "s_mov_b32 s5, 0x76543210",
400 "v_permlane16_b32 v2, v1, 0xfedcba98, s5",
401 "v_add_nc_u32_e32 v1, v1, v2",
402 # xor 16: identity nibbles via v_permlanex16_b32
403 "s_mov_b32 s4, 0x76543210",
404 "s_mov_b32 s5, 0xfedcba98",
405 "v_permlanex16_b32 v2, v1, s4, s5",
406 "v_add_nc_u32_e32 v1, v1, v2",
407 "v_lshlrev_b32_e32 v21, 2, v0",
408 "buffer_store_dword v1, v21, s[0:3], 0 offen",
409 ], 32, 32, init_inputs=init_vals)
410 self.assertEqual(got, [expected_sum] * 32)
411
412 def test_exec_destination_masking_and_all_op_sel_with_active_sources(self):
413 # Active lanes in each 16-lane half are {0, 2, 4, 6, 8, 9, 10, 11};
414 # selectors ONLY read from active lanes {0, 2, 4, 6, 8, 9, 10, 11}, so all 4 op_sel modes match ISA.
415 exec_mask = 0x0F550F55
416 s1_sel = 0x64206420 # nibbles in {0, 2, 4, 6} (all active)
417 s2_sel = 0xBA98BA98 # nibbles in {8, 9, 10, 11} (all active)
418 init_vals = [0x100 + l for l in range(32)]
419 old_vals = [OLD_SENTINEL | l for l in range(32)]
420 specs = []
421 for x16 in (False, True):
422 for mods in ("", " op_sel:[0,0]", " op_sel:[1,0]", " op_sel:[0,1]", " op_sel:[1,1]"):
423 specs.append((x16, s1_sel, s2_sel, "sgpr", mods))
424 results = self._run_batch(specs, init_vals, old_vals, exec_mask=exec_mask)
425 for idx, (x16, s1, s2, _, mods) in enumerate(specs):
426 want = ref_permlane(x16, init_vals, old_vals, s1, s2, exec_mask)
427 with self.subTest(x16=x16, mods=mods or "default"):
428 self.assertEqual(results[idx], want)
429
430 def test_op_sel_fi1_reads_inactive_source_lanes(self):
431 # Lanes 0, 16 are OFF in EXEC; active lanes modify v1 to 9999 AFTER pre-filling v1,
432 # then v_permlane16_b32 / v_permlanex16_b32 with op_sel:[1,0] and op_sel:[1,1] broadcast
433 # local lane 0 (inactive lane 0 / inactive lane 16!). Active lanes must see the inactive
434 # lanes' pre-existing values (2000 and 2016), while inactive lanes 0 and 16 keep OLD.
435 exec_mask = ALL32 ^ ((1 << 0) | (1 << 16))
436 init_vals = [2000 + l for l in range(32)]
437 old_vals = [OLD_SENTINEL | l for l in range(32)]
438 updated_vals = [init_vals[l] if not ((exec_mask >> l) & 1) else 9999 for l in range(32)]
439
440 lines = [
441 "v_lshlrev_b32_e32 v20, 2, v0",
442 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
443 "buffer_load_dword v1, v20, s[0:3], 0 offen",
444 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
445 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
446 f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0",
447 f"v_or_b32_e32 v5, {OLD_SENTINEL:#x}, v0",
448 *exec_mask_lines(exec_mask, 32),
449 "v_mov_b32_e32 v1, 9999", # inactive lanes 0 & 16 keep 2000 & 2016
450 "v_permlane16_b32 v2, v1, 0, 0 op_sel:[1,0]",
451 "v_permlane16_b32 v3, v1, 0, 0 op_sel:[1,1]",
452 "v_permlanex16_b32 v4, v1, 0, 0 op_sel:[1,0]",
453 "v_permlanex16_b32 v5, v1, 0, 0 op_sel:[1,1]",
454 *restore_exec_lines(32),
455 *store_slots_lines(["v2", "v3", "v4", "v5"], 32),
456 ]
457 flat = run_cs("cs_w32_permlane_fi1", lines, 32, 32, init_inputs=init_vals, out_slots=4)
458 for slot, x16 in enumerate((False, False, True, True)):
459 got = flat[slot * 32:(slot + 1) * 32]
460 want = ref_permlane(x16, updated_vals, old_vals, 0, 0, exec_mask, fi=1, bound_ctrl=slot & 1)
461 self.assertEqual(got, want)
462 self.assertEqual(flat[0], OLD_SENTINEL | 0)
463 self.assertEqual(flat[1], 2000)
464 self.assertEqual(flat[16], OLD_SENTINEL | 16)
465 self.assertEqual(flat[17], 2016)
466 # Slot 2 (permlanex16 op_sel:[1,0]): active lanes 1..15 read inactive lane 16 (2016).
467 self.assertEqual(flat[2 * 32 + 1], 2016)
468 self.assertEqual(flat[2 * 32 + 17], 2000)
469
470 def test_destination_aliasing_v1_and_v0(self):
471 init_vals = [300 + l for l in range(32)]
472 # 1. Alias v1, v1 (with EXEC mask & fi=1 reading inactive lane 0 before overwrite)
473 exec_mask = ALL32 ^ (1 << 0)
474 got_v1 = run_cs("cs_w32_permlane_alias_v1", [
475 "v_lshlrev_b32_e32 v20, 2, v0",
476 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
477 "buffer_load_dword v1, v20, s[0:3], 0 offen",
478 "v_mov_b32_e32 v2, v1",
479 *exec_mask_lines(exec_mask, 32),
480 "s_mov_b32 s4, 0x00000000",
481 "s_mov_b32 s5, 0x00000000",
482 "v_permlane16_b32 v1, v1, s4, s5 op_sel:[1,0]",
483 "v_permlanex16_b32 v2, v2, 0x76543210, 0xfedcba98 op_sel:[1,0]",
484 *restore_exec_lines(32),
485 *store_slots_lines(["v1", "v2"], 32),
486 ], 32, 32, init_inputs=init_vals, out_slots=2)
487 self.assertEqual(got_v1[:32], ref_permlane(False, init_vals, init_vals, 0, 0, exec_mask, fi=1))
488 self.assertEqual(got_v1[32:], ref_permlane(True, init_vals, init_vals, ID_S1, ID_S2, exec_mask, fi=1))
489
490 # 2. Alias v0, v0 directly (save output byte offset 4 * v0 in v21 first)
491 got_v0_16 = run_cs("cs_w32_permlane16_alias_v0", [
492 "v_lshlrev_b32_e32 v21, 2, v0",
493 f"s_mov_b32 s4, {REV16_S1:#x}",
494 f"s_mov_b32 s5, {REV16_S2:#x}",
495 "v_permlane16_b32 v0, v0, s4, s5",
496 "buffer_store_dword v0, v21, s[0:3], 0 offen",
497 ], 32, 32)
498 self.assertEqual(got_v0_16, ref_permlane(False, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32))
499
500 got_v0_x16 = run_cs("cs_w32_permlanex16_alias_v0", [
501 "v_lshlrev_b32_e32 v21, 2, v0",
502 f"s_mov_b32 s4, {REV16_S1:#x}",
503 f"s_mov_b32 s5, {REV16_S2:#x}",
504 "v_permlanex16_b32 v0, v0, s4, s5",
505 "buffer_store_dword v0, v21, s[0:3], 0 offen",
506 ], 32, 32)
507 self.assertEqual(got_v0_x16, ref_permlane(True, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32))
508
509 def test_partial_wave_20_lanes_avoids_missing_lanes(self):
510 # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist.
511 # 1. All 20 existing lanes active (0xFFFFF): selectors in {0..3} read existing active lanes 0..3 / 16..19.
512 exec_20 = 0xFFFFF
513 got_all20 = run_cs("cs_w32_partial20_all", [
514 "v_add_nc_u32_e32 v1, 700, v0",
515 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
516 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
517 *exec_mask_lines(exec_20, 32),
518 "v_permlane16_b32 v2, v1, 0x32103210, 0x01230123",
519 "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123",
520 *restore_exec_lines(32),
521 *store_slots_lines(["v2", "v3"], 20),
522 ], 20, 32, out_slots=2)
523 vals_padded = [700 + l for l in range(20)] + [0] * 12
524 old_padded = [OLD_SENTINEL | l for l in range(20)] + [0] * 12
525 self.assertEqual(got_all20[:20], ref_permlane(False, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20])
526 self.assertEqual(got_all20[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20])
527
528 # 2. EXEC = 0xFFFF (lanes 16..19 inactive): permlane16 reads [0..15] and preserves OLD on 16..19;
529 # permlanex16 op_sel:[1,0] (fi=1) reads inactive lanes 16..19 while inactive lanes 16..19 discard UNDEF
530 # shuffles from missing lanes 20..31 and keep OLD.
531 exec_16 = 0xFFFF
532 got_masked = run_cs("cs_w32_partial20_masked", [
533 "v_add_nc_u32_e32 v1, 700, v0",
534 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
535 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
536 *exec_mask_lines(exec_16, 32),
537 "v_permlane16_b32 v2, v1, 0x01234567, 0x89abcdef",
538 "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123 op_sel:[1,0]",
539 *restore_exec_lines(32),
540 *store_slots_lines(["v2", "v3"], 20),
541 ], 20, 32, out_slots=2)
542 self.assertEqual(got_masked[:20], ref_permlane(False, vals_padded, old_padded, REV8_S1, REV8_S2, exec_16)[:20])
543 self.assertEqual(got_masked[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_16, fi=1)[:20])
544
545
546class Wave64ExecutionTests(unittest.TestCase):
547 """End-to-end 64-lane execution across one 64-wide subgroup AND two 32-wide subgroups."""
548
549 def test_wave64_halves_selectors_exec_and_fi1_on_subgroup_64_and_32(self):
550 init_vals = [0x4000 + l * 31 for l in range(64)]
551 old_vals = [OLD_SENTINEL | l for l in range(64)]
552 # Asymmetric 64-bit EXEC: active lanes in each 16-lane quarter are {0, 2, 4, 6, 8, 9, 10, 11}.
553 exec_active_only = 0x0F550F550F550F55
554 # Inactive source lane 0 and lane 32 (one in each 32-lane row) for fi=1 test.
555 exec_no_0_32 = ALL64 ^ ((1 << 0) | (1 << 32))
556 updated_fi1 = [init_vals[l] if not ((exec_no_0_32 >> l) & 1) else (8800 + l) for l in range(64)]
557
558 lines = [
559 "s_mov_b64 exec, -1",
560 "v_lshlrev_b32_e32 v20, 2, v0",
561 f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20",
562 "buffer_load_dword v1, v20, s[0:3], 0 offen",
563 "v_mov_b32_e32 v10, v1",
564 # Slot 0: v_permlane16_b32 identity (stays in [0..15], [16..31], [32..47], [48..63])
565 f"s_mov_b32 s4, {ID_S1:#x}",
566 f"s_mov_b32 s5, {ID_S2:#x}",
567 "v_permlane16_b32 v2, v1, s4, s5",
568 # Slot 1: v_permlanex16_b32 identity (swaps [0..15]<->[16..31] and [32..47]<->[48..63])
569 "v_permlanex16_b32 v3, v1, s4, s5",
570 # Slot 2: v_permlane16_b32 asymmetric non-bijective selectors
571 f"s_mov_b32 s6, {ASYM_S1:#x}",
572 f"s_mov_b32 s7, {ASYM_S2:#x}",
573 "v_permlane16_b32 v4, v1, s6, s7",
574 # Slot 3: v_permlanex16_b32_e64 full 16-lane reversal
575 f"s_mov_b32 s8, {REV16_S2:#x}",
576 f"v_permlanex16_b32_e64 v5, v1, {REV16_S1:#x}, s8",
577 # Slot 4: 64-bit EXEC destination masking with active sources (v6 pre-loaded with OLD)
578 f"v_or_b32_e32 v6, {OLD_SENTINEL:#x}, v0",
579 "s_mov_b32 s9, 0xba98ba98",
580 *exec_mask_lines(exec_active_only, 64),
581 "v_permlanex16_b32 v6, v1, 0x64206420, s9",
582 *restore_exec_lines(64),
583 # Slot 5: fi=1 reading inactive source lane 0 (in low 32) and lane 32 (in high 32)
584 f"v_or_b32_e32 v7, {OLD_SENTINEL:#x}, v0",
585 *exec_mask_lines(exec_no_0_32, 64),
586 "v_add_nc_u32_e32 v10, 8800, v0",
587 "v_permlane16_b32 v7, v10, 0, 0 op_sel:[1,0]",
588 # Slot 6: fi=1 permlanex16 reading inactive lane 32 from lanes 48..63 & lane 0 from 16..31
589 *restore_exec_lines(64),
590 f"v_or_b32_e32 v8, {OLD_SENTINEL:#x}, v0",
591 *exec_mask_lines(exec_no_0_32, 64),
592 "v_permlanex16_b32 v8, v10, 0, 0 op_sel:[1,1]",
593 *restore_exec_lines(64),
594 *store_slots_lines(["v2", "v3", "v4", "v5", "v6", "v7", "v8"], 64),
595 ]
596
597 expected_slots = [
598 ref_permlane(False, init_vals, old_vals, ID_S1, ID_S2, ALL64),
599 ref_permlane(True, init_vals, old_vals, ID_S1, ID_S2, ALL64),
600 ref_permlane(False, init_vals, old_vals, ASYM_S1, ASYM_S2, ALL64),
601 ref_permlane(True, init_vals, old_vals, REV16_S1, REV16_S2, ALL64),
602 ref_permlane(True, init_vals, old_vals, 0x64206420, 0xBA98BA98, exec_active_only),
603 ref_permlane(False, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=0),
604 ref_permlane(True, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=1),
605 ]
606
607 for subgroup_size in (64, 32):
608 with self.subTest(subgroup_size=subgroup_size):
609 flat = run_cs(f"cs_w64_permlane_sg{subgroup_size}", lines, 64, subgroup_size,
610 init_inputs=init_vals, out_slots=7)
611 for slot, want in enumerate(expected_slots):
612 got = flat[slot * 64:(slot + 1) * 64]
613 self.assertEqual(got, want, f"subgroup={subgroup_size}, slot={slot}")
614
615 def test_wave64_destination_aliasing_v0_and_v1(self):
616 for subgroup_size in (64, 32):
617 with self.subTest(subgroup_size=subgroup_size):
618 got = run_cs(f"cs_w64_permlane_alias_sg{subgroup_size}", [
619 "s_mov_b64 exec, -1",
620 "v_lshlrev_b32_e32 v21, 2, v0",
621 "v_add_nc_u32_e32 v1, 500, v0",
622 f"s_mov_b32 s4, {PAIR_SWAP_S1:#x}",
623 f"s_mov_b32 s5, {PAIR_SWAP_S2:#x}",
624 "v_permlane16_b32 v1, v1, s4, s5",
625 "v_permlanex16_b32 v0, v0, s4, s5",
626 "buffer_store_dword v1, v21, s[0:3], 0 offen",
627 f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 64}",
628 ], 64, subgroup_size, out_slots=2)
629 self.assertEqual(
630 got[:64],
631 ref_permlane(False, [500 + l for l in range(64)], [0] * 64, PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64),
632 )
633 self.assertEqual(
634 got[64:],
635 ref_permlane(True, list(range(64)), list(range(64)), PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64),
636 )
637
638 def test_wave64_partial_wave_40_lanes(self):
639 # 40 threads in a 64-wide subgroup: lanes 32..39 exist in quarter [32..47]; lanes 40..63 do not.
640 # Active lanes 0..31 run v_permlanex16_b32 across [0..15] <-> [16..31], and lanes 32..39 run
641 # v_permlane16_b32 within [32..39]; inactive lanes 32..39 on permlanex16 discard UNDEF from [48..63].
642 exec_low32 = 0x00000000FFFFFFFF
643 got = run_cs("cs_w64_partial40_permlane", [
644 "s_mov_b64 exec, -1",
645 "v_add_nc_u32_e32 v1, 200, v0",
646 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
647 f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0",
648 "v_permlane16_b32 v2, v1, 0x32107654, 0x32107654",
649 *exec_mask_lines(exec_low32, 64),
650 "v_permlanex16_b32 v3, v1, 0x01234567, 0x89abcdef",
651 *restore_exec_lines(64),
652 *store_slots_lines(["v2", "v3"], 40),
653 ], 40, 64, out_slots=2)
654 vals64 = [200 + l for l in range(40)] + [0] * 24
655 old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24
656 self.assertEqual(got[:40], ref_permlane(False, vals64, old64, 0x32107654, 0x32107654, ALL64)[:40])
657 self.assertEqual(got[40:], ref_permlane(True, vals64, old64, REV8_S1, REV8_S2, exec_low32)[:40])
658
659
660class EmulationAndFindingTests(unittest.TestCase):
661 """Translation / structural SPIR-V checks for --wave64-emulate and documented op_sel finding."""
662
663 def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self):
664 base = [
665 "s_mov_b64 exec, -1",
666 "v_add_nc_u32_e32 v1, 100, v0",
667 f"s_mov_b32 s4, {ID_S1:#x}",
668 f"s_mov_b32 s5, {ID_S2:#x}",
669 ]
670 tail = [
671 "v_lshlrev_b32_e32 v21, 2, v0",
672 "buffer_store_dword v2, v21, s[0:3], 0 offen",
673 ]
674 spv_16, gen_16 = translate_cs("cs_w64_emu_perm16", base + ["v_permlane16_b32 v2, v1, s4, s5"] + tail,
675 64, emulate=True)
676 spv_x16, gen_x16 = translate_cs("cs_w64_emu_permx16", base + ["v_permlanex16_b32 v2, v1, s4, s5"] + tail,
677 64, emulate=True)
678 for spv, gen in ((spv_16, gen_16), (spv_x16, gen_x16)):
679 self.assertTrue(gen.wave64 and gen.emulate)
680 self.assertNotIn("OpGroupNonUniform", spv)
681 self.assertNotIn("%sg_lane", spv)
682 self.assertIn("%x_buf = OpVariable", spv)
683 self.assertGreaterEqual(spv.count("OpControlBarrier"), 2)
684 # Nibble extraction (width = 4) and 16-lane half mask (0xFFFFFFF0)
685 self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b")
686 self.assertIn("OpBitwiseAnd %uint %", spv)
687 self.assertIn("%cfffffff0", spv)
688 # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler.
689 with self.assertRaises(si.UnsupportedConstruct):
690 si.run_workgroup(
691 spv, 64, 32,
692 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32},
693 push_constants=VSHARP + [0] * 28, memory={},
694 )
695
696 # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not.
697 xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b"
698 self.assertIsNone(re.search(xor16_pat, spv_16))
699 self.assertIsNotNone(re.search(xor16_pat, spv_x16))
700
701 # Wave32 shaders are unaffected by WAVE64_EMULATE=True.
702 w32_lines = ["v_permlanex16_b32 v2, v0, 0x76543210, 0xfedcba98",
703 "v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v2, v21, s[0:3], 0 offen"]
704 spv_w32_plain, _ = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=False)
705 spv_w32_emu, gen_w32_emu = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=True)
706 self.assertFalse(gen_w32_emu.wave64 or gen_w32_emu.emulate)
707 self.assertEqual(spv_w32_plain, spv_w32_emu)
708
709 def test_op_sel_fi0_translates_cleanly_while_inactive_src_handling_is_excluded(self):
710 # Documented finding (tools/rdna2spirv.py lines 4608-4632): op_sel:[0,0] and op_sel:[0,1]
711 # are accepted by shader_ir/rdna2spirv without raising Unsupported, and lower to
712 # OpGroupNonUniformShuffle without inspecting mods or source %active; inactive-source fi=0
713 # value assertions stay excluded from Wave32ExecutionTests / Wave64ExecutionTests.
714 for op in ("v_permlane16_b32", "v_permlanex16_b32"):
715 for opsel in ("op_sel:[0,0]", "op_sel:[0,1]"):
716 with self.subTest(op=op, opsel=opsel):
717 spv, gen = translate_cs("cs_w32_opsel_fi0", [
718 "v_mov_b32_e32 v1, v0",
719 "s_mov_b32 exec_lo, 0xfffffffe",
720 f"{op} v2, v1, 0, 0 {opsel}",
721 "s_mov_b32 exec_lo, -1",
722 "v_lshlrev_b32_e32 v21, 2, v0",
723 "buffer_store_dword v2, v21, s[0:3], 0 offen",
724 ], 32)
725 self.assertFalse(gen.wave64)
726 self.assertIn("OpGroupNonUniformShuffle %uint %c3", spv)
727 self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b")
728
729
730class NegativeControls(unittest.TestCase):
731 """Sabotage the translated SPIR-V like a translator regression; multi-lane execution must detect it."""
732
733 def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]:
734 mem = _Heap()
735 si.run_workgroup(
736 spv, threads, subgroup_size,
737 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size},
738 push_constants=VSHARP + [0] * 28,
739 memory=mem,
740 )
741 return [mem.get(4 * k) for k in range(threads)]
742
743 def test_sabotage_permlanex16_xor16_dropped(self):
744 spv, _ = translate_cs("cs_w64_neg_x16", [
745 "s_mov_b64 exec, -1",
746 "v_add_nc_u32_e32 v1, 100, v0",
747 f"v_permlanex16_b32 v2, v1, {ID_S1:#x}, {ID_S2:#x}",
748 "v_lshlrev_b32_e32 v21, 2, v0",
749 "buffer_store_dword v2, v21, s[0:3], 0 offen",
750 ], 64)
751 want = ref_permlane(True, [100 + l for l in range(64)], [0] * 64, ID_S1, ID_S2, ALL64)
752 self.assertEqual(self._run(spv, 64, 64), want)
753
754 bad, n = re.subn(r"(%\w+) = OpBitwiseXor %uint (%\w+) %c10\b", r"\1 = OpCopyObject %uint \2", spv)
755 self.assertEqual(n, 1)
756 got_bad = self._run(bad, 64, 64)
757 self.assertNotEqual(got_bad, want)
758 self.assertEqual(got_bad, [100 + l for l in range(64)]) # collapsed to permlane16
759
760 def test_sabotage_half_base_dropped_or_shuffle_removed(self):
761 spv, _ = translate_cs("cs_w32_neg_perm16", [
762 "v_add_nc_u32_e32 v1, 200, v0",
763 f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0",
764 f"s_mov_b32 exec_lo, {0x0F550F55:#x}",
765 "s_mov_b32 s4, 0x64206420",
766 "s_mov_b32 s5, 0xba98ba98",
767 "v_permlane16_b32 v2, v1, s4, s5",
768 "s_mov_b32 exec_lo, -1",
769 "v_lshlrev_b32_e32 v21, 2, v0",
770 "buffer_store_dword v2, v21, s[0:3], 0 offen",
771 ], 32)
772 want = ref_permlane(False, [200 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)],
773 0x64206420, 0xBA98BA98, 0x0F550F55)
774 self.assertEqual(self._run(spv, 32, 32), want)
775
776 # 1. Dropping the 0xFFFFFFF0 half-base mask sends lanes 16..31 into [0..15].
777 bad_half, n1 = re.subn(r"OpBitwiseAnd %uint (%\w+) %cfffffff0\b", r"OpBitwiseAnd %uint \1 %c0", spv)
778 self.assertEqual(n1, 1)
779 self.assertNotEqual(self._run(bad_half, 32, 32), want)
780
781 # 2. Swapping the hi8 OpSelect arms swaps s1 (lanes 0..7) and s2 (lanes 8..15).
782 bad_sel, n2 = re.subn(
783 r"(%\w+ = OpUGreaterThanEqual %bool %\w+ %c8\n(?:.*\n){0,5}?\s*%\w+ = OpSelect %uint %\w+ )(%\w+) (%\w+)",
784 r"\1\3 \2",
785 spv,
786 )
787 self.assertEqual(n2, 1)
788 self.assertNotEqual(self._run(bad_sel, 32, 32), want)
789
790 # 3. Replacing OpGroupNonUniformShuffle with OpCopyObject turns permute into own-lane copy.
791 bad_shuf, n3 = re.subn(
792 r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+",
793 r"\1 = OpCopyObject %uint \2",
794 spv,
795 )
796 self.assertEqual(n3, 1)
797 self.assertNotEqual(self._run(bad_shuf, 32, 32), want)
798
799 # 4. Dropping the destination EXEC OpSelect overwrites inactive destination lanes.
800 bad_exec, n4 = re.subn(
801 r"(%\w+ = OpGroupNonUniformShuffle %uint %c3 %\w+ %\w+\n(?:.*\n){0,4}?\s*"
802 r"%\w+ = OpLoad %bool %active\n\s*"
803 r"(%\w+) = OpSelect %uint %\w+ (%\w+)) %\w+",
804 r"\1 \3",
805 spv,
806 )
807 self.assertEqual(n4, 1)
808 got_bad_exec = self._run(bad_exec, 32, 32)
809 self.assertNotEqual(got_bad_exec, want)
810 self.assertNotEqual(got_bad_exec[1], OLD_SENTINEL | 1)
811
812
813if __name__ == "__main__":
814 unittest.main()
diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py
new file mode 100644
index 000000000..e7f649ae0
--- /dev/null
+++ b/tests/semantic/test_valu_rcp_fdiv.py
@@ -0,0 +1,824 @@
1"""Semantic value tests for OpFDiv in spirv_mini_interp and RDNA2 reciprocal VALU ops:
2 - OpFDiv (scalar %float and vector %v2float) directly in tests/semantic/spirv_mini_interp.py
3 - v_rcp_f32: D.f32 = 1.0 / S0.f32
4 - v_rcp_iflag_f32: D.f32 = 1.0 / S0.f32 (no FP flags)
5 - v_rcp_f16: D.f16 = 1.0 / S0.f16 (preserves the untouched 16-bit half of D)
6
7Per the SPIR-V specification and tests/semantic/README.md, OpFDiv by zero (+-0.0) is undefined and raises
8spirv_mini_interp.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). Accordingly, finite non-zero,
9subnormal, +-inf, and NaN operands are value-checked against independent Fraction-based binary32/binary16
10oracles, while +-0.0 divisors/inputs are verified to raise UnsupportedConstruct.
11
12NaN payloads are not pinned because values passing through Python floats lose exact NaN payload bits; NaN
13results are asserted as binary32/binary16 NaNs. Standard library only; hand-written RDNA2 listings only.
14"""
15from fractions import Fraction
16import gc
17import itertools
18import math
19import os
20import re
21import struct
22import sys
23import tempfile
24import unittest
25import warnings
26
27HERE = os.path.dirname(os.path.abspath(__file__))
28ROOT = os.path.dirname(os.path.dirname(HERE))
29TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
30
31sys.dont_write_bytecode = True
32if TOOLS_DIR not in sys.path:
33 sys.path.insert(0, TOOLS_DIR)
34if HERE not in sys.path:
35 sys.path.insert(0, HERE)
36
37import rdna2spirv # noqa: E402
38import spirv_mini_interp as si # noqa: E402
39
40MASK32 = 0xFFFFFFFF
41STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
42VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC]
43OLD = 0xBEEF1234
44
45# Representative binary16 encodings.
46H_POS_ZERO = 0x0000
47H_NEG_ZERO = 0x8000
48H_SUB_MIN = 0x0001 # 2^-24
49H_NEG_SUB_MIN = 0x8001 # -2^-24
50H_SUB_2M16 = 0x0100 # 2^-16 (1/x = 65536 >= 65520 -> +inf)
51H_SUB_2M15 = 0x0200 # 2^-15 (1/x = 32768 = 0x7800)
52H_SUB_MAX = 0x03FF # 1023 * 2^-24
53H_NORM_MIN = 0x0400 # 2^-14 (1/x = 16384 = 0x7400)
54H_0P25 = 0x3400 # 0.25
55H_NEG_0P25 = 0xB400 # -0.25
56H_0P5 = 0x3800 # 0.5
57H_NEG_0P5 = 0xB800 # -0.5
58H_0P75 = 0x3A00 # 0.75
59H_1P0 = 0x3C00 # 1.0
60H_NEG_1P0 = 0xBC00 # -1.0
61H_NEG_1P25 = 0xBD00 # -1.25
62H_1P5 = 0x3E00 # 1.5
63H_2P0 = 0x4000 # 2.0
64H_NEG_2P0 = 0xC000 # -2.0
65H_3P0 = 0x4200 # 3.0
66H_NEG_3P0 = 0xC200 # -3.0
67H_4P0 = 0x4400 # 4.0
68H_NEG_4P0 = 0xC400 # -4.0
69H_8P0 = 0x4800 # 8.0
70H_16P0 = 0x4C00 # 16.0
71H_1024 = 0x6400 # 1024.0
72H_MAX = 0x7BFF # 65504.0
73H_NEG_MAX = 0xFBFF # -65504.0
74H_POS_INF = 0x7C00 # +inf
75H_NEG_INF = 0xFC00 # -inf
76H_QNAN = 0x7E01 # +qNaN
77H_NEG_QNAN = 0xFE01 # -qNaN
78H_SNAN = 0x7C01 # +sNaN
79
80
81def f32_bits(x: float) -> int:
82 try:
83 return struct.unpack("<I", struct.pack("<f", x))[0]
84 except OverflowError:
85 return 0x7F800000 if x > 0 else 0xFF800000
86
87
88def is_f32_nan_bits(bits: int) -> bool:
89 return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0
90
91
92def is_f16_nan(half: int) -> bool:
93 return (half & 0x7FFF) > 0x7C00
94
95
96def merge_half(old: int, half: int, dst_hi: int) -> int:
97 h = half & 0xFFFF
98 return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h)
99
100
101# -----------------------------------------------------------------------------
102# Independent Exact-Rational Binary32 / Binary16 Reference Oracles
103# -----------------------------------------------------------------------------
104
105def _rne_int(q: Fraction) -> int:
106 n = q.numerator // q.denominator
107 rem = q - n
108 if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)):
109 n += 1
110 return n
111
112
113def f32_to_fraction(bits: int) -> Fraction:
114 bits &= MASK32
115 sign = -1 if (bits >> 31) else 1
116 exp = (bits >> 23) & 0xFF
117 man = bits & 0x7FFFFF
118 if exp == 0xFF:
119 raise ValueError(f"non-finite f32 bits {bits:#010x}")
120 if exp == 0:
121 return sign * Fraction(man, 1 << 23) * Fraction(2) ** -126
122 return sign * Fraction((1 << 23) | man, 1 << 23) * Fraction(2) ** (exp - 127)
123
124
125def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int:
126 if val == 0:
127 return 0x80000000 if neg_zero else 0x00000000
128 sign = 0x80000000 if val < 0 else 0
129 a = abs(val)
130 e = a.numerator.bit_length() - a.denominator.bit_length()
131 if Fraction(2) ** e > a:
132 e -= 1
133 if e < -126:
134 n = _rne_int(a / Fraction(2) ** -149)
135 if n == 0:
136 return sign
137 if n < (1 << 23):
138 return sign | n
139 return sign | (1 << 23)
140 n = _rne_int(a / Fraction(2) ** (e - 23))
141 if n == (1 << 24):
142 n >>= 1
143 e += 1
144 if e > 127:
145 return sign | 0x7F800000
146 return sign | ((e + 127) << 23) | (n & 0x7FFFFF)
147
148
149def f16_to_fraction(half: int) -> Fraction:
150 half &= 0xFFFF
151 sign = -1 if (half >> 15) else 1
152 exp = (half >> 10) & 0x1F
153 man = half & 0x3FF
154 if exp == 0x1F:
155 raise ValueError(f"non-finite f16 bits {half:#06x}")
156 if exp == 0:
157 return sign * Fraction(man, 1 << 10) * Fraction(2) ** -14
158 return sign * Fraction((1 << 10) | man, 1 << 10) * Fraction(2) ** (exp - 15)
159
160
161def round_fraction_to_f16(val: Fraction, neg_zero: bool = False) -> int:
162 if val == 0:
163 return 0x8000 if neg_zero else 0x0000
164 sign = 0x8000 if val < 0 else 0
165 a = abs(val)
166 e = a.numerator.bit_length() - a.denominator.bit_length()
167 if Fraction(2) ** e > a:
168 e -= 1
169 if e < -14:
170 n = _rne_int(a / Fraction(2) ** -24)
171 return sign | n
172 n = _rne_int(a / Fraction(2) ** (e - 10))
173 if n == (1 << 11):
174 n >>= 1
175 e += 1
176 if e > 15:
177 return sign | 0x7C00
178 return sign | ((e + 15) << 10) | (n & 0x3FF)
179
180
181def ref_rcp_f32(x_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int:
182 """Reference oracle for non-zero f32 reciprocal (with optional output scale/clamp)."""
183 bits = x_bits & MASK32
184 sign = bits & 0x80000000
185 absu = bits & 0x7FFFFFFF
186 if absu == 0:
187 raise ValueError("division by zero is undefined in SPIR-V")
188 if absu > 0x7F800000:
189 if clamp:
190 raise ValueError("clamp of NaN is undefined in GLSL.std.450")
191 return 0x7FC00000
192 if absu == 0x7F800000:
193 # 1 / (+-inf) = +-0.0; omod preserves sign of zero, clamp orders -0 below +0 -> +0.
194 return 0 if clamp else sign
195 # Match OpFDiv(1, x) rounded to binary32 before clamp_mods (scale, then FClamp [0, 1]).
196 r_bits = round_fraction_to_f32(Fraction(1) / f32_to_fraction(bits))
197 if (r_bits & 0x7FFFFFFF) == 0x7F800000:
198 r_sign = r_bits & 0x80000000
199 if clamp:
200 return 0 if r_sign else 0x3F800000
201 return r_bits
202 val = f32_to_fraction(r_bits) * scale
203 if clamp:
204 if val <= 0:
205 return 0x00000000
206 if val >= 1:
207 return 0x3F800000
208 return round_fraction_to_f32(val)
209
210
211def ref_rcp_f16(h_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int:
212 """Reference oracle for non-zero f16 reciprocal (f32 OpFDiv + clamp_mods + f16_bits)."""
213 h = h_bits & 0xFFFF
214 sign = (h & 0x8000) << 16
215 absh = h & 0x7FFF
216 if absh == 0:
217 raise ValueError("division by zero is undefined in SPIR-V")
218 if absh > 0x7C00:
219 if clamp:
220 raise ValueError("clamp of NaN is undefined in GLSL.std.450")
221 return (h & 0x8000) | 0x7E00
222 if absh == 0x7C00:
223 return 0 if clamp else (h & 0x8000)
224 # Widening f16 -> f32 is exact, then f32 OpFDiv + omod/clamp, then f16 nearest-even narrowing.
225 r_bits = round_fraction_to_f32(Fraction(1) / f16_to_fraction(h))
226 r_sign = r_bits & 0x80000000
227 if (r_bits & 0x7FFFFFFF) == 0x7F800000:
228 if clamp:
229 return 0 if r_sign else 0x3C00
230 return (r_sign >> 16) | 0x7C00
231 val = f32_to_fraction(r_bits) * scale
232 if clamp:
233 if val <= 0:
234 return 0x0000
235 if val >= 1:
236 return 0x3C00
237 r_f32 = round_fraction_to_f32(val, neg_zero=bool(sign))
238 return round_fraction_to_f16(f32_to_fraction(r_f32), neg_zero=bool(r_f32 & 0x80000000))
239
240
241RCP_F32_HAND_WORKED = (
242 ("pos_one", 0x3F800000, 0x3F800000),
243 ("neg_one", 0xBF800000, 0xBF800000),
244 ("pos_two", 0x40000000, 0x3F000000),
245 ("neg_two", 0xC0000000, 0xBF000000),
246 ("pos_four", 0x40800000, 0x3E800000),
247 ("neg_quarter", 0xBE800000, 0xC0800000),
248 ("pos_2p20", 0x49800000, 0x35800000),
249 ("neg_2pm20", 0xB5800000, 0xC9800000),
250 ("pos_1p5", 0x3FC00000, 0x3F2AAAAB),
251 ("neg_3p0", 0xC0400000, 0xBEAAAAAB),
252 ("pos_0p3", 0x3E99999A, 0x40555555),
253 ("subnorm_2m128_to_inf", 0x00200000, 0x7F800000),
254 ("neg_subnorm_min_to_ninf", 0x80000001, 0xFF800000),
255 ("2p127_to_subnorm", 0x7F000000, 0x00400000),
256 ("pos_inf", 0x7F800000, 0x00000000),
257 ("neg_inf", 0xFF800000, 0x80000000),
258)
259
260RCP_F16_HAND_WORKED = (
261 ("pos_one", H_1P0, H_1P0),
262 ("neg_one", H_NEG_1P0, H_NEG_1P0),
263 ("pos_two", H_2P0, H_0P5),
264 ("neg_two", H_NEG_2P0, H_NEG_0P5),
265 ("pos_four", H_4P0, H_0P25),
266 ("neg_quarter", H_NEG_0P25, H_NEG_4P0),
267 ("pos_1p5", H_1P5, 0x3955),
268 ("pos_3p0", H_3P0, 0x3555),
269 ("neg_3p0", H_NEG_3P0, 0xB555),
270 ("sub_min_overflow", H_SUB_MIN, H_POS_INF),
271 ("neg_sub_min_overflow", H_NEG_SUB_MIN, H_NEG_INF),
272 ("sub_2m16_overflow", H_SUB_2M16, H_POS_INF),
273 ("sub_2m15", H_SUB_2M15, 0x7800),
274 ("sub_max", H_SUB_MAX, 0x7401),
275 ("norm_min", H_NORM_MIN, 0x7400),
276 ("f16_max", H_MAX, 0x0100),
277 ("neg_f16_max", H_NEG_MAX, 0x8100),
278 ("pos_inf", H_POS_INF, H_POS_ZERO),
279 ("neg_inf", H_NEG_INF, H_NEG_ZERO),
280)
281
282
283# -----------------------------------------------------------------------------
284# Translation & Execution Helpers
285# -----------------------------------------------------------------------------
286
287_TMP_DIR = None
288_PS_PATH = None
289_CS_PATH = None
290_CS_FSSM = None
291
292
293def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes:
294 header = bytearray(0x148)
295 struct.pack_into("<4I", header, 0x138, rsrc2, *group)
296 return bytes(header)
297
298
299def setUpModule():
300 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
301 _TMP_DIR = tempfile.TemporaryDirectory()
302 disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
303 fssm_dir = os.path.join(_TMP_DIR.name, "fssm")
304 os.mkdir(disasm_dir)
305 os.mkdir(fssm_dir)
306 _PS_PATH = os.path.join(disasm_dir, "ps_valu_rcp_fdiv.s")
307 _CS_PATH = os.path.join(disasm_dir, "cs_valu_rcp_fdiv.s")
308 _CS_FSSM = os.path.join(fssm_dir, "cs_valu_rcp_fdiv.fssm")
309 with open(os.path.join(_TMP_DIR.name, "ps_valu_rcp_fdiv.dxbc"), "wb") as f:
310 f.write(STUB_DXBC)
311
312
313def tearDownModule():
314 global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM
315 if _TMP_DIR is not None:
316 gc.collect()
317 _TMP_DIR.cleanup()
318 _TMP_DIR = None
319 _PS_PATH = None
320 _CS_PATH = None
321 _CS_FSSM = None
322
323
324def translate_ps(lines: list[str]) -> str:
325 if _TMP_DIR is None:
326 setUpModule()
327 asm = (
328 "; test_valu_rcp_fdiv\n"
329 + "".join(f"\t{ln}\n" for ln in lines)
330 + "\texp mrt0 v0, v0, v0, v0 done vm\n"
331 + "\ts_endpgm\n"
332 )
333 with open(_PS_PATH, "w", encoding="utf-8", newline="") as f:
334 f.write(asm)
335 with warnings.catch_warnings():
336 warnings.simplefilter("ignore", ResourceWarning)
337 spv = rdna2spirv.translate(_PS_PATH)
338 gc.collect()
339 return spv
340
341
342def run_ps_v0(lines: list[str]) -> int:
343 return si.run_fragment(translate_ps(lines))["%out_mrt0"][0]
344
345
346def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int:
347 return run_ps_v0([
348 f"s_mov_b32 s4, {s4:#x}",
349 f"v_mov_b32 v1, {v1:#x}",
350 f"v_mov_b32 v0, {old:#x}",
351 line,
352 ])
353
354
355def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]:
356 if _TMP_DIR is None:
357 setUpModule()
358 with open(_CS_FSSM, "wb") as f:
359 f.write(_make_fssm(0x0088, (group_size, 1, 1)))
360 asm = "; test_cs_valu_rcp_fdiv\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n"
361 with open(_CS_PATH, "w", encoding="utf-8", newline="") as f:
362 f.write(asm)
363 with warnings.catch_warnings():
364 warnings.simplefilter("ignore", ResourceWarning)
365 spv = rdna2spirv.translate(_CS_PATH)
366 gc.collect()
367 return si.run_workgroup(
368 spv, group_size, subgroup_size,
369 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)},
370 push_constants=VSHARP + [0] * 28,
371 memory=memory,
372 )
373
374
375# -----------------------------------------------------------------------------
376# 1. Reference Oracle Self-Tests
377# -----------------------------------------------------------------------------
378
379class OracleSelfTests(unittest.TestCase):
380 def test_hand_worked_rcp_f32_and_f16_match_fraction_oracles(self):
381 for name, x_bits, want in RCP_F32_HAND_WORKED:
382 with self.subTest(kind="f32", name=name):
383 self.assertEqual(ref_rcp_f32(x_bits), want)
384 for name, h_bits, want in RCP_F16_HAND_WORKED:
385 with self.subTest(kind="f16", name=name):
386 self.assertEqual(ref_rcp_f16(h_bits), want)
387
388
389# -----------------------------------------------------------------------------
390# 2. Direct OpFDiv Unit Tests in spirv_mini_interp.py
391# -----------------------------------------------------------------------------
392
393FDIV_HEADER = """\
394OpCapability Shader
395OpMemoryModel Logical GLSL450
396OpEntryPoint Fragment %main "main" %out
397%void = OpTypeVoid
398%fn = OpTypeFunction %void
399%uint = OpTypeInt 32 0
400%float = OpTypeFloat 32
401%v2float = OpTypeVector %float 2
402%_ptr_Output_uint = OpTypePointer Output %uint
403%out = OpVariable %_ptr_Output_uint Output
404%_ptr_PC = OpTypePointer PushConstant %uint
405%pc = OpVariable %_ptr_PC PushConstant
406%c0 = OpConstant %uint 0
407%c1 = OpConstant %uint 1
408%c2 = OpConstant %uint 2
409%c3 = OpConstant %uint 3
410%f0 = OpConstant %float 0
411%f0p5 = OpConstant %float 0.5
412%f1 = OpConstant %float 1
413%f2 = OpConstant %float 2
414%f3 = OpConstant %float 3
415%f4 = OpConstant %float 4
416%f255 = OpConstant %float 255
417%u_neg0 = OpConstant %uint 2147483648
418%u_inf = OpConstant %uint 2139095040
419%u_ninf = OpConstant %uint 4286578688
420%u_qnan = OpConstant %uint 2143289344
421%u_snan = OpConstant %uint 2139095041
422%u_fltmax = OpConstant %uint 2139095039
423%u_nfltmax = OpConstant %uint 4286578687
424%main = OpFunction %void None %fn
425%entry = OpLabel
426%fm0 = OpBitcast %float %u_neg0
427%inf = OpBitcast %float %u_inf
428%ninf = OpBitcast %float %u_ninf
429%qnan = OpBitcast %float %u_qnan
430%snan = OpBitcast %float %u_snan
431%fltmax = OpBitcast %float %u_fltmax
432%nfltmax = OpBitcast %float %u_nfltmax
433%fm2 = OpFNegate %float %f2
434%fm3 = OpFNegate %float %f3
435%fm1 = OpFNegate %float %f1
436"""
437FDIV_FOOTER = "OpReturn\nOpFunctionEnd\n"
438
439
440def run_fdiv_scalar(num: str, den: str) -> int:
441 text = (
442 FDIV_HEADER
443 + f"%r = OpFDiv %float {num} {den}\n"
444 + "%res = OpBitcast %uint %r\n"
445 + "OpStore %out %res\n"
446 + FDIV_FOOTER
447 )
448 return si.run_fragment(text)["%out"][0]
449
450
451def run_fdiv_vec2(n0: str, n1: str, d0: str, d1: str) -> tuple[int, int]:
452 hdr = FDIV_HEADER.replace(
453 'OpEntryPoint Fragment %main "main" %out',
454 'OpEntryPoint Fragment %main "main" %out %out1',
455 ).replace(
456 "%out = OpVariable %_ptr_Output_uint Output",
457 "%out = OpVariable %_ptr_Output_uint Output\n%out1 = OpVariable %_ptr_Output_uint Output",
458 )
459 body = (
460 f"%vn = OpCompositeConstruct %v2float {n0} {n1}\n"
461 + f"%vd = OpCompositeConstruct %v2float {d0} {d1}\n"
462 + "%vr = OpFDiv %v2float %vn %vd\n"
463 + "%r0 = OpCompositeExtract %float %vr 0\n"
464 + "%r1 = OpCompositeExtract %float %vr 1\n"
465 + "%b0 = OpBitcast %uint %r0\n"
466 + "%b1 = OpBitcast %uint %r1\n"
467 + "OpStore %out %b0\n"
468 + "OpStore %out1 %b1\n"
469 )
470 res = si.run_fragment(hdr + body + FDIV_FOOTER)
471 return res["%out"][0], res["%out1"][0]
472
473
474class OpFDivInterpreterTests(unittest.TestCase):
475 def test_scalar_finite_signed_zero_inf_and_overflow(self):
476 cases = (
477 ("%f1", "%f4", f32_bits(0.25)),
478 ("%fm3", "%f2", f32_bits(-1.5)),
479 ("%f3", "%f255", 0x3C40C0C1),
480 # Signed zero dividends keep exact IEEE sign rules.
481 ("%f0", "%f2", 0x00000000),
482 ("%f0", "%fm2", 0x80000000),
483 ("%fm0", "%f2", 0x80000000),
484 ("%fm0", "%fm2", 0x00000000),
485 # Division by +-inf -> +-0.0.
486 ("%f1", "%inf", 0x00000000),
487 ("%fm1", "%inf", 0x80000000),
488 ("%f1", "%ninf", 0x80000000),
489 ("%fm1", "%ninf", 0x00000000),
490 ("%f0", "%ninf", 0x80000000),
491 ("%fm0", "%inf", 0x80000000),
492 ("%fm0", "%ninf", 0x00000000),
493 # +-inf divided by finite non-zero -> +-inf.
494 ("%inf", "%f2", 0x7F800000),
495 ("%inf", "%fm2", 0xFF800000),
496 ("%ninf", "%f2", 0xFF800000),
497 ("%ninf", "%fm2", 0x7F800000),
498 # Binary32 overflow -> +-inf.
499 ("%fltmax", "%f0p5", 0x7F800000),
500 ("%nfltmax", "%f0p5", 0xFF800000),
501 )
502 for num, den, want in cases:
503 with self.subTest(num=num, den=den):
504 self.assertEqual(run_fdiv_scalar(num, den), want)
505
506 def test_scalar_inf_over_inf_and_nan_propagation(self):
507 nan_cases = (
508 ("%inf", "%inf"),
509 ("%inf", "%ninf"),
510 ("%ninf", "%inf"),
511 ("%ninf", "%ninf"),
512 ("%qnan", "%f2"),
513 ("%f2", "%qnan"),
514 ("%qnan", "%inf"),
515 ("%inf", "%qnan"),
516 ("%f0", "%qnan"),
517 ("%snan", "%f2"),
518 ("%f2", "%snan"),
519 )
520 for num, den in nan_cases:
521 with self.subTest(num=num, den=den):
522 got = run_fdiv_scalar(num, den)
523 self.assertTrue(is_f32_nan_bits(got), f"expected NaN for {num}/{den}, got {got:#010x}")
524
525 def test_vector_v2float_division(self):
526 self.assertEqual(run_fdiv_vec2("%f1", "%fm3", "%f4", "%fm2"), (f32_bits(0.25), f32_bits(1.5)))
527 self.assertEqual(run_fdiv_vec2("%f1", "%fm0", "%ninf", "%ninf"), (0x80000000, 0x00000000))
528 g0, g1 = run_fdiv_vec2("%f1", "%inf", "%ninf", "%ninf")
529 self.assertEqual(g0, 0x80000000)
530 self.assertTrue(is_f32_nan_bits(g1), f"expected NaN in lane 1, got {g1:#010x}")
531
532 def test_zero_divisor_and_non_float_are_rejected(self):
533 for num, den in (
534 ("%f1", "%f0"),
535 ("%f1", "%fm0"),
536 ("%fm1", "%f0"),
537 ("%fm1", "%fm0"),
538 ("%f0", "%f0"),
539 ("%fm0", "%fm0"),
540 ("%inf", "%f0"),
541 ("%qnan", "%f0"),
542 ("%qnan", "%fm0"),
543 ):
544 with self.subTest(num=num, den=den):
545 with self.assertRaises(si.UnsupportedConstruct):
546 run_fdiv_scalar(num, den)
547
548 for n0, n1, d0, d1 in (
549 ("%f1", "%f2", "%f0", "%f2"),
550 ("%f1", "%f2", "%f2", "%fm0"),
551 ):
552 with self.subTest(vec=(n0, n1, d0, d1)):
553 with self.assertRaises(si.UnsupportedConstruct):
554 run_fdiv_vec2(n0, n1, d0, d1)
555
556 with self.assertRaises(si.UnsupportedConstruct):
557 si.run_fragment(
558 FDIV_HEADER + "%res = OpFDiv %uint %c2 %c1\nOpStore %out %res\n" + FDIV_FOOTER
559 )
560
561
562# -----------------------------------------------------------------------------
563# 3. End-to-End v_rcp_f32 & v_rcp_iflag_f32 Value Tests
564# -----------------------------------------------------------------------------
565
566class RcpF32AndIflagExecutionTests(unittest.TestCase):
567 OPS = ("v_rcp_f32", "v_rcp_iflag_f32")
568
569 def test_hand_worked_and_edge_values_across_encodings(self):
570 for op in self.OPS:
571 for suffix in ("_e32", "_e64", ""):
572 for name, x_bits, want in RCP_F32_HAND_WORKED:
573 with self.subTest(op=op + suffix, case=name):
574 got = run_op(f"{op}{suffix} v0, v1", x_bits)
575 self.assertEqual(got, want)
576
577 def test_nan_inputs_preserve_nan(self):
578 for op in self.OPS:
579 for suffix in ("_e32", "_e64"):
580 for x_bits in (0x7FC00000, 0xFFC00001, 0x7F800001, 0xFF800001):
581 with self.subTest(op=op + suffix, x=hex(x_bits)):
582 got = run_op(f"{op}{suffix} v0, v1", x_bits)
583 self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}")
584
585 def test_zero_inputs_raise_unsupported_construct(self):
586 for op in self.OPS:
587 for suffix in ("_e32", "_e64"):
588 for x_bits in (0x00000000, 0x80000000):
589 with self.subTest(op=op + suffix, x=hex(x_bits)):
590 with self.assertRaises(si.UnsupportedConstruct):
591 run_op(f"{op}{suffix} v0, v1", x_bits)
592 with self.subTest(op=op, mod="-|0|"):
593 with self.assertRaises(si.UnsupportedConstruct):
594 run_op(f"{op}_e64 v0, -|0|", 0)
595
596 def test_vop3_output_and_source_modifiers(self):
597 cases = (
598 # (insn_suffix_and_src, v1_bits, scale, clamp)
599 ("v1 clamp", f32_bits(0.5), Fraction(1), True),
600 ("v1 clamp", f32_bits(-0.5), Fraction(1), True),
601 ("v1 clamp", f32_bits(4.0), Fraction(1), True),
602 ("v1 mul:2", f32_bits(4.0), Fraction(2), False),
603 ("v1 mul:2", f32_bits(-0.5), Fraction(2), False),
604 ("v1 mul:4", f32_bits(4.0), Fraction(4), False),
605 ("v1 mul:4", f32_bits(-2.0), Fraction(4), False),
606 ("v1 div:2", f32_bits(2.0), Fraction(1, 2), False),
607 ("v1 div:2", f32_bits(-0.5), Fraction(1, 2), False),
608 # omod applies before clamp: 1/0.5 * 0.5 = 1.0; 1/4.0 * 2 = 0.5; 1/0.5 * 2 -> clamped 1.0
609 ("v1 mul:2 clamp", f32_bits(0.5), Fraction(2), True),
610 ("v1 mul:2 clamp", f32_bits(4.0), Fraction(2), True),
611 ("v1 mul:2 clamp", f32_bits(-0.5), Fraction(2), True),
612 ("v1 clamp div:2", f32_bits(0.5), Fraction(1, 2), True),
613 ("v1 clamp div:2", f32_bits(-0.5), Fraction(1, 2), True),
614 )
615 for op in self.OPS:
616 for args, x_bits, scale, clamp in cases:
617 with self.subTest(op=op, args=args, x=hex(x_bits)):
618 got = run_op(f"{op}_e64 v0, {args}", x_bits)
619 want = ref_rcp_f32(x_bits, scale=scale, clamp=clamp)
620 self.assertEqual(got, want)
621
622 # Source modifiers (-v1, |v1|, -|v1|) alone and combined with output modifiers.
623 src_cases = (
624 ("-v1", f32_bits(2.0), f32_bits(-0.5)),
625 ("|v1|", f32_bits(-4.0), f32_bits(0.25)),
626 ("-|v1|", f32_bits(-2.0), f32_bits(-0.5)),
627 ("-|v1|", f32_bits(2.0), f32_bits(-0.5)),
628 ("-v1 clamp", f32_bits(-0.5), f32_bits(1.0)),
629 ("|v1| mul:2", f32_bits(-0.5), f32_bits(4.0)),
630 ("-|v1| mul:2 clamp", f32_bits(0.5), f32_bits(0.0)),
631 ("-|v1| div:2", f32_bits(-0.5), f32_bits(-1.0)),
632 )
633 for op in self.OPS:
634 for args, x_bits, want in src_cases:
635 with self.subTest(op=op, args=args, x=hex(x_bits)):
636 self.assertEqual(run_op(f"{op}_e64 v0, {args}", x_bits), want)
637
638 def test_inline_constants_literals_sgprs_and_aliasing(self):
639 for op in self.OPS:
640 # Inline float constants, VOP3 constant modifiers, and 32-bit literal.
641 self.assertEqual(run_op(f"{op}_e32 v0, 0.5", 0), f32_bits(2.0))
642 self.assertEqual(run_op(f"{op}_e32 v0, -0.5", 0), f32_bits(-2.0))
643 self.assertEqual(run_op(f"{op}_e32 v0, 4.0", 0), f32_bits(0.25))
644 self.assertEqual(run_op(f"{op}_e64 v0, -|2.0|", 0), f32_bits(-0.5))
645 self.assertEqual(run_op(f"{op}_e64 v0, neg(0x3f800000)", 0), f32_bits(-1.0))
646 self.assertEqual(run_op(f"{op}_e32 v0, 0x40400000", 0), 0x3EAAAAAB)
647
648 # SGPR source and modified SGPR source.
649 self.assertEqual(run_op(f"{op}_e32 v0, s4", 0, s4=f32_bits(-4.0)), f32_bits(-0.25))
650 self.assertEqual(run_op(f"{op}_e64 v0, |s4| mul:2", 0, s4=f32_bits(-4.0)), f32_bits(0.5))
651
652 # In-place aliasing: dst == src.
653 self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0x40000000", f"{op}_e32 v0, v0"]), f32_bits(0.5))
654 self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0xc0800000", f"{op}_e64 v0, -v0 mul:4"]), f32_bits(1.0))
655
656
657# -----------------------------------------------------------------------------
658# 4. End-to-End v_rcp_f16 Value Tests
659# -----------------------------------------------------------------------------
660
661class RcpF16ExecutionTests(unittest.TestCase):
662 def test_hand_worked_values_across_e32_e64_and_bare(self):
663 for suffix in ("_e32", "_e64", ""):
664 for name, h_bits, want_half in RCP_F16_HAND_WORKED:
665 with self.subTest(suffix=suffix, case=name):
666 got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h_bits)
667 self.assertEqual(got, merge_half(OLD, want_half, 0))
668
669 def test_nan_preserves_nan_and_other_half(self):
670 for suffix in ("_e32", "_e64"):
671 for h in (H_QNAN, H_NEG_QNAN, H_SNAN):
672 with self.subTest(suffix=suffix, h=hex(h)):
673 got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h)
674 self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000)
675 self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}")
676
677 def test_zero_inputs_raise_unsupported_construct(self):
678 for line, v1 in (
679 ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_POS_ZERO),
680 ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_ZERO),
681 ("v_rcp_f16_e64 v0, v1 op_sel:[1,0]", (H_POS_ZERO << 16) | H_1P0),
682 ("v_rcp_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_ZERO << 16) | H_1P0),
683 ):
684 with self.subTest(line=line, v1=hex(v1)):
685 with self.assertRaises(si.UnsupportedConstruct):
686 run_op(line, v1)
687
688 def test_op_sel_all_combinations(self):
689 # v1 = (hi: -4.0, lo: 0.5) -> rcp(hi) = -0.25, rcp(lo) = 2.0.
690 v1 = (H_NEG_4P0 << 16) | H_0P5
691 for src_hi, dst_hi in itertools.product((0, 1), repeat=2):
692 h_in = H_NEG_4P0 if src_hi else H_0P5
693 line = f"v_rcp_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]"
694 with self.subTest(line=line):
695 self.assertEqual(run_op(line, v1), merge_half(OLD, ref_rcp_f16(h_in), dst_hi))
696
697 def test_vop3_source_and_output_modifiers(self):
698 v1 = (H_NEG_0P5 << 16) | H_4P0
699 self.assertEqual(run_op("v_rcp_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_NEG_0P25, 0))
700 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1))
701 self.assertEqual(run_op("v_rcp_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0))
702
703 # Output modifiers scale first, then clamp to [0.0, 1.0], then pack to f16 keeping the other half.
704 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P5, 0))
705 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_1P0, 0))
706 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 div:2", v1), merge_half(OLD, 0x3000, 0)) # 0.125
707 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] mul:2", v1), merge_half(OLD, H_NEG_4P0, 1))
708 self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1))
709 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,0] mul:2 clamp", v1), merge_half(OLD, H_1P0, 0))
710 self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1] clamp div:2", v1), merge_half(OLD, H_1P0, 1))
711
712 def test_inline_constants_sgpr_and_aliasing(self):
713 self.assertEqual(run_op("v_rcp_f16_e32 v0, 0.5", 0), merge_half(OLD, H_2P0, 0))
714 self.assertEqual(run_op("v_rcp_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_2P0, 0))
715 self.assertEqual(run_op("v_rcp_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0))
716 self.assertEqual(run_op("v_rcp_f16_e64 v0, -|0x4000|", 0), merge_half(OLD, H_NEG_0P5, 0))
717
718 s4 = (H_NEG_4P0 << 16) | H_0P5
719 self.assertEqual(run_op("v_rcp_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0))
720 self.assertEqual(run_op("v_rcp_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_0P25, 1))
721
722 # In-place aliasing: dst == src reading one half and writing the other keeps the original unread half.
723 v0_init = (H_0P5 << 16) | H_4P0
724 self.assertEqual(
725 run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e64 v0, v0 op_sel:[1,0]"]),
726 (H_0P5 << 16) | H_2P0,
727 )
728 self.assertEqual(
729 run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e32 v0, v0"]),
730 (H_0P5 << 16) | H_0P25,
731 )
732
733
734# -----------------------------------------------------------------------------
735# 5. EXEC Masking & Negative Control Tests
736# -----------------------------------------------------------------------------
737
738class RcpExecMaskingTests(unittest.TestCase):
739 def test_single_lane_exec_masking(self):
740 for line in (
741 "v_rcp_f32_e32 v0, v1",
742 "v_rcp_iflag_f32_e32 v0, v1",
743 "v_rcp_f16_e32 v0, v1",
744 "v_rcp_f16_e64 v0, v1 op_sel:[1,1]",
745 ):
746 with self.subTest(line=line):
747 got = run_ps_v0([
748 f"v_mov_b32 v1, {(H_2P0 << 16) | H_4P0:#x}",
749 f"v_mov_b32 v0, {OLD:#x}",
750 "s_mov_b32 exec_lo, 0",
751 line,
752 "s_mov_b32 exec_lo, 1",
753 ])
754 self.assertEqual(got, OLD)
755
756 # Disabled ops leave v0 unchanged; re-enabling EXEC executes the subsequent op.
757 got_toggled = run_ps_v0([
758 f"v_mov_b32 v1, {(H_0P5 << 16) | H_4P0:#x}",
759 f"v_mov_b32 v0, {OLD:#x}",
760 "s_mov_b32 exec_lo, 0",
761 "v_rcp_f16_e64 v0, v1 op_sel:[0,0]",
762 "v_rcp_f16_e64 v0, v1 op_sel:[1,1]",
763 "s_mov_b32 exec_lo, 1",
764 "v_rcp_f16_e64 v0, v1 op_sel:[1,0]",
765 ])
766 self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0))
767
768 def test_multilane_compute_exec_masking(self):
769 # 4 lanes in wave32: disable odd lanes (lane & 1 != 0) before executing v_rcp_*.
770 # Active even lanes (0, 2) compute the reciprocal; inactive odd lanes (1, 3) keep OLD.
771 cases = (
772 ("v_rcp_f32_e32 v3, v2", f32_bits(4.0), f32_bits(0.25)),
773 ("v_rcp_iflag_f32_e64 v3, v2 mul:2", f32_bits(4.0), f32_bits(0.5)),
774 ("v_rcp_f16_e64 v3, v2 op_sel:[1,1]", (H_0P5 << 16) | H_4P0, merge_half(OLD, H_2P0, 1)),
775 )
776 for insn, src_word, active_want in cases:
777 with self.subTest(insn=insn):
778 mem = {}
779 lines = [
780 "v_lshlrev_b32 v4, 2, v0", # lane byte offset = lane * 4
781 f"v_mov_b32 v2, {src_word:#x}",
782 f"v_mov_b32 v3, {OLD:#x}",
783 "v_and_b32 v5, v0, 1",
784 "v_cmpx_eq_u32 v5, 0", # keep even lanes active
785 insn,
786 "s_mov_b32 exec_lo, -1",
787 "buffer_store_dword v3, v4, s[0:3], 0 offen",
788 ]
789 run_cs(lines, group_size=4, subgroup_size=32, memory=mem)
790 self.assertEqual(
791 [mem[4 * i] for i in range(4)],
792 [active_want, OLD, active_want, OLD],
793 )
794
795
796class NegativeControlTests(unittest.TestCase):
797 def test_sabotaged_spirv_is_detected(self):
798 cases = (
799 ("v_rcp_f32_e32 v0, v1", f32_bits(4.0), f32_bits(0.25)),
800 ("v_rcp_iflag_f32_e64 v0, v1 mul:2", f32_bits(4.0), f32_bits(0.5)),
801 ("v_rcp_f16_e64 v0, v1 op_sel:[0,1]", (H_1P0 << 16) | H_4P0, merge_half(OLD, H_0P25, 1)),
802 )
803 for line, v1_bits, want in cases:
804 with self.subTest(line=line):
805 spv = translate_ps([f"v_mov_b32 v0, {OLD:#x}", f"v_mov_b32 v1, {v1_bits:#x}", line])
806 self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want)
807 bad, n = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1)
808 self.assertEqual(n, 1)
809 self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want)
810
811 # Sabotaging FClamp on v_rcp_iflag_f32_e64 clamp changes clamped 1/0.5 = 2.0 -> 1.0.
812 spv_clamp = translate_ps([
813 f"v_mov_b32 v0, {OLD:#x}",
814 f"v_mov_b32 v1, {f32_bits(0.5):#x}",
815 "v_rcp_iflag_f32_e64 v0, v1 clamp",
816 ])
817 self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], f32_bits(1.0))
818 bad_clamp, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv_clamp)
819 self.assertEqual(n, 1)
820 self.assertEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], f32_bits(2.0))
821
822
823if __name__ == "__main__":
824 unittest.main()
diff --git a/tests/test_anim_rigs.py b/tests/test_anim_rigs.py
new file mode 100644
index 000000000..7ae94fb61
--- /dev/null
+++ b/tests/test_anim_rigs.py
@@ -0,0 +1,134 @@
1"""Synthetic tests for tools/anim_rigs.py.
2
3 python -I tests/test_anim_rigs.py
4
5Every byte here is built by the test: a fake RPF9 data area with two rig dictionaries and one clip dictionary
6(the builders of tests/test_anim_clips.py), and a small rig-set JSON in the shape `anim_index.py --rigs` writes.
7No game file or game asset name is used.
8"""
9import json
10import os
11import struct
12import subprocess
13import sys
14import tempfile
15import unittest
16
17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18TOOL = os.path.join(ROOT, "tools", "anim_rigs.py")
19sys.path.insert(0, os.path.join(ROOT, "tools"))
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21
22import anim_rigs # noqa: E402
23from anim_index import joaat32 # noqa: E402
24from test_anim_clips import Page, two_sequence_dictionary, write_rpf # noqa: E402
25
26KIND_A, KIND_B = joaat32("kind_a"), joaat32("kind_b")
27
28
29def rig_block(page, tables, version=2):
30 """`RIG` + version, u32 length, 8 filler bytes, then each table {kind, 0xC + 8n, n, word} + n items."""
31 body = bytearray(b"\x11" * 8)
32 for kind, items in tables:
33 body += struct.pack("<4I", kind, 0xC + 8 * len(items), len(items), 0x0300)
34 body += b"".join(struct.pack("<II", h, 0x0300 + i) for i, h in enumerate(items))
35 return page.alloc(MAGIC_V(version) + struct.pack("<I", len(body)) + bytes(body))
36
37
38def MAGIC_V(version):
39 return b"RIG" + bytes([version])
40
41
42def rig_dictionary(name, rigs):
43 """rigs: {rig path: [(kind, [item hashes])]}. The root's own +0x70 holds `RIG` + version like the real ones."""
44 p = Page()
45 pm = p.alloc(bytes(16))
46 p.b[pm + 8], p.b[pm + 9] = 1, 0
47 p.ptr(8, pm)
48 p.string(0x38, name)
49 struct.pack_into("<I", p.b, 0x68, joaat32(name))
50 p.b[0x70:0x74] = MAGIC_V(2)
51 items = []
52 for path, tables in rigs.items():
53 value = p.alloc(bytes(0x90))
54 p.ptr(value + 0x20, rig_block(p, tables))
55 items.append((joaat32(path), value))
56 p.atmap(0x48, items)
57 return bytes(p.b)
58
59
60RIGS = {
61 "src@one": {"anim/rig/x/a": [(KIND_A, [1, 2, 3])], "anim/rig/x/b": [(KIND_A, [4]), (KIND_B, [5, 6])]},
62 "src@two": {"anim/rig/y/c": [(KIND_B, [7, 8])], "anim/rig/y/unused": [(KIND_A, [9])]},
63}
64RIGSETS = {"rbf0": {"rigsets": [
65 {"key": "anim/rigset/ped/p", "entries": [
66 {"source": "src@one", "rig": "anim/rig/x/a", "group": "pose"},
67 {"source": "src@one", "rig": "anim/rig/x/b", "group": "deformation"},
68 {"source": "src@two", "rig": "anim/rig/y/c", "group": "facial"}]},
69 {"key": "anim/rigset/object/o", "entries": [
70 {"source": "src@two", "rig": "anim/rig/x/a", "group": "pose"}, # rig is in the other dictionary
71 {"source": "src@none", "rig": "anim/rig/z/q", "group": "pose"}, # no dictionary has this name
72 {"source": "src@one", "rig": "anim/rig/x/missing", "group": "pose"}]},
73]}}
74
75
76class RigDictionaryTest(unittest.TestCase):
77 def setUp(self):
78 self.tmp = tempfile.TemporaryDirectory()
79 self.rpf = os.path.join(self.tmp.name, "synthetic.rpf")
80 self.rigs = os.path.join(self.tmp.name, "rigs.json")
81 with open(self.rigs, "w", encoding="utf-8") as f:
82 json.dump(RIGSETS, f)
83 streams = [rig_dictionary(name, rigs) for name, rigs in RIGS.items()] + [two_sequence_dictionary()]
84 self.offsets = write_rpf(self.rpf, streams)
85
86 def tearDown(self):
87 self.tmp.cleanup()
88
89 def test_scan_reads_only_rig_dictionaries(self):
90 dicts, summary = anim_rigs.scan(self.rpf)
91 self.assertEqual([d["name"] for d in dicts], ["src@one", "src@two"])
92 self.assertEqual([d["offset"] for d in dicts], self.offsets[:2])
93 c = summary["counts"]
94 self.assertEqual((c["rig_dictionaries"], c["rig_dictionary_hash_matches_name"], c["entries"],
95 c["entries_with_block"], c["entries_key_high_zero"], c["block_version:2"]), (2, 2, 4, 4, 4, 4))
96 self.assertEqual((c["tables"], c[f"table_kind:0x{KIND_A:08x}"], c[f"table_kind:0x{KIND_B:08x}"]), (5, 3, 2))
97 self.assertEqual((c[f"table_items:0x{KIND_A:08x}"], c[f"table_items:0x{KIND_B:08x}"]), (5, 4))
98
99 def test_entry_keys_and_tables(self):
100 dicts, _ = anim_rigs.scan(self.rpf)
101 one = {e["key"]: e["tables"] for e in dicts[0]["entries"]}
102 self.assertEqual(one, {joaat32("anim/rig/x/a"): [(KIND_A, 3)],
103 joaat32("anim/rig/x/b"): [(KIND_A, 1), (KIND_B, 2)]})
104
105 def test_join_rbf0(self):
106 dicts, _ = anim_rigs.scan(self.rpf)
107 self.assertEqual(anim_rigs.join_rbf0(dicts, RIGSETS), {
108 "distinct_rigs": 6, "in_another_dictionary": 1, "key_missing": 1, "keys": 4,
109 "keys_named_by_an_entry": 3, "no_dictionary_named_source": 1, "resolved": 3})
110
111 def test_bad_block_is_reported_not_raised(self):
112 page = bytearray(rig_dictionary("src@bad", {"anim/rig/b": [(KIND_A, [1])]}))
113 at = page.rfind(b"RIG\x02")
114 page[at:at + 3] = b"XYZ"
115 rpf = os.path.join(self.tmp.name, "bad.rpf")
116 write_rpf(rpf, [bytes(page)])
117 dicts, summary = anim_rigs.scan(rpf)
118 self.assertEqual(summary["counts"]["rig_dictionaries_unparsed"], 1)
119 self.assertIn("no RIG block", dicts[0]["error"])
120
121 def test_cli_writes_counts_only(self):
122 out = os.path.join(self.tmp.name, "out.json")
123 r = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--rigs", self.rigs],
124 capture_output=True, text=True)
125 self.assertEqual(r.returncode, 0, r.stderr)
126 with open(out, encoding="utf-8") as f:
127 doc = json.load(f)
128 self.assertEqual(doc["summary"]["rbf0_join"]["resolved"], 3)
129 self.assertEqual([row["entries"] for row in doc["rig_dictionaries"]], [2, 2])
130 self.assertNotIn("tables", json.dumps(doc["rig_dictionaries"]))
131
132
133if __name__ == "__main__":
134 unittest.main()
diff --git a/tests/test_awc_names.py b/tests/test_awc_names.py
index b73cacc86..766cdd12d 100644
--- a/tests/test_awc_names.py
+++ b/tests/test_awc_names.py
@@ -188,6 +188,21 @@ class TestCli(unittest.TestCase):
188 with open(json_out, encoding="utf-8") as fh: 188 with open(json_out, encoding="utf-8") as fh:
189 self.assertEqual(json.load(fh)["summary"]["banks"]["streams"], 3) 189 self.assertEqual(json.load(fh)["summary"]["banks"]["streams"], 3)
190 190
191 def test_rejects_output_aliasing_conversation(self):
192 with tempfile.TemporaryDirectory() as tmp:
193 bank = write(os.path.join(tmp, "one.awc"), make_bank(["zz_rootau_abcd_01"]))
194 original = b"ZZ_ROOTAU_ABCD\x00ZZ_A\x00"
195 conv = write(os.path.join(tmp, "c.pso"), original)
196 alias = os.path.join(tmp, ".", "c.pso")
197 err = io.StringIO()
198 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
199 with self.assertRaises(SystemExit) as cm:
200 A.main([bank, "--conversations", conv, "--out", alias])
201 self.assertEqual(cm.exception.code, 2)
202 self.assertIn("--out must not overwrite an input", err.getvalue())
203 with open(conv, "rb") as f:
204 self.assertEqual(f.read(), original)
205
191 def test_hashdict_json_words(self): 206 def test_hashdict_json_words(self):
192 with tempfile.TemporaryDirectory() as tmp: 207 with tempfile.TemporaryDirectory() as tmp:
193 path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"})) 208 path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"}))
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py
index 76b26ff0c..aebdd0fd8 100644
--- a/tests/test_awc_opus.py
+++ b/tests/test_awc_opus.py
@@ -393,8 +393,9 @@ class ExportBankTest(unittest.TestCase):
393 self.assertEqual(last["serial"], 3) 393 self.assertEqual(last["serial"], 3)
394 394
395 def test_stereo_plain_stream_length_is_per_channel(self): 395 def test_stereo_plain_stream_length_is_per_channel(self):
396 # A stereo format tag stores interleaved samples. Three 960-frame stereo packets carry 396 # A stereo format tag stores interleaved samples: 3840 counts = 1920 frames per channel.
397 # 2880 frames per channel; the declared 3840 is twice the real per-channel length. 397 # Three 960-frame packets carry 2880 frames per channel, so the declared 1920 trims
398 # 960 frames of payload; the point is the halving, not a realistic stream length.
398 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel 399 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
399 opus = bytearray(3 * 2048) 400 opus = bytearray(3 * 2048)
400 for block in range(3): 401 for block in range(3):
@@ -414,8 +415,8 @@ class ExportBankTest(unittest.TestCase):
414 415
415 def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): 416 def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self):
416 # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz 417 # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz
417 # source rate. Scaling by 48000/32000 would make the length 4320, so the last granule 418 # source rate. Scaling by 48000/32000 would make the target 4320, above the payload, so
418 # would stay at 312 + 3840 and the padding would not be trimmed. 419 # the old code kept all 3840 packet frames (granule 3840, 3528 after the pre-skip).
419 packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames 420 packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames
420 opus = bytearray(4 * 2048) 421 opus = bytearray(4 * 2048)
421 for block in range(4): 422 for block in range(4):
@@ -431,12 +432,13 @@ class ExportBankTest(unittest.TestCase):
431 pages = parse_ogg_pages(f.read()) 432 pages = parse_ogg_pages(f.read())
432 self.assertEqual(pages[-1]["granule"], 312 + 2880) 433 self.assertEqual(pages[-1]["granule"], 312 + 2880)
433 434
434 def test_format_block_per_channel_frame_count_is_used(self): 435 def test_inconsistent_format_frame_count_falls_back(self):
435 # +0x0C is the per-channel Opus frame count and wins over dividing the +0 count: 436 # +0x0C is authoritative only when it agrees with the interleaved +0 count:
436 # 9999 interleaved samples / 2 would be 4999 frames and would not trim the padding. 437 # 1920 * 2 != 9999, so the block is malformed and +0 / channels (4999) is used
438 # instead of silently truncating the real audio.
437 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel 439 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
438 opus = bytearray(3 * 2048) 440 opus = bytearray(6 * 2048)
439 for block in range(3): 441 for block in range(6):
440 struct.pack_into("<H", opus, block * 2048, len(packet)) 442 struct.pack_into("<H", opus, block * 2048, len(packet))
441 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet 443 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet
442 fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) 444 fmt = bytearray(format_block(9999, 48000, 0x0B, 2))
@@ -449,8 +451,69 @@ class ExportBankTest(unittest.TestCase):
449 awc.export_bank(path, self.out) 451 awc.export_bank(path, self.out)
450 with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: 452 with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f:
451 pages = parse_ogg_pages(f.read()) 453 pages = parse_ogg_pages(f.read())
454 self.assertEqual(pages[-1]["granule"], 312 + 4999)
455
456 def test_consistent_format_frame_count_is_used(self):
457 # 3840 interleaved stereo samples = 1920 per channel, and +0x0C agrees.
458 packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel
459 opus = bytearray(3 * 2048)
460 for block in range(3):
461 struct.pack_into("<H", opus, block * 2048, len(packet))
462 opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet
463 fmt = bytearray(format_block(3840, 48000, 0x0B, 2))
464 struct.pack_into("<I", fmt, 12, 1920)
465 bank = build_bank([(12, bytes(fmt), bytes(opus))])
466 path = os.path.join(self.tmp.name, "frames_ok.awc")
467 with open(path, "wb") as f:
468 f.write(bank)
469
470 awc.export_bank(path, self.out)
471 with open(os.path.join(self.out, "frames_ok", "0000000C.ogg"), "rb") as f:
472 pages = parse_ogg_pages(f.read())
452 self.assertEqual(pages[-1]["granule"], 312 + 1920) 473 self.assertEqual(pages[-1]["granule"], 312 + 1920)
453 474
475 def test_eos_page_is_emitted_at_the_trim_point(self):
476 # 27 packets of 160 bytes / 960 frames: the 26th packet crosses the target
477 # (312 + 24000 = 24312) and would otherwise flush a full page first. The EOS
478 # page must carry the reaching packet and drop the 27th padding packet, not
479 # emit a later page whose granule is smaller than the previous one.
480 packet = bytes([0x08]) + bytes(159) # SILK 20 ms, 960 frames
481 packets = [packet] * 27
482 path = os.path.join(self.tmp.name, "trim.ogg")
483 awc.write_ogg_opus(path, packets, 1, 21, 24000)
484 with open(path, "rb") as f:
485 pages = parse_ogg_pages(f.read())
486 audio = pages[2:]
487 granules = [p["granule"] for p in audio]
488 self.assertEqual(granules, sorted(granules))
489 self.assertEqual(audio[-1]["granule"], 312 + 24000)
490 self.assertEqual(audio[-1]["flags"] & 0x04, 0x04)
491 self.assertEqual(sum(1 for p in audio for value in p["lacing"] if value < 255), 26)
492
493 def test_pre_skip_larger_than_the_stream_is_clamped(self):
494 # Six 960-frame packets are 5760 samples; a pre-skip of 65535 would put the
495 # EOS granule below the pre-skip and make the stream undecodable.
496 packet = bytes([0x08])
497 packets = [packet] * 6
498 path = os.path.join(self.tmp.name, "preskip.ogg")
499 awc.write_ogg_opus(path, packets, 1, 23, 4800, pre_skip=65535)
500 with open(path, "rb") as f:
501 pages = parse_ogg_pages(f.read())
502 self.assertEqual(struct.unpack_from("<H", pages[0]["body"], 10)[0], 5760)
503 self.assertGreaterEqual(pages[-1]["granule"], 5760)
504 with self.assertRaises(ValueError):
505 awc.write_ogg_opus(path, packets, 1, 24, 4800, pre_skip=65536)
506
507 def test_empty_packet_list_writes_an_eos_page(self):
508 # No audio packets is still a valid empty stream: the EOS flag must be present.
509 path = os.path.join(self.tmp.name, "empty.ogg")
510 self.assertEqual(awc.write_ogg_opus(path, [], 1, 25, 0), 0)
511 with open(path, "rb") as f:
512 pages = parse_ogg_pages(f.read())
513 self.assertEqual(len(pages), 3)
514 self.assertEqual(pages[-1]["flags"] & 0x04, 0x04)
515 self.assertEqual(pages[-1]["granule"], 0)
516
454 def test_cli_pre_skip_override(self): 517 def test_cli_pre_skip_override(self):
455 bank, _, _ = self.make_bank() 518 bank, _, _ = self.make_bank()
456 subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], 519 subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"],
diff --git a/tests/test_bink_names.py b/tests/test_bink_names.py
index 1a52eeb54..a78eb28e3 100644
--- a/tests/test_bink_names.py
+++ b/tests/test_bink_names.py
@@ -194,6 +194,18 @@ class TestLoadPins(unittest.TestCase):
194 194
195 195
196class TestCli(unittest.TestCase): 196class TestCli(unittest.TestCase):
197 def test_rejects_negative_max_skip(self):
198 with tempfile.TemporaryDirectory() as tmp:
199 xml = os.path.join(tmp, "list.xml")
200 with open(xml, "w", encoding="utf-8") as f:
201 f.write(mount_xml([]))
202 err = io.StringIO()
203 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
204 with self.assertRaises(SystemExit) as cm:
205 names_mod.main([tmp, "--mount", xml, "--max-skip", "-1"])
206 self.assertEqual(cm.exception.code, 2)
207 self.assertIn("--max-skip must be 0 or more", err.getvalue())
208
197 def test_archive_end_to_end(self): 209 def test_archive_end_to_end(self):
198 shapes = [(1280, 720, 40), (1920, 1080, 50), (512, 512, 15)] 210 shapes = [(1280, 720, 40), (1920, 1080, 50), (512, 512, 15)]
199 with tempfile.TemporaryDirectory() as tmp: 211 with tempfile.TemporaryDirectory() as tmp:
diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py
index 93457d1c7..75d938fdc 100644
--- a/tests/test_build_runtime_fallback.py
+++ b/tests/test_build_runtime_fallback.py
@@ -41,6 +41,11 @@ class FallbackBuildsTheHarnesses(unittest.TestCase):
41 with self.subTest(source=name): 41 with self.subTest(source=name):
42 self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) 42 self.assertTrue((ROOT / "runtime" / "test" / name).is_file())
43 43
44 def test_build_cmd_sets_utf8_codepage_for_ninja_showincludes(self):
45 text = SCRIPT.read_text(encoding="utf-8")
46 self.assertIn("chcp 65001 >nul", text)
47 self.assertLess(text.index("chcp 65001 >nul"), text.index('call `"$vcvars`"'))
48
44 49
45if __name__ == "__main__": 50if __name__ == "__main__":
46 unittest.main() 51 unittest.main()
diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py
index cfaad282f..980c11cec 100644
--- a/tests/test_ctest_registration.py
+++ b/tests/test_ctest_registration.py
@@ -63,6 +63,38 @@ class CTestRegistrationTest(unittest.TestCase):
63 self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}") 63 self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}")
64 self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77") 64 self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77")
65 65
66 def test_whole_test_skips_return_the_skip_code(self):
67 # A test registered with SKIP_RETURN_CODE 77 that prints SKIP and returns 0 is counted as passed although it
68 # checked nothing: bink_audio_test did that for a movie without audio tracks after #1580.
69 wrong = whole_test_skips_not_77(self.cmake, ROOT / "runtime")
70 self.assertEqual(wrong, [], f"SKIP followed by a return code other than 77: {wrong}")
71
72
73def whole_test_skips_not_77(cmake_text, runtime_dir):
74 """[(source:line, code)] for a SKIP print directly followed by `return N;` (N != 77) in the sources of a test
75 registered with SKIP_RETURN_CODE 77. A SKIP print with no return right after it skips one section, not the test."""
76 skip_tests = set(re.findall(r"set_tests_properties\(\s*([A-Za-z0-9_]+)\s+PROPERTIES[^)]*SKIP_RETURN_CODE\s+77",
77 cmake_text))
78 commands = dict(re.findall(r"add_test\(\s*NAME\s+([A-Za-z0-9_]+)\s+COMMAND\s+\"?([A-Za-z0-9_]+)", cmake_text))
79 wrong = []
80 for test in sorted(skip_tests):
81 exe = commands.get(test)
82 m = exe and re.search(r"add_executable\(\s*" + re.escape(exe) + r"\b([^)]*)\)", cmake_text)
83 if not m:
84 continue
85 for src in re.findall(r"(test/[A-Za-z0-9_./]+\.cpp)", m.group(1)):
86 path = runtime_dir / src
87 if not path.is_file():
88 continue
89 lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
90 for i, line in enumerate(lines):
91 if not re.search(r'(printf|puts)\(\s*"SKIP', line):
92 continue
93 after = re.match(r"\s*return\s+(\w+)\s*;", lines[i + 1]) if i + 1 < len(lines) else None
94 if after and after.group(1) != "77":
95 wrong.append((f"{src}:{i + 2}", after.group(1)))
96 return wrong
97
66 98
67if __name__ == "__main__": 99if __name__ == "__main__":
68 unittest.main() 100 unittest.main()
diff --git a/tests/test_d16_format_probe.py b/tests/test_d16_format_probe.py
new file mode 100644
index 000000000..320116d6d
--- /dev/null
+++ b/tests/test_d16_format_probe.py
@@ -0,0 +1,222 @@
1"""tools/d16_format_probe.py: the candidate rules, the GFX10 descriptor, what each kernel stages and loads, the
2comparison and its exit codes (through a fake oracle that plays the GPU), and the exit-77 contract. The last class
3runs on the hardware when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard
4library only."""
5import io
6import json
7import os
8from contextlib import redirect_stdout
9from pathlib import Path
10import re
11import subprocess
12import sys
13import tempfile
14import unittest
15from unittest import mock
16
17TOOLS = Path(__file__).resolve().parents[1] / "tools"
18sys.path.insert(0, str(TOOLS))
19import d16_format_probe as pr # noqa: E402
20from hw_oracle import asm, runner # noqa: E402
21
22
23class Rules(unittest.TestCase):
24 def test_self_test(self):
25 with redirect_stdout(io.StringIO()):
26 self.assertEqual(pr.self_test(), 0)
27
28 def test_the_489_counts_in_docs_design(self):
29 # docs/design.md ("d16 and f16 format narrowing"): with RTZ narrowing 123 of 256 UNORM8, 31,742 of 65,536
30 # UNORM16 and 110 of 256 SNORM8 values came out 1 ulp low
31 self.assertEqual(pr.rte_rtz_disagreements("unorm", 8), 123)
32 self.assertEqual(pr.rte_rtz_disagreements("snorm", 8), 110)
33 self.assertEqual(pr.rte_rtz_disagreements("unorm", 16), 31742)
34
35 def test_only_four_16_bit_values_separate_one_rounding_from_two(self):
36 split = {(k, v) for k in ("unorm", "snorm") for v in range(65536)
37 if pr.models16(k, 16, v)["rte"] != pr.models16(k, 16, v)["f32_rte"]}
38 self.assertEqual(split, {("unorm", 0xFFAF), ("unorm", 0xFFEF), ("snorm", 0x7FF7), ("snorm", 0x8009)})
39
40 def test_8_and_10_bit_formats_only_tell_rte_from_rtz(self):
41 for kind, n in (("unorm", 8), ("snorm", 8), ("unorm", 10)):
42 for v in range(1 << n):
43 m = pr.models16(kind, n, v)
44 self.assertEqual(len({m["f32_rte"], m["rte"], m["mul_rte"], m["f32_rte_flush"]}), 1, (kind, v))
45
46 def test_snorm_minimum_is_minus_one_and_f32_decode_is_exact(self):
47 self.assertEqual(pr.models16("snorm", 8, 0x80)["f32_rte"], 0xBC00)
48 self.assertEqual(pr.models16("snorm", 8, 0x81)["f32_rte"], 0xBC00)
49 self.assertEqual(pr.models32("unorm", 16, 0xFFFF)["f32_rte"], 0x3F800000)
50 self.assertEqual(pr.models32("unorm", 8, 0x80)["f32_rte"], 0x3F008081) # 128 / 255
51
52
53class Kernels(unittest.TestCase):
54 def test_descriptor_word3(self):
55 w = pr.descriptor_word3(8)
56 self.assertEqual([w & 7, w >> 3 & 7, w >> 6 & 7, w >> 9 & 7], [4, 5, 6, 7])
57 self.assertEqual((w >> 12 & 0x7F, w >> 24 & 1, w >> 28 & 3, w >> 30), (8, 1, 3, 0))
58
59 def test_every_value_is_staged_once(self):
60 for fmt, (_, _, n) in pr.FORMATS.items():
61 seen = []
62 for inst, base in pr.jobs(fmt):
63 if inst != "buffer_d16":
64 continue
65 self.assertEqual(pr.kernel_lines(inst, fmt, base)[0], f"v_add_nc_u32 v1, 0x{base:x}, v0")
66 seen += [(base + t) & ((1 << n) - 1) for t in range(min(pr.THREADS, (1 << n) - base))]
67 self.assertEqual(seen, list(range(1 << n)), fmt)
68
69 def test_mtbuf_names_the_format_and_mubuf_takes_it_from_the_descriptor(self):
70 lines = pr.kernel_lines("tbuffer_d16", "snorm16", 0)
71 self.assertIn("format:8 offen glc dlc", lines[10])
72 self.assertTrue(pr.kernel_lines("buffer_d16", "snorm16", 0)[10].startswith("buffer_load_format_d16_x"))
73 self.assertIn(f"s_mov_b32 s11, 0x{pr.descriptor_word3(8):x}", lines)
74
75 def test_kernels_assemble_for_rdna2(self):
76 try:
77 clang = runner.find_clang()
78 except runner.Unavailable as e:
79 self.skipTest(str(e))
80 kernels = [asm.Kernel(pr.kernel_lines(inst, fmt, 0), 32, pr.THREADS, pr.WORDS, raw=True, vgprs=8, sgprs=16)
81 for fmt in pr.FORMATS for inst in pr.INSTS]
82 text, names, _ = asm.module_text(kernels, "gfx1031", wave=32)
83 with tempfile.TemporaryDirectory() as d:
84 s = Path(d) / "k.s"
85 s.write_text(text, encoding="utf-8")
86 r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1031", "-c", str(s), "-o",
87 str(Path(d) / "k.o")], capture_output=True, text=True)
88 self.assertEqual(r.returncode, 0, r.stderr[:800])
89 self.assertIn("global_store_dword v4, v3, s[2:3]", text)
90 self.assertIn("s_waitcnt_vscnt null, 0x0", text)
91
92
93class FakeOracle:
94 """Plays the GPU: reads each kernel's base, format code and load, and answers with a rule's bits."""
95 arch = "gfx1031"
96 device = "fake gfx1031"
97
98 def __init__(self, rule="rte", clobber_hi=False, wave64_off=None):
99 self.rule, self.clobber_hi, self.wave64_off = rule, clobber_hi, wave64_off
100
101 def run(self, kernels, words=4):
102 code_of = {c: (f, k, n) for f, (c, k, n) in pr.FORMATS.items()}
103 out = []
104 for k in kernels:
105 base = int(re.search(r"0x([0-9a-f]+)", k.lines[0]).group(1), 16)
106 w3 = int(next(ln for ln in k.lines if ln.startswith("s_mov_b32 s11")).split("0x")[1], 16)
107 fmt, kind, n = code_of[w3 >> 12 & 0x7F]
108 load = k.lines[10]
109 staged = [(base + t) & ((1 << n) - 1) for t in range(pr.THREADS)]
110 res = []
111 for v in staged:
112 if kind == "f16":
113 bits = v
114 elif load.startswith("buffer_load_format_x"):
115 res.append(pr.models32(kind, n, v)["f32_rte"])
116 continue
117 else:
118 bits = pr.models16(kind, n, v)[self.rule]
119 if self.wave64_off is not None and k.wave == 64 and v == self.wave64_off:
120 bits ^= 1
121 hi = 0 if self.clobber_hi else pr.HI_SEED
122 res.append(hi | bits)
123 out.append(staged + res)
124 return out
125
126 def close(self):
127 pass
128
129
130def run_main(oracle, *args):
131 buf = io.StringIO()
132 with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf):
133 rc = pr.main(["--formats", "unorm8,float16", *args])
134 return rc, buf.getvalue()
135
136
137class Compare(unittest.TestCase):
138 def test_the_translators_rule_matches_everywhere(self):
139 rc, out = run_main(FakeOracle())
140 self.assertEqual(rc, 0, out)
141 self.assertIn("off the rule 0", out)
142 self.assertIn("own bits 65536/65536", out)
143
144 def test_double_rounding_hardware_shows_the_four_halfway_values(self):
145 buf = io.StringIO()
146 with mock.patch.object(runner, "open_oracle", return_value=FakeOracle("f32_rte")), redirect_stdout(buf):
147 rc = pr.main(["--formats", "unorm16,snorm16", "--waves", "32"])
148 self.assertEqual(rc, 0, buf.getvalue())
149 self.assertEqual(buf.getvalue().count("off the rule 2"), 4) # MUBUF and MTBUF, two formats
150 self.assertIn("value 0xffef: hw 0x3c00, rule 0x3bff", buf.getvalue())
151
152 def test_rtz_hardware_is_a_finding_not_a_failure(self):
153 with tempfile.TemporaryDirectory() as d:
154 j = os.path.join(d, "r.json")
155 rc, out = run_main(FakeOracle("f32_rtz"), "--json", j)
156 with open(j, encoding="utf-8") as f:
157 rep = json.load(f)
158 self.assertEqual(rc, 0, out)
159 d16 = rep["formats"]["unorm8"]["insts"]["buffer_d16"]
160 self.assertEqual(d16["off_rule"], 123)
161 self.assertEqual(d16["match"]["f32_rtz"], 256)
162 self.assertIn("f32_rtz", d16["first_off"][0]["fits"])
163
164 def test_a_wave_difference_exits_1(self):
165 rc, out = run_main(FakeOracle(wave64_off=9))
166 self.assertEqual(rc, 1, out)
167
168 def test_a_clobbered_high_half_is_a_harness_error(self):
169 rc, out = run_main(FakeOracle(clobber_hi=True))
170 self.assertEqual(rc, 2, out)
171 self.assertIn("high half", out)
172
173 def test_not_gfx10_exits_77(self):
174 o = FakeOracle()
175 o.arch = "gfx1150"
176 rc, out = run_main(o)
177 self.assertEqual(rc, 77, out)
178
179
180class Cli(unittest.TestCase):
181 def test_exits_77_without_the_tools(self):
182 env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="")
183 r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm8"],
184 capture_output=True, text=True, env=env)
185 self.assertEqual(r.returncode, 77, r.stdout + r.stderr)
186 self.assertIn("unavailable", r.stdout)
187
188 def test_unknown_format_is_a_usage_error(self):
189 r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm12"],
190 capture_output=True, text=True)
191 self.assertEqual(r.returncode, 2)
192 self.assertIn("unorm12", r.stderr)
193
194
195class OnHardware(unittest.TestCase):
196 @classmethod
197 def setUpClass(cls):
198 try:
199 cls.oracle = runner.open_oracle()
200 except runner.Unavailable as e:
201 raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None
202 if asm.family(cls.oracle.arch) != "gfx10":
203 cls.oracle.close()
204 raise unittest.SkipTest(f"{cls.oracle.arch} is not GFX10")
205
206 @classmethod
207 def tearDownClass(cls):
208 cls.oracle.close()
209
210 def test_unorm8_controls_hold_and_both_wave_sizes_agree(self):
211 w32 = pr.sweep(self.oracle, "unorm8", 32)
212 w64 = pr.sweep(self.oracle, "unorm8", 64)
213 self.assertEqual(w32, w64)
214 res = pr.classify("unorm8", w32)
215 self.assertEqual(res["control"], [])
216 self.assertEqual(w32["buffer_d16"][255] & 0xFFFF, 0x3C00)
217 self.assertEqual(w32["buffer_d16"][0] & 0xFFFF, 0)
218 self.assertEqual(w32["buffer_f32"][255], 0x3F800000)
219
220
221if __name__ == "__main__":
222 unittest.main()
diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py
index 536a2673a..754355d30 100644
--- a/tests/test_d3d12_xs_surface.py
+++ b/tests/test_d3d12_xs_surface.py
@@ -82,4 +82,9 @@ if __name__ == "__main__":
82 errors, checked, _um = S.check_sdk() 82 errors, checked, _um = S.check_sdk()
83 assert errors == [], errors 83 assert errors == [], errors
84 assert checked == 83 84 assert checked == 83
85 if os.environ.get("SCARAB_REF"):
86 errors, _notes = S.check_scarab(os.environ["SCARAB_REF"])
87 assert errors == [], errors
88 else:
89 print("SCARAB cross-check skipped: SCARAB_REF is not set")
85 print("ok") 90 print("ok")
diff --git a/tests/test_docs_design_rows.py b/tests/test_docs_design_rows.py
new file mode 100644
index 000000000..5da04ba59
--- /dev/null
+++ b/tests/test_docs_design_rows.py
@@ -0,0 +1,64 @@
1"""Each table in docs/design.md, docs/README.md and docs/testing.md names a topic once.
2
3 python -I tests/test_docs_design_rows.py
4
5The translator contract table is where every new rule is recorded (CONTRIBUTING.md, AGENTS.md). When two branches
6edit the same row and a merge keeps both sides, the table ends up with two rows for one topic, each holding facts the
7other lacks, and a reader who stops at the first one misses the rest. On 2026-11-22 twenty topics appeared two to six
8times; the docs index and the testing guide's "Known problems" had the same pattern. This test fails on a repeated
9first cell within one table of those pages, where the first cell is the topic (other pages repeat it on purpose, e.g.
10one row per benchmark size). No game files or build tools.
11"""
12import os
13import unittest
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16PAGES = ("design.md", "README.md", "testing.md")
17
18
19def repeated_topics(lines):
20 """[(topic, [1-based line numbers])] for first cells that appear more than once in one table."""
21 found = []
22 table, in_fence = [], False
23
24 def close():
25 seen = {}
26 for n in table[2:]: # skip the header and the |---| rule
27 cells = lines[n - 1].split("|")
28 if len(cells) > 2 and cells[1].strip():
29 seen.setdefault(cells[1].strip(), []).append(n)
30 found.extend((k, v) for k, v in seen.items() if len(v) > 1)
31
32 for n, line in enumerate(lines, 1):
33 if line.lstrip().startswith("```"):
34 in_fence = not in_fence
35 if not in_fence and line.startswith("|"):
36 table.append(n)
37 continue
38 if table:
39 close()
40 table = []
41 if table:
42 close()
43 return found
44
45
46class DesignTableRows(unittest.TestCase):
47 def test_checker_finds_a_repeated_topic_within_one_table_only(self):
48 lines = ["| Topic | Rule |", "|---|---|", "| EXEC | old |", "| LDS | x |", "| EXEC | new |", "",
49 "| Topic | Rule |", "|---|---|", "| LDS | other table |", "```", "| EXEC | in a code block |",
50 "| EXEC | in a code block |", "```"]
51 self.assertEqual(repeated_topics(lines), [("EXEC", [3, 5])])
52
53 def test_each_page_names_each_topic_once_per_table(self):
54 for page in PAGES:
55 with self.subTest(page=page):
56 with open(os.path.join(ROOT, "docs", page), encoding="utf-8") as f:
57 lines = f.read().split("\n")
58 repeated = repeated_topics(lines)
59 self.assertEqual(repeated, [], f"rows to merge into one in docs/{page} (topic, lines): " +
60 "; ".join(f"{k[:60]!r} at {v}" for k, v in repeated))
61
62
63if __name__ == "__main__":
64 unittest.main()
diff --git a/tests/test_docs_list_items.py b/tests/test_docs_list_items.py
new file mode 100644
index 000000000..029994b0d
--- /dev/null
+++ b/tests/test_docs_list_items.py
@@ -0,0 +1,72 @@
1"""No list item in the Markdown docs is repeated a few lines later.
2
3 python -I tests/test_docs_list_items.py
4
5When two branches rewrite the same bullet and a merge keeps both sides, the page shows the bullet twice: the current
6text and the one it replaced, often next to each other (docs/d3d12_vulkan.md had its RTV/DSV bullet twice and its
7"Hash-table cost" / "Wave64" risks twice each; docs/character_models.md kept the first line of a rewritten bullet).
8A reader cannot tell which copy is current. This test flags two list items within WINDOW lines of each other whose
9openings match. Reads tracked Markdown only; no game files.
10"""
11import os
12import re
13import subprocess
14import unittest
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17ITEM = re.compile(r"^(\s*)(?:[-*+]|\d+[.)])\s+(\S.*)$")
18WINDOW = 8 # lines between the two items
19OPENING = 60 # characters of the item's text that must match (after the list marker)
20
21
22def repeated_items(text):
23 """[(line a, line b)] for list items within WINDOW lines whose first OPENING characters are equal."""
24 items, in_fence = [], False
25 for n, line in enumerate(text.split("\n"), 1):
26 if line.lstrip().startswith("```"):
27 in_fence = not in_fence
28 continue
29 m = None if in_fence else ITEM.match(line)
30 if m and len(m.group(2)) >= OPENING:
31 items.append((n, len(m.group(1)), m.group(2)[:OPENING]))
32 found = []
33 for i, (n, indent, head) in enumerate(items):
34 for n2, indent2, head2 in items[i + 1:]:
35 if n2 - n > WINDOW:
36 break
37 if indent2 == indent and head2 == head:
38 found.append((n, n2))
39 return found
40
41
42def markdown_files():
43 try:
44 out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout
45 files = out.split()
46 except (OSError, subprocess.CalledProcessError):
47 files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/")
48 for r, d, fs in os.walk(ROOT) if ".git" not in r for f in fs if f.endswith(".md")]
49 return [f for f in files if not f.startswith("third_party/")]
50
51
52class RepeatedListItems(unittest.TestCase):
53 def test_checker_flags_a_repeated_item_only(self):
54 current = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD can require it"
55 old = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (old wording)"
56 text = "\n".join([current, " continued", "- **Other.** " + "x" * 70, old, "",
57 "- **19 two-slice 2D arrays** (`depth = 2`, `depth - 1 = 1`) appeared as `depth = 1`",
58 "- **99 three-slice 2D arrays** (`depth = 3`, `depth - 1 = 2`) appeared as `depth = 2`",
59 "```", current, current, "```"])
60 self.assertEqual(repeated_items(text), [(1, 4)])
61
62 def test_docs_have_no_repeated_list_items(self):
63 found = []
64 for path in markdown_files():
65 with open(os.path.join(ROOT, path), encoding="utf-8") as f:
66 found += [f"{path}:{a} and :{b}" for a, b in repeated_items(f.read())]
67 self.assertEqual(found, [], "a list item repeated a few lines later (keep the current copy): " +
68 "; ".join(found))
69
70
71if __name__ == "__main__":
72 unittest.main()
diff --git a/tests/test_docs_repo_paths.py b/tests/test_docs_repo_paths.py
new file mode 100644
index 000000000..69f19b0e2
--- /dev/null
+++ b/tests/test_docs_repo_paths.py
@@ -0,0 +1,79 @@
1"""Repository paths the docs name in backticks exist.
2
3 python -I tests/test_docs_repo_paths.py
4
5`tests/test_docs_links.py` checks Markdown links; this checks the other way the docs point at code, a backticked
6`tools/...`, `runtime/...`, `tests/...` or `scripts/...` path. A rename, or a page written against an unmerged pull
7request, leaves such a path pointing at nothing (docs/saves.md described #279's `xgameruntime_services.cpp` as the
8runtime's save store while #279 was still open). Reads tracked files only (`git ls-files`, with a directory walk when
9git is not available); no game files.
10"""
11import os
12import re
13import subprocess
14import unittest
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17PATH = re.compile(r"`((?:tools|runtime|tests|scripts)/[A-Za-z0-9_./\-]+)`")
18# Pages that quote another project's tree (SCARAB, americas-recomp): their paths are not this repository's.
19OTHER_PROJECTS = {"docs/fssm_crosscheck.md", "docs/d3d12_xs_surface.md"}
20# Build output, not tracked.
21BUILD_OUTPUT = ("runtime/build",)
22
23
24def tracked_files():
25 try:
26 out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout
27 return [p for p in out.splitlines() if p]
28 except (OSError, subprocess.CalledProcessError):
29 found = []
30 for root, dirs, files in os.walk(ROOT):
31 dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__")]
32 found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files]
33 return found
34
35
36def missing_paths(pages, files):
37 """[(page:line, path)] for backticked repository paths in `pages` ({name: text}) that `files` lacks."""
38 known = set(files)
39 for f in files:
40 parts = f.split("/")
41 known.update("/".join(parts[:i]) for i in range(1, len(parts)))
42 out = []
43 for page, text in sorted(pages.items()):
44 in_fence = False
45 for n, line in enumerate(text.split("\n"), 1):
46 if line.lstrip().startswith("```"):
47 in_fence = not in_fence
48 continue
49 if in_fence or "://" in line: # a link into another repository names its paths
50 continue
51 for m in PATH.finditer(line):
52 path = m.group(1).rstrip("/.")
53 if "*" in path or path.startswith(BUILD_OUTPUT) or path in known:
54 continue
55 out.append((f"{page}:{n}", path))
56 return out
57
58
59class DocsRepoPaths(unittest.TestCase):
60 def test_checker_reports_only_the_missing_path(self):
61 pages = {"docs/a.md": "Run `tools/real.py`, then `tools/gone.py`.\n```\n`tools/in_fence.py`\n```\n"
62 "`runtime/build/x.exe` and `tests/` and [`tools/x.py`](https://example.org/tools/x.py)"}
63 self.assertEqual(missing_paths(pages, ["tools/real.py", "tests/t.py"]), [("docs/a.md:1", "tools/gone.py")])
64
65 def test_docs_name_existing_paths(self):
66 files = tracked_files()
67 pages = {}
68 for p in files:
69 if p.startswith("docs/") and p.endswith(".md") and p not in OTHER_PROJECTS:
70 with open(os.path.join(ROOT, p), encoding="utf-8") as f:
71 pages[p] = f.read()
72 self.assertTrue(pages)
73 missing = missing_paths(pages, files)
74 self.assertEqual(missing, [], "backticked paths that name no tracked file: " +
75 "; ".join(f"{where} {path}" for where, path in missing))
76
77
78if __name__ == "__main__":
79 unittest.main()
diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py
index a3e80ae43..41a4dd815 100644
--- a/tests/test_feature_scan.py
+++ b/tests/test_feature_scan.py
@@ -318,9 +318,103 @@ def test_v_perm_b32_selectors():
318 assert failures == 0, f"{failures} v_perm_b32 check(s) failed" 318 assert failures == 0, f"{failures} v_perm_b32 check(s) failed"
319 319
320 320
321def psv0(records, size=24, truncate=False):
322 """PSV0 payload: a 24-byte runtime info, then the resource count, record size and (type, kind) records."""
323 body = struct.pack("<I", 24) + bytes(24) + struct.pack("<II", len(records), size)
324 for t, k in records:
325 rec = struct.pack("<4I", t, 0, 0, 0) + (struct.pack("<II", k, 0) if size >= 24 else b"")
326 body += rec + bytes(size - len(rec))
327 return body[:-4] if truncate else body
328
329
330def listing(lines):
331 """A .s listing with `; encoding:` comments of the right length, so pcs and branch targets are real."""
332 return "".join(f"\t{code} ; encoding: [{','.join(['0x00'] * n)}]\n" for code, n in lines)
333
334
335def test_typed_buffers_and_psv0():
336 """§8.2 #16: PSV0 counter/typed-buffer bindings, MTBUF formats and where each MUBUF V# word 3 comes from."""
337 with tempfile.TemporaryDirectory() as tmp:
338 sh = os.path.join(tmp, "shaders")
339 dx = os.path.join(sh, "dxbc")
340 dis = os.path.join(dx, "disasm")
341 os.makedirs(dis)
342 cs = listing([
343 ("s_load_dwordx4 s[8:11], s[0:1], 0x0", 8), # pc 0
344 ("s_mov_b32 s15, 0x38000", 8), # 8: format 56, 8_8_8_8_UNORM
345 ("s_mov_b32 s19, 0x24000", 8), # 16: format 36, 10_11_11_FLOAT
346 ("s_or_b32 s23, s23, 0x1000", 8), # 24: computed
347 ("s_cmp_eq_u32 s11, 0", 4), # 32: reads s11, writes nothing
348 ("buffer_load_format_xyzw v[0:3], v4, s[8:11], 0 idxen", 8), # 36: memory
349 ("buffer_load_format_x v5, v4, s[12:15], 0 idxen", 8), # 44: literal
350 ("buffer_store_format_x v5, v4, s[16:19], 0 idxen", 8), # 52: literal, not in the table
351 ("buffer_load_format_x v6, v4, s[20:23], 0 idxen", 8), # 60: computed
352 ("buffer_load_format_x v7, v4, s[24:27], 0 idxen", 8), # 68: never written: shader input
353 ("s_cbranch_scc0 1", 4), # 76: to 84; 80 and 84 lead blocks
354 ("s_nop 0", 4), # 80
355 ("buffer_load_format_x v8, v4, s[8:11], 0 idxen", 8), # 84: loaded in an earlier block
356 ("buffer_load_format_x v9, v4, s[12:15], 0 idxen", 8), # 92: literal from an earlier block
357 ("tbuffer_load_format_xy v[0:1], v4, s[8:11], 0 format:[BUF_FMT_16_16_SNORM] idxen", 8),
358 ("tbuffer_load_format_x v2, v4, s[8:11], 0 idxen", 8), # no format: GFX10 default 8_UNORM
359 ("tbuffer_store_format_x v2, v4, s[8:11], 0 format:[BUF_FMT_10_11_11_FLOAT] idxen", 8),
360 ("s_endpgm", 4)])
361 ps = listing([("s_mov_b32 s11, 0", 4), # word 3 0: FORMAT INVALID
362 ("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8),
363 ("buffer_load_format_x v2, v1, s[8:11], 0 idxen", 8), ("s_endpgm", 4)])
364 vs = listing([("v_mov_b32_e32 v0, v1", 4), ("s_endpgm", 4)])
365 synthetic = [
366 ("tb_cs", "cs", cs, psv0([(9, 12), (3, 10), (6, 2)])), # counter UAV, typed buffer SRV, typed 2D UAV
367 ("tb_ps", "ps", ps, psv0([(6, 10), (6, 10)])), # two typed buffer UAVs
368 ("tb_vs", "vs", vs, psv0([(3, 10)], size=16)), # v0 records carry no kind
369 ("tb_gs", "gs", None, psv0([(9, 12)], truncate=True)), # records past the end of the part
370 ]
371 index = []
372 for name, stage, text, psv in synthetic:
373 with open(os.path.join(dx, name + ".dxbc"), "wb") as f:
374 f.write(dxbc([("SFI0", struct.pack("<Q", 0)), ("OSG1", signature([0])), ("PSV0", psv)]))
375 index.append({"name": name, "file": name + ".dxbc", "stage": stage})
376 if text:
377 with open(os.path.join(dis, name + ".s"), "w", encoding="utf-8") as f:
378 f.write(f"; {name}\n" + text)
379 with open(os.path.join(dx, "index.json"), "w", encoding="utf-8") as f:
380 json.dump(index, f)
381
382 pv = F.scan_dxbc(dx, index)["psv0"]
383 check(pv["records"] == 6 and pv["unreadable"] == 1, f"PSV0: 6 records read, 1 truncated table ({pv})")
384 check(pv["shaders"] == {"uav_with_counter": 1, "typed_buffer_srv": 1, "typed_buffer_uav": 1},
385 f"PSV0 shaders with a counter UAV / typed buffer SRV / typed buffer UAV ({pv['shaders']})")
386 check(pv["records_of"] == {"uav_with_counter": 1, "typed_buffer_srv": 1, "typed_buffer_uav": 2},
387 "a typed UAV of a texture kind and a v0 record without a kind are not typed buffers")
388 check(pv["by_type"] == {"UAVStructuredWithCounter": 1, "SRVTyped": 2, "UAVTyped": 3}, f"by type {pv['by_type']}")
389
390 tb = F.scan_typed_buffers(dis, {e["name"]: e["stage"] for e in index})
391 check(tb["mtbuf"] == {"load 16_16_SNORM": 1, "load 8_UNORM": 1, "store 10_11_11_FLOAT": 1},
392 f"MTBUF formats from the instruction, 8_UNORM without format: ({tb['mtbuf']})")
393 check(tb["mubuf_word3"] == {"load computed": 1, "load earlier_literal": 1, "load earlier_memory": 1,
394 "load literal": 2, "load memory": 1, "load shader_input": 2,
395 "store literal": 1},
396 f"MUBUF word 3 by source, s_cmp is no write, a branch target starts a block ({tb['mubuf_word3']})")
397 check(tb["mubuf_literal_formats"] == {"load 8_8_8_8_UNORM": 2, "load INVALID": 1,
398 "store 10_11_11_FLOAT": 1}, f"literal word 3 formats ({tb['mubuf_literal_formats']})")
399 check(tb["not_in_translator"] == {"mtbuf store 10_11_11_FLOAT": 1, "mubuf_literal store 10_11_11_FLOAT": 1},
400 f"formats outside rdna2spirv.Gen.FORMATS are listed, INVALID (reads 0) is not ({tb['not_in_translator']})")
401 check(tb["shaders"] == {"mtbuf": {"cs": 1}, "mubuf": {"cs": 1, "ps": 1}, "mubuf_literal": {"cs": 1, "ps": 1},
402 "mubuf_runtime_format": {"cs": 1, "ps": 1}}, f"shaders per stage ({tb['shaders']})")
403
404 out_json = os.path.join(tmp, "out.json")
405 r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "feature_scan.py"), sh, "--out", out_json],
406 capture_output=True, text=True)
407 check(r.returncode == 0 and "PSV0 bindings: 6 records" in r.stdout and "uav_with_counter 1" in r.stdout
408 and "10_11_11_FLOAT" in r.stdout, f"CLI prints the #16 summary (rc={r.returncode})")
409 raw_json = open(out_json, encoding="utf-8").read()
410 check(all(n not in r.stdout and n not in raw_json for n, *_ in synthetic), "no shader name in stdout or JSON")
411 assert failures == 0, f"{failures} typed-buffer check(s) failed"
412
413
321if __name__ == "__main__": 414if __name__ == "__main__":
322 try: 415 try:
323 test_feature_scan() 416 test_feature_scan()
417 test_typed_buffers_and_psv0()
324 test_short_signature() 418 test_short_signature()
325 test_part_payload_outside_container_is_unreadable() 419 test_part_payload_outside_container_is_unreadable()
326 test_bad_shaders_folder_is_one_line() 420 test_bad_shaders_folder_is_one_line()
diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py
index db85fcd08..46c49f0cd 100644
--- a/tests/test_fma_mix_probe.py
+++ b/tests/test_fma_mix_probe.py
@@ -65,14 +65,13 @@ class Inputs(unittest.TestCase):
65 65
66 66
67class Translator(unittest.TestCase): 67class Translator(unittest.TestCase):
68 def test_translator_rounds_twice(self): 68 def test_translator_rounds_once(self):
69 # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the 69 # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware).
70 # translator is changed to round once (after a hardware measurement), this test and that sentence change too.
71 got = probe.run_translator() 70 got = probe.run_translator()
72 rule, _ = probe.verdict(list(zip(probe.CASES, got))) 71 rule, _ = probe.verdict(list(zip(probe.CASES, got)))
73 self.assertEqual(rule, probe.DOUBLE) 72 self.assertEqual(rule, probe.SINGLE)
74 for case, w in zip(probe.CASES, got): 73 for case, w in zip(probe.CASES, got):
75 self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) 74 self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name)
76 75
77 def test_compute_listing_gives_the_pixel_shader_words(self): 76 def test_compute_listing_gives_the_pixel_shader_words(self):
78 # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the 77 # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the
@@ -149,7 +148,7 @@ class Command(unittest.TestCase):
149 with contextlib.redirect_stdout(buf): 148 with contextlib.redirect_stdout(buf):
150 rc = probe.main([]) 149 rc = probe.main([])
151 self.assertEqual(rc, 0) 150 self.assertEqual(rc, 0)
152 self.assertIn("translator: follows double rounding", buf.getvalue()) 151 self.assertIn("translator: follows single rounding", buf.getvalue())
153 152
154 def test_unknown_side_and_missing_build_are_usage_errors(self): 153 def test_unknown_side_and_missing_build_are_usage_errors(self):
155 import contextlib 154 import contextlib
diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py
index 3c9c843fc..c5c8b8fd3 100644
--- a/tests/test_fspx_unpack.py
+++ b/tests/test_fspx_unpack.py
@@ -200,6 +200,26 @@ class Cli(unittest.TestCase):
200 with open(os.path.join(out, "lib_01.dxbc"), "rb") as f: 200 with open(os.path.join(out, "lib_01.dxbc"), "rb") as f:
201 self.assertEqual(f.read(), c) 201 self.assertEqual(f.read(), c)
202 202
203 def test_retains_programs_with_matching_input_stems(self):
204 container = Containers().container()
205 with tempfile.TemporaryDirectory() as tmp:
206 a = os.path.join(tmp, "a", "sample.dxbc")
207 b = os.path.join(tmp, "b", "sample.dll")
208 for path, data in ((a, container), (b, b"MZ" + bytes(62) + container)):
209 os.makedirs(os.path.dirname(path))
210 with open(path, "wb") as f:
211 f.write(data)
212 out = os.path.join(tmp, "out")
213 code, _, err = self.run_tool(a, b, "--out", out)
214 self.assertEqual(code, 0, err)
215 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
216 index = json.load(f)
217 self.assertEqual([entry["file"] for entry in index], ["sample.dxbc", "sample_2.dxbc"])
218 for name, offset in (("sample", 0), ("sample_2", 64)):
219 with open(os.path.join(out, "fspx", name + ".json"), encoding="utf-8") as f:
220 self.assertEqual(json.load(f)["source"]["offset"], offset)
221 self.assertTrue(os.path.isfile(os.path.join(out, name + ".dxbc")))
222
203 def test_bare_payload_and_a_file_without_fspx(self): 223 def test_bare_payload_and_a_file_without_fspx(self):
204 with tempfile.TemporaryDirectory() as t: 224 with tempfile.TemporaryDirectory() as t:
205 bare = os.path.join(t, "one.fspx") 225 bare = os.path.join(t, "one.fspx")
@@ -227,6 +247,24 @@ class Cli(unittest.TestCase):
227 self.assertEqual(code, 1) 247 self.assertEqual(code, 1)
228 self.assertIn("FSPX status 5", err) 248 self.assertIn("FSPX status 5", err)
229 249
250 def test_short_kind0_unpacks_without_keyerror(self):
251 with tempfile.TemporaryDirectory() as t:
252 src = os.path.join(t, "short.fspx")
253 with open(src, "wb") as f:
254 f.write(make_fspx([(0, struct.pack("<2I", 1, 2)), (6, program())]))
255 out = os.path.join(t, "out")
256 code, _, err = self.run_tool(src, "--out", out)
257 self.assertEqual(code, 0)
258 self.assertEqual(err, "")
259 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
260 index = json.load(f)
261 self.assertEqual(len(index), 1)
262 self.assertNotIn("threads", index[0])
263 self.assertNotIn("wave32", index[0])
264 with open(os.path.join(out, "fspx", "short.json"), encoding="utf-8") as f:
265 meta = json.load(f)
266 self.assertEqual(meta["words"], [1, 2])
267
230 268
231class TranslatorSidecars(unittest.TestCase): 269class TranslatorSidecars(unittest.TestCase):
232 """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" 270 """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob."""
diff --git a/tests/test_gamedata_index.py b/tests/test_gamedata_index.py
index 1409150dd..832926511 100644
--- a/tests/test_gamedata_index.py
+++ b/tests/test_gamedata_index.py
@@ -150,6 +150,25 @@ class GamedataIndexTest(unittest.TestCase):
150 self.assertEqual(rows[0]["root"], "RootA") 150 self.assertEqual(rows[0]["root"], "RootA")
151 self.assertEqual(rows[0]["type"], "xml") 151 self.assertEqual(rows[0]["type"], "xml")
152 152
153 def test_printable_page_directory_stream_is_not_xml(self):
154 # A resource stream with the "0DRP" page marker at +16 whose first 4 KiB are over 95% printable and hold a
155 # "<": data.rpf's 337 such streams were reported as incomplete XML with no root.
156 head = bytes(8) + bytes.fromhex("80ca005000000000") + b"0DRP" + bytes(12)
157 page = head + (b"<abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ>" * 80)[:4096 - len(head)]
158 page += bytes(512)
159 tool = load_tool()
160 self.assertGreater(tool.printable(page), 0.95) # the heuristic alone would call it text
161 self.add(page)
162 self.finish()
163 out = os.path.join(self.root, "index.json")
164 p = self.run_tool(self.carve, "--json", out)
165 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
166 with open(out, encoding="utf-8") as f:
167 data = json.load(f)
168 self.assertNotIn("xml", data["summary"]["types"])
169 self.assertEqual(data["summary"]["xml_incomplete"], 0)
170 self.assertEqual([(r["type"], r["detail"]) for r in data["rows"]], [("other", "0DRP")])
171
153 def test_archive_runs_the_carver_and_reads_roots(self): 172 def test_archive_runs_the_carver_and_reads_roots(self):
154 xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' 173 xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>'
155 blob = b"\x00\x01\x02binary\xff" * 32 174 blob = b"\x00\x01\x02binary\xff" * 32
diff --git a/tests/test_glb_writer.py b/tests/test_glb_writer.py
index ac3dcdbea..840fec126 100644
--- a/tests/test_glb_writer.py
+++ b/tests/test_glb_writer.py
@@ -748,6 +748,25 @@ class TestObjParserAndBounds(unittest.TestCase):
748 for actual, target in zip(normals[position, uv], expected_normal): 748 for actual, target in zip(normals[position, uv], expected_normal):
749 self.assertAlmostEqual(actual, target) 749 self.assertAlmostEqual(actual, target)
750 750
751 def test_parse_obj_explicit_faces_preserve_generated_hard_edge(self):
752 # A top face without normals shares two positions with a fully normaled side.
753 vertices = ["v 0 1 0", "v 1 1 0", "v 1 1 1", "v 0 1 1", "v 0 0 1", "v 1 0 1"]
754 top = "f 1 4 3 2"
755 side = "f 5//1 6//1 3//1 4//1"
756 for faces in ((top, side), (side, top)):
757 with self.subTest(first_face=faces[0]):
758 obj_text = "\n".join([*vertices, "vn 0 0 1", *faces])
759 prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y")
760 normals_by_face = [
761 {(0.0, 1.0, 0.0)} if face == top else {(0.0, 0.0, 1.0)}
762 for face in faces
763 ]
764 self.assertEqual(len(prim["positions"]), 8)
765 self.assertEqual(len(prim["indices"]), 12)
766 for start, expected in zip((0, 6), normals_by_face):
767 actual = {prim["normals"][i] for i in prim["indices"][start:start + 6]}
768 self.assertEqual(actual, expected)
769
751 def test_parse_obj_quad_fan_triangulation(self): 770 def test_parse_obj_quad_fan_triangulation(self):
752 obj_text = "\n".join([ 771 obj_text = "\n".join([
753 "v 0 0 0", 772 "v 0 0 0",
diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py
index c517f6a92..b9cc76a9a 100644
--- a/tests/test_hashdict.py
+++ b/tests/test_hashdict.py
@@ -359,6 +359,32 @@ class CarveAndExtraCLITest(unittest.TestCase):
359 self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) 359 self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr)
360 self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) 360 self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout)
361 361
362 def test_one_archive_folder_is_harvested_as_that_archive(self):
363 # <work>/carve/common (its own index.json, as the gamedata_* tools take it) used to give an empty
364 # dictionary with exit 0: only <carve>/<archive>/index.json was looked for.
365 p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", self.out_json)
366 self.assertEqual(p.returncode, 0, p.stderr)
367 self.assertIn("common: ", p.stdout)
368 with open(self.out_json, encoding="utf-8") as f:
369 d = json.load(f)
370 self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset")
371 self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d)
372 # An archive outside --archives still contributes only its PSIN/RBF0 blobs.
373 p = self.run_tool(os.path.join(self.carve_dir, "custom_pack"), "--out", self.out_json)
374 self.assertEqual(p.returncode, 0, p.stderr)
375 with open(self.out_json, encoding="utf-8") as f:
376 self.assertEqual(json.load(f), {f"{hashdict.joaat('pso_metadata_token'):08x}": "pso_metadata_token"})
377
378 def test_out_naming_a_one_archive_index_is_refused(self):
379 index = os.path.join(self.carve_dir, "common", "index.json")
380 with open(index, "rb") as f:
381 before = f.read()
382 p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", index)
383 self.assertEqual(p.returncode, 2, p.stderr)
384 self.assertIn("is one of the inputs", p.stderr)
385 with open(index, "rb") as f:
386 self.assertEqual(f.read(), before)
387
362 def test_build_requires_an_explicit_carve_directory(self): 388 def test_build_requires_an_explicit_carve_directory(self):
363 empty = os.path.join(self.dir, "empty") 389 empty = os.path.join(self.dir, "empty")
364 os.mkdir(empty) 390 os.mkdir(empty)
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py
new file mode 100644
index 000000000..751de8b90
--- /dev/null
+++ b/tests/test_imhex_patterns.py
@@ -0,0 +1,256 @@
1"""Tests for the ImHex patterns in tools/imhex.
2
3 python -I tests/test_imhex_patterns.py
4
5Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with
6tools/rbf0_index.py and the PSIN inputs with tools/psin_index.py and tools/psin_data.py, the repository's own
7parsers (the PSIN schema reuses the invented names of tests/test_psin_index.py). When ImHex is installed, each pattern
8then runs on the same bytes
9through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the
10parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it
11the ImHex half is skipped and the rest still runs.
12"""
13import json
14import os
15import shutil
16import struct
17import subprocess
18import sys
19import tempfile
20import unittest
21
22ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23PATTERNS = os.path.join(ROOT, "tools", "imhex")
24sys.path.insert(0, os.path.join(ROOT, "tools"))
25sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
27import psin_data # noqa: E402
28import psin_index # noqa: E402
29import rbf0_index # noqa: E402
30from test_psin_index import SCHEMA as PSIN_SCHEMA, joaat, make_lenm, make_lsch, make_section # noqa: E402
31
32
33def find_imhex():
34 candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")]
35 if os.name == "nt":
36 candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe"))
37 for c in candidates:
38 if c and os.path.isfile(c):
39 return c
40 return None
41
42
43IMHEX = find_imhex()
44
45
46# ---- synthetic inputs ------------------------------------------------------------------------------------------
47
48def _name(name):
49 return struct.pack("<H", len(name)) + name
50
51
52def rbf0_stream(wide):
53 """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close."""
54 q, d = ("Q", "d") if wide else ("I", "f")
55 q, d, d3 = "<" + q, "<" + d, "<" + d * 3
56 out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"")
57 out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1)
58 out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute
59 out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0)
60 out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5)
61 out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25)
62 out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe"
63 out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused
64 out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type
65 out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00"
66 out += b"\xff\xff" # close item
67 out += b"\xff\xff" # close root: the end
68 return out + b"\x00\x11\x22\x33" # not part of the resource
69
70
71def rpf9_archive(data_offset=0x100, size=0x140):
72 head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22)
73 toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head)))
74 body = b"\x78\x9c" + bytes(size - data_offset - 2)
75 return head + toc + body
76
77
78PSIN_BLOCKS = [(PSIN_SCHEMA[0][0], bytes(range(0x20))), (0x10, b"probe\x00"), (0x16, struct.pack("<3Q", 1, 2, 3))]
79PSIN_ENUMS = [(joaat("ProbeEnum"), 0x33333333, [(0, joaat("PROBE_A")), (-1, joaat("PROBE_B"))])]
80LSNS_BLOCKS = [(0x101, 32), (0x207, 16)]
81
82
83def psin_container(lsns=True):
84 """A complete container (docs/psin.md): block table, blocks, LSCH, LENM, LSNS, LGID, LRSC (root 1), CHKS."""
85 rows = b"".join(struct.pack("<II", t, len(d)) + b"\xaa" * 8 for t, d in PSIN_BLOCKS) + b"\x70" * 8
86 data = b"".join(d + bytes(-len(d) % 16) for _t, d in PSIN_BLOCKS)
87 first = 8 + len(rows) + len(data)
88 lsns_payload = struct.pack("<I", len(LSNS_BLOCKS)) + b"".join(struct.pack("<II", k, n) for k, n in LSNS_BLOCKS)
89 lsns_payload += bytes((i * 29) & 0xFF for i in range(sum(n for _k, n in LSNS_BLOCKS)))
90 lrsc = b"0DRP" + struct.pack("<I", 122) + bytes(8) + struct.pack("<I", 1) + bytes(12)
91 sections = make_section("LSCH", make_lsch(PSIN_SCHEMA)) + make_section("LENM", make_lenm(PSIN_ENUMS))
92 if lsns:
93 sections += make_section("LSNS", lsns_payload)
94 sections += make_section("LGID") + make_section("LRSC", lrsc)
95 sections += make_section("CHKS", struct.pack(">I", first + len(sections) + 16) + b"\x12\x34\x56\x78")
96 return b"PSIN" + struct.pack(">I", first) + rows + data + sections
97
98
99def pragma_magic(pattern):
100 """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file."""
101 with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f:
102 for line in f:
103 if line.startswith("#pragma magic"):
104 inside = line[line.index("[") + 1:line.index("]")]
105 return bytes(int(b, 16) for b in inside.split())
106 return None
107
108
109# ---- tests -----------------------------------------------------------------------------------------------------
110
111class InputsAndMagic(unittest.TestCase):
112 """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree."""
113
114 def test_synthetic_streams_parse(self):
115 for wide in (True, False):
116 r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4])
117 self.assertEqual(r["status"], "ok", r["error"])
118 self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32")
119 self.assertEqual(r["elements"], 2)
120 self.assertEqual(r["descriptors"], 7)
121
122 def test_synthetic_psin_parses(self):
123 blob = psin_container()
124 r = psin_index.parse(blob, schema=True)
125 self.assertTrue(r["complete"], r["error"])
126 self.assertEqual(r["schema"]["reason"], "")
127 self.assertEqual(r["lsns_blocks"], len(LSNS_BLOCKS))
128 blocks, exact = psin_data.block_table(blob, r["first_section"])
129 self.assertTrue(exact)
130 self.assertEqual([(t, n) for t, _at, n in blocks], [(t, len(d)) for t, d in PSIN_BLOCKS])
131
132 def test_pattern_magics(self):
133 self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC)
134 self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md)
135 self.assertEqual(pragma_magic("psin.hexpat"), psin_index.MAGIC)
136
137
138@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)")
139class PatternsInImHex(unittest.TestCase):
140 def setUp(self):
141 self.tmp = tempfile.TemporaryDirectory()
142 self.addCleanup(self.tmp.cleanup)
143
144 def run_pattern(self, pattern, data):
145 """Returns (decoded JSON or None, combined output)."""
146 src = os.path.join(self.tmp.name, "input.bin")
147 out = os.path.join(self.tmp.name, "out.json")
148 if os.path.exists(out):
149 os.remove(out)
150 with open(src, "wb") as f:
151 f.write(data)
152 cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"]
153 includes = os.path.join(os.path.dirname(IMHEX), "includes")
154 if os.path.isdir(includes):
155 cmd += ["-I", includes]
156 p = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
157 log = p.stdout + p.stderr
158 if not os.path.exists(out):
159 return None, log
160 with open(out, encoding="utf-8") as f:
161 return json.load(f), log
162
163 def check_rbf0(self, wide):
164 data = rbf0_stream(wide)
165 ref = rbf0_index.parse_rbf0(data[:-4])
166 got, log = self.run_pattern("rbf0.hexpat", data)
167 self.assertIsNotNone(got, log)
168 self.assertEqual("prologue" in got["header"], wide)
169 records = got["records"]
170
171 names = [r["name"] for r in records if "name" in r]
172 self.assertEqual(names, ref["descriptor_names"])
173 self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"])
174 ints = [r["value_int"] for r in records if "value_int" in r]
175 self.assertEqual(ints, ref["ints"])
176 floats = []
177 for r in records:
178 floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", [])
179 self.assertEqual(floats, ref["floats"])
180 strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r]
181 self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"])
182 self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0])
183 # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records.
184 self.assertEqual(records[-1]["index"], 0xFF)
185 self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2)
186
187 def test_rbf0_wide(self):
188 self.check_rbf0(wide=True)
189
190 def test_rbf0_narrow(self):
191 self.check_rbf0(wide=False)
192
193 def test_rpf9_header_and_opaque_toc(self):
194 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100))
195 self.assertIsNotNone(got, log)
196 self.assertEqual(got["header"]["magic"], "9FPR")
197 self.assertEqual(got["header"]["data_offset"], 0x100)
198 self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22))
199 self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10)
200
201 def test_psin_matches_psin_index_and_psin_data(self):
202 blob = psin_container()
203 ref = psin_index.parse(blob, schema=True)
204 table, _exact = psin_data.block_table(blob, ref["first_section"])
205 got, log = self.run_pattern("psin.hexpat", blob)
206 self.assertIsNotNone(got, log)
207 self.assertEqual(got["header"]["first_section"], ref["first_section"])
208
209 # Block table: rows, the "pppppppp" end, and each block's data where psin_data places it.
210 self.assertEqual([(r["type"], r["size"]) for r in got["rows"]], [(t, n) for t, _at, n in table])
211 self.assertEqual(got["table_end"], "pppppppp")
212 self.assertEqual([bytes(b["data"]) for b in got["blocks"]], [blob[at:at + n] for _t, at, n in table])
213
214 sections = {s["tag"]: s for s in got["sections"]}
215 self.assertEqual([(s["tag"], s["size"]) for s in got["sections"]],
216 [(s["tag"], s["size"]) for s in ref["sections"]])
217 schema = ref["schema"]
218 self.assertEqual([s["name_hash"] for s in sections["LSCH"]["structs"]],
219 [int(s["hash"], 16) for s in schema["structs"]])
220 self.assertEqual([(m["name_hash"], m["offset"], m["type"], m["index"], m["ref_hash"])
221 for m in sections["LSCH"]["members"]],
222 [(int(m["hash"], 16), m["offset"], m["type"], m["index"], int(m["ref"], 16))
223 for s in schema["structs"] for m in s["members"]])
224 self.assertEqual([e["value_count"] for e in sections["LENM"]["enums"]],
225 [len(e["values"]) for e in schema["enums"]])
226 self.assertEqual([v["value"] for v in sections["LENM"]["values"]],
227 [v["value"] for e in schema["enums"] for v in e["values"]])
228 lsns = next(s for s in ref["sections"] if s["tag"] == "LSNS")
229 self.assertEqual([(d["kind"], d["bytes"]) for d in sections["LSNS"]["descs"]],
230 [(int(b["kind"], 16), b["bytes"]) for b in lsns["blocks"]])
231 self.assertEqual([len(b["records"]) for b in sections["LSNS"]["lsns_blocks"]], [n // 16 for _k, n in LSNS_BLOCKS])
232 self.assertEqual(sections["LRSC"]["rsc_version"], ref["rsc_version"])
233 self.assertEqual(sections["LRSC"]["root_block"], 1)
234 self.assertEqual(sections["CHKS"]["checksum_size"], ref["checksum_size"])
235
236 def test_psin_truncated_keeps_the_whole_sections(self):
237 blob = psin_container(lsns=False)
238 first = struct.unpack_from(">I", blob, 4)[0]
239 lsch_size = struct.unpack_from(">I", blob, first + 4)[0]
240 cut = blob[:first + lsch_size + 20] # inside LENM
241 self.assertFalse(psin_index.parse(cut)["complete"])
242 got, log = self.run_pattern("psin.hexpat", cut)
243 self.assertIsNotNone(got, log)
244 tags = [s["tag"] for s in got["sections"]]
245 self.assertEqual(tags, ["LSCH", "LENM"])
246 self.assertIn("structs", got["sections"][0])
247 self.assertEqual(len(got["sections"][1]["truncated"]), 12) # what is left after LENM's 8-byte header
248
249 def test_rpf9_rejects_a_data_offset_past_the_end(self):
250 got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20])
251 self.assertIsNone(got)
252 self.assertIn("data offset is outside the file", log)
253
254
255if __name__ == "__main__":
256 unittest.main()
diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py
new file mode 100644
index 000000000..69336702b
--- /dev/null
+++ b/tests/test_int_hw_probe.py
@@ -0,0 +1,126 @@
1"""Unit tests for tools/int_hw_probe.py (SHADER-137). Standard library only; no GPU or game files needed."""
2import io
3import json
4import os
5import sys
6import tempfile
7import unittest
8import unittest.mock
9from contextlib import redirect_stderr, redirect_stdout
10from pathlib import Path
11
12ROOT = Path(__file__).resolve().parents[1]
13TOOLS = ROOT / "tools"
14sys.dont_write_bytecode = True
15if str(TOOLS) not in sys.path:
16 sys.path.insert(0, str(TOOLS))
17
18import int_hw_probe as probe # noqa: E402
19from hw_oracle import runner as hw_runner # noqa: E402
20
21
22class IntHwProbeTests(unittest.TestCase):
23 def test_cases_unique_and_nonempty(self):
24 cases = probe.build_cases()
25 self.assertGreaterEqual(len(cases), 80)
26 names = [c.name for c in cases]
27 self.assertEqual(len(names), len(set(names)))
28 groups = {c.group for c in cases}
29 self.assertGreaterEqual(len(groups), 19)
30 for key in probe.KNOWN_DIVERGENCES:
31 self.assertIn(key, names)
32
33 def test_wave32_and_wave64_placeholder_expansion(self):
34 by_name = {c.name: c for c in probe.build_cases()}
35 c = by_name["v_mad_u64_u32_inactive_lane"]
36 w32 = "\n".join(c.lines(wave=32))
37 w64 = "\n".join(c.lines(wave=64))
38 self.assertIn("s_mov_b32 s14, exec_lo", w32)
39 self.assertIn("v_mad_u64_u32 v[8:9], vcc_lo", w32)
40 self.assertIn("s_mov_b64 s[14:15], exec", w64)
41 self.assertIn("v_mad_u64_u32 v[8:9], vcc,", w64)
42 self.assertNotIn("{", w32)
43 self.assertNotIn("{", w64)
44
45 def test_self_test_and_translator_groups(self):
46 buf = io.StringIO()
47 with redirect_stdout(buf):
48 rc = probe.main(["--self-test"])
49 self.assertEqual(rc, 0)
50 self.assertIn("self-test:", buf.getvalue())
51
52 def test_list_groups_and_unknown_group(self):
53 out, err = io.StringIO(), io.StringIO()
54 with redirect_stdout(out):
55 rc = probe.main(["--list-groups"])
56 self.assertEqual(rc, 0)
57 self.assertIn("valu_cvt_pknorm", out.getvalue())
58
59 with redirect_stderr(err):
60 rc = probe.main(["--group", "does_not_exist"])
61 self.assertEqual(rc, 2)
62 self.assertIn("unknown group", err.getvalue())
63
64 def test_hw_unavailable_returns_77(self):
65 err = io.StringIO()
66 with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no GPU")):
67 with redirect_stderr(err):
68 rc = probe.main(["--oracle", "hw", "--group", "salu_bfe_past31"])
69 self.assertEqual(rc, 77)
70 self.assertIn("no GPU", err.getvalue())
71
72 def test_known_divergence_vs_strict_and_json_output(self):
73 # Mock hardware oracle returning the measured gfx1035 words for valu_cvt_flr_rpi.
74 measured = {
75 "v_cvt_rpi_precision": [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000],
76 "v_cvt_flr_rpi_nan_inf": [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000],
77 "v_cvt_i32_f32_nan_control": [0x00000000, 0x00000000, 0x00000000, 0x00000000],
78 "v_cvt_flr_edges": [0xFFFFFFFE, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF],
79 }
80 fake_hw = ("device=mock arch=gfx1035", {32: measured, 64: measured})
81 with tempfile.TemporaryDirectory() as tmp:
82 jpath = os.path.join(tmp, "out.json")
83 out = io.StringIO()
84 # The table is empty since #1831/#1856 fixed the measured divergences, so give the reporting path one: the
85 # "hardware" returns other words for v_cvt_flr_edges, and the table lists them as a known divergence.
86 fake_hw[1][32]["v_cvt_flr_edges"] = fake_hw[1][64]["v_cvt_flr_edges"] = [1, 2, 3, 4]
87 known = {"v_cvt_flr_edges": ("synthetic", [1, 2, 3, 4], "test-only divergence")}
88 patch_known = unittest.mock.patch.dict(probe.KNOWN_DIVERGENCES, known)
89 patch_known.start()
90 self.addCleanup(patch_known.stop)
91 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
92 with redirect_stdout(out):
93 rc = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", jpath])
94 self.assertEqual(rc, 0)
95 self.assertIn("3 match, 1 known divergence, 0 unexpected mismatch, 0 wave32/64 diff", out.getvalue())
96 data = json.loads(Path(jpath).read_text(encoding="utf-8"))
97 self.assertEqual(data["device"], "device=mock arch=gfx1035")
98 self.assertEqual(len(data["cases"]), 4)
99
100 out2 = io.StringIO()
101 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
102 with redirect_stdout(out2):
103 rc_strict = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--strict"])
104 self.assertEqual(rc_strict, 1)
105
106 err = io.StringIO()
107 with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw):
108 with redirect_stderr(err):
109 rc_dir = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", tmp])
110 self.assertEqual(rc_dir, 2)
111
112 def test_unexpected_mismatch_and_wave_diff_fail(self):
113 bad_hw = ("device=mock arch=gfx1035", {
114 32: {"s_bfe_i32_past31": [1, 2, 3, 4], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]},
115 64: {"s_bfe_i32_past31": [1, 2, 3, 5], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]},
116 })
117 out = io.StringIO()
118 with unittest.mock.patch.object(probe, "run_hw", return_value=bad_hw):
119 with redirect_stdout(out):
120 rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31"])
121 self.assertEqual(rc, 1)
122 self.assertIn("WAVE_DIFF", out.getvalue())
123
124
125if __name__ == "__main__":
126 unittest.main()
diff --git a/tests/test_lds_fuzz.py b/tests/test_lds_fuzz.py
index e59020c2c..3c286e45b 100644
--- a/tests/test_lds_fuzz.py
+++ b/tests/test_lds_fuzz.py
@@ -85,6 +85,24 @@ class Generator(unittest.TestCase):
85 else: 85 else:
86 self.assertEqual(x, y) 86 self.assertEqual(x, y)
87 87
88 def test_permute_is_generated_and_no_exec_clears_only_permute(self):
89 self.assertIn("permute", f.EXEC_KINDS)
90 found = 0
91 for idx in range(40):
92 a = f.Program(1, idx, 64, permute=True)
93 b = f.Program(1, idx, 64, no_exec=("permute",), permute=True)
94 self.assertEqual(len(a.ops), len(b.ops))
95 for x, y in zip(a.ops, b.ops):
96 if x["kind"] == "permute":
97 if x["exec"] is not None:
98 found += 1
99 self.assertIsNone(y["exec"])
100 self.assertEqual({k: v for k, v in x.items() if k not in ("exec", "hyp")},
101 {k: v for k, v in y.items() if k not in ("exec", "hyp")})
102 else:
103 self.assertEqual(x, y)
104 self.assertGreater(found, 0, "expected at least one permute op with non-None exec mask")
105
88 106
89class Model(unittest.TestCase): 107class Model(unittest.TestCase):
90 def test_initial_lds_pattern(self): 108 def test_initial_lds_pattern(self):
@@ -104,6 +122,48 @@ class Model(unittest.TestCase):
104 keep.ops = [] 122 keep.ops = []
105 self.assertEqual(regs[9][21], keep.model()[0][9][21]) # lane 9 is off itself: keeps its value 123 self.assertEqual(regs[9][21], keep.model()[0][9][21]) # lane 9 is off itself: keeps its value
106 124
125 def test_permute_collision_highest_active_wins_and_unaddressed_is_zero(self):
126 # All active lanes scatter to lane 5 in their own 32-lane half (mul=0, add=5, offset=0).
127 # EXEC: low half has lanes 0..7 active (highest active = 7); high half has lanes 32, 35, 40 active (highest = 40).
128 mask = 0xFF | (1 << 32) | (1 << 35) | (1 << 40)
129 p = f.Program(1, 0, 64)
130 p.ops = [{"kind": "permute", "mul": 0, "add": 5, "offset": 0, "src": 20, "dst": 21, "exec": mask}]
131 base = f.Program(1, 0, 64)
132 base.ops = []
133 init_regs, _ = base.model()
134 regs, _ = p.model()
135
136 # Low half: lane 5 is active and receives highest active source (lane 7).
137 self.assertEqual(regs[5][21], init_regs[7][20])
138 # Low half: active lanes != 5 receive nobody -> 0.
139 for t in (0, 1, 2, 3, 4, 6, 7):
140 self.assertEqual(regs[t][21], 0)
141 # Low half: inactive lanes keep their original v21.
142 for t in (8, 15, 31):
143 self.assertEqual(regs[t][21], init_regs[t][21])
144 # High half: target lane 32+5=37 is INACTIVE, so it keeps its original v21 even though 32,35,40 targeted it.
145 self.assertEqual(regs[37][21], init_regs[37][21])
146 # High half: active lanes 32, 35, 40 receive nobody -> 0.
147 for t in (32, 35, 40):
148 self.assertEqual(regs[t][21], 0)
149 self.assertIn("ds_permute_b32 v21, v6, v20 offset:0", p.asm())
150
151 with f.perturbed("permute_lowest_wins"):
152 bad_regs, _ = p.model()
153 self.assertEqual(bad_regs[5][21], init_regs[0][20])
154
155 def test_permute_half_isolation_and_offset(self):
156 # Identity + offset:8 (+2 lanes) mod 32 within each 32-lane half, all lanes active.
157 p = f.Program(2, 1, 64)
158 p.ops = [{"kind": "permute", "mul": 1, "add": 0, "offset": 8, "src": 20, "dst": 22, "exec": None}]
159 base = f.Program(2, 1, 64)
160 base.ops = []
161 init_regs, _ = base.model()
162 regs, _ = p.model()
163 for t in range(64):
164 src_lane = (t & ~31) | ((t - 2) & 31)
165 self.assertEqual(regs[t][22], init_regs[src_lane][20])
166
107 def test_d16_hi_read_keeps_the_low_half(self): 167 def test_d16_hi_read_keeps_the_low_half(self):
108 p = f.Program(1, 0, 64) 168 p = f.Program(1, 0, 64)
109 p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}] 169 p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}]
diff --git a/tests/test_lds_fuzz_hw.py b/tests/test_lds_fuzz_hw.py
index 6041abfda..986fddbb3 100644
--- a/tests/test_lds_fuzz_hw.py
+++ b/tests/test_lds_fuzz_hw.py
@@ -122,11 +122,13 @@ class OpMix(unittest.TestCase):
122 progs = f.programs(3, 40, (64, 32), permute=True) 122 progs = f.programs(3, 40, (64, 32), permute=True)
123 perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)] 123 perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)]
124 self.assertTrue(perm) 124 self.assertTrue(perm)
125 parities = set()
125 for p in perm: 126 for p in perm:
126 for i, op in enumerate(p.ops): 127 for i, op in enumerate(p.ops):
127 self.assertEqual(i in p.hyp_ops, op["kind"] == "permute") 128 self.assertEqual(i in p.hyp_ops, op["kind"] == "permute")
128 if op["kind"] == "permute": 129 if op["kind"] == "permute":
129 self.assertEqual(op["mul"] % 2, 1) # a bijection: no two lanes send to one lane 130 parities.add(op["mul"] % 2)
131 self.assertEqual(parities, {0, 1}) # generates both colliding and bijective multipliers
130 132
131 def test_swizzle_exec_hypothesis_only_under_a_mask(self): 133 def test_swizzle_exec_hypothesis_only_under_a_mask(self):
132 progs = f.programs(3, 60, (32,), swizzle_exec=True) 134 progs = f.programs(3, 60, (32,), swizzle_exec=True)
diff --git a/tests/test_make_game_assets_pools.py b/tests/test_make_game_assets_pools.py
index 9716b5ad7..0de945dfe 100644
--- a/tests/test_make_game_assets_pools.py
+++ b/tests/test_make_game_assets_pools.py
@@ -39,7 +39,7 @@ class AssetsPoolsTest(unittest.TestCase):
39 pass 39 pass
40 40
41 def pool(self, rel, size=100): 41 def pool(self, rel, size=100):
42 path = os.path.join(self.game, rel) 42 path = os.path.join(self.game, *rel.split("/"))
43 os.makedirs(os.path.dirname(path), exist_ok=True) 43 os.makedirs(os.path.dirname(path), exist_ok=True)
44 with open(path, "wb") as f: 44 with open(path, "wb") as f:
45 f.write(b"x" * size) 45 f.write(b"x" * size)
diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py
index eb6964bb1..540d0b0e3 100644
--- a/tests/test_make_game_preflight.py
+++ b/tests/test_make_game_preflight.py
@@ -654,9 +654,41 @@ class PathAndGameSelectionTest(PreflightTestBase):
654 self.assert_fails(make_game.choose_game, 654 self.assert_fails(make_game.choose_game,
655 match="More than one copy found: choose one with --game.") 655 match="More than one copy found: choose one with --game.")
656 656
657 def default_out_in(self, platform, icloud_documents, earlier_build=False, call=None):
658 """default_out() (or `call`) with a temporary home folder; icloud_documents makes the folder macOS keeps in
659 iCloud Drive when Desktop & Documents sync is on (~/Library/Mobile Documents/com~apple~CloudDocs/Documents),
660 earlier_build a ~/Documents/Leonida from before the change."""
661 with tempfile.TemporaryDirectory() as home:
662 if icloud_documents:
663 os.makedirs(os.path.join(home, "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents"))
664 if earlier_build:
665 os.makedirs(os.path.join(home, "Documents", "Leonida", "work"))
666 with mock.patch.object(make_game.os.path, "expanduser", lambda p: home + p[1:] if p.startswith("~") else p), \
667 mock.patch.object(make_game.sys, "platform", platform):
668 if call:
669 return [note.replace(home, "~") for note in call()]
670 return os.path.relpath(make_game.default_out(), home)
671
672 def test_icloud_note_names_an_earlier_build_in_documents(self):
673 # A Mac that built into ~/Documents/Leonida before the default moved: say where that resumable build is.
674 notes = self.default_out_in("darwin", True, earlier_build=True, call=make_game.icloud_default_notes)
675 self.assertEqual(len(notes), 2, notes)
676 self.assertIn("off iCloud", notes[0])
677 self.assertIn(os.path.join("~", "Documents", "Leonida"), notes[1])
678 self.assertIn(os.path.join("~", "Leonida") + " to resume", notes[1])
679 self.assertIn("--out", notes[1])
680 self.assertEqual(len(self.default_out_in("darwin", True, call=make_game.icloud_default_notes)), 1)
681
657 def test_default_out_matches_documents_folder(self): 682 def test_default_out_matches_documents_folder(self):
658 expected = os.path.join(os.path.expanduser("~"), "Documents", "Leonida") 683 for platform in ("win32", "linux", "darwin"):
659 self.assertEqual(make_game.default_out(), expected) 684 self.assertEqual(self.default_out_in(platform, False), os.path.join("Documents", "Leonida"), platform)
685
686 def test_default_out_leaves_icloud_synced_documents_on_a_mac(self):
687 # Before: with iCloud Desktop & Documents sync on, ~/Documents/Leonida (and its work folder, hundreds of GB
688 # made from the game) went into iCloud Drive, which uploads it and can evict the work files from the disk.
689 self.assertEqual(self.default_out_in("darwin", True), "Leonida")
690 # Only macOS keeps Documents in iCloud Drive this way; elsewhere the folder means nothing.
691 self.assertEqual(self.default_out_in("linux", True), os.path.join("Documents", "Leonida"))
660 692
661 def test_constants_definitions(self): 693 def test_constants_definitions(self):
662 self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) 694 self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"])
diff --git a/tests/test_manifest.py b/tests/test_manifest.py
index ae335871a..52afc1cbc 100644
--- a/tests/test_manifest.py
+++ b/tests/test_manifest.py
@@ -401,9 +401,9 @@ class ManifestAtomicCreateTest(unittest.TestCase):
401 f.write(b"atomic create payload") 401 f.write(b"atomic create payload")
402 self.out = os.path.join(self.tmp.name, "manifest.json") 402 self.out = os.path.join(self.tmp.name, "manifest.json")
403 403
404 def create(self): 404 def create(self, jobs=1):
405 with contextlib.redirect_stdout(io.StringIO()): 405 with contextlib.redirect_stdout(io.StringIO()):
406 return manifest.create(self.pkg, self.out, jobs=1) 406 return manifest.create(self.pkg, self.out, jobs=jobs)
407 407
408 def test_create_preserves_an_existing_partial_sibling(self): 408 def test_create_preserves_an_existing_partial_sibling(self):
409 sibling = self.out + ".partial" 409 sibling = self.out + ".partial"
@@ -452,6 +452,55 @@ class ManifestAtomicCreateTest(unittest.TestCase):
452 self.assertEqual(self.create(), 0) 452 self.assertEqual(self.create(), 0)
453 self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) 453 self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"])
454 454
455 def test_size_change_before_open_keeps_the_previous_manifest(self):
456 self.assertEqual(self.create(), 0)
457 with open(self.out, "rb") as f:
458 previous = f.read()
459 source = os.path.join(self.pkg, "sample.dat")
460
461 def open_after_growth(path, mode, **kwargs):
462 if path == source and mode == "rb":
463 with open(source, "ab") as f:
464 f.write(b"more bytes")
465 return open(path, mode, **kwargs)
466
467 for jobs in (1, 2):
468 with self.subTest(jobs=jobs):
469 with patch.object(manifest, "open", side_effect=open_after_growth, create=True):
470 with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"):
471 self.create(jobs=jobs)
472 with open(self.out, "rb") as f:
473 self.assertEqual(f.read(), previous)
474
475 def test_same_size_change_during_read_keeps_the_previous_manifest(self):
476 self.assertEqual(self.create(), 0)
477 with open(self.out, "rb") as f:
478 previous = f.read()
479 source = os.path.join(self.pkg, "sample.dat")
480
481 def open_with_edit(path, mode, **kwargs):
482 stream = open(path, mode, **kwargs)
483 if path == source and mode == "rb":
484 original_read = stream.read
485
486 def read_then_edit(size):
487 chunk = original_read(size)
488 stream.read = original_read
489 stamp = os.stat(source)
490 with open(source, "r+b") as f:
491 f.write(b"X")
492 os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 2_000_000_000))
493 return chunk
494
495 stream.read = read_then_edit
496 return stream
497
498 with patch.object(manifest, "open", side_effect=open_with_edit, create=True):
499 with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"):
500 self.create()
501 with open(self.out, "rb") as f:
502 self.assertEqual(f.read(), previous)
503
455 504
456class ManifestBelowNormalTest(unittest.TestCase): 505class ManifestBelowNormalTest(unittest.TestCase):
457 def test_below_normal_callable(self): 506 def test_below_normal_callable(self):
diff --git a/tests/test_mission_tables.py b/tests/test_mission_tables.py
new file mode 100644
index 000000000..738266023
--- /dev/null
+++ b/tests/test_mission_tables.py
@@ -0,0 +1,235 @@
1"""Synthetic tests for tools/mission_tables.py (no game data: every byte below is built here)."""
2import json
3import os
4import struct
5import subprocess
6import sys
7import tempfile
8import unittest
9
10ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11TOOL = os.path.join(ROOT, "tools", "mission_tables.py")
12sys.path.insert(0, os.path.join(ROOT, "tools"))
13
14import mission_tables as M # noqa: E402
15
16
17def record(key, kind, offset, count, col_b=1, band=0):
18 """One 32-byte record. The offset sits in the high half of the dword at +16."""
19 word = (kind & 0xFFFF) | ((offset & 0xFFFF) << 16)
20 return struct.pack("<8I", key, 0, col_b, 0, word, band, (count << 16) | count, 0)
21
22
23def element(archetype, pos, rot, link, hash_value=None, extra=0):
24 """One 64-byte pool element: hash, 3 zeros, pos(x,y,z,x), rot(x,y,z,x), hash, link, extra, 0."""
25 head = struct.pack("<4I", archetype, 0, 0, 0)
26 pos_bytes = struct.pack("<4f", pos[0], pos[1], pos[2], pos[0])
27 rot_bytes = struct.pack("<4f", rot[0], rot[1], rot[2], rot[0])
28 tail = struct.pack("<4I", archetype if hash_value is None else hash_value, link, extra, 0)
29 return head + pos_bytes + rot_bytes + tail
30
31
32def blob_with(records, elements):
33 """records: [(address, bytes)]; elements: [(address, bytes)]. Returns a zero-padded bytearray."""
34 end = max([address + len(data) for address, data in records + elements] + [0])
35 blob = bytearray(end)
36 for address, data in records + elements:
37 blob[address:address + len(data)] = data
38 return blob
39
40
41def good_element(archetype=0x11223344, pos=(1.5, -2.25, 3.75), rot=(0.25, 0.5, -0.75),
42 link=0x55667788, extra=0):
43 return element(archetype, pos, rot, link, extra=extra)
44
45
46class TestRecord(unittest.TestCase):
47 def test_big_endian_offset_half(self):
48 # The measured bytes of a real record: 03 00 80 07. kind is 3 and the offset is 0x780.
49 raw = struct.pack("<8I", 0x3B643C5E, 0, 1, 0, 0x07800003, 0, 0x00010001, 0)
50 self.assertEqual(raw[16:20], bytes((0x03, 0x00, 0x80, 0x07)))
51 decoded = M.decode_record(raw, 0)
52 self.assertIsNotNone(decoded)
53 self.assertEqual(decoded["key"], 0x3B643C5E)
54 self.assertEqual(decoded["kind"], 3)
55 self.assertEqual(decoded["poolOffset"], 0x780) # not 0x8007: the u16 is still little-endian
56 self.assertEqual(decoded["count"], 1)
57 self.assertEqual(decoded["band"], 0)
58 self.assertEqual(decoded["colB"], 1)
59
60 def test_duplicated_count_and_zero_fields_are_required(self):
61 self.assertIsNone(M.decode_record(bytes(16), 0)) # shorter than a record
62 bad_count = bytearray(record(0x12345678, 1, 0x100, 1))
63 struct.pack_into("<I", bad_count, 24, 0x00010002)
64 self.assertIsNone(M.decode_record(bytes(bad_count), 0))
65 bad_zero = bytearray(record(0x12345678, 1, 0x100, 1))
66 struct.pack_into("<I", bad_zero, 28, 1)
67 self.assertIsNone(M.decode_record(bytes(bad_zero), 0))
68
69 def test_joaat_folds_case(self):
70 self.assertEqual(M.joaat("AlphaBeta"), M.joaat("alphabeta"))
71 self.assertEqual(M.joaat("ALPHABETA"), M.joaat("alphabeta"))
72 # An independent transcription of Jenkins one-at-a-time, seeded at 0.
73 def reference(text):
74 value = 0
75 for byte in text.lower().encode("latin-1"):
76 value = (value + byte) & 0xFFFFFFFF
77 value = (value + (value << 10)) & 0xFFFFFFFF
78 value ^= value >> 6
79 value = (value + (value << 3)) & 0xFFFFFFFF
80 value ^= value >> 11
81 return (value + (value << 15)) & 0xFFFFFFFF
82 for name in ("", "StateOne", "RoadJob", "a_b-c.d"):
83 self.assertEqual(M.joaat(name), reference(name))
84
85
86class TestElement(unittest.TestCase):
87 def test_round_trip(self):
88 state_one = 0x11111111
89 state_two = 0x22222222
90 blob = blob_with(
91 [(0x100, record(state_one, 7, 0x1C0, 1)),
92 (0x120, record(state_two, 7, 0x200, 1))],
93 [(0x1C0, good_element(archetype=0xAABBCCDD, link=0x01020304)),
94 (0x200, good_element(archetype=0x99887766, link=0x05060708,
95 pos=(-10.0, 20.0, 30.0), rot=(0.0, 1.0, 2.0)))],
96 )
97 result = M.parse_blob(bytes(blob), "round-trip.bin")
98 self.assertEqual(result["records"], 2)
99 self.assertEqual(result["chunks"], 1)
100 self.assertEqual(result["state_keys"], 2)
101 self.assertEqual(result["entities"], 2)
102 self.assertEqual(result["unresolved_records"], 0)
103 self.assertEqual(result["skipped_slots"], 0)
104 by_archetype = {entity["archetype"]: entity for entity in result["entity_list"]}
105 self.assertEqual(set(by_archetype), {0xAABBCCDD, 0x99887766})
106 first = by_archetype[0xAABBCCDD]
107 self.assertEqual(first["link"], 0x01020304)
108 self.assertEqual([round(value, 4) for value in first["pos"]], [1.5, -2.25, 3.75])
109 self.assertEqual([round(value, 4) for value in first["rot"]], [0.25, 0.5, -0.75])
110 second = by_archetype[0x99887766]
111 self.assertEqual([round(value, 4) for value in second["pos"]], [-10.0, 20.0, 30.0])
112
113 def test_mismatched_duplicated_position_is_not_an_entity(self):
114 broken = bytearray(good_element(archetype=0xDEADBEEF, link=0x00000001))
115 struct.pack_into("<I", broken, 0x1C, 0x7FC00000) # pos.x copy no longer equals pos.x
116 blob = blob_with(
117 [(0x100, record(0x11111111, 7, 0x180, 1)),
118 (0x120, record(0x22222222, 7, 0x1C0, 1))],
119 [(0x180, bytes(broken)),
120 (0x1C0, good_element(archetype=0xCAFEBABE, link=0x00000002))],
121 )
122 result = M.parse_blob(bytes(blob), "mismatch.bin")
123 self.assertEqual(result["records"], 2)
124 self.assertEqual(result["entities"], 1)
125 self.assertEqual(result["skipped_slots"], 1)
126 self.assertEqual(result["unresolved_records"], 1)
127 self.assertEqual([entity["archetype"] for entity in result["entity_list"]], [0xCAFEBABE])
128
129 def test_mismatched_duplicated_rotation_is_not_an_entity(self):
130 broken = bytearray(good_element(archetype=0xDEADBEEF))
131 struct.pack_into("<I", broken, 0x2C, 0x40000000) # rot.x copy no longer equals rot.x
132 blob = blob_with(
133 [(0x100, record(0x11111111, 7, 0x180, 1)),
134 (0x120, record(0x22222222, 7, 0x180, 1))],
135 [(0x180, bytes(broken))],
136 )
137 result = M.parse_blob(bytes(blob), "mismatch-rot.bin")
138 self.assertEqual(result["entities"], 0)
139 self.assertEqual(result["skipped_slots"], 2)
140
141 def test_extra_tail_hash_does_not_hide_an_entity(self):
142 # Some elements carry a second hash in the third-last dword; it must not invalidate the element.
143 blob = blob_with(
144 [(0x100, record(0x11111111, 7, 0x180, 1)),
145 (0x120, record(0x22222222, 7, 0x180, 1))],
146 [(0x180, good_element(archetype=0x1234ABCD, link=0x0BADF00D, extra=0xFEEDFACE))],
147 )
148 result = M.parse_blob(bytes(blob), "extra.bin")
149 self.assertEqual(result["entities"], 1)
150 self.assertEqual(result["entity_list"][0]["extra"], 0xFEEDFACE)
151
152
153class TestBrokenInput(unittest.TestCase):
154 def test_truncated_element_is_skipped_without_a_crash(self):
155 blob = blob_with(
156 [(0x100, record(0x11111111, 7, 0x1C0, 1)),
157 (0x120, record(0x22222222, 7, 0x1C0, 1))],
158 [(0x1C0, good_element())],
159 )
160 truncated = bytes(blob[:0x1C0 + 40]) # the element loses its last 24 bytes
161 result = M.parse_blob(truncated, "truncated.bin")
162 self.assertEqual(result["records"], 2)
163 self.assertEqual(result["entities"], 0)
164 self.assertEqual(result["skipped_slots"], 2)
165 self.assertEqual(result["trailing_bytes"], len(truncated) - 0x140)
166 self.assertEqual(result["skipped_bytes"], len(truncated) - 2 * M.RECORD_SIZE)
167
168 def test_shorter_than_one_record_is_all_skipped(self):
169 result = M.parse_blob(b"\x01" * 20, "tiny.bin")
170 self.assertEqual(result["records"], 0)
171 self.assertEqual(result["entities"], 0)
172 self.assertEqual(result["skipped_bytes"], 20)
173 self.assertEqual(result["trailing_bytes"], 20)
174
175 def test_offset_outside_the_file_is_a_record_but_not_an_entity(self):
176 blob = blob_with(
177 [(0x100, record(0x11111111, 7, 0x180, 1)),
178 (0x120, record(0x22222222, 7, 0xFFF0, 1))],
179 [(0x180, good_element(archetype=0xABCDEF01, link=0x00000003))],
180 )
181 result = M.parse_blob(bytes(blob), "outside.bin")
182 self.assertEqual(result["records"], 2)
183 self.assertEqual(result["state_keys"], 2)
184 self.assertEqual(result["entities"], 1)
185 self.assertEqual(result["unresolved_records"], 1)
186 self.assertEqual(result["entity_list"][0]["archetype"], 0xABCDEF01)
187 self.assertIn(0x22222222, {state["key"] for state in result["states"]})
188
189
190class TestCli(unittest.TestCase):
191 def test_directory_is_sorted_and_json_is_machine_readable(self):
192 one = bytes(blob_with(
193 [(0x100, record(0x11111111, 7, 0x180, 1)),
194 (0x120, record(0x22222222, 7, 0x180, 1))],
195 [(0x180, good_element())],
196 ))
197 with tempfile.TemporaryDirectory() as folder:
198 for name in ("b.bin", "a.bin"):
199 with open(os.path.join(folder, name), "wb") as handle:
200 handle.write(one)
201 with open(os.path.join(folder, "notes.txt"), "w", encoding="utf-8") as handle:
202 handle.write("not a stream")
203 result = M.collect(folder)
204 self.assertEqual([record["file"] for record in result], ["a.bin", "b.bin"])
205 completed = subprocess.run(
206 [sys.executable, "-I", TOOL, folder, "--json"],
207 capture_output=True, text=True, check=True,
208 )
209 payload = json.loads(completed.stdout)
210 self.assertEqual([record["file"] for record in payload["files"]], ["a.bin", "b.bin"])
211 self.assertEqual(payload["summary"]["files"], 2)
212 self.assertEqual(payload["summary"]["records"], 4)
213 self.assertEqual(payload["summary"]["entities"], 2)
214 self.assertRegex(payload["files"][0]["entity_list"][0]["archetype"], r"^[0-9a-f]{8}$")
215
216 def test_limit_stops_after_the_requested_file_count(self):
217 one = bytes(blob_with(
218 [(0x100, record(0x11111111, 7, 0x180, 1)),
219 (0x120, record(0x22222222, 7, 0x180, 1))],
220 [(0x180, good_element())],
221 ))
222 with tempfile.TemporaryDirectory() as folder:
223 for name in ("a.bin", "b.bin", "c.bin"):
224 with open(os.path.join(folder, name), "wb") as handle:
225 handle.write(one)
226 completed = subprocess.run(
227 [sys.executable, "-I", TOOL, folder, "--limit", "2"],
228 capture_output=True, text=True, check=True,
229 )
230 self.assertEqual(completed.stdout.count(" records="), 2)
231 self.assertIn("2 files,", completed.stdout)
232
233
234if __name__ == "__main__":
235 unittest.main()
diff --git a/tests/test_opus_tags.py b/tests/test_opus_tags.py
index 13c9720c9..3eb8215eb 100644
--- a/tests/test_opus_tags.py
+++ b/tests/test_opus_tags.py
@@ -139,6 +139,17 @@ class TestFolder(unittest.TestCase):
139 self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) 139 self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"])
140 self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) 140 self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), [])
141 141
142 def test_duplicate_id_stream_gets_the_same_tags(self):
143 # awc_opus.py names a bank's second stream with an id already used <id>~2 (export_stems); it has the same
144 # id, so it is the same name and dialogue line.
145 stem = awc_opus.export_stems([0x0ABCDEF1, 0x0ABCDEF1])[1]
146 make_ogg(os.path.join(self.opus, "story", "bank_01", stem + ".ogg"))
147 dialogue, langs = T.load_dialogue(self.dialogue)
148 stats = T.tag_folder(self.opus, T.load_names(self.names, "story"), dialogue, langs)
149 self.assertEqual((stats["ogg files"], stats["tagged"], stats["without a name"]), (4, 3, 1))
150 self.assertEqual(self.tags("story", "bank_01", stem + ".ogg"), self.tags("story", "bank_01", "0ABCDEF1.ogg"))
151 self.assertIn("TITLE=heistau_abcd_01", self.tags("story", "bank_01", stem + ".ogg"))
152
142 def test_second_run_replaces_its_own_tags(self): 153 def test_second_run_replaces_its_own_tags(self):
143 names = T.load_names(self.names, "story") 154 names = T.load_names(self.names, "story")
144 T.tag_folder(self.opus, names) 155 T.tag_folder(self.opus, names)
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py
index f4dd76356..0534be001 100644
--- a/tests/test_pe_inspect.py
+++ b/tests/test_pe_inspect.py
@@ -636,5 +636,33 @@ class TruncatedImageTest(unittest.TestCase):
636 self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) 636 self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2)
637 637
638 638
639class DeclaredOptionalHeaderSizeTest(unittest.TestCase):
640 """Reject optional headers smaller than the fields the parser reads."""
641
642 def test_declared_optional_header_too_small(self):
643 for is64 in (False, True):
644 for declared_size in (0, 2, 71):
645 with self.subTest(is64=is64, declared_size=declared_size):
646 data = bytearray(build_image(is64=is64))
647 pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
648 struct.pack_into("<H", data, pe_offset + 20, declared_size)
649
650 with self.assertRaisesRegex(
651 pe_inspect.PeFormatError, "truncated optional header"
652 ):
653 pe_inspect.PeImage(bytes(data))
654
655 def test_declared_optional_header_extends_beyond_file(self):
656 for is64 in (False, True):
657 with self.subTest(is64=is64):
658 data = bytearray(build_image(is64=is64))
659 pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
660 struct.pack_into("<H", data, pe_offset + 20, 0xFFFF)
661
662 with self.assertRaisesRegex(
663 pe_inspect.PeFormatError, "truncated optional header"
664 ):
665 pe_inspect.PeImage(bytes(data))
666
639if __name__ == "__main__": 667if __name__ == "__main__":
640 unittest.main() 668 unittest.main()
diff --git a/tests/test_pe_shader_containers.py b/tests/test_pe_shader_containers.py
new file mode 100644
index 000000000..a7ffb8a08
--- /dev/null
+++ b/tests/test_pe_shader_containers.py
@@ -0,0 +1,171 @@
1"""Unit tests for tools/pe_shader_containers.py, on synthetic containers (no game data, no PE needed).
2
3The containers are built by hand here: a u32 offset table at +32, and each chunk beginning with its fourcc
4and a u32 size. The scan's job is to accept exactly that shape and to reject the `DXBC` immediates and error
5strings that occur in ordinary code.
6"""
7
8import json
9import os
10import random
11import struct
12import sys
13import tempfile
14import unittest
15
16HERE = os.path.dirname(os.path.abspath(__file__))
17ROOT = os.path.dirname(HERE)
18sys.path.insert(0, os.path.join(ROOT, "tools"))
19
20import pe_shader_containers as psc
21
22
23def container(parts) -> bytes:
24 """Assemble a DXBC container from (fourcc, payload) pairs."""
25 header = 32 + 4 * len(parts)
26 offsets, body, end = [], b"", header
27 for fourcc, payload in parts:
28 offsets.append(header + len(body))
29 body += fourcc + struct.pack("<I", len(payload)) + payload
30 end = header + len(body)
31 body += bytes(
32 (-len(body)) % 4
33 ) # chunks are 4-byte aligned; nothing follows the last one
34 total = end
35 out = b"DXBC" + bytes(16) + struct.pack("<III", 1, total, len(parts))
36 out += b"".join(struct.pack("<I", o) for o in offsets)
37 return out + body[: total - header]
38
39
40def xdat(entries, base: int) -> bytes:
41 """An XDAT directory whose payload offsets are relative to the DXIL part, as the package has it."""
42 head = base + 12 + 12 * len(entries)
43 directory, payload = b"", b""
44 for tag, value in entries:
45 directory += struct.pack("<III", tag, head + len(payload), len(value))
46 payload += value
47 return b"XDAT" + struct.pack("<II", len(entries), 0) + directory + payload
48
49
50def dxil_payload(name: str, xbch: bool = True, bitcode: bool = True) -> bytes:
51 entries = [(0x12, bytes(16))]
52 if xbch:
53 entries.append((0x0D, b"XBCH" + bytes(20) + b"payload"))
54 if bitcode:
55 entries.append((0x07, b"BC\xc0\xde" + bytes(8)))
56 prefix = (
57 b"e\x00\x05\x00"
58 + struct.pack("<I", 24)
59 + b"DXIL"
60 + b"\x05\x01\x00\x00"
61 + struct.pack("<I", 0x70)
62 + struct.pack("<I", 0x668)
63 )
64 return prefix + xdat(entries, len(prefix))
65
66
67def ildn(name: str) -> bytes:
68 path = (
69 "X:\\americas\\src\\dev\\rage\\3rdparty\\Microsoft\\XboxBvhBuilder\\Build\\Release\\Output\\"
70 f"XboxBvhBuilder\\{name}.pdb"
71 ).encode()
72 return b"\x00\x00" + struct.pack("<H", len(path)) + path
73
74
75class ContainerTests(unittest.TestCase):
76 def test_scan_reads_one_container(self):
77 data = container(
78 [
79 (b"SFI0", bytes(8)),
80 (b"ILDN", ildn("BitonicPreSort64CS")),
81 (b"DXIL", dxil_payload("BitonicPreSort64CS")),
82 ]
83 )
84 found, rejected = psc.inspect(b"MZ" + bytes(64) + data, "fake.dll")
85 self.assertEqual(rejected, [])
86 self.assertEqual(len(found), 1)
87 r = found[0]
88 self.assertEqual(r["offset"], 66)
89 self.assertEqual(r["size"], len(data))
90 self.assertEqual(r["name"], "BitonicPreSort64CS")
91 self.assertTrue(r["has_xbch"])
92 self.assertTrue(r["has_bitcode"])
93 self.assertFalse(r["has_fspx"])
94 self.assertEqual([c["fourcc"] for c in r["chunks"]], ["SFI0", "ILDN", "DXIL"])
95
96 def test_scan_rejects_a_bare_magic(self):
97 data = b"junk" + b"DXBC" + bytes(40)
98 found, rejected = psc.inspect(data, "fake.dll")
99 self.assertEqual(found, [])
100 self.assertEqual(rejected, [4])
101
102 def test_scan_rejects_a_truncated_chunk(self):
103 good = container([(b"SFI0", bytes(8)), (b"DXIL", dxil_payload("x"))])
104 data = good[:-8]
105 found, rejected = psc.inspect(data, "fake.dll")
106 self.assertEqual(found, [])
107 self.assertEqual(len(rejected), 1)
108
109 def test_fspx_is_reported_and_has_no_xbch(self):
110 data = container([(b"SFI0", bytes(8)), (b"ACCC", b"FSPX" + bytes(12))])
111 found, _ = psc.inspect(data, "fsr.dll")
112 self.assertEqual(len(found), 1)
113 self.assertTrue(found[0]["has_fspx"])
114 self.assertFalse(found[0]["has_xbch"])
115 self.assertFalse(found[0]["has_bitcode"])
116 self.assertIsNone(found[0]["name"])
117
118 def test_xdat_directory(self):
119 tags = psc.xdat_tags(dxil_payload("x"))
120 self.assertEqual([t["tag"] for t in tags], [0x12, 0x0D, 0x07])
121 self.assertEqual(tags[1]["magic"], "XBCH")
122
123 def test_module_name_forms(self):
124 self.assertEqual(psc.module_name(ildn("ConstructBVH4")), "ConstructBVH4")
125 self.assertEqual(psc.module_name(b"\x00\x00\x0a\x00C:\\a\\b.pdb"), "b")
126 self.assertIsNone(psc.module_name(b""))
127
128 def test_extract_writes_container_and_index(self):
129 data = container(
130 [(b"ILDN", ildn("RefitBVH4")), (b"DXIL", dxil_payload("RefitBVH4"))]
131 )
132 found, _ = psc.inspect(data, "fake.dll")
133 with tempfile.TemporaryDirectory() as tmp:
134 index = psc.extract(data, found, tmp)
135 with open(os.path.join(tmp, index[0]["file"]), "rb") as f:
136 self.assertEqual(f.read(), data)
137 with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f:
138 json.dump(index, f)
139 with open(os.path.join(tmp, "index.json"), encoding="utf-8") as f:
140 self.assertEqual(
141 json.load(f)[0],
142 {"name": "RefitBVH4", "file": "RefitBVH4.dxbc", "stage": "cs"},
143 )
144
145 def test_safe_stem(self):
146 self.assertEqual(psc.safe_stem("a b/c", 1), "a_b_c")
147 self.assertEqual(psc.safe_stem(None, 7), "container_07")
148
149 def test_random_buffers_raise_only_container_error(self):
150 """The scan must never traceback on bytes that are not a container (dcastell1's review)."""
151 rng = random.Random(0xDBC)
152 for _ in range(2000):
153 size = rng.randrange(0, 400)
154 data = bytearray(rng.randbytes(size))
155 if size >= 4:
156 at = rng.randrange(0, size - 3)
157 data[at : at + 4] = b"DXBC"
158 try:
159 psc.parse_container(bytes(data), at)
160 except psc.ContainerError:
161 pass
162 except Exception as e: # noqa: BLE001 - any other type is the failure being asserted
163 self.fail(f"parse_container raised {type(e).__name__}: {e}")
164 try:
165 psc.inspect(bytes(data), "fuzz.dll")
166 except Exception as e: # noqa: BLE001 - any exception is the failure being asserted
167 self.fail(f"inspect raised {type(e).__name__}: {e}")
168
169
170if __name__ == "__main__":
171 unittest.main()
diff --git a/tests/test_psin_names.py b/tests/test_psin_names.py
index d4f0d50ed..7502db7b0 100644
--- a/tests/test_psin_names.py
+++ b/tests/test_psin_names.py
@@ -137,6 +137,24 @@ class TestCli(unittest.TestCase):
137 self.assertEqual(r.returncode, 0, r.stderr) 137 self.assertEqual(r.returncode, 0, r.stderr)
138 self.assertEqual(json.loads(r.stdout)["summary"]["u64 resolved"], 1) 138 self.assertEqual(json.loads(r.stdout)["summary"]["u64 resolved"], 1)
139 139
140 def test_rejects_refs_aliasing_inputs(self):
141 with tempfile.TemporaryDirectory() as tmp:
142 source = os.path.join(tmp, "one.bin")
143 names = os.path.join(tmp, "names.txt")
144 for path, data in ((source, sample()), (names, b"prop_crate_01\n")):
145 with open(path, "wb") as f:
146 f.write(data)
147 for destination in (source, names):
148 with self.subTest(destination=destination):
149 with open(destination, "rb") as f:
150 original = f.read()
151 alias = os.path.join(tmp, ".", os.path.basename(destination))
152 result = self.run_tool(source, "--names", names, "--refs", alias)
153 self.assertEqual(result.returncode, 2, result.stderr)
154 self.assertIn("--refs must not overwrite an input", result.stderr)
155 with open(destination, "rb") as f:
156 self.assertEqual(f.read(), original)
157
140 def test_missing_names_file_is_one_line(self): 158 def test_missing_names_file_is_one_line(self):
141 with tempfile.TemporaryDirectory() as d: 159 with tempfile.TemporaryDirectory() as d:
142 r = self.run_tool(d, "--names", os.path.join(d, "none.txt")) 160 r = self.run_tool(d, "--names", os.path.join(d, "none.txt"))
diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py
index 64dfca3bb..353f79cdb 100644
--- a/tests/test_rdna2spirv_cli.py
+++ b/tests/test_rdna2spirv_cli.py
@@ -215,6 +215,34 @@ class ValidatedOutput(unittest.TestCase):
215 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) 215 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous)
216 self.assertEqual(other.read_bytes(), b"unrelated module") 216 self.assertEqual(other.read_bytes(), b"unrelated module")
217 217
218 def test_unsupported_clears_retried_shader_but_preserves_unrelated_output(self):
219 # s_barrier is compute-only, so this PS is Unsupported before any SPIR-V tool runs. A module an
220 # earlier run published for it must not survive: the index is make_game.py's proof of completion.
221 self.src.write_text("\ts_barrier\n\ts_endpgm\n", encoding="utf-8")
222 other = self.out / "cs_other.spv"
223 other.write_bytes(b"unrelated module")
224 previous = {"cs_other": {"stage": "cs"}}
225 self.module.write_bytes(b"old module")
226 self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8")
227 output = self.translate()
228 self.assertIn("s_barrier outside compute", output)
229 self.assertFalse(self.module.exists())
230 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous)
231 self.assertEqual(other.read_bytes(), b"unrelated module")
232 self.assertEqual(list(self.out.glob("*.tmp")), [])
233
234 def test_translator_error_clears_retried_shader(self):
235 self.module.write_bytes(b"old module")
236 self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8")
237 output = io.StringIO()
238 with mock.patch.object(rdna2spirv, "translate", side_effect=ValueError("synthetic translator error")), \
239 mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \
240 redirect_stdout(output):
241 rdna2spirv.main()
242 self.assertIn("translator error ValueError", output.getvalue())
243 self.assertFalse(self.module.exists())
244 self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {})
245
218 def test_validation_success_publishes_binary_and_metadata(self): 246 def test_validation_success_publishes_binary_and_metadata(self):
219 self.assertIn("1 pass spirv-val", self.translate()) 247 self.assertIn("1 pass spirv-val", self.translate())
220 self.assertEqual(self.module.read_bytes(), b"new module") 248 self.assertEqual(self.module.read_bytes(), b"new module")
@@ -223,3 +251,26 @@ class ValidatedOutput(unittest.TestCase):
223 251
224if __name__ == "__main__": 252if __name__ == "__main__":
225 unittest.main() 253 unittest.main()
254
255
256class EmptyShader(unittest.TestCase):
257 """A .s with no tab-indented instruction parses to an empty shader.
258
259 It used to translate to a module that passes spirv-val, lands in index.json and does no work at all, which is
260 what a hand-written or re-indented .s looks like: found while writing a fixture with spaces instead of tabs.
261 """
262
263 def test_no_instructions_is_reported_and_no_module_is_published(self):
264 with tempfile.TemporaryDirectory() as tmp:
265 src = os.path.join(tmp, "disasm")
266 os.mkdir(src)
267 with open(os.path.join(src, "ps_empty.s"), "w", encoding="utf-8") as f:
268 f.write("; ps_empty code 0x0..0x0 (synthetic), gfx1013, 0 invalid words\n s_endpgm\n")
269 with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f:
270 f.write(b"DXBC" + bytes(28))
271 out = os.path.join(tmp, "spirv")
272 p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out], capture_output=True, text=True)
273 self.assertEqual(p.returncode, 0, p.stderr)
274 self.assertIn("0 translated", p.stdout, p.stdout)
275 self.assertIn("no instructions (nothing tab-indented?)", p.stdout, p.stdout)
276 self.assertFalse(os.path.exists(os.path.join(out, "ps_empty.spv")))
diff --git a/tests/test_rdna2spirv_merge.py b/tests/test_rdna2spirv_merge.py
new file mode 100644
index 000000000..20bc22a7d
--- /dev/null
+++ b/tests/test_rdna2spirv_merge.py
@@ -0,0 +1,180 @@
1"""tools/rdna2spirv.py --merge: an incomplete shard set is refused, not published as a partial index.
2
3 python -I tests/test_rdna2spirv_merge.py
4"""
5import json
6import subprocess
7import sys
8import tempfile
9import unittest
10from pathlib import Path
11
12ROOT = Path(__file__).resolve().parents[1]
13sys.path.insert(0, str(ROOT / "tools"))
14import rdna2spirv as R # noqa: E402
15
16TOOL = ROOT / "tools" / "rdna2spirv.py"
17
18
19class MergeShardPartsTest(unittest.TestCase):
20 def setUp(self):
21 self.tmp = tempfile.TemporaryDirectory()
22 self.addCleanup(self.tmp.cleanup)
23 self.out = Path(self.tmp.name)
24
25 def part(self, index, doc):
26 (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8")
27
28 def marker(self, index, count):
29 (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8")
30
31 def plan(self, jobs):
32 (self.out / "shards.json").write_text(json.dumps({"jobs": jobs}), encoding="utf-8")
33
34 def merge_error(self):
35 with self.assertRaises(R.ShardSetError) as cm:
36 R.merge_shard_parts(str(self.out))
37 return str(cm.exception)
38
39 def test_complete_set_merges(self):
40 self.part(0, {"a": {"r": 1}})
41 self.part(1, {"b": {"r": 2}})
42 self.marker(0, 2)
43 self.marker(1, 2)
44 self.assertEqual(R.merge_shard_parts(str(self.out)), {"a": {"r": 1}, "b": {"r": 2}})
45
46 def test_missing_part_is_refused(self):
47 self.part(0, {"a": {}})
48 self.marker(0, 3)
49 self.marker(1, 3)
50 self.marker(2, 3)
51 message = self.merge_error()
52 self.assertIn("incomplete shard set", message)
53 self.assertIn("1 of 3", message)
54 self.assertIn("missing [1, 2]", message)
55
56 def test_extra_part_is_refused(self):
57 for i in range(3):
58 self.part(i, {})
59 self.marker(i, 2)
60 message = self.merge_error()
61 self.assertIn("incomplete shard set", message)
62 self.assertIn("unexpected [2]", message)
63
64 def test_parts_and_markers_must_match(self):
65 self.part(0, {})
66 self.part(1, {})
67 self.marker(0, 2)
68 self.assertIn("index parts and shard markers disagree", self.merge_error())
69
70 def test_a_part_without_its_marker_is_refused(self):
71 # A part left by an older rdna2spirv.py that did not write markers mixed with a newer set.
72 for i in range(3):
73 self.part(i, {})
74 self.marker(1, 3)
75 self.marker(2, 3)
76 message = self.merge_error()
77 self.assertIn("index parts and shard markers disagree", message)
78 self.assertIn("parts [0, 1, 2]", message)
79 self.assertIn("markers [1, 2]", message)
80
81 def test_marker_counts_must_agree(self):
82 self.part(0, {})
83 self.part(1, {})
84 self.marker(0, 2)
85 self.marker(1, 3)
86 self.assertIn("disagree on the shard count", self.merge_error())
87
88 def test_plan_count_is_used_without_markers(self):
89 self.part(0, {})
90 self.plan(2)
91 self.assertIn("incomplete shard set", self.merge_error())
92
93 def test_legacy_parts_without_metadata_still_merge(self):
94 self.part(0, {"a": {}})
95 self.part(1, {"b": {}})
96 self.assertEqual(sorted(R.merge_shard_parts(str(self.out))), ["a", "b"])
97
98 def test_unexpected_part_name_is_refused(self):
99 (self.out / "index.partx.json").write_text("{}", encoding="utf-8")
100 self.assertIn("not an index.part", self.merge_error())
101
102
103class MergeCliTest(unittest.TestCase):
104 def setUp(self):
105 self.tmp = tempfile.TemporaryDirectory()
106 self.addCleanup(self.tmp.cleanup)
107 self.out = Path(self.tmp.name)
108
109 def part(self, index, doc):
110 (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8")
111
112 def marker(self, index, count):
113 (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8")
114
115 def run_merge(self):
116 return subprocess.run([sys.executable, "-I", str(TOOL), str(self.out), "--out", str(self.out), "--merge"],
117 capture_output=True, text=True, timeout=120)
118
119 def test_cli_refuses_a_partial_set_and_writes_no_index(self):
120 self.part(0, {"a": {}})
121 self.marker(0, 2)
122 self.marker(1, 2)
123 result = self.run_merge()
124 self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
125 self.assertIn("ERROR: incomplete shard set", result.stderr)
126 self.assertNotIn("Traceback", result.stderr)
127 self.assertFalse((self.out / "index.json").exists())
128
129 def test_cli_merges_a_complete_set(self):
130 self.part(0, {"a": {}})
131 self.part(1, {"b": {}})
132 self.marker(0, 2)
133 self.marker(1, 2)
134 result = self.run_merge()
135 self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
136 self.assertIn("merged 2 entries", result.stdout)
137 merged = json.loads((self.out / "index.json").read_text(encoding="utf-8"))
138 self.assertEqual(sorted(merged), ["a", "b"])
139
140
141class ShardRoundTripTest(unittest.TestCase):
142 """The writer and the merge through the real CLI, on an empty input directory (no .s and no llvm-mc needed)."""
143
144 def setUp(self):
145 self.tmp = tempfile.TemporaryDirectory()
146 self.addCleanup(self.tmp.cleanup)
147 self.src = Path(self.tmp.name) / "src"
148 self.out = Path(self.tmp.name) / "out"
149 self.src.mkdir()
150 self.out.mkdir()
151
152 def run_tool(self, *args):
153 return subprocess.run([sys.executable, "-I", str(TOOL), str(self.src), "--out", str(self.out), *args],
154 capture_output=True, text=True, timeout=120)
155
156 def test_a_shard_writes_its_marker_and_part_and_merge_needs_the_whole_set(self):
157 first = self.run_tool("--shard", "0/2")
158 self.assertEqual(first.returncode, 0, first.stdout + first.stderr)
159 self.assertTrue((self.out / "index.part0.json").is_file())
160 marker = json.loads((self.out / "shard0.json").read_text(encoding="utf-8"))
161 self.assertEqual(marker, {"index": 0, "count": 2})
162
163 partial = self.run_tool("--merge")
164 self.assertEqual(partial.returncode, 2, partial.stdout + partial.stderr)
165 self.assertIn("incomplete shard set", partial.stderr)
166 self.assertFalse((self.out / "index.json").exists())
167
168 second = self.run_tool("--shard", "1/2")
169 self.assertEqual(second.returncode, 0, second.stdout + second.stderr)
170 self.assertTrue((self.out / "index.part1.json").is_file())
171 self.assertTrue((self.out / "shard1.json").is_file())
172
173 full = self.run_tool("--merge")
174 self.assertEqual(full.returncode, 0, full.stdout + full.stderr)
175 self.assertIn("merged 0 entries", full.stdout)
176 self.assertEqual(json.loads((self.out / "index.json").read_text(encoding="utf-8")), {})
177
178
179if __name__ == "__main__":
180 unittest.main()
diff --git a/tests/test_save_keys.py b/tests/test_save_keys.py
index d50996fe9..906b7c6a0 100644
--- a/tests/test_save_keys.py
+++ b/tests/test_save_keys.py
@@ -143,6 +143,11 @@ class Resolve(unittest.TestCase):
143 self.assertNotIn("Traceback", r.stderr) 143 self.assertNotIn("Traceback", r.stderr)
144 self.assertEqual(r.stdout, "") # refused before the resolve ran 144 self.assertEqual(r.stdout, "") # refused before the resolve ran
145 145
146 def test_rejects_negative_compose_count(self):
147 result = self.resolve_cli(self.dir, "--dict", self.dict, "--compose", "-1")
148 self.assertEqual(result.returncode, 2, result.stderr)
149 self.assertIn("--compose must be 0 or more", result.stderr)
150
146 def test_compose_finds_two_word_names(self): 151 def test_compose_finds_two_word_names(self):
147 text = run(["resolve", self.jsav, "--dict", self.dict, "--compose", "50"]) 152 text = run(["resolve", self.jsav, "--dict", self.dict, "--compose", "50"])
148 self.assertIn("joaat, composed 1 more keys", text) # SprocketCount from Sprocket + Count 153 self.assertIn("joaat, composed 1 more keys", text) # SprocketCount from Sprocket + Count
diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py
new file mode 100644
index 000000000..99c467b12
--- /dev/null
+++ b/tests/test_shader_build_fallbacks.py
@@ -0,0 +1,124 @@
1"""runtime/test/shaders/build.py under the PerVertexKHR fallbacks (LEONIDA_BARY_FALLBACK=1, LEONIDA_F16_INTERP_FALLBACK=1).
2
3The translator refuses a computed I/J pair (ps_ij_computed) without PerVertexKHR inputs, which both fallbacks take
4away. build.py used to treat that as a failed batch: it exited before publishing anything, so check.py then reported
5every test missing (0 of 147 on a Mac, where check.py needs LEONIDA_F16_INTERP_FALLBACK=1). check.py and
6run_gpu_tests.py report ps_ij_computed as SKIP there; build.py now leaves it out and builds the rest.
7
8Standard library only; the translator is replaced by a stand-in that writes the index and modules and, like the real
9one, refuses ps_ij_computed under a fallback. No llvm-mc, SPIR-V tools, GPU or game data.
10
11 python -I tests/test_shader_build_fallbacks.py
12"""
13import contextlib
14import importlib.util
15import io
16import json
17import os
18import sys
19import tempfile
20import types
21import unittest
22from pathlib import Path
23from unittest import mock
24
25ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26BUILD = os.path.join(ROOT, "runtime", "test", "shaders", "build.py")
27FALLBACKS = ("LEONIDA_BARY_FALLBACK", "LEONIDA_F16_INTERP_FALLBACK")
28
29
30def load_build():
31 spec = importlib.util.spec_from_file_location("shaders_build_under_test", BUILD)
32 module = importlib.util.module_from_spec(spec)
33 spec.loader.exec_module(module)
34 return module
35
36
37class BuildUnderFallbackTest(unittest.TestCase):
38 def setUp(self):
39 self.fresh()
40
41 def fresh(self):
42 """A new build.py, output folder and record of what the translator was asked for (one per subtest)."""
43 self.build = load_build()
44 tmp = tempfile.TemporaryDirectory()
45 self.addCleanup(tmp.cleanup)
46 self.out = Path(tmp.name) / "out"
47 self.asked = []
48
49 def fake_translate(self, work, names):
50 """What rdna2spirv.py leaves in <work>/spirv: a module and an index entry per shader it validated."""
51 self.asked.append(list(names))
52 fallback = any(os.environ.get(v) == "1" for v in FALLBACKS)
53 spirv = Path(work) / "spirv"
54 spirv.mkdir(parents=True)
55 index = {}
56 for n in names:
57 if n == "ps_ij_computed" and fallback:
58 continue # "computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs"
59 (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07")
60 (spirv / (n + ".spvasm")).write_text("; SPIR-V\n", encoding="utf-8")
61 index[n] = {"stage": n[:2]}
62 (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8")
63 return 0
64
65 def run_build(self, names, env):
66 stubs = {"spirv_stubs": types.SimpleNamespace(generate_for_index=lambda *a: None),
67 "bary_fallback_gs": types.SimpleNamespace(build_for_index=lambda *a: None)}
68 clean = {k: v for k, v in os.environ.items() if k not in FALLBACKS}
69 stdout = io.StringIO()
70 with mock.patch.dict(os.environ, {**clean, **env}, clear=True), \
71 mock.patch.dict(sys.modules, stubs), \
72 mock.patch.object(self.build, "translate_tests", self.fake_translate), \
73 mock.patch.object(sys, "argv", ["build.py", str(self.out), *names]), \
74 contextlib.redirect_stdout(stdout):
75 try:
76 status = self.build.main()
77 except SystemExit as e:
78 status = e.code
79 return status, stdout.getvalue()
80
81 def test_each_fallback_builds_the_rest_without_ps_ij_computed(self):
82 for var in FALLBACKS:
83 with self.subTest(fallback=var):
84 self.fresh()
85 status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"})
86 self.assertEqual(status, 0, printed)
87 self.assertEqual(self.asked, [["cs_store"]])
88 self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file())
89 self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists())
90 self.assertIn("ps_ij_computed", printed)
91 self.assertIn("PerVertexKHR", printed)
92
93 def test_the_whole_list_builds_under_a_fallback(self):
94 # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty <out>/spirv.
95 status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"})
96 self.assertEqual(status, 0, printed)
97 self.assertNotIn("ps_ij_computed", self.asked[0])
98 published = {p.stem for p in (self.out / "spirv").glob("*.spv")}
99 self.assertEqual(published, set(self.asked[0]))
100 self.assertIn("ps_interp_f16_high", published) # the f16 halves still translate under this fallback
101
102 def test_without_a_fallback_ps_ij_computed_is_still_built(self):
103 status, printed = self.run_build(["cs_store", "ps_ij_computed"], {})
104 self.assertEqual(status, 0, printed)
105 self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]])
106 self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file())
107
108 def test_a_missing_module_without_a_fallback_still_fails_the_batch(self):
109 keep = self.fake_translate
110
111 def refuse(work, names):
112 keep(work, names)
113 os.remove(os.path.join(work, "spirv", "cs_store.spv"))
114 return 0
115 self.fake_translate = refuse
116 try:
117 status, _ = self.run_build(["cs_store"], {})
118 finally:
119 self.fake_translate = keep
120 self.assertIn("did not produce validated SPIR-V for: cs_store", str(status))
121
122
123if __name__ == "__main__":
124 unittest.main()
diff --git a/tests/test_shader_carve.py b/tests/test_shader_carve.py
index b7c875c74..24b0b7a78 100644
--- a/tests/test_shader_carve.py
+++ b/tests/test_shader_carve.py
@@ -449,11 +449,31 @@ class ShaderCarveCliIntegrationTest(unittest.TestCase):
449 f.write(make_rpf_entry("synthetic", 1, dxbc, compressed_override=compressed)) 449 f.write(make_rpf_entry("synthetic", 1, dxbc, compressed_override=compressed))
450 450
451 res = self.run_carve(self.archive, self.out) 451 res = self.run_carve(self.archive, self.out)
452 self.assertEqual(res.returncode, 0, res.stderr) 452 self.assertEqual(res.returncode, 1, res.stderr)
453 self.assertIn("0 shaders carved, 1 candidates rejected", res.stdout) 453 self.assertIn("no shaders carved", res.stderr)
454 with open(os.path.join(self.out, "index.json"), encoding="utf-8") as f: 454 self.assertIn("rejected candidates: 1", res.stderr)
455 self.assertEqual(json.load(f), []) 455 self.assertEqual(os.listdir(self.out), [])
456 self.assertEqual(os.listdir(self.out), ["index.json"]) 456
457 def test_empty_carve_preserves_an_existing_index(self):
458 dxbc = make_dxbc([(b"PRIV", bytes(range(32)))])
459 with open(self.archive, "wb") as f:
460 f.write(make_rpf_entry("valid", 1, dxbc))
461 initial = self.run_carve(self.archive, self.out)
462 self.assertEqual(initial.returncode, 0, initial.stderr)
463 index_path = os.path.join(self.out, "index.json")
464 with open(index_path, "rb") as f:
465 previous = f.read()
466 with open(self.archive, "wb") as f:
467 f.write(b"no shader entries")
468
469 res = self.run_carve(self.archive, self.out)
470
471 self.assertEqual(res.returncode, 1, res.stderr)
472 self.assertIn("no shaders carved", res.stderr)
473 self.assertIn("rejected candidates: 0", res.stderr)
474 with open(index_path, "rb") as f:
475 self.assertEqual(f.read(), previous)
476 self.assertEqual(sorted(os.listdir(self.out)), ["index.json", "valid.dxbc"])
457 477
458 def test_carve_rejects_incomplete_parts_and_continues(self): 478 def test_carve_rejects_incomplete_parts_and_continues(self):
459 valid = make_dxbc([(b"PRIV", bytes(range(32)))]) 479 valid = make_dxbc([(b"PRIV", bytes(range(32)))])
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py
index 9518c82c7..a9f6453ec 100644
--- a/tests/test_shader_checks.py
+++ b/tests/test_shader_checks.py
@@ -16,6 +16,7 @@ import check
16 16
17GOOD_FMT = struct.pack("<64I", *check.FMT_1010102_WORDS, *[0xEEEEEEEE] * 48) 17GOOD_FMT = struct.pack("<64I", *check.FMT_1010102_WORDS, *[0xEEEEEEEE] * 48)
18GOOD_XY_XYZ = struct.pack("<192I", *check.FMT_XY_XYZ_WORDS, *[0xEEEEEEEE] * 108) 18GOOD_XY_XYZ = struct.pack("<192I", *check.FMT_XY_XYZ_WORDS, *[0xEEEEEEEE] * 108)
19GOOD_TBUFFER_STORE = struct.pack("<192I", *check.TBUFFER_STORE_WORDS, *[0xEEEEEEEE] * 140)
19FULL_WAVE = ((0, "compute subgroup size: 64\n0 mismatches\n"), 20FULL_WAVE = ((0, "compute subgroup size: 64\n0 mismatches\n"),
20 (0, "compute subgroup size: 64\nout[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n")) 21 (0, "compute subgroup size: 64\nout[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n"))
21 22
@@ -29,11 +30,12 @@ WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n
29 30
30# All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's 31# All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's
31# vk_store_test "words" fixtures and image_get_lod draws. 32# vk_store_test "words" fixtures and image_get_lod draws.
32TOTAL = (len(check.COMPUTE) + 4 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 33TOTAL = (len(check.COMPUTE) + 5 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4
33 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) 34 + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET)
34 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) 35 + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS)
35 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) 36 + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS)
36 + len(check.TEXTURE_CONSTANTS) + 9) # three mesh fixtures, ps_tex, four compute fixtures and ps_ssharp 37 + len(check.TEXTURE_CONSTANTS) + 10) # three mesh fixtures, ps_tex, ps_imgatomic, four compute fixtures and
38 # ps_ssharp
37CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} 39CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES}
38 40
39 41
@@ -69,9 +71,9 @@ class Wave64Checks(unittest.TestCase):
69 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64")) 71 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64"))
70 Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS)) 72 Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS))
71 return 0, "" 73 return 0, ""
72 if name == "cs_fmt_xy_xyz": 74 if name in ("cs_fmt_xy_xyz", "cs_tbuffer_store"):
73 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) 75 self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192"))
74 Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ) 76 Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ if name == "cs_fmt_xy_xyz" else GOOD_TBUFFER_STORE)
75 return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n" 77 return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n"
76 if name == "cs_user_sgprs": 78 if name == "cs_user_sgprs":
77 # The seeded words come back only if check.py passed them in VKC_SGPRS. 79 # The seeded words come back only if check.py passed them in VKC_SGPRS.
@@ -256,6 +258,23 @@ class FloatToIntSweep(unittest.TestCase):
256 self.assertIn("1 of 16 inputs wrong", problem) 258 self.assertIn("1 of 16 inputs wrong", problem)
257 self.assertIn("0x4f000000", problem) 259 self.assertIn("0x4f000000", problem)
258 260
261 def test_a_device_that_cannot_pin_the_wave_size_skips_instead_of_failing(self):
262 # Before: on a 4..32 device (Apple under MoltenVK) every dispatch came back as unpinned_subgroup_skip's Skip,
263 # and the sweep reported it as "16 of 16 inputs wrong, first 0x00000000: SKIP (...)", a failure.
264 calls = []
265
266 def harness(_tool, _shader, *_args, env=None):
267 calls.append(env.get("VKC_SUBGROUP_SIZE"))
268 return 1, "compute subgroup size: 32 not available\n"
269
270 with patch.object(check, "run", side_effect=harness), \
271 patch.object(check, "subgroup_size", return_value=32):
272 problem = check.cvt_f32_sat_test("tools", "spirv")
273 self.assertIsInstance(problem, check.Skip)
274 self.assertIn("can't run this shader at 32 lanes", problem)
275 self.assertNotIn("inputs wrong", problem)
276 self.assertEqual(calls, ["32"]) # the first dispatch decides; the other 15 would say the same
277
259 def test_inputs_match_the_interpreter_test(self): 278 def test_inputs_match_the_interpreter_test(self):
260 # The GPU sweep and tests/semantic/test_float_to_int.py must judge the same inputs the same way. 279 # The GPU sweep and tests/semantic/test_float_to_int.py must judge the same inputs the same way.
261 src = (Path(__file__).resolve().parent / "semantic" / "test_float_to_int.py").read_text(encoding="utf-8") 280 src = (Path(__file__).resolve().parent / "semantic" / "test_float_to_int.py").read_text(encoding="utf-8")
diff --git a/tests/test_spirv_metal_set0_aliases.py b/tests/test_spirv_metal_set0_aliases.py
new file mode 100644
index 000000000..6399ac7f1
--- /dev/null
+++ b/tests/test_spirv_metal_set0_aliases.py
@@ -0,0 +1,386 @@
1"""Regression tests for tools/spirv_metal_set0.py file hygiene and aliased set-0 bindings.
2
3Standard library only; uses synthetic SPIR-V disassembly, no game data and no external SPIRV-Tools binaries.
4
5 python -I -W error::ResourceWarning tests/test_spirv_metal_set0_aliases.py -v
6"""
7import ast
8import contextlib
9import gc
10import io
11import os
12import re
13import sys
14import tempfile
15import unittest
16import warnings
17
18ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19TOOLS_DIR = os.path.join(ROOT, "tools")
20TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py")
21if TOOLS_DIR not in sys.path:
22 sys.path.insert(0, TOOLS_DIR)
23
24import spirv_metal_set0 as m # noqa: E402
25
26
27def _parse_defs_and_order(text):
28 """Parse SSA definitions, check for duplicates and declaration-before-use ordering."""
29 defs = {}
30 def_line = {}
31 decs = []
32 lines = text.splitlines()
33 for idx, ln in enumerate(lines):
34 m_dec = re.match(r"^\s*OpDecorate (%\S+) (\S+) (\d+)$", ln)
35 if m_dec:
36 decs.append((m_dec.group(1), m_dec.group(2), int(m_dec.group(3))))
37 continue
38 m_def = re.match(r"^\s*(%\S+) = (.*)$", ln)
39 if not m_def:
40 continue
41 rid, rhs = m_def.group(1), m_def.group(2)
42 if rid in defs:
43 raise AssertionError(f"duplicate SSA definition for {rid} at line {idx + 1}: {ln}")
44 defs[rid] = rhs
45 def_line[rid] = idx
46
47 # Verify declaration-before-use for constants, array types, pointers, and variables.
48 for rid, rhs in defs.items():
49 cur = def_line[rid]
50 parts = rhs.split()
51 op = parts[0]
52 if op == "OpConstant":
53 ty = parts[1]
54 assert def_line[ty] < cur, f"{rid} uses {ty} before definition"
55 elif op == "OpTypeRuntimeArray":
56 elem = parts[1]
57 assert def_line[elem] < cur, f"{rid} uses {elem} before definition"
58 elif op == "OpTypeArray":
59 elem, length = parts[1], parts[2]
60 assert def_line[elem] < cur, f"{rid} uses {elem} before definition"
61 assert def_line[length] < cur, f"{rid} uses {length} before definition"
62 elif op == "OpTypePointer":
63 pointee = parts[2]
64 assert def_line[pointee] < cur, f"{rid} uses {pointee} before definition"
65 elif op == "OpVariable":
66 ptr = parts[1]
67 assert def_line[ptr] < cur, f"{rid} uses {ptr} before definition"
68
69 return defs, def_line, decs
70
71
72class TestFileHygiene(unittest.TestCase):
73 def test_capacities_and_print_layout_emit_no_resource_warning(self):
74 with tempfile.TemporaryDirectory() as tmp:
75 good_hdr = os.path.join(tmp, "good.h")
76 bad_hdr = os.path.join(tmp, "bad.h")
77 with open(good_hdr, "w", encoding="utf-8") as f:
78 f.write("std::array<Binding, 2> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 16}, "
79 "{VK_DESCRIPTOR_TYPE_SAMPLER, 8}}};\n")
80 with open(bad_hdr, "w", encoding="utf-8") as f:
81 f.write("// missing table\n")
82
83 with warnings.catch_warnings():
84 warnings.simplefilter("error", ResourceWarning)
85 counts = m.capacities()
86 self.assertEqual(len(counts), 26)
87 self.assertEqual(m.capacities(good_hdr), [16, 8])
88 with self.assertRaises(SystemExit):
89 m.capacities(bad_hdr)
90 with contextlib.redirect_stdout(io.StringIO()):
91 self.assertEqual(m.main(["spirv_metal_set0.py", "--print-layout"]), 0)
92 gc.collect()
93
94 def test_spirv_metal_set0_has_no_unmanaged_open_calls(self):
95 with open(TOOL_PATH, encoding="utf-8") as f:
96 src = f.read()
97 tree = ast.parse(src, filename=TOOL_PATH)
98 managed = set()
99 for node in ast.walk(tree):
100 if isinstance(node, (ast.With, ast.AsyncWith)):
101 for item in node.items:
102 if isinstance(item.context_expr, ast.Call):
103 managed.add(id(item.context_expr))
104 bare = [
105 node.lineno
106 for node in ast.walk(tree)
107 if isinstance(node, ast.Call)
108 and isinstance(node.func, ast.Name)
109 and node.func.id == "open"
110 and id(node) not in managed
111 ]
112 self.assertEqual(bare, [])
113
114
115class TestSingleAndAliasedBindings(unittest.TestCase):
116 def test_single_variable_bindings_keep_canonical_msl_ids(self):
117 module = """\
118 OpDecorate %images DescriptorSet 0
119 OpDecorate %images Binding 0
120 OpDecorate %samplers DescriptorSet 0
121 OpDecorate %samplers Binding 1
122 OpDecorate %desc_map DescriptorSet 0
123 OpDecorate %desc_map Binding 2
124 %uint = OpTypeInt 32 0
125 %float = OpTypeFloat 32
126 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
127 %smp = OpTypeSampler
128 %rt_img = OpTypeRuntimeArray %img2d
129 %rt_smp = OpTypeRuntimeArray %smp
130 %ptr_img = OpTypePointer UniformConstant %rt_img
131 %ptr_smp = OpTypePointer UniformConstant %rt_smp
132 %rt_map = OpTypeRuntimeArray %uint
133 %map = OpTypeStruct %rt_map
134 %ptr_map = OpTypePointer StorageBuffer %map
135 %images = OpVariable %ptr_img UniformConstant
136 %samplers = OpVariable %ptr_smp UniformConstant
137 %desc_map = OpVariable %ptr_map StorageBuffer
138"""
139 counts = m.capacities()
140 out = m.rewrite(module, counts)
141 defs, _, decs = _parse_defs_and_order(out)
142
143 self.assertEqual(defs["%msl_cap_b0"], f"OpConstant %uint {counts[0]}")
144 self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0")
145 self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0")
146 self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant")
147
148 self.assertEqual(defs["%msl_cap_b1"], f"OpConstant %uint {counts[1]}")
149 self.assertEqual(defs["%msl_arr_b1"], "OpTypeArray %smp %msl_cap_b1")
150 self.assertEqual(defs["%msl_ptr_b1"], "OpTypePointer UniformConstant %msl_arr_b1")
151 self.assertEqual(defs["%samplers"], "OpVariable %msl_ptr_b1 UniformConstant")
152 self.assertEqual(defs["%desc_map"], "OpVariable %ptr_map StorageBuffer")
153
154 bindings = {vid: val for vid, kind, val in decs if kind == "Binding"}
155 self.assertEqual(bindings, {"%images": 0, "%samplers": 4096, "%desc_map": 5120})
156
157 def test_distinct_element_type_aliases_at_same_binding(self):
158 # Mirrors tools/rdna2spirv.py emitting %images + typed %itx* aliases at binding 0
159 # and %images_arr + %itx1_1 at binding 3, plus a 3D alias at binding 0.
160 module = """\
161 OpDecorate %images DescriptorSet 0
162 OpDecorate %images Binding 0
163 OpDecorate %samplers DescriptorSet 0
164 OpDecorate %samplers Binding 1
165 OpDecorate %images_arr DescriptorSet 0
166 OpDecorate %images_arr Binding 3
167 OpDecorate %itx1_0 DescriptorSet 0
168 OpDecorate %itx1_0 Binding 0
169 OpDecorate %itx2_0 DescriptorSet 0
170 OpDecorate %itx2_0 Binding 0
171 OpDecorate %itx3d_0 DescriptorSet 0
172 OpDecorate %itx3d_0 Binding 0
173 OpDecorate %itx1_1 DescriptorSet 0
174 OpDecorate %itx1_1 Binding 3
175 %uint = OpTypeInt 32 0
176 %int = OpTypeInt 32 1
177 %float = OpTypeFloat 32
178 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
179 %smp = OpTypeSampler
180 %img2da = OpTypeImage %float 2D 0 1 0 1 Unknown
181 %itximg1_0 = OpTypeImage %uint 2D 0 0 0 1 Unknown
182 %itximg2_0 = OpTypeImage %int 2D 0 0 0 1 Unknown
183 %img_3d = OpTypeImage %float 3D 0 0 0 1 Unknown
184 %itximg1_1 = OpTypeImage %uint 2D 0 1 0 1 Unknown
185 %rt_img = OpTypeRuntimeArray %img2d
186 %ptr_img = OpTypePointer UniformConstant %rt_img
187 %rt_smp = OpTypeRuntimeArray %smp
188 %ptr_smp = OpTypePointer UniformConstant %rt_smp
189 %rt_imga = OpTypeRuntimeArray %img2da
190 %ptr_imga = OpTypePointer UniformConstant %rt_imga
191 %rt_itx10 = OpTypeRuntimeArray %itximg1_0
192 %ptr_itx10 = OpTypePointer UniformConstant %rt_itx10
193 %rt_itx20 = OpTypeRuntimeArray %itximg2_0
194 %ptr_itx20 = OpTypePointer UniformConstant %rt_itx20
195 %rt_3d0 = OpTypeRuntimeArray %img_3d
196 %ptr_3d0 = OpTypePointer UniformConstant %rt_3d0
197 %rt_itx11 = OpTypeRuntimeArray %itximg1_1
198 %ptr_itx11 = OpTypePointer UniformConstant %rt_itx11
199 %images = OpVariable %ptr_img UniformConstant
200 %samplers = OpVariable %ptr_smp UniformConstant
201 %images_arr = OpVariable %ptr_imga UniformConstant
202 %itx1_0 = OpVariable %ptr_itx10 UniformConstant
203 %itx2_0 = OpVariable %ptr_itx20 UniformConstant
204 %itx3d_0 = OpVariable %ptr_3d0 UniformConstant
205 %itx1_1 = OpVariable %ptr_itx11 UniformConstant
206"""
207 counts = m.capacities()
208 ids = m.metal_ids(counts)
209 out = m.rewrite(module, counts)
210 defs, _, decs = _parse_defs_and_order(out)
211
212 # OpConstant is emitted once per binding that has UniformConstant runtime arrays.
213 b0_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[0]}"]
214 b1_b3_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[3]}"]
215 self.assertEqual(b0_consts, ["%msl_cap_b0"])
216 self.assertEqual(counts[1], counts[3])
217 self.assertEqual(b1_b3_consts, ["%msl_cap_b1", "%msl_cap_b3"])
218 for b in (0, 1, 3):
219 self.assertEqual(out.count(f"%msl_cap_b{b} = "), 1)
220
221 # Every variable keeps the exact element type of its original runtime array and binding capacity.
222 expected_vars = {
223 "%images": ("%img2d", "%msl_cap_b0", ids[0]),
224 "%samplers": ("%smp", "%msl_cap_b1", ids[1]),
225 "%images_arr": ("%img2da", "%msl_cap_b3", ids[3]),
226 "%itx1_0": ("%itximg1_0", "%msl_cap_b0", ids[0]),
227 "%itx2_0": ("%itximg2_0", "%msl_cap_b0", ids[0]),
228 "%itx3d_0": ("%img_3d", "%msl_cap_b0", ids[0]),
229 "%itx1_1": ("%itximg1_1", "%msl_cap_b3", ids[3]),
230 }
231 bindings = {vid: val for vid, kind, val in decs if kind == "Binding"}
232 seen_ptrs = set()
233 for var_id, (elem, cap, expected_bind) in expected_vars.items():
234 self.assertEqual(bindings[var_id], expected_bind)
235 m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id])
236 self.assertIsNotNone(m_var, defs[var_id])
237 ptr_id = m_var.group(1)
238 seen_ptrs.add(ptr_id)
239 m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id])
240 self.assertIsNotNone(m_ptr, defs[ptr_id])
241 arr_id = m_ptr.group(1)
242 self.assertEqual(defs[arr_id], f"OpTypeArray {elem} {cap}")
243
244 # Distinct element types get distinct pointer types.
245 self.assertEqual(len(seen_ptrs), len(expected_vars))
246
247 def test_reversed_decoration_order_still_declares_cap_before_first_array(self):
248 # %itx1_0 is decorated before %images, yet %ptr_img is declared before %ptr_itx.
249 module = """\
250 OpDecorate %itx1_0 DescriptorSet 0
251 OpDecorate %itx1_0 Binding 0
252 OpDecorate %images DescriptorSet 0
253 OpDecorate %images Binding 0
254 %uint = OpTypeInt 32 0
255 %int = OpTypeInt 32 1
256 %float = OpTypeFloat 32
257 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
258 %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown
259 %rt_img = OpTypeRuntimeArray %img2d
260 %ptr_img = OpTypePointer UniformConstant %rt_img
261 %rt_itx = OpTypeRuntimeArray %itximg1_0
262 %ptr_itx = OpTypePointer UniformConstant %rt_itx
263 %images = OpVariable %ptr_img UniformConstant
264 %itx1_0 = OpVariable %ptr_itx UniformConstant
265"""
266 out = m.rewrite(module, [4096])
267 defs, def_line, decs = _parse_defs_and_order(out)
268
269 self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0"])
270 self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0_1"])
271 self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant")
272 self.assertEqual(defs["%itx1_0"], "OpVariable %msl_ptr_b0_1 UniformConstant")
273 self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0")
274 self.assertEqual(defs["%msl_arr_b0_1"], "OpTypeArray %itximg1_0 %msl_cap_b0")
275 self.assertEqual([(v, val) for v, k, val in decs if k == "Binding"], [("%itx1_0", 0), ("%images", 0)])
276
277 def test_same_binding_and_same_optypepointer_shares_sized_type_without_duplicates(self):
278 module = """\
279 OpDecorate %images DescriptorSet 0
280 OpDecorate %images Binding 0
281 OpDecorate %alias DescriptorSet 0
282 OpDecorate %alias Binding 0
283 OpDecorate %single DescriptorSet 0
284 OpDecorate %single Binding 0
285 %uint = OpTypeInt 32 0
286 %float = OpTypeFloat 32
287 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
288 %rt_img = OpTypeRuntimeArray %img2d
289 %ptr_img = OpTypePointer UniformConstant %rt_img
290 %ptr_one = OpTypePointer UniformConstant %img2d
291 %images = OpVariable %ptr_img UniformConstant
292 %alias = OpVariable %ptr_img UniformConstant
293 %single = OpVariable %ptr_one UniformConstant
294"""
295 out = m.rewrite(module, [128])
296 defs, _, decs = _parse_defs_and_order(out)
297
298 self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 128")
299 self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0")
300 self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0")
301 self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant")
302 self.assertEqual(defs["%alias"], "OpVariable %msl_ptr_b0 UniformConstant")
303 self.assertEqual(defs["%single"], "OpVariable %ptr_one UniformConstant")
304 self.assertEqual(out.count("%msl_cap_b0 = "), 1)
305 self.assertEqual(out.count("%msl_arr_b0 = "), 1)
306 self.assertEqual(out.count("%msl_ptr_b0 = "), 1)
307 self.assertEqual({v: val for v, k, val in decs if k == "Binding"},
308 {"%images": 0, "%alias": 0, "%single": 0})
309
310 def test_same_binding_and_same_element_via_distinct_pointers(self):
311 module = """\
312 OpDecorate %v1 DescriptorSet 0
313 OpDecorate %v1 Binding 0
314 OpDecorate %v2 DescriptorSet 0
315 OpDecorate %v2 Binding 0
316 %uint = OpTypeInt 32 0
317 %float = OpTypeFloat 32
318 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
319 %rt_a = OpTypeRuntimeArray %img2d
320 %ptr_a = OpTypePointer UniformConstant %rt_a
321 %rt_b = OpTypeRuntimeArray %img2d
322 %ptr_b = OpTypePointer UniformConstant %rt_b
323 %v1 = OpVariable %ptr_a UniformConstant
324 %v2 = OpVariable %ptr_b UniformConstant
325"""
326 out = m.rewrite(module, [64])
327 defs, def_line, _ = _parse_defs_and_order(out)
328
329 for var_id in ("%v1", "%v2"):
330 m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id])
331 self.assertIsNotNone(m_var)
332 ptr_id = m_var.group(1)
333 self.assertLess(def_line[ptr_id], def_line[var_id])
334 m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id])
335 self.assertIsNotNone(m_ptr)
336 self.assertEqual(defs[m_ptr.group(1)], "OpTypeArray %img2d %msl_cap_b0")
337
338 def test_preexisting_msl_ids_in_input_never_collide(self):
339 module = """\
340 OpDecorate %images DescriptorSet 0
341 OpDecorate %images Binding 0
342 OpDecorate %itx1_0 DescriptorSet 0
343 OpDecorate %itx1_0 Binding 0
344 %uint = OpTypeInt 32 0
345 %int = OpTypeInt 32 1
346 %float = OpTypeFloat 32
347%msl_cap_b0 = OpConstant %uint 7
348%msl_arr_b0 = OpTypeFloat 16
349%msl_ptr_b0 = OpTypeStruct %float
350%msl_arr_b0_1 = OpConstant %uint 9
351 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
352 %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown
353 %rt_img = OpTypeRuntimeArray %img2d
354 %ptr_img = OpTypePointer UniformConstant %rt_img
355 %rt_itx = OpTypeRuntimeArray %itximg1_0
356 %ptr_itx = OpTypePointer UniformConstant %rt_itx
357 %images = OpVariable %ptr_img UniformConstant
358 %itx1_0 = OpVariable %ptr_itx UniformConstant
359"""
360 out = m.rewrite(module, [4096])
361 defs, _, _ = _parse_defs_and_order(out)
362
363 # Pre-existing IDs keep their original definitions untouched.
364 self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 7")
365 self.assertEqual(defs["%msl_arr_b0"], "OpTypeFloat 16")
366 self.assertEqual(defs["%msl_ptr_b0"], "OpTypeStruct %float")
367 self.assertEqual(defs["%msl_arr_b0_1"], "OpConstant %uint 9")
368
369 # Newly synthesized IDs avoid every existing definition and match each variable's element type.
370 m_img = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%images"])
371 m_itx = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%itx1_0"])
372 self.assertIsNotNone(m_img)
373 self.assertIsNotNone(m_itx)
374 ptr_img, ptr_itx = m_img.group(1), m_itx.group(1)
375 self.assertNotEqual(ptr_img, ptr_itx)
376
377 arr_img = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_img]).group(1)
378 arr_itx = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_itx]).group(1)
379 cap_img = re.match(r"^OpTypeArray %img2d (%\S+)$", defs[arr_img]).group(1)
380 cap_itx = re.match(r"^OpTypeArray %itximg1_0 (%\S+)$", defs[arr_itx]).group(1)
381 self.assertEqual(cap_img, cap_itx)
382 self.assertEqual(defs[cap_img], "OpConstant %uint 4096")
383
384
385if __name__ == "__main__":
386 unittest.main()
diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py
new file mode 100644
index 000000000..5b03f429e
--- /dev/null
+++ b/tests/test_spirv_metal_set0_extra.py
@@ -0,0 +1,1043 @@
1"""Expanded stdlib-only unit tests for tools/spirv_metal_set0.py.
2
3Covers bindless capacity parsing from vulkan_bindless.h and custom headers,
4metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 /
5push-constant / non-runtime-array / pre-sized / raw-ID / error branches,
6synthetic SPIR-V binary word header/magic/endianness/bounds handling,
7out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as,
8--print-layout, invalid argument handling, and __main__ entry guard.
9
10Standard library only; no spirv-dis/spirv-as/spirv-val binary, no GPU,
11and no game data.
12
13 python -I tests/test_spirv_metal_set0_extra.py -v
14"""
15import contextlib
16import io
17import os
18import re
19import runpy
20import struct
21import subprocess
22import sys
23import tempfile
24import unittest
25from unittest import mock
26import warnings
27
28ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29TOOLS_DIR = os.path.join(ROOT, "tools")
30TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py")
31if TOOLS_DIR not in sys.path:
32 sys.path.insert(0, TOOLS_DIR)
33
34import spirv_metal_set0 as m # noqa: E402
35
36
37SPIRV_MAGIC = 0x07230203
38SPIRV_VERSION_1_0 = 0x00010000
39SPIRV_VERSION_1_5 = 0x00010500
40
41OP_MEMORY_MODEL = 14
42OP_CAPABILITY = 17
43OP_TYPE_VOID = 19
44OP_TYPE_INT = 21
45OP_TYPE_FLOAT = 22
46OP_TYPE_IMAGE = 25
47OP_TYPE_SAMPLER = 26
48OP_TYPE_ARRAY = 28
49OP_TYPE_RUNTIME_ARRAY = 29
50OP_TYPE_STRUCT = 30
51OP_TYPE_POINTER = 32
52OP_CONSTANT = 43
53OP_VARIABLE = 59
54OP_DECORATE = 71
55
56CAP_SHADER = 1
57CAP_RUNTIME_DESCRIPTOR_ARRAY = 5301
58ADDR_LOGICAL = 0
59MEM_GLSL450 = 1
60
61DEC_BLOCK = 2
62DEC_BINDING = 33
63DEC_DESCRIPTOR_SET = 34
64
65SC_UNIFORM_CONSTANT = 0
66SC_PUSH_CONSTANT = 9
67SC_STORAGE_BUFFER = 12
68
69STORAGE_CLASS_BY_NAME = {
70 "UniformConstant": SC_UNIFORM_CONSTANT,
71 "PushConstant": SC_PUSH_CONSTANT,
72 "StorageBuffer": SC_STORAGE_BUFFER,
73}
74STORAGE_CLASS_BY_CODE = {v: k for k, v in STORAGE_CLASS_BY_NAME.items()}
75
76DIM_BY_CODE = {0: "1D", 1: "2D", 2: "3D"}
77DIM_BY_NAME = {v: k for k, v in DIM_BY_CODE.items()}
78
79FMT_BY_CODE = {0: "Unknown", 33: "R32ui"}
80FMT_BY_NAME = {v: k for k, v in FMT_BY_CODE.items()}
81
82
83def _encode_inst(opcode: int, *operands: int) -> list[int]:
84 """Encode one SPIR-V instruction into 32-bit binary words."""
85 wc = 1 + len(operands)
86 return [(wc << 16) | opcode, *operands]
87
88
89def _pack_spv(
90 inst_words: list[int],
91 *,
92 version: int = SPIRV_VERSION_1_5,
93 generator: int = 0,
94 bound: int | None = None,
95 schema: int = 0,
96 endian: str = "<",
97) -> bytes:
98 """Pack a 5-word SPIR-V header and instruction stream into binary bytes."""
99 if bound is None:
100 max_id = 0
101 pos = 0
102 while pos < len(inst_words):
103 wc = inst_words[pos] >> 16
104 op = inst_words[pos] & 0xFFFF
105 if wc < 1 or pos + wc > len(inst_words):
106 break
107 ops = inst_words[pos + 1 : pos + wc]
108 if op in (OP_TYPE_VOID, OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_IMAGE, OP_TYPE_SAMPLER,
109 OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER):
110 max_id = max(max_id, ops[0])
111 elif op in (OP_CONSTANT, OP_VARIABLE):
112 max_id = max(max_id, ops[1])
113 elif op == OP_DECORATE:
114 max_id = max(max_id, ops[0])
115 pos += wc
116 bound = max_id + 1
117 words = [SPIRV_MAGIC, version, generator, bound, schema, *inst_words]
118 return struct.pack(f"{endian}{len(words)}I", *words)
119
120
121def _decode_spv(data: bytes) -> tuple[tuple[int, int, int, int, int], list[tuple[int, list[int]]]]:
122 """Validate SPIR-V binary header/endianness/word-bounds and decode instructions."""
123 if len(data) < 20 or len(data) % 4 != 0:
124 raise ValueError(f"invalid SPIR-V byte length: {len(data)}")
125 words = list(struct.unpack(f"<{len(data) // 4}I", data))
126 magic, version, generator, bound, schema = words[:5]
127 if magic == 0x03022307:
128 raise ValueError("wrong endianness (big-endian SPIR-V magic)")
129 if magic != SPIRV_MAGIC:
130 raise ValueError(f"bad SPIR-V magic: {magic:#010x}")
131 if bound < 1:
132 raise ValueError(f"invalid SPIR-V ID bound: {bound}")
133 if schema != 0:
134 raise ValueError(f"unsupported non-zero schema: {schema}")
135 insts = []
136 pos = 5
137 while pos < len(words):
138 wc = words[pos] >> 16
139 op = words[pos] & 0xFFFF
140 if wc < 1 or pos + wc > len(words):
141 raise ValueError(f"truncated or zero-length instruction at word {pos}")
142 insts.append((op, words[pos + 1 : pos + wc]))
143 pos += wc
144 return (magic, version, generator, bound, schema), insts
145
146
147def _synthetic_spv_to_disasm(data: bytes) -> str:
148 """Decode synthetic SPIR-V binary words into spirv-dis-style assembly text."""
149 header, insts = _decode_spv(data)
150 _, version, generator, bound, schema = header
151 major = (version >> 16) & 0xFF
152 minor = (version >> 8) & 0xFF
153 lines = [
154 "; SPIR-V",
155 f"; Version: {major}.{minor}",
156 f"; Generator: {generator}",
157 f"; Bound: {bound}",
158 f"; Schema: {schema}",
159 ]
160 indent = " " * 15
161 def lhs(res_id: int) -> str:
162 return f"%{res_id}".rjust(12)
163
164 for op, ops in insts:
165 if op == OP_CAPABILITY:
166 name = {CAP_SHADER: "Shader", CAP_RUNTIME_DESCRIPTOR_ARRAY: "RuntimeDescriptorArray"}[ops[0]]
167 lines.append(f"{indent}OpCapability {name}")
168 elif op == OP_MEMORY_MODEL:
169 lines.append(f"{indent}OpMemoryModel Logical GLSL450")
170 elif op == OP_DECORATE:
171 if ops[1] == DEC_DESCRIPTOR_SET:
172 lines.append(f"{indent}OpDecorate %{ops[0]} DescriptorSet {ops[2]}")
173 elif ops[1] == DEC_BINDING:
174 lines.append(f"{indent}OpDecorate %{ops[0]} Binding {ops[2]}")
175 elif ops[1] == DEC_BLOCK:
176 lines.append(f"{indent}OpDecorate %{ops[0]} Block")
177 else:
178 raise ValueError(f"unsupported decoration {ops[1]}")
179 elif op == OP_TYPE_VOID:
180 lines.append(f"{lhs(ops[0])} = OpTypeVoid")
181 elif op == OP_TYPE_INT:
182 lines.append(f"{lhs(ops[0])} = OpTypeInt {ops[1]} {ops[2]}")
183 elif op == OP_TYPE_FLOAT:
184 lines.append(f"{lhs(ops[0])} = OpTypeFloat {ops[1]}")
185 elif op == OP_TYPE_IMAGE:
186 dim = DIM_BY_CODE[ops[2]]
187 fmt = FMT_BY_CODE[ops[7]]
188 lines.append(
189 f"{lhs(ops[0])} = OpTypeImage %{ops[1]} {dim} {ops[3]} {ops[4]} {ops[5]} {ops[6]} {fmt}"
190 )
191 elif op == OP_TYPE_SAMPLER:
192 lines.append(f"{lhs(ops[0])} = OpTypeSampler")
193 elif op == OP_TYPE_ARRAY:
194 lines.append(f"{lhs(ops[0])} = OpTypeArray %{ops[1]} %{ops[2]}")
195 elif op == OP_TYPE_RUNTIME_ARRAY:
196 lines.append(f"{lhs(ops[0])} = OpTypeRuntimeArray %{ops[1]}")
197 elif op == OP_TYPE_STRUCT:
198 members = " ".join(f"%{m_id}" for m_id in ops[1:])
199 lines.append(f"{lhs(ops[0])} = OpTypeStruct {members}".rstrip())
200 elif op == OP_TYPE_POINTER:
201 sc = STORAGE_CLASS_BY_CODE[ops[1]]
202 lines.append(f"{lhs(ops[0])} = OpTypePointer {sc} %{ops[2]}")
203 elif op == OP_CONSTANT:
204 lines.append(f"{lhs(ops[1])} = OpConstant %{ops[0]} {ops[2]}")
205 elif op == OP_VARIABLE:
206 sc = STORAGE_CLASS_BY_CODE[ops[2]]
207 lines.append(f"{lhs(ops[1])} = OpVariable %{ops[0]} {sc}")
208 else:
209 raise ValueError(f"unsupported opcode {op}")
210 return "\n".join(lines) + "\n"
211
212
213def _synthetic_disasm_to_spv(text: str, target_env: str) -> bytes:
214 """Assemble synthetic spirv-dis text (including rewritten %msl_* IDs) into SPIR-V words."""
215 id_map: dict[str, int] = {}
216 next_id = 1
217
218 def resolve(tok: str) -> int:
219 nonlocal next_id
220 if tok in id_map:
221 return id_map[tok]
222 if tok[1:].isdigit():
223 val = int(tok[1:])
224 id_map[tok] = val
225 next_id = max(next_id, val + 1)
226 return val
227 val = next_id
228 next_id += 1
229 id_map[tok] = val
230 return val
231
232 # Pre-register numeric IDs so newly synthesized %msl_* names never collide.
233 for tok in re.findall(r"%\S+", text):
234 if tok[1:].isdigit():
235 resolve(tok)
236
237 inst_words: list[int] = []
238 for raw in text.splitlines():
239 line = raw.strip()
240 if not line or line.startswith(";"):
241 continue
242 if line.startswith("OpCapability "):
243 cap = {"Shader": CAP_SHADER, "RuntimeDescriptorArray": CAP_RUNTIME_DESCRIPTOR_ARRAY}[line.split()[1]]
244 inst_words.extend(_encode_inst(OP_CAPABILITY, cap))
245 elif line == "OpMemoryModel Logical GLSL450":
246 inst_words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450))
247 elif line.startswith("OpDecorate "):
248 parts = line.split()
249 tid = resolve(parts[1])
250 if parts[2] == "DescriptorSet":
251 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_DESCRIPTOR_SET, int(parts[3])))
252 elif parts[2] == "Binding":
253 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BINDING, int(parts[3])))
254 elif parts[2] == "Block":
255 inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BLOCK))
256 else:
257 raise ValueError(f"unsupported OpDecorate: {line}")
258 else:
259 lhs, rhs = [p.strip() for p in line.split("=", 1)]
260 rid = resolve(lhs)
261 parts = rhs.split()
262 opname = parts[0]
263 if opname == "OpTypeVoid":
264 inst_words.extend(_encode_inst(OP_TYPE_VOID, rid))
265 elif opname == "OpTypeInt":
266 inst_words.extend(_encode_inst(OP_TYPE_INT, rid, int(parts[1]), int(parts[2])))
267 elif opname == "OpTypeFloat":
268 inst_words.extend(_encode_inst(OP_TYPE_FLOAT, rid, int(parts[1])))
269 elif opname == "OpTypeImage":
270 inst_words.extend(_encode_inst(
271 OP_TYPE_IMAGE,
272 rid,
273 resolve(parts[1]),
274 DIM_BY_NAME[parts[2]],
275 int(parts[3]),
276 int(parts[4]),
277 int(parts[5]),
278 int(parts[6]),
279 FMT_BY_NAME[parts[7]],
280 ))
281 elif opname == "OpTypeSampler":
282 inst_words.extend(_encode_inst(OP_TYPE_SAMPLER, rid))
283 elif opname == "OpTypeArray":
284 inst_words.extend(_encode_inst(OP_TYPE_ARRAY, rid, resolve(parts[1]), resolve(parts[2])))
285 elif opname == "OpTypeRuntimeArray":
286 inst_words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, rid, resolve(parts[1])))
287 elif opname == "OpTypeStruct":
288 inst_words.extend(_encode_inst(OP_TYPE_STRUCT, rid, *[resolve(p) for p in parts[1:]]))
289 elif opname == "OpTypePointer":
290 inst_words.extend(_encode_inst(OP_TYPE_POINTER, rid, STORAGE_CLASS_BY_NAME[parts[1]], resolve(parts[2])))
291 elif opname == "OpConstant":
292 inst_words.extend(_encode_inst(OP_CONSTANT, resolve(parts[1]), rid, int(parts[2])))
293 elif opname == "OpVariable":
294 inst_words.extend(_encode_inst(OP_VARIABLE, resolve(parts[1]), rid, STORAGE_CLASS_BY_NAME[parts[2]]))
295 else:
296 raise ValueError(f"unsupported op: {line}")
297
298 ver = SPIRV_VERSION_1_5 if target_env == "spv1.5" else SPIRV_VERSION_1_0
299 return _pack_spv(inst_words, version=ver, bound=next_id)
300
301
302def _build_mixed_bindless_spv_words() -> list[int]:
303 """Build synthetic SPIR-V instruction words with set-0, set-1, and PushConstant resources."""
304 # IDs:
305 # 1=uint, 2=float, 3=img2d, 4=smp, 5=rt_img, 6=rt_smp, 7=ptr_img, 8=ptr_smp
306 # 9=rt_map, 10=struct_map, 11=ptr_map, 12=ptr_pc_u32
307 # 13=images (set 0, b0), 14=samplers (set 0, b1), 15=desc_map (set 0, b2)
308 # 16=push_consts, 17=set1_var (set 1, b0)
309 words: list[int] = []
310 words.extend(_encode_inst(OP_CAPABILITY, CAP_SHADER))
311 words.extend(_encode_inst(OP_CAPABILITY, CAP_RUNTIME_DESCRIPTOR_ARRAY))
312 words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450))
313 words.extend(_encode_inst(OP_DECORATE, 13, DEC_DESCRIPTOR_SET, 0))
314 words.extend(_encode_inst(OP_DECORATE, 13, DEC_BINDING, 0))
315 words.extend(_encode_inst(OP_DECORATE, 14, DEC_DESCRIPTOR_SET, 0))
316 words.extend(_encode_inst(OP_DECORATE, 14, DEC_BINDING, 1))
317 words.extend(_encode_inst(OP_DECORATE, 15, DEC_DESCRIPTOR_SET, 0))
318 words.extend(_encode_inst(OP_DECORATE, 15, DEC_BINDING, 2))
319 words.extend(_encode_inst(OP_DECORATE, 10, DEC_BLOCK))
320 words.extend(_encode_inst(OP_DECORATE, 17, DEC_DESCRIPTOR_SET, 1))
321 words.extend(_encode_inst(OP_DECORATE, 17, DEC_BINDING, 0))
322 words.extend(_encode_inst(OP_TYPE_INT, 1, 32, 0))
323 words.extend(_encode_inst(OP_TYPE_FLOAT, 2, 32))
324 words.extend(_encode_inst(OP_TYPE_IMAGE, 3, 2, 1, 0, 0, 0, 1, 0))
325 words.extend(_encode_inst(OP_TYPE_SAMPLER, 4))
326 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 5, 3))
327 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 6, 4))
328 words.extend(_encode_inst(OP_TYPE_POINTER, 7, SC_UNIFORM_CONSTANT, 5))
329 words.extend(_encode_inst(OP_TYPE_POINTER, 8, SC_UNIFORM_CONSTANT, 6))
330 words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 9, 1))
331 words.extend(_encode_inst(OP_TYPE_STRUCT, 10, 9))
332 words.extend(_encode_inst(OP_TYPE_POINTER, 11, SC_STORAGE_BUFFER, 10))
333 words.extend(_encode_inst(OP_TYPE_POINTER, 12, SC_PUSH_CONSTANT, 1))
334 words.extend(_encode_inst(OP_VARIABLE, 7, 13, SC_UNIFORM_CONSTANT))
335 words.extend(_encode_inst(OP_VARIABLE, 8, 14, SC_UNIFORM_CONSTANT))
336 words.extend(_encode_inst(OP_VARIABLE, 11, 15, SC_STORAGE_BUFFER))
337 words.extend(_encode_inst(OP_VARIABLE, 12, 16, SC_PUSH_CONSTANT))
338 words.extend(_encode_inst(OP_VARIABLE, 7, 17, SC_UNIFORM_CONSTANT))
339 return words
340
341
342def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"):
343 """Return a subprocess.run replacement backed by the synthetic SPIR-V binary codec."""
344 calls: list[list[str]] = []
345
346 def fake_run(cmd, check=False, capture_output=False, text=False, input=None):
347 calls.append(list(cmd))
348 exe = cmd[0]
349 if exe == dis_name:
350 in_path = cmd[1]
351 try:
352 with open(in_path, "rb") as f:
353 data = f.read()
354 disasm = _synthetic_spv_to_disasm(data)
355 except (OSError, ValueError) as exc:
356 if check:
357 raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc
358 return subprocess.CompletedProcess(cmd, 1, "", str(exc))
359 return subprocess.CompletedProcess(cmd, 0, disasm, "")
360 if exe == asm_name:
361 # Expect: [asm, "--target-env", target, "-", "-o", out_path]
362 target_env = cmd[cmd.index("--target-env") + 1]
363 out_path = cmd[cmd.index("-o") + 1]
364 try:
365 out_bytes = _synthetic_disasm_to_spv(input, target_env)
366 with open(out_path, "wb") as f:
367 f.write(out_bytes)
368 except (OSError, ValueError) as exc:
369 if check:
370 raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc
371 return subprocess.CompletedProcess(cmd, 1, "", str(exc))
372 return subprocess.CompletedProcess(cmd, 0, "", "")
373 raise AssertionError(f"unexpected subprocess command: {cmd!r}")
374
375 return fake_run, calls
376
377
378class TestCapacities(unittest.TestCase):
379 def test_default_bindless_header_all_26_entries_and_cross_check(self):
380 counts = m.capacities()
381 expected = [4096, 1024, 1, 1024, 1024] + [256] * 21
382 self.assertEqual(counts, expected)
383 self.assertEqual(len(counts), 26)
384 self.assertEqual(sum(counts), 12545)
385
386 with open(m.BINDLESS_H, encoding="utf-8") as f:
387 hdr = f.read()
388 self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr)
389 self.assertIn("inline constexpr std::array<Binding, 26> bindings =", hdr)
390
391 def test_custom_header_parsing_variants(self):
392 cases = [
393 ("empty_table", "std::array<Binding, 0> bindings = {{}};\n", []),
394 (
395 "single_line",
396 "std::array<Binding, 1> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLER, 7}}};\n",
397 [7],
398 ),
399 (
400 "multiline_mixed_types_and_comments",
401 """
402 // unrelated header prefix
403 inline constexpr std::array<Binding, 4> bindings = {{
404 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128},
405 {VK_DESCRIPTOR_TYPE_SAMPLER, 32},
406 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
407 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64},
408 }};
409 """,
410 [128, 32, 1, 64],
411 ),
412 ]
413 with tempfile.TemporaryDirectory() as tmp:
414 for name, body, expected in cases:
415 with self.subTest(case=name):
416 p = os.path.join(tmp, f"{name}.h")
417 with open(p, "w", encoding="utf-8") as f:
418 f.write(body)
419 self.assertEqual(m.capacities(p), expected)
420
421 def test_missing_file_raises_file_not_found(self):
422 with tempfile.TemporaryDirectory() as tmp:
423 missing = os.path.join(tmp, "missing_bindless.h")
424 with self.assertRaises(FileNotFoundError):
425 m.capacities(missing)
426
427 def test_missing_or_mismatched_bindings_table_raises_system_exit(self):
428 bad_headers = [
429 ("empty_file", "", "no `bindings` table"),
430 ("wrong_type_name", "std::array<int, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 4} }};", "no `bindings` table"),
431 (
432 "too_few_entries",
433 "std::array<Binding, 3> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};",
434 "`bindings` declares 3 entries, found 2",
435 ),
436 (
437 "too_many_entries",
438 "std::array<Binding, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};",
439 "`bindings` declares 1 entries, found 2",
440 ),
441 (
442 "unmatched_entry_syntax",
443 "std::array<Binding, 1> bindings = {{ {NOT_A_VK_DESCRIPTOR, 1} }};",
444 "`bindings` declares 1 entries, found 0",
445 ),
446 ]
447 with tempfile.TemporaryDirectory() as tmp:
448 for name, body, msg_part in bad_headers:
449 with self.subTest(case=name):
450 p = os.path.join(tmp, f"{name}.h")
451 with open(p, "w", encoding="utf-8") as f:
452 f.write(body)
453 with self.assertRaises(SystemExit) as ctx:
454 m.capacities(p)
455 self.assertIn(p, str(ctx.exception))
456 self.assertIn(msg_part, str(ctx.exception))
457
458
459class TestMetalIds(unittest.TestCase):
460 def test_empty_single_and_zero_capacities(self):
461 self.assertEqual(m.metal_ids([]), [])
462 self.assertEqual(m.metal_ids([42]), [0])
463 self.assertEqual(m.metal_ids([10, 0, 5, 0, 1]), [0, 10, 10, 15, 15])
464
465 def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self):
466 counts = m.capacities()
467 ids = m.metal_ids(counts)
468 self.assertEqual(len(ids), 26)
469 self.assertEqual(ids[0], 0)
470 self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169])
471 self.assertEqual(ids[8], 7937)
472 self.assertEqual(ids[20], 11009)
473 self.assertEqual(ids[25], 12289)
474 for b in range(len(counts) - 1):
475 self.assertEqual(ids[b + 1], ids[b] + counts[b])
476 self.assertEqual(ids[-1] + counts[-1], sum(counts))
477
478 seen_total = 0
479 for b in range(len(counts)):
480 if b > 0:
481 self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1)
482 seen_total += counts[b]
483 self.assertEqual(seen_total, 12545)
484
485
486class TestRewrite(unittest.TestCase):
487 def test_all_26_vulkan_bindless_bindings(self):
488 counts = m.capacities()
489 ids = m.metal_ids(counts)
490 lines = [
491 " OpCapability Shader",
492 " OpCapability RuntimeDescriptorArray",
493 " OpMemoryModel Logical GLSL450",
494 ]
495 for b in range(26):
496 lines.append(f" OpDecorate %v{b} DescriptorSet 0")
497 lines.append(f" OpDecorate %v{b} Binding {b}")
498 lines.extend([
499 " %uint = OpTypeInt 32 0",
500 " %float = OpTypeFloat 32",
501 " %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown",
502 " %smp = OpTypeSampler",
503 " %rt_map = OpTypeRuntimeArray %uint",
504 " %map = OpTypeStruct %rt_map",
505 " %ptr_map = OpTypePointer StorageBuffer %map",
506 ])
507 for b in range(26):
508 if b == 2:
509 continue
510 elem = "%smp" if b == 1 else "%img2d"
511 lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}")
512 lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}")
513 for b in range(26):
514 if b == 2:
515 lines.append(" %v2 = OpVariable %ptr_map StorageBuffer")
516 else:
517 lines.append(f" %v{b} = OpVariable %ptr_b{b} UniformConstant")
518
519 out = m.rewrite("\n".join(lines) + "\n", counts)
520 out_lines = out.splitlines()
521
522 for b in range(26):
523 self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines)
524 if b == 2:
525 self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines)
526 self.assertNotIn("%msl_cap_b2 ", out)
527 self.assertNotIn("%msl_arr_b2 ", out)
528 self.assertNotIn("%msl_ptr_b2 ", out)
529 else:
530 elem = "%smp" if b == 1 else "%img2d"
531 cap_line = f"%msl_cap_b{b} = OpConstant %uint {counts[b]}"
532 arr_line = f"%msl_arr_b{b} = OpTypeArray {elem} %msl_cap_b{b}"
533 ptr_line = f"%msl_ptr_b{b} = OpTypePointer UniformConstant %msl_arr_b{b}"
534 orig_ptr_line = f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}"
535 idx = out_lines.index(orig_ptr_line)
536 self.assertEqual(out_lines[idx + 1 : idx + 4], [cap_line, arr_line, ptr_line])
537 self.assertIn(f" %v{b} = OpVariable %msl_ptr_b{b} UniformConstant", out_lines)
538
539 def test_push_constants_and_other_descriptor_sets_untouched(self):
540 module = """\
541 OpDecorate %set0_img DescriptorSet 0
542 OpDecorate %set0_img Binding 0
543 OpDecorate %set0_smp DescriptorSet 0
544 OpDecorate %set0_smp Binding 1
545 OpDecorate %set1_in DescriptorSet 1
546 OpDecorate %set1_in Binding 0
547 OpDecorate %set1_high DescriptorSet 1
548 OpDecorate %set1_high Binding 99
549 OpDecorate %set2_uc DescriptorSet 2
550 OpDecorate %set2_uc Binding 0
551 %uint = OpTypeInt 32 0
552 %float = OpTypeFloat 32
553 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
554 %smp = OpTypeSampler
555 %rt_img = OpTypeRuntimeArray %img2d
556 %rt_smp = OpTypeRuntimeArray %smp
557 %ptr_img = OpTypePointer UniformConstant %rt_img
558 %ptr_smp = OpTypePointer UniformConstant %rt_smp
559 %ptr_pc = OpTypePointer PushConstant %uint
560 %ptr_s1hi = OpTypePointer UniformConstant %rt_img
561 %ptr_s2uc = OpTypePointer UniformConstant %rt_img
562 %set0_img = OpVariable %ptr_img UniformConstant
563 %set0_smp = OpVariable %ptr_smp UniformConstant
564 %user_data = OpVariable %ptr_pc PushConstant
565 %set1_in = OpVariable %ptr_img StorageBuffer
566 %set1_high = OpVariable %ptr_s1hi UniformConstant
567 %set2_uc = OpVariable %ptr_s2uc UniformConstant
568"""
569 out = m.rewrite(module, [8, 4])
570 self.assertIn("OpDecorate %set0_img Binding 0", out)
571 self.assertIn("OpDecorate %set0_smp Binding 8", out)
572 # Set 1 (including binding 99 >= len(counts)), Set 2, and PushConstant stay untouched.
573 self.assertIn("OpDecorate %set1_in DescriptorSet 1", out)
574 self.assertIn("OpDecorate %set1_in Binding 0", out)
575 self.assertIn("OpDecorate %set1_high DescriptorSet 1", out)
576 self.assertIn("OpDecorate %set1_high Binding 99", out)
577 self.assertIn("OpDecorate %set2_uc DescriptorSet 2", out)
578 self.assertIn("OpDecorate %set2_uc Binding 0", out)
579 self.assertIn("%user_data = OpVariable %ptr_pc PushConstant", out)
580 self.assertIn("%set1_in = OpVariable %ptr_img StorageBuffer", out)
581 self.assertIn("%set1_high = OpVariable %ptr_s1hi UniformConstant", out)
582 self.assertIn("%set2_uc = OpVariable %ptr_s2uc UniformConstant", out)
583
584 def test_non_runtime_array_set0_resources_rebind_without_retyping_or_uint32(self):
585 # No OpTypeInt 32 0 is present, yet none of these set-0 bindings use OpTypeRuntimeArray
586 # under OpTypePointer UniformConstant, so rewriting succeeds without raising.
587 module = """\
588 OpDecorate %single DescriptorSet 0
589 OpDecorate %single Binding 0
590 OpDecorate %fixed DescriptorSet 0
591 OpDecorate %fixed Binding 1
592 OpDecorate %ubo DescriptorSet 0
593 OpDecorate %ubo Binding 2
594 OpDecorate %mismatch DescriptorSet 0
595 OpDecorate %mismatch Binding 3
596 OpDecorate %dangling DescriptorSet 0
597 OpDecorate %dangling Binding 4
598 %float = OpTypeFloat 32
599 %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
600 %sint = OpTypeInt 32 1
601 %c16 = OpConstant %sint 16
602 %fixed_arr = OpTypeArray %img2d %c16
603 %ubo_blk = OpTypeStruct %float
604 %ptr_single = OpTypePointer UniformConstant %img2d
605 %ptr_fixed = OpTypePointer UniformConstant %fixed_arr
606 %ptr_ubo = OpTypePointer Uniform %ubo_blk
607 %ptr_mis_sb = OpTypePointer StorageBuffer %fixed_arr
608%ptr_dangling = OpTypePointer UniformConstant %missing_pointee
609 %single = OpVariable %ptr_single UniformConstant
610 %fixed = OpVariable %ptr_fixed UniformConstant
611 %ubo = OpVariable %ptr_ubo Uniform
612 %mismatch = OpVariable %ptr_mis_sb UniformConstant
613 %dangling = OpVariable %ptr_dangling UniformConstant
614"""
615 counts = [10, 20, 1, 5, 2]
616 out = m.rewrite(module, counts)
617 self.assertIn("OpDecorate %single Binding 0", out)
618 self.assertIn("OpDecorate %fixed Binding 10", out)
619 self.assertIn("OpDecorate %ubo Binding 30", out)
620 self.assertIn("OpDecorate %mismatch Binding 31", out)
621 self.assertIn("OpDecorate %dangling Binding 36", out)
622 self.assertIn("%single = OpVariable %ptr_single UniformConstant", out)
623 self.assertIn("%fixed = OpVariable %ptr_fixed UniformConstant", out)
624 self.assertIn("%ubo = OpVariable %ptr_ubo Uniform", out)
625 self.assertIn("%mismatch = OpVariable %ptr_mis_sb UniformConstant", out)
626 self.assertIn("%dangling = OpVariable %ptr_dangling UniformConstant", out)
627 self.assertNotIn("%msl_", out)
628
629 def test_partial_decorations_and_missing_var_def(self):
630 module = """\
631OpDecorate %only_set DescriptorSet 0
632OpDecorate %only_bind Binding 1
633OpDecorate %orphan DescriptorSet 0
634OpDecorate %orphan Binding 1
635%u = OpTypeInt 32 0
636"""
637 out = m.rewrite(module, [5, 7])
638 self.assertIn("OpDecorate %only_set DescriptorSet 0", out)
639 self.assertIn("OpDecorate %only_bind Binding 1", out)
640 self.assertIn("OpDecorate %orphan Binding 5", out)
641 self.assertNotIn("%msl_", out)
642
643 def test_raw_numeric_ids_custom_uint_and_crlf_and_shared_pointer(self):
644 module = (
645 "; Header comment\r\n"
646 "OpName %10 \"images\"\r\n"
647 "OpDecorate %10 DescriptorSet 0\r\n"
648 "OpDecorate %10 Binding 1\r\n"
649 "OpDecorate %11 DescriptorSet 0\r\n"
650 "OpDecorate %11 Binding 0\r\n"
651 "%1 = OpTypeVoid\r\n"
652 "%2 = OpTypeInt 32 1\r\n"
653 "%3 = OpTypeInt 64 0\r\n"
654 "%4 = OpTypeInt 32 0\r\n"
655 "%5 = OpTypeFloat 32\r\n"
656 "%6 = OpTypeImage %5 2D 0 0 0 1 Unknown\r\n"
657 "%7 = OpTypeRuntimeArray %6\r\n"
658 "%8 = OpTypePointer UniformConstant %7\r\n"
659 "%9 = OpTypePointer Function %5\r\n"
660 "%10 = OpVariable %8 UniformConstant\r\n"
661 "%11 = OpVariable %8 UniformConstant\r\n"
662 )
663 out = m.rewrite(module, [16, 8])
664 self.assertNotIn("\r\n", out)
665 self.assertTrue(out.endswith("\n"))
666 self.assertIn("OpDecorate %11 Binding 0", out)
667 self.assertIn("OpDecorate %10 Binding 16", out)
668 # First OpTypeInt 32 0 is %4 (not %2 signed or %3 64-bit).
669 self.assertIn("%msl_cap_b0 = OpConstant %4 16", out)
670 self.assertIn("%msl_cap_b1 = OpConstant %4 8", out)
671 self.assertIn("%11 = OpVariable %msl_ptr_b0 UniformConstant", out)
672 self.assertIn("%10 = OpVariable %msl_ptr_b1 UniformConstant", out)
673 # Sorted binding order (b0 then b1) inserted immediately after %8, not after %9.
674 lines = out.splitlines()
675 idx8 = lines.index("%8 = OpTypePointer UniformConstant %7")
676 self.assertEqual(lines[idx8 + 1 : idx8 + 7], [
677 "%msl_cap_b0 = OpConstant %4 16",
678 "%msl_arr_b0 = OpTypeArray %6 %msl_cap_b0",
679 "%msl_ptr_b0 = OpTypePointer UniformConstant %msl_arr_b0",
680 "%msl_cap_b1 = OpConstant %4 8",
681 "%msl_arr_b1 = OpTypeArray %6 %msl_cap_b1",
682 "%msl_ptr_b1 = OpTypePointer UniformConstant %msl_arr_b1",
683 ])
684 idx9 = lines.index("%9 = OpTypePointer Function %5")
685 self.assertEqual(lines[idx9 + 1], "%10 = OpVariable %msl_ptr_b1 UniformConstant")
686
687 def test_empty_and_no_set0_modules(self):
688 self.assertEqual(m.rewrite("", [4]), "\n")
689 plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n"
690 self.assertEqual(m.rewrite(plain, [4]), plain)
691
692 def test_out_of_bounds_set0_binding_raises_system_exit(self):
693 for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())):
694 with self.subTest(binding=b, count_len=len(counts)):
695 text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n"
696 with self.assertRaises(SystemExit) as ctx:
697 m.rewrite(text, counts)
698 self.assertIn("%bad", str(ctx.exception))
699 self.assertIn(f"binding {b}", str(ctx.exception))
700
701 def test_missing_uint32_type_raises_when_runtime_array_rewritten(self):
702 base = """\
703OpDecorate %images DescriptorSet 0
704OpDecorate %images Binding 0
705{int_decl}
706%float = OpTypeFloat 32
707%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown
708%rt_img = OpTypeRuntimeArray %img2d
709%ptr_img = OpTypePointer UniformConstant %rt_img
710%images = OpVariable %ptr_img UniformConstant
711"""
712 for label, int_decl in (
713 ("no_int", ""),
714 ("signed_32", "%s32 = OpTypeInt 32 1"),
715 ("unsigned_64", "%u64 = OpTypeInt 64 0"),
716 ):
717 with self.subTest(case=label):
718 with self.assertRaises(SystemExit) as ctx:
719 m.rewrite(base.format(int_decl=int_decl), [4096])
720 self.assertIn("no 32-bit uint type", str(ctx.exception))
721
722
723class TestMainAndCli(unittest.TestCase):
724 def _call_main(self, argv):
725 out, err = io.StringIO(), io.StringIO()
726 # tools/spirv_metal_set0.py:31 uses open(path).read() without a context manager, which emits
727 # ResourceWarning under unittest's default filter on redirected stderr; isolate tool stderr here.
728 with warnings.catch_warnings():
729 warnings.simplefilter("ignore", ResourceWarning)
730 with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
731 code = m.main(argv)
732 return code, out.getvalue(), err.getvalue()
733
734 def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self):
735 with mock.patch.object(m.subprocess, "run") as run_mock:
736 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"])
737 run_mock.assert_not_called()
738 self.assertEqual(code, 0)
739 self.assertEqual(err, "")
740 lines = out.splitlines()
741 self.assertEqual(len(lines), 26)
742 self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095")
743 self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119")
744 self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120")
745 self.assertEqual(lines[3], "binding 3: 1024 descriptors at IDs 5121..6144")
746 self.assertEqual(lines[4], "binding 4: 1024 descriptors at IDs 6145..7168")
747 self.assertEqual(lines[25], "binding 25: 256 descriptors at IDs 12289..12544")
748
749 def test_print_layout_uses_capacities_table(self):
750 with mock.patch.object(m, "capacities", return_value=[3, 1, 2]):
751 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"])
752 self.assertEqual(code, 0)
753 self.assertEqual(err, "")
754 self.assertEqual(out.splitlines(), [
755 "binding 0: 3 descriptors at IDs 0..2",
756 "binding 1: 1 descriptors at IDs 3..3",
757 "binding 2: 2 descriptors at IDs 4..5",
758 ])
759
760 def test_invalid_argc_returns_2_and_prints_usage_to_stderr(self):
761 bad_argvs = [
762 [],
763 ["spirv_metal_set0.py"],
764 ["spirv_metal_set0.py", "in.spv"],
765 ["spirv_metal_set0.py", "--unknown"],
766 ["spirv_metal_set0.py", "--print-layout", "in.spv", "out.spv"],
767 ["spirv_metal_set0.py", "in.spv", "out.spv", "extra"],
768 ]
769 for argv in bad_argvs:
770 with self.subTest(argv=argv), mock.patch.object(m.subprocess, "run") as run_mock:
771 code, out, err = self._call_main(argv)
772 run_mock.assert_not_called()
773 self.assertEqual(code, 2)
774 self.assertEqual(out, "")
775 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err)
776 self.assertIn("--print-layout", err)
777
778 def test_print_layout_with_extra_arg_falls_through_to_two_arg_mode(self):
779 with mock.patch.object(
780 m.subprocess,
781 "run",
782 side_effect=[
783 subprocess.CompletedProcess([], 0, "OpCapability Shader\n", ""),
784 subprocess.CompletedProcess([], 0, "", ""),
785 ],
786 ) as run_mock:
787 code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout", "out.spv"])
788 self.assertEqual((code, out, err), (0, "", ""))
789 self.assertEqual(run_mock.call_args_list[0].args[0], ["spirv-dis", "--print-layout"])
790 self.assertEqual(
791 run_mock.call_args_list[1].args[0],
792 ["spirv-as", "--target-env", "vulkan1.2", "-", "-o", "out.spv"],
793 )
794
795 def test_cli_subprocess_isolated_print_layout_and_bad_args(self):
796 r_layout = subprocess.run(
797 [sys.executable, "-I", TOOL_PATH, "--print-layout"],
798 capture_output=True,
799 text=True,
800 cwd=ROOT,
801 )
802 self.assertEqual(r_layout.returncode, 0, r_layout.stderr)
803 self.assertEqual(r_layout.stderr, "")
804 self.assertEqual(len(r_layout.stdout.splitlines()), 26)
805 self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095")
806
807 for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]):
808 with self.subTest(args=args):
809 r = subprocess.run(
810 [sys.executable, "-I", TOOL_PATH, *args],
811 capture_output=True,
812 text=True,
813 cwd=ROOT,
814 )
815 self.assertEqual(r.returncode, 2)
816 self.assertEqual(r.stdout, "")
817 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", r.stderr)
818 self.assertNotIn("Traceback", r.stderr)
819
820 def test_synthetic_spv_out_of_place_and_in_place_binary_round_trip(self):
821 in_bytes = _pack_spv(_build_mixed_bindless_spv_words(), version=SPIRV_VERSION_1_5)
822 fake_run, calls = _make_fake_spirv_tools()
823
824 with tempfile.TemporaryDirectory() as tmp:
825 unicode_dir = os.path.join(tmp, "dir-\u00e9-\u2603")
826 os.makedirs(unicode_dir)
827 in_path = os.path.join(unicode_dir, "in.spv")
828 out_path = os.path.join(unicode_dir, "out.spv")
829 with open(in_path, "wb") as f:
830 f.write(in_bytes)
831
832 with mock.patch.dict(os.environ, {}, clear=False), \
833 mock.patch.object(m.subprocess, "run", side_effect=fake_run):
834 os.environ.pop("SPIRV_DIS", None)
835 os.environ.pop("SPIRV_AS", None)
836 code, out, err = self._call_main(["spirv_metal_set0.py", in_path, out_path])
837
838 self.assertEqual(code, 0)
839 self.assertEqual(out, "")
840 self.assertEqual(err, "")
841 self.assertEqual(calls, [
842 ["spirv-dis", in_path],
843 ["spirv-as", "--target-env", "spv1.5", "-", "-o", out_path],
844 ])
845
846 # Original input file is preserved untouched for out-of-place conversion.
847 with open(in_path, "rb") as f:
848 self.assertEqual(f.read(), in_bytes)
849
850 with open(out_path, "rb") as f:
851 out_bytes = f.read()
852 header, insts = _decode_spv(out_bytes)
853 self.assertEqual(header[0], SPIRV_MAGIC)
854 self.assertEqual(header[1], SPIRV_VERSION_1_5)
855 self.assertEqual(header[4], 0)
856
857 decs = [ops for op, ops in insts if op == OP_DECORATE]
858 bindings_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_BINDING}
859 sets_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_DESCRIPTOR_SET}
860 self.assertEqual(sets_by_id, {13: 0, 14: 0, 15: 0, 17: 1})
861 # Set-0 bindings rewritten per vulkan_bindless.h; set-1 binding 0 stays 0.
862 self.assertEqual(bindings_by_id, {13: 0, 14: 4096, 15: 5120, 17: 0})
863
864 consts = {ops[1]: ops[2] for op, ops in insts if op == OP_CONSTANT}
865 arrays = {ops[0]: (ops[1], consts[ops[2]]) for op, ops in insts if op == OP_TYPE_ARRAY}
866 ptrs = {ops[0]: (ops[1], ops[2]) for op, ops in insts if op == OP_TYPE_POINTER}
867 vars_by_id = {ops[1]: (ops[0], ops[2]) for op, ops in insts if op == OP_VARIABLE}
868
869 # %13 (images) and %14 (samplers) are retyped to sized arrays [4096] and [1024];
870 # %15 (desc_map StorageBuffer), %16 (PushConstant), and %17 (set 1) keep original types.
871 self.assertEqual(arrays[ptrs[vars_by_id[13][0]][1]], (3, 4096))
872 self.assertEqual(arrays[ptrs[vars_by_id[14][0]][1]], (4, 1024))
873 self.assertEqual(vars_by_id[15], (11, SC_STORAGE_BUFFER))
874 self.assertEqual(vars_by_id[16], (12, SC_PUSH_CONSTANT))
875 self.assertEqual(vars_by_id[17], (7, SC_UNIFORM_CONSTANT))
876
877 # In-place conversion: argv[1] == argv[2].
878 inplace_path = os.path.join(unicode_dir, "inplace.spv")
879 with open(inplace_path, "wb") as f:
880 f.write(in_bytes)
881 calls.clear()
882 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
883 code, out, err = self._call_main(["spirv_metal_set0.py", inplace_path, inplace_path])
884 self.assertEqual(code, 0)
885 self.assertEqual(out, "")
886 self.assertEqual(err, "")
887 self.assertEqual(calls, [
888 ["spirv-dis", inplace_path],
889 ["spirv-as", "--target-env", "spv1.5", "-", "-o", inplace_path],
890 ])
891 with open(inplace_path, "rb") as f:
892 self.assertEqual(f.read(), out_bytes)
893
894 def test_target_env_extraction_and_env_var_overrides(self):
895 cases = [
896 ("; Version: 1.0\n", "spv1.0"),
897 ("; SPIR-V\n; Version: 1.5\n", "spv1.5"),
898 ("; Version: 1.6\n", "spv1.6"),
899 ("; SPIR-V without version comment\n", "vulkan1.2"),
900 ]
901 for header_text, expected_target in cases:
902 with self.subTest(expected_target=expected_target):
903 disasm = header_text + "OpCapability Shader\n"
904 seen_cmds = []
905
906 def run_stub(cmd, check=False, capture_output=False, text=False, input=None):
907 seen_cmds.append((list(cmd), check, capture_output, text, input))
908 if len(seen_cmds) == 1:
909 return subprocess.CompletedProcess(cmd, 0, disasm, "")
910 return subprocess.CompletedProcess(cmd, 0, "", "")
911
912 with mock.patch.dict(os.environ, {"SPIRV_DIS": "/opt/bin/dis", "SPIRV_AS": "/opt/bin/as"}), \
913 mock.patch.object(m.subprocess, "run", side_effect=run_stub):
914 code, out, err = self._call_main(["spirv_metal_set0.py", "in.spv", "out.spv"])
915
916 self.assertEqual((code, out, err), (0, "", ""))
917 self.assertEqual(seen_cmds[0][0], ["/opt/bin/dis", "in.spv"])
918 self.assertTrue(seen_cmds[0][1])
919 self.assertTrue(seen_cmds[0][2])
920 self.assertTrue(seen_cmds[0][3])
921 self.assertEqual(seen_cmds[1][0], ["/opt/bin/as", "--target-env", expected_target, "-", "-o", "out.spv"])
922 self.assertTrue(seen_cmds[1][1])
923 self.assertTrue(seen_cmds[1][3])
924 self.assertEqual(seen_cmds[1][4], disasm)
925
926 def test_invalid_spirv_binary_words_and_missing_or_directory_paths(self):
927 fake_run, calls = _make_fake_spirv_tools()
928 valid_words = _build_mixed_bindless_spv_words()
929
930 bad_inputs = [
931 ("empty_file", b""),
932 ("truncated_header_8B", struct.pack("<2I", SPIRV_MAGIC, SPIRV_VERSION_1_5)),
933 ("unaligned_21B", _pack_spv([], bound=1) + b"\x00"),
934 ("big_endian_magic", struct.pack(">5I", SPIRV_MAGIC, SPIRV_VERSION_1_5, 0, 2, 0)),
935 ("wrong_magic", struct.pack("<5I", 0xDEADBEEF, SPIRV_VERSION_1_5, 0, 2, 0)),
936 ("non_zero_schema", _pack_spv([], bound=1, schema=1)),
937 ("zero_bound", _pack_spv([], bound=0)),
938 ("zero_word_count_inst", _pack_spv([OP_CAPABILITY], bound=2)),
939 ("truncated_inst_bounds", _pack_spv(valid_words[:-1], bound=18)),
940 ]
941 with tempfile.TemporaryDirectory() as tmp:
942 for label, blob in bad_inputs:
943 with self.subTest(case=label):
944 calls.clear()
945 in_path = os.path.join(tmp, f"{label}.spv")
946 out_path = os.path.join(tmp, f"{label}.out.spv")
947 with open(in_path, "wb") as f:
948 f.write(blob)
949 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
950 with self.assertRaises(subprocess.CalledProcessError):
951 m.main(["spirv_metal_set0.py", in_path, out_path])
952 self.assertEqual(calls, [["spirv-dis", in_path]])
953 self.assertFalse(os.path.exists(out_path))
954
955 # Missing input file and directory passed as input file both fail at spirv-dis.
956 missing_in = os.path.join(tmp, "does_not_exist.spv")
957 dir_in = os.path.join(tmp, "a_directory")
958 os.makedirs(dir_in)
959 for label, bad_path in (("missing_file", missing_in), ("directory_input", dir_in)):
960 with self.subTest(case=label):
961 calls.clear()
962 out_path = os.path.join(tmp, f"{label}.out.spv")
963 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
964 with self.assertRaises(subprocess.CalledProcessError):
965 m.main(["spirv_metal_set0.py", bad_path, out_path])
966 self.assertEqual(calls, [["spirv-dis", bad_path]])
967 self.assertFalse(os.path.exists(out_path))
968
969 def test_spirv_as_failure_missing_executable_and_rewrite_abort(self):
970 with tempfile.TemporaryDirectory() as tmp:
971 in_path = os.path.join(tmp, "in.spv")
972 out_path = os.path.join(tmp, "out.spv")
973 with open(in_path, "wb") as f:
974 f.write(_pack_spv(_build_mixed_bindless_spv_words()))
975
976 # 1. Missing spirv-dis binary raises FileNotFoundError before calling spirv-as.
977 with mock.patch.object(m.subprocess, "run", side_effect=FileNotFoundError("no spirv-dis")) as run_mock:
978 with self.assertRaises(FileNotFoundError):
979 m.main(["spirv_metal_set0.py", in_path, out_path])
980 self.assertEqual(run_mock.call_count, 1)
981 self.assertFalse(os.path.exists(out_path))
982
983 # 2. rewrite() SystemExit aborts before spirv-as is invoked.
984 bad_spv = _pack_spv([
985 *_encode_inst(OP_DECORATE, 2, DEC_DESCRIPTOR_SET, 0),
986 *_encode_inst(OP_DECORATE, 2, DEC_BINDING, 99),
987 ], bound=3)
988 with open(in_path, "wb") as f:
989 f.write(bad_spv)
990 fake_run, calls = _make_fake_spirv_tools()
991 with mock.patch.object(m.subprocess, "run", side_effect=fake_run):
992 with self.assertRaises(SystemExit) as ctx:
993 m.main(["spirv_metal_set0.py", in_path, out_path])
994 self.assertIn("binding 99", str(ctx.exception))
995 self.assertEqual(calls, [["spirv-dis", in_path]])
996 self.assertFalse(os.path.exists(out_path))
997
998 # 3. spirv-as failure raises CalledProcessError.
999 dis_ok = subprocess.CompletedProcess(["spirv-dis", in_path], 0, "; Version: 1.5\nOpCapability Shader\n", "")
1000 asm_fail = subprocess.CalledProcessError(1, ["spirv-as"], stderr="bad asm")
1001 with mock.patch.object(m.subprocess, "run", side_effect=[dis_ok, asm_fail]) as run_mock:
1002 with self.assertRaises(subprocess.CalledProcessError):
1003 m.main(["spirv_metal_set0.py", in_path, out_path])
1004 self.assertEqual(run_mock.call_count, 2)
1005
1006 def test_main_guard_handles_stdout_reconfigure_errors_and_exit_codes(self):
1007 class _Stream(io.StringIO):
1008 def __init__(self, exc):
1009 super().__init__()
1010 self._exc = exc
1011
1012 def reconfigure(self, **_kwargs):
1013 raise self._exc
1014
1015 for exc in (AttributeError("no reconfigure"), ValueError("bad"), OSError("io")):
1016 with self.subTest(exc=type(exc).__name__):
1017 out_stream = _Stream(exc)
1018 err_stream = io.StringIO()
1019 with warnings.catch_warnings():
1020 warnings.simplefilter("ignore", ResourceWarning)
1021 with mock.patch.object(sys, "argv", ["spirv_metal_set0.py", "--print-layout"]), \
1022 mock.patch.object(sys, "stdout", out_stream), \
1023 mock.patch.object(sys, "stderr", err_stream):
1024 with self.assertRaises(SystemExit) as ctx:
1025 runpy.run_path(TOOL_PATH, run_name="__main__")
1026 self.assertEqual(ctx.exception.code, 0)
1027 self.assertEqual(err_stream.getvalue(), "")
1028 self.assertEqual(len(out_stream.getvalue().splitlines()), 26)
1029
1030 err_stream = io.StringIO()
1031 with warnings.catch_warnings():
1032 warnings.simplefilter("ignore", ResourceWarning)
1033 with mock.patch.object(sys, "argv", ["spirv_metal_set0.py"]), \
1034 mock.patch.object(sys, "stdout", io.StringIO()), \
1035 mock.patch.object(sys, "stderr", err_stream):
1036 with self.assertRaises(SystemExit) as ctx:
1037 runpy.run_path(TOOL_PATH, run_name="__main__")
1038 self.assertEqual(ctx.exception.code, 2)
1039 self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err_stream.getvalue())
1040
1041
1042if __name__ == "__main__":
1043 unittest.main()
diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py
index 670b92df6..2714d2b90 100644
--- a/tests/test_text_tables.py
+++ b/tests/test_text_tables.py
@@ -178,6 +178,62 @@ class TestCli(unittest.TestCase):
178 with open(outs["strings"], encoding="utf-8", newline="") as fh: 178 with open(outs["strings"], encoding="utf-8", newline="") as fh:
179 strings = list(csv.DictReader(fh)) 179 strings = list(csv.DictReader(fh))
180 self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) 180 self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings})
181 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")],
182 "staging files must not be left behind")
183
184 def test_failed_later_write_leaves_earlier_reports_intact(self):
185 with tempfile.TemporaryDirectory() as tmp:
186 src = os.path.join(tmp, "src")
187 os.mkdir(src)
188 write(os.path.join(src, "conv.pso"), CONV)
189 dialogue = os.path.join(tmp, "dialogue.csv")
190 old = "OLD GOOD REPORT\n"
191 with open(dialogue, "w", encoding="utf-8") as fh:
192 fh.write(old)
193 tables = os.path.join(tmp, "tables.csv")
194 os.mkdir(tables) # a later output that cannot be written
195 with contextlib.redirect_stderr(io.StringIO()) as err:
196 self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2)
197 self.assertIn("cannot write", err.getvalue())
198 with open(dialogue, encoding="utf-8") as fh:
199 self.assertEqual(fh.read(), old)
200 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")])
201
202 @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader")
203 def test_reader_holding_a_later_report_keeps_all_reports(self):
204 with tempfile.TemporaryDirectory() as tmp:
205 src = os.path.join(tmp, "src")
206 os.mkdir(src)
207 write(os.path.join(src, "conv.pso"), CONV)
208 dialogue = os.path.join(tmp, "dialogue.csv")
209 tables = os.path.join(tmp, "tables.csv")
210 old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n"
211 for path, text in ((dialogue, old_dialogue), (tables, old_tables)):
212 with open(path, "w", encoding="utf-8") as fh:
213 fh.write(text)
214 with open(tables, "rb"): # a reader keeps the second output open
215 with contextlib.redirect_stderr(io.StringIO()) as err:
216 self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2)
217 self.assertIn("cannot write", err.getvalue())
218 with open(dialogue, encoding="utf-8") as fh:
219 self.assertEqual(fh.read(), old_dialogue)
220 with open(tables, encoding="utf-8") as fh:
221 self.assertEqual(fh.read(), old_tables)
222 self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")],
223 "staging and backup files must not be left behind")
224
225 def test_two_outputs_naming_one_file_are_refused(self):
226 with tempfile.TemporaryDirectory() as tmp:
227 src = os.path.join(tmp, "src")
228 os.mkdir(src)
229 write(os.path.join(src, "conv.pso"), CONV)
230 out = os.path.join(tmp, "same.csv")
231 with contextlib.redirect_stderr(io.StringIO()) as err:
232 with self.assertRaises(SystemExit) as cm:
233 T.main([src, "--dialogue", out, "--tables", out])
234 self.assertEqual(cm.exception.code, 2)
235 self.assertIn("distinct", err.getvalue())
236 self.assertFalse(os.path.exists(out), "no report may be written before the check")
181 237
182 def test_missing_input(self): 238 def test_missing_input(self):
183 with contextlib.redirect_stderr(io.StringIO()): 239 with contextlib.redirect_stderr(io.StringIO()):
diff --git a/tests/test_text_write_line_endings.py b/tests/test_text_write_line_endings.py
new file mode 100644
index 000000000..e8be2944b
--- /dev/null
+++ b/tests/test_text_write_line_endings.py
@@ -0,0 +1,88 @@
1"""Every text-mode file write in the Python tools names its line ending (BUILD-468).
2
3`open(path, "w")` with no `newline=` turns each "\\n" into "\\r\\n" on Windows, so the same JSON report, manifest or
4assembly listing is CRLF there and LF on Linux and macOS: the same input gives byte-different output per platform
5(checksums and diffs differ). The CSV writers were fixed in #1573; this covers the other text writers. This test reads
6the source with `ast` (standard library, no game data, no GPU) and fails for any `open` / `os.fdopen` in a text write
7mode (`w`, `a`, `x`) or any `Path.write_text` under tools/, scripts/, make_game.py and runtime/test/shaders/ that has
8no `newline=` argument. Pass `newline="\\n"` for LF output (or `newline=""` when the text carries its own line ends,
9like a csv writer).
10"""
11import ast
12import os
13import sys
14import unittest
15
16HERE = os.path.dirname(os.path.abspath(__file__))
17ROOT = os.path.dirname(HERE)
18SCAN = ("tools", "scripts", "make_game.py", os.path.join("runtime", "test", "shaders"))
19
20
21def python_files():
22 for entry in SCAN:
23 path = os.path.join(ROOT, entry)
24 if os.path.isfile(path):
25 yield path
26 continue
27 for base, dirs, files in os.walk(path):
28 dirs[:] = [d for d in dirs if d not in ("__pycache__", "build") and not d.startswith(".")]
29 for name in sorted(files):
30 if name.endswith(".py"):
31 yield os.path.join(base, name)
32
33
34def unpinned_text_writes(source: str):
35 """Line numbers of text-mode writes in `source` that pass no `newline=`."""
36 found = []
37 for node in ast.walk(ast.parse(source)):
38 if not isinstance(node, ast.Call):
39 continue
40 func = node.func
41 name = getattr(func, "attr", getattr(func, "id", None))
42 if any(k.arg == "newline" for k in node.keywords):
43 continue
44 if name in ("open", "fdopen"):
45 mode = None
46 if len(node.args) >= 2 and isinstance(node.args[1], ast.Constant):
47 mode = node.args[1].value
48 for k in node.keywords:
49 if k.arg == "mode" and isinstance(k.value, ast.Constant):
50 mode = k.value.value
51 if isinstance(mode, str) and "b" not in mode and any(c in mode for c in "wax"):
52 found.append(node.lineno)
53 elif name == "write_text":
54 found.append(node.lineno)
55 return found
56
57
58class TextWriteLineEndings(unittest.TestCase):
59 def test_detector_finds_the_unpinned_forms(self):
60 src = (
61 "open('a', 'w')\n" # 1
62 "open('a', 'w', encoding='utf-8')\n" # 2
63 "open('a', mode='a')\n" # 3
64 "os.fdopen(3, 'w', encoding='utf-8')\n" # 4
65 "p.write_text('x', encoding='utf-8')\n" # 5
66 "open('a', 'w', newline='\\n')\n" # pinned
67 "open('a', 'w', newline='')\n" # pinned
68 "open('a', 'wb')\n" # binary
69 "open('a')\n" # read
70 "open('a', 'r', encoding='utf-8')\n" # read
71 "p.write_text('x', newline='\\n')\n" # pinned
72 )
73 self.assertEqual(unpinned_text_writes(src), [1, 2, 3, 4, 5])
74
75 def test_every_text_write_pins_its_newline(self):
76 bad = []
77 count = 0
78 for path in python_files():
79 count += 1
80 with open(path, encoding="utf-8") as f:
81 for line in unpinned_text_writes(f.read()):
82 bad.append(f"{os.path.relpath(path, ROOT)}:{line}")
83 self.assertGreater(count, 50, "the scan found almost no Python files; is the layout different?")
84 self.assertEqual(bad, [], "text writes without newline= (CRLF on Windows, LF elsewhere): " + ", ".join(bad))
85
86
87if __name__ == "__main__":
88 unittest.main()
diff --git a/tests/test_tool_startup.py b/tests/test_tool_startup.py
new file mode 100644
index 000000000..6933ad597
--- /dev/null
+++ b/tests/test_tool_startup.py
@@ -0,0 +1,72 @@
1"""Every tool that imports a sibling module starts under the project's own `python -I` convention.
2
3`-I` implies `-P`, so the script's directory is not put on `sys.path`; a tool that imports the module next to it
4has to add that directory itself (the pattern in `tools/anim_clips.py:40`). Two tools did not and died with
5`ModuleNotFoundError` before `main()` — `calibrated_texture.py` and `ttpf_assets.py` — which this test caught.
6
7The tool list is derived from the sources rather than written down, so a new tool with a sibling import is covered
8without touching this file. `--help` is used because it reaches the argument parser without game files or a GPU;
9the three module-only tools (`bcpack`, `calibrated_texture`, `cf_ref`) have no `__main__` and simply exit 0 on the
10import. Tools that need numpy are skipped where it is not installed, as the texture tools are allowed to use it.
11"""
12import ast
13import glob
14import importlib.util
15import os
16import subprocess
17import sys
18import unittest
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21ROOT = os.path.dirname(HERE)
22TOOLS = os.path.join(ROOT, "tools")
23TOOL_NAMES = {os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(TOOLS, "*.py"))}
24NUMERIC = {"amd_swizzle", "calibrated_texture", "swizzle_search", "tex_export", "tex_mode_probe", "tile_probe"}
25
26# One process per tool is a few seconds in total; a hung import is a failure, not an infinite test.
27TIMEOUT = 120
28
29
30def imports(path):
31 """The module names `path` imports at top level, relative imports excluded."""
32 names = set()
33 for node in ast.walk(ast.parse(open(path, encoding="utf-8").read())):
34 if isinstance(node, ast.Import):
35 names |= {alias.name.split(".")[0] for alias in node.names}
36 elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
37 names.add(node.module.split(".")[0])
38 return names
39
40
41def sibling_importers():
42 found = []
43 for path in sorted(glob.glob(os.path.join(TOOLS, "*.py"))):
44 own = os.path.splitext(os.path.basename(path))[0]
45 if imports(path) & (TOOL_NAMES - {own}):
46 found.append(path)
47 return found
48
49
50class ToolStartupTests(unittest.TestCase):
51 def test_each_sibling_importing_tool_starts(self):
52 paths = sibling_importers()
53 self.assertGreater(len(paths), 20, "the sibling-import scan found almost nothing")
54 have_numpy = importlib.util.find_spec("numpy") is not None
55 for path in paths:
56 name = os.path.splitext(os.path.basename(path))[0]
57 if name in NUMERIC and not have_numpy:
58 continue
59 with self.subTest(tool=name):
60 proc = subprocess.run([sys.executable, "-I", path, "--help"], capture_output=True, text=True,
61 timeout=TIMEOUT, errors="replace")
62 self.assertEqual(proc.returncode, 0, proc.stderr[-2000:])
63 self.assertNotIn("Traceback", proc.stderr)
64
65 def test_the_two_fixed_tools_are_in_the_scan(self):
66 names = {os.path.splitext(os.path.basename(path))[0] for path in sibling_importers()}
67 self.assertIn("calibrated_texture", names)
68 self.assertIn("ttpf_assets", names)
69
70
71if __name__ == "__main__":
72 unittest.main()
diff --git a/tests/test_user_sgpr_census.py b/tests/test_user_sgpr_census.py
index 4a94ff372..2c52fbe46 100644
--- a/tests/test_user_sgpr_census.py
+++ b/tests/test_user_sgpr_census.py
@@ -1,7 +1,12 @@
1"""tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU).""" 1"""tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU)."""
2import json 2import json
3import os 3import os
4from pathlib import Path
5import subprocess
4import sys 6import sys
7import tempfile
8
9import pytest
5 10
6ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 11ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7sys.path.insert(0, os.path.join(ROOT, "tools")) 12sys.path.insert(0, os.path.join(ROOT, "tools"))
@@ -73,9 +78,62 @@ def test_the_two_packing_models_are_told_apart():
73 assert b["below_base"] == {"s1:const32": 1} 78 assert b["below_base"] == {"s1:const32": 1}
74 79
75 80
81@pytest.mark.parametrize("output_kind", ["same-path", "relative-alias", "hard-link"])
82def test_json_report_refuses_to_overwrite_index(tmp_path, capsys, output_kind):
83 index = tmp_path / "index.json"
84 original = json.dumps(INDEX).encode("utf-8")
85 index.write_bytes(original)
86 output = index
87 if output_kind == "relative-alias":
88 subdir = tmp_path / "subdir"
89 subdir.mkdir()
90 output = subdir / ".." / index.name
91 elif output_kind == "hard-link":
92 output = tmp_path / "alias.json"
93 try:
94 output.hardlink_to(index)
95 except OSError as err:
96 pytest.skip(f"hard links unavailable: {err}")
97
98 with pytest.raises(SystemExit) as exc:
99 usc.main([str(index), "--json", str(output)])
100
101 assert exc.value.code == 2
102 assert "--json must not overwrite the input index" in capsys.readouterr().err
103 assert index.read_bytes() == original
104
105
106def test_json_report_accepts_a_separate_output(tmp_path):
107 index = tmp_path / "index.json"
108 output = tmp_path / "summary.json"
109 index.write_text(json.dumps(INDEX), encoding="utf-8")
110
111 assert usc.main([str(index), "--json", str(output)]) == 0
112 assert json.loads(output.read_text(encoding="utf-8"))["ps"]["lowest_pointer_sgpr"] == {"s8": 2, "s9": 1}
113 assert json.loads(index.read_text(encoding="utf-8")) == INDEX
114
115
76def test_expect_passes_and_fails(tmp_path, capsys): 116def test_expect_passes_and_fails(tmp_path, capsys):
77 p = tmp_path / "index.json" 117 p = tmp_path / "index.json"
78 p.write_text(json.dumps(INDEX), encoding="utf-8") 118 p.write_text(json.dumps(INDEX), encoding="utf-8")
79 assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0 119 assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0
80 assert usc.main([str(p), "--expect", "ps=0"]) == 1 120 assert usc.main([str(p), "--expect", "ps=0"]) == 1
81 assert "expected s0, got s8" in capsys.readouterr().err 121 assert "expected s0, got s8" in capsys.readouterr().err
122
123
124def test_cli_rejects_malformed_stage_assignment():
125 with tempfile.TemporaryDirectory() as tmp:
126 index = Path(tmp, "index.json")
127 report = Path(tmp, "report.json")
128 index.write_text(json.dumps(INDEX), encoding="utf-8")
129 tool = os.path.join(ROOT, "tools", "user_sgpr_census.py")
130 for option in ("--base", "--expect"):
131 for assignment in ("ps", "ps=bad", "=8", "ps=-1"):
132 result = subprocess.run(
133 [sys.executable, "-I", tool, str(index), "--json", str(report), option, assignment],
134 capture_output=True, text=True,
135 )
136 assert result.returncode == 2, result.stderr
137 assert "expected STAGE=SGPR" in result.stderr
138 assert "Traceback" not in result.stderr
139 assert not report.exists()
diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs
index 596caaa19..666bd9ffc 100644
--- a/tests/test_viewer_streaming.cjs
+++ b/tests/test_viewer_streaming.cjs
@@ -6,6 +6,7 @@ const { test } = require('node:test');
6 6
7// Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. 7// Exercise the viewer's actual loading and streaming code without WebGL, a network or game data.
8const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); 8const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8');
9const viewerModule = html.match(/<script type="module">([\s\S]*?)<\/script>/)[1].replace(/^import .*;$/gm, '');
9const worldBegin = html.indexOf('// ---------- world description ----------'); 10const worldBegin = html.indexOf('// ---------- world description ----------');
10const worldEnd = html.indexOf('// Deterministic test terrain:', worldBegin); 11const worldEnd = html.indexOf('// Deterministic test terrain:', worldBegin);
11assert(worldBegin >= 0 && worldEnd > worldBegin, 'viewer world description section must exist'); 12assert(worldBegin >= 0 && worldEnd > worldBegin, 'viewer world description section must exist');
@@ -69,8 +70,21 @@ test('test mode, a missing manifest, and an unreadable manifest have distinct me
69 assert.match(unreachable.reason, /could not be loaded/); 70 assert.match(unreachable.reason, /could not be loaded/);
70}); 71});
71 72
73test('a WebGL startup error replaces the fly prompt and preserves the original error', async () => {
74 const error = new Error('Error creating WebGL context.');
75 const attributes = new Map();
76 const start = { textContent: 'Click to fly', style: {}, setAttribute: (name, value) => attributes.set(name, value) };
77 const startup = vm.runInNewContext(`(async () => { ${viewerModule} })()`, {
78 THREE: { WebGLRenderer: class { constructor() { throw error; } } },
79 document: { getElementById: id => { assert.equal(id, 'start'); return start; } },
80 });
81 await assert.rejects(startup, actual => actual === error);
82 assert.match(start.textContent, /Could not start WebGL/);
83 assert.equal(start.style.cursor, 'default');
84 assert.equal(attributes.get('role'), 'alert');
85});
86
72test('the bounds overlay creates helpers on the first G press and reuses them', async () => { 87test('the bounds overlay creates helpers on the first G press and reuses them', async () => {
73 const viewerModule = html.match(/<script type="module">([\s\S]*?)<\/script>/)[1].replace(/^import .*;$/gm, '');
74 const chunks = [worldChunk, { id: 'other', url: 'other.glb', bounds: [5, 6, 7, 8, 9, 10] }]; 88 const chunks = [worldChunk, { id: 'other', url: 'other.glb', bounds: [5, 6, 7, 8, 9, 10] }];
75 const handlers = new Map(); 89 const handlers = new Map();
76 const boundsGroup = await vm.runInNewContext(`(async () => { ${viewerModule}\nreturn boundsGroup; })()`, { 90 const boundsGroup = await vm.runInNewContext(`(async () => { ${viewerModule}\nreturn boundsGroup; })()`, {
diff --git a/tests/test_vk_pipeline_check_index.py b/tests/test_vk_pipeline_check_index.py
new file mode 100644
index 000000000..a94023c80
--- /dev/null
+++ b/tests/test_vk_pipeline_check_index.py
@@ -0,0 +1,65 @@
1"""vk_pipeline_check: a missing, unreadable or empty index.json is an error, not an empty corpus (TEST-257).
2
3It used to exit 0 after checking nothing. The index is read before Vulkan is loaded, so the failing cases need no GPU
4and no game data. A valid `{}` stays an intentionally empty index: it gets past the index (the run may then stop at
5Vulkan on a machine without a device, which is not what is checked here). Skips when vk_pipeline_check isn't built.
6Set LEONIDA_VK_PIPELINE_CHECK to use a binary elsewhere.
7"""
8import os
9import subprocess
10import tempfile
11import unittest
12from pathlib import Path
13
14ROOT = Path(__file__).resolve().parent.parent
15
16
17def find_binary():
18 env = os.environ.get("LEONIDA_VK_PIPELINE_CHECK")
19 if env:
20 return Path(env) if Path(env).is_file() else None
21 build = ROOT / "runtime" / "build"
22 for p in (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check", build / "Release" / "vk_pipeline_check.exe"):
23 if p.is_file():
24 return p
25 return None
26
27
28class IndexTest(unittest.TestCase):
29 @classmethod
30 def setUpClass(cls):
31 cls.exe = find_binary()
32 if cls.exe is None:
33 raise unittest.SkipTest("vk_pipeline_check isn't built (cmake -S runtime -B runtime/build/linux)")
34
35 def run_tool(self, index_text):
36 with tempfile.TemporaryDirectory() as d:
37 if index_text is not None:
38 Path(d, "index.json").write_text(index_text, encoding="utf-8")
39 return subprocess.run([str(self.exe), d], capture_output=True, text=True, timeout=60)
40
41 def assert_index_error(self, r):
42 self.assertEqual(r.returncode, 2, r.stderr)
43 self.assertIn("cannot use", r.stderr)
44 self.assertIn("index.json", r.stderr)
45
46 def test_missing_index_is_an_error(self):
47 self.assert_index_error(self.run_tool(None))
48
49 def test_empty_index_is_an_error(self):
50 self.assert_index_error(self.run_tool(""))
51
52 def test_whitespace_only_index_is_an_error(self):
53 self.assert_index_error(self.run_tool(" \n\t \n"))
54
55 def test_malformed_index_is_still_an_error(self):
56 self.assert_index_error(self.run_tool('{"a": '))
57
58 def test_valid_empty_object_is_an_empty_corpus(self):
59 r = self.run_tool("{}")
60 self.assertNotIn("cannot use", r.stderr)
61 self.assertIn("0 shaders in index", r.stderr)
62
63
64if __name__ == "__main__":
65 unittest.main()
diff --git a/tests/test_vk_pipeline_check_isolate.py b/tests/test_vk_pipeline_check_isolate.py
new file mode 100644
index 000000000..38147cbeb
--- /dev/null
+++ b/tests/test_vk_pipeline_check_isolate.py
@@ -0,0 +1,129 @@
1"""vk_pipeline_check --isolate: a module that kills the driver is recorded as failed and the pass goes on.
2
3No game data: five tiny compute shaders are assembled here with spirv-as. The crash is simulated with the tool's test
4hook VK_PIPELINE_CHECK_SIMULATE_CRASH (a signal raised just before the pipeline of the named module), so no crashing
5driver is needed. Skips (not fails) when vk_pipeline_check isn't built, spirv-as is missing, the platform is not POSIX
6or there is no usable Vulkan device. Pin a GPU with VK_LOADER_DRIVERS_SELECT / LEONIDA_VK_DEVICE as for the other
7Vulkan tools. Set LEONIDA_VK_PIPELINE_CHECK to use a binary elsewhere.
8"""
9import json
10import os
11import shutil
12import subprocess
13import tempfile
14import unittest
15from pathlib import Path
16
17ROOT = Path(__file__).resolve().parent.parent
18NAMES = ["m_alpha", "m_bravo", "m_charlie", "m_delta", "m_echo"]
19CRASHER = "m_charlie"
20
21ASM = """OpCapability Shader
22OpMemoryModel Logical GLSL450
23OpEntryPoint GLCompute %main "main"
24OpExecutionMode %main LocalSize {size} 1 1
25%void = OpTypeVoid
26%fn = OpTypeFunction %void
27%main = OpFunction %void None %fn
28%entry = OpLabel
29OpReturn
30OpFunctionEnd
31"""
32
33
34def find_binary():
35 env = os.environ.get("LEONIDA_VK_PIPELINE_CHECK")
36 if env:
37 return Path(env) if Path(env).is_file() else None
38 build = ROOT / "runtime" / "build"
39 for p in (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check"):
40 if p.is_file():
41 return p
42 return None
43
44
45class IsolateTest(unittest.TestCase):
46 @classmethod
47 def setUpClass(cls):
48 if os.name != "posix":
49 raise unittest.SkipTest("--isolate is POSIX only")
50 cls.exe = find_binary()
51 if cls.exe is None:
52 raise unittest.SkipTest("vk_pipeline_check isn't built (cmake -S runtime -B runtime/build/linux)")
53 spirv_as = shutil.which("spirv-as")
54 if not spirv_as:
55 raise unittest.SkipTest("spirv-as not found")
56 cls.tmp = tempfile.TemporaryDirectory()
57 cls.addClassCleanup(cls.tmp.cleanup)
58 cls.dir = Path(cls.tmp.name) / "spirv"
59 cls.dir.mkdir()
60 index = {}
61 for i, name in enumerate(NAMES):
62 asm = Path(cls.tmp.name) / (name + ".spvasm")
63 asm.write_text(ASM.format(size=1 << i))
64 subprocess.run([spirv_as, "--target-env", "vulkan1.1", str(asm), "-o", str(cls.dir / (name + ".spv"))],
65 check=True)
66 index[name] = {"stage": "cs", "subgroup_size": None, "features": []}
67 (cls.dir / "index.json").write_text(json.dumps(index))
68 probe = cls.run_tool([], cache=Path(cls.tmp.name) / "probe.cache")
69 if probe.returncode != 0 or "cs pipelines: 5 ok, 0 failed" not in probe.stdout:
70 raise unittest.SkipTest("no usable Vulkan device (exit %d): %s" % (probe.returncode, probe.stderr.strip()[-300:]))
71
72 @classmethod
73 def run_tool(cls, args, crash=None, cache=None):
74 env = dict(os.environ)
75 env.pop("VK_PIPELINE_CHECK_SIMULATE_CRASH", None)
76 if crash:
77 env["VK_PIPELINE_CHECK_SIMULATE_CRASH"] = crash
78 cmd = [str(cls.exe), str(cls.dir)] + ([str(cache)] if cache else []) + ["--jobs", "2"] + args
79 return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=300)
80
81 def cache(self, name):
82 return Path(self.tmp.name) / name
83
84 def test_normal_run_passes(self):
85 r = self.run_tool([], cache=self.cache("normal.cache"))
86 self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
87 self.assertIn("cs: 5 modules ok, 0 failed", r.stdout)
88 self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout)
89
90 def test_isolate_without_a_crash_matches_normal_counts(self):
91 r = self.run_tool(["--isolate", "--isolate-batch", "2"], cache=self.cache("iso_clean.cache"))
92 self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
93 self.assertIn("cs: 5 modules ok, 0 failed", r.stdout)
94 self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout)
95 self.assertNotIn("CRASH", r.stdout)
96
97 def test_without_isolate_the_driver_crash_ends_the_process(self):
98 r = self.run_tool([], crash=CRASHER, cache=self.cache("dies.cache"))
99 self.assertEqual(r.returncode, -8, r.stdout + r.stderr) # killed by SIGFPE: no summary, no exit status
100
101 def test_isolate_records_the_crashed_module_and_goes_on(self):
102 cache = self.cache("iso.cache")
103 for batch in ("5", "2", "1"): # one batch bisected down, several batches, one module at a time
104 with self.subTest(batch=batch):
105 r = self.run_tool(["--isolate", "--isolate-batch", batch], crash=CRASHER + ":SIGFPE", cache=cache)
106 self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr)
107 self.assertGreater(r.returncode, 0, "the parent itself must not die: " + r.stdout + r.stderr)
108 self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGFPE)" % CRASHER, r.stdout)
109 self.assertEqual(r.stdout.count("MODULE CRASH"), 1, r.stdout)
110 self.assertIn("cs: 4 modules ok, 0 failed", r.stdout)
111 self.assertIn("cs pipelines: 4 ok, 1 failed, 0 skipped", r.stdout)
112 self.assertIn("cs crashed the driver: 1", r.stdout)
113 for name in NAMES:
114 if name != CRASHER:
115 self.assertNotIn("FAIL " + name, r.stdout)
116 self.assertTrue(cache.is_file(), "the shared pipeline cache must survive the crash")
117
118 def test_other_signal(self):
119 r = self.run_tool(["--isolate"], crash=CRASHER + ":SEGV")
120 self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
121 self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGSEGV)" % CRASHER, r.stdout)
122
123 def test_isolate_rejects_stats(self):
124 r = self.run_tool(["--isolate", "--stats", str(self.cache("s.csv"))])
125 self.assertEqual(r.returncode, 2)
126
127
128if __name__ == "__main__":
129 unittest.main()
diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py
index a6fce5ea4..d8ca4ed0f 100644
--- a/tests/test_vk_subgroup_info.py
+++ b/tests/test_vk_subgroup_info.py
@@ -525,6 +525,67 @@ class QueryTest(unittest.TestCase):
525 self.assertEqual(res["device"], expected_name) 525 self.assertEqual(res["device"], expected_name)
526 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) 526 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE])
527 527
528 def test_leonida_vk_device_filters_case_insensitively_and_fails_on_no_match(self):
529 igpu = FakeDevice(
530 name="AMD Radeon(TM) 780M Graphics",
531 device_type=1,
532 subgroup_size=64,
533 min_subgroup_size=32,
534 max_subgroup_size=64,
535 )
536 dgpu = FakeDevice(
537 name="NVIDIA GeForce RTX 4070",
538 device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU,
539 subgroup_size=32,
540 min_subgroup_size=32,
541 max_subgroup_size=32,
542 )
543 other_dgpu = FakeDevice(
544 name="AMD Radeon RX 7900 XTX",
545 device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU,
546 subgroup_size=64,
547 min_subgroup_size=32,
548 max_subgroup_size=64,
549 )
550 old_match = FakeDevice(
551 name="Legacy Radeon 1.2",
552 api_version=(1 << 22) | (2 << 12),
553 )
554
555 # Unset or empty selects the last discrete GPU as usual.
556 for empty in ("",):
557 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": empty}):
558 res, _ = self._run_query(igpu, dgpu)
559 self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070")
560 self.assertFalse(res["native64"])
561
562 # Case-insensitive substring can select the integrated GPU over a later discrete GPU.
563 for filt in ("780m", "RADEON(tm) 780M", "amd radeon"):
564 with self.subTest(filter=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}):
565 res, vk = self._run_query(igpu, dgpu)
566 self.assertEqual(res["device"], "AMD Radeon(TM) 780M Graphics")
567 self.assertTrue(res["native64"])
568 # Non-matching discrete GPU was skipped before feature/queue queries.
569 self.assertEqual(vk.features_calls, [vk._device_handles[0]])
570 self.assertEqual(vk.queue_calls, [vk._device_handles[0], vk._device_handles[0]])
571
572 # Among multiple matching devices, the runtime's discrete/last-discrete rule still applies.
573 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "radeon"}):
574 res, _ = self._run_query(igpu, dgpu, other_dgpu)
575 self.assertEqual(res["device"], "AMD Radeon RX 7900 XTX")
576 with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "geforce"}):
577 res, _ = self._run_query(igpu, dgpu, other_dgpu)
578 self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070")
579
580 # A filter that matches no device (or only an unsuitable device) raises RuntimeError and destroys the instance.
581 for filt, devs in (("nomatch", (igpu, dgpu)), ("legacy", (old_match, dgpu))):
582 with self.subTest(no_match=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}):
583 vk = FakeVulkan(devices=devs)
584 with mock.patch.object(vk_info, "load_vulkan", return_value=vk):
585 with self.assertRaisesRegex(RuntimeError, rf"LEONIDA_VK_DEVICE={filt}"):
586 vk_info.query()
587 self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE])
588
528 def test_native64_conditions_and_boundaries(self): 589 def test_native64_conditions_and_boundaries(self):
529 both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT 590 both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT
530 cases = [ 591 cases = [
diff --git a/tests/test_wave64_graphics_scan.py b/tests/test_wave64_graphics_scan.py
index 45945cd29..1aff7139e 100644
--- a/tests/test_wave64_graphics_scan.py
+++ b/tests/test_wave64_graphics_scan.py
@@ -140,6 +140,15 @@ class ScanTests(unittest.TestCase):
140 140
141 141
142class CliTests(unittest.TestCase): 142class CliTests(unittest.TestCase):
143 def test_scan_ignores_shader_named_directories(self):
144 with tempfile.TemporaryDirectory() as src:
145 os.mkdir(os.path.join(src, "cache.s"))
146 name, text = PS_W64_SENSITIVE
147 with open(os.path.join(src, name), "w", encoding="utf-8") as f:
148 f.write(text)
149 report = scan.scan_directory(src)
150 self.assertEqual(report["per_stage"]["ps"]["shaders"], 1)
151
143 def test_missing_source_directory_raises_error(self): 152 def test_missing_source_directory_raises_error(self):
144 with self.assertRaises(SystemExit) as cm: 153 with self.assertRaises(SystemExit) as cm:
145 with contextlib.redirect_stderr(io.StringIO()): 154 with contextlib.redirect_stderr(io.StringIO()):
diff --git a/tests/test_wave64_halves_fixtures.py b/tests/test_wave64_halves_fixtures.py
index 8d0fbe584..7cf045ec9 100644
--- a/tests/test_wave64_halves_fixtures.py
+++ b/tests/test_wave64_halves_fixtures.py
@@ -1,9 +1,11 @@
1"""SHADER-10: the hand-written ps_w64_* fixtures get the tier their header names, and the census counts tiers. 1"""SHADER-10: the hand-written ps_w64_* and vs_w64_* fixtures get the tier their header names, and the census counts
2 2tiers.
3The fixtures (runtime/test/shaders/ps_w64_{a,b,c}_*.asm) are the GPU tests of w64_graphics.py: each was drawn on an 3
4AMD Radeon 880M with the fragment subgroup size required to 64 and to 32. Tier A and B fixtures gave identical images 4The fixtures (runtime/test/shaders/{ps,vs}_w64_{a,b,c}_*.asm) are the GPU tests of w64_graphics.py: each pixel fixture
5(and the words their header derives), tier C fixtures differed, so this test pins the translator's detector to what 5was drawn on an AMD Radeon 880M with the fragment subgroup size required to 64 and to 32, each vertex fixture (TEST-251)
6the hardware showed. Needs llvm-mc with the AMDGPU target and spirv-as / spirv-val, like the other tests that build 6on an RX 9070 XT and a Ryzen 9800X3D iGPU (RADV) with the VS stage at wave64 and at wave32 (RADV_PERFTEST=gewave32).
7Tier A and B fixtures gave identical words (and the words their header derives), tier C fixtures differed, so this
8test pins the translator's detector to what the hardware showed. Needs llvm-mc with the AMDGPU target and spirv-as / spirv-val, like the other tests that build
7shaders; the pure-Python parts run without them. 9shaders; the pure-Python parts run without them.
8""" 10"""
9import json 11import json
@@ -38,11 +40,18 @@ EXPECT = {
38 "ps_w64_c_vote_else": ("C", ["unsafe-vote-branch"], None), 40 "ps_w64_c_vote_else": ("C", ["unsafe-vote-branch"], None),
39 "ps_w64_c_scc_vote": ("C", ["cross-lane"], None), 41 "ps_w64_c_scc_vote": ("C", ["cross-lane"], None),
40 "ps_w64_c_execz_sgpr": ("C", ["stale-scalar", "unsafe-execz-branch"], None), 42 "ps_w64_c_execz_sgpr": ("C", ["stale-scalar", "unsafe-execz-branch"], None),
43 "vs_w64_a_skip": ("A", [], []),
44 "vs_w64_b_waterfall": ("B", [], ["waterfall"]),
45 "vs_w64_b_readlane_uniform": ("B", [], ["readfirstlane-uniform", "readlane-uniform"]),
46 "vs_w64_b_ballot_atomic": ("B", [], ["aggregated-atomic", "elected-lane"]),
47 "vs_w64_c_bcnt_export": ("C", ["lane-count"], None),
48 "vs_w64_c_readlane": ("C", ["cross-lane"], None),
49 "vs_w64_c_lane_id": ("C", ["lane-id"], None),
41} 50}
42 51
43 52
44def test_every_fixture_has_a_tier_and_a_gpu_check(): 53def test_every_fixture_has_a_tier_and_a_gpu_check():
45 asm = {f[:-4] for f in os.listdir(SHADERS) if f.startswith("ps_w64_") and f.endswith(".asm")} 54 asm = {f[:-4] for f in os.listdir(SHADERS) if f.startswith(("ps_w64_", "vs_w64_")) and f.endswith(".asm")}
46 assert asm == set(EXPECT) == set(w64_graphics.FIXTURES) 55 assert asm == set(EXPECT) == set(w64_graphics.FIXTURES)
47 for name, (tier, _, _) in EXPECT.items(): 56 for name, (tier, _, _) in EXPECT.items():
48 assert w64_graphics.FIXTURES[name][0] == tier 57 assert w64_graphics.FIXTURES[name][0] == tier
@@ -125,3 +134,15 @@ def test_expected_words_of_the_gpu_fixtures():
125 assert w64_graphics._a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3) 134 assert w64_graphics._a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3)
126 assert w64_graphics._b_waterfall(5 + 64 * 6) == (17 * ((5 & 3) + 4 * (6 & 3)) + 5, (5 & 3) + 4 * (6 & 3), 0, 0) 135 assert w64_graphics._b_waterfall(5 + 64 * 6) == (17 * ((5 & 3) + 4 * (6 & 3)) + 5, (5 & 3) + 4 * (6 & 3), 0, 0)
127 assert w64_graphics._b_readfirstlane(10) == (133, 277, 0, 0) 136 assert w64_graphics._b_readfirstlane(10) == (133, 277, 0, 0)
137 assert w64_graphics._vs_a_skip(1 + 64 * 3) == (7 * 3 + 1, 1, 2000 + 3, 2) # no whole-quad word in r1
138 assert w64_graphics._vs_a_skip(6 + 64 * 2) == (1006, 0, 2000 + 2 + 9, 3)
139 assert w64_graphics._vs_b_readlane_uniform(70) == (6 + 123, 200, 6 + 123, 277)
140 assert w64_graphics._vs_c_lane_id(700) == (None, None, 700, 0)
141
142
143def test_vs_probe_and_radv_perftest(monkeypatch):
144 monkeypatch.setenv("RADV_PERFTEST", "gewave32,nggc")
145 assert w64_graphics._radv_perftest(64) == "nggc" # the user's other flags stay, gewave32 goes
146 assert w64_graphics._radv_perftest(32) == "nggc,gewave32"
147 assert w64_graphics.FIXTURES[w64_graphics.VS_PROBE][0] == "C"
148 assert w64_graphics.VS_RECORDS * 4 >= 0x100 + 4 * w64_graphics.VS_VERTICES # the atomic's slots end below the records
diff --git a/tests/test_world_index.py b/tests/test_world_index.py
index 7f6d39569..93ca58e68 100644
--- a/tests/test_world_index.py
+++ b/tests/test_world_index.py
@@ -609,6 +609,22 @@ class WorldIndexTest(unittest.TestCase):
609 rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) 609 rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10))
610 self.assertEqual(rows, []) 610 self.assertEqual(rows, [])
611 611
612 def test_carved_file_inflate_cap_matches_directory_scan(self):
613 resource = make_resource()
614 path = os.path.join(self.dir, "sample.bin")
615 with open(path, "wb") as f:
616 f.write(resource)
617
618 for source in (path, self.dir):
619 for cap, expected in ((len(resource) - 1, 0), (len(resource), 1)):
620 with self.subTest(source=source, cap=cap):
621 entities = []
622 rows, stats = WI.scan_path(source, max_inflate=cap, collect=entities)
623 self.assertEqual(len(rows), expected)
624 self.assertEqual(len(entities), expected)
625 self.assertEqual(stats["files"], expected)
626 self.assertEqual(stats["scanned_bytes"], expected * len(resource))
627
612 def test_directory_inflate_cap_does_not_exclude_large_archives(self): 628 def test_directory_inflate_cap_does_not_exclude_large_archives(self):
613 resource = make_resource() 629 resource = make_resource()
614 cap = len(resource) 630 cap = len(resource)
diff --git a/tests/test_world_lights_paths.py b/tests/test_world_lights_paths.py
index 2ca8d6052..7ab8a665d 100644
--- a/tests/test_world_lights_paths.py
+++ b/tests/test_world_lights_paths.py
@@ -371,6 +371,16 @@ class ScanTest(unittest.TestCase):
371 two = T.summarize(T.scan(self.rpf, jobs=2)) 371 two = T.summarize(T.scan(self.rpf, jobs=2))
372 self.assertEqual(one, two) 372 self.assertEqual(one, two)
373 373
374 def test_cli_rejects_shared_report_destination(self):
375 out = os.path.join(self.tmp.name, "lights.json")
376 alias = os.path.join(self.tmp.name, ".", "lights.json")
377 err = io.StringIO()
378 with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm:
379 T.main([self.rpf, "--out", out, "--lights-out", alias])
380 self.assertEqual(cm.exception.code, 2)
381 self.assertIn("--out and --lights-out must use different paths", err.getvalue())
382 self.assertFalse(os.path.exists(out))
383
374 def test_cli_writes_summary_and_placed_lights(self): 384 def test_cli_writes_summary_and_placed_lights(self):
375 out = os.path.join(self.tmp.name, "summary.json") 385 out = os.path.join(self.tmp.name, "summary.json")
376 lights = os.path.join(self.tmp.name, "lights.jsonl") 386 lights = os.path.join(self.tmp.name, "lights.jsonl")
diff --git a/tests/test_world_names.py b/tests/test_world_names.py
index 772e1b1d4..08b80483a 100644
--- a/tests/test_world_names.py
+++ b/tests/test_world_names.py
@@ -337,7 +337,7 @@ class CliTest(unittest.TestCase):
337 err = io.StringIO() 337 err = io.StringIO()
338 with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): 338 with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
339 self.assertNotEqual(WN.main(["resolve", *prefix, "--out", source]), 0) 339 self.assertNotEqual(WN.main(["resolve", *prefix, "--out", source]), 0)
340 self.assertIn(repr(source), err.getvalue()) 340 self.assertIn(f"would overwrite input {source}", err.getvalue())
341 with open(source, "rb") as handle: 341 with open(source, "rb") as handle:
342 self.assertEqual(handle.read(), original) 342 self.assertEqual(handle.read(), original)
343 343
diff --git a/tools/ab_control_flow.py b/tools/ab_control_flow.py
index 577c402c1..d38b33a85 100644
--- a/tools/ab_control_flow.py
+++ b/tools/ab_control_flow.py
@@ -111,7 +111,7 @@ def write_outcomes(out_dir, outcomes):
111 """Write (shader name, outcome) pairs to the harness's tab-separated report.""" 111 """Write (shader name, outcome) pairs to the harness's tab-separated report."""
112 os.makedirs(out_dir, exist_ok=True) 112 os.makedirs(out_dir, exist_ok=True)
113 path = os.path.join(out_dir, "outcomes.tsv") 113 path = os.path.join(out_dir, "outcomes.tsv")
114 with open(path, "w", encoding="utf-8") as f: 114 with open(path, "w", encoding="utf-8", newline="\n") as f:
115 f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) 115 f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes))
116 return path 116 return path
117 117
@@ -169,7 +169,7 @@ OpFunctionEnd
169""" 169"""
170 src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv") 170 src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv")
171 os.makedirs(out_dir, exist_ok=True) 171 os.makedirs(out_dir, exist_ok=True)
172 with open(src, "w", encoding="utf-8") as f: 172 with open(src, "w", encoding="utf-8", newline="\n") as f:
173 f.write(asm) 173 f.write(asm)
174 runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True) 174 runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True)
175 runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True) 175 runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True)
diff --git a/tools/analyze_4240_full.py b/tools/analyze_4240_full.py
index 3dd9c243c..e5b6f50e3 100644
--- a/tools/analyze_4240_full.py
+++ b/tools/analyze_4240_full.py
@@ -352,7 +352,7 @@ def main() -> int:
352 parent = os.path.dirname(os.path.abspath(args.json)) 352 parent = os.path.dirname(os.path.abspath(args.json))
353 if parent: # every archive has been read by now; a missing folder used to lose the run 353 if parent: # every archive has been read by now; a missing folder used to lose the run
354 os.makedirs(parent, exist_ok=True) 354 os.makedirs(parent, exist_ok=True)
355 with open(args.json, "w", encoding="utf-8") as f: 355 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
356 json.dump(output, f, indent=2) 356 json.dump(output, f, indent=2)
357 return status 357 return status
358 358
diff --git a/tools/anim_clips.py b/tools/anim_clips.py
index 047a9834a..ca48ea5cb 100644
--- a/tools/anim_clips.py
+++ b/tools/anim_clips.py
@@ -886,7 +886,7 @@ def main():
886 parent = os.path.dirname(os.path.abspath(a.out)) 886 parent = os.path.dirname(os.path.abspath(a.out))
887 if parent: 887 if parent:
888 os.makedirs(parent, exist_ok=True) 888 os.makedirs(parent, exist_ok=True)
889 with open(a.out, "w", encoding="utf-8") as f: 889 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
890 json.dump({"summary": summary, "dictionaries": rows}, f, indent=1) 890 json.dump({"summary": summary, "dictionaries": rows}, f, indent=1)
891 except OSError as e: 891 except OSError as e:
892 sys.exit(f"{a.out}: cannot write: {e.strerror or e}") 892 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
diff --git a/tools/anim_index.py b/tools/anim_index.py
index 29d590685..119b81613 100644
--- a/tools/anim_index.py
+++ b/tools/anim_index.py
@@ -454,7 +454,7 @@ def write_output(path, rows, summary):
454 """Write CSV or JSON from the file extension. CSV writes one summary line to stderr.""" 454 """Write CSV or JSON from the file extension. CSV writes one summary line to stderr."""
455 ext = os.path.splitext(path)[1].lower() 455 ext = os.path.splitext(path)[1].lower()
456 if ext == ".json": 456 if ext == ".json":
457 with open(path, "w", encoding="utf-8") as f: 457 with open(path, "w", encoding="utf-8", newline="\n") as f:
458 json.dump({"summary": summary, "files": rows}, f, indent=1) 458 json.dump({"summary": summary, "files": rows}, f, indent=1)
459 return 459 return
460 with open(path, "w", encoding="utf-8", newline="") as f: 460 with open(path, "w", encoding="utf-8", newline="") as f:
@@ -570,7 +570,7 @@ def main():
570 print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr) 570 print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr)
571 return 2 571 return 2
572 try: 572 try:
573 with open(a.rigs, "w", encoding="utf-8") as f: 573 with open(a.rigs, "w", encoding="utf-8", newline="\n") as f:
574 json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1) 574 json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1)
575 except OSError as e: 575 except OSError as e:
576 sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}") 576 sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}")
diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py
new file mode 100644
index 000000000..cd2fb9dbc
--- /dev/null
+++ b/tools/anim_rigs.py
@@ -0,0 +1,172 @@
1"""Read the rig dictionaries in anim.rpf and join the RBF0 rig-set manager's entries to them (ASSET-20).
2
3 python -I tools/anim_rigs.py <package>\\anim.rpf <work>\\anim-rigs.json [--rigs <work>\\rigs.json]
4
5A rig dictionary has the clip dictionary's root layout (docs/animation.md, "Clip dictionaries are RAGE
6resources") with `RIG` + a version byte at +0x70 instead of the pack array. Its map is keyed by `joaat32` of a rig
7path. Each value points at +0x20 to a `RIG` block, which holds tables of 8-byte `(hash, word)` items. `--rigs`
8takes the JSON `anim_index.py --rigs` writes and resolves every rig-set entry (source = rig dictionary name,
9rig = key). The output holds counts and one row per rig dictionary, no item values.
10"""
11import argparse
12import collections
13import json
14import mmap
15import os
16import struct
17import sys
18import zlib
19
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21import anim_clips # noqa: E402
22import anim_index # noqa: E402
23
24SYSTEM = anim_clips.SYSTEM
25MAGIC = b"RIG"
26
27
28def is_rig_dictionary(data):
29 return len(data) >= 0x78 and data[0x70:0x73] == MAGIC
30
31
32def block_tables(s, at):
33 """Tables of a `RIG` block at page offset `at`: `RIG` + u8 version, u32 length of what follows, then tables
34 `{u32 kind hash; u32 size = 0xC + 8 * count; u32 count; u32 word}` + count × `{u32 hash; u32 word}`, with other
35 bytes between them. Returns (version, length, [(kind, count)])."""
36 if s.d[at:at + 3] != MAGIC:
37 raise anim_clips.DecodeError(f"no RIG block at 0x{at:x}")
38 version, length = s.d[at + 3], s.u32(at + 4)
39 end = min(len(s.d), at + 8 + length)
40 o, tables = at + 8, []
41 while o + 16 <= end:
42 kind, size, count, _word = struct.unpack_from("<4I", s.d, o)
43 if 0 < count < 4096 and size == 0xC + 8 * count and o + 16 + 8 * count <= end:
44 tables.append((kind, count))
45 o += 16 + 8 * count
46 else:
47 o += 4
48 return version, length, tables
49
50
51def parse_rig_dictionary(s):
52 """Root: +0x38 name, +0x48 map (key = joaat32(rig path), high half 0), +0x68 joaat32(name), +0x70 `RIG`."""
53 d = {"name": s.string(0x38), "hash": s.u32(0x68), "version": s.d[0x73], "entries": []}
54 for key, value in s.atmap(0x48):
55 if value is None:
56 continue
57 block = s.ptr(value + 0x20)
58 e = {"key": key & 0xFFFFFFFF, "key_high": key >> 32, "block": block}
59 if block is not None:
60 e["block_version"], e["block_length"], e["tables"] = block_tables(s, block)
61 d["entries"].append(e)
62 return d
63
64
65def _read(path, segments):
66 with open(path, "rb") as fh:
67 data = b""
68 for off, stored, raw in segments:
69 fh.seek(off)
70 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
71 return data
72
73
74def scan(path, start=None, limit=None):
75 rows, walk = anim_index.scan_rpf(path, start, limit)
76 with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
77 groups, _unresolved, _gaps = anim_clips.group(m, rows)
78 stats, dicts = collections.Counter(), []
79 for _i, parts in groups:
80 segments = [anim_clips.segment(rows, k) for k in parts]
81 with open(path, "rb") as fh:
82 fh.seek(segments[0][0])
83 head = fh.read(segments[0][1])
84 first = head if segments[0][2] else zlib.decompressobj().decompress(head, 0x80)
85 if not is_rig_dictionary(first):
86 continue
87 s = anim_clips.System(_read(path, segments))
88 try:
89 d = parse_rig_dictionary(s)
90 except (anim_clips.DecodeError, struct.error) as e:
91 stats["rig_dictionaries_unparsed"] += 1
92 dicts.append({"offset": segments[0][0], "error": str(e)[:120]})
93 continue
94 d["offset"], d["streams"], d["system_bytes"] = segments[0][0], len(segments), len(s.d)
95 dicts.append(d)
96 stats["rig_dictionaries"] += 1
97 stats["rig_dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"]
98 stats[f"rig_dictionary_version:{d['version']}"] += 1
99 for e in d["entries"]:
100 stats["entries"] += 1
101 stats["entries_key_high_zero"] += e["key_high"] == 0
102 if e["block"] is None:
103 stats["entries_without_block"] += 1
104 continue
105 stats["entries_with_block"] += 1
106 stats[f"block_version:{e['block_version']}"] += 1
107 stats["tables"] += len(e["tables"])
108 for kind, count in e["tables"]:
109 stats[f"table_kind:0x{kind:08x}"] += 1
110 stats[f"table_items:0x{kind:08x}"] += count
111 return dicts, {"streams": walk["files"], "dictionary_roots": len(groups), "counts": dict(sorted(stats.items()))}
112
113
114def join_rbf0(dicts, rigs):
115 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there."""
116 keys = {d["name"]: {e["key"] for e in d.get("entries", ())} for d in dicts if d.get("name")}
117 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]]
118 c = collections.Counter()
119 for e in entries:
120 h = anim_index.joaat32(e["rig"].lower())
121 if h in keys.get(e["source"], ()):
122 c["resolved"] += 1
123 elif any(h in k for k in keys.values()):
124 c["in_another_dictionary"] += 1
125 elif e["source"] not in keys:
126 c["no_dictionary_named_source"] += 1
127 else:
128 c["key_missing"] += 1
129 distinct = {(e["source"], e["rig"].lower()) for e in entries}
130 used = {(src, anim_index.joaat32(r)) for src, r in distinct}
131 c["distinct_rigs"] = len(distinct)
132 c["keys"] = sum(len(k) for k in keys.values())
133 c["keys_named_by_an_entry"] = sum(1 for name, k in keys.items() for h in k if (name, h) in used)
134 return dict(sorted(c.items()))
135
136
137def main():
138 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
139 ap.add_argument("archive", help="anim.rpf")
140 ap.add_argument("out", help="output .json (counts and one row per rig dictionary)")
141 ap.add_argument("--rigs", help="the JSON anim_index.py --rigs wrote, to resolve the RBF0 entries")
142 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)")
143 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan")
144 a = ap.parse_args()
145 try:
146 dicts, summary = scan(a.archive, a.start, a.limit)
147 if a.rigs:
148 with open(a.rigs, encoding="utf-8") as f:
149 summary["rbf0_join"] = join_rbf0(dicts, json.load(f))
150 except ValueError as e:
151 sys.exit(f"{a.archive}: {e}")
152 except OSError as e:
153 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}")
154 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts]
155 try:
156 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
157 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1)
158 except OSError as e:
159 sys.exit(f"{a.out}: cannot write: {e.strerror or e}")
160 c = summary["counts"]
161 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")}))
162 if "rbf0_join" in summary:
163 print(json.dumps(summary["rbf0_join"]))
164 return 0
165
166
167if __name__ == "__main__":
168 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
169 sys.stdout.reconfigure(errors="replace")
170 except (AttributeError, ValueError, OSError):
171 pass
172 sys.exit(main())
diff --git a/tools/awc_names.py b/tools/awc_names.py
index ae8b345fe..ec3568e34 100644
--- a/tools/awc_names.py
+++ b/tools/awc_names.py
@@ -281,11 +281,12 @@ def main(argv=None) -> int:
281 a = ap.parse_args(argv) 281 a = ap.parse_args(argv)
282 if not a.words and not a.conversations: 282 if not a.words and not a.conversations:
283 ap.error("give at least one --words or --conversations source") 283 ap.error("give at least one --words or --conversations source")
284 for path in a.banks + a.words + a.conversations: 284 inputs = a.banks + a.words + a.conversations
285 for path in inputs:
285 if not os.path.exists(path): 286 if not os.path.exists(path):
286 print(f"awc_names: error: {path}: no such file or directory", file=sys.stderr) 287 print(f"awc_names: error: {path}: no such file or directory", file=sys.stderr)
287 return 2 288 return 2
288 if a.out and any(os.path.exists(a.out) and os.path.samefile(p, a.out) for p in a.banks + a.words): 289 if a.out and os.path.exists(a.out) and any(os.path.samefile(p, a.out) for p in inputs):
289 ap.error("--out must not overwrite an input") 290 ap.error("--out must not overwrite an input")
290 291
291 words = [] 292 words = []
@@ -317,7 +318,7 @@ def main(argv=None) -> int:
317 if a.out: 318 if a.out:
318 try: 319 try:
319 if a.out.lower().endswith(".json"): 320 if a.out.lower().endswith(".json"):
320 with open(a.out, "w", encoding="utf-8") as fh: 321 with open(a.out, "w", encoding="utf-8", newline="\n") as fh:
321 json.dump({"summary": summary, "streams": rows}, fh, indent=1) 322 json.dump({"summary": summary, "streams": rows}, fh, indent=1)
322 else: 323 else:
323 with open(a.out, "w", encoding="utf-8", newline="") as fh: 324 with open(a.out, "w", encoding="utf-8", newline="") as fh:
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index cb96c55a9..5bad0dfbb 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -95,25 +95,47 @@ OPUS_PRE_SKIP = 312
95 95
96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, 96def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
97 pre_skip: int = OPUS_PRE_SKIP) -> int: 97 pre_skip: int = OPUS_PRE_SKIP) -> int:
98 """length: the stream's declared per-channel sample count at 48 kHz; the last page's granule position is 98 """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming 99 trimmed to pre_skip + length (Ogg Opus granules count the pre-skip too), so decoders drop the encoder priming
100 at the start and stop at the exact end instead of the padded last frame.""" 100 at the start and stop at the exact end instead of the padded last frame.
101
102 The EOS page is emitted at the packet that first reaches pre_skip + length; any later packets are encoder
103 padding and are dropped. Clamping only the final page would make its granule smaller than the previous page's
104 when the trim point falls before that page starts, which is invalid Ogg and makes decoders keep the excess.
105 """
106 if not 0 <= pre_skip <= 0xFFFF:
107 raise ValueError(f"pre-skip must be 0..65535, got {pre_skip}")
108 if length < 0:
109 raise ValueError(f"length must be non-negative, got {length}")
110 total = sum(opus_samples(p) for p in packets)
111 if pre_skip > total:
112 pre_skip = total # a granule below the pre-skip makes the stream undecodable
101 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0) 113 head = b"OpusHead" + struct.pack("<BBHIhB", 1, channels, pre_skip, 48000, 0, 0)
102 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0) 114 tags = b"OpusTags" + struct.pack("<I", 8) + b"leonida " + struct.pack("<I", 0)
103 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)] 115 out = [ogg_page(serial, 0, 0, [head], 0x02), ogg_page(serial, 1, 0, [tags], 0x00)]
104 seq, granule, pending, size = 2, 0, [], 0 116 seq, granule, pending, size = 2, 0, [], 0
117 target = pre_skip + length if length > 0 else None
118 written = 0
119 if not packets:
120 out.append(ogg_page(serial, 2, pre_skip, [], 0x04))
121 write_file(path, b"".join(out))
122 return pre_skip
105 for i, p in enumerate(packets): 123 for i, p in enumerate(packets):
106 pending.append(p) 124 pending.append(p)
107 granule += opus_samples(p) 125 granule += opus_samples(p)
108 size += len(p) 126 size += len(p)
127 reach = target is not None and granule >= target
109 last = i == len(packets) - 1 128 last = i == len(packets) - 1
110 if size > 4000 or len(pending) >= 50 or last: 129 if reach or size > 4000 or len(pending) >= 50 or last:
111 g = min(granule, pre_skip + length) if (last and 0 < length) else granule 130 g = target if reach else granule
112 out.append(ogg_page(serial, seq, g, pending, 0x04 if last else 0x00)) 131 out.append(ogg_page(serial, seq, g, pending, 0x04 if (reach or last) else 0x00))
132 written = g
113 seq += 1 133 seq += 1
114 pending, size = [], 0 134 pending, size = [], 0
135 if reach or last:
136 break
115 write_file(path, b"".join(out)) 137 write_file(path, b"".join(out))
116 return granule 138 return written
117 139
118 140
119def write_file(path: str, data: bytes) -> None: 141def write_file(path: str, data: bytes) -> None:
@@ -293,9 +315,12 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
293 pk = opus_packets(d, at, size) 315 pk = opus_packets(d, at, size)
294 if pk: 316 if pk:
295 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and 317 # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and
296 # half of it for stereo in all 7,451 measured streams. Fall back to dividing the 318 # half of it for stereo in all 7,451 measured streams. Use it only when it agrees
297 # interleaved count when a synthetic or malformed block leaves the field zero. 319 # with the interleaved +0 count; a synthetic or malformed block that disagrees
298 frames = s["frames"] or s["samples"] // max(1, s["channels"]) 320 # must not silently truncate the real audio.
321 frames = s["frames"]
322 if not frames or frames * s["channels"] != s["samples"]:
323 frames = s["samples"] // max(1, s["channels"])
299 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, 324 write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames,
300 pre_skip=pre_skip) 325 pre_skip=pre_skip)
301 counts["opus"] += 1 326 counts["opus"] += 1
diff --git a/tools/bink_index.py b/tools/bink_index.py
index 2b8232834..0d4ac4315 100644
--- a/tools/bink_index.py
+++ b/tools/bink_index.py
@@ -285,7 +285,7 @@ def write_csv(path, rows, probe):
285def write_json(path, target, rows, summary, probe): 285def write_json(path, target, rows, summary, probe):
286 fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) 286 fields = BASE_FIELDS + (PROBE_FIELDS if probe else [])
287 streams = [_flat(row, fields) for row in rows] 287 streams = [_flat(row, fields) for row in rows]
288 with open(path, "w", encoding="utf-8") as fh: 288 with open(path, "w", encoding="utf-8", newline="\n") as fh:
289 json.dump({"target": target, "summary": summary, "streams": streams}, 289 json.dump({"target": target, "summary": summary, "streams": streams},
290 fh, indent=1) 290 fh, indent=1)
291 291
diff --git a/tools/bink_names.py b/tools/bink_names.py
index 13bc9b12a..a31c3d2c6 100644
--- a/tools/bink_names.py
+++ b/tools/bink_names.py
@@ -299,7 +299,7 @@ def name_streams(names, streams, pins=None, max_skip=MAX_SKIP):
299 299
300def write(out, rows, unmatched, summary): 300def write(out, rows, unmatched, summary):
301 if out.lower().endswith(".json"): 301 if out.lower().endswith(".json"):
302 with open(out, "w", encoding="utf-8") as fh: 302 with open(out, "w", encoding="utf-8", newline="\n") as fh:
303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) 303 json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1)
304 else: 304 else:
305 with open(out, "w", encoding="utf-8", newline="") as fh: 305 with open(out, "w", encoding="utf-8", newline="") as fh:
@@ -318,6 +318,8 @@ def main(argv=None):
318 ap.add_argument("--max-skip", type=int, default=MAX_SKIP, help="most list entries skipped in a row") 318 ap.add_argument("--max-skip", type=int, default=MAX_SKIP, help="most list entries skipped in a row")
319 ap.add_argument("--out", help="names.csv or names.json; default is a summary only") 319 ap.add_argument("--out", help="names.csv or names.json; default is a summary only")
320 a = ap.parse_args(argv) 320 a = ap.parse_args(argv)
321 if a.max_skip < 0:
322 ap.error("--max-skip must be 0 or more")
321 inputs = [a.source, *a.mount] + ([a.pins] if a.pins else []) 323 inputs = [a.source, *a.mount] + ([a.pins] if a.pins else [])
322 for path in inputs: 324 for path in inputs:
323 if not os.path.exists(path): 325 if not os.path.exists(path):
diff --git a/tools/bvh_index.py b/tools/bvh_index.py
index 90bcd3bbc..501774553 100644
--- a/tools/bvh_index.py
+++ b/tools/bvh_index.py
@@ -351,7 +351,7 @@ def write_outputs(rows, summaries, out, csv_path):
351 if out: 351 if out:
352 _make_parent(out) 352 _make_parent(out)
353 payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {}) 353 payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {})
354 with open(out, "w", encoding="utf-8") as f: 354 with open(out, "w", encoding="utf-8", newline="\n") as f:
355 json.dump({"summary": payload, "streams": rows}, f, indent=0) 355 json.dump({"summary": payload, "streams": rows}, f, indent=0)
356 if csv_path: 356 if csv_path:
357 _make_parent(csv_path) 357 _make_parent(csv_path)
diff --git a/tools/calibrated_texture.py b/tools/calibrated_texture.py
index 641b44a09..6aeefc697 100644
--- a/tools/calibrated_texture.py
+++ b/tools/calibrated_texture.py
@@ -10,6 +10,9 @@ import sys
10import tempfile 10import tempfile
11import zlib 11import zlib
12 12
13# `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it.
14sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
15
13import numpy as np 16import numpy as np
14import bcpack 17import bcpack
15import bcpack_tables 18import bcpack_tables
diff --git a/tools/cf_diff.py b/tools/cf_diff.py
index 741e21561..70d144753 100644
--- a/tools/cf_diff.py
+++ b/tools/cf_diff.py
@@ -567,7 +567,7 @@ def self_test():
567 e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))] 567 e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))]
568 with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: 568 with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp:
569 p = os.path.join(tmp, "c.s") 569 p = os.path.join(tmp, "c.s")
570 with open(p, "w", encoding="utf-8") as f: 570 with open(p, "w", encoding="utf-8", newline="\n") as f:
571 f.write(listing_text(e.assemble(), "ps_canary_bad")) 571 f.write(listing_text(e.assemble(), "ps_canary_bad"))
572 if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on 572 if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on
573 print("canary FAILED: the reference did not drop lanes whose EXEC was never restored") 573 print("canary FAILED: the reference did not drop lanes whose EXEC was never restored")
diff --git a/tools/classify_carve.py b/tools/classify_carve.py
index 1c3e6f5d2..819de999f 100644
--- a/tools/classify_carve.py
+++ b/tools/classify_carve.py
@@ -102,7 +102,7 @@ def main():
102 out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per} 102 out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per}
103 fd, temp = tempfile.mkstemp(dir=root, prefix=".types-", suffix=".tmp") 103 fd, temp = tempfile.mkstemp(dir=root, prefix=".types-", suffix=".tmp")
104 try: 104 try:
105 with os.fdopen(fd, "w", encoding="utf-8") as f: 105 with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
106 json.dump(out, f, indent=1) 106 json.dump(out, f, indent=1)
107 f.flush() 107 f.flush()
108 os.fsync(f.fileno()) 108 os.fsync(f.fileno())
diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py
index 92b9ea3fb..7072978c3 100644
--- a/tools/crosslane_fuzz.py
+++ b/tools/crosslane_fuzz.py
@@ -739,10 +739,10 @@ def assemble(mc, prog, src, disasm, fssm):
739 if r.returncode or "error:" in r.stderr: 739 if r.returncode or "error:" in r.stderr:
740 raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}") 740 raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}")
741 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 741 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
742 with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8") as f: 742 with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8", newline="\n") as f:
743 f.write(f"; {prog.name} crosslane_fuzz\n{code}") 743 f.write(f"; {prog.name} crosslane_fuzz\n{code}")
744 asm_path = os.path.join(fssm, prog.name + ".asm") 744 asm_path = os.path.join(fssm, prog.name + ".asm")
745 with open(asm_path, "w", encoding="utf-8") as f: 745 with open(asm_path, "w", encoding="utf-8", newline="\n") as f:
746 f.write(src) 746 f.write(src)
747 with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f: 747 with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f:
748 f.write(compute_fixture.compute_header(asm_path)) 748 f.write(compute_fixture.compute_header(asm_path))
@@ -1008,7 +1008,7 @@ def main():
1008 print(describe(p, bad)) 1008 print(describe(p, bad))
1009 if args.keep: 1009 if args.keep:
1010 os.makedirs(args.keep, exist_ok=True) 1010 os.makedirs(args.keep, exist_ok=True)
1011 with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8") as f: 1011 with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8", newline="\n") as f:
1012 f.write(kept_source(p, mode, None, not args.no_hw_guard)) 1012 f.write(kept_source(p, mode, None, not args.no_hw_guard))
1013 if args.minimize and bad and what.startswith("mismatch"): 1013 if args.minimize and bad and what.startswith("mismatch"):
1014 if mode == "hw": 1014 if mode == "hw":
@@ -1021,7 +1021,7 @@ def main():
1021 print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "") 1021 print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "")
1022 for i, o in enumerate(ops))) 1022 for i, o in enumerate(ops)))
1023 if args.keep: 1023 if args.keep:
1024 with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8") as f: 1024 with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8", newline="\n") as f:
1025 f.write(kept_source(p, mode, ops, not args.no_hw_guard)) 1025 f.write(kept_source(p, mode, ops, not args.no_hw_guard))
1026 finally: 1026 finally:
1027 if oracle: 1027 if oracle:
diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py
new file mode 100644
index 000000000..23fe49b6c
--- /dev/null
+++ b/tools/d16_format_probe.py
@@ -0,0 +1,341 @@
1r"""How an RDNA2 GPU rounds UNORM/SNORM buffer loads to f16 with d16 (BUILD-161). Standard library only.
2
3docs/design.md ("d16 and f16 format narrowing") narrows every d16 result with integer round to nearest even, but
4for typed buffer loads that rounding was inferred (#489, #711), not measured. This sweep measures it: every value of
5each format below goes through buffer_load_format_d16_x and tbuffer_load_format_d16_x natively on the GPU (through
6tools/hw_oracle/), in wave32 and wave64. Every result is compared with several candidate rules computed from the
7exact quotient (Fraction arithmetic):
8
9 f32_rte x / (2^n - 1) (SNORM: max(s / (2^(n-1) - 1), -1)) rounded to f32 (nearest even), then to f16
10 nearest even: the translator's rule before BUILD-161 (the exact binary32 decode, then Gen.f16_bits)
11 f32_rtz rounded to f32, then to f16 toward zero (v_cvt_pkrtz_f16_f32 of the f32 value; PackHalf2x16 on AMD
12 drivers, the #489 bug)
13 rte the exact quotient rounded once to f16, nearest even (no f32 step): what an RX 6700 does, and the
14 translator's rule since BUILD-161 (Gen.d16_norm_f16)
15 rtz the exact quotient rounded once to f16, toward zero
16 mul_rte the f32 product v * f32(1 / (2^n - 1)) (a reciprocal multiply, not a division), then f16 nearest even
17
18and each rule again with f16 denormal results flushed to zero (UNORM16 and SNORM16 have quotients under 2^-14).
19Only the 16-bit formats tell the f32 step apart: rte and f32_rte differ on UNORM16 0xffaf and 0xffef and on SNORM16
200x7ff7 and 0x8009, and a flush shows on the smallest UNORM16 / SNORM16 values. On UNORM8, SNORM8 and UNORM10 every
21rule but the rtz ones gives the same bits.
22buffer_load_format_x (an f32 result, no d16) runs on the same values against the f32 rules, so the two stages can be
23told apart. Controls that must hold for the sweep to count: every staged input word reads back as written, a
2416_FLOAT d16 load returns its own bits, and d16_x leaves the high half of its VGPR as it was.
25
26The kernels write their own inputs: thread t stores the format's bits for value base + t at dword t of the output
27buffer, waits for the store, builds a GFX10 buffer descriptor (V#) over that buffer and loads its element with glc dlc
28(past the L0 and GL1 caches), then stores the loaded VGPR at dword 1024 + t. GFX10 only (RDNA1 and RDNA2: the
29V# layout, RESOURCE_LEVEL = 1), which is what BUILD-161 asks for; another architecture exits 77.
30
31Usage:
32 python -I tools/d16_format_probe.py [--formats unorm8,snorm16] [--waves 32,64] [--json out.json]
33 python -I tools/d16_format_probe.py --self-test # the models against known counts, no GPU
34
35Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when wave32 and wave64
36or MUBUF and MTBUF disagree, 2 on a harness error (a control failed, a kernel without its words), 77 when the
37hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files.
38"""
39import argparse
40import json
41import os
42import struct
43import sys
44from fractions import Fraction
45
46HERE = os.path.dirname(os.path.abspath(__file__))
47sys.dont_write_bytecode = True
48if HERE not in sys.path:
49 sys.path.insert(0, HERE)
50
51# name: (GFX10 unified buffer format code, kind, bits of the x channel). The codes are the translator's FORMATS
52# table (tools/rdna2spirv.py); 10_10_10_2 (50) holds x in its low 10 bits.
53FORMATS = {
54 "unorm8": (1, "unorm", 8),
55 "snorm8": (2, "snorm", 8),
56 "unorm16": (7, "unorm", 16),
57 "snorm16": (8, "snorm", 16),
58 "unorm10": (50, "unorm", 10),
59 "float16": (13, "f16", 16), # control: d16 of an f16 element is its own bits
60}
61INSTS = ("buffer_d16", "tbuffer_d16", "buffer_f32")
62THREADS = 1024
63WORDS = 2 * THREADS
64HI_SEED = 0xBEEF0000 # the d16_x destination starts as this | 0x1234; the high half must stay
65LO_SEED = 0x1234
66RULES16 = ("f32_rte", "f32_rtz", "rte", "rtz", "mul_rte")
67RULES32 = ("f32_rte", "f32_rtz", "mul_f32")
68
69
70# ---- exact arithmetic ----
71
72def round_frac(x, prec, emin, rtz=False):
73 """x rounded to a binary float with prec significand bits (implicit bit included) and minimum normal exponent
74 emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1]."""
75 if x == 0:
76 return Fraction(0)
77 sign = -1 if x < 0 else 1
78 a = abs(x)
79 e = a.numerator.bit_length() - a.denominator.bit_length()
80 if Fraction(2) ** e > a:
81 e -= 1
82 if Fraction(2) ** (e + 1) <= a:
83 e += 1
84 ulp = Fraction(2) ** (max(e, emin) - prec + 1)
85 q = a / ulp
86 n = q.numerator // q.denominator if rtz else round(q) # round() of a Fraction is half to even
87 return sign * n * ulp
88
89
90def f16_bits(v):
91 return struct.unpack("<H", struct.pack("<e", float(v)))[0]
92
93
94def f32_bits(v):
95 return struct.unpack("<I", struct.pack("<f", float(v)))[0]
96
97
98def to_f16(x, rtz=False):
99 return round_frac(x, 11, -14, rtz)
100
101
102def to_f32(x, rtz=False):
103 return round_frac(x, 24, -126, rtz)
104
105
106def quotient(kind, n, v):
107 """The exact value of raw channel bits v (n bits) for a UNORM or SNORM channel."""
108 if kind == "unorm":
109 return Fraction(v, (1 << n) - 1)
110 s = v - (1 << n) if v >> (n - 1) else v
111 return max(Fraction(s, (1 << (n - 1)) - 1), Fraction(-1))
112
113
114def is_denorm16(h):
115 return (h & 0x7C00) == 0 and (h & 0x3FF) != 0
116
117
118def models16(kind, n, v):
119 """{rule: f16 bits} for one input, plus each rule with a denormal result flushed (rule + '_flush')."""
120 x = quotient(kind, n, v)
121 rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1))
122 s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v
123 prod = max(to_f32(s * rcp), Fraction(-1))
124 out = {"rte": f16_bits(to_f16(x)), "rtz": f16_bits(to_f16(x, True)), "f32_rte": f16_bits(to_f16(to_f32(x))),
125 "f32_rtz": f16_bits(to_f16(to_f32(x), True)), "mul_rte": f16_bits(to_f16(prod))}
126 for r in RULES16:
127 out[r + "_flush"] = (out[r] & 0x8000) if is_denorm16(out[r]) else out[r]
128 return out
129
130
131def models32(kind, n, v):
132 x = quotient(kind, n, v)
133 rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1))
134 s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v
135 return {"f32_rte": f32_bits(to_f32(x)), "f32_rtz": f32_bits(to_f32(x, True)),
136 "mul_f32": f32_bits(max(to_f32(s * rcp), Fraction(-1)))}
137
138
139# ---- kernels ----
140
141def descriptor_word3(code):
142 """GFX10 V# dword 3: DST_SEL x/y/z/w = X/Y/Z/W (4, 5, 6, 7), FORMAT [18:12], RESOURCE_LEVEL [24] = 1,
143 OOB_SELECT [29:28] = 3 (raw: in bounds while offset < NUM_RECORDS), TYPE [31:30] = 0 (buffer)."""
144 return 4 | 5 << 3 | 6 << 6 | 7 << 9 | code << 12 | 1 << 24 | 3 << 28
145
146
147def kernel_lines(inst, fmt, base):
148 """Thread t: stage format bits (base + t) & mask at dword t, load the element, store the VGPR at dword 1024 + t."""
149 code, kind, n = FORMATS[fmt]
150 mask = (1 << n) - 1
151 load = {"buffer_d16": "buffer_load_format_d16_x v3, v2, s[8:11], 0 offen glc dlc",
152 "tbuffer_d16": f"tbuffer_load_format_d16_x v3, v2, s[8:11], 0 format:{code} offen glc dlc",
153 "buffer_f32": "buffer_load_format_x v3, v2, s[8:11], 0 offen glc dlc"}[inst]
154 return [
155 f"v_add_nc_u32 v1, 0x{base:x}, v0",
156 f"v_and_b32 v1, 0x{mask:x}, v1",
157 "v_lshlrev_b32 v2, 2, v0",
158 "global_store_b32 v2, v1, s[2:3]",
159 "s_waitcnt_vscnt null, 0x0",
160 "s_mov_b32 s8, s2",
161 "s_and_b32 s9, s3, 0xffff", # BASE_ADDRESS[47:32]; STRIDE 0, no swizzle
162 f"s_mov_b32 s10, 0x{4 * THREADS:x}", # NUM_RECORDS: the staged inputs, in bytes
163 f"s_mov_b32 s11, 0x{descriptor_word3(code):x}",
164 f"v_mov_b32 v3, 0x{HI_SEED | LO_SEED:x}",
165 load,
166 "s_waitcnt vmcnt(0)",
167 f"v_add_nc_u32 v4, 0x{4 * THREADS:x}, v2",
168 "global_store_b32 v4, v3, s[2:3]",
169 "s_endpgm",
170 ]
171
172
173def jobs(fmt):
174 """(inst, base) for every kernel a format needs: one per 1024 values."""
175 n = FORMATS[fmt][2]
176 insts = ("buffer_d16", "tbuffer_d16") if FORMATS[fmt][1] == "f16" else INSTS
177 return [(inst, base) for inst in insts for base in range(0, 1 << n, THREADS)]
178
179
180def sweep(oracle, fmt, wave):
181 """{inst: [loaded VGPR word per value]} for every value of the format, or raise RuntimeError."""
182 from hw_oracle import asm
183 n = FORMATS[fmt][2]
184 todo = jobs(fmt)
185 kernels = [asm.Kernel(kernel_lines(inst, fmt, base), wave, THREADS, WORDS, raw=True, vgprs=8, sgprs=16)
186 for inst, base in todo]
187 got = oracle.run(kernels, words=WORDS)
188 out = {}
189 for (inst, base), words in zip(todo, got):
190 if isinstance(words, str) or len(words) != WORDS:
191 raise RuntimeError(f"{fmt} {inst} wave{wave} base {base}: "
192 f"{words if isinstance(words, str) else f'{len(words)} words'}")
193 count = min(THREADS, (1 << n) - base)
194 staged = words[:count]
195 want = [(base + t) & ((1 << n) - 1) for t in range(count)]
196 if staged != want:
197 bad = next(t for t in range(count) if staged[t] != want[t])
198 raise RuntimeError(f"{fmt} {inst} wave{wave}: staged input {want[bad]:#x} read back as {staged[bad]:#x}")
199 out.setdefault(inst, []).extend(words[THREADS:THREADS + count])
200 return out
201
202
203# ---- comparison ----
204
205def classify(fmt, hw):
206 """Counts of inputs each rule predicts exactly, the inputs where the translator's rule (rte for d16, f32_rte for f32) is wrong, and the
207 control failures. hw: {inst: [VGPR word per value]}."""
208 _, kind, n = FORMATS[fmt]
209 res = {"inputs": 1 << n, "insts": {}, "control": []}
210 for inst, words in hw.items():
211 d16 = inst.endswith("d16")
212 if d16:
213 hi_bad = [v for v, w in enumerate(words) if w >> 16 != HI_SEED >> 16]
214 if hi_bad:
215 res["control"].append(f"{inst}: d16_x changed the high half for {len(hi_bad)} values "
216 f"(first {hi_bad[0]:#x}: {words[hi_bad[0]]:#010x})")
217 if kind == "f16":
218 wrong = [v for v, w in enumerate(words) if (w & 0xFFFF) != v and not (
219 (v & 0x7C00) == 0x7C00 and v & 0x3FF and (w & 0x7C00) == 0x7C00 and w & 0x3FF)]
220 if wrong:
221 res["control"].append(f"{inst}: 16_FLOAT came back changed for {len(wrong)} values "
222 f"(first {wrong[0]:#06x} -> {words[wrong[0]] & 0xFFFF:#06x})")
223 res["insts"][inst] = {"own_bits": (1 << n) - len(wrong)}
224 continue
225 rules = (tuple(RULES16) + tuple(r + "_flush" for r in RULES16)) if d16 else RULES32
226 match = dict.fromkeys(rules, 0)
227 off = []
228 for v, w in enumerate(words):
229 got = w & 0xFFFF if d16 else w
230 m = models16(kind, n, v) if d16 else models32(kind, n, v)
231 for r in rules:
232 match[r] += got == m[r]
233 rule = "rte" if d16 else "f32_rte" # the translator's rule (Gen.d16_norm_f16, norm_bits)
234 if got != m[rule]:
235 off.append((v, got, m[rule], m))
236 res["insts"][inst] = {"match": match, "off_rule": len(off),
237 "first_off": [{"value": f"{v:#x}", "hw": f"{g:#x}", "rule": f"{r:#x}",
238 "fits": [k for k in rules if m[k] == g]} for v, g, r, m in off[:8]]}
239 return res
240
241
242def rte_rtz_disagreements(kind, n):
243 """How many inputs the translator's rule and the #489 bug (f32 then RTZ) narrow differently (docs/design.md:
244 123 of 256 UNORM8 and 110 of 256 SNORM8 loaded 1 ulp low)."""
245 return sum(models16(kind, n, v)["f32_rte"] != models16(kind, n, v)["f32_rtz"] for v in range(1 << n))
246
247
248def self_test():
249 assert round_frac(Fraction(1, 3), 11, -14) == Fraction(1365, 4096) # 0x3555
250 assert f16_bits(to_f16(Fraction(1, 255))) == 0x1C04 # 2^-8 * 1.00390625
251 assert f16_bits(to_f16(Fraction(9, 255))) == 0x2885 and f16_bits(to_f16(Fraction(9, 255), True)) == 0x2884
252 assert f16_bits(to_f16(Fraction(1, 65535))) == 0x0100 and is_denorm16(0x0100) # under 2^-14
253 assert f16_bits(to_f16(Fraction(1, 2) + Fraction(1, 4096))) == 0x3800 # a tie: to even
254 assert quotient("snorm", 8, 0x80) == -1 and quotient("snorm", 8, 0x81) == -1 and quotient("snorm", 8, 0x7F) == 1
255 assert models16("unorm", 8, 255)["rte"] == 0x3C00 and models16("snorm", 16, 0x8000)["rte"] == 0xBC00
256 assert models32("unorm", 8, 1)["f32_rte"] == 0x3B808081 # 1/255 in f32
257 assert models16("unorm", 16, 1)["f32_rte_flush"] == 0
258 assert models16("unorm", 16, 0xFFEF)["rte"] == 0x3BFF and models16("unorm", 16, 0xFFEF)["f32_rte"] == 0x3C00
259 assert models16("snorm", 16, 0x8009)["rte"] == 0xBBFF and models16("snorm", 16, 0x8009)["f32_rte"] == 0xBC00
260 assert rte_rtz_disagreements("unorm", 8) == 123
261 assert rte_rtz_disagreements("snorm", 8) == 110
262 w3 = descriptor_word3(7)
263 assert w3 & 0xFFF == 0xFAC and (w3 >> 12) & 0x7F == 7 and (w3 >> 24) & 1 and (w3 >> 28) & 3 == 3
264 lines = kernel_lines("tbuffer_d16", "unorm16", 0x400)
265 assert lines[0] == "v_add_nc_u32 v1, 0x400, v0" and "format:7 offen glc dlc" in lines[10]
266 assert len(jobs("unorm16")) == 3 * 64 and len(jobs("unorm8")) == 3 and len(jobs("float16")) == 2 * 64
267 print("self-test ok")
268 return 0
269
270
271def main(argv=None):
272 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
273 ap.add_argument("--formats", default=",".join(FORMATS))
274 ap.add_argument("--waves", default="32,64")
275 ap.add_argument("--json", help="write the counts and the first differences here")
276 ap.add_argument("--hw-arch")
277 ap.add_argument("--self-test", action="store_true")
278 a = ap.parse_args(argv)
279 if a.self_test:
280 return self_test()
281 fmts = [f for f in a.formats.split(",") if f]
282 waves = [int(w) for w in a.waves.split(",") if w.strip().isdigit()]
283 bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")]
284 if bad or not fmts or not waves:
285 ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"]))
286 from hw_oracle import asm, runner
287 try:
288 oracle = runner.open_oracle(arch=a.hw_arch)
289 except runner.Unavailable as e:
290 print(f"hardware oracle unavailable: {e}")
291 return 77
292 try:
293 if asm.family(oracle.arch) != "gfx10":
294 print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the descriptor here is GFX10's (RDNA2)")
295 return 77
296 print(f"hardware oracle: {oracle.device}")
297 report = {"device": str(oracle.device), "arch": oracle.arch, "formats": {}}
298 rc = 0
299 for fmt in fmts:
300 hw = {w: sweep(oracle, fmt, w) for w in waves}
301 first = hw[waves[0]]
302 entry = classify(fmt, first)
303 entry["waves_differ"] = {inst: sum(a_ != b_ for a_, b_ in zip(first[inst], hw[w][inst]))
304 for w in waves[1:] for inst in first}
305 if "tbuffer_d16" in first:
306 entry["mubuf_mtbuf_differ"] = sum((x ^ y) & 0xFFFF != 0
307 for x, y in zip(first["buffer_d16"], first["tbuffer_d16"]))
308 report["formats"][fmt] = entry
309 if entry["control"]:
310 for c in entry["control"]:
311 print(f"harness error: {fmt} {c}")
312 rc = 2
313 if any(entry["waves_differ"].values()) or entry.get("mubuf_mtbuf_differ"):
314 rc = max(rc, 1) if rc != 2 else 2
315 print(f"{fmt} ({entry['inputs']} values): wave32/64 differ {entry['waves_differ'] or 'n/a'}; "
316 f"MUBUF/MTBUF d16 differ {entry.get('mubuf_mtbuf_differ', 'n/a')}")
317 for inst, s in entry["insts"].items():
318 if "own_bits" in s:
319 print(f" {inst}: own bits {s['own_bits']}/{entry['inputs']}")
320 continue
321 print(f" {inst}: " + ", ".join(f"{r} {k}" for r, k in s["match"].items()) +
322 f"; off the rule {s['off_rule']}")
323 for o in s["first_off"][:3]:
324 print(f" value {o['value']}: hw {o['hw']}, rule {o['rule']}, fits {','.join(o['fits']) or '-'}")
325 except RuntimeError as e:
326 print(f"harness error: {e}")
327 return 2
328 finally:
329 oracle.close()
330 if a.json:
331 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
332 json.dump(report, f, indent=1)
333 return rc
334
335
336if __name__ == "__main__":
337 try:
338 sys.stdout.reconfigure(errors="replace")
339 except (AttributeError, ValueError, OSError):
340 pass
341 sys.exit(main())
diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py
index 2b7f377df..96dd542d4 100644
--- a/tools/f16_trans_sweep.py
+++ b/tools/f16_trans_sweep.py
@@ -454,7 +454,7 @@ def main(argv=None):
454 finally: 454 finally:
455 oracle.close() 455 oracle.close()
456 if a.json: 456 if a.json:
457 with open(a.json, "w", encoding="utf-8") as f: 457 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
458 json.dump(report, f, indent=1) 458 json.dump(report, f, indent=1)
459 return rc 459 return rc
460 460
diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py
index 7c23a58fd..09d464530 100644
--- a/tools/f32_fuzz.py
+++ b/tools/f32_fuzz.py
@@ -687,7 +687,7 @@ def run_translated(text, name="ps_f32_fuzz"):
687 dis = os.path.join(tmp, "disasm") 687 dis = os.path.join(tmp, "disasm")
688 os.mkdir(dis) 688 os.mkdir(dis)
689 path = os.path.join(dis, name + ".s") 689 path = os.path.join(dis, name + ".s")
690 with open(path, "w", encoding="utf-8") as f: 690 with open(path, "w", encoding="utf-8", newline="\n") as f:
691 f.write(text) 691 f.write(text)
692 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: 692 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
693 f.write(STUB_DXBC) 693 f.write(STUB_DXBC)
@@ -1727,7 +1727,7 @@ def main(argv=None):
1727 if a.keep and rep.mismatches: 1727 if a.keep and rep.mismatches:
1728 os.makedirs(a.keep, exist_ok=True) 1728 os.makedirs(a.keep, exist_ok=True)
1729 for k, (c, _, _) in enumerate(rep.mismatches): 1729 for k, (c, _, _) in enumerate(rep.mismatches):
1730 with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8") as f: 1730 with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8", newline="\n") as f:
1731 f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n") 1731 f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n")
1732 if a.perturb: 1732 if a.perturb:
1733 print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED")) 1733 print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED"))
diff --git a/tools/feature_scan.py b/tools/feature_scan.py
index 622a0bf8e..f2e28bf2d 100644
--- a/tools/feature_scan.py
+++ b/tools/feature_scan.py
@@ -1,4 +1,4 @@
1"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10 and #14). 1"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10, #14, #16).
2 2
3 python -I tools/feature_scan.py <work>/shaders [--out feature_scan.json] 3 python -I tools/feature_scan.py <work>/shaders [--out feature_scan.json]
4 4
@@ -7,9 +7,12 @@ Reads what the shaders stage of make_game.py leaves in <work>/shaders, and print
7- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification 7- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification
8 stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h, 8 stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h,
9 among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream 9 among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream
10 output to a stream other than 0 needs a geometry shader writing that stream. 10 output to a stream other than 0 needs a geometry shader writing that stream. The PSV0 resource bindings: structured
11 UAVs with a counter (append/consume buffers) and typed buffer SRVs/UAVs (#16).
11- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*, 12- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*,
12 v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). 13 v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). Typed buffer
14 accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked
15 against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS).
13- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases 16- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases
14 (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in 17 (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in
15 the executable, not in shaders.rpf. 18 the executable, not in shaders.rpf.
@@ -80,6 +83,61 @@ def streams(sig: bytes) -> set:
80 return {struct.unpack_from("<I", sig, first + 32 * i)[0] for i in range(count)} 83 return {struct.unpack_from("<I", sig, first + 32 * i)[0] for i in range(count)}
81 84
82 85
86# DXC include/dxc/DxilContainer/DxilPipelineStateValidation.h (PSVResourceType) and DxilConstants.h
87# (DXIL::ResourceKind), by value.
88PSV_RES_TYPES = ("Invalid", "Sampler", "CBV", "SRVTyped", "SRVRaw", "SRVStructured", "UAVTyped", "UAVRaw",
89 "UAVStructured", "UAVStructuredWithCounter")
90PSV_RES_KINDS = ("Invalid", "Texture1D", "Texture2D", "Texture2DMS", "Texture3D", "TextureCube", "Texture1DArray",
91 "Texture2DArray", "Texture2DMSArray", "TextureCubeArray", "TypedBuffer", "RawBuffer",
92 "StructuredBuffer", "CBuffer", "Sampler", "TBuffer", "RTAccelerationStructure", "FeedbackTexture2D",
93 "FeedbackTexture2DArray")
94
95
96def psv0_bindings(psv: bytes) -> list:
97 """(resource type, resource kind) of every PSV0 resource binding record.
98
99 The part is: u32 runtime-info size, the runtime info, u32 resource count and, when that is not 0, u32 record
100 size and the records. A record is PSVResourceBindInfo0 (type, space, lower and upper bound: 16 bytes) or
101 PSVResourceBindInfo1 (plus resource kind and flags: 24 bytes); a 16-byte record has kind "?". Raises ValueError
102 when the table does not fit in the part."""
103 if len(psv) < 4:
104 raise ValueError("PSV0 shorter than its runtime-info size")
105 pos = 4 + struct.unpack_from("<I", psv, 0)[0]
106 if pos + 4 > len(psv):
107 raise ValueError("PSV0 truncated before the resource count")
108 count = struct.unpack_from("<I", psv, pos)[0]
109 pos += 4
110 if not count:
111 return []
112 if pos + 4 > len(psv):
113 raise ValueError("PSV0 truncated before the record size")
114 size = struct.unpack_from("<I", psv, pos)[0]
115 pos += 4
116 if size < 16 or pos + size * count > len(psv):
117 raise ValueError("PSV0 resource records do not fit")
118 out = []
119 for i in range(count):
120 at = pos + i * size
121 t = struct.unpack_from("<I", psv, at)[0]
122 k = struct.unpack_from("<I", psv, at + 16)[0] if size >= 20 else None
123 out.append((PSV_RES_TYPES[t] if t < len(PSV_RES_TYPES) else f"type{t}",
124 "?" if k is None else PSV_RES_KINDS[k] if k < len(PSV_RES_KINDS) else f"kind{k}"))
125 return out
126
127
128# §8.2 #16: append/consume buffers are the structured UAVs with a counter; typed buffers are typed SRVs/UAVs of
129# kind TypedBuffer (a typed SRV/UAV of a texture kind is an image, not a buffer).
130WATCHED_BINDINGS = ("uav_with_counter", "typed_buffer_srv", "typed_buffer_uav")
131
132
133def watched_binding(res_type: str, kind: str):
134 if res_type == "UAVStructuredWithCounter":
135 return "uav_with_counter"
136 if kind == "TypedBuffer" and res_type in ("SRVTyped", "UAVTyped"):
137 return "typed_buffer_srv" if res_type == "SRVTyped" else "typed_buffer_uav"
138 return None
139
140
83def stage_name(row: dict) -> str: 141def stage_name(row: dict) -> str:
84 stage = row.get("stage") 142 stage = row.get("stage")
85 return stage if isinstance(stage, str) and stage else "?" 143 return stage if isinstance(stage, str) and stage else "?"
@@ -90,6 +148,8 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict:
90 flags = defaultdict(Counter) # flag -> stage -> shaders 148 flags = defaultdict(Counter) # flag -> stage -> shaders
91 gs_streams = Counter() 149 gs_streams = Counter()
92 non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 150 non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0
151 records, shaders_with = Counter(), Counter() # PSV0: (type, kind) -> records; watched class -> shaders
152 psv_bad = 0
93 missing = 0 153 missing = 0
94 for e in index: 154 for e in index:
95 if not isinstance(e, dict): 155 if not isinstance(e, dict):
@@ -113,14 +173,33 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict:
113 for bit, name in SFI0_FLAGS.items(): 173 for bit, name in SFI0_FLAGS.items():
114 if mask & bit: 174 if mask & bit:
115 flags[name][stage] += 1 175 flags[name][stage] += 1
176 try:
177 binds = psv0_bindings(p["PSV0"]) if "PSV0" in p else None
178 except ValueError:
179 binds = None
180 if binds is None:
181 psv_bad += 1
182 else:
183 records.update(binds)
184 for cls in {watched_binding(t, k) for t, k in binds} - {None}:
185 shaders_with[cls] += 1
116 out = streams(p.get("OSG1", b"")) 186 out = streams(p.get("OSG1", b""))
117 if stage == "gs": 187 if stage == "gs":
118 gs_streams[len(out)] += 1 188 gs_streams[len(out)] += 1
119 if out - {0}: 189 if out - {0}:
120 non_zero_stream[stage] += 1 190 non_zero_stream[stage] += 1
191 by_type = Counter()
192 for (t, _), n in records.items():
193 by_type[t] += n
121 return {"stages": {s: stages.get(s, 0) for s in ALL_STAGES} | {k: v for k, v in stages.items() if k not in ALL_STAGES}, 194 return {"stages": {s: stages.get(s, 0) for s in ALL_STAGES} | {k: v for k, v in stages.items() if k not in ALL_STAGES},
122 "sfi0": {n: dict(flags[n]) for n in sorted(flags)}, 195 "sfi0": {n: dict(flags[n]) for n in sorted(flags)},
123 "gs_output_stream_count": dict(gs_streams), "output_on_stream_other_than_0": dict(non_zero_stream), 196 "gs_output_stream_count": dict(gs_streams), "output_on_stream_other_than_0": dict(non_zero_stream),
197 "psv0": {"records": sum(records.values()),
198 "by_type": dict(by_type),
199 "shaders": {c: shaders_with.get(c, 0) for c in WATCHED_BINDINGS},
200 "records_of": {c: sum(n for (t, k), n in records.items() if watched_binding(t, k) == c)
201 for c in WATCHED_BINDINGS},
202 "unreadable": psv_bad},
124 "unreadable": missing} 203 "unreadable": missing}
125 204
126 205
@@ -251,6 +330,139 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict:
251 }} 330 }}
252 331
253 332
333# Scalar ops whose first operand is a source, not an SGPR they write.
334NO_SDST = ("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_endpgm", "s_store", "s_buffer_store",
335 "s_scratch_store", "s_setpc", "s_sendmsg", "s_nop", "s_barrier", "s_dcache", "s_icache", "s_gl1_inv",
336 "s_setprio", "s_sleep", "s_ttrace", "s_set_gpr_idx", "s_setreg", "s_inst_prefetch", "s_round_mode",
337 "s_denorm_mode", "s_clause", "s_trap", "s_wakeup", "s_code_end", "s_atc_probe", "s_setkill", "s_incperflevel",
338 "s_decperflevel", "s_version")
339BRANCH_OPS = frozenset(("s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz",
340 "s_cbranch_execz", "s_cbranch_execnz"))
341TYPED_MUBUF = re.compile(r"^buffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$")
342TYPED_MTBUF = re.compile(r"^tbuffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$")
343
344
345def translator_formats():
346 """(codes the translator models, GFX10 code -> format name), read from rdna2spirv itself so the scan follows the
347 table as it changes. Modelled: the typed-buffer table and INVALID (0), an unbound descriptor, which reads 0 on the
348 hardware and in the translator."""
349 import rdna2spirv
350 return frozenset(rdna2spirv.Gen.FORMATS) | {0}, {c: n.replace("GFX10_FORMAT_", "") for c, n in
351 rdna2spirv.GFX10_FORMATS.items()}
352
353
354def sgpr_writes(ins: dict) -> range:
355 """The SGPRs an instruction writes (as far as a V# word can be written: scalar destinations, v_readlane and
356 v_readfirstlane, the SGPR mask of a VOP3 compare and the carry of a VOP3b add)."""
357 op, args = ins["op"], ins["args"]
358 dst = None
359 if op.startswith("s_") and not op.startswith(NO_SDST):
360 dst = args[0] if args else None
361 elif op.startswith(("v_readlane", "v_readfirstlane")) or (op.startswith("v_cmp") and not op.startswith("v_cmpx")
362 and op.endswith("_e64")):
363 dst = args[0] if args else None
364 elif op.startswith("v_") and len(args) > 1 and ("_co_" in op or op.startswith("v_div_scale")):
365 dst = args[1]
366 if dst and dst.get("k") == "sgpr":
367 return range(dst["r"], dst["r"] + dst.get("n", 1))
368 return range(0)
369
370
371def branch_target(ins: dict):
372 """Byte pc a branch goes to (simm16 dwords after the branch), or None without an encoding."""
373 imm = next((x for x in ins["args"] if x.get("k") == "imm"), None)
374 if imm is None or not ins.get("enc"):
375 return None
376 v = imm["v"] & 0xFFFF
377 return ins["pc"] + len(ins["enc"]) // 2 + 4 * (v - 0x10000 if v & 0x8000 else v)
378
379
380def typed_buffer_ops(insns: list, table: frozenset, names: dict) -> Counter:
381 """Count the typed buffer accesses of one listing (§8.2 #16).
382
383 MTBUF (tbuffer_*) carries its format in the instruction; LLVM leaves `format:` out for GFX10's default, 8_UNORM.
384 MUBUF (buffer_*_format_*) takes it from V# word 3 bits 18:12, and the result says where that word comes from in the
385 basic block of the access (blocks start at branch targets and after branches, as rdna2spirv.translate splits
386 them): an s_mov_b32 literal (the only form the translator folds, so the format is known when translating), a
387 scalar load (a descriptor from memory), or any other instruction (computed). A word 3 not written in the block is
388 "earlier_" + the class of the last write before it in listing order, or "shader_input" when nothing before it
389 writes the register (a user or system SGPR: the root signature's descriptor).
390
391 Keys: ("mtbuf", load|store, format), ("mubuf", load|store, class) and, for a literal word 3 (in the block or
392 earlier), ("mubuf_literal", load|store, format). A format the translator's table lacks gets a "!" in front."""
393 leaders = {insns[0]["pc"]} if insns else set()
394 for ins in insns:
395 if ins["op"] in BRANCH_OPS:
396 t = branch_target(ins)
397 if t is not None:
398 leaders.add(t)
399 if ins.get("enc"):
400 leaders.add(ins["pc"] + len(ins["enc"]) // 2)
401 out = Counter()
402 block, last = {}, {} # SGPR -> (class, literal or None): written in this block / last write so far
403 for ins in insns:
404 if ins["pc"] in leaders:
405 block = {}
406 op = ins["op"]
407 m = TYPED_MTBUF.match(op) or TYPED_MUBUF.match(op)
408 if m:
409 kind = m.group(1)
410 if op.startswith("t"):
411 fm = next((x for x in ins["mods"] if x.startswith("format:")), "format:[BUF_FMT_8_UNORM]")
412 name = fm.split("BUF_FMT_")[-1].rstrip("]")
413 code = next((c for c, n in names.items() if n == name), None)
414 out[("mtbuf", kind, ("" if code in table else "!") + name)] += 1
415 elif len(ins["args"]) > 2 and ins["args"][2].get("k") == "sgpr":
416 w3 = ins["args"][2]["r"] + 3
417 if w3 in block:
418 cls, lit = block[w3]
419 elif w3 in last:
420 cls, lit = "earlier_" + last[w3][0], last[w3][1]
421 else:
422 cls, lit = "shader_input", None
423 out[("mubuf", kind, cls)] += 1
424 if lit is not None:
425 code = (lit >> 12) & 0x7F
426 out[("mubuf_literal", kind, ("" if code in table else "!") + names.get(code, f"code{code}"))] += 1
427 regs = sgpr_writes(ins)
428 if regs:
429 if op == "s_mov_b32" and len(ins["args"]) > 1 and ins["args"][1].get("k") == "imm":
430 state = ("literal", ins["args"][1]["v"] & 0xFFFFFFFF)
431 elif op.startswith(("s_load", "s_buffer_load")):
432 state = ("memory", None)
433 else:
434 state = ("computed", None)
435 for r in regs:
436 block[r] = last[r] = state
437 return out
438
439
440def scan_typed_buffers(disasm_dir: str, stage_of: dict) -> dict:
441 """§8.2 #16 over every listing: typed buffer access counts (typed_buffer_ops) summed, and shaders per stage."""
442 import shader_ir
443 table, names = translator_formats()
444 total, shaders = Counter(), defaultdict(Counter)
445 for fn in sorted(os.listdir(disasm_dir)):
446 if not fn.endswith(".s"):
447 continue
448 path = os.path.join(disasm_dir, fn)
449 with open(path, encoding="utf-8", errors="replace") as f:
450 if "_format_" not in f.read(): # no typed buffer op: skip the slower full parse
451 continue
452 stage = stage_of.get(fn[:-2], "?")
453 c = typed_buffer_ops(shader_ir.parse_file(path)["insns"], table, names)
454 total.update(c)
455 for what in {k[0] for k in c}:
456 shaders[what][stage] += 1
457 if any(k[0] == "mubuf" and k[2] not in ("literal", "earlier_literal") for k in c):
458 shaders["mubuf_runtime_format"][stage] += 1
459 group = lambda what: {f"{k[1]} {k[2].lstrip('!')}": n for k, n in sorted(total.items()) if k[0] == what}
460 return {"mtbuf": group("mtbuf"), "mubuf_word3": group("mubuf"), "mubuf_literal_formats": group("mubuf_literal"),
461 "not_in_translator": {f"{k[0]} {k[1]} {k[2][1:]}": n for k, n in sorted(total.items())
462 if k[0] != "mubuf" and k[2].startswith("!")},
463 "shaders": {w: dict(s) for w, s in sorted(shaders.items())}}
464
465
254def scan_spirv(spirv_index: str) -> dict: 466def scan_spirv(spirv_index: str) -> dict:
255 with open(spirv_index, encoding="utf-8") as f: 467 with open(spirv_index, encoding="utf-8") as f:
256 idx = json.load(f) 468 idx = json.load(f)
@@ -336,6 +548,7 @@ def main() -> int:
336 disasm = os.path.join(dxbc_dir, "disasm") 548 disasm = os.path.join(dxbc_dir, "disasm")
337 if os.path.isdir(disasm): 549 if os.path.isdir(disasm):
338 result["disasm"] = scan_disasm(disasm, stage_of) 550 result["disasm"] = scan_disasm(disasm, stage_of)
551 result["typed_buffers"] = scan_typed_buffers(disasm, stage_of)
339 spirv = os.path.join(a.shaders, "spirv", "index.json") 552 spirv = os.path.join(a.shaders, "spirv", "index.json")
340 if os.path.isfile(spirv): 553 if os.path.isfile(spirv):
341 try: 554 try:
@@ -352,6 +565,10 @@ def main() -> int:
352 print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()}) 565 print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()})
353 print("GS output-signature stream counts:", d["gs_output_stream_count"], 566 print("GS output-signature stream counts:", d["gs_output_stream_count"],
354 "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0) 567 "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0)
568 pv = d["psv0"]
569 print(f"PSV0 bindings: {pv['records']} records | shaders with "
570 + ", ".join(f"{c} {pv['shaders'][c]} ({pv['records_of'][c]} records)" for c in WATCHED_BINDINGS)
571 + (f" | {pv['unreadable']} unreadable PSV0" if pv["unreadable"] else ""))
355 if "disasm" in result: 572 if "disasm" in result:
356 s = result["disasm"] 573 s = result["disasm"]
357 print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " 574 print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders "
@@ -362,6 +579,12 @@ def main() -> int:
362 f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | " 579 f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | "
363 f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | " 580 f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | "
364 f"bytes {vp['selector_classes']}") 581 f"bytes {vp['selector_classes']}")
582 tb = result["typed_buffers"]
583 print("typed buffers, MTBUF formats (instruction):", tb["mtbuf"] or 0)
584 print("typed buffers, MUBUF V# word 3 source:", tb["mubuf_word3"] or 0, "| literal formats:",
585 tb["mubuf_literal_formats"] or 0)
586 print("typed buffers, formats the translator's table lacks:", tb["not_in_translator"] or 0,
587 "| shaders:", tb["shaders"] or 0)
365 else: 588 else:
366 print("disasm: not there yet (run the shaders stage)") 589 print("disasm: not there yet (run the shaders stage)")
367 if "spirv" in result: 590 if "spirv" in result:
@@ -375,7 +598,7 @@ def main() -> int:
375 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does 598 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does
376 if folder: 599 if folder:
377 os.makedirs(folder, exist_ok=True) 600 os.makedirs(folder, exist_ok=True)
378 with open(a.out, "w", encoding="utf-8") as f: 601 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
379 json.dump(result, f, indent=1) 602 json.dump(result, f, indent=1)
380 return 0 603 return 0
381 604
diff --git a/tools/fma_mix_probe.py b/tools/fma_mix_probe.py
index 23cf1f8d6..7a77fe486 100644
--- a/tools/fma_mix_probe.py
+++ b/tools/fma_mix_probe.py
@@ -179,7 +179,7 @@ def verdict(results):
179def _translate(work, name, text, fssm=None): 179def _translate(work, name, text, fssm=None):
180 os.makedirs(os.path.join(work, "disasm"), exist_ok=True) 180 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
181 src = os.path.join(work, "disasm", name + ".s") 181 src = os.path.join(work, "disasm", name + ".s")
182 with open(src, "w", encoding="utf-8") as f: 182 with open(src, "w", encoding="utf-8", newline="\n") as f:
183 f.write(text) 183 f.write(text)
184 with open(os.path.join(work, name + ".dxbc"), "wb") as f: 184 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
185 f.write(STUB_DXBC) 185 f.write(STUB_DXBC)
@@ -264,7 +264,7 @@ def run_vulkan(build, cases=CASES):
264 with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: 264 with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work:
265 text = translate_cs(work, cases) 265 text = translate_cs(work, cases)
266 sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv") 266 sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv")
267 with open(sa, "w", encoding="utf-8") as f: 267 with open(sa, "w", encoding="utf-8", newline="\n") as f:
268 f.write(text) 268 f.write(text)
269 try: 269 try:
270 r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) 270 r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True)
diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py
index ea79e8001..3d002d0d6 100644
--- a/tools/fspx_unpack.py
+++ b/tools/fspx_unpack.py
@@ -178,6 +178,7 @@ def main(argv=None) -> int:
178 disasm = shader_disasm 178 disasm = shader_disasm
179 os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True) 179 os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True)
180 index, bad = [], 0 180 index, bad = [], 0
181 used_names = set()
181 for path in a.files: 182 for path in a.files:
182 with open(path, "rb") as f: 183 with open(path, "rb") as f:
183 data = f.read() 184 data = f.read()
@@ -197,29 +198,39 @@ def main(argv=None) -> int:
197 print(f"{name}: FSPX status {status}", file=sys.stderr) 198 print(f"{name}: FSPX status {status}", file=sys.stderr)
198 bad += 1 199 bad += 1
199 continue 200 continue
201 base_name = name
202 number = 1
203 while name.casefold() in used_names:
204 number += 1
205 name = f"{base_name}_{number}"
206 used_names.add(name.casefold())
200 meta, blob = got 207 meta, blob = got
201 stage = psv_stage(dxbc_parts(container)) if container else None 208 stage = psv_stage(dxbc_parts(container)) if container else None
202 meta["source"] = {"file": os.path.basename(path), "offset": off} 209 meta["source"] = {"file": os.path.basename(path), "offset": off}
203 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}", 210 entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}",
204 "source_offset": off, "threads": meta["threads"], "wave32": meta["wave32"]} 211 "source_offset": off}
212 if "threads" in meta:
213 entry["threads"] = meta["threads"]
214 if "wave32" in meta:
215 entry["wave32"] = meta["wave32"]
205 if container: 216 if container:
206 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: 217 with open(os.path.join(a.out, name + ".dxbc"), "wb") as f:
207 f.write(container) 218 f.write(container)
208 with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f: 219 with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f:
209 f.write(blob[6]) 220 f.write(blob[6])
210 with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8") as f: 221 with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f:
211 json.dump(meta, f, indent=1) 222 json.dump(meta, f, indent=1)
212 if disasm and meta["code"]["end"]: 223 if disasm and meta["code"]["end"]:
213 start, end = meta["code"]["start"], meta["code"]["end"] 224 start, end = meta["code"]["start"], meta["code"]["end"]
214 asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) 225 asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu)
215 entry["invalid_words"] = invalid 226 entry["invalid_words"] = invalid
216 with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8") as f: 227 with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f:
217 f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") 228 f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n")
218 f.write(asm) 229 f.write(asm)
219 if err.strip(): 230 if err.strip():
220 f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") 231 f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n")
221 index.append(entry) 232 index.append(entry)
222 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 233 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
223 json.dump(index, f, indent=1) 234 json.dump(index, f, indent=1)
224 print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else "")) 235 print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else ""))
225 return 1 if bad else 0 236 return 1 if bad else 0
diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py
index a463465b9..1a462144c 100644
--- a/tools/fssm_unpack.py
+++ b/tools/fssm_unpack.py
@@ -153,7 +153,7 @@ def main(argv=None) -> int:
153 "game version.", file=sys.stderr) 153 "game version.", file=sys.stderr)
154 return 1 154 return 1
155 tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none 155 tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none
156 with open(tmp, "w", encoding="utf-8") as f: 156 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
157 json.dump(rows, f) 157 json.dump(rows, f)
158 f.flush() 158 f.flush()
159 os.fsync(f.fileno()) 159 os.fsync(f.fileno())
diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py
index ec1126ade..507aac4a9 100644
--- a/tools/gamedata_graph.py
+++ b/tools/gamedata_graph.py
@@ -624,7 +624,7 @@ def main() -> int:
624 print_summary(graph) 624 print_summary(graph)
625 if args.json: 625 if args.json:
626 try: 626 try:
627 with open(args.json, "w", encoding="utf-8") as f: 627 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
628 json.dump(graph, f, indent=1) 628 json.dump(graph, f, indent=1)
629 except OSError as exc: 629 except OSError as exc:
630 print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 630 print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py
index 732ff0d30..5464cdfe4 100644
--- a/tools/gamedata_index.py
+++ b/tools/gamedata_index.py
@@ -41,6 +41,10 @@ XML_CLOSE_TAIL = re.compile(rb"</([A-Za-z_][\w.:-]*)>\s*$")
41# Tag-like text inside these cannot open or close an element. 41# Tag-like text inside these cannot open or close an element.
42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S) 42XML_NON_TAG = re.compile(rb"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>", re.S)
43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"} 43MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1Z": "SPS1Z", b"RBF0": "RBF0", b"PSIN": "PSIN"}
44# A resource whose page directory starts the stream carries "0DRP" at +16 (docs/animation.md, "0DRP page marker").
45# Its first 4 KiB can be over 95% printable, so without this check such a stream reads as text, and as XML when it
46# holds a "<": data.rpf has 337 of them and no XML at all (docs/gamedata.md, "Relationship to data.rpf").
47PAGE_MARKER, PAGE_MARKER_AT = b"0DRP", 16
44 48
45 49
46def printable(data: bytes) -> float: 50def printable(data: bytes) -> float:
@@ -123,6 +127,8 @@ def stream_kind(data: bytes, row: dict) -> str:
123 for magic in MAGIC: 127 for magic in MAGIC:
124 if data.startswith(magic): 128 if data.startswith(magic):
125 return "other" 129 return "other"
130 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
131 return "other"
126 if printable(data) > 0.95: 132 if printable(data) > 0.95:
127 return "text" 133 return "text"
128 return "binary" 134 return "binary"
@@ -132,6 +138,8 @@ def magic_name(data: bytes) -> str:
132 for magic, name in MAGIC.items(): 138 for magic, name in MAGIC.items():
133 if data.startswith(magic): 139 if data.startswith(magic):
134 return name 140 return name
141 if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER:
142 return PAGE_MARKER.decode()
135 return "" 143 return ""
136 144
137 145
@@ -435,7 +443,7 @@ def main() -> int:
435 write_csv(a.csv, rows) 443 write_csv(a.csv, rows)
436 if a.json: 444 if a.json:
437 _make_parent(a.json) 445 _make_parent(a.json)
438 with open(a.json, "w", encoding="utf-8") as f: 446 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
439 json.dump({"summary": summary, "rows": rows}, f, indent=1) 447 json.dump({"summary": summary, "rows": rows}, f, indent=1)
440 448
441 print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, ' 449 print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, '
diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py
index d3d465f0e..56fa68ca0 100644
--- a/tools/gamedata_maps.py
+++ b/tools/gamedata_maps.py
@@ -385,7 +385,7 @@ def main() -> int:
385 if census: 385 if census:
386 out["pamh_census"] = census 386 out["pamh_census"] = census
387 try: 387 try:
388 with open(a.json, "w", encoding="utf-8") as f: 388 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
389 json.dump(out, f, indent=1) 389 json.dump(out, f, indent=1)
390 except OSError as e: 390 except OSError as e:
391 print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) 391 print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
index 02cea8dee..e869dc234 100644
--- a/tools/gamedata_xml.py
+++ b/tools/gamedata_xml.py
@@ -635,7 +635,7 @@ def main() -> int:
635 if args.json: 635 if args.json:
636 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows] 636 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows]
637 _make_parent(args.json) 637 _make_parent(args.json)
638 with open(args.json, "w", encoding="utf-8") as f: 638 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
639 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1) 639 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1)
640 print("wrote", args.json) 640 print("wrote", args.json)
641 return 0 if clean else 1 641 return 0 if clean else 1
diff --git a/tools/glb_writer.py b/tools/glb_writer.py
index 0fa942c51..c6900bfef 100644
--- a/tools/glb_writer.py
+++ b/tools/glb_writer.py
@@ -453,10 +453,19 @@ def parse_obj(
453 first_vertex.setdefault(corner[0], vertex) 453 first_vertex.setdefault(corner[0], vertex)
454 for corner, vertex in builder["vert_map"].items() 454 for corner, vertex in builder["vert_map"].items()
455 ] 455 ]
456 computed = _compute_smooth_normals(positions, (normal_vertices[i] for i in indices)) 456 raw_normals = builder["normals"]
457 index_iter = iter(indices)
458 # Fully explicit triangles should not smooth neighboring generated normals.
459 normal_indices = (
460 normal_vertices[i]
461 for a, b, c in zip(index_iter, index_iter, index_iter)
462 if None in (raw_normals[a], raw_normals[b], raw_normals[c])
463 for i in (a, b, c)
464 )
465 computed = _compute_smooth_normals(positions, normal_indices)
457 normals = [ 466 normals = [
458 normal if normal is not None else computed[normal_vertex] 467 normal if normal is not None else computed[normal_vertex]
459 for normal, normal_vertex in zip(builder["normals"], normal_vertices) 468 for normal, normal_vertex in zip(raw_normals, normal_vertices)
460 ] 469 ]
461 else: 470 else:
462 normals = builder["normals"] 471 normals = builder["normals"]
diff --git a/tools/hashdict.py b/tools/hashdict.py
index cc8da2ace..f75fee68f 100644
--- a/tools/hashdict.py
+++ b/tools/hashdict.py
@@ -6,6 +6,7 @@ When multiple names share a hash, the dictionary keeps the lexicographically fir
6 6
7Usage: 7Usage:
8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] 8 python -I hashdict.py <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3]
9 <carve dir> holds one folder per archive (<work>/carve), or is one archive's folder (<work>/carve/common).
9 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ... 10 python -I hashdict.py --lookup <hashes.json> 0x28cca8df ...
10""" 11"""
11import argparse 12import argparse
@@ -91,11 +92,17 @@ def main():
91 what = "is not a folder" if os.path.exists(a.carve) else "does not exist" 92 what = "is not a folder" if os.path.exists(a.carve) else "does not exist"
92 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr) 93 print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr)
93 return 2 94 return 2
95 # A folder with its own index.json is one archive's carve (<work>\carve\common, the folder the gamedata_*
96 # tools take): harvest it as that archive. Otherwise each subfolder with an index.json is one archive.
97 if os.path.isfile(os.path.join(a.carve, "index.json")):
98 archives = [(os.path.basename(os.path.normpath(os.path.abspath(a.carve))), a.carve)]
99 else:
100 archives = [(d, os.path.join(a.carve, d)) for d in sorted(os.listdir(a.carve))]
94 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it. 101 # The dictionary is written after the harvest: an --out naming one of the inputs would replace it.
95 # samefile also catches a case-only difference on Windows and macOS's default volume. 102 # samefile also catches a case-only difference on Windows and macOS's default volume.
96 if os.path.exists(a.out): 103 if os.path.exists(a.out):
97 inputs = [x for x in a.extra if os.path.isfile(x)] 104 inputs = [x for x in a.extra if os.path.isfile(x)]
98 inputs += [os.path.join(a.carve, d, "index.json") for d in os.listdir(a.carve)] 105 inputs += [os.path.join(d, "index.json") for _, d in archives]
99 for x in inputs: 106 for x in inputs:
100 try: 107 try:
101 same = os.path.isfile(x) and os.path.samefile(a.out, x) 108 same = os.path.isfile(x) and os.path.samefile(a.out, x)
@@ -108,8 +115,8 @@ def main():
108 strings = set() 115 strings = set()
109 full = set(a.archives.split(",")) 116 full = set(a.archives.split(","))
110 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported 117 missing = [] # carved blobs an index.json lists that can't be read: skipped, reported
111 for arch in sorted(os.listdir(a.carve)): 118 for arch, arch_dir in archives:
112 p = os.path.join(a.carve, arch, "index.json") 119 p = os.path.join(arch_dir, "index.json")
113 if not os.path.isfile(p): 120 if not os.path.isfile(p):
114 continue 121 continue
115 try: 122 try:
@@ -126,7 +133,7 @@ def main():
126 continue 133 continue
127 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630") 134 meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630")
128 if arch in full or meta: 135 if arch in full or meta:
129 blob = os.path.join(a.carve, arch, f"{r['off']:012x}.bin") 136 blob = os.path.join(arch_dir, f"{r['off']:012x}.bin")
130 try: 137 try:
131 with open(blob, "rb") as f: 138 with open(blob, "rb") as f:
132 data = f.read() 139 data = f.read()
@@ -152,7 +159,7 @@ def main():
152 # Other tools create the output parent too: a long harvest must not be lost to a missing folder. 159 # Other tools create the output parent too: a long harvest must not be lost to a missing folder.
153 try: 160 try:
154 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) 161 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
155 with open(a.out, "w", encoding="utf-8") as f: 162 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
156 json.dump(d, f) 163 json.dump(d, f)
157 except OSError as e: 164 except OSError as e:
158 print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr) 165 print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr)
diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py
index bd19f0667..a89f42817 100644
--- a/tools/hw_oracle/runner.py
+++ b/tools/hw_oracle/runner.py
@@ -136,7 +136,7 @@ def build_command(kind, cc, src, out, workdir):
136 installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), 136 installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
137 "Microsoft Visual Studio", "Installer") 137 "Microsoft Visual Studio", "Installer")
138 script = os.path.join(workdir, "build_hw_oracle.cmd") 138 script = os.path.join(workdir, "build_hw_oracle.cmd")
139 with open(script, "w", encoding="ascii") as f: 139 with open(script, "w", encoding="ascii", newline="\n") as f:
140 f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' 140 f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n'
141 + subprocess.list2cmdline(cl) + "\r\n") 141 + subprocess.list2cmdline(cl) + "\r\n")
142 return ["cmd.exe", "/d", "/c", script] 142 return ["cmd.exe", "/d", "/c", script]
diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py
index 2fb857732..709ffa595 100644
--- a/tools/image_fuzz.py
+++ b/tools/image_fuzz.py
@@ -88,7 +88,7 @@ def assemble(asm: str, name: str, work: str) -> None:
88 if not line.lstrip().startswith(".")) 88 if not line.lstrip().startswith("."))
89 disasm = os.path.join(work, "disasm") 89 disasm = os.path.join(work, "disasm")
90 os.makedirs(disasm, exist_ok=True) 90 os.makedirs(disasm, exist_ok=True)
91 with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8") as f: 91 with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
92 f.write(f"; {name} generated by tools/image_fuzz.py\n{code}") 92 f.write(f"; {name} generated by tools/image_fuzz.py\n{code}")
93 with open(os.path.join(work, name + ".dxbc"), "wb") as f: 93 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
94 f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name 94 f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name
@@ -268,7 +268,7 @@ def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, d
268 with open(texels_path, "wb") as f: 268 with open(texels_path, "wb") as f:
269 f.write(texels) 269 f.write(texels)
270 spec_path = os.path.join(work, "spec.txt") 270 spec_path = os.path.join(work, "spec.txt")
271 with open(spec_path, "w", encoding="utf-8") as f: 271 with open(spec_path, "w", encoding="utf-8", newline="\n") as f:
272 f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n" 272 f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n"
273 f"tsharp={','.join(hex(w) for w in tsharp)}\n") 273 f"tsharp={','.join(hex(w) for w in tsharp)}\n")
274 out_path = os.path.join(work, "out.raw") 274 out_path = os.path.join(work, "out.raw")
diff --git a/tools/imhex/psin.hexpat b/tools/imhex/psin.hexpat
new file mode 100644
index 000000000..c3dc014d9
--- /dev/null
+++ b/tools/imhex/psin.hexpat
@@ -0,0 +1,193 @@
1// ImHex pattern for a PSIN metadata container (docs/psin.md; tools/psin_index.py and tools/psin_data.py read it).
2//
3// Layout, as measured in docs/psin.md:
4// 0x00 "PSIN"
5// 0x04 big-endian absolute offset of the first section
6// 0x08 instance-data block table: rows of {u32 block type, u32 data size, aa x 8}, ended by "pppppppp" 8 bytes
7// short of a 16-byte boundary. The blocks follow in table order, each padded to 16 bytes, numbered from 1;
8// the last one ends at the first section. Their contents are shown as raw bytes: decoding them needs the
9// schema walk that psin_data.py does.
10// sections from the first-section offset to EOF: ASCII tag, big-endian total size (header included)
11// LSCH struct headers (32 bytes) then all members (16 bytes); the header count is not stored, it is the one
12// count whose headers and members fill the payload exactly
13// LENM enum headers (24 bytes) then all values (16 bytes); same rule
14// LSNS u32 block count, {u32 kind, u32 byte count} per block, then the blocks: opaque 16-byte records
15// LRSC "0DRP", u32 version, ...; the u32 at +0x10 is the root block number
16// CHKS big-endian file size and a 32-bit value (not verified here)
17// LGID empty
18// Little-endian everywhere except the first-section offset and the section sizes. A truncated container shows what
19// is whole and the rest as raw bytes.
20
21#pragma description PSIN metadata container: block table, LSCH/LENM schema, LSNS, LRSC, CHKS (docs/psin.md)
22#pragma endian little
23#pragma magic [ 50 53 49 4E ] @ 0x00
24#pragma array_limit 1048576
25#pragma pattern_limit 8388608
26
27import std.mem;
28import std.core;
29
30// ---- header and instance-data block table ---------------------------------------------------------------------
31
32struct Header {
33 char magic[4];
34 be u32 first_section [[comment("big-endian absolute offset of the first section")]];
35};
36
37Header header @ 0x00;
38
39fn count_rows(u128 limit) {
40 u128 p = 0x08;
41 u32 n = 0;
42 while (p + 16 <= limit && std::mem::read_unsigned(p, 8) != 0x7070707070707070) {
43 p += 16;
44 n += 1;
45 }
46 return n;
47};
48
49u128 g_limit = header.first_section < std::mem::size() ? header.first_section : std::mem::size();
50u32 g_rows = count_rows(g_limit);
51
52struct BlockRow {
53 u32 type [[comment("struct name hash from LSCH, a member type code below 0x100, or 0x100 + n")]];
54 u32 size [[comment("data size in bytes")]];
55 u8 fill[8] [[comment("aa x 8")]];
56};
57
58struct Block {
59 u32 i = std::core::array_index();
60 u8 data[rows[i].size] [[comment("block number i + 1; raw: see psin_data.py")]];
61 u8 pad[(16 - rows[i].size % 16) % 16];
62};
63
64BlockRow rows[g_rows] @ 0x08;
65char table_end[8] @ 0x08 + 16 * g_rows [[comment("\"pppppppp\"")]];
66Block blocks[g_rows] @ 0x08 + 16 * g_rows + 8;
67
68// ---- sections ---------------------------------------------------------------------------------------------------
69
70fn header_count(u128 payload, u128 length, u32 header_size, u32 element_size, u32 count_at, u32 count_size) {
71 if (length == 0) return 0;
72 u32 elements = 0;
73 u32 k = 1;
74 while (header_size * k <= length) {
75 elements += std::mem::read_unsigned(payload + header_size * (k - 1) + count_at, count_size);
76 if (header_size * k + element_size * elements == length) return k;
77 k += 1;
78 }
79 return 0xFFFFFFFF; // no count fits: shown as raw bytes
80};
81
82fn sum_counts(u128 payload, u32 k, u32 header_size, u32 count_at, u32 count_size) {
83 u32 total = 0;
84 for (u32 i = 0, i < k, i += 1) {
85 total += std::mem::read_unsigned(payload + header_size * i + count_at, count_size);
86 }
87 return total;
88};
89
90struct StructHeader {
91 u32 name_hash;
92 u32 signature [[comment("layout signature")]];
93 u8 flags;
94 u8 align_log2;
95 u16 zero_0a;
96 u32 zero_0c;
97 u8 fill[8] [[comment("aa x 8")]];
98 u32 size [[comment("byte size of the struct")]];
99 u16 zero_1c;
100 u16 member_count;
101};
102
103struct Member {
104 u32 name_hash [[comment("0x100 = array element descriptor")]];
105 u32 offset;
106 u8 type;
107 u8 sub;
108 u16 index [[comment("for type 0x5c: position of its 0x100 element descriptor in this struct's members")]];
109 u32 ref_hash [[comment("struct or enum name hash for the referring types, else 0")]];
110};
111
112struct EnumHeader {
113 u32 name_hash;
114 u32 signature;
115 u8 fill[8] [[comment("ee x 8")]];
116 u32 value_count;
117 u32 zero_14;
118};
119
120struct EnumValue {
121 s64 value;
122 u64 name_hash [[comment("case-sensitive joaat in the low half")]];
123};
124
125struct LsnsDesc {
126 u32 kind;
127 u32 bytes;
128};
129
130struct LsnsRecord {
131 u8 bytes[16] [[comment("opaque")]];
132};
133
134struct LsnsBlock {
135 u32 i = std::core::array_index();
136 LsnsRecord records[parent.descs[i].bytes / 16];
137};
138
139bool g_bad = false;
140
141struct Section {
142 char tag[4];
143 be u32 size [[comment("big-endian total size, header included")]];
144 u128 payload = $;
145 if (size < 8 || addressof(tag) + size > std::mem::size()) {
146 g_bad = true;
147 u8 truncated[std::mem::size() - $] [[comment("section runs past the end of the file")]];
148 } else {
149 u32 length = size - 8;
150 if (tag == "LSCH") {
151 u32 k = header_count(payload, length, 32, 16, 30, 2);
152 if (k == 0xFFFFFFFF) {
153 u8 raw[length] [[comment("no struct count fills the payload")]];
154 } else {
155 StructHeader structs[k];
156 Member members[sum_counts(payload, k, 32, 30, 2)];
157 }
158 } else if (tag == "LENM") {
159 u32 k = header_count(payload, length, 24, 16, 16, 4);
160 if (k == 0xFFFFFFFF) {
161 u8 raw[length] [[comment("no enum count fills the payload")]];
162 } else {
163 EnumHeader enums[k];
164 EnumValue values[sum_counts(payload, k, 24, 16, 4)];
165 }
166 } else if (tag == "LSNS" && length >= 4) {
167 u32 block_count;
168 if (4 + 8 * block_count <= length) {
169 LsnsDesc descs[block_count];
170 LsnsBlock lsns_blocks[block_count];
171 }
172 if ($ < payload + length) {
173 u8 rest[payload + length - $] [[comment("does not fit the block table")]];
174 }
175 } else if (tag == "LRSC" && length >= 0x14 && std::mem::read_string(payload, 4) == "0DRP") {
176 char rsc_magic[4];
177 u32 rsc_version;
178 u32 u32_08;
179 u32 u32_0c;
180 u32 root_block [[comment("block number of the root struct")]];
181 u8 rest[length - 0x14];
182 } else if (tag == "CHKS" && length >= 8) {
183 be u32 checksum_size [[comment("big-endian file size")]];
184 u8 checksum[4] [[comment("32-bit value, not verified")]];
185 u8 rest[length - 8];
186 } else {
187 u8 raw[length];
188 }
189 }
190};
191
192Section sections[while(!g_bad && header.first_section + 8 <= std::mem::size() && std::mem::size() - $ >= 8)]
193 @ header.first_section;
diff --git a/tools/imhex/rbf0.hexpat b/tools/imhex/rbf0.hexpat
new file mode 100644
index 000000000..8d311e099
--- /dev/null
+++ b/tools/imhex/rbf0.hexpat
@@ -0,0 +1,96 @@
1// ImHex pattern for one RBF0 resource: RAGE's binary form of an XML data file.
2//
3// The grammar is the one measured in docs/rbf0.md (section 3) and parsed by tools/rbf0_index.py (parse_rbf0):
4//
5// 0x00 "RBF0"
6// 0x04 FB FF 01 00 optional prologue. With it, integers and floats are 8 bytes ("wide"); without it they are
7// 4 bytes ("narrow") and the records start at 0x04. What the four bytes mean is not established;
8// the width follows them in every measured resource (docs/rbf0.md).
9// records, each a u8 descriptor index and a u8 type:
10// FF FF close the open element
11// FD FF text for the open element: u32 length, then that many bytes
12// index == descriptors so far a new descriptor: u16 name length, then the UTF-8 name, before the payload
13// type 0x00 open an element: u16 0, u16 0, u16 attribute count
14// type 0x10 integer 0x20 true 0x30 false 0x40 float 0x50 three floats
15// type 0x60 string: u16 length, then UTF-8 bytes
16// The stream has no length field and no section table: it ends where the root element closes, and the pattern
17// stops there.
18//
19// Open an inflated, joined resource, not the archive. A resource larger than 64 KiB is split over several zlib
20// streams, with no header on the continuations (docs/rbf0.md section 2); tools/rbf0_index.py joins them.
21
22#pragma description RBF0 record stream (binary XML, docs/rbf0.md)
23#pragma endian little
24#pragma magic [ 52 42 46 30 ] @ 0x00
25// The largest measured resource has 68,398 elements and about twice as many records.
26#pragma array_limit 4194304
27#pragma pattern_limit 33554432
28
29import std.mem;
30import std.io;
31
32bool g_wide = std::mem::size() >= 8 && std::mem::read_unsigned(0x04, 4) == 0x0001FFFB;
33u32 g_descriptors = 0;
34u32 g_depth = 0;
35bool g_done = false;
36
37struct Header {
38 char magic[4];
39 if (g_wide) {
40 u8 prologue[4] [[comment("FB FF 01 00: 8-byte integers and floats follow")]];
41 }
42};
43
44struct Record {
45 u8 index;
46 u8 type;
47 if (index == 0xFF) {
48 if (g_depth > 0) g_depth -= 1;
49 if (g_depth == 0) g_done = true;
50 } else if (index == 0xFD) {
51 u32 text_length;
52 char text[text_length];
53 } else {
54 if (index == g_descriptors) {
55 u16 name_length;
56 char name[name_length] [[comment("new descriptor")]];
57 g_descriptors += 1;
58 }
59 if (type == 0x00) {
60 u16 word0;
61 u16 word1;
62 u16 attribute_count;
63 g_depth += 1;
64 } else if (type == 0x10) {
65 if (g_wide) {
66 u64 value_int;
67 } else {
68 u32 value_int;
69 }
70 } else if (type == 0x40) {
71 if (g_wide) {
72 double value_float;
73 } else {
74 float value_float;
75 }
76 } else if (type == 0x50) {
77 if (g_wide) {
78 double value_vec3[3];
79 } else {
80 float value_vec3[3];
81 }
82 } else if (type == 0x60) {
83 u16 string_length;
84 char value_string[string_length];
85 }
86 }
87} [[format("format_record")]];
88
89fn format_record(Record r) {
90 if (r.index == 0xFF) return "close";
91 if (r.index == 0xFD) return "text";
92 return std::format("descriptor {} type 0x{:02X}", r.index, r.type);
93};
94
95Header header @ 0x00;
96Record records[while(!g_done && !std::mem::eof())] @ sizeof(header);
diff --git a/tools/imhex/rpf9.hexpat b/tools/imhex/rpf9.hexpat
new file mode 100644
index 000000000..0fbc1e450
--- /dev/null
+++ b/tools/imhex/rpf9.hexpat
@@ -0,0 +1,32 @@
1// ImHex pattern for the header of an RPF9 archive.
2//
3// Only measured fields are named (docs/rpf.md "What is readable"; docs/story.md "Signatures actually observed"):
4// 0x00 "9FPR" RPF9 stored little-endian
5// 0x04 data offset u32, where the data area (zlib streams laid end to end) starts
6// 0x08 u32 present in every header; meaning not established
7// 0x0C u32 present in every header; meaning not established
8// Everything from 0x10 to the data offset is the rest of the header and the table of contents. The TOC is
9// encrypted/packed: this pattern shows that range as opaque bytes and decodes nothing in it (no keys, no decryption).
10//
11// This describes the archive's own header at offset 0. Nested RPF9 headers occur inside the data area
12// (docs/story.md); their offsets are not covered here.
13
14#pragma description RPF9 archive header, opaque TOC and data area start (docs/rpf.md)
15#pragma endian little
16#pragma magic [ 39 46 50 52 ] @ 0x00
17
18import std.mem;
19import std.sys;
20
21struct Rpf9Header {
22 char magic[4] [[comment("\"9FPR\": RPF9 stored little-endian")]];
23 u32 data_offset [[comment("start of the data area (docs/rpf.md)")]];
24 u32 u32_08 [[comment("meaning not established")]];
25 u32 u32_0c [[comment("meaning not established")]];
26};
27
28Rpf9Header header @ 0x00;
29std::assert(header.data_offset >= sizeof(header) && header.data_offset <= std::mem::size(),
30 "the data offset is outside the file");
31u8 header_rest_and_toc[header.data_offset - sizeof(header)] @ sizeof(header)
32 [[comment("rest of the header and the table of contents: encrypted/packed, not decoded")]];
diff --git a/tools/instance_lists.py b/tools/instance_lists.py
index 988f35563..bc7fedd96 100644
--- a/tools/instance_lists.py
+++ b/tools/instance_lists.py
@@ -357,7 +357,7 @@ def main(argv=None):
357 if args.json: 357 if args.json:
358 try: 358 try:
359 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) 359 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True)
360 with open(args.json, "w", encoding="utf-8") as fh: 360 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
361 json.dump(T, fh, indent=1, sort_keys=True) 361 json.dump(T, fh, indent=1, sort_keys=True)
362 except OSError as exc: 362 except OSError as exc:
363 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 363 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
new file mode 100644
index 000000000..9ebd50d9d
--- /dev/null
+++ b/tools/int_hw_probe.py
@@ -0,0 +1,743 @@
1r"""SHADER-137: RDNA2 hardware probe for the integer contract rows checked only on the CPU.
2
3Runs small, self-contained RDNA2 instruction sequences natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (each references its contract row in docs/design.md):
8 salu_absdiff_mulhi s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (SCC written vs kept)
9 salu_lshl_add s_lshl1..4_add_u32 (64-bit carry / shift-out into SCC)
10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept)
11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept)
12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0
13 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64
14 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32
15 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data
16 salu_movrels s_movrels_b32, s_movrels_b64 (M0 indexing, SCC kept)
17 valu_add_nc_clamp v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16 with clamp
18 valu_add_co_clamp v_add/sub/subrev_co[_ci]_u32 with clamp (saturation + carry)
19 valu_mad64 v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and inactive EXEC lane)
20 valu_sad_lerp v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
21 valu_qsad_mqsad v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
22 valu_mul24_sh64 v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
23 valu_mad16 v_mad_u16, v_mad_i16 (clamp, op_sel, kept half)
24 valu_cvt_16 v_cvt_f16_u16/i16, v_cvt_u16/i16_f16 (kept half, op_sel, NaN, inf)
25 valu_cvt_flr_rpi v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 (exact floor(x+0.5), signed NaN)
26 valu_cvt_pknorm v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32 (ties, saturation, NaN)
27
28Usage:
29 python -I tools/int_hw_probe.py # translator side only (CPU)
30 python -I tools/int_hw_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
31 python -I tools/int_hw_probe.py --oracle both # compare hardware vs translator
32 python -I tools/int_hw_probe.py --oracle both --strict # fail on known translator divergences too
33 python -I tools/int_hw_probe.py --self-test
34
35Exit codes:
36 0 all unexpected comparisons match (and wave32 == wave64 on hardware)
37 1 at least one unexpected mismatch, wave32/64 diff, or known divergence under --strict
38 2 bad CLI arguments or harness error
39 77 hardware oracle requested but unavailable on this machine
40"""
41import argparse
42import json
43import os
44import struct
45import sys
46import tempfile
47import warnings
48
49HERE = os.path.dirname(os.path.abspath(__file__))
50ROOT = os.path.dirname(HERE)
51sys.dont_write_bytecode = True
52for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
53 if p not in sys.path:
54 sys.path.insert(0, p)
55
56import rdna2spirv # noqa: E402
57import spirv_mini_interp # noqa: E402
58
59STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
60SENTINEL = 0x5A5A5A5A
61
62# Live translator divergences confirmed on AMD Radeon 680M (gfx1035, RDNA2, wave32 & wave64).
63# Each entry maps case.name -> (tag, expected_hw_words, reason). Empty: the five measured on gfx1035 (VOP3 clamp
64# on the carry-out add/sub ops, v_cvt_rpi_i32_f32's exact floor(x + 0.5), and v_cvt_flr/rpi's NaN saturation by
65# sign) are translated as the hardware does since #1831 and #1856.
66KNOWN_DIVERGENCES = {}
67
68
69class Case:
70 """One self-contained 4-word probe. `body` leaves results in v8..v11 and must not clobber s[0:3] or v0.
71 For wave-size-dependent mask instructions, `{vcc}`, `{exec}`, `{smov}`, `{stmp}` expand to wave32/wave64 forms."""
72
73 __slots__ = ("group", "name", "body", "note")
74
75 def __init__(self, group, name, body, note=""):
76 self.group = group
77 self.name = name
78 self.body = tuple(body)
79 self.note = note
80
81 def lines(self, wave=32):
82 vcc = "vcc_lo" if wave == 32 else "vcc"
83 exc = "exec_lo" if wave == 32 else "exec"
84 smov = "s_mov_b32" if wave == 32 else "s_mov_b64"
85 stmp = "s14" if wave == 32 else "s[14:15]"
86 return [ln.format(vcc=vcc, exec=exc, smov=smov, stmp=stmp) for ln in self.body]
87
88
89def _scc_seed(val):
90 return "s_cmp_eq_u32 0, 0" if val else "s_cmp_eq_u32 0, 1"
91
92
93def _salu32_pair(group, name, setup, op_line, note=""):
94 """Run one 32-bit scalar op twice: once with SCC preset to 0 (v8=D, v9=SCC) and once with SCC preset to 1
95 (v10=D, v11=SCC), so 'SCC kept' and 'SCC written' are both directly observed."""
96 body = [
97 *setup, _scc_seed(0), op_line,
98 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s6", "v_mov_b32 v9, s30",
99 *setup, _scc_seed(1), op_line,
100 "s_cselect_b32 s30, 1, 0", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30",
101 ]
102 return Case(group, name, body, note)
103
104
105def _salu64_case(group, name, setup, op_line, scc_in, note=""):
106 """Run one 64-bit scalar op with SCC preset to scc_in; output v8=s6 (lo), v9=s7 (hi), v10=SCC, v11=0."""
107 body = [
108 *setup, _scc_seed(scc_in), op_line,
109 "s_cselect_b32 s30, 1, 0",
110 "v_mov_b32 v8, s6", "v_mov_b32 v9, s7", "v_mov_b32 v10, s30", "v_mov_b32 v11, 0",
111 ]
112 return Case(group, name, body, note)
113
114
115def _valu4_case(group, name, body, note=""):
116 return Case(group, name, body, note)
117
118
119def build_cases():
120 cases = []
121
122 # 1. s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (docs/design.md)
123 cases += [
124 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_basic",
125 ["s_mov_b32 s4, 10", "s_mov_b32 s5, 25"],
126 "s_absdiff_i32 s6, s4, s5", "|10 - 25| = 15, SCC=1"),
127 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_equal",
128 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
129 "s_absdiff_i32 s6, s4, s5", "equal -> 0, SCC=0"),
130 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_wrap_max_min",
131 ["s_mov_b32 s4, 0x7fffffff", "s_mov_b32 s5, 0x80000000"],
132 "s_absdiff_i32 s6, s4, s5", "0x7fffffff - 0x80000000 wraps to -1 -> abs 1, SCC=1"),
133 _salu32_pair("salu_absdiff_mulhi", "s_absdiff_int_min",
134 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0"],
135 "s_absdiff_i32 s6, s4, s5", "diff = INT_MIN stays 0x80000000, SCC=1"),
136 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_min_min",
137 ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"],
138 "s_mul_hi_i32 s6, s4, s5", "(-2^31)*(-2^31) >> 32 = 0x40000000, SCC kept"),
139 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_neg_pos",
140 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 2"],
141 "s_mul_hi_i32 s6, s4, s5", "(-1)*2 >> 32 = 0xffffffff, SCC kept"),
142 _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_u32_max_max",
143 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
144 "s_mul_hi_u32 s6, s4, s5", "(2^32-1)^2 >> 32 = 0xfffffffe, SCC kept"),
145 ]
146
147 # 2. s_lshl1..4_add_u32 (64-bit shift-out + add carry into SCC)
148 for shift in (1, 2, 3, 4):
149 op = f"s_lshl{shift}_add_u32"
150 high_bit = 1 << (32 - shift)
151 cases += [
152 _salu32_pair("salu_lshl_add", f"{op}_no_carry",
153 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 5"],
154 f"{op} s6, s4, s5", "no shift-out, no add carry -> SCC=0"),
155 _salu32_pair("salu_lshl_add", f"{op}_shift_out_only",
156 [f"s_mov_b32 s4, 0x{high_bit:08x}", "s_mov_b32 s5, 0"],
157 f"{op} s6, s4, s5", "bit shifted out of S0 with S1=0 -> D=0, SCC=1"),
158 _salu32_pair("salu_lshl_add", f"{op}_add_carry_only",
159 ["s_mov_b32 s4, 1", "s_mov_b32 s5, 0xffffffff"],
160 f"{op} s6, s4, s5", "add carry without shift-out -> SCC=1"),
161 ]
162
163 # 3. s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32
164 cases += [
165 _salu32_pair("salu_sext_flbit", "s_sext_i8_neg",
166 ["s_mov_b32 s4, 0x12345680"], "s_sext_i32_i8 s6, s4", "0x80 -> 0xffffff80, SCC kept"),
167 _salu32_pair("salu_sext_flbit", "s_sext_i8_pos",
168 ["s_mov_b32 s4, 0xffffff7f"], "s_sext_i32_i8 s6, s4", "0x7f -> 0x0000007f, SCC kept"),
169 _salu32_pair("salu_sext_flbit", "s_sext_i16_neg",
170 ["s_mov_b32 s4, 0x00008001"], "s_sext_i32_i16 s6, s4", "0x8001 -> 0xffff8001, SCC kept"),
171 _salu32_pair("salu_sext_flbit", "s_sext_i16_pos",
172 ["s_mov_b32 s4, 0xffff7fff"], "s_sext_i32_i16 s6, s4", "0x7fff -> 0x00007fff, SCC kept"),
173 _salu32_pair("salu_sext_flbit", "s_flbit_i32_zero",
174 ["s_mov_b32 s4, 0"], "s_flbit_i32 s6, s4", "0 -> 0xffffffff, SCC kept"),
175 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg1",
176 ["s_mov_b32 s4, 0xffffffff"], "s_flbit_i32 s6, s4", "-1 -> 0xffffffff, SCC kept"),
177 _salu32_pair("salu_sext_flbit", "s_flbit_i32_pos1",
178 ["s_mov_b32 s4, 1"], "s_flbit_i32 s6, s4", "1 -> 30, SCC kept"),
179 _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg16",
180 ["s_mov_b32 s4, 0xfffffff0"], "s_flbit_i32 s6, s4", "-16 -> 27, SCC kept"),
181 _salu32_pair("salu_sext_flbit", "s_flbit_i32_int_min",
182 ["s_mov_b32 s4, 0x80000000"], "s_flbit_i32 s6, s4", "INT_MIN -> 0, SCC kept"),
183 ]
184
185 # 4. s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16
186 cases += [
187 _salu32_pair("salu_cmov_pack", "s_cmov_b32",
188 ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s6, 0xaabbccdd"],
189 "s_cmov_b32 s6, s4", "SCC=0 keeps D, SCC=1 takes S0, SCC kept"),
190 _salu32_pair("salu_cmov_pack", "s_cmovk_i32_neg",
191 ["s_mov_b32 s6, 0x12345678"],
192 "s_cmovk_i32 s6, -300", "SCC=0 keeps D, SCC=1 sign-extends imm16, SCC kept"),
193 _salu32_pair("salu_cmov_pack", "s_pack_ll",
194 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
195 "s_pack_ll_b32_b16 s6, s4, s5", "{S1.lo, S0.lo} = 0x44442222, SCC kept"),
196 _salu32_pair("salu_cmov_pack", "s_pack_lh",
197 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
198 "s_pack_lh_b32_b16 s6, s4, s5", "{S1.hi, S0.lo} = 0x33332222, SCC kept"),
199 _salu32_pair("salu_cmov_pack", "s_pack_hh",
200 ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"],
201 "s_pack_hh_b32_b16 s6, s4, s5", "{S1.hi, S0.hi} = 0x33331111, SCC kept"),
202 ]
203
204 # 5. s_bfe_u32 / s_bfe_i32 past bit 31
205 cases += [
206 _salu32_pair("salu_bfe_past31", "s_bfe_i32_past31",
207 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0x7f001c"],
208 "s_bfe_i32 s6, s4, s5", "off=28 width=127 stops at bit 31 -> 0xfffffffd, SCC=1"),
209 _salu32_pair("salu_bfe_past31", "s_bfe_u32_past31",
210 ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0xff7f001c"],
211 "s_bfe_u32 s6, s4, s5", "upper bits ignored, stops at bit 31 -> 0x0000000d, SCC=1"),
212 _salu32_pair("salu_bfe_past31", "s_bfe_i32_width0",
213 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0x00000005"],
214 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"),
215 ]
216
217 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64)
218 cases += [
219 _salu64_case("salu_64_data", "s_brev_b64_scc1",
220 ["s_mov_b32 s4, 0x80000001", "s_mov_b32 s5, 0x12345678"],
221 "s_brev_b64 s[6:7], s[4:5]", 1, "bit-reverse 64-bit pair, SCC kept"),
222 _salu64_case("salu_64_data", "s_bfe_u64_cross_past63",
223 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
224 "s_bfe_u64 s[6:7], s[4:5], s8", 0, "off=60 width=127 stops at bit 63 -> 0xd, SCC=1"),
225 _salu64_case("salu_64_data", "s_bfe_i64_past63",
226 ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"],
227 "s_bfe_i64 s[6:7], s[4:5], s8", 0, "off=60 width=127 sign-extends 0xd -> -3, SCC=1"),
228 _salu64_case("salu_64_data", "s_bfe_u64_width0",
229 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff", "s_mov_b32 s8, 0x00000010"],
230 "s_bfe_u64 s[6:7], s[4:5], s8", 1, "width=0 -> 0, SCC=0"),
231 _salu64_case("salu_64_data", "s_bitset0_b64_hi",
232 ["s_mov_b32 s6, 0xffffffff", "s_mov_b32 s7, 0xffffffff", "s_mov_b32 s8, 63"],
233 "s_bitset0_b64 s[6:7], s8", 1, "clear bit 63, SCC kept"),
234 _salu64_case("salu_64_data", "s_bitset1_b64_mod64",
235 ["s_mov_b32 s6, 0", "s_mov_b32 s7, 0", "s_mov_b32 s8, 97"],
236 "s_bitset1_b64 s[6:7], s8", 0, "set bit 97 & 63 = 33 (hi bit 1), SCC kept"),
237 _salu32_pair("salu_64_data", "s_flbit_i32_b64_zero",
238 ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0"],
239 "s_flbit_i32_b64 s6, s[4:5]", "0 -> -1, SCC kept"),
240 _salu32_pair("salu_64_data", "s_flbit_i32_b64_lo",
241 ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 0"],
242 "s_flbit_i32_b64 s6, s[4:5]", "bit 16 -> 47 leading zeros, SCC kept"),
243 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg",
244 ["s_mov_b32 s4, 0xfffffff0", "s_mov_b32 s5, 0xffffffff"],
245 "s_flbit_i32_i64 s6, s[4:5]", "-16 -> 59 sign bits, SCC kept"),
246 _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg1",
247 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
248 "s_flbit_i32_i64 s6, s[4:5]", "-1 -> -1, SCC kept"),
249 ]
250
251 # 7. s_quadmask_b32/b64, s_bitreplicate_b64_b32
252 cases += [
253 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_nz",
254 ["s_mov_b32 s4, 0x10080041"],
255 "s_quadmask_b32 s6, s4", "quads 0,1,4,7 set -> 0x93, SCC=1"),
256 _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_zero",
257 ["s_mov_b32 s4, 0"],
258 "s_quadmask_b32 s6, s4", "0 -> 0, SCC=0"),
259 _salu64_case("salu_quad_bitrep", "s_quadmask_b64_hi",
260 ["s_mov_b32 s4, 0x00000000", "s_mov_b32 s5, 0x80000001"],
261 "s_quadmask_b64 s[6:7], s[4:5]", 0, "quads 8,15 -> lo=0x8100 hi=0, SCC=1"),
262 _salu64_case("salu_quad_bitrep", "s_bitreplicate_b64_b32",
263 ["s_mov_b32 s4, 0x80010005"],
264 "s_bitreplicate_b64_b32 s[6:7], s4", 1, "each bit doubled, SCC kept"),
265 ]
266
267 # 8. 64-bit scalar bitwise ops on scalar data
268 for op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
269 "s_nand_b64", "s_nor_b64", "s_xnor_b64"):
270 cases.append(_salu64_case(
271 "salu_64_bitwise", f"{op}_data",
272 ["s_mov_b32 s4, 0xf0f000ff", "s_mov_b32 s5, 0x12345678",
273 "s_mov_b32 s8, 0x0ff0ff00", "s_mov_b32 s9, 0x87654321"],
274 f"{op} s[6:7], s[4:5], s[8:9]", 0, f"{op} on 64-bit scalar data + SCC",
275 ))
276 cases.append(_salu64_case(
277 "salu_64_bitwise", "s_not_b64_all_ones",
278 ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"],
279 "s_not_b64 s[6:7], s[4:5]", 1, "~(-1) = 0, SCC=0",
280 ))
281
282 # 9. s_movrels_b32 / s_movrels_b64
283 cases += [
284 _salu32_pair("salu_movrels", "s_movrels_b32_m0_2",
285 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
286 "s_mov_b32 s12, 0x33333333", "s_mov_b32 m0, 2"],
287 "s_movrels_b32 s6, s10", "SGPR[10+2] = 0x33333333, SCC kept"),
288 _salu64_case("salu_movrels", "s_movrels_b64_m0_2",
289 ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222",
290 "s_mov_b32 s12, 0x33333333", "s_mov_b32 s13, 0x44444444", "s_mov_b32 m0, 2"],
291 "s_movrels_b64 s[6:7], s[10:11]", 1, "SGPR[12:13], SCC kept"),
292 ]
293
294 # 10. Integer clamp on v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16
295 cases += [
296 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u32_clamp", [
297 "v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x30",
298 "v_add_nc_u32_e64 v8, v1, v2 clamp", # saturates to 0xffffffff
299 "v_sub_nc_u32_e64 v9, v2, v1 clamp", # saturates to 0
300 "v_subrev_nc_u32_e64 v10, v1, v2 clamp", # v2 - v1 -> saturates to 0
301 "v_subrev_nc_u32_e64 v11, v2, v1 clamp", # v1 - v2 = 0xffffffc0
302 ], "u32 nc add/sub/subrev with clamp"),
303 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i32_clamp", [
304 "v_mov_b32 v1, 0x7ffffff0", "v_mov_b32 v2, 0x30",
305 "v_mov_b32 v3, 0x80000010", "v_mov_b32 v4, 0x30",
306 "v_add_nc_i32_e64 v8, v1, v2 clamp", # +overflow -> 0x7fffffff
307 "v_sub_nc_i32_e64 v9, v3, v4 clamp", # -overflow -> 0x80000000
308 "v_add_nc_i32_e64 v10, v3, v3 clamp", # neg+neg overflow -> 0x80000000
309 "v_sub_nc_i32_e64 v11, v1, v3 clamp", # pos-neg overflow -> 0x7fffffff
310 ], "i32 nc add/sub with clamp"),
311 _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u16_clamp", [
312 "v_mov_b32 v1, 0x1234fff0", "v_mov_b32 v2, 0x56780030",
313 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
314 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
315 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
316 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
317 "v_add_nc_u16_e64 v8, v1, v2 clamp", # lo saturates 0xffff, hi kept
318 "v_sub_nc_u16_e64 v9, v2, v1 clamp", # lo saturates 0x0000, hi kept
319 "v_add_nc_u16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0xffff, lo kept
320 "v_sub_nc_u16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 -> 0x0000, hi kept
321 ], "u16 nc add/sub with clamp and op_sel (untouched half kept)"),
322 ]
323
324 # 11. v_add/sub/subrev_co[_ci]_u32 with clamp (known divergence: translator ignores clamp)
325 cases += [
326 _valu4_case("valu_add_co_clamp", "v_add_co_u32_clamp", [
327 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
328 "v_add_co_u32 v8, {vcc}, v1, v2 clamp",
329 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
330 "v_mov_b32 v3, 5", "v_mov_b32 v4, 10",
331 "v_sub_co_u32 v10, {vcc}, v3, v4 clamp",
332 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
333 ], "v_add_co_u32 / v_sub_co_u32 clamp: hardware saturates D and reports real carry/borrow"),
334 _valu4_case("valu_add_co_clamp", "v_subrev_co_u32_clamp", [
335 "v_mov_b32 v1, 10", "v_mov_b32 v2, 5",
336 "v_subrev_co_u32 v8, {vcc}, v1, v2 clamp",
337 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
338 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
339 "{smov} {vcc}, -1",
340 "v_subrev_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
341 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
342 ], "v_subrev_co_u32 / v_subrev_co_ci_u32 clamp: hardware saturates D to 0 and reports borrow=1"),
343 _valu4_case("valu_add_co_clamp", "v_add_co_ci_u32_clamp", [
344 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0",
345 "{smov} {vcc}, -1",
346 "v_add_co_ci_u32_e64 v8, {vcc}, v1, v2, {vcc} clamp",
347 "v_cndmask_b32_e64 v9, 0, 1, {vcc}",
348 "v_mov_b32 v3, 0", "v_mov_b32 v4, 0",
349 "{smov} {vcc}, -1",
350 "v_sub_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp",
351 "v_cndmask_b32_e64 v11, 0, 1, {vcc}",
352 ], "v_add_co_ci_u32 / v_sub_co_ci_u32 clamp: carry-in overflow saturates D and sets carry-out"),
353 ]
354
355 # 12. v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and EXEC masking)
356 cases += [
357 _valu4_case("valu_mad64", "v_mad_u64_u32_carry", [
358 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
359 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
360 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
361 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
362 "v_mov_b32 v11, 0",
363 ], "u64 max*max + max64 -> carry=1"),
364 _valu4_case("valu_mad64", "v_mad_i64_i32_pos_overflow", [
365 "v_mov_b32 v1, 0x80000000", "v_mov_b32 v2, 0x80000000",
366 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0x7fffffff",
367 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
368 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
369 "v_mov_b32 v11, 0",
370 ], "(-2^31)^2 + INT64_MAX > 0 (signed overflow, positive exact sum -> sdst=0)"),
371 _valu4_case("valu_mad64", "v_mad_i64_i32_neg_sum", [
372 "v_mov_b32 v1, 0xfffffffe", "v_mov_b32 v2, 3",
373 "v_mov_b32 v4, 0", "v_mov_b32 v5, 0",
374 "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]",
375 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
376 "v_mov_b32 v11, 0",
377 ], "(-2)*3 + 0 = -6 -> sdst=1 (bit 64 sign of exact 65-bit sum)"),
378 _valu4_case("valu_mad64", "v_mad_u64_u32_inactive_lane", [
379 "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff",
380 "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff",
381 "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222",
382 "{smov} {vcc}, -1",
383 "{smov} {stmp}, {exec}",
384 "{smov} {exec}, 0",
385 "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]",
386 "{smov} {exec}, {stmp}",
387 "v_cndmask_b32_e64 v10, 0, 1, {vcc}",
388 "v_mov_b32 v11, 0",
389 ], "inactive EXEC lane: D untouched and sdst bit cleared to 0"),
390 ]
391
392 # 13. v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8
393 cases += [
394 _valu4_case("valu_sad_lerp", "v_sad_ops", [
395 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x0080f002", "v_mov_b32 v3, 0xffffff00",
396 "v_sad_u8 v8, v1, v2, v3", # wraps 32-bit
397 "v_sad_hi_u8 v9, v1, v2, v3", # (byte_sad << 16) + S2
398 "v_sad_u16 v10, v1, v2, v3", # 2x16-bit SAD + S2
399 "v_sad_u32 v11, v1, v2, v3", # |v1 - v2| + S2
400 ], "v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_sad_u32 with 32-bit wrap"),
401 _valu4_case("valu_sad_lerp", "v_msad_and_lerp", [
402 "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x00800005", "v_mov_b32 v3, 100",
403 "v_msad_u8 v8, v1, v2, v3", # skips bytes 1 and 3 where S1 byte == 0
404 "v_mov_b32 v4, 0xff030200", "v_mov_b32 v5, 0xff040301", "v_mov_b32 v6, 0x01000100",
405 "v_lerp_u8 v9, v4, v5, v6", # per-byte (a+b+(c&1))>>1
406 "v_mov_b32 v7, 0x00feffff",
407 "v_lerp_u8 v10, v4, v5, v7", # upper bits of S2 bytes ignored
408 "v_mov_b32 v11, 0",
409 ], "v_msad_u8 zero-byte mask and v_lerp_u8 rounding/no-carry"),
410 ]
411
412 # 14. v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8
413 cases += [
414 _valu4_case("valu_qsad_mqsad", "v_qsad_mqsad_pk_u16", [
415 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
416 "v_mov_b32 v4, 0x00150025", # S1 has two zero bytes for mqsad
417 "v_mov_b32 v6, 0xfffe0005", "v_mov_b32 v7, 0xfff00100",
418 "v_qsad_pk_u16_u8 v[8:9], v[2:3], v4, v[6:7]",
419 "v_mqsad_pk_u16_u8 v[10:11], v[2:3], v4, v[6:7]",
420 ], "v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8 with 16-bit wrap and zero S1 bytes"),
421 _valu4_case("valu_qsad_mqsad", "v_mqsad_u32_u8", [
422 "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050",
423 "v_mov_b32 v4, 0x00150025",
424 "v_mov_b32 v12, 0xfffffffe", "v_mov_b32 v13, 10",
425 "v_mov_b32 v14, 20", "v_mov_b32 v15, 0xffffffff",
426 "v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[12:15]",
427 ], "v_mqsad_u32_u8 four 32-bit accumulators with wrap"),
428 ]
429
430 # 15. v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64
431 cases += [
432 _valu4_case("valu_mul24_sh64", "v_mul_hi_24", [
433 "v_mov_b32 v1, 0xabffffff", "v_mov_b32 v2, 0xcdffffff",
434 "v_mul_hi_u32_u24 v8, v1, v2", # upper 8 bits ignored
435 "v_mul_hi_i32_i24 v9, v1, v2", # (-1)*(-1) >> 32 = 0
436 "v_mov_b32 v3, 0x12800000", "v_mov_b32 v4, 0x347fffff",
437 "v_mul_hi_i32_i24 v10, v3, v4", # (-2^23)*(2^23-1) >> 32
438 "v_mul_hi_u32_u24 v11, v3, v4",
439 ], "v_mul_hi_u32_u24 and v_mul_hi_i32_i24 (upper 8 bits ignored)"),
440 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64", [
441 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
442 "v_mov_b32 v1, 36",
443 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
444 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
445 ], "v_lshrrev_b64 and v_ashrrev_i64 shift=36"),
446 _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64_mod64", [
447 "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321",
448 "v_mov_b32 v1, 68", # 68 & 63 = 4
449 "v_lshrrev_b64 v[8:9], v1, v[2:3]",
450 "v_ashrrev_i64 v[10:11], v1, v[2:3]",
451 ], "v_lshrrev_b64 and v_ashrrev_i64 shift masked to 6 bits"),
452 ]
453
454 # 16. v_mad_u16 / v_mad_i16 (clamp, op_sel, kept half)
455 cases += [
456 _valu4_case("valu_mad16", "v_mad_u16_i16_clamp_opsel", [
457 "v_mov_b32 v1, 0x80000300", "v_mov_b32 v2, 0x00020200", "v_mov_b32 v3, 0x00010010",
458 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
459 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
460 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
461 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
462 "v_mad_u16 v8, v1, v2, v3 clamp", # 0x300*0x200+0x10 = 0x60010 -> 0xffff
463 "v_mad_u16 v9, v1, v2, v3", # wraps to 0x0010, hi kept
464 "v_mad_i16 v10, v1, v2, v3 op_sel:[1,1,1,0] clamp", # (-32768)*2 + 1 = -65535 -> 0x8000
465 "v_mad_i16 v11, v1, v2, v3 op_sel:[0,0,0,1] clamp", # 0x300*0x200+0x10 -> 0x7fff in hi, lo kept
466 ], "v_mad_u16 / v_mad_i16 clamp, op_sel and untouched destination half"),
467 ]
468
469 # 17. v_cvt_f16_u16 / v_cvt_f16_i16 / v_cvt_u16_f16 / v_cvt_i16_f16 (kept half, NaN, inf)
470 cases += [
471 _valu4_case("valu_cvt_16", "v_cvt_u16_i16_f16_e64_nan_inf", [
472 "v_mov_b32 v1, 0x00007e00", # +qNaN
473 "v_mov_b32 v2, 0x0000fe00", # -qNaN
474 "v_mov_b32 v3, 0x00007c00", # +inf
475 "v_mov_b32 v4, 0x0000fc00", # -inf
476 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
477 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
478 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
479 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
480 "v_cvt_u16_f16_e64 v8, v1", # +qNaN -> 0, check high half
481 "v_cvt_i16_f16_e64 v9, v2", # -qNaN -> 0, check high half
482 "v_cvt_u16_f16_e64 v10, v3", # +inf -> 0xffff, check high half
483 "v_cvt_i16_f16_e64 v11, v4", # -inf -> 0x8000, check high half
484 ], "v_cvt_u16/i16_f16_e64 on +-qNaN and +-inf (high half behavior)"),
485 _valu4_case("valu_cvt_16", "v_cvt_f16_u16_i16_e64_keep", [
486 "v_mov_b32 v1, 0x0000fff0", # 65520 -> +inf (0x7c00)
487 "v_mov_b32 v2, 0x00008000", # -32768 -> -32768.0 (0xf800)
488 "v_mov_b32 v3, 0x0000002a", # 42 -> 42.0 (0x5140)
489 "v_mov_b32 v4, 0x00007fff", # 32767 -> 32768.0 (0x7800)
490 f"v_mov_b32 v8, 0x{SENTINEL:08x}",
491 f"v_mov_b32 v9, 0x{SENTINEL:08x}",
492 f"v_mov_b32 v10, 0x{SENTINEL:08x}",
493 f"v_mov_b32 v11, 0x{SENTINEL:08x}",
494 "v_cvt_f16_u16_e64 v8, v1",
495 "v_cvt_f16_i16_e64 v9, v2",
496 "v_cvt_f16_u16_e64 v10, v3",
497 "v_cvt_f16_i16_e64 v11, v4",
498 ], "v_cvt_f16_u16/i16_e64 overflow to +inf and high half behavior"),
499 ]
500
501 # 18. v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 (exact floor(x+0.5) + signed NaN; v_cvt_i32_f32 control)
502 cases += [
503 _valu4_case("valu_cvt_flr_rpi", "v_cvt_rpi_precision", [
504 "v_mov_b32 v1, 0x3effffff", # 0.49999997 (f32(x+0.5)==1.0, exact floor(x+0.5)==0)
505 "v_mov_b32 v2, 0x4b000001", # 8388609.0 (f32(x+0.5)==8388610.0, exact==8388609)
506 "v_mov_b32 v3, 0x4b7fffff", # 16777215.0 (f32(x+0.5)==16777216.0, exact==16777215)
507 "v_mov_b32 v4, 0xbf000000", # -0.5 -> floor(-0.5 + 0.5) = 0
508 "v_cvt_rpi_i32_f32 v8, v1",
509 "v_cvt_rpi_i32_f32 v9, v2",
510 "v_cvt_rpi_i32_f32 v10, v3",
511 "v_cvt_rpi_i32_f32 v11, v4",
512 ], "v_cvt_rpi_i32_f32 exact floor(x+0.5) vs binary32 x+0.5"),
513 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_rpi_nan_inf", [
514 "v_mov_b32 v1, 0x7fc00000", # +qNaN
515 "v_mov_b32 v2, 0xffc00000", # -qNaN
516 "v_cvt_flr_i32_f32 v8, v1",
517 "v_cvt_flr_i32_f32 v9, v2",
518 "v_cvt_rpi_i32_f32 v10, v1",
519 "v_cvt_rpi_i32_f32 v11, v2",
520 ], "v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 on +qNaN and -qNaN"),
521 _valu4_case("valu_cvt_flr_rpi", "v_cvt_i32_f32_nan_control", [
522 "v_mov_b32 v1, 0x7fc00000", # +qNaN
523 "v_mov_b32 v2, 0xffc00000", # -qNaN
524 "v_mov_b32 v3, 0x7f800001", # +sNaN
525 "v_mov_b32 v4, 0xff800001", # -sNaN
526 "v_cvt_i32_f32 v8, v1",
527 "v_cvt_i32_f32 v9, v2",
528 "v_cvt_i32_f32 v10, v3",
529 "v_cvt_i32_f32 v11, v4",
530 ], "control: v_cvt_i32_f32 returns 0 for every NaN"),
531 _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_edges", [
532 "v_mov_b32 v1, 0xbf800001", # -1.0000001 -> -2
533 "v_mov_b32 v2, 0x7f800000", # +inf -> INT_MAX
534 "v_mov_b32 v3, 0xff800000", # -inf -> INT_MIN
535 "v_mov_b32 v4, 0x4f000000", # +2^31 -> INT_MAX
536 "v_cvt_flr_i32_f32 v8, v1",
537 "v_cvt_flr_i32_f32 v9, v2",
538 "v_cvt_flr_i32_f32 v10, v3",
539 "v_cvt_flr_i32_f32 v11, v4",
540 ], "v_cvt_flr_i32_f32 negative fraction, infinities and 2^31 saturation"),
541 ]
542
543 # 19. v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 (NaN, inf, out-of-range, ties)
544 cases += [
545 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_nan_inf", [
546 "v_mov_b32 v1, 0x7fc00000", # +qNaN
547 "v_mov_b32 v2, 0xffc00000", # -qNaN
548 "v_mov_b32 v3, 0x7f800000", # +inf
549 "v_mov_b32 v4, 0xff800000", # -inf
550 "v_cvt_pknorm_i16_f32 v8, v1, v2",
551 "v_cvt_pknorm_u16_f32 v9, v1, v2",
552 "v_cvt_pknorm_i16_f32 v10, v3, v4",
553 "v_cvt_pknorm_u16_f32 v11, v3, v4",
554 ], "v_cvt_pknorm_i16/u16_f32 on +-qNaN and +-inf"),
555 _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_ties", [
556 "v_mov_b32 v1, 0x3f000000", # 0.5 -> 0.5*32767 = 16383.5 (RNE=16384), 0.5*65535 = 32767.5 (RNE=32768)
557 "v_mov_b32 v2, 0xbf000000", # -0.5 -> -16383.5 (RNE=-16384), u16 -> 0
558 "v_mov_b32 v3, 0x3f800000", # 1.0 -> 32767 / 65535
559 "v_mov_b32 v4, 0xbf800000", # -1.0 -> -32767 (0x8001) / 0
560 "v_cvt_pknorm_i16_f32 v8, v1, v2",
561 "v_cvt_pknorm_u16_f32 v9, v1, v2",
562 "v_cvt_pknorm_i16_f32 v10, v3, v4",
563 "v_cvt_pknorm_u16_f32 v11, v3, v4",
564 ], "v_cvt_pknorm_i16/u16_f32 ties at +-0.5 and +-1.0 endpoints"),
565 ]
566
567 return cases
568
569
570def _translate_case(work, case):
571 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
572 name = f"ps_int_hw_{case.name}"
573 src = os.path.join(work, "disasm", name + ".s")
574 body = case.lines(wave=32) + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]
575 with open(src, "w", encoding="utf-8", newline="\n") as f:
576 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
577 with open(os.path.join(work, name + ".dxbc"), "wb") as f:
578 f.write(STUB_DXBC)
579 with warnings.catch_warnings():
580 warnings.simplefilter("ignore", ResourceWarning)
581 spv = rdna2spirv.translate(src)
582 return list(spirv_mini_interp.run_fragment(spv)["%out_mrt0"])
583
584
585def run_translator(cases):
586 out = {}
587 with tempfile.TemporaryDirectory(prefix="int_hw_probe_") as work:
588 for case in cases:
589 try:
590 out[case.name] = _translate_case(work, case)
591 except Exception as e:
592 out[case.name] = f"error: {type(e).__name__}: {e}"
593 return out
594
595
596def run_hw(cases, arch=None, waves=(32, 64)):
597 from hw_oracle import asm, runner # noqa: E402
598 oracle = runner.open_oracle(arch=arch)
599 try:
600 device = oracle.device
601 per_wave = {}
602 for wave in waves:
603 kernels = [asm.Kernel(case.lines(wave=wave), wave=wave, threads=1, words=4) for case in cases]
604 res = oracle.run(kernels, words=4)
605 per_wave[wave] = {case.name: r for case, r in zip(cases, res)}
606 return device, per_wave
607 finally:
608 oracle.close()
609
610
611def _fmt_words(w):
612 if isinstance(w, list):
613 return " ".join(f"0x{x:08x}" for x in w)
614 return str(w)
615
616
617def self_test():
618 cases = build_cases()
619 names = [c.name for c in cases]
620 assert len(names) == len(set(names)), "duplicate case names"
621 for name in KNOWN_DIVERGENCES:
622 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
623 res = run_translator(cases)
624 errors = {k: v for k, v in res.items() if not isinstance(v, list)}
625 assert not errors, f"translator errors: {errors}"
626 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
627 return 0
628
629
630def main(argv=None):
631 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
632 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
633 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
634 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
635 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
636 ap.add_argument("--list-groups", action="store_true")
637 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
638 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
639 ap.add_argument("--self-test", action="store_true")
640 args = ap.parse_args(argv)
641
642 if args.self_test:
643 return self_test()
644
645 cases = build_cases()
646 groups = []
647 for c in cases:
648 if c.group not in groups:
649 groups.append(c.group)
650 if args.list_groups:
651 for g in groups:
652 n = sum(1 for c in cases if c.group == g)
653 print(f"{g:<22} ({n} cases)")
654 return 0
655
656 if args.group:
657 unknown = [g for g in args.group if g not in groups]
658 if unknown:
659 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
660 return 2
661 want = set(args.group)
662 cases = [c for c in cases if c.group in want]
663
664 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
665 tr_res = run_translator(cases) if args.oracle in ("translator", "both") else None
666 hw_device, hw_res = None, None
667 if args.oracle in ("hw", "both"):
668 from hw_oracle import runner # noqa: E402
669 try:
670 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
671 except runner.Unavailable as e:
672 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
673 return 77
674 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
675
676 mismatches = 0
677 known_diffs = 0
678 wave_diffs = 0
679 records = []
680 for c in cases:
681 tr = tr_res[c.name] if tr_res is not None else None
682 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
683 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
684 hw_ref = h32 if h32 is not None else h64
685 status = "OK"
686 tag = None
687 if h32 is not None and h64 is not None and h32 != h64:
688 status = "WAVE_DIFF"
689 wave_diffs += 1
690 elif (tr is not None and not isinstance(tr, list)) or (hw_ref is not None and not isinstance(hw_ref, list)):
691 status = "ERROR"
692 mismatches += 1
693 elif tr is not None and hw_ref is not None and tr != hw_ref:
694 known = KNOWN_DIVERGENCES.get(c.name)
695 if known and hw_ref == known[1]:
696 status = "KNOWN_DIFF"
697 tag = known[0]
698 known_diffs += 1
699 else:
700 status = "MISMATCH"
701 mismatches += 1
702 records.append({
703 "group": c.group, "name": c.name, "note": c.note, "status": status, "known_tag": tag,
704 "translator": tr, "hw_w32": h32, "hw_w64": h64,
705 })
706 if status != "OK" or args.oracle != "both":
707 label = f"{status}:{tag}" if tag else status
708 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
709 if h32 is not None:
710 print(f" hw_w32: {_fmt_words(h32)}")
711 if h64 is not None and h64 != h32:
712 print(f" hw_w64: {_fmt_words(h64)}")
713 if tr is not None:
714 print(f" transl: {_fmt_words(tr)}")
715
716 total = len(cases)
717 matched = total - mismatches - known_diffs - wave_diffs
718 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
719 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
720
721 if args.json_out:
722 out_path = os.path.abspath(args.json_out)
723 if os.path.isdir(out_path):
724 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
725 return 2
726 parent = os.path.dirname(out_path)
727 if parent:
728 os.makedirs(parent, exist_ok=True)
729 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
730 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
731 f.write("\n")
732
733 if mismatches or wave_diffs or (args.strict and known_diffs):
734 return 1
735 return 0
736
737
738if __name__ == "__main__":
739 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
740 sys.stdout.reconfigure(errors="replace")
741 except (AttributeError, ValueError, OSError):
742 pass
743 sys.exit(main())
diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py
index 6b3bb4ca8..e2be8b9b2 100644
--- a/tools/lds_fuzz.py
+++ b/tools/lds_fuzz.py
@@ -108,6 +108,7 @@ PERTURBATIONS = {
108 "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"), 108 "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"),
109 "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"), 109 "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"),
110 "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"), 110 "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"),
111 "permute_lowest_wins": ("permute", "ds_permute_b32 lets the lowest active source lane win a collision"),
111} 112}
112PERTURB = set() 113PERTURB = set()
113 114
@@ -382,13 +383,13 @@ class Program:
382 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), 383 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL),
383 "dst": rng.choice(POOL), "exec": self.exec_mask()} 384 "dst": rng.choice(POOL), "exec": self.exec_mask()}
384 if kind == "permute": 385 if kind == "permute":
385 # an odd multiplier makes the lane -> lane map a bijection in a 32- and in a 64-lane group, so no two 386 # allow both odd (bijective) and even (colliding) multipliers; RDNA2 hw (gfx1030, SHADER-133) and gfx1150
386 # lanes send to the same lane and the result doesn't depend on which write wins 387 # confirm the highest active source lane wins a collision, unaddressed active lanes get 0, halves separate
387 return {"kind": kind, "mul": rng.randrange(1, 64, 2), "add": rng.randrange(0, 64), 388 return {"kind": kind, "mul": rng.randrange(0, 64), "add": rng.randrange(0, 64),
388 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), 389 "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL),
389 "dst": rng.choice(POOL), "exec": self.exec_mask(), 390 "dst": rng.choice(POOL), "exec": self.exec_mask(),
390 "hyp": "the ISA text: only active lanes send, a lane nobody sends to gets 0, each 32-lane half " 391 "hyp": "only active lanes send, highest active sender wins collisions, a lane nobody sends to "
391 "is separate"} 392 "gets 0, each 32-lane half is separate (measured on gfx1030 SHADER-133 and gfx1150)"}
392 raise ValueError(kind) 393 raise ValueError(kind)
393 394
394 # ---- the program text ---- 395 # ---- the program text ----
@@ -681,11 +682,12 @@ class Program:
681 for t, v in new.items(): 682 for t, v in new.items():
682 regs[t][op["dst"]] = v 683 regs[t][op["dst"]] = v
683 elif k == "permute": 684 elif k == "permute":
684 # forward permute: an active lane sends its data to lane (addr + offset) / 4 of its 32-lane group, an 685 # forward scatter within each 32-lane half: active lanes send to lane (addr + offset) / 4 of their 32-lane
685 # active lane gets what was sent to it, or 0 686 # group; highest-numbered active source wins collisions; active destination lanes nobody targets get 0
686 src = [regs[t][op["src"]] for t in range(T)] 687 src = [regs[t][op["src"]] for t in range(T)]
687 sent = {} 688 sent = {}
688 for t in range(T): 689 lanes = range(T - 1, -1, -1) if "permute_lowest_wins" in PERTURB else range(T)
690 for t in lanes:
689 if act[t]: 691 if act[t]:
690 word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2 692 word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2
691 sent[(t & ~31) | (word & 31)] = src[t] 693 sent[(t & ~31) | (word & 31)] = src[t]
@@ -739,7 +741,7 @@ def translate(progs, work, emulate):
739 for p in progs: 741 for p in progs:
740 text = p.asm() 742 text = p.asm()
741 asm_path = work / (p.name + ".asm") 743 asm_path = work / (p.name + ".asm")
742 asm_path.write_text(text, encoding="utf-8") 744 asm_path.write_text(text, encoding="utf-8", newline="\n")
743 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] 745 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
744 if p.wave == 64: 746 if p.wave == 64:
745 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") 747 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32")
@@ -747,7 +749,7 @@ def translate(progs, work, emulate):
747 if r.returncode or "error:" in r.stderr: 749 if r.returncode or "error:" in r.stderr:
748 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") 750 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}")
749 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 751 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
750 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") 752 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n")
751 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) 753 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path))
752 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] 754 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)]
753 if emulate: 755 if emulate:
@@ -943,7 +945,7 @@ def run_hw(oracle, progs, a, tally, results):
943 print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else "")) 945 print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else ""))
944 if a.keep: 946 if a.keep:
945 os.makedirs(a.keep, exist_ok=True) 947 os.makedirs(a.keep, exist_ok=True)
946 Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8") 948 Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8", newline="\n")
947 print("hardware summary:") 949 print("hardware summary:")
948 for key, st in sorted(stats.items()): 950 for key, st in sorted(stats.items()):
949 print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) 951 print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items()))
diff --git a/tools/manifest.py b/tools/manifest.py
index 9c39d9030..7ffa41c10 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -22,7 +22,7 @@ DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.jso
22 22
23 23
24class ManifestError(Exception): 24class ManifestError(Exception):
25 """A manifest that isn't valid JSON or doesn't have the layout create() writes.""" 25 """An input or manifest error that the CLI reports without a traceback."""
26 26
27 27
28def default_jobs() -> int: 28def default_jobs() -> int:
@@ -52,12 +52,32 @@ def below_normal() -> None:
52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS 52 k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS
53 53
54 54
55def sha256(path: str) -> str: 55def _file_stamp(st: os.stat_result) -> tuple[int, int, int]:
56 return st.st_size, st.st_mtime_ns, st.st_ctime_ns
57
58
59def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str]:
60 """Return the size and digest of the same open file, or fail if it changes."""
56 h = hashlib.sha256() 61 h = hashlib.sha256()
57 with open(path, "rb", buffering=0) as f: 62 with open(path, "rb", buffering=0) as f:
58 while chunk := f.read(CHUNK): 63 before = os.fstat(f.fileno())
64 size = before.st_size
65 if expected_size is not None and size != expected_size:
66 raise ManifestError(f"{path}: file size changed before hashing")
67 remaining = size
68 while remaining and (chunk := f.read(min(CHUNK, remaining))):
59 h.update(chunk) 69 h.update(chunk)
60 return h.hexdigest() 70 remaining -= len(chunk)
71 # Compare timestamps from the same handle. Windows can report different times by path.
72 # Compare the path by identity so a replacement of the open file is detected too.
73 if (remaining or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before)
74 or not os.path.samestat(before, os.stat(path))):
75 raise ManifestError(f"{path}: file changed while hashing")
76 return size, h.hexdigest()
77
78
79def sha256(path: str) -> str:
80 return _hash_file(path)[1]
61 81
62 82
63def same_output_path(first: str, second: str) -> bool: 83def same_output_path(first: str, second: str) -> bool:
@@ -114,7 +134,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
114 if same_output_path(out, path): 134 if same_output_path(out, path):
115 raise ManifestError(f"--out would overwrite the input {path}; " 135 raise ManifestError(f"--out would overwrite the input {path}; "
116 "choose a manifest path that is not one of the hashed files") 136 "choose a manifest path that is not one of the hashed files")
117 total = sum(os.path.getsize(p) for _, p in files) 137 sizes = {path: os.path.getsize(path) for _, path in files}
138 total = sum(sizes.values())
118 entries = {} 139 entries = {}
119 done = count = 0 140 done = count = 0
120 t0 = time.time() 141 t0 = time.time()
@@ -131,7 +152,8 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
131 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True) 152 print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True)
132 153
133 def work(rel: str, path: str) -> tuple[str, int, str]: 154 def work(rel: str, path: str) -> tuple[str, int, str]:
134 return rel, os.path.getsize(path), sha256(path) 155 size, digest = _hash_file(path, expected_size=sizes[path])
156 return rel, size, digest
135 157
136 if jobs == 1: 158 if jobs == 1:
137 for rel, p in files: 159 for rel, p in files:
@@ -148,7 +170,7 @@ def create(game_dir: str, out: str, jobs: int = 1) -> int:
148 os.makedirs(out_dir, exist_ok=True) 170 os.makedirs(out_dir, exist_ok=True)
149 with tempfile.TemporaryDirectory(dir=out_dir) as staging: 171 with tempfile.TemporaryDirectory(dir=out_dir) as staging:
150 staged = os.path.join(staging, "manifest.json") 172 staged = os.path.join(staging, "manifest.json")
151 with open(staged, "w", encoding="utf-8") as f: 173 with open(staged, "w", encoding="utf-8", newline="\n") as f:
152 json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1) 174 json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1)
153 os.replace(staged, out) 175 os.replace(staged, out)
154 print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}") 176 print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}")
diff --git a/tools/mem_diff.py b/tools/mem_diff.py
index 2be12e8bd..ebee3554e 100644
--- a/tools/mem_diff.py
+++ b/tools/mem_diff.py
@@ -640,7 +640,7 @@ def run_one(name, prog):
640 dis = os.path.join(tmp, "disasm") 640 dis = os.path.join(tmp, "disasm")
641 os.mkdir(dis) 641 os.mkdir(dis)
642 path = os.path.join(dis, name + ".s") 642 path = os.path.join(dis, name + ".s")
643 with open(path, "w", encoding="utf-8") as f: 643 with open(path, "w", encoding="utf-8", newline="\n") as f:
644 f.write(_listing(prog.lines)) 644 f.write(_listing(prog.lines))
645 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: 645 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
646 f.write(STUB_DXBC) 646 f.write(STUB_DXBC)
diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py
index a2f8508ae..febba1dab 100644
--- a/tools/meshlet_page.py
+++ b/tools/meshlet_page.py
@@ -487,7 +487,7 @@ def main(argv=None):
487 report = json.dumps({"bindings": rows}, indent=2) 487 report = json.dumps({"bindings": rows}, indent=2)
488 if args.json: 488 if args.json:
489 try: 489 try:
490 with open(args.json, "w", encoding="utf-8") as out: 490 with open(args.json, "w", encoding="utf-8", newline="\n") as out:
491 out.write(report + "\n") 491 out.write(report + "\n")
492 except OSError as exc: 492 except OSError as exc:
493 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 493 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
@@ -514,7 +514,7 @@ def main(argv=None):
514 print(json.dumps(total, indent=1)) 514 print(json.dumps(total, indent=1))
515 if args.json: 515 if args.json:
516 try: 516 try:
517 with open(args.json, "w", encoding="utf-8") as fh: 517 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
518 json.dump({"totals": total, "pages": pages}, fh, indent=1) 518 json.dump({"totals": total, "pages": pages}, fh, indent=1)
519 except OSError as exc: 519 except OSError as exc:
520 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 520 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/mission_tables.py b/tools/mission_tables.py
new file mode 100644
index 000000000..d2da85a93
--- /dev/null
+++ b/tools/mission_tables.py
@@ -0,0 +1,524 @@
1"""Read mission-state tables: 32-byte state records and the 64-byte pool elements they point at.
2
3`docs/mission_logic.md` describes the tables that carry mission structure in the PSIN streams of the script
4archives. This tool is the reader for them. It takes inflated PSIN files (a directory of carved `.bin`
5streams works too) and prints, per file, the number of records, the distinct state keys, the distinct
6archetype and link hashes, and every entity it could resolve to a world transform.
7
8Record, 32 bytes:
9
10 +0 u32 key joaat of the state name, lower-cased first
11 +4 u32 0
12 +8 u32 colB an ascending band-like column; 1 on every record measured here
13 +12 u32 0
14 +16 u32 (u16 kind at the low half, u16 offset at the high half)
15 +20 u32 band an ascending band counter, not always zero (0, 0, 1, 2, 2, ...)
16 +24 u32 (u16 n, u16 n) the entity count, stored twice
17 +28 u32 0
18
19The offset is a byte offset. It is stored in the **high half** of the dword at +16, which is the big end of
20the little-endian word; the low half is `kind`. The two u16s are not byte-swapped: the measured bytes
21`03 00 80 07` resolve kind 3 and offset 0x780, not 0x8007. A record whose offset is outside the file is
22still a record; it simply resolves to no entity.
23
24Pool element, 64 bytes, 16 dwords:
25
26 +0x00 u32 archetype/state hash
27 +0x04 u32 0
28 +0x08 u32 0
29 +0x0C u32 0
30 +0x10 f32 pos.x, pos.y, pos.z (world coordinates in RAGE space, Z up)
31 +0x1C f32 pos.x the first position component, duplicated
32 +0x20 f32 rot.x, rot.y, rot.z
33 +0x2C f32 rot.x the first rotation component, duplicated
34 +0x30 u32 hash repeats the archetype hash on most elements
35 +0x34 u32 linkHash joaat of the lower-cased linked name (a character, for example)
36 +0x38 u32 0 a second hash on some elements, otherwise zero
37 +0x3C u32 0 zero on every element measured here
38
39The duplicated first component is the cheap structural test that separates a real element from a random
4064-byte window. This tool requires it for both the position and the rotation, and finite values in a
41plausible world range. The last two dwords are not required to be zero: a measured minority of elements
42carries a second link hash in the third-last dword. Requiring `+0x38 == +0x3C == 0` would silently drop
43those entities, so the reader keeps them and reports the extra hash as `extra`.
44
45Resolution is two-step, because the measured streams prove two encodings:
46
471. **File-absolute** (the common case): the record's offset is the byte address of the element.
482. **Linked pool** (the family documented as the "next even-tagged pool chunk" rule): inside a PSIN
49 container, a block of records is followed by the block that holds its elements. The record offset is
50 then a 16-byte-unit offset into that pool block: `element = pool_block_base + (offset >> 4)`. The
51 measured family uses offsets such as 0x0, 0xC00, 0x1800, ... while its elements sit 0xC0 bytes apart.
52
53Both addresses are scored when they exist: the one that validates more of the record's `n` slots wins, and
54a tie keeps the file-absolute reading. A slot that fails the duplicated-component test is counted as
55skipped, never reported as an entity. The scoring matters on the pool-relative family, where an offset
56such as 0x3000 can also name an unrelated element elsewhere in the file.
57
58Detection is structural rather than schema-driven so a bare `.bin` works as well as a PSIN container. A
59record chunk is a run of at least two consecutive 32-byte records with the same `kind`; a lone record is
60kept when it has a hash-sized key, a small `colB`, and an offset that already names an element. For PSIN
61input the block table is used to find the linked pool block (skip sub-64-byte blocks and other record
62blocks, then take the first block that starts with a valid element). Bytes outside a record chunk and a
63resolved entity are counted as skipped.
64
65Usage:
66 python -I mission_tables.py <file-or-dir> [--json] [--limit N]
67
68Text output prints one line per file and one line per entity; `--json` writes `{files, summary}` with the
69same numbers and the entity list (hashes as eight lowercase hex digits).
70"""
71import argparse
72import collections
73import json
74import math
75import os
76import struct
77import sys
78
79sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
80try:
81 import psin_index # noqa: E402
82except ImportError: # a bare checkout without the sibling readers: scan raw bytes only
83 psin_index = None
84try:
85 import psin_data # noqa: E402
86except ImportError:
87 psin_data = None
88
89RECORD_SIZE = 32
90ELEMENT_SIZE = 64
91MAX_ENTITIES = 4096 # a sane upper bound for the duplicated u16 count
92MAX_WORLD = 1e7 # positions and rotations outside this are not world transforms
93RECORD_KEY_MIN = 0x10000 # below this a u32 is a small field, not a joaat state key
94POOL_SHIFT = 4 # linked-pool offsets are in 16-byte units
95
96
97def joaat(text):
98 """joaat32 of a lower-cased name (Jenkins one-at-a-time, seed 0)."""
99 h = 0
100 for byte in text.lower().encode("latin-1", "replace"):
101 h = (h + byte) & 0xFFFFFFFF
102 h = (h + (h << 10)) & 0xFFFFFFFF
103 h ^= h >> 6
104 h = (h + (h << 3)) & 0xFFFFFFFF
105 h ^= h >> 11
106 return (h + (h << 15)) & 0xFFFFFFFF
107
108
109def decode_record(blob, at):
110 """Decode the 32-byte record at `at`, or None when the bytes are not a record.
111
112 The only zero fields are +4, +12 and +28; `band` is deliberately not required to be zero (it is an
113 ascending band counter, not a reserved word).
114 """
115 if at < 0 or at + RECORD_SIZE > len(blob):
116 return None
117 key, zero_a, col_b, zero_b, kind_offset, band, duplicated, zero_c = struct.unpack_from("<8I", blob, at)
118 kind = kind_offset & 0xFFFF
119 offset = kind_offset >> 16
120 count_a, count_b = duplicated >> 16, duplicated & 0xFFFF
121 if key < RECORD_KEY_MIN or zero_a or zero_b or zero_c:
122 return None
123 if count_a != count_b or count_a > MAX_ENTITIES:
124 return None
125 return {
126 "offset": at,
127 "key": key,
128 "colB": col_b,
129 "kind": kind,
130 "poolOffset": offset,
131 "band": band,
132 "count": count_a,
133 }
134
135
136def decode_element(blob, at):
137 """Decode the 64-byte pool element at `at`, or None when the layout does not hold."""
138 if at < 0 or at + ELEMENT_SIZE > len(blob):
139 return None
140 words = struct.unpack_from("<16I", blob, at)
141 if words[0] == 0 or words[1] or words[2] or words[3]:
142 return None
143 if words[4] != words[7] or words[8] != words[11]:
144 return None
145 values = struct.unpack_from("<8f", blob, at + 16)
146 if not all(math.isfinite(v) and abs(v) <= MAX_WORLD for v in values):
147 return None
148 return {
149 "offset": at,
150 "archetype": words[0],
151 "pos": list(values[0:3]),
152 "rot": list(values[4:7]),
153 "hash": words[12],
154 "link": words[13],
155 "extra": words[14],
156 }
157
158
159def scan_elements(blob, end):
160 """Every valid pool element that starts in [0, end), keyed by its byte address."""
161 found = {}
162 for at in range(0, max(0, end - ELEMENT_SIZE + 1), 4):
163 element = decode_element(blob, at)
164 if element is not None:
165 found[at] = element
166 return found
167
168
169def find_chunks(blob, end, elements):
170 """Maximal record runs. Returns [{offset, records}] in file order.
171
172 A run is two or more consecutive 32-byte records of the same kind. A lone record survives only when
173 its file-absolute offset already names a valid element, which keeps a synthetic one-record table
174 readable without turning every aligned window in a schema into a table.
175 """
176 covered = bytearray(end)
177 chunks = []
178 at = 0
179 while at + RECORD_SIZE <= end:
180 if covered[at]:
181 at += 4
182 continue
183 first = decode_record(blob, at)
184 if first is None:
185 at += 4
186 continue
187 run = [(at, first)]
188 nxt = at + RECORD_SIZE
189 while nxt + RECORD_SIZE <= end:
190 following = decode_record(blob, nxt)
191 if following is None or following["kind"] != first["kind"]:
192 break
193 run.append((nxt, following))
194 nxt += RECORD_SIZE
195 if len(run) >= 2 or (first["key"] >= 0x1000000 and first["colB"] <= 4
196 and first["poolOffset"] in elements):
197 chunks.append({"offset": at, "records": run})
198 for record_at, _ in run:
199 covered[record_at:record_at + RECORD_SIZE] = b"\x01" * RECORD_SIZE
200 at = nxt
201 else:
202 at += RECORD_SIZE
203 return chunks
204
205
206def record_blocks(blob, blocks):
207 """The indices of blocks that are a whole table of same-kind records."""
208 out = []
209 for index, (_kind, base, size) in enumerate(blocks):
210 if size < RECORD_SIZE * 2 or size % RECORD_SIZE:
211 continue
212 first = decode_record(blob, base)
213 if first is None:
214 continue
215 rows = [decode_record(blob, base + at) for at in range(0, size, RECORD_SIZE)]
216 if all(row is not None and row["kind"] == first["kind"] for row in rows):
217 out.append(index)
218 return out
219
220
221def linked_pool(blob, blocks, block_indices, chunk_at, elements):
222 """The base of the pool block linked to the record block that holds `chunk_at`, or None.
223
224 The element block follows the record block. Sub-64-byte metadata blocks are stepped over; another
225 record block is skipped (its own pool follows it). The first other block must start with a valid
226 element, otherwise this chunk belongs to a pool family this reader does not decode.
227 """
228 if not blocks:
229 return None
230 owner = None
231 for index, (_kind, base, size) in enumerate(blocks):
232 if base <= chunk_at < base + size:
233 owner = index
234 break
235 if owner is None or owner not in block_indices:
236 return None
237 for index in range(owner + 1, len(blocks)):
238 _kind, base, size = blocks[index]
239 if size < ELEMENT_SIZE:
240 continue
241 if index in block_indices:
242 continue
243 return base if base in elements else None
244 return None
245
246
247def resolve(record, elements, pool_base):
248 """Resolve one record to [(address, element)].
249
250 Both the file-absolute address and the linked-pool address are tried when they exist. The one that
251 validates more of the record's `n` slots wins; a tie keeps the file-absolute reading. This matters on
252 the pool-relative family, where an offset such as 0x3000 can also land on an unrelated element in the
253 file and would otherwise shadow the correct pool slot.
254
255 Returns (entities, mode, skipped_slots). mode is "absolute", "pool", "empty" or "unresolved".
256 """
257 count = record["count"]
258 if count == 0:
259 return [], "empty", 0
260 candidates = []
261 if record["poolOffset"] in elements:
262 candidates.append((record["poolOffset"], "absolute"))
263 if pool_base is not None:
264 address = pool_base + (record["poolOffset"] >> POOL_SHIFT)
265 if address in elements:
266 candidates.append((address, "pool"))
267 if not candidates:
268 return [], "unresolved", count
269 best = None
270 for base, mode in candidates:
271 entities = []
272 skipped = 0
273 for slot in range(count):
274 address = base + slot * ELEMENT_SIZE
275 element = elements.get(address)
276 if element is None:
277 skipped += 1
278 else:
279 entities.append((address, element))
280 if best is None or len(entities) > len(best[0]):
281 best = (entities, mode, skipped)
282 entities, mode, skipped = best
283 if not entities:
284 return [], "unresolved", skipped
285 return entities, mode, skipped
286
287
288def parse_blob(blob, name="<memory>"):
289 """Parse one inflated stream (PSIN or bare bytes) into the tool's per-file record."""
290 first_section = len(blob)
291 blocks = []
292 if psin_index is not None and blob[:4] == b"PSIN":
293 parsed = psin_index.parse(blob)
294 if parsed is not None:
295 first_section = min(max(parsed["first_section"], 0), len(blob))
296 if psin_data is not None:
297 try:
298 blocks, _fill = psin_data.block_table(blob, first_section)
299 except (ValueError, struct.error):
300 blocks = []
301 end = first_section if first_section >= RECORD_SIZE else len(blob)
302 elements = scan_elements(blob, end)
303 chunks = find_chunks(blob, end, elements)
304 table_blocks = record_blocks(blob, blocks) if blocks else []
305 if table_blocks:
306 known = {at for chunk in chunks for at, _record in chunk["records"]}
307 for index in table_blocks:
308 _kind, base, size = blocks[index]
309 addresses = list(range(base, base + size, RECORD_SIZE))
310 if any(address in known for address in addresses):
311 continue
312 rows = [(address, decode_record(blob, address)) for address in addresses]
313 if all(row is not None for _address, row in rows):
314 chunks.append({"offset": base, "records": rows})
315 known.update(addresses)
316 chunks.sort(key=lambda chunk: chunk["offset"])
317
318 records = []
319 entity_by_address = {}
320 states = collections.defaultdict(lambda: {"key": 0, "records": 0, "slots": 0, "entities": 0})
321 skipped_slots = 0
322 unresolved = 0
323 for chunk in chunks:
324 pool_base = linked_pool(blob, blocks, table_blocks, chunk["offset"], elements)
325 for _at, record in chunk["records"]:
326 records.append(record)
327 state = states[record["key"]]
328 state["key"] = record["key"]
329 state["records"] += 1
330 found, _mode, skipped = resolve(record, elements, pool_base)
331 skipped_slots += skipped
332 if not found and record["count"]:
333 unresolved += 1
334 for address, element in found:
335 state["slots"] += 1
336 entity_by_address.setdefault(address, element)
337 for state in states.values():
338 state["entities"] = state["slots"]
339
340 entities = [entity_by_address[address] for address in sorted(entity_by_address)]
341 covered = bytearray(end)
342 for chunk in chunks:
343 for at, _record in chunk["records"]:
344 covered[at:at + RECORD_SIZE] = b"\x01" * RECORD_SIZE
345 for address in entity_by_address:
346 covered[address:address + ELEMENT_SIZE] = b"\x01" * ELEMENT_SIZE
347 skipped_bytes = end - sum(covered)
348 trailing = end
349 while trailing > 0 and not covered[trailing - 1]:
350 trailing -= 1
351 trailing_bytes = end - trailing
352
353 return {
354 "file": name,
355 "size": len(blob),
356 "scan_bytes": end,
357 "records": len(records),
358 "chunks": len(chunks),
359 "record_blocks": len(table_blocks),
360 "state_keys": len(states),
361 "entities": len(entities),
362 "entity_slots": sum(state["slots"] for state in states.values()),
363 "unresolved_records": unresolved,
364 "skipped_slots": skipped_slots,
365 "skipped_bytes": skipped_bytes,
366 "trailing_bytes": trailing_bytes,
367 "distinct_archetypes": len({entity["archetype"] for entity in entities}),
368 "distinct_links": len({entity["link"] for entity in entities}),
369 "states": [
370 {
371 "key": state["key"],
372 "records": state["records"],
373 "entities": state["entities"],
374 }
375 for _key, state in sorted(states.items())
376 ],
377 "entity_list": [
378 {
379 "archetype": entity["archetype"],
380 "link": entity["link"],
381 "hash": entity["hash"],
382 "extra": entity["extra"],
383 "pos": entity["pos"],
384 "rot": entity["rot"],
385 "offset": entity["offset"],
386 }
387 for entity in entities
388 ],
389 }
390
391
392def parse_file(path):
393 with open(path, "rb") as handle:
394 blob = handle.read()
395 return parse_blob(blob, os.path.basename(path))
396
397
398def files_in(src):
399 """(path, name) pairs, sorted by name for a directory; one pair for a file."""
400 if os.path.isfile(src):
401 yield src, os.path.basename(src)
402 return
403 for name in sorted(os.listdir(src)):
404 if not name.endswith(".bin"):
405 continue
406 path = os.path.join(src, name)
407 if os.path.isfile(path):
408 yield path, name
409
410
411def collect(src, limit=None):
412 files = []
413 for path, name in files_in(src):
414 record = parse_file(path)
415 record["file"] = name
416 files.append(record)
417 if limit and len(files) >= limit:
418 break
419 return files
420
421
422def summarize(files):
423 """Totals over files; the distinct hash counts are over the union, not a sum of per-file counts."""
424 archetypes = set()
425 links = set()
426 states = set()
427 for record in files:
428 states.update(state["key"] for state in record["states"])
429 archetypes.update(entity["archetype"] for entity in record["entity_list"])
430 links.update(entity["link"] for entity in record["entity_list"])
431 return {
432 "files": len(files),
433 "records": sum(record["records"] for record in files),
434 "chunks": sum(record["chunks"] for record in files),
435 "state_keys": len(states),
436 "entities": sum(record["entities"] for record in files),
437 "entity_slots": sum(record["entity_slots"] for record in files),
438 "distinct_archetypes": len(archetypes),
439 "distinct_links": len(links),
440 "unresolved_records": sum(record["unresolved_records"] for record in files),
441 "skipped_slots": sum(record["skipped_slots"] for record in files),
442 "skipped_bytes": sum(record["skipped_bytes"] for record in files),
443 }
444
445
446def _hex(value):
447 return f"{value:08x}"
448
449
450def _json_record(record):
451 """The same record with hashes formatted as eight hex digits."""
452 out = dict(record)
453 out["states"] = [dict(state, key=_hex(state["key"])) for state in record["states"]]
454 out["entity_list"] = [
455 {
456 "archetype": _hex(entity["archetype"]),
457 "link": _hex(entity["link"]),
458 "hash": _hex(entity["hash"]),
459 "extra": _hex(entity["extra"]),
460 "pos": [round(value, 6) for value in entity["pos"]],
461 "rot": [round(value, 6) for value in entity["rot"]],
462 "offset": entity["offset"],
463 }
464 for entity in record["entity_list"]
465 ]
466 return out
467
468
469def count(text):
470 """--limit: a positive file count."""
471 try:
472 value = int(text)
473 except ValueError:
474 raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
475 if value < 1:
476 raise argparse.ArgumentTypeError("must be at least 1")
477 return value
478
479
480def main(argv=None):
481 ap = argparse.ArgumentParser(description="Read mission-state tables from inflated PSIN streams.")
482 ap.add_argument("src", help="PSIN file or directory of carved .bin streams")
483 ap.add_argument("--json", action="store_true", help="write the files and summary as JSON")
484 ap.add_argument("--limit", type=count, help="stop after this many files")
485 args = ap.parse_args(argv)
486 if not os.path.exists(args.src):
487 print(f"ERROR: {args.src}: no such file or folder", file=sys.stderr)
488 return 2
489 try:
490 files = collect(args.src, args.limit)
491 except OSError as error:
492 print(f"ERROR: {args.src}: {error}", file=sys.stderr)
493 return 2
494 summary = summarize(files)
495 if args.json:
496 json.dump({"files": [_json_record(record) for record in files], "summary": summary},
497 sys.stdout, indent=1)
498 sys.stdout.write("\n")
499 return 0
500 for record in files:
501 print(f"{record['file']} size={record['size']} records={record['records']} "
502 f"chunks={record['chunks']} states={record['state_keys']} "
503 f"entities={record['entities']} archetypes={record['distinct_archetypes']} "
504 f"links={record['distinct_links']} unresolved={record['unresolved_records']} "
505 f"skipped_slots={record['skipped_slots']} skipped_bytes={record['skipped_bytes']}")
506 for entity in record["entity_list"]:
507 pos = ", ".join(f"{value:.3f}" for value in entity["pos"])
508 rot = ", ".join(f"{value:.3f}" for value in entity["rot"])
509 print(f" entity {_hex(entity['archetype'])} {_hex(entity['link'])} "
510 f"pos=({pos}) rot=({rot}) +0x{entity['offset']:x}")
511 print(f"{summary['files']} files, {summary['records']} records in {summary['chunks']} chunks; "
512 f"{summary['state_keys']} distinct state keys; {summary['entities']} entities "
513 f"({summary['entity_slots']} slots), {summary['distinct_archetypes']} archetypes, "
514 f"{summary['distinct_links']} links; unresolved {summary['unresolved_records']}, "
515 f"skipped slots {summary['skipped_slots']}, skipped bytes {summary['skipped_bytes']}")
516 return 0
517
518
519if __name__ == "__main__":
520 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
521 sys.stdout.reconfigure(errors="replace")
522 except (AttributeError, ValueError, OSError):
523 pass
524 sys.exit(main())
diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py
index 7571c2ae9..3b01bc381 100644
--- a/tools/navmesh_decode.py
+++ b/tools/navmesh_decode.py
@@ -1011,7 +1011,7 @@ def main(argv=None):
1011 print("error: %s" % exc, file=sys.stderr) 1011 print("error: %s" % exc, file=sys.stderr)
1012 return 2 1012 return 2
1013 _make_parent(out) 1013 _make_parent(out)
1014 with open(out, "w", encoding="utf-8") as f: 1014 with open(out, "w", encoding="utf-8", newline="\n") as f:
1015 json.dump(summary, f, indent=1, allow_nan=False) 1015 json.dump(summary, f, indent=1, allow_nan=False)
1016 if a.csv: 1016 if a.csv:
1017 write_csv(a.csv, rows) 1017 write_csv(a.csv, rows)
diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py
index 0fa6c7f83..7ad5e0a2d 100644
--- a/tools/navmesh_index.py
+++ b/tools/navmesh_index.py
@@ -198,7 +198,7 @@ def _make_parent(path):
198 198
199def write_outputs(rows, summary, out_path, csv_path): 199def write_outputs(rows, summary, out_path, csv_path):
200 _make_parent(out_path) 200 _make_parent(out_path)
201 with open(out_path, "w", encoding="utf-8") as f: 201 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
202 json.dump({"summary": summary, "pages": rows}, f, indent=1) 202 json.dump({"summary": summary, "pages": rows}, f, indent=1)
203 written = [] 203 written = []
204 if csv_path: 204 if csv_path:
diff --git a/tools/opus_tags.py b/tools/opus_tags.py
index a1395e6ef..4b29c9328 100644
--- a/tools/opus_tags.py
+++ b/tools/opus_tags.py
@@ -4,8 +4,9 @@ awc_opus.py writes <out>/<bank>/<stream id>.ogg with an empty OpusTags header. T
4from two local work products: 4from two local work products:
5 5
6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file 6``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file
7 name) and its bank (the folder path below the Opus folder; if that has no match, the path with its 7 name; awc_opus.py's ``<id>~2.ogg`` for a second stream with the same id gets the same name) and its
8 leading folders removed one at a time, so the Opus folder may hold several archives' outputs). 8 bank (the folder path below the Opus folder; if that has no match, the path with its leading folders
9 removed one at a time, so the Opus folder may hold several archives' outputs).
9``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is 10``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_<lang> ...). A named stream whose name is
10 a dialogue wave gets that line's label, speaker and subtitles. 11 a dialogue wave gets that line's label, speaker and subtitles.
11 12
@@ -40,7 +41,7 @@ from awc_opus import ogg_page, write_file # noqa: E402
40VENDOR = b"leonida " 41VENDOR = b"leonida "
41MARKUP = re.compile(r"~[^~]*~") 42MARKUP = re.compile(r"~[^~]*~")
42SPACES = re.compile(r"\s+") 43SPACES = re.compile(r"\s+")
43STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})\.ogg$") 44STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})(?:~\d+)?\.ogg$") # <id>~2 ...: a later stream with the same id
44MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one 45MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one
45 46
46 47
diff --git a/tools/page_index.py b/tools/page_index.py
index 41d9f3783..059f4d91f 100644
--- a/tools/page_index.py
+++ b/tools/page_index.py
@@ -316,7 +316,7 @@ def summarise(pages, mode, source):
316 316
317 317
318def write_json(path, pages, summary): 318def write_json(path, pages, summary):
319 with open(path, "w", encoding="utf-8") as f: 319 with open(path, "w", encoding="utf-8", newline="\n") as f:
320 json.dump({"summary": summary, "pages": pages}, f, indent=1) 320 json.dump({"summary": summary, "pages": pages}, f, indent=1)
321 321
322 322
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index 148318c15..aabb42765 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -78,7 +78,9 @@ class PeImage:
78 magic = struct.unpack_from("<H", data, opt)[0] 78 magic = struct.unpack_from("<H", data, opt)[0]
79 if magic not in (0x10B, 0x20B): 79 if magic not in (0x10B, 0x20B):
80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}") 80 raise PeFormatError(f"unknown optional header magic 0x{magic:x}")
81 if opt + 72 > len(data): # the fixed fields read below end with DllCharacteristics at +70 81 # The declared optional header must contain every fixed field we read,
82 # and the complete declared header must fit inside the file.
83 if opt_size < 72 or opt + opt_size > len(data):
82 raise PeFormatError("truncated optional header") 84 raise PeFormatError("truncated optional header")
83 self.is64 = magic == 0x20B 85 self.is64 = magic == 0x20B
84 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0] 86 self.entry_rva = struct.unpack_from("<I", data, opt + 16)[0]
@@ -458,9 +460,9 @@ def main(argv: list[str] | None = None) -> int:
458 rc = 1 460 rc = 1
459 continue 461 continue
460 try: 462 try:
461 with open(json_path, "w", encoding="utf-8") as f: 463 with open(json_path, "w", encoding="utf-8", newline="\n") as f:
462 json.dump(r, f, indent=1) 464 json.dump(r, f, indent=1)
463 with open(md_path, "w", encoding="utf-8") as f: 465 with open(md_path, "w", encoding="utf-8", newline="\n") as f:
464 f.write(to_markdown(r)) 466 f.write(to_markdown(r))
465 except OSError as e: 467 except OSError as e:
466 print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr) 468 print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr)
diff --git a/tools/pe_shader_containers.py b/tools/pe_shader_containers.py
new file mode 100644
index 000000000..5b4d39565
--- /dev/null
+++ b/tools/pe_shader_containers.py
@@ -0,0 +1,272 @@
1"""Inventory the DXBC shader containers embedded in a PE image, outside `shaders.rpf`.
2
3The package ships shader programs in two places: the game's own containers inside `shaders.rpf`, which
4`tools/shader_carve.py` recovers, and containers embedded in DLLs. This tool scans any binary for the latter,
5validates each container's chunk table, reads the `ILDN` module name, and reports what each container carries:
6
7* `has_xbch`: the `DXIL` chunk's `XDAT` tag 0x0d starts with `XBCH`. This is the console program:
8 `tools/fssm_unpack.py` decompresses it to `FSSM` and the game's RDNA2 pipeline (disasm + `rdna2spirv.py`)
9 translates it, exactly like a shader from `shaders.rpf`. `docs/embedded_shaders.md` has the measurement.
10* `has_fspx`: the `ACCC` chunk starts with `FSPX`. That is the FidelityFX AOT compute program, a different
11 format (`tools/fspx_unpack.py`, `docs/fspx.md`).
12* `has_bitcode`: the `DXIL` chunk contains an LLVM bitcode magic (`BC C0 DE`). Some containers carry both the
13 bitcode and the console `XBCH` record; the console runtime uses the latter.
14
15Usage:
16 python -I pe_shader_containers.py <image> [<image> ...] [--json FILE] [--extract DIR] [--verbose]
17
18`--json` writes the per-container records (offset, size, sha256, chunk list, name, flags). `--extract` writes
19each container as `<module>.dxbc` plus an `index.json` whose entries the translator reads (`stage: "cs"`), so the
20next step can be `fssm_unpack.py <DIR>`: nothing is extracted unless asked for, and extracted shaders are game
21data that must stay in the user's work folder, never in the repository. Nothing here prints shader bytes.
22
23Standard library only; reads files, never runs them.
24"""
25
26from __future__ import annotations
27
28import argparse
29import hashlib
30import json
31import os
32import re
33import struct
34import sys
35
36DXBC = b"DXBC"
37XDAT = b"XDAT"
38XBCH = b"XBCH"
39FSPX = b"FSPX"
40BITCODE = b"BC\xc0\xde"
41MAX_CHUNKS = 64 # a container with more chunks is not one this parser accepts
42NAME_LIMIT = 4096 # longer than any ILDN path seen; stops a malformed length from reading the image
43SAFE_NAME = re.compile(r"[^A-Za-z0-9_.-]+")
44
45
46class ContainerError(ValueError):
47 """The bytes at this offset do not form a DXBC container this parser accepts."""
48
49
50def u32(data: bytes, offset: int) -> int:
51 return struct.unpack_from("<I", data, offset)[0]
52
53
54def parse_container(data: bytes, offset: int):
55 """Return (total_size, chunks) for the container at `offset`, or raise ContainerError.
56
57 The package's containers differ from DXC's in one place only: the chunk table is a u32 offset array at
58 +32 (count at +28), and each chunk starts with its fourcc and a u32 size. `tools/fspx_unpack.parts()`
59 reads the same shape. The checks below reject the four-byte `DXBC` immediates and error strings that
60 occur in ordinary code.
61 """
62 if data[offset : offset + 4] != DXBC:
63 raise ContainerError("no DXBC magic")
64 if offset + 32 > len(data):
65 raise ContainerError("truncated header")
66 total, count = u32(data, offset + 24), u32(data, offset + 28)
67 if not 32 < total <= len(data) - offset:
68 raise ContainerError(f"total size {total} does not fit the image")
69 if not 0 < count <= MAX_CHUNKS:
70 raise ContainerError(f"implausible chunk count {count}")
71 table_end = 32 + 4 * count
72 if table_end > total:
73 raise ContainerError("chunk table past the container")
74 chunks = []
75 for k in range(count):
76 start = u32(data, offset + 32 + 4 * k)
77 if not table_end <= start <= total - 8:
78 raise ContainerError(f"chunk {k} offset {start} outside the container")
79 fourcc = data[offset + start : offset + start + 4]
80 size = u32(data, offset + start + 4)
81 if start + 8 + size > total:
82 raise ContainerError(f"chunk {k} payload past the container")
83 if start % 4:
84 raise ContainerError(f"chunk {k} offset {start} not 4-byte aligned")
85 if not all(0x20 <= b < 0x7F for b in fourcc):
86 raise ContainerError(f"chunk {k} fourcc is not printable")
87 chunks.append((fourcc, start, size))
88 starts = [start for _, start, _ in chunks]
89 if starts != sorted(starts) or len(set(starts)) != len(starts):
90 raise ContainerError("chunk table is not sorted and unique")
91 if not chunks or max(start + 8 + size for _, start, size in chunks) != total:
92 raise ContainerError("the last chunk does not end at the container size")
93 return total, chunks
94
95
96def chunk_payload(data: bytes, offset: int, chunk) -> bytes:
97 _, start, size = chunk
98 return data[offset + start + 8 : offset + start + 8 + size]
99
100
101def module_name(ildn: bytes) -> str | None:
102 """The module name in an `ILDN` part: `00 00 <u16 length> <PDB path>`; basename without `.pdb`."""
103 if len(ildn) < 4:
104 return None
105 length = struct.unpack_from("<H", ildn, 2)[0]
106 path = ildn[4 : 4 + min(length, NAME_LIMIT)].split(b"\0", 1)[0]
107 base = path.replace(b"\\", b"/").rsplit(b"/", 1)[-1].decode("latin-1")
108 return base[:-4] if base.lower().endswith(".pdb") else base or None
109
110
111def xdat_tags(dxil: bytes) -> list[dict]:
112 """The XDAT entries of a `DXIL` part, as {tag, size, magic} with the first four payload bytes as ASCII."""
113 start = dxil.find(XDAT)
114 if start < 0 or start + 12 > len(dxil):
115 return []
116 count, _header = struct.unpack_from("<II", dxil, start + 4)
117 if count > 256:
118 return []
119 out = []
120 for k in range(count):
121 at = start + 12 + 12 * k
122 if at + 12 > len(dxil):
123 break
124 tag, offset, size = struct.unpack_from("<III", dxil, at)
125 if offset + size > len(dxil):
126 continue
127 magic = dxil[offset : offset + 4]
128 out.append(
129 {
130 "tag": tag,
131 "size": size,
132 "magic": magic.decode("latin-1")
133 if all(0x20 <= b < 0x7F for b in magic)
134 else "",
135 }
136 )
137 return out
138
139
140def inspect(data: bytes, image: str) -> tuple[list[dict], list[int]]:
141 """Every valid container in `data`, and the offsets of `DXBC` hits that failed validation."""
142 found, rejected = [], []
143 i = 0
144 while True:
145 i = data.find(DXBC, i)
146 if i < 0:
147 break
148 try:
149 total, chunks = parse_container(data, i)
150 except ContainerError:
151 rejected.append(i)
152 i += 4
153 continue
154 parts = {fourcc: (start, size) for fourcc, start, size in chunks}
155 dialect = b""
156 if b"DXIL" in parts:
157 dialect = chunk_payload(data, i, (b"DXIL",) + parts[b"DXIL"])
158 elif b"ACCC" in parts:
159 dialect = chunk_payload(data, i, (b"ACCC",) + parts[b"ACCC"])
160 tags = xdat_tags(dialect) if b"DXIL" in parts else []
161 record = {
162 "image": image,
163 "offset": i,
164 "size": total,
165 "sha256": hashlib.sha256(data[i : i + total]).hexdigest(),
166 "name": module_name(chunk_payload(data, i, (b"ILDN",) + parts[b"ILDN"]))
167 if b"ILDN" in parts
168 else None,
169 "chunks": [
170 {"fourcc": fourcc.decode("latin-1"), "size": size}
171 for fourcc, _, size in chunks
172 ],
173 "xdat_tags": tags,
174 "has_xbch": any(t["tag"] == 0x0D and t["magic"] == "XBCH" for t in tags),
175 "has_fspx": (b"ACCC" in parts and dialect[:4] == FSPX),
176 "has_bitcode": BITCODE in dialect,
177 }
178 found.append(record)
179 i += total
180 return found, rejected
181
182
183def safe_stem(name: str | None, index: int) -> str:
184 stem = SAFE_NAME.sub("_", name or "").strip("._")
185 return stem or f"container_{index:02d}"
186
187
188def extract(data: bytes, records: list[dict], directory: str) -> list[dict]:
189 """Write each container as `<module>.dxbc`; return the translator's index entries."""
190 os.makedirs(directory, exist_ok=True)
191 index = []
192 for k, record in enumerate(records):
193 stem = safe_stem(record["name"], k)
194 file = f"{stem}.dxbc"
195 target = os.path.join(directory, file)
196 if os.path.exists(target):
197 file = f"{stem}_{k:02d}.dxbc"
198 target = os.path.join(directory, file)
199 with open(target, "wb") as f:
200 f.write(data[record["offset"] : record["offset"] + record["size"]])
201 index.append({"name": stem, "file": file, "stage": "cs"})
202 return index
203
204
205def main(argv=None) -> int:
206 ap = argparse.ArgumentParser(
207 description="Inventory the DXBC shader containers embedded in PE images."
208 )
209 ap.add_argument("images", nargs="+", help="PE image(s) to scan")
210 ap.add_argument("--json", help="write the per-container records here")
211 ap.add_argument(
212 "--extract",
213 metavar="DIR",
214 help="write each container as <module>.dxbc plus index.json (game data: keep it out of the repo)",
215 )
216 ap.add_argument(
217 "--verbose", action="store_true", help="print one line per container"
218 )
219 a = ap.parse_args(argv)
220
221 all_records, status, index = [], 0, []
222 for image in a.images:
223 try:
224 with open(image, "rb") as f:
225 data = f.read()
226 except OSError as e:
227 print(f"ERROR: cannot read {image}: {e.strerror or e}", file=sys.stderr)
228 status = 2
229 continue
230 records, rejected = inspect(data, image)
231 all_records.extend(records)
232 print(
233 f"{image}: {len(records)} container(s), {len(rejected)} rejected DXBC hit(s)"
234 )
235 if a.verbose:
236 for r in records:
237 name = r["name"] or "?"
238 flags = "".join(
239 c
240 for c, on in (
241 ("X", r["has_xbch"]),
242 ("F", r["has_fspx"]),
243 ("B", r["has_bitcode"]),
244 )
245 if on
246 )
247 chunks = ",".join(c["fourcc"] for c in r["chunks"])
248 print(
249 f" {r['offset']:#x} {r['size']:>7} {flags:<3} {name:<28} {chunks}"
250 )
251 if a.extract:
252 index.extend(extract(data, records, a.extract))
253
254 if a.extract:
255 with open(os.path.join(a.extract, "index.json"), "w", encoding="utf-8", newline="\n") as f:
256 json.dump(index, f, indent=0)
257 print(f" extracted {len(index)} file(s) to {a.extract}")
258 print(" these are game data: do not commit them", file=sys.stderr)
259
260 if a.json:
261 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
262 json.dump(all_records, f, indent=1)
263 print(f"wrote {a.json}")
264 return status
265
266
267if __name__ == "__main__":
268 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
269 sys.stdout.reconfigure(errors="replace")
270 except (AttributeError, ValueError, OSError):
271 pass
272 sys.exit(main())
diff --git a/tools/psin_names.py b/tools/psin_names.py
index 0c9b7281e..c57b590c5 100644
--- a/tools/psin_names.py
+++ b/tools/psin_names.py
@@ -188,14 +188,17 @@ def main():
188 ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)") 188 ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)")
189 ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files") 189 ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files")
190 a = ap.parse_args() 190 a = ap.parse_args()
191 for path in [a.src] + a.names: 191 inputs = [a.src, *a.names]
192 for path in inputs:
192 if not os.path.exists(path): 193 if not os.path.exists(path):
193 print(f"ERROR: {path}: no such file or folder", file=sys.stderr) 194 print(f"ERROR: {path}: no such file or folder", file=sys.stderr)
194 return 2 195 return 2
195 try: 196 try:
197 if a.refs and os.path.exists(a.refs) and any(os.path.samefile(path, a.refs) for path in inputs):
198 ap.error("--refs must not overwrite an input")
196 names = load_names(a.names) 199 names = load_names(a.names)
197 if a.refs: 200 if a.refs:
198 with open(a.refs, "w", encoding="utf-8") as refs: 201 with open(a.refs, "w", encoding="utf-8", newline="\n") as refs:
199 refs.write("file\tstruct\tfield\ttype\tvalue\tname\n") 202 refs.write("file\tstruct\tfield\ttype\tvalue\tname\n")
200 summary, table = scan(a.src, names, a.limit, refs) 203 summary, table = scan(a.src, names, a.limit, refs)
201 else: 204 else:
diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py
index c13122afa..cb41da559 100644
--- a/tools/rbf0_index.py
+++ b/tools/rbf0_index.py
@@ -464,7 +464,7 @@ def write_output(path, records, summary, all_strings=False):
464 doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"] 464 doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"]
465 doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"]) 465 doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"])
466 docs.append(doc) 466 docs.append(doc)
467 with open(path, "w", encoding="utf-8") as f: 467 with open(path, "w", encoding="utf-8", newline="\n") as f:
468 json.dump({"summary": summary, "files": docs}, f, indent=1) 468 json.dump({"summary": summary, "files": docs}, f, indent=1)
469 return 469 return
470 with open(path, "w", encoding="utf-8", newline="") as f: 470 with open(path, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 8addea7b7..9961152f0 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -70,11 +70,14 @@ MESH_COMPUTE = False
70# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high 70# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high
71# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The 71# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The
72# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the 72# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the
73# device's interpolator instead of by explicit arithmetic. The halves sit below location F16_HALF_TOP (30: 31 73# device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's
74# locations is MoltenVK's limit, 124 components), counting down from param 0, so a producer with params 0..P-1 has 74# high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params
75# room for the halves of params 0..(29 - P) / 2; Gen.export skips the ones that would land on its own params. 75# 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291):
76# MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and
77# the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS
78# can use there.
76F16_HALVES = False 79F16_HALVES = False
77F16_HALF_TOP = 30 80F16_HALF_TOP = 29
78 81
79 82
80def f16_half_location(n, half): 83def f16_half_location(n, half):
@@ -436,7 +439,10 @@ class Gen:
436 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") 439 selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]")
437 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 440 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
438 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] 441 hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")]
439 return [self.f16_in(src, sb[i]) if hb[i] else self.src_f(src) for i, src in enumerate(a[1:4])] 442 # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals
443 # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and
444 # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values.
445 return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])]
440 446
441 def f16_bits(self, f, rtz=False): 447 def f16_bits(self, f, rtz=False):
442 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). 448 """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56).
@@ -1279,11 +1285,18 @@ class Gen:
1279 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)), 1285 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)),
1280 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)), 1286 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)),
1281 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)), 1287 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)),
1282 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8))} 1288 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8)),
1289 # Narrow integer formats, measured natively on gfx1036 (wave32 and wave64): UINT loads zero-extend
1290 # and stores saturate to the channel; SINT loads sign-extend and stores clamp the 32-bit signed value
1291 # to [-2^(w-1), 2^(w-1) - 1].
1292 5: (1, "uint", (8,)), 11: (2, "uint", (16,)), 18: (2, "uint", (8, 8)),
1293 6: (1, "sint", (8,)), 12: (2, "sint", (16,)), 19: (2, "sint", (8, 8)), 28: (4, "sint", (16, 16)),
1294 61: (4, "sint", (8, 8, 8, 8)), 70: (8, "sint", (16, 16, 16, 16))}
1283 1295
1284 def encode_format(self, fcomps, icomps, code): 1296 def encode_format(self, fcomps, icomps, code):
1285 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one 1297 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one
1286 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns (u32/i32/uint).""" 1298 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns
1299 (u32/i32/uint/sint)."""
1287 try: 1300 try:
1288 size, kind, widths = self.FORMATS[code] 1301 size, kind, widths = self.FORMATS[code]
1289 except KeyError: 1302 except KeyError:
@@ -1312,6 +1325,11 @@ class Gen:
1312 self.emit(f"{i} = OpConvertFToS %int {rd}") 1325 self.emit(f"{i} = OpConvertFToS %int {rd}")
1313 self.emit(f"{u} = OpBitcast %uint {i}") 1326 self.emit(f"{u} = OpBitcast %uint {i}")
1314 field = u 1327 field = u
1328 elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range.
1329 clamped, field = self.tmp(), self.tmp()
1330 lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1))
1331 self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {self.as_int(icomps[c])} {lo} {hi}")
1332 self.emit(f"{field} = OpBitcast %uint {clamped}")
1315 else: # Narrow UINT stores saturate to the field width before insertion. 1333 else: # Narrow UINT stores saturate to the field width before insertion.
1316 field = self.tmp() 1334 field = self.tmp()
1317 self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}") 1335 self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}")
@@ -1420,6 +1438,11 @@ class Gen:
1420 self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}") 1438 self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}")
1421 self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}") 1439 self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}")
1422 out.append(res) 1440 out.append(res)
1441 elif kind == "sint":
1442 si, su = self.tmp(), self.tmp()
1443 self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}")
1444 self.emit(f"{su} = OpBitcast %uint {si}")
1445 out.append(su)
1423 else: # uint: raw integer 1446 else: # uint: raw integer
1424 out.append(f) 1447 out.append(f)
1425 bit += w 1448 bit += w
@@ -1771,12 +1794,12 @@ class Gen:
1771 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W. 1794 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
1772 is_int_fmt, is_signed = "%false", "%false" 1795 is_int_fmt, is_signed = "%false", "%false"
1773 for code_v, (_, kind, _) in self.FORMATS.items(): 1796 for code_v, (_, kind, _) in self.FORMATS.items():
1774 if kind in ("u32", "i32", "uint"): 1797 if kind in ("u32", "i32", "uint", "sint"):
1775 e, o = self.tmp(), self.tmp() 1798 e, o = self.tmp(), self.tmp()
1776 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 1799 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1777 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}") 1800 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
1778 is_int_fmt = o 1801 is_int_fmt = o
1779 if d16 and kind == "i32": 1802 if d16 and kind in ("i32", "sint"):
1780 signed = self.tmp() 1803 signed = self.tmp()
1781 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}") 1804 self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}")
1782 is_signed = signed 1805 is_signed = signed
@@ -1807,6 +1830,13 @@ class Gen:
1807 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}") 1830 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}")
1808 return half 1831 return half
1809 1832
1833 is_norm = "%false"
1834 for code_v, (_, kind, _) in self.FORMATS.items():
1835 if kind in ("unorm", "snorm") and (fixed_fmt is None or code_v == fixed_fmt):
1836 e, o = self.tmp(), self.tmp()
1837 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1838 self.emit(f"{o} = OpLogicalOr %bool {is_norm} {e}")
1839 is_norm = o
1810 for i in range(0, len(outs), 2): 1840 for i in range(0, len(outs), 2):
1811 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} 1841 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
1812 lo = outs[i] 1842 lo = outs[i]
@@ -1814,12 +1844,15 @@ class Gen:
1814 r = self.tmp() 1844 r = self.tmp()
1815 if i + 1 == len(outs): 1845 if i + 1 == len(outs):
1816 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. 1846 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits.
1817 fl = self.f16_bits(self.tof(lo)) 1847 fl = self.d16_norm_f16(lo, is_norm)
1818 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}") 1848 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
1819 self.write_lo16(dest, r) 1849 self.write_lo16(dest, r)
1820 continue 1850 continue
1821 hi = outs[i + 1] 1851 hi = outs[i + 1]
1822 ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) 1852 ph = self.tmp()
1853 fh_s = self.tmp()
1854 self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm)} {self.cu(16)}")
1855 self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm)} {fh_s}")
1823 ih, pi = self.tmp(), self.tmp() 1856 ih, pi = self.tmp(), self.tmp()
1824 high_half = int_half(hi) 1857 high_half = int_half(hi)
1825 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") 1858 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}")
@@ -1827,6 +1860,30 @@ class Gen:
1827 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}") 1860 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}")
1828 self.dst(dest, r) 1861 self.dst(dest, r)
1829 1862
1863 # The f32 quotients m / (2^n - 1), 1 <= n <= 16, that land exactly on an f16 halfway point: 0x3f7ff000 is
1864 # 16379/16383, 32759/32767 and 65519/65535, 0x3f7fb000 is 65455/65535 (an enumeration of every m and n). The exact
1865 # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700).
1866 D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000)
1867
1868 def d16_norm_f16(self, bits, is_norm):
1869 """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even
1870 (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the
1871 f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp
1872 high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit
1873 twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and
1874 MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A float format keeps the plain rounding: a 32_FLOAT
1875 0x3f7ff000 is a real tie."""
1876 h = self.f16_bits(self.tof(bits))
1877 mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7))
1878 self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
1879 self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}")
1880 self.emit(f"{b} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[1])}")
1881 self.emit(f"{hit} = OpLogicalOr %bool {a} {b}")
1882 self.emit(f"{both} = OpLogicalAnd %bool {hit} {is_norm}")
1883 self.emit(f"{dn} = OpISub %uint {h} {self.cu(1)}") # sign-magnitude: 1 ulp toward zero
1884 self.emit(f"{out} = OpSelect %uint {both} {dn} {h}")
1885 return out
1886
1830 def global_address(self, op, vaddr, saddr, mods): 1887 def global_address(self, op, vaddr, saddr, mods):
1831 """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended 1888 """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended
1832 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset.""" 1889 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset."""
@@ -2286,9 +2343,21 @@ class Gen:
2286 return addr, d3, in_b, (check if mode in (None, 0, 3) else None), step 2343 return addr, d3, in_b, (check if mode in (None, 0, 3) else None), step
2287 return addr, d3, in_b, step 2344 return addr, d3, in_b, step
2288 2345
2289 def buffer_store(self, op, a, mods): 2346 def mtbuf_format(self, op, mods):
2290 """buffer_store_dword[xN] (raw) and buffer_store_format_* (f32 formats stored raw, f16x2/x4, unorm8x4). 2347 """The format code an MTBUF instruction (tbuffer_load/store_format_*) encodes for itself, which replaces the
2291 Only active lanes store, inside a structured if.""" 2348 V#'s. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM (code 1)."""
2349 fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]")
2350 name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]")
2351 code = next((c for c, n in GFX10_FORMATS.items() if n == name), None)
2352 if code is None or code not in self.FORMATS:
2353 raise Unsupported(op + " " + name)
2354 self.fixed_format_codes.add(code)
2355 return code
2356
2357 def buffer_store(self, op, a, mods, fixed_fmt=None):
2358 """buffer_store_dword[xN] (raw) and buffer_store_format_* (every format in FORMATS, read from the V# at run
2359 time). tbuffer_store_format_* comes here with its own format in fixed_fmt: only that one is encoded, and the
2360 bounds check uses its element size, whatever the V# says. Only active lanes store, inside a structured if."""
2292 if any(m in mods for m in ("lds", "tfe", "d16")): 2361 if any(m in mods for m in ("lds", "tfe", "d16")):
2293 raise Unsupported(op + " form") 2362 raise Unsupported(op + " form")
2294 d16 = "_d16_" in op 2363 d16 = "_d16_" in op
@@ -2297,7 +2366,7 @@ class Gen:
2297 if dword_store: 2366 if dword_store:
2298 addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True) 2367 addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True)
2299 else: 2368 else:
2300 addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt") 2369 addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt)
2301 per = None 2370 per = None
2302 if dword_store: 2371 if dword_store:
2303 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) 2372 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1])
@@ -2322,8 +2391,11 @@ class Gen:
2322 else: 2391 else:
2323 comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] 2392 comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)]
2324 icomps = comps 2393 icomps = comps
2325 fmt = self.tmp() 2394 if fixed_fmt is not None:
2326 self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") 2395 fmt = None # tbuffer: the instruction's format, so no V# FORMAT to branch on
2396 else:
2397 fmt = self.tmp()
2398 self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}")
2327 # Encodings for the formats that appear in store-heavy shaders; others store nothing. 2399 # Encodings for the formats that appear in store-heavy shaders; others store nothing.
2328 f32 = {22: 1, 64: 2, 74: 3, 77: 4} 2400 f32 = {22: 1, 64: 2, 74: 3, 77: 4}
2329 # Float views of the components, computed before any branch so every branch can use them. 2401 # Float views of the components, computed before any branch so every branch can use them.
@@ -2346,6 +2418,14 @@ class Gen:
2346 self.emit(f"OpBranch {lbl_end}") 2418 self.emit(f"OpBranch {lbl_end}")
2347 self.emit(f"{lbl_end} = OpLabel") 2419 self.emit(f"{lbl_end} = OpLabel")
2348 return 2420 return
2421 if fixed_fmt is not None:
2422 # A V# whose FORMAT is 0 (INVALID) disables the store, though MTBUF brings its own format (measured natively
2423 # on gfx1035, wave32 and wave64, in OOB_SELECT 0, 1 and 3).
2424 vf, valid, ok = self.tmp(), self.tmp(), self.tmp()
2425 self.emit(f"{vf} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}")
2426 self.emit(f"{valid} = OpINotEqual %bool {vf} {self.cu(0)}")
2427 self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {valid}")
2428 in_b = ok
2349 act = self.tmp() 2429 act = self.tmp()
2350 self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}") 2430 self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}")
2351 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" 2431 lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
@@ -2387,19 +2467,21 @@ class Gen:
2387 extended = self.tmp() 2467 extended = self.tmp()
2388 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}") 2468 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
2389 signed_ic.append(self.tou(extended)) 2469 signed_ic.append(self.tou(extended))
2390 for code, (size, kind, widths) in self.FORMATS.items(): 2470 formats = self.FORMATS.items() if fmt is not None else [(fixed_fmt, self.FORMATS[fixed_fmt])]
2391 e = self.tmp() 2471 for code, (size, kind, widths) in formats:
2392 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") 2472 if fmt is not None:
2393 ld, le = self.tmp() + "_s", self.tmp() + "_se" 2473 e = self.tmp()
2394 self.emit(f"OpSelectionMerge {le} None") 2474 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
2395 self.emit(f"OpBranchConditional {e} {ld} {le}") 2475 ld, le = self.tmp() + "_s", self.tmp() + "_se"
2396 self.emit(f"{ld} = OpLabel") 2476 self.emit(f"OpSelectionMerge {le} None")
2477 self.emit(f"OpBranchConditional {e} {ld} {le}")
2478 self.emit(f"{ld} = OpLabel")
2397 ncomp = min(len(widths), n) 2479 ncomp = min(len(widths), n)
2398 source = normalized if kind in ("unorm", "snorm") else fc 2480 source = normalized if kind in ("unorm", "snorm") else fc
2399 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2481 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2400 if code in (50, 56): 2482 if code in (50, 56):
2401 fcs = unorm_view 2483 fcs = unorm_view
2402 integer_source = signed_ic if kind == "i32" else ic 2484 integer_source = signed_ic if kind in ("i32", "sint") else ic
2403 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2485 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2404 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) 2486 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code)
2405 if size >= 4: 2487 if size >= 4:
@@ -2428,8 +2510,9 @@ class Gen:
2428 self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") 2510 self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}")
2429 self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") 2511 self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}")
2430 self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") 2512 self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}")
2431 self.emit(f"OpBranch {le}") 2513 if fmt is not None:
2432 self.emit(f"{le} = OpLabel") 2514 self.emit(f"OpBranch {le}")
2515 self.emit(f"{le} = OpLabel")
2433 self.emit(f"OpBranch {lbl_end}") 2516 self.emit(f"OpBranch {lbl_end}")
2434 self.emit(f"{lbl_end} = OpLabel") 2517 self.emit(f"{lbl_end} = OpLabel")
2435 2518
@@ -3059,6 +3142,28 @@ class Gen:
3059 self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") 3142 self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}")
3060 self.emit(f"OpStore %scc {z}") 3143 self.emit(f"OpStore %scc {z}")
3061 3144
3145 MASK_SOP2_B32 = ("s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32",
3146 "s_xnor_b32", "s_cselect_b32")
3147
3148 def sop2_b32_srcs(self, op, a):
3149 """The two sources of a 32-bit SOP2. In a wave32 program a bitwise op (or s_cselect) that writes EXEC / VCC
3150 reads both through mask_src, so a constant, inline or held in an SGPR, gives each lane its own bit; a mask is
3151 read as before. Until 2026-11-22
3152 a constant was used whole: `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every
3153 lane of EXEC on. Data ops, and wave64 programs (a b32 op there is on one half of a mask), are unchanged."""
3154 if op in self.MASK_SOP2_B32 and not self.wave64 and len(a) >= 3:
3155 d = a[0]
3156 to_mask = d["k"] == "special" and d.get("t", "") in ("exec_lo", "vcc_lo", "exec", "vcc")
3157 maskable = all(x["k"] in ("sgpr", "imm") or (x["k"] == "special" and
3158 x.get("t", "").startswith(("exec", "vcc"))) for x in a[1:3])
3159 # Only when the result is a mask (EXEC / VCC destination). An SGPR destination is classified by
3160 # lane_masks.py, which calls it data when the other operand is a constant; a per-lane bit stored there
3161 # would then be counted as data (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0
3162 # instead of 1, found by @Pierre-Kookis on #1792), so that case keeps the data read.
3163 if maskable and to_mask:
3164 return self.mask_src(a[1], wide=False), self.mask_src(a[2], wide=False)
3165 return self.src_u(a[1]), self.src_u(a[2])
3166
3062 def scc_logic(self, a, r): 3167 def scc_logic(self, a, r):
3063 """SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program 3168 """SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program
3064 an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC 3169 an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC
@@ -3343,7 +3448,26 @@ class Gen:
3343 or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no 3448 or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no
3344 lane, 5 every lane).""" 3449 lane, 5 every lane)."""
3345 if a["k"] == "sgpr": 3450 if a["k"] == "sgpr":
3346 return self.load_reg("sgpr", a["r"]) 3451 if self.holds_lane_mask(a):
3452 return self.load_reg("sgpr", a["r"])
3453 # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in
3454 # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used
3455 # and any non-zero constant enabled every lane. A mask the analysis missed is still exact: each
3456 # invocation holds 0 or ~0 there, and bit L of that is the same 0 or 1. A pair in a wave64 64-bit
3457 # context gives lanes 32..63 their bit from the high SGPR (a mask keeps the same 0 / ~0 in both).
3458 lane = self.wave_lane()
3459 word = self.load_reg("sgpr", a["r"])
3460 if a.get("n", 1) == 2 and wide and self.wave64:
3461 hi, up, sel = self.load_reg("sgpr", a["r"] + 1), self.tmp(), self.tmp()
3462 self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}")
3463 self.emit(f"{sel} = OpSelect %uint {up} {hi} {word}")
3464 word = sel
3465 sh, shr, bit, r = (self.tmp() for _ in range(4))
3466 self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}")
3467 self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}")
3468 self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}")
3469 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
3470 return r
3347 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): 3471 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
3348 v = self.tmp() 3472 v = self.tmp()
3349 self.emit(f"{v} = OpLoad %uint %vcc") 3473 self.emit(f"{v} = OpLoad %uint %vcc")
@@ -3895,13 +4019,16 @@ class Gen:
3895 if op in ("s_denorm_mode", "s_round_mode"): 4019 if op in ("s_denorm_mode", "s_round_mode"):
3896 raise Unsupported(op + " (not in the corpus; MODE is modelled through s_setreg only)") 4020 raise Unsupported(op + " (not in the corpus; MODE is modelled through s_setreg only)")
3897 if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \ 4021 if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \
3898 (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm")): 4022 (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm") or
4023 (a[1]["k"] == "sgpr" and not self.holds_lane_mask(a[1]))):
3899 src = a[1] 4024 src = a[1]
3900 const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None 4025 const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None
3901 if src["k"] == "fimm": 4026 if src["k"] == "fimm":
3902 const = struct.unpack("<I", struct.pack("<f", src["v"]))[0] 4027 const = struct.unpack("<I", struct.pack("<f", src["v"]))[0]
3903 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, None if const is not None else self.src_u(src), 4028 # an SGPR that isn't a mask (a constant, say) gives each lane its own bit, as a constant does (mask_src)
3904 const) 4029 val = None if const is not None else (self.mask_src(src, wide=False) if src["k"] == "sgpr"
4030 else self.src_u(src))
4031 self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, val, const)
3905 elif op == "v_mov_b32" or op == "s_mov_b32": 4032 elif op == "v_mov_b32" or op == "s_mov_b32":
3906 lit_val = None 4033 lit_val = None
3907 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok(): 4034 if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok():
@@ -4754,13 +4881,11 @@ class Gen:
4754 elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", 4881 elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz",
4755 "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", 4882 "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy",
4756 "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"): 4883 "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"):
4757 # MTBUF encodes its own format. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM. 4884 self.buffer_load_format(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods))
4758 fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]") 4885 elif op in ("tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz",
4759 name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") 4886 "tbuffer_store_format_xyzw", "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy",
4760 code = next((c for c, n in GFX10_FORMATS.items() if n == name), None) 4887 "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw"):
4761 if code is None or code not in self.FORMATS: 4888 self.buffer_store(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods))
4762 raise Unsupported(op + " " + name)
4763 self.buffer_load_format(op[1:], a, mods, fixed_fmt=code)
4764 elif op in ("s_bitset0_b64", "s_bitset1_b64"): 4889 elif op in ("s_bitset0_b64", "s_bitset1_b64"):
4765 # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair 4890 # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair
4766 # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported. 4891 # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported.
@@ -5746,10 +5871,16 @@ class Gen:
5746 self.emit(f"{r} = OpCompositeExtract %uint {s2} 0") 5871 self.emit(f"{r} = OpCompositeExtract %uint {s2} 0")
5747 self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") 5872 self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1")
5748 self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}") 5873 self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}")
5874 carry_nz = self.tmp_bool_nz(carry)
5875 if "clamp" in mods:
5876 # Hardware saturates D (0xffffffff on add carry, 0 on sub borrow) while reporting the real carry/borrow.
5877 clamped = self.tmp()
5878 self.emit(f"{clamped} = OpSelect %uint {carry_nz} {self.cu(0) if sub else self.cu(0xFFFFFFFF)} {r}")
5879 r = clamped
5749 self.dst(vd, r) 5880 self.dst(vd, r)
5750 if not (cd["k"] == "special" and cd["t"] == "null"): 5881 if not (cd["k"] == "special" and cd["t"] == "null"):
5751 cm, m = self.tmp(), self.tmp() 5882 cm, m = self.tmp(), self.tmp()
5752 self.emit(f"{cm} = OpLogicalAnd %bool {self.tmp_bool_nz(carry)} {self.active_b()}") # inactive lanes write 0 5883 self.emit(f"{cm} = OpLogicalAnd %bool {carry_nz} {self.active_b()}") # inactive lanes write 0
5753 self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") 5884 self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
5754 self.mask_dst(cd, m) 5885 self.mask_dst(cd, m)
5755 elif op == "v_mul_legacy_f32": 5886 elif op == "v_mul_legacy_f32":
@@ -5924,7 +6055,7 @@ class Gen:
5924 self.dst(a[0], r) 6055 self.dst(a[0], r)
5925 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") 6056 self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
5926 return 6057 return
5927 x, y = self.src_u(a[1]), self.src_u(a[2]) 6058 x, y = self.sop2_b32_srcs(op, a)
5928 r = self.tmp() 6059 r = self.tmp()
5929 if op == "s_cselect_b32": 6060 if op == "s_cselect_b32":
5930 c, b = self.tmp(), self.tmp() 6061 c, b = self.tmp(), self.tmp()
@@ -6445,16 +6576,7 @@ class Gen:
6445 self.scc_nonzero(r) 6576 self.scc_nonzero(r)
6446 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): 6577 elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"):
6447 vals = self.fma_mix_srcs(a, mods) 6578 vals = self.fma_mix_srcs(a, mods)
6448 r = self.tmp() 6579 r = self.fma_mix_odd(*vals)
6449 self.emit_fma(r, vals[0], vals[1], vals[2])
6450 if self.round_mode:
6451 # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly.
6452 # Nearest even keeps the f32 Fma then narrow (unchanged).
6453 ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp()
6454 self.emit(f"{m} = OpLoad %uint %mode_r16")
6455 self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}")
6456 self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}")
6457 r = rs
6458 r = self.clamp_mods(r, mods) 6580 r = self.clamp_mods(r, mods)
6459 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) 6581 self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16"))
6460 elif op == "v_cvt_pk_u8_f32": 6582 elif op == "v_cvt_pk_u8_f32":
@@ -6652,30 +6774,34 @@ class Gen:
6652 self.emit(f"{r} = OpConvertUToF %float {m}") 6774 self.emit(f"{r} = OpConvertUToF %float {m}")
6653 self.dst(a[0], self.tou(self.clamp_mods(r, mods))) 6775 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
6654 elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"): 6776 elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"):
6655 # RDNA ISA pseudocode: flr = f32_to_i32(floor(S0)), rpi = f32_to_i32(floor(S0 + 0.5)), the + 0.5 rounded 6777 # Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64):
6656 # in binary32 like any f32 add. f32_to_i32 saturates as v_cvt_i32_f32 does (#300): +-2^31 and beyond go to 6778 # - v_cvt_flr_i32_f32 = sat_i32(floor(S0)).
6657 # INT_MAX / INT_MIN, NaN to 0. Source neg/abs apply before the rounding. 6779 # - v_cvt_rpi_i32_f32 = sat_i32(floor(S0 + 0.5)) computed exactly without binary32 rounding of S0 + 0.5:
6780 # with f = Floor(x), frac = x - f is exact in binary32 across all normal ranges (0 for |x| >= 2^23,
6781 # and rounds to >= 0.5 iff exact x - f >= 0.5 around -0.5), so (frac >= 0.5) ? (f + 1.0) : f is exact.
6782 # - Out-of-range values (|x| >= 2^31, +-inf) and NaNs all saturate by the sign bit of x (+ -> 0x7FFFFFFF,
6783 # - -> 0x80000000). Check x's bits before Floor so a driver cannot lose a NaN's sign bit.
6658 x = self.src_f(a[1]) 6784 x = self.src_f(a[1])
6785 x_bits = self.tou(x)
6786 x_mag, x_neg, x_in_range, bound, safe_x_u, fl, signed, converted, result = (self.tmp() for _ in range(9))
6787 self.emit(f"{x_mag} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7FFFFFFF)}")
6788 self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31
6789 self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}")
6790 self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}")
6791 # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly.
6792 self.emit(f"{safe_x_u} = OpSelect %uint {x_in_range} {x_bits} {self.cu(0)}")
6793 safe_x = self.tof(safe_x_u)
6794 self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}")
6659 if op == "v_cvt_rpi_i32_f32": 6795 if op == "v_cvt_rpi_i32_f32":
6660 t = self.tmp() 6796 frac, ge_half, fl_plus1, rounded = (self.tmp() for _ in range(4))
6661 self.emit(f"{t} = OpFAdd %float {x} {self.fconst(0.5)}") 6797 self.emit(f"{frac} = OpFSub %float {safe_x} {fl}")
6662 x = t 6798 self.emit(f"{ge_half} = OpFOrdGreaterThanEqual %bool {frac} {self.fconst(0.5)}")
6663 fl = self.tmp() 6799 self.emit(f"{fl_plus1} = OpFAdd %float {fl} %f1")
6664 self.emit(f"{fl} = OpExtInst %float %glsl Floor {x}") 6800 self.emit(f"{rounded} = OpSelect %float {ge_half} {fl_plus1} {fl}")
6665 bits = self.tou(fl) 6801 fl = rounded
6666 magnitude, negative, not_nan, bound, in_range, saturated, safe, signed, converted, result = \ 6802 self.emit(f"{signed} = OpConvertFToS %int {fl}")
6667 (self.tmp() for _ in range(10))
6668 self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
6669 self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # |x| < 2^31
6670 self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}")
6671 self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {self.cu(0x7F800001)}")
6672 self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}")
6673 self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {self.cu(0)}")
6674 # Convert only an in-range operand: SPIR-V leaves the out-of-range conversion undefined.
6675 self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {self.cu(0)}")
6676 self.emit(f"{signed} = OpConvertFToS %int {self.tof(safe)}")
6677 self.emit(f"{converted} = OpBitcast %uint {signed}") 6803 self.emit(f"{converted} = OpBitcast %uint {signed}")
6678 self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") 6804 self.emit(f"{result} = OpSelect %uint {x_in_range} {converted} {bound}")
6679 self.dst(a[0], result) 6805 self.dst(a[0], result)
6680 elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): 6806 elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"):
6681 # Compare binary32 words before converting: the raw SPIR-V conversion 6807 # Compare binary32 words before converting: the raw SPIR-V conversion
@@ -6749,9 +6875,9 @@ class Gen:
6749 m = self.tmp() 6875 m = self.tmp()
6750 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}") 6876 self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}")
6751 y = m 6877 y = m
6878 x = self.src_u(a[1])
6752 else: 6879 else:
6753 y = self.src_u(a[2]) 6880 x, y = self.sop2_b32_srcs(op, a) # lane-mask sources as mask_src (s_and/or_b32 on EXEC)
6754 x = self.src_u(a[1])
6755 self.emit(f"{r} = {kind} %uint {x} {y}") 6881 self.emit(f"{r} = {kind} %uint {x} {y}")
6756 self.dst(a[0], r) 6882 self.dst(a[0], r)
6757 if op in ("s_and_b32", "s_or_b32"): 6883 if op in ("s_and_b32", "s_or_b32"):
@@ -6873,6 +6999,24 @@ class Gen:
6873 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") 6999 self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}")
6874 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}") 7000 self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}")
6875 self.dst(a[0], r) 7001 self.dst(a[0], r)
7002 elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"):
7003 # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for
7004 # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits.
7005 # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"), where clamp saturates
7006 # v_dot4_i32_i8 to a signed 32-bit value and op_sel picks the 16-bit half of a source each half of the
7007 # product reads. llvm-mc prints neither for the programs measured, so both forms are refused, not guessed.
7008 if "clamp" in mods or any(m.startswith("op_sel") for m in mods):
7009 raise Unsupported(op + (" clamp" if "clamp" in mods else " op_sel"))
7010 x, y = self.src_u(a[1]), self.src_u(a[2])
7011 acc = self.src_u(a[3]) if op == "v_dot4_i32_i8" else self.src_u(a[0])
7012 for i in range(4):
7013 xb, yb, prod, total = (self.tmp() for _ in range(4))
7014 self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}")
7015 self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}")
7016 self.emit(f"{prod} = OpIMul %uint {xb} {yb}")
7017 self.emit(f"{total} = OpIAdd %uint {acc} {prod}")
7018 acc = total
7019 self.dst(a[0], acc)
6876 elif op == "v_mad_u32_u24": 7020 elif op == "v_mad_u32_u24":
6877 x, y, z = (self.src_u(t) for t in a[1:4]) 7021 x, y, z = (self.src_u(t) for t in a[1:4])
6878 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() 7022 xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp()
@@ -9046,6 +9190,11 @@ def assemble(gen):
9046 used = set(gen.inputs.values()) 9190 used = set(gen.inputs.values())
9047 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute 9191 if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute
9048 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") 9192 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9193 # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a
9194 # raw attribute at the location of a half this shader doesn't read is overwritten all the same.
9195 reserved = {f16_half_location(n, h) for n in gen.f16_halves for h in (0, 1)}
9196 if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()):
9197 raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute")
9049 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None 9198 gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) if bary and BARY_FALLBACK else None
9050 bary_builtin = bary and gen.bary_location is None 9199 bary_builtin = bary and gen.bary_location is None
9051 if gen.frag_inputs or bary: 9200 if gen.frag_inputs or bary:
@@ -10000,7 +10149,8 @@ def read_before_write_vgprs(insns):
10000 a, op = ins["args"], ins["op"] 10149 a, op = ins["args"], ins["op"]
10001 if not a: 10150 if not a:
10002 continue 10151 continue
10003 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) \ 10152 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10153 "global_store")) \
10004 or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc 10154 or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc
10005 regs = [] 10155 regs = []
10006 for x in (a if reads_all else a[1:]): 10156 for x in (a if reads_all else a[1:]):
@@ -10008,7 +10158,7 @@ def read_before_write_vgprs(insns):
10008 regs += range(x["r"], x["r"] + x.get("n", 1)) 10158 regs += range(x["r"], x["r"] + x.get("n", 1))
10009 elif x["k"] == "vlist": 10159 elif x["k"] == "vlist":
10010 regs += x["r"] 10160 regs += x["r"]
10011 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16") or 10161 if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8") or
10012 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half 10162 (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half
10013 regs.append(a[0]["r"]) 10163 regs.append(a[0]["r"])
10014 for r in regs: 10164 for r in regs:
@@ -10058,7 +10208,8 @@ def interp_ij_analysis(insns, g):
10058 a, op = ins["args"], ins["op"] 10208 a, op = ins["args"], ins["op"]
10059 if not a: 10209 if not a:
10060 continue 10210 continue
10061 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) 10211 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10212 "global_store"))
10062 if not reads_all and a[0]["k"] == "vgpr": 10213 if not reads_all and a[0]["k"] == "vgpr":
10063 for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)): 10214 for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)):
10064 writes[r].append(n) 10215 writes[r].append(n)
@@ -10229,14 +10380,15 @@ def reg_reads_writes(insns):
10229 a, op = ins["args"], ins["op"] 10380 a, op = ins["args"], ins["op"]
10230 if not a: 10381 if not a:
10231 continue 10382 continue
10232 reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) 10383 reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
10384 "global_store"))
10233 regs = [] 10385 regs = []
10234 for x in (a if reads_all else a[1:]): 10386 for x in (a if reads_all else a[1:]):
10235 if x["k"] == "vgpr": 10387 if x["k"] == "vgpr":
10236 regs += range(x["r"], x["r"] + x.get("n", 1)) 10388 regs += range(x["r"], x["r"] + x.get("n", 1))
10237 elif x["k"] == "vlist": 10389 elif x["k"] == "vlist":
10238 regs += x["r"] 10390 regs += x["r"]
10239 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16") and a[0]["k"] == "vgpr": 10391 if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16", "v_dot4c_i32_i8") and a[0]["k"] == "vgpr":
10240 regs.append(a[0]["r"]) 10392 regs.append(a[0]["r"])
10241 rr.update(regs) 10393 rr.update(regs)
10242 if not reads_all and a[0]["k"] == "vgpr": 10394 if not reads_all and a[0]["k"] == "vgpr":
@@ -10463,6 +10615,10 @@ def translate(path):
10463 if stage not in ("vs", "ps", "cs", "ms", "gs"): 10615 if stage not in ("vs", "ps", "cs", "ms", "gs"):
10464 raise Unsupported(f"stage {stage}") 10616 raise Unsupported(f"stage {stage}")
10465 insns = info["insns"] 10617 insns = info["insns"]
10618 if not insns:
10619 # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing
10620 # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead.
10621 raise Unsupported("no instructions (nothing tab-indented?)")
10466 if info["invalid"]: 10622 if info["invalid"]:
10467 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to 10623 # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to
10468 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then 10624 # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then
@@ -11302,13 +11458,95 @@ def write_index(path, index):
11302 """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of 11458 """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of
11303 one: make_game.py takes these files as proof that a shard, or the whole translation, finished.""" 11459 one: make_game.py takes these files as proof that a shard, or the whole translation, finished."""
11304 tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json 11460 tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json
11305 with open(tmp, "w", encoding="utf-8") as f: 11461 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
11306 _json.dump(index, f, indent=0, sort_keys=True) 11462 _json.dump(index, f, indent=0, sort_keys=True)
11307 f.flush() 11463 f.flush()
11308 os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data 11464 os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data
11309 os.replace(tmp, path) # ponytail: no retry; add one if a scanner on Windows ever holds the new file open 11465 os.replace(tmp, path) # ponytail: no retry; add one if a scanner on Windows ever holds the new file open
11310 11466
11311 11467
11468class ShardSetError(Exception):
11469 """The index parts on disk are not one complete shard set: merging them would publish a partial index."""
11470
11471
11472SHARD_MARKER = "shard{index}.json"
11473
11474
11475def _read_shard_markers(out):
11476 """{index: count} from the shard<i>.json markers a --shard run writes beside its index.part<i>.json."""
11477 import glob as _gl, json as _js
11478 markers = {}
11479 for path in sorted(_gl.glob(os.path.join(out, "shard*.json"))):
11480 m = re.fullmatch(r"shard(\d+)\.json", os.path.basename(path))
11481 if not m: # make_game.py's shards.json plan is not a marker
11482 continue
11483 with open(path, encoding="utf-8") as f:
11484 doc = _js.load(f)
11485 try:
11486 index, count = int(doc["index"]), int(doc["count"])
11487 except (KeyError, TypeError, ValueError):
11488 raise ShardSetError(f"{path} is not a shard marker (expected an object with \"index\" and \"count\")") from None
11489 if index != int(m.group(1)):
11490 raise ShardSetError(f"{path} is a marker for shard {index}, but its name says shard {m.group(1)}")
11491 if index in markers and markers[index] != count:
11492 raise ShardSetError(f"shard markers disagree on the shard count: {path}")
11493 markers[index] = count
11494 return markers
11495
11496
11497def merge_shard_parts(out):
11498 """{shader: meta} from index.part*.json, after checking the set is complete.
11499
11500 A --shard i/n run writes index.part<i>.json and shard<i>.json ({"index": i, "count": n}); the markers say how
11501 many parts the set has. Parts from before the markers existed fall back to make_game.py's shards.json plan.
11502 With neither there is no way to know the count, so the old merge-everything behaviour is kept."""
11503 import glob as _gl, json as _js
11504 parts = sorted(_gl.glob(os.path.join(out, "index.part*.json")))
11505 indices = []
11506 for part in parts:
11507 m = re.search(r"index\.part(\d+)\.json$", part)
11508 if not m:
11509 raise ShardSetError(f"{part} is not an index.part<i>.json file")
11510 indices.append(int(m.group(1)))
11511 if len(set(indices)) != len(indices):
11512 raise ShardSetError(f"index.part*.json has two parts with the same index: {sorted(indices)}")
11513 markers = _read_shard_markers(out)
11514 expected = None
11515 if markers:
11516 counts = set(markers.values())
11517 if len(counts) != 1:
11518 raise ShardSetError(f"shard markers disagree on the shard count: {sorted(counts)}")
11519 expected = counts.pop()
11520 else:
11521 plan = os.path.join(out, "shards.json")
11522 if os.path.isfile(plan):
11523 try:
11524 with open(plan, encoding="utf-8") as f:
11525 expected = int(_js.load(f).get("jobs") or 0) or None
11526 except (OSError, ValueError, TypeError, AttributeError):
11527 expected = None
11528 if expected is not None:
11529 missing = [i for i in range(expected) if i not in set(indices)]
11530 extra = [i for i in indices if i >= expected]
11531 if missing or extra:
11532 raise ShardSetError(
11533 f"incomplete shard set: {len(indices)} of {expected} parts (0..{expected - 1})"
11534 + (f", missing {missing}" if missing else "")
11535 + (f", unexpected {extra}" if extra else "")
11536 + "; let every --shard run finish before --merge")
11537 if markers and set(markers) != set(indices):
11538 raise ShardSetError(f"index parts and shard markers disagree: parts {sorted(set(indices))}, "
11539 f"markers {sorted(markers)}")
11540 merged = {}
11541 for part in parts:
11542 with open(part, encoding="utf-8") as f:
11543 doc = _js.load(f)
11544 if not isinstance(doc, dict):
11545 raise ShardSetError(f"{part} does not contain a shader index object")
11546 merged.update(doc)
11547 return merged
11548
11549
11312def assemble_spirv(sa, sv): 11550def assemble_spirv(sa, sv):
11313 """Keep the assembled module out of the final path until validation succeeds.""" 11551 """Keep the assembled module out of the final path until validation succeeds."""
11314 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: 11552 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f:
@@ -11411,11 +11649,11 @@ def main():
11411 MESH_COMPUTE = a.mesh_compute 11649 MESH_COMPUTE = a.mesh_compute
11412 F16_HALVES = a.f16_interp_fallback 11650 F16_HALVES = a.f16_interp_fallback
11413 if a.merge: 11651 if a.merge:
11414 import glob as _gl, json as _js 11652 try:
11415 merged = {} 11653 merged = merge_shard_parts(a.out)
11416 for part in sorted(_gl.glob(os.path.join(a.out, "index.part*.json"))): 11654 except ShardSetError as e:
11417 with open(part, encoding="utf-8") as f: 11655 print(f"ERROR: {e}", file=sys.stderr)
11418 merged.update(_js.load(f)) 11656 return 2
11419 # The stubs go first: index.json is what tells make_game.py the translation finished. 11657 # The stubs go first: index.json is what tells make_game.py the translation finished.
11420 import spirv_stubs 11658 import spirv_stubs
11421 spirv_stubs.generate_for_index(a.out, merged) 11659 spirv_stubs.generate_for_index(a.out, merged)
@@ -11439,20 +11677,30 @@ def main():
11439 why, ok, valid = Counter(), 0, 0 11677 why, ok, valid = Counter(), 0, 0
11440 meta = {} 11678 meta = {}
11441 invalid = set() 11679 invalid = set()
11680
11681 def drop_stale(name):
11682 # A shader that no longer translates must not stay published from an earlier run: remove its old
11683 # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The
11684 # .spvasm text stays for diagnosis, as it does on a rejection.
11685 Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True)
11686 invalid.add(name)
11687
11442 for p in files: 11688 for p in files:
11443 name = os.path.splitext(os.path.basename(p))[0] 11689 name = os.path.splitext(os.path.basename(p))[0]
11444 try: 11690 try:
11445 asm = translate(p) 11691 asm = translate(p)
11446 except Unsupported as e: 11692 except Unsupported as e:
11447 why[str(e)] += 1 11693 why[str(e)] += 1
11694 drop_stale(name)
11448 continue 11695 continue
11449 except (IndexError, KeyError, ValueError) as e: 11696 except (IndexError, KeyError, ValueError) as e:
11450 why[f"translator error {type(e).__name__}"] += 1 11697 why[f"translator error {type(e).__name__}"] += 1
11698 drop_stale(name)
11451 continue 11699 continue
11452 ok += 1 11700 ok += 1
11453 sa = os.path.join(a.out, name + ".spvasm") 11701 sa = os.path.join(a.out, name + ".spvasm")
11454 sv = os.path.join(a.out, name + ".spv") 11702 sv = os.path.join(a.out, name + ".spv")
11455 with open(sa, "w") as f: 11703 with open(sa, "w", newline="\n") as f:
11456 f.write(asm) 11704 f.write(asm)
11457 r = assemble_spirv(sa, sv) 11705 r = assemble_spirv(sa, sv)
11458 if r.returncode == 0: 11706 if r.returncode == 0:
@@ -11463,7 +11711,7 @@ def main():
11463 except Exception as e: # noqa: BLE001 - metadata must never cost a translation 11711 except Exception as e: # noqa: BLE001 - metadata must never cost a translation
11464 meta[name] = {"error": f"{type(e).__name__}: {e}"} 11712 meta[name] = {"error": f"{type(e).__name__}: {e}"}
11465 else: 11713 else:
11466 invalid.add(name) 11714 drop_stale(name)
11467 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 11715 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1
11468 if a.no_asm and os.path.exists(sa): 11716 if a.no_asm and os.path.exists(sa):
11469 os.remove(sa) 11717 os.remove(sa)
@@ -11476,6 +11724,8 @@ def main():
11476 for name in invalid: 11724 for name in invalid:
11477 old.pop(name, None) 11725 old.pop(name, None)
11478 old.update(meta) 11726 old.update(meta)
11727 if shard is not None: # a marker beside the part, so --merge can tell a complete set from a partial one
11728 write_index(os.path.join(a.out, SHARD_MARKER.format(index=shard)), {"index": shard, "count": sn})
11479 write_index(idx_path, old) 11729 write_index(idx_path, old)
11480 if shard is None: 11730 if shard is None:
11481 import spirv_stubs 11731 import spirv_stubs
diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py
index c890cf65b..76b263ded 100644
--- a/tools/restofworld_index.py
+++ b/tools/restofworld_index.py
@@ -322,7 +322,7 @@ def summarise(rows, span, zero, unread):
322def write_output(path, rows, summary): 322def write_output(path, rows, summary):
323 """Write CSV or JSON from the file extension.""" 323 """Write CSV or JSON from the file extension."""
324 if os.path.splitext(path)[1].lower() == ".json": 324 if os.path.splitext(path)[1].lower() == ".json":
325 with open(path, "w", encoding="utf-8") as f: 325 with open(path, "w", encoding="utf-8", newline="\n") as f:
326 json.dump({"summary": summary, "files": rows}, f, indent=1) 326 json.dump({"summary": summary, "files": rows}, f, indent=1)
327 return 327 return
328 with open(path, "w", encoding="utf-8", newline="") as f: 328 with open(path, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py
index 43863d4cf..9621ea212 100644
--- a/tools/rpf9_carve.py
+++ b/tools/rpf9_carve.py
@@ -162,7 +162,7 @@ def main() -> int:
162 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"), 162 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"),
163 "zero_padding": zero, "unread_bytes": unread, 163 "zero_padding": zero, "unread_bytes": unread,
164 "span": span} 164 "span": span}
165 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 165 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
166 json.dump({"summary": summary, "files": rows}, f) 166 json.dump({"summary": summary, "files": rows}, f)
167 print(json.dumps(summary, indent=1)) 167 print(json.dumps(summary, indent=1))
168 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by 168 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by
diff --git a/tools/rpf9_names.py b/tools/rpf9_names.py
index f131f82d6..f2d50e8fc 100644
--- a/tools/rpf9_names.py
+++ b/tools/rpf9_names.py
@@ -207,7 +207,7 @@ def publish_report(path, rows, summary):
207 os.makedirs(directory, exist_ok=True) 207 os.makedirs(directory, exist_ok=True)
208 with tempfile.TemporaryDirectory(dir=directory, prefix=".rpf9_names-") as stage_dir: 208 with tempfile.TemporaryDirectory(dir=directory, prefix=".rpf9_names-") as stage_dir:
209 temp = os.path.join(stage_dir, "report.json") 209 temp = os.path.join(stage_dir, "report.json")
210 with open(temp, "w", encoding="utf-8") as f: 210 with open(temp, "w", encoding="utf-8", newline="\n") as f:
211 json.dump({"summary": summary, "files": rows}, f, indent=1) 211 json.dump({"summary": summary, "files": rows}, f, indent=1)
212 f.write("\n") 212 f.write("\n")
213 os.chmod(temp, published_mode(path)) 213 os.chmod(temp, published_mode(path))
diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py
index 7cfe678dc..49b512b3d 100644
--- a/tools/rpf_probe.py
+++ b/tools/rpf_probe.py
@@ -84,7 +84,7 @@ def main() -> int:
84 os.makedirs(out_dir, exist_ok=True) 84 os.makedirs(out_dir, exist_ok=True)
85 with tempfile.TemporaryDirectory(dir=out_dir) as staging: 85 with tempfile.TemporaryDirectory(dir=out_dir) as staging:
86 staged = os.path.join(staging, "rpf_probe.json") 86 staged = os.path.join(staging, "rpf_probe.json")
87 with open(staged, "w", encoding="utf-8") as f: 87 with open(staged, "w", encoding="utf-8", newline="\n") as f:
88 json.dump(rows, f, indent=1) 88 json.dump(rows, f, indent=1)
89 os.replace(staged, a.out) 89 os.replace(staged, a.out)
90 except OSError as error: 90 except OSError as error:
diff --git a/tools/salu_diff.py b/tools/salu_diff.py
index 244bee384..9108d5e01 100644
--- a/tools/salu_diff.py
+++ b/tools/salu_diff.py
@@ -71,7 +71,8 @@ OUT_SCC = 30 # s_cselect_b32 s30, 1, 0 observes SCC at the end
71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32 71BFE_ANY = False # any s_bfe_* control word (--bfe-any), not only offset + width <= 32
72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks 72INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks
73 73
74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_not_b64", "s_wqm_b64", 74LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_nand_b64", "s_nor_b64",
75 "s_xnor_b64", "s_not_b64", "s_wqm_b64",
75 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64") 76 "s_wqm_b32", "s_cselect_b64", "s_bfm_b64")
76 77
77INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 78INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE,
@@ -172,7 +173,9 @@ def _sop2():
172def _sop2_64(): 173def _sop2_64():
173 ops = {} 174 ops = {}
174 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), 175 for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b),
175 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b)): 176 ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b),
177 ("nand", lambda a, b: ~(a & b)), ("nor", lambda a, b: ~(a | b)),
178 ("xnor", lambda a, b: ~(a ^ b))):
176 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) 179 ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0)))
177 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) 180 ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None))
178 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) 181 ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0)))
@@ -493,7 +496,7 @@ def translated(lines, name="ps_salu"):
493 dis = os.path.join(tmp, "disasm") 496 dis = os.path.join(tmp, "disasm")
494 os.mkdir(dis) 497 os.mkdir(dis)
495 path = os.path.join(dis, name + ".s") 498 path = os.path.join(dis, name + ".s")
496 with open(path, "w", encoding="utf-8") as f: 499 with open(path, "w", encoding="utf-8", newline="\n") as f:
497 if has_branches(lines): 500 if has_branches(lines):
498 # The translator places branch targets from the encoding sizes; it does not read the bytes. 501 # The translator places branch targets from the encoding sizes; it does not read the bytes.
499 body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]) 502 body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"])
diff --git a/tools/save_keys.py b/tools/save_keys.py
index a5280b9cc..503b42bad 100644
--- a/tools/save_keys.py
+++ b/tools/save_keys.py
@@ -317,7 +317,7 @@ def cmd_resolve(a):
317 print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)") 317 print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)")
318 if a.out: 318 if a.out:
319 try: 319 try:
320 with open(a.out, "w", encoding="utf-8") as f: 320 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
321 json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())}, 321 json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())},
322 f, indent=1) 322 f, indent=1)
323 except OSError as e: 323 except OSError as e:
@@ -337,6 +337,8 @@ def main(argv=None):
337 r.add_argument("--compose", type=int, default=0, metavar="N") 337 r.add_argument("--compose", type=int, default=0, metavar="N")
338 r.add_argument("--out") 338 r.add_argument("--out")
339 a = ap.parse_args(argv) 339 a = ap.parse_args(argv)
340 if a.cmd == "resolve" and a.compose < 0:
341 r.error("--compose must be 0 or more")
340 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0 342 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0
341 343
342 344
diff --git a/tools/saves.py b/tools/saves.py
index a7fcef116..428346305 100644
--- a/tools/saves.py
+++ b/tools/saves.py
@@ -14,7 +14,7 @@ Commands
14 diff <JSAV a> <JSAV b> list blocks that were added, removed or changed between two saves 14 diff <JSAV a> <JSAV b> list blocks that were added, removed or changed between two saves
15 import <save dir>... [--out DIR] [--map OLD=CONTAINER/BLOB]... [--with-packed] [--force] [--dry-run] 15 import <save dir>... [--out DIR] [--map OLD=CONTAINER/BLOB]... [--with-packed] [--force] [--dry-run]
16 copy the ASAV/JSAV payloads out of plain save folders into the on-disk layout 16 copy the ASAV/JSAV payloads out of plain save folders into the on-disk layout
17 of the offline XGameSave shim (runtime/shims/xgameruntime_services.cpp): 17 of the offline XGameSave shim of the open #279 (not on main yet):
18 DIR/local-user/<container>/<blob>, names %-encoded the same way. 18 DIR/local-user/<container>/<blob>, names %-encoded the same way.
19 DIR defaults to %LOCALAPPDATA%\\Leonida\\saves (the shim's LEONIDA_SAVE_DIR default). 19 DIR defaults to %LOCALAPPDATA%\\Leonida\\saves (the shim's LEONIDA_SAVE_DIR default).
20 VERIFY: container/blob names are a guess until the executable shows them; by default 20 VERIFY: container/blob names are a guess until the executable shows them; by default
@@ -245,16 +245,16 @@ def extract(p, out):
245 e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json' 245 e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json'
246 with open(os.path.join(out, e['file']), 'wb') as f: 246 with open(os.path.join(out, e['file']), 'wb') as f:
247 f.write(b) 247 f.write(b)
248 with open(os.path.join(out, 'index.json'), 'w') as f: 248 with open(os.path.join(out, 'index.json'), 'w', newline="\n") as f:
249 json.dump({'header': h, 'entries': es}, f, indent=1) 249 json.dump({'header': h, 'entries': es}, f, indent=1)
250 body = d[h['body_offset']:h['body_end']].decode('utf-8') 250 body = d[h['body_offset']:h['body_end']].decode('utf-8')
251 with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8') as f: 251 with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8', newline="\n") as f:
252 json.dump(json.loads(body), f, indent=1) 252 json.dump(json.loads(body), f, indent=1)
253 print(f'{len(es)} blocks -> {out}') 253 print(f'{len(es)} blocks -> {out}')
254 elif k == 'ASAV': 254 elif k == 'ASAV':
255 h = parse_asav(d) 255 h = parse_asav(d)
256 pl = asav_payload(d, h) 256 pl = asav_payload(d, h)
257 with open(os.path.join(out, 'header.json'), 'w') as f: 257 with open(os.path.join(out, 'header.json'), 'w', newline="\n") as f:
258 json.dump(h, f, indent=1) 258 json.dump(h, f, indent=1)
259 with open(os.path.join(out, 'header.bin'), 'wb') as f: 259 with open(os.path.join(out, 'header.bin'), 'wb') as f:
260 f.write(d[:h['payload_offset']]) 260 f.write(d[:h['payload_offset']])
@@ -263,7 +263,7 @@ def extract(p, out):
263 if pl[:1] == b'{': 263 if pl[:1] == b'{':
264 try: 264 try:
265 obj = json.loads(pl.rstrip(b'\0').decode('utf-8')) 265 obj = json.loads(pl.rstrip(b'\0').decode('utf-8'))
266 with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8') as f: 266 with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8', newline="\n") as f:
267 json.dump(obj, f, indent=1) 267 json.dump(obj, f, indent=1)
268 except ValueError as ex: 268 except ValueError as ex:
269 print('payload looks like text but did not parse as JSON:', ex) 269 print('payload looks like text but did not parse as JSON:', ex)
@@ -467,7 +467,7 @@ def import_saves(args):
467 with open(tmp, 'wb') as f: 467 with open(tmp, 'wb') as f:
468 f.write(read(src)) 468 f.write(read(src))
469 os.replace(tmp, dst) 469 os.replace(tmp, dst)
470 with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8') as f: 470 with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8', newline="\n") as f:
471 json.dump(manifest, f, indent=1) 471 json.dump(manifest, f, indent=1)
472 print(f'wrote {len(plan)} blobs under {root}') 472 print(f'wrote {len(plan)} blobs under {root}')
473 473
diff --git a/tools/shader_carve.py b/tools/shader_carve.py
index 15fb02c4d..a2252628a 100644
--- a/tools/shader_carve.py
+++ b/tools/shader_carve.py
@@ -116,10 +116,13 @@ def main(argv=None) -> int:
116 f.write(data) 116 f.write(data)
117 index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0], 117 index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0],
118 "stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}}) 118 "stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}})
119 if not index:
120 print(f"ERROR: no shaders carved from {src} (rejected candidates: {bad}).", file=sys.stderr)
121 return 1
119 # make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename. 122 # make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename.
120 with tempfile.TemporaryDirectory(dir=out, prefix=".shader-index-") as staging: 123 with tempfile.TemporaryDirectory(dir=out, prefix=".shader-index-") as staging:
121 tmp = os.path.join(staging, "index.json") 124 tmp = os.path.join(staging, "index.json")
122 with open(tmp, "w", encoding="utf-8") as f: 125 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
123 json.dump(index, f, indent=1) 126 json.dump(index, f, indent=1)
124 f.flush() 127 f.flush()
125 os.fsync(f.fileno()) 128 os.fsync(f.fileno())
diff --git a/tools/shader_diff.py b/tools/shader_diff.py
index c42bcf22f..4b52ab7ba 100644
--- a/tools/shader_diff.py
+++ b/tools/shader_diff.py
@@ -177,7 +177,7 @@ def generate_program(rng, n_ops):
177 177
178 178
179def _write_listing(path, lines, with_export): 179def _write_listing(path, lines, with_export):
180 with open(path, "w", encoding="utf-8") as f: 180 with open(path, "w", encoding="utf-8", newline="\n") as f:
181 f.write("; shader_diff case code 0x0..0x1000\n") 181 f.write("; shader_diff case code 0x0..0x1000\n")
182 for line in lines: 182 for line in lines:
183 f.write("\t" + line + "\n") 183 f.write("\t" + line + "\n")
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index d22ca2bc2..38f49e7a6 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -119,7 +119,7 @@ def one(path, out, mcpu):
119 FAILED.append((path, reason)) 119 FAILED.append((path, reason))
120 return "failed" 120 return "failed"
121 name = os.path.splitext(os.path.basename(path))[0] 121 name = os.path.splitext(os.path.basename(path))[0]
122 with open(os.path.join(out, name + ".s"), "w", encoding="utf-8") as f: 122 with open(os.path.join(out, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
123 f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n") 123 f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n")
124 f.write(asm) 124 f.write(asm)
125 if err.strip(): 125 if err.strip():
diff --git a/tools/shader_profile.py b/tools/shader_profile.py
index 47a975fe4..b14d0d346 100644
--- a/tools/shader_profile.py
+++ b/tools/shader_profile.py
@@ -363,7 +363,7 @@ def main():
363 if a.per_shader: 363 if a.per_shader:
364 out["per_shader"] = sorted(shaders, key=lambda e: e["name"]) 364 out["per_shader"] = sorted(shaders, key=lambda e: e["name"])
365 try: 365 try:
366 with open(path, "w", encoding="utf-8") as f: 366 with open(path, "w", encoding="utf-8", newline="\n") as f:
367 json.dump(out, f, indent=1, allow_nan=False) 367 json.dump(out, f, indent=1, allow_nan=False)
368 except OSError as e: 368 except OSError as e:
369 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) 369 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/skin_streams.py b/tools/skin_streams.py
index b453aadd9..db5adcfcc 100644
--- a/tools/skin_streams.py
+++ b/tools/skin_streams.py
@@ -486,7 +486,7 @@ def main(argv=None):
486 parent = os.path.dirname(os.path.abspath(a.json)) 486 parent = os.path.dirname(os.path.abspath(a.json))
487 if parent: 487 if parent:
488 os.makedirs(parent, exist_ok=True) 488 os.makedirs(parent, exist_ok=True)
489 with open(a.json, "w", encoding="utf-8") as fh: 489 with open(a.json, "w", encoding="utf-8", newline="\n") as fh:
490 json.dump(report, fh, indent=1) 490 json.dump(report, fh, indent=1)
491 except OSError as exc: 491 except OSError as exc:
492 print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr) 492 print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py
index afb9edba6..e480fd65d 100644
--- a/tools/spirv_gs_to_compute.py
+++ b/tools/spirv_gs_to_compute.py
@@ -325,7 +325,7 @@ def main(argv):
325 target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2" 325 target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2"
326 subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True) 326 subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True)
327 if lay_path: 327 if lay_path:
328 with open(lay_path, "w") as f: 328 with open(lay_path, "w", newline="\n") as f:
329 json.dump(lay, f, indent=1) 329 json.dump(lay, f, indent=1)
330 print(json.dumps(lay)) 330 print(json.dumps(lay))
331 return 0 331 return 0
diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py
index cbd2792f5..9282a60e6 100644
--- a/tools/spirv_metal_set0.py
+++ b/tools/spirv_metal_set0.py
@@ -28,7 +28,8 @@ BINDLESS_H = os.path.join(ROOT, "runtime", "src", "vulkan_bindless.h")
28 28
29def capacities(path=BINDLESS_H): 29def capacities(path=BINDLESS_H):
30 """Descriptor counts by binding number, from the `bindings` table of vulkan_bindless.h.""" 30 """Descriptor counts by binding number, from the `bindings` table of vulkan_bindless.h."""
31 src = open(path, encoding="utf-8").read() 31 with open(path, encoding="utf-8") as f:
32 src = f.read()
32 m = re.search(r"std::array<Binding,\s*(\d+)>\s*bindings\s*=\s*\{\{(.*?)\}\};", src, re.S) 33 m = re.search(r"std::array<Binding,\s*(\d+)>\s*bindings\s*=\s*\{\{(.*?)\}\};", src, re.S)
33 if not m: 34 if not m:
34 raise SystemExit(f"{path}: no `bindings` table") 35 raise SystemExit(f"{path}: no `bindings` table")
@@ -47,6 +48,17 @@ def metal_ids(counts):
47 return ids 48 return ids
48 49
49 50
51def _fresh_id(base, used):
52 """Return `base` if unused, otherwise `base_1`, `base_2`, ... and record it in `used`."""
53 cand = base
54 i = 1
55 while cand in used:
56 cand = f"{base}_{i}"
57 i += 1
58 used.add(cand)
59 return cand
60
61
50def rewrite(text, counts): 62def rewrite(text, counts):
51 """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module.""" 63 """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module."""
52 ids = metal_ids(counts) 64 ids = metal_ids(counts)
@@ -65,28 +77,52 @@ def rewrite(text, counts):
65 raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h") 77 raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h")
66 78
67 defs = {} # result id -> instruction text 79 defs = {} # result id -> instruction text
68 for ln in lines: 80 ptr_pos = {} # OpTypePointer result id -> line index, so shared capacities emit at the earliest pointer
81 for idx, ln in enumerate(lines):
69 m = re.match(r"\s*(%\S+) = (.*)$", ln) 82 m = re.match(r"\s*(%\S+) = (.*)$", ln)
70 if m: 83 if m:
71 defs[m.group(1)] = m.group(2) 84 defs[m.group(1)] = m.group(2)
85 if re.match(r"OpTypePointer\b", m.group(2)):
86 ptr_pos[m.group(1)] = idx
72 uint = next((r for r, d in defs.items() if d == "OpTypeInt 32 0"), None) 87 uint = next((r for r, d in defs.items() if d == "OpTypeInt 32 0"), None)
73 88
74 new_types = [] # inserted right after the variable's pointer type is declared 89 candidates = []
75 retype = {} # variable -> new pointer type 90 for order, (v, b) in enumerate(set0.items()):
76 for v, b in sorted(set0.items(), key=lambda kv: kv[1]):
77 var = re.match(r"OpVariable (%\S+) UniformConstant$", defs.get(v, "")) 91 var = re.match(r"OpVariable (%\S+) UniformConstant$", defs.get(v, ""))
78 if not var: 92 if not var:
79 continue # the hash table (a storage buffer) and other non-array resources keep their type 93 continue # the hash table (a storage buffer) and other non-array resources keep their type
80 ptr = re.match(r"OpTypePointer UniformConstant (%\S+)$", defs[var.group(1)]) 94 old_ptr = var.group(1)
95 ptr = re.match(r"OpTypePointer UniformConstant (%\S+)$", defs.get(old_ptr, ""))
81 rt = re.match(r"OpTypeRuntimeArray (%\S+)$", defs.get(ptr.group(1), "")) if ptr else None 96 rt = re.match(r"OpTypeRuntimeArray (%\S+)$", defs.get(ptr.group(1), "")) if ptr else None
82 if not rt: 97 if not rt:
83 continue 98 continue
84 if uint is None: 99 if uint is None:
85 raise SystemExit("module has no 32-bit uint type for the array lengths") 100 raise SystemExit("module has no 32-bit uint type for the array lengths")
86 cap, arr, nptr = f"%msl_cap_b{b}", f"%msl_arr_b{b}", f"%msl_ptr_b{b}" 101 candidates.append((b, ptr_pos.get(old_ptr, len(lines)), order, v, old_ptr, rt.group(1)))
87 new_types.append((var.group(1), [f"{cap} = OpConstant {uint} {counts[b]}", 102
88 f"{arr} = OpTypeArray {rt.group(1)} {cap}", 103 used_ids = set(defs) | set(sets) | set(binds)
89 f"{nptr} = OpTypePointer UniformConstant {arr}"])) 104 cap_by_bind = {} # binding -> OpConstant id (emitted once per binding)
105 ptr_by_key = {} # (binding, elem_type) -> new OpTypePointer id
106 new_types = [] # inserted right after the variable's pointer type is declared
107 retype = {} # variable -> new pointer type
108 for b, _, _, v, old_ptr, elem in sorted(candidates):
109 if (b, elem) in ptr_by_key:
110 retype[v] = ptr_by_key[(b, elem)]
111 continue
112 decl = []
113 cap = cap_by_bind.get(b)
114 if cap is None:
115 cap = _fresh_id(f"%msl_cap_b{b}", used_ids)
116 cap_by_bind[b] = cap
117 decl.append(f"{cap} = OpConstant {uint} {counts[b]}")
118 arr = _fresh_id(f"%msl_arr_b{b}", used_ids)
119 nptr = _fresh_id(f"%msl_ptr_b{b}", used_ids)
120 decl.extend([
121 f"{arr} = OpTypeArray {elem} {cap}",
122 f"{nptr} = OpTypePointer UniformConstant {arr}",
123 ])
124 new_types.append((old_ptr, decl))
125 ptr_by_key[(b, elem)] = nptr
90 retype[v] = nptr 126 retype[v] = nptr
91 127
92 out = [] 128 out = []
diff --git a/tools/story_index.py b/tools/story_index.py
index 7a7c7a837..06d1e742a 100644
--- a/tools/story_index.py
+++ b/tools/story_index.py
@@ -299,7 +299,7 @@ def write_output(path, rows, summary):
299 with tempfile.TemporaryDirectory(dir=parent) as staging: 299 with tempfile.TemporaryDirectory(dir=parent) as staging:
300 staged = os.path.join(staging, "story_index" + ext) 300 staged = os.path.join(staging, "story_index" + ext)
301 if ext == ".json": 301 if ext == ".json":
302 with open(staged, "w", encoding="utf-8") as f: 302 with open(staged, "w", encoding="utf-8", newline="\n") as f:
303 json.dump({"summary": summary, "files": rows}, f, indent=1) 303 json.dump({"summary": summary, "files": rows}, f, indent=1)
304 else: 304 else:
305 with open(staged, "w", encoding="utf-8", newline="") as f: 305 with open(staged, "w", encoding="utf-8", newline="") as f:
diff --git a/tools/tex_export.py b/tools/tex_export.py
index f7de7dd28..59d7d4c28 100644
--- a/tools/tex_export.py
+++ b/tools/tex_export.py
@@ -225,7 +225,7 @@ def main():
225 pngs[t["export"]["png"]] += 1 225 pngs[t["export"]["png"]] += 1
226 if i % 2000 == 0: 226 if i % 2000 == 0:
227 print(f"[{i}/{len(texs)}] {dict(res)}", flush=True) 227 print(f"[{i}/{len(texs)}] {dict(res)}", flush=True)
228 with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8") as f: 228 with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8", newline="\n") as f:
229 json.dump(texs, f) 229 json.dump(texs, f)
230 print(f"{len(texs)} textures: {dict(res)} -> {a.out}") 230 print(f"{len(texs)} textures: {dict(res)} -> {a.out}")
231 if a.png: 231 if a.png:
diff --git a/tools/tex_headers.py b/tools/tex_headers.py
index f41cc47bc..389b83cf2 100644
--- a/tools/tex_headers.py
+++ b/tools/tex_headers.py
@@ -751,7 +751,7 @@ def main():
751 if parent: # the scan is already done; a missing folder used to lose it in a FileNotFoundError 751 if parent: # the scan is already done; a missing folder used to lose it in a FileNotFoundError
752 os.makedirs(parent, exist_ok=True) 752 os.makedirs(parent, exist_ok=True)
753 try: 753 try:
754 with open(path, "w", encoding="utf-8") as f: 754 with open(path, "w", encoding="utf-8", newline="\n") as f:
755 json.dump(allt, f) 755 json.dump(allt, f)
756 except OSError as e: 756 except OSError as e:
757 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) 757 print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr)
diff --git a/tools/text_tables.py b/tools/text_tables.py
index 8db40ae5f..60c4e9dce 100644
--- a/tools/text_tables.py
+++ b/tools/text_tables.py
@@ -40,10 +40,12 @@ import os
40import re 40import re
41import struct 41import struct
42import sys 42import sys
43import tempfile
43 44
44ROOT = os.path.dirname(os.path.abspath(__file__)) 45ROOT = os.path.dirname(os.path.abspath(__file__))
45if ROOT not in sys.path: 46if ROOT not in sys.path:
46 sys.path.insert(0, ROOT) 47 sys.path.insert(0, ROOT)
48from file_mode import published_mode # noqa: E402
47from hashdict import joaat # noqa: E402 49from hashdict import joaat # noqa: E402
48 50
49RESOURCE_MAGIC = b"0DRP" 51RESOURCE_MAGIC = b"0DRP"
@@ -288,6 +290,12 @@ def main(argv=None) -> int:
288 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)") 290 ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)")
289 a = ap.parse_args(argv) 291 a = ap.parse_args(argv)
290 outs = [p for p in (a.dialogue, a.tables, a.strings) if p] 292 outs = [p for p in (a.dialogue, a.tables, a.strings) if p]
293 seen = set()
294 for p in outs:
295 key = os.path.normcase(os.path.realpath(p))
296 if key in seen:
297 ap.error("outputs must be distinct files")
298 seen.add(key)
291 for path in a.sources + a.labels: 299 for path in a.sources + a.labels:
292 if not os.path.exists(path): 300 if not os.path.exists(path):
293 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr) 301 print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr)
@@ -308,24 +316,73 @@ def main(argv=None) -> int:
308 316
309 lines = sum(len(v) for v in scan.pairs.values()) 317 lines = sum(len(v) for v in scan.pairs.values())
310 langs = scan.languages() 318 langs = scan.languages()
319 jobs = []
320 if a.dialogue:
321 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs]
322 jobs.append((a.dialogue, fields, scan.dialogue_rows()))
323 if a.tables:
324 jobs.append((a.tables, ["source", "offset", "lang", "group", "strings", "resolved"],
325 ({"source": s, "offset": o, "lang": lang,
326 "group": table_group(names[h] for h in t if h in names),
327 "strings": len(t), "resolved": sum(h in names for h in t)}
328 for s, o, lang, t in scan.tables)))
329 if a.strings:
330 jobs.append((a.strings, ["source", "offset", "lang", "hash", "label", "text"],
331 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""),
332 "text": _clean(text)}
333 for s, o, lang, t in scan.tables for h, text in t.items())))
334 # Stage every report next to its destination, then swap them all in. A write that fails part-way must
335 # leave the previous reports intact instead of truncating the ones that came before it.
336 staged = []
337 originals = {}
311 try: 338 try:
312 if a.dialogue: 339 for dest, fields, rows in jobs:
313 fields = ["wave", "key", "label", "speaker"] + [f"text_{x}" for x in langs] 340 parent = os.path.dirname(os.path.abspath(dest))
314 _write_csv(a.dialogue, fields, scan.dialogue_rows()) 341 fd, tmp = tempfile.mkstemp(dir=parent, prefix=".text_tables-", suffix=".csv")
315 if a.tables: 342 os.close(fd)
316 _write_csv(a.tables, ["source", "offset", "lang", "group", "strings", "resolved"], 343 staged.append((tmp, dest))
317 ({"source": s, "offset": o, "lang": lang, 344 _write_csv(tmp, fields, rows)
318 "group": table_group(names[h] for h in t if h in names), 345 for _tmp, dest in staged:
319 "strings": len(t), "resolved": sum(h in names for h in t)} 346 if os.path.isdir(dest):
320 for s, o, lang, t in scan.tables)) 347 raise OSError(f"{dest} is a directory")
321 if a.strings: 348 for tmp, dest in staged:
322 _write_csv(a.strings, ["source", "offset", "lang", "hash", "label", "text"], 349 os.chmod(tmp, published_mode(dest))
323 ({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""), 350 # Move every old report aside before putting any new one in place. On Windows a report held
324 "text": _clean(text)} 351 # open by a reader cannot be renamed; failing here leaves all the originals untouched.
325 for s, o, lang, t in scan.tables for h, text in t.items())) 352 for _tmp, dest in staged:
353 if os.path.lexists(dest):
354 fd, backup = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(dest)),
355 prefix=".text_tables-old-", suffix=".csv")
356 os.close(fd)
357 os.remove(backup)
358 os.replace(dest, backup)
359 originals[dest] = backup
360 else:
361 originals[dest] = None
362 for tmp, dest in staged:
363 os.replace(tmp, dest)
326 except OSError as error: 364 except OSError as error:
365 for dest, backup in originals.items():
366 try:
367 if os.path.lexists(dest):
368 os.remove(dest)
369 if backup is not None:
370 os.replace(backup, dest)
371 except OSError:
372 pass
373 for tmp, _ in staged:
374 try:
375 os.remove(tmp)
376 except OSError:
377 pass
327 print(f"text_tables: error: cannot write: {error}", file=sys.stderr) 378 print(f"text_tables: error: cannot write: {error}", file=sys.stderr)
328 return 2 379 return 2
380 for backup in originals.values():
381 if backup is not None:
382 try:
383 os.remove(backup)
384 except OSError:
385 pass
329 with_text = collections.Counter() 386 with_text = collections.Counter()
330 for row in scan.dialogue_rows(): 387 for row in scan.dialogue_rows():
331 for lang in langs: 388 for lang in langs:
diff --git a/tools/ttpf_assets.py b/tools/ttpf_assets.py
index da8470a85..2939c66c3 100644
--- a/tools/ttpf_assets.py
+++ b/tools/ttpf_assets.py
@@ -4,9 +4,13 @@ import hashlib
4import json 4import json
5import os 5import os
6from pathlib import Path 6from pathlib import Path
7import sys
7import tempfile 8import tempfile
8import zlib 9import zlib
9 10
11# `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it.
12sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
10import bcpack 14import bcpack
11from file_mode import published_mode 15from file_mode import published_mode
12import ttpf_mips as ttpf 16import ttpf_mips as ttpf
diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py
index 58e58e9be..698f4c558 100644
--- a/tools/ttpf_mips.py
+++ b/tools/ttpf_mips.py
@@ -1497,7 +1497,7 @@ def scan_pools(paths, as_json=None, include_tuples=False):
1497 if as_json: 1497 if as_json:
1498 try: 1498 try:
1499 os.makedirs(os.path.dirname(os.path.abspath(as_json)), exist_ok=True) 1499 os.makedirs(os.path.dirname(os.path.abspath(as_json)), exist_ok=True)
1500 with open(as_json, "w", encoding="utf-8") as f: 1500 with open(as_json, "w", encoding="utf-8", newline="\n") as f:
1501 json.dump(report, f, indent=1) 1501 json.dump(report, f, indent=1)
1502 except OSError as exc: 1502 except OSError as exc:
1503 raise ValueError(f"cannot write {as_json}: {exc.strerror or exc}") from None 1503 raise ValueError(f"cannot write {as_json}: {exc.strerror or exc}") from None
diff --git a/tools/turing_atlas.py b/tools/turing_atlas.py
index c058b55c2..56fcb2c76 100644
--- a/tools/turing_atlas.py
+++ b/tools/turing_atlas.py
@@ -188,7 +188,7 @@ def validate_cases():
188 for name, asm in CASES.items(): 188 for name, asm in CASES.items():
189 src = os.path.join(d, name + ".spvasm") 189 src = os.path.join(d, name + ".spvasm")
190 spv = os.path.join(d, name + ".spv") 190 spv = os.path.join(d, name + ".spv")
191 with open(src, "w", encoding="utf-8") as f: 191 with open(src, "w", encoding="utf-8", newline="\n") as f:
192 f.write(asm) 192 f.write(asm)
193 ra = run(["spirv-as", src, "-o", spv, "--target-env", "vulkan1.4"]) 193 ra = run(["spirv-as", src, "-o", spv, "--target-env", "vulkan1.4"])
194 if ra is None or ra.returncode != 0: 194 if ra is None or ra.returncode != 0:
@@ -230,7 +230,7 @@ def main():
230 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does 230 folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does
231 if folder: 231 if folder:
232 os.makedirs(folder, exist_ok=True) 232 os.makedirs(folder, exist_ok=True)
233 with open(a.out, "w", encoding="utf-8") as f: 233 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
234 f.write(text + "\n") 234 f.write(text + "\n")
235 print(f"atlas -> {a.out}") 235 print(f"atlas -> {a.out}")
236 else: 236 else:
diff --git a/tools/user_sgpr_census.py b/tools/user_sgpr_census.py
index 35fa44ddf..bdb49ff12 100644
--- a/tools/user_sgpr_census.py
+++ b/tools/user_sgpr_census.py
@@ -24,6 +24,7 @@ Usage:
24""" 24"""
25import argparse 25import argparse
26import json 26import json
27import os
27import sys 28import sys
28from collections import Counter, defaultdict 29from collections import Counter, defaultdict
29 30
@@ -83,19 +84,36 @@ def census(index, base=None):
83 return out 84 return out
84 85
85 86
87def stage_sgpr(text):
88 stage, _, value = text.partition("=")
89 message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}"
90 try:
91 sgpr = int(value)
92 except ValueError:
93 raise argparse.ArgumentTypeError(message) from None
94 if not stage or sgpr < 0:
95 raise argparse.ArgumentTypeError(message)
96 return stage, sgpr
97
98
86def main(argv=None): 99def main(argv=None):
87 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) 100 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
88 ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py") 101 ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py")
89 ap.add_argument("--json", help="also write the summary here") 102 ap.add_argument("--json", help="also write the summary here")
90 ap.add_argument("--expect", nargs="*", default=[], metavar="STAGE=SGPR", 103 ap.add_argument("--expect", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR",
91 help="fail if the most common lowest-pointer SGPR of STAGE is not SGPR") 104 help="fail if the most common lowest-pointer SGPR of STAGE is not SGPR")
92 ap.add_argument("--base", nargs="*", default=[], metavar="STAGE=SGPR", 105 ap.add_argument("--base", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR",
93 help="report the reads below this first root-argument SGPR per stage") 106 help="report the reads below this first root-argument SGPR per stage")
94 a = ap.parse_args(argv) 107 a = ap.parse_args(argv)
108 if a.json:
109 try:
110 if os.path.samefile(a.index, a.json):
111 ap.error("--json must not overwrite the input index")
112 except FileNotFoundError:
113 pass
95 with open(a.index, encoding="utf-8") as f: 114 with open(a.index, encoding="utf-8") as f:
96 index = json.load(f) 115 index = json.load(f)
97 base = {k: int(v) for k, _, v in (b.partition("=") for b in a.base)} 116 summary = census(index, dict(a.base))
98 summary = census(index, base)
99 for stage, s in summary.items(): 117 for stage, s in summary.items():
100 top = s["most_common_lowest_pointer_sgpr"] 118 top = s["most_common_lowest_pointer_sgpr"]
101 print(f"{stage}: {s['shaders']} shaders; lowest pointer SGPR " 119 print(f"{stage}: {s['shaders']} shaders; lowest pointer SGPR "
@@ -103,13 +121,12 @@ def main(argv=None):
103 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}" 121 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}"
104 + (f"; below base {s['below_base']}" if "below_base" in s else "")) 122 + (f"; below base {s['below_base']}" if "below_base" in s else ""))
105 if a.json: 123 if a.json:
106 with open(a.json, "w", encoding="utf-8") as f: 124 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
107 json.dump(summary, f, indent=1, sort_keys=True) 125 json.dump(summary, f, indent=1, sort_keys=True)
108 bad = [] 126 bad = []
109 for item in a.expect: 127 for stage, sgpr in a.expect:
110 stage, _, sgpr = item.partition("=")
111 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr") 128 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr")
112 if got != int(sgpr): 129 if got != sgpr:
113 bad.append(f"{stage}: expected s{sgpr}, got {'s%d' % got if got is not None else 'none'}") 130 bad.append(f"{stage}: expected s{sgpr}, got {'s%d' % got if got is not None else 'none'}")
114 for b in bad: 131 for b in bad:
115 print("MISMATCH", b, file=sys.stderr) 132 print("MISMATCH", b, file=sys.stderr)
diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py
index 2b9beeb97..ed6c24e0d 100644
--- a/tools/valu_fuzz.py
+++ b/tools/valu_fuzz.py
@@ -845,7 +845,7 @@ def translate(progs, work, emulate):
845 for p in progs: 845 for p in progs:
846 text = p.asm() 846 text = p.asm()
847 asm_path = work / (p.name + ".asm") 847 asm_path = work / (p.name + ".asm")
848 asm_path.write_text(text, encoding="utf-8") 848 asm_path.write_text(text, encoding="utf-8", newline="\n")
849 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] 849 cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
850 if p.wave == 64: 850 if p.wave == 64:
851 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") 851 cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32")
@@ -853,7 +853,7 @@ def translate(progs, work, emulate):
853 if r.returncode or "error:" in r.stderr: 853 if r.returncode or "error:" in r.stderr:
854 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") 854 raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}")
855 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) 855 code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
856 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") 856 (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n")
857 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) 857 (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path))
858 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] 858 cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)]
859 if emulate: 859 if emulate:
diff --git a/tools/vertex_types.py b/tools/vertex_types.py
index 6702b5fae..871d886e5 100644
--- a/tools/vertex_types.py
+++ b/tools/vertex_types.py
@@ -525,7 +525,7 @@ def main(argv=None):
525 if args.json: 525 if args.json:
526 try: 526 try:
527 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) 527 os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True)
528 with open(args.json, "w", encoding="utf-8") as fh: 528 with open(args.json, "w", encoding="utf-8", newline="\n") as fh:
529 json.dump(out, fh, indent=1) 529 json.dump(out, fh, indent=1)
530 except OSError as exc: 530 except OSError as exc:
531 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) 531 print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr)
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py
index 3630c2baf..97e3880cf 100644
--- a/tools/vk_subgroup_info.py
+++ b/tools/vk_subgroup_info.py
@@ -6,12 +6,13 @@ make_game.py uses it to choose between native wave64 translation and --wave64-em
6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything. 6Vulkan implementation through ctypes (standard library only), so it works before the runtime stage has built anything.
7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools. 7On macOS it opens MoltenVK directly, using the same LEONIDA_VULKAN_LOADER override as the C++ test tools.
8 8
9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp): Vulkan 1.3 devices with dynamicRendering, 9Device choice follows the runtime (runtime/shims/d3d12_vulkan_device.cpp, runtime/src/vulkan_device_filter.h):
10synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue family; a discrete GPU wins 10LEONIDA_VK_DEVICE filters by deviceName substring case-insensitively (failing when nothing matches), then Vulkan 1.3
11(the last one), otherwise the first. The runtime also needs the rest of its device setup (surface, extensions); 11devices with dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts and a graphics queue
12that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two differ the pipelines 12family; a discrete GPU wins (the last one), otherwise the first. The runtime also needs the rest of its device setup
13stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*') narrows which 13(surface, extensions); that is not checked here. vk_pipeline_check picks by device type only, so on a PC where the two
14drivers the loader offers. 14differ the pipelines stage can run on another GPU than the one asked here. VK_LOADER_DRIVERS_SELECT (e.g. '*amd*')
15narrows which drivers the loader offers.
15 16
16native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can 17native64 matches the current translated SPIR-V 1.5 modules, which do not allow varying subgroup sizes: either 64 can
17be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in 18be required for both compute and mesh, or the default subgroupSize is 64 and subgroup operations are supported in
@@ -180,6 +181,8 @@ def query() -> dict:
180 devs = physical_devices(vk, inst) 181 devs = physical_devices(vk, inst)
181 if not devs: 182 if not devs:
182 raise RuntimeError("no Vulkan device") 183 raise RuntimeError("no Vulkan device")
184 device_filter = os.environ.get("LEONIDA_VK_DEVICE", "")
185 wanted = device_filter.lower()
183 chosen = None 186 chosen = None
184 for d in devs: 187 for d in devs:
185 d = ctypes.c_void_p(d) 188 d = ctypes.c_void_p(d)
@@ -193,8 +196,11 @@ def query() -> dict:
193 set_next(props, subgroup) 196 set_next(props, subgroup)
194 vk.vkGetPhysicalDeviceProperties2(d, props) 197 vk.vkGetPhysicalDeviceProperties2(d, props)
195 raw = bytes(props)[16:] 198 raw = bytes(props)[16:]
199 dev_name = raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace")
196 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3: 200 if int.from_bytes(raw[PROPS_API_VERSION:PROPS_API_VERSION + 4], "little") < VK_API_VERSION_1_3:
197 continue 201 continue
202 if wanted and wanted not in dev_name.lower():
203 continue
198 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES) 204 f13 = block(F13_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES)
199 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES) 205 f12 = block(F12_SIZE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES)
200 set_next(f12, f13) 206 set_next(f12, f13)
@@ -215,13 +221,18 @@ def query() -> dict:
215 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little") 221 dtype = int.from_bytes(raw[PROPS_DEVICE_TYPE:PROPS_DEVICE_TYPE + 4], "little")
216 # the runtime's rule: the first usable device, replaced by every later discrete GPU 222 # the runtime's rule: the first usable device, replaced by every later discrete GPU
217 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: 223 if chosen is None or dtype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
218 chosen = (raw[PROPS_DEVICE_NAME:PROPS_DEVICE_NAME + 256].split(b"\0")[0].decode("utf-8", "replace"), 224 chosen = (dev_name,
219 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, 225 subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize,
220 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)), 226 sg.requiredSubgroupSizeStages, bool(u32(f13, F13_SUBGROUP_SIZE_CONTROL)),
221 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK, 227 bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK,
222 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"), 228 int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"),
223 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16)) 229 int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16))
224 if chosen is None: 230 if chosen is None:
231 if device_filter:
232 raise RuntimeError(
233 f"LEONIDA_VK_DEVICE={device_filter}: no Vulkan 1.3 GPU with the features and graphics queue "
234 "the runtime needs matches"
235 )
225 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") 236 raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs")
226 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen 237 name, subgroup_size, supported_stages, lo, hi, required_stages, sgc, per_vertex, vendor, device, driver = chosen
227 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) 238 compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT)
diff --git a/tools/wave64_graphics_scan.py b/tools/wave64_graphics_scan.py
index b9410a5e8..f830a2da7 100644
--- a/tools/wave64_graphics_scan.py
+++ b/tools/wave64_graphics_scan.py
@@ -96,10 +96,10 @@ def scan_directory(disasm):
96 "mask_word_source": {"exec_vcc": Counter(), "other": Counter()}} 96 "mask_word_source": {"exec_vcc": Counter(), "other": Counter()}}
97 for stage in GRAPHICS} 97 for stage in GRAPHICS}
98 other = {"shaders": 0, "wave64": 0} 98 other = {"shaders": 0, "wave64": 0}
99 for name in sorted(os.listdir(disasm)): 99 with os.scandir(disasm) as entries:
100 if not name.endswith(".s"): 100 paths = sorted(entry.path for entry in entries
101 continue 101 if entry.name.endswith(".s") and entry.is_file())
102 path = os.path.join(disasm, name) 102 for path in paths:
103 info = parse_file(path) 103 info = parse_file(path)
104 stage = rdna2spirv.stage_of(info["name"], path) 104 stage = rdna2spirv.stage_of(info["name"], path)
105 wave64 = wave64_rule(stage, info["insns"]) 105 wave64 = wave64_rule(stage, info["insns"])
@@ -158,7 +158,7 @@ def main(argv=None) -> int:
158 o = report["other_stages"] 158 o = report["other_stages"]
159 print("other stages: %d shaders, %d wave64 (not counted)" % (o["shaders"], o["wave64"])) 159 print("other stages: %d shaders, %d wave64 (not counted)" % (o["shaders"], o["wave64"]))
160 if args.out: 160 if args.out:
161 with open(args.out, "w", encoding="utf-8") as f: 161 with open(args.out, "w", encoding="utf-8", newline="\n") as f:
162 json.dump(report, f, indent=1) 162 json.dump(report, f, indent=1)
163 print("wrote %s" % args.out) 163 print("wrote %s" % args.out)
164 return 0 164 return 0
diff --git a/tools/world_census.py b/tools/world_census.py
index 86b63b4b5..0d1e04539 100644
--- a/tools/world_census.py
+++ b/tools/world_census.py
@@ -101,7 +101,7 @@ def _mapped_source(archive, expected_id):
101def _staged_json(path, doc, **options): 101def _staged_json(path, doc, **options):
102 with tempfile.TemporaryDirectory(dir=os.path.dirname(path)) as directory: 102 with tempfile.TemporaryDirectory(dir=os.path.dirname(path)) as directory:
103 tmp = os.path.join(directory, os.path.basename(path)) 103 tmp = os.path.join(directory, os.path.basename(path))
104 with open(tmp, "w", encoding="utf-8") as f: 104 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
105 json.dump(doc, f, **options) 105 json.dump(doc, f, **options)
106 try: 106 try:
107 mode = os.lstat(path).st_mode 107 mode = os.lstat(path).st_mode
diff --git a/tools/world_index.py b/tools/world_index.py
index e0464beac..972c986a9 100644
--- a/tools/world_index.py
+++ b/tools/world_index.py
@@ -419,6 +419,15 @@ def _carve_successors(folder):
419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off} 419 for off, stored in by_off.items() if (off + stored + 15) & ~15 in by_off}
420 420
421 421
422def _read_carved(path, max_inflate):
423 """Read a carved file within the cap, or return None if it is too large."""
424 with open(path, "rb") as f:
425 if os.fstat(f.fileno()).st_size > max_inflate:
426 return None
427 data = f.read(max_inflate + 1) # detect growth after fstat
428 return data if len(data) <= max_inflate else None
429
430
422def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None): 431def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, directory_files=None):
423 """Scan an RPF9 archive, or every carved file in a directory.""" 432 """Scan an RPF9 archive, or every carved file in a directory."""
424 if directory_files is not None or os.path.isdir(path): 433 if directory_files is not None or os.path.isdir(path):
@@ -440,10 +449,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
440 stats["files"] += 1 449 stats["files"] += 1
441 stats["scanned_bytes"] += sub["scanned_bytes"] 450 stats["scanned_bytes"] += sub["scanned_bytes"]
442 continue 451 continue
443 if os.path.getsize(p) > max_inflate: 452 b = _read_carved(p, max_inflate)
453 if b is None:
444 continue 454 continue
445 with open(p, "rb") as f:
446 b = f.read(max_inflate + 1)
447 stats["files"] += 1 455 stats["files"] += 1
448 stats["scanned_bytes"] += len(b) 456 stats["scanned_bytes"] += len(b)
449 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the 457 # As in scan_rpf: a 0DRPz resource that needs a continuation takes the next stream, when the
@@ -480,8 +488,9 @@ def scan_path(path, start=None, limit=None, max_inflate=CAP, collect=None, *, di
480 magic = f.read(4) 488 magic = f.read(4)
481 if magic == b"9FPR": 489 if magic == b"9FPR":
482 return scan_rpf(path, start, limit, max_inflate, collect) 490 return scan_rpf(path, start, limit, max_inflate, collect)
483 with open(path, "rb") as f: 491 b = _read_carved(path, max_inflate)
484 b = f.read(max_inflate + 1) 492 if b is None:
493 return [], {"path": os.path.abspath(path), "files": 0, "scanned_bytes": 0}
485 row = parse_resource(b, collect) 494 row = parse_resource(b, collect)
486 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [], 495 return ([dict(row, offset=0, size=len(b), file=os.path.basename(path))] if row else [],
487 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)}) 496 {"path": os.path.abspath(path), "files": 1, "scanned_bytes": len(b)})
@@ -742,7 +751,7 @@ def _write_reports(a, rows, stats, agg):
742 summary["versions"] = sorted({r["version"] for r in rows}) 751 summary["versions"] = sorted({r["version"] for r in rows})
743 doc = {"summary": summary, "resources": rows} 752 doc = {"summary": summary, "resources": rows}
744 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) 753 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
745 with open(a.out, "w", encoding="utf-8") as f: 754 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
746 json.dump(doc, f, indent=1, sort_keys=True) 755 json.dump(doc, f, indent=1, sort_keys=True)
747 if a.csv: 756 if a.csv:
748 cols = ["source", "offset", "size", "signature", "version", "kind", "structs", "enums", "blocks", 757 cols = ["source", "offset", "size", "signature", "version", "kind", "structs", "enums", "blocks",
@@ -763,7 +772,7 @@ def _write_reports(a, rows, stats, agg):
763 w.writerow(r) 772 w.writerow(r)
764 if agg is not None: 773 if agg is not None:
765 os.makedirs(os.path.dirname(os.path.abspath(a.archetypes_out)), exist_ok=True) 774 os.makedirs(os.path.dirname(os.path.abspath(a.archetypes_out)), exist_ok=True)
766 with open(a.archetypes_out, "w", encoding="utf-8") as f: 775 with open(a.archetypes_out, "w", encoding="utf-8", newline="\n") as f:
767 json.dump(agg.to_json(), f, indent=1, sort_keys=True) 776 json.dump(agg.to_json(), f, indent=1, sort_keys=True)
768 summary["archetype_file"] = agg.to_json()["summary"] 777 summary["archetype_file"] = agg.to_json()["summary"]
769 return summary 778 return summary
diff --git a/tools/world_lights_paths.py b/tools/world_lights_paths.py
index ee1c78c3d..65bce000b 100644
--- a/tools/world_lights_paths.py
+++ b/tools/world_lights_paths.py
@@ -708,6 +708,15 @@ def summarize(total, entities=None, lights_out=None):
708 return summary 708 return summary
709 709
710 710
711def same_report_path(first, second):
712 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
713 return True
714 try:
715 return os.path.samefile(first, second)
716 except OSError:
717 return False
718
719
711def main(argv=None): 720def main(argv=None):
712 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 721 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
713 ap.add_argument("archive") 722 ap.add_argument("archive")
@@ -727,6 +736,8 @@ def main(argv=None):
727 if a.entities and not os.path.isfile(a.entities): 736 if a.entities and not os.path.isfile(a.entities):
728 print(f"ERROR: {a.entities}: no such file", file=sys.stderr) 737 print(f"ERROR: {a.entities}: no such file", file=sys.stderr)
729 return 2 738 return 2
739 if a.out and a.lights_out and same_report_path(a.out, a.lights_out):
740 ap.error("--out and --lights-out must use different paths")
730 total = scan(a.archive, a.jobs, a.start, a.limit, bool(a.lights_out)) 741 total = scan(a.archive, a.jobs, a.start, a.limit, bool(a.lights_out))
731 summary = summarize(total, a.entities, a.lights_out) 742 summary = summarize(total, a.entities, a.lights_out)
732 text = json.dumps(summary, indent=1, sort_keys=True) 743 text = json.dumps(summary, indent=1, sort_keys=True)
diff --git a/tools/world_names.py b/tools/world_names.py
index 4ffe3f01a..06152aac5 100644
--- a/tools/world_names.py
+++ b/tools/world_names.py
@@ -606,7 +606,7 @@ def _write_json(path: str, data: dict) -> None:
606 os.makedirs(directory, exist_ok=True) 606 os.makedirs(directory, exist_ok=True)
607 with tempfile.TemporaryDirectory(dir=directory, prefix=".world-names-") as staging: 607 with tempfile.TemporaryDirectory(dir=directory, prefix=".world-names-") as staging:
608 tmp = os.path.join(staging, "report.json") 608 tmp = os.path.join(staging, "report.json")
609 with open(tmp, "w", encoding="utf-8") as handle: 609 with open(tmp, "w", encoding="utf-8", newline="\n") as handle:
610 json.dump(data, handle, indent=1, sort_keys=True) 610 json.dump(data, handle, indent=1, sort_keys=True)
611 handle.write("\n") 611 handle.write("\n")
612 os.replace(tmp, path) 612 os.replace(tmp, path)
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py
index edcc79a8b..e8fcefde3 100644
--- a/tools/xdxr_bvh.py
+++ b/tools/xdxr_bvh.py
@@ -740,11 +740,15 @@ def check_build(directory, rays=300, seed=1):
740 return [f"no cases in {directory}"] 740 return [f"no cases in {directory}"]
741 problems = [] 741 problems = []
742 cases = {n: _load_case(directory, n) for n in names} 742 cases = {n: _load_case(directory, n) for n in names}
743 mem = Memory()
744 for n, (desc, data) in cases.items():
745 mem.place(desc["address"], data)
746 rng = random.Random(seed) 743 rng = random.Random(seed)
747 for n, (desc, data) in cases.items(): 744 for n, (desc, data) in cases.items():
745 # An in-place update leaves two dumps at one address (before and after): the case being checked comes first,
746 # so its own bytes answer reads there.
747 mem = Memory()
748 mem.place(desc["address"], data)
749 for other, (odesc, odata) in cases.items():
750 if other != n:
751 mem.place(odesc["address"], odata)
748 errs = validate(data, expect_bottom=desc["kind"] == "blas") 752 errs = validate(data, expect_bottom=desc["kind"] == "blas")
749 problems += [f"{n}: {e}" for e in errs] 753 problems += [f"{n}: {e}" for e in errs]
750 if desc["kind"] == "blas": 754 if desc["kind"] == "blas":
diff --git a/viewer/index.html b/viewer/index.html
index 455bb664f..8b04c6fe4 100644
--- a/viewer/index.html
+++ b/viewer/index.html
@@ -148,7 +148,16 @@ function buildTestChunk([cx, cz, size]) {
148} 148}
149 149
150// ---------- scene ---------- 150// ---------- scene ----------
151const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" }); 151let renderer;
152try {
153 renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
154} catch (error) {
155 const start = document.getElementById("start");
156 start.setAttribute("role", "alert");
157 start.style.cursor = "default";
158 start.textContent = "Could not start WebGL. Check that WebGL is enabled, then reload.";
159 throw error;
160}
152renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5)); 161renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
153renderer.setSize(innerWidth, innerHeight); 162renderer.setSize(innerWidth, innerHeight);
154document.body.prepend(renderer.domElement); 163document.body.prepend(renderer.domElement);