GPU BVH: audit box16/box32 node intersection for inf/NaN ray directions and zero extents #1559

Open
github-bot wants to merge 1 commit from github-bot/gh-1559 into main AGit
Owner

@⁠slopgobblercobbler on GitHub · 2026-11-24 17:39 UTC · original
slopgobblercobbler:fix/bvh-node-intersection → main · +142 −3 · 2 files · 1 commits · open

Summary

Audits bounding volume hierarchy (BVH) node intersection in crates/xcl/src/gpu/bvh.rs and HLSL recompiler emission in crates/xcl/src/gpu/recomp/emit.rs for NaN/infinite ray parameters, degenerate directions, and zero-extent bounds:

  1. Upfront input validation & edge-case rejection in intersect_node:
    • Rejects non-finite/NaN ray origins (o), non-finite/NaN ray directions (d), NaN inverse ray directions (inv), all-zero ray directions (d == [0, 0, 0]), and negative/NaN ray extents (!(tmax >= 0.0)).
    • Prevents rays with NaN direction/origin from falsely matching all child boxes due to IEEE NaN.min(NaN) / max propagation leaving slab interval [a, b] as [-inf, inf].
    • Prevents rays with negative tmax from falsely matching enclosing boxes with negative t.
  2. Zero inverse direction handling (d = inf):
    • Unified inv[axis] == 0.0 with inv[axis].is_infinite(): rays with zero inverse direction (infinite velocity) only intersect if the origin already lies within the slab interval [mn, mx], rather than collapsing (mn - o) * 0.0 to 0.0 and declaring a false entry hit at t = 0.0.
  3. Zero-extent node and ray bounds conformance:
    • Validated zero-extent boxes (planar/2D boxes where mn[axis] == mx[axis], line segment boxes, and point boxes) across box32 and box16 half-precision formats.
    • Enforced zero ray extents (tmax == 0.0): hits only when ray origin o lies within or on the box boundary, and misses otherwise.
  4. HLSL recompiler parity (crates/xcl/src/gpu/recomp/emit.rs):
    • Mirrored upfront validation (any(isnan(o)), any(isinf(o)), any(isnan(d)), any(isinf(d)), any(isnan(inv)), all(d == 0.0f), isnan(tmax), tmax < 0.0f) and unified zero/infinite inverse direction handling in HLSL bvh_intersect.
  5. Unit tests:
    • Added box_intersection_nan_inf_ray_directions_and_bounds and box_intersection_zero_extents_box32_and_box16 in bvh.rs.

Changes

  • crates/xcl/src/gpu/bvh.rs: upfront ray parameter validation, infinite direction handling, and zero-extent bounds.
  • crates/xcl/src/gpu/recomp/emit.rs: HLSL emulation parity for ray intersection validation.

Tested

  • Windows 11 x64, Rust MSVC stable.
  • cargo test -p xcl -- bvh: 12 passed, 0 failed.
  • cargo test -p xcl --test console_dlls_e2e: 7 passed, 0 failed.
  • Clean diff: zero trailing whitespace, clean rebase on latest upstream/main, GPL-2.0-only compliant, zero retail game data or keys.

Not Tested

  • Real-time hardware DXR 1.1 inline ray tracing under high ray saturation.

AI Use

Co-Authored-By: Claude Code (Claude Opus 5.5) / Gemini Antigravity

