beta-amd v12 on Linux/Proton, RX 9070 XT: 6 ray-traced shadow pipelines never finish compiling, frames stuck at ~550 ms; faces wrong, scene very dark #120

Open
opened 2026-11-27 10:57:10 +00:00 by Exorion1er · 25 comments
Exorion1er commented 2026-11-27 10:57:10 +00:00 (Migrated from github.com)
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by Exorion1er on 2026-11-27T10:57:10Z.


Summary

Test run of beta-amd at 84a4f67 ("AMD beta v12") under Proton, code unmodified. It boots and plays the opening cutscene. It runs at about 1.8 fps (one frame every ~550 ms) the whole time and does not get better. Faces are deformed, the scene is so dark it is barely visible, and reflections look right.

The log points at one cause for most of the frame time. Six ray-traced shadow compute pipelines stay "compiling" for the whole session (192 s and counting when I stopped), and every frame seems to wait out VICTORY_PIPELINE_WAIT_MS=500 for them before dropping the draws.

Linux/Proton isn't a target of this build, so take it as a data point.

System and build

  • AMD Radeon RX 9070 XT (RADV GFX1201), Ryzen 7 9800X3D, 62 GB RAM
  • Fedora 44, kernel 7.3.5, KDE Plasma (Wayland)
  • Mesa 26.2.7 (Fedora package). Run 2 used a local Mesa 26.2.7 build with one RADV memory-model fix (see notes)
  • GE-Proton11-12 with its bundled vkd3d-proton, VKD3D_CONFIG=descriptor_heap, Microsoft d3dcompiler_47.dll beside victory.exe
  • beta-amd 84a4f67, cargo build --locked --profile diag -p victory --features diagnostics, cross-built for x86_64-pc-windows-msvc (lld-link + xwin), no other changes
  • Series X profile, output 2560x1440
  • Settings: play.ps1's $set exported as-is by a shell wrapper, plus VICTORY_PROBE_RAYS=1 when ray tracing is off. Shaders were translated ahead with victory.exe shaders shaders.rpf (25,689 in the cache, 200 do not translate, 69 s)

Runs

Run 1 Run 2
Ray tracing off (PROBE_RAYS=1) on (VICTORY_BVH_BUILDER=1)
Extra — KLBF_AMBIENT_EST=1, local RADV fix, LD_PRELOAD shim for Wine section memory
Length 2 min (capped) ~5 min, opening cutscene
Frame time in 3D ~390 ms (2.6 fps) 550 ms (1.8 fps), flat for 3+ min
Pipelines stuck 3 6
Faces deformed deformed
Lighting pitch black very dark, barely visible
Reflections wrong right
Crash / device loss none none

The stuck pipelines (run 2, after 3 min in the cutscene)

pipelines pending: 6 distinct (6 asked for by a draw; oldest 192 s), failed since the start: 0,
made in the last 2.0 frames: 0, workers busy 6 of 12
  CS_LaserLightShadowRaytracing_c3ab3042                                  5.0/frame, compiling, pending for 192 s
  CS_RTDistantShadowTrace32_Tiled_d6296256                                5.0/frame, compiling, pending for 192 s
  CS_RTDistantShadowTraceTemporalUpsample4X32_Tiled_d6296256              5.0/frame, compiling, pending for 192 s
  CS_RTDistantShadowTraceLeakPlug32_Tiled_d6296256                        5.0/frame, compiling, pending for 192 s
  CS_RTDistantShadowTraceLeakPlugTemporalUpsample4X32_Tiled_d6296256      5.0/frame, compiling, pending for 192 s
  CS_TraceShadowRays_Checkerboard_c568be8a                                5.0/frame, compiling, pending for 188 s

Run 1 (ray tracing off) had three of the same programs stuck for 98 s (LaserLightShadowRaytracing and the two DistantShadowTrace TemporalUpsample variants).

Frame line from the same moment:

1.8 fps, 552.1 ms/frame (41.1 preparing: copies 27.1 ms 56.8 MB, textures 0.4 ms 8.3 MB; 0.0 on the GPU;
6.0 copying back 2.1 MB), 4958 draws/frame, dropped 1 without a host pipeline (6 being made) and 5 indirect

Only about 41 ms of the 552 is preparing work. The rest fits one 500 ms pipeline wait per frame. Fps over the run: 30 in menus and videos, then 1.7–2.6 from the first 3D frame on.

Notes

  • I think these six are the same programs where, in another VIctory tree, I saw vkd3d-proton's dxil-spirv recurse forever on lane reads (v_readlane) inside branches: the pipeline never finishes building. Mirroring the read-lane VGPRs through LDS in the translator got all six to build there. I haven't checked this here, so it's a lead only. On Windows the native driver compiles the DXIL, so this would be Linux-only.
  • The local RADV fix in run 2 is for image loads not being made coherent under vkd3d-proton's descriptor heaps (stale L0 reads across CUs in WGP mode). In the other tree it fixed mouths. Here faces were still wrong with it.
  • Logs are 5–7 MB each. I can attach a trimmed one if that helps.
<!-- greyfinch-sync:PastiiJay/klbf-lab:issue:6645050740 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120). Originally posted by [Exorion1er](https://github.com/Exorion1er) on 2026-11-27T10:57:10Z. --- ## Summary Test run of `beta-amd` at `84a4f67` ("AMD beta v12") under Proton, **code unmodified**. It boots and plays the opening cutscene. It runs at about 1.8 fps (one frame every ~550 ms) the whole time and does not get better. Faces are deformed, the scene is so dark it is barely visible, and reflections look right. The log points at one cause for most of the frame time. Six ray-traced shadow compute pipelines stay "compiling" for the whole session (192 s and counting when I stopped), and every frame seems to wait out `VICTORY_PIPELINE_WAIT_MS=500` for them before dropping the draws. Linux/Proton isn't a target of this build, so take it as a data point. ## System and build - AMD Radeon RX 9070 XT (RADV GFX1201), Ryzen 7 9800X3D, 62 GB RAM - Fedora 44, kernel 7.3.5, KDE Plasma (Wayland) - Mesa 26.2.7 (Fedora package). Run 2 used a local Mesa 26.2.7 build with one RADV memory-model fix (see notes) - GE-Proton11-12 with its bundled vkd3d-proton, `VKD3D_CONFIG=descriptor_heap`, Microsoft `d3dcompiler_47.dll` beside `victory.exe` - `beta-amd` `84a4f67`, `cargo build --locked --profile diag -p victory --features diagnostics`, cross-built for `x86_64-pc-windows-msvc` (lld-link + xwin), no other changes - Series X profile, output 2560x1440 - Settings: `play.ps1`'s `$set` exported as-is by a shell wrapper, plus `VICTORY_PROBE_RAYS=1` when ray tracing is off. Shaders were translated ahead with `victory.exe shaders shaders.rpf` (25,689 in the cache, 200 do not translate, 69 s) ## Runs | | Run 1 | Run 2 | |---|---|---| | Ray tracing | off (`PROBE_RAYS=1`) | on (`VICTORY_BVH_BUILDER=1`) | | Extra | — | `KLBF_AMBIENT_EST=1`, local RADV fix, LD_PRELOAD shim for Wine section memory | | Length | 2 min (capped) | ~5 min, opening cutscene | | Frame time in 3D | ~390 ms (2.6 fps) | 550 ms (1.8 fps), flat for 3+ min | | Pipelines stuck | 3 | 6 | | Faces | deformed | deformed | | Lighting | pitch black | very dark, barely visible | | Reflections | wrong | right | | Crash / device loss | none | none | ## The stuck pipelines (run 2, after 3 min in the cutscene) ``` pipelines pending: 6 distinct (6 asked for by a draw; oldest 192 s), failed since the start: 0, made in the last 2.0 frames: 0, workers busy 6 of 12 CS_LaserLightShadowRaytracing_c3ab3042 5.0/frame, compiling, pending for 192 s CS_RTDistantShadowTrace32_Tiled_d6296256 5.0/frame, compiling, pending for 192 s CS_RTDistantShadowTraceTemporalUpsample4X32_Tiled_d6296256 5.0/frame, compiling, pending for 192 s CS_RTDistantShadowTraceLeakPlug32_Tiled_d6296256 5.0/frame, compiling, pending for 192 s CS_RTDistantShadowTraceLeakPlugTemporalUpsample4X32_Tiled_d6296256 5.0/frame, compiling, pending for 192 s CS_TraceShadowRays_Checkerboard_c568be8a 5.0/frame, compiling, pending for 188 s ``` Run 1 (ray tracing off) had three of the same programs stuck for 98 s (LaserLightShadowRaytracing and the two DistantShadowTrace TemporalUpsample variants). Frame line from the same moment: ``` 1.8 fps, 552.1 ms/frame (41.1 preparing: copies 27.1 ms 56.8 MB, textures 0.4 ms 8.3 MB; 0.0 on the GPU; 6.0 copying back 2.1 MB), 4958 draws/frame, dropped 1 without a host pipeline (6 being made) and 5 indirect ``` Only about 41 ms of the 552 is preparing work. The rest fits one 500 ms pipeline wait per frame. Fps over the run: 30 in menus and videos, then 1.7–2.6 from the first 3D frame on. ## Notes - I think these six are the same programs where, in another VIctory tree, I saw vkd3d-proton's dxil-spirv recurse forever on lane reads (`v_readlane`) inside branches: the pipeline never finishes building. Mirroring the read-lane VGPRs through LDS in the translator got all six to build there. I haven't checked this here, so it's a lead only. On Windows the native driver compiles the DXIL, so this would be Linux-only. - The local RADV fix in run 2 is for image loads not being made coherent under vkd3d-proton's descriptor heaps (stale L0 reads across CUs in WGP mode). In the other tree it fixed mouths. Here faces were still wrong with it. - Logs are 5–7 MB each. I can attach a trimmed one if that helps.
PastiiJay commented 2026-11-27 11:27:11 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T11:27:11Z.


Thanks @Exorion1er, this is a precise report: the six ray-traced shadow pipelines still "compiling" after 192 s, with the 500 ms wait on every frame, is exactly what we needed to see. Could you attach the full console log from run 2, with the KLBF_AMBIENT_EST line included?

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7217090611 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7217090611). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T11:27:11Z. --- Thanks @Exorion1er, this is a precise report: the six ray-traced shadow pipelines still "compiling" after 192 s, with the 500 ms wait on every frame, is exactly what we needed to see. Could you attach the full console log from run 2, with the `KLBF_AMBIENT_EST` line included?
PastiiJay commented 2026-11-27 11:30:22 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T11:30:22Z.


thanks, that log nailed it: a pipeline that never gets made took the whole 500 ms wait budget of every frame. A fix is written (a pipeline is waited for 5 s in all, then its draws are dropped until it's ready) and goes into the next beta. Meanwhile -More @{ VICTORY_PIPELINE_WAIT_MS = '0' } should give you the frame rate back.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7217151946 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7217151946). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T11:30:22Z. --- thanks, that log nailed it: a pipeline that never gets made took the whole 500 ms wait budget of every frame. A fix is written (a pipeline is waited for 5 s in all, then its draws are dropped until it's ready) and goes into the next beta. Meanwhile `-More @{ VICTORY_PIPELINE_WAIT_MS = '0' }` should give you the frame rate back.
PastiiJay commented 2026-11-27 13:01:01 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T13:01:01Z.


Thanks @Exorion1er, you're credited in the Quick fixes table in the README.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7218953979 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7218953979). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T13:01:01Z. --- Thanks @Exorion1er, you're credited in the Quick fixes table in the README.
PastiiJay commented 2026-11-27 13:20:00 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T13:20:00Z.


Thanks for the report. One thing to check first: the game needs its shaders prepared before the first start. Without that step they are translated during play, which can cause missing objects, wrong faces and stutter.

Could you run .\scripts\play-scarlett.ps1 -OnlyPrecompile once, wait for it to finish, then start the game normally? Also check that -NoPrecompile is not in your launch settings.

If it still happens after that, please post the output of the run so we can see where it goes wrong.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7219348593 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7219348593). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T13:20:00Z. --- Thanks for the report. One thing to check first: the game needs its shaders prepared before the first start. Without that step they are translated during play, which can cause missing objects, wrong faces and stutter. Could you run `.\scripts\play-scarlett.ps1 -OnlyPrecompile` once, wait for it to finish, then start the game normally? Also check that `-NoPrecompile` is not in your launch settings. If it still happens after that, please post the output of the run so we can see where it goes wrong.
PastiiJay commented 2026-11-27 13:22:57 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T13:22:57Z.


The fix is out on stable and beta-amd (4c79ac5): a pipeline that never gets made is now waited for 5 s in all, then its draws are skipped until it's ready, instead of 500 ms of every frame. Played on Windows with nothing missing from the picture. Could you pull and run once on Proton without the VICTORY_PIPELINE_WAIT_MS = '0' workaround and tell us the frame rate?

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7219408542 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7219408542). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T13:22:57Z. --- The fix is out on `stable` and `beta-amd` (4c79ac5): a pipeline that never gets made is now waited for 5 s in all, then its draws are skipped until it's ready, instead of 500 ms of every frame. Played on Windows with nothing missing from the picture. Could you pull and run once on Proton without the `VICTORY_PIPELINE_WAIT_MS = '0'` workaround and tell us the frame rate?
PastiiJay commented 2026-11-27 13:28:20 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T13:28:20Z.


@Exorion1er New stable v12 is up (stable branch, 4c79ac5): bench fix for slower cards (the opening fade no longer counts as black frames), Linux fix for the 2 fps stall, quick-fix table in the README. If you tested before, please re-test, and before any bench or comparison: start the game once and let it translate the shaders (a few minutes, automatic), then play about 10 minutes so the effects are built. Otherwise they compile during the run and the figures aren't comparable. Results with the bench card on github.com/PastiiJay/klbf-lab 🙏

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7219517982 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7219517982). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T13:28:20Z. --- @Exorion1er New stable v12 is up (`stable` branch, 4c79ac5): bench fix for slower cards (the opening fade no longer counts as black frames), Linux fix for the 2 fps stall, quick-fix table in the README. If you tested before, please re-test, and before any bench or comparison: start the game once and let it translate the shaders (a few minutes, automatic), then play about 10 minutes so the effects are built. Otherwise they compile during the run and the figures aren't comparable. Results with the bench card on github.com/PastiiJay/klbf-lab 🙏
HandshakeHackin commented 2026-11-27 13:37:39 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by HandshakeHackin on 2026-11-27T13:37:39Z.


I ran the unmodified wait path from stable 4c79ac5 on Windows with one pipeline deliberately left unresolved for 12 consecutive frames. At defaults, the cumulative charge reached 5,000 ms on frame 10 and stayed at 5,000 on frames 11 and 12. The zero-frame-wait workaround charged 0 on all 12. With the lifetime cap disabled and a 10 ms frame budget it charged 10 ms each frame.

One nuance for custom settings: a 3 ms lifetime cap with a 100 ms frame budget charged 100 ms once, then stopped. The cap is checked before the wait, so the last wait can overshoot. Four isolated Windows test runs and per-frame counters. This verifies the wait logic; the RX 9070 XT Proton retest is still needed for an in-game FPS figure.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7219732528 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7219732528). Originally posted by [HandshakeHackin](https://github.com/HandshakeHackin) on 2026-11-27T13:37:39Z. --- I ran the unmodified wait path from stable `4c79ac5` on Windows with one pipeline deliberately left unresolved for 12 consecutive frames. At defaults, the cumulative charge reached 5,000 ms on frame 10 and stayed at 5,000 on frames 11 and 12. The zero-frame-wait workaround charged 0 on all 12. With the lifetime cap disabled and a 10 ms frame budget it charged 10 ms each frame. One nuance for custom settings: a 3 ms lifetime cap with a 100 ms frame budget charged 100 ms once, then stopped. The cap is checked before the wait, so the last wait can overshoot. [Four isolated Windows test runs and per-frame counters](https://github.com/HandshakeHackin/klbf-lab/actions/runs/46008087076/job/140536253615). This verifies the wait logic; the RX 9070 XT Proton retest is still needed for an in-game FPS figure.
PastiiJay commented 2026-11-27 14:16:52 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T14:16:52Z.


Thanks @HandshakeHackin, frame-by-frame numbers like these make the wait logic easy to trust. @Exorion1er, the last missing piece is yours: one run on stable 4c79ac5 under Proton, to see whether the frame rate recovers once those six pipelines stop eating the budget.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7220582270 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7220582270). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T14:16:52Z. --- Thanks @HandshakeHackin, frame-by-frame numbers like these make the wait logic easy to trust. @Exorion1er, the last missing piece is yours: one run on stable `4c79ac5` under Proton, to see whether the frame rate recovers once those six pipelines stop eating the budget.
diafebus commented 2026-11-27 22:23:37 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-27T22:23:37Z.


RX 6950 XT on Proton renders 3D with the Belobug helper shader changes

On Linux with an RX 6950 XT (RDNA2), RADV NAVI21, and GE-Proton 11-14, our initial KLBF v12 runs showed menus and subtitles while the 3D scene stayed black. A local Belobug shader build displayed 3D. We ported its helper shader changes to KLBF v12-stable (4c79ac5272), which then displayed outdoor geometry, characters, and the prison interior.

Changes to reproduce

  • Parse the helper HLSL root signature declarations and serialize the D3D12 signatures on the host. In our earlier helper diagnostics, creating a root signature from the Wine-compiled shader blob failed with E_FAIL, while host serialization succeeded.
  • Carry over the paired HLSL changes for card compare and indirect execution, including the structured UAV accesses in the hash and clamp shaders. The KLBF port also uses the host serializer for the compositor, ambient and other matching helpers. KLBF v12 lacks Belobug's lightprobe module.
  • Use the successful launcher configuration for the initial comparison. It used descriptor_heap, feature level 12_1, KLBF's bundled Agility SDK, and Wine overrides d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b. The run used a copy of an existing Player save.

We observed this on one RDNA2 system with the combined patch and launch configuration. We did not isolate which changes are required, and our earlier KLBF runs did not use the same DXGI override.

Observed result

Patched KLBF showed a third person character, trees, grass and distant lights outdoors. The overlay showed 1.5 FPS in the captured outdoor frame and 5.9 FPS in a captured prison window frame. The tester briefly saw 16 FPS. These are snapshots. Lucia's eyes and mouth rendered while the facial surface was missing, and some scenes remained very dark.

Local KLBF candidate executable SHA-256
253a71856840f010469aa83038e4db769a3a31c743773f2921e37b2857c6802a

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7229290209 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7229290209). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-27T22:23:37Z. --- # RX 6950 XT on Proton renders 3D with the Belobug helper shader changes On Linux with an RX 6950 XT (RDNA2), RADV NAVI21, and GE-Proton 11-14, our initial KLBF v12 runs showed menus and subtitles while the 3D scene stayed black. A local Belobug shader build displayed 3D. We ported its helper shader changes to KLBF v12-stable (4c79ac52728f29163a4bad807911838a9f1c9774), which then displayed outdoor geometry, characters, and the prison interior. ## Changes to reproduce - Parse the helper HLSL root signature declarations and serialize the D3D12 signatures on the host. In our earlier helper diagnostics, creating a root signature from the Wine-compiled shader blob failed with E_FAIL, while host serialization succeeded. - Carry over the paired HLSL changes for card compare and indirect execution, including the structured UAV accesses in the hash and clamp shaders. The KLBF port also uses the host serializer for the compositor, ambient and other matching helpers. KLBF v12 lacks Belobug's lightprobe module. - Use the successful launcher configuration for the initial comparison. It used descriptor_heap, feature level 12_1, KLBF's bundled Agility SDK, and Wine overrides d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b. The run used a copy of an existing Player save. We observed this on one RDNA2 system with the combined patch and launch configuration. We did not isolate which changes are required, and our earlier KLBF runs did not use the same DXGI override. ## Observed result Patched KLBF showed a third person character, trees, grass and distant lights outdoors. The overlay showed 1.5 FPS in the captured outdoor frame and 5.9 FPS in a captured prison window frame. The tester briefly saw 16 FPS. These are snapshots. Lucia's eyes and mouth rendered while the facial surface was missing, and some scenes remained very dark. Local KLBF candidate executable SHA-256 253a71856840f010469aa83038e4db769a3a31c743773f2921e37b2857c6802a
PastiiJay commented 2026-11-27 22:29:16 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-27T22:29:16Z.


Thanks, getting 3D on RDNA 2 under Proton is a real step. The host-side root signature serialization is the part we want to look at first. Could you push your patched branch (on top of 4c79ac5) to a fork and link it here? That way we can test each change on its own and credit you for the ones that matter.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7229368383 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7229368383). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-27T22:29:16Z. --- Thanks, getting 3D on RDNA 2 under Proton is a real step. The host-side root signature serialization is the part we want to look at first. Could you push your patched branch (on top of 4c79ac5) to a fork and link it here? That way we can test each change on its own and credit you for the ones that matter.
diafebus commented 2026-11-28 09:48:44 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T09:48:44Z.


