Files
mandy/d3d12/docs/fork-ray-tracing.md
Callimann8 3a38a050d8 d3d12 hwrt: review addendum (one capability gate, AABB strides, TLAS layout, copy modes)
- One gate for both halves: supported() also asks for shader model 6.6, and the translator is
  told inline ray tracing runs (set_host_inline_rt) only once the DXR manager is made.
- AABB geometries take stride 0 (packed 24-byte boxes) and multiples of 8 of 24 or more, as
  DXR does; others are refused.
- A TLAS of instances by pointer (ARRAY_OF_POINTERS) is not built: the remap reads 64-byte
  instances in a row.
- Structure copies other than clone and compact are not done (said once).
- A TLAS clone points the heap slots that view the destination at the shared structure.
- The points not fixed here are listed in fork-ray-tracing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:40:30 +01:00

235 lines
16 KiB
Markdown

# Ray tracing in this fork: what the title does and what has been built
Status, 2026-11-25, midday: **with `LEONIDA_BVH_BUILDER=1` rooms get their
indirect light** (runs light-10, light-11, n19), for some 40 ms more of the
card's time a frame (the dorm: 75 of 90 ms busy against 34 of 64). Off by
default. **`LEONIDA_AMBIENT=1`** puts an estimate of that light in its place
for next to nothing (below).
## On the card's ray-tracing hardware (`LEONIDA_HW_RT=1`, off: a trial)
In place of `LEONIDA_BVH_BUILDER=1`, on a card with DXR 1.1 (on any other the switch does nothing: the title keeps its
own `XboxBvhBuilder.dll`, the translator its software walk, and the log says so; `-HardwareRT` of the play scripts, the launcher's
"Hardware ray tracing" box, or the F1 menu's HARDWARE RAY TRACING (TRIAL)). Taken from
trustno1-coder/VIctory-NVIDIA (its #3706; from Leslie-d-a/VIctory-NVIDIA-HWRT 61e389e0 and 5f55bca8, original by
dakisback2 ecc49d5b and 72f8316a), GPL-3.0, and fitted to this tree:
- the title's `XboxBvhBuilder.dll` is ours (`leonida-hle` `xboxbvh.rs`): its calls become host DXR 1.1 bottom and
top levels keyed by the console structure's address (`leonida-gpu` `hwrt.rs`), with refits, a scratch pool, the
instances' addresses remapped on the card, and eviction when the title frees the memory. The title's own builder
programs do not run; with both switches set, the hardware path is kept and the builder is turned off. The
structure work runs at its place in the title's list (`list::external`; with `LEONIDA_THIN=1` when the list's
calls are translated).
- the translator lifts the traversal loops of the trace programs to `RayQuery` (`leonida-shader`
`emit/rayquery.rs`) where every value a loop leaves behind is accounted for. A loop that is not is left as it
was, and its node test misses every node (`emit/intersect.rs` `bvh_miss`): the console structures are never
written, so a walk of them would read memory nobody filled. A program in the paired form (one host lane for two
console lanes) is not lifted. The structure is bound as root SRV `t230..t241`.
- the light stand-in (`LEONIDA_AMBIENT`) stands aside and the passes left out without structures run, as with the
title's builder. The play script leaves DLSS frame generation off with it, as with `-RayTracing`.
- the log has, per ray-tracing program, "ray queries lifted N of M ..., fell back: <reason>", and every 5 s
"ray queries: lifted shaders N, partly N, fell back N (software)" and "hardware RT: BLAS live ...".
`LEONIDA_HW_RT_REFIT=0` builds dynamic bottom levels whole every time; `LEONIDA_HW_RT_WHY=1` (`=2`: more) logs why
a loop is not lifted; `LEONIDA_HW_RT_LIFT=0` keeps the structure work and lifts no loop (every ray misses).
`LEONIDA_HW_RT_COPY_BACK=1` copies every shader write back to title memory, as VIctory-NVIDIA does with it (there,
with writes left on the card, the lighting swapped between two states). Off here: with it on, textures stretched
and flickered and the frame spent 30 to 45 ms copying back (below).
Gaps, as written:
- Only triangle candidates are committed: a candidate of an AABB (procedural) geometry is skipped, so such geometry
is never hit (`emit/rayquery.rs`, the `CandidateType` guard).
- Structure copies of a mode other than clone and compact (serialize, deserialize, visualization decode) are not
done; the log says so once. A TLAS of instances by pointer (`ARRAY_OF_POINTERS`) is not built either.
- Not spec-clean yet, from review: the compacted-size answer is written with `WriteBufferImmediate` into the
title's copy without a transition to `COPY_DEST`; a dynamic bottom level is refitted when its index buffer's
address is the same, though DXR forbids an update whose indices changed; the remap and sanitize dispatches have
no 65,535-group cap; `rehydrate_cpu` and `validate_rehydrate` answer `S_OK` without doing anything; prebuild
info is asked with null geometry pointers; instance transforms are not checked for non-finite values.
- The memory budget covers bottom levels only (a tenth of the card's budget, 256 MB to 1.5 GB); top levels,
scratch and the remap tables come on top.
- The ray-query opcodes are pinned against `dxc` (`rayquery_tests.rs` `the_ray_query_opcodes_are_dxils`), but no
test dispatches a ray: what a lifted loop returns is checked only by eye in the game.
Measured once, by the person who asked for the port (RTX 4070 laptop, 12 GB, Series X profile, no frame
generation, 2026-12-01, the frame log's lines): 22 to 25 frames a second with 3 MB a frame copied back, 14 of 14
ray-tracing programs in use wholly lifted, about 4,900 bottom levels and 5 top levels alive in 650 MB. The same
save with `-RayTracing` (the title's builder and the software walk): 6 frames a second, 104 to 118 ms of the card
a frame. Over the 64 ray-tracing programs of one `known-shaders.bin` (the ignored test
`the_local_shader_cache_lifts_its_ray_queries`): 56 wholly lifted, 6 partly, 2 that do not translate without it
either, none lifted that does not validate; loops 76 of 76 (64-bit nodes) and 299 of 315 (32-bit).
That run ended after six minutes with the device removed, the card's memory full (10,989 MB in use of a budget of
10,793 MB, 1,095 MB of it bottom levels, and the PC with 125 MB left to commit): the Series X profile fills this
12 GB card without the structures too.
Not measured: other cards, AMD, the Series S profile, a long session, and the picture against the builder's.
## What the title does
The title's indirect light (probes, bounce, reflections) and the
shadows of its lamps and sun are ray traced. Without them, anything the sun
does not hit directly is black: interiors, the shadowed side of a face, rooms
lit only by lamps.
The title does not use a ray-tracing API:
- Traversal is ordinary compute-shader code: a per-thread stack in shared
memory, and loads through raw 40-bit addresses of title memory.
- The static world's acceleration structures ship pre-built in the title's
data, in the console GPU's native node format (64-byte nodes: box nodes with
four children and 16-bit float bounds, 128-byte box nodes with 32-bit float
bounds, triangle nodes, instance nodes). They are unpacked on the GPU.
- A set of builder programs (from the title's `XboxBvhBuilder.dll`, 52 compute
programs) builds and refits the dynamic structures on the GPU every frame.
- Only the per-node test is hardware: the instructions
`image_bvh64_intersect_ray` and `image_bvh_intersect_ray`. One call tests a
ray against a box node's four children (returning the hit children, nearest
first) or against a triangle node (returning the intersection's numerator,
denominator and barycentric numerators).
So mapping this onto the host's own ray tracing (DXR) is not practical: the
layer would have to know the geometry behind structures the title never
describes to it, and the traversal loops live in 64 of the title's own
programs. This fork runs the title's builder and traversal as translated
shaders and emulates the one instruction.
## What this fork adds
1. **The builder programs translate** (all 52, with host pipelines on the RX
7900 XTX; the title creates 53 such pipelines). They pass buffer addresses in a spilled parameter table
rather than in descriptors. Added: the spilled user-data table, root
unordered-access views (translator and host binding), byte and 16-bit buffer
accesses, and several control-flow shapes.
2. **Title memory by raw address from shaders.** A directory with one entry per
64 KiB of title address space leads a shader to the layer's host copy of
that memory; loads, stores, atomic add/sub and float min/max go through it.
Before a dispatch the host makes ready the memory its root views and root
constants name.
3. **The ray test, emulated in DXIL.** Four slab tests and a sorting network
for box nodes; a watertight ray/triangle test for triangle nodes; both forms
of the instruction. A plain Rust reference lives in
`crates/leonida-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU
over 311 ray/node cases and compare with the reference bit for bit.
4. **The trace and shading programs translate** (59 of 64 trace programs, and
the irradiance-cache shading program). This needed lane masks treated as
plain numbers on some paths, and exact forms for programs written for
64-lane waves running on a GPU with 32-lane waves.
5. **A safety rule on the host side.** The builder's stages run only while
every builder pipeline the title has created has a host pipeline; otherwise
none run (`LEONIDA_BVH_BUILDER=1` asks for it; `LEONIDA_BVH_QUARANTINE=1`
also keeps the builder's stores out of title memory, for a first test). A
partly working builder wrote garbage bounds into title memory and crashed
the title.
## The structures (from dumps of the arenas, `LEONIDA_MEMORY_DUMP`)
- Header, 64 bytes: dword 0 the version 6 in the low half and marks in the high
(0x8000 bottom level, 0x4 compacted, 0x2 rehydrated, 0x100 still packed),
dword 1 the size in 64-byte nodes, 3 the number of elements, 4-9 the bounds,
10 the offset of the box nodes, 12 the root's node pointer, 13 the offset of
the elements, 14 the offset of the parent table (from the header; the static
ones' index counts the leaves too, so it is negative).
- An instance is 128 bytes at the top level's offset 13: a 3x4 matrix in dwords
0-11, id and mask, flags, the root pointer (bit 30 set for static ones), the
bottom level's address in 256-byte units.
- The static world's structures are shipped **packed ("dehydrated")** and
unpacked in place, once, by DecompressHeader, Box32/Box16Rehydration and
LeafRehydration when they have been streamed in (3,000 in the opening).
- Dynamic ones are built, their compacted size read back by the title from a
small buffer, and copied to a place of that size.
## How title memory by address is held (`memory.rs`)
Pages of 64 KiB in arenas on the card, whole title buffers in their own copies,
pages with small title buffers as windows of title memory. The module's
comment has the rules. In short: what the builder stores stays on the card
(only small title buffers it was given to write come back); a packed structure
goes up whole when the builder comes to it; title buffers take its stores only
after it was given them as an unordered access view.
| variable | does |
|---|---|
| `LEONIDA_BVH_BUILDER=1` | the builder's stages run |
| `LEONIDA_BVH_FENCES=0` | no fences around the builder's buffer atomics (beloooo's 72e748ea has them too) |
| `LEONIDA_BVH_SIZES_WAIT=1` | submissions that ask for structures' sizes are waited for (off: no help, slow) |
| `LEONIDA_BVH_BOUNDS=0` | the builder's accesses are not bounded |
| `LEONIDA_BVH_TRACE=1` | logs what sizes are asked, when they came, and the copies (diagnostics) |
| `LEONIDA_BVH_QUARANTINE=1` | nothing it stores comes back to title memory |
| `LEONIDA_MEMORY_CARD_MB` | the most of it on the card (4096) |
| `LEONIDA_MEMORY_DUMP=<folder>` | a file `go` there writes the arenas out (diagnostics) |
| `LEONIDA_UPLOAD_LOW=0`, `LEONIDA_LENT_HEAP=0` | lists' upload memory above 2^40, no view heap for lists without one, as before |
Every ten seconds the log has a line "title memory by address: ..." with pages,
dispatches, faults and what came.
## Known gaps
- Dynamic structures overlap each other (8 of 65 good in run light-10, 48 of
275 in light-15). Part of the cause, run light-11's trace (`LEONIDA_BVH_TRACE=1`): the title asks for a new
structure's compacted size, reads it one or two frames later without looking
whether it is there, takes memory of that size and has the structure copied
into it. Our submissions land up to two frames late; the title read what the
slot held before, another structure's size, and the copy wrote over the
neighbours. Waiting for a submission that asks (`LEONIDA_BVH_SIZES_WAIT=1`)
did not mend it and costs some 20 ms a frame (light-15): the title asks in
every frame, and what it read was as old as before. Open.
- What a structure that was written over says of its size sent the builder's
copy of it through gigabytes of other structures; bounded now
(`LEONIDA_BVH_BOUNDS`). Pages touched that are not there: 2,500 a frame
before, 90 after (the dorm).
- The card's time in the dorm with the builder (timing run light-13, title's
commands 84 ms): `CopyForBVHUpdate` 13.3 ms in 63 dispatches (before the
bound), traces 24 ms (`RaytraceVBuffer` 7.9, screen probes 6.4, irradiance
cache 3.5, primary probes 2.3, shadows 1.6).
- Captures made on 2026-11-25 (builder on or off) hang the card in a replay
(cause unknown; do not try).
- Five shadow-mask trace programs do not translate (a structure's address out
of a descriptor picked from the heap by a computed index: the host would have
to give a table of addresses by slot). The title did not create them in any
run so far.
- An access to a page that is not there is lost (a read gives zero, a store is
dropped).
- Not publicly documented, and assumed: the instruction's rounding, the order
of two boxes entered at the same distance, and the result for a ray exactly
through an edge.
## Without rays: the stand-in (`crates/leonida-gpu/src/ambient.rs`)
Without structures every ray misses. The title's program that resolves the
diffuse light of its screen probes (`CS_ScreenProbes_TemporalResolve_*`, list
184 of a frame) then leaves the sky's light outdoors, nothing indoors, and in
blocks of tiles what the probes' memory held. `LEONIDA_AMBIENT=<share>` raises
it to an estimate right after that program: the title keeps, for its own screen
traces, the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`,
1280x720, the frame before); its mean in 64x36 cells is gathered at 160x90
points, each cell weighted by the share of the surroundings it covers, as a
directional value; each pixel takes it between the points by depth, with its
normal and a shade in creases. So level and tint follow the hour, the room and
its lamps. What the program left counts up to four times the estimate.
Where it can be put, and the crease shade, are beloooo's (VIctory-Belobug-AMD
06031237, 4f45ab88, cd9f78ce); `LEONIDA_AMBIENT=constant:<level>` is that
fork's constant.
| variable | does |
|---|---|
| `LEONIDA_AMBIENT=<share>` | the estimate, 1 all of it (unset: the title's own) |
| `LEONIDA_AMBIENT=constant:<level>` | the same light everywhere |
| `LEONIDA_AMBIENT_SHADE=<strength>,<metres>` | the creases (1,0.6) |
| `LEONIDA_AMBIENT_AIR=<multiple>` | what the air scatters is bounded by a multiple of the light around (off: the brown veil in the day room stays with it, light-14) |
| `LEONIDA_AMBIENT_TRUE_DEPTH=1` | the resolve's depth is looked for at table offset 688 first (off: 464 alone). edsuuu/VI-BR-PORT 783b2e1 read off `CS_ScreenProbes_TemporalResolve_ReflectiveCaustics` (`34fb51b8a0312e82`) that 464 is its stencil plane and 688 its depth. Not tried in the game |
| (always) | where the view at 464 is the stencil plane, the depth plane of the same texture that the same dispatch reads elsewhere is taken (TaynanGT's 292adb5a8 in Fayberr/Victory-United). Before it, every run of 2026-11-27 07:27 on logged "missing depth SRV" for the resolve and never ran its stand-in: rooms lit by bounced light (Jason's house, every interior away from windows and lamps) kept the title's ray-less black |
| `LEONIDA_AMBIENT_FLOOR=<level>` | the estimate is at least that warm fill, shaded in creases (unset or 0: no floor). DoubleGhosty/cool_fox 98c3333 (`VICTORY_AMBIENT_FLOOR`, 0.4) |
It is off while the builder runs.
## Where to look
- `crates/leonida-shader/src/bvh.rs`: the reference for the node test.
- `crates/leonida-shader/src/emit/lower.rs`: the lowering of the two
instructions and of memory by address (`Lower::memory`).
- `crates/leonida-shader/src/resource.rs`: address tracking for descriptors
and raw addresses.
- `crates/leonida-gpu/src/pipeline.rs`, `draw.rs`: the builder rule and the
host side of root views and title memory.