**@⁠slopgobblercobbler** on GitHub · 2026-11-24 17:39 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559) `slopgobblercobbler:fix/bvh-node-intersection` → `main` · +142 −3 · 2 files · 1 commits · open ## Summary Audits bounding volume hierarchy (BVH) node intersection in `crates/xcl/src/gpu/bvh.rs` and HLSL recompiler emission in `crates/xcl/src/gpu/recomp/emit.rs` for NaN/infinite ray parameters, degenerate directions, and zero-extent bounds: 1. **Upfront input validation & edge-case rejection in `intersect_node`**: - Rejects non-finite/NaN ray origins (`o`), non-finite/NaN ray directions (`d`), NaN inverse ray directions (`inv`), all-zero ray directions (`d == [0, 0, 0]`), and negative/NaN ray extents (`!(tmax >= 0.0)`). - Prevents rays with NaN direction/origin from falsely matching all child boxes due to IEEE `NaN.min(NaN)` / `max` propagation leaving slab interval `[a, b]` as `[-inf, inf]`. - Prevents rays with negative `tmax` from falsely matching enclosing boxes with negative `t`. 2. **Zero inverse direction handling (d = inf)**: - Unified `inv[axis] == 0.0` with `inv[axis].is_infinite()`: rays with zero inverse direction (infinite velocity) only intersect if the origin already lies within the slab interval `[mn, mx]`, rather than collapsing `(mn - o) * 0.0` to `0.0` and declaring a false entry hit at `t = 0.0`. 3. **Zero-extent node and ray bounds conformance**: - Validated zero-extent boxes (planar/2D boxes where `mn[axis] == mx[axis]`, line segment boxes, and point boxes) across box32 and box16 half-precision formats. - Enforced zero ray extents (`tmax == 0.0`): hits only when ray origin `o` lies within or on the box boundary, and misses otherwise. 4. **HLSL recompiler parity (`crates/xcl/src/gpu/recomp/emit.rs`)**: - Mirrored upfront validation (`any(isnan(o))`, `any(isinf(o))`, `any(isnan(d))`, `any(isinf(d))`, `any(isnan(inv))`, `all(d == 0.0f)`, `isnan(tmax)`, `tmax < 0.0f`) and unified zero/infinite inverse direction handling in HLSL `bvh_intersect`. 5. **Unit tests**: - Added `box_intersection_nan_inf_ray_directions_and_bounds` and `box_intersection_zero_extents_box32_and_box16` in `bvh.rs`. ## Changes - `crates/xcl/src/gpu/bvh.rs`: upfront ray parameter validation, infinite direction handling, and zero-extent bounds. - `crates/xcl/src/gpu/recomp/emit.rs`: HLSL emulation parity for ray intersection validation. ## Tested - Windows 11 x64, Rust MSVC stable. - `cargo test -p xcl -- bvh`: 12 passed, 0 failed. - `cargo test -p xcl --test console_dlls_e2e`: 7 passed, 0 failed. - Clean diff: zero trailing whitespace, clean rebase on latest `upstream/main`, GPL-2.0-only compliant, zero retail game data or keys. ## Not Tested - Real-time hardware DXR 1.1 inline ray tracing under high ray saturation. ## AI Use Co-Authored-By: Claude Code (Claude Opus 5.5) / Gemini Antigravity
- crates/xcl/src/gpu/bvh.rs: reject non-finite/NaN ray origin, non-finite/NaN ray direction, NaN inverse direction, all-zero ray direction, and negative/NaN tmax upfront in box16/box32 intersect_node.

- Unify zero inverse direction (d = inf) with infinite inverse direction (d = 0) to avoid false hits when ray origin is outside the slab.

- crates/xcl/src/gpu/recomp/emit.rs: mirror the validation and zero-inverse handling in HLSL bvh_intersect.

- Add comprehensive unit tests in bvh.rs covering NaN/Inf ray directions and origins, zero/negative extents, point boxes, flat planar boxes, line segment boxes, and half-precision box16 edge cases.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:57:31 +00:00
Author
Owner

@⁠Diskuss on GitHub · 2026-11-24 17:48 UTC · original

Tested on AMD Radeon RX 9070 XT (RDNA4) at ca5f6a5e4345eabdbddc48e4513f0fecf3112031

AMD Radeon RX 9070 XT (RDNA4), driver 32.0.32015.7029; Ryzen 7 5700X3D; 32 GB RAM; Windows 11 Pro build 26300.9974; Rust 1.100.0 x86_64-pc-windows-msvc; DXC 1.9.2602.17; debug build.

Tested:

  • Bare PR head (a single commit on top of current main 9e3831e, so no local merge was needed).
  • cargo build --workspace: OK.
  • cargo test --workspace --no-fail-fast -- --test-threads=4: 778 passed, 0 failed, 41 ignored.
  • The PR's new tests, each run 5 times with cargo test -p xcl --lib <name> -- --test-threads=1: box_intersection_nan_inf_ray_directions_and_bounds 5/5 passed, box_intersection_zero_extents_box32_and_box16 5/5 passed (1 passed each run).
  • Device removal (DXGI_ERROR_DEVICE_REMOVED): none. 1 SKIPPED line printed (heap_window_out_of_memory_falls_back_to_the_switch_form: no heap windows, same on main); 2 debug-layer tests skip silently, no Graphics Tools installed.
  • Baseline, main 9e3831e on the same machine: 776 passed, 0 failed, 41 ignored. The +2 is the two new tests.

