D3D12.X: hook XboxBvhBuilder builds and ask for every range whole in GPU views #3662

Open
Kalmarv wants to merge 1 commit from upstream-pr/3662 into main
Kalmarv commented 2026-12-02 05:25:08 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T05:25:08Z.


Outer XboxBvhBuilder.dll HLE hooks that ask for every acceleration-structure build and rehydrate range whole in GPU views (d3d12x::view_want::Path::BvhBuild), laying the hook layer needed for the opt-in DXR 1.1 shadow builder follow-up.

On the 16-window GPU-view layout (XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16), XboxBvhBuilder.dll's compute passes reach vertex, index, and transform buffers through addresses inside uploaded geometry descriptions, and read/write destination, source, and scratch through root views that view_want only asks for 64 KiB for. Wrapping BuildRaytracingAccelerationStructureBatched2X and RehydrateRaytracingAccelerationStructureBatched2X on import resolution and GetProcAddress (named or by ordinal) lets XCL ask for every range whole before forwarding. On the default 4-window layout nothing is wrapped.

Part of #1751. Standalone on main (5eaadb54c; no stacked PRs underneath). Note: the solid-character improvement observed earlier in this thread was bisected by @KDenKC to #3517's 16-window layout change, not this PR.

(Why this is 1339 lines and not split further: ~635 lines are the XboxBvhBuilder.dll ABI definitions, safe tile-aware range calculation, and extern "system-unwind" hooks, and ~704 lines are their unit tests, kept together because CONTRIBUTING.md requires new code to ship with its tests.)

Related: #2184-#2189 (specifically #2186) and #3521. Concrete differences: this PR hooks XboxBvhBuilder.dll (BuildBatched2X + RehydrateBatched2X) on both import resolution and GetProcAddress without modifying the DLL or title shaders, asks for whole ranges in 16-window GPU views via view_want::Path::BvhBuild (sized by the DLL's own GetRaytracingAccelerationStructurePrebuildInfo using DXR-legal ALLOW_UPDATE flags rather than a VA-keyed cache), and uses extern "system-unwind" on all hook trampolines.

What is in it

  • crates/xcl/src/hle/bvh_builder.rs:
    • XboxBvhBuilder.dll ABI structs (BuildInputs, BuildDesc, BatchedBuildDesc2, GeometryDesc, PrebuildInfo, PostbuildInfoDesc, StreamDesc), safe geometry/postbuild readers, whole-range calculation (ranges_of_build), and extern "system-unwind" passthrough hooks for BuildBatched2X and RehydrateBatched2X, gated on active GPU view windows.
    • Resolves GetRaytracingAccelerationStructurePrebuildInfo directly from the mapped XboxBvhBuilder.dll module when wrapping any export (named or by ordinal), instead of waiting for the title to import it.
    • Strips BUILD_FLAG_PERFORM_UPDATE and sets BUILD_FLAG_ALLOW_UPDATE before querying GetRaytracingAccelerationStructurePrebuildInfo (the DXR-legal form) so update builds receive UpdateScratchDataSizeInBytes directly without an unbounded or VA-reuse-stale cache, falling back to scratch_size.max(SCRATCH_GUESS) if still 0.
    • Reads TLAS instance pointer tables and instance descriptions safely via read_gpu_bytes (view_want::cpu_run, splitting across 64 KiB GPU-view tile boundaries when CPU pages are discontiguous, plus dstorage::read_own kernel copy so concurrent title decommits never fault), coalescing 64-byte D3D12_RAYTRACING_INSTANCE_DESC target ranges and deduplicated referenced bottom-level AS header ranges (Use::BottomLevel, HEADER_BYTES) for both LAYOUT_ARRAY and LAYOUT_ARRAY_OF_POINTERS.
    • 12 unit tests covering ABI layout, wrap gating, mapped-module prebuild resolution and ordinal imports, geometry readers, R16_TYPELESS (53) index sizing, whole-range bottom-level builds, DXR-legal PERFORM_UPDATE flag stripping and VA-reuse safety (perform_update_queries_dxr_legal_flags_without_stale_cache), cross-64 KiB-tile ARRAY_OF_POINTERS + fault-safe read_own + BLAS header asks (tlas_pointer_array_cross_tile_read_own_and_blas_headers), fallback estimation, and build/rehydrate hook forwarding.
  • crates/xcl/src/hle/d3d12x/view_want.rs: add Path::BvhBuild ("acceleration-structure builds", PATHS = 14).
  • crates/xcl/src/hle/mod.rs, crates/xcl/src/resolver.rs: wire hle::bvh_builder::wrap in resolve_import and get_proc_address for xboxbvhbuilder.dll, passing the mapped module and ImportName.

Tested

  • Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 32.0.16.1074 / 610.74), AMD Ryzen 9 9950X, Windows 11 x64 (10.0.26200), rustc 1.99.0, DXC 1.9.2609.5.
  • cargo build --release -p xcl (commit 4082300ba84ea77630ac1050264b4d07fc4bb5a3): succeeded, 39 warnings (0 new vs main).
  • Full .\scripts\test.ps1 directly on 4082300ba84ea77630ac1050264b4d07fc4bb5a3: 2986 passed, 0 failed, 52 ignored across 43 suites; 24 SKIPPED GPU lines on this adapter (22 no wave64, 2 no heap windows), including all 12 hle::bvh_builder::tests passing.
  • 180 s live 16-window GPU-views run directly on 4082300ba84ea77630ac1050264b4d07fc4bb5a3 (XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1): exit: 0x0, 1645 frames shown (1645 PresentX calls), 0 device removals, 0 crashes; logged 29 GPU view (2 s) lines with acceleration-structure builds totaling 30036 range asks (478656 KB new), peaking at 4433 acceleration-structure builds (142976 KB new) at 96.6 s and 2237 acceleration-structure builds (50816 KB new) at 149.1 s.
  • Local timing instrumentation on 4082300ba (uncommitted, reverted after measurement) over 53.0 s of active 16-window BVH builds (113 BuildBatched2X calls / 1472 items, 83 RehydrateBatched2X calls / 1250 items; 2637 BLAS, 85 TLAS LAYOUT_ARRAY, 0 TLAS LAYOUT_ARRAY_OF_POINTERS, 74120 TLAS instances read in 1220 read_gpu_bytes calls): 13.92 ms total hook CPU time (0.026 % of wall time, 2.36 % of the 588.6 ms spent inside the real XboxBvhBuilder.dll calls; 71 µs / call, 5.1 µs / item, max single call 756 µs): read_geometries 2.47 ms, sizes_of 0.265 ms (0.10 µs / item), ranges_of_build 6.58 ms (77 µs / TLAS build), ask 4.16 ms.

Regression run
(Clean pair; the XboxBvhBuilder hook is not installed on the default 4-window layout.)

xcl-smoke v1
commit: 5eaadb54c14e0fc29597b2a1689d7dbd83491303
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1691 (PresentX 1691)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16674 MB
xcl-smoke v1
commit: 4082300ba84ea77630ac1050264b4d07fc4bb5a3
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1673 (PresentX 1673)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 17378 MB

Not tested

  • Default 4-window smoke does not exercise the hooks because view_windows() is false there.
  • LAYOUT_ARRAY_OF_POINTERS TLAS builds were not emitted by the tested retail title (only LAYOUT_ARRAY TLAS builds occurred); LAYOUT_ARRAY_OF_POINTERS is covered by unit tests only.
  • CopyRaytracingAccelerationStructure is not hooked: a compacted or cloned copy whose destination is in a view window is still only asked for its first 64 KiB.
  • Not tested on AMD or Intel GPUs, wave64 GPU tests (22 skipped), or combined with #3521 (XCL_SPARSE_LAZY=1).

AI use

  • Antigravity (Gemini 4 Neon): rebased standalone onto main, implemented review fixes (read_own + tile-splitting cpu_run, DXR-legal sizes_of without UPDATE_SCRATCH, TLAS BLAS header asks) and unit tests, ran the release build, full scripts/test.ps1, smoke runs, 180 s 16-window live run, and hook CPU timing measurement, and updated the PR description.
  • Claude Code (Claude Opus 5.5): authored the original range-request logic and earlier review fixes.
<!-- greyfinch-sync:ivall/xcl:issue:5600441212 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T05:25:08Z. --- Outer `XboxBvhBuilder.dll` HLE hooks that ask for every acceleration-structure build and rehydrate range whole in GPU views (`d3d12x::view_want::Path::BvhBuild`), laying the hook layer needed for the opt-in DXR 1.1 shadow builder follow-up. On the 16-window GPU-view layout (`XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16`), `XboxBvhBuilder.dll`'s compute passes reach vertex, index, and transform buffers through addresses inside uploaded geometry descriptions, and read/write destination, source, and scratch through root views that `view_want` only asks for 64 KiB for. Wrapping `BuildRaytracingAccelerationStructureBatched2X` and `RehydrateRaytracingAccelerationStructureBatched2X` on import resolution and `GetProcAddress` (named or by ordinal) lets XCL ask for every range whole before forwarding. On the default 4-window layout nothing is wrapped. Part of #1751. Standalone on `main` (`5eaadb54c`; no stacked PRs underneath). Note: the solid-character improvement observed earlier in this thread was bisected by @KDenKC to #3517's 16-window layout change, not this PR. (Why this is 1339 lines and not split further: ~635 lines are the `XboxBvhBuilder.dll` ABI definitions, safe tile-aware range calculation, and `extern "system-unwind"` hooks, and ~704 lines are their unit tests, kept together because `CONTRIBUTING.md` requires new code to ship with its tests.) Related: #2184-#2189 (specifically #2186) and #3521. Concrete differences: this PR hooks `XboxBvhBuilder.dll` (`BuildBatched2X` + `RehydrateBatched2X`) on both import resolution and `GetProcAddress` without modifying the DLL or title shaders, asks for whole ranges in 16-window GPU views via `view_want::Path::BvhBuild` (sized by the DLL's own `GetRaytracingAccelerationStructurePrebuildInfo` using DXR-legal `ALLOW_UPDATE` flags rather than a VA-keyed cache), and uses `extern "system-unwind"` on all hook trampolines. **What is in it** - `crates/xcl/src/hle/bvh_builder.rs`: - `XboxBvhBuilder.dll` ABI structs (`BuildInputs`, `BuildDesc`, `BatchedBuildDesc2`, `GeometryDesc`, `PrebuildInfo`, `PostbuildInfoDesc`, `StreamDesc`), safe geometry/postbuild readers, whole-range calculation (`ranges_of_build`), and `extern "system-unwind"` passthrough hooks for `BuildBatched2X` and `RehydrateBatched2X`, gated on active GPU view windows. - Resolves `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped `XboxBvhBuilder.dll` module when wrapping any export (named or by ordinal), instead of waiting for the title to import it. - Strips `BUILD_FLAG_PERFORM_UPDATE` and sets `BUILD_FLAG_ALLOW_UPDATE` before querying `GetRaytracingAccelerationStructurePrebuildInfo` (the DXR-legal form) so update builds receive `UpdateScratchDataSizeInBytes` directly without an unbounded or VA-reuse-stale cache, falling back to `scratch_size.max(SCRATCH_GUESS)` if still `0`. - Reads TLAS instance pointer tables and instance descriptions safely via `read_gpu_bytes` (`view_want::cpu_run`, splitting across 64 KiB GPU-view tile boundaries when CPU pages are discontiguous, plus `dstorage::read_own` kernel copy so concurrent title decommits never fault), coalescing 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target ranges and deduplicated referenced bottom-level AS header ranges (`Use::BottomLevel`, `HEADER_BYTES`) for both `LAYOUT_ARRAY` and `LAYOUT_ARRAY_OF_POINTERS`. - 12 unit tests covering ABI layout, wrap gating, mapped-module prebuild resolution and ordinal imports, geometry readers, `R16_TYPELESS` (53) index sizing, whole-range bottom-level builds, DXR-legal `PERFORM_UPDATE` flag stripping and VA-reuse safety (`perform_update_queries_dxr_legal_flags_without_stale_cache`), cross-64 KiB-tile `ARRAY_OF_POINTERS` + fault-safe `read_own` + BLAS header asks (`tlas_pointer_array_cross_tile_read_own_and_blas_headers`), fallback estimation, and build/rehydrate hook forwarding. - `crates/xcl/src/hle/d3d12x/view_want.rs`: add `Path::BvhBuild` (`"acceleration-structure builds"`, `PATHS = 14`). - `crates/xcl/src/hle/mod.rs`, `crates/xcl/src/resolver.rs`: wire `hle::bvh_builder::wrap` in `resolve_import` and `get_proc_address` for `xboxbvhbuilder.dll`, passing the mapped module and `ImportName`. **Tested** - Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 32.0.16.1074 / 610.74), AMD Ryzen 9 9950X, Windows 11 x64 (10.0.26200), `rustc 1.99.0`, DXC `1.9.2609.5`. - `cargo build --release -p xcl` (commit `4082300ba84ea77630ac1050264b4d07fc4bb5a3`): succeeded, 39 warnings (0 new vs `main`). - Full `.\scripts\test.ps1` directly on `4082300ba84ea77630ac1050264b4d07fc4bb5a3`: **2986 passed, 0 failed, 52 ignored** across 43 suites; **24 `SKIPPED` GPU lines** on this adapter (22 `no wave64`, 2 `no heap windows`), including all 12 `hle::bvh_builder::tests` passing. - 180 s live 16-window GPU-views run directly on `4082300ba84ea77630ac1050264b4d07fc4bb5a3` (`XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1`): `exit: 0x0`, `1645` frames shown (`1645` PresentX calls), `0` device removals, `0` crashes; logged 29 `GPU view (2 s)` lines with `acceleration-structure builds` totaling `30036` range asks (`478656 KB` new), peaking at `4433 acceleration-structure builds (142976 KB new)` at `96.6 s` and `2237 acceleration-structure builds (50816 KB new)` at `149.1 s`. - Local timing instrumentation on `4082300ba` (uncommitted, reverted after measurement) over 53.0 s of active 16-window BVH builds (`113` `BuildBatched2X` calls / `1472` items, `83` `RehydrateBatched2X` calls / `1250` items; `2637` BLAS, `85` TLAS `LAYOUT_ARRAY`, `0` TLAS `LAYOUT_ARRAY_OF_POINTERS`, `74120` TLAS instances read in `1220` `read_gpu_bytes` calls): **`13.92 ms` total hook CPU time** (`0.026 %` of wall time, `2.36 %` of the `588.6 ms` spent inside the real `XboxBvhBuilder.dll` calls; `71 µs` / call, `5.1 µs` / item, max single call `756 µs`): `read_geometries` `2.47 ms`, `sizes_of` `0.265 ms` (`0.10 µs` / item), `ranges_of_build` `6.58 ms` (`77 µs` / TLAS build), `ask` `4.16 ms`. **Regression run** (Clean pair; the `XboxBvhBuilder` hook is not installed on the default 4-window layout.) ``` xcl-smoke v1 commit: 5eaadb54c14e0fc29597b2a1689d7dbd83491303 gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 60 exit: 0x0 frames shown: 1691 (PresentX 1691) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 16674 MB ``` ``` xcl-smoke v1 commit: 4082300ba84ea77630ac1050264b4d07fc4bb5a3 gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 60 exit: 0x0 frames shown: 1673 (PresentX 1673) presents per 2 s (last 3): 61 60 60 device removals: 0 crashes: 0 peak commit: 17378 MB ``` **Not tested** - Default 4-window smoke does not exercise the hooks because `view_windows()` is false there. - `LAYOUT_ARRAY_OF_POINTERS` TLAS builds were not emitted by the tested retail title (only `LAYOUT_ARRAY` TLAS builds occurred); `LAYOUT_ARRAY_OF_POINTERS` is covered by unit tests only. - `CopyRaytracingAccelerationStructure` is not hooked: a compacted or cloned copy whose destination is in a view window is still only asked for its first 64 KiB. - Not tested on AMD or Intel GPUs, wave64 GPU tests (22 skipped), or combined with #3521 (`XCL_SPARSE_LAZY=1`). **AI use** - Antigravity (`Gemini 4 Neon`): rebased standalone onto `main`, implemented review fixes (`read_own` + tile-splitting `cpu_run`, DXR-legal `sizes_of` without `UPDATE_SCRATCH`, TLAS BLAS header asks) and unit tests, ran the release build, full `scripts/test.ps1`, smoke runs, 180 s 16-window live run, and hook CPU timing measurement, and updated the PR description. - Claude Code (`Claude Opus 5.5`): authored the original range-request logic and earlier review fixes.
KDenKC commented 2026-12-02 07:03:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KDenKC on 2026-12-02T07:03:15Z.


@Kalmarv a first in-world result with #3662 on the RTX 5090, and it's a big one for the picture, though we don't know yet which part of it does it.

What ran. Our tree (our window/alias fixes and diagnostics) + #3662 + #3656 (with #3327 under it), XCL_NATIVE_MESH=0 (so #3656's native path was off; its global shader changes were in), XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16, XCL_SKIP_CS=95cc13288a27a96e, a fully prepared shader cache plus a warm-up, one ~530 s run in the first interior scene.

Picture: clearly better than anything we've had in that scene. By eye and in the saved frames:

  • the window is lit: sky, the building, the watch tower, and the yard with its tables and several people sitting and standing in it;
  • the characters are solid and lit (hair, shoulders, jacket with rim light) instead of the see-through "glass" look every earlier build had;
  • what's still wrong is now localised: flat-coloured rectangles (missing texture tiles) over parts of the main character's head, neck and back, one flat tile on the wall, a part of the room's right side still unrendered, and frequent textures flickering in and out.
    Our own estimate: roughly 70 % of the scene correct, against far less before.

Performance: degraded. 4.6 fps in the world (stalls 7, longest 26 s) vs 6.8–7.2 fps for the #3656 A/B arms on the same save; peak commit 40,946 MB and peak local VRAM 20,376 MB (vs 39,228 / 19,217 MB for #3327 alone), no device removal or crash.

Ray tracing: our GPU counter on the node test still reads 0 node tests in this run. But with #3662 the top-level headers the walk reads moved (to 0x145db10000 / 0x145f8cf100 / 0x1460868d00 in this run) and their GPU-side roots now hold what looks like real node data, where before they read empty. Why the walk still tests no node is the next thing we're checking (which backend the ray programs take, which view they read the root through).

We don't know yet why the picture improved. Candidates: #3662's 16-window memory-layout commits (trailing view windows for overflow MEM_GRAPHICS reservations, 4 runtime sparse windows: e.g. character vertex/skinning data that was partly uncovered before), its null-window raw UAV fix, or #3656's global signature/optimizer changes. A run of our tree + #3662 alone is next and will split those; we'll post which one it is.

From here we'll focus on tools that find and pin down the remaining small artifacts (the tiles and flicker) automatically. The speed side we'd happily leave to you or a later step.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