Here is the source branch for the first KLBF build that rendered 3D in our RX 6950 XT run: diff against 4c79ac5 · branch. It contains the Belobug-derived rendering port before our later performance and texture experiments.

For isolation, start with crates/victory-gpu/src/rootstring.rs and the call sites that serialize the helper root signatures on the host. An earlier helper diagnostic returned E_FAIL when creating the signature from the Wine-compiled blob, while host serialization succeeded. The branch also changes helper HLSL resource access, including the indirect clamp and card compare. A useful comparison is base → host serialization only → complete branch, with the same launch environment and scene at each step. Check helper initialization and whether geometry appears before comparing FPS.

Our successful configuration was RX 6950 XT / RADV NAVI21 / GE-Proton 11-14 with KLBF's bundled Agility SDK, VKD3D_CONFIG=descriptor_heap, feature level 12_1, and WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b". Outdoor geometry and characters and the prison interior appeared with the combined port. Some scenes were still dark and Lucia's facial surface was missing. The earlier black-world run used a different DXGI override, so serialization alone and applicability across RDNA2 remain open.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7237482162 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237482162). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T09:48:44Z. --- Here is the source branch for the first KLBF build that rendered 3D in our RX 6950 XT run: [diff against `4c79ac5`](https://github.com/PastiiJay/klbf-lab/compare/4c79ac5...diafebus:klbf-lab:rdna2-proton-helper-render) · [branch](https://github.com/diafebus/klbf-lab/tree/rdna2-proton-helper-render). It contains the Belobug-derived rendering port before our later performance and texture experiments. For isolation, start with `crates/victory-gpu/src/rootstring.rs` and the call sites that serialize the helper root signatures on the host. An earlier helper diagnostic returned `E_FAIL` when creating the signature from the Wine-compiled blob, while host serialization succeeded. The branch also changes helper HLSL resource access, including the indirect clamp and card compare. A useful comparison is base → host serialization only → complete branch, with the same launch environment and scene at each step. Check helper initialization and whether geometry appears before comparing FPS. Our successful configuration was RX 6950 XT / RADV NAVI21 / GE-Proton 11-14 with KLBF's bundled Agility SDK, `VKD3D_CONFIG=descriptor_heap`, feature level 12_1, and `WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b"`. Outdoor geometry and characters and the prison interior appeared with the combined port. Some scenes were still dark and Lucia's facial surface was missing. The earlier black-world run used a different DXGI override, so serialization alone and applicability across RDNA2 remain open.
diafebus commented 2026-11-28 10:08:11 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T10:08:11Z.


The source branch is now available for review as PR #152 against stable: https://github.com/PastiiJay/klbf-lab/pull/152.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7237694543 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237694543). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T10:08:11Z. --- The source branch is now available for review as PR #152 against stable: https://github.com/PastiiJay/klbf-lab/pull/152.
diafebus commented 2026-11-28 10:09:04 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T10:09:04Z.


RDNA2 Proton source patch, part 1 of 2, against 4c79ac5. Save both diff blocks as patch files and apply them together with git apply 1.patch 2.patch. The launch settings and evidence are in the reproduction note.

diff --git a/crates/victory-gpu/src/rootstring.rs b/crates/victory-gpu/src/rootstring.rs
new file mode 100644
index 0000000..cbc2e8a
--- /dev/null
+++ b/crates/victory-gpu/src/rootstring.rs
@@ -0,0 +1,797 @@
+//! Root signatures for the shaders we compile ourselves: read from the
+//! `RS` string in the HLSL (`#define RS "..."`) and serialized from a
+//! description built from it, not taken out of the compiled blob. Under
+//! Wine the host refuses the embedded signature of the blob its compiler
+//! returns (E_FAIL), while a description we serialize ourselves works, as
+//! the title's own signatures do. Reading the string from the same source
+//! the shaders were compiled from keeps the description and what the
+//! shaders expect one and the same, word for word.
+
+use windows::Win32::Graphics::Direct3D::ID3DBlob;
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::core::Error;
+
+/// The root signature of the shaders compiled from `source`, read from its
+/// `#define RS "..."`.
+pub(crate) fn make(device: &ID3D12Device, source: &str) -> windows::core::Result<ID3D12RootSignature> {
+    const MARK: &str = "#define RS \"";
+    let refused = |why: &str| {
+        tracing::warn!(why, "a root signature of ours could not be read from the shader's source");
+        Error::empty()
+    };
+    let Some(at) = source.find(MARK) else {
+        return Err(refused("the source carries no RS"));
+    };
+    let rest = &source[at + MARK.len()..];
+    let Some(end) = rest.find('"') else {
+        return Err(refused("the RS is never closed"));
+    };
+    let sig = parse(&rest[..end]).ok_or_else(|| refused("the RS is of a word not understood"))?;
+    serialize(device, &sig)
+}
+
+/// What a parsed RS string is of, before it points into arrays.
+struct Sig {
+    params: Vec<Param>,
+    samplers: Vec<D3D12_STATIC_SAMPLER_DESC>,
+    flags: D3D12_ROOT_SIGNATURE_FLAGS,
+}
+
+enum Param {
+    Constants(D3D12_ROOT_CONSTANTS, D3D12_SHADER_VISIBILITY),
+    Descriptor(D3D12_ROOT_PARAMETER_TYPE, D3D12_ROOT_DESCRIPTOR, D3D12_SHADER_VISIBILITY),
+    Table(Vec<D3D12_DESCRIPTOR_RANGE>, D3D12_SHADER_VISIBILITY),
+}
+
+fn parse(text: &str) -> Option<Sig> {
+    let mut sig = Sig {
+        params: Vec::new(),
+        samplers: Vec::new(),
+        flags: D3D12_ROOT_SIGNATURE_FLAG_NONE,
+    };
+    for piece in split_top(text) {
+        let (name, args) = element(piece.trim())?;
+        match name {
+            "RootFlags" => sig.flags = D3D12_ROOT_SIGNATURE_FLAGS(flags(args)),
+            "RootConstants" => sig.params.push(constants(args)?),
+            "SRV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, args)?),
+            "UAV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, args)?),
+            "CBV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_CBV, args)?),
+            "DescriptorTable" => sig.params.push(table(args)?),
+            "StaticSampler" => sig.samplers.push(sampler(args)?),
+            _ => return None,
+        }
+    }
+    Some(sig)
+}
+
+/// The pieces `text` is of: its top-level words, commas between
+/// parentheses passed over.
+fn split_top(text: &str) -> Vec<&str> {
+    let mut pieces = Vec::new();
+    let (mut depth, mut start) = (0usize, 0);
+    for (at, c) in text.char_indices() {
+        match c {
+            '(' => depth += 1,
+            ')' => depth = depth.saturating_sub(1),
+            ',' if depth == 0 => {
+                pieces.push(&text[start..at]);
+                start = at + 1;
+            }
+            _ => {}
+        }
+    }
+    pieces.push(&text[start..]);
+    pieces
+}
+
+/// An element as its name and what is between its parentheses.
+fn element(piece: &str) -> Option<(&str, &str)> {
+    let (name, rest) = piece.split_once('(')?;
+    let end = rest.rfind(')')?;
+    Some((name.trim(), &rest[..end]))
+}
+
+/// A `key = value` word.
+fn pair(word: &str) -> Option<(&str, &str)> {
+    word.split_once('=').map(|(key, value)| (key.trim(), value.trim()))
+}
+
+/// A register word like `t3`: its number, of the kind `letter` names.
+fn register(word: &str, letter: char) -> Option<u32> {
+    let (first, number) = word.split_at(1);
+    (first.chars().next()? == letter).then(|| number.parse().ok())?
+}
+
+fn constants(args: &str) -> Option<Param> {
+    let mut count = None;
+    let mut register_at = None;
+    let mut space = 0;
+    let mut visibility = D3D12_SHADER_VISIBILITY_ALL;
+    for word in split_top(args) {
+        let word = word.trim();
+        match pair(word) {
+            Some(("num32BitConstants", value)) => count = value.parse().ok(),
+            Some(("visibility", value)) => visibility = shader_visibility(value)?,
+            Some(("space", value)) => space = value.parse().ok()?,
+            Some(_) => return None,
+            None => register_at = register(word, 'b'),
+        }
+    }
+    Some(Param::Constants(
+        D3D12_ROOT_CONSTANTS {
+            Num32BitValues: count?,
+            ShaderRegister: register_at?,
+            RegisterSpace: space,
+        },
+        visibility,
+    ))
+}
+
+fn descriptor(kind: D3D12_ROOT_PARAMETER_TYPE, args: &str) -> Option<Param> {
+    let letter = match kind {
+        D3D12_ROOT_PARAMETER_TYPE_SRV => 't',
+        D3D12_ROOT_PARAMETER_TYPE_UAV => 'u',
+        _ => 'b',
+    };
+    let mut register_at = None;
+    let mut space = 0;
+    let mut visibility = D3D12_SHADER_VISIBILITY_ALL;
+    for word in split_top(args) {
+        let word = word.trim();
+        match pair(word) {
+            Some(("visibility", value)) => visibility = shader_visibility(value)?,
+            Some(("space", value)) => space = value.parse().ok()?,
+            Some(_) => return None,
+            None => register_at = register(word, letter),
+        }
+    }
+    Some(Param::Descriptor(
+        kind,
+        D3D12_ROOT_DESCRIPTOR { ShaderRegister: register_at?, RegisterSpace: space },
+        visibility,
+    ))
+}
+
+fn table(args: &str) -> Option<Param> {
+    let mut visibility = D3D12_SHADER_VISIBILITY_ALL;
+    let mut ranges = Vec::new();
+    for word in split_top(args) {
+        let word = word.trim();
+        if word.contains('(') {
+            ranges.push(range(word)?);
+        } else {
+            match pair(word) {
+                Some(("visibility", value)) => visibility = shader_visibility(value)?,
+                _ => return None,
+            }
+        }
+    }
+    Some(Param::Table(ranges, visibility))
+}
+
+/// One range of a table: `SRV(t0, numDescriptors=2)` and such.
+fn range(word: &str) -> Option<D3D12_DESCRIPTOR_RANGE> {
+    let (name, args) = element(word.trim())?;
+    let kind = match name {
+        "SRV" => D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
+        "UAV" => D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
+        "CBV" => D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
+        "Sampler" => D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
+        _ => return None,
+    };
+    let letter = match kind {
+        D3D12_DESCRIPTOR_RANGE_TYPE_SRV => 't',
+        D3D12_DESCRIPTOR_RANGE_TYPE_UAV => 'u',
+        D3D12_DESCRIPTOR_RANGE_TYPE_CBV => 'b',
+        _ => 's',
+    };
+    let mut base = None;
+    let mut count = 1;
+    let mut space = 0;
+    for piece in split_top(args) {
+        let word = piece.trim();
+        match pair(word) {
+            // The 1.0 serialization carries no range flags; the strings that
+            // name them are the title's volatile tables as ours already are.
+            Some(("flags", _)) => {}
+            Some(("numDescriptors", value)) => count = value.parse().ok()?,
+            Some(("space", value)) => space = value.parse().ok()?,
+            Some(_) => return None,
+            None => base = register(word, letter),
+        }
+    }
+    Some(D3D12_DESCRIPTOR_RANGE {
+        RangeType: kind,
+        NumDescriptors: count,
+        BaseShaderRegister: base?,
+        RegisterSpace: space,
+        OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
+    })
+}
+
+fn sampler(args: &str) -> Option<D3D12_STATIC_SAMPLER_DESC> {
+    // The grammar's defaults, for the words the string leaves out.
+    let mut desc = D3D12_STATIC_SAMPLER_DESC {
+        Filter: D3D12_FILTER_ANISOTROPIC,
+        AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
+        AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
+        AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
+        MipLODBias: 0.0,
+        MaxAnisotropy: 16,
+        ComparisonFunc: D3D12_COMPARISON_FUNC_NONE,
+        BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK,
+        MinLOD: 0.0,
+        MaxLOD: f32::MAX,
+        ShaderRegister: 0,
+        RegisterSpace: 0,
+        ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
+    };
+    let mut register_at = None;
+    for word in split_top(args) {
+        let word = word.trim();
+        match pair(word) {
+            Some(("filter", value)) => desc.Filter = filter(value)?,
+            Some(("addressU", value)) => desc.AddressU = address(value)?,
+            Some(("addressV", value)) => desc.AddressV = address(value)?,
+            Some(("addressW", value)) => desc.AddressW = address(value)?,
+            Some(("mipLODBias", value)) => desc.MipLODBias = value.parse().ok()?,
+            Some(("maxAnisotropy", value)) => desc.MaxAnisotropy = value.parse().ok()?,
+            Some(("comparisonFunc", value)) => desc.ComparisonFunc = comparison(value)?,
+            Some(("borderColor", value)) => desc.BorderColor = border(value)?,
+            Some(("minLOD", value)) => desc.MinLOD = value.parse().ok()?,
+            Some(("maxLOD", value)) => desc.MaxLOD = value.parse().ok()?,
+            Some(("space", value)) => desc.RegisterSpace = value.parse().ok()?,
+            Some(("visibility", value)) => desc.ShaderVisibility = shader_visibility(value)?,
+            Some(_) => return None,
+            None => register_at = register(word, 's'),
+        }
+    }
+    desc.ShaderRegister = register_at?;
+    Some(desc)
+}
+
+fn filter(name: &str) -> Option<D3D12_FILTER> {
+    Some(match name {
+        "FILTER_MIN_MAG_MIP_POINT" => D3D12_FILTER_MIN_MAG_MIP_POINT,
+        "FILTER_MIN_MAG_POINT_MIP_LINEAR" => D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR,
+        "FILTER_MIN_POINT_MAG_MIP_LINEAR" => D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR,
+        "FILTER_MIN_LINEAR_MAG_MIP_POINT" => D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT,
+        "FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR" => D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR,
+        "FILTER_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MIN_MAG_MIP_LINEAR,
+        "FILTER_MIN_MAG_LINEAR_MIP_POINT" => D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT,
+        "FILTER_ANISOTROPIC" => D3D12_FILTER_ANISOTROPIC,
+        "FILTER_COMPARISON_MIN_MAG_MIP_POINT" => D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT,
+        "FILTER_COMPARISON_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR,
+        "FILTER_COMPARISON_ANISOTROPIC" => D3D12_FILTER_COMPARISON_ANISOTROPIC,
+        "FILTER_MINIMUM_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR,
+        "FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR,
+        _ => return None,
+    })
+}
+
+fn address(name: &str) -> Option<D3D12_TEXTURE_ADDRESS_MODE> {
+    Some(match name {
+        "TEXTURE_ADDRESS_WRAP" => D3D12_TEXTURE_ADDRESS_MODE_WRAP,
+        "TEXTURE_ADDRESS_MIRROR" => D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
+        "TEXTURE_ADDRESS_CLAMP" => D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+        "TEXTURE_ADDRESS_BORDER" => D3D12_TEXTURE_ADDRESS_MODE_BORDER,
+        "TEXTURE_ADDRESS_MIRROR_ONCE" => D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
+        _ => return None,
+    })
+}
+
+fn comparison(name: &str) -> Option<D3D12_COMPARISON_FUNC> {
+    Some(match name {
+        "COMPARISON_NONE" => D3D12_COMPARISON_FUNC_NONE,
+        "COMPARISON_LESS" => D3D12_COMPARISON_FUNC_LESS,
+        "COMPARISON_EQUAL" => D3D12_COMPARISON_FUNC_EQUAL,
+        "COMPARISON_LESS_EQUAL" => D3D12_COMPARISON_FUNC_LESS_EQUAL,
+        "COMPARISON_GREATER" => D3D12_COMPARISON_FUNC_GREATER,
+        "COMPARISON_NOT_EQUAL" => D3D12_COMPARISON_FUNC_NOT_EQUAL,
+        "COMPARISON_GREATER_EQUAL" => D3D12_COMPARISON_FUNC_GREATER_EQUAL,
+        "COMPARISON_ALWAYS" => D3D12_COMPARISON_FUNC_ALWAYS,
+        _ => return None,
+    })
+}
+
+fn border(name: &str) -> Option<D3D12_STATIC_BORDER_COLOR> {
+    Some(match name {
+        "STATIC_BORDER_COLOR_OPAQUE_BLACK" => D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK,
+        "STATIC_BORDER_COLOR_OPAQUE_WHITE" => D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE,
+        "STATIC_BORDER_COLOR_TRANSPARENT_BLACK" => D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK,
+        _ => return None,
+    })
+}
+
+fn shader_visibility(name: &str) -> Option<D3D12_SHADER_VISIBILITY> {
+    Some(match name {
+        "SHADER_VISIBILITY_ALL" => D3D12_SHADER_VISIBILITY_ALL,
+        "SHADER_VISIBILITY_VERTEX" => D3D12_SHADER_VISIBILITY_VERTEX,
+        "SHADER_VISIBILITY_HULL" => D3D12_SHADER_VISIBILITY_HULL,
+        "SHADER_VISIBILITY_DOMAIN" => D3D12_SHADER_VISIBILITY_DOMAIN,
+        "SHADER_VISIBILITY_GEOMETRY" => D3D12_SHADER_VISIBILITY_GEOMETRY,
+        "SHADER_VISIBILITY_PIXEL" => D3D12_SHADER_VISIBILITY_PIXEL,
+        _ => return None,
+    })
+}
+
+/// A root flag word: the names the strings use, or a number.
+fn flags(text: &str) -> i32 {
+    let mut value = 0;
+    for name in text.split('|') {
+        let bit = match name.trim() {
+            "0" => 0,
+            "ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT" => D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT.0,
+            "ALLOW_STREAM_OUTPUT" => D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT.0,
+            "DENY_VERTEX_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS.0,
+            "DENY_HULL_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS.0,
+            "DENY_DOMAIN_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS.0,
+            "DENY_GEOMETRY_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS.0,
+            "DENY_PIXEL_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS.0,
+            _ => return 0,
+        };
+        value |= bit;
+    }
+    value
+}
+
+fn serialize(device: &ID3D12Device, sig: &Sig) -> windows::core::Result<ID3D12RootSignature> {
+    // The tables' ranges are pointed at, so they are flattened into one
+    // array that lives through the serialization, then the parameters.
+    let mut ranges: Vec<D3D12_DESCRIPTOR_RANGE> = Vec::new();
+    let mut tables: Vec<(u32, u32)> = Vec::new();
+    for param in &sig.params {
+        if let Param::Table(own, _) = param {
+            tables.push((ranges.len() as u32, own.len() as u32));
+            ranges.extend_from_slice(own);
+        }
+    }
+    let mut left = tables.iter();
+    let params: Vec<D3D12_ROOT_PARAMETER> = sig
+        .params
+        .iter()
+        .map(|param| match param {
+            Param::Table(_, visibility) => {
+                let (first, count) = *left.next()?;
+                Some(D3D12_ROOT_PARAMETER {
+                    ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
+                    ShaderVisibility: *visibility,
+                    Anonymous: D3D12_ROOT_PARAMETER_0 {
+                        DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE {
+                            NumDescriptorRanges: count,
+                            pDescriptorRanges: ranges[first as usize..].as_ptr(),
+                        },
+                    },
+                })
+            }
+            Param::Constants(constants, visibility) => Some(D3D12_ROOT_PARAMETER {
+                ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
+                ShaderVisibility: *visibility,
+                Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: *constants },
+            }),
+            Param::Descriptor(kind, descriptor, visibility) => Some(D3D12_ROOT_PARAMETER {
+                ParameterType: *kind,
+                ShaderVisibility: *visibility,
+                Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: *descriptor },
+            }),
+        })
+        .collect::<Option<Vec<_>>>()
+        .ok_or_else(Error::empty)?;
+    let desc = D3D12_ROOT_SIGNATURE_DESC {
+        NumParameters: params.len() as u32,
+        pParameters: params.as_ptr(),
+        NumStaticSamplers: sig.samplers.len() as u32,
+        pStaticSamplers: sig.samplers.as_ptr(),
+        Flags: sig.flags,
+    };
+    // SAFETY: the description points at the live arrays; the blob is read
+    // in full before it is released.
+    unsafe {
+        let mut blob: Option<ID3DBlob> = None;
+        let mut errors: Option<ID3DBlob> = None;
+        if let Err(e) = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, Some(&mut errors)) {
+            if let Some(errors) = errors {
+                let text = std::slice::from_raw_parts(
+                    errors.GetBufferPointer().cast::<u8>(),
+                    errors.GetBufferSize(),
+                );
+                tracing::warn!("root signature: {}", String::from_utf8_lossy(text));
+            }
+            return Err(e);
+        }
+        let blob = blob.ok_or_else(Error::empty)?;
+        let bytes =
+            std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
+        device.CreateRootSignature(0, bytes)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn builtin_signatures() -> Vec<String> {
+        const MARK: &str = "#define RS \"";
+        let sources = [
+            include_str!("ambient.rs"),
+            include_str!("compose.rs"),
+            include_str!("host.rs"),
+            include_str!("indirect.rs"),
+            include_str!("replay/play/merge.rs"),
+        ];
+        let mut signatures = Vec::new();
+        for source in sources {
+            let mut rest = source;
+            while let Some(at) = rest.find(MARK) {
+                let after = &rest[at + MARK.len()..];
+                let end = after.find('"').expect("root signature string is closed");
+                signatures.push(after[..end].to_owned());
+                rest = &after[end + 1..];
+            }
+        }
+        let lightprobe = include_str!("lightprobe.rs");
+        for marker in ["const RS_EXPOSURE: &str = \"", "const RS_LUX: &str = \""] {
+            let at = lightprobe.find(marker).expect("lightprobe signature exists");
+            let after = &lightprobe[at + marker.len()..];
+            let end = after.find('"').expect("lightprobe signature is closed");
+            signatures.push(after[..end].to_owned());
+        }
+        assert_eq!(signatures.len(), 18, "built-in signature inventory changed");
+        signatures
+    }
+
+    fn compiler_diagnostic(source: &str, entry: windows::core::PCSTR) -> String {
+        use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
+        let mut code = None;
+        let mut errors = None;
+        let result = unsafe {
+            D3DCompile(
+                source.as_ptr().cast(),
+                source.len(),
+                windows::core::s!("victory"),
+                None,
+                None,
+                entry,
+                windows::core::s!("cs_5_1"),
+                0,
+                0,
+                &mut code,
+                Some(&mut errors),
+            )
+        };
+        match result {
+            Ok(()) => "secondary D3DCompile call succeeded".to_owned(),
+            Err(error) => errors.map_or_else(
+                || format!("{error:?}; no compiler diagnostic blob"),
+                |blob: ID3DBlob| unsafe {
+                    let bytes = std::slice::from_raw_parts(
+                        blob.GetBufferPointer().cast::<u8>(),
+                        blob.GetBufferSize(),
+                    );
+                    String::from_utf8_lossy(bytes).into_owned()
+                },
+            ),
+        }
+    }
+
+    #[test]
+    fn recognizes_supported_filter_constants() {
+        let cases = [
+            ("FILTER_MIN_MAG_MIP_POINT", D3D12_FILTER_MIN_MAG_MIP_POINT),
+            ("FILTER_MIN_MAG_POINT_MIP_LINEAR", D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR),
+            ("FILTER_MIN_POINT_MAG_MIP_LINEAR", D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR),
+            ("FILTER_MIN_LINEAR_MAG_MIP_POINT", D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT),
+            ("FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR", D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR),
+            ("FILTER_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MIN_MAG_MIP_LINEAR),
+            ("FILTER_MIN_MAG_LINEAR_MIP_POINT", D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT),
+            ("FILTER_ANISOTROPIC", D3D12_FILTER_ANISOTROPIC),
+            ("FILTER_COMPARISON_MIN_MAG_MIP_POINT", D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT),
+            ("FILTER_COMPARISON_MIN_MAG_MIP_LINEAR", D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR),
+            ("FILTER_COMPARISON_ANISOTROPIC", D3D12_FILTER_COMPARISON_ANISOTROPIC),
+            ("FILTER_MINIMUM_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR),
+            ("FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR),
+        ];
+        for (name, expected) in cases {
+            assert_eq!(filter(name), Some(expected), "{name}");
+        }
+        assert_eq!(filter("FILTER_UNKNOWN"), None);
+    }
+
+    #[test]
+    fn parses_builtin_shader_root_signatures() {
+        for signature in builtin_signatures() {
+            assert!(parse(&signature).is_some(), "unsupported root signature: {signature}");
+        }
+    }
+
+    #[test]
+    #[ignore = "requires a working D3D12 host device"]
+    fn creates_builtin_root_signatures_on_host_device() {
+        let mut device: Option<ID3D12Device> = None;
+        unsafe {
+            D3D12CreateDevice(
+                None::<&windows::core::IUnknown>,
+                windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0,
+                &mut device,
+            )
+            .expect("D3D12 device creation");
+        }
+        let device = device.expect("D3D12CreateDevice returned no device");
+        let luid = unsafe { device.GetAdapterLuid() };
+        let factory = unsafe {
+            windows::Win32::Graphics::Dxgi::CreateDXGIFactory1::<
+                windows::Win32::Graphics::Dxgi::IDXGIFactory4,
+            >()
+            .expect("DXGI factory creation")
+        };
+        let adapter = unsafe {
+            factory
+                .EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid)
+                .expect("adapter matching the D3D12 device")
+        };
+        let desc = unsafe { adapter.GetDesc1().expect("adapter description") };
+        let name_end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
+        let adapter_name = String::from_utf16_lossy(&desc.Description[..name_end]);
+        let signatures = builtin_signatures();
+        for signature in &signatures {
+            let source = format!("#define RS \"{signature}\"");
+            make(&device, &source).unwrap_or_else(|e| {
+                panic!("root signature serialization or creation failed for {signature}: {e:?}")
+            });
+        }
+        let control_source = r#"
+#define RS "UAV(u0)"
+RWByteAddressBuffer data : register(u0);
+[RootSignature(RS)]
+[numthreads(1, 1, 1)]
+void main() { data.Store(0, 1); }
+"#;
+        let control_code = crate::host::compile(
+            control_source,
+            windows::core::s!("main"),
+            windows::core::s!("cs_5_1"),
+        )
+        .expect("simple Store-only compute shader compilation");
+        let control_root = make(&device, control_source).expect("simple compute root signature");
+        let control_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
+            pRootSignature: unsafe { std::mem::transmute_copy(&control_root) },
+            CS: D3D12_SHADER_BYTECODE {
+                pShaderBytecode: control_code.as_ptr().cast(),
+                BytecodeLength: control_code.len(),
+            },
+            ..Default::default()
+        };
+        let _control_pso: ID3D12PipelineState = unsafe {
+            device
+                .CreateComputePipelineState(&control_desc)
+                .expect("simple Store-only compute PSO creation")
+        };
+        let readonly_load_source = r#"
+#define RS "SRV(t0), UAV(u0)"
+ByteAddressBuffer input : register(t0);
+RWByteAddressBuffer output : register(u0);
+[RootSignature(RS)]
+[numthreads(1, 1, 1)]
+void main() { output.Store4(0, input.Load4(0)); }
+"#;
+        let readonly_load_code = crate::host::compile(
+            readonly_load_source,
+            windows::core::s!("main"),
+            windows::core::s!("cs_5_1"),
+        )
+        .expect("read-only ByteAddressBuffer Load4 shader compilation");
+        let readonly_load_root = make(&device, readonly_load_source)
+            .expect("read-only ByteAddressBuffer Load4 root signature");
+        let readonly_load_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
+            pRootSignature: unsafe { std::mem::transmute_copy(&readonly_load_root) },
+            CS: D3D12_SHADER_BYTECODE {
+                pShaderBytecode: readonly_load_code.as_ptr().cast(),
+                BytecodeLength: readonly_load_code.len(),
+            },
+            ..Default::default()
+        };
+        let _readonly_load_pso: ID3D12PipelineState = unsafe {
+            device
+                .CreateComputePipelineState(&readonly_load_desc)
+                .expect("read-only ByteAddressBuffer Load4 PSO creation")
+        };
+        // Compile the fork's actual batching shader with the values selected
+        // for an AMD adapter by indirect::wide() and indirect::rest().
+        let batch = include_str!("indirect/batch.rs");
+        let batch_marker = "pub(crate) const SOURCE: &str = r#\"";
+        let batch_at = batch.find(batch_marker).expect("indirect batch HLSL exists");
+        let batch_after = &batch[batch_at + batch_marker.len()..];
+        let batch_end = batch_after.find("\"#;").expect("indirect batch HLSL is closed");
+        let batch_source = format!(
+            "#define WIDEST 1048576u\n#define REST 1\n{}",
+            &batch_after[..batch_end]
+        );
+        let batch_code = match crate::host::compile(
+            &batch_source,
+            windows::core::s!("main"),
+            windows::core::s!("cs_5_1"),
+        ) {
+            Ok(code) => code,
+            Err(e) => {
+                let diagnostic = compiler_diagnostic(
+                    &batch_source,
+                    windows::core::s!("main"),
+                );
+                if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") {
+                    std::fs::write(
+                        marker,
+                        format!(
+                            "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_compile=failed\n{diagnostic}\n",
+                            signatures.len()
+                        ),
+                    )
+                    .expect("write batching shader failure diagnostic");
+                }
+                panic!("indirect batching shader compilation failed: {e:?}; {diagnostic}");
+            }
+        };
+        let batch_root = make(&device, &batch_source)
+            .expect("indirect batching root signature creation");
+        let batch_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
+            pRootSignature: unsafe { std::mem::transmute_copy(&batch_root) },
+            CS: D3D12_SHADER_BYTECODE {
+                pShaderBytecode: batch_code.as_ptr().cast(),
+                BytecodeLength: batch_code.len(),
+            },
+            ..Default::default()
+        };
+        let _batch_pso: ID3D12PipelineState = unsafe {
+            device
+                .CreateComputePipelineState(&batch_desc)
+                .expect("indirect batching compute PSO creation")
+        };
+        let lightprobe = include_str!("lightprobe.rs");
+        const HLSL_MARK: &str = "const SOURCE: &str = r#\"";
+        let source_at = lightprobe.find(HLSL_MARK).expect("lightprobe HLSL source exists");
+        let source_after = &lightprobe[source_at + HLSL_MARK.len()..];
+        let source_end = source_after.find("\"#;").expect("lightprobe HLSL source is closed");
+        let mut hlsl = source_after[..source_end].to_owned();
+        let load4_expanded = std::env::var_os("VICTORY_TEST_EXPAND_LOAD4").is_some();
+        if load4_expanded {
+            hlsl = hlsl
+                .replace("stats.Load4(0)", "uint4(stats.Load(0), stats.Load(4), stats.Load(8), stats.Load(12))")
+                .replace("output.Load4(0)", "uint4(output.Load(0), output.Load(4), output.Load(8), output.Load(12))");
+        }
+        let mut pipelines = 0;
+        for (part, rs_marker, entry) in [
+            ("EXPOSURE", "const RS_EXPOSURE: &str = \"", windows::core::s!("exposure")),
+            ("LUX", "const RS_LUX: &str = \"", windows::core::s!("lux")),
+        ] {
+            let rs_at = lightprobe.find(rs_marker).expect("lightprobe RS exists");
+            let rs_after = &lightprobe[rs_at + rs_marker.len()..];
+            let rs_end = rs_after.find('"').expect("lightprobe RS is closed");
+            let source = format!("#define {part}\n#define RS \"{}\"\n{hlsl}", &rs_after[..rs_end]);
+            let code = match crate::host::compile(&source, entry, windows::core::s!("cs_5_1")) {
+                Ok(code) => code,
+                Err(e) => {
+                    let diagnostic = compiler_diagnostic(&source, entry);
+                    if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") {
+                        std::fs::write(
+                            marker,
+                            format!(
+                                "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_pso=created\nload4_expanded={load4_expanded}\nlightprobe_part={part}\ncompile=failed\n{diagnostic}\n",
+                                signatures.len()
+                            ),
+                        )
+                        .expect("write compiler-failure diagnostic");
+                    }
+                    panic!("lightprobe {part} shader compilation failed: {e:?}; {diagnostic}");
+                }
+            };
+            let root = make(&device, &source)
+                .unwrap_or_else(|e| panic!("lightprobe {part} root signature failed: {e:?}"));
+            let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
+                pRootSignature: unsafe { std::mem::transmute_copy(&root) },
+                CS: D3D12_SHADER_BYTECODE {
+                    pShaderBytecode: code.as_ptr().cast(),
+                    BytecodeLength: code.len(),
+                },
+                ..Default::default()
+            };
+            let _pso: ID3D12PipelineState = unsafe {
+                device
+                    .CreateComputePipelineState(&desc)
+                    .unwrap_or_else(|e| panic!("lightprobe {part} pipeline creation failed: {e:?}"))
+            };
+            pipelines += 1;
+        }
+        if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") {
+            std::fs::write(
+                marker,
+                format!(
+                    "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_pso=created\nload4_expanded={load4_expanded}\nlightprobe_psos_created={pipelines}\n",
+                    signatures.len()
+                ),
+            )
+            .expect("write success marker");
+        }
+    }
+
+    #[test]
+    #[ignore = "requires a working D3D12 host device"]
+    fn creates_compositor_pipeline_on_host_device() {
+        let mut device: Option<ID3D12Device> = None;
+        unsafe {
+            D3D12CreateDevice(
+                None::<&windows::core::IUnknown>,
+                windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0,
+                &mut device,
+            )
+            .expect("D3D12 device creation");
+        }
+        let device = device.expect("D3D12CreateDevice returned no device");
+        let luid = unsafe { device.GetAdapterLuid() };
+        let factory = unsafe {
+            windows::Win32::Graphics::Dxgi::CreateDXGIFactory1::<
+                windows::Win32::Graphics::Dxgi::IDXGIFactory4,
+            >()
+            .expect("DXGI factory creation")
+        };
+        let adapter = unsafe {
+            factory
+                .EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid)
+                .expect("adapter matching the D3D12 device")
+        };
+        let desc = unsafe { adapter.GetDesc1().expect("adapter description") };
+        let name_end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
+        let adapter_name = String::from_utf16_lossy(&desc.Description[..name_end]);
+
+        let compose = include_str!("compose.rs");
+        const HLSL_MARK: &str = "const SOURCE: &str = r#\"";
+        let source_at = compose.find(HLSL_MARK).expect("compositor HLSL exists");
+        let source_after = &compose[source_at + HLSL_MARK.len()..];
+        let source_end = source_after.find("\"#;").expect("compositor HLSL is closed");
+        let source = &source_after[..source_end];
+        let vs = crate::host::compile(source, windows::core::s!("vs"), windows::core::s!("vs_5_1"))
+            .expect("compositor vertex shader compilation");
+        let ps = crate::host::compile(source, windows::core::s!("ps"), windows::core::s!("ps_5_1"))
+            .expect("compositor pixel shader compilation");
+        let root = make(&device, source).expect("compositor root signature creation");
+        let shader = |code: &[u8]| D3D12_SHADER_BYTECODE {
+            pShaderBytecode: code.as_ptr().cast(),
+            BytecodeLength: code.len(),
+        };
+        let mut pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
+            pRootSignature: unsafe { std::mem::transmute_copy(&root) },
+            VS: shader(&vs),
+            PS: shader(&ps),
+            SampleMask: u32::MAX,
+            RasterizerState: D3D12_RASTERIZER_DESC {
+                FillMode: D3D12_FILL_MODE_SOLID,
+                CullMode: D3D12_CULL_MODE_NONE,
+                ..Default::default()
+            },
+            PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
+            NumRenderTargets: 1,
+            SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
+                Count: 1,
+                Quality: 0,
+            },
+            ..Default::default()
+        };
+        pipeline_desc.RTVFormats[0] =
+            windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM;
+        pipeline_desc.BlendState.RenderTarget[0].RenderTargetWriteMask =
+            D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
+        let _pso: ID3D12PipelineState = unsafe {
+            device
+                .CreateGraphicsPipelineState(&pipeline_desc)
+                .expect("compositor graphics PSO creation")
+        };
+        if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_TEST_MARKER") {
+            std::fs::write(
+                marker,
+                format!(
+                    "adapter={adapter_name}\nvs=compiled\nps=compiled\nroot_signature=created\nfilter=FILTER_MIN_MAG_MIP_LINEAR\ngraphics_pso=created\n"
+                ),
+            )
+            .expect("write compositor test result");
+        }
+    }
+}
<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7237704495 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237704495). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T10:09:04Z. --- RDNA2 Proton source patch, part 1 of 2, against `4c79ac5`. Save both diff blocks as patch files and apply them together with `git apply 1.patch 2.patch`. The launch settings and evidence are in [the reproduction note](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237482162). ````diff diff --git a/crates/victory-gpu/src/rootstring.rs b/crates/victory-gpu/src/rootstring.rs new file mode 100644 index 0000000..cbc2e8a --- /dev/null +++ b/crates/victory-gpu/src/rootstring.rs @@ -0,0 +1,797 @@ +//! Root signatures for the shaders we compile ourselves: read from the +//! `RS` string in the HLSL (`#define RS "..."`) and serialized from a +//! description built from it, not taken out of the compiled blob. Under +//! Wine the host refuses the embedded signature of the blob its compiler +//! returns (E_FAIL), while a description we serialize ourselves works, as +//! the title's own signatures do. Reading the string from the same source +//! the shaders were compiled from keeps the description and what the +//! shaders expect one and the same, word for word. + +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Error; + +/// The root signature of the shaders compiled from `source`, read from its +/// `#define RS "..."`. +pub(crate) fn make(device: &ID3D12Device, source: &str) -> windows::core::Result<ID3D12RootSignature> { + const MARK: &str = "#define RS \""; + let refused = |why: &str| { + tracing::warn!(why, "a root signature of ours could not be read from the shader's source"); + Error::empty() + }; + let Some(at) = source.find(MARK) else { + return Err(refused("the source carries no RS")); + }; + let rest = &source[at + MARK.len()..]; + let Some(end) = rest.find('"') else { + return Err(refused("the RS is never closed")); + }; + let sig = parse(&rest[..end]).ok_or_else(|| refused("the RS is of a word not understood"))?; + serialize(device, &sig) +} + +/// What a parsed RS string is of, before it points into arrays. +struct Sig { + params: Vec<Param>, + samplers: Vec<D3D12_STATIC_SAMPLER_DESC>, + flags: D3D12_ROOT_SIGNATURE_FLAGS, +} + +enum Param { + Constants(D3D12_ROOT_CONSTANTS, D3D12_SHADER_VISIBILITY), + Descriptor(D3D12_ROOT_PARAMETER_TYPE, D3D12_ROOT_DESCRIPTOR, D3D12_SHADER_VISIBILITY), + Table(Vec<D3D12_DESCRIPTOR_RANGE>, D3D12_SHADER_VISIBILITY), +} + +fn parse(text: &str) -> Option<Sig> { + let mut sig = Sig { + params: Vec::new(), + samplers: Vec::new(), + flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + for piece in split_top(text) { + let (name, args) = element(piece.trim())?; + match name { + "RootFlags" => sig.flags = D3D12_ROOT_SIGNATURE_FLAGS(flags(args)), + "RootConstants" => sig.params.push(constants(args)?), + "SRV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, args)?), + "UAV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, args)?), + "CBV" => sig.params.push(descriptor(D3D12_ROOT_PARAMETER_TYPE_CBV, args)?), + "DescriptorTable" => sig.params.push(table(args)?), + "StaticSampler" => sig.samplers.push(sampler(args)?), + _ => return None, + } + } + Some(sig) +} + +/// The pieces `text` is of: its top-level words, commas between +/// parentheses passed over. +fn split_top(text: &str) -> Vec<&str> { + let mut pieces = Vec::new(); + let (mut depth, mut start) = (0usize, 0); + for (at, c) in text.char_indices() { + match c { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + pieces.push(&text[start..at]); + start = at + 1; + } + _ => {} + } + } + pieces.push(&text[start..]); + pieces +} + +/// An element as its name and what is between its parentheses. +fn element(piece: &str) -> Option<(&str, &str)> { + let (name, rest) = piece.split_once('(')?; + let end = rest.rfind(')')?; + Some((name.trim(), &rest[..end])) +} + +/// A `key = value` word. +fn pair(word: &str) -> Option<(&str, &str)> { + word.split_once('=').map(|(key, value)| (key.trim(), value.trim())) +} + +/// A register word like `t3`: its number, of the kind `letter` names. +fn register(word: &str, letter: char) -> Option<u32> { + let (first, number) = word.split_at(1); + (first.chars().next()? == letter).then(|| number.parse().ok())? +} + +fn constants(args: &str) -> Option<Param> { + let mut count = None; + let mut register_at = None; + let mut space = 0; + let mut visibility = D3D12_SHADER_VISIBILITY_ALL; + for word in split_top(args) { + let word = word.trim(); + match pair(word) { + Some(("num32BitConstants", value)) => count = value.parse().ok(), + Some(("visibility", value)) => visibility = shader_visibility(value)?, + Some(("space", value)) => space = value.parse().ok()?, + Some(_) => return None, + None => register_at = register(word, 'b'), + } + } + Some(Param::Constants( + D3D12_ROOT_CONSTANTS { + Num32BitValues: count?, + ShaderRegister: register_at?, + RegisterSpace: space, + }, + visibility, + )) +} + +fn descriptor(kind: D3D12_ROOT_PARAMETER_TYPE, args: &str) -> Option<Param> { + let letter = match kind { + D3D12_ROOT_PARAMETER_TYPE_SRV => 't', + D3D12_ROOT_PARAMETER_TYPE_UAV => 'u', + _ => 'b', + }; + let mut register_at = None; + let mut space = 0; + let mut visibility = D3D12_SHADER_VISIBILITY_ALL; + for word in split_top(args) { + let word = word.trim(); + match pair(word) { + Some(("visibility", value)) => visibility = shader_visibility(value)?, + Some(("space", value)) => space = value.parse().ok()?, + Some(_) => return None, + None => register_at = register(word, letter), + } + } + Some(Param::Descriptor( + kind, + D3D12_ROOT_DESCRIPTOR { ShaderRegister: register_at?, RegisterSpace: space }, + visibility, + )) +} + +fn table(args: &str) -> Option<Param> { + let mut visibility = D3D12_SHADER_VISIBILITY_ALL; + let mut ranges = Vec::new(); + for word in split_top(args) { + let word = word.trim(); + if word.contains('(') { + ranges.push(range(word)?); + } else { + match pair(word) { + Some(("visibility", value)) => visibility = shader_visibility(value)?, + _ => return None, + } + } + } + Some(Param::Table(ranges, visibility)) +} + +/// One range of a table: `SRV(t0, numDescriptors=2)` and such. +fn range(word: &str) -> Option<D3D12_DESCRIPTOR_RANGE> { + let (name, args) = element(word.trim())?; + let kind = match name { + "SRV" => D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + "UAV" => D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + "CBV" => D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + "Sampler" => D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, + _ => return None, + }; + let letter = match kind { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV => 't', + D3D12_DESCRIPTOR_RANGE_TYPE_UAV => 'u', + D3D12_DESCRIPTOR_RANGE_TYPE_CBV => 'b', + _ => 's', + }; + let mut base = None; + let mut count = 1; + let mut space = 0; + for piece in split_top(args) { + let word = piece.trim(); + match pair(word) { + // The 1.0 serialization carries no range flags; the strings that + // name them are the title's volatile tables as ours already are. + Some(("flags", _)) => {} + Some(("numDescriptors", value)) => count = value.parse().ok()?, + Some(("space", value)) => space = value.parse().ok()?, + Some(_) => return None, + None => base = register(word, letter), + } + } + Some(D3D12_DESCRIPTOR_RANGE { + RangeType: kind, + NumDescriptors: count, + BaseShaderRegister: base?, + RegisterSpace: space, + OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }) +} + +fn sampler(args: &str) -> Option<D3D12_STATIC_SAMPLER_DESC> { + // The grammar's defaults, for the words the string leaves out. + let mut desc = D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_ANISOTROPIC, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MipLODBias: 0.0, + MaxAnisotropy: 16, + ComparisonFunc: D3D12_COMPARISON_FUNC_NONE, + BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, + MinLOD: 0.0, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let mut register_at = None; + for word in split_top(args) { + let word = word.trim(); + match pair(word) { + Some(("filter", value)) => desc.Filter = filter(value)?, + Some(("addressU", value)) => desc.AddressU = address(value)?, + Some(("addressV", value)) => desc.AddressV = address(value)?, + Some(("addressW", value)) => desc.AddressW = address(value)?, + Some(("mipLODBias", value)) => desc.MipLODBias = value.parse().ok()?, + Some(("maxAnisotropy", value)) => desc.MaxAnisotropy = value.parse().ok()?, + Some(("comparisonFunc", value)) => desc.ComparisonFunc = comparison(value)?, + Some(("borderColor", value)) => desc.BorderColor = border(value)?, + Some(("minLOD", value)) => desc.MinLOD = value.parse().ok()?, + Some(("maxLOD", value)) => desc.MaxLOD = value.parse().ok()?, + Some(("space", value)) => desc.RegisterSpace = value.parse().ok()?, + Some(("visibility", value)) => desc.ShaderVisibility = shader_visibility(value)?, + Some(_) => return None, + None => register_at = register(word, 's'), + } + } + desc.ShaderRegister = register_at?; + Some(desc) +} + +fn filter(name: &str) -> Option<D3D12_FILTER> { + Some(match name { + "FILTER_MIN_MAG_MIP_POINT" => D3D12_FILTER_MIN_MAG_MIP_POINT, + "FILTER_MIN_MAG_POINT_MIP_LINEAR" => D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR, + "FILTER_MIN_POINT_MAG_MIP_LINEAR" => D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR, + "FILTER_MIN_LINEAR_MAG_MIP_POINT" => D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT, + "FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR" => D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, + "FILTER_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MIN_MAG_MIP_LINEAR, + "FILTER_MIN_MAG_LINEAR_MIP_POINT" => D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, + "FILTER_ANISOTROPIC" => D3D12_FILTER_ANISOTROPIC, + "FILTER_COMPARISON_MIN_MAG_MIP_POINT" => D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT, + "FILTER_COMPARISON_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, + "FILTER_COMPARISON_ANISOTROPIC" => D3D12_FILTER_COMPARISON_ANISOTROPIC, + "FILTER_MINIMUM_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR, + "FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR" => D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR, + _ => return None, + }) +} + +fn address(name: &str) -> Option<D3D12_TEXTURE_ADDRESS_MODE> { + Some(match name { + "TEXTURE_ADDRESS_WRAP" => D3D12_TEXTURE_ADDRESS_MODE_WRAP, + "TEXTURE_ADDRESS_MIRROR" => D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + "TEXTURE_ADDRESS_CLAMP" => D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + "TEXTURE_ADDRESS_BORDER" => D3D12_TEXTURE_ADDRESS_MODE_BORDER, + "TEXTURE_ADDRESS_MIRROR_ONCE" => D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, + _ => return None, + }) +} + +fn comparison(name: &str) -> Option<D3D12_COMPARISON_FUNC> { + Some(match name { + "COMPARISON_NONE" => D3D12_COMPARISON_FUNC_NONE, + "COMPARISON_LESS" => D3D12_COMPARISON_FUNC_LESS, + "COMPARISON_EQUAL" => D3D12_COMPARISON_FUNC_EQUAL, + "COMPARISON_LESS_EQUAL" => D3D12_COMPARISON_FUNC_LESS_EQUAL, + "COMPARISON_GREATER" => D3D12_COMPARISON_FUNC_GREATER, + "COMPARISON_NOT_EQUAL" => D3D12_COMPARISON_FUNC_NOT_EQUAL, + "COMPARISON_GREATER_EQUAL" => D3D12_COMPARISON_FUNC_GREATER_EQUAL, + "COMPARISON_ALWAYS" => D3D12_COMPARISON_FUNC_ALWAYS, + _ => return None, + }) +} + +fn border(name: &str) -> Option<D3D12_STATIC_BORDER_COLOR> { + Some(match name { + "STATIC_BORDER_COLOR_OPAQUE_BLACK" => D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, + "STATIC_BORDER_COLOR_OPAQUE_WHITE" => D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + "STATIC_BORDER_COLOR_TRANSPARENT_BLACK" => D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + _ => return None, + }) +} + +fn shader_visibility(name: &str) -> Option<D3D12_SHADER_VISIBILITY> { + Some(match name { + "SHADER_VISIBILITY_ALL" => D3D12_SHADER_VISIBILITY_ALL, + "SHADER_VISIBILITY_VERTEX" => D3D12_SHADER_VISIBILITY_VERTEX, + "SHADER_VISIBILITY_HULL" => D3D12_SHADER_VISIBILITY_HULL, + "SHADER_VISIBILITY_DOMAIN" => D3D12_SHADER_VISIBILITY_DOMAIN, + "SHADER_VISIBILITY_GEOMETRY" => D3D12_SHADER_VISIBILITY_GEOMETRY, + "SHADER_VISIBILITY_PIXEL" => D3D12_SHADER_VISIBILITY_PIXEL, + _ => return None, + }) +} + +/// A root flag word: the names the strings use, or a number. +fn flags(text: &str) -> i32 { + let mut value = 0; + for name in text.split('|') { + let bit = match name.trim() { + "0" => 0, + "ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT" => D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT.0, + "ALLOW_STREAM_OUTPUT" => D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT.0, + "DENY_VERTEX_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS.0, + "DENY_HULL_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS.0, + "DENY_DOMAIN_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS.0, + "DENY_GEOMETRY_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS.0, + "DENY_PIXEL_SHADER_ROOT_ACCESS" => D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS.0, + _ => return 0, + }; + value |= bit; + } + value +} + +fn serialize(device: &ID3D12Device, sig: &Sig) -> windows::core::Result<ID3D12RootSignature> { + // The tables' ranges are pointed at, so they are flattened into one + // array that lives through the serialization, then the parameters. + let mut ranges: Vec<D3D12_DESCRIPTOR_RANGE> = Vec::new(); + let mut tables: Vec<(u32, u32)> = Vec::new(); + for param in &sig.params { + if let Param::Table(own, _) = param { + tables.push((ranges.len() as u32, own.len() as u32)); + ranges.extend_from_slice(own); + } + } + let mut left = tables.iter(); + let params: Vec<D3D12_ROOT_PARAMETER> = sig + .params + .iter() + .map(|param| match param { + Param::Table(_, visibility) => { + let (first, count) = *left.next()?; + Some(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: *visibility, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: count, + pDescriptorRanges: ranges[first as usize..].as_ptr(), + }, + }, + }) + } + Param::Constants(constants, visibility) => Some(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: *visibility, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: *constants }, + }), + Param::Descriptor(kind, descriptor, visibility) => Some(D3D12_ROOT_PARAMETER { + ParameterType: *kind, + ShaderVisibility: *visibility, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: *descriptor }, + }), + }) + .collect::<Option<Vec<_>>>() + .ok_or_else(Error::empty)?; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: sig.samplers.len() as u32, + pStaticSamplers: sig.samplers.as_ptr(), + Flags: sig.flags, + }; + // SAFETY: the description points at the live arrays; the blob is read + // in full before it is released. + unsafe { + let mut blob: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + if let Err(e) = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, Some(&mut errors)) { + if let Some(errors) = errors { + let text = std::slice::from_raw_parts( + errors.GetBufferPointer().cast::<u8>(), + errors.GetBufferSize(), + ); + tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let blob = blob.ok_or_else(Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn builtin_signatures() -> Vec<String> { + const MARK: &str = "#define RS \""; + let sources = [ + include_str!("ambient.rs"), + include_str!("compose.rs"), + include_str!("host.rs"), + include_str!("indirect.rs"), + include_str!("replay/play/merge.rs"), + ]; + let mut signatures = Vec::new(); + for source in sources { + let mut rest = source; + while let Some(at) = rest.find(MARK) { + let after = &rest[at + MARK.len()..]; + let end = after.find('"').expect("root signature string is closed"); + signatures.push(after[..end].to_owned()); + rest = &after[end + 1..]; + } + } + let lightprobe = include_str!("lightprobe.rs"); + for marker in ["const RS_EXPOSURE: &str = \"", "const RS_LUX: &str = \""] { + let at = lightprobe.find(marker).expect("lightprobe signature exists"); + let after = &lightprobe[at + marker.len()..]; + let end = after.find('"').expect("lightprobe signature is closed"); + signatures.push(after[..end].to_owned()); + } + assert_eq!(signatures.len(), 18, "built-in signature inventory changed"); + signatures + } + + fn compiler_diagnostic(source: &str, entry: windows::core::PCSTR) -> String { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + let mut code = None; + let mut errors = None; + let result = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory"), + None, + None, + entry, + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + match result { + Ok(()) => "secondary D3DCompile call succeeded".to_owned(), + Err(error) => errors.map_or_else( + || format!("{error:?}; no compiler diagnostic blob"), + |blob: ID3DBlob| unsafe { + let bytes = std::slice::from_raw_parts( + blob.GetBufferPointer().cast::<u8>(), + blob.GetBufferSize(), + ); + String::from_utf8_lossy(bytes).into_owned() + }, + ), + } + } + + #[test] + fn recognizes_supported_filter_constants() { + let cases = [ + ("FILTER_MIN_MAG_MIP_POINT", D3D12_FILTER_MIN_MAG_MIP_POINT), + ("FILTER_MIN_MAG_POINT_MIP_LINEAR", D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR), + ("FILTER_MIN_POINT_MAG_MIP_LINEAR", D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR), + ("FILTER_MIN_LINEAR_MAG_MIP_POINT", D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT), + ("FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR", D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR), + ("FILTER_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MIN_MAG_MIP_LINEAR), + ("FILTER_MIN_MAG_LINEAR_MIP_POINT", D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT), + ("FILTER_ANISOTROPIC", D3D12_FILTER_ANISOTROPIC), + ("FILTER_COMPARISON_MIN_MAG_MIP_POINT", D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT), + ("FILTER_COMPARISON_MIN_MAG_MIP_LINEAR", D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR), + ("FILTER_COMPARISON_ANISOTROPIC", D3D12_FILTER_COMPARISON_ANISOTROPIC), + ("FILTER_MINIMUM_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR), + ("FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR", D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR), + ]; + for (name, expected) in cases { + assert_eq!(filter(name), Some(expected), "{name}"); + } + assert_eq!(filter("FILTER_UNKNOWN"), None); + } + + #[test] + fn parses_builtin_shader_root_signatures() { + for signature in builtin_signatures() { + assert!(parse(&signature).is_some(), "unsupported root signature: {signature}"); + } + } + + #[test] + #[ignore = "requires a working D3D12 host device"] + fn creates_builtin_root_signatures_on_host_device() { + let mut device: Option<ID3D12Device> = None; + unsafe { + D3D12CreateDevice( + None::<&windows::core::IUnknown>, + windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0, + &mut device, + ) + .expect("D3D12 device creation"); + } + let device = device.expect("D3D12CreateDevice returned no device"); + let luid = unsafe { device.GetAdapterLuid() }; + let factory = unsafe { + windows::Win32::Graphics::Dxgi::CreateDXGIFactory1::< + windows::Win32::Graphics::Dxgi::IDXGIFactory4, + >() + .expect("DXGI factory creation") + }; + let adapter = unsafe { + factory + .EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid) + .expect("adapter matching the D3D12 device") + }; + let desc = unsafe { adapter.GetDesc1().expect("adapter description") }; + let name_end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let adapter_name = String::from_utf16_lossy(&desc.Description[..name_end]); + let signatures = builtin_signatures(); + for signature in &signatures { + let source = format!("#define RS \"{signature}\""); + make(&device, &source).unwrap_or_else(|e| { + panic!("root signature serialization or creation failed for {signature}: {e:?}") + }); + } + let control_source = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer data : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { data.Store(0, 1); } +"#; + let control_code = crate::host::compile( + control_source, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) + .expect("simple Store-only compute shader compilation"); + let control_root = make(&device, control_source).expect("simple compute root signature"); + let control_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&control_root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: control_code.as_ptr().cast(), + BytecodeLength: control_code.len(), + }, + ..Default::default() + }; + let _control_pso: ID3D12PipelineState = unsafe { + device + .CreateComputePipelineState(&control_desc) + .expect("simple Store-only compute PSO creation") + }; + let readonly_load_source = r#" +#define RS "SRV(t0), UAV(u0)" +ByteAddressBuffer input : register(t0); +RWByteAddressBuffer output : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { output.Store4(0, input.Load4(0)); } +"#; + let readonly_load_code = crate::host::compile( + readonly_load_source, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) + .expect("read-only ByteAddressBuffer Load4 shader compilation"); + let readonly_load_root = make(&device, readonly_load_source) + .expect("read-only ByteAddressBuffer Load4 root signature"); + let readonly_load_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&readonly_load_root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: readonly_load_code.as_ptr().cast(), + BytecodeLength: readonly_load_code.len(), + }, + ..Default::default() + }; + let _readonly_load_pso: ID3D12PipelineState = unsafe { + device + .CreateComputePipelineState(&readonly_load_desc) + .expect("read-only ByteAddressBuffer Load4 PSO creation") + }; + // Compile the fork's actual batching shader with the values selected + // for an AMD adapter by indirect::wide() and indirect::rest(). + let batch = include_str!("indirect/batch.rs"); + let batch_marker = "pub(crate) const SOURCE: &str = r#\""; + let batch_at = batch.find(batch_marker).expect("indirect batch HLSL exists"); + let batch_after = &batch[batch_at + batch_marker.len()..]; + let batch_end = batch_after.find("\"#;").expect("indirect batch HLSL is closed"); + let batch_source = format!( + "#define WIDEST 1048576u\n#define REST 1\n{}", + &batch_after[..batch_end] + ); + let batch_code = match crate::host::compile( + &batch_source, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) { + Ok(code) => code, + Err(e) => { + let diagnostic = compiler_diagnostic( + &batch_source, + windows::core::s!("main"), + ); + if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") { + std::fs::write( + marker, + format!( + "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_compile=failed\n{diagnostic}\n", + signatures.len() + ), + ) + .expect("write batching shader failure diagnostic"); + } + panic!("indirect batching shader compilation failed: {e:?}; {diagnostic}"); + } + }; + let batch_root = make(&device, &batch_source) + .expect("indirect batching root signature creation"); + let batch_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&batch_root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: batch_code.as_ptr().cast(), + BytecodeLength: batch_code.len(), + }, + ..Default::default() + }; + let _batch_pso: ID3D12PipelineState = unsafe { + device + .CreateComputePipelineState(&batch_desc) + .expect("indirect batching compute PSO creation") + }; + let lightprobe = include_str!("lightprobe.rs"); + const HLSL_MARK: &str = "const SOURCE: &str = r#\""; + let source_at = lightprobe.find(HLSL_MARK).expect("lightprobe HLSL source exists"); + let source_after = &lightprobe[source_at + HLSL_MARK.len()..]; + let source_end = source_after.find("\"#;").expect("lightprobe HLSL source is closed"); + let mut hlsl = source_after[..source_end].to_owned(); + let load4_expanded = std::env::var_os("VICTORY_TEST_EXPAND_LOAD4").is_some(); + if load4_expanded { + hlsl = hlsl + .replace("stats.Load4(0)", "uint4(stats.Load(0), stats.Load(4), stats.Load(8), stats.Load(12))") + .replace("output.Load4(0)", "uint4(output.Load(0), output.Load(4), output.Load(8), output.Load(12))"); + } + let mut pipelines = 0; + for (part, rs_marker, entry) in [ + ("EXPOSURE", "const RS_EXPOSURE: &str = \"", windows::core::s!("exposure")), + ("LUX", "const RS_LUX: &str = \"", windows::core::s!("lux")), + ] { + let rs_at = lightprobe.find(rs_marker).expect("lightprobe RS exists"); + let rs_after = &lightprobe[rs_at + rs_marker.len()..]; + let rs_end = rs_after.find('"').expect("lightprobe RS is closed"); + let source = format!("#define {part}\n#define RS \"{}\"\n{hlsl}", &rs_after[..rs_end]); + let code = match crate::host::compile(&source, entry, windows::core::s!("cs_5_1")) { + Ok(code) => code, + Err(e) => { + let diagnostic = compiler_diagnostic(&source, entry); + if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") { + std::fs::write( + marker, + format!( + "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_pso=created\nload4_expanded={load4_expanded}\nlightprobe_part={part}\ncompile=failed\n{diagnostic}\n", + signatures.len() + ), + ) + .expect("write compiler-failure diagnostic"); + } + panic!("lightprobe {part} shader compilation failed: {e:?}; {diagnostic}"); + } + }; + let root = make(&device, &source) + .unwrap_or_else(|e| panic!("lightprobe {part} root signature failed: {e:?}")); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }; + let _pso: ID3D12PipelineState = unsafe { + device + .CreateComputePipelineState(&desc) + .unwrap_or_else(|e| panic!("lightprobe {part} pipeline creation failed: {e:?}")) + }; + pipelines += 1; + } + if let Some(marker) = std::env::var_os("VICTORY_ROOTSTRING_TEST_MARKER") { + std::fs::write( + marker, + format!( + "adapter={adapter_name}\nroot_signatures_created={}\nsimple_compute_pso=created\nreadonly_load4_pso=created\nbatch_indirect_pso=created\nload4_expanded={load4_expanded}\nlightprobe_psos_created={pipelines}\n", + signatures.len() + ), + ) + .expect("write success marker"); + } + } + + #[test] + #[ignore = "requires a working D3D12 host device"] + fn creates_compositor_pipeline_on_host_device() { + let mut device: Option<ID3D12Device> = None; + unsafe { + D3D12CreateDevice( + None::<&windows::core::IUnknown>, + windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0, + &mut device, + ) + .expect("D3D12 device creation"); + } + let device = device.expect("D3D12CreateDevice returned no device"); + let luid = unsafe { device.GetAdapterLuid() }; + let factory = unsafe { + windows::Win32::Graphics::Dxgi::CreateDXGIFactory1::< + windows::Win32::Graphics::Dxgi::IDXGIFactory4, + >() + .expect("DXGI factory creation") + }; + let adapter = unsafe { + factory + .EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid) + .expect("adapter matching the D3D12 device") + }; + let desc = unsafe { adapter.GetDesc1().expect("adapter description") }; + let name_end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let adapter_name = String::from_utf16_lossy(&desc.Description[..name_end]); + + let compose = include_str!("compose.rs"); + const HLSL_MARK: &str = "const SOURCE: &str = r#\""; + let source_at = compose.find(HLSL_MARK).expect("compositor HLSL exists"); + let source_after = &compose[source_at + HLSL_MARK.len()..]; + let source_end = source_after.find("\"#;").expect("compositor HLSL is closed"); + let source = &source_after[..source_end]; + let vs = crate::host::compile(source, windows::core::s!("vs"), windows::core::s!("vs_5_1")) + .expect("compositor vertex shader compilation"); + let ps = crate::host::compile(source, windows::core::s!("ps"), windows::core::s!("ps_5_1")) + .expect("compositor pixel shader compilation"); + let root = make(&device, source).expect("compositor root signature creation"); + let shader = |code: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }; + let mut pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: shader(&vs), + PS: shader(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + pipeline_desc.RTVFormats[0] = + windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + pipeline_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let _pso: ID3D12PipelineState = unsafe { + device + .CreateGraphicsPipelineState(&pipeline_desc) + .expect("compositor graphics PSO creation") + }; + if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_TEST_MARKER") { + std::fs::write( + marker, + format!( + "adapter={adapter_name}\nvs=compiled\nps=compiled\nroot_signature=created\nfilter=FILTER_MIN_MAG_MIP_LINEAR\ngraphics_pso=created\n" + ), + ) + .expect("write compositor test result"); + } + } +} ````
diafebus commented 2026-11-28 10:09:05 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T10:09:05Z.