Not tested: retail title / scripts/smoke.ps1 (no game files), release build.

Report written by Claude Code (Claude Sonnet 5.5) from a real run on this machine.

**@⁠Diskuss** on GitHub · 2026-11-24 17:48 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#issuecomment-7139727384) **Tested on AMD Radeon RX 9070 XT (RDNA4) at `ca5f6a5e4345eabdbddc48e4513f0fecf3112031`** AMD Radeon RX 9070 XT (RDNA4), driver 32.0.32015.7029; Ryzen 7 5700X3D; 32 GB RAM; Windows 11 Pro build 26300.9974; Rust 1.100.0 x86_64-pc-windows-msvc; DXC 1.9.2602.17; debug build. **Tested**: - Bare PR head (a single commit on top of current main 9e3831e, so no local merge was needed). - `cargo build --workspace`: OK. - `cargo test --workspace --no-fail-fast -- --test-threads=4`: **778 passed, 0 failed, 41 ignored**. - The PR's new tests, each run 5 times with `cargo test -p xcl --lib <name> -- --test-threads=1`: `box_intersection_nan_inf_ray_directions_and_bounds` 5/5 passed, `box_intersection_zero_extents_box32_and_box16` 5/5 passed (1 passed each run). - Device removal (DXGI_ERROR_DEVICE_REMOVED): none. 1 SKIPPED line printed (`heap_window_out_of_memory_falls_back_to_the_switch_form: no heap windows`, same on main); 2 debug-layer tests skip silently, no Graphics Tools installed. - Baseline, main 9e3831e on the same machine: 776 passed, 0 failed, 41 ignored. The +2 is the two new tests. **Not tested**: retail title / `scripts/smoke.ps1` (no game files), release build. Report written by Claude Code (Claude Sonnet 5.5) from a real run on this machine.
Author
Owner

@⁠Anon64 on GitHub · 2026-11-24 17:54 UTC · original

Regression run for this PR: head ca5f6a5, based on main 9e3831e. RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, XCL_NETWORK=0, A pressed every 4 s from 20 s, scripts/smoke.ps1 on a retail title for 60 s.

main 9e3831e:

xcl-smoke v1
commit: 9e3831e1f570d3646e53ab753b19ec07eb8f1485
gpu: NVIDIA GeForce RTX 3060
title: retail-title
seconds: 60
exit: 0x0
frames shown: 1601 (PresentX 1602)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 72801 MB

this PR:

xcl-smoke v1
commit: ca5f6a5e4345eabdbddc48e4513f0fecf3112031
gpu: NVIDIA GeForce RTX 3060
title: retail-title
seconds: 60
exit: 0x0
frames shown: 1521 (PresentX 1521)
presents per 2 s (last 3): 38 42 37
device removals: 0
crashes: 0
peak commit: 21195 MB

No device removals or crashes; 95 % of main's frames, 29 % of its peak commit.

Peak commit on this machine is mostly the pipeline preload's DXC compiles (#1035) and varies a lot from run to run (21–92 GB with the same build), so it says little about this PR.

Not tested: the whole suite; whether the title reaches the changed code in these 60 s.

Written with Claude Code (Claude Opus 5.5) from runs on this machine.

**@⁠Anon64** on GitHub · 2026-11-24 17:54 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#issuecomment-7139872070) Regression run for this PR: head `ca5f6a5`, based on `main` `9e3831e`. RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, `XCL_NETWORK=0`, A pressed every 4 s from 20 s, `scripts/smoke.ps1` on a retail title for 60 s. main `9e3831e`: ``` xcl-smoke v1 commit: 9e3831e1f570d3646e53ab753b19ec07eb8f1485 gpu: NVIDIA GeForce RTX 3060 title: retail-title seconds: 60 exit: 0x0 frames shown: 1601 (PresentX 1602) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 72801 MB ``` this PR: ``` xcl-smoke v1 commit: ca5f6a5e4345eabdbddc48e4513f0fecf3112031 gpu: NVIDIA GeForce RTX 3060 title: retail-title seconds: 60 exit: 0x0 frames shown: 1521 (PresentX 1521) presents per 2 s (last 3): 38 42 37 device removals: 0 crashes: 0 peak commit: 21195 MB ``` No device removals or crashes; 95 % of main's frames, 29 % of its peak commit. Peak commit on this machine is mostly the pipeline preload's DXC compiles (#1035) and varies a lot from run to run (21–92 GB with the same build), so it says little about this PR. **Not tested:** the whole suite; whether the title reaches the changed code in these 60 s. Written with Claude Code (Claude Opus 5.5) from runs on this machine.
Author
Owner