<!-- greyfinch-sync:ivall/xcl:comment:7337717969 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7337717969). Originally posted by [KDenKC](https://github.com/KDenKC) on 2026-12-02T07:03:15Z. --- @Kalmarv a first in-world result with #3662 on the RTX 5090, and it's a big one for the picture, though we don't know yet which part of it does it. **What ran.** Our tree (our window/alias fixes and diagnostics) + #3662 + #3656 (with #3327 under it), `XCL_NATIVE_MESH=0` (so #3656's native path was off; its global shader changes were in), `XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16`, `XCL_SKIP_CS=95cc13288a27a96e`, a fully prepared shader cache plus a warm-up, one ~530 s run in the first interior scene. **Picture: clearly better than anything we've had in that scene.** By eye and in the saved frames: - the window is lit: sky, the building, the watch tower, and the yard with its tables and several people sitting and standing in it; - the characters are **solid and lit** (hair, shoulders, jacket with rim light) instead of the see-through "glass" look every earlier build had; - what's still wrong is now localised: flat-coloured rectangles (missing texture tiles) over parts of the main character's head, neck and back, one flat tile on the wall, a part of the room's right side still unrendered, and frequent textures flickering in and out. Our own estimate: roughly 70 % of the scene correct, against far less before. **Performance: degraded.** 4.6 fps in the world (stalls 7, longest 26 s) vs 6.8–7.2 fps for the #3656 A/B arms on the same save; peak commit 40,946 MB and peak local VRAM 20,376 MB (vs 39,228 / 19,217 MB for #3327 alone), no device removal or crash. **Ray tracing:** our GPU counter on the node test still reads 0 node tests in this run. But with #3662 the top-level headers the walk reads moved (to `0x145db10000` / `0x145f8cf100` / `0x1460868d00` in this run) and their GPU-side roots now hold what looks like real node data, where before they read empty. Why the walk still tests no node is the next thing we're checking (which backend the ray programs take, which view they read the root through). **We don't know yet why the picture improved.** Candidates: #3662's 16-window memory-layout commits (trailing view windows for overflow MEM_GRAPHICS reservations, 4 runtime sparse windows: e.g. character vertex/skinning data that was partly uncovered before), its null-window raw UAV fix, or #3656's global signature/optimizer changes. A run of our tree + #3662 alone is next and will split those; we'll post which one it is. From here we'll focus on tools that find and pin down the remaining small artifacts (the tiles and flicker) automatically. The speed side we'd happily leave to you or a later step. AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.
KDenKC commented 2026-12-02 07:46:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KDenKC on 2026-12-02T07:46:36Z.


@Kalmarv follow-up to the result above, as promised: the solid characters come from #3662's stack, not #3656. Our tree + #3662 alone (no #3656 or #3327), same env, same scene: the main character and the people in the yard are solid and lit, the window is lit, with the same flat missing-texture tiles on the character as the combined run. One more run will split #3662's memory-layout commits (the trailing view windows for overflow MEM_GRAPHICS reservations and the 4 runtime sparse windows) from the builder hook and the null raw-UAV fix; we'll add which one it is.

On the ray-tracing side, with #3662 the top-level headers on the GPU now hold built structures (one walk finds ~915,000 nodes in 787 bottom levels), and the title's ray programs do start (about 540 million lanes over a run), but they leave before their first node test: in the program we read, every lane exits at an early check on a per-pixel 32-bit classification word read from a 2D texture before any intersect instruction. We're tracing which pass writes that word next.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

<!-- greyfinch-sync:ivall/xcl:comment:7338595107 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7338595107). Originally posted by [KDenKC](https://github.com/KDenKC) on 2026-12-02T07:46:36Z. --- @Kalmarv follow-up to the result above, as promised: the solid characters come from **#3662's stack, not #3656**. Our tree + #3662 alone (no #3656 or #3327), same env, same scene: the main character and the people in the yard are solid and lit, the window is lit, with the same flat missing-texture tiles on the character as the combined run. One more run will split #3662's memory-layout commits (the trailing view windows for overflow MEM_GRAPHICS reservations and the 4 runtime sparse windows) from the builder hook and the null raw-UAV fix; we'll add which one it is. On the ray-tracing side, with #3662 the top-level headers on the GPU now hold built structures (one walk finds ~915,000 nodes in 787 bottom levels), and the title's ray programs do start (about 540 million lanes over a run), but they leave before their first node test: in the program we read, every lane exits at an early check on a per-pixel 32-bit classification word read from a 2D texture before any intersect instruction. We're tracing which pass writes that word next. AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.
KDenKC commented 2026-12-02 08:05:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KDenKC on 2026-12-02T08:05:54Z.


@Kalmarv @CharlyRien the split run answers it: the solid characters come from the two memory-layout commits under #3662, not the builder hook or the null raw-UAV fix. Our tree + only #3517's 16-window layout change (4 runtime sparse windows) and #3653's trailing view windows for overflow MEM_GRAPHICS reservations, same env and scene: the main character and the people in the yard are solid and lit, exactly as with the full #3662 stack (and see-through on every build without them). So #3517 + #3653 on the 16-window layout fix the "glass" characters on our RTX 5090 by themselves. The remaining flat texture tiles on the character are the same with and without the rest of #3662. In that run too, the ray programs start but do no node test.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

<!-- greyfinch-sync:ivall/xcl:comment:7338999827 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7338999827). Originally posted by [KDenKC](https://github.com/KDenKC) on 2026-12-02T08:05:54Z. --- @Kalmarv @CharlyRien the split run answers it: the solid characters come from the **two memory-layout commits** under #3662, not the builder hook or the null raw-UAV fix. Our tree + only #3517's 16-window layout change (4 runtime sparse windows) and #3653's trailing view windows for overflow MEM_GRAPHICS reservations, same env and scene: the main character and the people in the yard are solid and lit, exactly as with the full #3662 stack (and see-through on every build without them). So #3517 + #3653 on the 16-window layout fix the "glass" characters on our RTX 5090 by themselves. The remaining flat texture tiles on the character are the same with and without the rest of #3662. In that run too, the ray programs start but do no node test. AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.
Foniass commented 2026-12-02 08:36:34 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T08:36:34Z.


Review (head a69189b8, diff read, not a merge-check):

  • Size and stack. +2233/-93 in 6 commits, but only a69189b89 (+866/-1, about 350 lines tests) belongs to this PR. By reading, it applies to current main without conflicts and uses nothing from the stacked commits: hle/bvh_builder.rs only calls view_want, gpu::bvh::prebuild_size/HEADER_BYTES and gpu::shader::readable, all on main; the inner d3d12x::bvh_builder hook is only mentioned in doc comments. The stacked copies of #3517, #3349, #3521 and #3522 are rebased and do not match those PRs' heads (ce078501 vs 0b4283d1, e3ca17dd vs 5dc64ea7, 23d5cafd vs 2e2d9320, f0c6ae41 vs 5abd576b); with merge commits, each change would land in main twice. #3349 (null raw UAVs in shared_heap) is unrelated to BVH builds. Rebase a69189b89 alone onto main; if it must be smaller: (1) the ABI structs, ranges_of_build and their tests; (2) the hooks and the resolver.rs / view_want::Path::BvhBuild wiring. The two #3653 commits it carries are identical to #3653's.
  • An update's scratch is not asked for when the query returns 0. hle/bvh_builder.rs ~395-401 sizes a PERFORM_UPDATE build's scratch with UpdateScratchDataSizeInBytes from the prebuild query on the update's own inputs; when that is 0, push_range (~336) drops the range and only the 64 KiB root-view ask remains. The inner hook documents that this query "may give none" (d3d12x/bvh_builder.rs ~53) and keeps the size from the earlier ALLOW_UPDATE build, falling back to the larger scratch size. Reusing that logic (and its SIZES map) would fix this and avoid a second copy of the ABI and sizing code.
  • The prebuild query depends on the title importing it. REAL_PREBUILD_INFO (~236-240) is set only when the title resolves GetRaytracingAccelerationStructurePrebuildInfo itself; otherwise scratch is asked for at SCRATCH_GUESS (64 KiB), no better than before. The inner hook looks the export up in the mapped module directly (d3d12x/bvh_builder.rs ~81-82); the outer hook could do the same.
  • Instance descriptions behind pointers are not asked for. For a top-level build with ARRAY_OF_POINTERS (~403-404) only the 8-byte pointer array is asked for, not the 64-byte instance descriptions read through it, so in a GPU view they can still read zeros.
  • No runtime evidence for the hook. The commit says every other tile "read zeros and dropped writes" on the 16-window layout, but the 60 s 16-window run reached no acceleration-structure build, and the default-layout smoke runs install no hook (view_windows() is false). The unit tests check range arithmetic only (under test view_want::want returns early), so nothing shows the tiles get mapped or what that costs per build (sparse::map_mirror walks the ranges' tiles on the recording thread).
  • Nothing is translated. The hook forwards to the title's own XboxBvhBuilder.dll, which keeps writing its console-format BVH for XCL's traversal. No D3D12 acceleration structure is produced, so nothing here connects to #3659's RayQuery SRVs yet (no shared files, no overlap).

Fine (by reading): the ABI layouts (BuildDesc 0x30, BatchedBuildDesc2 0x50, GeometryDesc 0x38, triangle and AABB payloads, R16 index formats 53..=59) match their D3D12 counterparts; with XCL_SPARSE_LAZY=1 the calls go outer hook, inner hook, DLL; wrapping is gated on view windows, so the default 4-window layout is unchanged, and #3653's trailing reservations return None there.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7339682499 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7339682499). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T08:36:34Z. --- Review (head a69189b8, diff read, not a merge-check): - **Size and stack.** +2233/-93 in 6 commits, but only `a69189b89` (+866/-1, about 350 lines tests) belongs to this PR. By reading, it applies to current main without conflicts and uses nothing from the stacked commits: `hle/bvh_builder.rs` only calls `view_want`, `gpu::bvh::prebuild_size`/`HEADER_BYTES` and `gpu::shader::readable`, all on main; the inner `d3d12x::bvh_builder` hook is only mentioned in doc comments. The stacked copies of #3517, #3349, #3521 and #3522 are rebased and do not match those PRs' heads (`ce078501` vs `0b4283d1`, `e3ca17dd` vs `5dc64ea7`, `23d5cafd` vs `2e2d9320`, `f0c6ae41` vs `5abd576b`); with merge commits, each change would land in main twice. #3349 (null raw UAVs in `shared_heap`) is unrelated to BVH builds. Rebase `a69189b89` alone onto main; if it must be smaller: (1) the ABI structs, `ranges_of_build` and their tests; (2) the hooks and the `resolver.rs` / `view_want::Path::BvhBuild` wiring. The two #3653 commits it carries are identical to #3653's. - **An update's scratch is not asked for when the query returns 0.** `hle/bvh_builder.rs` ~395-401 sizes a `PERFORM_UPDATE` build's scratch with `UpdateScratchDataSizeInBytes` from the prebuild query on the update's own inputs; when that is 0, `push_range` (~336) drops the range and only the 64 KiB root-view ask remains. The inner hook documents that this query "may give none" (`d3d12x/bvh_builder.rs` ~53) and keeps the size from the earlier `ALLOW_UPDATE` build, falling back to the larger scratch size. Reusing that logic (and its `SIZES` map) would fix this and avoid a second copy of the ABI and sizing code. - **The prebuild query depends on the title importing it.** `REAL_PREBUILD_INFO` (~236-240) is set only when the title resolves `GetRaytracingAccelerationStructurePrebuildInfo` itself; otherwise scratch is asked for at `SCRATCH_GUESS` (64 KiB), no better than before. The inner hook looks the export up in the mapped module directly (`d3d12x/bvh_builder.rs` ~81-82); the outer hook could do the same. - **Instance descriptions behind pointers are not asked for.** For a top-level build with `ARRAY_OF_POINTERS` (~403-404) only the 8-byte pointer array is asked for, not the 64-byte instance descriptions read through it, so in a GPU view they can still read zeros. - **No runtime evidence for the hook.** The commit says every other tile "read zeros and dropped writes" on the 16-window layout, but the 60 s 16-window run reached no acceleration-structure build, and the default-layout smoke runs install no hook (`view_windows()` is false). The unit tests check range arithmetic only (under test `view_want::want` returns early), so nothing shows the tiles get mapped or what that costs per build (`sparse::map_mirror` walks the ranges' tiles on the recording thread). - **Nothing is translated.** The hook forwards to the title's own `XboxBvhBuilder.dll`, which keeps writing its console-format BVH for XCL's traversal. No D3D12 acceleration structure is produced, so nothing here connects to #3659's RayQuery SRVs yet (no shared files, no overlap). Fine (by reading): the ABI layouts (`BuildDesc` 0x30, `BatchedBuildDesc2` 0x50, `GeometryDesc` 0x38, triangle and AABB payloads, R16 index formats 53..=59) match their D3D12 counterparts; with `XCL_SPARSE_LAZY=1` the calls go outer hook, inner hook, DLL; wrapping is gated on view windows, so the default 4-window layout is unchanged, and #3653's trailing reservations return `None` there. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Decodere commented 2026-12-02 08:56:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Decodere on 2026-12-02T08:56:52Z.


Diff review (head a69189b89, read-only code review — not a test report):

Clean ABI verification for XboxBvhBuilder.dll and safe gating on view_windows() (crates/xcl/src/hle/bvh_builder.rs:203-221) so the default 4-window layout is unchanged. Reading the full diff (+2233/-93 across 16 files) turned up 3 concrete issues across both the 5-PR stack and the new hook itself:

  1. 5-PR stack carries rebased copies of unmerged PRs and inherits their open bugs:
    Only the top commit (a69189b89, +866/-1 across 4 files) belongs to this PR, and it depends only on symbols already on main (view_want, gpu::bvh, gpu::shader::readable). The 5 commits underneath carry copies of #3517, #3653, #3349, #3521, and #3522 (4 of 5 with different commit SHAs from those PRs' open heads), inheriting:

    • #3517's with_switch_fallback window-4 cutoff (crates/xcl/src/gpu/uma.rs:48, :59; crates/xcl/src/hle/d3d12x/real.rs:5178-5191; crates/xcl/src/gpu/recomp/pso.rs:147-161; crates/xcl/src/hle/d3d12x/bind.rs:5316-5318): moving 16-window coherent memory to window 4 places it past MAX_WINDOWS = 4 root UAVs (0..3) whenever a pipeline takes #156 switch fallback.
    • #3653's unrelated dead code (crates/xcl/src/hle/d3d12x/title_list.rs:292-298, :1135-1161): unused pub fn active_backing + unit test.
    • #3522's self.own lifecycle/recycle hazards in sparse.rs (un-cleared self.own on commit/decommit and same-submit yield_own -> self.parked -> new_mirror reuse before in-flight GPU completion).
  2. Three range-sizing / hook gaps in crates/xcl/src/hle/bvh_builder.rs:

    • Update scratch dropped when prebuild returns 0 (bvh_builder.rs:335-339, :395-401): for BUILD_FLAG_PERFORM_UPDATE, ranges_of_build passes sizes.update_scratch_data_size_in_bytes directly to push_range, dropping the scratch range whenever querying GetRaytracingAccelerationStructurePrebuildInfo with PERFORM_UPDATE returns 0 (whereas crates/xcl/src/hle/d3d12x/bvh_builder.rs:123-129 retains UpdateScratchDataSizeInBytes from the original ALLOW_UPDATE build and falls back to ScratchDataSizeInBytes.max(UpdateScratchDataSizeInBytes)).
    • REAL_PREBUILD_INFO depends on the title resolving that export first (bvh_builder.rs:236-241, :333, :344-366): REAL_PREBUILD_INFO is only captured if the title imports or calls GetProcAddress on SYM_PREBUILD_INFO before building; otherwise scratch falls back to SCRATCH_GUESS = 64 KiB. Looking up the export directly from the mapped module (as in d3d12x/bvh_builder.rs:81-83) and resolving ordinal imports in resolver.rs:327-329, :444-446 avoids this.
    • Indirect ARRAY_OF_POINTERS TLAS instance descriptions omitted (bvh_builder.rs:402-404): asks only for the 8 * num_descs pointer table, not the pointed-to 64-byte D3D12_RAYTRACING_INSTANCE_DESC targets.
  3. Performance regression & isolation:
    RTX 5090 testing in this thread measured degraded in-world throughput (4.6 fps and a 26 s stall vs 6.8–7.2 fps) and bisected the visual improvement solely to the #3517 + #3653 memory-layout commits rather than this hook. Rebasing a69189b89 standalone onto main (and unifying its prebuild/range sizing with d3d12x::bvh_builder once #3521/#3522 settle) will allow clean isolated measurement of the hook itself.

AI use: Antigravity (Gemini 4 Neon) audited the full diff against main and drafted this review.

<!-- greyfinch-sync:ivall/xcl:comment:7340147945 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7340147945). Originally posted by [Decodere](https://github.com/Decodere) on 2026-12-02T08:56:52Z. --- Diff review (head `a69189b89`, read-only code review — not a test report): Clean ABI verification for `XboxBvhBuilder.dll` and safe gating on `view_windows()` (`crates/xcl/src/hle/bvh_builder.rs:203-221`) so the default 4-window layout is unchanged. Reading the full diff (`+2233/-93` across 16 files) turned up 3 concrete issues across both the 5-PR stack and the new hook itself: 1. **5-PR stack carries rebased copies of unmerged PRs and inherits their open bugs**: Only the top commit (`a69189b89`, `+866/-1` across 4 files) belongs to this PR, and it depends only on symbols already on `main` (`view_want`, `gpu::bvh`, `gpu::shader::readable`). The 5 commits underneath carry copies of `#3517`, `#3653`, `#3349`, `#3521`, and `#3522` (4 of 5 with different commit SHAs from those PRs' open heads), inheriting: - **`#3517`'s `with_switch_fallback` window-4 cutoff** (`crates/xcl/src/gpu/uma.rs:48`, `:59`; `crates/xcl/src/hle/d3d12x/real.rs:5178-5191`; `crates/xcl/src/gpu/recomp/pso.rs:147-161`; `crates/xcl/src/hle/d3d12x/bind.rs:5316-5318`): moving 16-window coherent memory to window `4` places it past `MAX_WINDOWS = 4` root UAVs (`0..3`) whenever a pipeline takes `#156` switch fallback. - **`#3653`'s unrelated dead code** (`crates/xcl/src/hle/d3d12x/title_list.rs:292-298`, `:1135-1161`): unused `pub fn active_backing` + unit test. - **`#3522`'s `self.own` lifecycle/recycle hazards** in `sparse.rs` (un-cleared `self.own` on commit/decommit and same-submit `yield_own` -> `self.parked` -> `new_mirror` reuse before in-flight GPU completion). 2. **Three range-sizing / hook gaps in `crates/xcl/src/hle/bvh_builder.rs`**: - **Update scratch dropped when prebuild returns `0`** (`bvh_builder.rs:335-339`, `:395-401`): for `BUILD_FLAG_PERFORM_UPDATE`, `ranges_of_build` passes `sizes.update_scratch_data_size_in_bytes` directly to `push_range`, dropping the scratch range whenever querying `GetRaytracingAccelerationStructurePrebuildInfo` with `PERFORM_UPDATE` returns `0` (whereas `crates/xcl/src/hle/d3d12x/bvh_builder.rs:123-129` retains `UpdateScratchDataSizeInBytes` from the original `ALLOW_UPDATE` build and falls back to `ScratchDataSizeInBytes.max(UpdateScratchDataSizeInBytes)`). - **`REAL_PREBUILD_INFO` depends on the title resolving that export first** (`bvh_builder.rs:236-241`, `:333`, `:344-366`): `REAL_PREBUILD_INFO` is only captured if the title imports or calls `GetProcAddress` on `SYM_PREBUILD_INFO` before building; otherwise scratch falls back to `SCRATCH_GUESS = 64 KiB`. Looking up the export directly from the mapped module (as in `d3d12x/bvh_builder.rs:81-83`) and resolving ordinal imports in `resolver.rs:327-329`, `:444-446` avoids this. - **Indirect `ARRAY_OF_POINTERS` TLAS instance descriptions omitted** (`bvh_builder.rs:402-404`): asks only for the `8 * num_descs` pointer table, not the pointed-to 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` targets. 3. **Performance regression & isolation**: RTX 5090 testing in this thread measured degraded in-world throughput (`4.6 fps` and a 26 s stall vs `6.8–7.2 fps`) and bisected the visual improvement solely to the `#3517` + `#3653` memory-layout commits rather than this hook. Rebasing `a69189b89` standalone onto `main` (and unifying its prebuild/range sizing with `d3d12x::bvh_builder` once `#3521`/`#3522` settle) will allow clean isolated measurement of the hook itself. AI use: Antigravity (Gemini 4 Neon) audited the full diff against `main` and drafted this review.
KDenKC commented 2026-12-02 09:15:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KDenKC on 2026-12-02T09:15:42Z.


A narrower answer than in my last comment: #3517 alone is enough. Our tree + only @CharlyRien's #3517 (the 16-window layout keeping 4 runtime sparse windows), without #3653 or the rest of #3662, same env and scene: the characters are solid and lit, with the same flat texture tiles. So the "glass" characters come from what #3517 changes in the 16-window layout; #3653's overflow coverage isn't needed for that (it may still matter elsewhere). Ray programs: as before, they start and do no node test.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

<!-- greyfinch-sync:ivall/xcl:comment:7340618888 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7340618888). Originally posted by [KDenKC](https://github.com/KDenKC) on 2026-12-02T09:15:42Z. --- A narrower answer than in my last comment: #3517 **alone** is enough. Our tree + only @CharlyRien's #3517 (the 16-window layout keeping 4 runtime sparse windows), without #3653 or the rest of #3662, same env and scene: the characters are solid and lit, with the same flat texture tiles. So the "glass" characters come from what #3517 changes in the 16-window layout; #3653's overflow coverage isn't needed for that (it may still matter elsewhere). Ray programs: as before, they start and do no node test. AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.
Foniass commented 2026-12-02 11:03:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T11:03:36Z.


merge-check
base: 1c8b551475
head: a69189b894
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2936 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7339682499 and its findings stand. Most serious: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0.
performance: 60 s smoke of a retail title, main 1c8b5514 vs this merge (a69189b8): 1652 -> 1684 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 18228 -> 18899 MB, 0 device removals, 0 crashes.
verdict: not yet: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0 (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7343365994 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7343365994). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T11:03:36Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: a69189b894a5e0127eb543de55c29836367b0e9d merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2936 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7339682499 and its findings stand. Most serious: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0. performance: 60 s smoke of a retail title, main 1c8b5514 vs this merge (a69189b8): 1652 -> 1684 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 18228 -> 18899 MB, 0 device removals, 0 crashes. verdict: not yet: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0 (see the review) hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
Kalmarv commented 2026-12-02 15:06:12 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T15:06:12Z.


Updated in a65c38b16 (standalone on main 5eaadb54c — all 5 stacked commits from #3517/#3653/#3349/#3521/#3522 dropped) and addressed every review point:

  • @Foniass (PERFORM_UPDATE scratch size = 0): cached UpdateScratchDataSizeInBytes on ALLOW_UPDATE builds in UPDATE_SCRATCH (crates/xcl/src/hle/bvh_builder.rs, resolve_scratch_bytes) so a later PERFORM_UPDATE whose prebuild query returns 0 reuses the cached size (in-place or out-of-place), falling back to scratch_size.max(update_scratch_size).max(SCRATCH_GUESS) instead of dropping the scratch range; covered by perform_update_uses_cached_allow_update_scratch_and_falls_back_when_zero.
  • @Foniass (prebuild query lookup & ordinal imports): bvh_builder::wrap now takes the mapped XboxBvhBuilder.dll module and ImportName (crates/xcl/src/hle/bvh_builder.rs, record_prebuild_from_module / wrap_with_module; wired in crates/xcl/src/resolver.rs), resolving GetRaytracingAccelerationStructurePrebuildInfo directly from the mapped DLL when any export is wrapped and matching ordinal imports as well as names; covered by wrap_resolves_prebuild_info_from_mapped_module_and_handles_ordinals.
  • @Foniass (TLAS ARRAY_OF_POINTERS): ranges_of_build now translates inp.descs through list_x::cpu_at, reads the pointer array under shader::readable, and sorts/coalesces contiguous or overlapping 64-byte D3D12_RAYTRACING_INSTANCE_DESC target ranges before calling view_want::want; covered by a_top_level_build_names_its_instance_descriptions (including a non-identity GPU VA -> CPU VA mapping).
  • @Decodere (diff size & #3521 relation): rebased standalone onto main (5eaadb54c) so the PR diff is only the 4 files / +1139 -1 lines of this change (~585 prod + ~554 unit tests), and documented the concrete difference vs #3521 (and why UPDATE_SCRATCH temporarily mirrors #3521's SIZES until #3521 lands) in the PR body.
  • @KDenKC (bisect): thanks for bisecting the solid-character improvement to #3517's 16-window layout — updated the PR body to note that and drop the earlier attribution.

PR body updated with fresh scripts/test.ps1 counts, default smoke blocks, and 16-window live run results.

<!-- greyfinch-sync:ivall/xcl:comment:7349723234 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7349723234). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T15:06:12Z. --- Updated in `a65c38b16` (standalone on `main` `5eaadb54c` — all 5 stacked commits from `#3517`/`#3653`/`#3349`/`#3521`/`#3522` dropped) and addressed every review point: - **@Foniass (`PERFORM_UPDATE` scratch size = 0):** cached `UpdateScratchDataSizeInBytes` on `ALLOW_UPDATE` builds in `UPDATE_SCRATCH` (`crates/xcl/src/hle/bvh_builder.rs`, `resolve_scratch_bytes`) so a later `PERFORM_UPDATE` whose prebuild query returns `0` reuses the cached size (in-place or out-of-place), falling back to `scratch_size.max(update_scratch_size).max(SCRATCH_GUESS)` instead of dropping the scratch range; covered by `perform_update_uses_cached_allow_update_scratch_and_falls_back_when_zero`. - **@Foniass (prebuild query lookup & ordinal imports):** `bvh_builder::wrap` now takes the mapped `XboxBvhBuilder.dll` module and `ImportName` (`crates/xcl/src/hle/bvh_builder.rs`, `record_prebuild_from_module` / `wrap_with_module`; wired in `crates/xcl/src/resolver.rs`), resolving `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped DLL when any export is wrapped and matching ordinal imports as well as names; covered by `wrap_resolves_prebuild_info_from_mapped_module_and_handles_ordinals`. - **@Foniass (TLAS `ARRAY_OF_POINTERS`):** `ranges_of_build` now translates `inp.descs` through `list_x::cpu_at`, reads the pointer array under `shader::readable`, and sorts/coalesces contiguous or overlapping 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target ranges before calling `view_want::want`; covered by `a_top_level_build_names_its_instance_descriptions` (including a non-identity GPU VA -> CPU VA mapping). - **@Decodere (diff size & `#3521` relation):** rebased standalone onto `main` (`5eaadb54c`) so the PR diff is only the 4 files / +1139 -1 lines of this change (~585 prod + ~554 unit tests), and documented the concrete difference vs `#3521` (and why `UPDATE_SCRATCH` temporarily mirrors `#3521`'s `SIZES` until `#3521` lands) in the PR body. - **@KDenKC (bisect):** thanks for bisecting the solid-character improvement to `#3517`'s 16-window layout — updated the PR body to note that and drop the earlier attribution. PR body updated with fresh `scripts/test.ps1` counts, default smoke blocks, and 16-window live run results.
Kalmarv commented 2026-12-02 15:37:46 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T15:37:46Z.


Follow-up runtime evidence (@Foniass): once the 16-window shader cache warmed up, a 180 s XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1 run on the stacked #3700 binary with XCL_HW_RT unset (where #3662's hook is the only active one) completed with exit: 0x0, 1920 frames, 0 device removals, and logged 27 GPU view (2 s) lines containing acceleration-structure builds (peaking at 4089 acceleration-structure builds (139392 KB new) at 91.5 s and 1517 acceleration-structure builds (89152 KB new) at 174.9 s). Added to Tested / Not tested in the PR body.

<!-- greyfinch-sync:ivall/xcl:comment:7350650881 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7350650881). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T15:37:46Z. --- Follow-up runtime evidence (@Foniass): once the 16-window shader cache warmed up, a 180 s `XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1` run on the stacked #3700 binary with `XCL_HW_RT` unset (where `#3662`'s hook is the only active one) completed with `exit: 0x0`, `1920` frames, `0` device removals, and logged 27 `GPU view (2 s)` lines containing `acceleration-structure builds` (peaking at `4089 acceleration-structure builds (139392 KB new)` at `91.5 s` and `1517 acceleration-structure builds (89152 KB new)` at `174.9 s`). Added to **Tested** / **Not tested** in the PR body.
bmjask commented 2026-12-02 19:55:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:55:57Z.

Review: COMMENTED


Review of a65c38b1: 4 finding(s) (1 critical, 1 high, 2 medium), most severe first.

  1. Critical crates/xcl/src/hle/bvh_builder.rs:492: The CPU view of the top-level pointer array is read with raw read_unaligned after a shader::readable check, a check-then-use race on title memory that can be decommitted concurrently. (inline)
  2. High crates/xcl/src/hle/bvh_builder.rs:487: The ARRAY_OF_POINTERS pointer array is translated with cpu_at(inp.descs) (base address only) and then read as one contiguous n*8-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow .... (inline)
  3. Medium crates/xcl/src/hle/bvh_builder.rs:208: UPDATE_SCRATCH grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. (inline)
  4. Medium crates/xcl/src/hle/bvh_builder.rs:517: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's `AccelerationStructu.... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6157884042 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#pullrequestreview-6157884042). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:55:57Z. **Review:** COMMENTED --- Review of `a65c38b1`: 4 finding(s) (1 critical, 1 high, 2 medium), most severe first. 1. **Critical** `crates/xcl/src/hle/bvh_builder.rs:492`: The CPU view of the top-level pointer array is read with raw `read_unaligned` after a `shader::readable` check, a check-then-use race on title memory that can be decommitted concurrently. (inline) 2. **High** `crates/xcl/src/hle/bvh_builder.rs:487`: The ARRAY_OF_POINTERS pointer array is translated with `cpu_at(inp.descs)` (base address only) and then read as one contiguous `n*8`-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow .... (inline) 3. **Medium** `crates/xcl/src/hle/bvh_builder.rs:208`: `UPDATE_SCRATCH` grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. (inline) 4. **Medium** `crates/xcl/src/hle/bvh_builder.rs:517`: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's `AccelerationStructu.... (inline) --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 19:55:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:55:58Z.

Code review location: crates/xcl/src/hle/bvh_builder.rs; line 492

@@ -0,0 +1,1126 @@
+//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests.
+//!
+//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++
+//! batched build and rehydrate methods on static/delay import resolution and dynamic
+//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to
+//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`).
+//!
+//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers
+//! through addresses inside geometry descriptions they upload themselves, and the destination,
+//! source and scratch through root views, which `view_want` asks for 64 KiB from their address
+//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and
+//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels
+//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for
+//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own
+//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when
+//! the unified memory has view windows, so nothing changes on the default 4-window layout.
+
+#![allow(non_snake_case)]
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Mutex, Once};
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`.
+pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z";
+pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+
+/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`.
+pub const INSTANCE_DESC_BYTES: u64 = 64;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values.
+pub const AS_TYPE_TOP_LEVEL: u32 = 0;
+pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1;
+
+/// `D3D12_ELEMENTS_LAYOUT` values.
+pub const LAYOUT_ARRAY: u32 = 0;
+pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`.
+pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1;
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`.
+pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20;
+
+/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values.
+pub const GEOM_TYPE_TRIANGLES: u32 = 0;
+pub const GEOM_TYPE_AABBS: u32 = 1;
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildInputs {
+    pub ty: u32,           // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL
+    pub flags: u32,        // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS
+    pub num_descs: u32,    // +0x08: instance count (TLAS) or geometry count (BLAS)
+    pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS
+    pub descs: u64,        // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS)
+}
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildDesc {
+    pub dest: u64,           // +0x00: DestAccelerationStructureData GPU VA
+    pub inputs: BuildInputs, // +0x08..+0x20
+    pub source: u64,         // +0x20: SourceAccelerationStructureData GPU VA
+    pub scratch: u64,        // +0x28: ScratchAccelerationStructureData GPU VA
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PostbuildInfoDesc {
+    pub dest_buffer: u64, // +0x00
+    pub info_type: u32,   // +0x08
+    pub _pad: u32,        // +0x0C
+}
+
+/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct StreamDesc {
+    pub size_in_bytes: u64, // +0x00
+    pub p_stream: u64,      // +0x08
+}
+
+/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`).
+/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BatchedBuildDesc2 {
+    pub build: BuildDesc,              // +0x00..+0x30
+    pub num_postbuild_info_descs: u32, // +0x30
+    pub _pad: u32,                     // +0x34
+    pub p_postbuild_info_descs: u64,   // +0x38
+    pub stream: StreamDesc,            // +0x40..+0x50
+}
+
+/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct GeometryDesc {
+    pub ty: u32,           // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs
+    pub flags: u32,        // +0x04
+    pub payload: [u64; 6], // +0x08..+0x38
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TriangleGeometry {
+    pub transform3x4: u64,
+    pub index_format: u32,
+    pub vertex_format: u32,
+    pub index_count: u32,
+    pub vertex_count: u32,
+    pub index_buffer: u64,
+    pub vertex_buffer: u64,
+    pub vertex_stride: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AabbGeometry {
+    pub count: u64,
+    pub start_address: u64,
+    pub stride: u64,
+}
+
+impl GeometryDesc {
+    pub fn as_triangles(&self) -> Option<TriangleGeometry> {
+        if self.ty != GEOM_TYPE_TRIANGLES {
+            return None;
+        }
+        Some(TriangleGeometry {
+            transform3x4: self.payload[0],
+            index_format: self.payload[1] as u32,
+            vertex_format: (self.payload[1] >> 32) as u32,
+            index_count: self.payload[2] as u32,
+            vertex_count: (self.payload[2] >> 32) as u32,
+            index_buffer: self.payload[3],
+            vertex_buffer: self.payload[4],
+            vertex_stride: self.payload[5],
+        })
+    }
+
+    pub fn as_aabbs(&self) -> Option<AabbGeometry> {
+        if self.ty != GEOM_TYPE_AABBS {
+            return None;
+        }
+        Some(AabbGeometry {
+            count: self.payload[0],
+            start_address: self.payload[1],
+            stride: self.payload[2],
+        })
+    }
+}
+
+impl TriangleGeometry {
+    pub fn index_elem_bytes(&self) -> u64 {
+        match self.index_format {
+            0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer
+            // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS)
+            53..=59 => 2,
+            // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element
+            _ => 4,
+        }
+    }
+
+    pub fn triangle_count(&self) -> u64 {
+        if self.index_count > 0 {
+            u64::from(self.index_count) / 3
+        } else {
+            u64::from(self.vertex_count) / 3
+        }
+    }
+
+    pub fn vertex_bytes(&self) -> u64 {
+        u64::from(self.vertex_count).saturating_mul(self.vertex_stride)
+    }
+
+    pub fn index_bytes(&self) -> u64 {
+        u64::from(self.index_count).saturating_mul(self.index_elem_bytes())
+    }
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PrebuildInfo {
+    pub result_data_max_size_in_bytes: u64,     // +0x00
+    pub scratch_data_size_in_bytes: u64,        // +0x08
+    pub update_scratch_data_size_in_bytes: u64, // +0x10
+}
+
+/// True for lowercase DLL key `"xboxbvhbuilder.dll"`.
+pub fn is_bvh_builder_dll(key: &str) -> bool {
+    key == "xboxbvhbuilder.dll"
+}
+
+static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0);
+/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build,
+/// used when a later `PERFORM_UPDATE` prebuild query returns 0.
+static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles
+/// get video memory only when asked for: the 16-window layout).
+fn view_windows() -> bool {
+    crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k)))
+}
+
+/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped
+/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it.
+fn record_prebuild_from_module(module: &MappedModule) {
+    if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) {
+        REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release);
+    }
+}
+
+/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for)
+/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture
+/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the
+/// passthrough hook address; otherwise return `real_addr`.
+pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 || !view_windows() {
+        return real_addr;
+    }
+    static WHY: Once = Once::new();
+    WHY.call_once(|| {
+        crate::xlog_info!(
+            "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)"
+        );
+    });
+    wrap_with_module(module, what, real_addr)
+}
+
+fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    if let Some(m) = module {
+        record_prebuild_from_module(m);
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.and_then(|m| {
+            m.exports.by_name.iter().find_map(|(n, t)| {
+                matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str())
+            })
+        }),
+    };
+    match name {
+        Some(n) => wrap_with(n, real_addr),
+        None => real_addr,
+    }
+}
+
+fn wrap_with(function: &str, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    match function {
+        SYM_BUILD_BATCHED2X => {
+            REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release);
+            BuildBatched2X_hook as usize
+        }
+        SYM_REHYDRATE_BATCHED2X => {
+            REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release);
+            RehydrateBatched2X_hook as usize
+        }
+        SYM_PREBUILD_INFO => {
+            // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on
+            // title calls.
+            REAL_PREBUILD_INFO.store(real_addr, Ordering::Release);
+            real_addr
+        }
+        _ => real_addr,
+    }
+}
+
+/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays
+/// and pointer-arrays safely via `shader::readable`.
+pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> {
+    let n = inputs.num_descs as usize;
+    if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 {
+        return Vec::new();
+    }
+    let mut out = Vec::with_capacity(n.min(1024));
+    match inputs.descs_layout {
+        LAYOUT_ARRAY => {
+            let elem = std::mem::size_of::<GeometryDesc>();
+            let Some(bytes) = n.checked_mul(elem) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, bytes) {
+                return out;
+            }
+            let base = inputs.descs as *const GeometryDesc;
+            for i in 0..n {
+                out.push(base.add(i).read_unaligned());
+            }
+        }
+        LAYOUT_ARRAY_OF_POINTERS => {
+            let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) {
+                return out;
+            }
+            let ptrs = inputs.descs as *const u64;
+            let elem = std::mem::size_of::<GeometryDesc>();
+            for i in 0..n {
+                let p = ptrs.add(i).read_unaligned();
+                if p != 0 && crate::gpu::shader::readable(p as usize, elem) {
+                    out.push((p as *const GeometryDesc).read_unaligned());
+                }
+            }
+        }
+        _ => {}
+    }
+    out
+}
+
+fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 {
+    if inputs.ty == AS_TYPE_TOP_LEVEL {
+        return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true);
+    }
+    let mut leaves = 0u64;
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            leaves = leaves.saturating_add(t.triangle_count());
+        } else if let Some(a) = g.as_aabbs() {
+            leaves = leaves.saturating_add(a.count);
+        }
+    }
+    if leaves > 0 {
+        crate::gpu::bvh::prebuild_size(leaves, false)
+    } else {
+        0
+    }
+}
+
+/// What a range a build or rehydrate names is for.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Use {
+    Dest,
+    Source,
+    Scratch,
+    Instances,
+    Vertices,
+    Indices,
+    Transform,
+    Aabbs,
+    Postbuild,
+}
+
+/// A GPU range the builder's programs read or write for one batch item.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Range {
+    pub what: Use,
+    pub va: u64,
+    pub len: u64,
+}
+
+/// bytes of a geometry's 3x4 float transform
+const TRANSFORM_BYTES: u64 = 48;
+/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16)
+const POSTBUILD_BYTES: u64 = 16;
+/// postbuild-info descriptions read of one batch item at most
+const MAX_POSTBUILD: usize = 64;
+/// scratch asked for when the DLL's prebuild answer is not at hand
+const SCRATCH_GUESS: u64 = 0x1_0000;
+
+fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) {
+    if va != 0 && len != 0 {
+        out.push(Range { what, va, len });
+    }
+}
+
+/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU
+/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the
+/// leaves counted for the result and `SCRATCH_GUESS` for scratch.
+unsafe fn sizes_of(
+    this: *mut c_void,
+    inputs: &BuildInputs,
+    stream: &StreamDesc,
+    geoms: &[GeometryDesc],
+) -> PrebuildInfo {
+    let real = REAL_PREBUILD_INFO.load(Ordering::Acquire);
+    if real != 0 {
+        let f: PrebuildInfoFn = std::mem::transmute(real);
+        let mut info = PrebuildInfo::default();
+        let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc };
+        f(this, inputs, s, &mut info);
+        if info.result_data_max_size_in_bytes != 0 {
+            return info;
+        }
+    }
+    PrebuildInfo {
+        result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms)
+            .max(crate::gpu::bvh::HEADER_BYTES as u64),
+        scratch_data_size_in_bytes: SCRATCH_GUESS,
+        update_scratch_data_size_in_bytes: SCRATCH_GUESS,
+    }
+}
+
+/// The vertex, index, transform and AABB ranges of `geoms`.
+fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) {
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes());
+            if t.index_buffer != 0 {
+                push_range(out, Use::Indices, t.index_buffer, t.index_bytes());
+            }
+            push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES);
+        } else if let Some(a) = g.as_aabbs() {
+            // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum.
+            push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24)));
+        }
+    }
+}
+
+/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size
+/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses
+/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to
+/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`.
+fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 {
+    if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 {
+        let source = if b.source != 0 { b.source } else { b.dest };
+        let cached = cache.get(&source).copied().filter(|&n| n != 0);
+        let scratch = if sizes.update_scratch_data_size_in_bytes != 0 {
+            cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| {
+                c.max(sizes.update_scratch_data_size_in_bytes)
+            })
+        } else if let Some(c) = cached {
+            c
+        } else {
+            sizes
+                .scratch_data_size_in_bytes
+                .max(sizes.update_scratch_data_size_in_bytes)
+                .max(SCRATCH_GUESS)
+        };
+        if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) {
+            cache.insert(b.dest, scratch);
+        }
+        scratch
+    } else {
+        if b.dest != 0 {
+            if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 {
+                cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes);
+            } else {
+                cache.remove(&b.dest);
+            }
+        }
+        sizes.scratch_data_size_in_bytes
+    }
+}
+
+/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a
+/// rehydrate starts from when that is not the result itself, scratch (an update's when it is
+/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and
+/// the instance descriptions (top level: an array, or an array of their addresses plus each
+/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of
+/// its inputs (bottom level).
+unsafe fn ranges_of_build(
+    b: &BuildDesc,
+    geoms: &[GeometryDesc],
+    sizes: &PrebuildInfo,
+    update_scratch_cache: &mut HashMap<u64, u64>,
+    cpu_at: impl Fn(u64) -> u64,
+    out: &mut Vec<Range>,
+) {
+    let inp = &b.inputs;
+    let result = sizes.result_data_max_size_in_bytes;
+    push_range(out, Use::Dest, b.dest, result);
+    if b.source != b.dest {
+        push_range(out, Use::Source, b.source, result);
+    }
+    let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache);
+    push_range(out, Use::Scratch, b.scratch, scratch_bytes);
+    if inp.ty == AS_TYPE_TOP_LEVEL {
+        if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS {
+            let n = inp.num_descs as usize;
+            push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8));
+            if n > 0 && inp.descs != 0 {
+                if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) {
+                    let cpu = cpu_at(inp.descs);
+                    if cpu != 0 && crate::gpu::shader::readable(cpu as usize, bytes) {
+                        let ptrs = cpu as *const u64;
+                        let mut targets: Vec<u64> = Vec::with_capacity(n.min(1024));
+                        for i in 0..n {
+                            let target = ptrs.add(i).read_unaligned();

Critical: The CPU view of the top-level pointer array is read with raw read_unaligned after a shader::readable check, a check-then-use race on title memory that can be decommitted concurrently. bvh_want::read_title uses view_want::cpu_run plus dstorage::read_own (a kernel copy that can't fault) for exactly this. If the title's streaming thread decommits or releases the page holding the instance pointer table between readable() and the loop, the hook takes an access violation inside an extern "system-unwind" function on the title's render thread and the process crashes. Reading through read_own would make it safe.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775155811 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#discussion_r4775155811). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:55:58Z. **Code review location:** `crates/xcl/src/hle/bvh_builder.rs`; line 492 ~~~~diff @@ -0,0 +1,1126 @@ +//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests. +//! +//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++ +//! batched build and rehydrate methods on static/delay import resolution and dynamic +//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to +//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`). +//! +//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers +//! through addresses inside geometry descriptions they upload themselves, and the destination, +//! source and scratch through root views, which `view_want` asks for 64 KiB from their address +//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and +//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels +//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for +//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own +//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when +//! the unified memory has view windows, so nothing changes on the default 4-window layout. + +#![allow(non_snake_case)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, Once}; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`. +pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; +pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; + +/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`. +pub const INSTANCE_DESC_BYTES: u64 = 64; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values. +pub const AS_TYPE_TOP_LEVEL: u32 = 0; +pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1; + +/// `D3D12_ELEMENTS_LAYOUT` values. +pub const LAYOUT_ARRAY: u32 = 0; +pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`. +pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1; +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`. +pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20; + +/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values. +pub const GEOM_TYPE_TRIANGLES: u32 = 0; +pub const GEOM_TYPE_AABBS: u32 = 1; + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildInputs { + pub ty: u32, // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL + pub flags: u32, // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS + pub num_descs: u32, // +0x08: instance count (TLAS) or geometry count (BLAS) + pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS + pub descs: u64, // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS) +} + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildDesc { + pub dest: u64, // +0x00: DestAccelerationStructureData GPU VA + pub inputs: BuildInputs, // +0x08..+0x20 + pub source: u64, // +0x20: SourceAccelerationStructureData GPU VA + pub scratch: u64, // +0x28: ScratchAccelerationStructureData GPU VA +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PostbuildInfoDesc { + pub dest_buffer: u64, // +0x00 + pub info_type: u32, // +0x08 + pub _pad: u32, // +0x0C +} + +/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StreamDesc { + pub size_in_bytes: u64, // +0x00 + pub p_stream: u64, // +0x08 +} + +/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`). +/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BatchedBuildDesc2 { + pub build: BuildDesc, // +0x00..+0x30 + pub num_postbuild_info_descs: u32, // +0x30 + pub _pad: u32, // +0x34 + pub p_postbuild_info_descs: u64, // +0x38 + pub stream: StreamDesc, // +0x40..+0x50 +} + +/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GeometryDesc { + pub ty: u32, // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs + pub flags: u32, // +0x04 + pub payload: [u64; 6], // +0x08..+0x38 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TriangleGeometry { + pub transform3x4: u64, + pub index_format: u32, + pub vertex_format: u32, + pub index_count: u32, + pub vertex_count: u32, + pub index_buffer: u64, + pub vertex_buffer: u64, + pub vertex_stride: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AabbGeometry { + pub count: u64, + pub start_address: u64, + pub stride: u64, +} + +impl GeometryDesc { + pub fn as_triangles(&self) -> Option<TriangleGeometry> { + if self.ty != GEOM_TYPE_TRIANGLES { + return None; + } + Some(TriangleGeometry { + transform3x4: self.payload[0], + index_format: self.payload[1] as u32, + vertex_format: (self.payload[1] >> 32) as u32, + index_count: self.payload[2] as u32, + vertex_count: (self.payload[2] >> 32) as u32, + index_buffer: self.payload[3], + vertex_buffer: self.payload[4], + vertex_stride: self.payload[5], + }) + } + + pub fn as_aabbs(&self) -> Option<AabbGeometry> { + if self.ty != GEOM_TYPE_AABBS { + return None; + } + Some(AabbGeometry { + count: self.payload[0], + start_address: self.payload[1], + stride: self.payload[2], + }) + } +} + +impl TriangleGeometry { + pub fn index_elem_bytes(&self) -> u64 { + match self.index_format { + 0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer + // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS) + 53..=59 => 2, + // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element + _ => 4, + } + } + + pub fn triangle_count(&self) -> u64 { + if self.index_count > 0 { + u64::from(self.index_count) / 3 + } else { + u64::from(self.vertex_count) / 3 + } + } + + pub fn vertex_bytes(&self) -> u64 { + u64::from(self.vertex_count).saturating_mul(self.vertex_stride) + } + + pub fn index_bytes(&self) -> u64 { + u64::from(self.index_count).saturating_mul(self.index_elem_bytes()) + } +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrebuildInfo { + pub result_data_max_size_in_bytes: u64, // +0x00 + pub scratch_data_size_in_bytes: u64, // +0x08 + pub update_scratch_data_size_in_bytes: u64, // +0x10 +} + +/// True for lowercase DLL key `"xboxbvhbuilder.dll"`. +pub fn is_bvh_builder_dll(key: &str) -> bool { + key == "xboxbvhbuilder.dll" +} + +static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0); +/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build, +/// used when a later `PERFORM_UPDATE` prebuild query returns 0. +static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles +/// get video memory only when asked for: the 16-window layout). +fn view_windows() -> bool { + crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k))) +} + +/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped +/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it. +fn record_prebuild_from_module(module: &MappedModule) { + if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) { + REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release); + } +} + +/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for) +/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture +/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the +/// passthrough hook address; otherwise return `real_addr`. +pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 || !view_windows() { + return real_addr; + } + static WHY: Once = Once::new(); + WHY.call_once(|| { + crate::xlog_info!( + "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)" + ); + }); + wrap_with_module(module, what, real_addr) +} + +fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + if let Some(m) = module { + record_prebuild_from_module(m); + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.and_then(|m| { + m.exports.by_name.iter().find_map(|(n, t)| { + matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str()) + }) + }), + }; + match name { + Some(n) => wrap_with(n, real_addr), + None => real_addr, + } +} + +fn wrap_with(function: &str, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + match function { + SYM_BUILD_BATCHED2X => { + REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release); + BuildBatched2X_hook as usize + } + SYM_REHYDRATE_BATCHED2X => { + REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release); + RehydrateBatched2X_hook as usize + } + SYM_PREBUILD_INFO => { + // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on + // title calls. + REAL_PREBUILD_INFO.store(real_addr, Ordering::Release); + real_addr + } + _ => real_addr, + } +} + +/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays +/// and pointer-arrays safely via `shader::readable`. +pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> { + let n = inputs.num_descs as usize; + if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 { + return Vec::new(); + } + let mut out = Vec::with_capacity(n.min(1024)); + match inputs.descs_layout { + LAYOUT_ARRAY => { + let elem = std::mem::size_of::<GeometryDesc>(); + let Some(bytes) = n.checked_mul(elem) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, bytes) { + return out; + } + let base = inputs.descs as *const GeometryDesc; + for i in 0..n { + out.push(base.add(i).read_unaligned()); + } + } + LAYOUT_ARRAY_OF_POINTERS => { + let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) { + return out; + } + let ptrs = inputs.descs as *const u64; + let elem = std::mem::size_of::<GeometryDesc>(); + for i in 0..n { + let p = ptrs.add(i).read_unaligned(); + if p != 0 && crate::gpu::shader::readable(p as usize, elem) { + out.push((p as *const GeometryDesc).read_unaligned()); + } + } + } + _ => {} + } + out +} + +fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 { + if inputs.ty == AS_TYPE_TOP_LEVEL { + return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true); + } + let mut leaves = 0u64; + for g in geoms { + if let Some(t) = g.as_triangles() { + leaves = leaves.saturating_add(t.triangle_count()); + } else if let Some(a) = g.as_aabbs() { + leaves = leaves.saturating_add(a.count); + } + } + if leaves > 0 { + crate::gpu::bvh::prebuild_size(leaves, false) + } else { + 0 + } +} + +/// What a range a build or rehydrate names is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Use { + Dest, + Source, + Scratch, + Instances, + Vertices, + Indices, + Transform, + Aabbs, + Postbuild, +} + +/// A GPU range the builder's programs read or write for one batch item. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Range { + pub what: Use, + pub va: u64, + pub len: u64, +} + +/// bytes of a geometry's 3x4 float transform +const TRANSFORM_BYTES: u64 = 48; +/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16) +const POSTBUILD_BYTES: u64 = 16; +/// postbuild-info descriptions read of one batch item at most +const MAX_POSTBUILD: usize = 64; +/// scratch asked for when the DLL's prebuild answer is not at hand +const SCRATCH_GUESS: u64 = 0x1_0000; + +fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) { + if va != 0 && len != 0 { + out.push(Range { what, va, len }); + } +} + +/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU +/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the +/// leaves counted for the result and `SCRATCH_GUESS` for scratch. +unsafe fn sizes_of( + this: *mut c_void, + inputs: &BuildInputs, + stream: &StreamDesc, + geoms: &[GeometryDesc], +) -> PrebuildInfo { + let real = REAL_PREBUILD_INFO.load(Ordering::Acquire); + if real != 0 { + let f: PrebuildInfoFn = std::mem::transmute(real); + let mut info = PrebuildInfo::default(); + let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc }; + f(this, inputs, s, &mut info); + if info.result_data_max_size_in_bytes != 0 { + return info; + } + } + PrebuildInfo { + result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms) + .max(crate::gpu::bvh::HEADER_BYTES as u64), + scratch_data_size_in_bytes: SCRATCH_GUESS, + update_scratch_data_size_in_bytes: SCRATCH_GUESS, + } +} + +/// The vertex, index, transform and AABB ranges of `geoms`. +fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) { + for g in geoms { + if let Some(t) = g.as_triangles() { + push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes()); + if t.index_buffer != 0 { + push_range(out, Use::Indices, t.index_buffer, t.index_bytes()); + } + push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES); + } else if let Some(a) = g.as_aabbs() { + // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum. + push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24))); + } + } +} + +/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size +/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses +/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to +/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`. +fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 { + if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 { + let source = if b.source != 0 { b.source } else { b.dest }; + let cached = cache.get(&source).copied().filter(|&n| n != 0); + let scratch = if sizes.update_scratch_data_size_in_bytes != 0 { + cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| { + c.max(sizes.update_scratch_data_size_in_bytes) + }) + } else if let Some(c) = cached { + c + } else { + sizes + .scratch_data_size_in_bytes + .max(sizes.update_scratch_data_size_in_bytes) + .max(SCRATCH_GUESS) + }; + if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) { + cache.insert(b.dest, scratch); + } + scratch + } else { + if b.dest != 0 { + if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 { + cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes); + } else { + cache.remove(&b.dest); + } + } + sizes.scratch_data_size_in_bytes + } +} + +/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a +/// rehydrate starts from when that is not the result itself, scratch (an update's when it is +/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and +/// the instance descriptions (top level: an array, or an array of their addresses plus each +/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of +/// its inputs (bottom level). +unsafe fn ranges_of_build( + b: &BuildDesc, + geoms: &[GeometryDesc], + sizes: &PrebuildInfo, + update_scratch_cache: &mut HashMap<u64, u64>, + cpu_at: impl Fn(u64) -> u64, + out: &mut Vec<Range>, +) { + let inp = &b.inputs; + let result = sizes.result_data_max_size_in_bytes; + push_range(out, Use::Dest, b.dest, result); + if b.source != b.dest { + push_range(out, Use::Source, b.source, result); + } + let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache); + push_range(out, Use::Scratch, b.scratch, scratch_bytes); + if inp.ty == AS_TYPE_TOP_LEVEL { + if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS { + let n = inp.num_descs as usize; + push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8)); + if n > 0 && inp.descs != 0 { + if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) { + let cpu = cpu_at(inp.descs); + if cpu != 0 && crate::gpu::shader::readable(cpu as usize, bytes) { + let ptrs = cpu as *const u64; + let mut targets: Vec<u64> = Vec::with_capacity(n.min(1024)); + for i in 0..n { + let target = ptrs.add(i).read_unaligned(); ~~~~ --- **Critical**: The CPU view of the top-level pointer array is read with raw `read_unaligned` after a `shader::readable` check, a check-then-use race on title memory that can be decommitted concurrently. `bvh_want::read_title` uses `view_want::cpu_run` plus `dstorage::read_own` (a kernel copy that can't fault) for exactly this. If the title's streaming thread decommits or releases the page holding the instance pointer table between `readable()` and the loop, the hook takes an access violation inside an `extern "system-unwind"` function on the title's render thread and the process crashes. Reading through `read_own` would make it safe.
bmjask commented 2026-12-02 19:55:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:55:58Z.

Code review location: crates/xcl/src/hle/bvh_builder.rs; line 487

@@ -0,0 +1,1126 @@
+//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests.
+//!
+//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++
+//! batched build and rehydrate methods on static/delay import resolution and dynamic
+//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to
+//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`).
+//!
+//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers
+//! through addresses inside geometry descriptions they upload themselves, and the destination,
+//! source and scratch through root views, which `view_want` asks for 64 KiB from their address
+//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and
+//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels
+//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for
+//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own
+//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when
+//! the unified memory has view windows, so nothing changes on the default 4-window layout.
+
+#![allow(non_snake_case)]
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Mutex, Once};
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`.
+pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z";
+pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+
+/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`.
+pub const INSTANCE_DESC_BYTES: u64 = 64;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values.
+pub const AS_TYPE_TOP_LEVEL: u32 = 0;
+pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1;
+
+/// `D3D12_ELEMENTS_LAYOUT` values.
+pub const LAYOUT_ARRAY: u32 = 0;
+pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`.
+pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1;
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`.
+pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20;
+
+/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values.
+pub const GEOM_TYPE_TRIANGLES: u32 = 0;
+pub const GEOM_TYPE_AABBS: u32 = 1;
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildInputs {
+    pub ty: u32,           // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL
+    pub flags: u32,        // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS
+    pub num_descs: u32,    // +0x08: instance count (TLAS) or geometry count (BLAS)
+    pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS
+    pub descs: u64,        // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS)
+}
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildDesc {
+    pub dest: u64,           // +0x00: DestAccelerationStructureData GPU VA
+    pub inputs: BuildInputs, // +0x08..+0x20
+    pub source: u64,         // +0x20: SourceAccelerationStructureData GPU VA
+    pub scratch: u64,        // +0x28: ScratchAccelerationStructureData GPU VA
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PostbuildInfoDesc {
+    pub dest_buffer: u64, // +0x00
+    pub info_type: u32,   // +0x08
+    pub _pad: u32,        // +0x0C
+}
+
+/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct StreamDesc {
+    pub size_in_bytes: u64, // +0x00
+    pub p_stream: u64,      // +0x08
+}
+
+/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`).
+/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BatchedBuildDesc2 {
+    pub build: BuildDesc,              // +0x00..+0x30
+    pub num_postbuild_info_descs: u32, // +0x30
+    pub _pad: u32,                     // +0x34
+    pub p_postbuild_info_descs: u64,   // +0x38
+    pub stream: StreamDesc,            // +0x40..+0x50
+}
+
+/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct GeometryDesc {
+    pub ty: u32,           // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs
+    pub flags: u32,        // +0x04
+    pub payload: [u64; 6], // +0x08..+0x38
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TriangleGeometry {
+    pub transform3x4: u64,
+    pub index_format: u32,
+    pub vertex_format: u32,
+    pub index_count: u32,
+    pub vertex_count: u32,
+    pub index_buffer: u64,
+    pub vertex_buffer: u64,
+    pub vertex_stride: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AabbGeometry {
+    pub count: u64,
+    pub start_address: u64,
+    pub stride: u64,
+}
+
+impl GeometryDesc {
+    pub fn as_triangles(&self) -> Option<TriangleGeometry> {
+        if self.ty != GEOM_TYPE_TRIANGLES {
+            return None;
+        }
+        Some(TriangleGeometry {
+            transform3x4: self.payload[0],
+            index_format: self.payload[1] as u32,
+            vertex_format: (self.payload[1] >> 32) as u32,
+            index_count: self.payload[2] as u32,
+            vertex_count: (self.payload[2] >> 32) as u32,
+            index_buffer: self.payload[3],
+            vertex_buffer: self.payload[4],
+            vertex_stride: self.payload[5],
+        })
+    }
+
+    pub fn as_aabbs(&self) -> Option<AabbGeometry> {
+        if self.ty != GEOM_TYPE_AABBS {
+            return None;
+        }
+        Some(AabbGeometry {
+            count: self.payload[0],
+            start_address: self.payload[1],
+            stride: self.payload[2],
+        })
+    }
+}
+
+impl TriangleGeometry {
+    pub fn index_elem_bytes(&self) -> u64 {
+        match self.index_format {
+            0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer
+            // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS)
+            53..=59 => 2,
+            // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element
+            _ => 4,
+        }
+    }
+
+    pub fn triangle_count(&self) -> u64 {
+        if self.index_count > 0 {
+            u64::from(self.index_count) / 3
+        } else {
+            u64::from(self.vertex_count) / 3
+        }
+    }
+
+    pub fn vertex_bytes(&self) -> u64 {
+        u64::from(self.vertex_count).saturating_mul(self.vertex_stride)
+    }
+
+    pub fn index_bytes(&self) -> u64 {
+        u64::from(self.index_count).saturating_mul(self.index_elem_bytes())
+    }
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PrebuildInfo {
+    pub result_data_max_size_in_bytes: u64,     // +0x00
+    pub scratch_data_size_in_bytes: u64,        // +0x08
+    pub update_scratch_data_size_in_bytes: u64, // +0x10
+}
+
+/// True for lowercase DLL key `"xboxbvhbuilder.dll"`.
+pub fn is_bvh_builder_dll(key: &str) -> bool {
+    key == "xboxbvhbuilder.dll"
+}
+
+static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0);
+/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build,
+/// used when a later `PERFORM_UPDATE` prebuild query returns 0.
+static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles
+/// get video memory only when asked for: the 16-window layout).
+fn view_windows() -> bool {
+    crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k)))
+}
+
+/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped
+/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it.
+fn record_prebuild_from_module(module: &MappedModule) {
+    if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) {
+        REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release);
+    }
+}
+
+/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for)
+/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture
+/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the
+/// passthrough hook address; otherwise return `real_addr`.
+pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 || !view_windows() {
+        return real_addr;
+    }
+    static WHY: Once = Once::new();
+    WHY.call_once(|| {
+        crate::xlog_info!(
+            "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)"
+        );
+    });
+    wrap_with_module(module, what, real_addr)
+}
+
+fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    if let Some(m) = module {
+        record_prebuild_from_module(m);
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.and_then(|m| {
+            m.exports.by_name.iter().find_map(|(n, t)| {
+                matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str())
+            })
+        }),
+    };
+    match name {
+        Some(n) => wrap_with(n, real_addr),
+        None => real_addr,
+    }
+}
+
+fn wrap_with(function: &str, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    match function {
+        SYM_BUILD_BATCHED2X => {
+            REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release);
+            BuildBatched2X_hook as usize
+        }
+        SYM_REHYDRATE_BATCHED2X => {
+            REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release);
+            RehydrateBatched2X_hook as usize
+        }
+        SYM_PREBUILD_INFO => {
+            // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on
+            // title calls.
+            REAL_PREBUILD_INFO.store(real_addr, Ordering::Release);
+            real_addr
+        }
+        _ => real_addr,
+    }
+}
+
+/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays
+/// and pointer-arrays safely via `shader::readable`.
+pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> {
+    let n = inputs.num_descs as usize;
+    if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 {
+        return Vec::new();
+    }
+    let mut out = Vec::with_capacity(n.min(1024));
+    match inputs.descs_layout {
+        LAYOUT_ARRAY => {
+            let elem = std::mem::size_of::<GeometryDesc>();
+            let Some(bytes) = n.checked_mul(elem) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, bytes) {
+                return out;
+            }
+            let base = inputs.descs as *const GeometryDesc;
+            for i in 0..n {
+                out.push(base.add(i).read_unaligned());
+            }
+        }
+        LAYOUT_ARRAY_OF_POINTERS => {
+            let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) {
+                return out;
+            }
+            let ptrs = inputs.descs as *const u64;
+            let elem = std::mem::size_of::<GeometryDesc>();
+            for i in 0..n {
+                let p = ptrs.add(i).read_unaligned();
+                if p != 0 && crate::gpu::shader::readable(p as usize, elem) {
+                    out.push((p as *const GeometryDesc).read_unaligned());
+                }
+            }
+        }
+        _ => {}
+    }
+    out
+}
+
+fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 {
+    if inputs.ty == AS_TYPE_TOP_LEVEL {
+        return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true);
+    }
+    let mut leaves = 0u64;
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            leaves = leaves.saturating_add(t.triangle_count());
+        } else if let Some(a) = g.as_aabbs() {
+            leaves = leaves.saturating_add(a.count);
+        }
+    }
+    if leaves > 0 {
+        crate::gpu::bvh::prebuild_size(leaves, false)
+    } else {
+        0
+    }
+}
+
+/// What a range a build or rehydrate names is for.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Use {
+    Dest,
+    Source,
+    Scratch,
+    Instances,
+    Vertices,
+    Indices,
+    Transform,
+    Aabbs,
+    Postbuild,
+}
+
+/// A GPU range the builder's programs read or write for one batch item.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Range {
+    pub what: Use,
+    pub va: u64,
+    pub len: u64,
+}
+
+/// bytes of a geometry's 3x4 float transform
+const TRANSFORM_BYTES: u64 = 48;
+/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16)
+const POSTBUILD_BYTES: u64 = 16;
+/// postbuild-info descriptions read of one batch item at most
+const MAX_POSTBUILD: usize = 64;
+/// scratch asked for when the DLL's prebuild answer is not at hand
+const SCRATCH_GUESS: u64 = 0x1_0000;
+
+fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) {
+    if va != 0 && len != 0 {
+        out.push(Range { what, va, len });
+    }
+}
+
+/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU
+/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the
+/// leaves counted for the result and `SCRATCH_GUESS` for scratch.
+unsafe fn sizes_of(
+    this: *mut c_void,
+    inputs: &BuildInputs,
+    stream: &StreamDesc,
+    geoms: &[GeometryDesc],
+) -> PrebuildInfo {
+    let real = REAL_PREBUILD_INFO.load(Ordering::Acquire);
+    if real != 0 {
+        let f: PrebuildInfoFn = std::mem::transmute(real);
+        let mut info = PrebuildInfo::default();
+        let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc };
+        f(this, inputs, s, &mut info);
+        if info.result_data_max_size_in_bytes != 0 {
+            return info;
+        }
+    }
+    PrebuildInfo {
+        result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms)
+            .max(crate::gpu::bvh::HEADER_BYTES as u64),
+        scratch_data_size_in_bytes: SCRATCH_GUESS,
+        update_scratch_data_size_in_bytes: SCRATCH_GUESS,
+    }
+}
+
+/// The vertex, index, transform and AABB ranges of `geoms`.
+fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) {
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes());
+            if t.index_buffer != 0 {
+                push_range(out, Use::Indices, t.index_buffer, t.index_bytes());
+            }
+            push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES);
+        } else if let Some(a) = g.as_aabbs() {
+            // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum.
+            push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24)));
+        }
+    }
+}
+
+/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size
+/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses
+/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to
+/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`.
+fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 {
+    if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 {
+        let source = if b.source != 0 { b.source } else { b.dest };
+        let cached = cache.get(&source).copied().filter(|&n| n != 0);
+        let scratch = if sizes.update_scratch_data_size_in_bytes != 0 {
+            cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| {
+                c.max(sizes.update_scratch_data_size_in_bytes)
+            })
+        } else if let Some(c) = cached {
+            c
+        } else {
+            sizes
+                .scratch_data_size_in_bytes
+                .max(sizes.update_scratch_data_size_in_bytes)
+                .max(SCRATCH_GUESS)
+        };
+        if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) {
+            cache.insert(b.dest, scratch);
+        }
+        scratch
+    } else {
+        if b.dest != 0 {
+            if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 {
+                cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes);
+            } else {
+                cache.remove(&b.dest);
+            }
+        }
+        sizes.scratch_data_size_in_bytes
+    }
+}
+
+/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a
+/// rehydrate starts from when that is not the result itself, scratch (an update's when it is
+/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and
+/// the instance descriptions (top level: an array, or an array of their addresses plus each
+/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of
+/// its inputs (bottom level).
+unsafe fn ranges_of_build(
+    b: &BuildDesc,
+    geoms: &[GeometryDesc],
+    sizes: &PrebuildInfo,
+    update_scratch_cache: &mut HashMap<u64, u64>,
+    cpu_at: impl Fn(u64) -> u64,
+    out: &mut Vec<Range>,
+) {
+    let inp = &b.inputs;
+    let result = sizes.result_data_max_size_in_bytes;
+    push_range(out, Use::Dest, b.dest, result);
+    if b.source != b.dest {
+        push_range(out, Use::Source, b.source, result);
+    }
+    let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache);
+    push_range(out, Use::Scratch, b.scratch, scratch_bytes);
+    if inp.ty == AS_TYPE_TOP_LEVEL {
+        if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS {
+            let n = inp.num_descs as usize;
+            push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8));
+            if n > 0 && inp.descs != 0 {
+                if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) {
+                    let cpu = cpu_at(inp.descs);

High: The ARRAY_OF_POINTERS pointer array is translated with cpu_at(inp.descs) (base address only) and then read as one contiguous n*8-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow the first, which view_want::cpu_run exists to detect. For a top-level build with ~3000 instances whose 24 KB pointer array starts 8 KB before a tile boundary, with tiles mapped apart (queue page mappings or kernelx mirrors), the entries past the boundary are read from whatever follows the first CPU page. The wrong instance-desc ranges are asked for and the real ones are never mapped, so the builder reads zeros and those instances drop out of the top level. Translating per tile (or using cpu_run) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775155824 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#discussion_r4775155824). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:55:58Z. **Code review location:** `crates/xcl/src/hle/bvh_builder.rs`; line 487 ~~~~diff @@ -0,0 +1,1126 @@ +//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests. +//! +//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++ +//! batched build and rehydrate methods on static/delay import resolution and dynamic +//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to +//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`). +//! +//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers +//! through addresses inside geometry descriptions they upload themselves, and the destination, +//! source and scratch through root views, which `view_want` asks for 64 KiB from their address +//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and +//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels +//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for +//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own +//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when +//! the unified memory has view windows, so nothing changes on the default 4-window layout. + +#![allow(non_snake_case)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, Once}; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`. +pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; +pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; + +/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`. +pub const INSTANCE_DESC_BYTES: u64 = 64; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values. +pub const AS_TYPE_TOP_LEVEL: u32 = 0; +pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1; + +/// `D3D12_ELEMENTS_LAYOUT` values. +pub const LAYOUT_ARRAY: u32 = 0; +pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`. +pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1; +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`. +pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20; + +/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values. +pub const GEOM_TYPE_TRIANGLES: u32 = 0; +pub const GEOM_TYPE_AABBS: u32 = 1; + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildInputs { + pub ty: u32, // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL + pub flags: u32, // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS + pub num_descs: u32, // +0x08: instance count (TLAS) or geometry count (BLAS) + pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS + pub descs: u64, // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS) +} + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildDesc { + pub dest: u64, // +0x00: DestAccelerationStructureData GPU VA + pub inputs: BuildInputs, // +0x08..+0x20 + pub source: u64, // +0x20: SourceAccelerationStructureData GPU VA + pub scratch: u64, // +0x28: ScratchAccelerationStructureData GPU VA +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PostbuildInfoDesc { + pub dest_buffer: u64, // +0x00 + pub info_type: u32, // +0x08 + pub _pad: u32, // +0x0C +} + +/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StreamDesc { + pub size_in_bytes: u64, // +0x00 + pub p_stream: u64, // +0x08 +} + +/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`). +/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BatchedBuildDesc2 { + pub build: BuildDesc, // +0x00..+0x30 + pub num_postbuild_info_descs: u32, // +0x30 + pub _pad: u32, // +0x34 + pub p_postbuild_info_descs: u64, // +0x38 + pub stream: StreamDesc, // +0x40..+0x50 +} + +/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GeometryDesc { + pub ty: u32, // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs + pub flags: u32, // +0x04 + pub payload: [u64; 6], // +0x08..+0x38 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TriangleGeometry { + pub transform3x4: u64, + pub index_format: u32, + pub vertex_format: u32, + pub index_count: u32, + pub vertex_count: u32, + pub index_buffer: u64, + pub vertex_buffer: u64, + pub vertex_stride: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AabbGeometry { + pub count: u64, + pub start_address: u64, + pub stride: u64, +} + +impl GeometryDesc { + pub fn as_triangles(&self) -> Option<TriangleGeometry> { + if self.ty != GEOM_TYPE_TRIANGLES { + return None; + } + Some(TriangleGeometry { + transform3x4: self.payload[0], + index_format: self.payload[1] as u32, + vertex_format: (self.payload[1] >> 32) as u32, + index_count: self.payload[2] as u32, + vertex_count: (self.payload[2] >> 32) as u32, + index_buffer: self.payload[3], + vertex_buffer: self.payload[4], + vertex_stride: self.payload[5], + }) + } + + pub fn as_aabbs(&self) -> Option<AabbGeometry> { + if self.ty != GEOM_TYPE_AABBS { + return None; + } + Some(AabbGeometry { + count: self.payload[0], + start_address: self.payload[1], + stride: self.payload[2], + }) + } +} + +impl TriangleGeometry { + pub fn index_elem_bytes(&self) -> u64 { + match self.index_format { + 0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer + // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS) + 53..=59 => 2, + // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element + _ => 4, + } + } + + pub fn triangle_count(&self) -> u64 { + if self.index_count > 0 { + u64::from(self.index_count) / 3 + } else { + u64::from(self.vertex_count) / 3 + } + } + + pub fn vertex_bytes(&self) -> u64 { + u64::from(self.vertex_count).saturating_mul(self.vertex_stride) + } + + pub fn index_bytes(&self) -> u64 { + u64::from(self.index_count).saturating_mul(self.index_elem_bytes()) + } +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrebuildInfo { + pub result_data_max_size_in_bytes: u64, // +0x00 + pub scratch_data_size_in_bytes: u64, // +0x08 + pub update_scratch_data_size_in_bytes: u64, // +0x10 +} + +/// True for lowercase DLL key `"xboxbvhbuilder.dll"`. +pub fn is_bvh_builder_dll(key: &str) -> bool { + key == "xboxbvhbuilder.dll" +} + +static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0); +/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build, +/// used when a later `PERFORM_UPDATE` prebuild query returns 0. +static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles +/// get video memory only when asked for: the 16-window layout). +fn view_windows() -> bool { + crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k))) +} + +/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped +/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it. +fn record_prebuild_from_module(module: &MappedModule) { + if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) { + REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release); + } +} + +/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for) +/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture +/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the +/// passthrough hook address; otherwise return `real_addr`. +pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 || !view_windows() { + return real_addr; + } + static WHY: Once = Once::new(); + WHY.call_once(|| { + crate::xlog_info!( + "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)" + ); + }); + wrap_with_module(module, what, real_addr) +} + +fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + if let Some(m) = module { + record_prebuild_from_module(m); + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.and_then(|m| { + m.exports.by_name.iter().find_map(|(n, t)| { + matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str()) + }) + }), + }; + match name { + Some(n) => wrap_with(n, real_addr), + None => real_addr, + } +} + +fn wrap_with(function: &str, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + match function { + SYM_BUILD_BATCHED2X => { + REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release); + BuildBatched2X_hook as usize + } + SYM_REHYDRATE_BATCHED2X => { + REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release); + RehydrateBatched2X_hook as usize + } + SYM_PREBUILD_INFO => { + // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on + // title calls. + REAL_PREBUILD_INFO.store(real_addr, Ordering::Release); + real_addr + } + _ => real_addr, + } +} + +/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays +/// and pointer-arrays safely via `shader::readable`. +pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> { + let n = inputs.num_descs as usize; + if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 { + return Vec::new(); + } + let mut out = Vec::with_capacity(n.min(1024)); + match inputs.descs_layout { + LAYOUT_ARRAY => { + let elem = std::mem::size_of::<GeometryDesc>(); + let Some(bytes) = n.checked_mul(elem) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, bytes) { + return out; + } + let base = inputs.descs as *const GeometryDesc; + for i in 0..n { + out.push(base.add(i).read_unaligned()); + } + } + LAYOUT_ARRAY_OF_POINTERS => { + let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) { + return out; + } + let ptrs = inputs.descs as *const u64; + let elem = std::mem::size_of::<GeometryDesc>(); + for i in 0..n { + let p = ptrs.add(i).read_unaligned(); + if p != 0 && crate::gpu::shader::readable(p as usize, elem) { + out.push((p as *const GeometryDesc).read_unaligned()); + } + } + } + _ => {} + } + out +} + +fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 { + if inputs.ty == AS_TYPE_TOP_LEVEL { + return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true); + } + let mut leaves = 0u64; + for g in geoms { + if let Some(t) = g.as_triangles() { + leaves = leaves.saturating_add(t.triangle_count()); + } else if let Some(a) = g.as_aabbs() { + leaves = leaves.saturating_add(a.count); + } + } + if leaves > 0 { + crate::gpu::bvh::prebuild_size(leaves, false) + } else { + 0 + } +} + +/// What a range a build or rehydrate names is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Use { + Dest, + Source, + Scratch, + Instances, + Vertices, + Indices, + Transform, + Aabbs, + Postbuild, +} + +/// A GPU range the builder's programs read or write for one batch item. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Range { + pub what: Use, + pub va: u64, + pub len: u64, +} + +/// bytes of a geometry's 3x4 float transform +const TRANSFORM_BYTES: u64 = 48; +/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16) +const POSTBUILD_BYTES: u64 = 16; +/// postbuild-info descriptions read of one batch item at most +const MAX_POSTBUILD: usize = 64; +/// scratch asked for when the DLL's prebuild answer is not at hand +const SCRATCH_GUESS: u64 = 0x1_0000; + +fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) { + if va != 0 && len != 0 { + out.push(Range { what, va, len }); + } +} + +/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU +/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the +/// leaves counted for the result and `SCRATCH_GUESS` for scratch. +unsafe fn sizes_of( + this: *mut c_void, + inputs: &BuildInputs, + stream: &StreamDesc, + geoms: &[GeometryDesc], +) -> PrebuildInfo { + let real = REAL_PREBUILD_INFO.load(Ordering::Acquire); + if real != 0 { + let f: PrebuildInfoFn = std::mem::transmute(real); + let mut info = PrebuildInfo::default(); + let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc }; + f(this, inputs, s, &mut info); + if info.result_data_max_size_in_bytes != 0 { + return info; + } + } + PrebuildInfo { + result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms) + .max(crate::gpu::bvh::HEADER_BYTES as u64), + scratch_data_size_in_bytes: SCRATCH_GUESS, + update_scratch_data_size_in_bytes: SCRATCH_GUESS, + } +} + +/// The vertex, index, transform and AABB ranges of `geoms`. +fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) { + for g in geoms { + if let Some(t) = g.as_triangles() { + push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes()); + if t.index_buffer != 0 { + push_range(out, Use::Indices, t.index_buffer, t.index_bytes()); + } + push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES); + } else if let Some(a) = g.as_aabbs() { + // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum. + push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24))); + } + } +} + +/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size +/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses +/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to +/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`. +fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 { + if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 { + let source = if b.source != 0 { b.source } else { b.dest }; + let cached = cache.get(&source).copied().filter(|&n| n != 0); + let scratch = if sizes.update_scratch_data_size_in_bytes != 0 { + cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| { + c.max(sizes.update_scratch_data_size_in_bytes) + }) + } else if let Some(c) = cached { + c + } else { + sizes + .scratch_data_size_in_bytes + .max(sizes.update_scratch_data_size_in_bytes) + .max(SCRATCH_GUESS) + }; + if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) { + cache.insert(b.dest, scratch); + } + scratch + } else { + if b.dest != 0 { + if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 { + cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes); + } else { + cache.remove(&b.dest); + } + } + sizes.scratch_data_size_in_bytes + } +} + +/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a +/// rehydrate starts from when that is not the result itself, scratch (an update's when it is +/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and +/// the instance descriptions (top level: an array, or an array of their addresses plus each +/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of +/// its inputs (bottom level). +unsafe fn ranges_of_build( + b: &BuildDesc, + geoms: &[GeometryDesc], + sizes: &PrebuildInfo, + update_scratch_cache: &mut HashMap<u64, u64>, + cpu_at: impl Fn(u64) -> u64, + out: &mut Vec<Range>, +) { + let inp = &b.inputs; + let result = sizes.result_data_max_size_in_bytes; + push_range(out, Use::Dest, b.dest, result); + if b.source != b.dest { + push_range(out, Use::Source, b.source, result); + } + let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache); + push_range(out, Use::Scratch, b.scratch, scratch_bytes); + if inp.ty == AS_TYPE_TOP_LEVEL { + if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS { + let n = inp.num_descs as usize; + push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8)); + if n > 0 && inp.descs != 0 { + if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) { + let cpu = cpu_at(inp.descs); ~~~~ --- **High**: The ARRAY_OF_POINTERS pointer array is translated with `cpu_at(inp.descs)` (base address only) and then read as one contiguous `n*8`-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow the first, which `view_want::cpu_run` exists to detect. For a top-level build with ~3000 instances whose 24 KB pointer array starts 8 KB before a tile boundary, with tiles mapped apart (queue page mappings or kernelx mirrors), the entries past the boundary are read from whatever follows the first CPU page. The wrong instance-desc ranges are asked for and the real ones are never mapped, so the builder reads zeros and those instances drop out of the top level. Translating per tile (or using `cpu_run`) would fix it.
bmjask commented 2026-12-02 19:55:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:55:58Z.

Code review location: crates/xcl/src/hle/bvh_builder.rs; line 208

@@ -0,0 +1,1126 @@
+//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests.
+//!
+//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++
+//! batched build and rehydrate methods on static/delay import resolution and dynamic
+//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to
+//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`).
+//!
+//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers
+//! through addresses inside geometry descriptions they upload themselves, and the destination,
+//! source and scratch through root views, which `view_want` asks for 64 KiB from their address
+//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and
+//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels
+//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for
+//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own
+//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when
+//! the unified memory has view windows, so nothing changes on the default 4-window layout.
+
+#![allow(non_snake_case)]
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Mutex, Once};
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`.
+pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z";
+pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+
+/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`.
+pub const INSTANCE_DESC_BYTES: u64 = 64;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values.
+pub const AS_TYPE_TOP_LEVEL: u32 = 0;
+pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1;
+
+/// `D3D12_ELEMENTS_LAYOUT` values.
+pub const LAYOUT_ARRAY: u32 = 0;
+pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`.
+pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1;
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`.
+pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20;
+
+/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values.
+pub const GEOM_TYPE_TRIANGLES: u32 = 0;
+pub const GEOM_TYPE_AABBS: u32 = 1;
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildInputs {
+    pub ty: u32,           // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL
+    pub flags: u32,        // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS
+    pub num_descs: u32,    // +0x08: instance count (TLAS) or geometry count (BLAS)
+    pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS
+    pub descs: u64,        // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS)
+}
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildDesc {
+    pub dest: u64,           // +0x00: DestAccelerationStructureData GPU VA
+    pub inputs: BuildInputs, // +0x08..+0x20
+    pub source: u64,         // +0x20: SourceAccelerationStructureData GPU VA
+    pub scratch: u64,        // +0x28: ScratchAccelerationStructureData GPU VA
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PostbuildInfoDesc {
+    pub dest_buffer: u64, // +0x00
+    pub info_type: u32,   // +0x08
+    pub _pad: u32,        // +0x0C
+}
+
+/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct StreamDesc {
+    pub size_in_bytes: u64, // +0x00
+    pub p_stream: u64,      // +0x08
+}
+
+/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`).
+/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BatchedBuildDesc2 {
+    pub build: BuildDesc,              // +0x00..+0x30
+    pub num_postbuild_info_descs: u32, // +0x30
+    pub _pad: u32,                     // +0x34
+    pub p_postbuild_info_descs: u64,   // +0x38
+    pub stream: StreamDesc,            // +0x40..+0x50
+}
+
+/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct GeometryDesc {
+    pub ty: u32,           // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs
+    pub flags: u32,        // +0x04
+    pub payload: [u64; 6], // +0x08..+0x38
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TriangleGeometry {
+    pub transform3x4: u64,
+    pub index_format: u32,
+    pub vertex_format: u32,
+    pub index_count: u32,
+    pub vertex_count: u32,
+    pub index_buffer: u64,
+    pub vertex_buffer: u64,
+    pub vertex_stride: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AabbGeometry {
+    pub count: u64,
+    pub start_address: u64,
+    pub stride: u64,
+}
+
+impl GeometryDesc {
+    pub fn as_triangles(&self) -> Option<TriangleGeometry> {
+        if self.ty != GEOM_TYPE_TRIANGLES {
+            return None;
+        }
+        Some(TriangleGeometry {
+            transform3x4: self.payload[0],
+            index_format: self.payload[1] as u32,
+            vertex_format: (self.payload[1] >> 32) as u32,
+            index_count: self.payload[2] as u32,
+            vertex_count: (self.payload[2] >> 32) as u32,
+            index_buffer: self.payload[3],
+            vertex_buffer: self.payload[4],
+            vertex_stride: self.payload[5],
+        })
+    }
+
+    pub fn as_aabbs(&self) -> Option<AabbGeometry> {
+        if self.ty != GEOM_TYPE_AABBS {
+            return None;
+        }
+        Some(AabbGeometry {
+            count: self.payload[0],
+            start_address: self.payload[1],
+            stride: self.payload[2],
+        })
+    }
+}
+
+impl TriangleGeometry {
+    pub fn index_elem_bytes(&self) -> u64 {
+        match self.index_format {
+            0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer
+            // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS)
+            53..=59 => 2,
+            // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element
+            _ => 4,
+        }
+    }
+
+    pub fn triangle_count(&self) -> u64 {
+        if self.index_count > 0 {
+            u64::from(self.index_count) / 3
+        } else {
+            u64::from(self.vertex_count) / 3
+        }
+    }
+
+    pub fn vertex_bytes(&self) -> u64 {
+        u64::from(self.vertex_count).saturating_mul(self.vertex_stride)
+    }
+
+    pub fn index_bytes(&self) -> u64 {
+        u64::from(self.index_count).saturating_mul(self.index_elem_bytes())
+    }
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PrebuildInfo {
+    pub result_data_max_size_in_bytes: u64,     // +0x00
+    pub scratch_data_size_in_bytes: u64,        // +0x08
+    pub update_scratch_data_size_in_bytes: u64, // +0x10
+}
+
+/// True for lowercase DLL key `"xboxbvhbuilder.dll"`.
+pub fn is_bvh_builder_dll(key: &str) -> bool {
+    key == "xboxbvhbuilder.dll"
+}
+
+static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0);
+/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build,
+/// used when a later `PERFORM_UPDATE` prebuild query returns 0.
+static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);

Medium: UPDATE_SCRATCH grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. Besides growing for the whole session (the PR's own log shows ~4000 builds every 2 s, and streaming titles use new VAs), when a dest VA is freed and reused for a different, larger ALLOW_UPDATE structure whose PERFORM_UPDATE prebuild returns 0, the stale smaller size is used and the update scratch past it is never asked for. Querying prebuild with flags & !BUILD_FLAG_PERFORM_UPDATE (the DXR-legal form) would give the size directly and remove the cache.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775155833 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#discussion_r4775155833). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:55:58Z. **Code review location:** `crates/xcl/src/hle/bvh_builder.rs`; line 208 ~~~~diff @@ -0,0 +1,1126 @@ +//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests. +//! +//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++ +//! batched build and rehydrate methods on static/delay import resolution and dynamic +//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to +//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`). +//! +//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers +//! through addresses inside geometry descriptions they upload themselves, and the destination, +//! source and scratch through root views, which `view_want` asks for 64 KiB from their address +//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and +//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels +//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for +//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own +//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when +//! the unified memory has view windows, so nothing changes on the default 4-window layout. + +#![allow(non_snake_case)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, Once}; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`. +pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; +pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; + +/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`. +pub const INSTANCE_DESC_BYTES: u64 = 64; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values. +pub const AS_TYPE_TOP_LEVEL: u32 = 0; +pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1; + +/// `D3D12_ELEMENTS_LAYOUT` values. +pub const LAYOUT_ARRAY: u32 = 0; +pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`. +pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1; +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`. +pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20; + +/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values. +pub const GEOM_TYPE_TRIANGLES: u32 = 0; +pub const GEOM_TYPE_AABBS: u32 = 1; + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildInputs { + pub ty: u32, // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL + pub flags: u32, // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS + pub num_descs: u32, // +0x08: instance count (TLAS) or geometry count (BLAS) + pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS + pub descs: u64, // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS) +} + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildDesc { + pub dest: u64, // +0x00: DestAccelerationStructureData GPU VA + pub inputs: BuildInputs, // +0x08..+0x20 + pub source: u64, // +0x20: SourceAccelerationStructureData GPU VA + pub scratch: u64, // +0x28: ScratchAccelerationStructureData GPU VA +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PostbuildInfoDesc { + pub dest_buffer: u64, // +0x00 + pub info_type: u32, // +0x08 + pub _pad: u32, // +0x0C +} + +/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StreamDesc { + pub size_in_bytes: u64, // +0x00 + pub p_stream: u64, // +0x08 +} + +/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`). +/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BatchedBuildDesc2 { + pub build: BuildDesc, // +0x00..+0x30 + pub num_postbuild_info_descs: u32, // +0x30 + pub _pad: u32, // +0x34 + pub p_postbuild_info_descs: u64, // +0x38 + pub stream: StreamDesc, // +0x40..+0x50 +} + +/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GeometryDesc { + pub ty: u32, // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs + pub flags: u32, // +0x04 + pub payload: [u64; 6], // +0x08..+0x38 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TriangleGeometry { + pub transform3x4: u64, + pub index_format: u32, + pub vertex_format: u32, + pub index_count: u32, + pub vertex_count: u32, + pub index_buffer: u64, + pub vertex_buffer: u64, + pub vertex_stride: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AabbGeometry { + pub count: u64, + pub start_address: u64, + pub stride: u64, +} + +impl GeometryDesc { + pub fn as_triangles(&self) -> Option<TriangleGeometry> { + if self.ty != GEOM_TYPE_TRIANGLES { + return None; + } + Some(TriangleGeometry { + transform3x4: self.payload[0], + index_format: self.payload[1] as u32, + vertex_format: (self.payload[1] >> 32) as u32, + index_count: self.payload[2] as u32, + vertex_count: (self.payload[2] >> 32) as u32, + index_buffer: self.payload[3], + vertex_buffer: self.payload[4], + vertex_stride: self.payload[5], + }) + } + + pub fn as_aabbs(&self) -> Option<AabbGeometry> { + if self.ty != GEOM_TYPE_AABBS { + return None; + } + Some(AabbGeometry { + count: self.payload[0], + start_address: self.payload[1], + stride: self.payload[2], + }) + } +} + +impl TriangleGeometry { + pub fn index_elem_bytes(&self) -> u64 { + match self.index_format { + 0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer + // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS) + 53..=59 => 2, + // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element + _ => 4, + } + } + + pub fn triangle_count(&self) -> u64 { + if self.index_count > 0 { + u64::from(self.index_count) / 3 + } else { + u64::from(self.vertex_count) / 3 + } + } + + pub fn vertex_bytes(&self) -> u64 { + u64::from(self.vertex_count).saturating_mul(self.vertex_stride) + } + + pub fn index_bytes(&self) -> u64 { + u64::from(self.index_count).saturating_mul(self.index_elem_bytes()) + } +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrebuildInfo { + pub result_data_max_size_in_bytes: u64, // +0x00 + pub scratch_data_size_in_bytes: u64, // +0x08 + pub update_scratch_data_size_in_bytes: u64, // +0x10 +} + +/// True for lowercase DLL key `"xboxbvhbuilder.dll"`. +pub fn is_bvh_builder_dll(key: &str) -> bool { + key == "xboxbvhbuilder.dll" +} + +static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0); +/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build, +/// used when a later `PERFORM_UPDATE` prebuild query returns 0. +static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); ~~~~ --- **Medium**: `UPDATE_SCRATCH` grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. Besides growing for the whole session (the PR's own log shows ~4000 builds every 2 s, and streaming titles use new VAs), when a dest VA is freed and reused for a different, larger ALLOW_UPDATE structure whose PERFORM_UPDATE prebuild returns 0, the stale smaller size is used and the update scratch past it is never asked for. Querying prebuild with `flags & !BUILD_FLAG_PERFORM_UPDATE` (the DXR-legal form) would give the size directly and remove the cache.
bmjask commented 2026-12-02 19:55:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:55:58Z.

Code review location: crates/xcl/src/hle/bvh_builder.rs; line 517

@@ -0,0 +1,1126 @@
+//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests.
+//!
+//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++
+//! batched build and rehydrate methods on static/delay import resolution and dynamic
+//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to
+//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`).
+//!
+//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers
+//! through addresses inside geometry descriptions they upload themselves, and the destination,
+//! source and scratch through root views, which `view_want` asks for 64 KiB from their address
+//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and
+//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels
+//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for
+//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own
+//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when
+//! the unified memory has view windows, so nothing changes on the default 4-window layout.
+
+#![allow(non_snake_case)]
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Mutex, Once};
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`.
+pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z";
+pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+
+/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`.
+pub const INSTANCE_DESC_BYTES: u64 = 64;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values.
+pub const AS_TYPE_TOP_LEVEL: u32 = 0;
+pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1;
+
+/// `D3D12_ELEMENTS_LAYOUT` values.
+pub const LAYOUT_ARRAY: u32 = 0;
+pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1;
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`.
+pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1;
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`.
+pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20;
+
+/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values.
+pub const GEOM_TYPE_TRIANGLES: u32 = 0;
+pub const GEOM_TYPE_AABBS: u32 = 1;
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildInputs {
+    pub ty: u32,           // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL
+    pub flags: u32,        // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS
+    pub num_descs: u32,    // +0x08: instance count (TLAS) or geometry count (BLAS)
+    pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS
+    pub descs: u64,        // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS)
+}
+
+/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BuildDesc {
+    pub dest: u64,           // +0x00: DestAccelerationStructureData GPU VA
+    pub inputs: BuildInputs, // +0x08..+0x20
+    pub source: u64,         // +0x20: SourceAccelerationStructureData GPU VA
+    pub scratch: u64,        // +0x28: ScratchAccelerationStructureData GPU VA
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PostbuildInfoDesc {
+    pub dest_buffer: u64, // +0x00
+    pub info_type: u32,   // +0x08
+    pub _pad: u32,        // +0x0C
+}
+
+/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct StreamDesc {
+    pub size_in_bytes: u64, // +0x00
+    pub p_stream: u64,      // +0x08
+}
+
+/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`).
+/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BatchedBuildDesc2 {
+    pub build: BuildDesc,              // +0x00..+0x30
+    pub num_postbuild_info_descs: u32, // +0x30
+    pub _pad: u32,                     // +0x34
+    pub p_postbuild_info_descs: u64,   // +0x38
+    pub stream: StreamDesc,            // +0x40..+0x50
+}
+
+/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct GeometryDesc {
+    pub ty: u32,           // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs
+    pub flags: u32,        // +0x04
+    pub payload: [u64; 6], // +0x08..+0x38
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TriangleGeometry {
+    pub transform3x4: u64,
+    pub index_format: u32,
+    pub vertex_format: u32,
+    pub index_count: u32,
+    pub vertex_count: u32,
+    pub index_buffer: u64,
+    pub vertex_buffer: u64,
+    pub vertex_stride: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AabbGeometry {
+    pub count: u64,
+    pub start_address: u64,
+    pub stride: u64,
+}
+
+impl GeometryDesc {
+    pub fn as_triangles(&self) -> Option<TriangleGeometry> {
+        if self.ty != GEOM_TYPE_TRIANGLES {
+            return None;
+        }
+        Some(TriangleGeometry {
+            transform3x4: self.payload[0],
+            index_format: self.payload[1] as u32,
+            vertex_format: (self.payload[1] >> 32) as u32,
+            index_count: self.payload[2] as u32,
+            vertex_count: (self.payload[2] >> 32) as u32,
+            index_buffer: self.payload[3],
+            vertex_buffer: self.payload[4],
+            vertex_stride: self.payload[5],
+        })
+    }
+
+    pub fn as_aabbs(&self) -> Option<AabbGeometry> {
+        if self.ty != GEOM_TYPE_AABBS {
+            return None;
+        }
+        Some(AabbGeometry {
+            count: self.payload[0],
+            start_address: self.payload[1],
+            stride: self.payload[2],
+        })
+    }
+}
+
+impl TriangleGeometry {
+    pub fn index_elem_bytes(&self) -> u64 {
+        match self.index_format {
+            0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer
+            // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS)
+            53..=59 => 2,
+            // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element
+            _ => 4,
+        }
+    }
+
+    pub fn triangle_count(&self) -> u64 {
+        if self.index_count > 0 {
+            u64::from(self.index_count) / 3
+        } else {
+            u64::from(self.vertex_count) / 3
+        }
+    }
+
+    pub fn vertex_bytes(&self) -> u64 {
+        u64::from(self.vertex_count).saturating_mul(self.vertex_stride)
+    }
+
+    pub fn index_bytes(&self) -> u64 {
+        u64::from(self.index_count).saturating_mul(self.index_elem_bytes())
+    }
+}
+
+/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`).
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct PrebuildInfo {
+    pub result_data_max_size_in_bytes: u64,     // +0x00
+    pub scratch_data_size_in_bytes: u64,        // +0x08
+    pub update_scratch_data_size_in_bytes: u64, // +0x10
+}
+
+/// True for lowercase DLL key `"xboxbvhbuilder.dll"`.
+pub fn is_bvh_builder_dll(key: &str) -> bool {
+    key == "xboxbvhbuilder.dll"
+}
+
+static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0);
+static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0);
+/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build,
+/// used when a later `PERFORM_UPDATE` prebuild query returns 0.
+static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles
+/// get video memory only when asked for: the 16-window layout).
+fn view_windows() -> bool {
+    crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k)))
+}
+
+/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped
+/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it.
+fn record_prebuild_from_module(module: &MappedModule) {
+    if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) {
+        REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release);
+    }
+}
+
+/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for)
+/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture
+/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the
+/// passthrough hook address; otherwise return `real_addr`.
+pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 || !view_windows() {
+        return real_addr;
+    }
+    static WHY: Once = Once::new();
+    WHY.call_once(|| {
+        crate::xlog_info!(
+            "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)"
+        );
+    });
+    wrap_with_module(module, what, real_addr)
+}
+
+fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    if let Some(m) = module {
+        record_prebuild_from_module(m);
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.and_then(|m| {
+            m.exports.by_name.iter().find_map(|(n, t)| {
+                matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str())
+            })
+        }),
+    };
+    match name {
+        Some(n) => wrap_with(n, real_addr),
+        None => real_addr,
+    }
+}
+
+fn wrap_with(function: &str, real_addr: usize) -> usize {
+    if real_addr == 0 {
+        return real_addr;
+    }
+    match function {
+        SYM_BUILD_BATCHED2X => {
+            REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release);
+            BuildBatched2X_hook as usize
+        }
+        SYM_REHYDRATE_BATCHED2X => {
+            REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release);
+            RehydrateBatched2X_hook as usize
+        }
+        SYM_PREBUILD_INFO => {
+            // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on
+            // title calls.
+            REAL_PREBUILD_INFO.store(real_addr, Ordering::Release);
+            real_addr
+        }
+        _ => real_addr,
+    }
+}
+
+/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays
+/// and pointer-arrays safely via `shader::readable`.
+pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> {
+    let n = inputs.num_descs as usize;
+    if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 {
+        return Vec::new();
+    }
+    let mut out = Vec::with_capacity(n.min(1024));
+    match inputs.descs_layout {
+        LAYOUT_ARRAY => {
+            let elem = std::mem::size_of::<GeometryDesc>();
+            let Some(bytes) = n.checked_mul(elem) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, bytes) {
+                return out;
+            }
+            let base = inputs.descs as *const GeometryDesc;
+            for i in 0..n {
+                out.push(base.add(i).read_unaligned());
+            }
+        }
+        LAYOUT_ARRAY_OF_POINTERS => {
+            let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out };
+            if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) {
+                return out;
+            }
+            let ptrs = inputs.descs as *const u64;
+            let elem = std::mem::size_of::<GeometryDesc>();
+            for i in 0..n {
+                let p = ptrs.add(i).read_unaligned();
+                if p != 0 && crate::gpu::shader::readable(p as usize, elem) {
+                    out.push((p as *const GeometryDesc).read_unaligned());
+                }
+            }
+        }
+        _ => {}
+    }
+    out
+}
+
+fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 {
+    if inputs.ty == AS_TYPE_TOP_LEVEL {
+        return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true);
+    }
+    let mut leaves = 0u64;
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            leaves = leaves.saturating_add(t.triangle_count());
+        } else if let Some(a) = g.as_aabbs() {
+            leaves = leaves.saturating_add(a.count);
+        }
+    }
+    if leaves > 0 {
+        crate::gpu::bvh::prebuild_size(leaves, false)
+    } else {
+        0
+    }
+}
+
+/// What a range a build or rehydrate names is for.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Use {
+    Dest,
+    Source,
+    Scratch,
+    Instances,
+    Vertices,
+    Indices,
+    Transform,
+    Aabbs,
+    Postbuild,
+}
+
+/// A GPU range the builder's programs read or write for one batch item.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Range {
+    pub what: Use,
+    pub va: u64,
+    pub len: u64,
+}
+
+/// bytes of a geometry's 3x4 float transform
+const TRANSFORM_BYTES: u64 = 48;
+/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16)
+const POSTBUILD_BYTES: u64 = 16;
+/// postbuild-info descriptions read of one batch item at most
+const MAX_POSTBUILD: usize = 64;
+/// scratch asked for when the DLL's prebuild answer is not at hand
+const SCRATCH_GUESS: u64 = 0x1_0000;
+
+fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) {
+    if va != 0 && len != 0 {
+        out.push(Range { what, va, len });
+    }
+}
+
+/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU
+/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the
+/// leaves counted for the result and `SCRATCH_GUESS` for scratch.
+unsafe fn sizes_of(
+    this: *mut c_void,
+    inputs: &BuildInputs,
+    stream: &StreamDesc,
+    geoms: &[GeometryDesc],
+) -> PrebuildInfo {
+    let real = REAL_PREBUILD_INFO.load(Ordering::Acquire);
+    if real != 0 {
+        let f: PrebuildInfoFn = std::mem::transmute(real);
+        let mut info = PrebuildInfo::default();
+        let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc };
+        f(this, inputs, s, &mut info);
+        if info.result_data_max_size_in_bytes != 0 {
+            return info;
+        }
+    }
+    PrebuildInfo {
+        result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms)
+            .max(crate::gpu::bvh::HEADER_BYTES as u64),
+        scratch_data_size_in_bytes: SCRATCH_GUESS,
+        update_scratch_data_size_in_bytes: SCRATCH_GUESS,
+    }
+}
+
+/// The vertex, index, transform and AABB ranges of `geoms`.
+fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) {
+    for g in geoms {
+        if let Some(t) = g.as_triangles() {
+            push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes());
+            if t.index_buffer != 0 {
+                push_range(out, Use::Indices, t.index_buffer, t.index_bytes());
+            }
+            push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES);
+        } else if let Some(a) = g.as_aabbs() {
+            // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum.
+            push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24)));
+        }
+    }
+}
+
+/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size
+/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses
+/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to
+/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`.
+fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 {
+    if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 {
+        let source = if b.source != 0 { b.source } else { b.dest };
+        let cached = cache.get(&source).copied().filter(|&n| n != 0);
+        let scratch = if sizes.update_scratch_data_size_in_bytes != 0 {
+            cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| {
+                c.max(sizes.update_scratch_data_size_in_bytes)
+            })
+        } else if let Some(c) = cached {
+            c
+        } else {
+            sizes
+                .scratch_data_size_in_bytes
+                .max(sizes.update_scratch_data_size_in_bytes)
+                .max(SCRATCH_GUESS)
+        };
+        if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) {
+            cache.insert(b.dest, scratch);
+        }
+        scratch
+    } else {
+        if b.dest != 0 {
+            if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 {
+                cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes);
+            } else {
+                cache.remove(&b.dest);
+            }
+        }
+        sizes.scratch_data_size_in_bytes
+    }
+}
+
+/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a
+/// rehydrate starts from when that is not the result itself, scratch (an update's when it is
+/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and
+/// the instance descriptions (top level: an array, or an array of their addresses plus each
+/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of
+/// its inputs (bottom level).
+unsafe fn ranges_of_build(
+    b: &BuildDesc,
+    geoms: &[GeometryDesc],
+    sizes: &PrebuildInfo,
+    update_scratch_cache: &mut HashMap<u64, u64>,
+    cpu_at: impl Fn(u64) -> u64,
+    out: &mut Vec<Range>,
+) {
+    let inp = &b.inputs;
+    let result = sizes.result_data_max_size_in_bytes;
+    push_range(out, Use::Dest, b.dest, result);
+    if b.source != b.dest {
+        push_range(out, Use::Source, b.source, result);
+    }
+    let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache);
+    push_range(out, Use::Scratch, b.scratch, scratch_bytes);
+    if inp.ty == AS_TYPE_TOP_LEVEL {
+        if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS {
+            let n = inp.num_descs as usize;
+            push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8));
+            if n > 0 && inp.descs != 0 {
+                if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) {
+                    let cpu = cpu_at(inp.descs);
+                    if cpu != 0 && crate::gpu::shader::readable(cpu as usize, bytes) {
+                        let ptrs = cpu as *const u64;
+                        let mut targets: Vec<u64> = Vec::with_capacity(n.min(1024));
+                        for i in 0..n {
+                            let target = ptrs.add(i).read_unaligned();
+                            if target != 0 {
+                                targets.push(target);
+                            }
+                        }
+                        targets.sort_unstable();
+                        let mut cur: Option<(u64, u64)> = None;
+                        for va in targets {
+                            let end = va.saturating_add(INSTANCE_DESC_BYTES);
+                            match cur {
+                                Some((s, e)) if va <= e => cur = Some((s, e.max(end))),
+                                Some((s, e)) => {
+                                    push_range(out, Use::Instances, s, e.saturating_sub(s));
+                                    cur = Some((va, end));
+                                }
+                                None => cur = Some((va, end)),
+                            }
+                        }
+                        if let Some((s, e)) = cur {
+                            push_range(out, Use::Instances, s, e.saturating_sub(s));
+                        }
+                    }
+                }
+            }
+        } else {
+            push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(INSTANCE_DESC_BYTES));

Medium: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's AccelerationStructure field names. If a bottom level was built frames earlier and its view tiles have since been dropped or not asked again this generation, the top-level build reads zero bounds or headers for that instance, which ends up degenerate or missing. Asking for each referenced bottom level's range (at least its header) would cover it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775155842 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#discussion_r4775155842). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:55:58Z. **Code review location:** `crates/xcl/src/hle/bvh_builder.rs`; line 517 ~~~~diff @@ -0,0 +1,1126 @@ +//! Outer `XboxBvhBuilder.dll` HLE hooks for whole-range GPU-view requests. +//! +//! XCL still maps and runs the title's own `XboxBvhBuilder.dll`, wrapping its exported C++ +//! batched build and rehydrate methods on static/delay import resolution and dynamic +//! `GetProcAddress`, then forwarding every call cleanly to the original DLL function (or to +//! `d3d12x::bvh_builder`'s inner sparse-memory hook when `XCL_SPARSE_LAZY=1`). +//! +//! GPU views (`d3d12x::view_want`): the builder's compute programs reach vertex and index buffers +//! through addresses inside geometry descriptions they upload themselves, and the destination, +//! source and scratch through root views, which `view_want` asks for 64 KiB from their address +//! only. In a GPU view (view windows: the 16-window layout) every other tile reads zeros and +//! drops writes, leaving bottom levels built from zero vertices, rehydrated bottom levels +//! unwritten past their first 64 KiB, and scratch lost. Before forwarding, the hooks ask for +//! every range each batch item names whole (`ranges_of_build`), sized by the DLL's own +//! `GetRaytracingAccelerationStructurePrebuildInfo` answer. The exports are wrapped only when +//! the unified memory has view windows, so nothing changes on the default 4-window layout. + +#![allow(non_snake_case)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, Once}; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +/// Exact MSVC C++ mangled export names verified against `XboxBvhBuilder.dll`. +pub const SYM_BUILD_BATCHED2X: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +pub const SYM_REHYDRATE_BATCHED2X: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; +pub const SYM_PREBUILD_INFO: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +pub const SYM_COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; + +/// Size in bytes of `D3D12_RAYTRACING_INSTANCE_DESC`. +pub const INSTANCE_DESC_BYTES: u64 = 64; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE` values. +pub const AS_TYPE_TOP_LEVEL: u32 = 0; +pub const AS_TYPE_BOTTOM_LEVEL: u32 = 1; + +/// `D3D12_ELEMENTS_LAYOUT` values. +pub const LAYOUT_ARRAY: u32 = 0; +pub const LAYOUT_ARRAY_OF_POINTERS: u32 = 1; + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE`. +pub const BUILD_FLAG_ALLOW_UPDATE: u32 = 0x1; +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE`. +pub const BUILD_FLAG_PERFORM_UPDATE: u32 = 0x20; + +/// `D3D12_RAYTRACING_GEOMETRY_TYPE` values. +pub const GEOM_TYPE_TRIANGLES: u32 = 0; +pub const GEOM_TYPE_AABBS: u32 = 1; + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS` (24 bytes). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildInputs { + pub ty: u32, // +0x00: 0 = TOP_LEVEL, 1 = BOTTOM_LEVEL + pub flags: u32, // +0x04: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS + pub num_descs: u32, // +0x08: instance count (TLAS) or geometry count (BLAS) + pub descs_layout: u32, // +0x0C: 0 = ARRAY, 1 = ARRAY_OF_POINTERS + pub descs: u64, // +0x10: InstanceDescs GPU VA (TLAS) or CPU ptr to GeometryDesc(s) (BLAS) +} + +/// `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` (48 bytes = `0x30`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BuildDesc { + pub dest: u64, // +0x00: DestAccelerationStructureData GPU VA + pub inputs: BuildInputs, // +0x08..+0x20 + pub source: u64, // +0x20: SourceAccelerationStructureData GPU VA + pub scratch: u64, // +0x28: ScratchAccelerationStructureData GPU VA +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PostbuildInfoDesc { + pub dest_buffer: u64, // +0x00 + pub info_type: u32, // +0x08 + pub _pad: u32, // +0x0C +} + +/// `D3D12XBOX_XDXR_STREAM_DESC` (16 bytes = `0x10`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StreamDesc { + pub size_in_bytes: u64, // +0x00 + pub p_stream: u64, // +0x08 +} + +/// `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2` (80 bytes = `0x50`). +/// Stride `0x50` with postbuild descriptors at `+0x30`/`+0x38` and stream desc at `+0x40`/`+0x48`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BatchedBuildDesc2 { + pub build: BuildDesc, // +0x00..+0x30 + pub num_postbuild_info_descs: u32, // +0x30 + pub _pad: u32, // +0x34 + pub p_postbuild_info_descs: u64, // +0x38 + pub stream: StreamDesc, // +0x40..+0x50 +} + +/// `D3D12_RAYTRACING_GEOMETRY_DESC` (56 bytes = `0x38`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GeometryDesc { + pub ty: u32, // +0x00: 0 = Triangles, 1 = ProceduralPrimitiveAabbs + pub flags: u32, // +0x04 + pub payload: [u64; 6], // +0x08..+0x38 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TriangleGeometry { + pub transform3x4: u64, + pub index_format: u32, + pub vertex_format: u32, + pub index_count: u32, + pub vertex_count: u32, + pub index_buffer: u64, + pub vertex_buffer: u64, + pub vertex_stride: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AabbGeometry { + pub count: u64, + pub start_address: u64, + pub stride: u64, +} + +impl GeometryDesc { + pub fn as_triangles(&self) -> Option<TriangleGeometry> { + if self.ty != GEOM_TYPE_TRIANGLES { + return None; + } + Some(TriangleGeometry { + transform3x4: self.payload[0], + index_format: self.payload[1] as u32, + vertex_format: (self.payload[1] >> 32) as u32, + index_count: self.payload[2] as u32, + vertex_count: (self.payload[2] >> 32) as u32, + index_buffer: self.payload[3], + vertex_buffer: self.payload[4], + vertex_stride: self.payload[5], + }) + } + + pub fn as_aabbs(&self) -> Option<AabbGeometry> { + if self.ty != GEOM_TYPE_AABBS { + return None; + } + Some(AabbGeometry { + count: self.payload[0], + start_address: self.payload[1], + stride: self.payload[2], + }) + } +} + +impl TriangleGeometry { + pub fn index_elem_bytes(&self) -> u64 { + match self.index_format { + 0 => 0, // DXGI_FORMAT_UNKNOWN: no index buffer + // DXGI_FORMAT_R16_TYPELESS ..= R16_SINT (a retail title passes 53, R16_TYPELESS) + 53..=59 => 2, + // DXGI_FORMAT_R32_TYPELESS ..= R32_SINT, and any other: the wider element + _ => 4, + } + } + + pub fn triangle_count(&self) -> u64 { + if self.index_count > 0 { + u64::from(self.index_count) / 3 + } else { + u64::from(self.vertex_count) / 3 + } + } + + pub fn vertex_bytes(&self) -> u64 { + u64::from(self.vertex_count).saturating_mul(self.vertex_stride) + } + + pub fn index_bytes(&self) -> u64 { + u64::from(self.index_count).saturating_mul(self.index_elem_bytes()) + } +} + +/// `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO` (24 bytes = `0x18`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrebuildInfo { + pub result_data_max_size_in_bytes: u64, // +0x00 + pub scratch_data_size_in_bytes: u64, // +0x08 + pub update_scratch_data_size_in_bytes: u64, // +0x10 +} + +/// True for lowercase DLL key `"xboxbvhbuilder.dll"`. +pub fn is_bvh_builder_dll(key: &str) -> bool { + key == "xboxbvhbuilder.dll" +} + +static REAL_BUILD_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_REHYDRATE_BATCHED2X: AtomicUsize = AtomicUsize::new(0); +static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0); +/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build, +/// used when a later `PERFORM_UPDATE` prebuild query returns 0. +static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// Whether the unified memory has view windows (GPU views of the title's memory, whose tiles +/// get video memory only when asked for: the 16-window layout). +fn view_windows() -> bool { + crate::gpu::uma::get().is_some_and(|u| (0..u.shader_windows()).any(|k| u.is_view_window(k))) +} + +/// Resolve `GetRaytracingAccelerationStructurePrebuildInfo` directly from the mapped +/// `XboxBvhBuilder.dll` module so `sizes_of` does not wait for the title to import it. +fn record_prebuild_from_module(module: &MappedModule) { + if let Some(ExportTarget::Rva(rva)) = module.exports.by_name.get(SYM_PREBUILD_INFO) { + REAL_PREBUILD_INFO.store(module.base + *rva as usize, Ordering::Release); + } +} + +/// If the hooks are wanted (view windows whose tiles the builder's ranges must be asked for) +/// and `what` is a hooked `XboxBvhBuilder.dll` export, save `real_addr` (and capture +/// `GetRaytracingAccelerationStructurePrebuildInfo` directly from `module`) and return the +/// passthrough hook address; otherwise return `real_addr`. +pub fn wrap(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 || !view_windows() { + return real_addr; + } + static WHY: Once = Once::new(); + WHY.call_once(|| { + crate::xlog_info!( + "XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)" + ); + }); + wrap_with_module(module, what, real_addr) +} + +fn wrap_with_module(module: Option<&MappedModule>, what: &ImportName, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + if let Some(m) = module { + record_prebuild_from_module(m); + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.and_then(|m| { + m.exports.by_name.iter().find_map(|(n, t)| { + matches!(t, ExportTarget::Rva(r) if m.base + *r as usize == real_addr).then_some(n.as_str()) + }) + }), + }; + match name { + Some(n) => wrap_with(n, real_addr), + None => real_addr, + } +} + +fn wrap_with(function: &str, real_addr: usize) -> usize { + if real_addr == 0 { + return real_addr; + } + match function { + SYM_BUILD_BATCHED2X => { + REAL_BUILD_BATCHED2X.store(real_addr, Ordering::Release); + BuildBatched2X_hook as usize + } + SYM_REHYDRATE_BATCHED2X => { + REAL_REHYDRATE_BATCHED2X.store(real_addr, Ordering::Release); + RehydrateBatched2X_hook as usize + } + SYM_PREBUILD_INFO => { + // Capture the DLL's CPU prebuild-info query for `sizes_of` without interposing on + // title calls. + REAL_PREBUILD_INFO.store(real_addr, Ordering::Release); + real_addr + } + _ => real_addr, + } +} + +/// Deep-copy `GeometryDesc` entries for a BLAS input descriptor, handling both contiguous arrays +/// and pointer-arrays safely via `shader::readable`. +pub(crate) unsafe fn read_geometries(inputs: &BuildInputs) -> Vec<GeometryDesc> { + let n = inputs.num_descs as usize; + if inputs.ty != AS_TYPE_BOTTOM_LEVEL || n == 0 || inputs.descs == 0 { + return Vec::new(); + } + let mut out = Vec::with_capacity(n.min(1024)); + match inputs.descs_layout { + LAYOUT_ARRAY => { + let elem = std::mem::size_of::<GeometryDesc>(); + let Some(bytes) = n.checked_mul(elem) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, bytes) { + return out; + } + let base = inputs.descs as *const GeometryDesc; + for i in 0..n { + out.push(base.add(i).read_unaligned()); + } + } + LAYOUT_ARRAY_OF_POINTERS => { + let Some(ptr_bytes) = n.checked_mul(std::mem::size_of::<u64>()) else { return out }; + if !crate::gpu::shader::readable(inputs.descs as usize, ptr_bytes) { + return out; + } + let ptrs = inputs.descs as *const u64; + let elem = std::mem::size_of::<GeometryDesc>(); + for i in 0..n { + let p = ptrs.add(i).read_unaligned(); + if p != 0 && crate::gpu::shader::readable(p as usize, elem) { + out.push((p as *const GeometryDesc).read_unaligned()); + } + } + } + _ => {} + } + out +} + +fn estimate_dest_bytes(inputs: &BuildInputs, geoms: &[GeometryDesc]) -> u64 { + if inputs.ty == AS_TYPE_TOP_LEVEL { + return crate::gpu::bvh::prebuild_size(u64::from(inputs.num_descs), true); + } + let mut leaves = 0u64; + for g in geoms { + if let Some(t) = g.as_triangles() { + leaves = leaves.saturating_add(t.triangle_count()); + } else if let Some(a) = g.as_aabbs() { + leaves = leaves.saturating_add(a.count); + } + } + if leaves > 0 { + crate::gpu::bvh::prebuild_size(leaves, false) + } else { + 0 + } +} + +/// What a range a build or rehydrate names is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Use { + Dest, + Source, + Scratch, + Instances, + Vertices, + Indices, + Transform, + Aabbs, + Postbuild, +} + +/// A GPU range the builder's programs read or write for one batch item. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Range { + pub what: Use, + pub va: u64, + pub len: u64, +} + +/// bytes of a geometry's 3x4 float transform +const TRANSFORM_BYTES: u64 = 48; +/// bytes asked for at a postbuild-info destination (the largest kind, serialization, is 16) +const POSTBUILD_BYTES: u64 = 16; +/// postbuild-info descriptions read of one batch item at most +const MAX_POSTBUILD: usize = 64; +/// scratch asked for when the DLL's prebuild answer is not at hand +const SCRATCH_GUESS: u64 = 0x1_0000; + +fn push_range(out: &mut Vec<Range>, what: Use, va: u64, len: u64) { + if va != 0 && len != 0 { + out.push(Range { what, va, len }); + } +} + +/// What a build of `inputs` takes: the DLL's own prebuild answer when its export is known (a CPU +/// function: it reads only the inputs and the stream), else `gpu::bvh::prebuild_size` of the +/// leaves counted for the result and `SCRATCH_GUESS` for scratch. +unsafe fn sizes_of( + this: *mut c_void, + inputs: &BuildInputs, + stream: &StreamDesc, + geoms: &[GeometryDesc], +) -> PrebuildInfo { + let real = REAL_PREBUILD_INFO.load(Ordering::Acquire); + if real != 0 { + let f: PrebuildInfoFn = std::mem::transmute(real); + let mut info = PrebuildInfo::default(); + let s = if *stream == StreamDesc::default() { std::ptr::null() } else { stream as *const StreamDesc }; + f(this, inputs, s, &mut info); + if info.result_data_max_size_in_bytes != 0 { + return info; + } + } + PrebuildInfo { + result_data_max_size_in_bytes: estimate_dest_bytes(inputs, geoms) + .max(crate::gpu::bvh::HEADER_BYTES as u64), + scratch_data_size_in_bytes: SCRATCH_GUESS, + update_scratch_data_size_in_bytes: SCRATCH_GUESS, + } +} + +/// The vertex, index, transform and AABB ranges of `geoms`. +fn geometry_ranges(geoms: &[GeometryDesc], out: &mut Vec<Range>) { + for g in geoms { + if let Some(t) = g.as_triangles() { + push_range(out, Use::Vertices, t.vertex_buffer, t.vertex_bytes()); + if t.index_buffer != 0 { + push_range(out, Use::Indices, t.index_buffer, t.index_bytes()); + } + push_range(out, Use::Transform, t.transform3x4, TRANSFORM_BYTES); + } else if let Some(a) = g.as_aabbs() { + // D3D12_RAYTRACING_AABB is 24 bytes: a stride below it is the minimum. + push_range(out, Use::Aabbs, a.start_address, a.count.saturating_mul(a.stride.max(24))); + } + } +} + +/// Resolve scratch bytes for build `b`. An `ALLOW_UPDATE` build records its update-scratch size +/// in `cache` keyed by destination VA; a `PERFORM_UPDATE` whose prebuild query returns 0 reuses +/// that cached size (from `source`, or `dest` when updating in place) and otherwise falls back to +/// `scratch_data_size_in_bytes.max(update_scratch_data_size_in_bytes).max(SCRATCH_GUESS)`. +fn resolve_scratch_bytes(b: &BuildDesc, sizes: &PrebuildInfo, cache: &mut HashMap<u64, u64>) -> u64 { + if b.inputs.flags & BUILD_FLAG_PERFORM_UPDATE != 0 { + let source = if b.source != 0 { b.source } else { b.dest }; + let cached = cache.get(&source).copied().filter(|&n| n != 0); + let scratch = if sizes.update_scratch_data_size_in_bytes != 0 { + cached.map_or(sizes.update_scratch_data_size_in_bytes, |c| { + c.max(sizes.update_scratch_data_size_in_bytes) + }) + } else if let Some(c) = cached { + c + } else { + sizes + .scratch_data_size_in_bytes + .max(sizes.update_scratch_data_size_in_bytes) + .max(SCRATCH_GUESS) + }; + if b.dest != 0 && (cached.is_some() || sizes.update_scratch_data_size_in_bytes != 0) { + cache.insert(b.dest, scratch); + } + scratch + } else { + if b.dest != 0 { + if b.inputs.flags & BUILD_FLAG_ALLOW_UPDATE != 0 && sizes.update_scratch_data_size_in_bytes != 0 { + cache.insert(b.dest, sizes.update_scratch_data_size_in_bytes); + } else { + cache.remove(&b.dest); + } + } + sizes.scratch_data_size_in_bytes + } +} + +/// The ranges build `b` names, sized by `sizes`: its result, the structure an update or a +/// rehydrate starts from when that is not the result itself, scratch (an update's when it is +/// one, using `update_scratch_cache` or a safe fallback if the prebuild query returned 0), and +/// the instance descriptions (top level: an array, or an array of their addresses plus each +/// readable 64-byte `D3D12_RAYTRACING_INSTANCE_DESC` target) or `geoms`, the geometry read of +/// its inputs (bottom level). +unsafe fn ranges_of_build( + b: &BuildDesc, + geoms: &[GeometryDesc], + sizes: &PrebuildInfo, + update_scratch_cache: &mut HashMap<u64, u64>, + cpu_at: impl Fn(u64) -> u64, + out: &mut Vec<Range>, +) { + let inp = &b.inputs; + let result = sizes.result_data_max_size_in_bytes; + push_range(out, Use::Dest, b.dest, result); + if b.source != b.dest { + push_range(out, Use::Source, b.source, result); + } + let scratch_bytes = resolve_scratch_bytes(b, sizes, update_scratch_cache); + push_range(out, Use::Scratch, b.scratch, scratch_bytes); + if inp.ty == AS_TYPE_TOP_LEVEL { + if inp.descs_layout == LAYOUT_ARRAY_OF_POINTERS { + let n = inp.num_descs as usize; + push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8)); + if n > 0 && inp.descs != 0 { + if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) { + let cpu = cpu_at(inp.descs); + if cpu != 0 && crate::gpu::shader::readable(cpu as usize, bytes) { + let ptrs = cpu as *const u64; + let mut targets: Vec<u64> = Vec::with_capacity(n.min(1024)); + for i in 0..n { + let target = ptrs.add(i).read_unaligned(); + if target != 0 { + targets.push(target); + } + } + targets.sort_unstable(); + let mut cur: Option<(u64, u64)> = None; + for va in targets { + let end = va.saturating_add(INSTANCE_DESC_BYTES); + match cur { + Some((s, e)) if va <= e => cur = Some((s, e.max(end))), + Some((s, e)) => { + push_range(out, Use::Instances, s, e.saturating_sub(s)); + cur = Some((va, end)); + } + None => cur = Some((va, end)), + } + } + if let Some((s, e)) = cur { + push_range(out, Use::Instances, s, e.saturating_sub(s)); + } + } + } + } + } else { + push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(INSTANCE_DESC_BYTES)); ~~~~ --- **Medium**: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's `AccelerationStructure` field names. If a bottom level was built frames earlier and its view tiles have since been dropped or not asked again this generation, the top-level build reads zero bounds or headers for that instance, which ends up degenerate or missing. Asking for each referenced bottom level's range (at least its header) would cover it.
bmjask commented 2026-12-02 19:56:03 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:56:03Z.


