diff --git a/README.md b/README.md index 0dc65fb2e9..43418ad902 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,10 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o split-wave64 programs that access LDS stay on the HLSL path to preserve instruction order between their two hardware wave32 halves. Test results on other GPUs: [#42](https://github.com/xcl-dev/xcl/issues/42). +- **`XCL_BVH_WATERTIGHT=1`** (off by default): the ray/triangle test of `image_bvh_intersect_ray` + becomes watertight, so a ray exactly through an edge two triangles share hits one of them instead + of possibly missing both. Changes the translated shaders (they get their own cache entries). + Ported from victory-fork, after Mesa RADV (see `THIRD_PARTY.md`). ```powershell cargo build --release --workspace # target\release\xcl.exe diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..93a8c5d390 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,6 +11,8 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`, behind `XCL_BVH_WATERTIGHT=1`): after its `crates/victory-shader/src/bvh.rs` `triangle` at `9a9091d` (fxceless), changed 2026-11-27 | port with annotation | +| [Mesa RADV](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/vulkan) (Mesa) | MIT | the same triangle test, through victory-fork: `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri` (Copyright © 2021 Google, SPDX MIT; Woop, Benthin, Wald, JCGT 2013) | logic ported with annotation | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 5ff20d8911..cd4a85d15e 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -28,6 +28,14 @@ //! //! Top-down build: median split of the leaf box centroids on the longest axis, twice per box //! node (4 children), one triangle / instance per leaf. +//! +//! `triangle_hit_watertight` (`XCL_BVH_WATERTIGHT=1`) is adapted from victory-fork +//! (https://github.com/fxceless/victory-fork, GPL-3.0-or-later) commit `9a9091d`, +//! `crates/victory-shader/src/bvh.rs` `triangle` (by fxceless), which follows Mesa RADV +//! (https://gitlab.freedesktop.org/mesa/mesa, MIT, Copyright © 2021 Google) +//! `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed +//! 2026-11-27: f32 edge functions (Mesa computes them in f64), no t sign test, XCL's result +//! scale (Mesa returns t / |det| and the sign of det). pub const BOX32: u32 = 5; pub const INSTANCE: u32 = 6; @@ -254,8 +262,80 @@ fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -/// Möller–Trumbore as the triangle node returns it: (t·det, det, i·det, j·det), `None` = miss +/// The triangle node's test as it returns it: (t·det, det, i·det, j·det), `None` = miss. pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { + if watertight() { triangle_hit_watertight(v, o, d) } else { triangle_hit_mt(v, o, d) } +} + +/// `XCL_BVH_WATERTIGHT=1` (off by default): the triangle node uses the watertight test in the CPU +/// reference, the HLSL prelude and the DXIL lowering; otherwise Möller–Trumbore as before. Read +/// once; a test sets it for its own thread only (`tests::with_watertight`). Off, the HLSL is the +/// text it was before; on, a program calling `bvh_intersect` gets other text (so another DXC +/// cache key), and the translated cache's identity gets a tag (`recomp::pso`). +pub fn watertight() -> bool { + #[cfg(test)] + if let Some(w) = tests::WATERTIGHT.with(|c| c.get()) { + return w; + } + static W: std::sync::OnceLock = std::sync::OnceLock::new(); + *W.get_or_init(|| std::env::var("XCL_BVH_WATERTIGHT").is_ok_and(|v| v == "1")) +} + +/// The watertight test of `triangle_hit`: +/// Watertight (Woop, Benthin, Wald, "Watertight Ray/Triangle Intersection", JCGT 2013): the +/// vertices are sheared so the ray runs along its largest axis and the signs of the three edge +/// functions decide, so a ray through an edge two triangles share hits at least one of them +/// (both when the edge function is exactly 0; the console's rule for that tie is not known). +/// Edge-on (det = 0), NaN and a non-finite t or det miss; t's sign is not tested here (the +/// traversal does). The four values have the Möller–Trumbore scale XCL returned before. The +/// HLSL prelude (`recomp/emit.rs` `bvh_intersect`) and the DXIL lowering +/// (`dxil/lower_image.rs`) do the same operations in the same order. Ported code: see the file +/// header. +fn triangle_hit_watertight(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { + let kz = dominant_axis(d); + let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; + let sz = 1.0 / d[kz]; + let (sx, sy) = (d[kx] * sz, d[ky] * sz); + // (x, y) sheared, z the unscaled axial distance from the origin + let shear = |p: [f32; 3]| { + let r = sub(p, o); + [r[kx] - sx * r[kz], r[ky] - sy * r[kz], r[kz]] + }; + let (p0, p1, p2) = (shear(v[0]), shear(v[1]), shear(v[2])); + // edge functions: the barycentric numerators of v0, v1, v2 + let u = p2[0] * p1[1] - p2[1] * p1[0]; + let i = p0[0] * p2[1] - p0[1] * p2[0]; + let j = p1[0] * p0[1] - p1[1] * p0[0]; + let mixed = (u < 0.0 || i < 0.0 || j < 0.0) && (u > 0.0 || i > 0.0 || j > 0.0); + let det = u + (i + j); + // Möller–Trumbore's t·det is the depth sum over the sheared det times |d[kz]| / d[kz]: + // with the unscaled depths only d[kz]'s sign is left (exact), so nothing overflows that + // the old t·det does not + let tz = (u * p0[2] + i * p1[2]) + j * p2[2]; + let t = if d[kz] < 0.0 { -tz } else { tz }; + // back to Möller–Trumbore's scale (the sheared determinant is its det / |d[kz]|), after + // the decision + let s = d[kz].abs(); + let r = [t, det * s, i * s, j * s]; + // the plane's own orientation (Möller–Trumbore's det, as `triangle_hit_mt`) must agree with + // the sheared det's sign: a ray in (or within rounding of) the plane misses even when the + // rounded sheared det is not 0 + let mt = dot(sub(v[1], v[0]), cross(d, sub(v[2], v[0]))); + let facing = (det > 0.0 && mt > 0.0) || (det < 0.0 && mt < 0.0); + // the traversal divides by the encoded det: a normal number, so never 0 (also where a GPU + // flushes subnormals); a non-finite t or det misses + let normal = r[1].abs() >= f32::MIN_POSITIVE; + (!mixed && facing && normal && r[0].is_finite() && r[1].is_finite()).then_some(r) +} + +/// The ray's largest axis (ties: x before y before z), along which `triangle_hit` shears. +fn dominant_axis(d: [f32; 3]) -> usize { + let a = d.map(f32::abs); + if a[0] >= a[1] { if a[0] >= a[2] { 0 } else { 2 } } else if a[1] >= a[2] { 1 } else { 2 } +} + +/// The Möller–Trumbore test XCL used before the watertight one (`XCL_BVH_WATERTIGHT` unset). +fn triangle_hit_mt(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { let (e1, e2) = (sub(v[1], v[0]), sub(v[2], v[0])); let p = cross(d, e2); let det = dot(e1, p); @@ -1139,4 +1219,207 @@ pub(crate) mod tests { let got_o = intersect_node(&data, BOX32, 100.0, [f32::NAN, 0.5, 0.5], [1.0, 0.0, 0.0], [1.0, f32::INFINITY, f32::INFINITY], true); assert_eq!(got_o, [INVALID; 4], "a ray with NaN origin must miss"); } + + /// `p` rotated so that its axis 2 becomes `axis`, mirrored when `flip` + fn place(p: [f32; 3], axis: usize, flip: bool) -> [f32; 3] { + let mut r = [0.0; 3]; + for k in 0..3 { + r[(axis + 1 + k) % 3] = p[k]; + } + if flip { + r[axis] = -r[axis]; + } + r + } + + /// hits among `tris` for a ray from `o` along `d` + fn hits(tris: &[Triangle], o: [f32; 3], d: [f32; 3]) -> usize { + tris.iter().filter(|t| triangle_hit_watertight(t, o, d).is_some()).count() + } + + /// Away from edges the watertight test agrees with the old Möller–Trumbore one: same hit / + /// miss, same sign of det (facing), t and barycentrics within rounding. + #[test] + fn triangle_hit_agrees_with_moller_trumbore_on_generic_rays() { + for seed in 0..8u64 { + let tris = random_tris(50, 200 + seed); + let mut r = rng(300 + seed); + let mut both = 0; + for _ in 0..2000 { + let o = [r(-12.0, 12.0), r(-12.0, 12.0), r(-12.0, 12.0)]; + let to = [r(-8.0, 8.0), r(-8.0, 8.0), r(-8.0, 8.0)]; + let d = sub(to, o); + for t in &tris { + let (w, m) = (triangle_hit_watertight(t, o, d), triangle_hit_mt(t, o, d)); + let Some(m) = m else { + if let Some(w) = w { + // only a ray within rounding of an edge may differ + assert!([w[2], w[3], w[1] - w[2] - w[3]].iter().any(|x| (x / w[1]).abs() < 1e-4), "{t:?} {o:?} {d:?}: {w:?}"); + } + continue; + }; + let Some(w) = w else { + assert!([m[2], m[3], m[1] - m[2] - m[3]].iter().any(|x| (x / m[1]).abs() < 1e-4), "{t:?} {o:?} {d:?}: {m:?}"); + continue; + }; + assert_eq!(w[1] > 0.0, m[1] > 0.0, "facing"); + assert!((w[1] - m[1]).abs() <= 1e-3 * m[1].abs(), "det scale: {w:?} vs {m:?}"); + for k in [0, 2, 3] { + assert!((w[k] / w[1] - m[k] / m[1]).abs() < 1e-4, "{k}: {w:?} vs {m:?}"); + } + both += 1; + } + } + assert!(both > 100, "seed {seed}: {both} hits"); + } + } + + /// Dyadic coordinates, so the ray passes exactly through the shared edge / vertex: at least + /// one triangle hits, along every dominant axis, both signs, the shared edge listed in + /// opposite orders (consistent winding) and in the same order. + #[test] + fn triangle_hit_exact_shared_edge_and_vertex() { + let (a, b) = ([-1.0, -0.5, 1.0], [1.5, 1.0, 1.0]); + let (c, e) = ([-2.0, 3.0, 1.5], [2.0, -3.0, 0.5]); + let pairs: [[Triangle; 2]; 2] = [[[a, b, c], [b, a, e]], [[a, b, c], [a, b, e]]]; + let v = [0.25, -0.5, 1.0]; + let ring = [[2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [-2.0, 2.0], [-2.0, 0.0], [-2.0, -2.0], [0.0, -2.0], [2.0, -2.0]]; + let fan: Vec = (0..8) + .map(|k| { + let p = |k: usize| [v[0] + ring[k % 8][0], v[1] + ring[k % 8][1], 1.0 + 0.25 * (k % 2) as f32]; + [v, p(k), p(k + 1)] + }) + .collect(); + let dirs = [[0.0, 0.0, 1.0], [0.25, -0.5, 1.0], [-0.375, 0.125, 1.0], [0.5, 0.5, -1.0], [-0.75, 0.25, -1.0]]; + for axis in 0..3 { + for flip in [false, true] { + for dl in dirs { + let d = place(dl, axis, flip); + for s in [0.25f32, 0.5, 0.75] { + let on = [0, 1, 2].map(|k| a[k] + s * (b[k] - a[k])); + let o = place([0, 1, 2].map(|k| on[k] - 2.0 * dl[k]), axis, flip); + for pair in &pairs { + let pair = pair.map(|t| t.map(|p| place(p, axis, flip))); + assert!(hits(&pair, o, d) >= 1, "edge: axis {axis} flip {flip} s {s} d {d:?} {pair:?}"); + } + } + let o = place([0, 1, 2].map(|k| v[k] - 2.0 * dl[k]), axis, flip); + let fan: Vec = fan.iter().map(|t| t.map(|p| place(p, axis, flip))).collect(); + assert!(hits(&fan, o, d) >= 1, "vertex: axis {axis} flip {flip} d {d:?}"); + } + } + } + } + + /// Found by a random near-edge search (seed 11, first case): + /// a ray through the edge (1.911541, -2.025442, 0.78372467)–(1.911541, 2.740394, -0.50947857) + /// that Möller–Trumbore misses in both triangles; the watertight test hits at least one. + #[test] + fn triangle_hit_pinned_shared_edge_moller_trumbore_misses() { + let (a, b) = ([1.911541f32, -2.025442, 0.78372467], [1.911541f32, 2.740394, -0.50947857]); + let pair = [[a, b, [2.1104007, -1.6796683, 9.487581]], [b, a, [1.5455573, 0.7414906, -8.11272]]]; + let (o, d) = ([5.911541f32, -0.8080063, 0.59203976], [-1.0f32, -0.13060194, 0.000772506]); + assert_eq!(pair.iter().filter(|t| triangle_hit_mt(t, o, d).is_some()).count(), 0); + assert!(hits(&pair, o, d) >= 1); + // the switch: off (the default) = Möller–Trumbore, misses both; on = watertight + let n = |on| with_watertight(on, || pair.iter().filter(|t| triangle_hit(t, o, d).is_some()).count()); + assert_eq!(n(false), 0); + assert!(n(true) >= 1); + } + + /// The watertight test's edge cases: degenerate triangles, rays in the triangle's plane, a + /// zero direction and NaN miss; a tiny largest component (1e-38) gives a subnormal + /// encoded det and misses; the node then returns its miss encoding, never a NaN. Equal + /// largest components pick the first axis (x before y before z), as the HLSL and DXIL `kz`. + #[test] + fn triangle_hit_degenerate_non_finite_and_axis_ties() { + let node = |t: &Triangle| { + let mut data = vec![0u8; 64]; + for (k, p) in t.iter().enumerate() { + for a in 0..3 { + data[12 * k + 4 * a..12 * k + 4 * a + 4].copy_from_slice(&p[a].to_le_bytes()); + } + } + data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); + data + }; + let miss = [f32::INFINITY, 1.0, 0.0, 0.0]; + let at = |t: &Triangle, o: [f32; 3], d: [f32; 3]| with_watertight(true, || intersect_node(&node(t), 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); + let d = [0.0, 0.0, 1.0]; + let o = [0.2, 0.2, -1.0]; + let tri = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let mut nan = tri; + nan[1][0] = f32::NAN; + let degenerate: [Triangle; 4] = [ + [[0.0; 3], [0.0; 3], [0.0; 3]], + [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 2.0, 0.0]], + [[0.2, 0.2, 0.0], [0.2, 0.2, 0.0], [1.0, 0.0, 0.0]], + nan, + ]; + for t in °enerate { + assert!(triangle_hit_watertight(t, o, d).is_none(), "{t:?}"); + assert_eq!(at(t, o, d), miss, "{t:?}"); + } + // in the plane, along each in-plane axis and a diagonal + for d in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]] { + assert!(triangle_hit_watertight(&tri, [-1.0, 0.2, 0.0], d).is_none(), "{d:?}"); + } + assert!(triangle_hit_watertight(&tri, o, [0.0; 3]).is_none()); + assert!(triangle_hit_watertight(&tri, o, [f32::NAN, 0.0, 1.0]).is_none()); + assert!(triangle_hit_watertight(&tri, [f32::NAN, 0.2, -1.0], d).is_none()); + let far = [[5.0, 0.0, 0.0], [5.0, 1.0, 0.0], [5.0, 0.0, 1.0]]; + let (fo, fd) = ([0.0, 0.2, 0.2], [1e-38f32, 0.0, 0.0]); + assert!(triangle_hit_watertight(&far, fo, fd).is_none()); + assert_eq!(at(&far, fo, fd), miss); + for (d, k) in [([1.0, -1.0, 0.5], 0), ([-1.0, 1.0, 1.0], 0), ([0.5, 1.0, -1.0], 1), ([0.5, -0.25, 1.0], 2), ([0.0; 3], 0)] { + assert_eq!(dominant_axis(d), k, "{d:?}"); + } + } + + /// Review cases of #3038 (finite binary32 inputs; `p` = 2^p): + /// 1. a ray in the triangle's plane (Möller–Trumbore's det is exactly 0) whose rounded + /// sheared determinant is not 0 misses; + /// 2. a finite interior hit whose weighted sheared depths overflow (tiny d[kz]) still hits, + /// with Möller–Trumbore's values; + /// 3. a hit whose encoded determinant (sheared det · |d[kz]|) rounds to 0 misses, so the + /// traversal never divides by a zero denominator. + pub(crate) fn review_cases() -> [(Triangle, [f32; 3], [f32; 3]); 3] { + let p = |e: i32| 2f32.powi(e); + [ + ([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 5.0, 6.0]], [-1.0, -2.0, -3.0], [1.0, 2.0, 3.0]), + ([[0.0, 0.0, p(20)], [p(30), 0.0, p(20)], [0.0, p(30), p(20)]], [p(28), p(28), 0.0], [0.0, 0.0, p(-60)]), + ([[0.0, 0.0, 1.0], [p(-40), 0.0, 1.0], [0.0, p(-40), 1.0]], [p(-42), p(-42), 0.0], [0.0, 0.0, p(-80)]), + ] + } + + #[test] + fn triangle_hit_review_cases_coplanar_overflow_zero_denominator() { + let [c1, c2, c3] = review_cases(); + for (k, (t, o, d)) in review_cases().iter().enumerate() { + eprintln!("case {}: watertight {:?} mt {:?}", k + 1, triangle_hit_watertight(t, *o, *d), triangle_hit_mt(t, *o, *d)); + } + assert_eq!(triangle_hit_mt(&c1.0, c1.1, c1.2), None); + assert_eq!(triangle_hit_watertight(&c1.0, c1.1, c1.2), None, "coplanar ray"); + let p = |e: i32| 2f32.powi(e); + assert_eq!(triangle_hit_mt(&c2.0, c2.1, c2.2), Some([-p(80), -1.0, -0.25, -0.25])); + assert_eq!(triangle_hit_watertight(&c2.0, c2.1, c2.2), Some([-p(80), -1.0, -0.25, -0.25]), "overflowed depth"); + assert_eq!(triangle_hit_watertight(&c3.0, c3.1, c3.2), None, "zero denominator"); + // the same small triangle with a unit direction is a valid hit and still hits + let unit = [0.0, 0.0, 1.0]; + assert_eq!(triangle_hit_watertight(&c3.0, c3.1, unit), triangle_hit_mt(&c3.0, c3.1, unit)); + assert!(triangle_hit_watertight(&c3.0, c3.1, unit).is_some()); + } + + thread_local! { + /// `watertight()` for this test thread only (`None`: `XCL_BVH_WATERTIGHT`) + pub(crate) static WATERTIGHT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// `f` with the triangle test switched `on` / off on this thread, restored after + pub(crate) fn with_watertight(on: bool, f: impl FnOnce() -> R) -> R { + let old = WATERTIGHT.with(|c| c.replace(Some(on))); + let r = f(); + WATERTIGHT.with(|c| c.set(old)); + r + } } diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8e01ef00a4..8ef7c73951 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -252,12 +252,18 @@ fn translate_entry_with( let code = code.to_vec(); #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + // a test's `XCL_BVH_WATERTIGHT` setting is per thread: carried over to the translator's + #[cfg(test)] + let wt = crate::gpu::bvh::watertight(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + #[cfg(test)] + return crate::gpu::bvh::tests::with_watertight(wt, || translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask)); + #[cfg(not(test))] translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask) }) .map_err(|e| format!("translator thread: {e}"))? diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index ba7a38ddba..29f5badf4a 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -4,6 +4,11 @@ //! `image_bvh(64)_intersect_ray` on the flat memory (port of //! `recomp/emit.rs` `mimg` and `bvh_intersect`; compute rules: no implicit //! derivatives, so implicit-LOD samples take LOD 0 / the bias). +//! +//! The watertight BVH triangle test (`XCL_BVH_WATERTIGHT=1`) is adapted from victory-fork +//! (https://github.com/fxceless/victory-fork, GPL-3.0-or-later) `9a9091d`, +//! `crates/victory-shader/src/bvh.rs` `triangle`, after Mesa RADV (MIT, Copyright © 2021 Google) +//! `intersect_ray_amd_software_tri`; changed 2026-11-27 (see `gpu/bvh.rs`). use super::lower::{err, LResult, Lw, VAR_VGPR, VAR_WIN}; use super::module::{BinOp, Pred, Value}; @@ -284,31 +289,140 @@ impl Lw { let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; let tw = words[9]; - let e1 = lw.f3(v1, v0, Lw::fsub); - let e2 = lw.f3(v2, v0, Lw::fsub); - let p = lw.cross(dir, e2); - let det = lw.dot3(e1, p); - let sv = lw.f3(o, v0, Lw::fsub); - let q = lw.cross(sv, e1); - let i = lw.dot3(sv, p); - let j = lw.dot3(dir, q); - let t = lw.dot3(e2, q); - let z = lw.fc(0.0); - let ij = lw.fadd(i, j); - let dpos = lw.fcmp(Pred::FOGt, det, z); - let c1 = lw.fcmp(Pred::FOGe, i, z); - let c2 = lw.fcmp(Pred::FOGe, j, z); - let c3 = lw.fcmp(Pred::FOLe, ij, det); - let hp = lw.land(c1, c2); - let hp = lw.land(hp, c3); - let dneg = lw.fcmp(Pred::FOLt, det, z); - let n1 = lw.fcmp(Pred::FOLe, i, z); - let n2 = lw.fcmp(Pred::FOLe, j, z); - let n3 = lw.fcmp(Pred::FOGe, ij, det); - let hn = lw.land(dneg, n1); - let hn = lw.land(hn, n2); - let hn = lw.land(hn, n3); - let hit = lw.sel(dpos, hp, hn); + // `XCL_BVH_WATERTIGHT=1` (`gpu::bvh::watertight`): the watertight test as + // gpu::bvh::triangle_hit_watertight and the HLSL prelude; no fused products, so a shared edge's + // function is exactly negated in the other triangle. Limit: the module drops + // DisableMathRefactoring when it also uses FMad (shader.rs), and a driver may then + // fuse these products, which loses the exact negation (no worse than before) + let (t, det, i, j, hit, z) = if crate::gpu::bvh::watertight() { + lw.s.require(super::shader::Feature::DisableMathRefactoring); + let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; + let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); + let xz = lw.fcmp(Pred::FOGe, ad[0], ad[2]); + let yz = lw.fcmp(Pred::FOGe, ad[1], ad[2]); + let nxy = lw.lnot(xy); + let kz0 = lw.land(xy, xz); + let kz1 = lw.land(nxy, yz); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + let perm = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { + let x = lw.sel(kz1, v[2], v[0]); + let x = lw.sel(kz0, v[1], x); + let y = lw.sel(kz1, v[0], v[1]); + let y = lw.sel(kz0, v[2], y); + let z = lw.sel(kz1, v[1], v[2]); + let z = lw.sel(kz0, v[0], z); + [x, y, z] + }; + let pd = perm(lw, dir); + let z = lw.fc(0.0); + let sw = lw.fcmp(Pred::FOLt, pd[2], z); + let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; + let pd = swap(lw, pd); + let one = lw.fc(1.0); + let sz = lw.fdiv(one, pd[2]); + let sx = lw.fmul(pd[0], sz); + let sy = lw.fmul(pd[1], sz); + let mut sh = [[z; 3]; 3]; + for (k, v) in [v0, v1, v2].into_iter().enumerate() { + let r = lw.f3(v, o, Lw::fsub); + let r = perm(lw, r); + let r = swap(lw, r); + let ax = lw.fmul(sx, r[2]); + let ay = lw.fmul(sy, r[2]); + // (x, y) sheared, z the unscaled axial distance from the origin + sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), r[2]]; + } + let [p0, p1, p2] = sh; + let edge = |lw: &mut Lw, a: [Value; 3], b: [Value; 3]| { + let m0 = lw.fmul(a[0], b[1]); + let m1 = lw.fmul(a[1], b[0]); + lw.fsub(m0, m1) + }; + let u = edge(lw, p2, p1); + let i = edge(lw, p0, p2); + let j = edge(lw, p1, p0); + let mut neg = lw.fcmp(Pred::FOLt, u, z); + let mut pos = lw.fcmp(Pred::FOGt, u, z); + for e in [i, j] { + let n = lw.fcmp(Pred::FOLt, e, z); + neg = lw.lor(neg, n); + let p = lw.fcmp(Pred::FOGt, e, z); + pos = lw.lor(pos, p); + } + let mixed = lw.land(neg, pos); + let ij = lw.fadd(i, j); + let det = lw.fadd(u, ij); + let tu = lw.fmul(u, p0[2]); + let ti = lw.fmul(i, p1[2]); + let tj = lw.fmul(j, p2[2]); + let t = lw.fadd(tu, ti); + let t = lw.fadd(t, tj); + // Möller–Trumbore's t·det: the unscaled depth sum with d[kz]'s sign + let tn = lw.fneg(t); + let t = lw.sel(sw, tn, t); + // the plane's orientation (Möller–Trumbore's det, gpu::bvh order) must agree + // with the sheared det's sign; edge-on, NaN miss + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let c = lw.cross(dir, e2); + let m0 = lw.fmul(e1[0], c[0]); + let m1 = lw.fmul(e1[1], c[1]); + let m2 = lw.fmul(e1[2], c[2]); + let mt = lw.fadd(m0, m1); + let mt = lw.fadd(mt, m2); + let dpos = lw.fcmp(Pred::FOGt, det, z); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let mpos = lw.fcmp(Pred::FOGt, mt, z); + let mneg = lw.fcmp(Pred::FOLt, mt, z); + let fp = lw.land(dpos, mpos); + let fneg = lw.land(dneg, mneg); + let facing = lw.lor(fp, fneg); + let inside = lw.lnot(mixed); + let hit = lw.land(inside, facing); + // back to Möller–Trumbore's scale after the decision; the encoded det is a normal + // number (never 0 for the traversal), a non-finite t or det misses + let s = lw.fabs(pd[2]); + let (det, i, j) = (lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); + let adet = lw.fabs(det); + let fmin = lw.fc(f32::MIN_POSITIVE); + let normal = lw.fcmp(Pred::FOGe, adet, fmin); + let pinf = lw.fc(f32::INFINITY); + let mut hit = lw.land(hit, normal); + for x in [t, det] { + // |x| < inf is false for inf and NaN + let ax = lw.fabs(x); + let fin = lw.fcmp(Pred::FOLt, ax, pinf); + hit = lw.land(hit, fin); + } + (t, det, i, j, hit, z) + } else { + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let p = lw.cross(dir, e2); + let det = lw.dot3(e1, p); + let sv = lw.f3(o, v0, Lw::fsub); + let q = lw.cross(sv, e1); + let i = lw.dot3(sv, p); + let j = lw.dot3(dir, q); + let t = lw.dot3(e2, q); + let z = lw.fc(0.0); + let ij = lw.fadd(i, j); + let dpos = lw.fcmp(Pred::FOGt, det, z); + let c1 = lw.fcmp(Pred::FOGe, i, z); + let c2 = lw.fcmp(Pred::FOGe, j, z); + let c3 = lw.fcmp(Pred::FOLe, ij, det); + let hp = lw.land(c1, c2); + let hp = lw.land(hp, c3); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let n1 = lw.fcmp(Pred::FOLe, i, z); + let n2 = lw.fcmp(Pred::FOLe, j, z); + let n3 = lw.fcmp(Pred::FOGe, ij, det); + let hn = lw.land(dneg, n1); + let hn = lw.land(hn, n2); + let hn = lw.land(hn, n3); + let hit = lw.sel(dpos, hp, hn); + (t, det, i, j, hit, z) + }; let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1c51cfd0e2..35444c8e25 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1,4 +1,8 @@ //! Instruction semantics: one RDNA2 instruction → HLSL statements. +//! +//! `BVH_TRIANGLE_WATERTIGHT` is adapted from victory-fork (https://github.com/fxceless/victory-fork, +//! GPL-3.0-or-later) `9a9091d`, `crates/victory-shader/src/bvh.rs` `triangle`, after Mesa RADV +//! (MIT, Copyright © 2021 Google) `intersect_ray_amd_software_tri`; changed 2026-11-27 (see `gpu/bvh.rs`). use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; @@ -5031,7 +5035,11 @@ static uint xcl_cap = 1u << 16; } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); - h.push_str(PRELUDE_MEM); + if crate::gpu::bvh::watertight() && body.contains("bvh_intersect(") { + h.push_str(&bvh_watertight_prelude_mem()); + } else { + h.push_str(PRELUDE_MEM); + } if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } @@ -6254,6 +6262,63 @@ void scr_st(uint a, uint v, uint n) { } "#; +/// `bvh_intersect`'s Möller–Trumbore triangle test in `PRELUDE_MEM` (`XCL_BVH_WATERTIGHT` off). +pub(super) const BVH_TRIANGLE_MT: &str = r#" float3 e1 = v1 - v0, e2 = v2 - v0, p = cross(d, e2); + float det = dot(e1, p); + float3 sv = o - v0, q = cross(sv, e1); + float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); + // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow + bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); +"#; + +/// The watertight test that replaces `BVH_TRIANGLE_MT` with `XCL_BVH_WATERTIGHT=1`, as +/// `gpu::bvh::triangle_hit_watertight` (provenance in this file's header): shear so the ray runs +/// along its largest axis, signs of the edge functions decide; `precise` so that no product is +/// fused and a shared edge's function is exactly negated in the other triangle (a driver that +/// fuses anyway loses that). +const BVH_TRIANGLE_WATERTIGHT: &str = r#" float3 ad = abs(d); + uint kz = ad.x >= ad.y ? (ad.x >= ad.z ? 0u : 2u) : (ad.y >= ad.z ? 1u : 2u); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + float3 pd = kz == 0u ? d.yzx : (kz == 1u ? d.zxy : d.xyz); + bool sw = pd.z < 0.0f; + pd = sw ? pd.yxz : pd; + precise float sz = 1.0f / pd.z; + precise float sx = pd.x * sz, sy = pd.y * sz; + float3 r0 = v0 - o, r1 = v1 - o, r2 = v2 - o; + r0 = kz == 0u ? r0.yzx : (kz == 1u ? r0.zxy : r0); r0 = sw ? r0.yxz : r0; + r1 = kz == 0u ? r1.yzx : (kz == 1u ? r1.zxy : r1); r1 = sw ? r1.yxz : r1; + r2 = kz == 0u ? r2.yzx : (kz == 1u ? r2.zxy : r2); r2 = sw ? r2.yxz : r2; + // (x, y) sheared, z the unscaled axial distance from the origin + precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, r0.z); + precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, r1.z); + precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, r2.z); + precise float u = p2.x * p1.y - p2.y * p1.x; + precise float i = p0.x * p2.y - p0.y * p2.x; + precise float j = p1.x * p0.y - p1.y * p0.x; + bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); + precise float det = u + (i + j); + // Möller–Trumbore's t·det: the unscaled depth sum with d[kz]'s sign + precise float t = (u * p0.z + i * p1.z) + j * p2.z; + t = pd.z < 0.0f ? -t : t; + // the plane's orientation (Möller–Trumbore's det) must agree with the sheared det's sign + precise float3 e1 = v1 - v0, e2 = v2 - v0; + precise float3 c = float3(d.y * e2.z - d.z * e2.y, d.z * e2.x - d.x * e2.z, d.x * e2.y - d.y * e2.x); + precise float mt = (e1.x * c.x + e1.y * c.y) + e1.z * c.z; + bool facing = (det > 0.0f && mt > 0.0f) || (det < 0.0f && mt < 0.0f); + // back to Möller–Trumbore's scale after the decision; the encoded det is a normal + // number (never 0 for the traversal), a non-finite t or det misses + precise float s = abs(pd.z); + precise float dets = det * s; i = i * s; j = j * s; + bool hit = !mixed && facing && abs(dets) >= 1.17549435e-38f && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); + det = dets; +"#; + +/// `PRELUDE_MEM` with the watertight triangle test (only for shaders that call `bvh_intersect`). +fn bvh_watertight_prelude_mem() -> String { + assert!(PRELUDE_MEM.contains(BVH_TRIANGLE_MT), "PRELUDE_MEM lost its triangle test"); + PRELUDE_MEM.replacen(BVH_TRIANGLE_MT, BVH_TRIANGLE_WATERTIGHT, 1) +} + const PRELUDE_MEM: &str = r#" uint4 ld_raw(uint a) { // one Load4 + one Load (with several memory windows each is a switch) and no branch diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index cd7b234bf8..89de9d0a87 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -382,6 +382,8 @@ mod translated { } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; + // `XCL_BVH_WATERTIGHT=1`: another BVH triangle test in the HLSL and the DXIL (off keeps the identity) + let id = if crate::gpu::bvh::watertight() { identity_for(&id.to_string(), "xcl-bvh-watertight") } else { id }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d23899a80f..84d5abca18 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6323,6 +6323,157 @@ fn gpu_triangle_pair_and_box16_nodes() { assert!(checked > 5, "{checked} triangle hits"); } +/// Watertight triangle test on the GPU: rays exactly through the edge a triangle pair shares +/// (type 0 = (v0, v1, v2) and type 1 = (v1, v3, v2) share v1–v2), along each axis and both +/// signs. Each ray goes to both triangles in neighbouring lanes: at least one hits on the GPU, +/// and at least one in the CPU reference (each checked on its own). +#[test] +fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { + use crate::gpu::bvh; + if !gpu_ready() { + return; + } + let base = 0x1000usize; + let mut mem = vec![0u32; 0x2000 / 4]; + let w = |mem: &mut Vec, at: usize, vals: &[u32]| mem[(base + at) / 4..(base + at) / 4 + vals.len()].copy_from_slice(vals); + let ff = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + // one skewed quad across each axis: v1 = (-1.3, 0.7), v2 = (1.1, -0.9) in the other two axes + let quad = [[-1.7f32, -1.9, 0.0], [-1.3, 0.7, 0.2], [1.1, -0.9, -0.1], [1.6, 1.8, 0.3]]; + let at = |axis: usize, p: [f32; 3]| { + let mut r = [0.0f32; 3]; + r[(axis + 1) % 3] = p[0]; + r[(axis + 2) % 3] = p[1]; + r[axis] = 5.0 + p[2]; + r + }; + for axis in 0..3 { + let verts: Vec = quad.iter().flat_map(|&p| at(axis, p)).collect(); + w(&mut mem, 0x40 * (axis + 1), &ff(&verts)); + w(&mut mem, 0x40 * (axis + 1) + 48, &[0x80, 0, 1, 0x0909]); + } + // nodes 4 and 5: the pinned pair of `bvh.rs` that Möller–Trumbore misses in both triangles, + // each as type 0 in the same vertex order (so the old test rounds as there), last two lanes + let (pa, pb) = ([1.911541f32, -2.025442, 0.78372467], [1.911541f32, 2.740394, -0.50947857]); + for (n, tri) in [[pa, pb, [2.1104007, -1.6796683, 9.487581]], [pb, pa, [1.5455573, 0.7414906, -8.11272]]].iter().enumerate() { + w(&mut mem, 0x100 + 0x40 * n, &ff(&tri.concat())); + w(&mut mem, 0x100 + 0x40 * n + 48, &[0, 0, 1, 0x0909]); + } + let pinned_ray = ([5.911541f32, -0.8080063, 0.59203976], [-1.0f32, -0.13060194, 0.000772506], 3usize); + 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 st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); // word 3 bit 24: barycentric result (mode 1) + let mut r = bvh::tests::rng(23); + let mut rays = vec![]; + let mut ray = ([0.0f32; 3], [0.0f32; 3], 0usize); + for (l, v) in st.vgpr.iter_mut().enumerate() { + if l % 2 == 0 { + let axis = (l / 2) % 3; + let s = r(0.0, 1.0); + let (v1, v2) = (at(axis, quad[1]), at(axis, quad[2])); + let on = [0, 1, 2].map(|a| v1[a] + s * (v2[a] - v1[a])); + let mut d = [r(-0.4, 0.4), r(-0.4, 0.4), r(-0.4, 0.4)]; + d[axis] = if (l / 6) % 2 == 0 { 1.0 } else { -1.0 }; + ray = ([0, 1, 2].map(|a| on[a] - 3.0 * d[a]), d, axis); + } + if l >= 62 { + ray = pinned_ray; + } + let (o, d, axis) = ray; + let inv = d.map(|x| 1.0 / x); + let node = if axis == 3 { (0x100 + 0x40 * (l as u32 % 2)) >> 3 } else { ((0x40 * (axis as u32 + 1)) >> 3) | (l as u32 % 2) }; + v[0] = node; + for (k, x) in [100.0f32, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].iter().enumerate() { + v[1 + k] = x.to_bits(); + } + rays.push((node, o, d, inv)); + } + let res = bvh::tests::with_watertight(true, || runner::run_code(&code, &st, &mem)).unwrap(); + let data: Vec = mem[base / 4..].iter().flat_map(|x| x.to_le_bytes()).collect(); + // GPU and CPU may round 1 / d differently, so on the edge each is checked on its own + let (mut gh, mut ch) = ([false; 2], [false; 2]); + for (l, &(node, o, d, inv)) in rays.iter().enumerate() { + gh[l % 2] = f32::from_bits(res.vgpr[l][100]).is_finite(); + ch[l % 2] = f32::from_bits(bvh::tests::with_watertight(true, || bvh::intersect_node(&data, node, 100.0, o, d, inv, true))[0]).is_finite(); + if l % 2 == 1 { + assert!(gh[0] || gh[1], "lanes {} and {l}: GPU ray through the shared edge missed both", l - 1); + assert!(ch[0] || ch[1], "lanes {} and {l}: CPU ray through the shared edge missed both", l - 1); + } + } + // the pinned lanes separate the tests: the old one (switch off) misses both there + let ((n0, o, d, inv), n1) = (rays[62], rays[63].0); + let mt = |n| f32::from_bits(bvh::tests::with_watertight(false, || bvh::intersect_node(&data, n, 100.0, o, d, inv, true))[0]); + assert!(mt(n0).is_infinite() && mt(n1).is_infinite(), "Möller–Trumbore hits the pinned pair"); +} + +/// The #3038 review cases (`bvh::tests::review_cases`: coplanar ray, overflowing sheared depth, +/// zero encoded denominator) plus the small triangle with a unit direction, one per lane, with +/// the watertight test on the GPU (HLSL, or the direct DXIL with `XCL_DIRECT_DXIL=1`): the node +/// result is the CPU reference's bit for bit, and hit / miss is as the review expects. +#[test] +fn gpu_bvh_watertight_review_cases_match_the_cpu() { + use crate::gpu::bvh; + if !gpu_ready() { + return; + } + let base = 0x1000usize; + let mut mem = vec![0u32; 0x2000 / 4]; + let w = |mem: &mut Vec, at: usize, vals: &[u32]| mem[(base + at) / 4..(base + at) / 4 + vals.len()].copy_from_slice(vals); + let [c1, c2, c3] = bvh::tests::review_cases(); + let cases = [(c1, false), (c2, true), (c3, false), ((c3.0, c3.1, [0.0, 0.0, 1.0]), true)]; + for (k, ((tri, _, _), _)) in cases.iter().enumerate() { + let v: Vec = tri.concat().iter().map(|x| x.to_bits()).collect(); + w(&mut mem, 0x40 * (k + 1), &v); + w(&mut mem, 0x40 * (k + 1) + 48, &[0, 0, 1, 0x0909]); + } + 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 st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); // word 3 bit 24: barycentric result (mode 1) + let lane = |l: usize| (l % cases.len(), (0x40 * (l % cases.len() as usize + 1) as u32) >> 3); + for (l, v) in st.vgpr.iter_mut().enumerate() { + let (k, node) = lane(l); + let ((_, o, d), _) = cases[k]; + let inv = d.map(|x| 1.0 / x); + v[0] = node; + for (n, x) in [f32::MAX, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].iter().enumerate() { + v[1 + n] = x.to_bits(); + } + } + let res = bvh::tests::with_watertight(true, || runner::run_code(&code, &st, &mem)).unwrap(); + let data: Vec = mem[base / 4..].iter().flat_map(|x| x.to_le_bytes()).collect(); + for l in 0..cases.len() { + let (k, node) = lane(l); + let ((_, o, d), hit) = cases[k]; + let cpu = bvh::tests::with_watertight(true, || bvh::intersect_node(&data, node, f32::MAX, o, d, d.map(|x| 1.0 / x), true)); + let gpu: [u32; 4] = res.vgpr[l][100..104].try_into().unwrap(); + assert_eq!(gpu, cpu, "case {}: GPU {:?} CPU {:?}", k + 1, gpu.map(f32::from_bits), cpu.map(f32::from_bits)); + assert_eq!(f32::from_bits(cpu[0]).is_finite(), hit, "case {}: {:?}", k + 1, cpu.map(f32::from_bits)); + } +} + +/// `XCL_BVH_WATERTIGHT` selects the triangle test in the HLSL and in the direct DXIL. Off, the +/// HLSL has main's Möller–Trumbore text and nothing of the switch (DXC cache keys unchanged); +/// on, only a program that calls `bvh_intersect` changes. +#[test] +fn bvh_watertight_switch_changes_the_hlsl_and_the_dxil() { + use crate::gpu::bvh::tests::with_watertight; + 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 hlsl = |code: &[u8], on| with_watertight(on, || translate(code, &Options::default()).unwrap().hlsl); + let (off, on) = (hlsl(&code, false), hlsl(&code, true)); + assert!(!off.contains("XCL_BVH_WATERTIGHT") && !on.contains("XCL_BVH_WATERTIGHT")); + assert!(off.contains(super::emit::BVH_TRIANGLE_MT) && !off.contains("precise float sz")); + assert!(on.contains("precise float sz") && !on.contains("p = cross(d, e2)")); + let plain = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None)]); + assert_eq!(hlsl(&plain, false), hlsl(&plain, true), "a program without BVH changed"); + let dxil = |on| with_watertight(on, || runner::direct_kernel(&code, true)); + match (dxil(false), dxil(true)) { + (Ok(off), Ok(on)) => assert_ne!(off, on, "direct DXIL is the same with and without the switch"), + (a, b) => panic!("direct DXIL: {:?} / {:?}", a.err(), b.err()), + } +} + /// Multi-window `image_bvh64_intersect_ray` (full 64-bit node pointer into UMA window 1 with /// base = 0, plus 48-bit base in window 1) and axis-aligned grazing ray / NaN-disabled box. #[test]