From 2169264ca98fb0adae99559b2a4310718296a455 Mon Sep 17 00:00:00 2001 From: kilolimaVI <361259062+kilolimaVI@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:02:17 +0200 Subject: [PATCH 1/6] Shaders: quad reads at a triangle edge without the console's compiler flow_tests draws the derivative and quad-read cases from console-compiled HLSL, so it needs the console SDK's dxc.exe and most machines skip it. quad_read_tests hand-assembles the same shapes: each pixel computes a key from its position and reads its x, y and diagonal neighbours' keys with DPP quad_perm, on a triangle whose edge crosses quads (helper lanes), and again after the console's form of a discard (v_cmpx, s_andn2 of the live mask, s_cbranch_scc0 to a null export, s_wqm), whose killed pixels stay helpers and must not be written. wave32 and wave64, hardware and WARP. Radeon 780M (RDNA3) and WARP at 63bcca4: edge 136 pixels, discard 104, 0 wrong in all eight. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/mod.rs | 2 + .../src/emit/quad_read_tests.rs | 266 ++++++++++++++++++ 2 files changed, 268 insertions(+) create mode 100644 crates/victory-shader/src/emit/quad_read_tests.rs diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 91a5e64b985..abe6cbb511f 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -210,6 +210,8 @@ mod flow_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; +#[cfg(all(test, windows))] +mod quad_read_tests; mod rect; pub use rect::{rectangle_gs, right_angle}; #[cfg(all(test, windows))] diff --git a/crates/victory-shader/src/emit/quad_read_tests.rs b/crates/victory-shader/src/emit/quad_read_tests.rs new file mode 100644 index 00000000000..7e71f5111d5 --- /dev/null +++ b/crates/victory-shader/src/emit/quad_read_tests.rs @@ -0,0 +1,266 @@ +//! Quad reads at a triangle edge, without the console's compiler: the +//! cases `flow_tests` draws from console-compiled HLSL (which needs the +//! console SDK's `dxc.exe`, so most machines skip them), hand-assembled. +//! Each pixel computes a key from its position and reads its x, y and +//! diagonal neighbours' keys with DPP `quad_perm`, as the console compiler +//! takes derivatives and `QuadReadAcross*`. Along the edge some neighbours +//! are helper lanes (whole-quad mode), and with a discard some are killed +//! pixels, which stay helpers: either must still give its key. + +use super::container::{SigElement, signature}; +use super::host::{Draw, Host}; +use super::{HostShader, emit}; +use crate::native::{HwStage, NativeProgram, StageIo, Usage, VsInput}; +use crate::{Container, FourCC, io, ir, resource, structure}; + +const EXEC_LO: u32 = 0x7E; +const S_ENDPGM: u32 = 0xBF81_0000; +const fn sop1(op: u32, d: u32, s: u32) -> u32 { + 0xBE80_0000 | d << 16 | op << 8 | s +} +const fn sop2(op: u32, d: u32, a: u32, b: u32) -> u32 { + 0x8000_0000 | op << 23 | d << 16 | b << 8 | a +} +const fn vop1(op: u32, d: u32, s: u32) -> u32 { + 0x7E00_0000 | d << 17 | op << 9 | s +} +const fn vop2(op: u32, d: u32, s0: u32, v1: u32) -> u32 { + op << 25 | d << 17 | v1 << 9 | s0 +} +const fn v(n: u32) -> u32 { + 256 + n +} +/// `v_mov_b32 v, v quad_perm:[..] bound_ctrl:1`. +const fn quad_perm(d: u32, s: u32, ctrl: u32) -> [u32; 2] { + [ + 0x7E00_0000 | d << 17 | 0x01 << 9 | 0xFA, + 0xF << 28 | 0xF << 24 | 1 << 19 | ctrl << 8 | s, + ] +} + +/// Each pixel's key, `3x + 5y + 1`: distinct within a quad. +fn key(x: u32, y: u32) -> u32 { + 3 * x + 5 * y + 1 +} + +/// Whether the discarding program kills pixel (x, y). +fn killed(x: u32, y: u32) -> bool { + (7 * x + 3 * y) & 5 == 5 +} + +/// The key in v4, optionally a discard of the pixels `killed` names (the +/// console's form: `v_cmpx` of the lanes killed, `s_andn2` of the live +/// mask and its SCC to a null export, then EXEC the whole quads of the +/// live mask), then the x, y and diagonal neighbours' keys in v5-v7. +/// Exports (key, x neighbour, y neighbour, diagonal) as floats, from the +/// live pixels. +fn pixel_program(wave64: bool, discard: bool) -> Vec { + // s_mov, s_andn2 and s_wqm on EXEC's 32 or 64 bits. + let (mov, andn2, wqm) = if wave64 { + (0x04, 0x15, 0x0A) + } else { + (0x03, 0x14, 0x09) + }; + let mut w = vec![ + vop1(0x07, 2, v(0)), // v_cvt_u32_f32 v2, v0 (x) + vop1(0x07, 3, v(1)), // v_cvt_u32_f32 v3, v1 (y) + vop2(0x0B, 4, 128 + 3, 2), // v_mul_u32_u24 v4, 3, v2 + vop2(0x0B, 5, 128 + 5, 3), // v_mul_u32_u24 v5, 5, v3 + vop2(0x25, 4, v(4), 5), // v_add_nc_u32 v4, v4, v5 + vop2(0x25, 4, 128 + 1, 4), // v_add_nc_u32 v4, 1, v4 + ]; + let mut kill_at = None; + if discard { + w.extend([ + vop2(0x0B, 8, 128 + 7, 2), // v_mul_u32_u24 v8, 7, v2 + vop2(0x0B, 9, 128 + 3, 3), // v_mul_u32_u24 v9, 3, v3 + vop2(0x25, 8, v(8), 9), // v_add_nc_u32 v8, v8, v9 + vop2(0x1B, 8, 128 + 5, 8), // v_and_b32 v8, 5, v8 + sop1(mov, 10, EXEC_LO), // s_mov s10, exec (live) + 0x7C00_0000 | 0xD2 << 17 | 8 << 9 | (128 + 5), // v_cmpx_eq_u32 5, v8 (killed) + sop2(andn2, 10, 10, EXEC_LO), // s_andn2 s10, s10, exec + ]); + kill_at = Some(w.len()); + w.push(0); // s_cbranch_scc0 -> kill, patched below + w.push(sop1(wqm, EXEC_LO, 10)); // s_wqm exec, s10 + } + for (d, ctrl) in [(5, 0xB1), (6, 0x4E), (7, 0x1B)] { + w.extend(quad_perm(d, 4, ctrl)); // [1,0,3,2], [2,3,0,1], [3,2,1,0] + } + for r in 4..8 { + w.push(vop1(0x06, r, v(r))); // v_cvt_f32_u32 + } + if discard { + w.push(sop1(mov, EXEC_LO, 10)); // s_mov exec, s10: the live pixels export + } + w.extend([0xF800_180F, 0x0706_0504, S_ENDPGM]); // exp mrt0 v4-v7 done vm + if let Some(at) = kill_at { + let offset = (w.len() - at - 1) as u32; + w[at] = 0xBF80_0000 | 0x04 << 16 | offset; // s_cbranch_scc0 + w.extend([0xF800_1890, 0, S_ENDPGM]); // kill: exp null done vm + } + w +} + +fn sig(name: &str, kind: u8, interp: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + } +} + +fn translate(native: &NativeProgram, inputs: &[SigElement], outputs: &[SigElement]) -> HostShader { + let isg = signature(inputs, true); + let osg = signature(outputs, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg), (FourCC::OSG1, &osg)]); + let c = Container::parse(&bytes).expect("container"); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource"); + let io = io::raise(&p, native).expect("io"); + let h = emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut val) = + super::validator::Validator::load(super::validator::Validator::default_path().as_deref()) + { + val.validate(&mut h.dxil.clone()) + .expect("DXIL validation failed"); + } + h +} + +/// Quad reads of computed values reach the neighbours a triangle edge +/// leaves outside it (helper lanes) and the pixels a discard kills: every +/// drawn pixel reads its x, y and diagonal neighbours' keys, in wave32 and +/// wave64, on the hardware adapter and WARP. +#[test] +fn quad_reads_at_a_triangle_edge_reach_helpers_and_killed_pixels() { + let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done + let vs = translate( + &NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Vs { + inputs: vec![VsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + vgpr: 4, + }], + outputs: Vec::new(), + }, + code: vs_code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }, + &[sig("POSITION", 0, 0)], + &[sig("SV_Position", 3, 4)], + ); + // A triangle whose diagonal crosses quads of a 16x16 target. + let vertices = [ + -1.0, -1.0, 0.5, 1.0, // + -1.0, 1.1, 0.5, 1.0, // + 1.1, -1.0, 0.5, 1.0, + ]; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts: Vec<(&str, Host)> = [("hardware", false), ("warp", true)] + .into_iter() + .filter_map(|(label, warp)| Host::new(warp).ok().map(|h| (label, h))) + .collect(); + assert!(!hosts.is_empty(), "no SM 6.6 device"); + let mut failures = Vec::new(); + for discard in [false, true] { + for wave64 in [false, true] { + let ps = translate( + &NativeProgram { + stage: HwStage::Ps, + wave64, + vgprs: 10, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ps { + inputs: Vec::new(), + input_addr: 0x300, // SV_Position.x in v0, .y in v1 + db_shader_control: 0, + patches: Vec::new(), + }, + code: pixel_program(wave64, discard) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }, + &[sig("SV_Position", 3, 4)], + &[sig("SV_Target", 16, 0)], + ); + for (adapter, host) in &hosts { + let label = format!( + "{} wave{} {adapter}", + if discard { "discard" } else { "edge" }, + if wave64 { 64 } else { 32 } + ); + let (root, pso) = host + .pipeline(&vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pipeline: {e}")); + let pixels = host + .draw( + &root, + &pso, + &Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 16, + size: (16, 16), + mesh_groups: 0, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let (mut drawn, mut wrong, mut first) = (0, 0, None); + for (i, px) in pixels.iter().enumerate() { + let (x, y) = (i as u32 % 16, i as u32 / 16); + if px[0] != key(x, y) as f32 { + // Not drawn: outside the triangle or killed. + if discard && px[0] != 0.0 { + wrong += 1; + } + continue; + } + drawn += 1; + if discard && killed(x, y) { + wrong += 1; // a killed pixel was written + continue; + } + let want = [key(x ^ 1, y), key(x, y ^ 1), key(x ^ 1, y ^ 1)].map(|k| k as f32); + if px[1..] != want { + wrong += 1; + if first.is_none() { + first = Some(format!("({x}, {y}): {:?} instead of {want:?}", &px[1..])); + } + } + } + eprintln!( + "{label}: {drawn} pixels, {wrong} wrong{}", + first + .as_deref() + .map(|f| format!(", first {f}")) + .unwrap_or_default() + ); + if drawn < 50 || wrong > 0 { + failures.push(format!("{label}: {wrong} of {drawn}")); + } + } + } + } + assert!(failures.is_empty(), "{}", failures.join("; ")); +} From c7661dd85c22dde106147c3bc22b0ed37a9b97b5 Mon Sep 17 00:00:00 2001 From: kilolimaVI <361259062+kilolimaVI@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:19:30 +0200 Subject: [PATCH 2/6] Shaders: levels of detail at a triangle edge and after a discard lod_tests takes image_get_lod of coordinates linear in the pixel position (u = 0.3 x, v = 0.11 y of a 16x16 texture, so log2(4.8) at every pixel) next to a triangle edge and next to pixels the console's form of a discard killed: their helper lanes must compute the coordinates the derivatives take. wave32 and wave64, hardware and WARP, tolerance 0.02 of a level. Radeon 780M (RDNA3): 2.2617 at all 136 / 104 pixels (the level in 1/256 steps); WARP 2.2630; 0 wrong in all eight. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lod_tests.rs | 312 ++++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 2 + 2 files changed, 314 insertions(+) create mode 100644 crates/victory-shader/src/emit/lod_tests.rs diff --git a/crates/victory-shader/src/emit/lod_tests.rs b/crates/victory-shader/src/emit/lod_tests.rs new file mode 100644 index 00000000000..fab96dbf808 --- /dev/null +++ b/crates/victory-shader/src/emit/lod_tests.rs @@ -0,0 +1,312 @@ +//! A pixel program's level of detail at a triangle edge and after a +//! discard, without the console's compiler (`diff_tests`' "level of +//! detail" case needs the console SDK's `dxc.exe`). `image_get_lod` takes +//! the derivatives of the coordinates across each quad, so helper lanes +//! (outside the triangle, or killed by a discard) must have computed +//! theirs, or the level of the live pixels beside them is wrong. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::container::{SigElement, signature}; +use super::host::{Draw, Host, Root}; +use super::{HostShader, emit}; +use crate::native::{ + HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, Usage, UsedResource, + VsInput, +}; +use crate::{Container, FourCC, io, ir, resource, structure}; + +const EXEC_LO: u32 = 0x7E; +const S_ENDPGM: u32 = 0xBF81_0000; +const fn sop1(op: u32, d: u32, s: u32) -> u32 { + 0xBE80_0000 | d << 16 | op << 8 | s +} +const fn sop2(op: u32, d: u32, a: u32, b: u32) -> u32 { + 0x8000_0000 | op << 23 | d << 16 | b << 8 | a +} +const fn vop1(op: u32, d: u32, s: u32) -> u32 { + 0x7E00_0000 | d << 17 | op << 9 | s +} +const fn vop2(op: u32, d: u32, s0: u32, v1: u32) -> u32 { + op << 25 | d << 17 | v1 << 9 | s0 +} +const fn v(n: u32) -> u32 { + 256 + n +} + +/// The texture's size; one level. +const SIZE: u32 = 16; +/// The coordinates are `u = a * x`, `v = b * y` of the pixel position, so +/// the derivatives are `a` and `b` everywhere and the level is +/// `log2(SIZE * max(a, b))` (isotropic) at every pixel. +const A: f32 = 0.3; +const B: f32 = 0.11; + +fn level() -> f32 { + (SIZE as f32 * A.max(B)).log2() +} + +/// Whether the discarding program kills pixel (x, y). +fn killed(x: u32, y: u32) -> bool { + (7 * x + 3 * y) & 5 == 5 +} + +/// Loads the texture's descriptor (table at user data 4) into s[8:15] and +/// the sampler's (table at user data 6) into s[16:19], computes u and v in +/// v2 and v3, optionally discards (the console's form, as in +/// `quad_read_tests`, the live mask in s20), and exports `image_get_lod`'s clamped and unclamped +/// levels with 1.0 in alpha (drawn). +fn pixel_program(wave64: bool, discard: bool) -> Vec { + let (mov, andn2, wqm) = if wave64 { + (0x04, 0x15, 0x0A) + } else { + (0x03, 0x14, 0x09) + }; + let mut w = vec![ + sop1(0x03, 5, 0x80), // s_mov_b32 s5, 0 (table address, high) + sop1(0x03, 7, 0x80), // s_mov_b32 s7, 0 + 0x3D << 26 | 3 << 18 | 8 << 6 | 4 >> 1, // s_load_dwordx8 s[8:15], s[4:5], 0 + 125 << 25, + 0x3D << 26 | 2 << 18 | 16 << 6 | 6 >> 1, // s_load_dwordx4 s[16:19], s[6:7], 0 + 125 << 25, + vop2(0x08, 2, 0xFF, 0), // v_mul_f32 v2, A, v0 + A.to_bits(), + vop2(0x08, 3, 0xFF, 1), // v_mul_f32 v3, B, v1 + B.to_bits(), + ]; + let mut kill_at = None; + if discard { + w.extend([ + vop1(0x07, 6, v(0)), // v_cvt_u32_f32 v6, v0 (x) + vop1(0x07, 7, v(1)), // v_cvt_u32_f32 v7, v1 (y) + vop2(0x0B, 8, 128 + 7, 6), // v_mul_u32_u24 v8, 7, v6 + vop2(0x0B, 9, 128 + 3, 7), // v_mul_u32_u24 v9, 3, v7 + vop2(0x25, 8, v(8), 9), // v_add_nc_u32 v8, v8, v9 + vop2(0x1B, 8, 128 + 5, 8), // v_and_b32 v8, 5, v8 + sop1(mov, 20, EXEC_LO), // s_mov s20, exec (live) + 0x7C00_0000 | 0xD2 << 17 | 8 << 9 | (128 + 5), // v_cmpx_eq_u32 5, v8 (killed) + sop2(andn2, 20, 20, EXEC_LO), // s_andn2 s20, s20, exec + ]); + kill_at = Some(w.len()); + w.push(0); // s_cbranch_scc0 -> kill, patched below + w.push(sop1(wqm, EXEC_LO, 20)); // s_wqm exec, s20 + } + w.extend([ + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + // image_get_lod v[4:5], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:2D + 0xF000_0308 | 0x60 << 18, + 2 | 4 << 8 | 2 << 16 | 4 << 21, + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + vop1(0x01, 6, 0xF2), // v_mov_b32 v6, 1.0 + ]); + if discard { + w.push(sop1(mov, EXEC_LO, 20)); // s_mov exec, s20: the live pixels export + } + w.extend([0xF800_180F, 0x0606_0504, S_ENDPGM]); // exp mrt0 v4, v5, v6, v6 done vm + if let Some(at) = kill_at { + let offset = (w.len() - at - 1) as u32; + w[at] = 0xBF80_0000 | 0x04 << 16 | offset; // s_cbranch_scc0 + w.extend([0xF800_1890, 0, S_ENDPGM]); // kill: exp null done vm + } + w +} + +fn sig(name: &str, kind: u8, interp: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + } +} + +fn translate(native: &NativeProgram, inputs: &[SigElement], outputs: &[SigElement]) -> HostShader { + let isg = signature(inputs, true); + let osg = signature(outputs, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg), (FourCC::OSG1, &osg)]); + let c = Container::parse(&bytes).expect("container"); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource"); + let io = io::raise(&p, native).expect("io"); + let h = emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut val) = + super::validator::Validator::load(super::validator::Validator::default_path().as_deref()) + { + val.validate(&mut h.dxil.clone()) + .expect("DXIL validation failed"); + } + h +} + +fn param(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot, + } +} + +/// `image_get_lod` at every drawn pixel gives the level of the coordinates' +/// derivatives (clamped to the texture's one level: 0), next to a triangle +/// edge and next to pixels a discard killed, in wave32 and wave64, on the +/// hardware adapter and WARP. Tolerance 0.02 of a level, as `diff_tests` +/// takes for the hardware's 1/256 level steps. +#[test] +fn levels_of_detail_at_a_triangle_edge_and_after_a_discard() { + let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done + let vs = translate( + &NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Vs { + inputs: vec![VsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + vgpr: 4, + }], + outputs: Vec::new(), + }, + code: vs_code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }, + &[sig("POSITION", 0, 0)], + &[sig("SV_Position", 3, 4)], + ); + // A triangle whose diagonal crosses quads of a 16x16 target. + let vertices = [ + -1.0, -1.0, 0.5, 1.0, // + -1.0, 1.1, 0.5, 1.0, // + 1.1, -1.0, 0.5, 1.0, + ]; + let texels = vec![[0.5f32; 4]; (SIZE * SIZE) as usize]; + let linear = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts: Vec<(&str, Host)> = [("hardware", false), ("warp", true)] + .into_iter() + .filter_map(|(label, warp)| Host::new(warp).ok().map(|h| (label, h))) + .collect(); + assert!(!hosts.is_empty(), "no SM 6.6 device"); + let want = level(); + let mut failures = Vec::new(); + for discard in [false, true] { + for wave64 in [false, true] { + let ps = translate( + &NativeProgram { + stage: HwStage::Ps, + wave64, + vgprs: 12, + layout: vec![ + param(RootType::Constants, 0, 0), + param(RootType::Table, 4, 1), + param(RootType::Table, 6, 2), + ], + used: [(4, ResourceType::Srv, 8), (6, ResourceType::Sampler, 4)] + .map(|(user_data, kind, dwords)| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords, + user_data, + slot: user_data / 2 - 1, + }) + .to_vec(), + io: StageIo::Ps { + inputs: Vec::new(), + input_addr: 0x300, // SV_Position.x in v0, .y in v1 + db_shader_control: 0, + patches: Vec::new(), + }, + code: pixel_program(wave64, discard) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }, + &[sig("SV_Position", 3, 4)], + &[sig("SV_Target", 16, 0)], + ); + // The tables are heap index 0 of each heap. + let user_data = vec![0u32; ps.user_data_dwords().max(1) as usize]; + for (adapter, host) in &hosts { + let label = format!( + "{} wave{} {adapter}", + if discard { "discard" } else { "edge" }, + if wave64 { 64 } else { 32 } + ); + let (root, pso) = host + .pipeline(&vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pipeline: {e}")); + let pixels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(1, Root::Constants(user_data.clone()))], + textures: &[(SIZE, SIZE, &texels)], + samplers: &[linear], + vertices: &vertices, + stride: 16, + size: (16, 16), + mesh_groups: 0, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let (mut drawn, mut wrong, mut first) = (0, 0, None); + let (mut lo, mut hi) = (f32::MAX, f32::MIN); + for (i, px) in pixels.iter().enumerate() { + if px[3] != 1.0 { + continue; + } + drawn += 1; + let (x, y) = (i as u32 % 16, i as u32 / 16); + lo = lo.min(px[1]); + hi = hi.max(px[1]); + let bad = discard && killed(x, y) + || px[0].abs() > 0.02 + || (px[1] - want).abs() > 0.02; + if bad { + wrong += 1; + if first.is_none() { + first = Some(format!("({x}, {y}): [{:.4}, {:.4}]", px[0], px[1])); + } + } + } + eprintln!( + "{label}: {drawn} pixels, {wrong} wrong (want [0, {want:.4}], unclamped {lo:.4}..{hi:.4}){}", + first + .as_deref() + .map(|f| format!(", first {f}")) + .unwrap_or_default() + ); + if drawn < 50 || wrong > 0 { + failures.push(format!("{label}: {wrong} of {drawn}")); + } + } + } + } + assert!(failures.is_empty(), "{}", failures.join("; ")); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index abe6cbb511f..f27c59314db 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -209,6 +209,8 @@ mod diff_tests; mod flow_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +#[cfg(all(test, windows))] +mod lod_tests; mod lower; #[cfg(all(test, windows))] mod quad_read_tests; From d11d93a6815bc79e52d85b20c6c782c32e19afd5 Mon Sep 17 00:00:00 2001 From: kilolimaVI <361259062+kilolimaVI@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:39:01 +0200 Subject: [PATCH 3/6] Shaders: a NaN level of detail fails the LOD test A NaN compares false with the tolerance, so it passed; the levels must also be finite (pointed out by pickles976). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lod_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/victory-shader/src/emit/lod_tests.rs b/crates/victory-shader/src/emit/lod_tests.rs index fab96dbf808..4402133ac33 100644 --- a/crates/victory-shader/src/emit/lod_tests.rs +++ b/crates/victory-shader/src/emit/lod_tests.rs @@ -286,6 +286,8 @@ fn levels_of_detail_at_a_triangle_edge_and_after_a_discard() { lo = lo.min(px[1]); hi = hi.max(px[1]); let bad = discard && killed(x, y) + || !px[0].is_finite() + || !px[1].is_finite() || px[0].abs() > 0.02 || (px[1] - want).abs() > 0.02; if bad { From f0191df0036d46b38595244f561986d54c369536 Mon Sep 17 00:00:00 2001 From: kilolimaVI <361259062+kilolimaVI@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:55:31 +0200 Subject: [PATCH 4/6] Shaders: which texels gathers and point samples take near a boundary gather_tests looks up at t = x + d texels in u and v over a 16x16 texture whose texels hold their index, with image_gather4_lz (footprint at floor(t), half a texel back) and image_sample_lz with a point sampler (texel at floor(t)). At d 0.25 and 0.75 every host must take floor(t). Just below a boundary (d = -1/1024) it reports, without failing, whether the host rounds t up to x or keeps it below. Radeon 780M (RDNA3): gathers 256 of 256 round up, point samples 256 of 256 stay below; WARP: both stay below. Exact cases 0 wrong everywhere. Co-Authored-By: Claude Opus 5.5 --- .../victory-shader/src/emit/gather_tests.rs | 289 ++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 2 + 2 files changed, 291 insertions(+) create mode 100644 crates/victory-shader/src/emit/gather_tests.rs diff --git a/crates/victory-shader/src/emit/gather_tests.rs b/crates/victory-shader/src/emit/gather_tests.rs new file mode 100644 index 00000000000..1c492c236d1 --- /dev/null +++ b/crates/victory-shader/src/emit/gather_tests.rs @@ -0,0 +1,289 @@ +//! Which texels a gather (`image_gather4_lz`) and a point sample +//! (`image_sample_lz`) take near a texel boundary, without the console's +//! compiler. Each pixel looks up at `t = x + d` texels in u and v (a +//! gather's footprint and a point sample's texel start at `floor(t)`): away +//! from a boundary the texels are fixed; just below one (`d = -1/1024`) the +//! hardware's fixed-point coordinate decides whether `t` rounds up to `x` +//! or stays below it (`x - 1`), which hosts may do differently from the +//! console. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::container::{SigElement, signature}; +use super::host::{Draw, Host, Root}; +use super::{HostShader, emit}; +use crate::native::{ + HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, Usage, UsedResource, + VsInput, +}; +use crate::{Container, FourCC, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; +const fn sop1(op: u32, d: u32, s: u32) -> u32 { + 0xBE80_0000 | d << 16 | op << 8 | s +} +const fn vop2(op: u32, d: u32, s0: u32, v1: u32) -> u32 { + op << 25 | d << 17 | v1 << 9 | s0 +} + +/// The texture's size; its texel (i, j) holds `i + SIZE * j` in red. +const SIZE: u32 = 16; + +/// Loads the descriptors as `lod_tests` does, puts `(x + 0.5 + d) / SIZE` +/// of the pixel position in v2 and v3 and exports what the MIMG `op` reads +/// with `dmask` into v4-v7. +fn pixel_program(d: f32, op: u32, dmask: u32) -> Vec { + vec![ + sop1(0x03, 5, 0x80), // s_mov_b32 s5, 0 (table address, high) + sop1(0x03, 7, 0x80), // s_mov_b32 s7, 0 + 0x3D << 26 | 3 << 18 | 8 << 6 | 4 >> 1, // s_load_dwordx8 s[8:15], s[4:5], 0 + 125 << 25, + 0x3D << 26 | 2 << 18 | 16 << 6 | 6 >> 1, // s_load_dwordx4 s[16:19], s[6:7], 0 + 125 << 25, + vop2(0x03, 2, 0xFF, 0), // v_add_f32 v2, d, v0 + d.to_bits(), + vop2(0x03, 3, 0xFF, 1), // v_add_f32 v3, d, v1 + d.to_bits(), + vop2(0x08, 2, 0xFF, 2), // v_mul_f32 v2, 1/SIZE, v2 + (1.0 / SIZE as f32).to_bits(), + vop2(0x08, 3, 0xFF, 3), // v_mul_f32 v3, 1/SIZE, v3 + (1.0 / SIZE as f32).to_bits(), + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + // image_ v[4:7], v[2:3], s[8:15], s[16:19] dmask dim:2D + 0xF000_0008 | op << 18 | dmask << 8, + 2 | 4 << 8 | 2 << 16 | 4 << 21, + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF800_180F, // exp mrt0 v4, v5, v6, v7 done vm + 0x0706_0504, + S_ENDPGM, + ] +} + +/// The four red values a gather whose footprint starts at texel (i, j) +/// returns, in D3D's order: (i, j+1), (i+1, j+1), (i+1, j), (i, j); wrap. +fn gathered(i: i32, j: i32) -> [f32; 4] { + let t = |i: i32, j: i32| { + (i.rem_euclid(SIZE as i32) + SIZE as i32 * j.rem_euclid(SIZE as i32)) as f32 + }; + [t(i, j + 1), t(i + 1, j + 1), t(i + 1, j), t(i, j)] +} + +fn sig(name: &str, kind: u8, interp: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + } +} + +fn translate(native: &NativeProgram, inputs: &[SigElement], outputs: &[SigElement]) -> HostShader { + let isg = signature(inputs, true); + let osg = signature(outputs, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg), (FourCC::OSG1, &osg)]); + let c = Container::parse(&bytes).expect("container"); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource"); + let io = io::raise(&p, native).expect("io"); + let h = emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut val) = + super::validator::Validator::load(super::validator::Validator::default_path().as_deref()) + { + val.validate(&mut h.dxil.clone()) + .expect("DXIL validation failed"); + } + h +} + +fn param(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot, + } +} + +/// Draws `op` (with `dmask`) at `t = x + d` for each `d`, from a full-screen +/// triangle on the hardware adapter and WARP. The program's coordinate is +/// `x + 0.5 + d + shift` texels: a gather's footprint starts half a texel +/// back from it (shift 0), a point sample's texel at it (shift -0.5). `exact` cases +/// must all take `value(floor(t))`; the others report whether each host +/// rounded `t` up to `x`. Returns the failures. +fn lookups( + name: &str, + op: u32, + dmask: u32, + shift: f32, + value: fn(i32, i32) -> [f32; 4], +) -> Vec { + let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done + let vs = translate( + &NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Vs { + inputs: vec![VsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + vgpr: 4, + }], + outputs: Vec::new(), + }, + code: vs_code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }, + &[sig("POSITION", 0, 0)], + &[sig("SV_Position", 3, 4)], + ); + // A triangle covering the whole 16x16 target. + let vertices = [ + -1.0, -1.0, 0.5, 1.0, // + -1.0, 3.0, 0.5, 1.0, // + 3.0, -1.0, 0.5, 1.0, + ]; + let texels: Vec<[f32; 4]> = (0..SIZE * SIZE) + .map(|n| [n as f32, 0.0, 0.0, 1.0]) + .collect(); + let point = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts: Vec<(&str, Host)> = [("hardware", false), ("warp", true)] + .into_iter() + .filter_map(|(label, warp)| Host::new(warp).ok().map(|h| (label, h))) + .collect(); + assert!(!hosts.is_empty(), "no SM 6.6 device"); + let mut failures = Vec::new(); + for (d, exact) in [(0.25f32, true), (0.75, true), (-1.0 / 1024.0, false)] { + let ps = translate( + &NativeProgram { + stage: HwStage::Ps, + wave64: true, + vgprs: 8, + layout: vec![ + param(RootType::Constants, 0, 0), + param(RootType::Table, 4, 1), + param(RootType::Table, 6, 2), + ], + used: [(4, ResourceType::Srv, 8), (6, ResourceType::Sampler, 4)] + .map(|(user_data, kind, dwords)| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords, + user_data, + slot: user_data / 2 - 1, + }) + .to_vec(), + io: StageIo::Ps { + inputs: Vec::new(), + input_addr: 0x300, // SV_Position.x in v0, .y in v1 + db_shader_control: 0, + patches: Vec::new(), + }, + code: pixel_program(d + shift, op, dmask) + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }, + &[sig("SV_Position", 3, 4)], + &[sig("SV_Target", 16, 0)], + ); + let user_data = vec![0u32; ps.user_data_dwords().max(1) as usize]; + for (adapter, host) in &hosts { + let label = format!("{name} d {d:+.6} {adapter}"); + let (root, pso) = host + .pipeline(&vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pipeline: {e}")); + let pixels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(1, Root::Constants(user_data.clone()))], + textures: &[(SIZE, SIZE, &texels)], + samplers: &[point], + vertices: &vertices, + stride: 16, + size: (16, 16), + mesh_groups: 0, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let (mut floor, mut rounded, mut other, mut first) = (0, 0, 0, None); + for (n, px) in pixels.iter().enumerate() { + let (x, y) = ((n as u32 % 16) as i32, (n as u32 / 16) as i32); + let at = |k: i32| value(x + k, y + k); + // At floor(t): x where t is inside texel x, x - 1 just below it. + if *px == at(if exact { 0 } else { -1 }) { + floor += 1; + } else if *px == at(0) { + rounded += 1; + } else { + other += 1; + if first.is_none() { + first = Some(format!("({x}, {y}): {px:?}")); + } + } + } + eprintln!( + "{label}: 256 pixels, at floor(t) {floor}, rounded up to x {rounded}, neither {other}{}", + first + .as_deref() + .map(|f| format!(", first {f}")) + .unwrap_or_default() + ); + if other > 0 || exact && floor != 256 { + failures.push(format!( + "{label}: floor {floor}, rounded {rounded}, neither {other}" + )); + } + } + } + failures +} + +/// `image_gather4_lz` takes the 2x2 footprint at `floor(t)` where `t` lies +/// a quarter texel inside a texel (`d` 0.25 and 0.75). Just below a +/// boundary (`d = -1/1024`) it reports which way each host rounds, without +/// failing: the console's hardware keeps 8 fractional bits. +#[test] +fn gathers_take_the_footprint_at_the_coordinate() { + let failures = lookups("gather", 0x47, 0x1, 0.0, gathered); + assert!(failures.is_empty(), "{}", failures.join("; ")); +} + +/// `image_sample_lz` with a point sampler takes the texel at `floor(t)` +/// (`t = u * SIZE`), and reports the same boundary case. +#[test] +fn point_samples_take_the_texel_at_the_coordinate() { + let texel = |i: i32, j: i32| { + let n = i.rem_euclid(SIZE as i32) + SIZE as i32 * j.rem_euclid(SIZE as i32); + [n as f32, 0.0, 0.0, 1.0] + }; + let failures = lookups("point", 0x27, 0xF, -0.5, texel); + assert!(failures.is_empty(), "{}", failures.join("; ")); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f27c59314db..1aac1a94f91 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -207,6 +207,8 @@ mod crosslane_tests; mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; +#[cfg(all(test, windows))] +mod gather_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; #[cfg(all(test, windows))] From bbe216c3e8c814b69d9c789562f3750b1900ed9a Mon Sep 17 00:00:00 2001 From: kilolimaVI <361259062+kilolimaVI@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:10:38 +0200 Subject: [PATCH 5/6] Shaders: gathers from the first level take the console's footprint image_gather4_lz(_o) went to DXIL textureGather with the program's coordinate, so which four texels a gather took near a texel's edge was the host's choice. The console rounds u x size to 1/256 of a texel, half up, before taking floor(u x size - 0.5), the rule gather_first already implements for gathers at a level. Hosts differ: 1/1024 of a texel below an edge, the Radeon 780M rounds up as the console does and WARP stays below, taking the footprint one texel back. The coordinate along each axis is now moved to (first + 1) / size, the middle of the console's footprint, with first from gather_first: half a texel from either edge, so every host takes the same four texels in any address mode. NaN takes the footprint at 0, as on the console; beyond +-2 (where gather_first clamps) and at infinities the coordinate is kept. Cubes are left as they were. The helper lives in lower/gather.rs to keep lower.rs under the file size limit. gather_tests now requires the console's footprint on every host: 1/1024 and the tie of 1/512 below an edge round up, 1/512 + 1/65536 and 3/1024 stay below. Co-Authored-By: Claude Opus 5.5 --- .../victory-shader/src/emit/gather_tests.rs | 77 +++++++++++++------ crates/victory-shader/src/emit/lower.rs | 15 ++++ .../victory-shader/src/emit/lower/gather.rs | 36 +++++++++ 3 files changed, 105 insertions(+), 23 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/gather.rs diff --git a/crates/victory-shader/src/emit/gather_tests.rs b/crates/victory-shader/src/emit/gather_tests.rs index 1c492c236d1..13849a21373 100644 --- a/crates/victory-shader/src/emit/gather_tests.rs +++ b/crates/victory-shader/src/emit/gather_tests.rs @@ -2,10 +2,11 @@ //! (`image_sample_lz`) take near a texel boundary, without the console's //! compiler. Each pixel looks up at `t = x + d` texels in u and v (a //! gather's footprint and a point sample's texel start at `floor(t)`): away -//! from a boundary the texels are fixed; just below one (`d = -1/1024`) the -//! hardware's fixed-point coordinate decides whether `t` rounds up to `x` -//! or stays below it (`x - 1`), which hosts may do differently from the -//! console. +//! from a boundary the texels are fixed; just below one the hardware's +//! fixed-point coordinate decides whether `t` rounds up to `x` or stays +//! below it (`x - 1`). The console rounds `t` to 1/256 of a texel, half up; +//! hosts may not, so gathers are translated to take the console's +//! footprint (`lower/gather.rs`). use windows::Win32::Graphics::Direct3D12::*; @@ -113,18 +114,20 @@ fn param(root: RootType, user_data: u8, slot: u8) -> RootParam { } } -/// Draws `op` (with `dmask`) at `t = x + d` for each `d`, from a full-screen -/// triangle on the hardware adapter and WARP. The program's coordinate is -/// `x + 0.5 + d + shift` texels: a gather's footprint starts half a texel -/// back from it (shift 0), a point sample's texel at it (shift -0.5). `exact` cases -/// must all take `value(floor(t))`; the others report whether each host -/// rounded `t` up to `x`. Returns the failures. +/// Draws `op` (with `dmask`) at `t = x + d` for each case's `d`, from a +/// full-screen triangle on the hardware adapter and WARP. The program's +/// coordinate is `x + 0.5 + d + shift` texels: a gather's footprint starts +/// half a texel back from it (shift 0), a point sample's texel at it (shift +/// -0.5). A case with `Some(k)` must take `value(x + k)` at every pixel; with +/// `None` it reports whether each host rounded `t` up to `x` (`k` 0) or kept +/// it below (`k` -1). Returns the failures. fn lookups( name: &str, op: u32, dmask: u32, shift: f32, value: fn(i32, i32) -> [f32; 4], + cases: &[(f32, Option)], ) -> Vec { let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done let vs = translate( @@ -175,7 +178,7 @@ fn lookups( .collect(); assert!(!hosts.is_empty(), "no SM 6.6 device"); let mut failures = Vec::new(); - for (d, exact) in [(0.25f32, true), (0.75, true), (-1.0 / 1024.0, false)] { + for &(d, expect) in cases { let ps = translate( &NativeProgram { stage: HwStage::Ps, @@ -237,8 +240,9 @@ fn lookups( for (n, px) in pixels.iter().enumerate() { let (x, y) = ((n as u32 % 16) as i32, (n as u32 / 16) as i32); let at = |k: i32| value(x + k, y + k); - // At floor(t): x where t is inside texel x, x - 1 just below it. - if *px == at(if exact { 0 } else { -1 }) { + // Kept below the edge (x - 1, floor(t) just below x) or + // rounded up to it (x); inside a texel both are x. + if d < 0.0 && *px == at(-1) { floor += 1; } else if *px == at(0) { rounded += 1; @@ -250,15 +254,20 @@ fn lookups( } } eprintln!( - "{label}: 256 pixels, at floor(t) {floor}, rounded up to x {rounded}, neither {other}{}", + "{label}: 256 pixels, kept below {floor}, at x {rounded}, neither {other}{}", first .as_deref() .map(|f| format!(", first {f}")) .unwrap_or_default() ); - if other > 0 || exact && floor != 256 { + let wanted = match expect { + Some(0) => rounded, + Some(_) => floor, + None => 256 - other, + }; + if wanted != 256 { failures.push(format!( - "{label}: floor {floor}, rounded {rounded}, neither {other}" + "{label}: kept below {floor}, at x {rounded}, neither {other}" )); } } @@ -266,24 +275,46 @@ fn lookups( failures } -/// `image_gather4_lz` takes the 2x2 footprint at `floor(t)` where `t` lies -/// a quarter texel inside a texel (`d` 0.25 and 0.75). Just below a -/// boundary (`d = -1/1024`) it reports which way each host rounds, without -/// failing: the console's hardware keeps 8 fractional bits. +/// `image_gather4_lz` takes the console's 2x2 footprint: at `floor(t)` with +/// `t` rounded to 1/256 of a texel, half up. Inside a texel (`d` 0.25 and +/// 0.75) that is `x`; just below an edge, 1/1024 and the tie of 1/512 round +/// up to `x`, while 1/512 + 1/65536 and 3/1024 stay at `x - 1`, on every +/// host. #[test] fn gathers_take_the_footprint_at_the_coordinate() { - let failures = lookups("gather", 0x47, 0x1, 0.0, gathered); + let failures = lookups( + "gather", + 0x47, + 0x1, + 0.0, + gathered, + &[ + (0.25, Some(0)), + (0.75, Some(0)), + (-1.0 / 1024.0, Some(0)), + (-1.0 / 512.0, Some(0)), + (-(1.0 / 512.0 + 1.0 / 65536.0), Some(-1)), + (-3.0 / 1024.0, Some(-1)), + ], + ); assert!(failures.is_empty(), "{}", failures.join("; ")); } /// `image_sample_lz` with a point sampler takes the texel at `floor(t)` -/// (`t = u * SIZE`), and reports the same boundary case. +/// (`t = u * SIZE`), and reports which way each host takes `d = -1/1024`. #[test] fn point_samples_take_the_texel_at_the_coordinate() { let texel = |i: i32, j: i32| { let n = i.rem_euclid(SIZE as i32) + SIZE as i32 * j.rem_euclid(SIZE as i32); [n as f32, 0.0, 0.0, 1.0] }; - let failures = lookups("point", 0x27, 0xF, -0.5, texel); + let failures = lookups( + "point", + 0x27, + 0xF, + -0.5, + texel, + &[(0.25, Some(0)), (0.75, Some(0)), (-1.0 / 1024.0, None)], + ); assert!(failures.is_empty(), "{}", failures.join("; ")); } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c96f522ec82..f7704e6fa31 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -21,6 +21,7 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Structured}; mod bvh; +mod gather; type Why = &'static str; @@ -8974,6 +8975,20 @@ impl<'a> Lower<'a> { os[k] = self.s.m.bin(c, Bin::AShr, t, k26); } } + if kind != 5 { + // Hosts resolve a coordinate near a texel's edge + // differently: take the console's footprint. + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + for k in 0..spatial.min(2) { + let n = self.s.m.extract(c, d, k as u32); + args[2 + k] = self.gather_console_coordinate(cs[k], n); + } + } args.extend(&os[..2]); args.push(self.s.m.i32(dmask.trailing_zeros())); self.s.op( diff --git a/crates/victory-shader/src/emit/lower/gather.rs b/crates/victory-shader/src/emit/lower/gather.rs new file mode 100644 index 00000000000..5f0ef159529 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/gather.rs @@ -0,0 +1,36 @@ +//! Gathers from a view's first level (`image_gather4_lz`, `_o`) through the +//! host's `textureGather`. Which four texels a gather takes turns on how +//! finely the sampler resolves its coordinate: the console rounds +//! `u × size` to 1/256 of a texel, half up, before taking +//! `floor(u × size − 0.5)` (`gather_first`, `gather_level_tests`), while +//! hosts differ near a texel's edge (`gather_tests`: 1/1024 of a texel below +//! one, the 780M rounds up as the console does, WARP stays below). The +//! coordinate is moved to the middle of the console's footprint, half a +//! texel from either edge, where every host takes the same four texels. + +use super::Lower; +use crate::emit::bitcode::{Bin, Cast, V, pred}; + +impl Lower<'_> { + /// `u` (a float) moved to `(first + 1) / size`, the middle of the + /// footprint the console takes along an axis of `size` texels. NaN + /// takes the footprint at 0, as on the console. Beyond ±2, where + /// `gather_first` clamps (and a wrapping address mode would not), and + /// at infinities, `u` is kept. + pub(super) fn gather_console_coordinate(&mut self, u: V, size: V) -> V { + let c = self.cur; + let bits = self.as_int(u); + let first = self.gather_first(bits, size); + let one = self.s.m.i32(1); + let middle = self.s.m.bin(c, Bin::Add, first, one); + let f32t = self.s.t.f32; + let middle = self.s.m.cast(c, Cast::SiToFp, middle, f32t); + let n = self.s.m.cast(c, Cast::UiToFp, size, f32t); + let at = self.s.m.bin(c, Bin::SDiv, middle, n); + // FAbs; NaN compares false and takes the console's footprint. + let magnitude = self.unary(6, u); + let two = self.s.m.f32(2.0f32.to_bits()); + let far = self.s.m.cmp(c, pred::OGT, magnitude, two); + self.s.m.select(c, far, u, at) + } +} From 4fb5462d7aab724a415add1eb8f16e654bfdf1a8 Mon Sep 17 00:00:00 2001 From: andrewpozdnakov7-jpg Date: Fri, 27 Nov 2026 21:55:37 +0000 Subject: [PATCH 6/6] Shader tests: cover first-level gathers at non-power-of-two edges --- .../victory-shader/src/emit/gather_tests.rs | 109 ++++++++++++++---- 1 file changed, 84 insertions(+), 25 deletions(-) diff --git a/crates/victory-shader/src/emit/gather_tests.rs b/crates/victory-shader/src/emit/gather_tests.rs index 13849a21373..7efeb4ccae4 100644 --- a/crates/victory-shader/src/emit/gather_tests.rs +++ b/crates/victory-shader/src/emit/gather_tests.rs @@ -27,13 +27,13 @@ const fn vop2(op: u32, d: u32, s0: u32, v1: u32) -> u32 { op << 25 | d << 17 | v1 << 9 | s0 } -/// The texture's size; its texel (i, j) holds `i + SIZE * j` in red. +/// The default texture size; its texel (i, j) holds `i + SIZE * j` in red. const SIZE: u32 = 16; -/// Loads the descriptors as `lod_tests` does, puts `(x + 0.5 + d) / SIZE` +/// Loads the descriptors as `lod_tests` does, puts `(x + 0.5 + d) / size` /// of the pixel position in v2 and v3 and exports what the MIMG `op` reads /// with `dmask` into v4-v7. -fn pixel_program(d: f32, op: u32, dmask: u32) -> Vec { +fn pixel_program(d: f32, op: u32, dmask: u32, size: u32) -> Vec { vec![ sop1(0x03, 5, 0x80), // s_mov_b32 s5, 0 (table address, high) sop1(0x03, 7, 0x80), // s_mov_b32 s7, 0 @@ -46,9 +46,9 @@ fn pixel_program(d: f32, op: u32, dmask: u32) -> Vec { vop2(0x03, 3, 0xFF, 1), // v_add_f32 v3, d, v1 d.to_bits(), vop2(0x08, 2, 0xFF, 2), // v_mul_f32 v2, 1/SIZE, v2 - (1.0 / SIZE as f32).to_bits(), + (1.0 / size as f32).to_bits(), vop2(0x08, 3, 0xFF, 3), // v_mul_f32 v3, 1/SIZE, v3 - (1.0 / SIZE as f32).to_bits(), + (1.0 / size as f32).to_bits(), 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) // image_ v[4:7], v[2:3], s[8:15], s[16:19] dmask dim:2D 0xF000_0008 | op << 18 | dmask << 8, @@ -62,10 +62,9 @@ fn pixel_program(d: f32, op: u32, dmask: u32) -> Vec { /// The four red values a gather whose footprint starts at texel (i, j) /// returns, in D3D's order: (i, j+1), (i+1, j+1), (i+1, j), (i, j); wrap. -fn gathered(i: i32, j: i32) -> [f32; 4] { - let t = |i: i32, j: i32| { - (i.rem_euclid(SIZE as i32) + SIZE as i32 * j.rem_euclid(SIZE as i32)) as f32 - }; +fn gathered(i: i32, j: i32, size: u32) -> [f32; 4] { + let size = size as i32; + let t = |i: i32, j: i32| (i.rem_euclid(size) + size * j.rem_euclid(size)) as f32; [t(i, j + 1), t(i + 1, j + 1), t(i + 1, j), t(i, j)] } @@ -126,9 +125,11 @@ fn lookups( op: u32, dmask: u32, shift: f32, - value: fn(i32, i32) -> [f32; 4], + value: fn(i32, i32, u32) -> [f32; 4], cases: &[(f32, Option)], + (size, address): (u32, D3D12_TEXTURE_ADDRESS_MODE), ) -> Vec { + let count = (size * size) as usize; let vs_code = [0xF800_08CF, 0x0706_0504, S_ENDPGM]; // exp pos0 v4..v7 done let vs = translate( &NativeProgram { @@ -151,20 +152,21 @@ fn lookups( &[sig("POSITION", 0, 0)], &[sig("SV_Position", 3, 4)], ); - // A triangle covering the whole 16x16 target. + // A triangle covering the whole target. let vertices = [ -1.0, -1.0, 0.5, 1.0, // -1.0, 3.0, 0.5, 1.0, // 3.0, -1.0, 0.5, 1.0, ]; - let texels: Vec<[f32; 4]> = (0..SIZE * SIZE) + let texels: Vec<[f32; 4]> = (0..size * size) .map(|n| [n as f32, 0.0, 0.0, 1.0]) .collect(); let point = D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressU: address, + AddressV: address, + AddressW: address, + BorderColor: [0.625, 0.0, 0.0, 1.0], MaxAnisotropy: 1, MaxLOD: f32::MAX, ..Default::default() @@ -207,7 +209,7 @@ fn lookups( db_shader_control: 0, patches: Vec::new(), }, - code: pixel_program(d + shift, op, dmask) + code: pixel_program(d + shift, op, dmask, size) .iter() .flat_map(|w| w.to_le_bytes()) .collect(), @@ -227,19 +229,20 @@ fn lookups( &pso, &Draw { roots: vec![(1, Root::Constants(user_data.clone()))], - textures: &[(SIZE, SIZE, &texels)], + textures: &[(size, size, &texels)], samplers: &[point], vertices: &vertices, stride: 16, - size: (16, 16), + size: (size, size), mesh_groups: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + assert_eq!(pixels.len(), count); let (mut floor, mut rounded, mut other, mut first) = (0, 0, 0, None); for (n, px) in pixels.iter().enumerate() { - let (x, y) = ((n as u32 % 16) as i32, (n as u32 / 16) as i32); - let at = |k: i32| value(x + k, y + k); + let (x, y) = ((n as u32 % size) as i32, (n as u32 / size) as i32); + let at = |k: i32| value(x + k, y + k, size); // Kept below the edge (x - 1, floor(t) just below x) or // rounded up to it (x); inside a texel both are x. if d < 0.0 && *px == at(-1) { @@ -254,7 +257,7 @@ fn lookups( } } eprintln!( - "{label}: 256 pixels, kept below {floor}, at x {rounded}, neither {other}{}", + "{label}: {count} pixels, kept below {floor}, at x {rounded}, neither {other}{}", first .as_deref() .map(|f| format!(", first {f}")) @@ -263,9 +266,9 @@ fn lookups( let wanted = match expect { Some(0) => rounded, Some(_) => floor, - None => 256 - other, + None => count - other, }; - if wanted != 256 { + if wanted != count { failures.push(format!( "{label}: kept below {floor}, at x {rounded}, neither {other}" )); @@ -296,6 +299,7 @@ fn gathers_take_the_footprint_at_the_coordinate() { (-(1.0 / 512.0 + 1.0 / 65536.0), Some(-1)), (-3.0 / 1024.0, Some(-1)), ], + (SIZE, D3D12_TEXTURE_ADDRESS_MODE_WRAP), ); assert!(failures.is_empty(), "{}", failures.join("; ")); } @@ -304,8 +308,9 @@ fn gathers_take_the_footprint_at_the_coordinate() { /// (`t = u * SIZE`), and reports which way each host takes `d = -1/1024`. #[test] fn point_samples_take_the_texel_at_the_coordinate() { - let texel = |i: i32, j: i32| { - let n = i.rem_euclid(SIZE as i32) + SIZE as i32 * j.rem_euclid(SIZE as i32); + let texel = |i: i32, j: i32, size: u32| { + let size = size as i32; + let n = i.rem_euclid(size) + size * j.rem_euclid(size); [n as f32, 0.0, 0.0, 1.0] }; let failures = lookups( @@ -315,6 +320,60 @@ fn point_samples_take_the_texel_at_the_coordinate() { -0.5, texel, &[(0.25, Some(0)), (0.75, Some(0)), (-1.0 / 1024.0, None)], + (SIZE, D3D12_TEXTURE_ADDRESS_MODE_WRAP), + ); + assert!(failures.is_empty(), "{}", failures.join("; ")); +} + +#[test] +fn gathers_round_npot_wrapped_tile_edges() { + const EDGE_SIZE: u32 = 13; + let period = EDGE_SIZE as f32; + let failures = lookups( + "gather wrapped tiles", + 0x47, + 0x1, + 0.0, + gathered, + &[ + (-period - 1.0 / 1024.0, Some(0)), + (period - 1.0 / 1024.0, Some(0)), + ], + (EDGE_SIZE, D3D12_TEXTURE_ADDRESS_MODE_WRAP), + ); + assert!(failures.is_empty(), "{}", failures.join("; ")); +} + +#[test] +fn gathers_round_npot_border_edges() { + let border = |i: i32, j: i32, size: u32| { + let size = size as i32; + let texel = |x, y| { + if (0..size).contains(&x) && (0..size).contains(&y) { + (x + size * y) as f32 + } else { + 0.625 + } + }; + [ + texel(i, j + 1), + texel(i + 1, j + 1), + texel(i + 1, j), + texel(i, j), + ] + }; + let failures = lookups( + "gather texture border", + 0x47, + 0x1, + 0.0, + border, + &[ + (-1.0 / 1024.0, Some(0)), + (-3.0 / 1024.0, Some(-1)), + (0.25, Some(0)), + ], + (13, D3D12_TEXTURE_ADDRESS_MODE_BORDER), ); assert!(failures.is_empty(), "{}", failures.join("; ")); }