@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

<!-- greyfinch-sync:ivall/xcl:comment:7356952382 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7356952382). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:56:03Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
Kalmarv commented 2026-12-02 23:24:47 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T23:24:47Z.


Thanks @bmjask — all 4 review findings are fixed in 4082300ba:

  1. Critical (bvh_builder.rs:492 raw read_unaligned TOCTOU): Replaced raw pointer reads of title GPU memory with read_gpu_bytes, which reads exclusively through dstorage::read_own (ReadProcessMemory) so concurrent decommits fail cleanly instead of faulting inside extern "system-unwind".
  2. High (bvh_builder.rs:487 cross-64 KiB-tile ARRAY_OF_POINTERS): read_gpu_bytes now uses view_want::cpu_run on the fast path and falls back to per-64 KiB-tile translation + read_own when CPU pages across a tile boundary are discontiguous.
  3. Medium (bvh_builder.rs:208 unbounded/stale UPDATE_SCRATCH): Removed UPDATE_SCRATCH completely. sizes_of now strips BUILD_FLAG_PERFORM_UPDATE and sets BUILD_FLAG_ALLOW_UPDATE (the DXR-legal form) before calling GetRaytracingAccelerationStructurePrebuildInfo, returning UpdateScratchDataSizeInBytes directly (falling back to scratch.max(SCRATCH_GUESS) if still 0).
  4. Medium (bvh_builder.rs:517 referenced BLAS headers): Both LAYOUT_ARRAY and LAYOUT_ARRAY_OF_POINTERS TLAS builds now safely read each instance's AccelerationStructure VA at offset +0x38 via read_gpu_bytes and ask for deduplicated bottom-level header ranges (Use::BottomLevel, HEADER_BYTES).