@⁠DavidM1911 on GitHub · 2026-11-24 19:32 UTC · original

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~22 ignored. (Intermittent single-test flake under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified main.)

Thanks!

**@⁠DavidM1911** on GitHub · 2026-11-24 19:32 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#issuecomment-7142245097) Verification on RTX 3060 Ti (Windows 11), branch merged with current `main`: - `cargo test -p xcl --lib`: all passed, 0 failed, ~22 ignored. (Intermittent single-test flake under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified `main`.) Thanks!
Author
Owner

@⁠Melow-code on GitHub · 2026-11-24 23:02 UTC · original

The NaN/inf guards in intersect_node are correct in isolation, but Anon64 reports a 37-42 FPS regression from 60 FPS on a retail title. That needs investigation before merge.

Likely cause: the upfront if !origin.is_finite() || !dir.is_finite() || inv_dir.has_nan() || dir == Vec3::ZERO || tmax < 0.0 || tmax.is_nan() branch adds divergent control flow to the hottest loop in RT. On RDNA2/3, a branch that is almost never taken still costs the wavefront a few cycles per traversal step because the SIMD must evaluate both paths when any lane diverges.

Suggested fix: instead of an upfront branch, handle the edge cases in the slab math itself. For example, f32::min/f32::max with a NaN-aware clamp after the slab computation catches the same cases without a branch. This is what PR #1322 does for the NaN-ray case alone — extend it.

If performance is acceptable on the author's hardware, the reviewer data from Anon64 still suggests a problem on different configs. At minimum, the author should run the same 60-second smoke test to compare.

**@⁠Melow-code** on GitHub · 2026-11-24 23:02 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#issuecomment-7146940814) The NaN/inf guards in `intersect_node` are correct in isolation, but Anon64 reports a 37-42 FPS regression from 60 FPS on a retail title. That needs investigation before merge. Likely cause: the upfront `if !origin.is_finite() || !dir.is_finite() || inv_dir.has_nan() || dir == Vec3::ZERO || tmax < 0.0 || tmax.is_nan()` branch adds divergent control flow to the hottest loop in RT. On RDNA2/3, a branch that is almost never taken still costs the wavefront a few cycles per traversal step because the SIMD must evaluate both paths when any lane diverges. Suggested fix: instead of an upfront branch, handle the edge cases in the slab math itself. For example, `f32::min`/`f32::max` with a NaN-aware clamp after the slab computation catches the same cases without a branch. This is what PR #1322 does for the NaN-ray case alone — extend it. If performance is acceptable on the author's hardware, the reviewer data from Anon64 still suggests a problem on different configs. At minimum, the author should run the same 60-second smoke test to compare.
Author
Owner

@⁠Melow-code on GitHub · 2026-11-24 23:02 UTC · original · requested changes

The upfront branch adds divergent control flow to the hottest RT loop. Anon64 measured 37-42 FPS vs 60 on main. The NaN/inf cases should be handled in the slab math (branchless), not with an upfront rejection — see PR #1322 for a partial model. Also, the zero-direction rejection changes the semantics of point-in-box tests that the game's shaders may rely on. Needs an RDNA2 hardware measurement before merge.

**@⁠Melow-code** on GitHub · 2026-11-24 23:02 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#pullrequestreview-6048794433) · **requested changes** The upfront branch adds divergent control flow to the hottest RT loop. Anon64 measured 37-42 FPS vs 60 on main. The NaN/inf cases should be handled in the slab math (branchless), not with an upfront rejection — see PR #1322 for a partial model. Also, the zero-direction rejection changes the semantics of point-in-box tests that the game's shaders may rely on. Needs an RDNA2 hardware measurement before merge.
Author
Owner

@⁠thehollowedone on GitHub · 2026-11-26 08:15 UTC · original · edited 2026-11-26 08:23 UTC

Independent Direct DXIL BVH check on current main b49be18. #1559 head ca5f6a5 changes the CPU and HLSL box paths, but leaves gpu/dxil/lower_image.rs untouched. This is a separate Direct DXIL gap; I did not run the PR head.