RDNA2 Proton source patch, part 2 of 2, against 4c79ac5. Save both diff blocks as patch files and apply them together with git apply 1.patch 2.patch. The launch settings and evidence are in the reproduction note.

diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs
index 489dab8..6a36fa4 100644
--- a/crates/victory-gpu/src/ambient.rs
+++ b/crates/victory-gpu/src/ambient.rs
@@ -179,7 +179,7 @@ void keep(uint3 at : SV_DispatchThreadID) {
     for (uint y = 0; y < 5; y++) for (uint x = 0; x < 5; x++) {
         uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY));
         float3 c = max(radiance[p], 0.0);
-        c = any(isnan(c)) || any(isinf(c)) ? 0.0 : c;
+        c = (c.x != c.x || c.y != c.y || c.z != c.z) ? 0.0 : c;
         // Lamps and glints count, but not for everything.
         sum += c / max(1.0, dot(c, LUMA) / 20.0);
     }
@@ -364,10 +364,14 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option<ID3D12Resource>) -
     let mut root: Option<ID3D12RootSignature> = None;
     let mut pipeline = |part: &str, entry| -> windows::core::Result<ID3D12PipelineState> {
         let code = crate::host::compile(&format!("#define {part}\n{SOURCE}"), entry, s!("cs_5_1"))?;
-        // SAFETY: the root signature is inside the shader; plain creations.
+        // SAFETY: plain creations.
         unsafe {
             if root.is_none() {
-                root = Some(device.CreateRootSignature(0, &code)?);
+                // Not the blob: under Wine the host refuses the signature
+                // inside it (E_FAIL), while a description read from the
+                // source's `RS` and serialized here works, as the title's
+                // own signatures do. Every pass shares it.
+                root = Some(crate::rootstring::make(device, SOURCE)?);
             }
             let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
                 pRootSignature: std::mem::transmute_copy(&root),
diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs
index dfcf50b..4627990 100644
--- a/crates/victory-gpu/src/compose.rs
+++ b/crates/victory-gpu/src/compose.rs
@@ -72,11 +72,11 @@ impl Composer {
         );
         // SAFETY: the blobs' own bytes, alive through the calls.
         unsafe {
-            let bytes = |b: &ID3DBlob| {
-                std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize())
-            };
             let device = &host.device;
-            let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?;
+            // Not the blob: under Wine the host refuses the signature inside
+            // it (E_FAIL), while a description read from the source's `RS`
+            // and serialized here works, as the title's own signatures do.
+            let root: ID3D12RootSignature = crate::rootstring::make(device, SOURCE)?;
             let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE {
                 pShaderBytecode: b.GetBufferPointer(),
                 BytecodeLength: b.GetBufferSize(),
@@ -218,6 +218,9 @@ mod tests {
     fn composes_scaled_premultiplied_plane_on_gpu() {
         let Some(host) = crate::host::host() else {
             eprintln!("skipping display-plane readback: no D3D12 device");
+            if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_GPU_MARKER") {
+                std::fs::write(marker, "host_device=unavailable\n").unwrap();
+            }
             return;
         };
         let format = DXGI_FORMAT_R8G8B8A8_UNORM;
@@ -310,6 +313,13 @@ mod tests {
             let start = mapped.cast::<u8>().add(footprint.Offset as usize);
             let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap();
             buffer.Unmap(0, None);
+            if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_GPU_MARKER") {
+                std::fs::write(
+                    marker,
+                    format!("host_device=created\noutput=3x1 RGBA8\npixels={pixels:?}\n"),
+                )
+                .unwrap();
+            }
             for (actual, expected) in pixels
                 .iter()
                 .zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255])
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index d9c09bb..5bfad53 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -1741,10 +1741,12 @@ impl PlanePass {
             pShaderBytecode: bytes.as_ptr().cast(),
             BytecodeLength: bytes.len(),
         };
-        // SAFETY: the root signature is inside the pixel shader; the
+        // Not the blob: under Wine the host refuses the signature inside it
+        // (E_FAIL), while a description read from the source's `RS` and
+        // serialized here works, as the title's own signatures do. The
         // description points at live data and never releases its pointer.
         unsafe {
-            let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
+            let root: ID3D12RootSignature = crate::rootstring::make(device, source)?;
             let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
                 pRootSignature: std::mem::transmute_copy(&root),
                 VS: code(&vs[..]),
@@ -2354,7 +2356,7 @@ cbuffer Span : register(b0) {
 ByteAddressBuffer now : register(t0);
 // 16 bytes per piece of the copy: the hash of its bytes when they were
 // last sent up (or hashed whole, the first time).
-RWByteAddressBuffer hashes : register(u0);
+RWStructuredBuffer<uint4> hashes : register(u0);
 RWByteAddressBuffer differs : register(u1);
 groupshared uint4 parts[64];
 [RootSignature(RS)]
@@ -2413,12 +2415,12 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
     if (compare != 0u) {
         // The flag, and above it 31 bits of the hash (`torn`).
         uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
-        differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
+        differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes[piece]) ? 1u : 0u));
         // With the copy-back on its own thread: the next compare of the
         // piece finds what is written from here on.
-        if (compare == 2u) hashes.Store4(piece * 16u, h);
+        if (compare == 2u) hashes[piece] = h;
     } else {
-        hashes.Store4(piece * 16u, h);
+        hashes[piece] = h;
     }
 }
 "#;