Added regression tests perform_update_queries_dxr_legal_flags_without_stale_cache and tlas_pointer_array_cross_tile_read_own_and_blas_headers (hle::bvh_builder::tests: 12/12 passed; full stack scripts/test.ps1 at 1f287a928: 3006 passed, 0 failed, 52 ignored, 24 SKIPPED; 60 s smoke on 4082300ba: 1673 frames, 0 removals, 0 crashes).

(Fixed and replied via Antigravity (Gemini 4 Neon).)

<!-- greyfinch-sync:ivall/xcl:comment:7361962203 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7361962203). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T23:24:47Z. --- Thanks @bmjask — all 4 review findings are fixed in `4082300ba`: 1. **Critical (`bvh_builder.rs:492` raw `read_unaligned` TOCTOU):** Replaced raw pointer reads of title GPU memory with `read_gpu_bytes`, which reads exclusively through `dstorage::read_own` (`ReadProcessMemory`) so concurrent decommits fail cleanly instead of faulting inside `extern "system-unwind"`. 2. **High (`bvh_builder.rs:487` cross-64 KiB-tile `ARRAY_OF_POINTERS`):** `read_gpu_bytes` now uses `view_want::cpu_run` on the fast path and falls back to per-64 KiB-tile translation + `read_own` when CPU pages across a tile boundary are discontiguous. 3. **Medium (`bvh_builder.rs:208` unbounded/stale `UPDATE_SCRATCH`):** Removed `UPDATE_SCRATCH` completely. `sizes_of` now strips `BUILD_FLAG_PERFORM_UPDATE` and sets `BUILD_FLAG_ALLOW_UPDATE` (the DXR-legal form) before calling `GetRaytracingAccelerationStructurePrebuildInfo`, returning `UpdateScratchDataSizeInBytes` directly (falling back to `scratch.max(SCRATCH_GUESS)` if still `0`). 4. **Medium (`bvh_builder.rs:517` referenced BLAS headers):** Both `LAYOUT_ARRAY` and `LAYOUT_ARRAY_OF_POINTERS` TLAS builds now safely read each instance's `AccelerationStructure` VA at offset `+0x38` via `read_gpu_bytes` and ask for deduplicated bottom-level header ranges (`Use::BottomLevel`, `HEADER_BYTES`). Added regression tests `perform_update_queries_dxr_legal_flags_without_stale_cache` and `tlas_pointer_array_cross_tile_read_own_and_blas_headers` (`hle::bvh_builder::tests`: 12/12 passed; full stack `scripts/test.ps1` at `1f287a928`: 3006 passed, 0 failed, 52 ignored, 24 SKIPPED; 60 s smoke on `4082300ba`: 1673 frames, 0 removals, 0 crashes). *(Fixed and replied via Antigravity (Gemini 4 Neon).)*
Foniass commented 2026-12-03 01:58:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T01:58:17Z.