Tested: Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / NVIDIA 621.35, Rust 1.99.1 MSVC, DXC 1.8.2502.11. On b49be18 with only the synthetic regression added, cargo test --offline --locked -p xcl --lib direct_dxil_bvh_rejects_nan_ray_parameters -- --nocapture --test-threads=1 failed (0 passed, 1 failed, 0 ignored, 0 skipped): BOX16 and BOX32 each returned a child for a NaN origin and a NaN inverse direction. The finite hit, finite miss, and NaN parallel-origin controls behaved as expected. With the local Direct DXIL guard below, the same command passed (1 passed, 0 failed, 0 ignored, 0 skipped). With XCL_DXIL_CACHE set to a writable worktree-local cache, cargo build --offline --locked --workspace passed. cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --quiet then reported 1,436 passed, 0 failed, 47 ignored across 37 targets, with 25 GPU SKIPPED notices. Untouched b49be18 under the same cache setting reported 1,435 passed, 0 failed, 47 ignored, and the same 25 skips. Without the override, the public console_mesh cache test fails because this managed sandbox cannot persist its default %LOCALAPPDATA% DXIL cache; it passed in isolation after redirecting XCL_DXIL_CACHE. That setup failure is unrelated to the BVH change.

The proposed guard computes one ordered predicate per box from its three origin/inverse pairs, then includes it in each child's hit predicate. It avoids adding a branch to the finite-ray path. The regression covers both box formats and five synthetic rays each. This addresses the measured NaN slab-input gap; it does not establish parity for all of #1559's Inf, zero-direction, or tmax cases.

Suggested local diff (runtime guard and failing-before regression)
diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs
index c366666..8e84794 100644
--- a/crates/xcl/src/gpu/dxil/lower_image.rs
+++ b/crates/xcl/src/gpu/dxil/lower_image.rs
@@ -102,6 +102,11 @@ impl Lw {
                     out
                 });
                 let child = [words[0], words[1], words[2], words[3]];
+                // Min/max can discard NaN slab endpoints, so reject a NaN in
+                // either ray input before testing any child of this box.
+                let [x, y, z] = std::array::from_fn(|axis| lw.fcmp(Pred::FOrd, o[axis], inv[axis]));
+                let xy = lw.land(x, y);
+                let ray_ordered = lw.land(xy, z);
                 let ninf = lw.s.m.f32c(0xFF80_0000);
                 let pinf = lw.s.m.f32c(0x7F80_0000);
                 let mut tn = [pinf; 4];
@@ -146,7 +151,7 @@ impl Lw {
                     let b = lw.fmin(hi[0], hi[1]);
                     let b = lw.fmin(b, hi[2]);
                     let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX);
-                    let mut all = cv;
+                    let mut all = lw.land(cv, ray_ordered);
                     for c in 0..3 {
                         let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]);
                         all = lw.land(all, le);
diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 0b018ed..a02e1bf 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -10006,3 +10006,54 @@ fn gpu_v_dot8_u32_u4_edge_cases() {
         }
     }
 }