@@ -4637,11 +4639,13 @@ impl Host {
         const RESULTS: u64 = 1 << 20;
         let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
         name(&differs, || "card compare results".into());
-        // SAFETY: the blob's own bytes; the root signature is inside the
-        // shader.
+        // Not the blob: under Wine the host refuses the signature inside it
+        // (E_FAIL), while a description read from the source's `RS` and
+        // serialized here works, as the title's own signatures do.
+        let root = crate::rootstring::make(&self.device, CARD_COMPARE)?;
+        // SAFETY: the blob's own bytes.
         unsafe {
             let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
-            let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
             let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
                 pRootSignature: std::mem::transmute_copy(&root),
                 CS: D3D12_SHADER_BYTECODE {
diff --git a/crates/victory-gpu/src/host/awake.rs b/crates/victory-gpu/src/host/awake.rs
index 14f6ea5..b452108 100644
--- a/crates/victory-gpu/src/host/awake.rs
+++ b/crates/victory-gpu/src/host/awake.rs
@@ -126,7 +126,10 @@ fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> w
     // root signature is inside it. Two closed lists, sent in turn, whose
     // objects live until what was sent last has run.
     unsafe {
-        let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?;
+        // Not the blob: under Wine the host refuses the signature inside it
+        // (E_FAIL), while a description read from the source's `RS` and
+        // serialized here works, as the title's own signatures do.
+        let root: ID3D12RootSignature = crate::rootstring::make(device, COUNT)?;
         let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
             pRootSignature: std::mem::transmute_copy(&root),
             CS: D3D12_SHADER_BYTECODE {
diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs
index a96e60a..139ed51 100644
--- a/crates/victory-gpu/src/host/send.rs
+++ b/crates/victory-gpu/src/host/send.rs
@@ -83,10 +83,12 @@ fn pass(host: &Host) -> Option<&'static Pass> {
     static PASS: OnceLock<Option<Pass>> = OnceLock::new();
     PASS.get_or_init(|| {
         let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
-        // SAFETY: the code lives through the calls; the root signature is
-        // inside it.
+        // SAFETY: the code lives through the calls. Not the blob for the
+        // root signature: under Wine the host refuses the signature inside
+        // it (E_FAIL), while a description read from the source's `RS` and
+        // serialized here works, as the title's own signatures do.
         unsafe {
-            let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
+            let root: ID3D12RootSignature = crate::rootstring::make(&host.device, SCATTER).ok()?;
             let pso: ID3D12PipelineState = host
                 .device
                 .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs
index d82a0c9..888d66a 100644
--- a/crates/victory-gpu/src/host/upcheck.rs
+++ b/crates/victory-gpu/src/host/upcheck.rs
@@ -69,10 +69,12 @@ fn pass(host: &Host) -> Option<&'static Pass> {
     static PASS: OnceLock<Option<Pass>> = OnceLock::new();
     PASS.get_or_init(|| {
         let code = compile(SOURCE, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
-        // SAFETY: the code lives through the calls; the root signature is
-        // inside it.
+        // SAFETY: the code lives through the calls. Not the blob for the
+        // root signature: under Wine the host refuses the signature inside
+        // it (E_FAIL), while a description read from the source's `RS` and
+        // serialized here works, as the title's own signatures do.
         unsafe {
-            let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
+            let root: ID3D12RootSignature = crate::rootstring::make(&host.device, SOURCE).ok()?;
             let pso: ID3D12PipelineState = host
                 .device
                 .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs
index e50f572..c52730c 100644
--- a/crates/victory-gpu/src/indirect.rs
+++ b/crates/victory-gpu/src/indirect.rs
@@ -60,7 +60,7 @@ ByteAddressBuffer count_buf : register(t1);
 RWByteAddressBuffer dst_args : register(u0);
 // The list's work so far (vertex instances, threads): past the budget,
 // records run empty.
-RWByteAddressBuffer budget : register(u1);
+RWStructuredBuffer<uint> budget : register(u1);
 static const uint BUDGET = 1u << 27;
 // The vertices or indices an instance from which a draw record runs empty.
 static const uint MOST_DRAW = 1u << 23;
@@ -161,8 +161,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
         // (`rest`).
         // Only the group's own records are walked (one, clamped alone).
         uint before;
-        budget.InterlockedOr(0, 0, before);
-        [allow_uav_condition]
+        InterlockedOr(budget[0], 0, before);
         while (before < BUDGET) {
             uint next = before;
             for (uint j = 0; j < n; j++) {
@@ -173,7 +172,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
             }
             if (next == before) break;
             uint prev;
-            budget.InterlockedCompareExchange(0, before, next, prev);
+            InterlockedCompareExchange(budget[0], before, next, prev);
             if (prev == before) break;
             before = prev;
         }
@@ -195,17 +194,17 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
         // the largest cost there was (small ones are not told).
         uint told;
         if (refused > 0) {
-            budget.InterlockedAdd(12, refused, told);
+            InterlockedAdd(budget[3], refused, told);
         }
         if (biggest >= (1u << 22)) {
-            budget.InterlockedMax(16, biggest, told);
+            InterlockedMax(budget[4], biggest, told);
         }
     }
     GroupMemoryBarrierWithGroupSync();
     if (gi == 0 && kind > 2 && n > 0) {
         uint was;
-        budget.InterlockedMax(4, largest_asked, was);
-        budget.InterlockedAdd(8, all_asked, was);
+        InterlockedMax(budget[1], largest_asked, was);
+        InterlockedAdd(budget[2], all_asked, was);
     }
     if (!active) {
         return;
@@ -339,11 +338,15 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp
         return Err(e);
     }
     let code = code.ok_or_else(windows::core::Error::empty)?;
-    // SAFETY: the blob's own bytes; the root signature is inside the shader.
+    // The blob is not handed to `CreateRootSignature`: under Wine the host
+    // refuses the signature inside it (E_FAIL), while a description read
+    // from the source's `RS` and serialized here works, as the title's own
+    // signatures do.
+    let root = crate::rootstring::make(device, source)?;
+    // SAFETY: the blob's own bytes.
     unsafe {
         let bytes =
             std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
-        let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
         let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
             pRootSignature: std::mem::transmute_copy(&root),
             CS: D3D12_SHADER_BYTECODE {
@@ -639,15 +642,26 @@ pub(crate) mod tests {
 
     const WORKER_CS: &str = r#"
 #define RS "UAV(u0)"
-RWByteAddressBuffer hits : register(u0);
+RWStructuredBuffer<uint> hits : register(u0);
 [RootSignature(RS)]
 [numthreads(1, 1, 1)]
 void main() {
     uint prev;
-    hits.InterlockedAdd(0, 1, prev);
+    InterlockedAdd(hits[0], 1, prev);
 }
 "#;
 
+    /// Optional stage log for host GPU tests run through Proton, where Rust's
+    /// test-harness output is not reliably forwarded by the wrapper.
+    fn test_stage(message: &str) {
+        if let Some(path) = std::env::var_os("VICTORY_TEST_STAGE_FILE") {
+            if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
+                use std::io::Write;
+                let _ = writeln!(file, "{message}");
+            }
+        }
+    }
+
     struct WarpHarness {
         device: ID3D12Device,
         queue: ID3D12CommandQueue,
@@ -851,7 +865,8 @@ void main() {
         let mut code: Option<ID3DBlob> = None;
         // SAFETY: source and entry names outlive `D3DCompile`.
         unsafe {
-            D3DCompile(
+            test_stage("D3DCompile begin");
+            if let Err(error) = D3DCompile(
                 source.as_ptr().cast(),
                 source.len(),
                 s!("worker"),
@@ -863,21 +878,41 @@ void main() {
                 0,
                 &mut code,
                 None,
-            )?;
+            ) {
+                test_stage(&format!("D3DCompile failed: {error}"));
+                return Err(error);
+            }
+            test_stage("D3DCompile succeeded");
             let code = code.unwrap();
             let bytes = std::slice::from_raw_parts(
                 code.GetBufferPointer().cast::<u8>(),
                 code.GetBufferSize(),
             );
-            let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
-            let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+            test_stage("rootstring::make begin");
+            let root: ID3D12RootSignature = match crate::rootstring::make(device, source) {
+                Ok(root) => root,
+                Err(error) => {
+                    test_stage(&format!("rootstring::make failed: {error}"));
+                    return Err(error);
+                }
+            };
+            test_stage("rootstring::make succeeded");
+            test_stage("CreateComputePipelineState begin");
+            let pso = match device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
                 pRootSignature: std::mem::transmute_copy(&root),
                 CS: D3D12_SHADER_BYTECODE {
                     pShaderBytecode: bytes.as_ptr().cast(),
                     BytecodeLength: bytes.len(),
                 },
                 ..Default::default()
-            })?;
+            }) {
+                Ok(pso) => pso,
+                Err(error) => {
+                    test_stage(&format!("CreateComputePipelineState failed: {error}"));
+                    return Err(error);
+                }
+            };
+            test_stage("CreateComputePipelineState succeeded");
             Ok(Clamp { root, pso })
         }
     }
@@ -968,17 +1003,22 @@ void main() {
     #[test]
     #[ignore]
     fn card_compare_costs() {
+        test_stage("card_compare_costs begin");
         let Some(mut gpu) = WarpHarness::on(false) else {
+            test_stage("adapter 0 unavailable; benchmark returned early");
             return;
         };
+        test_stage(&format!("adapter 0 D3D12 device created amd={} widest={}", amd(&gpu.device), widest(true)));
         let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap());
         let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str()));
         let walked_alone = source.contains("SV_DispatchThreadID");
         let compare = compile_cs(&gpu.device, source).expect("the compare must compile");
+        test_stage(&format!("card-compare shader compiled walked_alone={walked_alone}"));
         let now = gpu.default_uav(256 << 20);
         let hashes = gpu.default_uav(64 << 10);
         let differs = gpu.default_uav(64 << 10);
         for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] {
+            test_stage(&format!("benchmark variant begin rounds={rounds} passes={passes} pieces={pieces}"));
             let mut best = f64::MAX;
             for _ in 0..6 {
                 // SAFETY: our open list, live buffers, the compare's own
@@ -1013,7 +1053,9 @@ void main() {
             }
             let mb = f64::from(rounds * passes * pieces) / 16.0;
             println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024);
+            test_stage(&format!("benchmark variant complete rounds={rounds} passes={passes} pieces={pieces} best_ms={best:.2} mb={mb:.0}"));
         }
+        test_stage("card_compare_costs complete");
     }
 
     /// What raw loads through views that are not raw give past the view's
@@ -2483,18 +2525,25 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
     /// the host device.
     #[test]
     fn host_list_reuses_and_grows_scratch_across_submissions() {
+        test_stage("host_list_reuses_and_grows_scratch_across_submissions begin");
         let Some(host) = super::host() else {
+            test_stage("host D3D12 device unavailable; test returned early");
             return;
         };
+        test_stage("host D3D12 device available");
         // What earlier tests left in the debug layer's queue, if it is on.
         let _ = host.log_messages();
         let Ok(list) = host.new_list() else {
+            test_stage("command list unavailable; test returned early");
             return;
         };
+        test_stage("command list created");
         let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
+            test_stage("source buffer unavailable; test returned early");
             return;
         };
         let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
+            test_stage("count buffer unavailable; test returned early");
             return;
         };
         // SAFETY: mapped host buffers.
@@ -2513,6 +2562,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             args,
             "a clamp leaves the scratch readable as arguments"
         );
+        test_stage("initial scratch allocation ready");
         let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
         assert_eq!(
             b1.as_raw(),
@@ -2520,6 +2570,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             "scratch buffer within capacity must be reused"
         );
         assert_eq!(list.indirect_state(&b2), args);
+        test_stage("within-capacity scratch reused");
 
         // A call needing >64 KiB grows the scratch buffer mid-list while keeping
         // `b1` alive until reset. The new buffer starts out common.
@@ -2542,6 +2593,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             D3D12_RESOURCE_STATE_COMMON,
             "the replaced buffer went back to common"
         );
+        test_stage("scratch grew beyond 64 KiB and old buffer returned to common");
 
         list.close();
         // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics):
@@ -2550,6 +2602,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
         assert_eq!(host.log_messages(), None, "the debug layer found an error");
         host.execute(&[&list]);
         list.reset();
+        test_stage("first submission completed and list reset");
 
         // After reset, requests up to the grown high-water mark reuse `b3` with
         // zero new allocations; the buffer decayed to common when the
@@ -2566,10 +2619,12 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             "grown scratch buffer must persist across reset"
         );
         assert_eq!(list.indirect_state(&b4), args);
+        test_stage("grown scratch reused after reset");
         list.close();
         assert_eq!(host.log_messages(), None, "the debug layer found an error");
         host.execute(&[&list]);
         list.reset();
+        test_stage("host_list_reuses_and_grows_scratch_across_submissions complete");
     }
 
     /// A group charges its records in lane order: with 300 left of the
@@ -2666,14 +2721,20 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
     /// small record still runs.
     #[test]
     fn host_list_budget_starts_empty_at_each_submission() {
+        test_stage("host_list_budget_starts_empty_at_each_submission begin");
         let Some(host) = super::host() else {
+            test_stage("host D3D12 device unavailable; test returned early");
             return;
         };
+        test_stage("host D3D12 device available");
         let Ok(list) = host.new_list() else {
+            test_stage("command list unavailable; test returned early");
             return;
         };
+        test_stage("command list created");
         let _ = host.log_messages();
         let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
+        test_stage("worker pipeline ready");
         const KIND_DISPATCH: u32 = 2;
         const STRIDE: u32 = 12;
         let signature = {
@@ -2722,6 +2783,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
         // SAFETY: a live buffer.
         let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
         for round in 0..2 {
+            test_stage(&format!("budget-spent submission {round} begin"));
             // Spends the budget (clamped, not executed), then one group.
             bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap();
             let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
@@ -2742,9 +2804,11 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             // The small record comes after the big ones spent the budget:
             // it runs empty, in every round alike (none carries over).
             assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it");
+            test_stage(&format!("budget-spent submission {round} readback hits={hits}"));
         }
         // A recording with only the small record: the budget is empty
         // again, so it runs.
+        test_stage("fresh-budget submission begin");
         let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
         // SAFETY: as above.
         unsafe {
@@ -2760,6 +2824,8 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
         // SAFETY: the list has run; a mapped buffer.
         let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
         assert_eq!(hits, 1, "the budget starts empty at the next submission");
+        test_stage(&format!("fresh-budget submission readback hits={hits}"));
+        test_stage("host_list_budget_starts_empty_at_each_submission complete");
     }
 
     /// Records the dispatch records `groups` (three words each, `step`
@@ -2851,15 +2917,21 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
     /// diagnostics build) no barrier names a state the buffer is not in.
     #[test]
     fn host_list_window_executions_need_no_barrier_of_their_own() {
+        test_stage("host_list_window_executions_need_no_barrier_of_their_own begin");
         let Some(host) = super::host() else {
+            test_stage("host D3D12 device unavailable; test returned early");
             return;
         };
+        test_stage("host D3D12 device available");
         // What earlier tests left in the debug layer's queue, if it is on.
         let _ = host.log_messages();
         let Ok(list) = host.new_list() else {
+            test_stage("command list unavailable; test returned early");
             return;
         };
+        test_stage("command list created");
         let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
+        test_stage("worker pipeline ready");
         const KIND_DISPATCH: u32 = 2;
         const STRIDE: u32 = 12;
         const STEP: u32 = 32;
@@ -2908,6 +2980,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
         // SAFETY: a live buffer.
         let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
         for _ in 0..2 {
+            test_stage("window-pair submission begin");
             // SAFETY: the mapping holds 256 bytes; nothing runs.
             unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
             for (groups, src) in windows.iter().zip(&sources) {
@@ -2935,7 +3008,9 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
             // SAFETY: the list has run; a mapped buffer.
             let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
             assert_eq!(hits, expected, "every record of both windows runs once");
+            test_stage(&format!("window-pair submission readback hits={hits} expected={expected}"));
         }
+        test_stage("host_list_window_executions_need_no_barrier_of_their_own complete");
     }
 
     /// A command signature of one argument of `kind` on `device`.
@@ -2963,31 +3038,41 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
     /// ([`widest`]), clamped one by one and in a batch. Others are not asked.
     #[test]
     fn card_runs_wide_indirect_dispatches() {
+        test_stage("card_runs_wide_indirect_dispatches begin");
         const CS: &str = r#"
 #define RS "UAV(u0)"
-RWByteAddressBuffer seen : register(u0);
+RWStructuredBuffer<uint> seen : register(u0);
 [RootSignature(RS)]
 [numthreads(1, 1, 1)]
 void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
     uint was;
-    seen.InterlockedAdd(0, 1, was);
-    seen.InterlockedMax(4, group.x, was);
-    seen.InterlockedMax(8, thread.x, was);
-    seen.InterlockedAdd(16 + group.x * 4, 1, was);
+    InterlockedAdd(seen[0], 1, was);
+    InterlockedMax(seen[1], group.x, was);
+    InterlockedMax(seen[2], thread.x, was);
+    InterlockedAdd(seen[4 + group.x], 1, was);
 }
 "#;
         let Some(mut gpu) = WarpHarness::on(false) else {
+            test_stage("adapter 0 unavailable; test returned early");
             return;
         };
-        if !amd(&gpu.device) || widest(true) == 65_535 {
+        test_stage("adapter 0 D3D12 device created");
+        let is_amd = amd(&gpu.device);
+        let max_wide = widest(true);
+        test_stage(&format!("amd={is_amd} widest={max_wide}"));
+        if !is_amd || max_wide == 65_535 {
+            test_stage("adapter does not meet AMD wide-dispatch test conditions; returned early");
             return;
         }
         let worker = compile_cs(&gpu.device, CS).expect("the worker must compile");
+        test_stage("structured wide-dispatch worker compiled");
         let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
+        test_stage("fork batch clamp compiled");
         let sig = gpu.signature(2, 12);
         for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] {
             let runs = if asked > 1 << 20 { 65_535 } else { asked };
             for batched in [false, true] {
+                test_stage(&format!("dispatch begin asked={asked} batched={batched} expected_groups={runs}"));
                 let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024);
                 let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256);
                 let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE);
@@ -3022,9 +3107,11 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
                 let word = |i: usize| unsafe { back_ptr.cast::<u32>().add(i).read_volatile() };
                 assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}");
                 let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1);
+                test_stage(&format!("dispatch readback asked={asked} batched={batched} observed=[{},{},{}] wrong_group={wrong:?}", word(0), word(1), word(2)));
                 assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}");
             }
         }
