From 2790f41d09db27dc6b88ad94cb69aaa3f24c5ef9 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:27:24 +0100 Subject: [PATCH 1/5] Recompiler: a PS reads float16 attributes packed two per dword per half A retail title's world pixel shaders (#505; 173 of its 362) pack their float16 interpolants: two components per dword (component c of a register in dword c / 2, the even one in the low half) and up to two signature registers per attribute, the second after the dwords the first one's components take (1 for .xy, 2 for .xyz / .xyzw). The PS reads each half with v_interp_p2_f16, SRC0 bit 8 choosing the high one. XCL refused the PS input table of such programs (records [6, reg, mask, attr, 0, reg2, packed reg, flags]: flag 8 = float16, flag 16 = byte 5 names the second register, byte 6 below byte 1 from the first pair on), so every attribute, plain ones included, fell back to "the N-th register" and the ones after a pair read their neighbour. The PS also converted the raw packed dword as a float, ignored the high bit and declared the float16 inputs nointerpolation. Now the table parses, each (dword, half) of a packed attribute maps to its element and component (f16_registers, ps_f16_slot; a record that repeats its own register pairs it with the next float16 register no other attribute names), and the PS reads that component as a float, interpolated with the attribute's own mode. Both translators (HLSL and direct DXIL). The layout was checked on the title's dumped programs: every v_interp_p2_f16 (dword, half) of 376 of 378 packed attributes in 362 PS is a declared component (2 read one past a .xy register). Not covered here: the VS / mesh side still exports the packed dwords raw (the next commit), so the GPU test feeds the PS from a PC VS that hands over each component as a float. register always in dwords 2-3, a repeated register paired with itself - which does not match the title's programs after a .xy register; both have since dropped their float16 part in favour of this change. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 92 ++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_gfx.rs | 18 +++- crates/xcl/src/gpu/recomp/emit.rs | 23 +++-- crates/xcl/src/gpu/recomp/mod.rs | 120 +++++++++++++++++++++++++- 4 files changed, 241 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index e1421c69bc..05f20fab41 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -384,6 +384,98 @@ fn direct_and_hlsl_graphics_stages_link() { assert_eq!(draw(&hvs, &dps), want, "HLSL VS + direct PS"); } +/// Float16 interpolants packed two per dword, two registers in one attribute (TEXCOORD1.xyz +/// and TEXCOORD4.xyzw in attribute 0, as a retail title's world shaders have them): the PS +/// reads each half with `v_interp_p2_f16` (SRC0 bit 8: the high half) and gets that component +/// of its own element interpolated across the triangle; the float attribute after the pair +/// keeps its register. Both translators. Before: the table was refused, the PS converted the +/// raw packed dword of a `nointerpolation` input and attribute 1 was read from TEXCOORD4. +#[test] +fn f16_packed_attributes_interpolate_per_half() { + use crate::gpu::dxbc::SigElement as S; + use crate::gpu::recomp::{runner, translate, Mode, Options, PsAttr, PsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; + const V: u64 = 256; + let user = vec![el("TEXCOORD", 1, 0, 6, 1, 0x7), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)]; + // a PC VS handing over each component as a float: COLOR c -> TEXCOORD1 = (c0, c1, c2, 0), + // TEXCOORD4 = (c3, c0, c1, c2), TEXCOORD3 = c reversed + let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t1 : TEXCOORD1; float4 t4 : TEXCOORD4; float4 t3 : TEXCOORD3; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t1 = float4(i.c.xyz, 0.0); o.t4 = float4(i.c.w, i.c.xyz); o.t3 = i.c.wzyx; return o; }\n"; + let pvs = crate::gpu::recomp::dxc::compile(pc_vs, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pc_vs}")); + let psi = PsInterface { + inputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: Some(vec![ + PsAttr { kind: 6, register: 1, mask: 3, flat: false, f16: true, pair: Some(2) }, + PsAttr { kind: 6, register: 3, mask: 0xF, flat: false, f16: false, pair: None }, + ]), + }; + // a PS returning four values: Some((dword, high)) of attribute 0, None: attr1[k] as f32 + let ps_code = |sel: [Option<(u64, u64)>; 4]| { + let mut ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, s) in sel.iter().enumerate() { + let k = k as u64; + match *s { + Some((chan, high)) => { + let attr = chan << 6 | high << 8; + ops.push(("V_INTERP_P1LL_F16", "ENC_VOP3", vec![("VDST", 8 + k), ("SRC1", V), ("SRC0", attr)], None)); + ops.push(("V_INTERP_P2_F16", "ENC_VOP3", vec![("VDST", 4 + k), ("SRC1", V + 1), ("SRC0", attr), ("SRC2", V + 8 + k)], None)); + ops.push(("V_CVT_F32_F16", "ENC_VOP1", vec![("VDST", 4 + k), ("SRC0", V + 4 + k)], None)); + } + None => { + ops.push(("V_INTERP_P1_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 0), ("ATTR", 1), ("ATTRCHAN", k)], None)); + ops.push(("V_INTERP_P2_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", k)], None)); + } + } + } + ops.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + prog(&list) + }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + // COLOR = (x, y, x / 4 + 1 / 2, y / 2 - 1 / 4) at each vertex: exact in float16, and linear + // in the pixel's position + let color = |x: f32, y: f32| [x, y, 0.25 * x + 0.5, 0.5 * y - 0.25]; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1]].into_iter().chain(color(p[0], p[1]))).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + // what each selection reads, as indices into COLOR (4: nothing declared there, 0) + let cases: [([Option<(u64, u64)>; 4], [usize; 4], &str); 4] = [ + ([Some((0, 0)), Some((0, 1)), Some((1, 0)), Some((2, 0))], [0, 1, 2, 3], "TEXCOORD1.xyz, TEXCOORD4.x"), + ([Some((2, 1)), Some((3, 0)), Some((3, 1)), Some((1, 1))], [0, 1, 2, 4], "TEXCOORD4.yzw, TEXCOORD1.w"), + ([Some((3, 1)), Some((2, 0)), Some((0, 1)), Some((0, 0))], [2, 3, 1, 0], "both registers, mixed halves"), + ([None, None, None, None], [3, 2, 1, 0], "the float attribute after the pair"), + ]; + for (sel, want, what) in cases { + let code = ps_code(sel); + let pt = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{what}: {:?}", pt.unsupported_why); + assert!(!pt.hlsl.contains("nointerpolation"), "{what}: the float16 inputs interpolate\n{}", pt.hlsl); + let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; + for (stages, vs, ps) in [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps)] { + let px = runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); + for y in 0..8usize { + for x in 0..8usize { + let c = color((x as f32 + 0.5) / 4.0 - 1.0, 1.0 - (y as f32 + 0.5) / 4.0); + let expected = want.map(|k| if k == 4 { 0.0 } else { c[k] }); + let got = px[y * 8 + x]; + assert!(got.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "{what}, {stages}: pixel ({x},{y}) = {got:?}, expected {expected:?}"); + } + } + } + } +} + fn sig(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 4869231851..21e6fb27bb 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{CastOp, Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{elements_at, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -166,7 +166,8 @@ impl Lw { for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { let attr = ps_slot_attribute(ps, k); let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); - let float = e.component_type == 3; + // float16 read through a packed attribute interpolates like a float + let float = e.component_type == 3 || (e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some())); let interp = if !float { Interp::Constant } else { @@ -401,11 +402,20 @@ impl Lw { let s1 = f("SRC1"); (f("VDST"), if s1 >= 256 { s1 - 256 } else { s1 }, f("SRC0") & 0x3F, f("SRC0") >> 6 & 3) }; - let Some(slot) = ps_attribute_slot(&ps, attr as usize, chan as usize) else { return err(d, "attribute outside ISG1") }; + // a float16-packed attribute: the PC input is the component itself (SRC0 bit 8: the + // high half of the dword); a half nothing declares reads 0 + let place = match ps_attribute_f16(&ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => ps_f16_slot(&ps, ®s, chan as usize, d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1), + None => match ps_attribute_slot(&ps, attr as usize, chan as usize) { + Some(slot) => Some((slot, chan as usize)), + None => return err(d, "attribute outside ISG1"), + }, + }; let load = |lw: &mut Lw| -> (Value, u32) { + let Some((slot, comp)) = place else { return (lw.fc(0.0), 3) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, ct) = g.ps_in[slot]; - (g.io.load_input(&mut lw.s, sig, 0, chan as u8), ct) + (g.io.load_input(&mut lw.s, sig, 0, comp as u8), ct) }; let as_f32 = |lw: &mut Lw, x: Value, ct: u32| -> Value { let f32 = lw.s.m.f32(); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a223135a50..1d4ba2c015 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{elements_at, param_registers, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2491,10 +2491,21 @@ impl Em { fn interp(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> { let Mode::Pixel(ps) = &self.opt.mode else { return Err("interpolation outside PS") }; let (vdst, ij, attr, chan) = Self::interp_fields(d); - let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { - return Err("attribute outside ISG1"); + // a float16-packed attribute (two registers, two components per dword): the PC input + // is the component itself, interpolated as a float – SRC0 bit 8 picks the high half + let high = d.enc.name != "ENC_VINTRP" && rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) >> 8 & 1 == 1; + let src = match ps_attribute_f16(ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => match ps_f16_slot(ps, ®s, chan as usize, high) { + Some((slot, comp)) => format!("xi.a{slot}[{comp}]"), + None => "0.0f".to_string(), + }, + None => { + let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { + return Err("attribute outside ISG1"); + }; + format!("xi.a{slot}[{chan}]") + } }; - let src = format!("xi.a{slot}[{chan}]"); let act = self.act(); match name { "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => { @@ -5577,7 +5588,9 @@ static uint xcl_cap = 1u << 16; // the mode of the attribute this input is read through (none: never read) let attr = ps_slot_attribute(ps, k); let mut m = attr.and_then(|a| self.ps_modes.get(&(a as u32))).cloned().unwrap_or_default(); - if e.component_type != 3 { + // float16 read through a packed attribute interpolates like a float + let f16 = e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some()); + if e.component_type != 3 && !f16 { m = "nointerpolation".into(); } let _ = writeln!(h, " {m} {}4 a{k} : {};", hlsl_type(e), e.semantic()); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 40e5550799..15ad7f1ecd 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -589,6 +589,10 @@ pub struct PsAttr { pub register: u8, pub mask: u8, pub flat: bool, + /// float16 values, two per dword (record flag 8) – see `f16_registers` + pub f16: bool, + /// the record names a second register (flag 16; the same register again: not named) + pub pair: Option, } /// The PS input table of an FSSM: SPI_PS_INPUT_ENA and, per `v_interp attrN`, the register it @@ -596,6 +600,11 @@ pub struct PsAttr { /// mask, attribute number, 0, 0, register again, 1 flat / 2 interpolated; then the record count /// (+0x100) and SPI_PS_INPUT_ENA (+0x110). Checked on every cached PS of three titles (472, 34, /// 1): consistent, and covering every attribute the code reads. +/// +/// A title that packs its float16 interpolants (378 such records in 362 PS of one): byte 7 also +/// has 8 (float16, two per dword) and 16 (byte 5 = the second register of the attribute), and +/// byte 6 is the register counted after that packing (below the DXIL register from the first +/// pair on). pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let base = 0x130 + fssm_shift(fssm)?; let rd = |o: usize| fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); @@ -606,10 +615,11 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 8 * k..base + 8 * k + 8)?; - if r[3] as usize != k || r[4] != 0 || r[5] != 0 || r[6] != r[1] { + let (f16, pair) = (r[7] & 8 != 0, r[7] & 16 != 0); + if r[3] as usize != k || r[4] != 0 || (!pair && r[5] != 0) || (pair && !f16) || r[6] > r[1] { return None; } - out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] == 1 }); + out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] & 3 == 1, f16, pair: pair.then_some(r[5]) }); } Some((ena, out)) } @@ -636,6 +646,47 @@ pub fn vs_output_table(fssm: &[u8]) -> Option> { Some(out) } +/// Where a float16-packed param / attribute keeps its registers: (register, first dword). +/// The console's compiler puts two float16 components in a dword – component c of a register +/// in dword c / 2, the even one in the low half – and up to two registers in one param: the +/// second follows the dwords the first one's components take (2 for .xyz / .xyzw, 1 for .xy). +/// The registers pair up in order, so where a table does not name the second one it is the +/// next float16 register that starts no param of its own (`claimed`). Checked against the +/// code of a retail title: every `v_interp_p2_f16` channel / half of 376 packed attributes +/// (362 PS) is a declared component (2 more read one past a .xy register), and the enable +/// mask of every `exp param` of 383 packed params (442 MS) is exactly these dwords. +pub fn f16_registers(sig: &[SigElement], first: u32, second: Option, pair: bool, claimed: &dyn Fn(u32) -> bool) -> Vec<(u32, usize)> { + let second = match second { + Some(r) if r != first => Some(r), + _ if !pair => None, + _ => sig.iter().filter(|e| e.component_type == 6 && e.system_value == 0 && e.register > first && !claimed(e.register)).map(|e| e.register).min(), + }; + let width = sig.iter().filter(|e| e.system_value == 0 && e.register == first).map(|e| 8 - e.mask.leading_zeros() as usize).max().unwrap_or(4); + std::iter::once((first, 0)).chain(second.map(|r| (r, width.div_ceil(2)))).collect() +} + +/// The registers of a float16-packed PS attribute with the first dword of each (None: the +/// attribute is not packed). +pub fn ps_attribute_f16(ps: &PsInterface, attr: usize) -> Option> { + let t = ps.attrs.as_ref()?; + let a = t.get(attr).filter(|a| a.f16)?; + let claimed = |r: u32| t.iter().any(|b| b.register as u32 == r || b.pair.is_some_and(|p| p as u32 == r)); + Some(f16_registers(&ps.inputs, a.register as u32, a.pair.map(|p| p as u32), a.pair.is_some(), &claimed)) +} + +/// The place in `ranked(inputs, false)` and the component of the float16 in half `high` of +/// dword `chan` of a packed attribute (`regs`: `ps_attribute_f16`). None: no such component. +pub fn ps_f16_slot(ps: &PsInterface, regs: &[(u32, usize)], chan: usize, high: bool) -> Option<(usize, usize)> { + let &(r, first) = regs.iter().rev().find(|&&(_, first)| first <= chan)?; + let comp = 2 * (chan - first) + high as usize; + if comp > 3 { + return None; + } + let all = ranked(&ps.inputs, false); + let slot = all.iter().position(|e| e.register == r && e.mask >> comp & 1 == 1).or_else(|| all.iter().position(|e| e.register == r))?; + Some((slot, comp)) +} + /// The register `v_interp attr` reads: the console's table, else the attr-th distinct register. pub fn ps_attribute_register(ps: &PsInterface, attr: usize) -> Option { match &ps.attrs { @@ -656,7 +707,10 @@ pub fn ps_attribute_slot(ps: &PsInterface, attr: usize, chan: usize) -> Option Option { let r = ranked(&ps.inputs, false).get(slot)?.register; match &ps.attrs { - Some(t) => t.iter().position(|a| a.register as u32 == r), + Some(t) => t + .iter() + .position(|a| a.register as u32 == r) + .or_else(|| (0..t.len()).find(|&k| ps_attribute_f16(ps, k).is_some_and(|regs| regs.iter().any(|&(x, _)| x == r)))), None => param_registers(&ps.inputs, false).iter().position(|&x| x == r), } } @@ -2125,6 +2179,66 @@ mod attribute_tests { assert_eq!(ps_attribute_slot(&ps, 1, 0), Some(1)); } + /// A signature with float16 elements (component type 6) between float ones, in the shapes a + /// retail title's PS / MS pack: r7 holds two elements, r9 a single component. + fn f16_sig() -> Vec { + let e = |name: &str, index: u32, ct: u32, register: u32, mask: u8| SigElement { component_type: ct, mask, ..input(name, index, register, mask) }; + let mut pos = input("SV_Position", 0, 0, 0); + pos.system_value = 1; + vec![ + pos, + e("COLOR", 0, 6, 1, 0xF), + e("COLOR", 1, 6, 2, 0xF), + e("TEXCOORD", 0, 3, 3, 0x3), + e("TEXCOORD", 1, 6, 4, 0x7), + e("TEXCOORD", 4, 6, 5, 0xF), + e("TEXCOORD", 3, 3, 6, 0xF), + e("TEXCOORD", 7, 6, 7, 0x3), + e("TEXCOORD", 8, 6, 7, 0xC), + e("TEXCOORD", 9, 6, 8, 0x7), + e("TEXCOORD", 14, 6, 9, 0x1), + ] + } + + /// Float16 interpolants packed two per dword and two registers per attribute (the record + /// shapes of a retail title's PS, FSSM sub-version 6): the table parses, each (dword, half) + /// names its element and component, the second register is found where the record does not + /// name it, and the attributes after a pair keep their registers. + #[test] + fn f16_packed_attributes() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // PS input records: [6, reg, 3, attr, 0, reg2, packed register, 0x1a]; attr 4 repeats + // its own register (the second one is r8); attr 5 is a single float16 (0x0a) + let recs: [[u8; 8]; 6] = [[6, 1, 3, 0, 0, 2, 1, 26], [6, 3, 3, 1, 0, 0, 2, 2], [6, 4, 3, 2, 0, 5, 3, 26], [6, 6, 15, 3, 0, 0, 4, 2], [6, 7, 3, 4, 0, 7, 5, 26], [6, 9, 1, 5, 0, 0, 6, 10]]; + f[0x138..0x138 + 48].copy_from_slice(&recs.concat()); + f[0x138 + 0x100] = 6; + f[0x138 + 0x110] = 2; + let (_, attrs) = ps_input_table(&f).unwrap(); + assert_eq!(attrs.iter().map(|a| (a.register, a.f16, a.pair)).collect::>(), [(1, true, Some(2)), (3, false, None), (4, true, Some(5)), (6, false, None), (7, true, Some(7)), (9, true, None)]); + let ps = PsInterface { inputs: sig, attrs: Some(attrs), ..Default::default() }; + assert_eq!((0..6).map(|a| ps_attribute_f16(&ps, a)).collect::>(), [Some(vec![(1, 0), (2, 2)]), None, Some(vec![(4, 0), (5, 2)]), None, Some(vec![(7, 0), (8, 2)]), Some(vec![(9, 0)])]); + let all = ranked(&ps.inputs, false); + // "semantic.component" of a (dword, half) + let at = |attr: usize, chan: usize, high: bool| ps_f16_slot(&ps, &ps_attribute_f16(&ps, attr).unwrap(), chan, high).map(|(s, c)| format!("{}.{c}", all[s].semantic())).unwrap_or_default(); + assert_eq!([at(0, 0, false), at(0, 0, true), at(0, 1, true), at(0, 2, false), at(0, 3, true)], ["COLOR0.0", "COLOR0.1", "COLOR0.3", "COLOR1.0", "COLOR1.3"]); + assert_eq!([at(2, 1, false), at(2, 2, true)], ["TEXCOORD1.2", "TEXCOORD4.1"]); + // two elements in the first register; a half past the last one's components + assert_eq!([at(4, 0, true), at(4, 1, true), at(4, 2, false)], ["TEXCOORD7.1", "TEXCOORD8.3", "TEXCOORD9.0"]); + assert_eq!([at(5, 0, false), at(5, 2, false)], ["TEXCOORD14.0", ""]); + // the attributes after a pair read their own registers + assert_eq!([1, 3].map(|a| all[ps_attribute_slot(&ps, a, 0).unwrap()].semantic()), ["TEXCOORD0", "TEXCOORD3"]); + assert_eq!((0..10).map(|j| ps_slot_attribute(&ps, j)).collect::>(), [0, 0, 1, 2, 2, 3, 4, 4, 4, 5].map(Some)); + // a second register without the float16 flag is not this table + f[0x138 + 7] = 18; + assert_eq!(ps_input_table(&f), None); + + // a .xy register takes one dword: the second register starts at dword 1 + let narrow = vec![SigElement { component_type: 6, mask: 0x3, ..input("COLOR", 3, 1, 0x3) }, SigElement { component_type: 6, mask: 0x7, ..input("TEXCOORD", 8, 2, 0x7) }]; + assert_eq!(f16_registers(&narrow, 1, None, true, &|r| r == 1), [(1, 0), (2, 1)]); + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] From 6d0d0b639d1f55215adb1800dfe4b7e98e294770 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:32:03 +0100 Subject: [PATCH 2/5] Recompiler: VS / mesh exports unpack float16 params packed two per dword The other half of the previous commit: the VS and mesh (NGG) programs that feed those pixel shaders export their float16 interpolants packed the same way - two components per dword, up to two signature registers per exp param. XCL refused the output table of such programs (records [6, reg, param, reg, 0, 1 | 3]: 1 = float16, 3 = more than one dword) and fell back to "the N-th register", so every param after a pair went to its neighbour's register; a packed param went raw into its first register alone. A mesh program never used its table at all. Now the table parses for VS and mesh programs (MsInterface::params) and a packed param is unpacked where it is exported: each half goes as a float to its own component of its own element, in the VS outputs and in the mesh record, in both translators. The table does not name the second register of a pair: the float16 registers pair up in order, so it is the next one no other param starts with (f16_registers). Checked on the title's dumped programs: the enable mask of every exp param of 383 packed params in 442 MS is exactly the predicted dwords. A mesh program with a table now takes its params' registers from it, float16 or not, as a VS already did; without one nothing changes. dwords 2-3 and paired a mesh program's registers without its table; it has since dropped that part in favour of this change. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 42 ++++++- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lower.rs | 2 + crates/xcl/src/gpu/dxil/lower_gfx.rs | 19 +++- crates/xcl/src/gpu/dxil/lower_mem.rs | 20 +++- crates/xcl/src/gpu/dxil/robustness_tests.rs | 2 +- crates/xcl/src/gpu/recomp/emit.rs | 32 ++++-- .../xcl/src/gpu/recomp/heap_window_tests.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 74 ++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 107 +++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 4 +- 11 files changed, 262 insertions(+), 44 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 05f20fab41..326397c4cd 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -65,7 +65,7 @@ fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { {d}"); // a mesh program's compute pass of one console wave (48 or 64 threads) exchanges the same way for threads in [48, 64] { - let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64 }; + let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64, params: None }; let d = super::validate::disassemble(&super::kernel::translate_mesh(&code, o, &ms).unwrap_or_else(|e| panic!("mesh, {threads} threads: {e}")).dxil).unwrap(); assert_eq!(syncs(&d), 1, "mesh, {threads} threads: a group barrier at the exchange: {d}"); @@ -388,12 +388,14 @@ fn direct_and_hlsl_graphics_stages_link() { /// and TEXCOORD4.xyzw in attribute 0, as a retail title's world shaders have them): the PS /// reads each half with `v_interp_p2_f16` (SRC0 bit 8: the high half) and gets that component /// of its own element interpolated across the triangle; the float attribute after the pair -/// keeps its register. Both translators. Before: the table was refused, the PS converted the -/// raw packed dword of a `nointerpolation` input and attribute 1 was read from TEXCOORD4. +/// keeps its register. The console VS exports the packed dwords as param 0 and unpacks them +/// into the same components. Every combination of the direct and the HLSL stages, and a PC VS. +/// Before: the tables were refused, the PS converted the raw packed dword of a +/// `nointerpolation` input and attribute 1 was read from TEXCOORD4. #[test] fn f16_packed_attributes_interpolate_per_half() { use crate::gpu::dxbc::SigElement as S; - use crate::gpu::recomp::{runner, translate, Mode, Options, PsAttr, PsInterface}; + use crate::gpu::recomp::{runner, translate, Mode, Options, OutParam, PsAttr, PsInterface, VsInterface}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; if !super::graphics::tests::draw_ready() { return; @@ -403,7 +405,32 @@ fn f16_packed_attributes_interpolate_per_half() { } let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; const V: u64 = 256; + // COLOR c in v8..v11 -> halves h0..h3 in v12..v15; param 0 = (h0 | h1 << 16, h2, h3 | h0 << 16, + // h1 | h2 << 16): TEXCOORD1 = (c0, c1, c2), TEXCOORD4 = (c3, c0, c1, c2); param 1 = c reversed + let mut vs_ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", vec![("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ]; + for i in 0..4u64 { + vs_ops.push(("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 12 + i), ("SRC0", V + 8 + i)], None)); + } + for (dst, lo, hi) in [(16u64, 12u64, 13u64), (18, 15, 12), (19, 13, 14)] { + vs_ops.push(("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", dst), ("SRC0", V + lo), ("SRC1", V + hi)], None)); + } + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 32), ("EN", 0xF), ("VSRC0", 16), ("VSRC1", 14), ("VSRC2", 18), ("VSRC3", 19)], None)); + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 33), ("EN", 0xF), ("VSRC0", 11), ("VSRC1", 10), ("VSRC2", 9), ("VSRC3", 8)], None)); + let vs_list: Vec<(&str, &str, &[(&str, u64)], Option)> = vs_ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let vs_code = prog(&vs_list); let user = vec![el("TEXCOORD", 1, 0, 6, 1, 0x7), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)]; + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + attr_base: 4, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; // a PC VS handing over each component as a float: COLOR c -> TEXCOORD1 = (c0, c1, c2, 0), // TEXCOORD4 = (c3, c0, c1, c2), TEXCOORD3 = c reversed let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t1 : TEXCOORD1; float4 t4 : TEXCOORD4; float4 t3 : TEXCOORD3; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t1 = float4(i.c.xyz, 0.0); o.t4 = float4(i.c.w, i.c.xyz); o.t3 = i.c.wzyx; return o; }\n"; @@ -440,6 +467,10 @@ fn f16_packed_attributes_interpolate_per_half() { prog(&list) }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(vt.complete(), "{:?}", vt.unsupported_why); + let hvs = crate::gpu::recomp::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; // COLOR = (x, y, x / 4 + 1 / 2, y / 2 - 1 / 4) at each vertex: exact in float16, and linear // in the pixel's position let color = |x: f32, y: f32| [x, y, 0.25 * x + 0.5, 0.5 * y - 0.25]; @@ -462,7 +493,8 @@ fn f16_packed_attributes_interpolate_per_half() { assert!(!pt.hlsl.contains("nointerpolation"), "{what}: the float16 inputs interpolate\n{}", pt.hlsl); let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; - for (stages, vs, ps) in [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps)] { + let pairs = [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps), ("HLSL VS + HLSL PS", &hvs, &hps), ("direct VS + direct PS", &dvs, &dps), ("direct VS + HLSL PS", &dvs, &hps), ("HLSL VS + direct PS", &hvs, &dps)]; + for (stages, vs, ps) in pairs { let px = runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); for y in 0..8usize { for x in 0..8usize { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d8d9939b27..002a73e604 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -1322,7 +1322,7 @@ pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::R let mut vgpr = HashMap::new(); vgpr.insert(5, v5); lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); - lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone(), params: ms.params.clone() }); } /// EXEC at entry: the console wave's threads (static per wave in the split form: no diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 07220732d1..e9490822ed 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -78,6 +78,8 @@ pub struct MeshCtx { pub vok: Value, pub pok: Value, pub outputs: Vec, + /// the console's output table (`MsInterface::params`) + pub params: Option>, } /// Initial register values: loaded from `io` in the entry block on first use. diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 21e6fb27bb..8bafd98b7d 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{CastOp, Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -119,7 +119,7 @@ impl Lw { _ => SemKind::Arbitrary, }; let s = io.output(GSig::new(&e.name, e.index, kind, gct(e.component_type), n)); - outs.push((s, n, e.component_type == 3)); + outs.push((s, n, matches!(e.component_type, 3 | 6))); } // initial VGPRs: v0 = vertex id, v3 = instance id, the fetch shader's attribute VGPRs let mut vgpr = HashMap::new(); @@ -327,15 +327,22 @@ impl Lw { 32..=63 => { let vs = self.gfx().vs.clone().expect("vs"); let k = (tgt - 32) as usize; - let at = vs_param_register(&vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + for (j, first) in at { let (vars, n) = { let o = &self.gfx().params[j]; (o.vars.clone(), o.comps) }; for c in 0..n as usize { - if enabled(c) { - let v = comp(self, c); + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } self.set_out(vars[c], v); } } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index dbe002c217..4a14959087 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2697,13 +2697,23 @@ impl Lw { 13..=15 | 9 => {} 32..=63 => { let k = (tgt - 32) as usize; - let outputs = self.mesh.as_ref().expect("mesh").outputs.clone(); - let at = crate::gpu::recomp::param_registers(&outputs, true).get(k).map(|&r| crate::gpu::recomp::elements_at(&outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = { + let m = self.mesh.as_ref().expect("mesh"); + crate::gpu::recomp::out_param_elements(&m.outputs, m.params.as_deref(), k) + }; + for (j, first) in at { for c in 0..4 { - if enabled(c) { + // packed float16: component c is half c & 1 of dword first + c / 2; the + // record keeps it as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { let a = self.addc(vtx, (4 * (j + 1) + c) as u32); - let v = comp(self, c); + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } st.push((a, v)); } } diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 9a82e67cae..32366c6786 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -125,7 +125,7 @@ fn a_group_barrier_of_several_hardware_waves_uses_safe_barrier_directly() { // (the kernel form of the tests is no thread group of a title's: its barrier stays) kernel::translate(&code, o(true, true)).expect("kernel"); // a mesh program's compute pass: two console waves a group, as a retail title's - let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64 }; + let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64, params: None }; for split in [true, false] { let k = kernel::translate_mesh(&code, o(true, split), &ms(128)) .unwrap_or_else(|e| panic!("mesh pass failed (split {split}): {e}")); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1d4ba2c015..c216e68c96 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2380,18 +2380,26 @@ impl Em { // param N is a register: channel c goes to component c of every element there let k = (tgt - 32) as usize; let params = ranked(&vs.outputs, true); - let at = vs_param_register(vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { let e = params[j]; let n = out_comps(e); for c in 0..n { - if enabled(c) { - let v = Self::exp_comp(srcs, compr, c); - let v = if e.component_type == 3 { format!("asfloat({v})") } else { format!("{v}") }; + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { + format!("f16tof32({v} >> {}u)", 16 * (c & 1)) + } else if e.component_type == 3 { + format!("asfloat({v})") + } else { + format!("{v}") + }; let comp = if n == 1 { String::new() } else { format!("[{c}]") }; st.push(format!("xo.p{j}{comp} = {v};")); } @@ -2442,15 +2450,19 @@ impl Em { // param N is a register: its record slot is that of every element there (the // pass-through reads an element's slot as the whole register, as for the GS) let k = (tgt - 32) as usize; - let at = param_registers(&ms.outputs, true).get(k).map(|&r| elements_at(&ms.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&ms.outputs, ms.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { for c in 0..4 { - if enabled(c) { - st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c))); + // packed float16 (as in the VS): the record keeps each half as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { format!("asuint(f16tof32({v} >> {}u))", 16 * (c & 1)) } else { v }; + st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } } diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 4245f3b105..79ba2f6b84 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -643,7 +643,7 @@ fn heap_windows_graphics_stages_validate() { let vs = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 1, 0)], attr_base: 4, params: None }; let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1, params: None }; let has_dxc = super::dxc::location().is_ok(); for windows in [4u32, crate::gpu::uma::MAX_HEAP_WINDOWS as u32] { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 15ad7f1ecd..7ec19f848d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -130,7 +130,7 @@ pub struct VsInterface { pub attr_base: u64, /// the OSG1 register of each `exp param N` from the console's table (`vs_output_table`; /// None: the N-th distinct register) - pub params: Option>, + pub params: Option>, } impl VsInterface { @@ -358,6 +358,8 @@ pub struct MsInterface { pub threads: u32, pub max_vertices: u32, pub max_primitives: u32, + /// the console's output table, as `VsInterface::params` + pub params: Option>, } /// dwords before the vertices of a mesh record: vertex count, primitive count, 2 spare @@ -452,6 +454,7 @@ impl GsInterface { threads: 64, max_vertices: (GS_PRIMS_PER_GROUP * mvc).clamp(1, 256), max_primitives: (GS_PRIMS_PER_GROUP * mvc.saturating_sub(2).max(1)).clamp(1, 256), + params: None, } } } @@ -595,6 +598,15 @@ pub struct PsAttr { pub pair: Option, } +/// One `exp param N` of the console's output table: its first OSG1 register; `f16`: float16 +/// values, two per dword (`pair`: more than one dword – a second register may follow). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OutParam { + pub register: u32, + pub f16: bool, + pub pair: bool, +} + /// The PS input table of an FSSM: SPI_PS_INPUT_ENA and, per `v_interp attrN`, the register it /// reads. 32 records of 8 bytes at +0x130 (+ the sub-version shift): kind, register, component /// mask, attribute number, 0, 0, register again, 1 flat / 2 interpolated; then the record count @@ -628,8 +640,11 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output /// register, but not always (a Fortnite VS exports its SV_Position register as a param). -/// Checked on every cached VS of three titles (984, 13, 1). -pub fn vs_output_table(fssm: &[u8]) -> Option> { +/// Checked on every cached VS of three titles (984, 13, 1). The same table describes a mesh +/// (NGG) program's params. A float16 param (two values per dword) has 1 in the last byte, 3 +/// when it takes more than one dword, and then repeats its register in byte 3 (442 MS of one +/// title); the table does not name the second register of a pair (`f16_registers`). +pub fn vs_output_table(fssm: &[u8]) -> Option> { let base = 0x1D4 + fssm_shift(fssm)?; let n = fssm.get(base + 0xC0..base + 0xC4).map(|b| u32::from_le_bytes(b.try_into().unwrap()))? as usize; if n > 32 { @@ -638,10 +653,11 @@ pub fn vs_output_table(fssm: &[u8]) -> Option> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 6 * k..base + 6 * k + 6)?; - if r[2] as usize != k || r[3..6] != [0, 0, 0] { + let f16 = r[5] & 1 == 1; + if r[2] as usize != k || r[4] != 0 || !matches!(r[5], 0 | 1 | 3) || (r[3] != 0 && !(f16 && r[3] == r[1])) { return None; } - out.push(r[1] as u32); + out.push(OutParam { register: r[1] as u32, f16, pair: r[5] == 3 }); } Some(out) } @@ -665,6 +681,28 @@ pub fn f16_registers(sig: &[SigElement], first: u32, second: Option, pair: std::iter::once((first, 0)).chain(second.map(|r| (r, width.div_ceil(2)))).collect() } +/// The registers of `exp param N` with the first dword of each (`f16_registers`), and whether +/// they hold packed float16: the console's table, else the N-th distinct register. +pub fn out_param_registers(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> Option<(Vec<(u32, usize)>, bool)> { + match params { + Some(t) => { + let p = t.get(n)?; + if !p.f16 { + return Some((vec![(p.register, 0)], false)); + } + Some((f16_registers(outputs, p.register, None, p.pair, &|r| t.iter().any(|q| q.register == r)), true)) + } + None => param_registers(outputs, true).get(n).map(|&r| (vec![(r, 0)], false)), + } +} + +/// The elements `exp param N` writes (places in `ranked(outputs, true)`), each with the first +/// dword of its register, and whether the param holds packed float16 (`out_param_registers`). +pub fn out_param_elements(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> (Vec<(usize, usize)>, bool) { + let (regs, f16) = out_param_registers(outputs, params, n).unwrap_or_default(); + (regs.iter().flat_map(|&(r, first)| elements_at(outputs, true, r).into_iter().map(move |j| (j, first))).collect(), f16) +} + /// The registers of a float16-packed PS attribute with the first dword of each (None: the /// attribute is not packed). pub fn ps_attribute_f16(ps: &PsInterface, attr: usize) -> Option> { @@ -718,7 +756,7 @@ pub fn ps_slot_attribute(ps: &PsInterface, slot: usize) -> Option { /// The register `exp param N` of a VS writes: the console's table, else the N-th distinct one. pub fn vs_param_register(vs: &VsInterface, n: usize) -> Option { match &vs.params { - Some(t) => t.get(n).copied(), + Some(t) => t.get(n).map(|p| p.register), None => param_registers(&vs.outputs, true).get(n).copied(), } } @@ -767,6 +805,7 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss threads, max_vertices: (p.ms_max_vertices as u32).clamp(1, 256), max_primitives: (p.ms_max_primitives as u32).clamp(1, 256), + params: vs_output_table(&f.data), })) } _ => None, @@ -2239,6 +2278,27 @@ mod attribute_tests { assert_eq!(f16_registers(&narrow, 1, None, true, &|r| r == 1), [(1, 0), (2, 1)]); } + /// Float16 params packed the same way in a VS / MS output table (the record shapes of the + /// title's MS): the table parses, the second register of a pair is the next float16 register + /// that starts no param of its own (the record does not name it), and `exp param N` writes + /// the elements of both registers. + #[test] + fn f16_packed_params() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // VS / MS output records: [6, reg, param, reg, 0, 3]; param 5 is a single float16 (1) + let outs: [[u8; 6]; 6] = [[6, 1, 0, 1, 0, 3], [6, 3, 1, 0, 0, 0], [6, 4, 2, 4, 0, 3], [6, 6, 3, 0, 0, 0], [6, 7, 4, 7, 0, 3], [6, 9, 5, 0, 0, 1]]; + f[0x1DC..0x1DC + 36].copy_from_slice(&outs.concat()); + f[0x1DC + 0xC0] = 6; + let params = vs_output_table(&f).unwrap(); + assert_eq!(params.iter().map(|p| (p.register, p.f16, p.pair)).collect::>(), [(1, true, true), (3, false, false), (4, true, true), (6, false, false), (7, true, true), (9, true, false)]); + let regs = |n: usize| out_param_registers(&sig, Some(¶ms), n); + assert_eq!([regs(0), regs(1), regs(4), regs(5), regs(6)], [Some((vec![(1, 0), (2, 2)], true)), Some((vec![(3, 0)], false)), Some((vec![(7, 0), (8, 2)], true)), Some((vec![(9, 0)], true)), None]); + // elements in `ranked` order: r7 holds two, r8 one + assert_eq!(out_param_elements(&sig, Some(¶ms), 4), (vec![(6, 0), (7, 0), (8, 2)], true)); + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] @@ -2276,7 +2336,7 @@ mod attribute_tests { f[0x10] = 5; f[0x1D4..0x1D4 + 18].copy_from_slice(&[6, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 6, 2, 2, 0, 0, 0]); f[0x1D4 + 0xC0] = 3; - assert_eq!(vs_output_table(&f), Some(vec![0, 1, 2])); + assert_eq!(vs_output_table(&f).map(|t| t.iter().map(|p| p.register).collect::>()), Some(vec![0, 1, 2])); f[0x1D4 + 8] = 7; assert_eq!(vs_output_table(&f), None); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 57fd25bfb5..da1cfc1f67 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4499,7 +4499,7 @@ fn gpu_mesh_mode_two_passes() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -4623,7 +4623,7 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -4684,6 +4684,100 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() { assert_eq!(rec[rd..].iter().position(|&w| w != 0), None, "a thread past the record's slots wrote behind it"); } +/// A mesh (NGG) program whose param 0 packs two float16 registers, two components per dword +/// (TEXCOORD1.xy in dword 0, TEXCOORD4.xyzw in dwords 1 and 2 – a retail title's transform +/// programs): the record keeps every component as a float in its own element's slot, the +/// pass-through hands them to the pixel shader by semantic, and the float param after the +/// pair lands in its own register. Before: param 0 went raw into TEXCOORD1 alone and param 1 +/// into TEXCOORD4. +#[test] +fn gpu_mesh_f16_packed_params() { + if !gpu_ready() || !mesh_ready() { + return; + } + use super::{dxc, mesh_passthrough, MsInterface, OutParam, MESH_HEADER}; + let ms = MsInterface { + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 1, 0, 6, 1, 0x3), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)], + threads: 128, + max_vertices: 128, + max_primitives: 128, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; + let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) + }; + // as `gpu_mesh_mode_two_passes`: v20 = group, v15 = thread in the group (floats) + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("S_LSHR_B32", "ENC_SOP2", vec![("SDST", 1), ("SSRC0", 1), ("SSRC1", 135)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 20), ("SRC0", 1)], None), + ("V_ADD_F32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 20), ("VSRC1", 10)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", V + 20)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 16), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 17), ("SRC0", 242)], None), + // halves: v22 = group, v23 = thread, v24 = 0.5, v25 = 2.0 + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 22), ("SRC0", V + 20)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 23), ("SRC0", V + 15)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 24), ("SRC0", 240)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 25), ("SRC0", 244)], None), + // TEXCOORD1 = (group, thread); TEXCOORD4 = (0.5, group, thread, 2.0) + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 26), ("SRC0", V + 22), ("SRC1", V + 23)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 27), ("SRC0", V + 24), ("SRC1", V + 22)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 28), ("SRC0", V + 23), ("SRC1", V + 25)], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0x7, [26, 27, 28, 0], 0)); + list.push(exp(33, 0xF, [14, 15, 16, 17], 0)); + list.push(("S_MOV_B64", "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 193)], None)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let opt = on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() }); + let t = translate(&code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let cs = direct_or(&code, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); + let pass = mesh_passthrough(&ms); + let msb = dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + let ps_src = "struct V { float4 pos : SV_Position; float4 a : TEXCOORD1; float4 b : TEXCOORD4; float4 c : TEXCOORD3; };\nfloat4 main(V v) : SV_Target0 { return float4(v.a.x, v.b.x, v.b.w, v.c.w); }\n"; + let ps = dxc::compile(ps_src, "main", "ps_6_6", &[]).unwrap(); + let mut mem = vec![0u32; 256]; + for (i, (x, y)) in [(-1.0f32, -1.0f32), (-1.0, 1.0), (0.0, -1.0)].iter().enumerate() { + mem[0x40 + 4 * i..0x40 + 4 * i + 4].copy_from_slice(&[f(*x), f(*y), f(0.0), f(1.0)]); + } + let mut sg = vec![0u32; 128]; + sg[16..20].copy_from_slice(&[0x100, 16 << 16, 3, 0]); + let (px, rec) = runner::mesh_draw(&cs, &msb, &ps, 2, ms.record_dwords(), &sg, &mem, 32, [-1.0; 4]).unwrap(); + let (rd, vd) = (ms.record_dwords(), ms.vert_dwords()); + for g in 0..2usize { + let r = &rec[g * rd..(g + 1) * rd]; + assert_eq!((r[0], r[1]), (3, 1), "group {g}: GS_ALLOC_REQ counts"); + for v in 0..3usize { + let b = MESH_HEADER + v * vd; + let at = |k: usize| f32::from_bits(r[b + k]); + let (gf, vf) = (g as f32, v as f32); + assert_eq!([at(4), at(5)], [gf, vf], "group {g} vertex {v}: TEXCOORD1.xy"); + assert_eq!([at(8), at(9), at(10), at(11)], [0.5, gf, vf, 2.0], "group {g} vertex {v}: TEXCOORD4"); + assert_eq!([at(12), at(13), at(14), at(15)], [gf, vf, 0.0, 1.0], "group {g} vertex {v}: TEXCOORD3 (param 1)"); + } + } + let at = |x: usize, y: usize| px[y * 32 + x]; + assert_eq!(at(3, 29), [0.0, 0.5, 2.0, 1.0], "group 0 triangle (left)"); + assert_eq!(at(19, 29), [1.0, 0.5, 2.0, 1.0], "group 1 triangle (right)"); + assert_eq!(at(29, 3), [-1.0; 4], "outside both triangles"); +} + #[test] fn mesh_passthrough_strips_rdna2_edge_flag_bits() { use super::{mesh_passthrough, MsInterface}; @@ -4702,6 +4796,7 @@ fn mesh_passthrough_strips_rdna2_edge_flag_bits() { threads: 128, max_vertices: 128, max_primitives: 128, + params: None, }; let unsplit = mesh_passthrough(&ms); assert!(unsplit.contains("uint3(p & 0x1FFu, (p >> 10) & 0x1FFu, (p >> 20) & 0x1FFu)"), "{unsplit}"); @@ -4743,7 +4838,7 @@ fn mesh_split_accounts_vertex_chunks() { outputs.push(sig("TEXCOORD", 0, k + 1, k)); } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); - let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at @@ -4800,7 +4895,7 @@ fn mesh_layout_independent_of_group_count() { } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit; 80 declared do not - let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // one triangle: its 3 copies fit one compact group, so the dispatch count is 1 @@ -5056,7 +5151,7 @@ fn gpu_mesh_mode_reads_memory_windows() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64, params: None }; let list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), // thread @@ -8459,7 +8554,7 @@ fn far_jumps_are_direct_branches() { /// programs with cross-half operations included; native wave64 and wave32 programs unchanged. #[test] fn mesh_split_wave64_form() { - let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![] }; + let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![], params: None }; let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); let branch = prog(&[("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None)]); for code in [&lane, &branch] { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..fa6e78c51d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9007,7 +9007,7 @@ pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { compute: 0, compute_rs: 0, mesh_rs: 0, - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64, params: None }, mesh_groups_per_record: 1, kind, }), @@ -14245,7 +14245,7 @@ mod mesh_stream_tests { let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], ms: vec![0; 16], - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1, params: None }, mesh_groups_per_record: 1, samplers: vec![sampler], }; From 27332a4edfe46fcecc748cc60adfa448376c619e Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:36:24 +0100 Subject: [PATCH 3/5] Recompiler: float16 params reach the PS as the floats of their halves The two commits before this one (PR 2513, ported) take every float16 record of a VS / mesh output table - flag 1 or 3 - as two halves a dword. The retail title (#505) has two kinds (PR 2513's thread, CharlyRien 2026-11-29, and its own listings): flag-3 records packed in dwords 0-1, with filler in dwords 2-3 of an .xyzw register (exp param 7: two v_pack_b32_f16, 0 and 0x3c00, en 0xF), and flag-1 records on .xyzw registers exported over four dwords, a half in the low bits of each (four v_and_b32 v, 0xffff, h, en 0xF). Taken as packed, the second kind lost dwords 2-3 and its components 1-3 got the wrong halves. A flag-3 record is packed; a flag-1 one only where its export writes exactly its packed dwords and not also one dword per component, else one half a dword: component c is the low half of dword c (ParamLayout, F16Param). Either way each component reaches its element as the float of its half, in the VS export and the mesh store of both translators, so a float16 element is an ordinary float however the PS reads it: interpolated by v_interp_p2_f16 (the PR's single float16, a flag-1 .x read so), or flat by v_interp_mov_f32, which now gives the half of a float16 attribute's float back in the low bits, as the title's v_cvt_f32_f16 takes it - both halves of the dword where the PS record names a second register (packed). The round trip is exact for every half but a NaN's payload. On the HLSL path the VS export assigned a dword to a float output as a number for every component type but 3 (the thread, 13:44Z: a raw half 1.0 arrived as 0, 0.7 as 2048); it is now bitcast for every element HLSL declares float (all but types 1 and 2). And a float16 PS input takes the interpolation its reads give it - flat where v_interp_mov reads it, interpolated where v_interp_p1 / p2 do - where it was flat unless the PS table marked it packed; integers stay flat. Both translators. Tests, each failing without its part: - dxil::core_tests::f16_params_reach_the_ps_as_the_floats_of_their_halves: the title's two kinds (flag 3 packed with filler, en 0xF; flag 1 over four dwords) and a flag-1 .x, from an HLSL and a direct VS to a PC PS; - dxil::core_tests::f16_params_reach_a_console_ps_however_it_reads_them: the same from a console VS to a console PS reading them by v_interp_p2_f16 per half, by v_interp_mov_f32 and v_cvt_f32_f16, and the .x interpolated by v_interp_p2_f16 - HLSL and direct, and across; - dxil::core_tests::f16_ps_inputs_take_the_mode_their_reads_give_them; - recomp::attribute_tests::a_float16_params_layout_follows_its_record_and_its_export; - recomp::tests::a_float16_ps_input_takes_the_mode_its_reads_give_it. Ported from Jockerino/xcl-fork b6ee86a1 (https://github.com/Jockerino/xcl-fork, GPL-3.0-or-later), written there on top of the fork's own port of #2513, with the fork author's agreement. Moved onto main b2b1f109 + #2513: conflicts in lower_gfx.rs (main's integer-to-float conversion of PS inputs, kept) and recomp/mod.rs. Co-authored-by: Jockerino <51916136+Jockerino@users.noreply.github.com> Assisted-by: Antigravity CLI (Gemini 4 Neon), conflict resolution Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 254 ++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_gfx.rs | 59 ++++-- crates/xcl/src/gpu/dxil/lower_mem.rs | 16 +- crates/xcl/src/gpu/recomp/emit.rs | 54 ++++-- crates/xcl/src/gpu/recomp/mod.rs | 130 +++++++++++++ crates/xcl/src/gpu/recomp/tests.rs | 28 +++ 6 files changed, 504 insertions(+), 37 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 326397c4cd..4c1e49811d 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -508,6 +508,260 @@ fn f16_packed_attributes_interpolate_per_half() { } } +/// The title's float16 params (PR 2513's thread, CharlyRien 2026-11-29, and its own listings, e.g. +/// `vs_dfd42921d79bb3f5`), made by a console VS: param 0 a flag-3 record packed in dwords 0-1 with +/// filler in dwords 2-3 (`exp param 7`: two `v_pack_b32_f16`, 0 and 0x3c00, `en 0xF`); params 1-3 +/// flag-1 records one half a dword (`v_and_b32 v, 0xffff, h` into all four, `en 0xF`); param 4 a +/// flag-1 `.x` (`en 0x1`, other bits in the high half). A PC PS gets every component as the float +/// of its half - through both translators. Before: param 0 was taken for one half a dword (its +/// `en 0xF` against the packed 0x3) and params 1-3 went over as their bits (as the PR had them: +/// unpacked from dwords 0-1, with 2-3 lost). +#[test] +fn f16_params_reach_the_ps_as_the_floats_of_their_halves() { + use crate::gpu::recomp::{runner, translate, Mode, Options, OutParam, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + const V: u64 = 256; + // (float16 bits: 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, -1.0) + let (q, half, tq, one, one_half, two, minus_one) = (0x3400u32, 0x3800u32, 0x3A00u32, 0x3C00u32, 0x3E00u32, 0x4000u32, 0xBC00u32); + let packed = [half | one_half << 16, two | minus_one << 16]; + let halves = [q, half, tq, one]; + let mut ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", vec![("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 10), ("SRC0", 255)], Some(packed[0])), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 255)], Some(packed[1])), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 12), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 13), ("SRC0", 255)], Some(one)), + ("EXP", "ENC_EXP", vec![("TGT", 32), ("EN", 0xF), ("VSRC0", 10), ("VSRC1", 11), ("VSRC2", 12), ("VSRC3", 13)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 18), ("SRC0", 255)], Some(0x5A5A_0000 | tq)), + ("EXP", "ENC_EXP", vec![("TGT", 36), ("EN", 0x1), ("VSRC0", 18), ("VSRC1", 18), ("VSRC2", 18), ("VSRC3", 18)], None), + ]; + for (k, &x) in halves.iter().enumerate() { + ops.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14 + k as u64), ("SRC0", 255)], Some(x))); + } + // (param p: halves rotated by p - 1) + for p in 1..4u64 { + let r = |c: u64| 14 + (c + p - 1) % 4; + ops.push(("EXP", "ENC_EXP", vec![("TGT", 32 + p), ("EN", 0xF), ("VSRC0", r(0)), ("VSRC1", r(1)), ("VSRC2", r(2)), ("VSRC3", r(3))], None)); + } + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let vs_code = prog(&list); + let f16 = |index: u32, reg: u32, mask: u8| sig("TEXCOORD", index, 0, 6, reg, mask); + let vsi = VsInterface { + inputs: vec![sig("POSITION", 0, 0, 3, 0, 3)], + outputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF), f16(7, 1, 0xF), f16(8, 2, 0xF), f16(9, 3, 0xF), f16(10, 4, 0xF), f16(11, 5, 0x1)], + attr_base: 4, + params: Some((1..=5).map(|register| OutParam { register, f16: true, pair: register == 1 }).collect()), + }; + let hvs = crate::gpu::recomp::dxc::compile(&translate(&vs_code, &Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; + // a PC PS returning what one param brought + let ps = |sel: &str| { + let src = format!( + "struct V {{ float4 pos : SV_Position; float4 t7 : TEXCOORD7; nointerpolation float4 t8 : TEXCOORD8; nointerpolation float4 t9 : TEXCOORD9; nointerpolation float4 t10 : TEXCOORD10; float4 t11 : TEXCOORD11; }};\nfloat4 main(V v) : SV_Target0 {{ return {sel}; }}\n" + ); + crate::gpu::recomp::dxc::compile(&src, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{src}")) + }; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1]]).collect(); + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let cases: [(&str, [f32; 4], &str); 5] = [ + ("v.t7", [0.5, 1.5, 2.0, -1.0], "param 0, flag 3 packed with filler"), + ("v.t8", [0.25, 0.5, 0.75, 1.0], "param 1, flag 1 a half a dword"), + ("v.t9", [0.5, 0.75, 1.0, 0.25], "param 2"), + ("v.t10", [0.75, 1.0, 0.25, 0.5], "param 3"), + ("float4(v.t11.x, 0.0, 0.0, 0.0)", [0.75, 0.0, 0.0, 0.0], "param 4, flag 1 .x"), + ]; + for (sel, want, what) in cases { + let pps = ps(sel); + for (path, vs) in [("HLSL VS", &hvs), ("direct VS", &dvs)] { + let px = runner::draw(vs, &pps, &layout, &verts, 8, &[], &[], 8, [9.0; 4]).unwrap(); + assert!(px.iter().all(|p| *p == want), "{what}, {path}: {:?}, expected {want:?}", px[0]); + } + } +} + +/// The same params from a console VS to a console PS, through both translators and across them: +/// the PS reads param 0 (flag 3, packed with filler) by `v_interp_p2_f16` per half; param 1 (flag 1 +/// over four dwords, its PS record flat - the thread's input flag 9) by `v_interp_mov_f32` and +/// `v_cvt_f32_f16`; param 2 (flag 1 `.x`, PS record 0x0a: the PR's single float16) by +/// `v_interp_p2_f16`, interpolated across the triangle. A float16 attribute's `v_interp_mov_f32` +/// gives back the half of its float. Before: param 0 taken for halves and params 1-2 sent as +/// bits, params 0 and 2 came out wrong; as the PR had them (flag 1 packed), param 1. +#[test] +fn f16_params_reach_a_console_ps_however_it_reads_them() { + use crate::gpu::recomp::{runner, translate, Mode, Options, OutParam, PsAttr, PsInterface, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + const V: u64 = 256; + let (q, half, tq, one, one_half, two, minus_one) = (0x3400u32, 0x3800u32, 0x3A00u32, 0x3C00u32, 0x3E00u32, 0x4000u32, 0xBC00u32); + let mut vs_ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", vec![("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 10), ("SRC0", 255)], Some(half | one_half << 16)), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 255)], Some(two | minus_one << 16)), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 12), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 13), ("SRC0", 255)], Some(one)), + ("EXP", "ENC_EXP", vec![("TGT", 32), ("EN", 0xF), ("VSRC0", 10), ("VSRC1", 11), ("VSRC2", 12), ("VSRC3", 13)], None), + // x as a half, varying across the triangle + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 18), ("SRC0", V + 4)], None), + ("EXP", "ENC_EXP", vec![("TGT", 34), ("EN", 0x1), ("VSRC0", 18), ("VSRC1", 18), ("VSRC2", 18), ("VSRC3", 18)], None), + ]; + for (k, x) in [q, half, tq, one].into_iter().enumerate() { + vs_ops.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14 + k as u64), ("SRC0", 255)], Some(x))); + } + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 33), ("EN", 0xF), ("VSRC0", 14), ("VSRC1", 15), ("VSRC2", 16), ("VSRC3", 17)], None)); + let vs_list: Vec<(&str, &str, &[(&str, u64)], Option)> = vs_ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let vs_code = prog(&vs_list); + let user = vec![sig("TEXCOORD", 7, 0, 6, 1, 0xF), sig("TEXCOORD", 8, 0, 6, 2, 0xF), sig("TEXCOORD", 9, 0, 6, 3, 0x1)]; + let vsi = VsInterface { + inputs: vec![sig("POSITION", 0, 0, 3, 0, 3)], + outputs: std::iter::once(sig("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + attr_base: 4, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 2, f16: true, pair: false }, OutParam { register: 3, f16: true, pair: false }]), + }; + let psi = PsInterface { + inputs: std::iter::once(sig("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: Some(vec![ + PsAttr { kind: 6, register: 1, mask: 0xF, flat: false, f16: true, pair: None }, + PsAttr { kind: 6, register: 2, mask: 0xF, flat: true, f16: true, pair: None }, + PsAttr { kind: 6, register: 3, mask: 0x1, flat: false, f16: true, pair: None }, + ]), + }; + // a read: P(attribute, dword, high half) by v_interp_p2_f16, M(attribute, channel) by mov + #[derive(Clone, Copy)] + enum R { + P(u64, u64, u64), + M(u64, u64), + } + let ps_code = |sel: [R; 4]| { + let mut ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, r) in sel.iter().enumerate() { + let k = k as u64; + match *r { + R::P(a, chan, high) => { + let attr = a | chan << 6 | high << 8; + ops.push(("V_INTERP_P1LL_F16", "ENC_VOP3", vec![("VDST", 8 + k), ("SRC1", V), ("SRC0", attr)], None)); + ops.push(("V_INTERP_P2_F16", "ENC_VOP3", vec![("VDST", 4 + k), ("SRC1", V + 1), ("SRC0", attr), ("SRC2", V + 8 + k)], None)); + } + R::M(a, chan) => ops.push(("V_INTERP_MOV_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 2), ("ATTR", a), ("ATTRCHAN", chan)], None)), + } + ops.push(("V_CVT_F32_F16", "ENC_VOP1", vec![("VDST", 4 + k), ("SRC0", V + 4 + k)], None)); + } + ops.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + prog(&list) + }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(vt.complete(), "{:?}", vt.unsupported_why); + let hvs = crate::gpu::recomp::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1]]).collect(); + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + // what each read gives: a value, or None for the pixel's x + use R::{M, P}; + let cases: [([R; 4], [Option; 4], &str); 3] = [ + ([P(0, 0, 0), P(0, 0, 1), P(0, 1, 0), P(0, 1, 1)], [Some(0.5), Some(1.5), Some(2.0), Some(-1.0)], "param 0 per half"), + ([M(1, 0), M(1, 1), M(1, 2), M(1, 3)], [Some(0.25), Some(0.5), Some(0.75), Some(1.0)], "param 1 flat by mov"), + ([P(2, 0, 0), M(1, 3), P(0, 1, 1), P(2, 0, 0)], [None, Some(1.0), Some(-1.0), None], "param 2 interpolated, and one of each"), + ]; + let mut bad = Vec::new(); + for (sel, want, what) in cases { + let code = ps_code(sel); + let pt = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{what}: {:?}", pt.unsupported_why); + let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; + for (stages, vs, ps) in [("HLSL VS + HLSL PS", &hvs, &hps), ("direct VS + direct PS", &dvs, &dps), ("HLSL VS + direct PS", &hvs, &dps), ("direct VS + HLSL PS", &dvs, &hps)] { + let px = runner::draw(vs, ps, &layout, &verts, 8, &[], &[], 8, [9.0; 4]).unwrap(); + let wrong = (0..64usize).find_map(|i| { + let x = (i % 8) as f32 / 4.0 + 0.125 - 1.0; + let expected = want.map(|w| w.unwrap_or(x)); + let got = px[i]; + (!got.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3)).then(|| format!("{what}, {stages}: pixel {i} = {got:?}, expected {expected:?}")) + }); + bad.extend(wrong); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + +/// Float16 PS inputs no PS table marks packed take the interpolation their reads give them, +/// through both translators: TEXCOORD0, read by `v_interp_p1 / p2_f32`, varies across the +/// triangle; TEXCOORD1, read by `v_interp_mov_f32`, is the provoking vertex's. Before: both +/// flat (a float16 input interpolated only where the PS table packed it). +#[test] +fn f16_ps_inputs_take_the_mode_their_reads_give_them() { + use crate::gpu::recomp::{runner, translate, Mode, Options, PsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t0 : TEXCOORD0; float4 t1 : TEXCOORD1; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t0 = i.c; o.t1 = i.c; return o; }\n"; + let pvs = crate::gpu::recomp::dxc::compile(pc_vs, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pc_vs}")); + let psi = PsInterface { + inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF), sig("TEXCOORD", 0, 0, 6, 1, 0xF), sig("TEXCOORD", 1, 0, 6, 2, 0xF)], + outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let code = prog(&[ + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 1)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 1)], None), + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 2), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 7), ("VSRC", 2), ("ATTR", 1), ("ATTRCHAN", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), + ]); + let pt = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{:?}", pt.unsupported_why); + let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; + // COLOR = (x, y, 0, 1) at each vertex; the first, (-1, -1), is the provoking one + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1], p[0], p[1], 0.0, 1.0]).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + let mut bad = Vec::new(); + for (path, ps) in [("HLSL PS", &hps), ("direct PS", &dps)] { + let px = runner::draw(&pvs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); + let wrong = (0..64usize).find_map(|i| { + let (x, y) = (i % 8, i / 8); + let expected = [(x as f32 + 0.5) / 4.0 - 1.0, 1.0 - (y as f32 + 0.5) / 4.0, -1.0, -1.0]; + let got = px[i]; + (!got.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3)).then(|| format!("{path}: pixel ({x},{y}) = {got:?}, expected {expected:?}")) + }); + bad.extend(wrong); + } + assert!(bad.is_empty(), "TEXCOORD0 interpolated, TEXCOORD1 flat:\n{}", bad.join("\n")); +} + fn sig(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 8bafd98b7d..4024936d98 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{CastOp, Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; +use crate::gpu::recomp::{out_param_layout, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -166,8 +166,9 @@ impl Lw { for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { let attr = ps_slot_attribute(ps, k); let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); - // float16 read through a packed attribute interpolates like a float - let float = e.component_type == 3 || (e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some())); + // a float16 input (packed or one half per dword) has the mode its reads give it - + // flat where `v_interp_mov` reads it; integers are flat + let float = matches!(e.component_type, 3 | 6); let interp = if !float { Interp::Constant } else { @@ -327,19 +328,21 @@ impl Lw { 32..=63 => { let vs = self.gfx().vs.clone().expect("vs"); let k = (tgt - 32) as usize; - let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + // (a float16 param's layout checked against the dwords the export writes) + let dwords = (0..4).filter(|&c| enabled(c)).fold(0u32, |m, c| m | 1 << c); + let (at, layout) = out_param_layout(&vs.outputs, vs.params.as_deref(), k, dwords); for (j, first) in at { let (vars, n) = { let o = &self.gfx().params[j]; (o.vars.clone(), o.comps) }; for c in 0..n as usize { - // packed float16: component c is half c & 1 of dword first + c / 2 - let dw = if f16 { first + c / 2 } else { c }; + // float16: component c is the float of its half (`ParamLayout::place`) + let (dw, half) = layout.place(first, c); if dw < 4 && enabled(dw) { let mut v = comp(self, dw); - if f16 { - let h = self.lshrc(v, 16 * (c as u32 & 1)); + if let Some(h) = half { + let h = self.lshrc(v, 16 * h); let x = self.s.f16_to_f32(h); v = self.bits(x); } @@ -418,8 +421,17 @@ impl Lw { None => return err(d, "attribute outside ISG1"), }, }; - let load = |lw: &mut Lw| -> (Value, u32) { - let Some((slot, comp)) = place else { return (lw.fc(0.0), 3) }; + // `v_interp_mov_f32` of a float16 attribute, whose halves reach the PS as their floats + // (`recomp::out_param_layout`): the half of channel `chan`'s float in the low bits, as the + // title's `v_cvt_f32_f16` takes it - both halves of the dword where the record names a + // second register (packed) + let f16_mov = match ps_attribute_f16(&ps, attr as usize).filter(|_| name == "v_interp_mov_f32") { + Some(regs) if ps.attrs.as_ref().and_then(|t| t.get(attr as usize)).is_some_and(|a| a.pair.is_some()) => Some([ps_f16_slot(&ps, ®s, chan as usize, false), ps_f16_slot(&ps, ®s, chan as usize, true)]), + Some(_) => Some([place, None]), + None => None, + }; + let load_at = |lw: &mut Lw, at: Option<(usize, usize)>| -> (Value, u32) { + let Some((slot, comp)) = at else { return (lw.fc(0.0), 3) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, ct) = g.ps_in[slot]; (g.io.load_input(&mut lw.s, sig, 0, comp as u8), ct) @@ -432,6 +444,7 @@ impl Lw { _ => x, } }; + let load = |lw: &mut Lw| load_at(lw, place); let dst = super::lower::Dst::V(vdst); match name { "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => {} @@ -445,8 +458,30 @@ impl Lw { if ij != 2 { return err(d, "v_interp_mov p10/p20"); } - let (x, _) = load(self); - let v = self.bits(x); + let v = match f16_mov { + None => { + let (x, _) = load(self); + self.bits(x) + } + Some([lo, hi]) => { + let half = |lw: &mut Lw, at: Option<(usize, usize)>| -> Value { + if at.is_none() { + return lw.c(0); + } + let (x, ct) = load_at(lw, at); + let xf = as_f32(lw, x, ct); + lw.to_f16(xf) + }; + let l = half(self, lo); + if hi.is_some() { + let h = half(self, hi); + let hs = self.shlc(h, 16); + self.or(l, hs) + } else { + l + } + } + }; self.write32(&dst, v); } "v_interp_p2_f16" => { diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 4a14959087..3139dc59dc 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2697,20 +2697,22 @@ impl Lw { 13..=15 | 9 => {} 32..=63 => { let k = (tgt - 32) as usize; - let (at, f16) = { + // (a float16 param's layout checked against the dwords the export writes) + let dwords = (0..4).filter(|&c| enabled(c)).fold(0u32, |m, c| m | 1 << c); + let (at, layout) = { let m = self.mesh.as_ref().expect("mesh"); - crate::gpu::recomp::out_param_elements(&m.outputs, m.params.as_deref(), k) + crate::gpu::recomp::out_param_layout(&m.outputs, m.params.as_deref(), k, dwords) }; for (j, first) in at { for c in 0..4 { - // packed float16: component c is half c & 1 of dword first + c / 2; the - // record keeps it as a float - let dw = if f16 { first + c / 2 } else { c }; + // float16: component c is the float of its half (`ParamLayout::place`); + // the record keeps it as a float + let (dw, half) = layout.place(first, c); if dw < 4 && enabled(dw) { let a = self.addc(vtx, (4 * (j + 1) + c) as u32); let mut v = comp(self, dw); - if f16 { - let h = self.lshrc(v, 16 * (c as u32 & 1)); + if let Some(h) = half { + let h = self.lshrc(v, 16 * h); let x = self.s.f16_to_f32(h); v = self.bits(x); } diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index c216e68c96..fb6a3b337b 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{out_param_layout, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2353,6 +2353,8 @@ impl Em { let done = rdna2::field_value(d.enc, &d.words, "DONE") == Some(1); let vm = rdna2::field_value(d.enc, &d.words, "VM") == Some(1); let enabled = |c: usize| if compr { en >> (c / 2 * 2) & 3 != 0 } else { en >> c & 1 == 1 }; + // (the dwords the export writes: a float16 param's layout is checked against them) + let dwords = (0..4).filter(|&c| enabled(c)).fold(0u32, |m, c| m | 1 << c); let mut st = Vec::new(); match (&self.opt.mode, tgt) { (Mode::Vertex(_), 12) => { @@ -2380,7 +2382,7 @@ impl Em { // param N is a register: channel c goes to component c of every element there let k = (tgt - 32) as usize; let params = ranked(&vs.outputs, true); - let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + let (at, layout) = out_param_layout(&vs.outputs, vs.params.as_deref(), k, dwords); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); @@ -2389,16 +2391,16 @@ impl Em { let e = params[j]; let n = out_comps(e); for c in 0..n { - // packed float16: component c is half c & 1 of dword first + c / 2 - let dw = if f16 { first + c / 2 } else { c }; + // float16: component c is the float of its half (`ParamLayout::place`) + let (dw, half) = layout.place(first, c); if dw < 4 && enabled(dw) { let v = Self::exp_comp(srcs, compr, dw); - let v = if f16 { - format!("f16tof32({v} >> {}u)", 16 * (c & 1)) - } else if e.component_type == 3 { - format!("asfloat({v})") - } else { - format!("{v}") + // (else the dword's bits: assigned to a float output the uint was + // converted as a number - PR 2513's thread, 2026-11-29 13:44Z) + let v = match half { + Some(h) => format!("f16tof32({v} >> {}u)", 16 * h), + None if matches!(e.component_type, 1 | 2) => v, + None => format!("asfloat({v})"), }; let comp = if n == 1 { String::new() } else { format!("[{c}]") }; st.push(format!("xo.p{j}{comp} = {v};")); @@ -2450,18 +2452,21 @@ impl Em { // param N is a register: its record slot is that of every element there (the // pass-through reads an element's slot as the whole register, as for the GS) let k = (tgt - 32) as usize; - let (at, f16) = out_param_elements(&ms.outputs, ms.params.as_deref(), k); + let (at, layout) = out_param_layout(&ms.outputs, ms.params.as_deref(), k, dwords); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } for (j, first) in at { for c in 0..4 { - // packed float16 (as in the VS): the record keeps each half as a float - let dw = if f16 { first + c / 2 } else { c }; + // float16 (as in the VS): the record keeps each half as a float + let (dw, half) = layout.place(first, c); if dw < 4 && enabled(dw) { let v = Self::exp_comp(srcs, compr, dw); - let v = if f16 { format!("asuint(f16tof32({v} >> {}u))", 16 * (c & 1)) } else { v }; + let v = match half { + Some(h) => format!("asuint(f16tof32({v} >> {}u))", 16 * h), + None => v, + }; st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } @@ -2518,6 +2523,18 @@ impl Em { format!("xi.a{slot}[{chan}]") } }; + // `v_interp_mov_f32` of a float16 attribute, whose halves reach the PS as their floats + // (`out_param_layout`): the half of channel `chan`'s float in the low bits, as the title's + // `v_cvt_f32_f16` takes it - both halves of the dword where the record names a second + // register (packed) + let f16_word = match ps_attribute_f16(ps, attr as usize).filter(|_| name == "v_interp_mov_f32") { + Some(regs) if ps.attrs.as_ref().and_then(|t| t.get(attr as usize)).is_some_and(|a| a.pair.is_some()) => { + let half = |high: bool| ps_f16_slot(ps, ®s, chan as usize, high).map(|(s, c)| to_f16_expr(self.dynamic_f16_rm, &format!("(float)xi.a{s}[{c}]"))); + Some(format!("({} | ({} << 16))", half(false).unwrap_or_else(|| "0u".into()), half(true).unwrap_or_else(|| "0u".into()))) + } + Some(_) => Some(to_f16_expr(self.dynamic_f16_rm, &format!("(float){src}"))), + None => None, + }; let act = self.act(); match name { "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => { @@ -2534,7 +2551,8 @@ impl Em { } let v = self.vreg(vdst); // P0 loads the parameter word, including integer selector bits (#249). - self.line(&format!("{v} = select({act}, asuint({src}), {v});")); + let word = f16_word.unwrap_or_else(|| format!("asuint({src})")); + self.line(&format!("{v} = select({act}, {word}, {v});")); } "v_interp_p2_f16" => { let v = self.vreg(vdst); @@ -5600,9 +5618,9 @@ static uint xcl_cap = 1u << 16; // the mode of the attribute this input is read through (none: never read) let attr = ps_slot_attribute(ps, k); let mut m = attr.and_then(|a| self.ps_modes.get(&(a as u32))).cloned().unwrap_or_default(); - // float16 read through a packed attribute interpolates like a float - let f16 = e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some()); - if e.component_type != 3 && !f16 { + // a float16 input (packed or one half per dword) has the mode its reads give + // it - flat where `v_interp_mov` reads it; integers are flat + if !matches!(e.component_type, 3 | 6) { m = "nointerpolation".into(); } let _ = writeln!(h, " {m} {}4 a{k} : {};", hlsl_type(e), e.semantic()); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 7ec19f848d..888baf6c84 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -696,6 +696,104 @@ pub fn out_param_registers(outputs: &[SigElement], params: Option<&[OutParam]>, } } +/// How `exp param N` holds the components of its elements in its dwords (`out_param_layout`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ParamLayout { + /// component c is dword c as it is (a float element takes its bits) + Dwords, + /// float16, two halves a dword: component c is half c & 1 of dword first + c / 2 + Packed, + /// float16, one half a dword: component c is the low half of dword c + Halves, +} + +impl ParamLayout { + /// The dword component `c` of an element whose register starts at dword `first` comes from, + /// and its half (None: the whole dword). A half reaches the element as its float value. + pub fn place(self, first: usize, c: usize) -> (usize, Option) { + match self { + ParamLayout::Dwords => (c, None), + ParamLayout::Packed => (first + c / 2, Some(c as u32 & 1)), + ParamLayout::Halves => (c, Some(0)), + } + } +} + +/// What decides a float16 param's layout (`f16_param_shape`): its record and its export. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct F16Param { + /// a flag-3 record (more than one dword); else flag 1 + pub flag3: bool, + /// the dwords its first register's components take one a dword (bit c: dword c) + pub plain: u32, + /// the dwords it takes packed, two halves a dword + pub packed: u32, + /// the dwords the export writes + pub en: u32, +} + +impl F16Param { + /// A flag-3 record is packed; a flag-1 one only where the export writes exactly its packed + /// dwords and not also one dword per component, else one half a dword (on a `.x` register, + /// where both are dword 0, the two are the same). + pub fn layout(self) -> ParamLayout { + if self.flag3 || (self.en == self.packed && self.en != self.plain) { + ParamLayout::Packed + } else { + ParamLayout::Halves + } + } + + /// The record and the export disagree: a flag-3 record whose packed dwords the export does + /// not all write, or a flag-1 one whose export writes neither its packed dwords nor one + /// dword per component. + pub fn disagrees(self) -> bool { + if self.flag3 { + self.en & self.packed != self.packed + } else { + self.en != self.packed && self.en != self.plain + } + } +} + +/// The elements `exp param N` writes (places in `ranked(outputs, true)`, each with the first +/// dword of its register) and how its dwords hold them, for an export whose enabled dwords are +/// `en` (bit c: dword c). A float16 param of the table reaches its elements as float values, +/// laid out as its record and its export say (`F16Param::layout`). PR 2513's thread +/// (CharlyRien, 2026-11-29) and the title's own listings: flag-1 records on `.xyzw` registers +/// exported over four dwords, a half in the low bits of each (`en 0xF`); flag-3 ones packed in +/// dwords 0-1 with filler in dwords 2-3 (`en 0xF`). As values, a half reaches a PS that +/// interpolates it (`v_interp_p2_f16`) and one that takes it flat (`v_interp_mov_f32`, whose +/// read gives its half back: `emit::interp`) alike. +pub fn out_param_layout(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize, en: u32) -> (Vec<(usize, usize)>, ParamLayout) { + let Some((regs, f16)) = out_param_registers(outputs, params, n) else { return (Vec::new(), ParamLayout::Dwords) }; + let at = |regs: &[(u32, usize)]| -> Vec<(usize, usize)> { regs.iter().flat_map(|&(r, first)| elements_at(outputs, true, r).into_iter().map(move |j| (j, first))).collect() }; + if !f16 { + return (at(®s), ParamLayout::Dwords); + } + match f16_param_shape(outputs, params, n, ®s, en).layout() { + ParamLayout::Packed => (at(®s), ParamLayout::Packed), + // (one half a dword: the first register's components; a flag-1 record names no second) + l => (at(®s[..1]).into_iter().map(|(j, _)| (j, 0)).collect(), l), + } +} + +/// `F16Param` of float16 param `n` over `regs` (`out_param_registers`) at an export writing +/// dwords `en`. +pub fn f16_param_shape(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize, regs: &[(u32, usize)], en: u32) -> F16Param { + let (packed, plain) = f16_param_dwords(outputs, regs); + F16Param { flag3: params.and_then(|t| t.get(n)).is_some_and(|p| p.pair), plain, packed, en: en & 0xF } +} + +/// The dwords (bit c: dword c) a float16 param over `regs` (`out_param_registers`) takes packed, +/// two halves a dword, and one component a dword (its first register's components). +pub fn f16_param_dwords(outputs: &[SigElement], regs: &[(u32, usize)]) -> (u32, u32) { + let width = |r: u32| outputs.iter().filter(|e| e.system_value == 0 && e.register == r).map(|e| 8 - e.mask.leading_zeros() as usize).max().unwrap_or(4).clamp(1, 4); + let packed = regs.iter().fold(0u32, |m, &(r, first)| m | ((1u32 << width(r).div_ceil(2)) - 1) << first) & 0xF; + let plain = regs.first().map_or(0, |&(r, _)| (1u32 << width(r)) - 1); + (packed, plain) +} + /// The elements `exp param N` writes (places in `ranked(outputs, true)`), each with the first /// dword of its register, and whether the param holds packed float16 (`out_param_registers`). pub fn out_param_elements(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> (Vec<(usize, usize)>, bool) { @@ -2340,4 +2438,36 @@ mod attribute_tests { f[0x1D4 + 8] = 7; assert_eq!(vs_output_table(&f), None); } + + /// (PR 2513's thread, the title's listings) A float16 param's layout: a flag-3 record is + /// packed whatever else its export writes - the title's `exp param 7` has `en 0xF`, two + /// `v_pack_b32_f16` in dwords 0-1 and filler (0, 0x3c00) in 2-3; a flag-1 record is packed only + /// where the export writes exactly its packed dwords and not also one a component, else one half + /// a dword (the title's `en 0xF` of four `v_and_b32 v, 0xffff, h`). `disagrees`: a flag-3 record + /// whose packed dwords are not all written, a flag-1 one whose export is neither layout. + #[test] + fn a_float16_params_layout_follows_its_record_and_its_export() { + let reg = |register: u32, mask: u8| SigElement { name: "TEXCOORD".into(), index: register, system_value: 0, component_type: 6, register, mask, rw_mask: mask, stream: 0 }; + let outputs = vec![reg(1, 0xF), reg(2, 0xF), reg(3, 0x3), reg(4, 0x1), reg(5, 0x1)]; + let p = |register: u32, pair: bool| OutParam { register, f16: true, pair }; + let t = [p(1, true), p(2, false), p(3, false), p(4, false), p(5, true)]; + let slot = |r: u32| ranked(&outputs, true).iter().position(|e| e.register == r).unwrap(); + let layout = |n: usize, en: u32| out_param_layout(&outputs, Some(&t), n, en); + let shape = |n: usize, en: u32| f16_param_shape(&outputs, Some(&t), n, &out_param_registers(&outputs, Some(&t), n).unwrap().0, en); + use ParamLayout::{Halves, Packed}; + assert_eq!(layout(0, 0xF), (vec![(slot(1), 0)], Packed), "flag 3 .xyzw, packed in dwords 0-1 and filler in 2-3 (the title's)"); + assert_eq!(layout(0, 0x3), (vec![(slot(1), 0)], Packed), "flag 3 .xyzw in dwords 0-1"); + assert_eq!(layout(1, 0xF), (vec![(slot(2), 0)], Halves), "flag 1 .xyzw over four dwords (the title's)"); + assert_eq!(layout(1, 0x3), (vec![(slot(2), 0)], Packed), "flag 1 .xyzw in dwords 0-1"); + assert_eq!(layout(2, 0x1), (vec![(slot(3), 0)], Packed), "flag 1 .xy in one dword"); + assert_eq!(layout(2, 0x3), (vec![(slot(3), 0)], Halves), "flag 1 .xy over two dwords"); + assert_eq!(layout(3, 0x1).1, Halves, "flag 1 .x: the low half of dword 0, as packed would take it"); + assert_eq!(layout(4, 0x1).1, Packed, "flag 3 .x"); + assert_eq!((Packed.place(2, 3), Halves.place(0, 3)), ((3, Some(1)), (3, Some(0)))); + assert_eq!(f16_param_dwords(&outputs, &[(1, 0)]), (0x3, 0xF)); + // where the record and the export disagree + assert!(!shape(0, 0xF).disagrees() && !shape(0, 0x3).disagrees() && shape(0, 0x1).disagrees(), "flag 3: its packed dwords all written"); + assert!(!shape(1, 0xF).disagrees() && !shape(1, 0x3).disagrees() && shape(1, 0x7).disagrees(), "flag 1: one layout or the other"); + assert_eq!(layout(1, 0x7).1, Halves, "flag 1 written as neither: one half a dword"); + } } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index da1cfc1f67..ff73ea931c 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -13058,3 +13058,31 @@ fn geometry_padding_before_gs_start_keeps_its_entry() { assert!(t.hlsl.contains(&format!("if (pc == {s}u)")), "split {split}: {}", t.hlsl); } } + +/// (PR 2513's thread, CharlyRien 2026-11-29) A float16 input of a PS has the mode its reads give +/// it: interpolated where `v_interp_p1 / p2` read it, flat where `v_interp_mov` does - not flat +/// for being float16. Integer inputs stay flat. +#[test] +fn a_float16_ps_input_takes_the_mode_its_reads_give_it() { + use super::PsInterface; + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32| crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask: 0xF, rw_mask: 0xF, stream: 0 }; + let ps = PsInterface { + inputs: vec![el("SV_Position", 0, 1, 3, 0), el("TEXCOORD", 0, 0, 6, 1), el("TEXCOORD", 1, 0, 6, 2), el("TEXCOORD", 2, 0, 1, 3)], + outputs: vec![el("SV_Target", 0, 64, 3, 0)], + input_ena: 0x302, + attrs: None, + }; + let code = prog(&[ + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 2), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 0), ("ATTR", 2), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 2), ("ATTRCHAN", 0)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0x7), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 6), ("DONE", 1), ("VM", 1)], None), + ]); + let hlsl = translate(&code, &Options { mode: Mode::Pixel(ps), wave64: true, ..Default::default() }).unwrap().hlsl; + let decl = |sem: &str| hlsl.lines().find(|l| l.contains(&format!(": {sem};"))).unwrap_or_else(|| panic!("{sem}\n{hlsl}")).to_string(); + assert!(!decl("TEXCOORD0").contains("nointerpolation"), "read by p1 / p2: interpolated\n{hlsl}"); + assert!(decl("TEXCOORD1").contains("nointerpolation"), "read by mov: flat\n{hlsl}"); + assert!(decl("TEXCOORD2").contains("nointerpolation"), "an integer: flat\n{hlsl}"); +} From 44b3dcd0e170f9a3921cc1e6eaa3a3218ba84aaf Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:16:17 +0100 Subject: [PATCH 4/5] Recompiler: a float16 half no PS input declares reads 0 ps_f16_slot fell back to the register's first element when no element declared the component of a (dword, half): the PS then read another element's component instead of the 0 its doc comment promises. In a retail title's shader pack 6 pixel shaders (character shaders) read such a half: channel 3 of a packed attribute whose register declares .xy only. Now the slot is None and both translators read 0. Test: f16_packed_attributes checks two such halves. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/mod.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 888baf6c84..8c15c7f8cb 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -819,7 +819,8 @@ pub fn ps_f16_slot(ps: &PsInterface, regs: &[(u32, usize)], chan: usize, high: b return None; } let all = ranked(&ps.inputs, false); - let slot = all.iter().position(|e| e.register == r && e.mask >> comp & 1 == 1).or_else(|| all.iter().position(|e| e.register == r))?; + // a half no element of the register declares reads 0 (None), not another element's component + let slot = all.iter().position(|e| e.register == r && e.mask >> comp & 1 == 1)?; Some((slot, comp)) } @@ -2364,6 +2365,9 @@ mod attribute_tests { // two elements in the first register; a half past the last one's components assert_eq!([at(4, 0, true), at(4, 1, true), at(4, 2, false)], ["TEXCOORD7.1", "TEXCOORD8.3", "TEXCOORD9.0"]); assert_eq!([at(5, 0, false), at(5, 2, false)], ["TEXCOORD14.0", ""]); + // a half the register's elements do not declare (TEXCOORD1 is .xyz, TEXCOORD14 .x) reads + // nothing, not the element's first component + assert_eq!([at(2, 1, true), at(5, 0, true)], ["", ""]); // the attributes after a pair read their own registers assert_eq!([1, 3].map(|a| all[ps_attribute_slot(&ps, a, 0).unwrap()].semantic()), ["TEXCOORD0", "TEXCOORD3"]); assert_eq!((0..10).map(|j| ps_slot_attribute(&ps, j)).collect::>(), [0, 0, 1, 2, 2, 3, 4, 4, 4, 5].map(Some)); From 7de960d31e2c0b101db6d675d124c5c385e19196 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:51:01 +0100 Subject: [PATCH 5/5] Recompiler: log the float16 layouts only the other stage can confirm Review on PR 3584 (Foniass): the VS picks a flag-1 param's layout from its export, the PS from its instruction, and nothing showed when they could disagree; F16Param::disagrees was only used by tests. Each stage now logs once per shape what is right only if the other made the same choice: an export that disagrees with its record, a flag-1 param exported packed (a PS reading it with v_interp_mov_f32 gets the low half), and a v_interp_p2_f16 read of a flag-1 attribute beyond the low half of dword 0 (right only if its VS packed it). The layouts chosen do not change. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/lower_gfx.rs | 8 +++- crates/xcl/src/gpu/recomp/emit.rs | 13 ++++-- crates/xcl/src/gpu/recomp/mod.rs | 60 +++++++++++++++++++++++++++- 3 files changed, 75 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 4024936d98..d17af78e3e 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -415,7 +415,13 @@ impl Lw { // a float16-packed attribute: the PC input is the component itself (SRC0 bit 8: the // high half of the dword); a half nothing declares reads 0 let place = match ps_attribute_f16(&ps, attr as usize).filter(|_| name.ends_with("_f16")) { - Some(regs) => ps_f16_slot(&ps, ®s, chan as usize, d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1), + Some(regs) => { + let high = d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1; + if name == "v_interp_p2_f16" { + crate::gpu::recomp::note_ps_f16_read(&ps, attr as usize, chan as usize, high); + } + ps_f16_slot(&ps, ®s, chan as usize, high) + } None => match ps_attribute_slot(&ps, attr as usize, chan as usize) { Some(slot) => Some((slot, chan as usize)), None => return err(d, "attribute outside ISG1"), diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index fb6a3b337b..dfe9e0bf0c 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2512,10 +2512,15 @@ impl Em { // is the component itself, interpolated as a float – SRC0 bit 8 picks the high half let high = d.enc.name != "ENC_VINTRP" && rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) >> 8 & 1 == 1; let src = match ps_attribute_f16(ps, attr as usize).filter(|_| name.ends_with("_f16")) { - Some(regs) => match ps_f16_slot(ps, ®s, chan as usize, high) { - Some((slot, comp)) => format!("xi.a{slot}[{comp}]"), - None => "0.0f".to_string(), - }, + Some(regs) => { + if name == "v_interp_p2_f16" { + super::note_ps_f16_read(ps, attr as usize, chan as usize, high); + } + match ps_f16_slot(ps, ®s, chan as usize, high) { + Some((slot, comp)) => format!("xi.a{slot}[{comp}]"), + None => "0.0f".to_string(), + } + } None => { let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { return Err("attribute outside ISG1"); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 8c15c7f8cb..3d69553bbd 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -754,6 +754,39 @@ impl F16Param { self.en != self.packed && self.en != self.plain } } + + /// A flag-1 record whose export takes it packed (`layout`): right only for a PS that reads it + /// with `v_interp_p2_f16`; one that takes it flat (`v_interp_mov_f32`) gets the low half. + pub fn flag1_packed(self) -> bool { + !self.flag3 && self.layout() == ParamLayout::Packed + } +} + +/// Logs once per kind and shape what the float16 layouts cannot settle alone (PR 3584 review): +/// a record and its export that disagree, a flag-1 param exported packed, and a PS that reads a +/// flag-1 attribute packed (`ps_f16_read_assumes_packed`). Each is right only if the other stage +/// made the same choice; the translation goes on with the layout it picked. +fn note_f16_shape(kind: &'static str, key: (usize, u32, u32, u32), what: impl FnOnce() -> String) { + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + if SEEN.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(BTreeSet::new).insert((kind, key)) { + crate::xlog_warn!("Recompiler: float16 {kind}: {}", what()); + } +} + +/// A PS read of float16 attribute `attr` by `v_interp_p2_f16` at channel `chan` / half `high` +/// that assumes the VS packed a flag-1 record (two halves a dword: `ps_f16_slot`) - beyond the +/// low half of dword 0, where packed and one-half-a-dword part. +pub fn ps_f16_read_assumes_packed(ps: &PsInterface, attr: usize, chan: usize, high: bool) -> bool { + ps.attrs.as_ref().and_then(|t| t.get(attr)).is_some_and(|a| a.f16 && a.pair.is_none()) && (chan > 0 || high) +} + +/// `ps_f16_read_assumes_packed`, logged once per attribute, channel and half. +pub fn note_ps_f16_read(ps: &PsInterface, attr: usize, chan: usize, high: bool) { + if ps_f16_read_assumes_packed(ps, attr, chan, high) { + note_f16_shape("PS read", (attr, chan as u32, high as u32, 0), || { + format!("v_interp_p2_f16 reads flag-1 attribute {attr} at channel {chan}{} as packed halves: right only if its VS exports it packed", if high { " (high half)" } else { "" }) + }); + } } /// The elements `exp param N` writes (places in `ranked(outputs, true)`, each with the first @@ -771,7 +804,17 @@ pub fn out_param_layout(outputs: &[SigElement], params: Option<&[OutParam]>, n: if !f16 { return (at(®s), ParamLayout::Dwords); } - match f16_param_shape(outputs, params, n, ®s, en).layout() { + let shape = f16_param_shape(outputs, params, n, ®s, en); + if shape.disagrees() { + note_f16_shape("export", (n, shape.en, shape.packed, shape.plain | (shape.flag3 as u32) << 8), || { + format!("param {n} ({} record) exported over dwords {:#x}, neither its packed dwords {:#x} nor one a component {:#x}: laid out {:?}", if shape.flag3 { "flag-3" } else { "flag-1" }, shape.en, shape.packed, shape.plain, shape.layout()) + }); + } else if shape.flag1_packed() { + note_f16_shape("export", (n, shape.en, shape.packed, shape.plain | 1 << 9), || { + format!("flag-1 param {n} exported packed (dwords {:#x}): a PS that reads it with v_interp_mov_f32 gets only the low half", shape.en) + }); + } + match shape.layout() { ParamLayout::Packed => (at(®s), ParamLayout::Packed), // (one half a dword: the first register's components; a flag-1 record names no second) l => (at(®s[..1]).into_iter().map(|(j, _)| (j, 0)).collect(), l), @@ -2473,5 +2516,20 @@ mod attribute_tests { assert!(!shape(0, 0xF).disagrees() && !shape(0, 0x3).disagrees() && shape(0, 0x1).disagrees(), "flag 3: its packed dwords all written"); assert!(!shape(1, 0xF).disagrees() && !shape(1, 0x3).disagrees() && shape(1, 0x7).disagrees(), "flag 1: one layout or the other"); assert_eq!(layout(1, 0x7).1, Halves, "flag 1 written as neither: one half a dword"); + // the shapes only right if the other stage chose the same layout (PR 3584 review) + assert!(shape(1, 0x3).flag1_packed() && shape(2, 0x1).flag1_packed(), "flag 1 exported packed: a flat read gets the low half"); + assert!(!shape(1, 0xF).flag1_packed() && !shape(3, 0x1).flag1_packed() && !shape(0, 0x3).flag1_packed(), "one half a dword, a .x, a flag-3 record"); + } + + /// A PS read of a flag-1 float16 attribute by `v_interp_p2_f16` beyond the low half of dword + /// 0 assumes its VS packed it; a flag-3 (paired) attribute or a plain one does not. + #[test] + fn a_ps_read_of_a_flag1_attribute_beyond_its_first_half_assumes_packing() { + let attr = |f16: bool, pair: Option| PsAttr { kind: 6, register: 1, mask: 0xF, flat: false, f16, pair }; + let ps = PsInterface { inputs: Vec::new(), outputs: Vec::new(), input_ena: 0, attrs: Some(vec![attr(true, None), attr(true, Some(2)), attr(false, None)]) }; + assert!(!ps_f16_read_assumes_packed(&ps, 0, 0, false), "dword 0, low half: the same either way"); + assert!(ps_f16_read_assumes_packed(&ps, 0, 0, true) && ps_f16_read_assumes_packed(&ps, 0, 1, false), "flag 1 beyond the first half"); + assert!(!ps_f16_read_assumes_packed(&ps, 1, 1, true), "flag 3: packed by its record"); + assert!(!ps_f16_read_assumes_packed(&ps, 2, 1, false) && !ps_f16_read_assumes_packed(&ps, 3, 1, false), "not float16, no such attribute"); } }