merge-check
base: 078358a058
head: 4082300ba8
merge: clean
build: ok
tests: 3018 passed, 0 failed, 52 ignored; 28 skipped, the same as on main
review: 3 medium, 2 nits (below)
performance: 60 s smoke run: 1669 → 1657 frames (99 % of main), peak commit 17577 → 17695 MB, no device removal, no crash
title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 225 s there, 0 device removals, 0 crashes, 3.4 presents/s; run with XCL_SKIP_CS=95cc13288a27a96e (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590)
verdict: not yet: PR description is red; otherwise no blocking finding, the suite passes and the smoke run is clean
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5


In short: Hooks XboxBvhBuilder.dll's BuildBatched2X and RehydrateBatched2X (named, by ordinal and through GetProcAddress) on the 16-window layout and asks view_want for every range a build names, whole, before forwarding to the DLL. It is now one commit on main, and the earlier review's sizing, prebuild-lookup and instance findings are fixed. Nothing blocks; still open are the missing 16-window run at this head and the unmeasured CPU cost per build.

Medium

  1. No 16-window run at this head. The only run that reaches the hooks (180 s, XCL_VIEW_STATS) was on an earlier revision, before read_own/cpu_run, the DXR-legal prebuild query and the BLAS header asks. The default-layout smoke installs no hook (view_windows() is false), and the unit tests check only range arithmetic. Rerun the 16-window session at 4082300b and post its acceleration-structure builds line and device-removal count.
  2. CPU cost per build is unmeasured. Every top-level build now reads up to 65536 instance descriptions or pointers on the recording thread (bvh_builder.rs ~507-565): one ReadProcessMemory per 4 KiB chunk, plus one 8-byte read_own per pointer target for ARRAY_OF_POINTERS, and cpu_run takes the kernelx::mirrors lock per tile. Every batch item also calls the DLL's prebuild query. The earlier run logged about 4000 builds per 2 s. Measure the time spent in the hooks on the 16-window layout, or batch the pointer-target reads.
  3. 1339 lines in one PR. This is over the ~800-line limit; a reason is given (about half is tests). The split from the earlier review would still work: first the ABI structs, ranges_of_build and their tests, then the hooks with the resolver.rs and view_want wiring.