+        test_stage("card_runs_wide_indirect_dispatches complete");
     }
 
     /// What a batch's table says of records added to it: one job per
@@ -3203,18 +3290,25 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
     /// the debug layer on no barrier names a state the buffer is not in.
     #[test]
     fn host_list_batches() {
+        test_stage("host_list_batches begin");
         let Some(host) = super::host() else {
+            test_stage("host D3D12 device unavailable; test returned early");
             return;
         };
+        test_stage("host D3D12 device available");
         let _ = host.log_messages();
         let Ok(list) = host.new_list() else {
+            test_stage("command list unavailable; test returned early");
             return;
         };
+        test_stage("command list created");
         let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
+        test_stage("worker pipeline ready");
         let signature = one_argument(&host.device, 2, 12);
         let mut sources = Vec::new();
         for first in [1u32, 100] {
             let Some((buffer, ptr)) = host.shared_buffer(1024) else {
+                test_stage("source buffer unavailable; test returned early");
                 return;
             };
             for i in 0..16u32 {
@@ -3226,11 +3320,13 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
             sources.push(buffer);
         }
         let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
+            test_stage("hits buffer unavailable; test returned early");
             return;
         };
         // SAFETY: a live buffer.
         let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
         for _ in 0..2 {
+            test_stage("batch pass begin");
             // SAFETY: the mapping holds 256 bytes; nothing runs.
             unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
             let mut expected = 0;
@@ -3253,13 +3349,19 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
                 }
             }
             list.close();
