From d7ba3cd7c709623553a55d8b4082a7a86b8da5d0 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:27:24 +0100 Subject: [PATCH 1/2] 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. #1975 / #1976 parsed the same records with a fixed layout - the second 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 7492f54b9c..16df320c1b 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -153,6 +153,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 a337d470bc..6b0a3e0848 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::{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 { + let Some((slot, comp)) = place else { return lw.c(0) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, _) = g.ps_in[slot]; - let x = g.io.load_input(&mut lw.s, sig, 0, chan as u8); + let x = g.io.load_input(&mut lw.s, sig, 0, comp as u8); let i32 = lw.s.m.i32(); lw.s.m.bitcast(x, i32) }; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index c5e389bcb2..ba133d24b2 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}; @@ -2436,10 +2436,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" => { @@ -5246,7 +5257,9 @@ impl Em { // 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 c2548d56e5..5b89d86156 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -365,6 +365,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 @@ -372,6 +376,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())); @@ -382,10 +391,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)) } @@ -412,6 +422,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 { @@ -432,7 +483,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), } } @@ -1662,6 +1716,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 3bc875816e45550c3aaa6d44da3b3922b82d18e3 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:32:03 +0100 Subject: [PATCH 2/2] 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. #1975 unpacked the same params with the second register always in 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 | 40 ++++++- 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/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 | 105 +++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 4 +- 10 files changed, 259 insertions(+), 41 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 16df320c1b..c31d7bfea3 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -157,12 +157,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; @@ -172,7 +174,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"; @@ -209,6 +236,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]; @@ -231,7 +262,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 6ef85ad800..d78a62bb16 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -786,7 +786,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, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, 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 5034d31903..926b40534d 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -65,6 +65,8 @@ pub struct MeshCtx { pub vtx: Value, pub prm: 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 6b0a3e0848..e8fb2ae53b 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::{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 cc7cd0116a..cff50b1a1b 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2535,13 +2535,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/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index ba133d24b2..25355fb46b 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}; @@ -2325,18 +2325,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};")); } @@ -2387,15 +2395,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!("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!("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 1ae5c75a4e..d75fccb679 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -397,7 +397,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 5b89d86156..b2fe40d522 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -117,7 +117,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 { @@ -162,6 +162,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 @@ -228,6 +230,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, } } } @@ -371,6 +374,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 @@ -404,8 +416,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 { @@ -414,10 +429,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) } @@ -441,6 +457,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> { @@ -494,7 +532,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(), } } @@ -543,6 +581,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, @@ -1776,6 +1815,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] @@ -1813,7 +1873,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 0b018edc36..41396b6a12 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3563,7 +3563,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) }; @@ -3641,6 +3641,100 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// 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}; @@ -3659,6 +3753,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}"); @@ -3700,7 +3795,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 @@ -3757,7 +3852,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 @@ -4013,7 +4108,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 @@ -6883,7 +6978,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 91085d3933..12c75c79d5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5739,7 +5739,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, }), @@ -8356,7 +8356,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], };