Nit

  1. Doc comment names a module that is not on main. bvh_builder.rs ~5-6 says calls forward "to d3d12x::bvh_builder's inner sparse-memory hook when XCL_SPARSE_LAZY=1". That module exists only in open #3521. Add "(with #3521)" or drop it.
  2. Suite counts come from another commit. Tested gives 3006/0/52 from 1f287a92 (the top of a stack). Only the 12 bvh_builder tests ran at this head.
Checked and fine
  • Earlier finding fixed: the PR now holds only its own commit on main 5eaadb54, with no rebased copies of #3517, #3349, #3521 or #3522
  • Earlier finding fixed: an update's scratch is no longer dropped when the query returns 0 (resolve_scratch_bytes falls back to scratch.max(SCRATCH_GUESS), and the query swaps PERFORM_UPDATE for ALLOW_UPDATE), and perform_update_queries_dxr_legal_flags_without_stale_cache covers it
  • Earlier finding fixed: GetRaytracingAccelerationStructurePrebuildInfo is looked up in the mapped module (record_prebuild_from_module), ordinal imports included, with a test
  • Earlier finding fixed: ARRAY_OF_POINTERS top levels now ask for the 64-byte instance descriptions behind the pointers and the referenced bottom-level headers
  • read_gpu_bytes translates tile by tile when cpu_run fails and cannot fault (ReadProcessMemory); the cross-tile test covers both the split read and a failing read_own
  • The default 4-window layout is unchanged: wrap returns the real address when view_windows() is false
  • The ABI sizes, offsets and mangled names match; both import resolution and GetProcAddress are hooked; there is no textual conflict with #3521, which intercepts in resolve_export_of_mapped_inner, so calls chain outer then inner