-            assert_eq!(host.log_messages(), None, "the debug layer found an error");
+            if let Some(messages) = host.log_messages() {
+                test_stage(&format!("D3D12 debug messages: {messages:?}"));
+                assert!(false, "the debug layer found an error");
+            }
+            test_stage("executing command list");
             host.execute(&[&list]);
             list.reset();
             // SAFETY: the list has run; a mapped buffer.
             let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
+            test_stage(&format!("readback hits={hits} expected={expected}"));
             assert_eq!(hits, expected, "every execution runs what it asked for");
         }
+        test_stage("host_list_batches complete");
     }
 
     /// What clamps of a frame cost on the card one by one and in batches
@@ -3268,11 +3370,15 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
     #[test]
     #[ignore]
     fn batch_costs() {
+        test_stage("batch_costs begin");
         let Some(mut gpu) = WarpHarness::on(false) else {
+            test_stage("adapter 0 unavailable; benchmark returned early");
             return;
         };
+        test_stage(&format!("adapter 0 D3D12 device created amd={} widest={}", amd(&gpu.device), widest(true)));
         const EXECUTIONS: u32 = 2355;
         let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
+        test_stage("fork batch clamp compiled");
         let sig = gpu.signature(2, 12);
         let groups: Vec<u32> = vec![1; 2048];
         let src = dispatch_records(&gpu, &groups, 32);
@@ -3285,6 +3391,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
         let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400);
         let dst = gpu.default_uav(4 << 20);
         for run in [0u32, 2355 / 49, 5, 1] {
+            test_stage(&format!("benchmark variant begin batch_interval={run}"));
             let mut best = f64::MAX;
             for _ in 0..6 {
                 let mut state = D3D12_RESOURCE_STATE_COMMON;
@@ -3316,7 +3423,9 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
             }
             let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") };
             println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms");
+            test_stage(&format!("benchmark variant complete batch_interval={run} best_gpu_submit_ms={best:.2}"));
         }
+        test_stage("batch_costs complete");
     }
 }
 
diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs
index d4f192d..a66ce6c 100644
--- a/crates/victory-gpu/src/indirect/batch.rs
+++ b/crates/victory-gpu/src/indirect/batch.rs
@@ -40,7 +40,7 @@ ByteAddressBuffer src3 : register(t3);
 // record's offset in the source; its place in the scratch buffer; nothing.
 ByteAddressBuffer jobs : register(t4);
 RWByteAddressBuffer dst_args : register(u0);
-RWByteAddressBuffer budget : register(u1);
+RWStructuredBuffer<uint> budget : register(u1);
 static const uint BUDGET = 1u << 27;
 static const uint GROUPS = 1u << 20;
 groupshared uint costs[64];
