upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
committerDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
commit5c1a1fbb6bf6f609eb4e61baa4961ce382743a4e (patch)
treeac8ad90058b97ab241fdc65edae3d4628d20ee1e
parentc45309e29f21c1d5b75678db0e2dc2dd11cff25b (diff)
parent4e390e0871d7265e629b51aca8ff99a15a6a6845 (diff)
Merge main to include the compute Y/Z harness test fix
-rw-r--r--README.md5
-rw-r--r--SECURITY.md64
-rw-r--r--docs/README.md3
-rw-r--r--docs/animation.md7
-rw-r--r--docs/audio.md10
-rw-r--r--docs/d3d12_command_objects.md19
-rw-r--r--docs/d3d12_vulkan.md14
-rw-r--r--docs/design.md32
-rw-r--r--docs/gamedata.md54
-rw-r--r--docs/rbf0.md178
-rw-r--r--docs/textures.md195
-rw-r--r--docs/world.md33
-rw-r--r--docs/world_census.md97
-rw-r--r--make_game.py5
-rw-r--r--runtime/CMakeLists.txt37
-rw-r--r--runtime/src/descriptor_table.h252
-rw-r--r--runtime/src/root_signature.cpp456
-rw-r--r--runtime/src/root_signature.h150
-rw-r--r--runtime/test/descriptor_table_test.cpp234
-rw-r--r--runtime/test/root_signature_oracle_test.cpp120
-rw-r--r--runtime/test/root_signature_test.cpp221
-rw-r--r--runtime/test/shaders/build.py24
-rw-r--r--runtime/test/shaders/check.py6
-rw-r--r--runtime/test/shaders/cs_smem_soffset_imm.asm61
-rw-r--r--runtime/test/vk_texture_test.cpp27
-rw-r--r--runtime/test/vulkan_loader.h11
-rw-r--r--scripts/build_llvm_mc.ps182
-rw-r--r--scripts/build_runtime.ps13
-rw-r--r--scripts/run_gpu_tests.py28
-rw-r--r--tests/conftest.py47
-rw-r--r--tests/semantic/test_mutations.py7
-rw-r--r--tests/semantic/test_scalar_mem_smem.py203
-rw-r--r--tests/test_awc_manifest.py19
-rw-r--r--tests/test_awc_opus.py81
-rw-r--r--tests/test_classify_carve.py152
-rw-r--r--tests/test_gamedata_xml.py211
-rw-r--r--tests/test_gen_d3d12_stubs.py254
-rw-r--r--tests/test_manifest.py34
-rw-r--r--tests/test_mc_command.py61
-rw-r--r--tests/test_rbf0_tree.py321
-rw-r--r--tests/test_root_sig_contract.py110
-rw-r--r--tests/test_rpf9_carve.py33
-rw-r--r--tests/test_rpf_probe.py153
-rw-r--r--tests/test_shader_checks.py6
-rw-r--r--tests/test_shader_ir.py226
-rw-r--r--tests/test_translate.py23
-rw-r--r--tests/test_ttpf_mips.py291
-rw-r--r--tests/test_world_census.py167
-rw-r--r--tools/awc_manifest.py9
-rw-r--r--tools/awc_opus.py32
-rw-r--r--tools/gamedata_xml.py568
-rw-r--r--tools/manifest.py15
-rw-r--r--tools/mc_command.py29
-rw-r--r--tools/rbf0_tree.py554
-rw-r--r--tools/rdna2spirv.py40
-rw-r--r--tools/root_sig_contract.py155
-rw-r--r--tools/rpf9_carve.py4
-rw-r--r--tools/shader_disasm.py26
-rw-r--r--tools/ttpf_mips.py845
-rw-r--r--tools/world_census.py697
60 files changed, 7629 insertions, 172 deletions
diff --git a/README.md b/README.md
index 0de5510c9..516318d86 100644
--- a/README.md
+++ b/README.md
@@ -84,8 +84,9 @@ Your game folder is the one that holds `MicrosoftGame.Config` and the `.rpf` arc
84- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 84- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
85- [Vulkan SDK](https://vulkan.lunarg.com/), for `spirv-as` / `spirv-val`. 85- [Vulkan SDK](https://vulkan.lunarg.com/), for `spirv-as` / `spirv-val`.
86- [LLVM 21+](https://github.com/llvm/llvm-project/releases) with the **AMDGPU target** for `llvm-mc`. The official 86- [LLVM 21+](https://github.com/llvm/llvm-project/releases) with the **AMDGPU target** for `llvm-mc`. The official
87 Windows build has no AMDGPU target: on Windows install `llvm-21` in WSL and set `LLVM_MC` to the whole command, 87 Windows build has no AMDGPU target. On Windows, `scripts\build_llvm_mc.ps1` builds a native `llvm-mc.exe` with it
88 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"` (see 88 (no WSL; needs git and the Visual Studio C++ tools below) and sets `LLVM_MC`. Or install `llvm-21` in WSL and set
89 `LLVM_MC` to the whole command, `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"` (see
89 [docs/design.md](docs/design.md#disassembling-shaders)). On Linux, `llvm-mc` on PATH is enough. 90 [docs/design.md](docs/design.md#disassembling-shaders)). On Linux, `llvm-mc` on PATH is enough.
90- Visual Studio 2022 with **Desktop development with C++**, for the runtime stage. 91- Visual Studio 2022 with **Desktop development with C++**, for the runtime stage.
91- [ffmpeg](https://ffmpeg.org/download.html) on PATH (optional: decodes the XMA2 streams, and required for `--wav`). 92- [ffmpeg](https://ffmpeg.org/download.html) on PATH (optional: decodes the XMA2 streams, and required for `--wav`).
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 000000000..7de12a508
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,64 @@
1# Security
2
3Leonida builds everything from the player's own copy, so the two things that can hurt the project are a
4security bug in the tools and game data that reaches the repository. This page covers both.
5
6## Report it privately
7
8Never put the details in a public issue, pull request, comment or Discord channel. Quoting the problem in public
9spreads it further.
10
11- **Preferred:** the repository's **Security** tab → **Advisories** → **Report a vulnerability**. Only the
12 maintainers see it.
13- **If that button is missing:** ask a maintainer for a private channel on [Discord](https://discord.gg/rexed).
14 Your first message should say only that you have something to report, with no details.
15
16Say what you found, where (file, commit, pull request or issue number) and when you noticed it. Don't attach the
17file itself.
18
19## Game data in the repository
20
21This covers everything [CONTRIBUTING.md](CONTRIBUTING.md) rules out: archives, the executable or DLLs, carved
22files, shaders in any form (DXBC, FSSM, disassembly, SPIR-V), textures, models, audio, videos, keys, and logs or
23reports that quote any of them. It applies wherever it shows up: a commit, a branch, a pull request, an issue or
24a comment attachment.
25
26**If you see it:** report it privately as above. Don't download it, mirror it, fork the repository to keep it,
27or comment on the pull request or issue that holds it.
28
29**If you pushed it yourself:**
30
311. Report it privately right away, even if you have already deleted the file. A later commit that deletes a file
32 leaves it in the history.
332. Don't push again to fix it, and don't open another pull request. The maintainers rewrite the history once.
343. If it is in your own fork, delete the fork or clean it the same way.
35
36**What the maintainers do:**
37
381. Close or merge the open pull requests that touch the affected history, then rewrite every ref with
39 [git-filter-repo](https://github.com/newren/git-filter-repo) (2.47 or later, `--sensitive-data-removal`,
40 `--invert-paths --path <file>` for each path the file ever had) and check that the data is gone.
412. Force-push with `git push --force --mirror origin`. Pull request refs are read-only and keep the old history.
423. Ask GitHub Support to dereference or delete the affected pull requests and to remove cached views. Give the
43 repository name, the number of affected pull requests and the first changed commit from the git-filter-repo
44 output.
454. Ask the owners of forks that contain the commits to delete them.
465. Hide or delete issue and comment attachments that hold the data.
476. Tell contributors to re-clone or rebase onto the new history. A `git pull` and `git push` from an old clone
48 puts the data back.
49
50## Security bugs in the tools
51
52The tools and the runtime read large binary files and run external programs (`git`, `llvm-mc`, `spirv-as`,
53`ffmpeg`). In scope:
54
55- A file in a game folder that makes a tool write outside `--out` or `--work`, or run a command it shouldn't.
56- Unsafe parsing in `tools/` or `runtime/` (for example `eval`, path traversal, or unchecked sizes and offsets).
57- The build downloading or running anything other than the pinned `third_party/rpf9-explorer` submodule.
58- `viewer/serve.py` being reachable from anywhere but `127.0.0.1`.
59- CI workflows that expose tokens or run untrusted code with write access.
60
61Out of scope: the game itself, Xbox or Rockstar services, and any copy protection. Leonida does not work around
62protection, and reports that ask it to are closed.
63
64Only the latest `main` gets fixes.
diff --git a/docs/README.md b/docs/README.md
index 0ecfe13a6..3facc8195 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -21,9 +21,10 @@ method, scope and caveats. No game data is included.
21| [animation.md](animation.md) | 130,470 `anim.rpf` streams, 95.4% readable; 1,126 rig sets / 6,677 source-to-rig entries / 3,669 rigs. | 21| [animation.md](animation.md) | 130,470 `anim.rpf` streams, 95.4% readable; 1,126 rig sets / 6,677 source-to-rig entries / 3,669 rigs. |
22| [navmesh.md](navmesh.md) | 90,295 `navmeshes.rpf` streams, 97.5% readable; `0DRP` pages, no navmesh-specific magic. | 22| [navmesh.md](navmesh.md) | 90,295 `navmeshes.rpf` streams, 97.5% readable; `0DRP` pages, no navmesh-specific magic. |
23| [bvh.md](bvh.md) | 565,596 `core_bvh4.rpf` streams; 271,627 BVH4 streams and 269,106 instances, prebuilt acceleration data. | 23| [bvh.md](bvh.md) | 565,596 `core_bvh4.rpf` streams; 271,627 BVH4 streams and 269,106 instances, prebuilt acceleration data. |
24| [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container. | 24| [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/XML tree decoder. |
25| [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN. | 25| [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN. |
26| [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. | 26| [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. |
27| [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact. |
27| [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. | 28| [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. |
28| [psin.md](psin.md) | PSIN metadata container: header, section walk, 671 streams in the `script.rpf` carve. | 29| [psin.md](psin.md) | PSIN metadata container: header, section walk, 671 streams in the `script.rpf` carve. |
29| [story.md](story.md) | `story000.rpf` 18.65 GiB mixed: 264 Bink 2 streams / 3.33 GB, 225,281 `RSC8` headers, 442 nested RPF9; `story000_script` PSIN, `shared_minigame` mixed content. | 30| [story.md](story.md) | `story000.rpf` 18.65 GiB mixed: 264 Bink 2 streams / 3.33 GB, 225,281 `RSC8` headers, 442 nested RPF9; `story000_script` PSIN, `shared_minigame` mixed content. |
diff --git a/docs/animation.md b/docs/animation.md
index 744d86e79..8d082eb24 100644
--- a/docs/animation.md
+++ b/docs/animation.md
@@ -224,6 +224,13 @@ The first rig-set block starts at 0x0045. The tag/length layout is visible direc
224 `deformation[2]` (1,702), `identity` (1,109), `pose` (938), `pose.ragdoll.post` (160), `facial` (152), and 224 `deformation[2]` (1,702), `identity` (1,109), `pose` (938), `pose.ragdoll.post` (160), `facial` (152), and
225 ten smaller values. 225 ten smaller values.
226 226
227The grammar-driven tree decoder (`tools/rbf0_tree.py`; `docs/rbf0.md` section 9) parses the same 1,348,436-byte
228blob to its last byte and confirms the counts above: 9 descriptors, 28,962 elements, 20,031 text records, 1,126
229string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes
230on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group`
231text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field
232semantics and the rig-to-skeleton link remain unresolved.
233
227Mapping to the name tables: 234Mapping to the name tables:
228 235
229- The 2,298 distinct `pack:/...` paths resolve to a stored joaat32 stem hash for **1,901** names (82.7%); 236- The 2,298 distinct `pack:/...` paths resolve to a stored joaat32 stem hash for **1,901** names (82.7%);
diff --git a/docs/audio.md b/docs/audio.md
index dcf8fee7a..6799be83a 100644
--- a/docs/audio.md
+++ b/docs/audio.md
@@ -99,7 +99,13 @@ then 16 bytes per channel:
99At the `0x55` data offset, each chunk starts with a 24-byte record per channel. The record's `+4` word is the 99At the `0x55` data offset, each chunk starts with a 24-byte record per channel. The record's `+4` word is the
100channel's subblock count and `+8` is a repeated-prefix sample count to skip. The channel data are its run of 100channel's subblock count and `+8` is a repeated-prefix sample count to skip. The channel data are its run of
1012048-byte subblocks after the 2048-aligned header. The skipped samples repeat the previous chunk's tail, so the 1012048-byte subblocks after the 2048-aligned header. The skipped samples repeat the previous chunk's tail, so the
102exporter drops whole packets until the count is consumed. Each Opus channel becomes one mono Ogg Opus file. 102exporter drops whole packets until the count is consumed. Each descriptor channel becomes one Ogg Opus file.
103
104The descriptor's `channels` field is the number of channel groups, not necessarily the packet channel count.
105An Opus packet's TOC stereo bit (`packet[0] & 0x04`) gives the real count, and the descriptor's `samples` field
106counts interleaved samples across those packet channels. The exporter therefore writes a stereo Ogg with
107`OpusHead channels=2` and `samples / 2` as the end granule when the packets are stereo; mono groups keep their
108count unchanged. Reading `samples` as a frame count produces a file that reports twice its real duration.
103 109
104## What the exporters write 110## What the exporters write
105 111
@@ -170,6 +176,8 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru
170- 300 random Opus streams decode with ffmpeg with no errors; their lengths match the declared sample counts. 176- 300 random Opus streams decode with ffmpeg with no errors; their lengths match the declared sample counts.
171- All 1,818 XMA2 streams decode after `rpf9dump xma`. 177- All 1,818 XMA2 streams decode after `rpf9dump xma`.
172- A 4-channel streamed-music bank gives four 42.0 s mono channels with real levels and no decoder errors. 178- A 4-channel streamed-music bank gives four 42.0 s mono channels with real levels and no decoder errors.
179- A 1-channel streamed-music descriptor can carry stereo Opus packets; it exports as one stereo Ogg with the
180 interleaved sample count halved, and a 3-channel descriptor with stereo packets exports three stereo Oggs.
173- All exported WAVs decode. Codec 2 values are stored as-is, so a float WAV can exceed ±1. 181- All exported WAVs decode. Codec 2 values are stored as-is, so a float WAV can exceed ±1.
174 182
175The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or 183The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or
diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md
index 27e8986f4..a064eb5bd 100644
--- a/docs/d3d12_command_objects.md
+++ b/docs/d3d12_command_objects.md
@@ -423,17 +423,14 @@ command object.
423| Builder's internal field layout (`+0x18`, `+0x30`, `+0x140`, `+0x344`, `+0x350`, `+0x544`) | No header or symbol; the helper's writes prove the contract is wider than the public vtable, but not what the fields mean. | 423| Builder's internal field layout (`+0x18`, `+0x30`, `+0x140`, `+0x344`, `+0x350`, `+0x544`) | No header or symbol; the helper's writes prove the contract is wider than the public vtable, but not what the fields mean. |
424| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it. | 424| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it. |
425 425
426### 5.4 A concrete current gap: GCL8 426### 5.4 GCL8 (resolved in PR #164)
427 427
428The shipped builder's rehydrate exports name `ID3D12GraphicsCommandList8`, and 428The shipped builder's rehydrate exports name `ID3D12GraphicsCommandList8`, and
429`OMSetFrontAndBackStencilRef` is public GCL8 at slot 81. The repository's command-list class is 429`OMSetFrontAndBackStencilRef` is public GCL8 at slot 81. **PR #164 adds the public GCL8 interface**
430`ID3D12GraphicsCommandList7` (`runtime/shims/d3d12_com.cpp:57-61`), so it cannot answer 430to `runtime/shims/d3d12_com.cpp`: it records the front/back values, resets them in `Reset`, answers
431`IID_ID3D12GraphicsCommandList8` and has no slot 81. `d3d12_vulkan.md` §4's table says the 431`IID_ID3D12GraphicsCommandList8`, and registers the `d3d12_gcl8` CTest (9/9). The values are recorded
432command list "supports … front/back stencil ref", but no such implementation exists in 432but not applied because this layer still has no pipeline/draw path. It does **not** close the
433`runtime/` (a source grep finds no `OMSetFrontAndBackStencilRef` or front/back stencil command). 433builder's `+0x490` gap, but a GCL8 pointer is now served instead of refused.
434Adding the public GCL8 interface is a small, justified runtime change: one method, one standard
435IID, no Xbox extension. It would not close the builder's `+0x490` gap, but it would let a GCL8
436pointer be served instead of refused.
437 434
438## 6. Return conventions 435## 6. Return conventions
439 436
@@ -463,8 +460,8 @@ than invent slots.
463 builder validates its inputs before reaching the dispatch, use a descriptor shaped like the 460 builder validates its inputs before reaching the dispatch, use a descriptor shaped like the
464 one its own `GetRaytracingAccelerationStructurePrebuildInfo` accepts (prior art measured a 461 one its own `GetRaytracingAccelerationStructurePrebuildInfo` accepts (prior art measured a
465 3,000-vertex triangle geometry; the prebuild answer is 204,800 bytes / 128,704 scratch). 462 3,000-vertex triangle geometry; the prebuild answer is 204,800 bytes / 128,704 scratch).
4662. **Add GCL8 to the runtime** (public, one method, slot 81) so the rehydrate entry points can 4632. **GCL8 is now implemented** in PR #164 (public slot 81, recorded/reset, CTest 9/9); the
467 be handed a real object. This is a code change for a separate PR, not this document. 464 remaining builder gap is the `+0x490` method.
4683. **When the executable appears, trace the four creation calls first.** Per-slot counters on 4653. **When the executable appears, trace the four creation calls first.** Per-slot counters on
469 device slots 8/9/12/36, then queue slots 10/14/15, fence slots 8/9/10, and every slot beyond 466 device slots 8/9/12/36, then queue slots 10/14/15, fence slots 8/9/10, and every slot beyond
470 the public chain. The first `PresentX` call and the queue vtable tail are the only way to 467 the public chain. The first `PresentX` call and the queue vtable tail are the only way to
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 5e0bde9bc..a232c361b 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -383,7 +383,8 @@ This is the least verifiable part of the layer. D3D12 gives the application a ro
383turns it into the user SGPRs (`s0..s31`) that the shader reads. The translator already copies those 32 dwords from 383turns it into the user SGPRs (`s0..s31`) that the shader reads. The translator already copies those 32 dwords from
384push constants into `s0..s31`. The layer must produce them. 384push constants into `s0..s31`. The layer must produce them.
385 385
386The default mapping (**Assumption**) follows root parameter order: 386The default mapping (implemented by `rt::rootsig::pack` in `runtime/src/root_signature.{h,cpp}`) follows root
387parameter order:
387 388
388| Root parameter | User-data dwords | 389| Root parameter | User-data dwords |
389|---|---| 390|---|---|
@@ -395,6 +396,15 @@ The default mapping (**Assumption**) follows root parameter order:
395Before the draw/dispatch, the layer copies the current root arguments into a 32-dword block in that order and 396Before the draw/dispatch, the layer copies the current root arguments into a 32-dword block in that order and
396uploads it as push constants. Missing parameters are zero. 397uploads it as push constants. Missing parameters are zero.
397 398
399Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-dword D3D12 cost limit, is
400refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through
401`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour.
402
403Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's
404`user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails
405the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not
406a rendered frame — is the acceptance gate for the mapping above.
407
398**Root-signature flag quirk.** Prior art measured Xbox root-signature descriptors carrying flags `0x03000000`; the 408**Root-signature flag quirk.** Prior art measured Xbox root-signature descriptors carrying flags `0x03000000`; the
399PC serializer rejects them with `E_INVALIDARG` because its flags live in the low 16 bits. Clear the high byte on a 409PC serializer rejects them with `E_INVALIDARG` because its flags live in the low 16 bits. Clear the high byte on a
400private copy before calling the host serializer/deserializer; never modify the game's descriptor. The meaning of the 410private copy before calling the host serializer/deserializer; never modify the game's descriptor. The meaning of the
@@ -756,7 +766,7 @@ store, load, mesh, geometry and BVH tests; this layer is the other half.
756| `s0..s31` user data | Root signature state at draw/dispatch: root constants copied, root CBV/SRV/UAV addresses and descriptor-table base addresses as 64-bit console VAs. Mapping per section 3.5; absent parameters zero. | 766| `s0..s31` user data | Root signature state at draw/dispatch: root constants copied, root CBV/SRV/UAV addresses and descriptor-table base addresses as 64-bit console VAs. Mapping per section 3.5; absent parameters zero. |
757| `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. | 767| `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. |
758| `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. | 768| `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. |
759| Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. | 769| Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. Implemented in `runtime/src/descriptor_table.h` (`DescriptorTable`). The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. |
760| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays, as the translator expects. | 770| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays, as the translator expects. |
761| Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. | 771| Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. |
762| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. | 772| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. |
diff --git a/docs/design.md b/docs/design.md
index dd1172545..debd059c0 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -94,11 +94,11 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b
94| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` | 94| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `<work>\assets\<archive>\textures\` |
95| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). 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 the BCPack next step are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` | 95| World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). 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 the BCPack next step are in [textures.md](textures.md). | `<work>\assets\ttpf\<pool>\` + `manifest.json` |
96| 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. 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\` | 96| 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. 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\` |
97| 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 trimmed to the declared sample count. 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 mono Ogg Opus per channel (3,008 banks contain music). Checked: a 4-channel music bank gives four 42.0 s channels with real levels and no decoder errors. 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\` | 97| 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 trimmed to the declared sample count. 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\` |
98| World placement | **Measured in `levels.rpf`:** map files occupy a continuous band from ~7.5 to ~62.9 GiB; 9,918 map files / 680,228 entities in 29 GiB of the 57 GiB band (50.9%, lower bound; block estimate 16.0k-39.6k maps / 1.03M-2.64M entities). `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/GUID/LOD fields; names and most archetypes are hash-only. | `tools\world_index.py`; [world.md](world.md) | 98| 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/GUID/LOD fields; names and most archetypes are hash-only. | `tools\world_index.py`, `tools\world_census.py`; [world.md](world.md), [world_census.md](world_census.md) |
99| 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) | 99| 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) |
100| 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) | 100| 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) |
101| RBF0 | 1,263 `data.rpf` resources, 475,461 elements, 44,887 descriptors and 340,859 strings. Inline record stream with no section table; UI/Scaleform (`rage__fwui*`, screens, subtitles, settings). The `anim.rpf` tail uses the same format (`rage__crRigSetManager`). | `tools\rbf0_index.py`; [rbf0.md](rbf0.md) | 101| RBF0 | 1,263 `data.rpf` resources, 475,461 elements, 44,887 descriptors and 340,859 strings. Inline record stream with no section table; UI/Scaleform (`rage__fwui*`, screens, subtitles, settings). The `anim.rpf` tail uses the same format (`rage__crRigSetManager`). `tools/rbf0_tree.py` decodes every resource to a strict JSON/XML element, value and text tree. | `tools\rbf0_index.py`, `tools\rbf0_tree.py`; [rbf0.md](rbf0.md) |
102| Gamedata | `common.rpf`: 954 streams (5,647,255 stored / 50,231,123 inflated), 85.5% readable; 266 XML documents / 118 roots (time/weather, vehicles/handling, peds/schedules, tuning, manifests, world/navigation). No RBF0/PSIN. | `tools\gamedata_index.py`; [gamedata.md](gamedata.md) | 102| Gamedata | `common.rpf`: 954 streams (5,647,255 stored / 50,231,123 inflated), 85.5% readable; 266 XML documents / 118 roots (time/weather, vehicles/handling, peds/schedules, tuning, manifests, world/navigation). No RBF0/PSIN. | `tools\gamedata_index.py`; [gamedata.md](gamedata.md) |
103| PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSNS` is high-entropy; no plaintext scripts or names. | `tools/psin_index.py`; [psin.md](psin.md) | 103| PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSNS` is high-entropy; no plaintext scripts or names. | `tools/psin_index.py`; [psin.md](psin.md) |
104| Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) | 104| Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) |
@@ -207,14 +207,14 @@ How the generated SPIR-V expects the runtime to work:
207| 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. 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. | 207| 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. 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. |
208| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + signed 12-bit offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. | 208| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + signed 12-bit offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. |
209| 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. | 209| 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. |
210| 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). See *Buffer bounds checking* below for `num_records` checks. | 210| 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`): the address is base + sOFF + IMM + 4·i for dword i. Measured on AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: soffset 8 + imm 4 reads +12 (`s_buffer_load_dword`, `x2`, `x4`, `x8`); `s_load_dword*` with both offsets wasn't measured and gets the same rule because it shares the SMEM encoding. The translator used to drop the immediate of that form. The translator's arithmetic is checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemSoffsetImmTranslatorTests`); a GPU test, `runtime/test/shaders/cs_smem_soffset_imm.asm`, is in `check.py` and `scripts/run_gpu_tests.py`. Known remaining differences, from the same measurement of `s_buffer_load*`: the hardware truncates base, sOFF and IMM each to a multiple of 4 and returns 0 past NUM_RECORDS; the translator does neither yet. See *Buffer bounds checking* below for the MUBUF `num_records` checks. |
211| 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/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. | 211| 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/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. |
212| 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. | 212| 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. |
213| 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**: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. | 213| 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**: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. |
214| 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. | 214| 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. |
215| 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.** | 215| 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.** |
216| 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. | 216| 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. |
217| 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, non-`off` `pos1..pos2` components default to `ClipDistance`. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | 217| 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`. |
218| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/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/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); **not yet GPU-verified**. | 218| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/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/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); **not yet GPU-verified**. |
219| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | 219| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). |
220| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. Not yet GPU-tested. | 220| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. Not yet GPU-tested. |
@@ -241,7 +241,7 @@ How the generated SPIR-V expects the runtime to work:
241| 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. | 241| 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. |
242| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). | 242| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). |
243| 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. | 243| 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. |
244| 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 MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `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). For `pos1..pos3` exports, because `PA_CL_VS_OUT_CNTL` is not in the shader blob, the clip/cull/misc split and component indices follow `OSG1` (assuming contiguous hardware packing clip→cull as in Mesa/LLPC); `PointSize`/`EdgeFlag`/`ShadingRate` in `pos1` misc are not emitted as Vulkan built-ins, and in mesh shaders a misc `OSG1` entry shifts clip/cull to `pos2..pos3` without emitting per-vertex `Layer`/`ViewportIndex`. | 244| 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 MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `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). For `pos1..pos3` exports, because `PA_CL_VS_OUT_CNTL` is not in the shader blob, the clip/cull/misc split and component indices follow `OSG1` (assuming contiguous hardware packing clip→cull as in Mesa/LLPC), and without `OSG1` declaring `SV_ClipDistance`/`SV_CullDistance` any `pos1..pos3` export is discarded rather than guessed; `PointSize`/`EdgeFlag`/`ShadingRate` in `pos1` misc are not emitted as Vulkan built-ins, and in mesh shaders a misc `OSG1` entry shifts clip/cull to `pos2..pos3` without emitting per-vertex `Layer`/`ViewportIndex`. |
245| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. | 245| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. |
246| 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. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. 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`. | 246| 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. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. 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`. |
247| 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 as the workgroup index. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | 247| 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 as the workgroup index. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). |
@@ -271,13 +271,31 @@ cross-half code on 32-wide subgroups.
271 271
272The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package 272The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package
273installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no 273installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no
274`llvm-mc.exe`, so on Windows run it from WSL and give `LLVM_MC` the whole command: 274`llvm-mc.exe`. On Windows, either build a native one or run it from WSL.
275
276Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone
277with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools
278don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in
279`%LOCALAPPDATA%\Leonida\llvm-mc`) and sets `LLVM_MC` for the user. It needs git, Python and Visual Studio with the C++
280x64 tools, about 2 GB of temporary space and 20-40 minutes. `-Dest`, `-NoEnv`, `-Keep` and `-Version` change the
281defaults.
282
283```
284powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1
285python -I make_game.py --game "D:\path\to\your\package" --stages shaders
286```
287
288WSL: install `llvm-21` and give `LLVM_MC` the whole command:
275 289
276``` 290```
277set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc 291set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc
278python -I make_game.py --game "D:\path\to\your\package" --stages shaders 292python -I make_game.py --game "D:\path\to\your\package" --stages shaders
279``` 293```
280 294
295The same form works in every tool that reads `LLVM_MC`. `tools/mc_command.py` splits it for `shader_disasm.py`,
296the tests, `runtime/test/shaders/build.py` and `scripts/run_gpu_tests.py`; the assembler callers pass the assembly
297on stdin, so a WSL command never receives a Windows file path.
298
281`shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run 299`shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run
282with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: 300with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL:
283 301
diff --git a/docs/gamedata.md b/docs/gamedata.md
index 8e7f73847..88b8f57e6 100644
--- a/docs/gamedata.md
+++ b/docs/gamedata.md
@@ -176,6 +176,60 @@ A runtime consumer needs:
176- strict handling of the 9 tail-only and 1 unattributed blocks: they are incomplete evidence, not documents 176- strict handling of the 9 tail-only and 1 unattributed blocks: they are incomplete evidence, not documents
177 to guess at. 177 to guess at.
178 178
179## XML catalog
180
181`tools/gamedata_xml.py` turns a carve into a per-file and per-root catalog. It is stdlib-only and rebuilds
182multi-stream documents with `gamedata_index.py`, so it reads the same 267 XML payloads the index reports:
183
184```powershell
185python -I tools/gamedata_xml.py <work>\carve\common --json xml.json --csv xml.csv --check
186```
187
188The file rows carry offset/bytes/chunks, root, category, element count, maximum depth, attribute names, `$(name)`
189and `platform:/` counts, include-like counts and the well-formed/fragment flags. The root rows add the
190element-name and attribute histograms and the reference targets. `--check` separates a rootless fragment, a
191tail-only document and a malformed document instead of treating all three as parse failures.
192
193Measured over the 267 payloads (43,284,925 B):
194
195| Measure | Value |
196|---|---:|
197| Well-formed | 259 (257 with a declaration, 2 tail-only) |
198| Truncated at the start | 7 |
199| Rootless fragment | 1 |
200| Malformed | 0 |
201| Named roots / catalogued roots | 118 (+1 unattributed) / 118 |
202| Elements / distinct element names | 428,611 / 5,293 |
203| Attribute names / `type` values / `content` kinds | 33 / 318 / 7 |
204| Maximum depth | 17 |
205| Comment starts (all / declaration-bearing) | 507 / 412 |
206| `filename` / `parentPath` / `parentFile` / XInclude | 3,315 / 40 / 3 / 0 |
207| `platform:/` references (levels / other) | 2,674 (2,346 / 328) |
208| `$(common)` / `$(root)` / `$(target)` references | 588 / 28 / 23 |
209
210Macro counts cover all element text; 587 of the 588 `$(common)` hits are in `<filename>` elements, which is the
211filename-only bucket in the table above.
212
213The root and element distribution is the one in the tables above: the five repeated roots hold 141 of the 266
214documents, and the element histogram is dominated by the general node names `Item` (118,179), `item` (16,316)
215and `Name` (12,850). The long tail is per-system parameter names; the manifest and timecycle names are a small
216part of it. A category is a dispatch bucket, not a schema: for the 266 documents the catalog reproduces the
217file and root counts in the functional table and assigns each root one category. No root has more than one
218handler.
219
220Reference handling is narrow. Every `$(...)` and `platform:/` string is element text, not an attribute; no
221document uses XInclude. The macro alphabet is `$(common)`, `$(target)` and `$(root)`, and the platform targets
222split into `platform:/levels/` and everything else. `filename` is the only include-like element with a large
223population; `parentPath`/`parentFile` are the only relative references outside it. A resolver therefore needs
224four prefix rules and a content-set/mount walk, not a general include processor.
225
226A runtime dispatcher needs the 118-root table (or an RTTI class bridge), the 12 category buckets, the 318-value
227`type` registry, the 33-name attribute whitelist, the `content=` array decoders and a streaming reader for the
22814 MB document. It also needs to mark the 9 tail-only documents and the one rootless block as incomplete
229evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only
230aggregate counts and schema/root/element/attribute names belong in git; the CSV/JSON, the element values, the
231`type`/`content` values and per-file paths stay on the local machine. The tests are synthetic.
232
179## Relationship to `data.rpf` and `script.rpf` 233## Relationship to `data.rpf` and `script.rpf`
180 234
181| Archive | Size | Streams | Inflated | Dominant payloads | XML | `RBF0` | `PSIN` | 235| Archive | Size | Streams | Inflated | Dominant payloads | XML | `RBF0` | `PSIN` |
diff --git a/docs/rbf0.md b/docs/rbf0.md
index a07d7962e..5322fda3d 100644
--- a/docs/rbf0.md
+++ b/docs/rbf0.md
@@ -15,6 +15,7 @@ payload, carved stream, path list or string dump is committed here.
15| Is there a name or hash table? | **No.** Schema names are inline UTF-8 with a u16 length. There is no hash table and no readable hash string. The 64-bit integers are mostly small codes; none is identified as a name hash. | 15| Is there a name or hash table? | **No.** Schema names are inline UTF-8 with a u16 length. There is no hash table and no readable hash string. The 64-bit integers are mostly small codes; none is identified as a name hash. |
16| What do the streams carry? | UI framework and UI data schemas, movie-subtitle containers, and three tuning/config schemas. No animation, mesh or audio payload. | 16| What do the streams carry? | UI framework and UI data schemas, movie-subtitle containers, and three tuning/config schemas. No animation, mesh or audio payload. |
17| Is it the same format as the `anim.rpf` rig blob? | **Yes, same container and grammar.** That blob is one `rage__crRigSetManager` resource; its 9 descriptors and 28,962 elements parse with the same rules. | 17| Is it the same format as the `anim.rpf` rig blob? | **Yes, same container and grammar.** That blob is one `rage__crRigSetManager` resource; its 9 descriptors and 28,962 elements parse with the same rules. |
18| Can it be decoded to a tree? | **Yes.** `tools/rbf0_tree.py` decodes all 1,263 resources to element/value/text trees. Unknown descriptors and record types fail closed. |
18| Compression inside `RBF0`? | **None observed.** The only compression is the outer RPF9 zlib framing. | 19| Compression inside `RBF0`? | **None observed.** The only compression is the outer RPF9 zlib framing. |
19 20
20## 1. Method and coverage 21## 1. Method and coverage
@@ -229,6 +230,12 @@ The rig blob's nine descriptors are `rage__crRigSetManager`, `RigSet`, `Item`, `
229strings. The element words are again `0, 0, attrs` (27,836 with 0, 1,126 with 1) and there are no attribute 230strings. The element words are again `0, 0, attrs` (27,836 with 0, 1,126 with 1) and there are no attribute
230mismatches. 231mismatches.
231 232
233The grammar-driven tree decoder in section 9 reproduces those counts and resolves the nesting. The root contains
234one `RigSet`, whose 1,126 `Item` elements each carry one `key` string attribute and one `Entries` element. Under
235`Entries`, the 6,677 entry `Item` elements contain a `Dictionary` text, a `Rig` text, a `Group` text and a
236`Priority` integer after the three child elements. Maximum element depth is 6. The decoder does not resolve the
237rig-to-skeleton link.
238
232So the container, prologue, record grammar and element header are shared. The difference is the root schema: 239So the container, prologue, record grammar and element header are shared. The difference is the root schema:
233`anim.rpf` carries a rig-set manager, while `data.rpf` carries UI and config schemas. No `data.rpf` resource has 240`anim.rpf` carries a rig-set manager, while `data.rpf` carries UI and config schemas. No `data.rpf` resource has
234the rig-set root, an `anim/` string or a `SKEL_` string. The `data.rpf` RBF0s are not animation data. 241the rig-set root, an `anim/` string or a `SKEL_` string. The `data.rpf` RBF0s are not animation data.
@@ -263,7 +270,163 @@ the rig-set root, an `anim/` string or a `SKEL_` string. The `data.rpf` RBF0s ar
2637. **Keep the compression boundary explicit.** The RBF0 bytes are uncompressed after the outer RPF9 zlib inflate. 2707. **Keep the compression boundary explicit.** The RBF0 bytes are uncompressed after the outer RPF9 zlib inflate.
264 There is no byte-blob value type and the parse consumes every byte, so there is no place for a nested frame. 271 There is no byte-blob value type and the parse consumes every byte, so there is no place for a nested frame.
265 272
266## 9. Reproduction 273The chunk join, descriptor/type pairing, width selection, attribute count and tree build are implemented in
274`tools/rbf0_tree.py`; section 9 records what that decoder measured and what it still cannot name.
275
276## 9. Tree decoder
277
278`tools/rbf0_tree.py` turns the record stream into a tree. It reads a carve directory or one complete resource,
279joins the 64 KiB continuations, and writes one JSON file with one object per resource, plus optional per-resource
280generic XML files. It is stdlib-only and uses no schema file.
281
282The full `data.rpf` carve decodes **1,263 of 1,263 resources with status `ok`**, and the totals are identical to the
283index counts in section 3: 475,461 elements, 254,935 text records, 85,924 string values, 160,490 value records,
28444,887 descriptors (698 distinct names) and maximum element depth 36. No unknown record type occurs in the corpus.
285
286### 9.1 Grammar used by the decoder
287
288| Bytes | Meaning |
289|---|---|
290| `RBF0` + `FB FF 01 00` | magic and the wide (64-bit integer/float) prologue; without the prologue values are 32-bit |
291| `idx type` | one record; `idx < descriptor_count` reuses a descriptor, `idx == descriptor_count` adds one |
292| `u16 len` + UTF-8 | descriptor name, present only when the record adds a descriptor |
293| `0x00` | element open; three u16 words follow, words 0 and 1 are zero and word 2 is the attribute count |
294| `0x10` | unsigned integer, 8 bytes wide or 4 bytes narrow |
295| `0x20` / `0x30` | true / false, no payload |
296| `0x40` | float, 8 bytes wide or 4 bytes narrow |
297| `0x50` | three floats, 3 x width (not present in this corpus) |
298| `0x60` | string; u16 length followed by that many UTF-8 bytes |
299| `FD FF` | text for the open element; u32 length followed by that many bytes (NUL-terminated in this corpus) |
300| `FF FF` | close the open element |
301
302A descriptor is a name index, not a type declaration. The decoder records the type that introduced the descriptor
303and all later types used with the same index.
304
305In every one of the 1,263 resources, the declared attributes are the first value records of their element: no child
306element or text record precedes them (0 violations). Values after the attribute prefix are content in stream order,
307and a value can follow a child element. A text record attaches to the open element.
308
309### 9.2 Measured tree facts
310
311| Measure | Value |
312|---|---:|
313| Resources decoded | 1,263 / 1,263 `ok` |
314| Elements | 475,461 |
315| Elements with 0 / 1 / 2 declared attributes | 389,525 / 84,541 / 1,395 |
316| Attribute values | 87,331: 85,924 string, 1,111 integer, 296 float |
317| Two-attribute type pairs | float/float 128, string/int 1,111, string/float 40, string/string 116 |
318| Non-attribute values | 73,159: 38,008 float, 28,289 integer, 6,862 boolean |
319| Non-attribute values after a child element | 22,977 |
320| Text records | 254,935, all NUL-terminated |
321| Text-only elements | 254,935; one text record, first content, no child or value |
322| String values | 85,924; all are attributes and none is NUL-terminated |
323| Text / string length | 2-1,006 / 1-126 bytes (the text length includes its trailing NUL) |
324| Descriptor instances reused with more than one type | 564 |
325| Root with an attribute | 1: `rage__SafeframeConfig` |
326| Descriptor names not usable as XML element names | 1: `xmlns:xi` |
327| Unknown record types | 0 |
328
329The single root attribute is `xmlns:xi` on the narrow `rage__SafeframeConfig` resource at archive offset
330`0x1c33e000` (18,317 inflated bytes). The same name is declared as descriptor 1 at offset `0x23` and is used 14 times
331in that resource. It is also the only descriptor name that cannot be used as an XML element name (the `xmlns`
332prefix is reserved), which is why the XML writer uses fixed tags and puts the exact name in a `name` attribute.
333
334Of the 26 text payloads that are not valid UTF-8, all are text records; no string value or descriptor name failed
335a strict UTF-8 decode. The decoder replaces invalid bytes with U+FFFD and sets `utf8_valid: false`; the original
336encoding is not established.
337
338### 9.3 Sample trees
339
340The three samples below are the smallest resources of their root schema that decode completely. Offsets are
341relative to the start of the joined resource.
342
343| Root schema | Archive offset | Inflated | Layout | Descriptors | Elements | Texts | Strings | Depth |
344|---|---|---:|---|---:|---:|---:|---:|---:|
345| `CMovieSubtitleContainer` | `0x9ed7280` | 490 | wide-64 | 13 | 11 | 3 | 3 | 4 |
346| `rage__fwuiPrefab` | `0x11dd8950` | 195 | wide-64 | 5 | 4 | 2 | 1 | 3 |
347| `UIScreen` | `0x12059180` | 385 | wide-64 | 9 | 9 | 6 | 0 | 3 |
348
349`CMovieSubtitleContainer` descriptor table:
350
351| ID | Name | First type | Uses |
352|---:|---|---|---:|
353| 0 | `CMovieSubtitleContainer` | open | 1 |
354| 1 | `TextBlockName` | open | 1 |
355| 2 | `pCutsceneEventArgsList` | open | 1 |
356| 3 | `Item` | open | 3 |
357| 4 | `type` | string | 3 |
358| 5 | `cName` | open | 2 |
359| 6 | `m_cOptionalActor` | open | 2 |
360| 7 | `fSubtitleDuration` | float | 2 |
361| 8 | `pCutsceneEventList` | open | 1 |
362| 9 | `fTime` | float | 1 |
363| 10 | `iEventId` | int | 1 |
364| 11 | `iEventArgsIndex` | int | 1 |
365| 12 | `iObjectId` | int | 1 |
366
367The tree shows the attribute/content split directly:
368
369```
3700x0008 element 0 CMovieSubtitleContainer attrs=0 end 0x01ea
3710x0029 element 1 TextBlockName
3720x0040 text length 8
3730x0050 element 2 pCutsceneEventArgsList
3740x0070 element 3 Item attrs=1
3750x007e value 4 type (string, attribute)
3760x009e element 5 cName
3770x00ad text length 12
3780x00c1 element 6 m_cOptionalActor
3790x00dd value 7 fSubtitleDuration (float, content after the child)
3800x0154 element 8 pCutsceneEventList
3810x0170 element 3 Item attrs=1
3820x018f value 9 fTime (float)
3830x01a0 value 10 iEventId (int)
3840x01b4 value 11 iEventArgsIndex (int)
3850x01cf value 12 iObjectId (int)
3860x01e8 close root; end 0x01ea
387```
388
389The 195-byte `rage__fwuiPrefab` uses descriptor IDs 0-4: root, `Id`, `PrefabObject`, `type` (string) and `Style`.
390Its root is at 0x08; `Id` at 0x22 with a 42-byte text at 0x2e; `PrefabObject` at 0x60 with one attribute `type`
391at 0x76; `Style` at 0x8f with a 25-byte text at 0x9e; root close at 0xc1, end 0xc3.
392
393The 385-byte `UIScreen` uses descriptor IDs 0-8: `UIScreen`, `LayoutParams`, `widthContentMode`,
394`heightContentMode`, `horizontalAlignment`, `verticalAlignment`, `Name`, `Screen` and `ID`. It has nine elements
395and six text leaves; `LayoutParams` contains four text-valued children and the root contains `Name`, `Screen` and
396`ID` siblings. No attribute is present.
397
398### 9.4 Output and failure behavior
399
400JSON carries one object per resource: `offset`, `size`, `chunks`, `layout`, `root_name`, `status`, `error`,
401`descriptors`, `counts` and `tree`. Every node has a `kind` and a byte `offset`. Elements carry `descriptor`,
402`attrs_declared`, `attributes`, ordered `content` and `end`; values carry `descriptor`, `type`, `payload_offset`,
403`size` and `value`; text nodes carry `length`, `nul_terminated`, `text` and `utf8_valid`.
404
405XML is a rendering, not a round-trip. Fixed tags avoid descriptor names that are not legal XML names:
406`<node name="...">`, `<attr>`, `<value>` and `<text>`. A string containing XML markup is escaped by the writer.
407
408The decoder fails closed. An index beyond the current descriptor table, an unknown record type, a non-zero element
409header word, a close or text with no open element, and a truncated payload stop that resource with `status` `bad`
410or `truncated`; the partial tree is kept and no value is invented. `status` `trailing` means the root closed before
411the last byte. The corpus has 0 bad, 0 truncated and 0 trailing resources.
412
413### 9.5 Remaining unknowns
414
415- There is no schema: descriptor names are fields, but value meaning, enum spelling and units are not stored.
416- The prologue's meaning is still not established; the decoder uses it only to select 4- or 8-byte values.
417- Element header words 0 and 1 are zero in all 475,461 elements. Their intended meaning is unknown; the decoder
418 rejects a non-zero value instead of guessing.
419- The attribute rule is measured, not proven universal: every corpus attribute leads its element and every text
420 element is a text-only leaf. The decoder marks `attribute_order_violation`, `multiple_text` and
421 `text_after_child` if a future resource departs from it; the corpus has none of these.
422- The 26 invalid UTF-8 text payloads have no established encoding. The XML writer replaces bad bytes, so it is
423 lossy for those records.
424- `xmlns:xi` is a literal field name. Its namespace meaning is not decoded.
425- `0x50` (three floats) is accepted by the grammar but never occurs in this corpus.
426- No external schema or XSD validates the tree; XML output is a structural rendering only.
427- A resource does not store its archive path. The source label is the carve offset or file name, not a game path.
428
429## 10. Reproduction
267 430
268```powershell 431```powershell
269# Index the archive: CSV or JSON, root/counts/strings; no payload is written 432# Index the archive: CSV or JSON, root/counts/strings; no payload is written
@@ -273,16 +436,23 @@ python -I tools/rbf0_index.py <package>\data.rpf <work>\rbf0.csv --quiet
273# Index a directory of already-carved streams (offsets from leading hex file names) 436# Index a directory of already-carved streams (offsets from leading hex file names)
274python -I tools/rbf0_index.py <work>\data-carve <work>\rbf0.json 437python -I tools/rbf0_index.py <work>\data-carve <work>\rbf0.json
275 438
276# Unit test: synthetic headers only 439# Decode trees from the same carve; JSON plus optional per-resource XML
440python -I tools/rbf0_tree.py <work>\data-carve <work>\rbf0-tree.json
441python -I tools/rbf0_tree.py <work>\data-carve <work>\rbf0-tree.json --xml <work>\rbf0-xml
442python -I tools/rbf0_tree.py <work>\data-carve <work>\subtitle.json --root CMovieSubtitleContainer --limit 1
443
444# Unit tests: synthetic headers and trees only
277python -I tests/test_rbf0_index.py 445python -I tests/test_rbf0_index.py
446python -I tests/test_rbf0_tree.py
278``` 447```
279 448
280The JSON summary carries the corpus totals used above (`streams`, `compressed_bytes`, `inflated_bytes`, 449The JSON summary carries the corpus totals used above (`streams`, `compressed_bytes`, `inflated_bytes`,
281`rbf0.resources`, `rbf0.multi_chunk`, `rbf0.by_root`, `rbf0.size_buckets`, record counts, string categories and 450`rbf0.resources`, `rbf0.multi_chunk`, `rbf0.by_root`, `rbf0.size_buckets`, record counts, string categories and
282keyword occurrences), so the numbers can be re-measured without committing an index. `--all-strings` writes the 451keyword occurrences), so the numbers can be re-measured without committing an index. `--all-strings` writes the
283full readable string list to JSON; that file is game data and must stay out of git. 452full readable string list to JSON; that file is game data and must stay out of git. The tree output and XML files
453contain names and payloads and are game data too.
284 454
285## 10. No-sharing rule 455## 11. No-sharing rule
286 456
287Game files, carved streams, inflated RBF0 blobs, readable string lists, parsed trees and reports that quote them 457Game files, carved streams, inflated RBF0 blobs, readable string lists, parsed trees and reports that quote them
288stay on the machine that owns the package. Do not commit them, attach them to an issue or pull request, or paste 458stay on the machine that owns the package. Do not commit them, attach them to an issue or pull request, or paste
diff --git a/docs/textures.md b/docs/textures.md
index 7ed20c0ae..52b085931 100644
--- a/docs/textures.md
+++ b/docs/textures.md
@@ -16,8 +16,9 @@ field.
16| skipped | 48,220 | 16| skipped | 48,220 |
17 17
18**Bottom line:** the gap is measurable and the codec mapping is certain, but BCPack itself is 18**Bottom line:** the gap is measurable and the codec mapping is certain, but BCPack itself is
19not decodable from public facts. No decoder is added; the next tractable work is the compact 19not decodable from public facts. No BCPack decoder is added. The compact mip chain, which the
20packed tail, not BCPack. 20first measurement called the next tractable work, is now decoded and validated below; the
21remaining gap is BCPack.
21 22
22This is the same 308,895 / 48,220 total already recorded in `docs/design.md`. The recount 23This is the same 308,895 / 48,220 total already recorded in `docs/design.md`. The recount
23splits the 48,220 by cause: the old "(BCPack or unmapped)" label hides 14,713 skips whose 24splits the 48,220 by cause: the old "(BCPack or unmapped)" label hides 14,713 skips whose
@@ -96,8 +97,137 @@ The partial exports are a separate gap. Of the 210,292:
96 97
97The packed-tail gap affects more textures than the BCPack skip count (196,257 partial 98The packed-tail gap affects more textures than the BCPack skip count (196,257 partial
98exports vs 33,507 skips), but it loses only the small mips. It is also not a BCPack problem: 99exports vs 33,507 skips), but it loses only the small mips. It is also not a BCPack problem:
99196,257 textures stop at the last standalone mip because `UsableMipLimit = NonTailMipCount` 100196,257 textures stop at the descriptor's `non_tail` field because `UsableMipLimit =
100for compact profiles, regardless of codec. 101NonTailMipCount` for compact profiles, regardless of codec. The next section measures that
102field against the layout and finds that it is not the tail boundary: most of the "packed
103tail" is standalone mips the reader drops.
104
105## The compact mip chain
106
107The 196,257 partial exports and the 14,030 compact-profile skips are the same layout
108problem, not a codec problem. `tools/ttpf_mips.py` measures and decodes it; the counts below
109come from its `scan` and `check` over the same 57 pools.
110
111### The descriptor mode is a flag plus a tile mode
112
113`TtpfReader` reads the descriptor mode as one number (`b >> 23`) and selects a 64 KiB tile
114only for mode 0. The observed values split into a low flag bit and a 4-bit Gfx10 tile mode at
115bit 1:
116
117| `(mode >> 1) & 0xF` | Gfx10 mode | Tile | Descriptors |
118|---:|---|---:|---:|
119| 0 | `SW_64KB_D` | 64 KiB | 39,283 |
120| 1 | `SW_4KB_S` | 4 KiB | 70,497 |
121| 2 | `SW_4KB_S` | 4 KiB | 195,957 |
122| 3 | `SW_4KB_S` | 4 KiB | 50,811 |
123| 9–12 | array/volume | — | 567 |
124
125Modes 9–12 are exactly the 567 cube descriptors; the other 111 array/volume records use tile
126mode 0 or 1. Bit 0 of the field is independent: modes 4/5 share tile mode 2, 6/7 share tile
127mode 3, and 36/38 share tile modes 2/3. The reader's `mode == 0` test therefore gives a 4 KiB
128layout to modes 1 and 32, which are 64 KiB. Fifteen mode 1/32 descriptors have a known element
129size; all fifteen match a 64 KiB allocation span and one (`maps_4_7` #6034) decodes at
1300.00–0.33 levels (see below). The other 19 mode 1/32 records are the unknown-format ones in
131the table below.
132
133### The layout is the AMD mip tail
134
135The compact profile is the Gfx10 mip chain: standalone mips are padded to whole blocks and
136stored smallest-first; a mip whose element count fits half a tile width and a tile height,
137among the last 8 (4 KiB) or 12 (64 KiB) mips, goes into one shared tile at offset 0 at the
138AMD entry offset (`m = max_tail - 1 - k`; `entry = m > 6 ? 16 << m : m << 8`).
139
140On all 356,413 2D descriptors with a known element size — the 232,789 already-trusted compact
141exports, the 14,011 layout-capable records the profile table rejects, and every non-compact
142mode — the computed size equals `next_allocation - base`. There are **0 mismatches**. The
143remaining 702 descriptors are 678 arrays/volumes and 24 formats without an element-size
144mapping.
145
146### `non_tail` is not the layout boundary
147
148The descriptor's 3-bit `non_tail` field (`b & 7`) is where the reader stops, and its note calls
149the remaining mips "packed tail". The bytes do not follow that split:
150
151- 177,111 of the 232,789 compact exports have `non_tail < first_tail`; 214,298 standalone
152 mips lie beyond the limit, 204,108 of them in zlib/raw chunks.
153- 196,257 partial exports stop exactly at `non_tail`; 158,272 of them stop **before** the
154 computed tail boundary, and only 37,985 stop at it.
155- Of the 1,072,068 missing mips, 1,065,138 are in zlib/raw chunks. That decodable part splits
156 into 193,019 standalone mips and 872,119 packed-tail mips; the other 6,930 missing mips (in
157 1,166 textures) touch BCPack.
158
159`UsableMipLimit = NonTailMipCount` therefore drops decodable standalone mips, not only the
160tile. The allocation spans and the decoded content both put the tail at the computed index.
161
162### The 14,030 profile-table records
163
164| | Textures |
165|---|---:|
166| same layout, new tuple (4 KiB) | 13,956 |
167| same layout, modes 5/7/34/38 | 40 |
168| same layout, 64 KiB (modes 1/32) | 15 |
169| **layout resolved** | **14,011** |
170| format without an element-size mapping | 19 |
171| **total** | **14,030** |
172
173- 11,570 have every mip in a zlib/raw chunk: all 35,727 mips decode (2.91 GiB decompressed).
174- 469 more have a zlib/raw tail tile but a BCPack larger mip, so only their lower mips can be
175 exported.
176- The 19 blocked records are mode 1 (64 KiB) with DXGI formats 156, 199, 211 and 226; the
177 format-to-element-size mapping is the only unknown, not the mip layout.
178
179The five DXGI 11 (`R16G16B16A16_UNORM`) records are a separate one-line gap: DXGI 11 is 8
180bytes per element, but the vendored element table has no entry. Their layout then matches,
181but uncompressed tiling is not validated, so they are not exported here.
182
183### Sample validation
184
185`tools/ttpf_mips.py check` detiles one chain, decodes BC1/BC3/BC4/BC5 and compares each mip
186with a 2x2 box downsample of its parent at BC-block resolution (one block is 4x4 pixels). A
187correct chain is 0–4 levels, as in the SixNG notes; the control is the first tail mip detiled
188at origin (0,0).
189
190| Pool # | Descriptor | Mips | non_tail / first_tail | Max error | Tail control |
191|---|---|---:|---:|---:|---:|
192| `interiors_0_3` #19 | 512×256 BC1 | 7 | 1 / 3 | 0.38 | 126.06 |
193| `interiors_0_3` #10 | 512×512 BC1 | 8 | 3 / 3 | 0.46 | 57.94 |
194| `graphics` #43 | 64×512 BC1 | 10 | 1 / 3 | 1.08 | 132.31 |
195| `interiors_2_3` #468 | 512×512 BC1 | 8 | 3 / 3 | 0.60 | 113.83 |
196| `maps_0_7` #3217 | 128×128 BC1 | 6 | 0 / 1 | 0.79 | 114.71 |
197| `peds_1_3` #527 | 512×512 BC1 | 8 | 3 / 3 | 3.87 | 83.83 |
198| `maps_1_7` #1500 | 128×256 BC4 | 6 | 1 / 2 | 0.34 | 72.08 |
199| `decorations_0_3` #818 | 128×128 BC5 | 6 | 1 / 2 | 0.02 | 85.48 |
200| `interiors_1_3` #507 | 256×256 BC3 | 7 | 1 / 2 | 1.21 | 51.84 |
201
202`interiors_0_3` #19 is a partial export: the reader emits one mip, while all seven decode and
203match. `graphics` #43 and `interiors_2_3` #468 are tuples outside the table; `maps_0_7` #3217
204is mode 34 with `non_tail = 0`, which would leave zero standalone mips even if the mode gate
205passed.
206
207BC7 was checked on two samples with an external decoder (Pillow, not a dependency of the
208tool): `terrain_4_7` #23 (512×512, 3 mips, 0.35–0.49) and `maps_4_7` #6034 (1024×1024, mode
20932, 64 KiB, 0.00–0.33, control 4.44).
210
211For `interiors_0_3` #19 the tool reports the byte layout: mip 0 (512×256, 128×64 blocks) at
21224,576, mip 1 (256×128, 64×32) at 8,192, mip 2 (128×64, 32×16) at 4,096, then the 4 KiB tile
213at 0 with mip 3 (64×32 px, 16×8 blocks) at origin (16,0), mip 4 (32×16 px, 8×4) at (8,8),
214mip 5 (16×8 px, 4×2) at (0,12) and mip 6 (8×4 px, 2×1) at (0,8). The mip byte sizes 65,536 /
21516,384 / 4,096 / 1,024 / 256 / 64 / 16 are exactly the BC1 block counts, and the exported DDS
216is 87,524 bytes (148 + 87,376).
217
218### What this unlocks
219
220"Decompressed" is the block-linear BC payload size (`blocks × block bytes`), not the inflated
221chunk size, which includes tile padding.
222
223| | Textures | New mips | Decompressed |
224|---|---:|---:|---:|
225| partial exports that become complete | 195,091 | 1,065,138 | 1.69 GiB |
226| compact skips that become complete | 11,570 | 35,727 | 2.91 GiB |
227| **total** | **206,661** | **1,100,865** | **4.59 GiB** |
228
2291,166 of the 196,257 partials still miss 6,930 mips that touch BCPack; those and the 33,507
230fully blocked textures wait on the codec. Nothing here decodes BCPack.
101 231
102## What BCPack is 232## What BCPack is
103 233
@@ -265,25 +395,46 @@ and the algorithm class are known; the bitstream is not.
265 395
266## Next step 396## Next step
267 397
2681. **Do not fake a BCPack decoder.** The current fallback (export the largest lower mip that 3981. **Port the tile-mode split and the computed tail boundary.** In `TtpfReader`, select
269 is zlib/raw) is used by 5,845 textures and should stay. 399 `tile = 65536` when `((mode >> 1) & 0xF) == 0` and 4096 otherwise, replace
2702. **Fix the compact packed tail first.** 196,257 of the 210,292 partial exports stop at 400 `ValidatedCompactProfile` with the allocation-span check, and set `UsableMipLimit` to the
271 `NonTailMipCount`; the tail layout is documented (SixNG §5) and needs no BCPack decoder. 401 computed `FirstTail` (or `mips` when the tail tile is zlib/raw). On this install that
272 This is the largest tractable texture gap. 402 completes 206,661 textures without touching BCPack.
2733. **Then the small independent gaps:** 678 array/volume layouts and 5 DXGI 11 textures. 4032. **Decode BC6H/BC7 in the validator.** `tools/ttpf_mips.py` decodes BC1/3/4/5; the BC7
274 Neither needs BCPack. 404 samples were checked with an external decoder. The layout is the same formula (16-byte
2754. **If a public decoder or bitstream spec appears under a compatible licence,** add it behind 405 elements), so this is validation breadth, not a new mapping.
276 `TtpfReader.DecodeChunk`; the container already carries the mode (codec id) and decoded 4063. **Identify DXGI 156/199/211/226 (19 records) and validate uncompressed tiling (formats
277 size, so no index work is needed. 407 11, 28, 49, 56).** These are the remaining non-BCPack blockers besides arrays.
2785. **If someone resumes the reverse engineering,** use the hard check the SixNG notes propose: 4084. **Arrays/volumes: 678 descriptors.** 567 use tile modes 9–12 and 111 are 2-slice; no
279 every lane must consume exactly its byte budget and finish at the rANS lower bound, with a 409 validated slice layout exists yet.
280 fixed symbol count. Reference blocks are the missing input; none are public. 4105. **Do not fake a BCPack decoder.** The current fallback (export the largest lower mip that
411 is zlib/raw) is used by 5,845 textures and should stay. If a public decoder or bitstream
412 spec appears under a compatible licence, add it behind `TtpfReader.DecodeChunk`; the
413 container already carries the mode (codec id) and decoded size, so no index work is
414 needed.
4156. **If someone resumes the BCPack reverse engineering,** use the hard check the SixNG notes
416 propose: every lane must consume exactly its byte budget and finish at the rANS lower
417 bound, with a fixed symbol count. Reference blocks are the missing input; none are public.
281 418
282## Reproduce 419## Reproduce
283 420
421`tools/ttpf_mips.py` is the read-only measurement and decode tool:
422
423```
424python -I tools/ttpf_mips.py scan <game root> --json scan.json
425python -I tools/ttpf_mips.py layout <pool.ttpf> <index>
426python -I tools/ttpf_mips.py check <pool.ttpf> <index>
427python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds>
428```
429
430`scan` reproduces the 357,115 / 98,603 / 210,292 / 48,220 split of this note and adds the
431layout and recovery columns. `check` reports the per-mip downsample error. `export` writes a
432full BC chain only when every source mip is zlib/raw. The tool writes no texture data and
433`tests/test_ttpf_mips.py` runs on a synthetic RDS5 pool, so the test needs no game files.
434
284`rpf9dump ttpf` writes one `manifest.json` per pool with a `Limitation` field for every 435`rpf9dump ttpf` writes one `manifest.json` per pool with a `Limitation` field for every
285catalog record, and its summary line has the same `ok` / `skip` totals. The split above comes 436catalog record, and its summary line has the same `ok` / `skip` totals. The first split above
286from a read-only mirror of `TtpfReader`'s catalog checks: it mmaps each pool and reads only 437came from a read-only mirror of `TtpfReader`'s catalog checks: it mmapped each pool and read
287the 24-byte RDS5 header, the chunk table, the ETPF records and the chunk ranges. It writes no 438only the 24-byte RDS5 header, the chunk table, the ETPF records and the chunk ranges, and it
288texture data. The mirror is not committed because it duplicates `TtpfReader`; the counts are 439wrote no texture data. `tools/ttpf_mips.py scan` is that mirror, now committed with the
289the evidence. 440compact-layout work; it reproduces the split and adds the recovery columns.
diff --git a/docs/world.md b/docs/world.md
index 8d32b951a..718e9abc4 100644
--- a/docs/world.md
+++ b/docs/world.md
@@ -238,21 +238,19 @@ pattern in the 0–2 GiB family is a hash-table slot, not a matrix row.
238 238
239### How many are there? 239### How many are there?
240 240
241The measured 9,918 files and 680,228 entities are a **lower bound**, not a whole-archive total. The sample is 241A full sharded census of the `levels.rpf` data area now gives a measured total: **23,535 map resources /
24229 GiB of the 57 GiB map band (50.9%) and 39.23 GiB of the archive (55.3%, including the carver-indexed 0–2 GiB 2421,670,442 placement entities**. Every map row is exact against its declared entity size and every expected
243window). 243shard completed. The earlier bounded passes measured 9,918 files and 680,228 entities in 55.3% of the archive;
244 244that was a lower bound, and the full pass settles the extrapolation. See
245A single multiplier is weak because density is not uniform: sampled 1-GiB blocks range from 96 to 2,174 map 245[world_census.md](world_census.md) for the shard layout, the exactness condition and the 98.32% stream
246files and from 4,754 to 145,118 entities. Treating the 29 sampled 1-GiB units as exchangeable gives a 246coverage.
247uniform-block estimate of **~26,600 map files / ~1.77 million entities**. A 20,000-resample block bootstrap 247
248gives an approximate 95% interval of 16.0k–39.6k map files and 1.03M–2.64M entities. The selection was 248The full count is lower than SixNG's published 30,785 map files / 2,249,490 entities
249purposive, not random, so those bounds are approximate; they are not a census. 249(https://github.com/holdmysocks/SixNG). The difference is not yet explained. The census counts only
250 250validated `0x7a` resources whose schema includes `CMapData` and whose entity table is self-consistent;
251SixNG's published full-archive measurement, 30,785 map files / 2,249,490 entities 251SixNG may count archive entries, nested maps, or map resources that this scanner rejects. Treat the
252(https://github.com/holdmysocks/SixNG), lies inside that interval. It is external evidence, not a measurement 25223,535 / 1,670,442 figure as the measured count for this package and this validation rule, not as a
253made here. The observed 9,918 files are 32.2% of that count and 680,228 entities are 30.2%, even though 50.9% of 253claim about a different enumeration method.
254the map band was scanned. That gap is consistent with the unsampled parts being denser, with map files whose
255entity blocks live in graphics pages, or with both; only a full band scan can settle it.
256 254
257## What is readable, what is hash-only 255## What is readable, what is hash-only
258 256
@@ -304,6 +302,11 @@ Hash-only or opaque:
304It implements the header/schema validation above and the continuation join. It does not decrypt anything, 302It implements the header/schema validation above and the continuation join. It does not decrypt anything,
305does not extract models/textures, and keeps the output aggregate (one row per resource, no entity dump). 303does not extract models/textures, and keeps the output aggregate (one row per resource, no entity dump).
306 304
305`tools/world_census.py` scans the whole `levels.rpf` data area in shards and counts every validated
306`0x7a` map resource and placement entity. The measured full pass is 23,535 maps / 1,670,442 entities
307with 98.32% stream coverage; the exactness condition and byte accounting are in
308[world_census.md](world_census.md).
309
307```powershell 310```powershell
308python -I tools\world_index.py <levels.rpf> --start 21474836480 --limit 1073741824 ` 311python -I tools\world_index.py <levels.rpf> --start 21474836480 --limit 1073741824 `
309 --out work\world\levels-20-21.json --csv work\world\levels-20-21.csv 312 --out work\world\levels-20-21.json --csv work\world\levels-20-21.csv
diff --git a/docs/world_census.md b/docs/world_census.md
new file mode 100644
index 000000000..128151954
--- /dev/null
+++ b/docs/world_census.md
@@ -0,0 +1,97 @@
1# Census of `levels.rpf`
2
3`levels.rpf` is 76,155,065,056 bytes. Its table of contents is encrypted, so the archive cannot be
4enumerated by name. `tools/world_census.py` measures the data area directly: it inflates every zlib
5stream, validates each `0DRP` / version `0x7a` resource, joins continuation streams, and counts the
6map resources and placement entities they contain.
7
8## Result
9
10| Measure | Value |
11|---|---:|
12| Data area scanned | 76,154,954,352 bytes (start `0x1B070`) |
13| Map resources (`kind=map`) | **23,535** |
14| Placement entities | **1,670,442** |
15| Complete / validated map rows | **23,535 / 23,535** |
16| Exact entity counts | **1,670,442 / 1,670,442** |
17| Shards complete | **36 / 36** |
18| Zlib streams inflated | **1,122,614** |
19| Stored stream bytes | 75,165,813,806 |
20| Inflated bytes (all streams) | 175,587,890,693 |
21| Rejected zlib candidates | 906 |
22| Adopted continuation streams | 174 |
23| Metadata streams | 165,880 |
24| Duplicate content groups | 0 |
25| Scan time | 290.8 s |
26
27A map row is a resource whose schema includes `CMapData`. `maps_exact` means every entity block
28counted against the declared `entity_size` and no entity block was left in a graphics page.
29`entities_exact` is the same check summed over all rows. Six entities of the 23,535 maps were split
30across a continuation; the joiner adopted 174 streams in total.
31
32## Coverage
33
34| Byte class | Bytes | Share of data area |
35|---|---:|---:|
36| Accepted stream payload | 74,877,281,159 | 98.32% |
37| Raw graphics pages (`0x6`) | 2,762,232 | 0.004% |
38| Raw system continuation | 44,304 | 0.0001% |
39| Zero padding | 1,058,806,784 | 1.39% |
40| Unread non-zero bytes | 216,059,873 | 0.28% |
41| **Accounted** | **76,154,954,352** | **100%** |
42
43The unread bytes are mostly small alignment and metadata gaps between streams. The gap audit found
44**23** `0DRP` signatures in unread ranges, but none resolved to a map or metadata resource
45(`raw_maps = 0`, `raw_meta = 0`), so the census is not missing a map class. No unaligned zlib stream
46that inflates to a `0DRP` header was found in a gap (`missed_zlib_meta = 0`). The 906 rejected
47candidates are zlib streams that do not form a complete `0x7a` resource; they are ordinary archive
48payload, not counted maps.
49
50## Exactness condition
51
52`summary.json` sets `census_exact` only when all of these hold:
53
54- `complete` is true and every expected shard was written;
55- `maps_exact == maps` and `entities_exact == entities`;
56- `entity_gfx == 0` and `entity_unresolved == 0`;
57- `raw_maps == 0` and `missed_zlib_meta == 0`.
58
59The run above satisfies every condition. `accounted_ratio` is 1.0 because every byte is assigned to
60accepted payload, a raw page, zero padding or counted unread data.
61
62## Method
63
64The scan starts at the data-area offset from the `9FPR` header. It walks 16-byte-aligned zlib
65candidates in independent shards and:
66
671. inflates each stream, keeping the first bytes needed to recognize `0DRPz`;
682. validates the little-endian `0x7a` header, struct table, block table and member offsets;
693. follows a contiguous split resource, either another zlib page or a raw system page whose length
70 the resource's pointers require;
714. counts `CEntityDef` blocks against the declared entity size, and records `0x6` graphics extents;
725. merges shard rows, checks duplicate names and content hashes, and audits every gap for a missed
73 `0DRP` signature or unaligned zlib stream.
74
75Each shard is written to `shard_<index>_<start>_<end>.json`; `summary.json` and `maps.json` are
76rebuilt from the shards, so an interrupted run resumes with `--resume` or `--merge-only`.
77
78```powershell
79python -I tools\world_census.py <levels.rpf> --out work\world\census --shard-size 2147483648 --jobs 12
80python -I tools\world_census.py <levels.rpf> --out work\world\census --merge-only
81python -I tests\test_world_census.py
82```
83
84The default shard size is 2 GiB, the default job count is half the logical CPUs, and the scan is
85bounded by `--start` / `--limit` when a partial pass is wanted.
86
87## Limits
88
89- The census counts resources, not names. It does not decrypt the RPF9 TOC, so it cannot say which
90 archive entry owns a map; `docs/world.md` correlates the measured bands with the placement files
91 it could carve.
92- Only `0x7a` resources are validated. Other resource types contribute to stream and byte counts but
93 are not classified.
94- A map row proves the resource has a `CMapData` root and a self-consistent entity table. It does not
95 prove the map is reachable, loaded, or complete in the runtime.
96- Output contains resource offsets, sizes, counts and content hashes only. It is aggregate metadata;
97 keep it out of git along with the archive and carved streams.
diff --git a/make_game.py b/make_game.py
index 3965439e5..bbad5bf5d 100644
--- a/make_game.py
+++ b/make_game.py
@@ -210,7 +210,8 @@ def preflight(stages: list, work: str, wav: bool = False) -> None:
210 if not tool_available(llvm): 210 if not tool_available(llvm):
211 missing.append( 211 missing.append(
212 "llvm-mc (LLVM 21+ with the AMDGPU target). The official Windows LLVM build has no AMDGPU " 212 "llvm-mc (LLVM 21+ with the AMDGPU target). The official Windows LLVM build has no AMDGPU "
213 "target: install llvm-21 in WSL and set LLVM_MC to the whole command, e.g. " 213 "target: build a native one with scripts\\build_llvm_mc.ps1, or install llvm-21 in WSL and set "
214 "LLVM_MC to the whole command, e.g. "
214 "LLVM_MC=\"wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc\" (docs/design.md)") 215 "LLVM_MC=\"wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc\" (docs/design.md)")
215 for t in ("spirv-as", "spirv-val"): 216 for t in ("spirv-as", "spirv-val"):
216 if not shutil.which(t): 217 if not shutil.which(t):
@@ -302,7 +303,7 @@ def shaders(game: str, work: str, jobs: int) -> None:
302 shutil.rmtree(spirv, ignore_errors=True) 303 shutil.rmtree(spirv, ignore_errors=True)
303 if not os.path.isfile(disassembled): 304 if not os.path.isfile(disassembled):
304 need(os.environ.get("LLVM_MC", "llvm-mc"), 305 need(os.environ.get("LLVM_MC", "llvm-mc"),
305 "Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's full path.") 306 "Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's path or whole command.")
306 log("shaders: disassembling (gfx1013)") 307 log("shaders: disassembling (gfx1013)")
307 drop(translated) 308 drop(translated)
308 py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs) 309 py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs)
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 3051d8012..d2df25019 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -17,6 +17,24 @@ if(WIN32)
17 target_compile_definitions(gta6rt_d3d12_xs_rootsig PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 17 target_compile_definitions(gta6rt_d3d12_xs_rootsig PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
18 target_compile_options(gta6rt_d3d12_xs_rootsig PRIVATE /W4 /permissive- /utf-8) 18 target_compile_options(gta6rt_d3d12_xs_rootsig PRIVATE /W4 /permissive- /utf-8)
19 19
20 # Portable root-signature model + packer to user SGPRs (no d3d12.h, no windows.h).
21 add_library(gta6rt_root_signature STATIC
22 src/root_signature.cpp
23 )
24 target_include_directories(gta6rt_root_signature PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src)
25 target_compile_definitions(gta6rt_root_signature PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
26 target_compile_options(gta6rt_root_signature PRIVATE /W4 /permissive- /utf-8)
27
28 # Portable contract test: model, packer, canonical codec and RTS0 hypothesis.
29 # Needs neither d3d12.lib nor the game; runs on Windows CI like the rest here.
30 add_executable(root_signature_test
31 test/root_signature_test.cpp
32 )
33 target_link_libraries(root_signature_test PRIVATE gta6rt_root_signature)
34 target_compile_definitions(root_signature_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
35 target_compile_options(root_signature_test PRIVATE /W4 /permissive- /utf-8)
36 target_link_options(root_signature_test PRIVATE /OPT:NOREF)
37
20 add_executable(gta6rt 38 add_executable(gta6rt
21 src/main.cpp 39 src/main.cpp
22 src/pe_loader.cpp 40 src/pe_loader.cpp
@@ -57,6 +75,17 @@ if(WIN32)
57 target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8) 75 target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8)
58 target_link_options(root_sig_test PRIVATE /OPT:NOREF) 76 target_link_options(root_sig_test PRIVATE /OPT:NOREF)
59 77
78 # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC
79 # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch
80 # fails here with the blob bytes, never silently in a draw.
81 add_executable(root_signature_oracle_test
82 test/root_signature_oracle_test.cpp
83 )
84 target_link_libraries(root_signature_oracle_test PRIVATE gta6rt_root_signature ${D3D12_LIBRARY})
85 target_compile_definitions(root_signature_oracle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
86 target_compile_options(root_signature_oracle_test PRIVATE /W4 /permissive- /utf-8)
87 target_link_options(root_signature_oracle_test PRIVATE /OPT:NOREF)
88
60 # Xbox-ABI device proxy test: WARP PC device, no game executable. Needs DXGI for the WARP adapter. 89 # Xbox-ABI device proxy test: WARP PC device, no game executable. Needs DXGI for the WARP adapter.
61 if(DXGI_LIBRARY) 90 if(DXGI_LIBRARY)
62 add_executable(device_proxy_test 91 add_executable(device_proxy_test
@@ -159,6 +188,8 @@ if(BUILD_TESTING)
159 endif() 188 endif()
160 add_executable(command_list_test test/command_list_test.cpp) 189 add_executable(command_list_test test/command_list_test.cpp)
161 add_test(NAME command_list COMMAND command_list_test) 190 add_test(NAME command_list COMMAND command_list_test)
191 add_executable(descriptor_table_test test/descriptor_table_test.cpp)
192 add_test(NAME descriptor_table COMMAND descriptor_table_test)
162 if(WIN32) 193 if(WIN32)
163 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. 194 # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set.
164 add_executable(bink_decode_test 195 add_executable(bink_decode_test
@@ -191,6 +222,12 @@ if(BUILD_TESTING)
191 if(WIN32 AND TARGET xmem_test) 222 if(WIN32 AND TARGET xmem_test)
192 add_test(NAME xmem COMMAND xmem_test) 223 add_test(NAME xmem COMMAND xmem_test)
193 endif() 224 endif()
225 if(WIN32 AND TARGET root_signature_test)
226 add_test(NAME root_signature COMMAND root_signature_test)
227 endif()
228 if(WIN32 AND TARGET root_signature_oracle_test)
229 add_test(NAME root_signature_oracle COMMAND root_signature_oracle_test)
230 endif()
194endif() 231endif()
195 232
196if(WIN32) 233if(WIN32)
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
new file mode 100644
index 000000000..2fc9e99cb
--- /dev/null
+++ b/runtime/src/descriptor_table.h
@@ -0,0 +1,252 @@
1#pragma once
2
3// The descriptor hash table for set 0, binding 2 (docs/d3d12_vulkan.md section 5.1 and docs/design.md):
4// Shaders look up bindless resource/sampler indices by FNV-1a hashing the 8-dword descriptor key (T# or padded S#)
5// and probing up to 8 slots in this table. Miss or fallback yields index 0.
6
7#include <algorithm>
8#include <array>
9#include <cstdint>
10#include <cstring>
11#include <mutex>
12#include <span>
13#include <vector>
14
15namespace leonida {
16
17// FNV-1a constants for 32-bit dwords
18inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u;
19inline constexpr std::uint32_t kFnvPrime = 16777619u;
20inline constexpr std::uint32_t kDescriptorProbes = 8;
21inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu;
22
23// Key types:
24// T# key is 8 dwords.
25// S# key is 4 dwords followed by 4x 0xFFFFFFFF.
26using DescriptorKey = std::array<std::uint32_t, 8>;
27
28inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) {
29 std::uint32_t h = kFnvOffsetBasis;
30 for (int i = 0; i < 8; ++i) {
31 h = (h ^ key[i]) * kFnvPrime;
32 }
33 return h;
34}
35
36inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) {
37 return hash_descriptor_key(key.data());
38}
39
40inline DescriptorKey make_tsharp_key(const std::uint32_t tsharp[8]) {
41 DescriptorKey k{};
42 std::memcpy(k.data(), tsharp, sizeof(DescriptorKey));
43 return k;
44}
45
46inline DescriptorKey make_ssharp_key(const std::uint32_t ssharp[4]) {
47 DescriptorKey k{};
48 k[0] = ssharp[0];
49 k[1] = ssharp[1];
50 k[2] = ssharp[2];
51 k[3] = ssharp[3];
52 k[4] = 0xFFFFFFFFu;
53 k[5] = 0xFFFFFFFFu;
54 k[6] = 0xFFFFFFFFu;
55 k[7] = 0xFFFFFFFFu;
56 return k;
57}
58
59// Memory layout of each entry in the table: 10 uint32s = 40 bytes.
60struct DescriptorEntry {
61 std::uint32_t key[8] = {};
62 std::uint32_t index = 0;
63 std::uint32_t pad = 0; // 0 when empty, kSlotOccupiedMarker when occupied
64};
65static_assert(sizeof(DescriptorEntry) == 40);
66
67class DescriptorTable {
68public:
69 explicit DescriptorTable(std::uint32_t initial_capacity = 16) {
70 std::uint32_t cap = 16;
71 while (cap < initial_capacity) cap <<= 1;
72 mask_ = cap - 1;
73 entries_.resize(cap);
74 }
75
76 // Inserts or updates a key -> index mapping.
77 // If the key already exists in one of the 8 probe slots, its index is updated.
78 // If insertion would exceed 8 probes or 50% load, the table grows and re-hashes.
79 bool insert(const std::uint32_t key[8], std::uint32_t index) {
80 std::lock_guard lock(mutex_);
81 return insert_locked(key, index);
82 }
83
84 bool insert(const DescriptorKey& key, std::uint32_t index) {
85 return insert(key.data(), index);
86 }
87
88 // Queries the index associated with key. Returns 0 if not found.
89 std::uint32_t lookup(const std::uint32_t key[8]) const {
90 std::lock_guard lock(mutex_);
91 const std::uint32_t h = hash_descriptor_key(key);
92 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
93 const std::uint32_t slot = (h + k) & mask_;
94 const auto& entry = entries_[slot];
95 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
96 return entry.index;
97 }
98 if (entry.pad != kSlotOccupiedMarker) {
99 return 0; // Empty slot encountered: key is definitely absent
100 }
101 }
102 return 0; // Exceeded 8 probes without a match
103 }
104
105 std::uint32_t lookup(const DescriptorKey& key) const {
106 return lookup(key.data());
107 }
108
109 bool contains(const std::uint32_t key[8]) const {
110 std::lock_guard lock(mutex_);
111 const std::uint32_t h = hash_descriptor_key(key);
112 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
113 const std::uint32_t slot = (h + k) & mask_;
114 const auto& entry = entries_[slot];
115 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
116 return true;
117 }
118 if (entry.pad != kSlotOccupiedMarker) return false;
119 }
120 return false;
121 }
122
123 bool contains(const DescriptorKey& key) const {
124 return contains(key.data());
125 }
126
127 void clear() {
128 std::lock_guard lock(mutex_);
129 std::fill(entries_.begin(), entries_.end(), DescriptorEntry{});
130 occupied_count_ = 0;
131 }
132
133 std::size_t size() const {
134 std::lock_guard lock(mutex_);
135 return occupied_count_;
136 }
137
138 std::size_t capacity() const {
139 std::lock_guard lock(mutex_);
140 return entries_.size();
141 }
142
143 std::uint32_t mask() const {
144 std::lock_guard lock(mutex_);
145 return mask_;
146 }
147
148 std::size_t size_dwords() const {
149 std::lock_guard lock(mutex_);
150 return 1 + entries_.size() * 10;
151 }
152
153 std::size_t size_bytes() const {
154 return size_dwords() * sizeof(std::uint32_t);
155 }
156
157 // Exports the table buffer format consumed by SPIR-V set 0, binding 2.
158 // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, pad.
159 std::vector<std::uint32_t> build_gpu_buffer(bool clear_pad = false) const {
160 std::lock_guard lock(mutex_);
161 std::vector<std::uint32_t> out(1 + entries_.size() * 10, 0);
162 out[0] = mask_;
163 for (std::size_t s = 0; s < entries_.size(); ++s) {
164 const std::size_t base = 1 + s * 10;
165 std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key));
166 out[base + 8] = entries_[s].index;
167 out[base + 9] = clear_pad ? 0 : entries_[s].pad;
168 }
169 return out;
170 }
171
172 void write_to_buffer(void* dest, bool clear_pad = false) const {
173 if (!dest) return;
174 const auto buf = build_gpu_buffer(clear_pad);
175 std::memcpy(dest, buf.data(), buf.size() * sizeof(std::uint32_t));
176 }
177
178private:
179 bool insert_locked(const std::uint32_t key[8], std::uint32_t index) {
180 while (true) {
181 const std::uint32_t h = hash_descriptor_key(key);
182 int empty_slot = -1;
183
184 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
185 const std::uint32_t slot = (h + k) & mask_;
186 auto& entry = entries_[slot];
187 if (entry.pad == kSlotOccupiedMarker) {
188 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
189 entry.index = index;
190 return true;
191 }
192 } else if (empty_slot < 0) {
193 empty_slot = static_cast<int>(slot);
194 }
195 }
196
197 // Check if we can place in an empty slot without exceeding 50% load
198 if (empty_slot >= 0 && (occupied_count_ + 1) * 2 <= entries_.size()) {
199 auto& entry = entries_[empty_slot];
200 std::memcpy(entry.key, key, sizeof(entry.key));
201 entry.index = index;
202 entry.pad = kSlotOccupiedMarker;
203 ++occupied_count_;
204 return true;
205 }
206
207 // Table is full (>50% load) or no slot found in 8 probes: grow and retry
208 grow_locked();
209 }
210 }
211
212 void grow_locked() {
213 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2);
214 while (true) {
215 std::vector<DescriptorEntry> new_entries(new_cap);
216 const std::uint32_t new_mask = new_cap - 1;
217 bool rehash_ok = true;
218
219 for (const auto& old : entries_) {
220 if (old.pad != kSlotOccupiedMarker) continue;
221 const std::uint32_t h = hash_descriptor_key(old.key);
222 bool placed = false;
223 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
224 const std::uint32_t s = (h + k) & new_mask;
225 if (new_entries[s].pad != kSlotOccupiedMarker) {
226 new_entries[s] = old;
227 placed = true;
228 break;
229 }
230 }
231 if (!placed) {
232 rehash_ok = false;
233 break;
234 }
235 }
236
237 if (rehash_ok) {
238 entries_ = std::move(new_entries);
239 mask_ = new_mask;
240 break;
241 }
242 new_cap *= 2;
243 }
244 }
245
246 mutable std::mutex mutex_;
247 std::uint32_t mask_ = 15;
248 std::vector<DescriptorEntry> entries_;
249 std::size_t occupied_count_ = 0;
250};
251
252} // namespace leonida
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
new file mode 100644
index 000000000..79a633b61
--- /dev/null
+++ b/runtime/src/root_signature.cpp
@@ -0,0 +1,456 @@
1// Portable root-signature packer, see root_signature.h.
2#include "root_signature.h"
3
4#include <cstring>
5
6namespace rt::rootsig {
7
8PackResult pack(const RootSignature& sig) {
9 PackResult out;
10 if (sig.params.size() > 64) {
11 out.error = "root signature has more than 64 root parameters";
12 return out;
13 }
14 uint32_t cost = 0;
15 for (const RootParameter& p : sig.params) {
16 if (p.type == ParamType::Constants && p.num_values == 0) {
17 out.error = "root constant parameter needs at least 1 dword";
18 return out;
19 }
20 const uint32_t dwords = p.type == ParamType::Table ? 2
21 : p.type == ParamType::Descriptor ? 2
22 : p.num_values;
23 cost += param_cost(p.type, p.num_values);
24 if (cost > kMaxD3d12Cost) {
25 out.error = "root signature exceeds the 64-dword D3D12 cost limit";
26 return out;
27 }
28 if (out.dword_count + dwords > kMaxUserSgprs) {
29 // Spill layout is unknown (see __XB_GetRootSignatureSpillPointer):
30 // refuse loudly instead of silently truncating every draw.
31 out.error = "root signature needs more than 32 user SGPRs (spill unsupported)";
32 return out;
33 }
34 const uint32_t param_index =
35 static_cast<uint32_t>(&p - sig.params.data());
36 for (uint32_t i = 0; i < dwords; ++i) {
37 out.dwords[out.dword_count] = 0; // filled at bind time
38 out.provenance.push_back({param_index, i});
39 ++out.dword_count;
40 }
41 }
42 out.d3d12_cost = cost;
43 out.ok = true;
44 return out;
45}
46
47namespace {
48
49void put_u32(std::vector<uint8_t>& out, uint32_t v) {
50 out.push_back(static_cast<uint8_t>(v));
51 out.push_back(static_cast<uint8_t>(v >> 8));
52 out.push_back(static_cast<uint8_t>(v >> 16));
53 out.push_back(static_cast<uint8_t>(v >> 24));
54}
55
56void put_f32(std::vector<uint8_t>& out, float v) {
57 uint32_t bits = 0;
58 static_assert(sizeof(bits) == sizeof(v));
59 std::memcpy(&bits, &v, sizeof(bits));
60 put_u32(out, bits);
61}
62
63class Reader {
64public:
65 Reader(const uint8_t* data, size_t size) : data_(data), size_(size) {}
66
67 [[nodiscard]] bool u32(uint32_t& v) {
68 if (pos_ + 4 > size_) return false;
69 v = static_cast<uint32_t>(data_[pos_]) |
70 (static_cast<uint32_t>(data_[pos_ + 1]) << 8) |
71 (static_cast<uint32_t>(data_[pos_ + 2]) << 16) |
72 (static_cast<uint32_t>(data_[pos_ + 3]) << 24);
73 pos_ += 4;
74 return true;
75 }
76
77 [[nodiscard]] bool f32(float& v) {
78 uint32_t bits = 0;
79 if (!u32(bits)) return false;
80 std::memcpy(&v, &bits, sizeof(v));
81 return true;
82 }
83
84 [[nodiscard]] bool at_end() const { return pos_ == size_; }
85
86private:
87 const uint8_t* data_ = nullptr;
88 size_t size_ = 0;
89 size_t pos_ = 0;
90};
91
92constexpr uint32_t kCanonicalMagic = 0x3153524Cu; // "LRS1" little-endian
93constexpr uint32_t kCanonicalVersion = 1;
94
95} // namespace
96
97std::vector<uint8_t> encode_canonical(const RootSignature& sig) {
98 std::vector<uint8_t> out;
99 put_u32(out, kCanonicalMagic);
100 put_u32(out, kCanonicalVersion);
101 put_u32(out, static_cast<uint32_t>(sig.version));
102 put_u32(out, static_cast<uint32_t>(sig.params.size()));
103 put_u32(out, static_cast<uint32_t>(sig.static_samplers.size()));
104 put_u32(out, sig.flags);
105 for (const RootParameter& p : sig.params) {
106 put_u32(out, static_cast<uint32_t>(p.type));
107 put_u32(out, static_cast<uint32_t>(p.visibility));
108 put_u32(out, p.num_values);
109 put_u32(out, p.shader_register);
110 put_u32(out, p.register_space);
111 put_u32(out, p.descriptor_register);
112 put_u32(out, p.descriptor_space);
113 put_u32(out, static_cast<uint32_t>(p.ranges.size()));
114 for (const DescriptorRange& r : p.ranges) {
115 put_u32(out, r.range_type);
116 put_u32(out, r.num_descriptors);
117 }
118 }
119 for (const StaticSampler& s : sig.static_samplers) {
120 put_u32(out, s.filter);
121 put_u32(out, s.address_u);
122 put_u32(out, s.address_v);
123 put_u32(out, s.address_w);
124 put_f32(out, s.mip_lod_bias);
125 put_u32(out, s.max_anisotropy);
126 put_u32(out, s.comparison_func);
127 put_u32(out, s.border_color);
128 put_f32(out, s.min_lod);
129 put_f32(out, s.max_lod);
130 put_u32(out, s.shader_register);
131 put_u32(out, s.register_space);
132 put_u32(out, static_cast<uint32_t>(s.visibility));
133 }
134 return out;
135}
136
137DecodeResult decode_canonical(const uint8_t* data, size_t size) {
138 DecodeResult out;
139 if (data == nullptr && size != 0) {
140 out.error = "null data with nonzero size";
141 return out;
142 }
143 Reader r(data == nullptr ? reinterpret_cast<const uint8_t*>("") : data, size);
144 uint32_t magic = 0, version = 0, nparams = 0, nsamplers = 0;
145 if (!r.u32(magic) || magic != kCanonicalMagic) {
146 out.error = "bad canonical magic";
147 return out;
148 }
149 if (!r.u32(version) || version != kCanonicalVersion) {
150 out.error = "unsupported canonical version";
151 return out;
152 }
153 uint32_t ver = 0;
154 if (!r.u32(ver) || !r.u32(nparams) || !r.u32(nsamplers) || !r.u32(out.sig.flags)) {
155 out.error = "truncated canonical header";
156 return out;
157 }
158 if (ver != 1 && ver != 2) {
159 out.error = "unknown root-signature version";
160 return out;
161 }
162 if (nparams > 64) {
163 out.error = "more than 64 root parameters";
164 return out;
165 }
166 if (nsamplers > 4096) {
167 out.error = "absurd sampler count";
168 return out;
169 }
170 out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1;
171 out.sig.params.reserve(nparams);
172 for (uint32_t i = 0; i < nparams; ++i) {
173 RootParameter p;
174 uint32_t type = 0, vis = 0, nranges = 0;
175 if (!r.u32(type) || !r.u32(vis) || !r.u32(p.num_values) || !r.u32(p.shader_register) ||
176 !r.u32(p.register_space) || !r.u32(p.descriptor_register) ||
177 !r.u32(p.descriptor_space) || !r.u32(nranges)) {
178 out.error = "truncated canonical parameter";
179 return out;
180 }
181 if (type > 2) {
182 out.error = "unknown parameter type";
183 return out;
184 }
185 p.type = static_cast<ParamType>(type);
186 p.visibility = static_cast<Visibility>(vis);
187 if (nranges > 1024) {
188 out.error = "absurd range count";
189 return out;
190 }
191 p.ranges.reserve(nranges);
192 for (uint32_t j = 0; j < nranges; ++j) {
193 DescriptorRange range;
194 if (!r.u32(range.range_type) || !r.u32(range.num_descriptors)) {
195 out.error = "truncated canonical range";
196 return out;
197 }
198 p.ranges.push_back(range);
199 }
200 out.sig.params.push_back(std::move(p));
201 }
202 out.sig.static_samplers.reserve(nsamplers);
203 for (uint32_t i = 0; i < nsamplers; ++i) {
204 StaticSampler s;
205 uint32_t vis = 0;
206 if (!r.u32(s.filter) || !r.u32(s.address_u) || !r.u32(s.address_v) || !r.u32(s.address_w) ||
207 !r.f32(s.mip_lod_bias) || !r.u32(s.max_anisotropy) || !r.u32(s.comparison_func) ||
208 !r.u32(s.border_color) || !r.f32(s.min_lod) || !r.f32(s.max_lod) ||
209 !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis)) {
210 out.error = "truncated canonical sampler";
211 return out;
212 }
213 s.visibility = static_cast<Visibility>(vis);
214 out.sig.static_samplers.push_back(s);
215 }
216 if (!r.at_end()) {
217 out.error = "trailing bytes after canonical root signature";
218 return out;
219 }
220 out.ok = true;
221 return out;
222}
223
224// RTS0 payload hypothesis: u32 version (1 = 1.0, 2 = 1.1), u32 num_params,
225// u32 num_static_samplers, u32 flags, then per-parameter fields in d3d12.h
226// order. Static samplers follow the same field order as D3D12_STATIC_SAMPLER_DESC.
227// Anything else (v1.2 blobs, extra dwords, truncation) is a hard error.
228// Payload decoder: the RTS0 chunk contents (see header for the hypothesis).
229static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) {
230 DecodeResult out;
231 if (data == nullptr && size != 0) {
232 out.error = "null data with nonzero size";
233 return out;
234 }
235 if (data == nullptr) {
236 out.error = "null RTS0 payload";
237 return out;
238 }
239 // Random access into the payload: every (offset, byte-count) pair is
240 // validated before any byte is touched. Offsets count from payload start.
241 auto at = [&](size_t off, size_t bytes) -> const uint8_t* {
242 if (bytes > size || off > size - bytes) return nullptr;
243 return data + off;
244 };
245 auto u32_at = [&](size_t off, uint32_t& v) {
246 const uint8_t* p = at(off, 4);
247 if (p == nullptr) return false;
248 v = static_cast<uint32_t>(p[0]) | (static_cast<uint32_t>(p[1]) << 8) |
249 (static_cast<uint32_t>(p[2]) << 16) | (static_cast<uint32_t>(p[3]) << 24);
250 return true;
251 };
252 auto f32_at = [&](size_t off, float& v) {
253 uint32_t bits = 0;
254 if (!u32_at(off, bits)) return false;
255 static_assert(sizeof(bits) == sizeof(v));
256 std::memcpy(&v, &bits, sizeof(v));
257 return true;
258 };
259 // Header: version, num_params, params_offset, num_samplers,
260 // samplers_offset, flags.
261 uint32_t ver = 0, nparams = 0, params_off = 0, nsamplers = 0, samplers_off = 0, flags = 0;
262 if (!u32_at(0, ver) || !u32_at(4, nparams) || !u32_at(8, params_off) ||
263 !u32_at(12, nsamplers) || !u32_at(16, samplers_off) || !u32_at(20, flags)) {
264 out.error = "truncated RTS0 header";
265 return out;
266 }
267 if (ver != 1 && ver != 2) {
268 out.error = "unknown RTS0 version (not 1.0/1.1)";
269 return out;
270 }
271 if (nparams > 64) {
272 out.error = "RTS0 with more than 64 root parameters";
273 return out;
274 }
275 if (nsamplers > 4096) {
276 out.error = "RTS0 with absurd sampler count";
277 return out;
278 }
279 out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1;
280 out.sig.flags = flags;
281 // Parameter table at params_off: num_params x {u32 d3d_type, u32
282 // visibility, u32 offset}. d3d_type follows D3D12_ROOT_PARAMETER_TYPE
283 // (0 table, 1 constants, 2/3/4 CBV/SRV/UAV root descriptors).
284 constexpr size_t kEntryBytes = 12;
285 if (nparams > 0 &&
286 (params_off > size || nparams > (size - params_off) / kEntryBytes)) {
287 out.error = "RTS0 parameter table overruns its payload";
288 return out;
289 }
290 out.sig.params.reserve(nparams);
291 for (uint32_t i = 0; i < nparams; ++i) {
292 const size_t eoff = static_cast<size_t>(params_off) + i * kEntryBytes;
293 uint32_t dtype = 0, vis = 0, poff = 0;
294 if (!u32_at(eoff, dtype) || !u32_at(eoff + 4, vis) || !u32_at(eoff + 8, poff)) {
295 out.error = "truncated RTS0 parameter entry";
296 return out;
297 }
298 RootParameter p;
299 p.visibility = static_cast<Visibility>(vis);
300 if (dtype == 1) {
301 p.type = ParamType::Constants;
302 if (!u32_at(poff, p.shader_register) || !u32_at(poff + 4, p.register_space) ||
303 !u32_at(poff + 8, p.num_values)) {
304 out.error = "truncated RTS0 constants payload";
305 return out;
306 }
307 } else if (dtype == 2 || dtype == 3 || dtype == 4) {
308 p.type = ParamType::Descriptor;
309 uint32_t dflags = 0;
310 const size_t need = ver == 2 ? 12 : 8;
311 if (poff > size || need > size - static_cast<size_t>(poff)) {
312 out.error = "truncated RTS0 descriptor payload";
313 return out;
314 }
315 if (!u32_at(poff, p.descriptor_register) || !u32_at(poff + 4, p.descriptor_space)) {
316 out.error = "truncated RTS0 descriptor payload";
317 return out;
318 }
319 if (ver == 2 && !u32_at(poff + 8, dflags)) {
320 out.error = "truncated RTS0 descriptor flags";
321 return out;
322 }
323 (void)dflags; // descriptor flags do not affect the user-SGPR map
324 } else if (dtype == 0) {
325 p.type = ParamType::Table;
326 uint32_t nranges = 0;
327 if (!u32_at(poff, nranges)) {
328 out.error = "truncated RTS0 table payload";
329 return out;
330 }
331 if (nranges > 1024) {
332 out.error = "absurd RTS0 range count";
333 return out;
334 }
335 // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1).
336 const size_t stride = ver == 2 ? 24 : 20;
337 if (nranges > 0 &&
338 (poff + 4 > size || nranges > (size - (poff + 4)) / stride)) {
339 out.error = "RTS0 ranges overrun their payload";
340 return out;
341 }
342 p.ranges.reserve(nranges);
343 for (uint32_t j = 0; j < nranges; ++j) {
344 const size_t roff = static_cast<size_t>(poff) + 4 + j * stride;
345 DescriptorRange range;
346 uint32_t base_reg = 0, space = 0, disp_off = 0, rflags = 0;
347 if (!u32_at(roff, range.range_type) || !u32_at(roff + 4, range.num_descriptors) ||
348 !u32_at(roff + 8, base_reg) || !u32_at(roff + 12, space) ||
349 !u32_at(roff + 16, disp_off) ||
350 (ver == 2 && !u32_at(roff + 20, rflags))) {
351 out.error = "truncated RTS0 range";
352 return out;
353 }
354 (void)base_reg;
355 (void)space;
356 (void)disp_off;
357 (void)rflags;
358 p.ranges.push_back(range);
359 }
360 } else {
361 out.error = "unknown RTS0 parameter type";
362 return out;
363 }
364 out.sig.params.push_back(std::move(p));
365 }
366 // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order.
367 constexpr size_t kSamplerBytes = 13 * 4;
368 if (nsamplers > 0 &&
369 (samplers_off > size || nsamplers > (size - samplers_off) / kSamplerBytes)) {
370 out.error = "RTS0 samplers overrun their payload";
371 return out;
372 }
373 out.sig.static_samplers.reserve(nsamplers);
374 for (uint32_t i = 0; i < nsamplers; ++i) {
375 const size_t soff = static_cast<size_t>(samplers_off) + i * kSamplerBytes;
376 StaticSampler s;
377 uint32_t vis = 0;
378 if (!u32_at(soff, s.filter) || !u32_at(soff + 4, s.address_u) ||
379 !u32_at(soff + 8, s.address_v) || !u32_at(soff + 12, s.address_w) ||
380 !f32_at(soff + 16, s.mip_lod_bias) || !u32_at(soff + 20, s.max_anisotropy) ||
381 !u32_at(soff + 24, s.comparison_func) || !u32_at(soff + 28, s.border_color) ||
382 !f32_at(soff + 32, s.min_lod) || !f32_at(soff + 36, s.max_lod) ||
383 !u32_at(soff + 40, s.shader_register) || !u32_at(soff + 44, s.register_space) ||
384 !u32_at(soff + 48, vis)) {
385 out.error = "truncated RTS0 sampler";
386 return out;
387 }
388 s.visibility = static_cast<Visibility>(vis);
389 out.sig.static_samplers.push_back(s);
390 }
391 out.ok = true;
392 return out;
393}
394
395DecodeResult parse_rts0(const uint8_t* data, size_t size) {
396 DecodeResult out;
397 if ((data == nullptr && size != 0) || (data != nullptr && size < 4)) {
398 out.error = "blob too small for a DXBC container";
399 return out;
400 }
401 if (data == nullptr) {
402 out.error = "null blob";
403 return out;
404 }
405 // A bare payload (unit-test path) has no DXBC magic: decode directly.
406 if (!(data[0] == 'D' && data[1] == 'X' && data[2] == 'B' && data[3] == 'C')) {
407 return parse_rts0_payload(data, size);
408 }
409 // DXBC container walk (mirrors input_signature in tools/rdna2spirv.py):
410 // +28: chunk count, +32: chunk offsets, each chunk is FourCC + u32 size.
411 auto at = [&](size_t off, uint32_t& v) {
412 if (off + 4 > size) return false;
413 v = static_cast<uint32_t>(data[off]) | (static_cast<uint32_t>(data[off + 1]) << 8) |
414 (static_cast<uint32_t>(data[off + 2]) << 16) | (static_cast<uint32_t>(data[off + 3]) << 24);
415 return true;
416 };
417 uint32_t nchunks = 0;
418 if (!at(28, nchunks)) {
419 out.error = "truncated DXBC header";
420 return out;
421 }
422 if (nchunks > 1024) {
423 out.error = "absurd DXBC chunk count";
424 return out;
425 }
426 for (uint32_t k = 0; k < nchunks; ++k) {
427 uint32_t off = 0;
428 // NOTE: off and payload_size are u32; promote to size_t BEFORE adding
429 // or a hostile container wraps the check and turns it into an OOB read.
430 if (!at(32 + 4 * static_cast<size_t>(k), off) ||
431 static_cast<size_t>(off) + 8 > size) {
432 out.error = "truncated DXBC chunk table";
433 return out;
434 }
435 if (data[off] == 'R' && data[off + 1] == 'T' && data[off + 2] == 'S' && data[off + 3] == '0') {
436 uint32_t payload_size = 0;
437 if (static_cast<size_t>(off) + 8 > size) {
438 out.error = "truncated RTS0 chunk header";
439 return out;
440 }
441 payload_size = static_cast<uint32_t>(data[off + 4]) |
442 (static_cast<uint32_t>(data[off + 5]) << 8) |
443 (static_cast<uint32_t>(data[off + 6]) << 16) |
444 (static_cast<uint32_t>(data[off + 7]) << 24);
445 if (static_cast<size_t>(off) + 8 + payload_size > size) {
446 out.error = "RTS0 chunk overruns its container";
447 return out;
448 }
449 return parse_rts0_payload(data + off + 8, payload_size);
450 }
451 }
452 out.error = "no RTS0 chunk in DXBC container";
453 return out;
454}
455
456} // namespace rt::rootsig
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h
new file mode 100644
index 000000000..4c19cf72d
--- /dev/null
+++ b/runtime/src/root_signature.h
@@ -0,0 +1,150 @@
1// Portable D3D12 root-signature model + packer to user SGPRs (s0..s31).
2//
3// No d3d12.h, no windows.h: this compiles on Linux CI and in the Windows
4// runtime alike. It models exactly what docs/d3d12_vulkan.md section 3.5
5// needs: root parameters in order, static samplers (no dwords), the 64-dword
6// D3D12 cost limit, and the 32-dword console user-SGPR budget. Anything that
7// does not fit is refused loudly, never guessed (see pack()).
8//
9// Numbering follows D3D12 docs: descriptor tables cost 1 dword of the 64-dword
10// limit, root views (CBV/SRV/UAV) cost 2, 32-bit constants cost their count.
11#pragma once
12
13#include <array>
14#include <cstdint>
15#include <string>
16#include <vector>
17
18namespace rt::rootsig {
19
20// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles.
21enum class Version : uint32_t { V1_0 = 1, V1_1 = 2 };
22
23// D3D12_ROOT_PARAMETER_TYPE subset (order matches D3D12 docs).
24enum class ParamType : uint32_t {
25 Constants = 0, // 32BIT_CONSTANTS: NumValues dwords
26 Descriptor = 1, // CBV/SRV/UAV root descriptor: 2 dwords (64-bit VA)
27 Table = 2, // DESCRIPTOR_TABLE: 2 dwords (table GPU VA)
28};
29
30// D3D12_SHADER_VISIBILITY (ALL 0, VERTEX 1, HULL 2, DOMAIN 3,
31// GEOMETRY 4, PIXEL 5, AMPLIFICATION 6, MESH 7).
32enum class Visibility : uint32_t {
33 All = 0,
34 Vertex = 1,
35 Geometry = 4,
36 Pixel = 5,
37 Amplification = 6,
38 Mesh = 7,
39};
40
41// One descriptor range inside a table (SRV/CBV/UAV/sampler + count).
42struct DescriptorRange {
43 uint32_t range_type = 0; // 0 SRV, 1 UAV, 2 CBV, 3 sampler (D3D12 order)
44 uint32_t num_descriptors = 0;
45};
46
47// Static sampler: no user-SGPR dwords; registered in the hash table instead.
48struct StaticSampler {
49 uint32_t filter = 0;
50 uint32_t address_u = 0;
51 uint32_t address_v = 0;
52 uint32_t address_w = 0;
53 float mip_lod_bias = 0.0f;
54 uint32_t max_anisotropy = 0;
55 uint32_t comparison_func = 0;
56 uint32_t border_color = 0; // 0 transparent-black .. 4 opaque-white
57 float min_lod = 0.0f;
58 float max_lod = 0.0f;
59 uint32_t shader_register = 0;
60 uint32_t register_space = 0;
61 Visibility visibility = Visibility::All;
62};
63
64struct RootParameter {
65 ParamType type = ParamType::Constants;
66 Visibility visibility = Visibility::All;
67 // Constants:
68 uint32_t num_values = 0; // shader register + space describe the slot
69 uint32_t shader_register = 0;
70 uint32_t register_space = 0;
71 // Root descriptor:
72 uint32_t descriptor_register = 0;
73 uint32_t descriptor_space = 0;
74 // Descriptor table:
75 std::vector<DescriptorRange> ranges;
76};
77
78struct RootSignature {
79 Version version = Version::V1_1;
80 std::vector<RootParameter> params; // at most 64 root parameters (D3D12)
81 std::vector<StaticSampler> static_samplers;
82 uint32_t flags = 0; // low 16 bits: PC meaning; high byte: Xbox type bits
83};
84
85// Where one packed dword came from (provenance for diagnostics).
86struct DwordProvenance {
87 uint32_t param_index = 0; // index into RootSignature::params
88 uint32_t sub_index = 0; // constant index, or 0 = VA lo, 1 = VA hi
89};
90
91struct PackResult {
92 bool ok = false;
93 std::string error; // set when !ok; names the refusing parameter
94 std::array<uint32_t, 32> dwords{}; // valid dwords [0, dword_count)
95 uint32_t dword_count = 0;
96 std::vector<DwordProvenance> provenance; // same length as dword_count
97 uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit
98};
99
100constexpr uint32_t kMaxUserSgprs = 32;
101constexpr uint32_t kMaxD3d12Cost = 64;
102
103// Packs root parameters in order. Static samplers consume no dwords.
104// Fails (ok == false) when the signature needs more than 32 user SGPRs
105// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword
106// D3D12 cost limit, or holds more than 64 root parameters.
107[[nodiscard]] PackResult pack(const RootSignature& sig);
108
109// D3D12 cost of one parameter against the 64-dword limit.
110[[nodiscard]] constexpr uint32_t param_cost(ParamType type, uint32_t num_values) noexcept {
111 switch (type) {
112 case ParamType::Constants:
113 return num_values;
114 case ParamType::Descriptor:
115 return 2;
116 case ParamType::Table:
117 return 1;
118 }
119 return 0;
120}
121
122// Canonical binary codec for caching root signatures (magic "LRS1",
123// little-endian). This is Leonida's own layout, NOT the Microsoft RTS0
124// format: it round-trips pack() inputs byte-exactly and is fully tested on
125// every CI leg. Never write game blobs in this format and claim otherwise.
126[[nodiscard]] std::vector<uint8_t> encode_canonical(const RootSignature& sig);
127
128struct DecodeResult {
129 bool ok = false;
130 std::string error;
131 RootSignature sig;
132};
133
134[[nodiscard]] DecodeResult decode_canonical(const uint8_t* data, size_t size);
135
136// RTS0 chunk parser (payload layout per the maintainer: offset table).
137//
138// The input is a whole DXBC container (what D3D12SerializeVersionedRootSignature
139// returns: "DXBC" magic, hash, size, chunk table). The parser walks the chunk
140// table exactly like tools/rdna2spirv.py:input_signature does, finds the
141// "RTS0" chunk and decodes its payload: version, counts and table offsets,
142// then a parameter table of {d3d_type, visibility, offset} entries with
143// payloads at their offsets (d3d types follow D3D12_ROOT_PARAMETER_TYPE
144// numbering). A bare payload without the DXBC header is also accepted
145// (unit-test path). Every deviation the oracle test finds is a hard failure
146// to investigate, not a quirk to absorb.
147// Returns ok == false with a reason for unknown versions or truncation.
148[[nodiscard]] DecodeResult parse_rts0(const uint8_t* data, size_t size);
149
150} // namespace rt::rootsig
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
new file mode 100644
index 000000000..f9c2ba186
--- /dev/null
+++ b/runtime/test/descriptor_table_test.cpp
@@ -0,0 +1,234 @@
1// Unit tests for the descriptor hash table (set 0, binding 2 contract).
2// Tests FNV-1a hashing, T#/S# key generation, probe resolution, dynamic resizing,
3// GPU buffer serialization, and multithreaded insertion.
4#include "../src/descriptor_table.h"
5
6#include <cassert>
7#include <cstdio>
8#include <cstring>
9#include <random>
10#include <thread>
11#include <vector>
12
13#define EXPECT(condition) do { \
14 if (!(condition)) { \
15 std::fprintf(stderr, "assertion failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \
16 return 1; \
17 } \
18} while (0)
19
20using namespace leonida;
21
22int test_fnv1a_hash_matches_contract() {
23 // Verified against vk_texture_test.cpp key_hash and rdna2spirv.py desc_probe
24 const std::uint32_t zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0};
25 std::uint32_t expected_zero_hash = 2166136261u;
26 for (int i = 0; i < 8; ++i) expected_zero_hash = (expected_zero_hash ^ 0) * 16777619u;
27 EXPECT(hash_descriptor_key(zeros) == expected_zero_hash);
28
29 const std::uint32_t sample_key[8] = {
30 0x12345678, 0x9abcdef0, 0x11223344, 0x55667788,
31 0x99aabbcc, 0xddeeff00, 0x01020304, 0x05060708
32 };
33 std::uint32_t expected_hash = 2166136261u;
34 for (int i = 0; i < 8; ++i) expected_hash = (expected_hash ^ sample_key[i]) * 16777619u;
35 EXPECT(hash_descriptor_key(sample_key) == expected_hash);
36 return 0;
37}
38
39int test_ssharp_key_padding() {
40 const std::uint32_t ssharp[4] = {0x92, 0xc00000, 0x14500000, 0x0};
41 const auto key = make_ssharp_key(ssharp);
42 EXPECT(key[0] == 0x92);
43 EXPECT(key[1] == 0xc00000);
44 EXPECT(key[2] == 0x14500000);
45 EXPECT(key[3] == 0x0);
46 EXPECT(key[4] == 0xFFFFFFFFu);
47 EXPECT(key[5] == 0xFFFFFFFFu);
48 EXPECT(key[6] == 0xFFFFFFFFu);
49 EXPECT(key[7] == 0xFFFFFFFFu);
50 return 0;
51}
52
53int test_basic_insertion_and_lookup() {
54 DescriptorTable table(16);
55 EXPECT(table.capacity() == 16);
56 EXPECT(table.mask() == 15);
57 EXPECT(table.size() == 0);
58
59 const std::uint32_t tsharp[8] = {
60 0x1000, 0x2000, 0x3000, 0x4000,
61 0x5000, 0x6000, 0x7000, 0x8000
62 };
63 EXPECT(table.lookup(tsharp) == 0);
64 EXPECT(!table.contains(tsharp));
65
66 EXPECT(table.insert(tsharp, 1));
67 EXPECT(table.size() == 1);
68 EXPECT(table.contains(tsharp));
69 EXPECT(table.lookup(tsharp) == 1);
70
71 // Duplicate key updates in place
72 EXPECT(table.insert(tsharp, 42));
73 EXPECT(table.size() == 1);
74 EXPECT(table.lookup(tsharp) == 42);
75
76 // S# key
77 const std::uint32_t ssharp[4] = {0xa, 0xb, 0xc, 0xd};
78 const auto skey = make_ssharp_key(ssharp);
79 EXPECT(table.insert(skey, 7));
80 EXPECT(table.size() == 2);
81 EXPECT(table.lookup(skey) == 7);
82 EXPECT(table.lookup(tsharp) == 42);
83 return 0;
84}
85
86int test_load_factor_and_growth() {
87 // Start with 16 slots. Load factor threshold 50% means max 8 entries before growth.
88 DescriptorTable table(16);
89 EXPECT(table.capacity() == 16);
90
91 std::vector<DescriptorKey> keys;
92 for (std::uint32_t i = 1; i <= 20; ++i) {
93 std::uint32_t k[8] = {i, i * 2, i * 3, i * 4, i * 5, i * 6, i * 7, i * 8};
94 keys.push_back(make_tsharp_key(k));
95 EXPECT(table.insert(keys.back(), i + 100));
96 }
97
98 EXPECT(table.size() == 20);
99 EXPECT(table.capacity() >= 64); // Doubled from 16 -> 32 -> 64
100 EXPECT(table.mask() == table.capacity() - 1);
101
102 // Verify all 20 keys resolve to their exact indices after growths
103 for (std::uint32_t i = 1; i <= 20; ++i) {
104 EXPECT(table.lookup(keys[i - 1]) == i + 100);
105 }
106 return 0;
107}
108
109int test_probe_collision_resolution() {
110 DescriptorTable table(64);
111
112 // Create 4 distinct keys that share the exact same hash
113 // We can forge keys that share hash or test linear collision handling
114 std::uint32_t k1[8] = {1, 0, 0, 0, 0, 0, 0, 0};
115 std::uint32_t k2[8] = {2, 0, 0, 0, 0, 0, 0, 0};
116 std::uint32_t k3[8] = {3, 0, 0, 0, 0, 0, 0, 0};
117
118 EXPECT(table.insert(k1, 10));
119 EXPECT(table.insert(k2, 20));
120 EXPECT(table.insert(k3, 30));
121
122 EXPECT(table.lookup(k1) == 10);
123 EXPECT(table.lookup(k2) == 20);
124 EXPECT(table.lookup(k3) == 30);
125 return 0;
126}
127
128int test_gpu_buffer_serialization() {
129 DescriptorTable table(16);
130 const std::uint32_t t1[8] = {10, 20, 30, 40, 50, 60, 70, 80};
131 const std::uint32_t s1[4] = {1, 2, 3, 4};
132 const auto skey = make_ssharp_key(s1);
133
134 EXPECT(table.insert(t1, 5));
135 EXPECT(table.insert(skey, 9));
136
137 const auto gpu_buf = table.build_gpu_buffer(false);
138 EXPECT(gpu_buf.size() == 1 + 16 * 10);
139 EXPECT(gpu_buf[0] == 15); // mask
140
141 // Verify lookup by traversing the generated buffer using the exact shader logic
142 const auto shader_lookup = [&](const std::uint32_t key[8]) -> std::uint32_t {
143 const std::uint32_t mask = gpu_buf[0];
144 const std::uint32_t h = hash_descriptor_key(key);
145 for (std::uint32_t k = 0; k < 8; ++k) {
146 const std::uint32_t slot = (h + k) & mask;
147 const std::size_t base = 1 + slot * 10;
148 bool match = true;
149 for (std::size_t j = 0; j < 8; ++j) {
150 if (gpu_buf[base + j] != key[j]) {
151 match = false;
152 break;
153 }
154 }
155 if (match) {
156 return gpu_buf[base + 8]; // index
157 }
158 }
159 return 0;
160 };
161
162 EXPECT(shader_lookup(t1) == 5);
163 EXPECT(shader_lookup(skey.data()) == 9);
164
165 const std::uint32_t missing[8] = {99, 99, 99, 99, 99, 99, 99, 99};
166 EXPECT(shader_lookup(missing) == 0);
167
168 // Test write_to_buffer
169 std::vector<std::uint32_t> raw_copy(gpu_buf.size());
170 table.write_to_buffer(raw_copy.data(), true);
171 EXPECT(raw_copy[0] == 15);
172 for (std::size_t s = 0; s < 16; ++s) {
173 EXPECT(raw_copy[1 + s * 10 + 9] == 0); // clear_pad = true
174 }
175 return 0;
176}
177
178int test_multithreaded_insert_and_lookup() {
179 DescriptorTable table(32);
180 constexpr int kThreads = 4;
181 constexpr int kPerThread = 50;
182
183 std::vector<std::thread> workers;
184 for (int t = 0; t < kThreads; ++t) {
185 workers.emplace_back([&table, t] {
186 for (int i = 0; i < kPerThread; ++i) {
187 const std::uint32_t id = static_cast<std::uint32_t>(t * kPerThread + i + 1);
188 std::uint32_t key[8] = {id, id * 3, id * 7, id * 11, id * 13, id * 17, id * 19, id * 23};
189 table.insert(key, id);
190 }
191 });
192 }
193
194 for (auto& w : workers) {
195 w.join();
196 }
197
198 EXPECT(table.size() == kThreads * kPerThread);
199 for (int t = 0; t < kThreads; ++t) {
200 for (int i = 0; i < kPerThread; ++i) {
201 const std::uint32_t id = static_cast<std::uint32_t>(t * kPerThread + i + 1);
202 std::uint32_t key[8] = {id, id * 3, id * 7, id * 11, id * 13, id * 17, id * 19, id * 23};
203 EXPECT(table.lookup(key) == id);
204 }
205 }
206 return 0;
207}
208
209int test_clear_resets_table() {
210 DescriptorTable table(16);
211 std::uint32_t k[8] = {1, 2, 3, 4, 5, 6, 7, 8};
212 table.insert(k, 100);
213 EXPECT(table.size() == 1);
214 EXPECT(table.lookup(k) == 100);
215
216 table.clear();
217 EXPECT(table.size() == 0);
218 EXPECT(table.lookup(k) == 0);
219 return 0;
220}
221
222int main() {
223 EXPECT(test_fnv1a_hash_matches_contract() == 0);
224 EXPECT(test_ssharp_key_padding() == 0);
225 EXPECT(test_basic_insertion_and_lookup() == 0);
226 EXPECT(test_load_factor_and_growth() == 0);
227 EXPECT(test_probe_collision_resolution() == 0);
228 EXPECT(test_gpu_buffer_serialization() == 0);
229 EXPECT(test_multithreaded_insert_and_lookup() == 0);
230 EXPECT(test_clear_resets_table() == 0);
231
232 std::printf("descriptor_table_test: all tests passed (0 failures)\n");
233 return 0;
234}
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
new file mode 100644
index 000000000..d60dfae3a
--- /dev/null
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -0,0 +1,120 @@
1// Windows oracle for the RTS0 parser hypothesis (needs a real PC d3d12.lib).
2//
3// Builds synthetic versioned root-signature descriptors by hand (no game
4// data), serializes each with Microsoft's D3D12SerializeVersionedRootSignature,
5// and requires rt::rootsig::parse_rts0 to recover the same model. If the
6// hypothesis layout in root_signature.cpp ever disagrees with the real
7// serializer, this fails loudly here instead of corrupting draws silently.
8// NOT portable: runs on Windows CI only, like root_sig_test.cpp.
9#include <windows.h>
10#include <d3d12.h>
11
12#include <cstdint>
13#include <cstdio>
14#include <vector>
15
16#include "root_signature.h"
17
18namespace {
19
20int g_failures = 0;
21
22void check(bool condition, const char* what) {
23 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
24 if (!condition) ++g_failures;
25}
26
27struct Blobs {
28 ID3DBlob* blob = nullptr;
29 ID3DBlob* error = nullptr;
30 ~Blobs() {
31 if (blob) blob->Release();
32 if (error) error->Release();
33 }
34};
35
36D3D12_VERSIONED_ROOT_SIGNATURE_DESC make_desc(
37 const D3D12_ROOT_PARAMETER1* params, uint32_t nparams) {
38 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
39 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
40 desc.Desc_1_1.NumParameters = nparams;
41 desc.Desc_1_1.pParameters = params;
42 desc.Desc_1_1.NumStaticSamplers = 0;
43 desc.Desc_1_1.pStaticSamplers = nullptr;
44 desc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
45 return desc;
46}
47
48bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) {
49 const auto* bytes = static_cast<const uint8_t*>(blob->GetBufferPointer());
50 const size_t size = blob->GetBufferSize();
51 // Diagnostics first: if the layout hypothesis is wrong, the CI log shows
52 // the real bytes instead of just a crash or a bare failure.
53 std::printf("oracle blob: %zu bytes: ", size);
54 for (size_t i = 0; i < 32 && i < size; ++i) {
55 std::printf("%02x", bytes[i]);
56 }
57 std::printf("\n");
58 std::fflush(stdout);
59 const rt::rootsig::DecodeResult d = rt::rootsig::parse_rts0(bytes, size);
60 if (!d.ok) {
61 std::printf("oracle parse failed: %s\n", d.error.c_str());
62 return false;
63 }
64 model = d.sig;
65 return true;
66}
67
68} // namespace
69
70int main() {
71 using namespace rt::rootsig;
72
73 // 4 constants (VS-visible) + 1 CBV: parses back to the same model and
74 // packs to 6 dwords, exactly like the portable packer says for 1.1.
75 D3D12_ROOT_PARAMETER1 params[2]{};
76 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
77 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
78 params[0].Constants.ShaderRegister = 0;
79 params[0].Constants.RegisterSpace = 0;
80 params[0].Constants.Num32BitValues = 4;
81 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
82 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
83 params[1].Descriptor.ShaderRegister = 2;
84 params[1].Descriptor.RegisterSpace = 0;
85 params[1].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE;
86
87 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = make_desc(params, 2);
88 Blobs blobs;
89 const HRESULT hr =
90 D3D12SerializeVersionedRootSignature(&desc, &blobs.blob, &blobs.error);
91 check(hr == S_OK, "Microsoft serializer accepts the synthetic desc");
92 if (hr != S_OK) {
93 if (blobs.error != nullptr) {
94 std::printf("serializer error: %s\n",
95 static_cast<const char*>(blobs.error->GetBufferPointer()));
96 }
97 std::printf("%d FAILURES\n", g_failures + 1);
98 return 1;
99 }
100
101 RootSignature model;
102 check(parse_blob(blobs.blob, model), "oracle blob parses");
103 if (g_failures != 0) {
104 // Never index into a model that failed to parse (that segfaulted CI).
105 std::printf("%d FAILURES\n", g_failures);
106 return 1;
107 }
108 check(model.params.size() == 2, "oracle model has 2 params");
109 check(model.params[0].type == ParamType::Constants &&
110 model.params[0].num_values == 4 &&
111 model.params[0].visibility == Visibility::Vertex,
112 "oracle constants match");
113 check(model.params[1].type == ParamType::Descriptor,
114 "oracle CBV matches");
115 const PackResult packed = pack(model);
116 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
117
118 if (g_failures != 0) std::printf("%d FAILURES\n", g_failures);
119 return g_failures == 0 ? 0 : 1;
120}
diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp
new file mode 100644
index 000000000..92ef8347f
--- /dev/null
+++ b/runtime/test/root_signature_test.cpp
@@ -0,0 +1,221 @@
1// Portable tests for runtime/src/root_signature.{h,cpp} (no windows.h).
2//
3// Own main + PASS/FAIL lines like the other runtime tests; returns nonzero
4// on any failure so CTest gates on it. Everything here is hand-built: no
5// game data, no DXBC, no serializer needed.
6#include <cstdint>
7#include <cstdio>
8#include <vector>
9
10#include "root_signature.h"
11
12namespace {
13
14int g_failures = 0;
15
16void check(bool condition, const char* what) {
17 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
18 if (!condition) ++g_failures;
19}
20
21rt::rootsig::RootParameter consts(uint32_t n) {
22 rt::rootsig::RootParameter p;
23 p.type = rt::rootsig::ParamType::Constants;
24 p.num_values = n;
25 return p;
26}
27
28rt::rootsig::RootParameter view() {
29 rt::rootsig::RootParameter p;
30 p.type = rt::rootsig::ParamType::Descriptor;
31 return p;
32}
33
34rt::rootsig::RootParameter table() {
35 rt::rootsig::RootParameter p;
36 p.type = rt::rootsig::ParamType::Table;
37 p.ranges.push_back({0, 8});
38 return p;
39}
40
41void put_u32(std::vector<uint8_t>& out, uint32_t v) {
42 out.push_back(static_cast<uint8_t>(v));
43 out.push_back(static_cast<uint8_t>(v >> 8));
44 out.push_back(static_cast<uint8_t>(v >> 16));
45 out.push_back(static_cast<uint8_t>(v >> 24));
46}
47
48// Hand-built RTS0 payload in the offset-table layout the maintainer
49// described: header, parameter table, then payloads at their offsets.
50std::vector<uint8_t> build_payload() {
51 std::vector<uint8_t> p;
52 put_u32(p, 2); // version 1.1
53 put_u32(p, 2); // 2 params
54 put_u32(p, 24); // params table offset
55 put_u32(p, 0); // 0 samplers
56 put_u32(p, 0); // samplers offset
57 put_u32(p, 0x03000000u); // Xbox flags
58 // entry 0: constants at 48; entry 1: CBV descriptor at 60.
59 put_u32(p, 1);
60 put_u32(p, 0);
61 put_u32(p, 48);
62 put_u32(p, 2);
63 put_u32(p, 4);
64 put_u32(p, 60);
65 put_u32(p, 7); // register (ignored by packer)
66 put_u32(p, 0); // space
67 put_u32(p, 3); // 3 values
68 put_u32(p, 0); // register
69 put_u32(p, 0); // space
70 put_u32(p, 0); // 1.1 descriptor flags
71 return p;
72}
73
74} // namespace
75
76int main() {
77 using namespace rt::rootsig;
78
79 // Mixed signature: 4 constants + CBV + table + 1 static sampler.
80 {
81 RootSignature sig;
82 sig.params = {consts(4), view(), table()};
83 StaticSampler s;
84 s.shader_register = 3;
85 sig.static_samplers = {s};
86 const PackResult r = pack(sig);
87 check(r.ok, "mixed signature packs");
88 check(r.dword_count == 8, "mixed signature uses 8 dwords");
89 check(r.d3d12_cost == 4 + 2 + 1, "mixed signature costs 7");
90 check(r.provenance.size() == 8 && r.provenance[0].param_index == 0 &&
91 r.provenance[0].sub_index == 0 && r.provenance[4].param_index == 1 &&
92 r.provenance[4].sub_index == 0 && r.provenance[5].sub_index == 1 &&
93 r.provenance[6].param_index == 2,
94 "provenance tracks param and sub-dword");
95 }
96
97 // Exactly 32 dwords still fits.
98 {
99 RootSignature sig;
100 for (int i = 0; i < 16; ++i) sig.params.push_back(view());
101 const PackResult r = pack(sig);
102 check(r.ok && r.dword_count == 32, "16 views fill 32 dwords");
103 }
104
105 // 34 dwords: spill is refused loudly, never truncated.
106 {
107 RootSignature sig;
108 for (int i = 0; i < 17; ++i) sig.params.push_back(view());
109 const PackResult r = pack(sig);
110 check(!r.ok && r.error.find("spill") != std::string::npos,
111 "17 views refused as spill");
112 }
113
114 // 65 constants exceed the 64-dword D3D12 cost limit.
115 {
116 RootSignature sig;
117 sig.params = {consts(65)};
118 const PackResult r = pack(sig);
119 check(!r.ok && r.error.find("64-dword") != std::string::npos,
120 "65 constants refused by cost limit");
121 }
122
123 // Canonical codec round-trips byte-exactly, sampler included.
124 {
125 RootSignature sig;
126 sig.version = Version::V1_0;
127 sig.params = {consts(2), table()};
128 sig.flags = 0x03000000u; // Xbox high byte survives the model
129 StaticSampler s;
130 s.filter = 21;
131 s.mip_lod_bias = 0.5f;
132 sig.static_samplers = {s};
133 const std::vector<uint8_t> bytes = encode_canonical(sig);
134 const DecodeResult d = decode_canonical(bytes.data(), bytes.size());
135 check(d.ok, "canonical round-trip decodes");
136 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 2 &&
137 d.sig.params[1].ranges.size() == 1 &&
138 d.sig.static_samplers.size() == 1 && d.sig.flags == 0x03000000u &&
139 d.sig.static_samplers[0].filter == 21,
140 "canonical round-trip preserves model");
141 }
142
143 // Canonical decoder controls: bad magic, truncation, trailing bytes.
144 {
145 const std::vector<uint8_t> bad = {0, 1, 2, 3};
146 check(!decode_canonical(bad.data(), bad.size()).ok, "bad magic rejected");
147 RootSignature sig;
148 sig.params = {consts(1)};
149 const std::vector<uint8_t> bytes = encode_canonical(sig);
150 check(!decode_canonical(bytes.data(), bytes.size() - 1).ok,
151 "truncated canonical rejected");
152 std::vector<uint8_t> trailed = bytes;
153 trailed.push_back(0);
154 check(!decode_canonical(trailed.data(), trailed.size()).ok,
155 "trailing bytes rejected");
156 }
157
158 // RTS0 hypothesis: a hand-built blob per the documented layout parses.
159 // Hand-built RTS0 payload in the offset-table layout the maintainer
160 // described: header, parameter table, then payloads at their offsets.
161 {
162 const std::vector<uint8_t> payload = build_payload();
163 const DecodeResult d = parse_rts0(payload.data(), payload.size());
164 check(d.ok, "hand-built RTS0 parses");
165 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 3 &&
166 d.sig.flags == 0x03000000u,
167 "RTS0 model matches hand-built blob");
168 const PackResult r = pack(d.sig);
169 check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords");
170 }
171
172 // RTS0 controls: unknown version, wild offsets and truncation fail loudly.
173 {
174 std::vector<uint8_t> blob;
175 put_u32(blob, 9); // unknown version
176 put_u32(blob, 0);
177 put_u32(blob, 0);
178 put_u32(blob, 0);
179 put_u32(blob, 0);
180 put_u32(blob, 0);
181 const DecodeResult d = parse_rts0(blob.data(), blob.size());
182 check(!d.ok, "unknown RTS0 version rejected");
183 std::vector<uint8_t> cut = {1, 0};
184 check(!parse_rts0(cut.data(), cut.size()).ok, "truncated RTS0 rejected");
185 std::vector<uint8_t> wild = build_payload();
186 // Corrupt the params offset to point past the end.
187 wild[8] = 0xFF;
188 wild[9] = 0xFF;
189 wild[10] = 0xFF;
190 wild[11] = 0xFF;
191 check(!parse_rts0(wild.data(), wild.size()).ok, "wild offset rejected");
192 }
193
194 // DXBC container walk: a hand-built container with one RTS0 chunk parses
195 // through the chunk table (same path the MS serializer blob takes).
196 {
197 const std::vector<uint8_t> payload = build_payload();
198 std::vector<uint8_t> blob;
199 blob.insert(blob.end(), {'D', 'X', 'B', 'C'});
200 blob.insert(blob.end(), 16, 0); // hash
201 put_u32(blob, 1); // version
202 put_u32(blob, 0); // file size (patched below)
203 put_u32(blob, 1); // 1 chunk
204 put_u32(blob, 36); // chunk offset: 4 magic + 16 hash + 4 ver + 4 size + 4 count + 4 offset
205 blob.insert(blob.end(), {'R', 'T', 'S', '0'});
206 put_u32(blob, static_cast<uint32_t>(payload.size()));
207 blob.insert(blob.end(), payload.begin(), payload.end());
208 const uint32_t total = static_cast<uint32_t>(blob.size());
209 blob[24] = static_cast<uint8_t>(total);
210 blob[25] = static_cast<uint8_t>(total >> 8);
211 blob[26] = static_cast<uint8_t>(total >> 16);
212 blob[27] = static_cast<uint8_t>(total >> 24);
213 const DecodeResult d = parse_rts0(blob.data(), blob.size());
214 check(d.ok, "DXBC container walk finds RTS0");
215 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 3,
216 "walked RTS0 model matches payload");
217 }
218
219 if (g_failures != 0) std::printf("%d FAILURES\n", g_failures);
220 return g_failures == 0 ? 0 : 1;
221}
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 180d48ec5..09730a2b0 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -3,8 +3,9 @@
3 python3 -I runtime/test/shaders/build.py <out dir> [name ...] 3 python3 -I runtime/test/shaders/build.py <out dir> [name ...]
4 4
5Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its 5Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its
6path, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are staged in a temporary 6path or to a whole command, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are
7directory. After validation, the build writes <out>/spirv/<name>.spv and the translator metadata. 7staged in a temporary directory. After validation, the build writes <out>/spirv/<name>.spv and the translator
8metadata.
8 9
9Compute shaders can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments. 10Compute shaders can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments.
10The stage comes from the name's prefix. Mesh and geometry shaders (ms_, gs_) also need a DXBC container with 11The stage comes from the name's prefix. Mesh and geometry shaders (ms_, gs_) also need a DXBC container with
@@ -20,10 +21,15 @@ import tempfile
20from pathlib import Path 21from pathlib import Path
21 22
22HERE = os.path.dirname(os.path.abspath(__file__)) 23HERE = os.path.dirname(os.path.abspath(__file__))
23TRANSLATOR = os.path.join(HERE, "..", "..", "..", "tools", "rdna2spirv.py") 24TOOLS = os.path.join(HERE, "..", "..", "..", "tools")
24LLVM_MC = os.environ.get("LLVM_MC", "llvm-mc") 25TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py")
26sys.path.insert(0, TOOLS)
27import mc_command # noqa: E402
28
29MC = mc_command.mc_command()
30RSRC2, GROUP = 0x8088, (64, 1, 1)
25sys.path.insert(0, HERE) # this script is also run with python -I 31sys.path.insert(0, HERE) # this script is also run with python -I
26from compute_fixture import compute_header 32from compute_fixture import compute_header # noqa: E402
27 33
28 34
29def asm_mattr(path): 35def asm_mattr(path):
@@ -45,12 +51,14 @@ def translate_tests(work, names):
45 fssm.mkdir() 51 fssm.mkdir()
46 for n in names: 52 for n in names:
47 asm_path = os.path.join(HERE, n + ".asm") 53 asm_path = os.path.join(HERE, n + ".asm")
54 raw = Path(asm_path).read_text(encoding="utf-8")
48 mattr = asm_mattr(asm_path) 55 mattr = asm_mattr(asm_path)
49 cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 56 cmd = MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
50 if mattr: 57 if mattr:
51 cmd.append(f"-mattr={mattr}") 58 cmd.append(f"-mattr={mattr}")
52 cmd += ["-show-encoding", asm_path] 59 cmd.append("-show-encoding")
53 r = subprocess.run(cmd, capture_output=True, text=True) 60 # Feed the text on stdin: an LLVM_MC command that runs in WSL cannot open a Windows path argument.
61 r = subprocess.run(cmd, input=raw, capture_output=True, text=True)
54 if r.returncode or "error:" in r.stderr: 62 if r.returncode or "error:" in r.stderr:
55 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") 63 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}")
56 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. 64 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first.
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 15c2a0c60..75f9a2d50 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -29,7 +29,9 @@ UNSUPPORTED = 77 # a test tool exits with
29COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh", "1", "bvh"), 29COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh", "1", "bvh"),
30 ("cs_workgroup_yz", "2x3x4", "workgroup_yz")] 30 ("cs_workgroup_yz", "2x3x4", "workgroup_yz")]
31CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800] 31CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800]
32CS_DUMPS = [("cs_store", CS_STORE), ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]), 32CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c]
33WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm")
34CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]),
33 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]), 35 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]),
34 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48])] 36 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48])]
35# Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups. 37# Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups.
@@ -229,7 +231,7 @@ def main():
229 require_wave64=not W64_EMULATED))) 231 require_wave64=not W64_EMULATED)))
230 for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated 232 for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated
231 results.append((name, compute_test(tools, spirv, name, "1", "dump", 233 results.append((name, compute_test(tools, spirv, name, "1", "dump",
232 require_wave64=name != "cs_store" and not W64_EMULATED, 234 require_wave64=name not in WAVE32_DUMPS and not W64_EMULATED,
233 expected_words=want))) 235 expected_words=want)))
234 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 236 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1
235 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, 237 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED,
diff --git a/runtime/test/shaders/cs_smem_soffset_imm.asm b/runtime/test/shaders/cs_smem_soffset_imm.asm
new file mode 100644
index 000000000..399de1860
--- /dev/null
+++ b/runtime/test/shaders/cs_smem_soffset_imm.asm
@@ -0,0 +1,61 @@
1; SMEM loads that carry a register offset AND an immediate (llvm-mc: "sOFF offset:IMM"): address = base + soffset + imm.
2; Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel:
3; soffset 8 + imm 4 reads the dword at +12. s_load_dword shares the SMEM encoding; applying the rule to it is an inference.
4; Thread 0 seeds heap bytes 0x10..0x30 with 0x5eed0000 + byte offset, then loads with s8 = 0x10:
5; s_buffer_load_dword s9, s[0:3], s8 offset:0x14 -> byte 0x24 (imm dropped: 0x10, s8 dropped: 0x14)
6; s_load_dword s10, s[4:5], s8 offset:0x18 -> byte 0x28 (imm dropped: 0x10, s8 dropped: 0x18)
7; s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c -> bytes 0x2c, 0x30 (imm dropped: 0x10, 0x14; s8 dropped: 0x1c, 0x20)
8; and writes s9, s10, s12, s13 to out[0..3]; out[4..7] keep the seeds of bytes 0x10..0x1c.
9; All offsets are multiples of 4 and inside the buffer, so alignment and num_records play no part.
10; Run: vk_compute_test cs_smem_soffset_imm.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0028 0x5eed002c 0x5eed0030
11; 0x5eed0010 0x5eed0014 0x5eed0018 0x5eed001c (1592590372 1592590376 1592590380 1592590384 1592590352 1592590356
12; 1592590360 1592590364). Same FSSM header as cs_lds.
13v_cmpx_eq_u32_e32 0, v0
14v_mov_b32 v1, 0x5eed0010
15v_mov_b32 v2, 0x10
16buffer_store_dword v1, v2, s[0:3], 0 offen
17v_mov_b32 v1, 0x5eed0014
18v_mov_b32 v2, 0x14
19buffer_store_dword v1, v2, s[0:3], 0 offen
20v_mov_b32 v1, 0x5eed0018
21v_mov_b32 v2, 0x18
22buffer_store_dword v1, v2, s[0:3], 0 offen
23v_mov_b32 v1, 0x5eed001c
24v_mov_b32 v2, 0x1c
25buffer_store_dword v1, v2, s[0:3], 0 offen
26v_mov_b32 v1, 0x5eed0020
27v_mov_b32 v2, 0x20
28buffer_store_dword v1, v2, s[0:3], 0 offen
29v_mov_b32 v1, 0x5eed0024
30v_mov_b32 v2, 0x24
31buffer_store_dword v1, v2, s[0:3], 0 offen
32v_mov_b32 v1, 0x5eed0028
33v_mov_b32 v2, 0x28
34buffer_store_dword v1, v2, s[0:3], 0 offen
35v_mov_b32 v1, 0x5eed002c
36v_mov_b32 v2, 0x2c
37buffer_store_dword v1, v2, s[0:3], 0 offen
38v_mov_b32 v1, 0x5eed0030
39v_mov_b32 v2, 0x30
40buffer_store_dword v1, v2, s[0:3], 0 offen
41s_waitcnt vmcnt(0)
42s_mov_b32 s4, 0
43s_mov_b32 s5, 0
44s_mov_b32 s8, 0x10
45s_buffer_load_dword s9, s[0:3], s8 offset:0x14
46s_load_dword s10, s[4:5], s8 offset:0x18
47s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c
48s_waitcnt lgkmcnt(0)
49v_mov_b32 v1, s9
50v_mov_b32 v2, 0
51buffer_store_dword v1, v2, s[0:3], 0 offen
52v_mov_b32 v1, s10
53v_mov_b32 v2, 4
54buffer_store_dword v1, v2, s[0:3], 0 offen
55v_mov_b32 v1, s12
56v_mov_b32 v2, 8
57buffer_store_dword v1, v2, s[0:3], 0 offen
58v_mov_b32 v1, s13
59v_mov_b32 v2, 12
60buffer_store_dword v1, v2, s[0:3], 0 offen
61s_endpgm
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index a46338bf6..fafc8ef50 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -34,23 +34,7 @@ static std::vector<uint32_t> read_spv(const char* p) {
34 return w; 34 return w;
35} 35}
36 36
37// Same hash as the translator's desc_lookup: FNV-1a over the 8 key dwords (whole dwords, not bytes). 37#include "../src/descriptor_table.h"
38static uint32_t key_hash(const uint32_t k[8]) {
39 uint32_t h = 2166136261u;
40 for (int i = 0; i < 8; i++) h = (h ^ k[i]) * 16777619u;
41 return h;
42}
43static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index) {
44 uint32_t mask = t[0], h = key_hash(key);
45 for (uint32_t k = 0; k < 8; k++) {
46 uint32_t slot = (h + k) & mask, base = slot * 10;
47 if (t[base + 10] == 0xA11CA7ED) continue; // pad dword marks a used slot (host-side only)
48 for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j];
49 t[base + 9] = index;
50 t[base + 10] = 0xA11CA7ED;
51 return;
52 }
53}
54 38
55int main(int argc, char** argv) { 39int main(int argc, char** argv) {
56 if (argc < 9) { std::fprintf(stderr, "usage: vk_texture_test vs fs out ptr_sgpr s0 s1 s2 s3\n"); return 2; } 40 if (argc < 9) { std::fprintf(stderr, "usage: vk_texture_test vs fs out ptr_sgpr s0 s1 s2 s3\n"); return 2; }
@@ -133,11 +117,10 @@ int main(int argc, char** argv) {
133 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; 117 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
134 VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); 118 VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai);
135 // Descriptor hash table: 16 slots. 119 // Descriptor hash table: 16 slots.
136 std::vector<uint32_t> table(1 + 16 * 10 + 10, 0); 120 leonida::DescriptorTable desc_table(16);
137 table[0] = 15; 121 desc_table.insert(tsharp, 1);
138 table_insert(table, tsharp, 1); 122 desc_table.insert(ssharp, 1);
139 table_insert(table, ssharp, 1); 123 const auto table = desc_table.build_gpu_buffer(true);
140 for (uint32_t s = 0; s <= 16; s++) if (s * 10 + 10 < table.size() && table[s * 10 + 10] == 0xA11CA7ED) table[s * 10 + 10] = 0;
141 VkBuffer tb; VkDeviceMemory tbm; void* tbp; 124 VkBuffer tb; VkDeviceMemory tbm; void* tbp;
142 CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp)); 125 CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp));
143 std::memcpy(tbp, table.data(), table.size() * 4); 126 std::memcpy(tbp, table.data(), table.size() * 4);
diff --git a/runtime/test/vulkan_loader.h b/runtime/test/vulkan_loader.h
index 43a54d242..a1a461ef0 100644
--- a/runtime/test/vulkan_loader.h
+++ b/runtime/test/vulkan_loader.h
@@ -1,4 +1,4 @@
1// Loads the Vulkan loader at run time: vulkan-1.dll on Windows, libvulkan.so.1 elsewhere. No import library. 1// Loads the Vulkan loader at run time: vulkan-1.dll on Windows, MoltenVK on macOS, libvulkan.so.1 elsewhere. No import library.
2#pragma once 2#pragma once
3 3
4#ifndef VK_NO_PROTOTYPES 4#ifndef VK_NO_PROTOTYPES
@@ -20,6 +20,15 @@ inline PFN_vkGetInstanceProcAddr load_vulkan() {
20 constexpr auto library_name = "vulkan-1.dll"; 20 constexpr auto library_name = "vulkan-1.dll";
21 static const auto library = LoadLibraryA(library_name); 21 static const auto library = LoadLibraryA(library_name);
22 const auto entry = library ? GetProcAddress(library, "vkGetInstanceProcAddr") : nullptr; 22 const auto entry = library ? GetProcAddress(library, "vkGetInstanceProcAddr") : nullptr;
23#elif defined(__APPLE__)
24 // MoltenVK directly: through the loader it is a portability driver, which every vkCreateInstance here would
25 // have to opt into. The Vulkan SDK installs it in /usr/local/lib (a default search path), Homebrew does not.
26 constexpr auto library_name = "libMoltenVK.dylib";
27 static const auto library = [] {
28 auto handle = dlopen(library_name, RTLD_NOW | RTLD_LOCAL);
29 return handle ? handle : dlopen("/opt/homebrew/lib/libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
30 }();
31 const auto entry = library ? dlsym(library, "vkGetInstanceProcAddr") : nullptr;
23#else 32#else
24 constexpr auto library_name = "libvulkan.so.1"; 33 constexpr auto library_name = "libvulkan.so.1";
25 static const auto library = dlopen(library_name, RTLD_NOW | RTLD_LOCAL); 34 static const auto library = dlopen(library_name, RTLD_NOW | RTLD_LOCAL);
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1
new file mode 100644
index 000000000..ea72db26f
--- /dev/null
+++ b/scripts/build_llvm_mc.ps1
@@ -0,0 +1,82 @@
1# Builds a native Windows llvm-mc.exe with the AMDGPU target, for the shader disassembler, without WSL.
2# The official Windows LLVM build ships no llvm-mc.exe and no AMDGPU target. This fetches only the LLVM sources the
3# tool needs (sparse, shallow), builds llvm-mc alone with AMDGPU as the only target, keeps llvm-mc.exe (static CRT,
4# so it runs without the VC++ redistributable) and deletes the rest. Needs git, Python 3 and Visual Studio with the
5# C++ x64 tools; uses VS's CMake + Ninja, or the ones on PATH. About 2 GB of temporary space, 20-40 minutes.
6#
7# powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1
8# powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv
9param(
10 [string]$Version = "21.1.8",
11 [string]$Dest = (Join-Path $env:LOCALAPPDATA "Leonida\llvm-mc"),
12 [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"),
13 [switch]$NoEnv, # don't set LLVM_MC for the current user
14 [switch]$Keep # keep the sources and build folder (faster rebuilds)
15)
16$ErrorActionPreference = "Stop"
17
18foreach ($t in "git", "python") {
19 if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." }
20}
21$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
22$vs = & "$installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
23if (-not $vs) { throw "Visual Studio with the C++ x64 tools wasn't found." }
24$vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat"
25$jobs = [Math]::Max(1, [int]([Environment]::ProcessorCount / 2))
26
27$cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake"
28$cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe"
29$ninja = Join-Path $cmakeDir "Ninja\ninja.exe"
30if (-not ((Test-Path $cmake) -and (Test-Path $ninja))) {
31 $cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source
32 $ninja = (Get-Command ninja -ErrorAction SilentlyContinue).Source
33 if (-not ($cmake -and $ninja)) { throw "CMake and Ninja weren't found (install VS's 'C++ CMake tools' or put them on PATH)." }
34}
35
36$src = Join-Path $Temp "src"
37$out = Join-Path $Temp "build"
38if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) {
39 if (Test-Path $src) { Remove-Item -Recurse -Force $src }
40 New-Item -ItemType Directory -Force $Temp | Out-Null
41 & git clone --quiet --depth 1 --branch "llvmorg-$Version" --filter=blob:none --sparse https://github.com/llvm/llvm-project $src
42 if ($LASTEXITCODE -ne 0) { throw "git clone of llvmorg-$Version failed." }
43 & git -C $src sparse-checkout set llvm cmake third-party
44 if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout failed." }
45}
46
47# DIA SDK off: its headers need ATL, which the C++ build tools don't always include, and llvm-mc doesn't use it.
48$body = @"
49"$cmake" -S "$src\llvm" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=Release ^
50 -DLLVM_TARGETS_TO_BUILD=AMDGPU -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DLLVM_ENABLE_DIA_SDK=OFF ^
51 -DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_DOCS=OFF ^
52 -DLLVM_ENABLE_ZLIB=OFF -DLLVM_ENABLE_ZSTD=OFF -DLLVM_ENABLE_LIBXML2=OFF || exit /b 1
53"$cmake" --build "$out" --target llvm-mc -j $jobs || exit /b 1
54"@
55New-Item -ItemType Directory -Force $out | Out-Null
56# A .cmd file avoids cmd.exe's quote stripping on paths with spaces.
57$bat = Join-Path $Temp "_build.cmd"
58"@echo off`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat
59
60$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru
61$null = $p.Handle # keeps the exit code readable after WaitForExit
62try { $p.PriorityClass = "BelowNormal" } catch {}
63$p.WaitForExit()
64if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode)); the build folder is kept in $out" }
65
66# Same check shader_disasm.py makes before a run: one s_endpgm on the console's GPU.
67$exe = Join-Path $out "bin\llvm-mc.exe"
68# Through a file: a PowerShell pipe can prepend a BOM, which llvm-mc rejects as an invalid token.
69$probeFile = Join-Path $Temp "probe.txt"
70[IO.File]::WriteAllText($probeFile, "0x00 0x00 0x81 0xbf`n")
71$probe = & $exe --disassemble -triple=amdgcn -mcpu=gfx1013 $probeFile
72if ($LASTEXITCODE -ne 0 -or -not ($probe -match "s_endpgm")) { throw "the built llvm-mc didn't disassemble an s_endpgm" }
73
74New-Item -ItemType Directory -Force $Dest | Out-Null
75$final = Join-Path $Dest "llvm-mc.exe"
76Copy-Item -Force $exe $final
77if (-not $Keep) { Remove-Item -Recurse -Force $Temp }
78if (-not $NoEnv) {
79 [Environment]::SetEnvironmentVariable("LLVM_MC", $final, "User")
80 Write-Host "LLVM_MC set for this user (open a new terminal to pick it up)."
81}
82Write-Host "built $final"
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index c5c8d760c..b480763cb 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -33,7 +33,10 @@ cd /d "$out" || exit /b 1
33cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $($files -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib || exit /b 1 33cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $($files -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib || exit /b 1
34cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 34cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1
35cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 35cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1
36cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1
37cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1
36if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1 38if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1
39if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1
37"@ 40"@
38} 41}
39 42
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 38047321c..edd5cad19 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -1,7 +1,9 @@
1"""Assemble, translate, and run the synthetic RDNA2->SPIR-V GPU test suite on Vulkan. 1"""Assemble, translate, and run the synthetic RDNA2->SPIR-V GPU test suite on Vulkan.
2 2
3Usage: 3Usage:
4 python -I scripts/run_gpu_tests.py [--llvm-mc PATH] [--build DIR] [--work DIR] [--filter SUBSTR] 4 python -I scripts/run_gpu_tests.py [--llvm-mc CMD] [--build DIR] [--work DIR] [--filter SUBSTR]
5
6--llvm-mc (or LLVM_MC) is a path or a whole command, e.g. "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc".
5""" 7"""
6import argparse 8import argparse
7import json 9import json
@@ -16,6 +18,8 @@ import tempfile
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders") 19SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders")
18TRANSLATOR = os.path.join(ROOT, "tools", "rdna2spirv.py") 20TRANSLATOR = os.path.join(ROOT, "tools", "rdna2spirv.py")
21sys.path.insert(0, os.path.join(ROOT, "tools"))
22import mc_command # noqa: E402
19sys.path.insert(0, SHADER_DIR) 23sys.path.insert(0, SHADER_DIR)
20from compute_fixture import compute_header 24from compute_fixture import compute_header
21 25
@@ -61,7 +65,7 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2) -> byt
61def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 65def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None:
62 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" 66 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py."""
63 raw = open(asm_path, encoding="utf-8").read() 67 raw = open(asm_path, encoding="utf-8").read()
64 cmd = [llvm_mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 68 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
65 for ln in raw.splitlines(): 69 for ln in raw.splitlines():
66 s = ln.strip() 70 s = ln.strip()
67 if not s: 71 if not s:
@@ -338,7 +342,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool,
338 342
339def main() -> int: 343def main() -> int:
340 ap = argparse.ArgumentParser() 344 ap = argparse.ArgumentParser()
341 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 345 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"),
346 help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'")
342 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) 347 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"))
343 ap.add_argument("--work", default=None) 348 ap.add_argument("--work", default=None)
344 ap.add_argument("--filter", default="") 349 ap.add_argument("--filter", default="")
@@ -372,9 +377,13 @@ def run_suite(a, work: str) -> int:
372 asm_files = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")) 377 asm_files = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".asm"))
373 if a.filter: 378 if a.filter:
374 asm_files = [f for f in asm_files if a.filter in f] 379 asm_files = [f for f in asm_files if a.filter in f]
380 # Shaders a selected test draws with are built even when the filter leaves them out (#192): ps_flat uses vs_ids.
381 build_files = list(asm_files)
382 if any(f.startswith("ps_flat") for f in asm_files) and "vs_ids.asm" not in build_files:
383 build_files.append("vs_ids.asm")
375 384
376 # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s 385 # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s
377 for fname in asm_files: 386 for fname in build_files:
378 name = os.path.splitext(fname)[0] 387 name = os.path.splitext(fname)[0]
379 if name == "gs_tri": 388 if name == "gs_tri":
380 dxbc = make_dxbc([ 389 dxbc = make_dxbc([
@@ -461,12 +470,15 @@ def run_suite(a, work: str) -> int:
461 results.append((name, False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)")) 470 results.append((name, False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)"))
462 else: 471 else:
463 results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) 472 results.append((name, rc == 0, msg.splitlines()[-1] if msg else ""))
464 elif name in ("cs_store", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", 473 elif name in ("cs_store", "cs_smem_soffset_imm", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl",
465 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", 474 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute",
466 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", 475 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw",
467 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load"): 476 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load"):
468 cs_dump_wants = { 477 cs_dump_wants = {
469 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800], 478 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800],
479 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone
480 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030,
481 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C],
470 "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], 482 "cs_wave64_ballot": [32, 16, 24, 40, 8, 48],
471 "cs_wm_half_ops": [32, 16, 16, 0, 16], 483 "cs_wm_half_ops": [32, 16, 16, 0, 16],
472 "cs_wm_half_cmp": [1, 0, 1, 1], 484 "cs_wm_half_cmp": [1, 0, 1, 1],
@@ -487,13 +499,13 @@ def run_suite(a, work: str) -> int:
487 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 499 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
488 } 500 }
489 want = cs_dump_wants[name] 501 want = cs_dump_wants[name]
490 # Every dump but cs_store is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, as 502 # Every dump but cs_store and cs_smem_soffset_imm is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, as
491 # check.py does, where the device has none (vk_compute_test exits 77) instead of reporting a failure. 503 # check.py does, where the device has none (vk_compute_test exits 77) instead of reporting a failure.
492 # With LEONIDA_W64_EMULATE=1 they were translated with --wave64-emulate and run on any subgroup size. 504 # With LEONIDA_W64_EMULATE=1 they were translated with --wave64-emulate and run on any subgroup size.
493 # cs_w64x_partial (a 40-thread group) can't have full subgroups: it asks for size 64 without them. 505 # cs_w64x_partial (a 40-thread group) can't have full subgroups: it asks for size 64 without them.
494 emulated = os.environ.get("LEONIDA_W64_EMULATE") == "1" 506 emulated = os.environ.get("LEONIDA_W64_EMULATE") == "1"
495 partial = name == "cs_w64x_partial" 507 partial = name == "cs_w64x_partial"
496 wave64 = name != "cs_store" and not emulated and not partial 508 wave64 = name not in ("cs_store", "cs_smem_soffset_imm") and not emulated and not partial
497 if partial and not emulated: 509 if partial and not emulated:
498 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") 510 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64")
499 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) 511 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env)
@@ -504,7 +516,7 @@ def run_suite(a, work: str) -> int:
504 elif rc == 0 and dump_line: 516 elif rc == 0 and dump_line:
505 vals = [int(x) for x in dump_line.split("=")[1].split()[:len(want)]] 517 vals = [int(x) for x in dump_line.split("=")[1].split()[:len(want)]]
506 ok = vals == want 518 ok = vals == want
507 fmt = hex if name == "cs_store" else str 519 fmt = hex if name in ("cs_store", "cs_smem_soffset_imm") else str
508 results.append((name, ok, " ".join(fmt(x) for x in vals))) 520 results.append((name, ok, " ".join(fmt(x) for x in vals)))
509 else: 521 else:
510 results.append((name, False, msg)) 522 results.append((name, False, msg))
diff --git a/tests/conftest.py b/tests/conftest.py
index c78e0209a..f614163c5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -17,13 +17,46 @@ import pytest
17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18sys.path.insert(0, os.path.join(ROOT, "tools")) 18sys.path.insert(0, os.path.join(ROOT, "tools"))
19 19
20import mc_command # noqa: E402
20import rdna2spirv # noqa: E402 21import rdna2spirv # noqa: E402
21 22
22 23
24def _repair_stdin_handle():
25 """Windows, under pytest's fd capture: give the children the tests start a stdin that is open.
26
27 The capture replaces fd 0 with os.dup2(), which closes the handle fd 0 had, while the process's
28 STD_INPUT_HANDLE keeps that handle's number. subprocess starts from GetStdHandle(), not from fd 0, so a child
29 started without stdin=/input= fails with "[WinError 6] The handle is invalid" or, when the number has been
30 reused meanwhile, gets whatever file now has it. Which one depends on what ran before, so the failures move
31 from run to run. With -s or --capture=sys, and without pytest, the two handles agree and nothing is done.
32 """
33 if sys.platform != "win32":
34 return
35 import ctypes
36 import msvcrt
37 kernel32 = ctypes.WinDLL("kernel32")
38 kernel32.GetStdHandle.restype = ctypes.c_void_p
39 kernel32.GetStdHandle.argtypes = [ctypes.c_uint32]
40 kernel32.SetStdHandle.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
41 std_input = 0xFFFFFFF6 # STD_INPUT_HANDLE, (DWORD)-10
42 handle = kernel32.GetStdHandle(std_input)
43 try:
44 fd0 = msvcrt.get_osfhandle(0)
45 except OSError:
46 fd0 = None
47 if not handle or handle == fd0: # no stdin at all (subprocess copes), or not redirected
48 return
49 # A NUL of our own, never closed: fd 0's handle would go stale again the next time the capture swaps fd 0.
50 kernel32.SetStdHandle(std_input, msvcrt.get_osfhandle(os.open(os.devnull, os.O_RDONLY)))
51
52
53_repair_stdin_handle() # before the llvm-mc probe below, which is the first child
54
55
23def _has_amdgpu(mc): 56def _has_amdgpu(mc):
24 """True if this llvm-mc was built with the AMDGPU target (the official Windows release archives are not).""" 57 """True if this llvm-mc was built with the AMDGPU target (the official Windows release archives are not)."""
25 try: 58 try:
26 r = subprocess.run([mc, "--version"], capture_output=True, text=True, timeout=60) 59 r = subprocess.run(mc + ["--version"], capture_output=True, text=True, timeout=60)
27 except (OSError, subprocess.SubprocessError): 60 except (OSError, subprocess.SubprocessError):
28 return False 61 return False
29 return "amdgcn" in r.stdout 62 return "amdgcn" in r.stdout
@@ -33,12 +66,14 @@ def _find_llvm_mc():
33 candidates = [] 66 candidates = []
34 env = os.environ.get("LLVM_MC") 67 env = os.environ.get("LLVM_MC")
35 if env: 68 if env:
36 candidates.append(shutil.which(env)) # None when the path doesn't exist 69 candidates.append(mc_command.split_command(env))
37 candidates.append(shutil.which("llvm-mc")) 70 found = shutil.which("llvm-mc")
71 if found:
72 candidates.append([found])
38 # Debian/Ubuntu install it versioned, out of PATH. 73 # Debian/Ubuntu install it versioned, out of PATH.
39 candidates += sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True) 74 candidates += [[p] for p in sorted(glob.glob("/usr/lib/llvm-*/bin/llvm-mc"), reverse=True)]
40 # Default location of the official Windows installer, which doesn't add LLVM to PATH unless asked to. 75 # Default location of the official Windows installer, which doesn't add LLVM to PATH unless asked to.
41 candidates += glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe") 76 candidates += [[p] for p in glob.glob(r"C:\Program Files\LLVM\bin\llvm-mc.exe")]
42 for c in candidates: 77 for c in candidates:
43 if c and _has_amdgpu(c): 78 if c and _has_amdgpu(c):
44 return c 79 return c
@@ -126,7 +161,7 @@ class Shader:
126 rsrc2, (lx, ly, lz) = cs_header 161 rsrc2, (lx, ly, lz) = cs_header
127 (workdir / "fssm").mkdir(exist_ok=True) 162 (workdir / "fssm").mkdir(exist_ok=True)
128 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz)) 163 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz))
129 cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 164 cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
130 for ln in asm.splitlines(): 165 for ln in asm.splitlines():
131 s = ln.strip() 166 s = ln.strip()
132 if not s: 167 if not s:
diff --git a/tests/semantic/test_mutations.py b/tests/semantic/test_mutations.py
index cce2b723a..0caca1d46 100644
--- a/tests/semantic/test_mutations.py
+++ b/tests/semantic/test_mutations.py
@@ -103,8 +103,11 @@ MUTATIONS = [
103 103
104 104
105def run_semantics(tools_dir): 105def run_semantics(tools_dir):
106 env = dict(os.environ, LEONIDA_TOOLS_DIR=tools_dir, PYTHONDONTWRITEBYTECODE="1") 106 # The child finds test_ps_semantics through PYTHONPATH, not cwd=HERE: Windows refuses a working directory longer
107 p = subprocess.run([sys.executable, "-m", "unittest", "test_ps_semantics", "-v"], cwd=HERE, env=env, 107 # than 258 characters (WinError 267), which a checkout in a deep folder reaches.
108 path = os.pathsep.join(filter(None, [HERE, os.environ.get("PYTHONPATH")]))
109 env = dict(os.environ, LEONIDA_TOOLS_DIR=tools_dir, PYTHONDONTWRITEBYTECODE="1", PYTHONPATH=path)
110 p = subprocess.run([sys.executable, "-m", "unittest", "test_ps_semantics", "-v"], env=env,
108 capture_output=True, text=True, timeout=300) 111 capture_output=True, text=True, timeout=300)
109 return p.returncode, p.stdout + p.stderr 112 return p.returncode, p.stdout + p.stderr
110 113
diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py
index a8e6cbde1..b9329793d 100644
--- a/tests/semantic/test_scalar_mem_smem.py
+++ b/tests/semantic/test_scalar_mem_smem.py
@@ -13,6 +13,8 @@ Covers AMD RDNA2 / GFX10 SMEM (Scalar Memory) ISA semantics and tools/rdna2spirv
13 * Multi-dword scalar loads (s_load_dword, s_load_dwordx2, x4, x8, x16) with sequential 4-byte address strides 13 * Multi-dword scalar loads (s_load_dword, s_load_dwordx2, x4, x8, x16) with sequential 4-byte address strides
14 * Destination register targeting: SGPR ranges and special registers (vcc_lo, vcc_hi, vcc pair, m0) 14 * Destination register targeting: SGPR ranges and special registers (vcc_lo, vcc_hi, vcc pair, m0)
15 * tools/rdna2spirv.py translator validation (Gen.scalar_load instruction sequences and operand validation) 15 * tools/rdna2spirv.py translator validation (Gen.scalar_load instruction sequences and operand validation)
16 * SMEM loads with a register offset and an immediate at once ("sOFF offset:IMM"): address = base + sOFF + IMM,
17 checked by running the emitted code (SmemBodyEvaluator, SmemSoffsetImmTranslatorTests)
16 * spirv_mini_interp strictness validation (rejecting unmodelled 64-bit types and PhysicalStorageBuffer) 18 * spirv_mini_interp strictness validation (rejecting unmodelled 64-bit types and PhysicalStorageBuffer)
17""" 19"""
18import os 20import os
@@ -372,6 +374,207 @@ class SmemTranslatorGenTests(unittest.TestCase):
372 g.scalar_load(ins_vgpr_base["op"], ins_vgpr_base["args"], ins_vgpr_base["mods"]) 374 g.scalar_load(ins_vgpr_base["op"], ins_vgpr_base["args"], ins_vgpr_base["mods"])
373 375
374 376
377class SmemBodyEvaluator:
378 """Runs the straight-line SPIR-V that Gen.scalar_load emits, against concrete SGPR values and a dword memory.
379
380 spirv_mini_interp refuses 64-bit integers and PhysicalStorageBuffer by design, so the address a scalar load
381 reads cannot be checked there. This evaluator knows only the handful of instructions scalar_load uses and
382 raises on anything else, so a change in the emitted code cannot be approximated silently. The heap base (push
383 constant dwords 32..33) is 0 unless given, which makes every address read an Xbox VA.
384 """
385
386 def __init__(self, gen, sgpr, memory, heap_base=0):
387 self.consts = {name: value for value, name in gen.consts.items()}
388 self.sgpr = dict(sgpr)
389 self.memory = memory
390 self.heap_base = heap_base
391 self.ids = {}
392 self.reads = [] # byte address of every PhysicalStorageBuffer dword load, in order
393 for line in gen.body:
394 self._step(line.split())
395
396 def _value(self, name):
397 if name == "%c64_32":
398 return 32
399 if name in self.ids:
400 return self.ids[name]
401 if name in self.consts:
402 return self.consts[name]
403 raise AssertionError(f"unknown id {name}")
404
405 def _step(self, words):
406 if words[0] == "OpStore":
407 kind, index = self._value(words[1])
408 if kind != "sgpr":
409 raise AssertionError(f"store through {kind}")
410 self.sgpr[index] = self._value(words[2])
411 return
412 if len(words) < 4 or words[1] != "=":
413 raise AssertionError("unmodelled line: " + " ".join(words))
414 result, op, ty, args = words[0], words[2], words[3], words[4:]
415 if op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] == "%sgpr":
416 value = ("sgpr", self._value(args[1]))
417 elif op == "OpAccessChain" and ty == "%_ptr_PSB_uint":
418 kind, address = self._value(args[0])
419 if kind != "psb":
420 raise AssertionError(f"PSB access chain on {kind}")
421 value = ("mem", (address + 4 * self._value(args[1])) & MASK64)
422 elif op == "OpLoad" and ty == "%uint" and args[0] == "%ud_base_lo_p":
423 value = self.heap_base & MASK32
424 elif op == "OpLoad" and ty == "%uint" and args[0] == "%ud_base_hi_p":
425 value = (self.heap_base >> 32) & MASK32
426 elif op == "OpLoad" and ty == "%uint":
427 kind, where = self._value(args[0])
428 if kind == "sgpr":
429 value = self.sgpr.get(where, 0) & MASK32
430 elif kind == "mem" and args[1:] == ["Aligned", "4"]:
431 self.reads.append(where)
432 value = self.memory.read_dword(where)
433 else:
434 raise AssertionError("unmodelled load: " + " ".join(words))
435 elif op == "OpBitwiseAnd" and ty == "%uint":
436 value = self._value(args[0]) & self._value(args[1])
437 elif op == "OpIAdd" and ty == "%uint":
438 value = (self._value(args[0]) + self._value(args[1])) & MASK32
439 elif op == "OpUConvert" and ty == "%ulong":
440 value = self._value(args[0]) & MASK32
441 elif op == "OpShiftLeftLogical" and ty == "%ulong":
442 value = (self._value(args[0]) << self._value(args[1])) & MASK64
443 elif op == "OpBitwiseOr" and ty == "%ulong":
444 value = self._value(args[0]) | self._value(args[1])
445 elif op == "OpIAdd" and ty == "%ulong":
446 value = (self._value(args[0]) + self._value(args[1])) & MASK64
447 elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_arr":
448 value = ("psb", self._value(args[0]))
449 else:
450 raise AssertionError("unmodelled instruction: " + " ".join(words))
451 self.ids[result] = value
452
453
454class SmemSoffsetImmTranslatorTests(unittest.TestCase):
455 """SMEM loads that carry a register offset and an immediate at once: llvm-mc prints "sOFF offset:IMM".
456
457 Rule: address = base + soffset + imm (+ 4*i for dword i).
458 Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel:
459 soffset 8 + imm 4 reads the dword at +12. s_load_dword* with both offsets was not measured; it shares the SMEM
460 encoding (soffset_en + imm), so the same rule is applied to it as an inference.
461 The hardware also truncates base, soffset and imm each to a multiple of 4 and returns 0 past NUM_RECORDS; the
462 translator does neither, so every case here is dword-aligned and in bounds.
463
464 The instruction lines are hand-written. Each case runs the code Gen.scalar_load emits with SmemBodyEvaluator
465 and asserts both the addresses read and the values that land in the destination SGPRs.
466 """
467
468 VSHARP_BASE = 0x0000000200001000 # s24 = 0x00001000, s25 = 0x80040002 (flags above bit 15 are not address)
469 POINTER = 0x0000000300004000 # s[24:25] for s_load
470
471 def run_load(self, line, pointer=False):
472 ins = parse_line(line)
473 g = rdna2spirv.Gen("ps")
474 g.scalar_load(ins["op"], ins["args"], ins["mods"])
475 base = self.POINTER if pointer else self.VSHARP_BASE
476 bank = SmemMemoryBank()
477 for off in range(0, 0x40, 4): # every dword near the base holds its own offset, tagged
478 bank.write_dword(base + off, 0x5EED0000 | off)
479 sgpr = {40: 8} # the register offset used by every case
480 if pointer:
481 sgpr.update({24: 0x00004000, 25: 0x00000003})
482 else:
483 sgpr.update({24: 0x00001000, 25: 0x80040002, 26: 0x00010000, 27: 0x00140000})
484 ev = SmemBodyEvaluator(g, sgpr, bank)
485 return ev, [a - base for a in ev.reads], g
486
487 def test_s_buffer_load_dword_soffset_plus_imm(self):
488 # The measured case: soffset 8 + imm 4 reads the dword at +12 (not +8, which is what dropping the imm gives).
489 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x4")
490 self.assertEqual(offsets, [12])
491 self.assertEqual(ev.sgpr[12], 0x5EED000C)
492
493 def test_s_load_dword_soffset_plus_imm(self):
494 # Inferred from the shared SMEM encoding; not measured on hardware.
495 ev, offsets, _ = self.run_load("s_load_dword s12, s[24:25], s40 offset:0x4", pointer=True)
496 self.assertEqual(offsets, [12])
497 self.assertEqual(ev.sgpr[12], 0x5EED000C)
498
499 def test_multi_dword_soffset_plus_imm(self):
500 cases = [
501 ("s_buffer_load_dwordx2 s[12:13], s[24:27], s40 offset:0x4", False, 2, 0x0C),
502 ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40 offset:0x10", False, 4, 0x18),
503 ("s_buffer_load_dwordx8 s[12:19], s[24:27], s40 offset:0x14", False, 8, 0x1C),
504 ("s_load_dwordx2 s[12:13], s[24:25], s40 offset:0x4", True, 2, 0x0C),
505 ("s_load_dwordx4 s[12:15], s[24:25], s40 offset:0x10", True, 4, 0x18),
506 ]
507 for line, pointer, n, first in cases:
508 with self.subTest(line=line):
509 ev, offsets, _ = self.run_load(line, pointer)
510 self.assertEqual(offsets, [first + 4 * i for i in range(n)])
511 self.assertEqual([ev.sgpr[12 + i] for i in range(n)], [0x5EED0000 | (first + 4 * i) for i in range(n)])
512
513 def test_imm_only_and_soffset_only_addresses_unchanged(self):
514 cases = [
515 ("s_buffer_load_dword s12, s[24:27], 0x4", False, [0x04]),
516 ("s_buffer_load_dword s12, s[24:27], s40", False, [0x08]),
517 ("s_buffer_load_dwordx2 s[12:13], s[24:27], 0x10", False, [0x10, 0x14]),
518 ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40", False, [0x08, 0x0C, 0x10, 0x14]),
519 ("s_load_dword s12, s[24:25], 0x4", True, [0x04]),
520 ("s_load_dword s12, s[24:25], s40", True, [0x08]),
521 ("s_load_dwordx2 s[12:13], s[24:25], 0", True, [0x00, 0x04]),
522 ("s_load_dwordx2 s[12:13], s[24:25], s40", True, [0x08, 0x0C]),
523 ]
524 for line, pointer, want in cases:
525 with self.subTest(line=line):
526 ev, offsets, _ = self.run_load(line, pointer)
527 self.assertEqual(offsets, want)
528 self.assertEqual([ev.sgpr[12 + i] for i in range(len(want))], [0x5EED0000 | o for o in want])
529
530 def test_zero_imm_with_soffset_reads_the_soffset_address(self):
531 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x0")
532 self.assertEqual(offsets, [8])
533 self.assertEqual(ev.sgpr[12], 0x5EED0008)
534
535 def test_non_sgpr_scalar_register_offset_plus_imm(self):
536 # llvm-mc also accepts m0, vcc_lo or null as the register offset. null reads as zero; m0 is not an SGPR slot,
537 # so only check that the form still translates and that the immediate changes the code.
538 ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], null offset:0x14")
539 self.assertEqual(offsets, [0x14])
540 self.assertEqual(ev.sgpr[12], 0x5EED0014)
541 bodies = []
542 for line in ("s_buffer_load_dword s12, s[24:27], m0", "s_buffer_load_dword s12, s[24:27], m0 offset:0x4"):
543 ins = parse_line(line)
544 g = rdna2spirv.Gen("ps")
545 g.scalar_load(ins["op"], ins["args"], ins["mods"])
546 bodies.append(g.body)
547 self.assertNotEqual(bodies[0], bodies[1])
548
549 def test_offset_modifier_changes_the_emitted_code(self):
550 for line, pointer in (("s_buffer_load_dword s12, s[24:27], s40", False),
551 ("s_load_dword s12, s[24:25], s40", True)):
552 with self.subTest(line=line):
553 _, _, plain = self.run_load(line, pointer)
554 _, _, both = self.run_load(line + " offset:0x4", pointer)
555 self.assertNotEqual(plain.body, both.body)
556
557 def test_heap_base_is_added_once(self):
558 ins = parse_line("s_buffer_load_dword s12, s[24:27], s40 offset:0x4")
559 g = rdna2spirv.Gen("ps")
560 g.scalar_load(ins["op"], ins["args"], ins["mods"])
561 ev = SmemBodyEvaluator(g, {24: 0x1000, 25: 0, 40: 8}, SmemMemoryBank(), heap_base=0x0000007F00000000)
562 self.assertEqual(ev.reads, [0x0000007F00000000 + 0x1000 + 12])
563
564 def test_offset_forms_the_assembler_rejects_raise(self):
565 # llvm-mc accepts none of these; hand-written or damaged listings must not translate to a guessed address.
566 for line in ("s_buffer_load_dword s12, s[24:27], 0x8 offset:0x4", # immediate operand and offset modifier
567 "s_buffer_load_dword s12, s[24:27], s40 offset:zz", # unparseable immediate
568 "s_buffer_load_dword s12, s[24:27], s40 offset:0x4 offset:0x8",
569 "s_buffer_load_dword s12, s[24:27], s40, 0x4", # a fourth operand
570 "s_load_dword s12, s[24:25], 0x8 offset:0x4"):
571 with self.subTest(line=line):
572 ins = parse_line(line)
573 g = rdna2spirv.Gen("ps")
574 with self.assertRaises(rdna2spirv.Unsupported):
575 g.scalar_load(ins["op"], ins["args"], ins["mods"])
576
577
375class SmemMiniInterpStrictnessTests(unittest.TestCase): 578class SmemMiniInterpStrictnessTests(unittest.TestCase):
376 """Verifies that spirv_mini_interp rejects storage classes and constructs it does not model. 579 """Verifies that spirv_mini_interp rejects storage classes and constructs it does not model.
377 580
diff --git a/tests/test_awc_manifest.py b/tests/test_awc_manifest.py
index acc8e12a6..651e21155 100644
--- a/tests/test_awc_manifest.py
+++ b/tests/test_awc_manifest.py
@@ -18,8 +18,8 @@ def fmt(samples, rate, codec, channels):
18 return bytes(block) 18 return bytes(block)
19 19
20 20
21def music_blob(ids, samples, rate): 21def music_blob(ids, samples, rate, toc=0xF8):
22 """(descriptor, data) for one block of mono Opus channels.""" 22 """(descriptor, data) for one block of Opus channels. toc is the packet TOC byte."""
23 desc = bytearray(12 + 16 * len(ids)) 23 desc = bytearray(12 + 16 * len(ids))
24 struct.pack_into("<III", desc, 0, 1, 2048, len(ids)) 24 struct.pack_into("<III", desc, 0, 1, 2048, len(ids))
25 for i, cid in enumerate(ids): 25 for i, cid in enumerate(ids):
@@ -31,7 +31,7 @@ def music_blob(ids, samples, rate):
31 for i in range(len(ids)): 31 for i in range(len(ids)):
32 struct.pack_into("<I", data, 24 * i + 4, 1) # subblock count; skip stays 0 32 struct.pack_into("<I", data, 24 * i + 4, 1) # subblock count; skip stays 0
33 struct.pack_into("<H", data, 2048 + 2048 * i, 1) 33 struct.pack_into("<H", data, 2048 + 2048 * i, 1)
34 data[2050 + 2048 * i] = 0xF8 # CELT 20 ms, one frame 34 data[2050 + 2048 * i] = toc # CELT 20 ms, one frame (stereo when bit 2 is set)
35 return bytes(desc), bytes(data) 35 return bytes(desc), bytes(data)
36 36
37 37
@@ -132,6 +132,19 @@ class ManifestTest(unittest.TestCase):
132 self.assertIs(doc["streams"][0]["streamed_music"], False) 132 self.assertIs(doc["streams"][0]["streamed_music"], False)
133 self.assertAlmostEqual(doc["streams"][0]["duration_s"], 0.1, places=6) 133 self.assertAlmostEqual(doc["streams"][0]["duration_s"], 0.1, places=6)
134 134
135 def test_stereo_streamed_music_uses_packet_channels_and_per_channel_samples(self):
136 desc, data = music_blob([0x40], 1920, 48000, toc=0xFC) # 2 x 960 interleaved samples
137 path = os.path.join(self.tmp.name, "stereo.awc")
138 with open(path, "wb") as f:
139 f.write(build_bank([(0x50, [(0x48, desc), (0x55, data)])]))
140 p = self.run_tool(path)
141 self.assertEqual(p.returncode, 0, p.stderr)
142 rows = {r["stream"]: r for r in csv.DictReader(io.StringIO(p.stdout))}
143 row = rows["00000040"]
144 self.assertEqual((row["channels"], row["declared_samples"]), ("2", "960"))
145 self.assertAlmostEqual(float(row["duration_s"]), 0.02, places=6)
146 self.assertEqual(row["streamed_music"], "yes")
147
135 148
136if __name__ == "__main__": 149if __name__ == "__main__":
137 unittest.main(verbosity=2) 150 unittest.main(verbosity=2)
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py
index 654fd85f7..5de874627 100644
--- a/tests/test_awc_opus.py
+++ b/tests/test_awc_opus.py
@@ -116,6 +116,33 @@ def build_bank(streams):
116 return bytes(out) 116 return bytes(out)
117 117
118 118
119def build_music_bank(tocs, samples, rate=48000):
120 """A one-stream AWC with a 0x48 streamed-music descriptor and one 2048-byte block.
121
122 tocs: one Opus TOC byte per descriptor channel, each in its own 2048-byte subblock.
123 samples: the descriptor's interleaved sample count (per-channel frames * packet channels).
124 """
125 channels = len(tocs)
126 desc = bytearray(12 + 16 * channels)
127 struct.pack_into("<III", desc, 0, 1, 2048, channels)
128 for i, toc in enumerate(tocs):
129 base = 12 + 16 * i
130 struct.pack_into("<II", desc, base, 0x100 + i, samples)
131 struct.pack_into("<H", desc, base + 10, rate)
132 desc[base + 12] = 0x0B
133 data = bytearray(2048 + 2048 * channels)
134 for i in range(channels):
135 struct.pack_into("<I", data, 24 * i + 4, 1) # one subblock
136 struct.pack_into("<H", data, 2048 + 2048 * i, 1)
137 data[2050 + 2048 * i] = tocs[i]
138 header = 16 + 4 + 2 * 8
139 out = bytearray(b"ADAT" + struct.pack("<III", 0, 1, header))
140 out += struct.pack("<I", 0x20 | (2 << 29))
141 out += struct.pack("<Q", tag(0x48, header, len(desc)))
142 out += struct.pack("<Q", tag(0x55, header + len(desc), len(data)))
143 return bytes(out + desc + data)
144
145
119class WriteWavTest(unittest.TestCase): 146class WriteWavTest(unittest.TestCase):
120 def setUp(self): 147 def setUp(self):
121 self.tmp = tempfile.TemporaryDirectory() 148 self.tmp = tempfile.TemporaryDirectory()
@@ -259,6 +286,60 @@ class ExportBankTest(unittest.TestCase):
259 self.assertEqual(last["serial"], 3) 286 self.assertEqual(last["serial"], 3)
260 287
261 288
289class StreamedMusicTest(unittest.TestCase):
290 def setUp(self):
291 self.tmp = tempfile.TemporaryDirectory()
292 self.addCleanup(self.tmp.cleanup)
293 self.out = os.path.join(self.tmp.name, "out")
294
295 def export(self, tocs, samples):
296 path = os.path.join(self.tmp.name, "streamed.awc")
297 with open(path, "wb") as f:
298 f.write(build_music_bank(tocs, samples))
299 counts = awc.export_bank(path, self.out)
300 return counts, os.path.join(self.out, "streamed")
301
302 def test_stereo_packets_export_one_stereo_ogg(self):
303 counts, od = self.export([0xFC], 1920) # 2 x 960 interleaved samples
304 self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 1})
305 with open(os.path.join(od, "00000100.ogg"), "rb") as f:
306 pages = parse_ogg_pages(f.read())
307 version, channels, preskip, in_rate, gain, mapping = struct.unpack_from("<BBHIhB", pages[0]["body"], 8)
308 self.assertEqual((version, channels, preskip, in_rate, gain, mapping), (1, 2, 0, 48000, 0, 0))
309 self.assertEqual(pages[-1]["granule"], 960)
310
311 def test_two_mono_groups_export_two_mono_oggs(self):
312 counts, od = self.export([0x78, 0x78], 960)
313 self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 2})
314 for sid in ("00000100", "00000101"):
315 with self.subTest(sid=sid):
316 with open(os.path.join(od, sid + ".ogg"), "rb") as f:
317 pages = parse_ogg_pages(f.read())
318 channels = pages[0]["body"][9]
319 self.assertEqual(channels, 1)
320 self.assertEqual(pages[-1]["granule"], 960)
321
322 def test_music_channels_halves_interleaved_samples(self):
323 path = os.path.join(self.tmp.name, "streamed.awc")
324 with open(path, "wb") as f:
325 f.write(build_music_bank([0xFC], 1920))
326 with open(path, "rb") as f:
327 d = f.read()
328 _, music = awc.parse_awc(d)
329 info = awc.music_channels(d, music[0][0], music[0][1])
330 self.assertEqual((info[0][1], info[0][5]), (960, 2))
331
332 def test_music_channels_metadata_only_still_reports_packet_channels(self):
333 path = os.path.join(self.tmp.name, "streamed.awc")
334 with open(path, "wb") as f:
335 f.write(build_music_bank([0xFC], 1920))
336 with open(path, "rb") as f:
337 d = f.read()
338 _, music = awc.parse_awc(d)
339 info = awc.music_channels(d, music[0][0], music[0][1], collect_packets=False)
340 self.assertEqual((info[0][1], info[0][4], info[0][5]), (960, [], 2))
341
342
262class MalformedBankTest(unittest.TestCase): 343class MalformedBankTest(unittest.TestCase):
263 def test_bad_magic_raises_value_error(self): 344 def test_bad_magic_raises_value_error(self):
264 with tempfile.TemporaryDirectory() as tmp: 345 with tempfile.TemporaryDirectory() as tmp:
diff --git a/tests/test_classify_carve.py b/tests/test_classify_carve.py
new file mode 100644
index 000000000..b0af5a543
--- /dev/null
+++ b/tests/test_classify_carve.py
@@ -0,0 +1,152 @@
1"""Tests for tools/classify_carve.py, built from synthetic carve indexes (no game data).
2
3 python -I tests/test_classify_carve.py
4"""
5import contextlib
6import importlib.util
7import io
8import json
9import os
10import tempfile
11import unittest
12from unittest import mock
13
14ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
16ZERO_HEAD = "00" * 16
17RBF0_HEAD = "5242463000000000"
18RESPAGE_HEAD = "42400000deadbeef"
19
20
21def load_module():
22 path = os.path.join(ROOT, "tools", "classify_carve.py")
23 spec = importlib.util.spec_from_file_location("classify_carve_under_test", path)
24 module = importlib.util.module_from_spec(spec)
25 spec.loader.exec_module(module)
26 return module
27
28
29carve = load_module()
30
31
32class ClassifyTests(unittest.TestCase):
33 def test_bink2_rows_do_not_need_a_head(self):
34 # rpf9_carve writes bink2 rows with dimensions and no head field.
35 self.assertEqual(carve.classify({"type": "bink2", "size": 12}), "bink2")
36
37 def test_bink2_wins_over_a_signature(self):
38 self.assertEqual(carve.classify({"type": "bink2", "head": RBF0_HEAD, "size": 1}), "bink2")
39
40 def test_rbf0_metadata(self):
41 self.assertEqual(carve.classify({"head": RBF0_HEAD, "size": 1}), "rbf0")
42
43 def test_resource_page(self):
44 self.assertEqual(carve.classify({"head": RESPAGE_HEAD, "size": 1}), "respage")
45
46 def test_gpu_zero_header_needs_sixteen_zero_bytes(self):
47 self.assertEqual(carve.classify({"head": ZERO_HEAD, "size": 1}), "gpu-zerohdr")
48 # Fifteen zero bytes are not enough, and the fallback names four bytes.
49 self.assertEqual(carve.classify({"head": "00" * 15, "size": 1}), "other:00000000")
50
51 def test_other_is_keyed_by_the_first_four_bytes(self):
52 self.assertEqual(carve.classify({"head": "deadbeefcafebabe", "size": 1}), "other:deadbeef")
53
54 def test_short_head_is_used_as_is(self):
55 self.assertEqual(carve.classify({"head": "abcd", "size": 1}), "other:abcd")
56
57 def test_signature_must_be_at_the_start(self):
58 self.assertEqual(carve.classify({"head": "ff" + RBF0_HEAD, "size": 1}), "other:ff524246")
59
60
61class MainTests(unittest.TestCase):
62 def setUp(self):
63 tmp = tempfile.TemporaryDirectory()
64 self.addCleanup(tmp.cleanup)
65 self.root = tmp.name
66
67 def archive(self, name, rows):
68 path = os.path.join(self.root, name)
69 os.makedirs(path, exist_ok=True)
70 with open(os.path.join(path, "index.json"), "w", encoding="utf-8") as f:
71 json.dump({"files": rows}, f)
72 return path
73
74 def run_main(self):
75 out = io.StringIO()
76 with mock.patch("sys.argv", ["classify_carve.py", self.root]), contextlib.redirect_stdout(out):
77 carve.main()
78 return out.getvalue()
79
80 def types(self):
81 with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f:
82 return json.load(f)
83
84 def test_counts_and_bytes_are_aggregated_per_class(self):
85 self.archive("a", [
86 {"head": RBF0_HEAD, "size": 10},
87 {"head": "5242463000000001", "size": 30},
88 {"head": ZERO_HEAD, "size": 5},
89 {"head": "deadbeefcafebabe", "size": 7},
90 {"type": "bink2", "size": 3},
91 ])
92 self.run_main()
93 types = self.types()
94 a = types["per_archive"]["a"]
95 self.assertEqual(a["rbf0"], {"files": 2, "bytes": 40})
96 self.assertEqual(a["gpu-zerohdr"], {"files": 1, "bytes": 5})
97 self.assertEqual(a["other:deadbeef"], {"files": 1, "bytes": 7})
98 self.assertEqual(a["bink2"], {"files": 1, "bytes": 3})
99 self.assertEqual(types["overall"]["rbf0"], {"files": 2, "bytes": 40})
100
101 def test_overall_sums_across_archives(self):
102 self.archive("a", [{"head": RBF0_HEAD, "size": 10}])
103 self.archive("b", [{"head": RBF0_HEAD, "size": 25}])
104 self.run_main()
105 types = self.types()
106 self.assertEqual(types["overall"]["rbf0"], {"files": 2, "bytes": 35})
107 self.assertEqual(types["per_archive"]["a"]["rbf0"], {"files": 1, "bytes": 10})
108
109 def test_archives_are_listed_in_name_order(self):
110 self.archive("b", [{"head": RBF0_HEAD, "size": 1}])
111 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
112 self.run_main()
113 self.assertEqual(list(self.types()["per_archive"]), ["a", "b"])
114
115 def test_classes_are_ordered_by_bytes_descending(self):
116 self.archive("a", [
117 {"head": RBF0_HEAD, "size": 50},
118 {"head": ZERO_HEAD, "size": 500},
119 ])
120 self.run_main()
121 types = self.types()
122 self.assertEqual(list(types["per_archive"]["a"]), ["gpu-zerohdr", "rbf0"])
123 self.assertEqual(list(types["overall"]), ["gpu-zerohdr", "rbf0"])
124
125 def test_directory_without_an_index_is_skipped(self):
126 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
127 os.makedirs(os.path.join(self.root, "empty"), exist_ok=True)
128 self.run_main()
129 self.assertEqual(list(self.types()["per_archive"]), ["a"])
130
131 def test_stdout_summary(self):
132 self.archive("a", [{"head": RBF0_HEAD, "size": 1}, {"head": ZERO_HEAD, "size": 2}])
133 out = self.run_main()
134 self.assertIn("GiB", out)
135 self.assertIn("rbf0", out)
136 self.assertIn("2 classes in total", out)
137
138 def test_empty_root(self):
139 out = self.run_main()
140 self.assertEqual(self.types(), {"overall": {}, "per_archive": {}})
141 self.assertIn("0 classes in total", out)
142
143 def test_types_json_uses_one_space_indent(self):
144 self.archive("a", [{"head": RBF0_HEAD, "size": 1}])
145 self.run_main()
146 with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f:
147 text = f.read()
148 self.assertTrue(text.startswith('{\n "overall": {'))
149
150
151if __name__ == "__main__":
152 unittest.main()
diff --git a/tests/test_gamedata_xml.py b/tests/test_gamedata_xml.py
new file mode 100644
index 000000000..2d0678684
--- /dev/null
+++ b/tests/test_gamedata_xml.py
@@ -0,0 +1,211 @@
1"""gamedata_xml.py must catalog synthetic XML without reading any game file.
2
3 python -I tests/test_gamedata_xml.py
4
5Fixtures are hand-written documents: nested elements, attributes, macro and platform references,
6an include-like manifest, a tail-only fragment and a malformed document. No game data is used.
7"""
8import csv
9import json
10import os
11import subprocess
12import sys
13import tempfile
14import unittest
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17TOOL = os.path.join(ROOT, "tools", "gamedata_xml.py")
18
19ALPHA = (
20 b'\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?>\n'
21 b'<CDataFileMgr__ContentChangeSetDef version="1">\n'
22 b' <id>fixture</id>\n'
23 b' <fileList>\n'
24 b' <Item type="file"><filename>$(common)/movies/fixture.bk2</filename>'
25 b'<fileType>bk2</fileType></Item>\n'
26 b' <Item type="file"><filename>platform:/levels/fixture.xml</filename>'
27 b'<fileType>xml</fileType></Item>\n'
28 b' <Item type="file"><filename>$(target)/data/fixture.xml</filename>'
29 b'<fileType>xml</fileType></Item>\n'
30 b' <Item type="file"><filename>platform:/data/fixture.xml</filename>'
31 b'<fileType>xml</fileType></Item>\n'
32 b' </fileList>\n'
33 b' <includedSets><Item ref="synthetic_set"><loadPath>$(root)/fixture</loadPath></Item>'
34 b'</includedSets>\n'
35 b' <!-- synthetic note -->\n'
36 b'</CDataFileMgr__ContentChangeSetDef>'
37)
38BETA = (
39 b'<timecycle_modifier_data version="1"><modifier name="fixture">'
40 b'<postfx_exposure>0 1</postfx_exposure></modifier></timecycle_modifier_data>'
41)
42TAIL = b'<Item type="x"/>\n</TailRoot>'
43BAD = b'<?xml version="1.0"?><Root><Item></Root>'
44ROOTLESS = b'plain text, not an XML document\n'
45
46
47class GamedataXmlTest(unittest.TestCase):
48 def setUp(self):
49 self.tmp = tempfile.TemporaryDirectory()
50 self.root = self.tmp.name
51
52 def tearDown(self):
53 self.tmp.cleanup()
54
55 def write(self, name, data):
56 path = os.path.join(self.root, name)
57 with open(path, "wb") as f:
58 f.write(data)
59 return path
60
61 def run_tool(self, *args):
62 return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root,
63 capture_output=True, text=True, encoding="utf-8", errors="replace")
64
65 def test_files_catalog_roots_elements_references_and_values(self):
66 alpha = self.write("alpha.xml", ALPHA)
67 beta = self.write("beta.xml", BETA)
68 out = os.path.join(self.root, "catalog.json")
69 csv_path = os.path.join(self.root, "catalog.csv")
70 p = self.run_tool(alpha, beta, "--json", out, "--csv", csv_path, "--check")
71 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
72
73 with open(out, encoding="utf-8") as f:
74 data = json.load(f)
75 s = data["summary"]
76 self.assertEqual(s["documents"], 2)
77 self.assertEqual(s["well_formed"], 2)
78 self.assertEqual(s["fragments"], 0)
79 self.assertEqual(s["truncated"], 0)
80 self.assertEqual(s["malformed"], 0)
81 self.assertEqual(s["root_count"], 2)
82 self.assertEqual(s["elements"], 21)
83 self.assertEqual(s["max_depth"], 4)
84 self.assertEqual(s["comments"], 1)
85 self.assertEqual(s["comments_header"], 1)
86 self.assertEqual(s["references"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
87 self.assertEqual(s["platform"], {"levels": 1, "other": 1})
88 self.assertEqual(s["platform_total"], 2)
89 self.assertEqual(s["filename"], 4)
90 self.assertEqual(s["include_like"]["fileList"], 1)
91 self.assertEqual(s["include_like"]["includedSets"], 1)
92 self.assertEqual(s["include_like"]["loadPath"], 1)
93 self.assertEqual(s["xi_include"], 0)
94
95 rows = {row["source"]: row for row in data["rows"]}
96 first = rows["alpha.xml"]
97 self.assertEqual(first["root"], "CDataFileMgr__ContentChangeSetDef")
98 self.assertEqual(first["category"], "mount / content manifests")
99 self.assertEqual(first["element_count"], 18)
100 self.assertEqual(first["max_depth"], 4)
101 self.assertEqual(first["attributes"], ["ref", "type", "version"])
102 self.assertEqual(first["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
103 self.assertEqual(first["platform"], {"levels": 1, "other": 1})
104 self.assertEqual(first["filename"], 4)
105 self.assertTrue(first["header"])
106 self.assertTrue(first["well_formed"])
107 self.assertFalse(first["fragment"])
108
109 second = rows["beta.xml"]
110 self.assertEqual(second["root"], "timecycle_modifier_data")
111 self.assertEqual(second["category"], "time, weather, sky, water")
112 self.assertEqual(second["element_count"], 3)
113 self.assertEqual(second["max_depth"], 3)
114 self.assertEqual(second["attributes"], ["name", "version"])
115 self.assertFalse(second["header"])
116
117 root = data["roots"]["CDataFileMgr__ContentChangeSetDef"]
118 self.assertEqual(root["files"], 1)
119 self.assertEqual(root["category"], "mount / content manifests")
120 self.assertEqual(root["elements"], 18)
121 self.assertEqual(root["element_names"]["filename"], 4)
122 self.assertEqual(root["element_names"]["Item"], 5)
123 self.assertEqual(root["attributes"]["type"], 4)
124 self.assertEqual(root["attributes"]["ref"], 1)
125 self.assertEqual(root["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1})
126 self.assertEqual(root["platform"], {"levels": 1, "other": 1})
127 self.assertEqual(root["filename"], 4)
128
129 with open(csv_path, newline="", encoding="utf-8") as f:
130 csv_rows = list(csv.DictReader(f))
131 self.assertEqual(len(csv_rows), 2)
132 self.assertEqual(csv_rows[0]["root"], "CDataFileMgr__ContentChangeSetDef")
133 self.assertEqual(csv_rows[0]["refs"], "$(common)=1;$(root)=1;$(target)=1")
134 self.assertEqual(csv_rows[0]["well_formed"], "true")
135
136 # Values, text and comments must not leak into the catalog; names and counts are fine.
137 with open(out, encoding="utf-8") as f:
138 blob = f.read()
139 for value in ("fixture.bk2", "synthetic note", "synthetic_set", "0 1", "fixture.xml"):
140 self.assertNotIn(value, blob)
141
142 def test_check_reports_tail_only_fragment_and_malformed(self):
143 tail = self.write("tail.xml", TAIL)
144 p = self.run_tool(tail, "--check")
145 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
146 self.assertIn("1 truncated at the start", p.stdout)
147 self.assertIn("0 rootless fragments", p.stdout)
148 self.assertIn("0 malformed", p.stdout)
149 self.assertIn("TailRoot", p.stdout)
150
151 rootless = self.write("rootless.xml", ROOTLESS)
152 p = self.run_tool(rootless, "--check")
153 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
154 self.assertIn("1 rootless fragment", p.stdout)
155
156 bad = self.write("bad.xml", BAD)
157 p = self.run_tool(bad, "--check")
158 self.assertEqual(p.returncode, 1, p.stdout + p.stderr)
159 self.assertIn("1 malformed", p.stdout)
160 self.assertIn("line 1", p.stdout)
161
162 def test_carve_directory_joins_chunks_and_marks_fragment(self):
163 carve = os.path.join(self.root, "carve")
164 os.makedirs(carve)
165 doc = b'<?xml version="1.0"?>\n<RootA>' + b"<Item value=\"1\"/>" * 20 + b"</RootA>"
166 split = doc.index(b"<Item")
167 parts = [doc[:split], doc[split:]]
168 rows = []
169 off = 0x1000
170 for part in parts:
171 with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f:
172 f.write(part)
173 rows.append({"off": off, "stored": len(part), "size": len(part),
174 "head": part[:16].hex(), "pre": ""})
175 off += 0x1000
176 with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f:
177 f.write(TAIL)
178 rows.append({"off": off, "stored": len(TAIL), "size": len(TAIL),
179 "head": TAIL[:16].hex(), "pre": ""})
180 with open(os.path.join(carve, "index.json"), "w", encoding="utf-8") as f:
181 json.dump({"summary": {"archive": "synthetic", "files": len(rows)}, "files": rows}, f)
182
183 out = os.path.join(self.root, "carve.json")
184 p = self.run_tool(carve, "--json", out, "--check")
185 self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
186 with open(out, encoding="utf-8") as f:
187 data = json.load(f)
188 s = data["summary"]
189 self.assertEqual(s["mode"], "carve")
190 self.assertEqual(s["documents"], 2)
191 self.assertEqual(s["well_formed"], 1)
192 self.assertEqual(s["tail_only"], 1)
193 self.assertEqual(s["truncated"], 1)
194 self.assertEqual(s["fragments"], 0)
195 self.assertEqual(s["root_count"], 2)
196 first = data["rows"][0]
197 self.assertEqual(first["root"], "RootA")
198 self.assertEqual(first["chunks"], 2)
199 self.assertEqual(first["bytes"], len(doc))
200 self.assertEqual(first["offset_hex"], "1000")
201 self.assertEqual(first["element_count"], 21)
202 self.assertEqual(first["max_depth"], 2)
203 tail = data["rows"][1]
204 self.assertEqual(tail["root"], "TailRoot")
205 self.assertTrue(tail["tail_only"])
206 self.assertTrue(tail["truncated"])
207 self.assertFalse(tail["malformed"])
208
209
210if __name__ == "__main__":
211 unittest.main()
diff --git a/tests/test_gen_d3d12_stubs.py b/tests/test_gen_d3d12_stubs.py
new file mode 100644
index 000000000..d03a1dd5f
--- /dev/null
+++ b/tests/test_gen_d3d12_stubs.py
@@ -0,0 +1,254 @@
1"""Tests for tools/gen_d3d12_stubs.py, driven by a synthetic d3d12.h (no Windows SDK).
2
3 python -I tests/test_gen_d3d12_stubs.py
4"""
5import importlib.util
6import os
7import tempfile
8import unittest
9from unittest import mock
10
11ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12
13
14def load_module():
15 path = os.path.join(ROOT, "tools", "gen_d3d12_stubs.py")
16 spec = importlib.util.spec_from_file_location("gen_d3d12_stubs_under_test", path)
17 module = importlib.util.module_from_spec(spec)
18 spec.loader.exec_module(module)
19 return module
20
21
22gen = load_module()
23
24GOOD_HEADER = """\
25MIDL_INTERFACE("11111111-2222-3333-4444-555555555555")
26IBase : public IUnknown
27{
28public:
29 virtual void STDMETHODCALLTYPE DoThing(UINT a, UINT b) = 0;
30 virtual HRESULT STDMETHODCALLTYPE Multi(
31 UINT first,
32 UINT second) = 0;
33 /* virtual void STDMETHODCALLTYPE Removed() = 0; */
34 virtual HRESULT STDMETHODCALLTYPE AfterComment(void) = 0; /* trailing note */
35};
36
37MIDL_INTERFACE("66666666-7777-8888-9999-AAAAAAAAAAAA")
38IChild : public IBase
39{
40public:
41 virtual HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const = 0;
42 virtual UINT64 STDMETHODCALLTYPE Size(void) = 0;
43};
44"""
45
46GUARDED_HEADER = """\
47MIDL_INTERFACE("22222222-2222-2222-2222-222222222222")
48IGuarded : public IUnknown
49{
50public:
51#if 0
52 virtual void STDMETHODCALLTYPE Gone(void) = 0;
53#endif
54 virtual void STDMETHODCALLTYPE Kept(void) = 0;
55};
56"""
57
58ORPHAN_HEADER = """\
59MIDL_INTERFACE("33333333-3333-3333-3333-333333333333")
60IOrphan : public IMissing
61{
62public:
63 virtual void STDMETHODCALLTYPE Nothing(void) = 0;
64};
65"""
66
67BROKEN_HEADER = """\
68MIDL_INTERFACE("44444444-4444-4444-4444-444444444444")
69IBroken : public IUnknown
70{
71public:
72 virtual void STDMETHODCALLTYPE NotAMethod = 0;
73};
74"""
75
76UNTERMINATED_HEADER = """\
77MIDL_INTERFACE("55555555-5555-5555-5555-555555555555")
78IHalf : public IUnknown
79{
80public:
81 virtual void STDMETHODCALLTYPE Missing(void);
82};
83"""
84
85IFACES = gen.parse_interfaces(GOOD_HEADER)
86
87
88class ParseInterfacesTests(unittest.TestCase):
89 def test_names_bases_and_methods(self):
90 self.assertEqual(sorted(IFACES), ["IBase", "IChild"])
91 self.assertEqual(IFACES["IBase"][0], "IUnknown")
92 self.assertEqual(IFACES["IChild"][0], "IBase")
93 methods = [item for item in IFACES["IBase"][1] if item[0] == "m"]
94 self.assertEqual([m[2] for m in methods], ["DoThing", "Multi", "AfterComment"])
95 self.assertEqual(methods[0], ("m", "void", "DoThing", "UINT a, UINT b", ""))
96
97 def test_multiline_declaration_is_joined(self):
98 methods = [item for item in IFACES["IBase"][1] if item[0] == "m"]
99 self.assertEqual(methods[1][3], "UINT first, UINT second")
100
101 def test_const_method_is_marked(self):
102 methods = [item for item in IFACES["IChild"][1] if item[0] == "m"]
103 self.assertEqual(methods[0][4], "const")
104 self.assertEqual(methods[0][2], "GetThing")
105
106 def test_commented_out_method_is_dropped(self):
107 names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"]
108 self.assertNotIn("Removed", names)
109
110 def test_inline_comment_after_a_declaration_keeps_it(self):
111 names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"]
112 self.assertIn("AfterComment", names)
113
114 def test_preprocessor_lines_pass_through(self):
115 items = gen.parse_interfaces(GUARDED_HEADER)["IGuarded"][1]
116 self.assertEqual(items[0], ("#", "#if 0"))
117 self.assertEqual(items[1][0], "m")
118 self.assertEqual(items[1][2], "Gone")
119 self.assertEqual(items[2], ("#", "#endif"))
120 self.assertEqual(items[3][2], "Kept")
121
122 def test_text_without_interfaces(self):
123 self.assertEqual(gen.parse_interfaces("// nothing here\n"), {})
124
125 def test_unterminated_declaration_raises(self):
126 with self.assertRaises(SystemExit):
127 gen.parse_interfaces(UNTERMINATED_HEADER)
128
129 def test_unparseable_declaration_raises(self):
130 with self.assertRaises(SystemExit):
131 gen.parse_interfaces(BROKEN_HEADER)
132
133
134class ChainTests(unittest.TestCase):
135 def test_leaf_comes_last(self):
136 self.assertEqual(gen.chain(IFACES, "IChild"), ["IBase", "IChild"])
137
138 def test_root_interface(self):
139 self.assertEqual(gen.chain(IFACES, "IBase"), ["IBase"])
140
141 def test_unknown_base_raises(self):
142 orphan = gen.parse_interfaces(ORPHAN_HEADER)
143 with self.assertRaises(SystemExit):
144 gen.chain(orphan, "IOrphan")
145
146
147class EmitClassTests(unittest.TestCase):
148 def test_class_skeleton_and_method_order(self):
149 text = gen.emit_class(IFACES, "IChild")
150 self.assertTrue(text.startswith("class IChildStubs : public IChild {\npublic:"))
151 self.assertTrue(text.endswith("};"))
152 self.assertLess(text.index("// IBase"), text.index("// IChild"))
153 self.assertLess(text.index("DoThing"), text.index("GetThing"))
154 self.assertNotIn("Removed", text)
155
156 def test_return_conventions_and_stub_names(self):
157 text = gen.emit_class(IFACES, "IChild")
158 self.assertIn(
159 ' void STDMETHODCALLTYPE DoThing(UINT a, UINT b) override '
160 '{ ::rt::d3d12::stub("IBase::DoThing"); }',
161 text,
162 )
163 self.assertIn(
164 ' HRESULT STDMETHODCALLTYPE Multi(UINT first, UINT second) override '
165 '{ ::rt::d3d12::stub("IBase::Multi"); return E_NOTIMPL; }',
166 text,
167 )
168 self.assertIn(
169 ' HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const override '
170 '{ ::rt::d3d12::stub("IChild::GetThing"); return E_NOTIMPL; }',
171 text,
172 )
173 self.assertIn(
174 ' UINT64 STDMETHODCALLTYPE Size(void) override '
175 '{ ::rt::d3d12::stub("IChild::Size"); return {}; }',
176 text,
177 )
178
179 def test_directives_are_emitted_verbatim(self):
180 text = gen.emit_class(gen.parse_interfaces(GUARDED_HEADER), "IGuarded")
181 self.assertIn("\n#if 0\n", text)
182 self.assertIn("\n#endif\n", text)
183 self.assertIn('stub("IGuarded::Gone")', text)
184
185
186class MainTests(unittest.TestCase):
187 def setUp(self):
188 tmp = tempfile.TemporaryDirectory()
189 self.addCleanup(tmp.cleanup)
190 self.dir = tmp.name
191 self.header = os.path.join(self.dir, "d3d12.h")
192 with open(self.header, "w", encoding="utf-8") as f:
193 f.write(GOOD_HEADER)
194 self.out = os.path.join(self.dir, "generated", "d3d12_stubs.h")
195
196 def run_main(self, *interfaces, include_header=True):
197 args = ["gen_d3d12_stubs.py", "--out", self.out]
198 if include_header:
199 args += ["--header", self.header]
200 with mock.patch("sys.argv", args + list(interfaces)):
201 return gen.main()
202
203 def test_writes_header_and_class(self):
204 self.assertEqual(self.run_main("IChild"), 0)
205 self.assertTrue(os.path.isdir(os.path.dirname(self.out)))
206 with open(self.out, encoding="utf-8") as f:
207 text = f.read()
208 self.assertTrue(
209 text.startswith(
210 "// Generated by tools/gen_d3d12_stubs.py from d3d12.h. Do not edit.\n"
211 )
212 )
213 for line in (
214 "#pragma once",
215 "#include <d3d12.h>",
216 "namespace rt::d3d12 { void stub(const char* method); }",
217 "#pragma warning(push)",
218 "#pragma warning(disable : 4100) // unreferenced parameters",
219 "class IChildStubs : public IChild {",
220 "#pragma warning(pop)",
221 ):
222 self.assertIn(line, text)
223 self.assertTrue(text.endswith("\n"))
224 self.assertNotIn("\r\n", text)
225
226 def test_second_run_does_not_rewrite(self):
227 self.assertEqual(self.run_main("IChild"), 0)
228 before = os.stat(self.out).st_mtime_ns
229 self.assertEqual(self.run_main("IChild"), 0)
230 self.assertEqual(os.stat(self.out).st_mtime_ns, before)
231
232 def test_two_interfaces_keep_their_order(self):
233 self.assertEqual(self.run_main("IBase", "IChild"), 0)
234 with open(self.out, encoding="utf-8") as f:
235 text = f.read()
236 self.assertLess(text.index("class IBaseStubs"), text.index("class IChildStubs"))
237
238 def test_unknown_interface_raises(self):
239 with self.assertRaises(SystemExit):
240 self.run_main("IWho")
241
242 def test_find_header_uses_the_include_environment(self):
243 with mock.patch.dict(os.environ, {"INCLUDE": self.dir}, clear=False):
244 self.assertEqual(gen.find_header(), self.header)
245 self.assertEqual(self.run_main("IChild", include_header=False), 0)
246 self.assertTrue(os.path.isfile(self.out))
247
248 def test_find_header_without_include_returns_none(self):
249 with mock.patch.dict(os.environ, {"INCLUDE": ""}, clear=False):
250 self.assertIsNone(gen.find_header())
251
252
253if __name__ == "__main__":
254 unittest.main()
diff --git a/tests/test_manifest.py b/tests/test_manifest.py
index bfd00622a..16b5a03c3 100644
--- a/tests/test_manifest.py
+++ b/tests/test_manifest.py
@@ -11,6 +11,7 @@ import subprocess
11import sys 11import sys
12import tempfile 12import tempfile
13import unittest 13import unittest
14from unittest.mock import patch
14 15
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16TOOL = os.path.join(ROOT, "tools", "manifest.py") 17TOOL = os.path.join(ROOT, "tools", "manifest.py")
@@ -69,6 +70,19 @@ class ManifestWalkTest(unittest.TestCase):
69 self.assertTrue(os.path.isabs(abs_path)) 70 self.assertTrue(os.path.isabs(abs_path))
70 self.assertTrue(os.path.exists(abs_path)) 71 self.assertTrue(os.path.exists(abs_path))
71 72
73 def test_walk_reports_an_unreadable_subdirectory(self):
74 blocked = os.path.join(self.pkg, "sub", "deep")
75 scandir = os.scandir
76
77 def scan(path):
78 if path == blocked:
79 raise PermissionError(f"cannot read {path}")
80 return scandir(path)
81
82 with patch.object(os, "scandir", side_effect=scan):
83 with self.assertRaises(PermissionError):
84 list(manifest.walk(self.pkg))
85
72 86
73class ManifestCreateVerifyTest(unittest.TestCase): 87class ManifestCreateVerifyTest(unittest.TestCase):
74 def setUp(self): 88 def setUp(self):
@@ -293,6 +307,26 @@ class ManifestCliTest(unittest.TestCase):
293 self.assertEqual(p_verify.returncode, 1) 307 self.assertEqual(p_verify.returncode, 1)
294 self.assertIn("problem(s)", p_verify.stdout) 308 self.assertIn("problem(s)", p_verify.stdout)
295 309
310 def test_cli_rejects_invalid_game_directories(self):
311 # Start with a valid empty manifest, which would otherwise verify even if the scan never ran.
312 empty = os.path.join(self.tmp.name, "empty")
313 os.mkdir(empty)
314 self.assertEqual(self.run_cli("create", empty, "--out", self.out_manifest).returncode, 0)
315 self.assertEqual(self.run_cli("verify", empty, "--manifest", self.out_manifest).returncode, 0)
316 with open(self.out_manifest, "rb") as f:
317 original = f.read()
318
319 for game_dir in (os.path.join(self.tmp.name, "missing"), os.path.join(self.pkg, "sample.dat")):
320 for command, option in (("create", "--out"), ("verify", "--manifest")):
321 with self.subTest(game_dir=game_dir, command=command):
322 result = self.run_cli(command, game_dir, option, self.out_manifest)
323 self.assertEqual(result.returncode, 2)
324 self.assertIn(os.path.basename(game_dir), result.stderr)
325 self.assertNotIn("Traceback", result.stderr)
326 self.assertEqual(result.stdout, "")
327 with open(self.out_manifest, "rb") as f:
328 self.assertEqual(f.read(), original)
329
296 330
297class ManifestBelowNormalTest(unittest.TestCase): 331class ManifestBelowNormalTest(unittest.TestCase):
298 def test_below_normal_callable(self): 332 def test_below_normal_callable(self):
diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py
new file mode 100644
index 000000000..0e3c84e53
--- /dev/null
+++ b/tests/test_mc_command.py
@@ -0,0 +1,61 @@
1"""LLVM_MC is one executable path or a whole command line, in every tool that reads it.
2
3Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU target):
4
5 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc
6
7 python -I tests/test_mc_command.py
8"""
9import os
10import sys
11import tempfile
12import unittest
13from unittest import mock
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16sys.path.insert(0, os.path.join(ROOT, "tools"))
17
18import mc_command # noqa: E402
19
20
21class SplitCommandTest(unittest.TestCase):
22 def test_bare_name(self):
23 self.assertEqual(mc_command.split_command("llvm-mc"), ["llvm-mc"])
24
25 def test_empty(self):
26 self.assertEqual(mc_command.split_command(""), [])
27 self.assertEqual(mc_command.split_command(" "), [])
28
29 def test_command_line(self):
30 self.assertEqual(mc_command.split_command("wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"),
31 ["wsl", "-d", "Ubuntu", "-e", "/usr/lib/llvm-21/bin/llvm-mc"])
32
33 def test_quoted_arguments(self):
34 if os.name == "nt":
35 raw = '"C:\\Program Files\\LLVM\\bin\\llvm-mc.exe" --version'
36 want = ["C:\\Program Files\\LLVM\\bin\\llvm-mc.exe", "--version"]
37 else:
38 raw = '"/opt/llvm 21/bin/llvm-mc" --version'
39 want = ["/opt/llvm 21/bin/llvm-mc", "--version"]
40 self.assertEqual(mc_command.split_command(raw), want)
41
42 def test_path_with_spaces_is_kept_whole(self):
43 with tempfile.TemporaryDirectory() as tmp:
44 path = os.path.join(tmp, "llvm mc")
45 with open(path, "w", encoding="utf-8") as f:
46 f.write("")
47 self.assertEqual(mc_command.split_command(path), [path])
48 self.assertEqual(mc_command.split_command(f'"{path}"'), [path])
49
50 def test_mc_command_reads_the_environment(self):
51 with mock.patch.dict(os.environ, {"LLVM_MC": "wsl -d Ubuntu -e /opt/llvm-21/bin/llvm-mc"}):
52 self.assertEqual(mc_command.mc_command(),
53 ["wsl", "-d", "Ubuntu", "-e", "/opt/llvm-21/bin/llvm-mc"])
54
55 def test_mc_command_falls_back_to_the_path_name(self):
56 with mock.patch.dict(os.environ, {"LLVM_MC": ""}):
57 self.assertEqual(mc_command.mc_command(), ["llvm-mc"])
58
59
60if __name__ == "__main__":
61 unittest.main()
diff --git a/tests/test_rbf0_tree.py b/tests/test_rbf0_tree.py
new file mode 100644
index 000000000..cb54b9ebf
--- /dev/null
+++ b/tests/test_rbf0_tree.py
@@ -0,0 +1,321 @@
1"""Synthetic-tree tests for tools/rbf0_tree.py.
2
3 python -I tests/test_rbf0_tree.py
4
5Every byte here is built by the test. No game file, game asset path or game name is used.
6"""
7import json
8import os
9import struct
10import sys
11import tempfile
12import unittest
13from xml.etree import ElementTree as ET
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16sys.path.insert(0, os.path.join(ROOT, "tools"))
17
18import rbf0_tree # noqa: E402
19
20WIDE = b"RBF0" + rbf0_tree.PROLOGUE
21CLOSE = b"\xff\xff"
22
23
24def _name(name):
25 return struct.pack("<H", len(name)) + name
26
27
28def _open(index, name=None, attrs=0):
29 out = bytes([index, 0x00])
30 if name is not None:
31 out += _name(name)
32 return out + struct.pack("<HHH", 0, 0, attrs)
33
34
35def _value(index, kind, payload=b"", name=None):
36 out = bytes([index, kind])
37 if name is not None:
38 out += _name(name)
39 return out + payload
40
41
42def _text(text, nul=True):
43 raw = text + (b"\x00" if nul else b"")
44 return b"\xfd\xff" + struct.pack("<I", len(raw)) + raw
45
46
47def wide_blob():
48 """Root -> Item(attrs=2) -> Child(text), then a value after the child."""
49 b = bytearray(WIDE)
50 b += _open(0, b"TestRoot")
51 b += _open(1, b"Item", attrs=2)
52 b += _value(2, 0x10, struct.pack("<Q", 7), b"count")
53 b += _value(3, 0x60, struct.pack("<H", 5) + b"alpha", b"label")
54 b += _open(4, b"Child")
55 b += _text(b"body")
56 b += CLOSE
57 b += _value(5, 0x40, struct.pack("<d", 0.5), b"ratio")
58 b += CLOSE
59 b += _open(6, b"Empty")
60 b += CLOSE
61 b += CLOSE
62 return bytes(b)
63
64
65def narrow_blob():
66 b = bytearray(b"RBF0")
67 b += _open(0, b"TestRoot")
68 b += _value(1, 0x10, struct.pack("<I", 7), b"count")
69 b += _value(2, 0x40, struct.pack("<f", 0.5), b"ratio")
70 b += CLOSE
71 return bytes(b)
72
73
74def other_blob():
75 b = bytearray(WIDE)
76 b += _open(0, b"OtherRoot")
77 b += _value(1, 0x20, b"", b"flag")
78 b += CLOSE
79 return bytes(b)
80
81
82class ParseTest(unittest.TestCase):
83 def test_tree_offsets_and_nesting(self):
84 blob = wide_blob()
85 doc = rbf0_tree.parse_resource(blob)
86 self.assertEqual(doc["status"], "ok")
87 self.assertEqual(doc["root_name"], "TestRoot")
88 self.assertEqual(doc["layout"], "wide-64")
89 self.assertEqual(doc["size"], len(blob))
90 self.assertEqual(doc["end"], len(blob))
91 self.assertEqual((doc["counts"]["elements"], doc["counts"]["values"], doc["counts"]["texts"]),
92 (4, 3, 1))
93 root = doc["tree"]
94 self.assertEqual(root["offset"], 8)
95 self.assertEqual(root["header_offset"], 20)
96 self.assertEqual(root["end"], len(blob))
97 item = root["content"][0]
98 self.assertEqual(item["name"], "Item")
99 self.assertEqual(item["offset"], 26)
100 self.assertEqual(item["header_offset"], 34)
101 self.assertEqual(item["depth"], 2)
102 self.assertEqual(item["attrs_declared"], 2)
103 self.assertEqual([a["name"] for a in item["attributes"]], ["count", "label"])
104 self.assertEqual([a["value"] for a in item["attributes"]], [7, "alpha"])
105 self.assertEqual([n["kind"] for n in item["content"]], ["element", "value"])
106 child = item["content"][0]
107 self.assertEqual(child["name"], "Child")
108 self.assertEqual(child["depth"], 3)
109 self.assertEqual(child["content"][0]["kind"], "text")
110 self.assertEqual(child["content"][0]["depth"], 4)
111 self.assertEqual(child["content"][0]["text"], "body")
112 self.assertTrue(child["content"][0]["nul_terminated"])
113 self.assertEqual(item["content"][1]["name"], "ratio")
114 self.assertEqual(item["content"][1]["value"], 0.5)
115 self.assertTrue(item["value_after_child"])
116 self.assertEqual(doc["attribute_mismatches"], 0)
117 self.assertEqual(doc["attribute_order_violations"], 0)
118 self.assertEqual(doc["max_depth"], 3) # elements only; the text child is at element depth 4
119
120 def test_descriptor_table(self):
121 doc = rbf0_tree.parse_resource(wide_blob())
122 self.assertEqual(doc["descriptor_count"], 7)
123 table = {d["index"]: d for d in doc["descriptors"]}
124 self.assertEqual(table[0]["name"], "TestRoot")
125 self.assertEqual(table[0]["first_type"], "open")
126 self.assertEqual(table[2]["name"], "count")
127 self.assertEqual(table[2]["first_type"], "int")
128 self.assertEqual(table[3]["name"], "label")
129 self.assertEqual(table[3]["first_type"], "string")
130 self.assertEqual(table[5]["types"], {"float": 1})
131 self.assertEqual(table[3]["uses"], 1)
132 self.assertEqual(doc["distinct_descriptor_names"], 7)
133
134 def test_descriptor_is_a_name_index_not_a_type(self):
135 b = bytearray(WIDE)
136 b += _open(0, b"TestRoot")
137 b += _open(1, b"Item", attrs=2)
138 b += _value(2, 0x10, struct.pack("<Q", 5), b"value")
139 b += _value(2, 0x40, struct.pack("<d", 1.5))
140 b += CLOSE
141 b += CLOSE
142 doc = rbf0_tree.parse_resource(bytes(b))
143 self.assertEqual(doc["status"], "ok")
144 desc = {d["index"]: d for d in doc["descriptors"]}[2]
145 self.assertEqual(desc["name"], "value")
146 self.assertEqual(desc["first_type"], "int")
147 self.assertEqual(desc["types"], {"int": 1, "float": 1})
148 item = doc["tree"]["content"][0]
149 self.assertEqual([a["type"] for a in item["attributes"]], ["int", "float"])
150
151 def test_narrow_widths(self):
152 doc = rbf0_tree.parse_resource(narrow_blob())
153 self.assertEqual(doc["status"], "ok")
154 self.assertEqual(doc["layout"], "narrow-32")
155 item = doc["tree"]
156 self.assertEqual(item["content"][0]["value"], 7)
157 self.assertEqual(item["content"][0]["size"], 4)
158 self.assertEqual(item["content"][1]["value"], 0.5)
159 self.assertEqual(item["content"][1]["size"], 4)
160
161 def test_text_and_string_framing(self):
162 doc = rbf0_tree.parse_resource(wide_blob())
163 item = doc["tree"]["content"][0]
164 label = item["attributes"][1]
165 self.assertEqual(label["type"], "string")
166 self.assertEqual(label["byte_length"], 5)
167 self.assertFalse(label["nul_terminated"])
168 self.assertEqual(label["payload_offset"] + label["size"], label["payload_offset"] + 5)
169 text = item["content"][0]["content"][0]
170 self.assertEqual(text["length"], 5)
171 self.assertTrue(text["nul_terminated"])
172 self.assertEqual(text["payload_offset"] + text["length"], text["offset"] + 2 + 4 + 5)
173
174 def test_trailing_bytes(self):
175 blob = wide_blob() + b"\x00\x00"
176 doc = rbf0_tree.parse_resource(blob)
177 self.assertEqual(doc["status"], "trailing")
178 self.assertEqual(doc["tree"]["end"], len(blob) - 2)
179 self.assertIn("after the root closed", doc["error"])
180
181 def test_truncated(self):
182 doc = rbf0_tree.parse_resource(wide_blob()[:30])
183 self.assertEqual(doc["status"], "truncated")
184 self.assertIn("truncated", doc["error"])
185
186 def test_unknown_descriptor_fails_closed(self):
187 b = WIDE + _open(0, b"TestRoot") + bytes([9, 0x10]) + struct.pack("<Q", 1) + CLOSE
188 doc = rbf0_tree.parse_resource(b)
189 self.assertEqual(doc["status"], "bad")
190 self.assertIn("descriptor index 9 of 1", doc["error"])
191 self.assertEqual(doc["descriptor_count"], 1)
192 self.assertEqual(doc["tree"]["name"], "TestRoot")
193 self.assertEqual(doc["tree"]["content"], [])
194 self.assertEqual(doc["counts"].get("values", 0), 0)
195
196 def test_unknown_record_type_fails_closed(self):
197 b = WIDE + _open(0, b"TestRoot") + bytes([1, 0x99]) + _name(b"weird") + CLOSE
198 doc = rbf0_tree.parse_resource(b)
199 self.assertEqual(doc["status"], "bad")
200 self.assertIn("unknown record type 0x99", doc["error"])
201 self.assertEqual([d["name"] for d in doc["descriptors"]], ["TestRoot", "weird"])
202 self.assertEqual(doc["tree"]["content"], [])
203
204 def test_bad_element_word_fails_closed(self):
205 b = WIDE + bytes([0, 0x00]) + _name(b"TestRoot") + struct.pack("<HHH", 1, 0, 0) + CLOSE
206 doc = rbf0_tree.parse_resource(b)
207 self.assertEqual(doc["status"], "bad")
208 self.assertIn("word is not zero", doc["error"])
209 self.assertIsNone(doc["tree"])
210
211 def test_not_rbf0(self):
212 with self.assertRaises(rbf0_tree.TreeError):
213 rbf0_tree.parse_resource(b"PSIN" + bytes(16))
214
215
216class JoinTest(unittest.TestCase):
217 def setUp(self):
218 self.tmp = tempfile.TemporaryDirectory()
219 self.root = self.tmp.name
220
221 def tearDown(self):
222 self.tmp.cleanup()
223
224 def test_join_at_64k(self):
225 b = bytearray(WIDE)
226 b += _open(0, b"BigRoot")
227 filler = b"x" * 4000
228 b += _value(1, 0x60, struct.pack("<H", len(filler)) + filler, b"filler")
229 while len(b) < 70000:
230 b += _value(1, 0x60, struct.pack("<H", len(filler)) + filler)
231 b += CLOSE
232 blob = bytes(b)
233 self.assertGreater(len(blob), 65536)
234 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
235 f.write(blob[:65536])
236 with open(os.path.join(self.root, "00010000.bin"), "wb") as f:
237 f.write(blob[65536:])
238 docs, summary = rbf0_tree.decode_source(self.root)
239 self.assertEqual(len(docs), 1)
240 self.assertEqual(docs[0]["chunks"], 2)
241 self.assertEqual(docs[0]["size"], len(blob))
242 self.assertEqual(docs[0]["status"], "ok")
243 self.assertEqual(docs[0]["root_name"], "BigRoot")
244 self.assertEqual(summary["resources"], 1)
245 self.assertEqual(summary["ok"], 1)
246
247 def test_single_resource_file(self):
248 path = os.path.join(self.root, "resource.bin")
249 with open(path, "wb") as f:
250 f.write(wide_blob())
251 docs, summary = rbf0_tree.decode_source(path)
252 self.assertEqual(len(docs), 1)
253 self.assertEqual(docs[0]["root_name"], "TestRoot")
254 self.assertEqual(summary["ok"], 1)
255
256
257class OutputTest(unittest.TestCase):
258 def setUp(self):
259 self.tmp = tempfile.TemporaryDirectory()
260 self.root = self.tmp.name
261
262 def tearDown(self):
263 self.tmp.cleanup()
264
265 def test_json_and_xml(self):
266 blob = bytearray(WIDE)
267 blob += _open(0, b"TestRoot", attrs=1)
268 blob += _value(1, 0x60, struct.pack("<H", 3) + b"a &", b"xmlns:xi")
269 blob += _open(2, b"Text")
270 blob += _text(b"a < b & c")
271 blob += CLOSE
272 blob += _open(3, b"Ctrl")
273 blob += _text(b"a\x01b")
274 blob += CLOSE
275 blob += CLOSE
276 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
277 f.write(blob)
278 out = os.path.join(self.root, "tree.json")
279 xml_dir = os.path.join(self.root, "xml")
280 self.assertEqual(rbf0_tree.main([self.root, out, "--xml", xml_dir, "--quiet"]), 0)
281 with open(out, encoding="utf-8") as f:
282 doc = json.load(f)
283 self.assertEqual(doc["summary"]["resources"], 1)
284 self.assertEqual(doc["summary"]["elements"], 3)
285 self.assertEqual(doc["resources"][0]["tree"]["attributes"][0]["name"], "xmlns:xi")
286 xml_path = os.path.join(xml_dir, "00000000.xml")
287 self.assertTrue(os.path.exists(xml_path))
288 tree = ET.parse(xml_path)
289 root = tree.getroot()
290 self.assertEqual(root.tag, "rbf0")
291 attr = root.find(".//attr")
292 self.assertEqual(attr.get("name"), "xmlns:xi")
293 self.assertEqual(attr.text, "a &")
294 texts = root.findall(".//text")
295 self.assertEqual(texts[0].text, "a < b & c")
296 self.assertEqual(texts[1].text, "a\ufffdb") # XML 1.0 control bytes are replaced, not emitted
297
298 def test_root_filter_and_limit(self):
299 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
300 f.write(wide_blob())
301 with open(os.path.join(self.root, "00001000.bin"), "wb") as f:
302 f.write(other_blob())
303 docs, summary = rbf0_tree.decode_source(self.root, roots=["OtherRoot"])
304 self.assertEqual(len(docs), 1)
305 self.assertEqual(docs[0]["root_name"], "OtherRoot")
306 self.assertEqual(summary["roots"], {"OtherRoot": 1})
307 docs, _ = rbf0_tree.decode_source(self.root, limit=1)
308 self.assertEqual(len(docs), 1)
309
310 def test_bad_resource_exit_code(self):
311 with open(os.path.join(self.root, "00000000.bin"), "wb") as f:
312 f.write(WIDE + _open(0, b"TestRoot") + bytes([9, 0x10]) + struct.pack("<Q", 1))
313 out = os.path.join(self.root, "tree.json")
314 self.assertEqual(rbf0_tree.main([self.root, out, "--quiet"]), 1)
315 with open(out, encoding="utf-8") as f:
316 doc = json.load(f)
317 self.assertEqual(doc["summary"]["bad"], 1)
318
319
320if __name__ == "__main__":
321 unittest.main()
diff --git a/tests/test_root_sig_contract.py b/tests/test_root_sig_contract.py
new file mode 100644
index 000000000..8b1ca221b
--- /dev/null
+++ b/tests/test_root_sig_contract.py
@@ -0,0 +1,110 @@
1"""Contract tests for tools/root_sig_contract.py (no game data, no GPU).
2
3Run from the repository root: python -m pytest tests/test_root_sig_contract.py
4Everything is hand-built: synthetic root signatures and synthetic index
5entries, so these run on every CI leg including Windows without llvm-mc.
6"""
7import json
8import os
9import subprocess
10import sys
11
12import pytest
13
14import root_sig_contract as rsc
15
16ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17TOOL = os.path.join(ROOT, "tools", "root_sig_contract.py")
18
19ROOT_SIG = {
20 "version": "1.1",
21 "flags": 0,
22 "params": [
23 {"type": "constants", "count": 4, "visibility": "all"},
24 {"type": "cbv", "visibility": "vertex"},
25 {"type": "table", "ranges": [{"kind": "srv", "count": 8}],
26 "visibility": "pixel"},
27 ],
28}
29
30
31def test_pack_layout_order_and_provenance():
32 dwords, error = rsc.pack_layout(ROOT_SIG)
33 assert error == ""
34 assert len(dwords) == 8
35 assert [d["param"] for d in dwords] == [0, 0, 0, 0, 1, 1, 2, 2]
36 assert [d["sub"] for d in dwords] == [0, 1, 2, 3, 0, 1, 0, 1]
37 assert dwords[0]["ptype"] == "constants"
38 assert dwords[4]["ptype"] == "descriptor"
39 assert dwords[6]["ptype"] == "table"
40
41
42def test_pack_layout_static_samplers_free():
43 sig = dict(ROOT_SIG, static_samplers=[{"filter": 21}])
44 dwords, error = rsc.pack_layout(sig)
45 assert error == "" and len(dwords) == 8
46
47
48def test_pack_layout_spill_refused():
49 sig = {"version": "1.1", "flags": 0,
50 "params": [{"type": "cbv"} for _ in range(17)]}
51 dwords, error = rsc.pack_layout(sig)
52 assert dwords == [] and "spill" in error
53
54
55def test_pack_layout_cost_limit():
56 sig = {"version": "1.1", "flags": 0,
57 "params": [{"type": "constants", "count": 65}]}
58 dwords, error = rsc.pack_layout(sig)
59 assert dwords == [] and "64-dword" in error
60
61
62def test_pack_layout_unknown_type():
63 sig = {"version": "1.1", "flags": 0, "params": [{"type": "ufo"}]}
64 dwords, error = rsc.pack_layout(sig)
65 assert dwords == [] and "unknown type" in error
66
67
68def test_reconcile_compatible():
69 dwords, _ = rsc.pack_layout(ROOT_SIG)
70 reads = [{"sgpr": 0, "kind": "const32"},
71 {"sgpr": 4, "kind": "ptr64_lo"},
72 {"sgpr": 5, "kind": "ptr64_hi"},
73 {"sgpr": 6, "kind": "tsharp"}]
74 assert rsc.reconcile(reads, dwords) == []
75
76
77@pytest.mark.parametrize(("sgpr", "kind", "needle"), [
78 (0, "ptr64_lo", "incompatible"), # s0 is a constant dword, not a VA
79 (31, "const32", "8 dwords"), # layout ends at s7
80 (4, "ptr64_hi", "paired lo"), # s4 is sub 0 of the CBV pair
81 (0, "nope", "unknown read kind"),
82])
83def test_reconcile_contradictions(sgpr, kind, needle):
84 dwords, _ = rsc.pack_layout(ROOT_SIG)
85 issues = rsc.reconcile([{"sgpr": sgpr, "kind": kind}], dwords)
86 assert len(issues) == 1 and needle in issues[0]
87
88
89def test_cluster_groups_shapes():
90 index = {
91 "a": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]},
92 "b": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]},
93 "c": {"user_sgpr_reads": [{"sgpr": 4, "kind": "ptr64_lo"}]},
94 }
95 ranked = rsc.cluster(index)
96 assert ranked[0][1] == 2 and ranked[1][1] == 1
97
98
99def test_cli_hard_fail_on_contradiction(tmp_path):
100 index = {"bad": {"user_sgpr_reads": [{"sgpr": 31, "kind": "const32"}]}}
101 index_path = tmp_path / "index.json"
102 index_path.write_text(json.dumps(index), encoding="utf-8")
103 sig_path = tmp_path / "sig.json"
104 sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8")
105 r = subprocess.run(
106 [sys.executable, "-I", TOOL, str(index_path),
107 "--rootsig", str(sig_path)],
108 capture_output=True, text=True)
109 assert r.returncode == 1
110 assert "CONTRADICTION bad" in r.stdout
diff --git a/tests/test_rpf9_carve.py b/tests/test_rpf9_carve.py
index b5407a12b..c7a11d82b 100644
--- a/tests/test_rpf9_carve.py
+++ b/tests/test_rpf9_carve.py
@@ -43,5 +43,38 @@ class CarveTrailingStreamTest(unittest.TestCase):
43 self.assertEqual(doc["files"][1]["off"], 0x40 + len(a)) 43 self.assertEqual(doc["files"][1]["off"], 0x40 + len(a))
44 44
45 45
46def carve(test, data):
47 """Run rpf9_carve.py on `data`; return its index.json after checking it exited cleanly."""
48 with tempfile.TemporaryDirectory() as tmp:
49 arc = os.path.join(tmp, "x.rpf")
50 out = os.path.join(tmp, "out")
51 with open(arc, "wb") as f:
52 f.write(data)
53 p = subprocess.run([sys.executable, "-I", TOOL, arc, out, "--index-only"], capture_output=True, text=True)
54 test.assertEqual(p.returncode, 0, p.stderr)
55 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
56 return json.load(f)
57
58
59class CarveEdgeTest(unittest.TestCase):
60 def test_bink_signature_cut_off_by_end_of_file(self):
61 # A truncated copy can end inside what looks like a Bink 2 header: its fields lie past the end of the file.
62 a = zlib.compress(b"A" * 1000)
63 data = bytearray(0x40) + a + b"KB2a" + bytes(8)
64 data[0:4] = b"RPF9"
65 struct.pack_into("<I", data, 4, 0x40)
66 doc = carve(self, bytes(data))
67 self.assertEqual(doc["summary"]["files"], 1, doc["summary"])
68 self.assertEqual(doc["summary"]["unread_bytes"], 12)
69
70 def test_empty_data_area(self):
71 data = bytearray(0x40)
72 data[0:4] = b"RPF9"
73 struct.pack_into("<I", data, 4, 0x40) # data starts at the end of the file
74 doc = carve(self, bytes(data))
75 self.assertEqual(doc["summary"]["files"], 0)
76 self.assertEqual(doc["summary"]["span"], 0)
77
78
46if __name__ == "__main__": 79if __name__ == "__main__":
47 unittest.main() 80 unittest.main()
diff --git a/tests/test_rpf_probe.py b/tests/test_rpf_probe.py
new file mode 100644
index 000000000..205a77103
--- /dev/null
+++ b/tests/test_rpf_probe.py
@@ -0,0 +1,153 @@
1"""Tests for tools/rpf_probe.py, built from synthetic archive headers (no game data).
2
3 python -I tests/test_rpf_probe.py
4"""
5import contextlib
6import importlib.util
7import io
8import json
9import os
10import struct
11import tempfile
12import unittest
13from unittest import mock
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
17
18def load_module():
19 path = os.path.join(ROOT, "tools", "rpf_probe.py")
20 spec = importlib.util.spec_from_file_location("rpf_probe_under_test", path)
21 module = importlib.util.module_from_spec(spec)
22 spec.loader.exec_module(module)
23 return module
24
25
26probe = load_module()
27
28
29def archive_bytes(version=b"4FPR", words=(0x10, 0x20, 0x30, 0x40), pad_to=None, tail=b""):
30 """Little-endian 'RPF4' magic, four header words, then optional padding and payload."""
31 data = version + struct.pack("<4I", *words)
32 if pad_to is not None and len(data) < pad_to:
33 data += b"\x00" * (pad_to - len(data))
34 return data + tail
35
36
37class EntropyTests(unittest.TestCase):
38 def test_empty_is_zero(self):
39 self.assertEqual(probe.entropy(b""), 0.0)
40
41 def test_single_symbol_is_zero(self):
42 self.assertEqual(probe.entropy(b"\x00" * 16), 0.0)
43
44 def test_two_equally_frequent_symbols(self):
45 self.assertEqual(probe.entropy(b"\x00\x01" * 8), 1.0)
46
47 def test_all_byte_values_once(self):
48 self.assertEqual(probe.entropy(bytes(range(256))), 8.0)
49
50
51class ProbeTests(unittest.TestCase):
52 def setUp(self):
53 tmp = tempfile.TemporaryDirectory()
54 self.addCleanup(tmp.cleanup)
55 self.dir = tmp.name
56
57 def write(self, data, name="a.rpf"):
58 path = os.path.join(self.dir, name)
59 os.makedirs(os.path.dirname(path), exist_ok=True)
60 with open(path, "wb") as f:
61 f.write(data)
62 return path
63
64 def test_version_and_header_words(self):
65 row = probe.probe(self.write(archive_bytes(words=(0x0, 0xFFFFFFFF, 0x1234, 0x10))))
66 self.assertEqual(row["version"], "RPF4")
67 self.assertEqual(row["header_words"], ["0x0", "0xffffffff", "0x1234", "0x10"])
68
69 def test_natural_order_magic_is_not_a_version(self):
70 self.assertEqual(probe.probe(self.write(b"RPF4" + b"\x00" * 16))["version"], None)
71
72 def test_other_magic_has_no_version(self):
73 self.assertEqual(probe.probe(self.write(b"DDS " + b"\x00" * 30))["version"], None)
74
75 def test_short_file_has_no_words(self):
76 row = probe.probe(self.write(b"4FPR" + b"\x00" * 4))
77 self.assertEqual(row["version"], "RPF4")
78 self.assertEqual(row["header_words"], [])
79 self.assertEqual(row["head_entropy"], 0.0)
80 self.assertFalse(row["looks_encrypted"])
81
82 def test_zero_filled_body_is_not_flagged(self):
83 row = probe.probe(self.write(archive_bytes(words=(0, 0, 0, 0), pad_to=1024)))
84 self.assertEqual(row["head_entropy"], 0.0)
85 self.assertFalse(row["looks_encrypted"])
86
87 def test_dense_body_is_flagged(self):
88 row = probe.probe(self.write(archive_bytes(tail=bytes(range(256)) * 16)))
89 self.assertGreater(row["head_entropy"], 7.9)
90 self.assertTrue(row["looks_encrypted"])
91
92 def test_only_the_first_64_kib_is_read(self):
93 path = self.write(archive_bytes(pad_to=0x10000, tail=bytes(range(256)) * 16))
94 row = probe.probe(path)
95 self.assertEqual(row["size"], 0x10000 + 4096)
96 self.assertEqual(row["head_entropy"], 0.0)
97 self.assertFalse(row["looks_encrypted"])
98
99 def test_size_is_the_full_file(self):
100 self.assertEqual(probe.probe(self.write(archive_bytes(pad_to=0x10000)))["size"], 0x10000)
101
102
103class MainTests(unittest.TestCase):
104 def setUp(self):
105 tmp = tempfile.TemporaryDirectory()
106 self.addCleanup(tmp.cleanup)
107 self.tmp = tmp.name
108 self.game = os.path.join(self.tmp, "game")
109 os.makedirs(self.game)
110 self.out = os.path.join(self.tmp, "reports", "rpf.json")
111
112 def write(self, rel, data):
113 path = os.path.join(self.game, rel)
114 os.makedirs(os.path.dirname(path), exist_ok=True)
115 with open(path, "wb") as f:
116 f.write(data)
117 return path
118
119 def run_main(self):
120 out = io.StringIO()
121 with mock.patch("sys.argv", ["rpf_probe.py", self.game, "--out", self.out]), contextlib.redirect_stdout(out):
122 self.assertEqual(probe.main(), 0)
123 return out.getvalue()
124
125 def rows(self):
126 with open(self.out, encoding="utf-8") as f:
127 return json.load(f)
128
129 def test_collects_rpf_files_recursively_and_sorts_by_size(self):
130 small = self.write("a.rpf", archive_bytes())
131 large = self.write("sub/b.RPF", archive_bytes(pad_to=4096))
132 self.write("sub/notes.txt", b"ignored")
133 out = self.run_main()
134 rows = self.rows()
135 self.assertEqual([os.path.basename(r["file"]) for r in rows], ["b.RPF", "a.rpf"])
136 self.assertEqual(os.path.normpath(rows[0]["file"]), os.path.normpath(large))
137 self.assertEqual(os.path.normpath(rows[1]["file"]), os.path.normpath(small))
138 self.assertIn("2 archives", out)
139 self.assertIn("'RPF4': 2", out)
140
141 def test_creates_the_output_directory(self):
142 self.write("a.rpf", archive_bytes())
143 self.run_main()
144 self.assertTrue(os.path.isfile(self.out))
145
146 def test_empty_game_directory(self):
147 out = self.run_main()
148 self.assertEqual(self.rows(), [])
149 self.assertIn("0 archives", out)
150
151
152if __name__ == "__main__":
153 unittest.main()
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py
index 68de87947..748c780d5 100644
--- a/tests/test_shader_checks.py
+++ b/tests/test_shader_checks.py
@@ -13,7 +13,7 @@ import check
13 13
14# The other wave64-only dump tests (#73's cs_wm_*, the cs_w64x_* cross-half tests): name -> expected out[] words. 14# The other wave64-only dump tests (#73's cs_wm_*, the cs_w64x_* cross-half tests): name -> expected out[] words.
15WAVE64_DUMPS = {n: w for n, w in check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL 15WAVE64_DUMPS = {n: w for n, w in check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL
16 if n not in ("cs_store", "cs_wave64_ballot")} 16 if n not in (*check.WAVE32_DUMPS, "cs_wave64_ballot")}
17# A group smaller than a wave can't ask for full subgroups: it asks for subgroup size 64 and reads the device's range. 17# A group smaller than a wave can't ask for full subgroups: it asks for subgroup size 64 and reads the device's range.
18PARTIAL = {n for n, _ in check.W64X_PARTIAL} 18PARTIAL = {n for n, _ in check.W64X_PARTIAL}
19 19
@@ -57,6 +57,10 @@ class Wave64Checks(unittest.TestCase):
57 self.assertNotIn("--require-wave64", args) 57 self.assertNotIn("--require-wave64", args)
58 if name == "cs_store": 58 if name == "cs_store":
59 return 0, "out[0..7] = 1073774847 3758097407 1006649344 4008636142 1073757184 3154130944 0 0\n" 59 return 0, "out[0..7] = 1073774847 3758097407 1006649344 4008636142 1073757184 3154130944 0 0\n"
60 if name == "cs_smem_soffset_imm":
61 return 0, "out[0..7] = " + " ".join(map(str, check.CS_SMEM)) + "\n"
62 if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line
63 return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n"
60 if name in ("cs_imgstore", "cs_imgload"): 64 if name in ("cs_imgstore", "cs_imgload"):
61 return 0, "0 bad\n0 bad\n0 bad\n" 65 return 0, "0 bad\n0 bad\n0 bad\n"
62 return 0, "0 mismatches\n" 66 return 0, "0 mismatches\n"
diff --git a/tests/test_shader_ir.py b/tests/test_shader_ir.py
new file mode 100644
index 000000000..b4655f533
--- /dev/null
+++ b/tests/test_shader_ir.py
@@ -0,0 +1,226 @@
1"""Tests for tools/shader_ir.py, built from synthetic AMDGPU disassembly (no game data).
2
3 python -I tests/test_shader_ir.py
4"""
5import importlib.util
6import os
7import tempfile
8import unittest
9
10ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
12
13def load_module():
14 path = os.path.join(ROOT, "tools", "shader_ir.py")
15 spec = importlib.util.spec_from_file_location("shader_ir_under_test", path)
16 module = importlib.util.module_from_spec(spec)
17 spec.loader.exec_module(module)
18 return module
19
20
21shader_ir = load_module()
22
23
24class OperandTests(unittest.TestCase):
25 def test_single_registers(self):
26 self.assertEqual(
27 shader_ir.operand("s5"),
28 {"k": "sgpr", "r": 5, "n": 1, "neg": False, "abs": False},
29 )
30 self.assertEqual(
31 shader_ir.operand("v3"),
32 {"k": "vgpr", "r": 3, "n": 1, "neg": False, "abs": False},
33 )
34
35 def test_register_ranges(self):
36 self.assertEqual(
37 shader_ir.operand("s[4:7]"),
38 {"k": "sgpr", "r": 4, "n": 4, "neg": False, "abs": False},
39 )
40 self.assertEqual(
41 shader_ir.operand("v[0:0]"),
42 {"k": "vgpr", "r": 0, "n": 1, "neg": False, "abs": False},
43 )
44
45 def test_negation_and_absolute_value(self):
46 self.assertTrue(shader_ir.operand("-v2")["neg"])
47 self.assertTrue(shader_ir.operand("|s1|")["abs"])
48 both = shader_ir.operand("-|v2|")
49 self.assertTrue(both["neg"])
50 self.assertTrue(both["abs"])
51
52 def test_inline_and_float_constants(self):
53 self.assertEqual(shader_ir.operand("0x10"), {"k": "imm", "v": 16})
54 self.assertEqual(shader_ir.operand("-5"), {"k": "imm", "v": -5})
55 self.assertEqual(shader_ir.operand("1.5"), {"k": "fimm", "v": 1.5, "abs": False})
56 self.assertEqual(shader_ir.operand("-2.5e1"), {"k": "fimm", "v": -25.0, "abs": False})
57 self.assertEqual(shader_ir.operand("|1.0|"), {"k": "fimm", "v": 1.0, "abs": True})
58
59 def test_hardware_negation_of_constants(self):
60 # The disassembler prints VOP3 inline negation as neg(0) / neg(5).
61 self.assertEqual(shader_ir.operand("neg(0)"), {"k": "fimm", "v": -0.0, "abs": False})
62 self.assertEqual(shader_ir.operand("neg(5)"), {"k": "imm", "v": -5})
63 self.assertEqual(shader_ir.operand("neg(1.0)"), {"k": "fimm", "v": -1.0, "abs": False})
64
65 def test_negation_of_registers_toggles(self):
66 self.assertTrue(shader_ir.operand("neg(v1)")["neg"])
67 self.assertFalse(shader_ir.operand("neg(neg(v1))")["neg"])
68
69 def test_sign_extension(self):
70 self.assertTrue(shader_ir.operand("sext(v1)")["sext"])
71 self.assertFalse(shader_ir.operand("sext(v1)")["neg"])
72 self.assertTrue(shader_ir.operand("-sext(v1)")["neg"])
73 self.assertTrue(shader_ir.operand("sext(neg(v1))")["neg"])
74
75 def test_ttmp_registers(self):
76 self.assertEqual(shader_ir.operand("ttmp5"), {"k": "ttmp", "t": "ttmp5"})
77 self.assertEqual(shader_ir.operand("ttmp[4:5]"), {"k": "ttmp", "t": "ttmp[4:5]"})
78
79 def test_non_contiguous_vgpr_list(self):
80 self.assertEqual(shader_ir.operand("[v1, v2, v3]"), {"k": "vlist", "r": [1, 2, 3]})
81
82 def test_attribute_and_interpolation(self):
83 self.assertEqual(shader_ir.operand("attr2.w"), {"k": "attr", "a": 2, "c": 3})
84 self.assertEqual(shader_ir.operand("p10"), {"k": "interp", "t": "p10"})
85
86 def test_export_targets(self):
87 self.assertEqual(shader_ir.operand("pos0"), {"k": "target", "t": "pos0"})
88 self.assertEqual(shader_ir.operand("mrt1"), {"k": "target", "t": "mrt1"})
89 self.assertEqual(shader_ir.operand("mrtz"), {"k": "target", "t": "mrtz"})
90
91 def test_special_registers_including_null(self):
92 for name in ("vcc_lo", "exec", "m0", "scc", "null", "off"):
93 with self.subTest(name=name):
94 self.assertEqual(shader_ir.operand(name)["k"], "special")
95 self.assertEqual(shader_ir.operand(name)["t"], name)
96
97 def test_hardware_register_and_counter_forms(self):
98 self.assertEqual(shader_ir.operand("hwreg(0x1234)")["k"], "special")
99 self.assertEqual(shader_ir.operand("vmcnt(3)")["k"], "special")
100 self.assertEqual(shader_ir.operand("sendmsg(MSG_GS)")["k"], "special")
101
102 def test_unknown_operand_falls_back_to_raw(self):
103 self.assertEqual(shader_ir.operand("weirdthing"), {"k": "raw", "t": "weirdthing"})
104
105
106class SplitArgsTests(unittest.TestCase):
107 def test_commas_inside_parentheses_stay_together(self):
108 self.assertEqual(
109 shader_ir.split_args("a, b(1, 2), c"),
110 ["a", " b(1, 2)", " c"],
111 )
112
113 def test_commas_inside_brackets_stay_together(self):
114 self.assertEqual(shader_ir.split_args("[v1, v2], v3"), ["[v1, v2]", " v3"])
115
116 def test_trailing_comma_is_dropped(self):
117 self.assertEqual(shader_ir.split_args("v0,"), ["v0"])
118
119 def test_empty_text(self):
120 self.assertEqual(shader_ir.split_args(""), [])
121
122
123class ParseLineTests(unittest.TestCase):
124 def test_operation_and_operands(self):
125 ins = shader_ir.parse_line("\tv_add_f32 v0, v1, v2")
126 self.assertEqual(ins["op"], "v_add_f32")
127 self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "vgpr"])
128 self.assertEqual(ins["mods"], [])
129 self.assertIsNone(ins["enc"])
130
131 def test_encoding_bytes(self):
132 ins = shader_ir.parse_line("\tv_mov_b32 v0, v1 ; encoding: [0x0a,0xff]")
133 self.assertEqual(ins["enc"], "0aff")
134 self.assertEqual(len(ins["args"]), 2)
135
136 def test_comment_or_blank_lines_are_skipped(self):
137 self.assertIsNone(shader_ir.parse_line("; only a comment"))
138 self.assertIsNone(shader_ir.parse_line(""))
139 self.assertIsNone(shader_ir.parse_line(" \t "))
140
141 def test_modifiers_are_removed_from_the_operands(self):
142 ins = shader_ir.parse_line(
143 "\tbuffer_load_dword v5, v[0:3], s[4:7], 0 offen offset:8 glc slc"
144 )
145 self.assertEqual(ins["mods"], ["offen", "offset:8", "glc", "slc"])
146 self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "sgpr", "imm"])
147 self.assertEqual(ins["args"][1]["n"], 4)
148 self.assertEqual(ins["args"][2]["n"], 4)
149
150 def test_dpp_modifiers_keep_their_bracket_lists(self):
151 ins = shader_ir.parse_line(
152 "\tv_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf"
153 )
154 self.assertEqual(
155 ins["mods"],
156 ["quad_perm:[1,0,3,2]", "row_mask:0xf", "bank_mask:0xf"],
157 )
158 self.assertEqual(len(ins["args"]), 2)
159
160 def test_exp_target_is_split_from_its_operands(self):
161 ins = shader_ir.parse_line("\texp mrt0 v0, v1, v2, v3")
162 self.assertEqual(len(ins["args"]), 5)
163 self.assertEqual(ins["args"][0], {"k": "target", "t": "mrt0"})
164 self.assertEqual(ins["args"][1]["k"], "vgpr")
165
166 def test_exp_null_off_target(self):
167 ins = shader_ir.parse_line("\texp null off, v0, v1, v2")
168 self.assertEqual([a["t"] for a in ins["args"][:2]], ["null", "off"])
169 self.assertEqual(len(ins["args"]), 5)
170
171 def test_sendmsg_commas_stay_in_one_operand(self):
172 ins = shader_ir.parse_line("\ts_sendmsg sendmsg(MSG_GS, GS_OP_NOP)")
173 self.assertEqual(len(ins["args"]), 1)
174 self.assertEqual(ins["args"][0]["k"], "special")
175
176 def test_no_operands(self):
177 self.assertEqual(shader_ir.parse_line("\ts_endpgm")["args"], [])
178
179
180class ParseFileTests(unittest.TestCase):
181 def write(self, text):
182 tmp = tempfile.TemporaryDirectory()
183 self.addCleanup(tmp.cleanup)
184 path = os.path.join(tmp.name, "shader_abc.s")
185 with open(path, "w", encoding="utf-8", newline="\n") as f:
186 f.write(text)
187 return path
188
189 def test_header_start_and_pc_stepping(self):
190 path = self.write(
191 "; shader.cs_5_0 code 0x00000100..0x00000110\n"
192 "\tv_mov_b32 v0, 1.0 ; encoding: [0x01,0x02]\n"
193 "\tv_add_f32 v1, v0, v2 ; encoding: [0x03,0x04]\n"
194 "\tv_sub_f32 v3, v1, v0 ; no encoding bytes here\n"
195 "\t.directive skipped\n"
196 "plain text is not an instruction\n"
197 "; ---\n"
198 "\tv_mul_f32 v4, v3, v2 ; encoding: [0x05,0x06]\n"
199 "; invalid instruction encoding [0xdead]\n"
200 )
201 info = shader_ir.parse_file(path)
202 self.assertEqual(info["name"], "shader_abc")
203 self.assertEqual(info["code_start"], 0x100)
204 self.assertEqual([i["op"] for i in info["insns"]],
205 ["v_mov_b32", "v_add_f32", "v_sub_f32"])
206 # pc advances by the encoding length; an instruction without bytes keeps the offset.
207 self.assertEqual([i["pc"] for i in info["insns"]], [0x100, 0x102, 0x104])
208 self.assertEqual(info["invalid"], 1)
209
210 def test_file_without_a_header_starts_at_zero(self):
211 path = self.write("\tv_mov_b32 v0, v1 ; encoding: [0xaa,0xbb]\n")
212 info = shader_ir.parse_file(path)
213 self.assertEqual(info["code_start"], 0)
214 self.assertEqual(info["insns"][0]["pc"], 0)
215 self.assertEqual(info["insns"][0]["enc"], "aabb")
216
217 def test_header_only_file_has_no_instructions(self):
218 path = self.write("; shader.cs_6_0 code 0x00001000..0x00001008\n")
219 info = shader_ir.parse_file(path)
220 self.assertEqual(info["code_start"], 0x1000)
221 self.assertEqual(info["insns"], [])
222 self.assertEqual(info["invalid"], 0)
223
224
225if __name__ == "__main__":
226 unittest.main()
diff --git a/tests/test_translate.py b/tests/test_translate.py
index b825b5416..4e60193b4 100644
--- a/tests/test_translate.py
+++ b/tests/test_translate.py
@@ -286,6 +286,29 @@ def test_vs_misc_pos1_shifts_clip_to_pos2(make_shader):
286 assert [int(x) for x in clip_chains] == [0, 1] 286 assert [int(x) for x in clip_chains] == [0, 1]
287 287
288 288
289def test_pos1_without_osg1_is_ignored(make_shader):
290 """Without OSG1 declaring SV_ClipDistance/SV_CullDistance, pos1 exports are discarded in both VS and MS."""
291 vs = make_shader(_vs_header_asm("exp pos1 v10, off, off, off done"), name="vs_no_osg1_pos1")
292 vs_spv = vs.translate()
293 vs.validate(vs_spv)
294 assert "OpCapability ClipDistance" not in vs_spv
295 assert "BuiltIn ClipDistance" not in vs_spv
296 vs_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, vs_spv)
297 assert "shaderClipDistance" not in vs_meta["features"]
298 assert 1 not in vs_meta.get("outputs", [])
299
300 ms = make_shader(_ms_header_asm("exp pos1 v10, off, off, off done"), name="ms_no_osg1_pos1",
301 dxbc=make_dxbc([mesh_psv0_chunk()]))
302 ms_spv = ms.translate()
303 ms.validate(ms_spv, KNOWN_VAL_ISSUES.get("ms_tri"))
304 assert "OpCapability ClipDistance" not in ms_spv
305 assert "BuiltIn ClipDistance" not in ms_spv
306 assert "%ms_out_pos" in ms_spv and "%ms_vtx_blk" not in ms_spv
307 ms_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, ms_spv)
308 assert "shaderClipDistance" not in ms_meta["features"]
309 assert 1 not in ms_meta.get("params", [])
310
311
289def test_ms_dummy_all_off_pos1_does_not_emit_clip(make_shader): 312def test_ms_dummy_all_off_pos1_does_not_emit_clip(make_shader):
290 """An all-off dummy pos1 export in a mesh shader must not emit ClipDistance or change the output block.""" 313 """An all-off dummy pos1 export in a mesh shader must not emit ClipDistance or change the output block."""
291 dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])]) 314 dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])])
diff --git a/tests/test_ttpf_mips.py b/tests/test_ttpf_mips.py
new file mode 100644
index 000000000..a41f6c0e3
--- /dev/null
+++ b/tests/test_ttpf_mips.py
@@ -0,0 +1,291 @@
1"""Tests for tools/ttpf_mips.py: tile modes, mip-tail layout, BC decode, metric, and a
2synthetic RDS5/ETPF pool round trip. No game data is used.
3
4 python -I tests/test_ttpf_mips.py
5"""
6import importlib.util
7import json
8import os
9import struct
10import sys
11import tempfile
12import unittest
13import zlib
14
15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16TOOL = os.path.join(ROOT, "tools", "ttpf_mips.py")
17spec = importlib.util.spec_from_file_location("ttpf_mips", TOOL)
18ttpf = importlib.util.module_from_spec(spec)
19spec.loader.exec_module(ttpf)
20
21
22def rgb565(r, g, b):
23 return ((r * 31 // 255) << 11) | ((g * 63 // 255) << 5) | (b * 31 // 255)
24
25
26def solid_bc1(color):
27 c = rgb565(*color)
28 return struct.pack("<HHI", c, c, 0)
29
30
31def retile_to(layout, mip, linear, out):
32 pat = (ttpf.PATTERNS_4K if layout["tile"] == 4096 else ttp64)[
33 {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]]
34 eb = layout["element_bytes"]
35 bw, bh = layout["block_w"], layout["block_h"]
36 for y in range(mip["blocks_h"]):
37 for x in range(mip["blocks_w"]):
38 off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"]
39 for bit, s in enumerate(pat):
40 if s > 0:
41 off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit
42 elif s < 0:
43 off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit
44 at = (y * mip["blocks_w"] + x) * eb
45 out[mip["offset"] + off:mip["offset"] + off + eb] = linear[at:at + eb]
46
47
48ttpf64 = {
49 0: (1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8),
50 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8),
51 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7),
52 3: (0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7),
53 4: (0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6),
54}
55
56
57def solid_chain(layout, fmt=71):
58 """Build block-linear bytes for every mip; each block is one solid BC1 colour."""
59 eb = layout["element_bytes"]
60 out = {}
61 # Smooth gradient at the top level; every lower mip is the 2x2 block mean.
62 top = layout["mips"][0]
63 colours = {}
64 for y in range(top["blocks_h"]):
65 for x in range(top["blocks_w"]):
66 colours[(0, x, y)] = (min(255, x * 255 // max(1, top["blocks_w"] - 1)),
67 min(255, y * 255 // max(1, top["blocks_h"] - 1)), 128)
68 for m in range(1, len(layout["mips"])):
69 pm = layout["mips"][m - 1]
70 cm = layout["mips"][m]
71 for y in range(cm["blocks_h"]):
72 for x in range(cm["blocks_w"]):
73 acc = [0, 0, 0]
74 n = 0
75 for dy in range(2):
76 for dx in range(2):
77 px, py = min(pm["blocks_w"] - 1, 2 * x + dx), min(pm["blocks_h"] - 1, 2 * y + dy)
78 q = colours[(m - 1, px, py)]
79 for k in range(3):
80 acc[k] += q[k]
81 n += 1
82 colours[(m, x, y)] = tuple(a // n for a in acc)
83 for mip in layout["mips"]:
84 buf = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb)
85 for y in range(mip["blocks_h"]):
86 for x in range(mip["blocks_w"]):
87 at = (y * mip["blocks_w"] + x) * eb
88 buf[at:at + eb] = solid_bc1(colours[(mip["index"], x, y)])[:eb].ljust(eb, b"\0")
89 out[mip["index"]] = bytes(buf)
90 return out
91
92
93def build_pool(path, width=256, height=256, mips=7, non_tail=1, fmt=71, mode=4,
94 meta=0x103, extra=0, packed=6):
95 layout = ttpf.surface_layout(width, height, fmt, mips, ttpf.tile_bytes(mode))
96 linear = solid_chain(layout, fmt)
97 payload = bytearray(layout["size"])
98 for mip in layout["mips"]:
99 retile_to(layout, mip, linear[mip["index"]], payload)
100 packed_payload = zlib.compress(bytes(payload), 9)
101 pad = (-len(packed_payload)) % 256
102 count = 3
103 table_end = 24 + (count - 1) * 8
104 etpf = ttpf.align(table_end, 256)
105 metadata = 16 + 24 + 32
106 padded = ttpf.align(metadata, 4096)
107 source = etpf + padded
108 chunk_end = source + len(packed_payload) + pad
109 virt = padded
110 vsize = virt + layout["size"]
111 assert vsize % 4096 == 0
112 entry = (source // 256) | (8 << 26) | ((virt // 4096) << 30) | (pad << 52)
113 sentinel = (chunk_end // 256) | ((vsize // 4096) << 30)
114 header = bytearray(24)
115 header[0:4] = b"RDS5"
116 struct.pack_into("<I", header, 4, count)
117 struct.pack_into("<Q", header, 8, vsize | (22 << 56))
118 struct.pack_into("<I", header, 16, (count + 31) // 32)
119 struct.pack_into("<I", header, 20, 0)
120 a = (width - 1) | ((height - 1) << 14) | ((packed & 0xF) << 28)
121 b = non_tail | (fmt << 3) | (1 << 21) | (mode << 23)
122 c = (virt // 4096) | (meta << 21)
123 record = struct.pack("<IIII", a, b, c, extra) + struct.pack("<Q", 0x1234567890ABCDEF)
124 blob = bytearray(chunk_end)
125 blob[0:24] = header
126 struct.pack_into("<QQ", blob, 24, entry, sentinel)
127 blob[etpf:etpf + 4] = b"ETPF"
128 struct.pack_into("<III", blob, etpf + 4, 634, 1, 24)
129 blob[etpf + 16:etpf + 16 + 24] = record
130 blob[source:source + len(packed_payload)] = packed_payload
131 with open(path, "wb") as f:
132 f.write(blob)
133 return layout
134
135
136class TileModeTest(unittest.TestCase):
137 def test_mode_is_flag_plus_tile_mode(self):
138 self.assertEqual([ttpf.tile_mode(m) for m in (0, 1, 2, 4, 5, 6, 7, 32, 34, 36, 38)],
139 [0, 0, 1, 2, 2, 3, 3, 0, 1, 2, 3])
140 self.assertEqual([ttpf.tile_bytes(m) for m in (0, 1, 2, 4, 32, 34)],
141 [65536, 65536, 4096, 4096, 65536, 4096])
142
143
144class LayoutTest(unittest.TestCase):
145 def test_known_bc1_chain_sizes(self):
146 lay = ttpf.surface_layout(256, 256, 71, 7, 4096)
147 self.assertEqual(lay["first_tail"], 2)
148 self.assertEqual(lay["size"], 45056)
149 self.assertEqual([m["region"] for m in lay["mips"]],
150 [32768, 8192, 4096, 4096, 4096, 4096, 4096])
151 self.assertEqual([m["offset"] for m in lay["mips"][:2]], [12288, 4096])
152 # 16x16 pixels = 4x4 blocks at in-tile origin (16, 0)
153 self.assertEqual((lay["mips"][2]["blocks_w"], lay["mips"][2]["blocks_h"]), (16, 16))
154 self.assertEqual((lay["mips"][2]["tile_x"], lay["mips"][2]["tile_y"]), (16, 0))
155
156 def test_validated_1024_chain(self):
157 lay = ttpf.surface_layout(1024, 1024, 71, 9, 4096)
158 self.assertEqual(lay["first_tail"], 4)
159 self.assertEqual(lay["size"], 700416)
160 self.assertEqual([m["region"] for m in lay["mips"][:4]],
161 [524288, 131072, 32768, 8192])
162 self.assertEqual(lay["mips"][4]["tile_x"], 16)
163 self.assertEqual(lay["mips"][4]["tile_y"], 0)
164
165 def test_64k_tile_mode(self):
166 lay = ttpf.surface_layout(1024, 1024, 98, 9, 65536)
167 self.assertEqual(lay["size"], 1441792)
168 self.assertEqual(lay["first_tail"], 3)
169 self.assertEqual(lay["tile"], 65536)
170
171 def test_bad_mip_count(self):
172 with self.assertRaises(ttpf.LayoutError):
173 ttpf.surface_layout(64, 64, 71, 20, 4096)
174
175
176class BcDecodeTest(unittest.TestCase):
177 def test_bc1_solid_block(self):
178 block = solid_bc1((255, 0, 0))
179 px = ttpf.decode_pixels(71, block, 1, 1)
180 self.assertEqual(len(px), 16)
181 self.assertGreater(px[0][0], 250)
182 self.assertLess(px[0][1], 8)
183
184 def test_bc1_four_colour_mode(self):
185 # c0=white > c1=black: index 0 -> white, index 3 -> (c0 + 2*c1)/3
186 white = ttpf.decode_pixels(71, struct.pack("<HHI", 0xFFFF, 0x0000, 0), 1, 1)
187 self.assertGreater(white[0][0], 250)
188 dark = ttpf.decode_pixels(71, struct.pack("<HHI", 0xFFFF, 0x0000, 0xFFFFFFFF), 1, 1)
189 self.assertLess(dark[0][0], 100)
190
191 def test_metric_rewards_the_true_downsample(self):
192 parent = [(0.0, 0.0, 0.0), (255.0, 0.0, 0.0), (0.0, 255.0, 0.0), (0.0, 0.0, 255.0)]
193 child = [(63.75, 63.75, 63.75)]
194 self.assertLess(ttpf.mean_abs_error(ttpf.downsample2(parent, 2, 2), child), 1.0)
195 wrong = [(0.0, 255.0, 0.0)]
196 self.assertGreater(ttpf.mean_abs_error(ttpf.downsample2(parent, 2, 2), wrong), 50)
197
198
199class SyntheticPoolTest(unittest.TestCase):
200 def setUp(self):
201 self.tmp = tempfile.TemporaryDirectory()
202 self.addCleanup(self.tmp.cleanup)
203 self.path = os.path.join(self.tmp.name, "synthetic.ttpf")
204 self.layout = build_pool(self.path)
205 self.pool = ttpf.Pool(self.path)
206 self.addCleanup(self.pool.close)
207
208 def test_descriptor_and_layout(self):
209 d = self.pool.descriptor(0)
210 self.assertEqual((d["width"], d["height"], d["format"], d["mips"], d["non_tail"]),
211 (256, 256, 71, 7, 1))
212 self.assertEqual(d["mode"], 4)
213 a = ttpf.analyze(self.pool, 0)
214 self.assertTrue(a["span_matches"])
215 self.assertTrue(a["full_chain"])
216 self.assertEqual(a["layout"]["first_tail"], 2)
217
218 def test_detile_round_trip(self):
219 a = ttpf.analyze(self.pool, 0)
220 layout = a["layout"]
221 tiled = self.pool.read_range(a["descriptor"]["base"], layout["size"])
222 linear = solid_chain(layout)
223 for mip in layout["mips"]:
224 data = ttpf.detile(layout, mip, tiled[mip["offset"]:mip["offset"] + mip["region"]])
225 self.assertEqual(data, linear[mip["index"]])
226
227 def test_chain_metric(self):
228 import io
229 from contextlib import redirect_stdout
230 buf = io.StringIO()
231 with redirect_stdout(buf):
232 code = ttpf.check(self.pool, 0)
233 result = json.loads(buf.getvalue())
234 self.assertEqual(code, 0, result)
235 self.assertLess(result["max_error"], 4.0)
236 # a wrong in-tile origin for the first tail mip must be much worse
237 self.assertGreater(result["tail_origin_control"], 5 * result["max_error"])
238
239 def test_export_full_chain(self):
240 out = os.path.join(self.tmp.name, "chain.dds")
241 import io
242 from contextlib import redirect_stdout
243 with redirect_stdout(io.StringIO()):
244 self.assertEqual(ttpf.export(self.pool, 0, out), 0)
245 with open(out, "rb") as f:
246 data = f.read()
247 self.assertEqual(data[:4], b"DDS ")
248 mips = struct.unpack_from("<I", data, 28)[0]
249 self.assertEqual(mips, 7)
250 expected = 148 + sum(m["blocks_w"] * m["blocks_h"] * 8 for m in self.layout["mips"])
251 self.assertEqual(len(data), expected)
252 # payload is exactly the concatenated block-linear chain
253 linear = solid_chain(self.layout)
254 self.assertEqual(data[148:], b"".join(linear[m["index"]] for m in self.layout["mips"]))
255
256 def test_scan_reports_the_whitelist_gate(self):
257 # The synthetic tuple is validated, so it is not gated: the partial export is
258 # the descriptor non_tail limit, not the 319-byte profile table.
259 out = os.path.join(self.tmp.name, "scan.json")
260 import io
261 from contextlib import redirect_stdout
262 with redirect_stdout(io.StringIO()):
263 ttpf.scan_pools([self.path], out)
264 with open(out, encoding="utf-8") as f:
265 result = json.load(f)["total"]
266 self.assertEqual(result["entries"], 1)
267 self.assertEqual(result["whitelist_gated"], 0)
268 self.assertEqual(result["reader_partial"], 1)
269 self.assertEqual(result["compact_partial_rows"], 1)
270 self.assertEqual(result["compact_missing_mips"], 6)
271 self.assertEqual(result["compact_decodable_mips"], 6)
272 self.assertEqual(result["compact_full_rows"], 1)
273
274 def test_scan_counts_an_unlisted_tuple_as_gated(self):
275 path = os.path.join(self.tmp.name, "unlisted.ttpf")
276 build_pool(path, meta=0x599)
277 out = os.path.join(self.tmp.name, "scan2.json")
278 import io
279 from contextlib import redirect_stdout
280 with redirect_stdout(io.StringIO()):
281 ttpf.scan_pools([path], out)
282 with open(out, encoding="utf-8") as f:
283 total = json.load(f)["total"]
284 self.assertEqual(total["whitelist_gated"], 1)
285 self.assertEqual(total["gated_layout_ok"], 1)
286 self.assertEqual(total["gated_full_chain"], 1)
287 self.assertEqual(total["gated_full_mips"], 7)
288
289
290if __name__ == "__main__":
291 unittest.main()
diff --git a/tests/test_world_census.py b/tests/test_world_census.py
new file mode 100644
index 000000000..dc98268ad
--- /dev/null
+++ b/tests/test_world_census.py
@@ -0,0 +1,167 @@
1"""Tests for tools/world_census.py, built from synthetic 0x7a resources and RPF9 streams (no game data).
2
3 python -I tests/test_world_census.py
4"""
5import importlib.util
6import os
7import struct
8import tempfile
9import unittest
10import zlib
11
12ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
14
15def load_tool():
16 path = os.path.join(ROOT, "tools", "world_census.py")
17 spec = importlib.util.spec_from_file_location("world_census_under_test", path)
18 module = importlib.util.module_from_spec(spec)
19 spec.loader.exec_module(module)
20 return module
21
22
23WC = load_tool()
24WI = WC.WI
25PTR = 0x50000000
26
27
28def ptr(off):
29 return PTR | off
30
31
32def member(hash_, off, ty, sub=0, ref=0, extra=0):
33 return struct.pack("<IIBBHI", hash_, off, ty, sub, ref, extra)
34
35
36def struct_def(hash_, size, members, at, member_at):
37 return struct.pack("<IIIIQIHH", hash_, 0, 0, 0, ptr(member_at), size, 0, len(members))
38
39
40def make_resource(map_file=True):
41 """A minimal, valid 0x7a resource with one entity and (optionally) a map root."""
42 b = bytearray(0x700)
43 b[0x10:0x14] = b"0DRP"
44 b[0x14] = 0x7A
45 struct.pack_into("<I", b, 0x20, 1)
46 struct.pack_into("<Q", b, 0x28, ptr(0x100))
47 struct.pack_into("<Q", b, 0x38, ptr(0x200))
48 nst = 2 if map_file else 1
49 nbl = 2 if map_file else 1
50 struct.pack_into("<HHHH", b, 0x48, nst, 0, nbl, 0)
51
52 members = [
53 member(WI.FIELD["archetypeName"], 0x44, 0x4A),
54 member(WI.FIELD["position"], 0x38, 0x32),
55 member(WI.FIELD["rotation"], 0x10, 0x34),
56 member(WI.FIELD["scaleXY"], 0x54, 0x21),
57 member(WI.FIELD["scaleZ"], 0x58, 0x21),
58 member(WI.FIELD["flags"], 0x48, 0x15),
59 member(WI.FIELD["guid"], 0x20, 0x4F),
60 member(WI.FIELD["lodLevel"], 0x7E, 0x60),
61 member(WI.FIELD["lodDist"], 0x60, 0x21),
62 ]
63 entity_members = 0x300
64 for i, m in enumerate(members):
65 b[entity_members + 16 * i:entity_members + 16 * (i + 1)] = m
66 b[0x100:0x120] = struct_def(WI.ENTITY, 0x90, members, 0x100, entity_members)
67 struct.pack_into("<IIQ", b, 0x200, WI.ENTITY, 0x90, ptr(0x400))
68
69 e = 0x400
70 struct.pack_into("<4f", b, e + 0x10, 0.0, 0.0, 0.0, 1.0)
71 struct.pack_into("<Q", b, e + 0x20, 0x1122334455667788)
72 struct.pack_into("<3f", b, e + 0x38, 1.5, 2.5, 3.5)
73 struct.pack_into("<I", b, e + 0x44, 0xDEADBEEF)
74 struct.pack_into("<I", b, e + 0x48, 5)
75 struct.pack_into("<2f", b, e + 0x54, 1.0, 1.0)
76 struct.pack_into("<f", b, e + 0x60, 250.0)
77 b[e + 0x7E] = 1
78
79 if map_file:
80 mm = [
81 member(WI.FIELD["name"], 0x08, 0x4A),
82 member(WI.FIELD["parent"], 0x68, 0x4A),
83 member(WI.FIELD["streamingExtentsMin"], 0x70, 0x32),
84 member(WI.FIELD["streamingExtentsMax"], 0x7C, 0x32),
85 member(WI.FIELD["flags_map"], 0x88, 0x15),
86 member(WI.FIELD["contentFlags"], 0x8C, 0x15),
87 ]
88 map_members = 0x3A0
89 for i, m in enumerate(mm):
90 b[map_members + 16 * i:map_members + 16 * (i + 1)] = m
91 b[0x120:0x140] = struct_def(WI.MAPDATA, 0x120, mm, 0x120, map_members)
92 struct.pack_into("<IIQ", b, 0x210, WI.MAPDATA, 0x120, ptr(0x500))
93 root = 0x500
94 struct.pack_into("<I", b, root + 0x08, 0x11223344)
95 struct.pack_into("<I", b, root + 0x68, 0xAABBCCDD)
96 struct.pack_into("<3f", b, root + 0x70, -10.0, -20.0, -30.0)
97 struct.pack_into("<3f", b, root + 0x7C, 10.0, 20.0, 30.0)
98 struct.pack_into("<I", b, root + 0x88, 2)
99 struct.pack_into("<I", b, root + 0x8C, 65)
100 return bytes(b)
101
102
103def make_rpf_streams(parts, start=0x40):
104 """A minimal RPF9-looking file: header word + compressed parts, 16-byte aligned."""
105 out = bytearray(start)
106 out[:4] = b"9FPR"
107 struct.pack_into("<I", out, 4, start)
108 for part in parts:
109 pos = (len(out) + 15) & ~15
110 out.extend(b"\0" * (pos - len(out)))
111 out.extend(zlib.compress(part))
112 return bytes(out)
113
114
115class CensusTest(unittest.TestCase):
116 def setUp(self):
117 self.tmp = tempfile.TemporaryDirectory()
118 self.dir = self.tmp.name
119
120 def tearDown(self):
121 self.tmp.cleanup()
122
123 def test_inflate_keeps_a_map_header(self):
124 resource = make_resource()
125 blob = zlib.compress(resource)
126 data, used, eof, is_meta, inflated, truncated = WC.inflate(blob, 0, len(blob), keep=True)
127 self.assertEqual(data, resource)
128 self.assertEqual(used, len(blob))
129 self.assertTrue(eof)
130 self.assertTrue(is_meta)
131 self.assertEqual(inflated, len(resource))
132 self.assertFalse(truncated)
133
134 def test_assemble_joins_a_split_resource(self):
135 resource = make_resource()
136 blob = make_rpf_streams([resource[:0x150], resource[0x150:]])
137 res = WC.assemble(blob, 0x40, len(blob))
138 self.assertIsNotNone(res)
139 self.assertEqual(res["data"], resource)
140 self.assertTrue(res["joined"])
141 self.assertTrue(res["complete"])
142 self.assertEqual(res["streams"], 2)
143
144 def test_shard_and_summary_count_one_map(self):
145 resource = make_resource()
146 archive = os.path.join(self.dir, "sample.rpf")
147 with open(archive, "wb") as f:
148 f.write(make_rpf_streams([resource]))
149 with open(archive, "rb") as f:
150 data_start = struct.unpack_from("<I", f.read(8), 4)[0]
151 size = os.path.getsize(archive)
152 out = os.path.join(self.dir, "census")
153 os.makedirs(out)
154 result = WC.scan_shard((archive, 0, data_start, size, out, data_start))
155 self.assertEqual((result["maps"], result["entities"]), (1, 1))
156 summary = WC.summarize(archive, out, data_start, size, size - data_start, data_start)
157 self.assertTrue(summary["complete"])
158 self.assertTrue(summary["maps_exact"])
159 self.assertTrue(summary["entities_exact"])
160 self.assertEqual((summary["maps"], summary["entities"]), (1, 1))
161 self.assertEqual(summary["totals"]["entity_unresolved"], 0)
162 self.assertEqual(summary["coverage"]["raw_maps"], 0)
163 self.assertEqual(summary["coverage"]["missed_zlib_meta"], 0)
164
165
166if __name__ == "__main__":
167 unittest.main(verbosity=2)
diff --git a/tools/awc_manifest.py b/tools/awc_manifest.py
index 27bf7b625..f8df52952 100644
--- a/tools/awc_manifest.py
+++ b/tools/awc_manifest.py
@@ -13,8 +13,9 @@ streamed_music, data_offset, data_size, bank_size, notes. JSON is an object with
13stream_count, streamed_music_channel_count and a streams list of the same fields (booleans and 13stream_count, streamed_music_channel_count and a streams list of the same fields (booleans and
14numbers keep their types). duration_s is the AWC header's declared samples / sample rate; notes 14numbers keep their types). duration_s is the AWC header's declared samples / sample rate; notes
15flags values that look inconsistent (zero/odd rate, data-size mismatch, implausible duration). 15flags values that look inconsistent (zero/odd rate, data-size mismatch, implausible duration).
16A streamed-music descriptor contributes one row per mono channel; data_offset/size is its shared 16A streamed-music descriptor contributes one row per channel group; `channels` is the packet channel count read
17data tag. 17from the Opus TOC stereo bit, and `declared_samples`/`duration_s` are per channel (the descriptor stores the
18interleaved count). `data_offset`/`size` is the shared data tag.
18""" 19"""
19import argparse 20import argparse
20import csv 21import csv
@@ -108,8 +109,8 @@ def _bank_rows(path: str) -> list:
108 print(f"awc_manifest: warning: {bank}: ignored malformed streamed-music descriptor", 109 print(f"awc_manifest: warning: {bank}: ignored malformed streamed-music descriptor",
109 file=sys.stderr) 110 file=sys.stderr)
110 continue 111 continue
111 for cid, samples, rate, codec, _packets in channels: 112 for cid, samples, rate, codec, _packets, packet_channels in channels:
112 rows[cid] = _row(bank, cid, codec, 1, rate, samples, data, bank_size, True) 113 rows[cid] = _row(bank, cid, codec, packet_channels, rate, samples, data, bank_size, True)
113 return list(rows.values()) 114 return list(rows.values())
114 115
115 116
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index b43a796f0..2f2156220 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -6,13 +6,15 @@ AWC layout (little-endian "ADAT"), as read by rpf9-explorer's OpusPreview.cpp: a
6(id[28:0] | tag count[31:29]), then 8-byte tags (type[63:56], size[55:28], offset[27:0]). Tag 0x55 = data, 6(id[28:0] | tag count[31:29]), then 8-byte tags (type[63:56], size[55:28], offset[27:0]). Tag 0x55 = data,
70x76 = format (u32 samples, u16 rate at +8, codec at +28, channels at +29). Codec 0x0B = Opus at 48 kHz: data is 70x76 = format (u32 samples, u16 rate at +8, codec at +28, channels at +29). Codec 0x0B = Opus at 48 kHz: data is
82048-byte blocks of [u16 length][packet] ..., a zero length pads the rest of the block. Codec 0 = PCM16 (written as 82048-byte blocks of [u16 length][packet] ..., a zero length pads the rest of the block. Codec 0 = PCM16 (written as
9.wav). Codec 2 = 32-bit float PCM (float .wav). Streamed music (tag 0x48, multi-channel interleaved blocks) is not handled here yet. 9.wav). Codec 2 = 32-bit float PCM (float .wav).
10 10
11Streamed music (tag 0x48 descriptor: u32 blocks, u32 chunk size, u32 channels, then 16 bytes per channel: id, 11Streamed music (tag 0x48 descriptor: u32 blocks, u32 chunk size, u32 channels, then 16 bytes per channel: id,
12samples, rate at +10, codec at +12) is split into one mono Ogg Opus per channel: each chunk starts with a 12samples, rate at +10, codec at +12) is split into one Ogg Opus per descriptor channel: each chunk starts with a
1324-byte record per channel (subblock count at +4, repeated-prefix samples to skip at +8), the channel data are 1324-byte record per channel (subblock count at +4, repeated-prefix samples to skip at +8), the channel data are
14its run of 2048-byte subblocks after the 2048-aligned header, and the first `skip` samples of a chunk repeat the 14its run of 2048-byte subblocks after the 2048-aligned header, and the first `skip` samples of a chunk repeat the
15previous chunk's tail and are dropped (whole packets). 15previous chunk's tail and are dropped (whole packets). The descriptor's `channels` is the number of channel
16groups, not necessarily the packet channel count: an Opus packet's TOC stereo bit gives the real channel count,
17and the descriptor's `samples` counts interleaved samples across those packet channels.
16 18
17Output: <out>/<bank>/<stream id>.ogg (or .wav), plus a summary line per bank. 19Output: <out>/<bank>/<stream id>.ogg (or .wav), plus a summary line per bank.
18 20
@@ -156,7 +158,11 @@ def parse_awc(d: bytes):
156 158
157 159
158def music_channels(d: bytes, mus, data, collect_packets: bool = True): 160def music_channels(d: bytes, mus, data, collect_packets: bool = True):
159 """[(channel id, samples, rate, codec, [packets])] for one streamed-music descriptor. 161 """[(channel id, samples, rate, codec, [packets], packet channels)] for one streamed-music descriptor.
162
163 `samples` is the per-channel frame count. The descriptor stores the interleaved sample count, so it is
164 divided by the packet channel count when the Opus packets are stereo. `packet channels` is read from the
165 Opus TOC stereo bit (bit 2) and defaults to 1 when no packet is present.
160 166
161 collect_packets=False keeps the packet lists empty for metadata-only callers (awc_manifest.py).""" 167 collect_packets=False keeps the packet lists empty for metadata-only callers (awc_manifest.py)."""
162 (m_at, m_size), (d_at, d_size) = mus, data 168 (m_at, m_size), (d_at, d_size) = mus, data
@@ -169,7 +175,7 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True):
169 cid = struct.unpack_from("<I", d, base)[0] & 0x1FFFFFFF 175 cid = struct.unpack_from("<I", d, base)[0] & 0x1FFFFFFF
170 samples, = struct.unpack_from("<I", d, base + 4) 176 samples, = struct.unpack_from("<I", d, base + 4)
171 rate, = struct.unpack_from("<H", d, base + 10) 177 rate, = struct.unpack_from("<H", d, base + 10)
172 info.append([cid, samples, rate, d[base + 12], []]) 178 info.append([cid, samples, rate, d[base + 12], [], 0])
173 for b in range(blocks): 179 for b in range(blocks):
174 at = d_at + b * chunk 180 at = d_at + b * chunk
175 recs = [struct.unpack_from("<III", d, at + 24 * c + 4)[:2] for c in range(channels)] # (count, skip) 181 recs = [struct.unpack_from("<III", d, at + 24 * c + 4)[:2] for c in range(channels)] # (count, skip)
@@ -179,14 +185,22 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True):
179 for c, (count, skip) in enumerate(recs): 185 for c, (count, skip) in enumerate(recs):
180 start = at + header + before * 2048 186 start = at + header + before * 2048
181 before += count 187 before += count
182 if info[c][3] != 0x0B or count == 0 or not collect_packets: 188 if info[c][3] != 0x0B or count == 0:
189 continue
190 packets = opus_packets(d, start, count * 2048)
191 if packets and info[c][5] == 0:
192 info[c][5] = 2 if any(p[0] & 0x04 for p in packets) else 1
193 if not collect_packets:
183 continue 194 continue
184 for pk in opus_packets(d, start, count * 2048): 195 for pk in packets:
185 n = opus_samples(pk) 196 n = opus_samples(pk)
186 if skip >= n and skip > 0: 197 if skip >= n and skip > 0:
187 skip -= n 198 skip -= n
188 continue 199 continue
189 info[c][4].append(pk) 200 info[c][4].append(pk)
201 for x in info:
202 if x[3] == 0x0B and x[5] > 1:
203 x[1] //= x[5]
190 return [tuple(x) for x in info] 204 return [tuple(x) for x in info]
191 205
192 206
@@ -213,10 +227,10 @@ def export_bank(path: str, out_dir: str):
213 counts = {"opus": 0, "pcm": 0, "other": 0, "music": 0} 227 counts = {"opus": 0, "pcm": 0, "other": 0, "music": 0}
214 streams, music = parse_awc(d) 228 streams, music = parse_awc(d)
215 for mus, data in music: 229 for mus, data in music:
216 for cid, samples, rate, codec, pk in music_channels(d, mus, data): 230 for cid, samples, rate, codec, pk, packet_channels in music_channels(d, mus, data):
217 if pk: 231 if pk:
218 n48 = samples * 48000 // rate if rate else 0 232 n48 = samples * 48000 // rate if rate else 0
219 write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, 1, cid, n48) 233 write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, packet_channels, cid, n48)
220 counts["music"] += 1 234 counts["music"] += 1
221 for s in streams: 235 for s in streams:
222 at, size = s["data"] 236 at, size = s["data"]
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
new file mode 100644
index 000000000..0b71fe41e
--- /dev/null
+++ b/tools/gamedata_xml.py
@@ -0,0 +1,568 @@
1"""Catalog the XML documents recovered from a carved RPF9 archive.
2
3RPF9 stores a logical XML document as one or more zlib streams. A carve from ``rpf9_carve.py`` has an
4``index.json`` plus one inflated ``<offset>.bin`` per stream, so ``gamedata_index.py`` can group the streams
5back into payloads. This tool parses those payloads and writes an aggregate catalog:
6
7 python -I gamedata_xml.py <carve_dir> [--csv FILE] [--json FILE] [--check]
8 python -I gamedata_xml.py <file.xml> [<file.xml> ...] [--csv FILE] [--json FILE] [--check]
9
10For every file it records the root element, element count, maximum depth, attribute names, ``$(name)`` and
11``platform:/`` references, and include-like structures. For every root it records the file count, category,
12element-name histogram, attribute histogram and reference targets. ``--check`` validates well-formedness and
13separates rootless fragments, tail-only documents and malformed documents.
14
15Only schema names, element/attribute names and reference tokens are written. Element text, attribute values,
16``type``/``content`` values and entry paths are not. For a carve directory a row is identified by offset; an
17individual file is identified by the basename that was passed. The output is a local work product: it must not
18be committed or attached to an issue. The test fixtures are synthetic and contain no game data.
19"""
20import argparse
21import csv
22import io
23import json
24import os
25import re
26import statistics
27import sys
28import xml.etree.ElementTree as ET
29from collections import Counter, defaultdict
30
31ROOT = os.path.dirname(os.path.abspath(__file__))
32if ROOT not in sys.path:
33 sys.path.insert(0, ROOT)
34import gamedata_index as gi # noqa: E402
35
36BOM = b"\xef\xbb\xbf"
37MACRO_REF = re.compile(r"\$\(([A-Za-z_][\w.-]*)\)")
38PLATFORM_REF = re.compile(r"platform:/([A-Za-z0-9_.-]+)?")
39XI_INCLUDE = "{http://www.w3.org/2001/XInclude}include"
40INCLUDE_ELEMENTS = ("fileList", "filename", "includedSets", "includedChangesets",
41 "changesetIncludeFlags", "loadPath")
42
43# Category names and root membership follow the functional table in docs/gamedata.md. A category is a
44# dispatch hint: the same root always belongs to one bucket, but a bucket is not a complete schema. Where a
45# document straddles two labels, the table's bucket is kept so the file and root counts line up.
46CATEGORY_ROOTS = {
47 "time, weather, sky, water": """
48 timecycle_modifier_data timecycle_keyframe_data CContentsOfWeatherXmlFile STS_Config CustomClouds
49 CScatteringTransmittance__FogVolumeListData FogVolumeProfileList OceanSimPresets
50 OceanWaveCalmingCurves EnvironmentalWaterDisturbManager ShoreWavePlacementData time_data
51 RegionTintMap
52 """,
53 "vehicles, tyres, handling data": """
54 CVehiclePoints CVehicleBoneOffsetsArray CVehiclePerformanceMaps CVehicleBaseRatingsAndEstimatesMap
55 CVehicleComponentSetManager CVehicleDistantLightData CVehiclePointsMeta CTyreDataSet CParkingSplines
56 CSnowTrackData CBreakableVehicleDoorLockManagerData CPaletteIndexedRecipeTintsArray
57 """,
58 "peds, schedules, appearance": """
59 CPedAccuracyManager CPedComponentSetManager CPedFormationInfoManager CPedHeadbobSettingsManager
60 CPedInventoryLoadOutManager CPedMoodConditionTreesManager CPedMoodSettingsManager
61 CPedMotivationInfoManager CPedScheduleInfoManager CPedSpeedDataBlock CPedTimeWarpSettingsManager
62 CPedVariationBodyTypeManager CPairedPedDataBlock CEnergyConfigInfos CIdlePreferenceManager
63 CUpperBodyIdleConditionManager CUpperBodyIdleSettingsManager CHeadbobConditionManager
64 CHealthConfigInfo sPedDamageModifiers sPedDistractionModifiers WalkAndTalkProfileData
65 STPedMotionPredictionSetContainer STPedNavigationPredictiontPresetContainer CBaitingInfo
66 CAnimalAnimationContexts CAnimalAttackBehaviours Relationships__GroupsData CMoodConditionManager
67 """,
68 "tuning, parameters, effects": """
69 CTuningFile CCoverProcessorTuning GridAtlasInfo PatchConstants CClimbTuneMgr CoverShadowTunables
70 LostTargetSearch__Tunables sCollisionEventScannerTuning hrsSimTuneMgr rage__fragTuneStruct
71 DiffractionProfiles GlintsProfiles LightAnimationPresets CGraphicsDefinitionsData
72 """,
73 "mount / content manifests": """
74 CDataFileMgr__ContentChangeSetDef CDataFileMgr__ContentDef
75 """,
76 "world, navigation, map": """
77 GameShape__Data__LocationNameLoopkup PathingStyleData CTrainConfigs CHazardNodes
78 MapState__Data__Templates aiNavIMapGroupData CLadderMetadataManager CLadderRailsMetadataManager
79 CDoorInteractionDataList CEntityComponentLodManagerData CGarageInitDataList
80 CSceneTerrainAnalyzerMgrDataInstance CScenicViewManager MaterialDataList TextureGridInfo
81 Sprinklers__RootData CProceduralInfo CFluidVesselManager CObjectComponentSetManager
82 """,
83 "combat and AI behaviour": """
84 CCombatInfoMgr CFiringPatternInfoManager CFleeDecisionMakerData Combat__GoalData__Store
85 CSearchPointOfInterestRuleSet CTacticalAnalysisDistributionStore
86 Modular__SM__AIBehaviour__LockControllerConfig Witnesses__Informations CTaskDataInfoManager
87 CDrivingStyleCollection CLassoDataManager CAimUpperBodyDataBlock SSetupData
88 """,
89 "animation, poses, weapons": """
90 WeaponAnimations__FullbodyControllerData WeaponAnimations__ConfigData CStandardPosesManager
91 CAnimSceneAttachSlotSetManager StudioConfigurationData rage__fwRetargetCoordinatorConfig
92 """,
93 "damage": "CDamageDataManager",
94 "audio, video, speech": """
95 LandingPageVideos CTVPlaylistContainer naSpeechEventTypeBatchRequestParams rage__MediaDecoderSettings
96 """,
97 "missions, scenarios, respawn": "CDynamicScenarioManager CMissions Respawn__MetaData",
98 "conversation": "CConversationList CConversationDictionary",
99}
100CATEGORY_BY_ROOT = {}
101for _category, _roots in CATEGORY_ROOTS.items():
102 for _root in _roots.split():
103 CATEGORY_BY_ROOT[_root] = _category
104UNCATALOGUED = "uncatalogued"
105
106
107def category_for(root: str) -> str:
108 return CATEGORY_BY_ROOT.get(root, UNCATALOGUED)
109
110
111def scan_refs(text: str, report: dict) -> None:
112 """Count symbolic macros and platform prefixes in one text or attribute value."""
113 if not text:
114 return
115 if "$(" in text:
116 for match in MACRO_REF.finditer(text):
117 report["refs"]["$(" + match.group(1) + ")"] += 1
118 if "platform:/" in text:
119 for match in PLATFORM_REF.finditer(text):
120 # Keep the bucket coarse: the first segment after a platform prefix can be a directory or a
121 # file-like archive name, and only levels/other is needed to route a mount.
122 report["platform"]["levels" if (match.group(1) or "").lower() == "levels" else "other"] += 1
123 report["platform_total"] += 1
124
125
126def scan_xml(data: bytes) -> dict:
127 """Parse one document and return aggregate facts. Never keeps element text or values."""
128 report = {
129 "root": "",
130 "well_formed": False,
131 "error": "",
132 "element_count": 0,
133 "max_depth": 0,
134 "attributes": [],
135 "comments": data.count(b"<!--"),
136 "elements": Counter(),
137 "attrs": Counter(),
138 "refs": Counter(),
139 "platform": Counter(),
140 "platform_total": 0,
141 "filename": 0,
142 "parent_path": 0,
143 "parent_file": 0,
144 "xi_include": 0,
145 "type_attrs": 0,
146 "type_values": set(),
147 "content_values": set(),
148 }
149 depth = 0
150 try:
151 parser = ET.iterparse(io.BytesIO(data), events=("start", "end"))
152 for event, elem in parser:
153 if event == "start":
154 depth += 1
155 report["max_depth"] = max(report["max_depth"], depth)
156 if not report["root"]:
157 report["root"] = elem.tag
158 report["element_count"] += 1
159 report["elements"][elem.tag] += 1
160 for name, value in elem.attrib.items():
161 report["attrs"][name] += 1
162 if name == "type":
163 report["type_attrs"] += 1
164 report["type_values"].add(value)
165 elif name == "content":
166 report["content_values"].add(value)
167 elif name == "parentPath":
168 report["parent_path"] += 1
169 elif name == "parentFile":
170 report["parent_file"] += 1
171 scan_refs(value, report)
172 if elem.tag == "filename":
173 report["filename"] += 1
174 if elem.tag == XI_INCLUDE or elem.tag == "xi:include":
175 report["xi_include"] += 1
176 else:
177 scan_refs(elem.text, report)
178 scan_refs(elem.tail, report)
179 depth -= 1
180 elem.clear()
181 report["well_formed"] = True
182 except ET.ParseError as exc:
183 # ET errors carry a line/column and a short reason, never the element content.
184 report["error"] = str(exc)
185 report["attributes"] = sorted(report["attrs"])
186 return report
187
188
189def looks_truncated(data: bytes, root: str) -> bool:
190 """True when the bytes start inside a document instead of at its root element."""
191 if not root:
192 return False
193 body = data[3:] if data.startswith(BOM) else data
194 body = body.lstrip(b" \t\r\n")
195 if body.startswith(b"<?xml"):
196 return False
197 return gi.xml_root(data) != root
198
199
200def file_row(doc: dict, scan: dict) -> dict:
201 # A truncated tail can begin with an inner element, so the index's closing-root hint wins.
202 root = doc.get("root_hint") or scan["root"]
203 header = doc.get("header")
204 if header is None:
205 header = gi.has_xml_decl(doc["data"])
206 if doc.get("from_carve"):
207 tail_only = not header
208 fragment = not root or not doc.get("complete", True)
209 else:
210 tail_only = not scan["well_formed"] and looks_truncated(doc["data"], root)
211 fragment = not root
212 malformed = not scan["well_formed"] and not tail_only and not fragment
213 row = {
214 "source": doc.get("name", ""),
215 "offset": doc.get("offset"),
216 "offset_hex": doc.get("offset_hex", ""),
217 "bytes": len(doc["data"]),
218 "chunks": doc.get("chunks", 1),
219 "root": root,
220 "category": category_for(root) if root else UNCATALOGUED,
221 "header": bool(header),
222 "complete": doc.get("complete", scan["well_formed"]),
223 "well_formed": scan["well_formed"],
224 "fragment": fragment,
225 "tail_only": tail_only and not fragment,
226 "truncated": tail_only and not fragment and not scan["well_formed"],
227 "malformed": malformed,
228 "error": scan["error"],
229 "element_count": scan["element_count"] if scan["well_formed"] else None,
230 "max_depth": scan["max_depth"] if scan["well_formed"] else None,
231 "comments": scan["comments"],
232 "attributes": scan["attributes"],
233 "refs": dict(sorted(scan["refs"].items())),
234 "platform": dict(sorted(scan["platform"].items())),
235 "platform_total": scan["platform_total"],
236 "filename": scan["filename"],
237 "parent_path": scan["parent_path"],
238 "parent_file": scan["parent_file"],
239 "xi_include": scan["xi_include"],
240 "type_attrs": scan["type_attrs"],
241 "type_values": len(scan["type_values"]),
242 "content_values": len(scan["content_values"]),
243 }
244 row["_scan"] = scan
245 return row
246
247
248def new_root_stats(root: str) -> dict:
249 return {
250 "root": root,
251 "category": category_for(root) if root else UNCATALOGUED,
252 "files": 0,
253 "well_formed": 0,
254 "fragments": 0,
255 "tail_only": 0,
256 "truncated": 0,
257 "malformed": 0,
258 "bytes": 0,
259 "elements": 0,
260 "max_depth": 0,
261 "element_names": Counter(),
262 "attributes": Counter(),
263 "refs": Counter(),
264 "platform": Counter(),
265 "platform_total": 0,
266 "filename": 0,
267 "parent_path": 0,
268 "parent_file": 0,
269 "xi_include": 0,
270 "type_attrs": 0,
271 "type_values": set(),
272 "content_values": set(),
273 }
274
275
276def aggregate(rows: list) -> dict:
277 roots = {}
278 for row in rows:
279 stats = roots.setdefault(row["root"], new_root_stats(row["root"]))
280 stats["files"] += 1
281 stats["bytes"] += row["bytes"]
282 stats["fragments"] += int(row["fragment"])
283 stats["tail_only"] += int(row["tail_only"])
284 stats["truncated"] += int(row["truncated"])
285 stats["malformed"] += int(row["malformed"])
286 if not row["well_formed"]:
287 continue
288 scan = row["_scan"]
289 stats["well_formed"] += 1
290 stats["elements"] += scan["element_count"]
291 stats["max_depth"] = max(stats["max_depth"], scan["max_depth"])
292 stats["element_names"].update(scan["elements"])
293 stats["attributes"].update(scan["attrs"])
294 stats["refs"].update(scan["refs"])
295 stats["platform"].update(scan["platform"])
296 stats["platform_total"] += scan["platform_total"]
297 stats["filename"] += scan["filename"]
298 stats["parent_path"] += scan["parent_path"]
299 stats["parent_file"] += scan["parent_file"]
300 stats["xi_include"] += scan["xi_include"]
301 stats["type_attrs"] += scan["type_attrs"]
302 stats["type_values"].update(scan["type_values"])
303 stats["content_values"].update(scan["content_values"])
304
305 total_elements = Counter()
306 total_attributes = Counter()
307 total_refs = Counter()
308 total_platform = Counter()
309 all_type_values = set()
310 all_content_values = set()
311 by_category = defaultdict(lambda: {"files": 0, "roots": 0, "elements": 0, "bytes": 0})
312 for root, stats in roots.items():
313 total_elements.update(stats["element_names"])
314 total_attributes.update(stats["attributes"])
315 total_refs.update(stats["refs"])
316 total_platform.update(stats["platform"])
317 all_type_values.update(stats["type_values"])
318 all_content_values.update(stats["content_values"])
319 cat = by_category[stats["category"]]
320 cat["files"] += stats["files"]
321 cat["roots"] += 1
322 cat["elements"] += stats["elements"]
323 cat["bytes"] += stats["bytes"]
324
325 for stats in roots.values():
326 stats["element_names"] = dict(sorted(stats["element_names"].items(), key=lambda kv: (-kv[1], kv[0])))
327 stats["attributes"] = dict(sorted(stats["attributes"].items(), key=lambda kv: (-kv[1], kv[0])))
328 stats["refs"] = dict(sorted(stats["refs"].items()))
329 stats["platform"] = dict(sorted(stats["platform"].items()))
330 stats["type_values"] = len(stats["type_values"])
331 stats["content_values"] = len(stats["content_values"])
332
333 ordered_roots = dict(sorted(roots.items(), key=lambda kv: (-kv[1]["files"], kv[0])))
334 return {
335 "roots": ordered_roots,
336 "elements": total_elements,
337 "attributes": total_attributes,
338 "refs": total_refs,
339 "platform": total_platform,
340 "type_values": len(all_type_values),
341 "content_kinds": len(all_content_values),
342 "categories": dict(sorted(by_category.items())),
343 }
344
345
346def summarize(rows: list, agg: dict, mode: str) -> dict:
347 sizes = sorted(row["bytes"] for row in rows)
348 header_sizes = sorted(row["bytes"] for row in rows if row["header"])
349 return {
350 "mode": mode,
351 "documents": len(rows),
352 "well_formed": sum(1 for row in rows if row["well_formed"]),
353 "fragments": sum(1 for row in rows if row["fragment"]),
354 "tail_only": sum(1 for row in rows if row["tail_only"]),
355 "truncated": sum(1 for row in rows if row["truncated"]),
356 "malformed": sum(1 for row in rows if row["malformed"]),
357 "root_count": sum(1 for root in agg["roots"] if root),
358 "unattributed": int("" in agg["roots"]),
359 "catalog_roots": sum(1 for root in agg["roots"] if root in CATEGORY_BY_ROOT),
360 "elements": sum(agg["elements"].values()),
361 "element_names": len(agg["elements"]),
362 "attributes": len(agg["attributes"]),
363 "max_depth": max((stats["max_depth"] for stats in agg["roots"].values()), default=0),
364 "comments": sum(row["comments"] for row in rows),
365 "comments_header": sum(row["comments"] for row in rows if row["header"]),
366 "header_documents": len(header_sizes),
367 "type_values": agg["type_values"],
368 "content_kinds": agg["content_kinds"],
369 "bytes": sum(sizes),
370 "min_bytes": sizes[0] if sizes else 0,
371 "median_bytes": int(statistics.median(sizes)) if sizes else 0,
372 "max_bytes": sizes[-1] if sizes else 0,
373 "header_bytes": {
374 "min": header_sizes[0] if header_sizes else 0,
375 "median": int(statistics.median(header_sizes)) if header_sizes else 0,
376 "max": header_sizes[-1] if header_sizes else 0,
377 },
378 "references": dict(sorted(agg["refs"].items())),
379 "platform": dict(sorted(agg["platform"].items())),
380 "platform_total": sum(agg["platform"].values()),
381 "filename": sum(stats["filename"] for stats in agg["roots"].values()),
382 "parent_path": sum(stats["parent_path"] for stats in agg["roots"].values()),
383 "parent_file": sum(stats["parent_file"] for stats in agg["roots"].values()),
384 "xi_include": sum(stats["xi_include"] for stats in agg["roots"].values()),
385 "include_like": {name: agg["elements"].get(name, 0) for name in INCLUDE_ELEMENTS},
386 "categories": agg["categories"],
387 "catalog": {
388 "roots": len(CATEGORY_BY_ROOT),
389 "categories": len(CATEGORY_ROOTS),
390 },
391 }
392
393
394def carve_documents(directory: str):
395 """Yield the XML payloads of an rpf9_carve.py directory, rebuilt by gamedata_index."""
396 source = gi.DirectorySource(directory)
397 rows = gi.build_rows(source.rows, source)
398 by_offset = {row["off"]: index for index, row in enumerate(source.rows)}
399 for row in rows:
400 if row["type"] != "xml":
401 continue
402 start = by_offset[row["offset"]]
403 data = b"".join(source.read(source.rows[index]) for index in range(start, start + row["chunks"]))
404 yield {
405 "data": data,
406 "from_carve": True,
407 "offset": row["offset"],
408 "offset_hex": row["offset_hex"],
409 "chunks": row["chunks"],
410 "header": row["header"],
411 "complete": row["complete"],
412 "root_hint": row["root"],
413 }
414
415
416def xml_files(directory: str):
417 for base, _, names in os.walk(directory):
418 for name in sorted(names):
419 if name.lower().endswith(".xml"):
420 yield os.path.join(base, name)
421
422
423def document_mode(targets: list) -> str:
424 for target in targets:
425 if os.path.isdir(target) and os.path.isfile(os.path.join(target, "index.json")):
426 return "carve"
427 return "files"
428
429
430def load_documents(targets: list):
431 """Yield one document per XML payload. Directories with index.json use the carve path."""
432 for target in targets:
433 if os.path.isdir(target):
434 if os.path.isfile(os.path.join(target, "index.json")):
435 for doc in carve_documents(target):
436 yield doc
437 else:
438 for path in xml_files(target):
439 yield file_document(path)
440 elif os.path.isfile(target):
441 yield file_document(target)
442 else:
443 raise FileNotFoundError(target)
444
445
446def file_document(path: str) -> dict:
447 with open(path, "rb") as f:
448 data = f.read()
449 root = gi.tail_root(data) or gi.xml_root(data)
450 return {
451 "data": data,
452 "from_carve": False,
453 "name": os.path.basename(path),
454 "root_hint": root,
455 }
456
457
458def write_csv(path: str, rows: list) -> None:
459 fields = ["source", "offset_hex", "bytes", "chunks", "root", "category", "header", "complete",
460 "well_formed", "fragment", "tail_only", "truncated", "malformed", "element_count",
461 "max_depth", "comments", "attributes", "refs", "platform", "platform_total", "filename",
462 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values",
463 "error"]
464 with open(path, "w", newline="", encoding="utf-8") as f:
465 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
466 writer.writeheader()
467 for row in rows:
468 out = dict(row)
469 out["attributes"] = " ".join(row["attributes"])
470 out["refs"] = ";".join(f"{key}={value}" for key, value in row["refs"].items())
471 out["platform"] = ";".join(f"{key}={value}" for key, value in row["platform"].items())
472 for flag in ("header", "complete", "well_formed", "fragment", "tail_only", "truncated",
473 "malformed"):
474 out[flag] = str(row[flag]).lower()
475 writer.writerow(out)
476
477
478def plural(count: int, word: str) -> str:
479 return f"{count} {word}" if count == 1 else f"{count} {word}s"
480
481
482def check_report(rows: list) -> bool:
483 """Print the validation split. Return True when no complete document is malformed."""
484 fragments = sum(1 for row in rows if row["fragment"])
485 print(f"check: {sum(1 for row in rows if row['well_formed'])} well-formed, "
486 f"{sum(1 for row in rows if row['truncated'])} truncated at the start, "
487 f"{plural(fragments, 'rootless fragment')}, "
488 f"{sum(1 for row in rows if row['malformed'])} malformed")
489 for row in rows:
490 if not (row["truncated"] or row["fragment"] or row["malformed"]):
491 continue
492 where = row["offset_hex"] or row["source"] or "?"
493 if row["malformed"]:
494 print(f" malformed {row['root'] or '?'} @ {where}: {row['error']}")
495 elif row["truncated"]:
496 print(f" truncated {row['root']} @ {where}: starts mid-document")
497 else:
498 print(f" fragment @ {where}: no root element")
499 return not any(row["malformed"] for row in rows)
500
501
502def print_summary(summary: dict, agg: dict) -> None:
503 docs = summary["documents"]
504 print(f'{docs} XML payloads, {summary["bytes"]:,} bytes '
505 f'(min {summary["min_bytes"]:,}, median {summary["median_bytes"]:,}, '
506 f'max {summary["max_bytes"]:,})')
507 print(f'{summary["well_formed"]} well-formed, {summary["tail_only"]} tail-only '
508 f'({summary["truncated"]} truncated), {plural(summary["fragments"], "rootless fragment")}, '
509 f'{summary["malformed"]} malformed')
510 print(f'{summary["root_count"]} named roots (+{summary["unattributed"]} unattributed), '
511 f'{summary["elements"]:,} elements, {summary["element_names"]:,} element names, '
512 f'{summary["attributes"]} attributes, max depth {summary["max_depth"]}, '
513 f'{summary["type_values"]} type values, {summary["content_kinds"]} content kinds')
514 print(f'{summary["comments"]} comment starts '
515 f'({summary["comments_header"]} in {summary["header_documents"]} declaration-bearing documents)')
516 refs = ", ".join(f"{key} {value:,}" for key, value in summary["references"].items())
517 platforms = ", ".join(f"{key} {value:,}" for key, value in summary["platform"].items())
518 print(f"references: {summary['platform_total']:,} platform:/ ({platforms}); {refs}")
519 print(f'include-like: {summary["filename"]:,} filename, {summary["parent_path"]} parentPath, '
520 f'{summary["parent_file"]} parentFile, {summary["xi_include"]} xi:include')
521 print("categories:")
522 for name, stats in summary["categories"].items():
523 print(f' {plural(stats["files"], "file"):8} {plural(stats["roots"], "root"):8} '
524 f'{stats["elements"]:7,} elements {name}')
525 print("roots:")
526 for root, stats in list(agg["roots"].items())[:10]:
527 if not root:
528 continue
529 print(f' {plural(stats["files"], "file"):8} {stats["elements"]:7,} elements '
530 f'{root} [{stats["category"]}]')
531
532
533def main() -> int:
534 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
535 parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)")
536 parser.add_argument("--csv", help="write one row per XML document to this CSV")
537 parser.add_argument("--json", help="write the summary, per-root catalog and rows to this JSON")
538 parser.add_argument("--check", action="store_true", help="validate well-formedness and report fragments")
539 args = parser.parse_args()
540
541 rows = []
542 mode = document_mode(args.targets)
543 try:
544 for doc in load_documents(args.targets):
545 rows.append(file_row(doc, scan_xml(doc["data"])))
546 except FileNotFoundError as exc:
547 print(f"not found: {exc}", file=sys.stderr)
548 return 2
549
550 agg = aggregate(rows)
551 summary = summarize(rows, agg, mode)
552 clean = True
553 if args.check:
554 clean = check_report(rows)
555 print_summary(summary, agg)
556 if args.csv:
557 write_csv(args.csv, rows)
558 print("wrote", args.csv)
559 if args.json:
560 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows]
561 with open(args.json, "w", encoding="utf-8") as f:
562 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1)
563 print("wrote", args.json)
564 return 0 if clean else 1
565
566
567if __name__ == "__main__":
568 sys.exit(main())
diff --git a/tools/manifest.py b/tools/manifest.py
index ec8fa7427..4dd175278 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -49,7 +49,11 @@ def sha256(path: str) -> str:
49 49
50 50
51def walk(game_dir: str): 51def walk(game_dir: str):
52 for root, _, files in os.walk(game_dir): 52 def scan_failed(error: OSError) -> None:
53 raise error
54
55 # os.walk otherwise treats missing or unreadable directories as empty.
56 for root, _, files in os.walk(game_dir, onerror=scan_failed):
53 for name in sorted(files): 57 for name in sorted(files):
54 p = os.path.join(root, name) 58 p = os.path.join(root, name)
55 yield os.path.relpath(p, game_dir).replace("\\", "/"), p 59 yield os.path.relpath(p, game_dir).replace("\\", "/"), p
@@ -150,8 +154,13 @@ def main() -> int:
150 add_jobs(v) 154 add_jobs(v)
151 a = ap.parse_args() 155 a = ap.parse_args()
152 below_normal() 156 below_normal()
153 return (create(a.game_dir, a.out, a.jobs) if a.cmd == "create" 157 try:
154 else verify(a.game_dir, a.manifest, a.jobs)) 158 if a.cmd == "create":
159 return create(a.game_dir, a.out, a.jobs)
160 return verify(a.game_dir, a.manifest, a.jobs)
161 except OSError as error:
162 print(f"ERROR: {error}", file=sys.stderr)
163 return 2
155 164
156 165
157if __name__ == "__main__": 166if __name__ == "__main__":
diff --git a/tools/mc_command.py b/tools/mc_command.py
new file mode 100644
index 000000000..9f76e03b4
--- /dev/null
+++ b/tools/mc_command.py
@@ -0,0 +1,29 @@
1"""Resolve LLVM_MC to an argv list.
2
3LLVM_MC may be one executable (a path, spaces and all) or a whole command line. Windows needs the command-line
4form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU target:
5
6 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc
7"""
8import os
9import shlex
10
11
12def split_command(raw: str) -> list:
13 """Split a command line without eating the backslashes of a Windows path (POSIX shlex would)."""
14 raw = raw.strip()
15 if not raw:
16 return []
17 if os.path.isfile(raw):
18 return [raw] # a plain path, spaces and all
19 if os.name != "nt":
20 return shlex.split(raw)
21 parts = shlex.split(raw, posix=False)
22 return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts]
23
24
25def mc_command(raw: str | None = None) -> list:
26 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'."""
27 if raw is None:
28 raw = os.environ.get("LLVM_MC", "llvm-mc")
29 return split_command(raw) or ["llvm-mc"]
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
new file mode 100644
index 000000000..bea6534f7
--- /dev/null
+++ b/tools/rbf0_tree.py
@@ -0,0 +1,554 @@
1"""Decode RBF0 resources into strict JSON trees, with an optional simple XML rendering.
2
3RBF0 is RAGE's binary form of an XML data file: one record stream with an inline descriptor table. This tool reads
4inflated RBF0 resources from a carve directory or a single resource file, joins the 64 KiB continuation streams of
5one logical resource, and builds the element tree. It reports unknown descriptors, unknown record types, truncated
6payloads and structural violations as errors instead of guessing a value.
7
8The output contains names and payloads taken from the archive, so treat it as game data: keep it out of git and do
9not attach it to an issue or a pull request. Format facts and aggregate counts are in docs/rbf0.md.
10
11Usage:
12 python -I tools/rbf0_tree.py <carve-dir> <out.json> [--xml DIR] [--root NAME]... [--offset 0x...] [--limit N]
13
14The input directory holds inflated zlib streams or complete RBF0 resources. A file name that starts with a
15hexadecimal archive offset is used to order and label the resource, as in the rbf0_index.py carve layout.
16"""
17import argparse
18import collections
19import json
20import math
21import os
22import re
23import struct
24import sys
25from xml.etree import ElementTree as ET
26
27sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
28
29import rbf0_index # noqa: E402
30
31MAGIC = rbf0_index.MAGIC
32PROLOGUE = rbf0_index.PROLOGUE
33MAX_CHUNK = rbf0_index.MAX_CHUNK
34MAX_CHUNKS = rbf0_index.MAX_CHUNKS
35MAX_BYTES = rbf0_index.MAX_BYTES
36RbfError = rbf0_index.RbfError
37TYPE_NAMES = {0x00: "open", 0x10: "int", 0x20: "true", 0x30: "false", 0x40: "float",
38 0x50: "vec3", 0x60: "string"}
39VALUE_TYPES = {0x10: "int", 0x20: "bool", 0x30: "bool", 0x40: "float", 0x50: "vec3", 0x60: "string"}
40XML_BAD = re.compile(r"[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]")
41
42
43def _utf8(raw):
44 """Return (text, valid). Invalid bytes become U+FFFD and are counted, never silently accepted."""
45 try:
46 return raw.decode("utf-8"), True
47 except UnicodeDecodeError:
48 return raw.decode("utf-8", "replace"), False
49
50
51def _render(value):
52 """A stable textual form for XML and for JSON consumers that want one scalar spelling."""
53 if isinstance(value, bool):
54 return "true" if value else "false"
55 if isinstance(value, float):
56 if math.isnan(value):
57 return "nan"
58 if math.isinf(value):
59 return "inf" if value > 0 else "-inf"
60 return repr(value)
61 if isinstance(value, (list, tuple)):
62 return "[" + ", ".join(_render(v) for v in value) + "]"
63 return str(value)
64
65
66class TreeError(RbfError):
67 """A malformed or truncated RBF0 record stream."""
68
69
70class Parser:
71 """One RBF0 resource. `parse()` always returns a document, with a partial tree on failure."""
72
73 def __init__(self, data, source="", offset=0, chunks=1):
74 self.data = data
75 self.source = source
76 self.offset = offset
77 self.chunks = chunks
78 self.wide = data[4:8] == PROLOGUE
79 self.p = 8 if self.wide else 4
80 self.scalar = 8 if self.wide else 4
81 self.descs = []
82 self.stack = []
83 self.root = None
84 self.status = "ok"
85 self.error = ""
86 self.error_offset = None
87 self.counts = collections.Counter()
88 self.descriptor_names = set()
89 self.attribute_mismatches = 0
90 self.attribute_order_violations = 0
91 self.text_after_child = 0
92 self.text_before_child = 0
93 self.value_after_child = 0
94 self.invalid_utf8 = 0
95 self.max_depth = 0
96
97 def take(self, n, what):
98 if self.p + n > len(self.data):
99 raise TreeError(f"{what} truncated", self.p, truncated=True)
100 start = self.p
101 self.p += n
102 return self.data[start:self.p]
103
104 def _descriptor(self, index, kind, at):
105 if index == len(self.descs):
106 n = struct.unpack("<H", self.take(2, "descriptor name length"))[0]
107 raw = self.take(n, "descriptor name")
108 name, valid = _utf8(raw)
109 if not valid:
110 self.invalid_utf8 += 1
111 self.descs.append({
112 "index": index,
113 "name": name,
114 "first_type": TYPE_NAMES.get(kind, f"0x{kind:02x}"),
115 "offset": at,
116 "name_offset": self.p - n,
117 "uses": 0,
118 "types": {},
119 "utf8_valid": valid,
120 })
121 self.descriptor_names.add(name)
122 elif index > len(self.descs):
123 raise TreeError(f"descriptor index {index} of {len(self.descs)}", at)
124 desc = self.descs[index]
125 desc["uses"] += 1
126 key = TYPE_NAMES.get(kind, f"0x{kind:02x}")
127 desc["types"][key] = desc["types"].get(key, 0) + 1
128 return desc
129
130 def _attach(self, frame, node):
131 node["depth"] = frame["depth"] + 1
132 if frame["node"]["kind"] != "element":
133 raise TreeError("record outside an element", node["offset"])
134 if node["kind"] == "value" and frame["attrs_seen"] < frame["attrs_declared"]:
135 if frame["content_started"]:
136 frame["node"]["attribute_order_violation"] = True
137 self.attribute_order_violations += 1
138 frame["node"]["attributes"].append(node)
139 frame["attrs_seen"] += 1
140 return
141 if node["kind"] in ("element", "text") and frame["attrs_seen"] < frame["attrs_declared"]:
142 frame["node"]["attribute_order_violation"] = True
143 self.attribute_order_violations += 1
144 frame["content_started"] = True
145 frame["node"]["content"].append(node)
146 if node["kind"] == "element":
147 if frame["text_seen"]:
148 frame["node"]["text_before_child"] = True
149 self.text_before_child += 1
150 frame["child_seen"] = True
151 elif node["kind"] == "value":
152 if frame["child_seen"]:
153 frame["node"]["value_after_child"] = True
154 self.value_after_child += 1
155 elif node["kind"] == "text":
156 if frame["child_seen"]:
157 frame["node"]["text_after_child"] = True
158 self.text_after_child += 1
159 if frame["text_seen"]:
160 frame["node"]["multiple_text"] = True
161 frame["text_seen"] = True
162
163 def parse(self):
164 data = self.data
165 if len(data) < 4 or data[:4] != MAGIC:
166 raise TreeError("not an RBF0 stream", 0)
167 try:
168 while self.p < len(data):
169 self.record_offset = self.p
170 at = self.p
171 index = self.take(1, "record index")[0]
172 kind = self.take(1, "record type")[0]
173 if index == 0xFF:
174 if kind != 0xFF:
175 raise TreeError("close tag is not FF FF", at)
176 if not self.stack:
177 raise TreeError("close without an open element", at)
178 frame = self.stack.pop()
179 frame["node"]["end"] = self.p
180 if frame["attrs_seen"] < frame["attrs_declared"]:
181 frame["node"]["attribute_mismatch"] = True
182 self.attribute_mismatches += 1
183 if not self.stack:
184 self.root = frame["node"]
185 break
186 continue
187 if index == 0xFD:
188 if kind != 0xFF:
189 raise TreeError("text tag is not FD FF", at)
190 n = struct.unpack("<I", self.take(4, "text length"))[0]
191 raw = self.take(n, "text")
192 payload_at = self.p - n
193 body = raw[:-1] if raw.endswith(b"\x00") else raw
194 text, valid = _utf8(body)
195 if not valid:
196 self.invalid_utf8 += 1
197 node = {
198 "kind": "text",
199 "offset": at,
200 "payload_offset": payload_at,
201 "length": n,
202 "nul_terminated": raw.endswith(b"\x00"),
203 "text": text,
204 "utf8_valid": valid,
205 }
206 if not self.stack:
207 raise TreeError("text outside an element", at)
208 self._attach(self.stack[-1], node)
209 self.counts["texts"] += 1
210 continue
211 desc = self._descriptor(index, kind, at)
212 name = desc["name"]
213 if kind == 0x00:
214 raw = self.take(6, "element header")
215 payload_at = self.p - 6
216 word0, word1, attrs = struct.unpack("<HHH", raw)
217 if word0 or word1:
218 raise TreeError(f"element header word is not zero ({word0}, {word1})", at)
219 node = {
220 "kind": "element",
221 "name": name,
222 "descriptor": index,
223 "offset": at,
224 "header_offset": payload_at,
225 "attrs_declared": attrs,
226 "depth": len(self.stack) + 1,
227 "attributes": [],
228 "content": [],
229 "end": None,
230 }
231 self.counts["elements"] += 1
232 self.max_depth = max(self.max_depth, len(self.stack) + 1)
233 if self.stack:
234 self._attach(self.stack[-1], node)
235 else:
236 if self.root is not None:
237 raise TreeError("second root element", at)
238 self.root = node
239 self.stack.append({
240 "node": node,
241 "attrs_declared": attrs,
242 "attrs_seen": 0,
243 "content_started": False,
244 "child_seen": False,
245 "text_seen": False,
246 "depth": len(self.stack) + 1,
247 })
248 continue
249 if kind not in VALUE_TYPES:
250 raise TreeError(f"unknown record type {kind:#04x}", at)
251 node = self._value(kind, name, index, at)
252 if not self.stack:
253 raise TreeError("value outside an element", at)
254 self._attach(self.stack[-1], node)
255 self.counts["values"] += 1
256 except TreeError as exc:
257 if not self.error:
258 self.status = "truncated" if exc.truncated else "bad"
259 self.error = str(exc)
260 self.error_offset = exc.offset
261 if self.status == "ok":
262 if self.stack:
263 self.status = "truncated"
264 self.error = f"{len(self.stack)} unclosed element(s) at 0x{self.p:x}"
265 self.error_offset = self.p
266 elif self.root is None:
267 self.status = "bad"
268 self.error = "no root element"
269 self.error_offset = self.p
270 elif self.root.get("end") != len(data):
271 self.status = "trailing"
272 self.error = f"{len(data) - self.root['end']} bytes after the root closed"
273 self.error_offset = self.root["end"]
274 return {
275 "source": self.source,
276 "offset": self.offset,
277 "size": len(data),
278 "chunks": self.chunks,
279 "layout": "wide-64" if self.wide else "narrow-32",
280 "prologue": PROLOGUE.hex() if self.wide else "",
281 "root_name": self.root["name"] if self.root else "",
282 "status": self.status,
283 "error": self.error,
284 "error_offset": self.error_offset,
285 "end": self.root["end"] if self.root and self.root.get("end") is not None else self.p,
286 "descriptors": self.descs,
287 "descriptor_count": len(self.descs),
288 "distinct_descriptor_names": len(self.descriptor_names),
289 "counts": dict(self.counts),
290 "attribute_mismatches": self.attribute_mismatches,
291 "attribute_order_violations": self.attribute_order_violations,
292 "text_after_child": self.text_after_child,
293 "text_before_child": self.text_before_child,
294 "value_after_child": self.value_after_child,
295 "invalid_utf8": self.invalid_utf8,
296 "max_depth": self.max_depth,
297 "tree": self.root,
298 }
299
300 def _value(self, kind, name, index, at):
301 payload_at = self.p
302 extra = {}
303 if kind == 0x10:
304 raw = self.take(self.scalar, "integer")
305 value = struct.unpack("<Q" if self.wide else "<I", raw)[0]
306 self.counts["ints"] += 1
307 elif kind == 0x20 or kind == 0x30:
308 value = kind == 0x20
309 self.counts["bools"] += 1
310 elif kind == 0x40:
311 raw = self.take(self.scalar, "float")
312 value = struct.unpack("<d" if self.wide else "<f", raw)[0]
313 self.counts["floats"] += 1
314 elif kind == 0x50:
315 raw = self.take(3 * self.scalar, "vector")
316 value = list(struct.unpack("<ddd" if self.wide else "<fff", raw))
317 if any(not math.isfinite(v) for v in value):
318 extra["float_special"] = [_render(v) for v in value]
319 value = [v if math.isfinite(v) else None for v in value]
320 self.counts["vec3"] += 1
321 else: # 0x60
322 n = struct.unpack("<H", self.take(2, "string length"))[0]
323 raw = self.take(n, "string")
324 payload_at = self.p - n
325 body = raw[:-1] if raw.endswith(b"\x00") else raw
326 value, valid = _utf8(body)
327 if not valid:
328 self.invalid_utf8 += 1
329 extra = {"byte_length": n, "nul_terminated": raw.endswith(b"\x00"), "utf8_valid": valid}
330 self.counts["strings"] += 1
331 if isinstance(value, float) and not math.isfinite(value):
332 extra["float_special"] = _render(value)
333 value = None
334 return {
335 "kind": "value",
336 "name": name,
337 "descriptor": index,
338 "type": VALUE_TYPES[kind],
339 "offset": at,
340 "payload_offset": payload_at,
341 "size": self.p - payload_at,
342 "value": value,
343 **extra,
344 }
345
346
347def parse_resource(data, source="", offset=0, chunks=1):
348 """Parse one complete RBF0 resource into a tree document. A non-RBF0 magic raises; a malformed stream
349 returns a partial document with status bad or truncated."""
350 return Parser(data, source, offset, chunks).parse()
351
352
353def _rows(source):
354 """Return (rows, read) for a single resource or a directory of inflated streams/resources."""
355 if os.path.isdir(source):
356 entries = []
357 unnamed = []
358 for name in sorted(os.listdir(source)):
359 full = os.path.join(source, name)
360 if not os.path.isfile(full):
361 continue
362 with open(full, "rb") as f:
363 head = f.read(8)
364 match = re.match(r"([0-9a-fA-F]{6,})", name)
365 if match:
366 entries.append((int(match.group(1), 16), name, full, head))
367 else:
368 unnamed.append((name, full, head))
369 next_offset = max((e[0] for e in entries), default=-1) + 1
370 for name, full, head in unnamed:
371 entries.append((next_offset, name, full, head))
372 next_offset += 1
373 entries.sort(key=lambda e: e[0])
374 rows = [{"offset": off, "stored": os.path.getsize(full), "size": os.path.getsize(full),
375 "head": head, "name": name} for off, name, full, head in entries]
376 by_offset = {row["offset"]: full for row, (_, _, full, _) in zip(rows, entries)}
377
378 def read(row):
379 with open(by_offset[row["offset"]], "rb") as f:
380 return f.read()
381 return rows, read
382 with open(source, "rb") as f:
383 data = f.read()
384 row = {"offset": 0, "stored": len(data), "size": len(data), "head": data[:8],
385 "name": os.path.basename(source)}
386 return [row], lambda _row: data
387
388
389def decode_source(source, roots=None, offset=None, limit=None, progress=None):
390 """Decode every RBF0 start in `source`, joining 64 KiB continuations. Returns (docs, summary)."""
391 rows, read = _rows(source)
392 starts = [i for i, row in enumerate(rows) if row["head"][:4] == MAGIC]
393 if offset is not None:
394 starts = [i for i in starts if rows[i]["offset"] == offset]
395 if not starts:
396 raise SystemExit(f"no RBF0 resource at offset 0x{offset:x}")
397 wanted = set(roots or ())
398 docs = []
399 for i in starts:
400 blob = read(rows[i])
401 chunks = 1
402 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
403 while (doc["status"] == "truncated" and chunks < MAX_CHUNKS and len(blob) < MAX_BYTES
404 and rows[i + chunks - 1]["size"] == MAX_CHUNK and i + chunks < len(rows)):
405 nxt = rows[i + chunks]
406 if nxt["head"][:4] in (MAGIC, b"PSIN"):
407 break
408 blob += read(nxt)
409 chunks += 1
410 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
411 if doc["status"] != "truncated":
412 break
413 if wanted and doc["root_name"] not in wanted:
414 continue
415 docs.append(doc)
416 if limit is not None and len(docs) >= limit:
417 break
418 if progress:
419 progress(len(docs), len(starts))
420 summary = _summary(docs)
421 summary["source"] = os.path.abspath(source)
422 return docs, summary
423
424
425def _summary(docs):
426 roots = collections.Counter(d["root_name"] for d in docs)
427 layouts = collections.Counter(d["layout"] for d in docs)
428 status = collections.Counter(d["status"] for d in docs)
429 counts = collections.Counter()
430 for d in docs:
431 counts.update(d["counts"])
432 return {
433 "resources": len(docs),
434 "ok": status.get("ok", 0),
435 "bad": status.get("bad", 0),
436 "truncated": status.get("truncated", 0),
437 "trailing": status.get("trailing", 0),
438 "layouts": dict(layouts),
439 "roots": dict(roots),
440 "descriptors": sum(d["descriptor_count"] for d in docs),
441 "distinct_descriptor_names": len({x["name"] for d in docs for x in d["descriptors"]}),
442 "elements": counts.get("elements", 0),
443 "values": counts.get("values", 0),
444 "texts": counts.get("texts", 0),
445 "strings": counts.get("strings", 0),
446 "ints": counts.get("ints", 0),
447 "floats": counts.get("floats", 0),
448 "bools": counts.get("bools", 0),
449 "vec3": counts.get("vec3", 0),
450 "max_depth": max((d["max_depth"] for d in docs), default=0),
451 "attribute_mismatches": sum(d["attribute_mismatches"] for d in docs),
452 "attribute_order_violations": sum(d["attribute_order_violations"] for d in docs),
453 "text_after_child": sum(d["text_after_child"] for d in docs),
454 "value_after_child": sum(d["value_after_child"] for d in docs),
455 "invalid_utf8": sum(d["invalid_utf8"] for d in docs),
456 "status": dict(status),
457 }
458
459
460def _xml_safe(text):
461 return XML_BAD.sub("\ufffd", text)
462
463
464def _xml_node(parent, node, tag=None):
465 if node["kind"] == "element":
466 attrs = {"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
467 "offset": f"0x{node['offset']:x}", "attrs": str(node["attrs_declared"])}
468 if node.get("end") is not None:
469 attrs["end"] = f"0x{node['end']:x}"
470 el = ET.SubElement(parent, "node", attrs)
471 for value in node["attributes"]:
472 _xml_node(el, value, "attr")
473 for child in node["content"]:
474 _xml_node(el, child)
475 return el
476 tag = tag or ("text" if node["kind"] == "text" else "value")
477 attrs = {"offset": f"0x{node['offset']:x}"}
478 if node["kind"] == "value":
479 attrs.update({"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
480 "type": node["type"]})
481 if node.get("float_special") is not None:
482 text = _render(node["float_special"])
483 else:
484 text = _render(node["value"])
485 else:
486 attrs["length"] = str(node["length"])
487 text = node["text"]
488 if node.get("utf8_valid") is False:
489 attrs["utf8"] = "invalid"
490 el = ET.SubElement(parent, tag, attrs)
491 el.text = _xml_safe(text)
492 return el
493
494
495def write_xml(directory, docs):
496 """Write one generic XML file per resource. Element names are fixed, so any descriptor name is safe."""
497 os.makedirs(directory, exist_ok=True)
498 paths = []
499 for i, doc in enumerate(docs):
500 root = ET.Element("rbf0", {
501 "root": _xml_safe(doc["root_name"]), "layout": doc["layout"],
502 "offset": f"0x{doc['offset']:x}",
503 "size": str(doc["size"]), "descriptors": str(doc["descriptor_count"]),
504 "status": doc["status"]})
505 if doc["tree"] is not None:
506 _xml_node(root, doc["tree"])
507 tree = ET.ElementTree(root)
508 ET.indent(tree, space=" ")
509 name = f"{doc['offset']:08x}.xml"
510 path = os.path.join(directory, name)
511 if os.path.exists(path):
512 path = os.path.join(directory, f"{doc['offset']:08x}-{i:04d}.xml")
513 tree.write(path, encoding="utf-8", xml_declaration=True)
514 paths.append(path)
515 return paths
516
517
518def write_json(path, docs, summary):
519 with open(path, "w", encoding="utf-8") as f:
520 json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs},
521 f, indent=1, ensure_ascii=False, allow_nan=False)
522
523
524def main(argv=None):
525 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
526 ap.add_argument("source", help="a carve directory, a complete resource, or a single RBF0 stream")
527 ap.add_argument("out", help="JSON output path")
528 ap.add_argument("--xml", metavar="DIR", help="also write one generic XML file per resource into DIR")
529 ap.add_argument("--root", action="append", metavar="NAME", help="keep only this root schema (repeatable)")
530 ap.add_argument("--offset", type=lambda s: int(s, 0), help="decode only the resource at this archive offset")
531 ap.add_argument("--limit", type=int, help="stop after this many selected resources")
532 ap.add_argument("--quiet", action="store_true")
533 args = ap.parse_args(argv)
534
535 def progress(n, total):
536 if not args.quiet and (n % 100 == 0 or n == total):
537 print(f"[{n}/{total}] resources", flush=True)
538
539 docs, summary = decode_source(args.source, roots=args.root, offset=args.offset,
540 limit=args.limit, progress=progress)
541 write_json(args.out, docs, summary)
542 paths = write_xml(args.xml, docs) if args.xml else []
543 if not args.quiet:
544 print(f"{summary['resources']} resources: {summary['ok']} ok, {summary['bad']} bad, "
545 f"{summary['truncated']} truncated, {summary['trailing']} trailing")
546 print(f"{summary['elements']} elements, {summary['texts']} texts, {summary['strings']} strings, "
547 f"{summary['descriptors']} descriptors -> {args.out}")
548 if paths:
549 print(f"{len(paths)} XML files -> {args.xml}")
550 return 0 if summary["ok"] == summary["resources"] else 1
551
552
553if __name__ == "__main__":
554 sys.exit(main())
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 819eb0aad..5201fa31d 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -3413,7 +3413,14 @@ class Gen:
3413 """s_load_dwordxN sD, s[p:p+1], off -> N dwords at (64-bit pointer + off) 3413 """s_load_dwordxN sD, s[p:p+1], off -> N dwords at (64-bit pointer + off)
3414 s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords at (V# base address + off) 3414 s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords at (V# base address + off)
3415 Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32 3415 Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32
3416 (AMD RDNA ISA, buffer resource descriptor).""" 3416 (AMD RDNA ISA, buffer resource descriptor).
3417 off is an immediate or a scalar register. An SMEM load can carry both, which llvm-mc prints as
3418 "sOFF offset:IMM" (the immediate arrives in mods); the address is then base + sOFF + IMM. Measured on an
3419 RX 6800 (gfx1030) for s_buffer_load_dword/x2/x4/x8: soffset 8 + imm 4 reads +12. s_load_dword* shares the
3420 encoding and gets the same rule (not measured). The immediate is zero-extended from 32 bits exactly as the
3421 immediate-only form is.
3422 Not modelled: for s_buffer_load* the hardware was measured to truncate base, sOFF and IMM each to a multiple
3423 of 4 and to return 0 past num_records (docs/design.md, Scalar/buffer memory)."""
3417 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) 3424 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1])
3418 d, base = a[0], a[1] 3425 d, base = a[0], a[1]
3419 # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...). 3426 # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...).
@@ -3432,6 +3439,15 @@ class Gen:
3432 if base.get("n") != 2: 3439 if base.get("n") != 2:
3433 raise Unsupported("s_load without 64-bit pointer") 3440 raise Unsupported("s_load without 64-bit pointer")
3434 off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} 3441 off = a[2] if len(a) > 2 else {"k": "imm", "v": 0}
3442 inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")]
3443 if len(a) > 3 or len(inst) > 1 or (inst and off["k"] == "imm"):
3444 raise Unsupported(f"{op} offset form") # not something llvm-mc prints: don't guess an address
3445 imm = None
3446 if inst:
3447 try:
3448 imm = int(inst[0], 0)
3449 except ValueError:
3450 raise Unsupported(f"{op} offset:{inst[0]}") from None
3435 offv = self.src_u(off) 3451 offv = self.src_u(off)
3436 l64, h64, sh, addr, o64, full = (self.tmp() for _ in range(6)) 3452 l64, h64, sh, addr, o64, full = (self.tmp() for _ in range(6))
3437 self.emit(f"{l64} = OpUConvert %ulong {lo}") 3453 self.emit(f"{l64} = OpUConvert %ulong {lo}")
@@ -3440,6 +3456,11 @@ class Gen:
3440 self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") 3456 self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}")
3441 self.emit(f"{o64} = OpUConvert %ulong {offv}") 3457 self.emit(f"{o64} = OpUConvert %ulong {offv}")
3442 self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") 3458 self.emit(f"{full} = OpIAdd %ulong {addr} {o64}")
3459 if imm is not None: # register offset and immediate: both are added
3460 i64, both = self.tmp(), self.tmp()
3461 self.emit(f"{i64} = OpUConvert %ulong {self.cu(imm)}")
3462 self.emit(f"{both} = OpIAdd %ulong {full} {i64}")
3463 full = both
3443 ptr = self.tmp() 3464 ptr = self.tmp()
3444 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 3465 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
3445 self.uses_psb = True 3466 self.uses_psb = True
@@ -5648,7 +5669,7 @@ def pos_export_layout(osg1, insns):
5648 - clip distances precede cull distances, packed contiguously into 4-component pos exports (<= 8 total). 5669 - clip distances precede cull distances, packed contiguously into 4-component pos exports (<= 8 total).
5649 Contrasted with DXBC OSG1 (D3D_NAME: 2=SV_ClipDistance, 3=SV_CullDistance, 5670 Contrasted with DXBC OSG1 (D3D_NAME: 2=SV_ClipDistance, 3=SV_CullDistance,
5650 4=SV_RenderTargetArrayIndex, 5=SV_ViewportArrayIndex, 23=SV_ShadingRate). 5671 4=SV_RenderTargetArrayIndex, 5=SV_ViewportArrayIndex, 23=SV_ShadingRate).
5651 When OSG1 is absent, infer contiguous ClipDistance slots from non-off pos1..pos2 exports. 5672 When OSG1 is absent (or declares no clip/cull/misc outputs), pos1..pos3 exports are ignored.
5652 """ 5673 """
5653 misc_svs = {sv for _, _, sv, _, _ in osg1 if sv in (4, 5, 23)} 5674 misc_svs = {sv for _, _, sv, _, _ in osg1 if sv in (4, 5, 23)}
5654 has_misc = bool(misc_svs) 5675 has_misc = bool(misc_svs)
@@ -5667,21 +5688,6 @@ def pos_export_layout(osg1, insns):
5667 if (mask >> c) & 1: 5688 if (mask >> c) & 1:
5668 slots.append(("cull", cull_n)) 5689 slots.append(("cull", cull_n))
5669 cull_n += 1 5690 cull_n += 1
5670 if not osg1:
5671 used = set()
5672 for ins in insns:
5673 if base_op(ins["op"]) != "exp":
5674 continue
5675 a = ins["args"]
5676 tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else ""
5677 if tgt in ("pos1", "pos2"):
5678 p = int(tgt[3:])
5679 for c, x in enumerate(a[1:5]):
5680 if not (x["k"] == "special" and x["t"] == "off"):
5681 used.add((p - 1) * 4 + c)
5682 if used:
5683 clip_n = min(max(used) + 1, 8)
5684 slots = [("clip", i) for i in range(clip_n)]
5685 base_pos = 2 if has_misc else 1 5691 base_pos = 2 if has_misc else 1
5686 pos_map = {} 5692 pos_map = {}
5687 for k, target in enumerate(slots[:8]): 5693 for k, target in enumerate(slots[:8]):
diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py
new file mode 100644
index 000000000..e1a46ae86
--- /dev/null
+++ b/tools/root_sig_contract.py
@@ -0,0 +1,155 @@
1r"""Reconcile a root signature against the translator's user-SGPR reads (stdlib only).
2
3A shader is identified by its index.json entry (user_sgpr_reads from
4tools/shader_meta.py); the candidate root signature is a hand-written JSON
5file in this tool's format (see --example), never game data.
6
7Usage:
8 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json>
9 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json> --cluster
10 python -I tools/root_sig_contract.py --example
11
12Exit code is 0 when every read is compatible, 1 on the first contradiction
13(hard fail: a mismatch means every draw/dispatch with that pair is corrupt).
14"""
15import argparse
16import json
17import sys
18
19# Packing order mirrors runtime/src/root_signature.{h,cpp}: constants take
20# NumValues dwords, root descriptors and tables take 2 (VA lo/hi), static
21# samplers take none.
22KIND_TO_TYPES = {
23 "const32": {"constants"},
24 "ptr64_lo": {"descriptor", "table"},
25 "ptr64_hi": {"descriptor", "table"},
26 "ptr32_lo": {"descriptor", "table"},
27 "vsharp": {"descriptor", "table"},
28 "tsharp": {"descriptor", "table"},
29 "ssharp": {"descriptor", "table"},
30}
31
32
33def pack_layout(sig):
34 """Lay out root params into 32 dwords. Returns (dwords, error).
35
36 dwords[i] = {"param": index, "sub": sub-dword, "ptype": ptype}.
37 error is set (and dwords empty) on spill, cost overflow or bad input:
38 refuse, never truncate.
39 """
40 dwords = []
41 cost = 0
42 params = [dict(p) for p in sig.get("params", [])] # normalized copy; input untouched
43 if len(params) > 64:
44 return [], "more than 64 root parameters"
45 for index, p in enumerate(params):
46 ptype = p.get("type", "")
47 if ptype == "constants":
48 count = p.get("count", 0)
49 if not isinstance(count, int) or count < 1:
50 return [], f"param {index}: constants need count >= 1"
51 width, cost_add = count, count
52 elif ptype in ("cbv", "srv", "uav"):
53 width, cost_add = 2, 2
54 ptype = "descriptor"
55 elif ptype == "table":
56 width, cost_add = 2, 1
57 else:
58 return [], f"param {index}: unknown type {ptype!r}"
59 cost += cost_add
60 if cost > 64:
61 return [], "exceeds the 64-dword D3D12 cost limit"
62 if len(dwords) + width > 32:
63 return [], "needs more than 32 user SGPRs (spill unsupported)"
64 for sub in range(width):
65 dwords.append({"param": index, "sub": sub, "ptype": ptype})
66 return dwords, ""
67
68
69def reconcile(shader_reads, dwords):
70 """Check one shader's reads against the packed layout.
71
72 Returns a list of contradiction strings (empty = compatible).
73 """
74 issues = []
75 by_sgpr = {}
76 for read in shader_reads:
77 by_sgpr.setdefault(read["sgpr"], []).append(read["kind"])
78 for sgpr in sorted(by_sgpr):
79 kinds = by_sgpr[sgpr]
80 if sgpr >= len(dwords):
81 issues.append(f"s{sgpr} read but layout has {len(dwords)} dwords")
82 continue
83 slot = dwords[sgpr]
84 for kind in kinds:
85 allowed = KIND_TO_TYPES.get(kind)
86 if allowed is None:
87 issues.append(f"s{sgpr}: unknown read kind {kind!r}")
88 elif slot["ptype"] not in allowed:
89 issues.append(
90 f"s{sgpr} ({kind}) incompatible with param "
91 f"{slot['param']} ({slot['ptype']})")
92 if kind == "ptr64_hi":
93 lo = dwords[sgpr - 1] if sgpr > 0 else None
94 if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \
95 or lo["sub"] != 0:
96 issues.append(f"s{sgpr} (ptr64_hi) without paired lo dword")
97 return issues
98
99
100def cluster(shaders):
101 """Group shaders by read-set shape. Returns [(shape, count, names)]."""
102 groups = {}
103 for name, entry in shaders.items():
104 reads = entry.get("user_sgpr_reads", [])
105 shape = tuple(sorted((r["sgpr"], r["kind"]) for r in reads))
106 groups.setdefault(shape, []).append(name)
107 ranked = sorted(groups.items(), key=lambda kv: -len(kv[1]))
108 return [(shape, len(names), names) for shape, names in ranked]
109
110
111def main():
112 ap = argparse.ArgumentParser(description="Root-signature vs shader-reads reconciler.")
113 ap.add_argument("index", nargs="?", help="spirv/index.json")
114 ap.add_argument("--rootsig", default=None, help="hand-written root-signature JSON")
115 ap.add_argument("--cluster", action="store_true", help="print read-set shape clustering")
116 ap.add_argument("--example", action="store_true", help="print an empty hand-written sig template")
117 a = ap.parse_args()
118 if a.example:
119 print(json.dumps({"version": "1.1", "flags": 0, "params": [
120 {"type": "constants", "count": 4, "visibility": "all"},
121 {"type": "cbv", "visibility": "vertex"},
122 {"type": "table", "ranges": [{"kind": "srv", "count": 8}],
123 "visibility": "pixel"}],
124 "static_samplers": []}, indent=2))
125 return 0
126 if not a.index or not a.rootsig:
127 ap.error("index.json and --rootsig are required (or --example)")
128 with open(a.index, encoding="utf-8") as f:
129 index = json.load(f)
130 with open(a.rootsig, encoding="utf-8") as f:
131 sig = json.load(f)
132 dwords, error = pack_layout(sig)
133 if error:
134 print(f"root signature refused: {error}")
135 return 1
136 print(f"packed {len(dwords)} dwords from {len(sig.get('params', []))} params")
137 bad = 0
138 for name in sorted(index):
139 reads = index[name].get("user_sgpr_reads", [])
140 issues = reconcile(reads, dwords)
141 if issues:
142 bad += 1
143 print(f"CONTRADICTION {name}:")
144 for issue in issues:
145 print(f" - {issue}")
146 if a.cluster:
147 print("read-set shapes (shape -> shaders):")
148 for shape, count, names in cluster(index)[:20]:
149 print(f" {count:6} {shape} e.g. {names[0]}")
150 print(f"{len(index)} shaders: {len(index) - bad} compatible, {bad} contradictory")
151 return 1 if bad else 0
152
153
154if __name__ == "__main__":
155 sys.exit(main())
diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py
index be24299ff..871e7f610 100644
--- a/tools/rpf9_carve.py
+++ b/tools/rpf9_carve.py
@@ -51,6 +51,9 @@ def main() -> int:
51 break 51 break
52 s = mt.start() 52 s = mt.start()
53 if m[s:s + 3] == b"KB2": 53 if m[s:s + 3] == b"KB2":
54 if s + 0x1C > size: # header cut off by the end of the file (a truncated copy): not a video
55 pos = s + 1
56 continue
54 blen = struct.unpack_from("<I", m, s + 4)[0] + 8 57 blen = struct.unpack_from("<I", m, s + 4)[0] + 8
55 w, h = struct.unpack_from("<II", m, s + 0x14) 58 w, h = struct.unpack_from("<II", m, s + 0x14)
56 if not (64 <= blen <= size - s and 16 <= w <= 8192 and 16 <= h <= 8192): 59 if not (64 <= blen <= size - s and 16 <= w <= 8192 and 16 <= h <= 8192):
@@ -117,6 +120,7 @@ def main() -> int:
117 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 120 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f:
118 json.dump({"summary": summary, "files": rows}, f) 121 json.dump({"summary": summary, "files": rows}, f)
119 print(json.dumps(summary, indent=1)) 122 print(json.dumps(summary, indent=1))
123 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by
120 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}") 124 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}")
121 return 0 125 return 0
122 126
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index 942d44dac..5923ee66c 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -13,34 +13,20 @@ Set LLVM_MC to llvm-mc's path, or to a whole command such as
13""" 13"""
14import argparse 14import argparse
15import os 15import os
16import shlex
17import struct 16import struct
18import subprocess 17import subprocess
19import sys 18import sys
20from concurrent.futures import ThreadPoolExecutor 19from concurrent.futures import ThreadPoolExecutor
21 20
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22from mc_command import mc_command # noqa: E402
23
22TRIPLE = "amdgcn--amdpal" 24TRIPLE = "amdgcn--amdpal"
23ENDPGM = b"\x00\x00\x81\xbf" 25ENDPGM = b"\x00\x00\x81\xbf"
24PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with 26PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with
25FAILED = [] # (path, first stderr line) for shaders that produced no disassembly 27FAILED = [] # (path, first stderr line) for shaders that produced no disassembly
26 28
27 29
28def split_command(raw: str) -> list:
29 """Split LLVM_MC without eating the backslashes of a Windows path (POSIX shlex would)."""
30 if os.name != "nt":
31 return shlex.split(raw)
32 parts = shlex.split(raw, posix=False)
33 return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts]
34
35
36def mc_command() -> list:
37 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'."""
38 raw = os.environ.get("LLVM_MC", "llvm-mc").strip()
39 if os.path.isfile(raw):
40 return [raw] # a plain path, spaces and all
41 return split_command(raw) or ["llvm-mc"]
42
43
44MC = mc_command() 30MC = mc_command()
45 31
46 32
@@ -56,13 +42,15 @@ def probe(mcpu: str) -> None:
56 input=PROBE, capture_output=True, text=True, 42 input=PROBE, capture_output=True, text=True,
57 creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) 43 creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0))
58 except OSError as e: 44 except OSError as e:
59 fail(f"'{MC[0]}' could not be started: {e}. Put llvm-mc on PATH or set LLVM_MC to it, e.g.\n" 45 fail(f"'{MC[0]}' could not be started: {e}. Put llvm-mc on PATH or set LLVM_MC to it (on Windows,\n"
46 f"scripts\\build_llvm_mc.ps1 builds one and sets it), e.g.\n"
60 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") 47 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc")
61 if p.returncode != 0 or "s_endpgm" not in p.stdout: 48 if p.returncode != 0 or "s_endpgm" not in p.stdout:
62 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] 49 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0]
63 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" 50 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n"
64 f"The disassembler needs LLVM 21+ with the AMDGPU target. The official Windows LLVM build has no\n" 51 f"The disassembler needs LLVM 21+ with the AMDGPU target. The official Windows LLVM build has no\n"
65 f"AMDGPU target; run it from WSL instead (docs/design.md, 'Disassembling shaders'), e.g.\n" 52 f"AMDGPU target: build a native one with scripts\\build_llvm_mc.ps1, or run it from WSL\n"
53 f"(docs/design.md, 'Disassembling shaders'), e.g.\n"
66 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") 54 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc")
67 55
68 56
diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py
new file mode 100644
index 000000000..050eb9b22
--- /dev/null
+++ b/tools/ttpf_mips.py
@@ -0,0 +1,845 @@
1"""Measure and decode the TTPF (RDS5) compact mip chain, including the packed tail.
2
3The compact profile in `TtpfReader` is the AMD Gfx10 mip-tail layout: mips smaller
4than half a tile share one tile at offset 0, and the rest are standalone, smallest
5first. `TtpfReader` only trusts a hand-validated tuple table and stops at the
6descriptor's `nonTail` field, which is not the layout boundary. This tool computes
7the layout from the descriptor and validates it against the native allocation span,
8then decodes the mips that are zlib/raw (no BCPack backend is used or guessed).
9
10Read-only: no texture bytes are printed or committed. `scan` emits aggregate
11counters only. `layout` prints descriptor fields and offsets. `check` prints the
12BC block-average error against a 2x2 downsample of the parent mip; it decodes
13BC1, BC3, BC4_UNORM and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7
14are sized but not decoded, and uncompressed tiling is not validated). `export`
15writes a full BC chain only when every source mip is zlib/raw.
16
17 python -I tools/ttpf_mips.py scan <game root or pool paths...> [--json out]
18 python -I tools/ttpf_mips.py layout <pool.ttpf> <index>
19 python -I tools/ttpf_mips.py check <pool.ttpf> <index>
20 python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds> [--mips N] [--force]
21
22Standard library only. The RDS5/ETPF checks mirror rpf9-explorer's `TtpfReader`
23(MIT); the tile patterns and tail formula are the AMD Gfx10 4 KiB/64 KiB layouts
24already used by that reader and recorded in docs/textures.md.
25"""
26import argparse
27import glob
28import json
29import mmap
30import os
31import struct
32import sys
33import zlib
34
35MAX_OUTPUT = 256 * 1024 * 1024
36MAX_TEXTURES = 250_000
37ETPF_VERSION = 634
38
39# DXGI format -> element bytes, as RageTextureDecoder.ElementBytes. DXGI 11
40# (R16G16B16A16_UNORM) is 8 bytes but is left out here as well: its uncompressed
41# tiling has not been validated, so `scan` reports it as a format gap.
42ELEMENT_BYTES = {
43 2: 16, 3: 16, 4: 16, 6: 12, 7: 12, 8: 12, 10: 8, 12: 8, 13: 8, 14: 8,
44 16: 8, 17: 8, 18: 8, 24: 4, 25: 4, 26: 4, 28: 4, 29: 4, 30: 4, 31: 4, 32: 4,
45 34: 4, 35: 4, 36: 4, 37: 4, 38: 4, 41: 4, 42: 4, 43: 4, 49: 2, 50: 2, 51: 2,
46 52: 2, 54: 2, 56: 2, 57: 2, 58: 2, 59: 2, 61: 1, 62: 1, 63: 1, 64: 1, 65: 1,
47 71: 8, 72: 8, 74: 16, 75: 16, 77: 16, 78: 16, 80: 8, 81: 8, 83: 16, 84: 16,
48 87: 4, 88: 4, 91: 4, 93: 4, 95: 16, 96: 16, 98: 16, 99: 16,
49}
50BC_FORMATS = frozenset(range(70, 85)) | frozenset(range(94, 100))
51
52# AMD Gfx10 intra-tile bit order (bit index -> source bit), from TtpfReader.
53PATTERNS_4K = {
54 0: (1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6),
55 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6),
56 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5),
57 3: (0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5),
58 4: (0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4),
59}
60PATTERNS_64K = {
61 0: (1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8),
62 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8),
63 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7),
64 3: (0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7),
65 4: (0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6),
66}
67
68# The profile tuples `TtpfReader.ValidatedCompactProfile` accepts. Reproduced only
69# so `scan` can show the reader's published skip/partial split next to the layout
70# result; decoding does not depend on this table.
71VALIDATED_COMPACT = {
72 (4, 1024, 1024, 9, 3, 8, 0x503, 0x00B00106),
73 (6, 512, 512, 8, 3, 8, 0x041, 0x00B800D4),
74 (4, 256, 256, 7, 1, 8, 0x103, 0),
75 (4, 512, 512, 8, 3, 16, 0x482, 0x015000F5),
76 (4, 1024, 512, 8, 3, 8, 0x482, 0x015000F5),
77 (4, 512, 1024, 8, 3, 8, 0x483, 0x013000F5),
78 (4, 128, 256, 6, 1, 8, 0x083, 0),
79 (4, 256, 512, 7, 1, 8, 0x167, 0),
80 (4, 512, 256, 7, 1, 8, 0x166, 0),
81 (4, 256, 256, 7, 1, 16, 0x166, 0),
82 (4, 1024, 512, 8, 3, 16, 0x504, 0x900106),
83 (4, 1024, 256, 7, 3, 16, 0x484, 0x11000F5),
84 (6, 1024, 256, 7, 3, 8, 0x42, 0x9800D4),
85 (6, 64, 1024, 5, 3, 8, 0x83, 0x3800B4),
86 (4, 512, 1024, 8, 3, 16, 0x503, 0xB00106),
87 (4, 512, 128, 6, 1, 16, 0x168, 0),
88 (6, 256, 1024, 7, 3, 8, 0x83, 0x3800D4),
89 (4, 1024, 128, 6, 1, 8, 0x168, 0),
90 (4, 2048, 256, 7, 3, 16, 0x508, 0x100106),
91 (4, 2048, 512, 8, 3, 8, 0x504, 0x900106),
92 (6, 512, 256, 7, 3, 16, 0x42, 0x9800D4),
93 (6, 1024, 128, 6, 3, 16, 0x84, 0x1800D4),
94 (4, 512, 128, 6, 1, 8, 0x104, 0),
95 (4, 256, 1024, 7, 3, 16, 0x483, 0x13000F5),
96 (6, 1024, 64, 5, 3, 16, 0x83, 0x3800B4),
97 (6, 256, 512, 7, 3, 16, 0x41, 0xB800D4),
98 (4, 128, 128, 6, 1, 16, 0x82, 0),
99 (4, 512, 64, 5, 1, 16, 0x108, 0),
100 (4, 256, 128, 6, 1, 16, 0x104, 0),
101 (6, 128, 1024, 6, 3, 16, 0x83, 0x3800D4),
102 (4, 512, 64, 5, 1, 8, 0x84, 0),
103 (4, 128, 512, 6, 1, 16, 0x167, 0),
104 (4, 256, 128, 6, 1, 8, 0x82, 0),
105 (4, 1024, 64, 5, 1, 8, 0x108, 0),
106 (6, 1024, 32, 4, 3, 16, 0x82, 0x5800B4),
107 (4, 128, 512, 6, 1, 8, 0x107, 0),
108 (4, 512, 2048, 8, 3, 8, 0x507, 0x300106),
109 (4, 256, 2048, 7, 3, 8, 0x507, 0x3000F5),
110 (4, 512, 32, 4, 1, 16, 0x107, 0),
111 (6, 128, 1024, 6, 3, 8, 0x83, 0x3800B4),
112 (6, 64, 1024, 5, 3, 16, 0x83, 0x3800B4),
113 (4, 256, 256, 5, 1, 16, 0x166, 0),
114 (4, 128, 256, 6, 1, 16, 0x103, 0),
115 (4, 256, 64, 5, 1, 16, 0x84, 0),
116 (4, 16, 256, 3, 1, 16, 0x83, 0),
117 (4, 256, 32, 4, 1, 16, 0x84, 0),
118 (4, 64, 512, 5, 1, 16, 0x107, 0),
119 (4, 2048, 256, 7, 3, 8, 0x484, 0x11000F5),
120 (4, 64, 512, 5, 1, 8, 0x107, 0),
121 (4, 64, 256, 5, 1, 8, 0x83, 0),
122 (6, 256, 512, 9, 3, 16, 0x41, 0xB800D4),
123 (6, 32, 1024, 4, 3, 16, 0x82, 0x5800B4),
124 (4, 512, 512, 3, 3, 8, 0x502, 0xD00006),
125 (36, 1024, 1024, 9, 3, 8, 0x503, 0xB00106),
126 (36, 256, 256, 7, 1, 8, 0x103, 0),
127}
128VALIDATED_AUX = dict(mips=3, non_tail=3, meta=0x1A8, extra=0x01080008, width=1024,
129 height_a=512, fmt_a=61, height_b=1024, bytes_b=8)
130
131
132class LayoutError(ValueError):
133 pass
134
135
136class BcpackRequired(NotImplementedError):
137 pass
138
139
140def u32(b, o):
141 return struct.unpack_from("<I", b, o)[0]
142
143
144def u64(b, o):
145 return struct.unpack_from("<Q", b, o)[0]
146
147
148def align(v, n):
149 return (v + n - 1) // n * n
150
151
152def tile_mode(mode):
153 """Descriptor mode is a flag bit plus a 4-bit Gfx10 tile mode at bit 1."""
154 return (mode >> 1) & 0xF
155
156
157def tile_bytes(mode):
158 # Tile mode 0 is SW_64KB_D; 1-3 are SW_4KB_S; 9-12 appear only on arrays.
159 return 65536 if tile_mode(mode) == 0 else 4096
160
161
162def element_bytes(fmt):
163 if fmt not in ELEMENT_BYTES:
164 raise LayoutError(f"no element-size mapping for DXGI format {fmt}")
165 return ELEMENT_BYTES[fmt]
166
167
168def surface_layout(width, height, fmt, mips, tile=4096):
169 """AMD Gfx10 surface layout: standalone mips smallest-first, then one tail tile.
170
171 Returns a dict with the allocation size, the first tail mip index, block
172 dimensions and a per-mip list. `offset` is relative to the allocation base.
173 """
174 eb = element_bytes(fmt)
175 log = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]
176 px = 4 if fmt in BC_FORMATS else 1
177 levels = 1
178 v = max(width, height)
179 while v > 1:
180 levels += 1
181 v >>= 1
182 if mips < 1 or mips > levels:
183 raise LayoutError(f"invalid mip count {mips} for {width}x{height}")
184 half_bits = 6 if tile == 4096 else 8
185 max_tail = 8 if tile == 4096 else 12
186 bw = 1 << (half_bits - log // 2)
187 bh = 1 << (half_bits - (log + 1) // 2)
188 mw, mh = {0: (16, 16), 1: (16, 8), 2: (8, 8), 3: (8, 4)}.get(log, (4, 4))
189 ew = (width + px - 1) // px
190 eh = (height + px - 1) // px
191 tail = mips
192 sizes = []
193 out = []
194 for i in range(mips):
195 wc = max(1, (ew + (1 << i) - 1) >> i)
196 hc = max(1, (eh + (1 << i) - 1) >> i)
197 if mips > 1 and wc <= bw // 2 and hc <= bh and mips - i <= max_tail:
198 tail = i
199 break
200 pw = align(wc, bw)
201 ph = align(hc, bh)
202 sizes.append(pw * ph * eb)
203 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=pw, padded_h=ph,
204 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
205 offset=0, region=pw * ph * eb, tile_x=0, tile_y=0, in_tail=False))
206 off = tile if tail < mips else 0
207 for i in range(tail - 1, -1, -1):
208 out[i]["offset"] = off
209 off += sizes[i]
210 for i in range(tail, mips):
211 entry = max_tail - 1 - (i - tail)
212 moff = (16 << entry) if entry > 6 else entry << 8
213 x = y = 0
214 for bit in range(6):
215 x |= ((moff >> (9 + 2 * bit)) & 1) << bit
216 y |= ((moff >> (8 + 2 * bit)) & 1) << bit
217 wc = max(1, (ew + (1 << i) - 1) >> i)
218 hc = max(1, (eh + (1 << i) - 1) >> i)
219 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=bw, padded_h=bh,
220 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
221 offset=0, region=tile, tile_x=x * mw, tile_y=y * mh,
222 in_tail=True, tail_offset=moff))
223 return dict(size=off, tile=tile, first_tail=tail, block_w=bw, block_h=bh,
224 element_bytes=eb, mips=out)
225
226
227def detile(layout, mip, tiled):
228 """Copy the mip's elements out of the tiled allocation into block-linear order."""
229 pat = (PATTERNS_4K if layout["tile"] == 4096 else PATTERNS_64K)[
230 {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]]
231 bw, bh = layout["block_w"], layout["block_h"]
232 eb = layout["element_bytes"]
233 out = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb)
234 for y in range(mip["blocks_h"]):
235 for x in range(mip["blocks_w"]):
236 off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"]
237 for bit, s in enumerate(pat):
238 if s > 0:
239 off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit
240 elif s < 0:
241 off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit
242 at = (y * mip["blocks_w"] + x) * eb
243 out[at:at + eb] = tiled[off:off + eb]
244 return bytes(out)
245
246
247# --- BC decoding (color only; enough for the downsample check) -------------
248
249def _rgb565(c):
250 return ((c >> 11) & 31) * 255.0 / 31, ((c >> 5) & 63) * 255.0 / 63, (c & 31) * 255.0 / 31
251
252
253def decode_bc1_block(data, at):
254 c0, c1, idx = struct.unpack_from("<HHI", data, at)
255 p0, p1 = _rgb565(c0), _rgb565(c1)
256 if c0 > c1:
257 pal = [p0, p1, tuple((2 * a + b) / 3 for a, b in zip(p0, p1)),
258 tuple((a + 2 * b) / 3 for a, b in zip(p0, p1))]
259 else:
260 pal = [p0, p1, tuple((a + b) / 2 for a, b in zip(p0, p1)), (0.0, 0.0, 0.0)]
261 return [pal[(idx >> (2 * (y * 4 + x))) & 3] for y in range(4) for x in range(4)]
262
263
264def decode_bc4_block(data, at):
265 e0, e1 = data[at], data[at + 1]
266 bits = int.from_bytes(data[at + 2:at + 8], "little")
267 if e0 > e1:
268 pal = [e0, e1] + [((7 - i) * e0 + i * e1) // 7 for i in range(1, 7)]
269 else:
270 pal = [e0, e1] + [((5 - i) * e0 + i * e1) // 5 for i in range(1, 5)] + [0, 255]
271 vals = [pal[(bits >> (3 * (y * 4 + x))) & 7] for y in range(4) for x in range(4)]
272 return [(float(v),) * 3 for v in vals]
273
274
275def decode_pixels(fmt, data, blocks_w, blocks_h):
276 """Return one (r, g, b) per pixel, or None for a format this tool cannot decode."""
277 px = []
278 for by in range(blocks_h):
279 rows = [[None] * (blocks_w * 4) for _ in range(4)]
280 for bx in range(blocks_w):
281 at = (by * blocks_w + bx) * 16
282 if fmt in (71, 72):
283 blk = decode_bc1_block(data, (by * blocks_w + bx) * 8)
284 elif fmt in (77, 78):
285 blk = decode_bc1_block(data, at + 8)
286 elif fmt in (80,):
287 blk = decode_bc4_block(data, (by * blocks_w + bx) * 8, False)
288 elif fmt in (83,):
289 a = decode_bc4_block(data, at, False)
290 b = decode_bc4_block(data, at + 8, False)
291 blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)]
292 else:
293 return None
294 for y in range(4):
295 for x in range(4):
296 rows[y][bx * 4 + x] = blk[y * 4 + x]
297 px.extend(rows)
298 return [p for row in px for p in row]
299
300
301def block_means(pixels, blocks_w, blocks_h):
302 out = []
303 for by in range(blocks_h):
304 for bx in range(blocks_w):
305 acc = [0.0, 0.0, 0.0]
306 for y in range(4):
307 for x in range(4):
308 q = pixels[(by * 4 + y) * (blocks_w * 4) + bx * 4 + x]
309 for k in range(3):
310 acc[k] += q[k]
311 out.append((acc[0] / 16, acc[1] / 16, acc[2] / 16))
312 return out
313
314
315def downsample2(blocks, blocks_w, blocks_h):
316 ow, oh = max(1, blocks_w // 2), max(1, blocks_h // 2)
317 out = []
318 for y in range(oh):
319 for x in range(ow):
320 acc = [0.0, 0.0, 0.0]
321 n = 0
322 for dy in range(2):
323 for dx in range(2):
324 bx = min(blocks_w - 1, 2 * x + dx)
325 by = min(blocks_h - 1, 2 * y + dy)
326 q = blocks[by * blocks_w + bx]
327 for k in range(3):
328 acc[k] += q[k]
329 n += 1
330 out.append(tuple(a / n for a in acc))
331 return out
332
333
334def mean_abs_error(a, b):
335 if not a:
336 return None
337 return sum(abs(x - y) for pa, pb in zip(a, b) for x, y in zip(pa, pb)) / (3 * len(a))
338
339
340# --- RDS5 / ETPF container ------------------------------------------------
341
342class Pool:
343 """Read-only RDS5 texture pool, mirroring TtpfReader's catalog checks."""
344
345 def __init__(self, path):
346 self.path = path
347 self._fh = open(path, "rb")
348 try:
349 self.data = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ)
350 except Exception:
351 self._fh.close()
352 raise
353 d = self.data
354 if len(d) < 256 or d[:4] != b"RDS5":
355 raise ValueError("not an RDS5 container or truncated header")
356 count = u32(d, 4)
357 size_word = u64(d, 8)
358 self.virtual_size = size_word & 0x00FFFFFFFFFFFFFF
359 if (count < 3 or count > 1_000_002 or (size_word >> 56) != 22 or
360 self.virtual_size < 4096 or u32(d, 16) not in
361 ((count + 31) // 32, (count + 31) // 32 + 1)):
362 raise ValueError("unsupported RDS5 index layout")
363 self.chunk_count = count - 2
364 table_end = 24 + (count - 1) * 8
365 self.etpf = align(table_end, 256)
366 if table_end > len(d) - 16:
367 raise ValueError("RDS5 index exceeds its source")
368 table = d[24:table_end]
369 if ((u64(table, len(table) - 8) & 0x3FFFFFF) * 256 != len(d) or
370 ((u64(table, len(table) - 8) >> 30) & 0x3FFFFF) * 4096 != self.virtual_size):
371 raise ValueError("RDS5 sentinel does not match its lengths")
372 self.chunks = []
373 for i in range(self.chunk_count):
374 v, nxt = u64(table, i * 8), u64(table, (i + 1) * 8)
375 start, end = (v & 0x3FFFFFF) * 256, (nxt & 0x3FFFFFF) * 256
376 virt, vend = ((v >> 30) & 0x3FFFFF) * 4096, ((nxt >> 30) & 0x3FFFFF) * 4096
377 pad = v >> 52
378 codec = (v >> 26) & 15
379 packed, size = end - start - pad, vend - virt
380 if (start < self.etpf + 16 or end > len(d) or packed < 1 or packed > MAX_OUTPUT or
381 size < 1 or size > MAX_OUTPUT or vend > self.virtual_size or
382 (codec == 0 and packed != size)):
383 raise ValueError(f"RDS5 chunk {i} range is invalid")
384 self.chunks.append((virt, size, start, packed, codec, pad))
385 eh = d[self.etpf:self.etpf + 16]
386 if eh[:4] != b"ETPF" or u32(eh, 4) != ETPF_VERSION:
387 raise ValueError("unsupported embedded ETPF version")
388 self.textures = u32(eh, 8)
389 area = u32(eh, 12)
390 metadata = 16 + area + self.textures * 32
391 padded = align(metadata, 4096)
392 alignment = u32(d, 20)
393 source_padding = (alignment >> 28) * 256
394 if (self.textures < 1 or self.textures > MAX_TEXTURES or area < self.textures * 16 or
395 (alignment & 0x0FFFFFFF) != 0 or padded != self.chunks[0][0] or
396 self.etpf + padded + source_padding != self.chunks[0][2]):
397 raise ValueError("ETPF tables do not match the data boundary")
398 self.area = area
399 self.records = d[self.etpf + 16:self.etpf + 16 + area]
400 self.ids = d[self.etpf + 16 + area:self.etpf + 16 + area + self.textures * 32]
401 self._starts = [c[0] for c in self.chunks]
402
403 def close(self):
404 self.data.close()
405 self._fh.close()
406
407 def descriptor(self, index):
408 if not 0 <= index < self.textures:
409 raise IndexError(index)
410 a, b, c, d = struct.unpack_from("<IIII", self.records, index * 16)
411 return dict(
412 index=index, width=(a & 0x3FFF) + 1, height=((a >> 14) & 0x3FFF) + 1,
413 mips=(a >> 28) + (b & 7), packed_mips=a >> 28, non_tail=b & 7,
414 format=(b >> 3) & 255, depth=((b >> 11) & 1023) + 1,
415 dimension=(b >> 21) & 3, mode=b >> 23, meta=c >> 21, extra=d,
416 base=(c & 0x1FFFFF) * 4096, asset_key_at=(
417 u64(self.records, self.textures * 16 + index * 8)
418 if (self.textures * 16 + index * 8 + 8 <= len(self.records))
419 else None),
420 )
421
422 def chunks_for(self, start, size):
423 import bisect
424 end = start + size
425 i = max(0, bisect.bisect_right(self._starts, start) - 1)
426 out = []
427 covered = start
428 while i < len(self.chunks) and self.chunks[i][0] < end:
429 virt, csize, src, packed, codec, pad = self.chunks[i]
430 if virt > covered:
431 raise ValueError("texture crosses an unmapped virtual range")
432 out.append(self.chunks[i])
433 covered = min(end, virt + csize)
434 i += 1
435 if covered != end:
436 raise ValueError("texture range is not completely mapped")
437 return out
438
439 def codecs(self, start, size):
440 return {c[4] for c in self.chunks_for(start, size)}
441
442 def readable(self, start, size):
443 return self.codecs(start, size) <= {0, 8}
444
445 def read_range(self, start, size, cache=None):
446 cache = {} if cache is None else cache
447 out = bytearray(size)
448 for virt, csize, src, packed, codec, pad in self.chunks_for(start, size):
449 key = (src, packed, codec)
450 if key not in cache:
451 raw = self.data[src:src + packed]
452 if codec == 0:
453 cache[key] = bytes(raw)
454 elif codec == 8:
455 cache[key] = zlib.decompress(raw)
456 else:
457 raise BcpackRequired("range touches a BCPack chunk")
458 if len(cache[key]) != csize:
459 raise ValueError("decoded chunk length disagrees with its range")
460 lo, hi = max(start, virt), min(start + size, virt + csize)
461 out[lo - start:hi - start] = cache[key][lo - virt:hi - virt]
462 return bytes(out)
463
464 def span(self, index, base):
465 for j in range(index + 1, self.textures):
466 cand = (u32(self.records, j * 16 + 8) & 0x1FFFFF) * 4096
467 if cand < base:
468 return None
469 if cand > base:
470 return cand - base
471 return self.virtual_size - base
472
473
474def compact_row(desc):
475 """The reader's compact-profile gate (mode families 4/6/36 and aux mode 2)."""
476 return desc["mode"] in (4, 6, 36) or (desc["mode"] == 2 and (desc["meta"] or desc["extra"]))
477
478
479def validated_compact(desc, eb):
480 return (desc["mode"], desc["width"], desc["height"], desc["mips"], desc["non_tail"],
481 eb, desc["meta"], desc["extra"]) in VALIDATED_COMPACT
482
483
484def validated_aux(desc):
485 a = VALIDATED_AUX
486 return (desc["mips"] == a["mips"] and desc["non_tail"] == a["non_tail"] and
487 desc["meta"] == a["meta"] and desc["extra"] == a["extra"] and
488 desc["width"] == a["width"] and
489 ((desc["height"] == a["height_a"] and desc["format"] == a["fmt_a"]) or
490 (desc["height"] == a["height_b"] and desc["format"] in BC_FORMATS and
491 ELEMENT_BYTES.get(desc["format"]) == a["bytes_b"])))
492
493
494def analyze(pool, index):
495 """Descriptor + layout + per-mip codec availability for one texture."""
496 d = pool.descriptor(index)
497 out = dict(descriptor=d, tile_mode=tile_mode(d["mode"]), tile=tile_bytes(d["mode"]))
498 if d["dimension"] != 1 or d["depth"] != 1:
499 out["blocked"] = "array/volume descriptor"
500 return out
501 try:
502 layout = surface_layout(d["width"], d["height"], d["format"], d["mips"],
503 out["tile"])
504 except LayoutError as e:
505 out["blocked"] = str(e)
506 return out
507 out["layout"] = layout
508 if d["base"] == 0 or (d["base"] >> 12) == 0x1FFFFF:
509 out["blocked"] = "no mapped allocation"
510 return out
511 span = pool.span(index, d["base"])
512 out["allocation_span"] = span
513 out["span_matches"] = span == layout["size"]
514 if not out["span_matches"]:
515 out["blocked"] = "layout does not match the allocation span"
516 return out
517 avail = []
518 for mip in layout["mips"]:
519 try:
520 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
521 except ValueError:
522 avail = []
523 break
524 out["available"] = avail
525 if avail:
526 limit = d["non_tail"] if compact_row(d) else d["mips"]
527 limit = max(0, min(limit, len(avail)))
528 base_mip = next((i for i in range(limit) if avail[i]), None)
529 exported = 0
530 if base_mip is not None:
531 while base_mip + exported < limit and avail[base_mip + exported]:
532 exported += 1
533 out["reader_limit"] = limit
534 out["reader_base_mip"] = base_mip
535 out["reader_exported"] = exported
536 out["full_chain"] = bool(avail) and all(avail)
537 out["recoverable_mips"] = sum(1 for a in avail[exported:] if a) if base_mip == 0 else 0
538 return out
539
540
541# --- commands --------------------------------------------------------------
542
543def find_pools(arg):
544 if os.path.isfile(arg):
545 return [arg]
546 pools = sorted(glob.glob(os.path.join(arg, "data", "ttdb", "**", "*.ttpf"), recursive=True))
547 pools += sorted(glob.glob(os.path.join(arg, "pack", "*", "data", "ttdb", "**", "*.ttpf"),
548 recursive=True))
549 return pools
550
551
552def scan_pools(paths, as_json=None):
553 total = dict(pools=0, entries=0, arrays=0, unsupported_format=0, format11=0,
554 layout_mismatch=0, reader_full=0, reader_partial=0,
555 reader_skip_bcpack=0, whitelist_gated=0, gated_layout_ok=0,
556 gated_full_chain=0, gated_full_mips=0, gated_full_bytes=0,
557 gated_tail_only=0, gated_by_mode={},
558 compact_partial_rows=0, compact_missing_mips=0,
559 compact_decodable_mips=0, compact_decodable_bytes=0,
560 compact_missing_standalone=0, compact_missing_tail=0,
561 compact_rows_measured=0, compact_non_tail_before_tail=0,
562 compact_standalone_beyond_limit=0,
563 compact_standalone_decodable_beyond_limit=0,
564 compact_full_rows=0, tile_modes={})
565 for path in paths:
566 pool = Pool(path)
567 try:
568 total["pools"] += 1
569 for i in range(pool.textures):
570 d = pool.descriptor(i)
571 total["entries"] += 1
572 tm = str(tile_mode(d["mode"]))
573 total["tile_modes"][tm] = total["tile_modes"].get(tm, 0) + 1
574 if d["dimension"] != 1 or d["depth"] != 1:
575 total["arrays"] += 1
576 continue
577 # The reader's gate: modes 4/6/36 and aux mode 2 need a validated tuple;
578 # every other non-0/2 mode is rejected by the same branch.
579 aux = d["mode"] == 2 and (d["meta"] or d["extra"])
580 if d["mode"] in (0, 2):
581 gated = d["mode"] == 2 and aux and not validated_aux(d)
582 else:
583 eb = ELEMENT_BYTES.get(d["format"])
584 gated = not (d["mode"] in (4, 6, 36) and eb is not None and
585 validated_compact(d, eb))
586 try:
587 layout = surface_layout(d["width"], d["height"], d["format"],
588 d["mips"], tile_bytes(d["mode"]))
589 except LayoutError:
590 total["unsupported_format"] += 1
591 if d["format"] == 11:
592 total["format11"] += 1
593 if gated:
594 total["whitelist_gated"] += 1
595 continue
596 span = pool.span(i, d["base"])
597 if d["base"] == 0 or span != layout["size"]:
598 total["layout_mismatch"] += 1
599 continue
600 avail = []
601 for mip in layout["mips"]:
602 try:
603 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
604 except ValueError:
605 avail = []
606 break
607 if not avail:
608 total["layout_mismatch"] += 1
609 continue
610 if gated:
611 total["whitelist_gated"] += 1
612 total["gated_layout_ok"] += 1
613 key = str(d["mode"])
614 total["gated_by_mode"][key] = total["gated_by_mode"].get(key, 0) + 1
615 if all(avail):
616 total["gated_full_chain"] += 1
617 total["gated_full_mips"] += d["mips"]
618 total["gated_full_bytes"] += sum(
619 mip["blocks_w"] * mip["blocks_h"] * layout["element_bytes"]
620 for mip in layout["mips"])
621 elif (layout["first_tail"] < d["mips"] and
622 all(avail[k] for k in range(layout["first_tail"], d["mips"]))):
623 total["gated_tail_only"] += 1
624 continue
625 is_compact = compact_row(d)
626 limit = min(d["non_tail"], len(avail)) if is_compact else len(avail)
627 base_mip = next((k for k in range(limit) if avail[k]), None)
628 exported = 0
629 if base_mip is not None:
630 while base_mip + exported < limit and avail[base_mip + exported]:
631 exported += 1
632 if exported == 0:
633 total["reader_skip_bcpack"] += 1
634 elif exported < d["mips"]:
635 total["reader_partial"] += 1
636 if is_compact and base_mip == 0 and exported == limit:
637 total["compact_partial_rows"] += 1
638 missing = d["mips"] - exported
639 total["compact_missing_mips"] += missing
640 dec = 0
641 for k in range(exported, d["mips"]):
642 if avail[k]:
643 dec += 1
644 if k < layout["first_tail"]:
645 total["compact_missing_standalone"] += 1
646 else:
647 total["compact_missing_tail"] += 1
648 total["compact_decodable_mips"] += dec
649 total["compact_decodable_bytes"] += sum(
650 layout["mips"][k]["blocks_w"] * layout["mips"][k]["blocks_h"] *
651 layout["element_bytes"] for k in range(exported, d["mips"])
652 if avail[k])
653 if dec == missing:
654 total["compact_full_rows"] += 1
655 else:
656 total["reader_full"] += 1
657 if d["mode"] in (4, 6, 36):
658 total["compact_rows_measured"] += 1
659 if d["non_tail"] < layout["first_tail"]:
660 total["compact_non_tail_before_tail"] += 1
661 total["compact_standalone_beyond_limit"] += (
662 layout["first_tail"] - d["non_tail"])
663 total["compact_standalone_decodable_beyond_limit"] += sum(
664 1 for k in range(d["non_tail"], layout["first_tail"]) if avail[k])
665 finally:
666 pool.close()
667 report = dict(total=total)
668 if as_json:
669 with open(as_json, "w", encoding="utf-8") as f:
670 json.dump(report, f, indent=1)
671 print(json.dumps(report, indent=1))
672
673
674def describe(pool, index):
675 a = analyze(pool, index)
676 d = a["descriptor"]
677 out = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
678 mips=d["mips"], non_tail=d["non_tail"], mode=d["mode"],
679 tile_mode=a["tile_mode"], tile=a["tile"], base=d["base"],
680 meta=d["meta"], extra=d["extra"])
681 if "layout" in a:
682 out["allocation_size"] = a["layout"]["size"]
683 out["allocation_span"] = a.get("allocation_span")
684 out["span_matches"] = a.get("span_matches")
685 out["first_tail_mip"] = a["layout"]["first_tail"]
686 out["mips_detail"] = [
687 dict(index=m["index"], blocks=[m["blocks_w"], m["blocks_h"]], offset=m["offset"],
688 region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]])
689 for m in a["layout"]["mips"]]
690 if "available" in a:
691 out["available"] = a["available"]
692 out["reader_limit"] = a["reader_limit"]
693 out["reader_exported"] = a["reader_exported"]
694 out["full_chain"] = a["full_chain"]
695 if a.get("blocked"):
696 out["blocked"] = a["blocked"]
697 return out
698
699
700def check(pool, index):
701 a = analyze(pool, index)
702 if "layout" not in a:
703 print(json.dumps(dict(index=index, blocked=a.get("blocked")), indent=1))
704 return 2
705 layout = a["layout"]
706 d = a["descriptor"]
707 cache = {}
708 try:
709 tiled = pool.read_range(d["base"], layout["size"], cache)
710 except BcpackRequired:
711 print(json.dumps(dict(index=index, blocked="BCPack in allocation"), indent=1))
712 return 2
713 decoded, means = [], []
714 for mip in layout["mips"]:
715 data = detile(layout, mip, tiled[mip["offset"]:mip["offset"] + mip["region"]])
716 px = decode_pixels(d["format"], data, mip["blocks_w"], mip["blocks_h"])
717 if px is None:
718 decoded.append(None)
719 means.append(None)
720 else:
721 decoded.append(px)
722 means.append(block_means(px, mip["blocks_w"], mip["blocks_h"]))
723 if all(px is None for px in decoded):
724 print(json.dumps(dict(index=index, blocked=(
725 f"format {d['format']} is not one of the BC formats this tool decodes "
726 "(71/72/77/78/80/83)")), indent=1))
727 return 2
728 errs = []
729 for k in range(1, d["mips"]):
730 if means[k - 1] is None or means[k] is None:
731 errs.append(None)
732 continue
733 pm = layout["mips"][k - 1]
734 cm = layout["mips"][k]
735 errs.append(round(mean_abs_error(downsample2(means[k - 1], pm["blocks_w"], pm["blocks_h"]),
736 means[k]), 2))
737 control = None
738 if layout["first_tail"] < d["mips"] and decoded[layout["first_tail"] - 1] is not None:
739 tm = layout["mips"][layout["first_tail"]]
740 bad = dict(tm, tile_x=0, tile_y=0)
741 data = detile(layout, bad, tiled[:layout["tile"]])
742 px = decode_pixels(d["format"], data, tm["blocks_w"], tm["blocks_h"])
743 if px is not None:
744 pm = layout["mips"][layout["first_tail"] - 1]
745 control = round(mean_abs_error(
746 downsample2(means[layout["first_tail"] - 1], pm["blocks_w"], pm["blocks_h"]),
747 block_means(px, tm["blocks_w"], tm["blocks_h"])), 2)
748 result = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
749 mips=d["mips"], non_tail=d["non_tail"], first_tail=layout["first_tail"],
750 tile=layout["tile"], chain_error=errs, max_error=max(
751 (e for e in errs if e is not None), default=None),
752 tail_origin_control=control, full_chain=a.get("full_chain"))
753 print(json.dumps(result, indent=1))
754 return 0 if all(e is not None and e <= 6 for e in errs) else 1
755
756
757def dds_bytes(width, height, fmt, mips, linear, payload):
758 hdr = bytearray(128)
759 hdr[0:4] = b"DDS "
760 flags = 0x81007 if mips == 1 else 0xA1007
761 struct.pack_into("<IIIIIII", hdr, 4, 124, flags, height, width, linear, 0, mips)
762 struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
763 struct.pack_into("<II", hdr, 108, 0x1000 if mips == 1 else 0x401008, 0)
764 return bytes(hdr) + struct.pack("<IIIII", fmt, 3, 0, 1, 0) + payload
765
766
767def export(pool, index, out_path, mips=None, force=False):
768 a = analyze(pool, index)
769 if "layout" not in a or "available" not in a:
770 print(f"texture {index}: {a.get('blocked', 'layout unavailable')}", file=sys.stderr)
771 return 2
772 d = a["descriptor"]
773 if d["format"] not in BC_FORMATS:
774 print(f"texture {index}: format {d['format']} is uncompressed; this tool does not "
775 "validate uncompressed tiling, so it will not write a DDS", file=sys.stderr)
776 return 2
777 if not a["full_chain"]:
778 print(f"texture {index}: not every source mip is zlib/raw; refusing to mix BCPack",
779 file=sys.stderr)
780 return 2
781 count = d["mips"] if mips is None else mips
782 if count < 1 or count > d["mips"]:
783 print(f"texture {index}: --mips must be 1..{d['mips']}", file=sys.stderr)
784 return 2
785 layout = a["layout"]
786 cache = {}
787 payload = bytearray()
788 for mip in layout["mips"][:count]:
789 tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache)
790 payload += detile(layout, mip, tiled)
791 if 148 + len(payload) > MAX_OUTPUT:
792 print("DDS exceeds the 256 MiB output limit", file=sys.stderr)
793 return 2
794 if os.path.exists(out_path) and not force:
795 print(f"{out_path} exists; pass --force to replace it", file=sys.stderr)
796 return 2
797 top = layout["mips"][0]
798 linear = (top["blocks_w"] * top["blocks_h"] * layout["element_bytes"]
799 if d["format"] in BC_FORMATS else d["width"] * layout["element_bytes"])
800 with open(out_path, "wb") as f:
801 f.write(dds_bytes(d["width"], d["height"], d["format"], count, linear, payload))
802 print(f"texture {index}: {d['width']}x{d['height']} fmt {d['format']} {count} mips "
803 f"({148 + len(payload)} bytes) -> {out_path}")
804 return 0
805
806
807def main(argv=None):
808 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
809 sub = ap.add_subparsers(dest="cmd", required=True)
810 ps = sub.add_parser("scan", help="aggregate counters over pools")
811 ps.add_argument("paths", nargs="+")
812 ps.add_argument("--json")
813 pl = sub.add_parser("layout", help="descriptor fields and mip offsets")
814 pl.add_argument("pool")
815 pl.add_argument("index", type=int)
816 pc = sub.add_parser("check", help="decode a chain and report downsample error")
817 pc.add_argument("pool")
818 pc.add_argument("index", type=int)
819 pe = sub.add_parser("export", help="write the full zlib/raw chain as DDS")
820 pe.add_argument("pool")
821 pe.add_argument("index", type=int)
822 pe.add_argument("out")
823 pe.add_argument("--mips", type=int)
824 pe.add_argument("--force", action="store_true")
825 a = ap.parse_args(argv)
826 if a.cmd == "scan":
827 pools = []
828 for p in a.paths:
829 pools += find_pools(p)
830 scan_pools(pools, a.json)
831 return 0
832 pool = Pool(a.pool)
833 try:
834 if a.cmd == "layout":
835 print(json.dumps(describe(pool, a.index), indent=1))
836 return 0
837 if a.cmd == "check":
838 return check(pool, a.index)
839 return export(pool, a.index, a.out, a.mips, a.force)
840 finally:
841 pool.close()
842
843
844if __name__ == "__main__":
845 sys.exit(main())
diff --git a/tools/world_census.py b/tools/world_census.py
new file mode 100644
index 000000000..2a59decbb
--- /dev/null
+++ b/tools/world_census.py
@@ -0,0 +1,697 @@
1"""Census every 0x7a map resource in an RPF9 archive, with measured byte coverage.
2
3The archive table of contents is encrypted, but file payloads are zlib streams (and some graphics pages are
4stored raw). This walks the data area in independent byte shards, inflates every stream, validates the 0x7a
5header/schema, and joins the contiguous continuation streams of a split resource. Each shard writes its map
6rows, accepted stream intervals and 0x6 page extents; the merge step counts maps/entities, finds duplicate
7payloads, measures unread bytes, and audits the gaps for a 0x7a signature the walker did not read.
8
9Usage:
10 python -I world_census.py <archive.rpf> [--out DIR] [--shard-size BYTES] [--jobs N]
11 [--start N] [--limit BYTES] [--resume] [--merge-only]
12
13Only aggregate metadata is written: resource offsets/sizes, map/entity counts, extents and content hashes.
14No carved stream, model or texture is kept.
15"""
16from __future__ import annotations
17
18import argparse
19import bisect
20import hashlib
21import json
22import mmap
23import os
24import re
25import struct
26import sys
27import time
28import zlib
29from concurrent.futures import ProcessPoolExecutor, as_completed
30
31_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
32if _TOOLS_DIR not in sys.path:
33 sys.path.insert(0, _TOOLS_DIR)
34
35import world_index as WI
36
37ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]")
38SIG = b"0DRP"
39VERSION = 0x7A
40CAP = 64 << 20
41CHUNK = 1 << 20
42WARMUP = 8 << 20
43JOIN_MAX = 64
44BAND_GAP = 64 << 20
45GAP_CHUNK = 4 << 20
46FORMAT = 3
47
48
49def inflate(m, s, size, max_inflate=CAP, keep=False):
50 """Inflate one zlib stream.
51
52 Returns (data, used, eof, is_meta, inflated, truncated). ``used`` is the stored compressed length;
53 ``inflated`` counts the whole output even when only a 0x7a stream is kept.
54 """
55 d = zlib.decompressobj()
56 chunks = []
57 kept = 0
58 inflated = 0
59 carry = bytearray()
60 decided = False
61 is_meta = False
62 truncated = False
63 p = s
64 while not d.eof and p < size:
65 piece = m[p:p + CHUNK]
66 if not piece:
67 break
68 produced = d.decompress(piece)
69 p += len(piece)
70 inflated += len(produced)
71 if not decided:
72 carry.extend(produced)
73 if len(carry) >= 0x15:
74 decided = True
75 is_meta = bytes(carry[0x10:0x15]) == b"0DRPz"
76 if is_meta or keep:
77 take = bytes(carry[:max(0, max_inflate - kept)])
78 chunks.append(take)
79 kept += len(take)
80 truncated = len(take) < len(carry)
81 carry = None
82 elif is_meta or keep:
83 if kept < max_inflate:
84 take = produced[:max_inflate - kept]
85 chunks.append(take)
86 kept += len(take)
87 truncated = truncated or len(take) < len(produced)
88 elif produced:
89 truncated = True
90 if d.unused_data or d.eof:
91 break
92 if not d.eof:
93 return b"", 0, False, False, inflated, False
94 used = p - s - len(d.unused_data)
95 return b"".join(chunks), used, True, is_meta, inflated, truncated
96
97
98def required_len(b):
99 """Highest system offset (0x5 segment) referenced by a 0x7a resource's tables and blocks."""
100 if len(b) < 0x50 or b[0x10:0x14] != SIG or b[0x14] != VERSION:
101 return 0
102 nst, nen, nbl = struct.unpack_from("<HHH", b, 0x48)
103 if not (1 <= nst <= 4096 and nbl <= 4096 and nen <= 4096) or nbl == 0:
104 return 0
105 need = len(b)
106 for ptr, count, width in ((struct.unpack_from("<Q", b, 0x28)[0], nst, 32),
107 (struct.unpack_from("<Q", b, 0x38)[0], nbl, 16)):
108 if ptr >> 28 != 5:
109 return 0
110 need = max(need, (ptr & 0x0FFFFFFF) + count * width)
111 st = struct.unpack_from("<Q", b, 0x28)[0] & 0x0FFFFFFF
112 if st + 32 * nst > len(b):
113 return need
114 for i in range(nst):
115 o = st + 32 * i
116 count = struct.unpack_from("<H", b, o + 0x1E)[0]
117 table = struct.unpack_from("<Q", b, o + 0x10)[0]
118 if not count:
119 continue
120 if table >> 28 != 5:
121 return 0
122 need = max(need, (table & 0x0FFFFFFF) + 16 * count)
123 it = struct.unpack_from("<Q", b, 0x38)[0] & 0x0FFFFFFF
124 if it + 16 * nbl > len(b):
125 return need
126 for i in range(nbl):
127 o = it + 16 * i
128 size, ptr = struct.unpack_from("<I", b, o + 4)[0], struct.unpack_from("<Q", b, o + 8)[0]
129 if size > (1 << 24):
130 return 0
131 if ptr >> 28 == 5:
132 need = max(need, (ptr & 0x0FFFFFFF) + size)
133 return need
134
135
136def needs_more(b):
137 """True when a 0x7a header points at system data beyond this stream (a split resource)."""
138 return required_len(b) > len(b)
139
140
141def assemble(m, s, size):
142 """Inflate a 0x7a stream and its continuation pages.
143
144 A continuation is normally the next contiguous zlib stream, but a page that does not compress is stored raw.
145 Returns None for a stream that does not end inside the archive. Otherwise a dict with the joined bytes,
146 stored length of the zlib parts, raw continuation length, spans and whether all system pointers resolve.
147 """
148 data, used, eof, is_meta, inflated, truncated = inflate(m, s, size)
149 if not eof:
150 return None
151 out = {"data": data, "used": used, "raw_system": 0, "streams": 1, "pages": 1,
152 "inflated": inflated, "is_meta": is_meta, "truncated": truncated,
153 "spans": [(s, used)], "raw_spans": [], "joined": False, "end": s + used}
154 if not is_meta:
155 return out
156 while out["pages"] < JOIN_MAX:
157 row = WI.parse_resource(out["data"])
158 if row is not None and not needs_more(out["data"]):
159 break
160 if out["truncated"] or out["pages"] >= JOIN_MAX:
161 break
162 nxt = (out["end"] + 15) & ~15
163 if nxt >= size:
164 break
165 if ZHDR.match(m, nxt, size):
166 more, mused, meof, mmeta, minfl, mtrunc = inflate(m, nxt, size, keep=True)
167 if not meof:
168 break
169 if mmeta:
170 # A continuation never starts a second 0x7a resource; this one is truncated.
171 break
172 out["data"] += more
173 out["used"] += mused
174 out["inflated"] += minfl
175 out["streams"] += 1
176 out["pages"] += 1
177 out["joined"] = True
178 out["truncated"] = out["truncated"] or mtrunc
179 out["spans"].append((nxt, mused))
180 out["end"] = nxt + mused
181 continue
182 need = required_len(out["data"])
183 take = need - len(out["data"])
184 if take <= 0 or take > (64 << 20) or nxt + take > size:
185 break
186 extra = m[nxt:nxt + take]
187 if not extra or extra.count(0) == len(extra):
188 break
189 out["data"] += extra
190 out["raw_system"] += take
191 out["pages"] += 1
192 out["joined"] = True
193 out["raw_spans"].append((nxt, take))
194 out["end"] = nxt + take
195 out["complete"] = (not out["truncated"] and WI.parse_resource(out["data"]) is not None
196 and not needs_more(out["data"]))
197 return out
198
199
200def gfx_extent(data):
201 """Return (graphics block count, highest 0x6 offset+size) for a parsed 0x7a resource."""
202 it = WI._ptr(WI._u64(data, 0x38), len(data))
203 count = need = 0
204 for i in range(WI._u16(data, 0x4C) if it is not None else 0):
205 o = it + 16 * i
206 size, ptr = WI._u32(data, o + 4), WI._u64(data, o + 8)
207 if ptr >> 28 == 6:
208 count += 1
209 need = max(need, (ptr & 0x0FFFFFFF) + size)
210 return count, need
211
212
213def has_map_root(data):
214 """True when the resource's schema includes CMapData, even if it has no CEntityDef."""
215 st = WI._ptr(WI._u64(data, 0x28), len(data))
216 return st is not None and any(WI._u32(data, st + 32 * i) == WI.MAPDATA
217 for i in range(WI._u16(data, 0x48)))
218
219
220def inspect_map(data, row, res):
221 """Add the exactness diagnostics and payload hash to a parsed map row."""
222 out = dict(row)
223 out.update({"offset": res["offset"], "size": len(data), "stored": res["used"],
224 "raw_system": res["raw_system"], "inflated": res["inflated"],
225 "streams": res["streams"], "sha1": hashlib.sha1(data).hexdigest(),
226 "system_end": res["end"]})
227 entity_size = out.get("entity_size") or 0
228 it = WI._ptr(WI._u64(data, 0x38), len(data))
229 blocks = WI._u16(data, 0x4C) if it is not None else 0
230 counted = graphics = unresolved = duplicate = gfx = 0
231 gfx_need = 0
232 seen = set()
233 for i in range(blocks):
234 o = it + 16 * i
235 name, size, ptr = WI._u32(data, o), WI._u32(data, o + 4), WI._u64(data, o + 8)
236 hi = ptr >> 28
237 off = ptr & 0x0FFFFFFF
238 key = (name, off, size)
239 if key in seen:
240 duplicate += 1
241 seen.add(key)
242 if name == WI.ENTITY:
243 if hi == 5 and entity_size and size % entity_size == 0 and off + size <= len(data):
244 counted += 1
245 elif hi == 6:
246 graphics += 1
247 else:
248 unresolved += 1
249 elif hi == 6:
250 gfx += 1
251 gfx_need = max(gfx_need, off + size)
252 out.update({"entity_blocks_counted": counted, "entity_blocks_graphics": graphics,
253 "entity_blocks_unresolved": unresolved, "duplicate_blocks": duplicate,
254 "gfx_blocks": gfx, "gfx_need": gfx_need,
255 "exact": graphics == 0 and unresolved == 0 and duplicate == 0})
256 return out
257
258
259def scan_shard(job):
260 """Scan one [start, end) window and write its rows, intervals and stats to outdir."""
261 archive, index, start, end, outdir, data_start = job
262 t0 = time.time()
263 stats = {"streams": 0, "stored": 0, "raw_system": 0, "inflated": 0, "rejected": 0, "meta": 0,
264 "map_meta": 0, "meta_other": 0, "map_meta_bytes": 0,
265 "invalid": 0, "incomplete": 0, "join_max": 0, "entity_gfx": 0,
266 "entity_unresolved": 0, "adopted": 0}
267 rows, intervals, raw_pages, raw_system = [], [], [], []
268 with open(archive, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
269 size = len(m)
270 pos = max(data_start, start - WARMUP)
271 search_end = min(size, end + 16)
272 while pos < search_end:
273 found = ZHDR.search(m, pos, search_end)
274 if not found:
275 break
276 s = found.start()
277 if s >= end:
278 break
279 if s % 16:
280 pos = s + 1
281 continue
282 try:
283 res = assemble(m, s, size)
284 except (zlib.error, struct.error, IndexError):
285 stats["rejected"] += 1
286 pos = s + 1
287 continue
288 if res is None:
289 stats["rejected"] += 1
290 pos = s + 1
291 continue
292 for a, used in res["spans"]:
293 intervals.append([a, a + used])
294 raw_system.extend([a, a + used] for a, used in res["raw_spans"])
295 stats["streams"] += res["streams"]
296 stats["stored"] += res["used"]
297 stats["raw_system"] += res["raw_system"]
298 stats["inflated"] += res["inflated"]
299 pos = res["end"]
300 if pos <= s:
301 pos = s + 1
302 if not res["is_meta"]:
303 continue
304 if not res["complete"]:
305 stats["incomplete"] += 1
306 continue
307 row = WI.parse_resource(res["data"])
308 if row is None:
309 stats["invalid"] += 1
310 continue
311 res["offset"] = s
312 if row["kind"] != "map":
313 stats["meta"] += 1
314 if has_map_root(res["data"]):
315 stats["map_meta"] += 1
316 stats["map_meta_bytes"] += len(res["data"])
317 else:
318 stats["meta_other"] += 1
319 stats["join_max"] = max(stats["join_max"], res["pages"])
320 _, need = gfx_extent(res["data"])
321 if need:
322 raw_pages.append([(res["end"] + 15) & ~15, need])
323 continue
324 maprow = inspect_map(res["data"], row, res)
325 stats["join_max"] = max(stats["join_max"], res["pages"])
326 stats["entity_gfx"] += maprow["entity_blocks_graphics"]
327 stats["entity_unresolved"] += maprow["entity_blocks_unresolved"]
328 if s < start:
329 stats["adopted"] += 1
330 continue
331 rows.append(maprow)
332 if maprow["gfx_need"]:
333 raw_pages.append([(res["end"] + 15) & ~15, maprow["gfx_need"]])
334 rows.sort(key=lambda r: r["offset"])
335 doc = {"index": index, "start": start, "end": end, "archive_size": size,
336 "data_start": data_start, "elapsed": round(time.time() - t0, 3),
337 "complete": True, "format": FORMAT, "stats": stats, "rows": rows,
338 "intervals": intervals, "raw_pages": raw_pages, "raw_system": raw_system,
339 "map_first": rows[0]["offset"] if rows else None,
340 "map_last": rows[-1]["offset"] if rows else None}
341 path = os.path.join(outdir, "shard_%03d_%d_%d.json" % (index, start, end))
342 tmp = path + ".tmp"
343 with open(tmp, "w", encoding="utf-8") as f:
344 json.dump(doc, f, separators=(",", ":"))
345 os.replace(tmp, path)
346 return {"index": index, "start": start, "end": end, "elapsed": doc["elapsed"],
347 "maps": len(rows), "entities": sum(r["entities"] for r in rows), **stats}
348
349
350def _peek_meta(m, s, end):
351 """True when a zlib stream at s inflates to a 0x7a header; used only to audit gaps."""
352 d = zlib.decompressobj()
353 out = bytearray()
354 p = s
355 while len(out) < 0x15 and p < end:
356 piece = m[p:p + 256]
357 if not piece:
358 break
359 try:
360 out.extend(d.decompress(piece))
361 except zlib.error:
362 return False
363 p += len(piece)
364 if d.eof:
365 break
366 return len(out) >= 0x15 and out[0x10:0x15] == b"0DRPz"
367
368
369def classify_gaps(archive, intervals, raw_pages, raw_system, scan_start, scan_end):
370 """Merge accepted stream spans and account for every byte in the scanned range.
371
372 ``raw_pages`` are 0x6 graphics extents and ``raw_system`` are uncompressed system-continuation spans;
373 both are payload of an adjacent resource, not unexplained bytes.
374 """
375 spans = sorted((max(scan_start, a), min(scan_end, b)) for a, b in intervals if b > scan_start and a < scan_end)
376 merged = []
377 for a, b in spans:
378 if a >= b:
379 continue
380 if merged and a <= merged[-1][1]:
381 merged[-1][1] = max(merged[-1][1], b)
382 else:
383 merged.append([a, b])
384 segments = [(a, a + need, "raw_graphics") for a, need in raw_pages]
385 segments += [(a, b, "raw_system") for a, b in raw_system if b > a]
386 segments.sort()
387 starts = [s[0] for s in segments]
388 covered = sum(b - a for a, b in merged)
389 result = {"covered": covered, "raw_graphics": 0, "raw_system": 0, "zero_padding": 0, "unread": 0,
390 "gaps": 0, "unread_sample": [], "raw_0drp": 0,
391 "raw_0drp_offsets": [], "gap_0drp": 0, "gap_0drp_other": 0,
392 "raw_maps": 0, "raw_meta": 0, "missed_zlib_meta": 0,
393 "missed_zlib_offsets": []}
394 with open(archive, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
395 cursor = scan_start
396 bounds = merged + [[scan_end, scan_end]]
397 for a, b in bounds:
398 if cursor < a:
399 result["gaps"] += 1
400 pos = cursor
401 idx = bisect.bisect_left(starts, cursor)
402 while idx < len(segments) and segments[idx][0] < a:
403 s0, s1, kind = segments[idx]
404 start = max(pos, s0)
405 if start > pos:
406 _count_gap(m, pos, start, result)
407 take = max(0, min(s1, a) - start)
408 if take:
409 result[kind] += take
410 _audit_gap(m, start, start + take, result, allow_zlib=True)
411 pos = max(pos, start + take)
412 idx += 1
413 if pos < a:
414 _count_gap(m, pos, a, result)
415 _audit_gap(m, pos, a, result, allow_zlib=True)
416 cursor = max(cursor, b)
417 result["accounted"] = (result["covered"] + result["raw_graphics"] + result["raw_system"]
418 + result["zero_padding"] + result["unread"])
419 result["span"] = scan_end - scan_start
420 result["coverage"] = result["covered"] / result["span"] if result["span"] else 0.0
421 result["accounted_ratio"] = result["accounted"] / result["span"] if result["span"] else 0.0
422 if len(result["unread_sample"]) > 200:
423 result["unread_sample"] = result["unread_sample"][:200]
424 return result
425
426
427def _count_gap(m, a, b, result):
428 if a >= b:
429 return
430 p = a
431 while p < b:
432 piece = m[p:min(b, p + GAP_CHUNK)]
433 if not piece:
434 break
435 zero = piece.count(0)
436 result["zero_padding"] += zero
437 nz = len(piece) - zero
438 if nz:
439 result["unread"] += nz
440 if len(result["unread_sample"]) < 200:
441 i = next(k for k, c in enumerate(piece) if c)
442 result["unread_sample"].append([p + i, nz])
443 p += len(piece)
444
445
446def _audit_gap(m, a, b, result, allow_zlib):
447 """Search an unread gap for a 0x7a signature or an unaligned zlib stream that hides one."""
448 if a >= b:
449 return
450 p = a
451 while p < b:
452 piece = m[p:min(b, p + GAP_CHUNK)]
453 if not piece:
454 break
455 q = 0
456 while True:
457 i = piece.find(SIG, q)
458 if i < 0:
459 break
460 at = p + i
461 if at + 5 <= b and piece[i + 4] == VERSION:
462 result["gap_0drp"] += 1
463 start = at - 0x10
464 if start >= 0:
465 head = m[start:start + 0x18]
466 if len(head) == 0x18 and head[:8] == b"\0" * 8 and (struct.unpack_from("<Q", head, 8)[0] >> 28) == 5:
467 row = WI.parse_resource(m[start:start + CAP])
468 if row is not None:
469 if row.get("kind") == "map":
470 result["raw_maps"] += 1
471 else:
472 result["raw_meta"] += 1
473 result["raw_0drp"] += 1
474 if len(result["raw_0drp_offsets"]) < 50:
475 result["raw_0drp_offsets"].append(at)
476 else:
477 result["gap_0drp_other"] += 1
478 else:
479 result["gap_0drp_other"] += 1
480 q = i + 1
481 if allow_zlib:
482 q = 0
483 while True:
484 mt = ZHDR.search(piece, q)
485 if not mt:
486 break
487 at = p + mt.start()
488 if at % 16:
489 if at + 5 <= b and _peek_meta(m, at, b):
490 result["missed_zlib_meta"] += 1
491 if len(result["missed_zlib_offsets"]) < 50:
492 result["missed_zlib_offsets"].append(at)
493 q = mt.start() + 1
494 p += len(piece)
495
496
497def _expected_shards(start, end, shard_size):
498 out = []
499 index = 0
500 pos = start
501 while pos < end:
502 stop = min(end, pos + shard_size)
503 out.append({"index": index, "start": pos, "end": stop})
504 index += 1
505 pos = stop
506 return out
507
508
509def _shard_path(outdir, want):
510 return os.path.join(outdir, "shard_%03d_%d_%d.json" % (want["index"], want["start"], want["end"]))
511
512
513def _shard_ok(path, want):
514 try:
515 with open(path, encoding="utf-8") as f:
516 doc = json.load(f)
517 except (OSError, ValueError):
518 return False
519 return (doc.get("format") == FORMAT and doc.get("start") == want["start"]
520 and doc.get("end") == want["end"] and doc.get("complete") is True)
521
522
523def _load_shards(outdir, expected):
524 docs = {}
525 for want in expected:
526 path = _shard_path(outdir, want)
527 if _shard_ok(path, want):
528 with open(path, encoding="utf-8") as f:
529 docs[want["index"]] = json.load(f)
530 return docs
531
532
533def _duplicates(rows):
534 by_hash = {}
535 for r in rows:
536 by_hash.setdefault(r["sha1"], []).append(r)
537 groups = [v for v in by_hash.values() if len(v) > 1]
538 extra = sum(len(v) - 1 for v in groups)
539 extra_entities = sum(sum(x["entities"] for x in v[1:]) for v in groups)
540 by_name = {}
541 for r in rows:
542 if r.get("map_name"):
543 by_name.setdefault(r["map_name"], []).append(r)
544 ngroups = [v for v in by_name.values() if len(v) > 1]
545 return {"content_groups": len(groups), "content_extra_maps": extra,
546 "content_extra_entities": extra_entities,
547 "content_group_sample": [[v[0]["map_name"], len(v)] for v in groups[:20]],
548 "name_groups": len(ngroups), "name_extra_maps": sum(len(v) - 1 for v in ngroups)}
549
550
551def _bands(rows):
552 bands = []
553 for r in sorted(rows, key=lambda x: x["offset"]):
554 if bands and r["offset"] - bands[-1]["last_end"] <= BAND_GAP:
555 bands[-1]["last_end"] = max(bands[-1]["last_end"], r["offset"] + r["stored"])
556 bands[-1]["maps"] += 1
557 bands[-1]["entities"] += r["entities"]
558 else:
559 bands.append({"first": r["offset"], "last_end": r["offset"] + r["stored"],
560 "maps": 1, "entities": r["entities"]})
561 return bands
562
563
564def summarize(archive, outdir, start, end, shard_size, data_start):
565 expected = _expected_shards(start, end, shard_size)
566 docs = _load_shards(outdir, expected)
567 missing = [w for w in expected if w["index"] not in docs]
568 rows, intervals, raw_pages, raw_system = [], [], [], []
569 totals = {"streams": 0, "stored": 0, "raw_system": 0, "inflated": 0, "rejected": 0, "meta": 0,
570 "map_meta": 0, "meta_other": 0, "map_meta_bytes": 0,
571 "invalid": 0, "incomplete": 0, "join_max": 0, "entity_gfx": 0,
572 "entity_unresolved": 0, "adopted": 0}
573 shards = []
574 for want in expected:
575 doc = docs.get(want["index"])
576 if doc is None:
577 shards.append({**want, "present": False})
578 continue
579 shards.append({"index": want["index"], "start": want["start"], "end": want["end"],
580 "present": True, "elapsed": doc.get("elapsed"),
581 "maps": len(doc.get("rows", [])),
582 "entities": sum(r["entities"] for r in doc.get("rows", [])),
583 "map_first": doc.get("map_first"), "map_last": doc.get("map_last"),
584 "stats": doc.get("stats", {})})
585 rows.extend(doc.get("rows", []))
586 intervals.extend(doc.get("intervals", []))
587 raw_pages.extend(doc.get("raw_pages", []))
588 raw_system.extend(doc.get("raw_system", []))
589 for k in totals:
590 if k == "join_max":
591 totals[k] = max(totals[k], doc.get("stats", {}).get(k, 0))
592 else:
593 totals[k] += doc.get("stats", {}).get(k, 0)
594 seen = set()
595 unique = []
596 duplicate_offsets = 0
597 for r in sorted(rows, key=lambda x: x["offset"]):
598 if r["offset"] in seen:
599 duplicate_offsets += 1
600 continue
601 seen.add(r["offset"])
602 unique.append(r)
603 rows = unique
604 gaps = classify_gaps(archive, intervals, raw_pages, raw_system, start, end)
605 exact_maps = sum(1 for r in rows if r.get("exact"))
606 exact_entities = sum(r["entities"] for r in rows if r.get("exact"))
607 summary = {
608 "archive": os.path.abspath(archive), "archive_size": os.path.getsize(archive),
609 "data_start": data_start, "scan_start": start, "scan_end": end,
610 "span": end - start, "shards_expected": len(expected), "shards_complete": len(docs),
611 "complete": not missing, "missing_ranges": [[m["start"], m["end"]] for m in missing],
612 "elapsed_shard_sum": round(sum(d.get("elapsed", 0) for d in docs.values()), 3),
613 "maps": len(rows), "maps_exact": exact_maps,
614 "entities": sum(r["entities"] for r in rows),
615 "entities_exact": exact_entities,
616 "duplicate_offsets": duplicate_offsets,
617 "map_first": rows[0]["offset"] if rows else None,
618 "map_last": rows[-1]["offset"] if rows else None,
619 "totals": totals, "duplicates": _duplicates(rows),
620 "bands": _bands(rows), "coverage": gaps, "shards": shards,
621 }
622 summary["census_exact"] = (summary["complete"] and summary["maps_exact"] == summary["maps"]
623 and totals["entity_gfx"] == 0 and totals["entity_unresolved"] == 0
624 and gaps["raw_maps"] == 0 and gaps["missed_zlib_meta"] == 0)
625 return summary
626
627
628def main(argv=None):
629 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
630 ap.add_argument("archive")
631 ap.add_argument("--out", default=os.path.join("work", "world", "census"))
632 ap.add_argument("--shard-size", type=int, default=2 << 30)
633 ap.add_argument("--jobs", type=int, default=max(1, min(12, (os.cpu_count() or 2) // 2)))
634 ap.add_argument("--start", type=int)
635 ap.add_argument("--limit", type=int)
636 ap.add_argument("--resume", action="store_true")
637 ap.add_argument("--merge-only", action="store_true")
638 a = ap.parse_args(argv)
639 with open(a.archive, "rb") as f:
640 head = f.read(8)
641 if head[:4] != b"9FPR":
642 print("not an RPF9 archive", file=sys.stderr)
643 return 2
644 data_start = struct.unpack_from("<I", head, 4)[0]
645 size = os.path.getsize(a.archive)
646 start = a.start if a.start is not None else data_start
647 end = min(size, start + a.limit) if a.limit else size
648 if start < data_start or start >= end:
649 print("bad scan range", file=sys.stderr)
650 return 2
651 os.makedirs(a.out, exist_ok=True)
652 expected = _expected_shards(start, end, a.shard_size)
653 t0 = time.time()
654 if not a.merge_only:
655 jobs = []
656 for want in expected:
657 path = _shard_path(a.out, want)
658 if a.resume and _shard_ok(path, want):
659 continue
660 jobs.append((a.archive, want["index"], want["start"], want["end"], a.out, data_start))
661 print("census: %d shards, %d to scan, %d jobs, %.2f GiB" %
662 (len(expected), len(jobs), a.jobs, (end - start) / (1 << 30)), flush=True)
663 failures = 0
664 with ProcessPoolExecutor(max_workers=a.jobs) as ex:
665 futures = {ex.submit(scan_shard, job): job for job in jobs}
666 for done, fut in enumerate(as_completed(futures), 1):
667 job = futures[fut]
668 try:
669 r = fut.result()
670 except Exception as e: # keep completed shards; the rerun resumes them
671 failures += 1
672 print("[%d/%d] shard %d FAILED: %r" % (done, len(jobs), job[1], e), flush=True)
673 continue
674 print("[%d/%d] shard %03d %d..%d maps=%d entities=%d %.1fs" %
675 (done, len(jobs), r["index"], r["start"], r["end"], r["maps"],
676 r["entities"], r["elapsed"]), flush=True)
677 if failures:
678 print("%d shard(s) failed; writing the completed coverage" % failures, flush=True)
679 summary = summarize(a.archive, a.out, start, end, a.shard_size, data_start)
680 summary["elapsed"] = round(time.time() - t0, 3)
681 with open(os.path.join(a.out, "summary.json"), "w", encoding="utf-8") as f:
682 json.dump(summary, f, indent=1, sort_keys=True)
683 with open(os.path.join(a.out, "maps.json"), "w", encoding="utf-8") as f:
684 json.dump({"summary": {k: summary[k] for k in
685 ("maps", "maps_exact", "entities", "entities_exact", "scan_start",
686 "scan_end", "complete", "census_exact")},
687 "maps": [r for d in _load_shards(a.out, expected).values() for r in d.get("rows", [])]},
688 f, indent=1, sort_keys=True)
689 print(json.dumps({k: summary[k] for k in
690 ("maps", "maps_exact", "entities", "entities_exact", "complete", "census_exact",
691 "shards_complete", "shards_expected", "elapsed", "coverage", "duplicates")},
692 indent=1), flush=True)
693 return 0 if summary["complete"] else 1
694
695
696if __name__ == "__main__":
697 sys.exit(main())