How this was tested
  • Merged onto main 078358a0, then cargo build --workspace and cargo test --workspace --no-fail-fast -- --test-threads=4.
  • The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar).
  • scripts/smoke.ps1: 60 s of a retail title on main 078358a0 and on this merge; presents per 2 s at the end: 60 60 60.
  • Title run: the release build of this merge launched the retail title with XCL_RUN_SECONDS=300 and scripted A presses counted from the first frame (XCL_PRESS_BASE=frame, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7364939744 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7364939744). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T01:58:17Z. --- merge-check base: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a head: 4082300ba84ea77630ac1050264b4d07fc4bb5a3 merge: clean build: ok tests: 3018 passed, 0 failed, 52 ignored; 28 skipped, the same as on main review: 3 medium, 2 nits (below) performance: 60 s smoke run: 1669 → 1657 frames (99 % of main), peak commit 17577 → 17695 MB, no device removal, no crash title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 225 s there, 0 device removals, 0 crashes, 3.4 presents/s; run with `XCL_SKIP_CS=95cc13288a27a96e` (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590) verdict: not yet: `PR description` is red; otherwise no blocking finding, the suite passes and the smoke run is clean hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 --- **In short:** Hooks XboxBvhBuilder.dll's BuildBatched2X and RehydrateBatched2X (named, by ordinal and through GetProcAddress) on the 16-window layout and asks view_want for every range a build names, whole, before forwarding to the DLL. It is now one commit on main, and the earlier review's sizing, prebuild-lookup and instance findings are fixed. Nothing blocks; still open are the missing 16-window run at this head and the unmeasured CPU cost per build. #### Medium 1. **No 16-window run at this head.** The only run that reaches the hooks (180 s, XCL_VIEW_STATS) was on an earlier revision, before read_own/cpu_run, the DXR-legal prebuild query and the BLAS header asks. The default-layout smoke installs no hook (view_windows() is false), and the unit tests check only range arithmetic. Rerun the 16-window session at 4082300b and post its acceleration-structure builds line and device-removal count. 2. **CPU cost per build is unmeasured.** Every top-level build now reads up to 65536 instance descriptions or pointers on the recording thread (bvh_builder.rs ~507-565): one ReadProcessMemory per 4 KiB chunk, plus one 8-byte read_own per pointer target for ARRAY_OF_POINTERS, and cpu_run takes the kernelx::mirrors lock per tile. Every batch item also calls the DLL's prebuild query. The earlier run logged about 4000 builds per 2 s. Measure the time spent in the hooks on the 16-window layout, or batch the pointer-target reads. 3. **1339 lines in one PR.** This is over the ~800-line limit; a reason is given (about half is tests). The split from the earlier review would still work: first the ABI structs, ranges_of_build and their tests, then the hooks with the resolver.rs and view_want wiring. #### Nit 4. **Doc comment names a module that is not on main.** bvh_builder.rs ~5-6 says calls forward "to d3d12x::bvh_builder's inner sparse-memory hook when XCL_SPARSE_LAZY=1". That module exists only in open #3521. Add "(with #3521)" or drop it. 5. **Suite counts come from another commit.** Tested gives 3006/0/52 from 1f287a92 (the top of a stack). Only the 12 bvh_builder tests ran at this head. <details><summary>Checked and fine</summary> - Earlier finding fixed: the PR now holds only its own commit on main 5eaadb54, with no rebased copies of #3517, #3349, #3521 or #3522 - Earlier finding fixed: an update's scratch is no longer dropped when the query returns 0 (resolve_scratch_bytes falls back to scratch.max(SCRATCH_GUESS), and the query swaps PERFORM_UPDATE for ALLOW_UPDATE), and perform_update_queries_dxr_legal_flags_without_stale_cache covers it - Earlier finding fixed: GetRaytracingAccelerationStructurePrebuildInfo is looked up in the mapped module (record_prebuild_from_module), ordinal imports included, with a test - Earlier finding fixed: ARRAY_OF_POINTERS top levels now ask for the 64-byte instance descriptions behind the pointers and the referenced bottom-level headers - read_gpu_bytes translates tile by tile when cpu_run fails and cannot fault (ReadProcessMemory); the cross-tile test covers both the split read and a failing read_own - The default 4-window layout is unchanged: wrap returns the real address when view_windows() is false - The ABI sizes, offsets and mangled names match; both import resolution and GetProcAddress are hooked; there is no textual conflict with #3521, which intercepts in resolve_export_of_mapped_inner, so calls chain outer then inner </details> <details><summary>How this was tested</summary> - Merged onto main `078358a0`, then `cargo build --workspace` and `cargo test --workspace --no-fail-fast -- --test-threads=4`. - The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar). - `scripts/smoke.ps1`: 60 s of a retail title on main `078358a0` and on this merge; presents per 2 s at the end: 60 60 60. - Title run: the release build of this merge launched the retail title with `XCL_RUN_SECONDS=300` and scripted A presses counted from the first frame (`XCL_PRESS_BASE=frame`, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Kalmarv commented 2026-12-03 02:25:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-03T02:25:44Z.