@@ -117,8 +117,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
     uint n = count > first ? min(64u, count - first) : 0u;
     if (gi == 0 && n > 0) {
         uint before;
-        budget.InterlockedOr(0, 0, before);
-        [allow_uav_condition]
+        InterlockedOr(budget[0], 0, before);
         while (before < BUDGET) {
             uint next = before;
             for (uint j = 0; j < n; j++) {
@@ -129,7 +128,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
             }
             if (next == before) break;
             uint prev;
-            budget.InterlockedCompareExchange(0, before, next, prev);
+            InterlockedCompareExchange(budget[0], before, next, prev);
             if (prev == before) break;
             before = prev;
         }
@@ -151,17 +150,17 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
         // the largest cost there was (small ones are not told).
         uint told;
         if (refused > 0) {
-            budget.InterlockedAdd(12, refused, told);
+            InterlockedAdd(budget[3], refused, told);
         }
         if (biggest >= (1u << 22)) {
-            budget.InterlockedMax(16, biggest, told);
+            InterlockedMax(budget[4], biggest, told);
         }
     }
     GroupMemoryBarrierWithGroupSync();
     if (gi == 0 && n > 0 && all_asked > 0) {
         uint was;
-        budget.InterlockedMax(4, largest_asked, was);
-        budget.InterlockedAdd(8, all_asked, was);
+        InterlockedMax(budget[1], largest_asked, was);
+        InterlockedAdd(budget[2], all_asked, was);
     }
     if (!active) {
         return;
diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs
index 98edeca..d0ed138 100644
--- a/crates/victory-gpu/src/inplace.rs
+++ b/crates/victory-gpu/src/inplace.rs
@@ -804,12 +804,15 @@ impl Rig {
         const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n";
         let mut code: Option<ID3DBlob> = None;
         // SAFETY: the source and names live through the call; then the
-        // blob's own bytes, which hold the root signature too.
+        // blob's own bytes.
         let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe {
             D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?;
             let code = code.ok_or_else(windows::core::Error::empty)?;
+            // Not the blob: under Wine the host refuses the signature inside
+            // it (E_FAIL), while a description read from the source's `RS`
+            // and serialized here works, as the title's own signatures do.
+            let root = crate::rootstring::make(&self.device, SOURCE)?;
             let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
-            let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
             let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
                 pRootSignature: std::mem::transmute_copy(&root),
                 CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() },
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index 19ae3c5..547e50d 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -82,6 +82,8 @@ mod residency;
 pub mod resource;
 pub mod root;
 #[cfg(windows)]
+mod rootstring;
+#[cfg(windows)]
 mod safecopy;
 #[cfg(windows)]
 mod sampler;
diff --git a/crates/victory-gpu/src/replay/play/merge.rs b/crates/victory-gpu/src/replay/play/merge.rs
index daddcd0..4729ea9 100644
--- a/crates/victory-gpu/src/replay/play/merge.rs
+++ b/crates/victory-gpu/src/replay/play/merge.rs
@@ -174,7 +174,10 @@ impl Player {
                 code.GetBufferPointer().cast::<u8>(),
                 code.GetBufferSize(),
             );
-            let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
+            // Not the blob: under Wine the host refuses the signature inside
+            // it (E_FAIL), while a description read from the source's `RS`
+            // and serialized here works, as the title's own signatures do.
+            let root: ID3D12RootSignature = crate::rootstring::make(&self.device, SOURCE)?;
             let pso =
                 self.device
                     .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7237704678 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237704678). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T10:09:05Z. --- RDNA2 Proton source patch, part 2 of 2, against `4c79ac5`. Save both diff blocks as patch files and apply them together with `git apply 1.patch 2.patch`. The launch settings and evidence are in [the reproduction note](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7237482162). ````diff diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index 489dab8..6a36fa4 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -179,7 +179,7 @@ void keep(uint3 at : SV_DispatchThreadID) { for (uint y = 0; y < 5; y++) for (uint x = 0; x < 5; x++) { uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY)); float3 c = max(radiance[p], 0.0); - c = any(isnan(c)) || any(isinf(c)) ? 0.0 : c; + c = (c.x != c.x || c.y != c.y || c.z != c.z) ? 0.0 : c; // Lamps and glints count, but not for everything. sum += c / max(1.0, dot(c, LUMA) / 20.0); } @@ -364,10 +364,14 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option<ID3D12Resource>) - let mut root: Option<ID3D12RootSignature> = None; let mut pipeline = |part: &str, entry| -> windows::core::Result<ID3D12PipelineState> { let code = crate::host::compile(&format!("#define {part}\n{SOURCE}"), entry, s!("cs_5_1"))?; - // SAFETY: the root signature is inside the shader; plain creations. + // SAFETY: plain creations. unsafe { if root.is_none() { - root = Some(device.CreateRootSignature(0, &code)?); + // Not the blob: under Wine the host refuses the signature + // inside it (E_FAIL), while a description read from the + // source's `RS` and serialized here works, as the title's + // own signatures do. Every pass shares it. + root = Some(crate::rootstring::make(device, SOURCE)?); } let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs index dfcf50b..4627990 100644 --- a/crates/victory-gpu/src/compose.rs +++ b/crates/victory-gpu/src/compose.rs @@ -72,11 +72,11 @@ impl Composer { ); // SAFETY: the blobs' own bytes, alive through the calls. unsafe { - let bytes = |b: &ID3DBlob| { - std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize()) - }; let device = &host.device; - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + // Not the blob: under Wine the host refuses the signature inside + // it (E_FAIL), while a description read from the source's `RS` + // and serialized here works, as the title's own signatures do. + let root: ID3D12RootSignature = crate::rootstring::make(device, SOURCE)?; let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize(), @@ -218,6 +218,9 @@ mod tests { fn composes_scaled_premultiplied_plane_on_gpu() { let Some(host) = crate::host::host() else { eprintln!("skipping display-plane readback: no D3D12 device"); + if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_GPU_MARKER") { + std::fs::write(marker, "host_device=unavailable\n").unwrap(); + } return; }; let format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -310,6 +313,13 @@ mod tests { let start = mapped.cast::<u8>().add(footprint.Offset as usize); let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap(); buffer.Unmap(0, None); + if let Some(marker) = std::env::var_os("VICTORY_COMPOSITOR_GPU_MARKER") { + std::fs::write( + marker, + format!("host_device=created\noutput=3x1 RGBA8\npixels={pixels:?}\n"), + ) + .unwrap(); + } for (actual, expected) in pixels .iter() .zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255]) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d9c09bb..5bfad53 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1741,10 +1741,12 @@ impl PlanePass { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len(), }; - // SAFETY: the root signature is inside the pixel shader; the + // Not the blob: under Wine the host refuses the signature inside it + // (E_FAIL), while a description read from the source's `RS` and + // serialized here works, as the title's own signatures do. The // description points at live data and never releases its pointer. unsafe { - let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?; + let root: ID3D12RootSignature = crate::rootstring::make(device, source)?; let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), VS: code(&vs[..]), @@ -2354,7 +2356,7 @@ cbuffer Span : register(b0) { ByteAddressBuffer now : register(t0); // 16 bytes per piece of the copy: the hash of its bytes when they were // last sent up (or hashed whole, the first time). -RWByteAddressBuffer hashes : register(u0); +RWStructuredBuffer<uint4> hashes : register(u0); RWByteAddressBuffer differs : register(u1); groupshared uint4 parts[64]; [RootSignature(RS)] @@ -2413,12 +2415,12 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { if (compare != 0u) { // The flag, and above it 31 bits of the hash (`torn`). uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u); - differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u)); + differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes[piece]) ? 1u : 0u)); // With the copy-back on its own thread: the next compare of the // piece finds what is written from here on. - if (compare == 2u) hashes.Store4(piece * 16u, h); + if (compare == 2u) hashes[piece] = h; } else { - hashes.Store4(piece * 16u, h); + hashes[piece] = h; } } "#; @@ -4637,11 +4639,13 @@ impl Host { const RESULTS: u64 = 1 << 20; let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; name(&differs, || "card compare results".into()); - // SAFETY: the blob's own bytes; the root signature is inside the - // shader. + // Not the blob: under Wine the host refuses the signature inside it + // (E_FAIL), while a description read from the source's `RS` and + // serialized here works, as the title's own signatures do. + let root = crate::rootstring::make(&self.device, CARD_COMPARE)?; + // SAFETY: the blob's own bytes. unsafe { let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { diff --git a/crates/victory-gpu/src/host/awake.rs b/crates/victory-gpu/src/host/awake.rs index 14f6ea5..b452108 100644 --- a/crates/victory-gpu/src/host/awake.rs +++ b/crates/victory-gpu/src/host/awake.rs @@ -126,7 +126,10 @@ fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> w // root signature is inside it. Two closed lists, sent in turn, whose // objects live until what was sent last has run. unsafe { - let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; + // Not the blob: under Wine the host refuses the signature inside it + // (E_FAIL), while a description read from the source's `RS` and + // serialized here works, as the title's own signatures do. + let root: ID3D12RootSignature = crate::rootstring::make(device, COUNT)?; let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index a96e60a..139ed51 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -83,10 +83,12 @@ fn pass(host: &Host) -> Option<&'static Pass> { static PASS: OnceLock<Option<Pass>> = OnceLock::new(); PASS.get_or_init(|| { let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; - // SAFETY: the code lives through the calls; the root signature is - // inside it. + // SAFETY: the code lives through the calls. Not the blob for the + // root signature: under Wine the host refuses the signature inside + // it (E_FAIL), while a description read from the source's `RS` and + // serialized here works, as the title's own signatures do. unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; + let root: ID3D12RootSignature = crate::rootstring::make(&host.device, SCATTER).ok()?; let pso: ID3D12PipelineState = host .device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index d82a0c9..888d66a 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -69,10 +69,12 @@ fn pass(host: &Host) -> Option<&'static Pass> { static PASS: OnceLock<Option<Pass>> = OnceLock::new(); PASS.get_or_init(|| { let code = compile(SOURCE, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; - // SAFETY: the code lives through the calls; the root signature is - // inside it. + // SAFETY: the code lives through the calls. Not the blob for the + // root signature: under Wine the host refuses the signature inside + // it (E_FAIL), while a description read from the source's `RS` and + // serialized here works, as the title's own signatures do. unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; + let root: ID3D12RootSignature = crate::rootstring::make(&host.device, SOURCE).ok()?; let pso: ID3D12PipelineState = host .device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index e50f572..c52730c 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -60,7 +60,7 @@ ByteAddressBuffer count_buf : register(t1); RWByteAddressBuffer dst_args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. -RWByteAddressBuffer budget : register(u1); +RWStructuredBuffer<uint> budget : register(u1); static const uint BUDGET = 1u << 27; // The vertices or indices an instance from which a draw record runs empty. static const uint MOST_DRAW = 1u << 23; @@ -161,8 +161,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { // (`rest`). // Only the group's own records are walked (one, clamped alone). uint before; - budget.InterlockedOr(0, 0, before); - [allow_uav_condition] + InterlockedOr(budget[0], 0, before); while (before < BUDGET) { uint next = before; for (uint j = 0; j < n; j++) { @@ -173,7 +172,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } if (next == before) break; uint prev; - budget.InterlockedCompareExchange(0, before, next, prev); + InterlockedCompareExchange(budget[0], before, next, prev); if (prev == before) break; before = prev; } @@ -195,17 +194,17 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { // the largest cost there was (small ones are not told). uint told; if (refused > 0) { - budget.InterlockedAdd(12, refused, told); + InterlockedAdd(budget[3], refused, told); } if (biggest >= (1u << 22)) { - budget.InterlockedMax(16, biggest, told); + InterlockedMax(budget[4], biggest, told); } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && kind > 2 && n > 0) { uint was; - budget.InterlockedMax(4, largest_asked, was); - budget.InterlockedAdd(8, all_asked, was); + InterlockedMax(budget[1], largest_asked, was); + InterlockedAdd(budget[2], all_asked, was); } if (!active) { return; @@ -339,11 +338,15 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp return Err(e); } let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes; the root signature is inside the shader. + // The blob is not handed to `CreateRootSignature`: under Wine the host + // refuses the signature inside it (E_FAIL), while a description read + // from the source's `RS` and serialized here works, as the title's own + // signatures do. + let root = crate::rootstring::make(device, source)?; + // SAFETY: the blob's own bytes. unsafe { let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -639,15 +642,26 @@ pub(crate) mod tests { const WORKER_CS: &str = r#" #define RS "UAV(u0)" -RWByteAddressBuffer hits : register(u0); +RWStructuredBuffer<uint> hits : register(u0); [RootSignature(RS)] [numthreads(1, 1, 1)] void main() { uint prev; - hits.InterlockedAdd(0, 1, prev); + InterlockedAdd(hits[0], 1, prev); } "#; + /// Optional stage log for host GPU tests run through Proton, where Rust's + /// test-harness output is not reliably forwarded by the wrapper. + fn test_stage(message: &str) { + if let Some(path) = std::env::var_os("VICTORY_TEST_STAGE_FILE") { + if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + use std::io::Write; + let _ = writeln!(file, "{message}"); + } + } + } + struct WarpHarness { device: ID3D12Device, queue: ID3D12CommandQueue, @@ -851,7 +865,8 @@ void main() { let mut code: Option<ID3DBlob> = None; // SAFETY: source and entry names outlive `D3DCompile`. unsafe { - D3DCompile( + test_stage("D3DCompile begin"); + if let Err(error) = D3DCompile( source.as_ptr().cast(), source.len(), s!("worker"), @@ -863,21 +878,41 @@ void main() { 0, &mut code, None, - )?; + ) { + test_stage(&format!("D3DCompile failed: {error}")); + return Err(error); + } + test_stage("D3DCompile succeeded"); let code = code.unwrap(); let bytes = std::slice::from_raw_parts( code.GetBufferPointer().cast::<u8>(), code.GetBufferSize(), ); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; - let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + test_stage("rootstring::make begin"); + let root: ID3D12RootSignature = match crate::rootstring::make(device, source) { + Ok(root) => root, + Err(error) => { + test_stage(&format!("rootstring::make failed: {error}")); + return Err(error); + } + }; + test_stage("rootstring::make succeeded"); + test_stage("CreateComputePipelineState begin"); + let pso = match device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len(), }, ..Default::default() - })?; + }) { + Ok(pso) => pso, + Err(error) => { + test_stage(&format!("CreateComputePipelineState failed: {error}")); + return Err(error); + } + }; + test_stage("CreateComputePipelineState succeeded"); Ok(Clamp { root, pso }) } } @@ -968,17 +1003,22 @@ void main() { #[test] #[ignore] fn card_compare_costs() { + test_stage("card_compare_costs begin"); let Some(mut gpu) = WarpHarness::on(false) else { + test_stage("adapter 0 unavailable; benchmark returned early"); return; }; + test_stage(&format!("adapter 0 D3D12 device created amd={} widest={}", amd(&gpu.device), widest(true))); let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap()); let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str())); let walked_alone = source.contains("SV_DispatchThreadID"); let compare = compile_cs(&gpu.device, source).expect("the compare must compile"); + test_stage(&format!("card-compare shader compiled walked_alone={walked_alone}")); let now = gpu.default_uav(256 << 20); let hashes = gpu.default_uav(64 << 10); let differs = gpu.default_uav(64 << 10); for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] { + test_stage(&format!("benchmark variant begin rounds={rounds} passes={passes} pieces={pieces}")); let mut best = f64::MAX; for _ in 0..6 { // SAFETY: our open list, live buffers, the compare's own @@ -1013,7 +1053,9 @@ void main() { } let mb = f64::from(rounds * passes * pieces) / 16.0; println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024); + test_stage(&format!("benchmark variant complete rounds={rounds} passes={passes} pieces={pieces} best_ms={best:.2} mb={mb:.0}")); } + test_stage("card_compare_costs complete"); } /// What raw loads through views that are not raw give past the view's @@ -2483,18 +2525,25 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// the host device. #[test] fn host_list_reuses_and_grows_scratch_across_submissions() { + test_stage("host_list_reuses_and_grows_scratch_across_submissions begin"); let Some(host) = super::host() else { + test_stage("host D3D12 device unavailable; test returned early"); return; }; + test_stage("host D3D12 device available"); // What earlier tests left in the debug layer's queue, if it is on. let _ = host.log_messages(); let Ok(list) = host.new_list() else { + test_stage("command list unavailable; test returned early"); return; }; + test_stage("command list created"); let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else { + test_stage("source buffer unavailable; test returned early"); return; }; let Some((count_buf, count_ptr)) = host.shared_buffer(256) else { + test_stage("count buffer unavailable; test returned early"); return; }; // SAFETY: mapped host buffers. @@ -2513,6 +2562,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { args, "a clamp leaves the scratch readable as arguments" ); + test_stage("initial scratch allocation ready"); let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); assert_eq!( b1.as_raw(), @@ -2520,6 +2570,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { "scratch buffer within capacity must be reused" ); assert_eq!(list.indirect_state(&b2), args); + test_stage("within-capacity scratch reused"); // A call needing >64 KiB grows the scratch buffer mid-list while keeping // `b1` alive until reset. The new buffer starts out common. @@ -2542,6 +2593,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { D3D12_RESOURCE_STATE_COMMON, "the replaced buffer went back to common" ); + test_stage("scratch grew beyond 64 KiB and old buffer returned to common"); list.close(); // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): @@ -2550,6 +2602,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); + test_stage("first submission completed and list reset"); // After reset, requests up to the grown high-water mark reuse `b3` with // zero new allocations; the buffer decayed to common when the @@ -2566,10 +2619,12 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { "grown scratch buffer must persist across reset" ); assert_eq!(list.indirect_state(&b4), args); + test_stage("grown scratch reused after reset"); list.close(); assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); + test_stage("host_list_reuses_and_grows_scratch_across_submissions complete"); } /// A group charges its records in lane order: with 300 left of the @@ -2666,14 +2721,20 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// small record still runs. #[test] fn host_list_budget_starts_empty_at_each_submission() { + test_stage("host_list_budget_starts_empty_at_each_submission begin"); let Some(host) = super::host() else { + test_stage("host D3D12 device unavailable; test returned early"); return; }; + test_stage("host D3D12 device available"); let Ok(list) = host.new_list() else { + test_stage("command list unavailable; test returned early"); return; }; + test_stage("command list created"); let _ = host.log_messages(); let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + test_stage("worker pipeline ready"); const KIND_DISPATCH: u32 = 2; const STRIDE: u32 = 12; let signature = { @@ -2722,6 +2783,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { // SAFETY: a live buffer. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; for round in 0..2 { + test_stage(&format!("budget-spent submission {round} begin")); // Spends the budget (clamped, not executed), then one group. bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); @@ -2742,9 +2804,11 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { // The small record comes after the big ones spent the budget: // it runs empty, in every round alike (none carries over). assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + test_stage(&format!("budget-spent submission {round} readback hits={hits}")); } // A recording with only the small record: the budget is empty // again, so it runs. + test_stage("fresh-budget submission begin"); let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); // SAFETY: as above. unsafe { @@ -2760,6 +2824,8 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { // SAFETY: the list has run; a mapped buffer. let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; assert_eq!(hits, 1, "the budget starts empty at the next submission"); + test_stage(&format!("fresh-budget submission readback hits={hits}")); + test_stage("host_list_budget_starts_empty_at_each_submission complete"); } /// Records the dispatch records `groups` (three words each, `step` @@ -2851,15 +2917,21 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// diagnostics build) no barrier names a state the buffer is not in. #[test] fn host_list_window_executions_need_no_barrier_of_their_own() { + test_stage("host_list_window_executions_need_no_barrier_of_their_own begin"); let Some(host) = super::host() else { + test_stage("host D3D12 device unavailable; test returned early"); return; }; + test_stage("host D3D12 device available"); // What earlier tests left in the debug layer's queue, if it is on. let _ = host.log_messages(); let Ok(list) = host.new_list() else { + test_stage("command list unavailable; test returned early"); return; }; + test_stage("command list created"); let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + test_stage("worker pipeline ready"); const KIND_DISPATCH: u32 = 2; const STRIDE: u32 = 12; const STEP: u32 = 32; @@ -2908,6 +2980,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { // SAFETY: a live buffer. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; for _ in 0..2 { + test_stage("window-pair submission begin"); // SAFETY: the mapping holds 256 bytes; nothing runs. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; for (groups, src) in windows.iter().zip(&sources) { @@ -2935,7 +3008,9 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { // SAFETY: the list has run; a mapped buffer. let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; assert_eq!(hits, expected, "every record of both windows runs once"); + test_stage(&format!("window-pair submission readback hits={hits} expected={expected}")); } + test_stage("host_list_window_executions_need_no_barrier_of_their_own complete"); } /// A command signature of one argument of `kind` on `device`. @@ -2963,31 +3038,41 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// ([`widest`]), clamped one by one and in a batch. Others are not asked. #[test] fn card_runs_wide_indirect_dispatches() { + test_stage("card_runs_wide_indirect_dispatches begin"); const CS: &str = r#" #define RS "UAV(u0)" -RWByteAddressBuffer seen : register(u0); +RWStructuredBuffer<uint> seen : register(u0); [RootSignature(RS)] [numthreads(1, 1, 1)] void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { uint was; - seen.InterlockedAdd(0, 1, was); - seen.InterlockedMax(4, group.x, was); - seen.InterlockedMax(8, thread.x, was); - seen.InterlockedAdd(16 + group.x * 4, 1, was); + InterlockedAdd(seen[0], 1, was); + InterlockedMax(seen[1], group.x, was); + InterlockedMax(seen[2], thread.x, was); + InterlockedAdd(seen[4 + group.x], 1, was); } "#; let Some(mut gpu) = WarpHarness::on(false) else { + test_stage("adapter 0 unavailable; test returned early"); return; }; - if !amd(&gpu.device) || widest(true) == 65_535 { + test_stage("adapter 0 D3D12 device created"); + let is_amd = amd(&gpu.device); + let max_wide = widest(true); + test_stage(&format!("amd={is_amd} widest={max_wide}")); + if !is_amd || max_wide == 65_535 { + test_stage("adapter does not meet AMD wide-dispatch test conditions; returned early"); return; } let worker = compile_cs(&gpu.device, CS).expect("the worker must compile"); + test_stage("structured wide-dispatch worker compiled"); let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + test_stage("fork batch clamp compiled"); let sig = gpu.signature(2, 12); for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] { let runs = if asked > 1 << 20 { 65_535 } else { asked }; for batched in [false, true] { + test_stage(&format!("dispatch begin asked={asked} batched={batched} expected_groups={runs}")); let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024); let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256); let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE); @@ -3022,9 +3107,11 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { let word = |i: usize| unsafe { back_ptr.cast::<u32>().add(i).read_volatile() }; assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}"); let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1); + test_stage(&format!("dispatch readback asked={asked} batched={batched} observed=[{},{},{}] wrong_group={wrong:?}", word(0), word(1), word(2))); assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}"); } } + test_stage("card_runs_wide_indirect_dispatches complete"); } /// What a batch's table says of records added to it: one job per @@ -3203,18 +3290,25 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { /// the debug layer on no barrier names a state the buffer is not in. #[test] fn host_list_batches() { + test_stage("host_list_batches begin"); let Some(host) = super::host() else { + test_stage("host D3D12 device unavailable; test returned early"); return; }; + test_stage("host D3D12 device available"); let _ = host.log_messages(); let Ok(list) = host.new_list() else { + test_stage("command list unavailable; test returned early"); return; }; + test_stage("command list created"); let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + test_stage("worker pipeline ready"); let signature = one_argument(&host.device, 2, 12); let mut sources = Vec::new(); for first in [1u32, 100] { let Some((buffer, ptr)) = host.shared_buffer(1024) else { + test_stage("source buffer unavailable; test returned early"); return; }; for i in 0..16u32 { @@ -3226,11 +3320,13 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { sources.push(buffer); } let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + test_stage("hits buffer unavailable; test returned early"); return; }; // SAFETY: a live buffer. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; for _ in 0..2 { + test_stage("batch pass begin"); // SAFETY: the mapping holds 256 bytes; nothing runs. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; let mut expected = 0; @@ -3253,13 +3349,19 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { } } list.close(); - assert_eq!(host.log_messages(), None, "the debug layer found an error"); + if let Some(messages) = host.log_messages() { + test_stage(&format!("D3D12 debug messages: {messages:?}")); + assert!(false, "the debug layer found an error"); + } + test_stage("executing command list"); host.execute(&[&list]); list.reset(); // SAFETY: the list has run; a mapped buffer. let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + test_stage(&format!("readback hits={hits} expected={expected}")); assert_eq!(hits, expected, "every execution runs what it asked for"); } + test_stage("host_list_batches complete"); } /// What clamps of a frame cost on the card one by one and in batches @@ -3268,11 +3370,15 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { #[test] #[ignore] fn batch_costs() { + test_stage("batch_costs begin"); let Some(mut gpu) = WarpHarness::on(false) else { + test_stage("adapter 0 unavailable; benchmark returned early"); return; }; + test_stage(&format!("adapter 0 D3D12 device created amd={} widest={}", amd(&gpu.device), widest(true))); const EXECUTIONS: u32 = 2355; let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + test_stage("fork batch clamp compiled"); let sig = gpu.signature(2, 12); let groups: Vec<u32> = vec![1; 2048]; let src = dispatch_records(&gpu, &groups, 32); @@ -3285,6 +3391,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400); let dst = gpu.default_uav(4 << 20); for run in [0u32, 2355 / 49, 5, 1] { + test_stage(&format!("benchmark variant begin batch_interval={run}")); let mut best = f64::MAX; for _ in 0..6 { let mut state = D3D12_RESOURCE_STATE_COMMON; @@ -3316,7 +3423,9 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { } let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") }; println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms"); + test_stage(&format!("benchmark variant complete batch_interval={run} best_gpu_submit_ms={best:.2}")); } + test_stage("batch_costs complete"); } } diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index d4f192d..a66ce6c 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -40,7 +40,7 @@ ByteAddressBuffer src3 : register(t3); // record's offset in the source; its place in the scratch buffer; nothing. ByteAddressBuffer jobs : register(t4); RWByteAddressBuffer dst_args : register(u0); -RWByteAddressBuffer budget : register(u1); +RWStructuredBuffer<uint> budget : register(u1); static const uint BUDGET = 1u << 27; static const uint GROUPS = 1u << 20; groupshared uint costs[64]; @@ -117,8 +117,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { uint n = count > first ? min(64u, count - first) : 0u; if (gi == 0 && n > 0) { uint before; - budget.InterlockedOr(0, 0, before); - [allow_uav_condition] + InterlockedOr(budget[0], 0, before); while (before < BUDGET) { uint next = before; for (uint j = 0; j < n; j++) { @@ -129,7 +128,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } if (next == before) break; uint prev; - budget.InterlockedCompareExchange(0, before, next, prev); + InterlockedCompareExchange(budget[0], before, next, prev); if (prev == before) break; before = prev; } @@ -151,17 +150,17 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { // the largest cost there was (small ones are not told). uint told; if (refused > 0) { - budget.InterlockedAdd(12, refused, told); + InterlockedAdd(budget[3], refused, told); } if (biggest >= (1u << 22)) { - budget.InterlockedMax(16, biggest, told); + InterlockedMax(budget[4], biggest, told); } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && n > 0 && all_asked > 0) { uint was; - budget.InterlockedMax(4, largest_asked, was); - budget.InterlockedAdd(8, all_asked, was); + InterlockedMax(budget[1], largest_asked, was); + InterlockedAdd(budget[2], all_asked, was); } if (!active) { return; diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 98edeca..d0ed138 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -804,12 +804,15 @@ impl Rig { const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; let mut code: Option<ID3DBlob> = None; // SAFETY: the source and names live through the call; then the - // blob's own bytes, which hold the root signature too. + // blob's own bytes. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; let code = code.ok_or_else(windows::core::Error::empty)?; + // Not the blob: under Wine the host refuses the signature inside + // it (E_FAIL), while a description read from the source's `RS` + // and serialized here works, as the title's own signatures do. + let root = crate::rootstring::make(&self.device, SOURCE)?; let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 19ae3c5..547e50d 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -82,6 +82,8 @@ mod residency; pub mod resource; pub mod root; #[cfg(windows)] +mod rootstring; +#[cfg(windows)] mod safecopy; #[cfg(windows)] mod sampler; diff --git a/crates/victory-gpu/src/replay/play/merge.rs b/crates/victory-gpu/src/replay/play/merge.rs index daddcd0..4729ea9 100644 --- a/crates/victory-gpu/src/replay/play/merge.rs +++ b/crates/victory-gpu/src/replay/play/merge.rs @@ -174,7 +174,10 @@ impl Player { code.GetBufferPointer().cast::<u8>(), code.GetBufferSize(), ); - let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + // Not the blob: under Wine the host refuses the signature inside + // it (E_FAIL), while a description read from the source's `RS` + // and serialized here works, as the title's own signatures do. + let root: ID3D12RootSignature = crate::rootstring::make(&self.device, SOURCE)?; let pso = self.device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { ````
PastiiJay commented 2026-11-28 13:38:26 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-28T13:38:26Z.


Thanks @diafebus, we have both patches and the branch from #152 and will test them on our side, with credit for whatever we take. If you still have the console log from that first run that drew the interior, attaching it here as a .txt would help us compare.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7240078991 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7240078991). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-28T13:38:26Z. --- Thanks @diafebus, we have both patches and the branch from #152 and will test them on our side, with credit for whatever we take. If you still have the console log from that first run that drew the interior, attaching it here as a .txt would help us compare.
diafebus commented 2026-11-28 19:28:01 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T19:28:01Z.


@PastiiJay I recovered renderer telemetry from two fresh reproductions on RX 6950 XT (RADV NAVI21, GE-Proton 11-14, descriptor_heap, feature level 12_1). The original run's saved console captured Proton startup only. These are new runs with KLBF tracing written directly to a file.

  • A: stable 4c79ac5 + the published Wine rendering port + HandshakeHackin's sampler default and fixture corrections. In “Nine Months Ago,” most NPCs lacked skin, while the guard's face looked correct. Prison window walls took roughly 30–50 seconds to appear. The cell reached about 20 FPS. Daylight reached the interior through windows and doors. Reflections looked wrong and I couldn't confirm illumination from the ceiling fixtures.
  • B: A plus the face-bake queue fix and shorter pipeline wait from 3f08d23 with KLBF_PIPELINE_NOBLOCK=1. More NPCs had skin, but their faces were deformed like Lucia's. The guard still looked correct. Walls seemed to come in sooner on the first pass and movement felt more responsive. After restarting the mission the walls eventually returned, but the window glass was missing. There was no clear improvement in interior lighting.

Selected console lines (the trailing heap/texture counters are omitted):

A, settled cell:
20.0 fps, 50.0 ms/frame (35.0 preparing: copies 19.5 ms 57.7 MB, textures 0.7 ms 23.0 MB; 0.5 on the GPU; 11.1 copying back 1.4 MB), 5187 draws/frame, dropped 374 without a host pipeline (3 being made) and 2 indirect

B, settled cell:
19.8 fps, 50.6 ms/frame (34.2 preparing: copies 18.6 ms 52.6 MB, textures 0.8 ms 20.8 MB; 0.8 on the GPU; 12.8 copying back 1.3 MB), 5040 draws/frame, dropped 356 without a host pipeline (3 being made) and 2 indirect

B, after mission restart during the slowdown:
2.1 fps, 478.7 ms/frame (473.7 preparing: copies 353.5 ms 84.9 MB, textures 37.0 ms 43.5 MB; 2.7 on the GPU; 7.2 copying back 1.3 MB), 3519 draws/frame, dropped 499 without a host pipeline

These are individual samples from a live comparison. The slow restart sample is dominated by reported preparation and copy time. I preserved the two full renderer logs locally (about 5.4 and 7.0 MiB) and can provide a specific interval or additional counters if useful.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7244565146 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7244565146). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T19:28:01Z. --- @PastiiJay I recovered renderer telemetry from two fresh reproductions on RX 6950 XT (RADV NAVI21, GE-Proton 11-14, descriptor_heap, feature level 12_1). The original run's saved console captured Proton startup only. These are new runs with KLBF tracing written directly to a file. - A: stable `4c79ac5` + the published Wine rendering port + HandshakeHackin's sampler default and fixture corrections. In “Nine Months Ago,” most NPCs lacked skin, while the guard's face looked correct. Prison window walls took roughly 30–50 seconds to appear. The cell reached about 20 FPS. Daylight reached the interior through windows and doors. Reflections looked wrong and I couldn't confirm illumination from the ceiling fixtures. - B: A plus the face-bake queue fix and shorter pipeline wait from `3f08d23` with `KLBF_PIPELINE_NOBLOCK=1`. More NPCs had skin, but their faces were deformed like Lucia's. The guard still looked correct. Walls seemed to come in sooner on the first pass and movement felt more responsive. After restarting the mission the walls eventually returned, but the window glass was missing. There was no clear improvement in interior lighting. Selected console lines (the trailing heap/texture counters are omitted): ```text A, settled cell: 20.0 fps, 50.0 ms/frame (35.0 preparing: copies 19.5 ms 57.7 MB, textures 0.7 ms 23.0 MB; 0.5 on the GPU; 11.1 copying back 1.4 MB), 5187 draws/frame, dropped 374 without a host pipeline (3 being made) and 2 indirect B, settled cell: 19.8 fps, 50.6 ms/frame (34.2 preparing: copies 18.6 ms 52.6 MB, textures 0.8 ms 20.8 MB; 0.8 on the GPU; 12.8 copying back 1.3 MB), 5040 draws/frame, dropped 356 without a host pipeline (3 being made) and 2 indirect B, after mission restart during the slowdown: 2.1 fps, 478.7 ms/frame (473.7 preparing: copies 353.5 ms 84.9 MB, textures 37.0 ms 43.5 MB; 2.7 on the GPU; 7.2 copying back 1.3 MB), 3519 draws/frame, dropped 499 without a host pipeline ``` These are individual samples from a live comparison. The slow restart sample is dominated by reported preparation and copy time. I preserved the two full renderer logs locally (about 5.4 and 7.0 MiB) and can provide a specific interval or additional counters if useful.
PastiiJay commented 2026-11-28 19:43:03 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-28T19:43:03Z.


