From a56538a588f72f053be108b6efedfa044d248839 Mon Sep 17 00:00:00 2001 From: nog <177071794+brothernog@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:00:57 -0300 Subject: [PATCH] Recompiler: gather4 with an explicit LOD reads the mip it names (HLSL) image_gather4_l / _l_o took mip 0 in the HLSL backend. The level now follows the S# as in the direct backend (#1951): LOD plus LOD_BIAS, clamped to MIN_LOD..MAX_LOD, raised to the T# MIN_LOD, then floor(l + 257/512) (the LOD rounded to 1/256, ties up), clamped to the view's mips; MIP_FILTER none reads floor(T# MIN_LOD). The four taps are Loads at that level with the S# addressing applied per axis, so the host sampler and the view's clamp cannot move them. The half-border modes (4, 5) give no border colour, as in desc::sampler_d3d12 and the direct backend. 2D and 2D arrays; cube and 3D are refused. The kernel test runner gets mip chains (TestTexture::mips from the data length). gpu_gather4_explicit_lod_hlsl / _direct run the same cases through each backend (one test per backend, so a driver crash names it); the direct one runs #1951's code on a GPU. --- crates/xcl/src/gpu/recomp/emit.rs | 56 ++++++- crates/xcl/src/gpu/recomp/runner.rs | 46 ++++-- crates/xcl/src/gpu/recomp/tests.rs | 229 ++++++++++++++++++++++++++++ 3 files changed, 320 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f6facf9b08..5764beed6b 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2749,7 +2749,13 @@ impl Em { self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({idx})];")); let sampler = self.sampler_ref(d.pc, has_c, &s3); self.line(&format!("{samp} {t}_S = {sampler};")); - if let Some(o) = &offset { + // gather4_l / _l_o: the 2x2 footprint of the mip the S# and `lod` name. HLSL's Gather has no + // level, so the four texels are Loads (compare forms keep the mip-0 GatherCmp) + let glod = base.starts_with("gather4") && lod.is_some() && !has_c; + if glod && !matches!(dim, 1 | 5) { + return Err("gather4 explicit LOD (not 2D)"); + } + if let (Some(o), false) = (&offset, glod) { let level = match (&lod, has_lz || base.starts_with("gather4"), ps && grads.is_none() && !has_c) { (_, true, _) => "0u".to_string(), (Some(l), _, _) => format!("(uint)max(round({l}), 0.0f)"), @@ -2764,6 +2770,47 @@ impl Em { } let ch = ["Red", "Green", "Blue", "Alpha"][comps[0] as usize]; match &cmp { + _ if glod => { + let l = lod.clone().unwrap_or_default(); + let [w0, w1, w2, w3] = match self.static_ss.get(&d.pc) { + Some(w) => w.map(|x| format!("{x}u")), + None => [self.sreg(ssamp), self.sreg(ssamp + 1), self.sreg(ssamp + 2), s3.clone()], + }; + let dims = |lv: &str| if dim == 5 { format!("{t}_T.GetDimensions({lv}, {t}_gw, {t}_gh, {t}_gz, {t}_gn);") } else { format!("{t}_T.GetDimensions({lv}, {t}_gw, {t}_gh, {t}_gn);") }; + self.line(&format!("uint {t}_gw = 1u, {t}_gh = 1u, {t}_gz = 1u, {t}_gn = 1u; {}", dims("0u"))); + // level (gfx1036 measurement): LOD + S# bias, clamped to the S# MIN_LOD..MAX_LOD, raised to the + // T# MIN_LOD, then the nearest level: the LOD is first rounded to 1/256 (halves up), then ties go up, + // both in floor(l + 257/512) (exact in f32); MIP_FILTER none reads floor(T# MIN_LOD). All u4.8. + // shortcut: T# MIN_LOD taken relative to the view's base level, measured with BASE_LEVEL 0 only + let tmin = format!("((float)(({tw1} >> 8) & 0xFFFu) / 256.0f)"); + self.line(&format!( + "uint {t}_gl = min((({w2} >> 26) & 3u) == 0u ? (uint)floor({tmin}) : (uint)floor(max(clamp({l} + (float)(((int)({w2} << 18)) >> 18) / 256.0f, (float)({w1} & 0xFFFu) / 256.0f, (float)(({w1} >> 12) & 0xFFFu) / 256.0f), {tmin}) + 0.501953125f), max({t}_gn, 1u) - 1u); {}", + dims(&format!("{t}_gl")) + )); + let o = offset.as_ref().map(|o| format!(" + int2(((int)({o} << 26)) >> 26, ((int)({o} << 18)) >> 26)")).unwrap_or_default(); + self.line(&format!("int2 {t}_gs = int2((int){t}_gw, (int){t}_gh);")); + self.line(&format!("int2 {t}_gp = int2(floor(float2({}, {}) * float2({t}_gs) - 0.5f)){o};", coords_unmoved[0], coords_unmoved[1])); + // integer taps: the S# addressing is applied here, so no sampler LOD clamp / bias can change the level + self.line(&format!( + "int4 {t}_ga = int4(gat_ax({t}_gp.x, {t}_gs.x, {w0} & 7u), gat_ax({t}_gp.x + 1, {t}_gs.x, {w0} & 7u), gat_ax({t}_gp.y, {t}_gs.y, ({w0} >> 3) & 7u), gat_ax({t}_gp.y + 1, {t}_gs.y, ({w0} >> 3) & 7u));" + )); + let ci = comps[0] as usize; + let border = if ci == 3 { format!("((({w3} >> 30) - 1u) < 2u ? 1.0f : 0.0f)") } else { format!("(({w3} >> 30) == 2u ? 1.0f : 0.0f)") }; + let c = ["r", "g", "b", "a"][ci]; + let layer = if dim == 5 { + self.line(&format!("int {t}_gk = min(max((int)round({}), 0), (int){t}_gz - 1);", coords_unmoved[2])); + format!(", {t}_gk") + } else { + String::new() + }; + let ld = if dim == 5 { "int4" } else { "int3" }; + // D3D Gather order: (x, y+1), (x+1, y+1), (x+1, y), (x, y) + let tap = |x: &str, y: &str| { + let (x, y) = (format!("{t}_ga.{x}"), format!("{t}_ga.{y}")); + format!("(({x} < 0 || {y} < 0) ? {border} : {t}_T.Load({ld}({x}, {y}{layer}, (int){t}_gl)).{c})") + }; + format!("float4({}, {}, {}, {})", tap("x", "w"), tap("y", "w"), tap("y", "z"), tap("x", "z")) + } Some(z) => format!("{t}_T.GatherCmp{ch}({t}_S, {coord}, {z})"), None => format!("{t}_T.Gather{ch}({t}_S, {coord})"), } @@ -5934,6 +5981,13 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i } return uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); } +// gather4_l texel index i of an n-texel axis under S# address mode m (0 wrap, 1 mirror, 2 / 4 clamp, 3 / 5 mirror once, 6 clamp border, +// 7 mirror-once border; the half-border modes 4 / 5 give no border colour, as in desc::sampler_d3d12 and the direct backend); -1: the border colour +int gat_ax(int i, int n, uint m) { + uint t = i < 0 ? (uint)~i : (uint)i; uint r = t % (m == 1u ? 2u * (uint)n : (uint)n); + int v = m == 0u ? (i < 0 ? n - 1 - (int)r : (int)r) : m == 1u ? (r < (uint)n ? (int)r : 2 * n - 1 - (int)r) : (m & 1u) == 0u ? clamp(i, 0, n - 1) : (int)min(t, (uint)n - 1u); + return ((m == 6u && (i < 0 || i >= n)) || (m == 7u && t >= (uint)n)) ? -1 : v; +} uint img_cls(uint fmt) { uint ty = select(fmt <= 77u, (FMT_INFO[min(fmt, 77u)] >> 3) & 7u, 6u); return select(ty == 4u, 1u, select(ty == 5u, 2u, 0u)); } void put_bits(inout uint4 r, uint off, uint w, uint v) { uint m = w >= 32u ? 0xFFFFFFFFu : ((1u << w) - 1u); v &= m; diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 0d020cd63f..cc56f091b0 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -167,11 +167,34 @@ pub struct TestTexture { /// array slices (cube: 6 per cube) or depth pub depth: u32, pub texel_bytes: u32, - /// tightly packed texels, slice after slice + /// tightly packed texels, slice after slice (each slice: its mip levels one after the other) pub data: Vec, pub uav: bool, } +impl TestTexture { + /// Mip levels, from the data's length: an SRV-only 2D or 2D array texture whose `data` holds + /// every slice's full chain down to some level has that many; anything else has 1. (Not a + /// field, so the struct literals of tests that don't care need no change.) + pub fn mips(&self) -> u32 { + if self.uav || !matches!(self.dim, TexDim::D2 | TexDim::D2Array) { + return 1; + } + let mut bytes = 0usize; + for m in 0..16 { + let (w, h) = ((self.width >> m).max(1), (self.height >> m).max(1)); + bytes += (w * h * self.texel_bytes * self.depth) as usize; + if bytes == self.data.len() { + return m + 1; + } + if bytes > self.data.len() || (w == 1 && h == 1) { + break; + } + } + 1 + } +} + /// A sampler for kernel tests at sampler heap index j. pub struct TestSampler { pub filter: D3D12_FILTER, @@ -273,13 +296,13 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t Width: t.width as u64, Height: t.height, DepthOrArraySize: depth_or_array as u16, - MipLevels: 1, + MipLevels: t.mips() as u16, Format: t.format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: if t.uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, ..Default::default() } }; - let subs = if t.dim == TexDim::D3 { 1 } else { t.depth }; + let subs = if t.dim == TexDim::D3 { 1 } else { t.depth * t.mips() }; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); subs as usize]; let mut size = 0u64; dev.GetCopyableFootprints(&rd, 0, subs, total, Some(fps.as_mut_ptr()), None, None, Some(&mut size)); @@ -298,17 +321,20 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t mk += 1; } for (t, fps) in textures.iter().zip(&plans).filter(|(t, _)| t.dim.samples().is_none()) { - let row = (t.width * t.texel_bytes) as usize; - let slices = t.depth as usize; + let mut at = 0usize; + let slices = if t.dim == TexDim::D3 { t.depth } else { t.depth * t.mips() } as usize; for z in 0..slices { + let (w, h) = if t.dim == TexDim::D3 { (t.width, t.height) } else { ((t.width >> (z as u32 % t.mips())).max(1), (t.height >> (z as u32 % t.mips())).max(1)) }; + let row = (w * t.texel_bytes) as usize; let fp = if t.dim == TexDim::D3 { &fps[0] } else { &fps[z] }; - let slice_pitch = fp.Footprint.RowPitch as usize * t.height as usize; + let slice_pitch = fp.Footprint.RowPitch as usize * h as usize; let zoff = if t.dim == TexDim::D3 { z * slice_pitch } else { 0 }; - for y in 0..t.height as usize { - let src = &t.data[(z * t.height as usize + y) * row..][..row]; + for y in 0..h as usize { + let src = &t.data[at + y * row..][..row]; let dst = (p as *mut u8).add(fp.Offset as usize + zoff + y * fp.Footprint.RowPitch as usize); std::ptr::copy_nonoverlapping(src.as_ptr(), dst, row); } + at += row * h as usize; } } up.Unmap(0, None); @@ -361,12 +387,12 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t } TexDim::D2 => { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }; + sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: t.mips(), ..Default::default() }; uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; } TexDim::D2Array => { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - sv.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: 1, ArraySize: t.depth, ..Default::default() }; + sv.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: t.mips(), ArraySize: t.depth, ..Default::default() }; uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; uv.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: t.depth, ..Default::default() }; } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 60a1bf1d25..83d586601d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2982,6 +2982,235 @@ fn gpu_image_load_reads_a_store_of_the_same_dispatch() { assert!(bad.is_empty(), "image_load after image_store of the same dispatch (want 1000 + lane, 1000 + (lane ^ 1)):\n{}", bad.join("\n")); } +/// `image_gather4_l` / `_l_o` read the 2x2 footprint of the mip the S# and the LOD name, not mip 0: +/// level = floor(LOD + S# bias, clamped to the S# MIN_LOD..MAX_LOD, raised to the T# MIN_LOD, + 257/512) (the +/// LOD rounded to 1/256 with halves up, then ties up: 0.499 -> 1), floor(T# MIN_LOD) with MIP_FILTER none, clamped to the view's mips. Every mip and texel holds its own value, the offsets are negative / +/// far out, and the S# address modes (wrap, mirror, clamp, mirror once, borders) apply per texel. Both the +/// HLSL and the direct DXIL backend run it (one test each, so a driver crash names its backend), whatever +/// `XCL_DIRECT_DXIL` says. +#[test] +fn gpu_gather4_explicit_lod_hlsl() { + gather4_explicit_lod(false); +} + +/// `gpu_gather4_explicit_lod_hlsl` through the direct DXIL backend. +#[test] +fn gpu_gather4_explicit_lod_direct() { + gather4_explicit_lod(true); +} + +fn gather4_explicit_lod(direct: bool) { + if !gpu_ready() { + return; + } + use runner::{TestSampler, TestTexture, TexDim}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32B32A32_FLOAT; + let mimg = |name: &'static str, f: &[(&str, u64)]| -> Vec { encode(name, "ENC_MIMG", f, None).unwrap() }; + let mut code = Vec::new(); + // T# 2D in s[16:23] (SRSRC 4), T# 2D array in s[24:31] (SRSRC 6), S# linear clamp in s[32:35] (SSAMP 8) + code.extend(mimg("IMAGE_GATHER4_L", &[("VDATA", 20), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 8), ("DMASK", 0x1), ("DIM", 1)])); + code.extend(mimg("IMAGE_GATHER4_L_O", &[("VDATA", 30), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 8), ("DMASK", 0x1), ("DIM", 1)])); + code.extend(mimg("IMAGE_GATHER4_L", &[("VDATA", 40), ("VADDR", 8), ("SRSRC", 6), ("SSAMP", 8), ("DMASK", 0x1), ("DIM", 5)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + // 8 x 8, 4 mips; the red channel of texel (x, y) of mip m of layer a = 5000 a + 1000 m + 10 y + x + let data = |layers: u32| { + let mut d = Vec::new(); + for a in 0..layers { + for m in 0..4u32 { + let size = 8 >> m; + for y in 0..size { + for x in 0..size { + for v in [(5000 * a + 1000 * m + 10 * y + x) as f32, 0.0, 0.0, 1.0] { + d.extend_from_slice(&v.to_le_bytes()); + } + } + } + } + } + d + }; + let tex = [ + TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 8, height: 8, depth: 1, texel_bytes: 16, data: data(1), uav: false }, + TestTexture { dim: TexDim::D2Array, format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 8, height: 8, depth: 2, texel_bytes: 16, data: data(2), uav: false }, + ]; + let samp = [TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }]; + + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&tsharp(0, 77, 9)); + st.sgpr[24..32].copy_from_slice(&tsharp(2, 77, 13)); + // none of these lands on a texel boundary (coord * size - 0.5 is never an integer at 8, 4 or 2 texels) + let us = [0.0f32, 0.3, 0.7, 1.0, 0.99, 0.02, 0.45, 0.83]; + let vs = [1.0f32, 0.0, 0.7, 0.3, 0.02, 0.99, 0.45, 0.83]; + let offs = [(-1i32, 0i32), (0, -1), (1, 1), (-2, -3), (3, 2), (0, 0), (-1, -1), (7, -5)]; + // 0; the ties 0.5 -> 1 and 2.5 -> 3; 1; 0.499 -> 1 (1/256 rounding first); 2; past the last mip (3); negative (0) + let lods = [0.0f32, 0.5, 1.0, 0.499, 2.0, 2.5, 5.0, -1.0]; + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (c, lod) = (l % 8, lods[l / 8 % 8]); + r[0] = f(us[c]); + r[1] = f(vs[c]); + r[2] = f(lod); + r[4] = ((offs[c].0 & 0x3F) | ((offs[c].1 & 0x3F) << 8)) as u32; + r[5] = f(us[c]); + r[6] = f(vs[c]); + r[7] = f(lod); + r[8] = f(us[c]); + r[9] = f(vs[c]); + r[10] = f((l % 2) as f32); + r[11] = f(lod); + } + // cases: S# [word 0 (addressing), word 1 (MIN_LOD / MAX_LOD), word 2 (bias, MIP_FILTER), word 3 (border)], + // T# MIN_LOD (u4.8) + let (full, point) = (0xFFFu32 << 12, 1u32 << 26); + let clamp = 2 | 2 << 3 | 2 << 6; + let cases: [(&str, [u32; 4], u32); 18] = [ + ("clamp, point mip", [clamp, full, point, 0], 0), + ("linear mip gathers like point", [clamp, full, 2 << 26, 0], 0), + ("MAX_LOD 1", [clamp, 0x100 << 12, point, 0], 0), + ("MIN_LOD 2", [clamp, 0x200 | full, point, 0], 0), + ("MIP_FILTER none", [clamp, full, 0, 0], 0), + ("bias +1", [clamp, full, point | 256, 0], 0), + ("bias -1", [clamp, full, point | (-256i32 as u32 & 0x3FFF), 0], 0), + ("wrap", [0, full, point, 0], 0), + ("mirror", [1 | 1 << 3 | 1 << 6, full, point, 0], 0), + ("mirror once", [3 | 3 << 3 | 3 << 6, full, point, 0], 0), + ("wrap x, mirror y", [1 << 3, full, point, 0], 0), + ("clamp border, white", [6 | 6 << 3 | 6 << 6, full, point, 2 << 30], 0), + // the half-border modes give no border colour (desc::sampler_d3d12 maps them to clamp / mirror once) + ("clamp half border, black", [4 | 4 << 3 | 4 << 6, full, point, 1 << 30], 0), + ("mirror-once border x, half border y, white", [7 | 5 << 3 | 7 << 6, full, point, 2 << 30], 0), + // floor(T# MIN_LOD) at every LOD: 1.75 -> 1, 2.5 -> 2 + ("T# MIN_LOD 1.75, MIP_FILTER none", [clamp, full, 0, 0], 0x1C0), + ("T# MIN_LOD 2.5, MIP_FILTER none", [clamp, full, 0, 0], 0x280), + ("T# MIN_LOD 1.75, point mip", [clamp, full, point, 0], 0x1C0), + // the T# MIN_LOD comes after the S# clamp: 1.75 -> 2, not the S# MAX_LOD 1 + ("T# MIN_LOD 1.75 over S# MAX_LOD 1", [clamp, 0x100 << 12, point, 0], 0x1C0), + ]; + // Gather order (x, y + 1), (x + 1, y + 1), (x + 1, y), (x, y) of the footprint at the S# / T# level + let gather = |sh: [u32; 4], tmin: u32, layer: u32, u: f32, v: f32, lod: f32, off: (i32, i32)| -> [f32; 4] { + let k = |x: u32| x as f32 / 256.0; + let bias = (((sh[2] << 18) as i32) >> 18) as f32 / 256.0; + let l = (lod + bias).max(k(sh[1] & 0xFFF)).min(k(sh[1] >> 12 & 0xFFF)).max(k(tmin)); + let m = if sh[2] >> 26 & 3 == 0 { k(tmin).floor() as u32 } else { (l + 257.0 / 512.0).floor() as u32 }.min(3); + let size = 8 >> m; + let (px, py) = ((u * size as f32 - 0.5).floor() as i32 + off.0, (v * size as f32 - 0.5).floor() as i32 + off.1); + // texel index under an address mode, None: the border colour + let addr = |i: i32, mode: u32| -> Option { + let (n, once) = (size, if i < 0 { -i - 1 } else { i }); + match mode { + 0 => Some(i.rem_euclid(n)), + 1 => Some(i.rem_euclid(2 * n)).map(|r| if r < n { r } else { 2 * n - 1 - r }), + 2 => Some(i.clamp(0, n - 1)), + 3 => Some(once.min(n - 1)), + 4 => Some(i.clamp(0, n - 1)), + 5 => Some(once.min(n - 1)), + 6 => (0..n).contains(&i).then_some(i), + _ => (once < n).then_some(once), + } + }; + let border = if sh[3] >> 30 == 2 { 1.0 } else { 0.0 }; + let at = |x: i32, y: i32| match (addr(x, sh[0] & 7), addr(y, sh[0] >> 3 & 7)) { + (Some(x), Some(y)) => (5000 * layer + 1000 * m) as f32 + (10 * y + x) as f32, + _ => border, + }; + [at(px, py + 1), at(px + 1, py + 1), at(px + 1, py), at(px, py)] + }; + let (backend, dxil, statics) = if direct { + let k = runner::direct_kernel_full(&code, true).unwrap(); + ("direct dxil", k.dxil, k.static_samplers) + } else { + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + ("hlsl", super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), t.static_samplers) + }; + let tw1 = (st.sgpr[17], st.sgpr[25]); + for (case, sharp, tmin) in cases { + st.sgpr[32..36].copy_from_slice(&sharp); + st.sgpr[17] = tw1.0 & !(0xFFF << 8) | tmin << 8; + st.sgpr[25] = tw1.1 & !(0xFFF << 8) | tmin << 8; + let r = runner::run_with_statics(&dxil, &st, &[], &tex, &samp, &statics).unwrap(); + for l in 0..64 { + let (c, lod) = (l % 8, lods[l / 8 % 8]); + let v = &r.vgpr[l]; + let got = |b: usize| [0, 1, 2, 3].map(|i| f32::from_bits(v[b + i])); + let what = format!("{backend} [{case}] lane {l} (uv {}, {}; lod {lod}; offset {:?})", us[c], vs[c], offs[c]); + assert_eq!(got(20), gather(sharp, tmin, 0, us[c], vs[c], lod, (0, 0)), "gather4_l {what}"); + assert_eq!(got(30), gather(sharp, tmin, 0, us[c], vs[c], lod, offs[c]), "gather4_l_o {what}"); + assert_eq!(got(40), gather(sharp, tmin, (l % 2) as u32, us[c], vs[c], lod, (0, 0)), "gather4_l 2D array {what}"); + } + } +} + +/// `image_gather4_l` in a pixel shader, through the host sampler of the S#: its MinLOD / MaxLOD / bias and +/// the SRV's clamp must not move the footprint to another mip. An 8 x 8, 4-mip texture (texel x of mip m +/// holds 100 m + x), point x / y, clamp: (a) LOD 1 with a point mip filter reads mip 1, (b) LOD 2 with +/// MAX_LOD 1 reads mip 1, (c) LOD 1 with MIP_FILTER none reads mip 0. +#[test] +fn gpu_ps_image_gather4_l_s_sharp_level() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_SAMPLE_DESC}; + let mut data = Vec::new(); + for m in 0..4u32 { + let n = 8 >> m; + for _y in 0..n { + for x in 0..n { + data.extend_from_slice(&[(100 * m + x) as f32; 4].map(f32::to_le_bytes).concat()); + } + } + } + let res = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 4, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + srv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 4, ..Default::default() }; + let clamp = 2 | 2 << 3 | 2 << 6; + // (case, LOD inline constant: 242 = 1.0, 244 = 2.0, S# word 1, S# word 2, level) + for (case, lod, w1, w2, level) in [ + ("(a) LOD 1, full range, point mip", 242, 0xFFFu32 << 12, 1u32 << 26, 1u32), + ("(b) LOD 2, MAX_LOD 1", 244, 0x100 << 12, 1 << 26, 1), + ("(c) LOD 1, MIP_FILTER none", 242, 0xFFF << 12, 0, 0), + ] { + let ps = prog(&[ + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 255), ("VSRC1", 2)], Some((1.0f32 / 16.0).to_bits())), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], Some((1.0f32 / 16.0).to_bits())), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", lod)], None), + ("IMAGE_GATHER4_L", "ENC_MIMG", &[("VDATA", 8), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11), ("DONE", 1), ("VM", 1)], None), + ]); + let tex = runner::ViewTexture { res, srv, data: data.clone(), row_bytes: 8 * 16 }; + let s_sharp = [clamp, w1, w2, 0]; + let mut sgprs = vec![0u32; 32]; + sgprs[16..24].copy_from_slice(&tsharp(0, 77, 9)); + sgprs[24..28].copy_from_slice(&s_sharp); + let px = draw_console_views(None, Some(&ps), &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]], &sgprs, &[tex], &[crate::gpu::desc::sampler_d3d12(&s_sharp, false)]); + let n = 8 >> level; + let wrong = (0..256) + .filter(|&i| { + let left = (((i % 16) as f32 + 0.5) / 16.0 * n as f32 - 0.5).floor() as i32; + let t = |c: i32| (100 * level as i32 + c.clamp(0, n - 1)) as f32; + px[i] != [t(left), t(left + 1), t(left + 1), t(left)] + }) + .count(); + assert_eq!(wrong, 0, "{case}: pixels off the level-{level} footprint, e.g. {:?}", px[7]); + } +} + /// Static samplers: the program builds two S# from constants (point / linear, clamp) – as /// the console compiler places a root signature's static samplers – and samples the same /// texel boundary with each; they become static samplers of the root signature.