Thanks for the thorough merge-check and title run @Foniass!

  • PR description is red: every pull_request_target workflow on xcl-dev/xcl (PR checks, Auto triage, Testing feed, Discord mirror) has been failing with startup_failure repo-wide since ~22:47 UTC on 2026-12-02, so PR description never started on 4082300ba (check suites 127103282286 / 127103289399). Running main's scripts/pr_check.py --local against PR #3662's updated description and 4-file list for 4082300ba passes (description ok), and Build and test (Windows, no GPU) is green (46994358570). Once pull_request_target recovers, I'll retrigger PR checks via a no-op description edit without changing 4082300ba.
  • Medium 1 (16-window run at 4082300ba): ran a fresh 180 s XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1 session directly on 4082300ba: exit: 0x0, 1645 frames shown (1645 PresentX calls), 0 device removals, 0 crashes, with 29 GPU view (2 s) lines logging acceleration-structure builds (30,036 total range asks / 478,656 KB new), peaking at:
    • [96.640] GPU view (2 s): 11452 root views (3776 KB new), 766 mesh stage views (448 KB new), 4433 acceleration-structure builds (142976 KB new)
    • [149.056] GPU view (2 s): 725 views by address (2560 KB new), 3 buffer views (0 KB new), 1 placed buffers (0 KB new), 4491 root views (320 KB new), 1514 mesh stage views (64 KB new), 2237 acceleration-structure builds (50816 KB new)
  • Medium 2 (hook CPU cost on 16-window layout): measured with local timing instrumentation on 4082300ba (reverted after measurement) across 53.0 s of active 16-window BVH builds (113 BuildBatched2X calls / 1,472 items, 83 RehydrateBatched2X calls / 1,250 items; 2,637 BLAS, 85 TLAS LAYOUT_ARRAY, 0 TLAS LAYOUT_ARRAY_OF_POINTERS, 74,120 TLAS instances read across 1,220 read_gpu_bytes calls):
    • Total hook CPU time: 13.92 ms (0.026 % of wall time; 2.36 % of the 588.6 ms spent in the real XboxBvhBuilder.dll calls) — 71 µs/call, 5.1 µs/item, worst single call 756 µs.
    • Breakdown: read_geometries 2.47 ms, sizes_of 0.265 ms (0.10 µs/item), ranges_of_build 6.58 ms (77 µs/TLAS build), ask 4.16 ms.
    • Note: the ~4000 acceleration-structure builds in GPU view (2 s) counts individual view_want::want range calls (dest/source/scratch/vertex/index/transform/instances/headers), not batch calls (~50 hook calls / ~750 items in that 2 s window, taking ~2 ms total).
  • Nit 5 (suite counts at 4082300ba): ran full .\scripts\test.ps1 directly on 4082300ba: 2986 passed, 0 failed, 52 ignored across 43 suites; 24 SKIPPED GPU lines on this adapter (22 no wave64, 2 no heap windows). Updated Tested and Not tested in the PR description.
  • Medium 3 & Nit 4 (diff size & #3521 doc comment): noted — leaving 4082300ba untouched for now so this merge-check and the stacked PRs (#3697, #3700, #3704, #3705) stay aligned; happy to add (with #3521) to the doc comment if #3662 needs another push or in a follow-up.

(Tested, measured, and replied via Antigravity (Gemini 4 Neon).)

<!-- greyfinch-sync:ivall/xcl:comment:7365450311 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7365450311). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-03T02:25:44Z. --- Thanks for the thorough merge-check and title run @Foniass! - **`PR description` is red:** every `pull_request_target` workflow on `xcl-dev/xcl` (`PR checks`, `Auto triage`, `Testing feed`, `Discord mirror`) has been failing with `startup_failure` repo-wide since ~22:47 UTC on 2026-12-02, so `PR description` never started on `4082300ba` (check suites `127103282286` / `127103289399`). Running `main`'s `scripts/pr_check.py --local` against PR #3662's updated description and 4-file list for `4082300ba` passes (`description ok`), and `Build and test (Windows, no GPU)` is green (`46994358570`). Once `pull_request_target` recovers, I'll retrigger `PR checks` via a no-op description edit without changing `4082300ba`. - **Medium 1 (16-window run at `4082300ba`):** ran a fresh 180 s `XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1` session directly on `4082300ba`: `exit: 0x0`, `1645` frames shown (`1645` PresentX calls), **`0` device removals**, `0` crashes, with 29 `GPU view (2 s)` lines logging `acceleration-structure builds` (`30,036` total range asks / `478,656 KB` new), peaking at: - `[96.640] GPU view (2 s): 11452 root views (3776 KB new), 766 mesh stage views (448 KB new), 4433 acceleration-structure builds (142976 KB new)` - `[149.056] GPU view (2 s): 725 views by address (2560 KB new), 3 buffer views (0 KB new), 1 placed buffers (0 KB new), 4491 root views (320 KB new), 1514 mesh stage views (64 KB new), 2237 acceleration-structure builds (50816 KB new)` - **Medium 2 (hook CPU cost on 16-window layout):** measured with local timing instrumentation on `4082300ba` (reverted after measurement) across 53.0 s of active 16-window BVH builds (`113` `BuildBatched2X` calls / `1,472` items, `83` `RehydrateBatched2X` calls / `1,250` items; `2,637` BLAS, `85` TLAS `LAYOUT_ARRAY`, `0` TLAS `LAYOUT_ARRAY_OF_POINTERS`, `74,120` TLAS instances read across `1,220` `read_gpu_bytes` calls): - Total hook CPU time: **`13.92 ms`** (`0.026 %` of wall time; `2.36 %` of the `588.6 ms` spent in the real `XboxBvhBuilder.dll` calls) — `71 µs`/call, `5.1 µs`/item, worst single call `756 µs`. - Breakdown: `read_geometries` `2.47 ms`, `sizes_of` `0.265 ms` (`0.10 µs`/item), `ranges_of_build` `6.58 ms` (`77 µs`/TLAS build), `ask` `4.16 ms`. - Note: the `~4000 acceleration-structure builds` in `GPU view (2 s)` counts individual `view_want::want` range calls (dest/source/scratch/vertex/index/transform/instances/headers), not batch calls (~50 hook calls / ~750 items in that 2 s window, taking `~2 ms` total). - **Nit 5 (suite counts at `4082300ba`):** ran full `.\scripts\test.ps1` directly on `4082300ba`: **`2986` passed, `0` failed, `52` ignored** across 43 suites; `24` `SKIPPED` GPU lines on this adapter (22 `no wave64`, 2 `no heap windows`). Updated **Tested** and **Not tested** in the PR description. - **Medium 3 & Nit 4 (diff size & `#3521` doc comment):** noted — leaving `4082300ba` untouched for now so this merge-check and the stacked PRs (`#3697`, `#3700`, `#3704`, `#3705`) stay aligned; happy to add `(with #3521)` to the doc comment if `#3662` needs another push or in a follow-up. *(Tested, measured, and replied via Antigravity (Gemini 4 Neon).)*
KDenKC commented 2026-12-03 07:58:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KDenKC on 2026-12-03T07:58:38Z.


@Kalmarv a freeze in the retail title that sits in #3662's BVH walk (head 4082300b, which we run on a
combined tree with native mesh off). It ended the run on the title's own 30-second watchdog.

What we saw. The world ran normally until a heavy slice (13,663 draws and 27,290 dispatches in 2 s),
then nothing for 31 s, then the title's watchdog crash. XCL's crash-time thread dump, symbolized with the
build's PDB, has the title's present thread here; no other XCL thread was busy:

xcl::gpu::bvh::Mem::get+0x306
xcl::gpu::bvh::walk+0x4c2
xcl::gpu::bvh::walk_scene+0x2f3
xcl::hle::d3d12x::bvh_want::walk+0x4af
xcl::hle::d3d12x::bvh_want::frame+0x2c1
xcl::hle::d3d12x::present::present_x+0x217
xcl::hle::d3d12x::real::queue_dispatch+0x8bf

Why it can take that long. bvh_want::frame runs inside present_x, synchronously, and walks up to
A_FRAME (2) stale top levels per present, with their stale bottom levels. bvh::Limits::default()
allows 2 GiB of reads and 4 M nodes per structure, 32 M per scene, 65,536 bottom levels, read 64 KiB at a
time from the title's memory (read_title → read_own). When the title's memory is paged out (our run
was under disk load at the time), one walk can outlast the watchdog, and the present, and with it the
title's frame, waits for all of it.

The ask: keep the walk from blocking the present: a per-present budget (time or bytes, continuing the
walk on the next present), or the walk on a worker thread with the present only picking up finished
results. Either way, a log line with the walk's time when it is long would make this visible.

A question we're measuring: how much the walk costs on an ordinary frame. A top level goes stale
whenever the CPU writes a page it covers, so a title that rewrites its instance data every frame walks
every present. We're running the same build with XCL_BVH_WALK=0 against it tonight and will post the
fps difference here.

Your loyal testing minion stands by for the next head.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

<!-- greyfinch-sync:ivall/xcl:comment:7371663554 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7371663554). Originally posted by [KDenKC](https://github.com/KDenKC) on 2026-12-03T07:58:38Z. --- @Kalmarv a freeze in the retail title that sits in #3662's BVH walk (head `4082300b`, which we run on a combined tree with native mesh off). It ended the run on the title's own 30-second watchdog. **What we saw.** The world ran normally until a heavy slice (13,663 draws and 27,290 dispatches in 2 s), then nothing for 31 s, then the title's watchdog crash. XCL's crash-time thread dump, symbolized with the build's PDB, has the title's present thread here; no other XCL thread was busy: ``` xcl::gpu::bvh::Mem::get+0x306 xcl::gpu::bvh::walk+0x4c2 xcl::gpu::bvh::walk_scene+0x2f3 xcl::hle::d3d12x::bvh_want::walk+0x4af xcl::hle::d3d12x::bvh_want::frame+0x2c1 xcl::hle::d3d12x::present::present_x+0x217 xcl::hle::d3d12x::real::queue_dispatch+0x8bf ``` **Why it can take that long.** `bvh_want::frame` runs inside `present_x`, synchronously, and walks up to `A_FRAME` (2) stale top levels per present, with their stale bottom levels. `bvh::Limits::default()` allows 2 GiB of reads and 4 M nodes per structure, 32 M per scene, 65,536 bottom levels, read 64 KiB at a time from the title's memory (`read_title` → `read_own`). When the title's memory is paged out (our run was under disk load at the time), one walk can outlast the watchdog, and the present, and with it the title's frame, waits for all of it. **The ask:** keep the walk from blocking the present: a per-present budget (time or bytes, continuing the walk on the next present), or the walk on a worker thread with the present only picking up finished results. Either way, a log line with the walk's time when it is long would make this visible. **A question we're measuring:** how much the walk costs on an ordinary frame. A top level goes stale whenever the CPU writes a page it covers, so a title that rewrites its instance data every frame walks every present. We're running the same build with `XCL_BVH_WALK=0` against it tonight and will post the fps difference here. Your loyal testing minion stands by for the next head. AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.
Kalmarv commented 2026-12-03 08:12:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-03T08:12:54Z.


Thanks for the symbolized stack and diagnosis @KDenKC!

One important clarification on where this sits: that stack (present_x → bvh_want::frame → bvh_want::walk → bvh::walk_scene → bvh::Mem::get) is entirely in main's pre-existing bvh_want.rs / gpu/bvh.rs (commits ba6b879bb and 6f1f5574e), which #3662 (4082300ba) does not touch — #3662 only adds the XboxBvhBuilder.dll HLE hooks in crates/xcl/src/hle/bvh_builder.rs (plus wiring in resolver.rs, hle/mod.rs, and view_want.rs).

What #3662 did was unmask that pre-existing main path: before #3662, XboxBvhBuilder produced empty structures on the 16-window layout, so bvh_want::walk returned in tens of microseconds at 0 nodes. Once #3662 lets the builder populate real trees (and whenever the CPU side of those pages holds the built nodes), main's synchronous walk hits real node counts under Limits::default() (2 GiB / 32 M scene nodes / 65,536 bottom levels, read 64 KiB at a time) and can outlast the 30 s watchdog under paging/disk load.

Two extra notes from checking bvh_want.rs:

  1. view_made is also synchronous: in addition to bvh_want::frame() in present_x, bvh_want::view_made(va) (called from CreateShaderResourceView in real.rs) calls bvh_want::walk(va) synchronously on the recording thread whenever a new TLAS view is created or a stale TLAS is viewed on a later frame. Moving the walk onto a dedicated background worker thread (with frame() and view_made() only enqueueing stale VAs and applying finished tile sets) would keep both present_x and SRV creation non-blocking, and logging any slow walk (above a millisecond threshold, not just power-of-two counts) would make long walks visible.
  2. XCL_BVH_WALK=0 with #3662: for acceleration structures built or rehydrated through XboxBvhBuilder.dll, #3662 already asks view_want (Path::BvhBuild) for every result buffer whole up front (and referenced BLAS headers on TLAS builds), so running with XCL_BVH_WALK=0 is a clean immediate workaround and A/B test.

To keep #3662 scoped to one logical change (it is already at 1,339 lines, has @Foniass's merge-check at 4082300ba, and sits under stacked #3697 / #3700 / #3704 / #3705), I am leaving 4082300ba untouched and can follow up with a small standalone PR against main for bvh_want once we see your XCL_BVH_WALK=0 fps comparison tonight (to know whether steady-state frame time is also affected or mainly paging stalls).

(Checked and replied via Antigravity (Gemini 4 Neon).)

<!-- greyfinch-sync:ivall/xcl:comment:7371972809 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7371972809). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-03T08:12:54Z. --- Thanks for the symbolized stack and diagnosis @KDenKC! One important clarification on where this sits: that stack (`present_x` → `bvh_want::frame` → `bvh_want::walk` → `bvh::walk_scene` → `bvh::Mem::get`) is entirely in **`main`'s pre-existing `bvh_want.rs` / `gpu/bvh.rs`** (commits `ba6b879bb` and `6f1f5574e`), which `#3662` (`4082300ba`) does not touch — `#3662` only adds the `XboxBvhBuilder.dll` HLE hooks in `crates/xcl/src/hle/bvh_builder.rs` (plus wiring in `resolver.rs`, `hle/mod.rs`, and `view_want.rs`). What `#3662` did was **unmask** that pre-existing `main` path: before `#3662`, `XboxBvhBuilder` produced empty structures on the 16-window layout, so `bvh_want::walk` returned in tens of microseconds at 0 nodes. Once `#3662` lets the builder populate real trees (and whenever the CPU side of those pages holds the built nodes), `main`'s synchronous walk hits real node counts under `Limits::default()` (`2 GiB` / `32 M` scene nodes / `65,536` bottom levels, read 64 KiB at a time) and can outlast the 30 s watchdog under paging/disk load. Two extra notes from checking `bvh_want.rs`: 1. **`view_made` is also synchronous:** in addition to `bvh_want::frame()` in `present_x`, `bvh_want::view_made(va)` (called from `CreateShaderResourceView` in `real.rs`) calls `bvh_want::walk(va)` synchronously on the recording thread whenever a new TLAS view is created or a stale TLAS is viewed on a later frame. Moving the walk onto a dedicated background worker thread (with `frame()` and `view_made()` only enqueueing stale VAs and applying finished tile sets) would keep both `present_x` and SRV creation non-blocking, and logging any slow walk (above a millisecond threshold, not just power-of-two counts) would make long walks visible. 2. **`XCL_BVH_WALK=0` with `#3662`:** for acceleration structures built or rehydrated through `XboxBvhBuilder.dll`, `#3662` already asks `view_want` (`Path::BvhBuild`) for every result buffer whole up front (and referenced BLAS headers on TLAS builds), so running with `XCL_BVH_WALK=0` is a clean immediate workaround and A/B test. To keep `#3662` scoped to one logical change (it is already at 1,339 lines, has `@Foniass`'s merge-check at `4082300ba`, and sits under stacked `#3697` / `#3700` / `#3704` / `#3705`), I am leaving `4082300ba` untouched and can follow up with a small standalone PR against `main` for `bvh_want` once we see your `XCL_BVH_WALK=0` fps comparison tonight (to know whether steady-state frame time is also affected or mainly paging stalls). *(Checked and replied via Antigravity (Gemini 4 Neon).)*
Foniass commented 2026-12-03 15:36:33 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T15:36:33Z.


merge-check
base: 078358a058
head: 4082300ba8
merge: clean
build: ok
tests: 3018 passed, 0 failed, 52 ignored; 28 skipped, the same as on main
review: 3 medium, 2 nits (below)
performance: 60 s smoke run: 1669 → 1657 frames (99 % of main), peak commit 17577 → 17695 MB, no device removal, no crash
title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 225 s there, 0 device removals, 0 crashes, 3.4 presents/s; run with XCL_SKIP_CS=95cc13288a27a96e (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590)
verdict: safe to merge: no blocking finding (the points below are medium or nits), the suite passes and the smoke run is clean
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5


In short: Hooks XboxBvhBuilder.dll's BuildBatched2X and RehydrateBatched2X (named, by ordinal and through GetProcAddress) on the 16-window layout and asks view_want for every range a build names, whole, before forwarding to the DLL. It is now one commit on main, and the earlier review's sizing, prebuild-lookup and instance findings are fixed. Nothing blocks; still open are the missing 16-window run at this head and the unmeasured CPU cost per build.

Medium

  1. No 16-window run at this head. The only run that reaches the hooks (180 s, XCL_VIEW_STATS) was on an earlier revision, before read_own/cpu_run, the DXR-legal prebuild query and the BLAS header asks. The default-layout smoke installs no hook (view_windows() is false), and the unit tests check only range arithmetic. Rerun the 16-window session at 4082300b and post its acceleration-structure builds line and device-removal count.
  2. CPU cost per build is unmeasured. Every top-level build now reads up to 65536 instance descriptions or pointers on the recording thread (bvh_builder.rs ~507-565): one ReadProcessMemory per 4 KiB chunk, plus one 8-byte read_own per pointer target for ARRAY_OF_POINTERS, and cpu_run takes the kernelx::mirrors lock per tile. Every batch item also calls the DLL's prebuild query. The earlier run logged about 4000 builds per 2 s. Measure the time spent in the hooks on the 16-window layout, or batch the pointer-target reads.
  3. 1339 lines in one PR. This is over the ~800-line limit; a reason is given (about half is tests). The split from the earlier review would still work: first the ABI structs, ranges_of_build and their tests, then the hooks with the resolver.rs and view_want wiring.

Nit

  1. Doc comment names a module that is not on main. bvh_builder.rs ~5-6 says calls forward "to d3d12x::bvh_builder's inner sparse-memory hook when XCL_SPARSE_LAZY=1". That module exists only in open #3521. Add "(with #3521)" or drop it.
  2. Suite counts come from another commit. Tested gives 3006/0/52 from 1f287a92 (the top of a stack). Only the 12 bvh_builder tests ran at this head.
Checked and fine
  • Earlier finding fixed: the PR now holds only its own commit on main 5eaadb54, with no rebased copies of #3517, #3349, #3521 or #3522
  • Earlier finding fixed: an update's scratch is no longer dropped when the query returns 0 (resolve_scratch_bytes falls back to scratch.max(SCRATCH_GUESS), and the query swaps PERFORM_UPDATE for ALLOW_UPDATE), and perform_update_queries_dxr_legal_flags_without_stale_cache covers it
  • Earlier finding fixed: GetRaytracingAccelerationStructurePrebuildInfo is looked up in the mapped module (record_prebuild_from_module), ordinal imports included, with a test
  • Earlier finding fixed: ARRAY_OF_POINTERS top levels now ask for the 64-byte instance descriptions behind the pointers and the referenced bottom-level headers
  • read_gpu_bytes translates tile by tile when cpu_run fails and cannot fault (ReadProcessMemory); the cross-tile test covers both the split read and a failing read_own
  • The default 4-window layout is unchanged: wrap returns the real address when view_windows() is false
  • The ABI sizes, offsets and mangled names match; both import resolution and GetProcAddress are hooked; there is no textual conflict with #3521, which intercepts in resolve_export_of_mapped_inner, so calls chain outer then inner
How this was tested
  • Merged onto main 078358a0, then cargo build --workspace and cargo test --workspace --no-fail-fast -- --test-threads=4.
  • The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar).
  • scripts/smoke.ps1: 60 s of a retail title on main 078358a0 and on this merge; presents per 2 s at the end: 60 60 60.
  • Title run: the release build of this merge launched the retail title with XCL_RUN_SECONDS=300 and scripted A presses counted from the first frame (XCL_PRESS_BASE=frame, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7383431915 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3662#issuecomment-7383431915). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T15:36:33Z. --- merge-check base: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a head: 4082300ba84ea77630ac1050264b4d07fc4bb5a3 merge: clean build: ok tests: 3018 passed, 0 failed, 52 ignored; 28 skipped, the same as on main review: 3 medium, 2 nits (below) performance: 60 s smoke run: 1669 → 1657 frames (99 % of main), peak commit 17577 → 17695 MB, no device removal, no crash title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 225 s there, 0 device removals, 0 crashes, 3.4 presents/s; run with `XCL_SKIP_CS=95cc13288a27a96e` (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590) verdict: safe to merge: no blocking finding (the points below are medium or nits), the suite passes and the smoke run is clean hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 --- **In short:** Hooks XboxBvhBuilder.dll's BuildBatched2X and RehydrateBatched2X (named, by ordinal and through GetProcAddress) on the 16-window layout and asks view_want for every range a build names, whole, before forwarding to the DLL. It is now one commit on main, and the earlier review's sizing, prebuild-lookup and instance findings are fixed. Nothing blocks; still open are the missing 16-window run at this head and the unmeasured CPU cost per build. #### Medium 1. **No 16-window run at this head.** The only run that reaches the hooks (180 s, XCL_VIEW_STATS) was on an earlier revision, before read_own/cpu_run, the DXR-legal prebuild query and the BLAS header asks. The default-layout smoke installs no hook (view_windows() is false), and the unit tests check only range arithmetic. Rerun the 16-window session at 4082300b and post its acceleration-structure builds line and device-removal count. 2. **CPU cost per build is unmeasured.** Every top-level build now reads up to 65536 instance descriptions or pointers on the recording thread (bvh_builder.rs ~507-565): one ReadProcessMemory per 4 KiB chunk, plus one 8-byte read_own per pointer target for ARRAY_OF_POINTERS, and cpu_run takes the kernelx::mirrors lock per tile. Every batch item also calls the DLL's prebuild query. The earlier run logged about 4000 builds per 2 s. Measure the time spent in the hooks on the 16-window layout, or batch the pointer-target reads. 3. **1339 lines in one PR.** This is over the ~800-line limit; a reason is given (about half is tests). The split from the earlier review would still work: first the ABI structs, ranges_of_build and their tests, then the hooks with the resolver.rs and view_want wiring. #### Nit 4. **Doc comment names a module that is not on main.** bvh_builder.rs ~5-6 says calls forward "to d3d12x::bvh_builder's inner sparse-memory hook when XCL_SPARSE_LAZY=1". That module exists only in open #3521. Add "(with #3521)" or drop it. 5. **Suite counts come from another commit.** Tested gives 3006/0/52 from 1f287a92 (the top of a stack). Only the 12 bvh_builder tests ran at this head. <details><summary>Checked and fine</summary> - Earlier finding fixed: the PR now holds only its own commit on main 5eaadb54, with no rebased copies of #3517, #3349, #3521 or #3522 - Earlier finding fixed: an update's scratch is no longer dropped when the query returns 0 (resolve_scratch_bytes falls back to scratch.max(SCRATCH_GUESS), and the query swaps PERFORM_UPDATE for ALLOW_UPDATE), and perform_update_queries_dxr_legal_flags_without_stale_cache covers it - Earlier finding fixed: GetRaytracingAccelerationStructurePrebuildInfo is looked up in the mapped module (record_prebuild_from_module), ordinal imports included, with a test - Earlier finding fixed: ARRAY_OF_POINTERS top levels now ask for the 64-byte instance descriptions behind the pointers and the referenced bottom-level headers - read_gpu_bytes translates tile by tile when cpu_run fails and cannot fault (ReadProcessMemory); the cross-tile test covers both the split read and a failing read_own - The default 4-window layout is unchanged: wrap returns the real address when view_windows() is false - The ABI sizes, offsets and mangled names match; both import resolution and GetProcAddress are hooked; there is no textual conflict with #3521, which intercepts in resolve_export_of_mapped_inner, so calls chain outer then inner </details> <details><summary>How this was tested</summary> - Merged onto main `078358a0`, then `cargo build --workspace` and `cargo test --workspace --no-fail-fast -- --test-threads=4`. - The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar). - `scripts/smoke.ps1`: 60 s of a retail title on main `078358a0` and on this merge; presents per 2 s at the end: 60 60 60. - Title run: the release build of this merge launched the retail title with `XCL_RUN_SECONDS=300` and scripted A presses counted from the first frame (`XCL_PRESS_BASE=frame`, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3662:upstream-pr/3662'
git switch 'upstream-pr/3662'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3662'
git switch 'upstream-pr/3662'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3662'
git switch 'upstream-pr/3662'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3662'
git switch 'main'
git merge --squash 'upstream-pr/3662'
git switch 'main'
git merge --ff-only 'upstream-pr/3662'
git switch 'main'
git merge 'upstream-pr/3662'
git push origin 'main'
Sign in to join this conversation.
No reviewers
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
xcl-dev/xcl!3662
No description provided.