thanks a lot for the two traced runs, very clear. the line that stands out is "dropped 374 without a host pipeline (3 being made)": those draws are skipped while their pipelines are still being built, which fits missing skin and late walls. could you do one run where you let Prepare shaders finish first (Settings), then send the same settled-cell line? if the dropped count goes near 0 and skins come back, we know where to look

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7244753012 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7244753012). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-28T19:43:03Z. --- thanks a lot for the two traced runs, very clear. the line that stands out is "dropped 374 without a host pipeline (3 being made)": those draws are skipped while their pipelines are still being built, which fits missing skin and late walls. could you do one run where you let Prepare shaders finish first (Settings), then send the same settled-cell line? if the dropped count goes near 0 and skins come back, we know where to look
diafebus commented 2026-11-28 21:51:19 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-28T21:51:19Z.


@PastiiJay I ran both preparation steps under GE-Proton 11-14 on the RX 6950 XT / RADV: victory shaders completed, then victory warm completed with 83,527 entries recorded as done and 33 marked bad in the pipeline book's warmup logs.

Settled prison cell at 21:50:22 UTC, with inmates missing facial skin (eyes and mouths visible):

20.8 fps, 48.2 ms/frame (33.8 preparing: copies 18.6 ms 54.4 MB, textures 1.1 ms 22.4 MB; 0.1 on the GPU; 9.6 copying back 1.2 MB), 4624 draws/frame, dropped 368 without a host pipeline (3 being made) and 2 indirect

The earlier sample was 374 drops/frame, so the count did not go near zero in this sample and inmate facial skin was still missing. This run used our patched stable-amd build at 75022ba (v26.11.6), with the Wine helper port, sampler correction, and the shorter wait enabled. The 374-drop sample used the patched 4c79ac5 base, so the comparison does not isolate preparation alone.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7246322091 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7246322091). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-28T21:51:19Z. --- @PastiiJay I ran both preparation steps under GE-Proton 11-14 on the RX 6950 XT / RADV: `victory shaders` completed, then `victory warm` completed with 83,527 entries recorded as done and 33 marked bad in the pipeline book's warmup logs. Settled prison cell at 21:50:22 UTC, with inmates missing facial skin (eyes and mouths visible): ```text 20.8 fps, 48.2 ms/frame (33.8 preparing: copies 18.6 ms 54.4 MB, textures 1.1 ms 22.4 MB; 0.1 on the GPU; 9.6 copying back 1.2 MB), 4624 draws/frame, dropped 368 without a host pipeline (3 being made) and 2 indirect ``` The earlier sample was 374 drops/frame, so the count did not go near zero in this sample and inmate facial skin was still missing. This run used our patched `stable-amd` build at `75022ba` (v26.11.6), with the Wine helper port, sampler correction, and the shorter wait enabled. The 374-drop sample used the patched `4c79ac5` base, so the comparison does not isolate preparation alone.
PastiiJay commented 2026-11-28 22:39:36 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-28T22:39:36Z.


thanks diafebus, both steps finishing under GE-Proton with only 33 bad entries out of 83,527 is good news for RADV. the missing facial skin is a known bug we're working on, on Windows too. if you can, attach the run log of that session so we can compare it with ours

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7246891337 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7246891337). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-28T22:39:36Z. --- thanks diafebus, both steps finishing under GE-Proton with only 33 bad entries out of 83,527 is good news for RADV. the missing facial skin is a known bug we're working on, on Windows too. if you can, attach the run log of that session so we can compare it with ours
diafebus commented 2026-11-29 01:07:55 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by diafebus on 2026-11-29T01:07:55Z.


@PastiiJay Would two small GPU readback probes be useful for narrowing down the missing facial skin? Xbox2Windows documents a constant-buffer swap and a two-mip explicit LOD test. We could use that test design with synthetic resources through KLBF's own shader translation and descriptor binding paths:

  1. Constant-buffer binding: Bind buffer A, then buffer B at the same root or table slot. Give them distinct values and verify the shader's output by readback. If feasible, repeat with the same descriptor slot rewritten between submissions to check for stale bindings.
  2. Texture mip selection: Give mip 0 and mip 1 distinct colors and read each explicitly through the same texture view. Verify the returned color, then repeat with a view that starts at mip 1 to check that the view-relative index is handled correctly.

On our RX 6950 XT / RADV / GE-Proton setup, one inmate's facial skin appeared when I approached and disappeared again when I backed away in VIctory-RDNA. That makes a distance-dependent mesh or material path worth checking. The mip probe would isolate one possible cause. These probes could run with synthetic assets and avoid another full playthrough. A passing result would narrow the search, but it wouldn't rule out geometry LOD, streaming, or a missing host pipeline.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7248580447 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7248580447). Originally posted by [diafebus](https://github.com/diafebus) on 2026-11-29T01:07:55Z. --- @PastiiJay Would two small GPU readback probes be useful for narrowing down the missing facial skin? Xbox2Windows documents [a constant-buffer swap and a two-mip explicit LOD test](https://github.com/R0Y00/Xbox2Windows). We could use that test design with synthetic resources through KLBF's own shader translation and descriptor binding paths: 1. **Constant-buffer binding:** Bind buffer A, then buffer B at the same root or table slot. Give them distinct values and verify the shader's output by readback. If feasible, repeat with the same descriptor slot rewritten between submissions to check for stale bindings. 2. **Texture mip selection:** Give mip 0 and mip 1 distinct colors and read each explicitly through the same texture view. Verify the returned color, then repeat with a view that starts at mip 1 to check that the view-relative index is handled correctly. On our RX 6950 XT / RADV / GE-Proton setup, one inmate's facial skin appeared when I approached and disappeared again when I backed away in VIctory-RDNA. That makes a distance-dependent mesh or material path worth checking. The mip probe would isolate one possible cause. These probes could run with synthetic assets and avoid another full playthrough. A passing result would narrow the search, but it wouldn't rule out geometry LOD, streaming, or a missing host pipeline.
HandshakeHackin commented 2026-11-29 01:30:51 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by HandshakeHackin on 2026-11-29T01:30:51Z.


@diafebus I ran both probes through KLBF's native compute-shader translator on Windows WARP. Each dispatch waits for the GPU fence before rewriting the same D3D12 descriptor slots. The output contains the constant-buffer marker followed by the red samples at explicit levels 0 and 1.

First mip in view Bound constant buffer Readback at LOD 0 Readback at LOD 1
0 A: 0x12345678 0.25 0.75
0 B: 0x87654321 0.25 0.75
1 A: 0x12345678 0.75 0.75

All three markers matched. With only the second mip exposed, a request for LOD 1 also clamped to that mip. The existing cube-gradient regression passed alongside it. This covers translated shader reads and a real D3D12 heap rewrite. The title's material/streaming path and RADV on the physical card are still open questions. Probe and harness changes · Windows readback log.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7248830829 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7248830829). Originally posted by [HandshakeHackin](https://github.com/HandshakeHackin) on 2026-11-29T01:30:51Z. --- @diafebus I ran both probes through KLBF's native compute-shader translator on Windows WARP. Each dispatch waits for the GPU fence before rewriting the same D3D12 descriptor slots. The output contains the constant-buffer marker followed by the red samples at explicit levels 0 and 1. | First mip in view | Bound constant buffer | Readback at LOD 0 | Readback at LOD 1 | |---|---|---:|---:| | 0 | A: 0x12345678 | 0.25 | 0.75 | | 0 | B: 0x87654321 | 0.25 | 0.75 | | 1 | A: 0x12345678 | 0.75 | 0.75 | All three markers matched. With only the second mip exposed, a request for LOD 1 also clamped to that mip. The existing cube-gradient regression passed alongside it. This covers translated shader reads and a real D3D12 heap rewrite. The title's material/streaming path and RADV on the physical card are still open questions. [Probe and harness changes](https://github.com/HandshakeHackin/klbf-lab/compare/72d557fde55e76abf60a301569992b76978b7176...cd1197b6c51edd01e54c194c72649fea8bf6ebaf) · [Windows readback log](https://github.com/HandshakeHackin/klbf-lab/actions/runs/46211384039/job/141185673797).
PastiiJay commented 2026-11-29 08:25:11 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-29T08:25:11Z.


@diafebus good idea, and @HandshakeHackin thanks for running both probes: constant buffers and mip selection read back right, so two causes are off the list. skin that comes and goes with distance points more at streaming or level of detail, noted.

the v26.11.10 pre-release keeps pipelines from one run to the next under Proton. diafebus, could you attach a run log of a session on it in your GE-Proton setup?

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7253092763 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7253092763). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-29T08:25:11Z. --- @diafebus good idea, and @HandshakeHackin thanks for running both probes: constant buffers and mip selection read back right, so two causes are off the list. skin that comes and goes with distance points more at streaming or level of detail, noted. the v26.11.10 pre-release keeps pipelines from one run to the next under Proton. diafebus, could you attach a run log of a session on it in your GE-Proton setup?
PastiiJay commented 2026-11-29 18:54:19 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-29T18:54:19Z.


Reposted from @diafebus (23:23) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding!

RX 6950 XT on Proton renders 3D with the Belobug helper shader changes

On Linux with an RX 6950 XT (RDNA2), RADV NAVI21, and GE-Proton 11-14, our initial KLBF v12 runs showed menus and subtitles while the 3D scene stayed black. A local Belobug shader build displayed 3D. We ported its helper shader changes to KLBF v12-stable (4c79ac5272), which then displayed outdoor geometry, characters, and the prison interior.

Changes to reproduce

  • Parse the helper HLSL root signature declarations and serialize the D3D12 signatures on the host. In our earlier helper diagnostics, creating a root signature from the Wine-compiled shader blob failed with E_FAIL, while host serialization succeeded.
  • Carry over the paired HLSL changes for card compare and indirect execution, including the structured UAV accesses in the hash and clamp shaders. The KLBF port also uses the host serializer for the compositor, ambient and other matching helpers. KLBF v12 lacks Belobug's lightprobe module.
  • Use the successful launcher configuration for the initial comparison. It used descriptor_heap, feature level 12_1, KLBF's bundled Agility SDK, and Wine overrides d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b. The run used a copy of an existing Player save.

We observed this on one RDNA2 system with the combined patch and launch configuration. We did not isolate which changes are required, and our earlier KLBF runs did not use the same DXGI override.

Observed result

Patched KLBF showed a third person character, trees, grass and distant lights outdoors. The overlay showed 1.5 FPS in the captured outdoor frame and 5.9 FPS in a captured prison window frame. The tester briefly saw 16 FPS. These are snapshots. the first character's eyes and mouth rendered while the facial surface was missing, and some scenes remained very dark.

Local KLBF candidate executable SHA-256
253a71856840f010469aa83038e4db769a3a31c743773f2921e37b2857c6802a

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7260851775 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7260851775). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-29T18:54:19Z. --- Reposted from @diafebus (23:23) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding! # RX 6950 XT on Proton renders 3D with the Belobug helper shader changes On Linux with an RX 6950 XT (RDNA2), RADV NAVI21, and GE-Proton 11-14, our initial KLBF v12 runs showed menus and subtitles while the 3D scene stayed black. A local Belobug shader build displayed 3D. We ported its helper shader changes to KLBF v12-stable (4c79ac52728f29163a4bad807911838a9f1c9774), which then displayed outdoor geometry, characters, and the prison interior. ## Changes to reproduce - Parse the helper HLSL root signature declarations and serialize the D3D12 signatures on the host. In our earlier helper diagnostics, creating a root signature from the Wine-compiled shader blob failed with E_FAIL, while host serialization succeeded. - Carry over the paired HLSL changes for card compare and indirect execution, including the structured UAV accesses in the hash and clamp shaders. The KLBF port also uses the host serializer for the compositor, ambient and other matching helpers. KLBF v12 lacks Belobug's lightprobe module. - Use the successful launcher configuration for the initial comparison. It used descriptor_heap, feature level 12_1, KLBF's bundled Agility SDK, and Wine overrides d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b. The run used a copy of an existing Player save. We observed this on one RDNA2 system with the combined patch and launch configuration. We did not isolate which changes are required, and our earlier KLBF runs did not use the same DXGI override. ## Observed result Patched KLBF showed a third person character, trees, grass and distant lights outdoors. The overlay showed 1.5 FPS in the captured outdoor frame and 5.9 FPS in a captured prison window frame. The tester briefly saw 16 FPS. These are snapshots. the first character's eyes and mouth rendered while the facial surface was missing, and some scenes remained very dark. Local KLBF candidate executable SHA-256 253a71856840f010469aa83038e4db769a3a31c743773f2921e37b2857c6802a
PastiiJay commented 2026-11-29 18:54:55 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-29T18:54:55Z.


Reposted from @diafebus (10:48) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding!

Here is the source branch for the first KLBF build that rendered 3D in our RX 6950 XT run: diff against 4c79ac5 · branch. It contains the Belobug-derived rendering port before our later performance and texture experiments.

For isolation, start with crates/victory-gpu/src/rootstring.rs and the call sites that serialize the helper root signatures on the host. An earlier helper diagnostic returned E_FAIL when creating the signature from the Wine-compiled blob, while host serialization succeeded. The branch also changes helper HLSL resource access, including the indirect clamp and card compare. A useful comparison is base → host serialization only → complete branch, with the same launch environment and scene at each step. Check helper initialization and whether geometry appears before comparing FPS.

Our successful configuration was RX 6950 XT / RADV NAVI21 / GE-Proton 11-14 with KLBF's bundled Agility SDK, VKD3D_CONFIG=descriptor_heap, feature level 12_1, and WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b". Outdoor geometry and characters and the prison interior appeared with the combined port. Some scenes were still dark and the first character's facial surface was missing. The earlier black-world run used a different DXGI override, so serialization alone and applicability across RDNA2 remain open.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7260859764 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7260859764). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-29T18:54:55Z. --- Reposted from @diafebus (10:48) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding! Here is the source branch for the first KLBF build that rendered 3D in our RX 6950 XT run: [diff against `4c79ac5`](https://github.com/PastiiJay/klbf-lab/compare/4c79ac5...diafebus:klbf-lab:rdna2-proton-helper-render) · [branch](https://github.com/diafebus/klbf-lab/tree/rdna2-proton-helper-render). It contains the Belobug-derived rendering port before our later performance and texture experiments. For isolation, start with `crates/victory-gpu/src/rootstring.rs` and the call sites that serialize the helper root signatures on the host. An earlier helper diagnostic returned `E_FAIL` when creating the signature from the Wine-compiled blob, while host serialization succeeded. The branch also changes helper HLSL resource access, including the indirect clamp and card compare. A useful comparison is base → host serialization only → complete branch, with the same launch environment and scene at each step. Check helper initialization and whether geometry appears before comparing FPS. Our successful configuration was RX 6950 XT / RADV NAVI21 / GE-Proton 11-14 with KLBF's bundled Agility SDK, `VKD3D_CONFIG=descriptor_heap`, feature level 12_1, and `WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b;d3dcompiler_47=n,b"`. Outdoor geometry and characters and the prison interior appeared with the combined port. Some scenes were still dark and the first character's facial surface was missing. The earlier black-world run used a different DXGI override, so serialization alone and applicability across RDNA2 remain open.
PastiiJay commented 2026-11-29 18:55:16 +00:00 (Migrated from github.com)
Author
Contributor

Imported from PastiiJay/klbf-lab. Originally posted by PastiiJay on 2026-11-29T18:55:16Z.


Reposted from @diafebus (20:28) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding!

@PastiiJay I recovered renderer telemetry from two fresh reproductions on RX 6950 XT (RADV NAVI21, GE-Proton 11-14, descriptor_heap, feature level 12_1). The original run's saved console captured Proton startup only. These are new runs with KLBF tracing written directly to a file.

  • A: stable 4c79ac5 + the published Wine rendering port + HandshakeHackin's sampler default and fixture corrections. In “Nine Months Ago,” most NPCs lacked skin, while the guard's face looked correct. Prison window walls took roughly 30–50 seconds to appear. The cell reached about 20 FPS. Daylight reached the interior through windows and doors. Reflections looked wrong and I couldn't confirm illumination from the ceiling fixtures.
  • B: A plus the face-bake queue fix and shorter pipeline wait from 3f08d23 with KLBF_PIPELINE_NOBLOCK=1. More NPCs had skin, but their faces were deformed like the first character's. The guard still looked correct. Walls seemed to come in sooner on the first pass and movement felt more responsive. After restarting the mission the walls eventually returned, but the window glass was missing. There was no clear improvement in interior lighting.

Selected console lines (the trailing heap/texture counters are omitted):

A, settled cell:
20.0 fps, 50.0 ms/frame (35.0 preparing: copies 19.5 ms 57.7 MB, textures 0.7 ms 23.0 MB; 0.5 on the GPU; 11.1 copying back 1.4 MB), 5187 draws/frame, dropped 374 without a host pipeline (3 being made) and 2 indirect

B, settled cell:
19.8 fps, 50.6 ms/frame (34.2 preparing: copies 18.6 ms 52.6 MB, textures 0.8 ms 20.8 MB; 0.8 on the GPU; 12.8 copying back 1.3 MB), 5040 draws/frame, dropped 356 without a host pipeline (3 being made) and 2 indirect

B, after mission restart during the slowdown:
2.1 fps, 478.7 ms/frame (473.7 preparing: copies 353.5 ms 84.9 MB, textures 37.0 ms 43.5 MB; 2.7 on the GPU; 7.2 copying back 1.3 MB), 3519 draws/frame, dropped 499 without a host pipeline

These are individual samples from a live comparison. The slow restart sample is dominated by reported preparation and copy time. I preserved the two full renderer logs locally (about 5.4 and 7.0 MiB) and can provide a specific interval or additional counters if useful.

<!-- greyfinch-sync:PastiiJay/klbf-lab:comment:7260864348 --> Imported from [PastiiJay/klbf-lab](https://github.com/PastiiJay/klbf-lab/issues/120#issuecomment-7260864348). Originally posted by [PastiiJay](https://github.com/PastiiJay) on 2026-11-29T18:55:16Z. --- Reposted from @diafebus (20:28) with the game names taken out. no worries, we just keep content and names from any game out of this repo, thanks for understanding! @PastiiJay I recovered renderer telemetry from two fresh reproductions on RX 6950 XT (RADV NAVI21, GE-Proton 11-14, descriptor_heap, feature level 12_1). The original run's saved console captured Proton startup only. These are new runs with KLBF tracing written directly to a file. - A: stable `4c79ac5` + the published Wine rendering port + HandshakeHackin's sampler default and fixture corrections. In “Nine Months Ago,” most NPCs lacked skin, while the guard's face looked correct. Prison window walls took roughly 30–50 seconds to appear. The cell reached about 20 FPS. Daylight reached the interior through windows and doors. Reflections looked wrong and I couldn't confirm illumination from the ceiling fixtures. - B: A plus the face-bake queue fix and shorter pipeline wait from `3f08d23` with `KLBF_PIPELINE_NOBLOCK=1`. More NPCs had skin, but their faces were deformed like the first character's. The guard still looked correct. Walls seemed to come in sooner on the first pass and movement felt more responsive. After restarting the mission the walls eventually returned, but the window glass was missing. There was no clear improvement in interior lighting. Selected console lines (the trailing heap/texture counters are omitted): ```text A, settled cell: 20.0 fps, 50.0 ms/frame (35.0 preparing: copies 19.5 ms 57.7 MB, textures 0.7 ms 23.0 MB; 0.5 on the GPU; 11.1 copying back 1.4 MB), 5187 draws/frame, dropped 374 without a host pipeline (3 being made) and 2 indirect B, settled cell: 19.8 fps, 50.6 ms/frame (34.2 preparing: copies 18.6 ms 52.6 MB, textures 0.8 ms 20.8 MB; 0.8 on the GPU; 12.8 copying back 1.3 MB), 5040 draws/frame, dropped 356 without a host pipeline (3 being made) and 2 indirect B, after mission restart during the slowdown: 2.1 fps, 478.7 ms/frame (473.7 preparing: copies 353.5 ms 84.9 MB, textures 37.0 ms 43.5 MB; 2.7 on the GPU; 7.2 copying back 1.3 MB), 3519 draws/frame, dropped 499 without a host pipeline ``` These are individual samples from a live comparison. The slow restart sample is dominated by reported preparation and copy time. I preserved the two full renderer logs locally (about 5.4 and 7.0 MiB) and can provide a specific interval or additional counters if useful.
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
PastiiJay/klbf-lab#120
No description provided.