+
+/// A NaN ray parameter must not become a BVH box hit after min/max reduction.
+#[test]
+fn direct_dxil_bvh_rejects_nan_ray_parameters() {
+    use crate::gpu::bvh;
+    if !gpu_ready() { return; }
+
+    const CHILD: u32 = 0x10;
+    const BOX16_NODE: u32 = 0x14;
+    let base = 0x1000usize;
+    let mut mem = vec![0u32; (base + 192) / 4];
+    let children = [CHILD, bvh::INVALID, bvh::INVALID, bvh::INVALID];
+    let bounds = [0.0f32, 0.0, 0.0, 1.0, 1.0, 1.0].map(f32::to_bits);
+    let box32 = base / 4;
+    mem[box32..box32 + 4].copy_from_slice(&children);
+    mem[box32 + 4..box32 + 10].copy_from_slice(&bounds);
+    let box16 = (base + 128) / 4;
+    mem[box16..box16 + 4].copy_from_slice(&children);
+    mem[box16 + 4..box16 + 7].copy_from_slice(&[0, 0x3c00_0000, 0x3c00_3c00]);
+
+    let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap();
+    code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
+    let mut state = KernelState::default();
+    state.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]);
+    let inf = f32::INFINITY;
+    let nan = f32::NAN;
+    let cases = [
+        ("finite-hit", [0.5, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], CHILD),
+        ("finite-miss", [2.0, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID),
+        ("nan-origin", [0.5, 0.5, nan], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID),
+        ("nan-inverse", [0.5, 0.5, -1.0], [0.0, 0.0, nan], [inf, inf, nan], bvh::INVALID),
+        ("nan-parallel-origin", [nan, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID),
+    ];
+    let rays = [bvh::BOX32, BOX16_NODE].into_iter().flat_map(|node| cases.into_iter().map(move |case| (node, case)));
+    for (lane, (node, (_, o, d, inv, _))) in rays.clone().enumerate() {
+        state.vgpr[lane][0] = node;
+        for (k, value) in [100.0f32, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].into_iter().enumerate() {
+            state.vgpr[lane][1 + k] = value.to_bits();
+        }
+    }
+    let dxil = runner::direct_kernel(&code, true).unwrap();
+    let result = runner::run_with(&dxil, &state, &mem, &[], &[]).unwrap();
+    println!("BVH adapter: {}", runner::adapter().unwrap());
+    let mut mismatches = Vec::new();
+    for (lane, (node, (name, _, _, _, expected))) in rays.enumerate() {
+        let got = &result.vgpr[lane][100..104];
+        let expected = [expected, bvh::INVALID, bvh::INVALID, bvh::INVALID];
+        if got != expected { mismatches.push(format!("box type {}, {name}: {got:?}", node & 7)); }
+    }
+    assert!(mismatches.is_empty(), "unexpected BVH hits or misses: {mismatches:?}");
+}

Not tested: #1559 exact head, AMD, a retail title, or performance impact. No game files or dumps were used. AI use: Codex (GPT-6.2 Sol) investigated, wrote the local diff, ran the tests, and drafted this report.

**@⁠thehollowedone** on GitHub · 2026-11-26 08:15 UTC · [original](https://github.com/xcl-dev/xcl/pull/1559#issuecomment-7186386010) · edited 2026-11-26 08:23 UTC Independent Direct DXIL BVH check on current [main `b49be18`](https://github.com/xcl-dev/xcl/commit/b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7). [#1559 head `ca5f6a5`](https://github.com/xcl-dev/xcl/commit/ca5f6a5e4345eabdbddc48e4513f0fecf3112031) changes the CPU and HLSL box paths, but leaves `gpu/dxil/lower_image.rs` untouched. This is a separate Direct DXIL gap; I did not run the PR head. **Tested:** Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / NVIDIA 621.35, Rust 1.99.1 MSVC, DXC 1.8.2502.11. On `b49be18` with only the synthetic regression added, `cargo test --offline --locked -p xcl --lib direct_dxil_bvh_rejects_nan_ray_parameters -- --nocapture --test-threads=1` failed (0 passed, 1 failed, 0 ignored, 0 skipped): BOX16 and BOX32 each returned a child for a NaN origin and a NaN inverse direction. The finite hit, finite miss, and NaN parallel-origin controls behaved as expected. With the local Direct DXIL guard below, the same command passed (1 passed, 0 failed, 0 ignored, 0 skipped). With `XCL_DXIL_CACHE` set to a writable worktree-local cache, `cargo build --offline --locked --workspace` passed. `cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --quiet` then reported **1,436 passed, 0 failed, 47 ignored** across 37 targets, with 25 GPU `SKIPPED` notices. Untouched `b49be18` under the same cache setting reported 1,435 passed, 0 failed, 47 ignored, and the same 25 skips. Without the override, the public `console_mesh` cache test fails because this managed sandbox cannot persist its default `%LOCALAPPDATA%` DXIL cache; it passed in isolation after redirecting `XCL_DXIL_CACHE`. That setup failure is unrelated to the BVH change. The proposed guard computes one ordered predicate per box from its three origin/inverse pairs, then includes it in each child's hit predicate. It avoids adding a branch to the finite-ray path. The regression covers both box formats and five synthetic rays each. This addresses the measured NaN slab-input gap; it does not establish parity for all of #1559's Inf, zero-direction, or `tmax` cases. <details><summary>Suggested local diff (runtime guard and failing-before regression)</summary> ```diff diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index c366666..8e84794 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -102,6 +102,11 @@ impl Lw { out }); let child = [words[0], words[1], words[2], words[3]]; + // Min/max can discard NaN slab endpoints, so reject a NaN in + // either ray input before testing any child of this box. + let [x, y, z] = std::array::from_fn(|axis| lw.fcmp(Pred::FOrd, o[axis], inv[axis])); + let xy = lw.land(x, y); + let ray_ordered = lw.land(xy, z); let ninf = lw.s.m.f32c(0xFF80_0000); let pinf = lw.s.m.f32c(0x7F80_0000); let mut tn = [pinf; 4]; @@ -146,7 +151,7 @@ impl Lw { let b = lw.fmin(hi[0], hi[1]); let b = lw.fmin(b, hi[2]); let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); - let mut all = cv; + let mut all = lw.land(cv, ray_ordered); for c in 0..3 { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); all = lw.land(all, le); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018ed..a02e1bf 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -10006,3 +10006,54 @@ fn gpu_v_dot8_u32_u4_edge_cases() { } } } + +/// A NaN ray parameter must not become a BVH box hit after min/max reduction. +#[test] +fn direct_dxil_bvh_rejects_nan_ray_parameters() { + use crate::gpu::bvh; + if !gpu_ready() { return; } + + const CHILD: u32 = 0x10; + const BOX16_NODE: u32 = 0x14; + let base = 0x1000usize; + let mut mem = vec![0u32; (base + 192) / 4]; + let children = [CHILD, bvh::INVALID, bvh::INVALID, bvh::INVALID]; + let bounds = [0.0f32, 0.0, 0.0, 1.0, 1.0, 1.0].map(f32::to_bits); + let box32 = base / 4; + mem[box32..box32 + 4].copy_from_slice(&children); + mem[box32 + 4..box32 + 10].copy_from_slice(&bounds); + let box16 = (base + 128) / 4; + mem[box16..box16 + 4].copy_from_slice(&children); + mem[box16 + 4..box16 + 7].copy_from_slice(&[0, 0x3c00_0000, 0x3c00_3c00]); + + let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut state = KernelState::default(); + state.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]); + let inf = f32::INFINITY; + let nan = f32::NAN; + let cases = [ + ("finite-hit", [0.5, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], CHILD), + ("finite-miss", [2.0, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID), + ("nan-origin", [0.5, 0.5, nan], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID), + ("nan-inverse", [0.5, 0.5, -1.0], [0.0, 0.0, nan], [inf, inf, nan], bvh::INVALID), + ("nan-parallel-origin", [nan, 0.5, -1.0], [0.0, 0.0, 1.0], [inf, inf, 1.0], bvh::INVALID), + ]; + let rays = [bvh::BOX32, BOX16_NODE].into_iter().flat_map(|node| cases.into_iter().map(move |case| (node, case))); + for (lane, (node, (_, o, d, inv, _))) in rays.clone().enumerate() { + state.vgpr[lane][0] = node; + for (k, value) in [100.0f32, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].into_iter().enumerate() { + state.vgpr[lane][1 + k] = value.to_bits(); + } + } + let dxil = runner::direct_kernel(&code, true).unwrap(); + let result = runner::run_with(&dxil, &state, &mem, &[], &[]).unwrap(); + println!("BVH adapter: {}", runner::adapter().unwrap()); + let mut mismatches = Vec::new(); + for (lane, (node, (name, _, _, _, expected))) in rays.enumerate() { + let got = &result.vgpr[lane][100..104]; + let expected = [expected, bvh::INVALID, bvh::INVALID, bvh::INVALID]; + if got != expected { mismatches.push(format!("box type {}, {name}: {got:?}", node & 7)); } + } + assert!(mismatches.is_empty(), "unexpected BVH hits or misses: {mismatches:?}"); +} ``` </details> **Not tested:** #1559 exact head, AMD, a retail title, or performance impact. No game files or dumps were used. AI use: Codex (GPT-6.2 Sol) investigated, wrote the local diff, ran the tests, and drafted this report.
This pull request has changes conflicting with the target branch.
  • crates/xcl/src/gpu/bvh.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1559/head:github-bot/gh-1559'
git switch 'github-bot/gh-1559'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1559'
git switch 'github-bot/gh-1559'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1559'
git switch 'github-bot/gh-1559'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1559'
git switch 'main'
git merge --squash 'github-bot/gh-1559'
git switch 'main'
git merge --ff-only 'github-bot/gh-1559'
git switch 'main'
git merge 'github-bot/gh-1559'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.