From 0ed6179327294708a5aca6522722152ccacfad77 Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:06:25 +0000 Subject: [PATCH] Implement Waves 1-5 across shader, GPU, formats, HLE, and loader Waves 1-4: - Shader translator: merged Es/Ls/Gs/Hs stages, RootType::Constants 64-bit VA pairs (CONST_VIEW_SPACE=2), 64-bit image_atomic_*, Wave64-on-Wave32 LDS adaptation, transitive phi liveness, host-wave lane ops, NGG geometry mesh path, VSH3 shader cache - GPU runtime: waitable-timer frame pacing, host ID3D12QueryHeap & timestamp frequency, IDXGIOutput6 HDR + SetColorSpace1 + Blitter PSO + clamped CopyTextureRegion fallback, physical_epoch-gated texture hashing, coalesced watch guards, Shadow::copy_back scratch, indirect execution & descriptor heap scaling - Formats: GFX10.3 HTILE/DCC/CMASK/FMASK metadata planes and layout support - HLE: SAPI 5 speech synthesis, Freeverb DSP reverb, WinRT WGI 4-motor rumble, DirectStorage zero-staging streaming & 16 MiB scratch, APU Opus tests, display HDR mode resolution Wave 5: - victory-shader: ordered OLT|OGT for v_cmp_lg (#706), denormal-as-zero legacy_mul (#682), 16-bit VALU omod & v_cvt_{u16,i16}_f16 modifiers/saturation (#668), v_interp_p1ll_f16 high-half preservation (#683), LOD-clamped image_sample_*_cl & image_gather4_l (#694), root-view structured buffer raw fallback (#709), conversion-free tbuffer_store_format_* (#707), cfg(windows) gate on constant_color (#685) - victory-gpu & formats: upload CPU-written textures before CopyResource/CopyTextureRegion (#671), clear vertex-buffer slots on null views (#681), command-list 64-bit memory wait sync (#700), dynamic descriptor slot reclamation from executed lists (#688), private MICRO doc-link fix (#696), clippy::field_reassign_with_default fix (#692) - victory-hle, loader, formats, apps: 0x-prefixed TitleId & self-closing XML handling (#715), xg null-out/bounds/checked-span validation (#674), Media Foundation local-file URL policy on MFCreateFile/MFBeginCreateFile/MFCreateSourceReaderFromURL/MFCreateSinkWriterFromURL (#663), checked PE patch offsets (#670), zero-alloc streaming bcpack Workspace (#703), in-repo capture/dump directory guards (#679/#664) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- apps/victory/src/main.rs | 3 +- apps/victory/src/translate.rs | 32 +- crates/victory-core/src/config.rs | 10 + crates/victory-formats/src/bcpack.rs | 605 +++-- crates/victory-formats/src/texture.rs | 503 +++- crates/victory-gpu/src/capture.rs | 65 +- crates/victory-gpu/src/descriptor/host.rs | 379 ++- crates/victory-gpu/src/draw.rs | 423 +++- crates/victory-gpu/src/frame.rs | 394 +-- crates/victory-gpu/src/host.rs | 957 +++++++- crates/victory-gpu/src/indirect.rs | 38 +- crates/victory-gpu/src/lib.rs | 22 +- crates/victory-gpu/src/list.rs | 279 ++- crates/victory-gpu/src/pipeline/host.rs | 509 +++- crates/victory-gpu/src/query.rs | 120 +- crates/victory-gpu/src/queue.rs | 12 +- crates/victory-gpu/src/resource.rs | 101 +- crates/victory-gpu/src/shader_cache.rs | 78 +- crates/victory-gpu/src/shadow.rs | 96 +- crates/victory-gpu/src/texture.rs | 118 +- crates/victory-gpu/src/watch.rs | 80 +- crates/victory-hle/src/host.rs | 1 + crates/victory-hle/src/modules/apu.rs | 125 + crates/victory-hle/src/modules/audio.rs | 37 +- crates/victory-hle/src/modules/display.rs | 100 +- crates/victory-hle/src/modules/dsp.rs | 388 ++- crates/victory-hle/src/modules/dstorage.rs | 153 +- crates/victory-hle/src/modules/gameinput.rs | 420 +++- crates/victory-hle/src/modules/kernel.rs | 55 +- crates/victory-hle/src/modules/media.rs | 184 +- crates/victory-hle/src/modules/mod.rs | 2 + crates/victory-hle/src/modules/speech.rs | 719 +++++- crates/victory-hle/src/modules/xg.rs | 209 +- crates/victory-hle/src/modules/xmem.rs | 202 +- crates/victory-hle/src/modules/xuser.rs | 14 +- crates/victory-hle/src/runtime.rs | 41 +- crates/victory-loader/src/prepare.rs | 104 +- crates/victory-shader/src/emit/bitcode.rs | 11 + crates/victory-shader/src/emit/diff_tests.rs | 52 +- crates/victory-shader/src/emit/host.rs | 51 +- crates/victory-shader/src/emit/lower.rs | 2321 ++++++++++++++++-- crates/victory-shader/src/emit/mod.rs | 90 +- crates/victory-shader/src/emit/shader.rs | 270 +- crates/victory-shader/src/emit/valu_tests.rs | 7 + crates/victory-shader/src/emit/wave.rs | 49 +- crates/victory-shader/src/io.rs | 4 +- crates/victory-shader/src/native.rs | 14 +- crates/victory-shader/src/resource.rs | 1067 ++++++-- 48 files changed, 9965 insertions(+), 1549 deletions(-) diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 31392ffb08..4cf7c314f3 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -180,6 +180,7 @@ fn show_config() -> Result<()> { ); println!("game_dir : {}", status(&cfg.game_dir)); println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); for t in &cfg.test_titles { println!("test_title : {}", status(&Some(t.clone()))); } @@ -187,7 +188,7 @@ fn show_config() -> Result<()> { .game_dir .iter() .chain(&cfg.test_titles) - .chain([&cfg.cache_dir]) + .chain([&cfg.cache_dir, &cfg.data_dir]) { if let Err(e) = victory_core::ensure_outside_repo(p) { println!("POLICY VIOLATION: {e}"); diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index dcaf924bd5..48bdb1e72a 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -17,6 +17,21 @@ use victory_shader::{io, resource}; use crate::shader::{MAX_FILE, Source, sources}; +/// Resolved `VICTORY_EMIT_DUMP` folder, refused if it points inside a VIctory +/// source tree (enforcing `docs/asset-policy.md`). +fn emit_dump_dir() -> Option<&'static Path> { + static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); + DIR.get_or_init(|| { + let dir = PathBuf::from(std::env::var_os("VICTORY_EMIT_DUMP")?); + if let Err(e) = victory_core::ensure_outside_repo(&dir) { + eprintln!("refusing VICTORY_EMIT_DUMP: {e}"); + return None; + } + Some(dir) + }) + .as_deref() +} + #[derive(Default)] struct Tally { containers: usize, @@ -422,14 +437,14 @@ fn check( } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list - && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") + && let Some(dir) = emit_dump_dir() { let name: String = label() .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) .collect(); let _ = std::fs::write( - format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]), + dir.join(format!("{}.dxil", &name[name.len().saturating_sub(100)..])), &shader.dxil, ); } @@ -466,22 +481,25 @@ fn check( .find(|l| l.contains("error")) .unwrap_or(text.lines().next().unwrap_or("")) .to_owned(); - if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") { + if let Some(dir) = emit_dump_dir() { let n = t .failed .get(&format!("validator: {first}")) .map_or(0, |f| f.0); if n < 3 { - let name = format!( - "{dir}/{}_{n}", + let stem = format!( + "{}_{n}", first .chars() .filter(char::is_ascii_alphanumeric) .take(40) .collect::() ); - let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil); - let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label())); + let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &shader.dxil); + let _ = std::fs::write( + dir.join(format!("{stem}.txt")), + format!("{}\n{text}", label()), + ); } } t.fail(format!("validator: {first}"), label); diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 596aa430ae..9e55eb87cc 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -181,4 +181,14 @@ mod tests { }; assert!(cfg.cache_subdir("x").is_err()); } + + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } } diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index cb4ea5383a..263fa86545 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -212,7 +212,14 @@ impl Tables { bits: [r.u8(), r.u8()], ..Default::default() }; - for v in ix.ix.as_flattened_mut() { + // Bytes 52..54 hold a second width word before the 16 set-0 + // indices at bytes 54..86; bytes 86..116 hold 15 set-1 i16s + // (all zero in shipped tables, where `bits[1]` is 0). + let _extra_widths = r.u16(); + for v in &mut ix.ix[0] { + *v = r.u16() as i16; + } + for v in &mut ix.ix[1][..15] { *v = r.u16() as i16; } (ep, ix) @@ -238,10 +245,71 @@ impl Tables { } } +/// Reusable scratch history for [`decode_with`], avoiding per-call heap +/// allocations across repeated BCPack decodes. +#[derive(Default)] +pub struct Workspace { + plain: Vec, + bc6: Vec<(Bc6Ep, Bc6Ix)>, + bc7: Vec<(Bc7Ep, Bc7Ix)>, +} + +impl Workspace { + /// Creates an empty workspace; format history ring buffers are allocated + /// lazily on first use and reused across subsequent calls. + pub const fn new() -> Self { + Self { + plain: Vec::new(), + bc6: Vec::new(), + bc7: Vec::new(), + } + } + + fn plain_history(&mut self) -> &mut [Plain] { + if self.plain.len() < HISTORY { + self.plain.resize(HISTORY, Plain::default()); + } + &mut self.plain[..HISTORY] + } + + fn bc6_history(&mut self) -> &mut [(Bc6Ep, Bc6Ix)] { + if self.bc6.len() < HISTORY { + self.bc6.resize(HISTORY, (Bc6Ep::default(), Bc6Ix::default())); + } + &mut self.bc6[..HISTORY] + } + + fn bc7_history(&mut self) -> &mut [(Bc7Ep, Bc7Ix)] { + if self.bc7.len() < HISTORY { + self.bc7.resize(HISTORY, (Bc7Ep::default(), Bc7Ix::default())); + } + &mut self.bc7[..HISTORY] + } +} + /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives /// the block count. The stream carries no size: bytes after the last one the /// lanes need are ignored, a stream that runs out is an error. +/// +/// Reuses a thread-local [`Workspace`] and streams block records on the stack, +/// avoiding per-call heap allocations. pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { + thread_local! { + static WORKSPACE: std::cell::RefCell = const { + std::cell::RefCell::new(Workspace::new()) + }; + } + WORKSPACE.with(|ws| decode_with(bc, src, dst, tables, &mut ws.borrow_mut())) +} + +/// Unpacks `src` into `dst` using the caller-provided reusable [`Workspace`]. +pub fn decode_with( + bc: u8, + src: &[u8], + dst: &mut [u8], + tables: &Tables, + ws: &mut Workspace, +) -> Result<(), Error> { let block = match bc { 1 | 4 => 8, 3 | 5 | 6 | 7 => 16, @@ -259,20 +327,108 @@ pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), }; - let stride = widths.len() * per; - let mut records = vec![0u8; blocks * stride]; let mut next = src.iter().copied(); - lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; - let records = records.chunks_exact(stride); - let out = dst.chunks_exact_mut(block); let t = tables; match bc { - 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), - 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), - 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), - 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), - 6 => bc6(records, out, &t.bc6), - _ => bc7(records, out, t), + 1 => { + let history = ws.plain_history(); + let zero = Plain::default(); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + plain_block( + i, + s, + &mut dst[i * block..(i + 1) * block], + history, + &t.bc1, + &zero, + &BC1, + |s| bc1_residual(t, s), + bc1_pack, + ); + Ok(()) + }) + } + 3 => { + let history = ws.plain_history(); + let zero = Plain::default(); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + plain_block( + i, + s, + &mut dst[i * block..(i + 1) * block], + history, + &t.bc3, + &zero, + &BC3, + |s| bc3_residual(t, s), + bc3_pack, + ); + Ok(()) + }) + } + 4 => { + let history = ws.plain_history(); + let zero = Plain::default(); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + plain_block( + i, + s, + &mut dst[i * block..(i + 1) * block], + history, + &t.bc4, + &zero, + &BC4, + |s| bc4_residual(t, s), + bc4_pack, + ); + Ok(()) + }) + } + 5 => { + let history = ws.plain_history(); + let zero = Plain::default(); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + plain_block( + i, + s, + &mut dst[i * block..(i + 1) * block], + history, + &t.bc5, + &zero, + &BC5, + |s| bc5_residual(t, s), + bc5_pack, + ); + Ok(()) + }) + } + 6 => { + let history = ws.bc6_history(); + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + bc6_block( + i, + s, + &mut dst[i * block..(i + 1) * block], + history, + &t.bc6, + &zero, + ) + }) + } + _ => { + let history = ws.bc7_history(); + let zero = (Bc7Ep::default(), Bc7Ix::default()); + lanes_stream(tables, widths, per, blocks, |_| next.next(), |i, s| { + bc7_block(i, s, &mut dst[i * block..(i + 1) * block], history, t, &zero) + }) + } } } @@ -385,20 +541,21 @@ impl Lane { } } -/// Decodes `per` symbols per block on every lane into `records` (one record -/// of `widths.len() * per` symbols per block), taking input from `fetch` -/// (given the lane that takes the byte) in the order of the schedule: each -/// round the lanes step in order and take at most 8 bytes between them. +/// Decodes `per` symbols per block on every lane and streams each completed +/// block record (`widths.len() * per <= 32` bytes) to `emit` on the stack, +/// taking input from `fetch` (given the lane that takes the byte) in the +/// order of the schedule: each round the lanes step in order and take at most +/// 8 bytes between them. // shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s // on one core); if texture streaming needs more, run the schedule only to // split the input per lane and decode the lanes apart. -fn lanes( +fn lanes_stream( t: &Tables, widths: &[u8], per: usize, blocks: usize, mut fetch: impl FnMut(usize) -> Option, - records: &mut [u8], + mut emit: impl FnMut(usize, &[u8]) -> Result<(), Error>, ) -> Result<(), Error> { let mut lanes = [Lane::default(); 16]; let lanes = &mut lanes[..widths.len()]; @@ -407,10 +564,12 @@ fn lanes( lane.need = true; } let stride = widths.len() * per; + let mut record = [0u8; 32]; let full = (1u32 << widths.len()) - 1; let (mut pos, mut done, mut idle) = (0, 0u32, 0); while pos < blocks * per { let (mut taken, mut moved) = (0, false); + let sub = pos % per; for (j, lane) in lanes.iter_mut().enumerate() { let bit = 1 << j; let before = taken; @@ -429,12 +588,15 @@ fn lanes( if !lane.stalled && let Some(sym) = lane.out.take() { - records[pos / per * stride + j * per + pos % per] = sym; + record[j * per + sub] = sym; done |= bit; moved = true; } } if done == full { + if sub + 1 == per { + emit(pos / per, &record[..stride])?; + } pos += 1; done = 0; moved = true; @@ -448,6 +610,22 @@ fn lanes( Ok(()) } +#[cfg(test)] +fn lanes( + t: &Tables, + widths: &[u8], + per: usize, + blocks: usize, + fetch: impl FnMut(usize) -> Option, + records: &mut [u8], +) -> Result<(), Error> { + let stride = widths.len() * per; + lanes_stream(t, widths, per, blocks, fetch, |i, rec| { + records[i * stride..(i + 1) * stride].copy_from_slice(rec); + Ok(()) + }) +} + // Blocks. /// The record's endpoint and index references. @@ -505,31 +683,30 @@ const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); -fn plain<'a>( - records: impl Iterator, - out: impl Iterator, +#[allow(clippy::too_many_arguments)] +fn plain_block( + i: usize, + s: &[u8], + block: &mut [u8], + history: &mut [Plain], dictionary: &[Plain], + zero: &Plain, w: &Widths, residual: impl Fn(&[u8]) -> Plain, pack: fn(&Plain, &mut [u8]), -) -> Result<(), Error> { - let mut history = vec![Plain::default(); HISTORY]; - let zero = Plain::default(); - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, w.paired); - let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; - let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; - let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; - } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); - } - history[i % HISTORY] = v; - pack(&v, block); +) { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, history, dictionary, zero).ep; + let ix_ref = &pick(i, ix_ref, history, dictionary, zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; } - Ok(()) + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); } /// 2-bit index residuals: one symbol per 2x2 quad. @@ -736,93 +913,91 @@ fn bc7_precision(ctrl: u16) -> [u8; 4] { p } -fn bc7<'a>( - records: impl Iterator, - out: impl Iterator, +fn bc7_block( + i: usize, + s: &[u8], + block: &mut [u8], + history: &mut [(Bc7Ep, Bc7Ix)], t: &Tables, + zero: &(Bc7Ep, Bc7Ix), ) -> Result<(), Error> { - let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; - let zero = (Bc7Ep::default(), Bc7Ix::default()); - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, true); - let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; - if ctrl == 0 { - return Err(Error("unused BC7 control code")); + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, history, &t.bc7, zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + // Rows the reference lacks build on its first row. + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; } - let mode = usize::from(ctrl & 7); - let subsets = usize::from((ctrl & 0xff) >> 6); - let prec = bc7_precision(ctrl); - let three = subsets == 3; - let or0 = |v: u8| if three { 0 } else { v }; - let if3 = |v: u8| if three { v } else { 0 }; - let stored = [ - [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], - [ - s[12], - s[13], - s[14], - s[15], - s[16], - s[17], - or0(s[18]), - or0(s[19]), - ], - [ - s[20], - s[21], - if3(s[10]), - if3(s[11]), - if3(s[18]), - if3(s[19]), - 0, - 0, - ], - ]; - let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; - let mut ep = Bc7Ep { - ctrl, - ..Default::default() - }; - // Rows the reference lacks build on its first row. - let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); - let columns = if prec[3] > 0 { 8 } else { 6 }; - for c in 0..columns { - let p = prec[c / 2]; - if p == 0 { - continue; - } - let mask = 0xffffu16 << (16 - p); - for (row, st) in stored.iter().enumerate().take(subsets) { - let v = st[c]; - let residual = - (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); - let base = r.rows[if row < common { row } else { 0 }][c] & mask; - ep.rows[row][c] = base.wrapping_add(residual); - } + let mask = 0xffffu16 << (16 - p); + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); } - let bits = BC7_INDEX[mode]; - let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; - let mut ix = Bc7Ix { - bits, - ..Default::default() - }; - for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { - if bits[set] == 0 { - continue; - } - for (k, o) in offsets.into_iter().enumerate() { - for (b, &byte) in s[o..o + 2].iter().enumerate() { - let pair = nibbles(byte, k < 3); - for (h, &v) in pair.iter().enumerate() { - let p = 4 * k + 2 * b + h; - ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); - } + } + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, history, &t.bc7, zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { + if bits[set] == 0 { + continue; + } + for (k, o) in offsets.into_iter().enumerate() { + for (b, &byte) in s[o..o + 2].iter().enumerate() { + let pair = nibbles(byte, k < 3); + for (h, &v) in pair.iter().enumerate() { + let p = 4 * k + 2 * b + h; + ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); } } } - history[i % HISTORY] = (ep, ix); - bc7_pack(&ep, &ix, prec, block); } + history[i % HISTORY] = (ep, ix); + bc7_pack(&ep, &ix, prec, block); Ok(()) } @@ -1036,107 +1211,100 @@ fn bc6_index_bits(mode: u8) -> u8 { } } -fn bc6<'a>( - records: impl Iterator, - out: impl Iterator, +fn bc6_block( + i: usize, + s: &[u8], + block: &mut [u8], + history: &mut [(Bc6Ep, Bc6Ix)], dictionary: &[(Bc6Ep, Bc6Ix)], + zero: &(Bc6Ep, Bc6Ix), ) -> Result<(), Error> { - let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; - let zero = ( - Bc6Ep::default(), - Bc6Ix { - mode: 11, - ..Default::default() - }, - ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); let wide = |a: u8, b: u8| { (0..8).fold(0u16, |acc, k| { acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) }) }; - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, true); - let mode = s[30].wrapping_add(1); - if !(1..=14).contains(&mode) { - return Err(Error("BC6H mode out of range")); - } - let two = mode < 11; - let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); - let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); - let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); - let (e2, e3) = if two { - ( - [s[16], s[18], s[20]].map(|v| z(v.into())), - [s[17], s[19], s[21]].map(|v| z(v.into())), - ) - } else { - (e0, e1) - }; - let r = &pick(i, ep_ref, &history, dictionary, &zero).0; - let mut ep = Bc6Ep::default(); - // Endpoint 0 at the base precision, the others per channel; the - // reference is cut by the mask after the sum. - let mask = |sh: u32| 0xffffu16 << sh; - for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { - *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); - } - for (k, res) in [e1, e2, e3] - .iter() - .enumerate() - .take(if two { 3 } else { 1 }) - { - for c in 0..3 { - ep.e[k + 1][c] = - r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); - } - } - if !two { - for c in 0..3 { - ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; - } - ep.e[3] = ep.e[1]; + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); + } + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) + } else { + (e0, e1) + }; + let r = &pick(i, ep_ref, history, dictionary, zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); + } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); } - let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; - let bits = bc6_index_bits(mode); - let mut ix = Bc6Ix { - mode, - ..Default::default() - }; - for k in 0..8 { - for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { - let p = 2 * k + h; - ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); - } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; } - history[i % HISTORY] = (ep, ix); - // Fields: the working value has its top bit flipped. - let field = |k: usize, c: usize| { - let sh = if k == 0 { shift[0] } else { shift[1 + c] }; - u64::from((ep.e[k][c] ^ 0x8000) >> sh) - }; - let mut w = Bits::default(); - let (code, n) = BC6_CODE[usize::from(mode)]; - w.put(code, n); - let part = s[31] & 31; - for run in BC6_LAYOUT[usize::from(mode)] { - if run.ch == 3 { - w.put(part.into(), 5); - } else { - w.put( - field(run.ep.into(), run.ch.into()) >> run.first, - run.len.into(), - ); - } + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, history, dictionary, zero).1; + let bits = bc6_index_bits(mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { + let p = 2 * k + h; + ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; - for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + } + history[i % HISTORY] = (ep, ix); + // Fields: the working value has its top bit flipped. + let field = |k: usize, c: usize| { + let sh = if k == 0 { shift[0] } else { shift[1 + c] }; + u64::from((ep.e[k][c] ^ 0x8000) >> sh) + }; + let mut w = Bits::default(); + let (code, n) = BC6_CODE[usize::from(mode)]; + w.put(code, n); + let part = s[31] & 31; + for run in BC6_LAYOUT[usize::from(mode)] { + if run.ch == 3 { + w.put(part.into(), 5); + } else { + w.put( + field(run.ep.into(), run.ch.into()) >> run.first, + run.len.into(), + ); } - block.copy_from_slice(&w.v.to_le_bytes()); } + let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + for (p, &v) in ix.ix.iter().enumerate() { + let short = p == 0 || p == usize::from(anchor); + let v = (v as u16).wrapping_add(1 << (bits - 1)); + w.put(v.into(), u32::from(bits) - u32::from(short)); + } + block.copy_from_slice(&w.v.to_le_bytes()); Ok(()) } @@ -1348,6 +1516,21 @@ mod tests { assert!(Tables::parse(&no_tiling).is_err()); } + #[test] + fn bc7_dictionary_indices_start_after_width_word() { + let t = Tables::builtin().unwrap(); + // Entry 0: anchor index 0 is 1 (not the width word 2 at byte 52). + assert_eq!(t.bc7[0].1.bits, [4, 0]); + assert_eq!(t.bc7[0].1.ix[0][0], 1); + assert_eq!(t.bc7[0].1.ix[0][1], 0); + // Entry 1: width 3, anchor 1, then 0s and -1s. + assert_eq!(t.bc7[1].1.bits, [3, 0]); + assert_eq!(t.bc7[1].1.ix[0][0], 1); + assert_eq!(t.bc7[1].1.ix[0][15], 1); + // Set 1 is empty in all shipped entries. + assert!(t.bc7.iter().all(|(_, ix)| ix.ix[1] == [0; 16])); + } + #[test] fn noise_never_panics() { let t = Tables::parse(&tables()).unwrap(); @@ -1395,4 +1578,14 @@ mod tests { } assert!(n > 0); } + + #[test] + fn workspace_decode_matches_and_reuses_across_calls() { + let t = Tables::parse(&tables()).unwrap(); + let mut ws = Workspace::new(); + let mut dst = [0u8; 8]; + assert!(decode_with(1, &[], &mut dst, &t, &mut ws).is_err()); + assert!(decode_with(2, &[0; 32], &mut dst, &t, &mut ws).is_err()); + assert!(decode_with(1, &[0; 32], &mut [0u8; 7], &t, &mut ws).is_err()); + } } diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 5d8926c8d5..88567ddfa1 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -13,7 +13,7 @@ //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile -//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on //! RDNA2). addrlib carries this notice: //! //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. @@ -594,9 +594,9 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }) + let plan = self.copy_plan(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch)?; + plan.detile(self, tiled, linear); + Ok(()) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -609,14 +609,13 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }) + let plan = self.copy_plan(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch)?; + plan.tile(self, tiled, linear); + Ok(()) } - /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). - #[allow(clippy::too_many_arguments)] - fn walk( + /// Validates dimensions and precomputes per-row contiguous byte runs. + fn copy_plan( &self, tiled_len: usize, mip: u32, @@ -624,8 +623,7 @@ impl Layout { linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut copy: impl FnMut(usize, usize, usize), - ) -> Result<(), Error> { + ) -> Result { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; let first = if self.desc.dimension == Dimension::Tex3d { @@ -671,23 +669,159 @@ impl Layout { } runs.push((first_tiled, first_linear, bytes - first_linear)); } - for z in 0..depth { - let (s, inner) = self.split(first + z); - let base = u64::from(s) * self.slice_size + m.offset; - for y in 0..m.height { - let linear_row = z as usize * depth_pitch + y as usize * row_pitch; - if linear { - let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + let uniform_run = runs + .first() + .map(|r| r.2) + .filter(|&len| runs.iter().all(|r| r.2 == len)); + Ok(CopyPlan { + mip: mip as usize, + first, + depth, + bytes, + row_pitch, + depth_pitch, + linear, + runs, + uniform_run, + }) + } +} + +struct CopyPlan { + mip: usize, + first: u32, + depth: u32, + bytes: usize, + row_pitch: usize, + depth_pitch: usize, + linear: bool, + runs: Vec<(usize, usize, usize)>, + uniform_run: Option, +} + +impl CopyPlan { + fn detile(&self, layout: &Layout, tiled: &[u8], linear: &mut [u8]) { + let m = &layout.mips[self.mip]; + let n = layout.desc.element_bytes as usize; + let tiled_pitch = m.pitch as usize * n; + for z in 0..self.depth { + let (s, inner) = layout.split(self.first + z); + let base = u64::from(s) * layout.slice_size + m.offset; + let linear_slice = z as usize * self.depth_pitch; + if self.linear { + if self.row_pitch == self.bytes && tiled_pitch == self.bytes { + let len = m.height as usize * self.bytes; + linear[linear_slice..][..len].copy_from_slice(&tiled[base as usize..][..len]); } else { - let tiled_row = (base + self.row(m, y, inner)) as usize; - for &(tiled, linear, len) in &runs { - copy(tiled_row + tiled, linear_row + linear, len); + for y in 0..m.height { + let tiled_row = base as usize + y as usize * tiled_pitch; + let linear_row = linear_slice + y as usize * self.row_pitch; + linear[linear_row..][..self.bytes] + .copy_from_slice(&tiled[tiled_row..][..self.bytes]); + } + } + continue; + } + match self.uniform_run { + Some(4) => self.detile_fixed::<4>(layout, m, base, inner, linear_slice, tiled, linear), + Some(8) => self.detile_fixed::<8>(layout, m, base, inner, linear_slice, tiled, linear), + Some(16) => self.detile_fixed::<16>(layout, m, base, inner, linear_slice, tiled, linear), + Some(32) => self.detile_fixed::<32>(layout, m, base, inner, linear_slice, tiled, linear), + Some(64) => self.detile_fixed::<64>(layout, m, base, inner, linear_slice, tiled, linear), + _ => { + for y in 0..m.height { + let tiled_row = (base + layout.row(m, y, inner)) as usize; + let linear_row = linear_slice + y as usize * self.row_pitch; + for &(t, l, len) in &self.runs { + linear[linear_row + l..][..len] + .copy_from_slice(&tiled[tiled_row + t..][..len]); + } } } } } - Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn detile_fixed( + &self, + layout: &Layout, + m: &Mip, + base: u64, + inner: u32, + linear_slice: usize, + tiled: &[u8], + linear: &mut [u8], + ) { + for y in 0..m.height { + let tiled_row = (base + layout.row(m, y, inner)) as usize; + let linear_row = linear_slice + y as usize * self.row_pitch; + for &(t, l, _) in &self.runs { + linear[linear_row + l..][..N].copy_from_slice(&tiled[tiled_row + t..][..N]); + } + } + } + + fn tile(&self, layout: &Layout, tiled: &mut [u8], linear: &[u8]) { + let m = &layout.mips[self.mip]; + let n = layout.desc.element_bytes as usize; + let tiled_pitch = m.pitch as usize * n; + for z in 0..self.depth { + let (s, inner) = layout.split(self.first + z); + let base = u64::from(s) * layout.slice_size + m.offset; + let linear_slice = z as usize * self.depth_pitch; + if self.linear { + if self.row_pitch == self.bytes && tiled_pitch == self.bytes { + let len = m.height as usize * self.bytes; + tiled[base as usize..][..len].copy_from_slice(&linear[linear_slice..][..len]); + } else { + for y in 0..m.height { + let tiled_row = base as usize + y as usize * tiled_pitch; + let linear_row = linear_slice + y as usize * self.row_pitch; + tiled[tiled_row..][..self.bytes] + .copy_from_slice(&linear[linear_row..][..self.bytes]); + } + } + continue; + } + match self.uniform_run { + Some(4) => self.tile_fixed::<4>(layout, m, base, inner, linear_slice, tiled, linear), + Some(8) => self.tile_fixed::<8>(layout, m, base, inner, linear_slice, tiled, linear), + Some(16) => self.tile_fixed::<16>(layout, m, base, inner, linear_slice, tiled, linear), + Some(32) => self.tile_fixed::<32>(layout, m, base, inner, linear_slice, tiled, linear), + Some(64) => self.tile_fixed::<64>(layout, m, base, inner, linear_slice, tiled, linear), + _ => { + for y in 0..m.height { + let tiled_row = (base + layout.row(m, y, inner)) as usize; + let linear_row = linear_slice + y as usize * self.row_pitch; + for &(t, l, len) in &self.runs { + tiled[tiled_row + t..][..len] + .copy_from_slice(&linear[linear_row + l..][..len]); + } + } + } + } + } + } + + #[allow(clippy::too_many_arguments)] + fn tile_fixed( + &self, + layout: &Layout, + m: &Mip, + base: u64, + inner: u32, + linear_slice: usize, + tiled: &mut [u8], + linear: &[u8], + ) { + for y in 0..m.height { + let tiled_row = (base + layout.row(m, y, inner)) as usize; + let linear_row = linear_slice + y as usize * self.row_pitch; + for &(t, l, _) in &self.runs { + tiled[tiled_row + t..][..N].copy_from_slice(&linear[linear_row + l..][..N]); + } + } } } @@ -752,23 +886,107 @@ pub struct Plane { pub layout: Layout, } -/// Every data plane of a texture (depth, then stencil), placed one after -/// the other. -/// -/// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC); -/// the console adds them to render targets and depth buffers unless the -/// description denies them, so those are smaller here than on the console. -/// The host GPU renders them, so nothing reads that memory; add the planes -/// if a title sizes a pool from console sizes and runs out. +/// Hardware compression/acceleration metadata plane kind on GFX10.3/RDNA2. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MetadataKind { + /// Color mask for MSAA fast-clear / compression (`XG_PLANE_USAGE_COLOR_MASK = 2`). + Cmask, + /// Fragment mask mapping MSAA sample indices (`XG_PLANE_USAGE_FRAGMENT_MASK = 3`). + Fmask, + /// Hierarchical depth/stencil tile metadata (`XG_PLANE_USAGE_HTILE = 4`). + Htile, + /// Delta color compression metadata (`XG_PLANE_USAGE_DELTA_COLOR_COMPRESSION = 9`). + Dcc, +} + +impl MetadataKind { + /// Xbox `XG_PLANE_USAGE` discriminant for `xg_xs.dll` (`LayoutOut`). + pub const fn xg_usage(self) -> u32 { + match self { + MetadataKind::Cmask => 2, + MetadataKind::Fmask => 3, + MetadataKind::Htile => 4, + MetadataKind::Dcc => 9, + } + } +} + +/// Optional metadata plane placed after a texture's data planes (HTILE, DCC, +/// CMASK, FMASK). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MetadataPlane { + pub kind: MetadataKind, + /// Byte offset from the start of the texture allocation. + pub offset: u64, + /// Total byte size across all slices. + pub size: u64, + /// Bytes per array slice. + pub slice_size: u64, + /// Hardware alignment requirement in bytes. + pub alignment: u64, + /// Logical metadata element width in bytes. + pub element_bytes: u32, +} + +/// Flags controlling which GFX10.3 compression metadata planes are generated +/// for render targets and depth/stencil buffers. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MetadataFlags { + pub render_target: bool, + pub depth_stencil: bool, + pub deny_compression: bool, +} + +impl MetadataFlags { + pub const NONE: Self = Self { + render_target: false, + depth_stencil: false, + deny_compression: false, + }; + + /// Decodes D3D12.X `D3D12_RESOURCE_FLAGS` into metadata plane eligibility. + /// Bit 0 (`0x1`) = `ALLOW_RENDER_TARGET`, bit 1 (`0x2`) = `ALLOW_DEPTH_STENCIL`, + /// bit 30 (`0x4000_0000`) = `D3D12XBOX_RESOURCE_FLAG_DENY_COMPRESSION_DATA`. + pub const fn from_d3d12_flags(flags: u32) -> Self { + const ALLOW_RT: u32 = 0x1; + const ALLOW_DS: u32 = 0x2; + const DENY_COMPRESSION: u32 = 0x4000_0000; + Self { + render_target: flags & ALLOW_RT != 0, + depth_stencil: flags & ALLOW_DS != 0, + deny_compression: flags & DENY_COMPRESSION != 0, + } + } +} + +/// Every data plane of a texture (color/depth, plus optional stencil) followed +/// by any GFX10.3 compression metadata planes (HTILE, DCC, CMASK, FMASK) when +/// requested via [`Texture::with_metadata`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Texture { pub planes: Vec, + pub metadata: Vec, pub size: u64, pub alignment: u64, } +/// GFX10.3 metadata surface alignment for a given swizzle mode: 64 KiB for +/// 64 KiB macro-tiled modes, 4 KiB for 4 KiB modes, 256 B otherwise. +fn metadata_alignment(swizzle: Swizzle) -> u64 { + match swizzle.0 { + 0 => 256, + 1..=3 => 256, + 4..=7 | 20..=22 => 4096, + _ => 65_536, + } +} + impl Texture { pub fn new(desc: &TextureDesc) -> Result { + Self::with_metadata(desc, MetadataFlags::NONE) + } + + pub fn with_metadata(desc: &TextureDesc, meta_flags: MetadataFlags) -> Result { let f = format(desc.format).ok_or(Error::Invalid)?; let depth3d = if desc.dimension == Dimension::Tex3d { desc.depth_or_array @@ -779,6 +997,7 @@ impl Texture { 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), n => n, }; + let samples = desc.samples.max(1); let plane = |bytes| Desc { dimension: desc.dimension, width: desc.width, @@ -787,7 +1006,7 @@ impl Texture { mips, element_bytes: bytes, block: f.block, - samples: desc.samples.max(1), + samples, swizzle: desc.swizzle, }; let mut planes = vec![Plane { @@ -804,11 +1023,126 @@ impl Texture { layout, }); } - let last = &planes[planes.len() - 1]; - let size = last.offset + last.layout.size; - let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1); + + let mut cursor = { + let last = &planes[planes.len() - 1]; + last.offset + last.layout.size + }; + let mut alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1); + let mut metadata = Vec::new(); + + // Hardware compression metadata applies to tiled 2D surfaces (not + // linear row-major or 1D/block-compressed surfaces) when not denied. + let tiled_2d = desc.dimension == Dimension::Tex2d + && desc.swizzle != Swizzle::LINEAR + && f.block == 1 + && !meta_flags.deny_compression; + if tiled_2d { + let slices = u64::from(desc.depth_or_array.max(1)); + let surf_align = metadata_alignment(desc.swizzle); + let push_meta = |metadata: &mut Vec, + cursor: &mut u64, + alignment: &mut u64, + kind: MetadataKind, + slice_size: u64, + align: u64, + element_bytes: u32| { + let offset = (*cursor).next_multiple_of(align); + let total = (slice_size * slices).next_multiple_of(align); + metadata.push(MetadataPlane { + kind, + offset, + size: total, + slice_size, + alignment: align, + element_bytes, + }); + *cursor = offset + total; + *alignment = (*alignment).max(align); + }; + + if meta_flags.depth_stencil { + // GFX10.3 HTILE: 1 u32 (4 bytes) per 8x8 pixel block, padded + // to 64x64 meta-block granularity and 2048/4096 B slice align. + let meta_w = u64::from(desc.width.div_ceil(8).next_multiple_of(8)); + let meta_h = u64::from(desc.height.div_ceil(8).next_multiple_of(8)); + let slice_align = if surf_align >= 65_536 { 4096 } else { 2048 }; + let slice_size = (meta_w * meta_h * 4).max(slice_align).next_multiple_of(slice_align); + push_meta( + &mut metadata, + &mut cursor, + &mut alignment, + MetadataKind::Htile, + slice_size, + surf_align, + 4, + ); + } else if meta_flags.render_target { + if samples > 1 { + // CMASK: 4 bits per 8x8 tile for MSAA fast-clear / compression. + let cm_w = u64::from(desc.width.div_ceil(8).next_multiple_of(16)); + let cm_h = u64::from(desc.height.div_ceil(8).next_multiple_of(16)); + let cm_slice = (cm_w * cm_h / 2).max(256).next_multiple_of(256); + push_meta( + &mut metadata, + &mut cursor, + &mut alignment, + MetadataKind::Cmask, + cm_slice, + surf_align, + 1, + ); + // FMASK: per-pixel sample-pointer map (1 B for 2x/4x, 4 B for 8x). + let fmask_bpe = if samples <= 4 { 1u32 } else { 4u32 }; + let fmask_slice = if let Ok(fl) = Layout::new(&Desc { + dimension: Dimension::Tex2d, + width: desc.width, + height: desc.height, + depth: 1, + mips: 1, + element_bytes: fmask_bpe, + block: 1, + samples: 1, + swizzle: desc.swizzle, + }) { + fl.slice_size + } else { + (u64::from(desc.width) * u64::from(desc.height) * u64::from(fmask_bpe)) + .next_multiple_of(surf_align) + }; + push_meta( + &mut metadata, + &mut cursor, + &mut alignment, + MetadataKind::Fmask, + fmask_slice, + surf_align, + fmask_bpe, + ); + } + // DCC: 1 metadata byte per 256 bytes of tiled color surface. + let color_slice = planes[0].layout.slice_size; + let dcc_slice_align = if surf_align >= 65_536 { 4096 } else { 256 }; + let dcc_slice = color_slice + .div_ceil(256) + .max(dcc_slice_align) + .next_multiple_of(dcc_slice_align); + push_meta( + &mut metadata, + &mut cursor, + &mut alignment, + MetadataKind::Dcc, + dcc_slice, + surf_align, + 1, + ); + } + } + + let size = cursor; Ok(Texture { planes, + metadata, size, alignment, }) @@ -1063,4 +1397,101 @@ mod tests { ); assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); } + + #[test] + fn fast_path_tile_and_detile_match_point_offsets() { + for (w, h, bpp, swizzle) in [ + (64, 32, 4, Swizzle::LINEAR), + (37, 19, 4, Swizzle::LINEAR), + (64, 64, 1, Swizzle::SW_64KB_S), + (64, 64, 4, Swizzle::SW_64KB_S), + (64, 64, 8, Swizzle::SW_64KB_D), + (32, 32, 16, Swizzle::SW_64KB_S), + (37, 29, 4, Swizzle::SW_4KB_S), + ] { + let layout = Layout::new(&desc(w, h, 1, bpp, swizzle)).unwrap(); + let row_bytes = (w * bpp) as usize; + let row_pitch = if swizzle == Swizzle::LINEAR && w == 64 { + row_bytes + } else { + row_bytes + 16 + }; + let mut src = vec![0u8; h as usize * row_pitch]; + for y in 0..h { + for x in 0..w { + for k in 0..bpp { + src[y as usize * row_pitch + (x * bpp + k) as usize] = + ((x * 13 + y * 37 + k * 7) & 0xff) as u8; + } + } + } + let mut tiled = vec![0u8; layout.size as usize]; + layout.tile(&mut tiled, 0, 0, &src, row_pitch, 0).unwrap(); + for y in 0..h { + for x in 0..w { + let off = layout.offset(0, x, y, 0).unwrap() as usize; + let lin = y as usize * row_pitch + (x * bpp) as usize; + assert_eq!(&tiled[off..off + bpp as usize], &src[lin..lin + bpp as usize]); + } + } + let mut out = vec![0u8; src.len()]; + layout.detile(&tiled, 0, 0, &mut out, row_pitch, 0).unwrap(); + for y in 0..h as usize { + let a = y * row_pitch; + assert_eq!(&out[a..a + row_bytes], &src[a..a + row_bytes]); + } + } + } + + #[test] + fn render_target_and_depth_metadata_planes_are_laid_out_and_aligned() { + let base = TextureDesc { + dimension: Dimension::Tex2d, + width: 1920, + height: 1080, + depth_or_array: 1, + mips: 1, + format: 28, // R8G8B8A8_UNORM + samples: 1, + swizzle: Swizzle::SW_64KB_R_X, + }; + let plain = Texture::new(&base).unwrap(); + assert!(plain.metadata.is_empty()); + + // Single-sample render target gets a 64 KiB-aligned DCC plane. + let rt = Texture::with_metadata(&base, MetadataFlags::from_d3d12_flags(0x1)).unwrap(); + assert_eq!(rt.planes.len(), 1); + assert_eq!(rt.metadata.len(), 1); + assert_eq!(rt.metadata[0].kind, MetadataKind::Dcc); + assert_eq!(rt.metadata[0].offset % 65_536, 0); + assert!(rt.size > plain.size); + + // Deny-compression bit suppresses DCC. + let denied = + Texture::with_metadata(&base, MetadataFlags::from_d3d12_flags(0x4000_0001)).unwrap(); + assert!(denied.metadata.is_empty()); + assert_eq!(denied.size, plain.size); + + // MSAA 4x render target gets CMASK, FMASK, and DCC. + let msaa_desc = TextureDesc { samples: 4, ..base }; + let msaa = Texture::with_metadata(&msaa_desc, MetadataFlags::from_d3d12_flags(0x1)).unwrap(); + assert_eq!( + msaa.metadata.iter().map(|m| m.kind).collect::>(), + vec![MetadataKind::Cmask, MetadataKind::Fmask, MetadataKind::Dcc] + ); + + // Depth+stencil target (D32_FLOAT_S8X24_UINT = 20) gets depth + stencil + HTILE. + let ds_desc = TextureDesc { + format: 20, + swizzle: Swizzle::SW_64KB_Z_X, + ..base + }; + let ds = Texture::with_metadata(&ds_desc, MetadataFlags::from_d3d12_flags(0x2)).unwrap(); + assert_eq!(ds.planes.len(), 2); + assert_eq!(ds.metadata.len(), 1); + assert_eq!(ds.metadata[0].kind, MetadataKind::Htile); + assert_eq!(ds.metadata[0].element_bytes, 4); + assert_eq!(ds.metadata[0].offset % 65_536, 0); + assert!(ds.metadata[0].size >= 65_536); + } } diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 28c256949f..de94778238 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -8,11 +8,46 @@ use std::path::PathBuf; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -/// The folder frames go to, if capturing. +/// Returns `true` if `path` (or its deepest existing ancestor) lies inside a +/// VIctory checkout or Git repository, enforcing rule #1 on diagnostic dumps. +fn is_inside_repo(path: &std::path::Path) -> bool { + let abs = if path.is_absolute() { + path.to_path_buf() + } else { + let Ok(cwd) = std::env::current_dir() else { + return true; + }; + cwd.join(path) + }; + let mut cur = abs.as_path(); + let base = loop { + if let Ok(canon) = std::fs::canonicalize(cur) { + break canon; + } + match cur.parent() { + Some(p) if !p.as_os_str().is_empty() => cur = p, + _ => break abs, + } + }; + base.ancestors() + .any(|a| a.join(".victory-root").is_file() || a.join(".git").exists()) +} + +/// The folder frames go to, if capturing (refused when inside a repository). pub(crate) fn folder() -> Option<&'static PathBuf> { static FOLDER: std::sync::OnceLock> = std::sync::OnceLock::new(); FOLDER - .get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from)) + .get_or_init(|| { + let path = PathBuf::from(std::env::var_os("VICTORY_CAPTURE")?); + if is_inside_repo(&path) { + tracing::warn!( + path = %path.display(), + "refusing VICTORY_CAPTURE inside repository (keep captures outside the source tree)" + ); + return None; + } + Some(path) + }) .as_ref() } @@ -97,12 +132,12 @@ fn crc32(bytes: &[u8]) -> u32 { } /// Records a copy of `texture` (in the copy-source state) into a -/// readback buffer. +/// readback buffer, returning the buffer, footprint and allocation size. pub(crate) fn read_back( device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, -) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u64)> { let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0; // SAFETY: a live texture; outputs for one subresource. @@ -165,7 +200,7 @@ pub(crate) fn read_back( }, }; list.CopyTextureRegion(&to, 0, 0, 0, &from, None); - Some((buffer, footprint)) + Some((buffer, footprint, total)) } } @@ -174,6 +209,7 @@ pub(crate) fn save_read_back( frame: u64, buffer: &ID3D12Resource, footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + total: u64, ) { let f = footprint.Footprint; let bgra = match f.Format { @@ -186,12 +222,14 @@ pub(crate) fn save_read_back( }; let mut data = std::ptr::null_mut(); // SAFETY: the copy finished (every submission is waited for); the - // mapping spans the footprint's rows. + // readback buffer was allocated with `total` bytes. unsafe { if buffer.Map(0, None, Some(&mut data)).is_err() { return; } - let len = f.RowPitch as usize * f.Height as usize; + let len = (f.RowPitch as usize) + .saturating_mul(f.Height as usize) + .min(total as usize); let rows = std::slice::from_raw_parts(data.cast::(), len); save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows); buffer.Unmap(0, None); @@ -210,7 +248,7 @@ static TARGETS: std::sync::Mutex bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) + *ON.get_or_init(|| folder().is_some() && crate::host::env_flag("VICTORY_DUMP_TARGETS")) } /// Notes a title texture the frame being built renders to or writes. @@ -271,16 +309,21 @@ fn dump_one( }; list.close(); host.execute(&[&list]); - let Some((buffer, footprint)) = read else { return }; + let Some((buffer, footprint, total)) = read else { + return; + }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); - // SAFETY: the copy finished; the mapping spans the footprint's rows. + // SAFETY: the copy finished; the readback buffer was allocated with `total` bytes. unsafe { if buffer.Map(0, None, Some(&mut data)).is_err() { return; } let pitch = f.RowPitch as usize; - let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize); + let len = pitch + .saturating_mul(f.Height as usize) + .min(total as usize); + let rows = std::slice::from_raw_parts(data.cast::(), len); if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 43dba24285..0a58573e3f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -12,15 +12,19 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +use victory_shader::ResourceType; pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, - /// Slots mirroring the title's; view heaps have [`DYNAMIC`] more. + /// Slots mirroring the title's; view heaps have `dynamic_count` more. count: u32, + /// Number of dynamic slots appended after `count` (0 for sampler heaps). + dynamic_count: u32, sampler: bool, - /// The record (view index and generation) each slot was last made from. + /// The record (view index and generation) each slot was last made from, + /// or one of the `NULL_*` sentinels when left null with a specific kind. made: Mutex>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it @@ -59,10 +63,20 @@ pub(crate) fn near_heaps(va: u64) -> String { /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; -/// Slots past the title's in a view heap, for tables a draw needs made -/// afresh (constant buffers copied per draw). A list holds the slots it -/// took until it is reset (its submissions have run) or released. -const DYNAMIC: u32 = 1 << 16; +/// Preferred dynamic slot reserve past the title's slots in a view heap, +/// for tables a draw needs made afresh (constant buffers copied per draw). +/// Falls back to [`DYNAMIC_MIN`] when capped at [`PORTABLE_VIEWS`] so the +/// title keeps as many direct slots as possible. +const DYNAMIC: u32 = 1 << 18; +const DYNAMIC_MIN: u32 = 1 << 16; + +/// Sentinel `made` keys for null slots of each descriptor kind (real view +/// keys pack `generation << 32 | index` with small non-zero generations). +const NULL_SRV: u64 = 0; +const NULL_BUFFER_SRV: u64 = u64::MAX - 3; +const NULL_TEXTURE_UAV: u64 = u64::MAX - 2; +const NULL_BUFFER_UAV: u64 = u64::MAX - 1; +const NULL_CBV: u64 = u64::MAX; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { @@ -84,14 +98,26 @@ impl HostHeap { }) } }; - let extra = if sampler { 0 } else { DYNAMIC }; - let (heap, count) = match make(count + extra) { - Ok(heap) => (heap, count), - Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left out; - // a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra) + let preferred_extra = if sampler { 0 } else { DYNAMIC }; + let (heap, count, extra) = match make(count.saturating_add(preferred_extra)) { + Ok(heap) => (heap, count, preferred_extra), + Err(e) if !sampler && count.saturating_add(preferred_extra) > PORTABLE_VIEWS => { + // Keep all title slots if a smaller dynamic reserve fits, + // otherwise cap at `PORTABLE_VIEWS` with `DYNAMIC_MIN`. + let extra = if count.saturating_add(DYNAMIC_MIN) <= PORTABLE_VIEWS { + PORTABLE_VIEWS - count + } else { + DYNAMIC_MIN + }; + let capped_count = count.min(PORTABLE_VIEWS - extra); + tracing::warn!( + error = %e, + count, + capped_count, + extra, + "host view heap capped at {PORTABLE_VIEWS}" + ); + (make(PORTABLE_VIEWS).ok()?, capped_count, extra) } Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); @@ -105,7 +131,7 @@ impl HostHeap { host.device.GetDescriptorHandleIncrementSize(kind), ) }; - tracing::debug!(count, sampler, "host descriptor heap"); + tracing::debug!(count, extra, sampler, "host descriptor heap"); // SAFETY: a live shader-visible heap. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( @@ -119,10 +145,11 @@ impl HostHeap { cpu, step, count, + dynamic_count: extra, sampler, - made: Mutex::new(vec![0; count as usize]), + made: Mutex::new(vec![NULL_SRV; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; DYNAMIC as usize])), + next: Mutex::new((0, vec![false; extra as usize])), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -201,14 +228,16 @@ impl HostHeap { /// `n` consecutive free dynamic slots (view heaps only), taken until /// [`HostHeap::release`]: the first's index. pub(crate) fn dynamic(&self, n: u32) -> Option { - if self.sampler || n == 0 || n > DYNAMIC { + let cap = self.dynamic_count; + if self.sampler || n == 0 || n > cap { return None; } let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; let n = n as usize; + let cap_usize = cap as usize; // Search from `next` on, then from the start. - let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize); + let starts = (*next as usize..cap_usize).chain(0..*next as usize); let mut run = 0; let mut found = None; let mut last = usize::MAX; @@ -224,13 +253,9 @@ impl HostHeap { break; } } - let Some(first) = found else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); - return None; - }; + let first = found?; taken[first..first + n].fill(true); - *next = ((first + n) % DYNAMIC as usize) as u32; + *next = ((first + n) % cap_usize) as u32; Some(self.count + first as u32) } @@ -249,7 +274,7 @@ impl HostHeap { return; }; let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let end = (at + n).min(DYNAMIC) as usize; + let end = (at.saturating_add(n)).min(self.dynamic_count) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { slots.fill(false); } @@ -275,11 +300,38 @@ impl HostHeap { self.keep(index, None); } + /// Makes slot `index` a null descriptor matching the shader's expected + /// resource kind and descriptor width (`4` dwords = buffer, `8` = image), + /// so writing to an unbound UAV slot hits a hardware null UAV instead of + /// a null SRV (which page-faults on RDNA3). + pub(crate) fn make_null_for(&self, index: u32, kind: ResourceType, dwords: u8) { + let at = self.cpu(index); + if self.sampler || kind == ResourceType::Sampler { + self.null_sampler(index); + } else { + match (kind, dwords == 4) { + (ResourceType::Uav, true) => null_buffer_uav(at), + (ResourceType::Uav, false) => null_texture_uav(4, at), + (ResourceType::Cbv, _) => null_cbv(at), + (ResourceType::Srv, true) => null_buffer_view(at), + (ResourceType::Srv, false) => null_view(at), + (ResourceType::Sampler, _) => unreachable!(), + } + } + self.keep(index, None); + } + /// Slot `index` now views `resource` (or nothing of the host's). + /// Any previously held host resource is retired across frames so in-flight + /// multi-list or indirect draws reading this descriptor slot cannot fault. fn keep(&self, index: u32, resource: Option) { - let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slot) = kept.get_mut(index as usize) { - *slot = resource; + let old = { + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + kept.get_mut(index as usize) + .and_then(|slot| std::mem::replace(slot, resource)) + }; + if let Some(old) = old { + crate::host::retire_resource(old); } } @@ -310,6 +362,20 @@ impl HostHeap { /// views are made only for draws (`for_draw`), which also copy their /// data: a host copy of a buffer is made on first use. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { + self.mirror_for(index, handle, for_draw, ResourceType::Srv, 8) + } + + /// Like [`HostHeap::mirror`], but when the slot is unbound (`None`) makes + /// a null descriptor of the shader's expected `kind` and descriptor width + /// (`dwords == 4` for buffers, `8` for images). + pub(crate) fn mirror_for( + &self, + index: u32, + handle: u64, + for_draw: bool, + kind: ResourceType, + dwords: u8, + ) -> Option { if index >= self.count { // Diagnostic (NVIDIA heap cap): the highest title slot past the // host heap seen so far. @@ -332,16 +398,28 @@ impl HostHeap { let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { // Not a view of ours (never written, or of a resource the - // title released): nothing to read. - if made[index as usize] != 0 { - made[index as usize] = 0; - self.make_null(index); + // title released): ensure the slot carries a matching null view. + let want = if self.sampler || kind == ResourceType::Sampler { + NULL_SRV + } else { + match (kind, dwords == 4) { + (ResourceType::Uav, true) => NULL_BUFFER_UAV, + (ResourceType::Uav, false) => NULL_TEXTURE_UAV, + (ResourceType::Cbv, _) => NULL_CBV, + (ResourceType::Srv, true) => NULL_BUFFER_SRV, + (ResourceType::Srv, false) => NULL_SRV, + (ResourceType::Sampler, _) => unreachable!(), + } + }; + if made[index as usize] != want { + made[index as usize] = want; + self.make_null_for(index, kind, dwords); } return None; }; if made[index as usize] != key { let later = !for_draw && view.is_buffer(); - made[index as usize] = if later { 0 } else { key }; + made[index as usize] = if later { NULL_SRV } else { key }; let kept = if later { None } else { @@ -361,7 +439,7 @@ impl HostHeap { #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; - if key == 0 { + if key == NULL_SRV || key >= NULL_BUFFER_SRV { return Some("null".into()); } let view = view_at(key as u32, (key >> 32) as u32)?; @@ -492,7 +570,23 @@ fn buffer_srv( ); return None; } - buffer.FirstElement += offset / element; + let total = shadow.len / element; + let Some(first) = buffer.FirstElement.checked_add(offset / element) else { + return None; + }; + if first >= total || buffer.NumElements == 0 { + once!( + first, + total, + "buffer shader view starts past the end of its host copy" + ); + return None; + } + let avail = (total - first).min(u64::from(u32::MAX)) as u32; + buffer.FirstElement = first; + if buffer.NumElements > avail { + buffer.NumElements = avail; + } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { @@ -534,7 +628,23 @@ fn buffer_uav( once!(offset, element, "unordered buffer view not on an element of its host copy"); return None; } - buffer.FirstElement += offset / element; + let total = shadow.len / element; + let Some(first) = buffer.FirstElement.checked_add(offset / element) else { + return None; + }; + if first >= total || buffer.NumElements == 0 { + once!( + first, + total, + "buffer unordered view starts past the end of its host copy" + ); + return None; + } + let avail = (total - first).min(u64::from(u32::MAX)) as u32; + buffer.FirstElement = first; + if buffer.NumElements > avail { + buffer.NumElements = avail; + } buffer.CounterOffsetInBytes = 0; let host = host()?; // SAFETY: a live buffer and a slot of our heap. @@ -598,6 +708,49 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +/// Converts a depth/stencil SRV format to its readable host DXGI format and +/// selects the matching plane (`0` for depth, `1` for stencil) on 2D and +/// 2D-array views of typeless depth/stencil host textures. +fn fix_depth_stencil_srv(own: u32, desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC) { + let raw = desc.Format.0 as u32; + let mapped = match (own, raw) { + // D32_FLOAT_S8X24 family (typeless 19): DSV 20 -> depth SRV 21; stencil SRV 22. + (19, 0 | 19 | 20) => 21, + (19, 22) => 22, + // R32 / D32 family (typeless 39): DSV 40 -> R32_FLOAT 41. + (39, 0 | 39 | 40) => 41, + // D24_UNORM_S8_UINT family (typeless 44): DSV 45 -> depth SRV 46; stencil SRV 47. + (44, 0 | 44 | 45) => 46, + (44, 47) => 47, + // R16 / D16 family (typeless 53): DSV 55 -> R16_UNORM 56. + (53, 0 | 53 | 55) => 56, + (_, 20) => 21, + (_, 40) => 41, + (_, 45) => 46, + (_, 55) => 56, + _ => raw, + }; + desc.Format = DXGI_FORMAT(mapped as i32); + let plane = match mapped { + 22 | 47 => Some(1u32), + 21 | 46 if matches!(own, 19 | 44) => Some(0u32), + _ => None, + }; + if let Some(plane) = plane { + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: `ViewDimension` selects the `Texture2D` union member. + unsafe { desc.Anonymous.Texture2D.PlaneSlice = plane }; + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: `ViewDimension` selects the `Texture2DArray` union member. + unsafe { desc.Anonymous.Texture2DArray.PlaneSlice = plane }; + } + _ => {} + } + } +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -626,6 +779,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { let mut desc = desc.as_ref().map(srv_desc); + if let Some(d) = desc.as_mut() { + // SAFETY: a live texture. + let own = unsafe { texture.GetDesc() }.Format.0 as u32; + fix_depth_stencil_srv(own, d); + } if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } @@ -729,14 +887,29 @@ pub(crate) fn placed_texture(view: &View) -> Option { } /// A null view of the kind `view` is, for a slot whose view the host -/// cannot make: unordered access (to a buffer or a 2D texture) or a shader -/// view. Writes to it are dropped, reads give zeros. +/// cannot make: unordered access (matching the buffer or texture dimension) +/// or a shader view. Writes to it are dropped, reads give zeros. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { - let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); - let buffer = match view { - View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1), - View::Placed(true, resource, _) => resource[0] == 1, + let (buffer, uav_dim) = match view { + View::Unordered(r, _, desc) => { + let buf = is_buffer(r) || desc.is_some_and(|d| d[1] == 1); + let dim = desc.map_or(4, |d| d[1]); + (buf, dim) + } + View::Placed(true, resource, desc) => { + let buf = resource[0] == 1; + let dim = if desc[1] != 0 { + desc[1] + } else { + match resource[0] { + 2 => 2, // TEXTURE1D + 4 => 8, // TEXTURE3D + _ => 4, // TEXTURE2D + } + }; + (buf, dim) + } // Shader views of buffers read nothing through a null buffer view: // a null 2D view where the shader expects a buffer is a mismatch // the hardware does not survive in general (GPU-based validation @@ -751,21 +924,94 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { View::Placed(false, _, desc) => { return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); } - View::Constant(..) => { - let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); - // SAFETY: a slot of our heap; a zero location makes a null view. - return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; - } + View::Constant(..) => return null_cbv(at), _ => return null_view(at), }; + if buffer { + null_buffer_uav(at); + } else { + null_texture_uav(uav_dim, at); + } +} + +/// A constant buffer view that reads zeros. +fn null_cbv(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); + // SAFETY: a slot of our heap; a zero location makes a null view. + unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; +} + +/// A raw buffer UAV that drops writes and reads zeros. +fn null_buffer_uav(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R32_UINT, - ViewDimension: if buffer { - D3D12_UAV_DIMENSION_BUFFER - } else { - D3D12_UAV_DIMENSION_TEXTURE2D + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 1, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) + }; +} + +/// A texture UAV of dimension `dim` (1D, 1DArray, 2D, 2DArray, or 3D; defaults +/// to 2D) that drops writes and reads zeros. +fn null_texture_uav(dim: u32, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = match dim { + 2 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE1D, + ..Default::default() + }, + 3 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE1DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture1DArray: D3D12_TEX1D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }, + }, + }, + 5 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }, + }, + }, + 8 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE3D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture3D: D3D12_TEX3D_UAV { + WSize: 1, + ..Default::default() + }, + }, + }, + _ => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() }, - ..Default::default() }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { @@ -871,4 +1117,29 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40)); } + + #[test] + fn depth_stencil_srv_maps_format_and_plane() { + let mut depth = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(20), // D32_FLOAT_S8X24_UINT + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + // SAFETY: `ViewDimension` is `TEXTURE2D`. + unsafe { depth.Anonymous.Texture2D.PlaneSlice = 1 }; + fix_depth_stencil_srv(19, &mut depth); + assert_eq!(depth.Format.0, 21); // R32_FLOAT_X8X24_TYPELESS + // SAFETY: `ViewDimension` is `TEXTURE2D`. + assert_eq!(unsafe { depth.Anonymous.Texture2D.PlaneSlice }, 0); + + let mut stencil = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(47), // X24_TYPELESS_G8_UINT + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + ..Default::default() + }; + fix_depth_stencil_srv(44, &mut stencil); + assert_eq!(stencil.Format.0, 47); + // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`. + assert_eq!(unsafe { stencil.Anonymous.Texture2DArray.PlaneSlice }, 1); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b7ac..8cdbff3b56 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -8,6 +8,7 @@ //! stencil reference, topology, targets) is set on the host list as the //! title sets it. +use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use victory_shader::{ResourceType, RootType, UsedResource}; @@ -74,17 +75,6 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, -} - -impl Drop for State { - fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { - crate::descriptor::release_dynamic(heap, first, n); - } - } } /// Draws recorded on the host GPU since the last frame line. @@ -129,19 +119,45 @@ pub(crate) fn dispatched() -> u64 { DISPATCHED.load(Ordering::Relaxed) } +#[derive(Clone, Copy)] +enum RootViewKind { + Cbv, + Srv, + Uav, +} + +const BUFFER_READ: u32 = D3D12_RESOURCE_STATE_GENERIC_READ.0 as u32; +const BUFFER_UAV: u32 = D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32; + /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB, /// other views as 1 MiB (both cut at their buffer's end). -fn root_view(list: &HostList, address: u64, srv: bool) -> Option { +fn root_view( + list: &HostList, + address: u64, + kind: RootViewKind, + uav_buffers: &mut Vec, +) -> Option { let shadow = crate::shadow::find(address, 1)?; - let len = shadow - .left(address) - .min(if srv { 1 << 20 } else { 1 << 16 }); + let len = shadow.left(address).min(match kind { + RootViewKind::Cbv => 1 << 16, + RootViewKind::Srv | RootViewKind::Uav => 1 << 20, + }); let gpu = shadow.gpu(address); - if srv || gpu % 256 == 0 { + if !matches!(kind, RootViewKind::Cbv) || gpu.is_multiple_of(256) { shadow.refresh(list, address, len); + let key = Arc::as_ptr(&shadow) as usize; + if matches!(kind, RootViewKind::Uav) { + shadow.gpu_writes(list, address, len); + if !uav_buffers.contains(&key) { + uav_buffers.push(key); + } + list.ensure_buffer(&shadow, BUFFER_UAV); + } else if !uav_buffers.contains(&key) { + list.ensure_buffer(&shadow, BUFFER_READ); + } return Some(gpu); } let (gpu, to) = list.scratch(len)?; @@ -242,6 +258,14 @@ impl State { } } + pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + for i in 0..count as usize { + if let Some(slot) = self.vertex.get_mut(start as usize + i) { + *slot = VertexView::default(); + } + } + } + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { self.index = view.copied().unwrap_or_default(); } @@ -288,9 +312,43 @@ impl State { }; } + /// The host byte length of a bound root view for `slot` (0 if unset or + /// outside shadow memory), matching [`root_view`]'s 64 KiB CBV / 1 MiB + /// SRV/UAV cap so shaders never read or write past the host mapping. + fn root_view_bytes( + &self, + stage: &crate::pipeline::host::Stage, + compute: bool, + slot: u8, + ) -> u32 { + let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { + return 0; + }; + let Some(shadow) = crate::shadow::find(*address, 1) else { + return 0; + }; + let cap = if stage.root_cbvs.iter().any(|&(s, _)| s == slot) { + 1u64 << 16 + } else { + 1u64 << 20 + }; + shadow.left(*address).min(cap) as u32 + } + /// The user-data value of a root argument, as translated shaders read - /// it: a table's byte offset in its heap, a constant's value. - fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { + /// it: a table's byte offset in its heap, a constant's value, or a root + /// view's bound byte size. + fn user_value( + &self, + stage: &crate::pipeline::host::Stage, + compute: bool, + slot: u8, + root: RootType, + dword: u32, + ) -> u32 { + if root == RootType::Descriptor { + return self.root_view_bytes(stage, compute, slot); + } match (self.roots_ref(compute).get(usize::from(slot)), root) { (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { Some(heap) => (handle - heap.start) as u32, @@ -344,7 +402,7 @@ impl State { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; } - self.bind(list, p, false); + let uav_buffers = self.bind(list, p, false); let l = &list.list; // Vertex buffers the input layout reads. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; @@ -361,6 +419,9 @@ impl State { continue; }; shadow.refresh(list, v.address, u64::from(v.size)); + if !uav_buffers.contains(&(Arc::as_ptr(&shadow) as usize)) { + list.ensure_buffer(&shadow, BUFFER_READ); + } *view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), SizeInBytes: v.size, @@ -379,6 +440,9 @@ impl State { return false; }; shadow.refresh(list, v.address, u64::from(v.size)); + if !uav_buffers.contains(&(Arc::as_ptr(&shadow) as usize)) { + list.ensure_buffer(&shadow, BUFFER_READ); + } let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), SizeInBytes: v.size, @@ -402,8 +466,11 @@ impl State { /// it changed, constant data copied, textures made readable. /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the - /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + /// descriptors its tables hold. Returns shadow-buffer pointers bound as + /// UAVs by this operation so callers do not transition them away from + /// `UNORDERED_ACCESS`. + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> Vec { + let mut uav_buffers = Vec::new(); let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -446,8 +513,12 @@ impl State { } for stage in &p.stages { let t = stage.translated(); - let made = self.tables(list, &t.used, compute); - if let Some((param, dwords)) = stage.user_data { + let made = self.tables(list, &t.used, compute, &mut uav_buffers); + if let Some(binding) = stage.user_data { + let dwords = match binding { + crate::pipeline::host::UserDataBinding::Constants { dwords, .. } + | crate::pipeline::host::UserDataBinding::RootCbv { dwords, .. } => dwords, + }; let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { let fresh = made @@ -455,40 +526,149 @@ impl State { .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, - None => self.user_value(compute, u.slot, u.root, u.dword), + None => self.user_value(stage, compute, u.slot, u.root, u.dword), }; } - // SAFETY: an open list; `values` covers the parameter. - unsafe { - if compute { - l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); - } else { - l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + match binding { + crate::pipeline::host::UserDataBinding::Constants { param, dwords } => { + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants( + param, + dwords, + values.as_ptr().cast(), + 0, + ); + } else { + l.SetGraphicsRoot32BitConstants( + param, + dwords, + values.as_ptr().cast(), + 0, + ); + } + } + } + crate::pipeline::host::UserDataBinding::RootCbv { param, dwords } => { + let byte_len = (dwords as usize) * 4; + let padded = u64::from(dwords * 4).next_multiple_of(256); + if let Some((gpu, to)) = list.scratch(padded) { + // SAFETY: `to` points to `padded >= byte_len` writable bytes of + // the list's upload ring; `values` is `byte_len` valid bytes. + unsafe { + std::ptr::copy_nonoverlapping( + values.as_ptr().cast::(), + to, + byte_len, + ); + if compute { + l.SetComputeRootConstantBufferView(param, gpu); + } else { + l.SetGraphicsRootConstantBufferView(param, gpu); + } + } + } else { + once!(param, "no scratch upload memory for spilled user-data CBV"); + } } } } - for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { + for (views, kind) in [ + (&stage.root_cbvs, RootViewKind::Cbv), + (&stage.root_srvs, RootViewKind::Srv), + (&stage.root_uavs, RootViewKind::Uav), + ] { for &(slot, param) in views { let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); continue; }; - let Some(gpu) = root_view(list, *address, srv) else { + let Some(gpu) = root_view(list, *address, kind, &mut uav_buffers) else { continue; }; // SAFETY: an open list; the address is in live memory. unsafe { - match (compute, srv) { - (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), - (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), - (true, false) => l.SetComputeRootConstantBufferView(param, gpu), - (true, true) => l.SetComputeRootShaderResourceView(param, gpu), + match (compute, kind) { + (false, RootViewKind::Cbv) => { + l.SetGraphicsRootConstantBufferView(param, gpu) + } + (false, RootViewKind::Srv) => { + l.SetGraphicsRootShaderResourceView(param, gpu) + } + (false, RootViewKind::Uav) => { + l.SetGraphicsRootUnorderedAccessView(param, gpu) + } + (true, RootViewKind::Cbv) => { + l.SetComputeRootConstantBufferView(param, gpu) + } + (true, RootViewKind::Srv) => { + l.SetComputeRootShaderResourceView(param, gpu) + } + (true, RootViewKind::Uav) => { + l.SetComputeRootUnorderedAccessView(param, gpu) + } + } + } + } + } + for (views, kind) in [ + (&stage.const_cbvs, RootViewKind::Cbv), + (&stage.const_srvs, RootViewKind::Srv), + (&stage.const_uavs, RootViewKind::Uav), + ] { + for &(slot, dword, param) in views { + let Some(Root::Constants(c)) = self.roots_ref(compute).get(usize::from(slot)) + else { + once!( + slot, + "a shader reads a constant-pair root view the title did not set" + ); + continue; + }; + let (Some(&lo), Some(&hi)) = ( + c.get(dword as usize), + c.get((dword as usize).saturating_add(1)), + ) else { + once!( + slot, + dword, + "a constant-pair root view reads past the set root constants" + ); + continue; + }; + let address = u64::from(lo) | (u64::from(hi) << 32); + let Some(gpu) = root_view(list, address, kind, &mut uav_buffers) else { + continue; + }; + // SAFETY: an open list; the address is in live memory. + unsafe { + match (compute, kind) { + (false, RootViewKind::Cbv) => { + l.SetGraphicsRootConstantBufferView(param, gpu) + } + (false, RootViewKind::Srv) => { + l.SetGraphicsRootShaderResourceView(param, gpu) + } + (false, RootViewKind::Uav) => { + l.SetGraphicsRootUnorderedAccessView(param, gpu) + } + (true, RootViewKind::Cbv) => { + l.SetComputeRootConstantBufferView(param, gpu) + } + (true, RootViewKind::Srv) => { + l.SetComputeRootShaderResourceView(param, gpu) + } + (true, RootViewKind::Uav) => { + l.SetComputeRootUnorderedAccessView(param, gpu) + } } } } } } + uav_buffers } /// Runs a dispatch on the host. @@ -513,7 +693,7 @@ impl State { once!("a dispatch with a graphics pipeline"); return; } - self.bind(list, p, true); + let _ = self.bind(list, p, true); #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. @@ -539,14 +719,19 @@ impl State { let t = stage.translated(); let _ = write!(text, " | {}:", stage.shader.hash); for u in &t.host.user_data { - let v = self.user_value(compute, u.slot, u.root, u.dword); + let v = self.user_value(stage, compute, u.slot, u.root, u.dword); let _ = write!(text, " u{}={v:#x}", u.index); let index = if u.root == RootType::Table { v / 32 } else { v }; if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { let _ = write!(text, " [heap {index}: {slot}]"); } } - for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) { + for &(slot, _) in stage + .root_cbvs + .iter() + .chain(&stage.root_srvs) + .chain(&stage.root_uavs) + { if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { let host = crate::shadow::find(*address, 1) .map(|s| (s.gpu(*address), s.left(*address))); @@ -590,7 +775,13 @@ impl State { } } - fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) { + fn table_entry( + &self, + list: &HostList, + u: &UsedResource, + compute: bool, + uav_buffers: &mut Vec, + ) { let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { return; }; @@ -601,8 +792,8 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { return; }; - if let Some(view) = host.mirror(index, handle, true) { - readable(list, u, &view); + if let Some(view) = host.mirror_for(index, handle, true, u.kind, u.dwords) { + readable(list, u, &view, uav_buffers); } } @@ -617,7 +808,13 @@ impl State { /// once: its constant data is copied at submission either way, and the /// big tables the world binds would otherwise take hundreds of slots per /// draw, wrapping the dynamic slots onto lists not yet submitted. - fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> { + fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + compute: bool, + uav_buffers: &mut Vec, + ) -> Vec<(u8, u32)> { let tables = |u: &&UsedResource| u.root == RootType::Table; let mut fresh: Vec = used .iter() @@ -650,7 +847,7 @@ impl State { fresh.dedup(); for u in used.iter().filter(tables) { if !fresh.contains(&u.slot) { - self.table_entry(list, u, compute); + self.table_entry(list, u, compute, uav_buffers); } } let mut made = Vec::new(); @@ -689,18 +886,34 @@ impl State { for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { - readable(list, u, &view); + readable(list, u, &view, uav_buffers); } } made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { + let heap_ptr = std::ptr::from_ref(heap) as usize; + let Some(first) = host.dynamic(n).or_else(|| { + let reclaimed = crate::host::reclaim_dynamic_slots(heap_ptr); + if reclaimed > 0 { + tracing::debug!( + reclaimed, + needed = n, + "reclaimed dynamic descriptor slots from executed lists" + ); + host.dynamic(n) + } else { + None + } + }) else { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") + }); continue; }; self.fresh_tables.insert(key, first); - self.dynamic - .push((std::ptr::from_ref(heap) as usize, first, n)); + list.record_dynamic(heap_ptr, first, n); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -709,7 +922,7 @@ impl State { match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((gpu, to)) = list.scratch(u64::from(size)) else { - host.make_null(index); + host.make_null_for(index, ResourceType::Cbv, 4); continue; }; list.defer_fill(to, address as *const u8, size as usize); @@ -718,13 +931,15 @@ impl State { Some(view) => { host.make_at(index, &view); if let Some(u) = used { - readable(list, u, &view); + readable(list, u, &view, uav_buffers); } } None => { - host.make_null(index); - if used.is_some() { + if let Some(u) = used { + host.make_null_for(index, u.kind, u.dwords); once!(slot, "a table entry without a view"); + } else { + host.make_null(index); } } } @@ -853,20 +1068,20 @@ impl State { continue; } let v = self.vertex[slot as usize]; - let stride = u64::from(v.stride); - let from = v.address + u64::from(first) * stride; - if v.address == 0 - || stride == 0 - || u64::from(first + count) * stride > u64::from(v.size) - || crate::shadow::find(from, rects * 3 * stride).is_none() - { + let Some((from, src_bytes, dst_bytes)) = + rect_vertex_range(v.address, v.size, v.stride, first, count) + else { + once!(slot, "rectangle vertices outside their buffer"); + return false; + }; + if crate::shadow::find(from, src_bytes).is_none() { once!(slot, "rectangle vertices outside their buffer"); return false; } - let Some((gpu, to)) = list.scratch(rects * 6 * stride) else { + let Some((gpu, to)) = list.scratch(u64::from(dst_bytes)) else { return false; }; - let (from, to, stride) = (from as usize, to as usize, stride as usize); + let (from, to, stride) = (from as usize, to as usize, v.stride as usize); let n = rects as usize; list.defer_host(move || { // SAFETY: the vertices lie in a title buffer (checked when @@ -881,7 +1096,7 @@ impl State { }); let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: gpu, - SizeInBytes: (rects * 6 * stride as u64) as u32, + SizeInBytes: dst_bytes, StrideInBytes: v.stride, }; // SAFETY: an open list; the view names live scratch memory. @@ -977,11 +1192,15 @@ impl State { if let Some((s, at)) = &counter { s.refresh(list, *at, 4); } - // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + // Bounded first: the clamp binds a compute pipeline of its own, and + // leaves `args` in `GENERIC_READ`. + if !crate::indirect::bound(list, &args, args.gpu(arguments), (kind, stride, max)) { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; } + if let Some((s, _)) = &counter { + list.ensure_buffer(s, BUFFER_READ); + } self.host_pipeline = 0; self.host_roots[1] = 0; let ran = match kind { @@ -989,7 +1208,7 @@ impl State { MESH => self.prepare_for(list, false, true), DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { Some(p) if p.compute => { - self.bind(list, p, true); + let _ = self.bind(list, p, true); true } _ => false, @@ -997,7 +1216,6 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => crate::pipeline::note_drop(self.pipeline as This), @@ -1005,6 +1223,13 @@ impl State { } return false; } + // Ensure indirect argument and count buffers stay in `GENERIC_READ` + // (includes `INDIRECT_ARGUMENT`) even if `bind` touched the same + // backing shadow buffer. + list.ensure_buffer(&args, BUFFER_READ); + if let Some((s, _)) = &counter { + list.ensure_buffer(s, BUFFER_READ); + } #[cfg(feature = "diagnostics")] list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) @@ -1021,7 +1246,6 @@ impl State { counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - crate::indirect::done(list, &args.buffer); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { @@ -1070,8 +1294,8 @@ fn host_signature(kind: u32, stride: u32) -> Option { } /// Gets what a shader reads or writes through a view ready: buffer data -/// copied, textures moved to the state they need. -fn readable(list: &HostList, u: &UsedResource, view: &View) { +/// copied, textures and buffers moved to the state they need. +fn readable(list: &HostList, u: &UsedResource, view: &View, uav_buffers: &mut Vec) { const SHADER_RESOURCE: u32 = 0x40 | 0x80; const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); @@ -1083,8 +1307,15 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { && let Some(shadow) = crate::shadow::find(address, len) { shadow.refresh(list, address, len); + let key = Arc::as_ptr(&shadow) as usize; if u.kind == ResourceType::Uav { shadow.gpu_writes(list, address, len); + if !uav_buffers.contains(&key) { + uav_buffers.push(key); + } + list.ensure_buffer(&shadow, BUFFER_UAV); + } else if !uav_buffers.contains(&key) { + list.ensure_buffer(&shadow, BUFFER_READ); } } match (view, u.kind) { @@ -1180,3 +1411,55 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { + if crate::host::host().is_some_and(crate::host::Host::depth_bounds) + && let Ok(l1) = list.list.cast::() + { + // SAFETY: an open list on a host supporting depth bounds. + unsafe { l1.OMSetDepthBounds(min, max) }; + } +} + +/// Validates and computes `(from_address, src_bytes, dst_bytes)` for expanding +/// `count / 3` console rectangles starting at vertex `first` into triangles. +fn rect_vertex_range( + address: u64, + size: u32, + stride: u32, + first: u32, + count: u32, +) -> Option<(u64, u64, u32)> { + if address == 0 || stride == 0 { + return None; + } + let stride = u64::from(stride); + let end_vertex = u64::from(first).checked_add(u64::from(count))?; + if end_vertex.checked_mul(stride)? > u64::from(size) { + return None; + } + let from = address.checked_add(u64::from(first).checked_mul(stride)?)?; + let rects = u64::from(count / 3); + let src_bytes = rects.checked_mul(3)?.checked_mul(stride)?; + let dst_bytes = u32::try_from(rects.checked_mul(6)?.checked_mul(stride)?).ok()?; + Some((from, src_bytes, dst_bytes)) +} + +#[cfg(test)] +mod tests { + use super::rect_vertex_range; + + #[test] + fn rect_vertex_range_rejects_overflow_and_out_of_bounds() { + assert_eq!(rect_vertex_range(0x1000, 96, 16, 0, 6), Some((0x1000, 96, 192))); + assert_eq!(rect_vertex_range(0x1000, 96, 16, 3, 3), Some((0x1030, 48, 96))); + // `first + count` wraps u32 if not widened to u64. + assert_eq!(rect_vertex_range(0x1000, u32::MAX, 16, u32::MAX - 2, 3), None); + // Zero address or stride or past buffer size. + assert_eq!(rect_vertex_range(0, 96, 16, 0, 3), None); + assert_eq!(rect_vertex_range(0x1000, 96, 0, 0, 3), None); + assert_eq!(rect_vertex_range(0x1000, 47, 16, 0, 3), None); + // Expanded triangle buffer would exceed u32 `SizeInBytes`. + assert_eq!(rect_vertex_range(0x1000, u32::MAX, 16, 0, (1 << 28) - 1), None); + } +} diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 837dfbce18..acd4ab291e 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -1,176 +1,268 @@ -//! Frame pacing: the title sets a frame interval and waits for each frame -//! to begin. Ours is a clock started by the first interval set, ticking -//! once per interval; the token is the frame number. Each event kind -//! (origin, vblank, flip) happens once per tick, so two waits for the same -//! kind never end on the same tick: Grand Theft Auto VI polls the origin -//! with "token on time-out" (starting its next frame at once) and is paced -//! by a blocking wait for the flip before each present. -//! -//! shortcut: event offsets are ignored (every event is at the tick); tie -//! the clock to presentation if a title paces by them. +//! Frame pacing: the console's display interrupt, which titles schedule +//! against and wait on. Driven here from a steady monotonic clock so the +//! title paces its loop at the rate it asked for, using a Windows +//! high-resolution waitable timer (`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`) +//! plus a short spin-tail to the exact deadline so release builds do not +//! suffer 15.6 ms OS timer-quantum drift. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard}; use std::time::{Duration, Instant}; -use crate::object::{HRESULT, S_FALSE, S_OK, This}; +use crate::object::{E_INVALIDARG, HRESULT, S_OK, This}; -/// What a wait returns when its time is up first. -const TIMEOUT: HRESULT = S_FALSE; -/// The frame-origin event: the one that starts frames and makes tokens. -const ORIGIN: u32 = 0; -/// Make the frame's token even if the wait times out (the title starts the -/// frame early). -const TOKEN_ON_TIMEOUT: u32 = 2; -const SIXTIETH: Duration = Duration::from_micros(16_667); +const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32; // WAIT_TIMEOUT + +/// One 60 Hz frame, the default interval before the title sets one. +const SIXTIETH: Duration = Duration::from_nanos(16_666_667); + +/// Spin-tail window before the exact tick deadline: sleeping stops this far +/// ahead of the target `Instant` and yields/spins out the final sub-millisecond +/// to absorb OS wakeup jitter. +const SPIN_MARGIN: Duration = Duration::from_micros(500); struct Clock { + /// Anchor time for `first`. start: Instant, interval: Duration, - /// The tick number at `start` (ticks go on across interval changes). + /// Tick number at `start`, monotonic across interval changes. first: u64, + /// Optional per-event scheduling offset in microseconds (`schedule`). + offsets_us: [u32; 4], } static CLOCK: Mutex> = Mutex::new(None); -static FRAME: AtomicU64 = AtomicU64::new(0); +/// Last tick delivered, per event kind (origin, present, ...). +static LAST: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; -fn clock() -> std::sync::MutexGuard<'static, Option> { +fn clock() -> MutexGuard<'static, Option> { CLOCK.lock().unwrap_or_else(|e| e.into_inner()) } -/// Device method: a frame every `length` microseconds. The period is how -/// many intervals a frame may take to reach the display (pipeline depth), -/// not part of the rate. +fn last(kind: u32) -> &'static AtomicU64 { + &LAST[(kind as usize).min(LAST.len() - 1)] +} + +fn ensure_clock(slot: &mut Option) -> &mut Clock { + slot.get_or_insert_with(|| Clock { + start: Instant::now(), + interval: SIXTIETH, + first: 0, + offsets_us: [0; 4], + }) +} + +/// `SetFrameIntervalX(output, period_us, count, flags)`. pub(crate) extern "system" fn set_interval( _: This, _output: This, - length: u32, - _period: u32, + period_us: u32, + count: u32, _flags: u32, ) -> HRESULT { - let interval = match length { - 0 => SIXTIETH, - us => Duration::from_micros(u64::from(us)), + let interval = Duration::from_micros(u64::from(period_us) * u64::from(count)); + if interval.is_zero() { + return E_INVALIDARG; + } + tracing::debug!(?interval, "frame interval"); + let now = Instant::now(); + let mut guard = clock(); + let mut offsets_us = [0; 4]; + let first = match guard.as_ref() { + Some(c) => { + offsets_us = c.offsets_us; + let elapsed = now.saturating_duration_since(c.start).as_nanos(); + c.first + (elapsed / c.interval.as_nanos().max(1)) as u64 + } + None => 0, }; - tracing::info!(?interval, "frame interval"); - // A new interval starts from now, after the last tick handed out. - let first = LAST - .iter() - .map(|t| t.load(Ordering::Relaxed)) - .max() - .unwrap_or(0); - *clock() = Some(Clock { - start: Instant::now(), + *guard = Some(Clock { + start: now, interval, first, + offsets_us, }); S_OK } -/// Device method: events are scheduled at every tick. +/// `ScheduleFrameEventX(kind, offset_us, flags)`: records the per-event offset +/// within the frame interval (clamped below one full interval). pub(crate) extern "system" fn schedule( _: This, - _kind: u32, - _offset: u32, - _list: *const u8, + kind: u32, + offset_us: u32, _flags: u32, ) -> HRESULT { + let mut guard = clock(); + let c = ensure_clock(&mut guard); + let slot = (kind as usize).min(c.offsets_us.len() - 1); + let max_offset = (c.interval.as_micros() as u32).saturating_sub(1); + c.offsets_us[slot] = offset_us.min(max_offset); S_OK } -/// Frames begun so far (frame waits that ended). -pub(crate) fn current() -> u64 { - FRAME.load(Ordering::Relaxed) +/// Pure deadline calculation for the next tick strictly after `last_tick`. +/// Returns `(tick, target_instant)` without accumulated drift across frames. +fn compute_next_deadline( + start: Instant, + interval: Duration, + first: u64, + offset: Duration, + last_tick: u64, + now: Instant, +) -> (u64, Instant) { + let interval_ns = interval.as_nanos().max(1); + let offset_ns = offset.as_nanos().min(interval_ns.saturating_sub(1)); + let elapsed_ns = now.saturating_duration_since(start).as_nanos(); + // Solve `first + k` such that `k * interval_ns + offset_ns > elapsed_ns`. + let k_from_clock = if elapsed_ns < offset_ns { + 0u64 + } else { + ((elapsed_ns - offset_ns) / interval_ns + 1) as u64 + }; + let tick = (first + k_from_clock).max(last_tick + 1); + let target_ns = u128::from(tick - first) * interval_ns + offset_ns; + // Split nanoseconds cleanly into Duration (safe up to >500 years). + let secs = (target_ns / 1_000_000_000) as u64; + let nanos = (target_ns % 1_000_000_000) as u32; + let target = start + Duration::new(secs, nanos); + (tick, target) } -/// Per event kind (origin, vblank, flip and later kinds): the last tick a -/// wait for it ended on. -static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// The next tick for `kind` and its exact target `Instant`. +fn next_tick(kind: u32, now: Instant) -> (u64, Instant) { + let mut guard = clock(); + let c = ensure_clock(&mut guard); + let slot = (kind as usize).min(c.offsets_us.len() - 1); + let offset = Duration::from_micros(u64::from(c.offsets_us[slot])); + let prev = last(kind).load(Ordering::Relaxed); + compute_next_deadline(c.start, c.interval, c.first, offset, prev, now) +} -fn last(kind: u32) -> &'static AtomicU64 { - &LAST[(kind as usize).min(LAST.len() - 1)] +/// Sleeps accurately until `deadline` using a Windows high-resolution waitable +/// timer plus a sub-millisecond spin-tail so frame pacing does not drift on +/// Windows' default 15.6 ms scheduler tick. +fn sleep_until(deadline: Instant) { + let now = Instant::now(); + if now >= deadline { + return; + } + let remaining = deadline - now; + if remaining > SPIN_MARGIN { + let coarse = remaining - SPIN_MARGIN; + sleep_precise(coarse); + } + while Instant::now() < deadline { + std::hint::spin_loop(); + } } -/// The next tick after now and after the last one a wait for `kind` ended -/// on (an event happens once per tick: a wait woken a little early must not -/// let the next one end on the same tick), and how long until it. -fn next_tick(kind: u32) -> (u64, Duration) { - let mut clock = clock(); - let c = clock.get_or_insert_with(|| Clock { - start: Instant::now(), - interval: SIXTIETH, - first: 0, +#[cfg(windows)] +fn sleep_precise(duration: Duration) { + use std::cell::Cell; + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::Threading::{ + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, INFINITE, + SetWaitableTimer, TIMER_ALL_ACCESS, WaitForSingleObject, + }; + + struct Timer(HANDLE); + impl Drop for Timer { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: handle created by `CreateWaitableTimerExW` for this thread. + unsafe { CloseHandle(self.0) }; + } + } + } + + thread_local! { + static HI_RES_TIMER: Cell> = const { Cell::new(None) }; + } + + let waited = HI_RES_TIMER.with(|cell| { + let mut timer = cell.take(); + if timer.is_none() { + // SAFETY: creating a thread-local unnamed high-resolution waitable timer. + let handle = unsafe { + CreateWaitableTimerExW( + std::ptr::null(), + std::ptr::null(), + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, + TIMER_ALL_ACCESS, + ) + }; + if !handle.is_null() { + timer = Some(Timer(handle)); + } + } + let ok = if let Some(ref t) = timer { + // Relative negative due time in 100-nanosecond intervals. + let ticks_100ns = (duration.as_nanos() / 100).max(1); + let due = -(i64::try_from(ticks_100ns).unwrap_or(i64::MAX)); + // SAFETY: valid waitable timer handle and due time pointer. + unsafe { + SetWaitableTimer(t.0, &due, 0, None, std::ptr::null(), 0) != 0 + && WaitForSingleObject(t.0, INFINITE) == 0 + } + } else { + false + }; + cell.set(timer); + ok }); - let elapsed = c.start.elapsed().as_nanos(); - let interval = c.interval.as_nanos().max(1); - let tick = - (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); - let at = u128::from(tick - c.first) * interval; - ( - tick, - Duration::from_nanos(at.saturating_sub(elapsed) as u64), - ) + if !waited { + std::thread::sleep(duration); + } } -/// Device method: blocks until the next tick (or the time-out); an origin -/// wait then hands out the new frame's token. Other events keep the token -/// the title passes. Ticks are absolute (start plus whole intervals), so -/// lateness never accumulates. +#[cfg(not(windows))] +fn sleep_precise(duration: Duration) { + std::thread::sleep(duration); +} + +/// `WaitFrameEventX(kind, timeout_ms, event, token)`: sleeps until the next +/// tick of `kind` (or `timeout_ms`) and writes the token. A zero timeout +/// returns immediately without yielding or sleeping. pub(crate) extern "system" fn wait( _: This, kind: u32, timeout_ms: u32, - _list: *const u8, - flags: u32, + _event: *mut u8, token: *mut u64, ) -> HRESULT { - let origin = kind == ORIGIN; - let (tick, wait) = next_tick(kind); + let now = Instant::now(); + let (tick, target) = next_tick(kind, now); + let wait = target.saturating_duration_since(now); let limit = Duration::from_millis(u64::from(timeout_ms)); let hr = if wait > limit { - std::thread::sleep(limit); + if !limit.is_zero() { + sleep_until(now + limit); + } TIMEOUT } else { - std::thread::sleep(wait); + if !wait.is_zero() { + sleep_until(target); + } last(kind).fetch_max(tick, Ordering::Relaxed); S_OK }; - // A frame begun on a time-out takes no tick: its flip still does. - if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { - // Tokens count frames (consecutive), not ticks. - let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; - if !token.is_null() { - // SAFETY: checked non-null; the title passes its token. - unsafe { token.write(frame) }; - } + if !token.is_null() { + // SAFETY: optional out parameter. + unsafe { token.write(if hr == S_OK { tick } else { 0 }) }; } - #[cfg(feature = "diagnostics")] - tracing::debug!( - kind, - timeout_ms, - flags, - hr, - tick, - wait_us = wait.as_micros() as u64, - frame = current(), - "frame wait" - ); hr } -/// Device method: no statistics are kept, so none are returned. -pub(crate) extern "system" fn statistics( - _: This, - _token: u64, - _kinds: u32, - count: *mut u32, - _out: *mut u8, -) -> HRESULT { - if !count.is_null() { - // SAFETY: checked non-null. - unsafe { count.write(0) }; +/// `GetFrameStatisticsX(count, stats)`: zeroed counts and timestamps for now. +pub(crate) extern "system" fn statistics(_: This, count: u32, stats: *mut u8) -> HRESULT { + if stats.is_null() { + return E_INVALIDARG; } + const ENTRY: usize = 0x58; + // SAFETY: the title passes room for `count` `D3D12XBOX_FRAME_PIPELINE_STATISTICS`. + unsafe { stats.write_bytes(0, count as usize * ENTRY) }; S_OK } @@ -179,48 +271,48 @@ mod tests { use super::*; #[test] - fn waits_end_on_ticks_and_count_frames() { - let null = std::ptr::null(); - assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK); - let mut first = 0; - assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK); - let before = Instant::now(); - let mut second = 0; - assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); - assert!(second > first); - assert!(before.elapsed() <= Duration::from_millis(50)); - assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); - // Tokens count frames, a frame started early on a time-out too. - let mut early = 0; - let flags = TOKEN_ON_TIMEOUT; + fn compute_next_deadline_has_no_cumulative_drift() { + let start = Instant::now(); + let interval = Duration::from_micros(16_667); + // Simulate 120 frames with small random jitter around each deadline. + let mut last_tick = 0; + for frame in 1..=120u64 { + // Arrive 2 ms early before tick `frame`. + let now = start + interval * (frame as u32) - Duration::from_millis(2); + let (tick, target) = + compute_next_deadline(start, interval, 0, Duration::ZERO, last_tick, now); + assert_eq!(tick, frame); + assert_eq!(target, start + interval * (frame as u32)); + last_tick = tick; + } + } + + #[test] + fn compute_next_deadline_honors_event_offset() { + let start = Instant::now(); + let interval = Duration::from_millis(16); + let offset = Duration::from_millis(4); + let (tick, target) = compute_next_deadline(start, interval, 10, offset, 9, start); + assert_eq!(tick, 10); + assert_eq!(target, start + offset); + + let (tick2, target2) = compute_next_deadline( + start, + interval, + 10, + offset, + 10, + start + Duration::from_millis(5), + ); + assert_eq!(tick2, 11); + assert_eq!(target2, start + interval + offset); + } + + #[test] + fn set_interval_rejects_zero() { assert_eq!( - wait(null, 0, 0, std::ptr::null(), flags, &mut early), - TIMEOUT + set_interval(std::ptr::null_mut(), std::ptr::null_mut(), 0, 1, 0), + E_INVALIDARG ); - let mut next = 0; - assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK); - assert!(early == second + 1 && next == early + 1); - assert!(LAST[0].load(Ordering::Relaxed) >= 2); - - // The title's loop (the clock is global, so in the same test): an - // origin poll that times out (and starts the frame), then a - // blocking flip wait. Each flip takes its own tick. - const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); - let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); - assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); - // Even when a flip wait begins on the tick another just ended on. - let (tick, _) = next_tick(FLIP); - assert!(tick > flips[3]); } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c041282748..3d00a0f26d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -17,6 +17,110 @@ use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObj use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::{Interface, PCWSTR, w}; +/// Completed host presents and submissions, used to retire released GPU +/// resources only after multi-list and indirect frames referencing them have +/// finished running. +static COMPLETED_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static COMPLETED_SUBMISSIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static RETIRED_RESOURCES: Mutex> = Mutex::new(Vec::new()); + +/// Dynamic descriptor-slot allocations belonging to lists that have already +/// finished executing on the host GPU, kept reclaimable if a descriptor heap +/// runs short before those lists are reset. +type DynamicSlotList = std::sync::Arc>>; +static EXECUTED_DYNAMIC: Mutex>>>> = + Mutex::new(Vec::new()); + +/// Reclaims dynamic descriptor slots for `target_heap` held by command lists +/// that have already completed execution, returning the total slots freed. +pub(crate) fn reclaim_dynamic_slots(target_heap: usize) -> usize { + let mut to_release = Vec::new(); + { + let mut reg = EXECUTED_DYNAMIC.lock().unwrap_or_else(|e| e.into_inner()); + reg.retain(|weak| { + let Some(list_slots) = weak.upgrade() else { + return false; + }; + let mut slots = list_slots.lock().unwrap_or_else(|e| e.into_inner()); + let mut i = 0; + while i < slots.len() { + if slots[i].0 == target_heap { + to_release.push(slots.swap_remove(i)); + } else { + i += 1; + } + } + !slots.is_empty() + }); + } + let mut reclaimed = 0usize; + for (heap, first, n) in to_release { + crate::descriptor::release_dynamic(heap, first, n); + reclaimed += n as usize; + } + reclaimed +} + +/// Keeps a released host GPU resource alive until several presented frames +/// (or many completed submissions during loading) have elapsed, so indirect +/// draws and directly-indexed heap reads from earlier frames cannot fault on +/// a freed streaming texture or shadow buffer. +pub(crate) fn retire_resource(resource: ID3D12Resource) { + let frame = COMPLETED_FRAMES.load(Ordering::Relaxed); + let sub = COMPLETED_SUBMISSIONS.load(Ordering::Relaxed); + RETIRED_RESOURCES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((frame, sub, resource)); +} + +/// Drops retired GPU resources old enough that no live command list or +/// multi-list indirect frame can still reference them. +fn drain_retired(frame_lag: u64, submission_lag: u64) { + let frame = COMPLETED_FRAMES.load(Ordering::Relaxed); + let sub = COMPLETED_SUBMISSIONS.load(Ordering::Relaxed); + let mut retired = RETIRED_RESOURCES + .lock() + .unwrap_or_else(|e| e.into_inner()); + if retired.is_empty() { + return; + } + let mut drop_now = Vec::new(); + let mut i = 0; + while i < retired.len() { + let (rf, rs, _) = &retired[i]; + if frame.saturating_sub(*rf) >= frame_lag || sub.saturating_sub(*rs) >= submission_lag { + drop_now.push(retired.swap_remove(i).2); + } else { + i += 1; + } + } + drop(retired); + drop(drop_now); +} + +/// Whether a diagnostics environment switch is enabled: unset, empty, and +/// `0`/`false`/`no`/`off` (ASCII case-insensitive) are off; anything else is +/// on. +pub(crate) fn env_flag(name: &str) -> bool { + parse_env_flag(std::env::var_os(name).as_deref()) +} + +fn parse_env_flag(value: Option<&std::ffi::OsStr>) -> bool { + let Some(v) = value else { + return false; + }; + let Some(s) = v.to_str() else { + return !v.is_empty(); + }; + let trimmed = s.trim(); + !trimmed.is_empty() + && !trimmed.eq_ignore_ascii_case("0") + && !trimmed.eq_ignore_ascii_case("false") + && !trimmed.eq_ignore_ascii_case("no") + && !trimmed.eq_ignore_ascii_case("off") +} + /// Resource states without the console's own bits (compression hints from /// bit 25 up), which the host rejects. pub(crate) fn pc_state(state: u32) -> u32 { @@ -135,8 +239,7 @@ fn create() -> windows::core::Result { // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. - let debug = - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + let debug = cfg!(feature = "diagnostics") && env_flag("VICTORY_D3D12_DEBUG"); if debug { let mut layer: Option = None; match D3D12GetDebugInterface(&mut layer) { @@ -147,7 +250,7 @@ fn create() -> windows::core::Result { // descriptor heap indices and the like become messages naming // the command instead of page faults. Without state tracking // (directly indexed textures are not transitioned). - if std::env::var_os("VICTORY_D3D12_GBV").is_some() + if env_flag("VICTORY_D3D12_GBV") && let Some(l) = &layer { if let Ok(d1) = l.cast::() { @@ -176,7 +279,7 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + if cfg!(feature = "diagnostics") && env_flag("VICTORY_D3D12_WARP") { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); @@ -248,6 +351,12 @@ fn warp_adapter() -> windows::core::Result { } } +impl Drop for HostList { + fn drop(&mut self) { + self.release_dynamic_slots(); + } +} + #[cfg(test)] mod tests { use super::*; @@ -292,6 +401,9 @@ pub(crate) struct HostList { /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex, + /// Host buffer states the list assumes, by shadow buffer: at its start + /// and at its end, reconciled with each buffer's real state in `prelude`. + buffer_states: Mutex, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -299,6 +411,10 @@ pub(crate) struct HostList { /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Dynamic descriptor slots `(title_heap, first, count)` allocated for + /// this list; released on reset/drop or reclaimed once executed if a heap + /// runs short. + dynamic_slots: DynamicSlotList, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -322,13 +438,14 @@ type States = std::collections::HashMap< (u32, u32, std::sync::Arc), >; +type BufferStates = + std::collections::HashMap)>; + /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| { - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() - }) + *ON.get_or_init(|| cfg!(feature = "diagnostics") && env_flag("VICTORY_D3D12_DRED")) } /// Whether each list of a submission runs and is timed on its own, slow @@ -337,7 +454,7 @@ pub(crate) fn dred_on() -> bool { #[cfg(feature = "diagnostics")] fn timing() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) + *ON.get_or_init(|| env_flag("VICTORY_GPU_TIMING")) } /// Names a host object for the device-removed report, which names the @@ -387,6 +504,81 @@ enum Step { Texture(std::sync::Arc), } +/// A 64-bit memory wait recorded on a command list and satisfied before the +/// list executes on the host GPU. +#[derive(Debug, Clone, Copy)] +struct MemoryWait { + address: usize, + comparison: u32, + reference: u64, +} + +/// Evaluates a D3D12 `D3D12_COMPARISON_FUNC` (`1..=8`) against `current` and +/// `reference`. Unknown/zero codes and `NEVER` return `true` so a malformed +/// comparison never hangs submission. +fn memory_wait_satisfied(current: u64, comparison: u32, reference: u64) -> bool { + match comparison { + 2 => current < reference, + 3 => current == reference, + 4 => current <= reference, + 5 => current > reference, + 6 => current != reference, + 7 => current >= reference, + _ => true, + } +} + +/// Waits outside the submission mutex for `waits` to become satisfied by +/// another queue or the CPU, with a bounded timeout so a dead producer logs +/// once rather than deadlocking forever. +fn wait_for_memory(waits: &[MemoryWait]) { + if waits.is_empty() { + return; + } + const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + let read_u64 = |addr: usize| -> u64 { + let val = if addr.is_multiple_of(8) { + // SAFETY: title memory address recorded by the command list. + unsafe { (*(addr as *const std::sync::atomic::AtomicU64)).load(Ordering::Acquire) } + } else { + // SAFETY: title memory address recorded by the command list. + let v = unsafe { (addr as *const u64).read_unaligned() }; + std::sync::atomic::fence(Ordering::Acquire); + v + }; + val + }; + let satisfied = |w: &MemoryWait| memory_wait_satisfied(read_u64(w.address), w.comparison, w.reference); + if waits.iter().all(satisfied) { + return; + } + let started = std::time::Instant::now(); + let mut spins = 0u32; + while !waits.iter().all(satisfied) { + if started.elapsed() >= TIMEOUT { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let first = waits[0]; + let current = read_u64(first.address); + tracing::warn!( + address = format_args!("{:#x}", first.address), + comparison = first.comparison, + reference = first.reference, + current, + "command-list 64-bit memory wait timed out; continuing" + ); + }); + return; + } + spins += 1; + if spins <= 64 { + std::thread::yield_now(); + } else { + std::thread::sleep(std::time::Duration::from_micros(200)); + } + } +} + /// What a list does on the CPU when it is submitted: copies between host /// memory regions (title buffers, upload buffers and buffer copies), and /// the upload buffers its GPU commands read, kept until the list is reset. @@ -404,9 +596,15 @@ struct Deferred { refreshed: std::collections::HashSet<(usize, usize, usize)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// 64-bit memory waits that must be satisfied before the list runs. + waits: Vec, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, + /// Post-execution callbacks run right after the GPU finishes (e.g. + /// copying resolved query readback data into title memory), before + /// bottom-of-pipe writes signal completion. + after: Vec>, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, } @@ -447,6 +645,116 @@ impl Host { }) } + /// Whether the host supports depth-bounds testing (`OMSetDepthBounds` + /// and `D3D12_DEPTH_STENCIL_DESC1`). + pub(crate) fn depth_bounds(&self) -> bool { + static SUPPORTED: OnceLock = OnceLock::new(); + *SUPPORTED.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + // SAFETY: query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS2, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.DepthBoundsTestSupported.as_bool(); + tracing::info!(supported, "host depth bounds test support"); + supported + }) + } + + /// Maximum shader wave lane count supported by the host GPU (`32` on + /// NVIDIA/Intel, `64` on AMD RDNA/GCN). + pub(crate) fn wave_lane_count_max(&self) -> u32 { + static MAX_LANES: OnceLock = OnceLock::new(); + *MAX_LANES.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let max = if ok && options.WaveLaneCountMax > 0 { + options.WaveLaneCountMax + } else { + 32 + }; + tracing::info!( + min = options.WaveLaneCountMin, + max, + wave_ops = options.WaveOps.as_bool(), + "host GPU wave lane count" + ); + max + }) + } + + /// Host GPU direct queue timestamp frequency in ticks per second. + pub(crate) fn timestamp_frequency(&self) -> Option { + static FREQ: OnceLock> = OnceLock::new(); + *FREQ.get_or_init(|| { + // SAFETY: plain query on our live direct command queue. + let freq = unsafe { self.queue.GetTimestampFrequency() }.ok()?; + (freq > 0).then_some(freq) + }) + } + + /// A mapped buffer in the readback heap (`D3D12_RESOURCE_STATE_COPY_DEST`) + /// for GPU-to-CPU readbacks such as `ResolveQueryData`. + pub(crate) fn readback_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and persistent mapping of a readback buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no readback buffer"); + None + } + } + } + /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result { // SAFETY: plain object creation. @@ -476,9 +784,11 @@ impl Host { deferred: Mutex::default(), scratch: Mutex::default(), states: Mutex::default(), + buffer_states: Mutex::default(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), + dynamic_slots: std::sync::Arc::new(Mutex::new(Vec::new())), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -487,8 +797,25 @@ impl Host { } } - /// Runs closed lists and waits for them. + /// Runs closed lists and waits for them. Splits before any list carrying + /// a 64-bit memory wait so earlier lists in the same submission flush + /// their writes first, and waits outside `self.submitted` so concurrent + /// producer queues can satisfy the wait without deadlocking. pub(crate) fn execute(&self, runs: &[&HostList]) { + let mut start = 0; + while start < runs.len() { + let waits = runs[start].deferred().waits.clone(); + wait_for_memory(&waits); + let mut end = start + 1; + while end < runs.len() && runs[end].deferred().waits.is_empty() { + end += 1; + } + self.execute_batch(&runs[start..end]); + start = end; + } + } + + fn execute_batch(&self, runs: &[&HostList]) { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); @@ -551,6 +878,11 @@ impl Host { } let _ = (i, started); } + COMPLETED_SUBMISSIONS.fetch_add(1, Ordering::Relaxed); + // During long loading screens without presents, reclaim resources + // retired more than 128 completed (fence-waited) submissions ago so + // VRAM stays bounded while still outliving multi-list work. + drain_retired(4, 128); let _ = &firsts; let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); @@ -596,11 +928,29 @@ impl Host { COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); } COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + for list in runs { + for work in &list.deferred().after { + work(); + } + } for list in runs { for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); } } + // These lists have completed execution on the host GPU; register + // their dynamic descriptor slots as reclaimable under heap pressure. + let mut reg = EXECUTED_DYNAMIC.lock().unwrap_or_else(|e| e.into_inner()); + reg.retain(|w| w.strong_count() > 0); + for list in runs { + if !list.dynamic_slots.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { + let weak = std::sync::Arc::downgrade(&list.dynamic_slots); + if !reg.iter().any(|existing| existing.ptr_eq(&weak)) { + reg.push(weak); + } + } + } + drop(reg); self.log_messages(); } @@ -878,8 +1228,13 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + self.release_dynamic_slots(); *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.buffer_states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -923,12 +1278,51 @@ impl HostList { } } - /// At submission: the list that moves each texture this list uses from - /// its real state to the one the list starts with; the textures' real + /// Moves a title buffer's host copy to `wanted` (a host buffer state) in + /// this list. The list's first use of a buffer records nothing: its + /// prelude brings the buffer there at submission. + pub(crate) fn ensure_buffer( + &self, + shadow: &std::sync::Arc, + wanted: u32, + ) { + let before = { + let mut states = self + .buffer_states + .lock() + .unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(shadow) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, shadow.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let prev = std::mem::replace(&mut o.get_mut().1, wanted); + (prev != wanted).then_some(prev) + } + } + }; + if let Some(before) = before { + let barrier = transition( + &shadow.buffer, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + ); + // SAFETY: an open list; `buffer_states` keeps the buffer alive. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + } + + /// At submission: the list that moves each texture and buffer this list + /// uses from its real state to the one the list starts with; their real /// states become those the list ends with. fn prelude(&self) -> Option { let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states + let buffer_states = self + .buffer_states + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut barriers: Vec = states .values() .filter_map(|(first, last, copy)| { let real = copy.state.swap(*last, Ordering::Relaxed); @@ -941,6 +1335,16 @@ impl HostList { }) }) .collect(); + barriers.extend(buffer_states.values().filter_map(|(first, last, shadow)| { + let real = shadow.state.swap(*last, Ordering::Relaxed); + (real != *first).then(|| { + transition( + &shadow.buffer, + D3D12_RESOURCE_STATES(real as i32), + D3D12_RESOURCE_STATES(*first as i32), + ) + }) + })); if barriers.is_empty() { return None; } @@ -1063,6 +1467,33 @@ impl HostList { self.deferred().writes.push((dst as usize, what, bytes)); } + /// Waits for `*(address as *const u64)` to satisfy `comparison` against + /// `reference` before this list executes on the host GPU. + pub(crate) fn defer_wait(&self, address: u64, comparison: u32, reference: u64) { + self.deferred().waits.push(MemoryWait { + address: address as usize, + comparison, + reference, + }); + } + + /// Tracks dynamic descriptor slots allocated while recording this list. + pub(crate) fn record_dynamic(&self, heap: usize, first: u32, n: u32) { + self.dynamic_slots + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((heap, first, n)); + } + + fn release_dynamic_slots(&self) { + let slots = std::mem::take( + &mut *self.dynamic_slots.lock().unwrap_or_else(|e| e.into_inner()), + ); + for (heap, first, n) in slots { + crate::descriptor::release_dynamic(heap, first, n); + } + } + /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// @@ -1153,6 +1584,12 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } + /// Runs `work` right after the list's GPU submission completes, before + /// bottom-of-pipe writes signal completion (used for query readbacks). + pub(crate) fn defer_after(&self, work: impl Fn() + Send + 'static) { + self.deferred().after.push(Box::new(work)); + } + /// Brings a texture's staging buffer up to date when the list is /// submitted, keeping it alive until the list is reset. pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { @@ -1437,6 +1874,227 @@ impl Host { } } +/// Host display HDR capability and luminance bounds, queried once from DXGI +/// (`IDXGIOutput6::GetDesc1`) with optional `VICTORY_HDR` override. +pub fn hdr_info() -> crate::HdrInfo { + static INFO: OnceLock = OnceLock::new(); + *INFO.get_or_init(|| { + if let Some(raw) = std::env::var_os("VICTORY_HDR") { + if !parse_env_flag(Some(&raw)) { + return crate::HdrInfo::default(); + } + return crate::HdrInfo { + supported: true, + min_nits: 0.005, + max_nits: 1000.0, + max_full_frame_nits: 400.0, + }; + } + detect_hdr_output().unwrap_or_default() + }) +} + +fn detect_hdr_output() -> Option { + // SAFETY: read-only DXGI adapter/output enumeration. + unsafe { + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter = factory.EnumAdapters1(0).ok()?; + let output = adapter.EnumOutputs(0).ok()?; + let output6: IDXGIOutput6 = output.cast().ok()?; + let desc = output6.GetDesc1().ok()?; + let supported = desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; + let info = crate::HdrInfo { + supported, + min_nits: desc.MinLuminance.max(0.0), + max_nits: if desc.MaxLuminance > 0.0 { + desc.MaxLuminance + } else { + 1000.0 + }, + max_full_frame_nits: if desc.MaxFullFrameLuminance > 0.0 { + desc.MaxFullFrameLuminance + } else { + 400.0 + }, + }; + tracing::info!(?info, color_space = desc.ColorSpace.0, "host display HDR probe"); + Some(info) + } +} + +/// Maps a presented texture format to a concrete SRV format usable by the +/// present-scaling blitter (resolving typeless and sRGB swapchain formats). +fn present_srv_format(format: DXGI_FORMAT) -> Option { + Some(match format.0 { + 27 | 28 => DXGI_FORMAT_R8G8B8A8_UNORM, + 29 => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + 87 | 90 => DXGI_FORMAT_B8G8R8A8_UNORM, + 91 => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + 23 | 24 => DXGI_FORMAT_R10G10B10A2_UNORM, + 9 | 10 => DXGI_FORMAT_R16G16B16A16_FLOAT, + _ => return None, + }) +} + +/// Swap chain color space matching the presented back-buffer format. +fn swap_color_space(format: DXGI_FORMAT, hdr: bool) -> DXGI_COLOR_SPACE_TYPE { + match format { + DXGI_FORMAT_R10G10B10A2_UNORM if hdr => DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, + DXGI_FORMAT_R16G16B16A16_FLOAT => DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, + _ => DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, + } +} + +/// Fullscreen bilinear scaling & format-conversion blit pipeline used when +/// presenting a texture whose resolution or format differs from the swap chain. +struct Blitter { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + pso_format: DXGI_FORMAT, + srv_heap: ID3D12DescriptorHeap, +} + +impl Blitter { + fn new(device: &ID3D12Device, rtv_format: DXGI_FORMAT) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::core::PCSTR; + + const HLSL: &[u8] = b"\ +Texture2D src : register(t0); +SamplerState lin : register(s0); +struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; }; +VSOut vs(uint id : SV_VertexID) { + VSOut o; + float2 uv = float2((id << 1) & 2, id & 2); + o.uv = uv; + o.pos = float4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0); + return o; +} +float4 ps(VSOut i) : SV_Target { + return src.Sample(lin, i.uv); +} +"; + let compile = |entry: &std::ffi::CStr, target: &std::ffi::CStr| -> windows::core::Result { + let mut blob: Option = None; + // SAFETY: compiling static HLSL source via `d3dcompiler_47.dll`. + unsafe { + D3DCompile( + HLSL.as_ptr().cast(), + HLSL.len(), + PCSTR::null(), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut blob, + None, + )?; + } + blob.ok_or_else(windows::core::Error::empty) + }; + let vs = compile(c"vs", c"vs_5_0")?; + let ps = compile(c"ps", c"ps_5_0")?; + + let range = D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + }; + let param = D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: &range, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }; + let sampler = D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + ..Default::default() + }; + let rs_desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: 1, + pParameters: ¶m, + NumStaticSamplers: 1, + pStaticSamplers: &sampler, + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }, + }, + }; + let mut rs_blob: Option = None; + // SAFETY: serializing valid root signature description and creating root signature + PSO + heap. + unsafe { + D3D12SerializeVersionedRootSignature(&rs_desc, &mut rs_blob, None)?; + let rs_blob = rs_blob.ok_or_else(windows::core::Error::empty)?; + let rs_bytes = std::slice::from_raw_parts( + rs_blob.GetBufferPointer().cast::(), + rs_blob.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, rs_bytes)?; + + let mut pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.GetBufferPointer(), + BytecodeLength: vs.GetBufferSize(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.GetBufferPointer(), + BytecodeLength: ps.GetBufferSize(), + }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RTVFormats[0] = rtv_format; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&pso_desc)?; + + let srv_heap: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + + Ok(Self { + root, + pso, + pso_format: rtv_format, + srv_heap, + }) + } + } +} + /// The swap chain formats a presented texture can be copied into: its own /// family's. fn swap_format(format: DXGI_FORMAT) -> Option { @@ -1456,9 +2114,11 @@ struct Presenter { width: u32, height: u32, format: DXGI_FORMAT, + color_space: DXGI_COLOR_SPACE_TYPE, copy: HostList, hwnd: HWND, meter: Meter, + blitter: Option, } /// The frame rate, shown in the window's caption every second and logged @@ -1584,10 +2244,10 @@ impl Host { tracing::warn!(format = desc.Format.0, "cannot present this format"); return None; }; - let (width, height) = (desc.Width as u32, desc.Height); + let (tex_width, tex_height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); if presenter.is_none() { - *presenter = match self.presenter(width, height, format) { + *presenter = match self.presenter(tex_width, tex_height, format) { Ok(p) => Some(p), Err(e) => { tracing::warn!(error = %e, "no swap chain"); @@ -1596,6 +2256,29 @@ impl Host { }; } let p = presenter.as_mut()?; + // Track the window's client size so presented frames scale cleanly to + // resized windows or dynamic render resolutions. + let (target_width, target_height) = { + let mut rect = RECT::default(); + // SAFETY: live window handle. + let ok = unsafe { GetClientRect(p.hwnd, &mut rect) }.is_ok(); + let cw = rect.right.saturating_sub(rect.left) as u32; + let ch = rect.bottom.saturating_sub(rect.top) as u32; + if ok && cw > 0 && ch > 0 { + (cw, ch) + } else { + (tex_width, tex_height) + } + }; + let can_scale = desc.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0 + && present_srv_format(desc.Format).is_some(); + let (width, height) = if can_scale { + (target_width, target_height) + } else { + (tex_width, tex_height) + }; + let hdr = hdr_info().supported; + let desired_space = swap_color_space(format, hdr); if (p.width, p.height, p.format) != (width, height, format) { // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { @@ -1610,6 +2293,31 @@ impl Host { } } } + if p.color_space != desired_space { + // SAFETY: live swap chain; ignore unsupported color spaces gracefully. + if unsafe { p.swap_chain.SetColorSpace1(desired_space) }.is_ok() { + p.color_space = desired_space; + tracing::info!( + format = format.0, + color_space = desired_space.0, + "swap chain color space updated" + ); + } + } + let need_blit = (tex_width, tex_height) != (width, height); + if need_blit + && p.blitter + .as_ref() + .is_none_or(|b| b.pso_format != format) + { + p.blitter = match Blitter::new(&self.device, format) { + Ok(b) => Some(b), + Err(e) => { + tracing::warn!(error = %e, "present scaling blitter unavailable"); + None + } + }; + } let state = D3D12_RESOURCE_STATES(state as i32); // SAFETY: our swap chain, list and a live source texture. unsafe { @@ -1619,38 +2327,160 @@ impl Host { }; p.copy.reset(); let list = &p.copy.list; - list.ResourceBarrier(&[ - transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition( - &back, - D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_COPY_DEST, - ), - ]); - list.CopyResource(&back, texture); + let used_blit = if need_blit + && let Some(blitter) = &p.blitter + && let Some(srv_fmt) = present_srv_format(desc.Format) + { + let rtv = self.rtv(&back, None); + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: srv_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + self.device.CreateShaderResourceView( + texture, + Some(&srv_desc), + blitter.srv_heap.GetCPUDescriptorHandleForHeapStart(), + ); + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ), + ]); + let vp = D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }; + let scissor = RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }; + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[vp]); + list.RSSetScissorRects(&[scissor]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetGraphicsRootSignature(&blitter.root); + list.SetPipelineState(&blitter.pso); + list.SetDescriptorHeaps(&[Some(blitter.srv_heap.clone())]); + list.SetGraphicsRootDescriptorTable( + 0, + blitter.srv_heap.GetGPUDescriptorHandleForHeapStart(), + ); + list.DrawInstanced(3, 1, 0, 0); + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + true + } else { + false + }; #[cfg(feature = "diagnostics")] - let capture = crate::capture::wanted(frame) - .then(|| crate::capture::read_back(&self.device, list, texture)) - .flatten(); + let mut capture = None; #[cfg(feature = "diagnostics")] - let probe = crate::capture::probe(&self.device, list, texture); + let mut probe = None; + if !used_blit { + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + ), + ]); + if (tex_width, tex_height) == (width, height) { + list.CopyResource(&back, texture); + } else { + let src_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&back), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let copy_box = D3D12_BOX { + left: 0, + top: 0, + front: 0, + right: tex_width.min(width), + bottom: tex_height.min(height), + back: 1, + }; + list.CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, Some(©_box)); + } + #[cfg(feature = "diagnostics")] + { + capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + probe = crate::capture::probe(&self.device, list, texture); + } + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + } else { + #[cfg(feature = "diagnostics")] + { + list.ResourceBarrier(&[transition( + texture, + state, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + probe = crate::capture::probe(&self.device, list, texture); + list.ResourceBarrier(&[transition( + texture, + D3D12_RESOURCE_STATE_COPY_SOURCE, + state, + )]); + } + } #[cfg(not(feature = "diagnostics"))] let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( - &back, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PRESENT, - ), - ]); p.copy.close(); self.execute(&[&p.copy]); #[cfg(feature = "diagnostics")] - if let Some((buffer, footprint)) = capture { - crate::capture::save_read_back(frame, &buffer, &footprint); + if let Some((buffer, footprint, total)) = capture { + crate::capture::save_read_back(frame, &buffer, &footprint, total); } let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + COMPLETED_FRAMES.fetch_add(1, Ordering::Relaxed); + drain_retired(4, 128); p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); @@ -1688,17 +2518,28 @@ impl Host { let swap_chain = factory .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? .cast::()?; + let hdr = hdr_info().supported; + let color_space = swap_color_space(format, hdr); + let _ = swap_chain.SetColorSpace1(color_space); let copy = self.new_list()?; copy.close(); - tracing::info!(width, height, format = format.0, "presenting to a window"); + tracing::info!( + width, + height, + format = format.0, + color_space = color_space.0, + "presenting to a window" + ); Ok(Presenter { swap_chain, width, height, format, + color_space, copy, hwnd, meter: Meter::new(), + blitter: None, }) } } @@ -2042,4 +2883,44 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at before.as_secs_f64() / after.as_secs_f64() ); } + + #[test] + fn env_flag_respects_falsy_values() { + use std::ffi::OsStr; + for off in [None, Some(""), Some(" "), Some("0"), Some("false"), Some("FALSE"), Some("no"), Some("Off")] { + assert!(!super::parse_env_flag(off.map(OsStr::new)), "expected off for {off:?}"); + } + for on in ["1", "true", "yes", "on", "anything"] { + assert!(super::parse_env_flag(Some(OsStr::new(on))), "expected on for {on:?}"); + } + } + + #[test] + fn memory_wait_comparisons_and_producer_wakeup() { + assert!(super::memory_wait_satisfied(1, 2, 2)); // LESS + assert!(!super::memory_wait_satisfied(2, 2, 2)); + assert!(super::memory_wait_satisfied(5, 3, 5)); // EQUAL + assert!(!super::memory_wait_satisfied(4, 3, 5)); + assert!(super::memory_wait_satisfied(5, 4, 5)); // LESS_EQUAL + assert!(super::memory_wait_satisfied(6, 5, 5)); // GREATER + assert!(super::memory_wait_satisfied(4, 6, 5)); // NOT_EQUAL + assert!(super::memory_wait_satisfied(5, 7, 5)); // GREATER_EQUAL + assert!(!super::memory_wait_satisfied(4, 7, 5)); + assert!(super::memory_wait_satisfied(0, 8, 99)); // ALWAYS + + let cell = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let producer = cell.clone(); + let addr = std::sync::Arc::as_ptr(&cell) as usize; + let t = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(5)); + producer.store(42, std::sync::atomic::Ordering::Release); + }); + super::wait_for_memory(&[super::MemoryWait { + address: addr, + comparison: 7, // GREATER_EQUAL + reference: 42, + }]); + t.join().unwrap(); + assert_eq!(cell.load(std::sync::atomic::Ordering::Acquire), 42); + } } diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index c0236d8229..ff733693a9 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -16,12 +16,15 @@ //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. +use std::sync::Arc; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::core::s; -use crate::host::{HostList, host, transition}; +use crate::host::{HostList, host}; +use crate::shadow::Shadow; const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" @@ -141,12 +144,13 @@ fn make() -> windows::core::Result { /// Records, in `list`, the clamp of `records` records of `kind` (PC /// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. +/// `args`, and leaves the buffer in `GENERIC_READ` ready to be read as +/// indirect arguments (or vertex/index/shader data). Replaces the list's +/// compute root signature and pipeline (callers bind theirs after). False +/// if the clamp is not available. pub(crate) fn bound( list: &HostList, - buffer: &ID3D12Resource, + args: &Arc, gpu: u64, (kind, stride, records): (u32, u32, u32), ) -> bool { @@ -156,6 +160,7 @@ pub(crate) fn bound( if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { return false; } + list.ensure_buffer(args, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32); let l = &list.list; let constants = [kind, stride, records, 0]; // SAFETY: an open list; our root signature, pipeline and a live buffer @@ -169,31 +174,12 @@ pub(crate) fn bound( l.SetComputeRootUnorderedAccessView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); l.Dispatch(records.div_ceil(64), 1, 1); - l.ResourceBarrier(&[ - uav_barrier(), - transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), - ]); + l.ResourceBarrier(&[uav_barrier()]); } + list.ensure_buffer(args, D3D12_RESOURCE_STATE_GENERIC_READ.0 as u32); true } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { - // SAFETY: an open list and a live buffer. - unsafe { - list.list.ResourceBarrier(&[transition( - buffer, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]) - }; -} - fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index f91782d941..c1e0f19241 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -52,7 +52,25 @@ mod texture; #[cfg(windows)] mod watch; +/// Host display HDR capability and luminance bounds (in nits), queried from +/// DXGI (`IDXGIOutput6`) and surfaced to `victory-hle` (`XDisplayTryEnableHdrMode`). +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct HdrInfo { + pub supported: bool, + pub min_nits: f32, + pub max_nits: f32, + pub max_full_frame_nits: f32, +} + #[cfg(windows)] -pub use host::on_failure; +pub use host::{hdr_info, on_failure}; #[cfg(windows)] -pub use watch::{title_memory_remapped, writing as kernel_will_write}; +pub use watch::{physical_memory_written, title_memory_remapped, writing as kernel_will_write}; + +#[cfg(not(windows))] +pub fn physical_memory_written() {} + +#[cfg(not(windows))] +pub fn hdr_info() -> HdrInfo { + HdrInfo::default() +} diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d736e2..9a588aa66b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -446,6 +446,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + if crate::texture::title_written(from) { + crate::texture::upload(list, src, from); + } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); @@ -535,6 +538,9 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } @@ -630,7 +636,11 @@ extern "system" fn resolve( unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); let format = DXGI_FORMAT(format as i32); - if (a.Width, a.Height) == (b.Width, b.Height) { + let dst_mip = dst_sub % u32::from(a.MipLevels.max(1)); + let src_mip = src_sub % u32::from(b.MipLevels.max(1)); + let (aw, ah) = ((a.Width >> dst_mip).max(1), (a.Height >> dst_mip).max(1)); + let (bw, bh) = ((b.Width >> src_mip).max(1), (b.Height >> src_mip).max(1)); + if (aw, ah) == (bw, bh) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { @@ -638,8 +648,8 @@ extern "system" fn resolve( let rect = RECT { left: 0, top: 0, - right: a.Width.min(b.Width) as i32, - bottom: a.Height.min(b.Height) as i32, + right: aw.min(bw) as i32, + bottom: ah.min(bh) as i32, }; list1.ResolveSubresourceRegion( to, @@ -793,33 +803,107 @@ extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { } } -/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when -/// resolved. -extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} - -/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes -/// each query's result into the buffer once the list has run. Timestamps -/// (type 2) are the GPU clock then; occlusion counts (0) say a million -/// samples passed and binary occlusion (1) visible, so nothing is culled -/// by a query. -/// shortcut: no query runs on the host GPU; results are plausible values, -/// not measured ones (time spans come out as the submission's length). +/// `BeginQuery(heap, type, index)`: forwards to the host `ID3D12QueryHeap` +/// when available. +extern "system" fn begin_query(this: This, heap: This, kind: u32, index: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some((host_heap, count)) = crate::query::host_heap(heap) + && let Some((host_kind, _)) = crate::query::query_type_info(kind) + && index < count + { + use windows::Win32::Graphics::Direct3D12::D3D12_QUERY_TYPE; + // SAFETY: open host command list and live query heap with in-bounds index. + unsafe { + list.list + .BeginQuery(&host_heap, D3D12_QUERY_TYPE(host_kind), index) + }; + list.keep(&host_heap); + } + #[cfg(not(windows))] + let _ = (this, heap, kind, index); +} + +/// `EndQuery(heap, type, index)`: forwards to the host `ID3D12QueryHeap` +/// when available. +extern "system" fn end_query(this: This, heap: This, kind: u32, index: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some((host_heap, count)) = crate::query::host_heap(heap) + && let Some((host_kind, _)) = crate::query::query_type_info(kind) + && index < count + { + use windows::Win32::Graphics::Direct3D12::D3D12_QUERY_TYPE; + // SAFETY: open host command list and live query heap with in-bounds index. + unsafe { + list.list + .EndQuery(&host_heap, D3D12_QUERY_TYPE(host_kind), index) + }; + list.keep(&host_heap); + } + #[cfg(not(windows))] + let _ = (this, heap, kind, index); +} + +/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: resolves real +/// GPU query results from the host `ID3D12QueryHeap` into a readback buffer +/// and copies them into title memory once the submission completes, falling +/// back to plausible synthetic values when headless or for unsupported query +/// types. extern "system" fn resolve_queries( this: This, - _heap: This, + heap: This, kind: u32, - _first: u32, + first: u32, count: u32, buffer: This, offset: u64, ) { + let Some((data, size)) = crate::resource::buffer_bytes(buffer) else { + return; + }; + if count == 0 { + return; + } + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some(host) = crate::host::host() + && let Some((host_heap, heap_count)) = crate::query::host_heap(heap) + && let Some((host_kind, stride)) = crate::query::query_type_info(kind) + && first.checked_add(count).is_some_and(|end| end <= heap_count) + && let Some(total) = u64::from(count).checked_mul(stride) + && offset.checked_add(total).is_some_and(|end| end <= size) + && let Some((rb_buf, rb_ptr)) = host.readback_buffer(total) + { + use windows::Win32::Graphics::Direct3D12::D3D12_QUERY_TYPE; + // SAFETY: open list, live query heap, and readback buffer large enough for `total` bytes. + unsafe { + list.list.ResolveQueryData( + &host_heap, + D3D12_QUERY_TYPE(host_kind), + first, + count, + &rb_buf, + 0, + ); + } + list.keep(&host_heap); + list.keep(&rb_buf); + let dst = data as usize + offset as usize; + let src = rb_ptr as usize; + let len = total as usize; + list.defer_after(move || { + crate::watch::writing(dst, len); + crate::host::write_mapped(dst as *mut u8, src as *const u8, len); + }); + return; + } + #[cfg(not(windows))] + let _ = (heap, first); const OCCLUSION: u32 = 0; const BINARY: u32 = 1; const TIMESTAMP: u32 = 2; const PIPELINE_STATISTICS: u32 = 3; - let Some((data, size)) = crate::resource::buffer_bytes(buffer) else { - return; - }; let (what, bytes) = match kind { OCCLUSION => (Written::Value(1 << 20), 8), BINARY => (Written::Value(1), 8), @@ -947,6 +1031,11 @@ mod state { crate::draw::stencil_ref(list, reference); } } + pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { + if let Some(list) = host_list(this) { + crate::draw::depth_bounds(list, min, max); + } + } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); } @@ -1007,7 +1096,11 @@ mod state { views: *const VertexView, ) { with_state(this, |_, s| { - s.set_vertex_buffers(start, items(views, count)) + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } }); } /// `(count, handles, one range, depth)`: with one range, the handles @@ -1102,6 +1195,7 @@ mod state { pub(super) use super::ignored_state as compute_constants; pub(super) use super::ignored_state as compute_table; pub(super) use super::ignored_state as compute_view; + pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as graphics_constant; pub(super) use super::ignored_state as graphics_constants; pub(super) use super::ignored_state as graphics_table; @@ -1212,29 +1306,121 @@ pub(crate) fn take_counts() -> (u64, u64) { (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) } -/// A GPU wait for a memory value `(address, comparison, reference, ...)`. -/// Lists run one after another and to completion, so a value another queue -/// or the CPU has to write first cannot be waited for; nothing to do. -extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} - -/// The enhanced barriers `(group count, groups)`: buffer, texture and -/// global barriers with layouts instead of states. Every host use of a -/// title texture (clears, copies) moves its host copy to the state it needs -/// first, so only their ordering matters: one barrier on every shader -/// write (the title's buffer barriers order compute passes). -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { +/// A GPU wait for a 64-bit memory value `(address, comparison, reference)`: +/// recorded on the list and awaited at submission time before the list's +/// host work runs, so cross-queue and CPU producers can satisfy it first. +extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) { + if address == 0 { + return; + } + #[cfg(windows)] + if let Some(list) = host_list(this) { + list.defer_wait(address, comparison, reference); + } + #[cfg(not(windows))] + let _ = (this, address, comparison, reference); +} + +#[cfg(windows)] +#[repr(C)] +struct BarrierGroup { + kind: u32, + count: u32, + barriers: *const c_void, +} + +#[cfg(windows)] +#[repr(C)] +struct TextureBarrier { + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, + layout_before: i32, + layout_after: i32, + resource: This, + subresources: [u32; 6], + flags: u32, +} + +/// Maps an enhanced-barrier `D3D12_BARRIER_LAYOUT` to the equivalent legacy +/// host `D3D12_RESOURCE_STATES` mask (`None` for `UNDEFINED` or unknown). +#[cfg(any(windows, test))] +fn enhanced_layout_state(layout: i32) -> Option { + Some(match layout { + 0 | 18 | 24 => 0, // COMMON / PRESENT + 1 | 19 | 25 => 0x8C0, // GENERIC_READ (SRV + COPY_SOURCE) + 2 => 0x4, // RENDER_TARGET + 3 | 20 | 26 => 0x8, // UNORDERED_ACCESS + 4 => 0x10, // DEPTH_STENCIL_WRITE + 5 => 0x20, // DEPTH_STENCIL_READ + 6 | 21 | 27 => 0xC0, // SHADER_RESOURCE (PS | NON_PS) + 7 | 22 | 28 => 0x800, // COPY_SOURCE + 8 | 23 | 29 => 0x400, // COPY_DEST + 9 => 0x2000, // RESOLVE_SOURCE + 10 => 0x1000, // RESOLVE_DEST + 11 => 0x0100_0000, // SHADING_RATE_SOURCE + _ => return None, + }) +} + +/// The enhanced barriers `(group count, groups)`: translates texture layout +/// transitions through [`ensure_state`] so host textures stay in the right +/// state for direct-indexed reads and cross-list `prelude` tracking, and emits +/// a global UAV barrier for global/buffer/UAV groups. +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { #[cfg(windows)] if count > 0 && let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + const GLOBAL: u32 = 0; + const TEXTURE: u32 = 1; + const BUFFER: u32 = 2; + const ACCESS_UAV: u32 = 0x80; + let mut need_uav = groups.is_null(); + if !groups.is_null() { + // SAFETY: the title passes `count` contiguous `D3D12_BARRIER_GROUP` entries. + let slice = unsafe { std::slice::from_raw_parts(groups.cast::(), count as usize) }; + for group in slice { + match group.kind { + TEXTURE if !group.barriers.is_null() && group.count > 0 => { + // SAFETY: the group points at `group.count` texture barriers. + let textures = unsafe { + std::slice::from_raw_parts( + group.barriers.cast::(), + group.count as usize, + ) + }; + for tb in textures { + if !tb.resource.is_null() + && let Some(state) = enhanced_layout_state(tb.layout_after) + { + ensure_state(list, tb.resource, state); + } + if (tb.access_before | tb.access_after) & ACCESS_UAV != 0 + || matches!(tb.layout_before, 3 | 20 | 26) + || matches!(tb.layout_after, 3 | 20 | 26) + { + need_uav = true; + } + } + } + GLOBAL | BUFFER => need_uav = true, + _ => need_uav = true, + } + } + } + if need_uav { + // SAFETY: the same layout; no resource named. + let barrier = + unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } } #[cfg(not(windows))] - let _ = (this, count); + let _ = (this, count, groups); } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and @@ -1315,7 +1501,7 @@ const METHODS: [(usize, *const ()); 52] = [ (52, clear_rtv as *const ()), // 0x1a0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 - (68, ignored_state as *const ()), // 0x220 depth bounds + (68, state::depth_bounds as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 (71, wait_value as *const ()), // 0x238, 32 bits @@ -1328,8 +1514,8 @@ const METHODS: [(usize, *const ()); 52] = [ ]; /// The rest of [`METHODS`], kept apart only to stay readable. const MORE_METHODS: [(usize, *const ()); 9] = [ - (28, query_mark as *const ()), // 0xe0 BeginQuery - (29, query_mark as *const ()), // 0xe8 EndQuery + (28, begin_query as *const ()), // 0xe0 BeginQuery + (29, end_query as *const ()), // 0xe8 EndQuery (30, resolve_queries as *const ()), // 0xf0 (78, dispatch_x as *const ()), // 0x270 (98, state::dispatch_mesh_x as *const ()), // 0x310 @@ -1434,4 +1620,19 @@ mod tests { assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } + + #[test] + fn enhanced_barrier_layouts_map_to_legacy_states() { + assert_eq!(enhanced_layout_state(0), Some(0)); // COMMON + assert_eq!(enhanced_layout_state(2), Some(0x4)); // RENDER_TARGET + assert_eq!(enhanced_layout_state(3), Some(0x8)); // UNORDERED_ACCESS + assert_eq!(enhanced_layout_state(4), Some(0x10)); // DEPTH_STENCIL_WRITE + assert_eq!(enhanced_layout_state(5), Some(0x20)); // DEPTH_STENCIL_READ + assert_eq!(enhanced_layout_state(6), Some(0xC0)); // SHADER_RESOURCE + assert_eq!(enhanced_layout_state(7), Some(0x800)); // COPY_SOURCE + assert_eq!(enhanced_layout_state(8), Some(0x400)); // COPY_DEST + assert_eq!(enhanced_layout_state(21), Some(0xC0)); // DIRECT_QUEUE_SHADER_RESOURCE + assert_eq!(enhanced_layout_state(26), Some(0x8)); // COMPUTE_QUEUE_UNORDERED_ACCESS + assert_eq!(enhanced_layout_state(-1), None); // UNDEFINED + } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa10c..05395b32ed 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -8,7 +8,7 @@ use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use victory_shader::emit::{CONST_VIEW_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -24,6 +24,7 @@ pub(crate) struct GraphicsState { sample_mask: u32, rasterizer: D3D12_RASTERIZER_DESC, depth: D3D12_DEPTH_STENCIL_DESC, + depth_bounds: bool, /// Input elements, their names pointing into `names`. inputs: Vec, names: Vec, @@ -75,6 +76,7 @@ impl Default for GraphicsState { BackFace: keep, ..Default::default() }, + depth_bounds: false, inputs: Vec::new(), names: Vec::new(), strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, @@ -103,11 +105,11 @@ impl GraphicsState { 8 => self.blend = data.cast::().read_unaligned(), 9 => self.sample_mask = data.cast::().read_unaligned(), 10 => self.rasterizer = data.cast::().read_unaligned(), - 11 => self.depth = data.cast::().read_unaligned(), + 11 => { + self.depth = data.cast::().read_unaligned(); + self.depth_bounds = false; + } 21 => { - // shortcut: the depth bounds test is dropped (the host - // pipeline uses the plain description); bring it back - // with a stream if a title enables it. let d = data.cast::().read_unaligned(); self.depth = D3D12_DEPTH_STENCIL_DESC { DepthEnable: d.DepthEnable, @@ -119,6 +121,7 @@ impl GraphicsState { FrontFace: d.FrontFace, BackFace: d.BackFace, }; + self.depth_bounds = d.DepthBoundsTestEnable.as_bool(); } 12 => { let layout = at.add(8).cast::().read_unaligned(); @@ -184,11 +187,12 @@ impl GraphicsState { }) .collect(); format!( - "{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}", + "{:?} {} {:?} {:?} {} {inputs:?} {} {} {:?} {} {:?}", self.blend, self.sample_mask, self.rasterizer, self.depth, + self.depth_bounds, self.strip_cut.0, self.topology.0, self.targets, @@ -204,7 +208,8 @@ impl GraphicsState { .fold(0, |m, e| m | 1 << e.InputSlot.min(31)) } - /// The input elements with their byte offsets worked out. + /// The input elements with their byte offsets worked out, aligning + /// `D3D12_APPEND_ALIGNED_ELEMENT` to `min(4, element_bytes)` as D3D12 does. fn elements(&self) -> Vec { let mut next = [0u32; 32]; self.inputs @@ -212,13 +217,19 @@ impl GraphicsState { .map(|e| { let slot = e.InputSlot.min(31) as usize; let format = e.Format.0 as u32; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + let align = bytes.clamp(1, 4); let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { - next[slot] + let rem = next[slot] % align; + if rem == 0 { + next[slot] + } else { + next[slot].saturating_add(align - rem) + } } else { e.AlignedByteOffset }; - let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); - next[slot] = offset + bytes; + next[slot] = offset.saturating_add(bytes); Input { slot: slot as u32, offset, @@ -243,14 +254,29 @@ pub(crate) struct Input { const RECTANGLES: i32 = 19; const QUADS: i32 = 32; +/// How a stage's user-data block is bound in the host root signature: +/// inline 32-bit root constants normally, or a 2-DWORD root CBV when inline +/// constants would exceed D3D12's 64-DWORD root signature limit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum UserDataBinding { + Constants { param: u32, dwords: u32 }, + RootCbv { param: u32, dwords: u32 }, +} + /// One stage of a host pipeline and where its bindings go. pub(crate) struct Stage { pub(crate) shader: Arc, - /// The root parameter of its user data, and its size in dwords. - pub(crate) user_data: Option<(u32, u32)>, + /// The root parameter of its user data, and whether it is inline or spilled. + pub(crate) user_data: Option, /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + pub(crate) root_uavs: Vec<(u8, u32)>, + /// Root parameters of 64-bit addresses carried in adjacent root constants: + /// (title root parameter slot, low constant dword, our root parameter). + pub(crate) const_cbvs: Vec<(u8, u32, u32)>, + pub(crate) const_srvs: Vec<(u8, u32, u32)>, + pub(crate) const_uavs: Vec<(u8, u32, u32)>, } impl Stage { @@ -297,17 +323,21 @@ impl HostPipeline { [cs] if cs.stage == "compute" => Some(cs), _ => None, }; + // An NGG geometry stage (`HwStage::Gs`) translates as a mesh stage (`ms_6_6`). + let ngg_gs = find("geometry") + .filter(|g| g.translated().is_some_and(|t| t.host.stage == victory_shader::HwStage::Gs)); if compute.is_none() - && shaders - .iter() - .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh")) + && shaders.iter().any(|s| { + !matches!(s.stage, "vertex" | "pixel" | "mesh") + && !(s.stage == "geometry" && ngg_gs.is_some()) + }) { return refuse( - "only vertex, mesh, pixel and compute stages are translated", + "only vertex, mesh, NGG geometry, pixel and compute stages are translated", shaders, ); } - let mesh = find("mesh"); + let mesh = find("mesh").or(ngg_gs); let stages = if let Some(cs) = compute { vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] } else { @@ -328,32 +358,87 @@ impl HostPipeline { } let host = host()?; + // Decide whether any stage's user-data root constants must spill to a + // 2-DWORD root CBV to stay within D3D12's 64-DWORD root signature cap. + const MAX_ROOT_DWORDS: u32 = 64; + let stage_dwords: Vec = stages + .iter() + .map(|(s, _)| s.translated().unwrap().host.user_data_dwords()) + .collect(); + let fixed_dwords: u32 = stages + .iter() + .map(|(s, _)| { + let t = &s.translated().unwrap().host; + 2 * (t.root_cbvs.len() + + t.root_srvs.len() + + t.root_uavs.len() + + t.const_cbvs.len() + + t.const_srvs.len() + + t.const_uavs.len()) as u32 + }) + .sum(); + let mut spilled = vec![false; stages.len()]; + let mut total_dwords = fixed_dwords + stage_dwords.iter().sum::(); + if total_dwords > MAX_ROOT_DWORDS { + let mut order: Vec = (0..stages.len()).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(stage_dwords[i])); + for i in order { + if total_dwords <= MAX_ROOT_DWORDS { + break; + } + if stage_dwords[i] > 2 { + spilled[i] = true; + total_dwords -= stage_dwords[i] - 2; + } + } + } + // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); - for &(shader, visibility) in &stages { + for (stage_index, &(shader, visibility)) in stages.iter().enumerate() { let t = &shader.translated()?.host; let mut stage = Stage { shader: shader.clone(), user_data: None, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + const_cbvs: Vec::new(), + const_srvs: Vec::new(), + const_uavs: Vec::new(), }; - let dwords = t.user_data_dwords(); + let dwords = stage_dwords[stage_index]; if dwords > 0 { - stage.user_data = Some((params.len() as u32, dwords)); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: USER_DATA_SPACE, - Num32BitValues: dwords, + let param = params.len() as u32; + if spilled[stage_index] { + stage.user_data = Some(UserDataBinding::RootCbv { param, dwords }); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_CBV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, + }, }, - }, - ShaderVisibility: visibility, - }); + ShaderVisibility: visibility, + }); + } else { + stage.user_data = Some(UserDataBinding::Constants { param, dwords }); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); + } } for (slots, kind, out) in [ ( @@ -366,6 +451,11 @@ impl HostPipeline { D3D12_ROOT_PARAMETER_TYPE_SRV, &mut stage.root_srvs, ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), ] { for &slot in slots { out.push((slot, params.len() as u32)); @@ -382,6 +472,38 @@ impl HostPipeline { }); } } + for (views, kind, out) in [ + ( + &t.const_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.const_cbvs, + ), + ( + &t.const_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.const_srvs, + ), + ( + &t.const_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.const_uavs, + ), + ] { + for &cv in views { + out.push((cv.slot, cv.dword, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: cv.register, + RegisterSpace: CONST_VIEW_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { Filter: D3D12_FILTER(s.filter as i32), @@ -457,6 +579,7 @@ impl HostPipeline { return refuse("graphics state not kept (plain description)", shaders); }; let state = g.describe(); + let use_depth_bounds = g.depth_bounds && host.depth_bounds(); if mesh.is_some() { let name = super::library::name( "mesh", @@ -464,7 +587,15 @@ impl HostPipeline { &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, ); - let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, &name) { + let pso = match mesh_pipeline( + &host.device, + &root, + code(0), + code(1), + g, + use_depth_bounds, + &name, + ) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -486,45 +617,49 @@ impl HostPipeline { }); } - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - // SAFETY: a borrowed pointer the description never releases. - pRootSignature: unsafe { std::mem::transmute_copy(&root) }, - VS: code(0), - PS: code(1), - BlendState: g.blend, - SampleMask: g.sample_mask, - RasterizerState: g.rasterizer, - DepthStencilState: g.depth, - InputLayout: D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: g.inputs.as_ptr(), - NumElements: g.inputs.len() as u32, - }, - IBStripCutValue: g.strip_cut, - // The console's rectangle and quad types draw as triangles on - // the host (see `draw`). - PrimitiveTopologyType: match g.topology.0 { - RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - _ => g.topology, - }, - NumRenderTargets: g.targets.NumRenderTargets, - RTVFormats: g.targets.RTFormats, - DSVFormat: g.depth_format, - SampleDesc: g.samples, - ..Default::default() - }; let name = super::library::name( "graphics", &root_blob, &[&code_bytes(&code(0)), &code_bytes(&code(1))], &state, ); - let made = super::library::pipeline( - &name, - // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, - // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, - ); + let made = if use_depth_bounds { + graphics_pipeline_depth_bounds(&host.device, &root, code(0), code(1), g, &name) + } else { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(0), + PS: code(1), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: g.inputs.as_ptr(), + NumElements: g.inputs.len() as u32, + }, + IBStripCutValue: g.strip_cut, + // The console's rectangle and quad types draw as triangles on + // the host (see `draw`). + PrimitiveTopologyType: match g.topology.0 { + RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + _ => g.topology, + }, + NumRenderTargets: g.targets.NumRenderTargets, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, + ) + }; let pso = match made { Ok(pso) => pso, Err(e) => { @@ -557,6 +692,92 @@ impl HostPipeline { } } +/// A stream subobject: its type, then its description, pointer-aligned. +#[repr(C, align(8))] +struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + +fn depth_stencil1(g: &GraphicsState, enabled: bool) -> D3D12_DEPTH_STENCIL_DESC1 { + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: g.depth.DepthEnable, + DepthWriteMask: g.depth.DepthWriteMask, + DepthFunc: g.depth.DepthFunc, + StencilEnable: g.depth.StencilEnable, + StencilReadMask: g.depth.StencilReadMask, + StencilWriteMask: g.depth.StencilWriteMask, + FrontFace: g.depth.FrontFace, + BackFace: g.depth.BackFace, + DepthBoundsTestEnable: enabled.into(), + } +} + +/// A graphics pipeline in stream form when the title enables depth bounds. +fn graphics_pipeline_depth_bounds( + device: &ID3D12Device, + root: &ID3D12RootSignature, + vs: D3D12_SHADER_BYTECODE, + ps: D3D12_SHADER_BYTECODE, + g: &GraphicsState, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + vs: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + layout: Sub, + strip_cut: Sub, + topology: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + let topology = match g.topology.0 { + RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + _ => g.topology, + }; + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, vs), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + depth_stencil1(g, true), + ), + layout: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: g.inputs.as_ptr(), + NumElements: g.inputs.len() as u32, + }, + ), + strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, g.strip_cut), + topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, topology), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let device = device.cast::()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + /// A mesh pipeline from the title's graphics state: the pipeline-state /// stream form (no input layout or topology). fn mesh_pipeline( @@ -565,12 +786,52 @@ fn mesh_pipeline( ms: D3D12_SHADER_BYTECODE, ps: D3D12_SHADER_BYTECODE, g: &GraphicsState, + depth_bounds: bool, name: &str, ) -> windows::core::Result { use windows::core::Interface; - /// A stream subobject: its type, then its description, pointer-aligned. - #[repr(C, align(8))] - struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + let device = device.cast::()?; + if depth_bounds { + #[repr(C)] + struct Stream1 { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + let mut stream = Stream1 { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + depth_stencil1(g, true), + ), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + return super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ); + } #[repr(C)] struct Stream { root: Sub<*mut std::ffi::c_void>, @@ -600,7 +861,6 @@ fn mesh_pipeline( SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut stream).cast(), }; - let device = device.cast::()?; super::library::pipeline( name, // SAFETY: the stream holds whole subobjects pointing at live data. @@ -630,7 +890,10 @@ fn root_signature( } else { D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT }; - let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + let direct_flags = input + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + let make_desc = |flags| D3D12_VERSIONED_ROOT_SIGNATURE_DESC { Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { @@ -638,30 +901,112 @@ fn root_signature( pParameters: params.as_ptr(), NumStaticSamplers: samplers.len() as u32, pStaticSamplers: samplers.as_ptr(), - Flags: input - | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED - | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + Flags: flags, }, }, }; - // SAFETY: the description points at live arrays; the blob is read in - // full before it is released. - unsafe { + let serialize = |flags| -> windows::core::Result<(ID3DBlob, Option)> { + let desc = make_desc(flags); let mut blob: Option = None; let mut error: Option = None; - if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) { - if let Some(error) = error { - let text = std::slice::from_raw_parts( + // SAFETY: the description points at live arrays; any error blob is + // copied to a `String` before release. + let result = + unsafe { D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) }; + let message = error.map(|error| { + // SAFETY: a valid blob returned by `D3D12SerializeVersionedRootSignature`. + let text = unsafe { + std::slice::from_raw_parts( error.GetBufferPointer().cast::(), error.GetBufferSize(), - ); - tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + ) + }; + String::from_utf8_lossy(text).into_owned() + }); + match result { + Ok(()) => Ok((blob.ok_or_else(windows::core::Error::empty)?, message)), + Err(e) => { + if let Some(msg) = message { + tracing::warn!("root signature: {msg}"); + } + Err(e) } - return Err(e); } - let blob = blob.ok_or_else(windows::core::Error::empty)?; + }; + // Older Windows 10 inbox `d3d12core.dll` (pre-Agility SDK / SM 6.6) + // rejects the direct heap-indexing flags (`0xc00`). Retry without them + // so pipelines that do not index the heaps directly can still be built. + let (blob, _) = match serialize(direct_flags) { + Ok(ok) => ok, + Err(_) => { + static FALLBACK: std::sync::Once = std::sync::Once::new(); + FALLBACK.call_once(|| { + tracing::warn!( + "root signature: retrying without HEAP_DIRECTLY_INDEXED flags \ + (older Windows 10 D3D12 runtime)" + ); + }); + serialize(input)? + } + }; + // SAFETY: `blob` is valid for its reported size; the bytes are read in + // full before `blob` is released. + unsafe { let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn elem(format: u32, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { + D3D12_INPUT_ELEMENT_DESC { + Format: DXGI_FORMAT(format as i32), + AlignedByteOffset: offset, + ..Default::default() + } + } + + #[test] + fn appended_elements_are_aligned() { + // R8G8_UNORM (49, 2B) @ 0, then R32G32_FLOAT (16, 8B) appended -> aligned to 4. + let g = GraphicsState { + inputs: vec![ + elem(49, D3D12_APPEND_ALIGNED_ELEMENT), + elem(16, D3D12_APPEND_ALIGNED_ELEMENT), + ], + ..Default::default() + }; + let offsets: Vec = g.elements().into_iter().map(|e| e.offset).collect(); + assert_eq!(offsets, vec![0, 4]); + + // R8_UNORM (61, 1B), R16_FLOAT (54, 2B), R8_UNORM (61, 1B) -> 0, 2, 4. + let g2 = GraphicsState { + inputs: vec![ + elem(61, D3D12_APPEND_ALIGNED_ELEMENT), + elem(54, D3D12_APPEND_ALIGNED_ELEMENT), + elem(61, D3D12_APPEND_ALIGNED_ELEMENT), + ], + ..Default::default() + }; + let offsets2: Vec = g2.elements().into_iter().map(|e| e.offset).collect(); + assert_eq!(offsets2, vec![0, 2, 4]); + } + + #[test] + fn huge_explicit_offset_does_not_overflow() { + let g = GraphicsState { + inputs: vec![ + elem(16, u32::MAX - 2), + elem(16, D3D12_APPEND_ALIGNED_ELEMENT), + ], + ..Default::default() + }; + let elems = g.elements(); + assert_eq!(elems[0].offset, u32::MAX - 2); + assert_eq!(elems[1].offset, u32::MAX); + } +} diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs index f3eb6b040f..af663a3d04 100644 --- a/crates/victory-gpu/src/query.rs +++ b/crates/victory-gpu/src/query.rs @@ -1,11 +1,13 @@ -//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a -//! result; the heap only remembers its description. +//! Query heaps. On Windows, each title query heap creates a matching host +//! `ID3D12QueryHeap` so `BeginQuery`/`EndQuery`/`ResolveQueryData` measure +//! real host GPU occlusion, timestamps, and pipeline statistics (falling back +//! cleanly when headless or for console-only query heap types). #![allow(clippy::not_unsafe_ptr_arg_deref)] use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; -const HEAP_IIDS: [Iid; 4] = [ +const QUERY_HEAP_IIDS: [Iid; 4] = [ guid( 0x0d9658ae, 0xed45, @@ -20,18 +22,41 @@ const HEAP_IIDS: [Iid; 4] = [ #[repr(C)] #[derive(Debug, Clone, Copy)] pub(crate) struct Desc { - kind: u32, - count: u32, - nodes: u32, + pub(crate) kind: u32, + pub(crate) count: u32, + pub(crate) nodes: u32, } -#[repr(C)] struct Heap { - object: Object, + _object: Object, desc: Desc, + #[cfg(windows)] + host: Option, +} + +/// Maps a console/D3D12 query heap type (`D3D12_QUERY_HEAP_TYPE`) to a host +/// D3D12 query heap type value (`0=OCCLUSION`, `1=TIMESTAMP`, +/// `2=PIPELINE_STATISTICS`, `3=SO_STATISTICS`, `5=COPY_QUEUE_TIMESTAMP`). +pub(crate) fn host_heap_type(kind: u32) -> Option { + match kind { + 0..=3 | 5 => Some(kind as i32), + _ => None, + } +} + +/// Maps a console/D3D12 `D3D12_QUERY_TYPE` to `(host_query_type, result_bytes)`. +/// Returns `None` for unknown/console-only query types. +pub(crate) fn query_type_info(kind: u32) -> Option<(i32, u64)> { + Some(match kind { + 0 => (0, 8), // OCCLUSION + 1 => (1, 8), // BINARY_OCCLUSION + 2 => (2, 8), // TIMESTAMP + 3 => (3, 88), // PIPELINE_STATISTICS (11 * u64) + 4..=7 => (kind as i32, 16), // SO_STATISTICS_STREAM0..3 (2 * u64) + _ => return None, + }) } -/// Device method. pub(crate) extern "system" fn create( _: This, desc: *const Desc, @@ -43,18 +68,59 @@ pub(crate) extern "system" fn create( return E_INVALIDARG; }; tracing::debug!(?desc, "query heap"); + #[cfg(windows)] + let host = create_host_heap(desc); let heap = Box::new(Heap { - object: Object::new(&FUNCTIONS), + _object: Object::new(&FUNCTIONS), desc, + #[cfg(windows)] + host, }); - object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out) + object::hand_out(QUERY_HEAP, heap, iid, &QUERY_HEAP_IIDS, out) +} + +#[cfg(windows)] +fn create_host_heap(desc: Desc) -> Option { + use windows::Win32::Graphics::Direct3D12::{D3D12_QUERY_HEAP_DESC, D3D12_QUERY_HEAP_TYPE}; + let host = crate::host::host()?; + let host_kind = host_heap_type(desc.kind)?; + if desc.count == 0 { + return None; + } + let host_desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE(host_kind), + Count: desc.count, + NodeMask: 0, + }; + let mut heap = None; + // SAFETY: plain D3D12 query heap creation on the host device. + match unsafe { host.device.CreateQueryHeap(&host_desc, &mut heap) } { + Ok(()) => heap, + Err(e) => { + tracing::warn!(error = %e, ?desc, "no host query heap"); + None + } + } +} + +/// Returns the host `ID3D12QueryHeap` and slot count for a title query heap. +#[cfg(windows)] +pub(crate) fn host_heap( + this: This, +) -> Option<(windows::Win32::Graphics::Direct3D12::ID3D12QueryHeap, u32)> { + if this.is_null() { + return None; + } + // SAFETY: title passes a query heap object created by `create`. + let heap = unsafe { &*this.cast::() }; + Some((heap.host.clone()?, heap.desc.count)) } extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { object::answer( QUERY_HEAP, iid, - object::is(iid, &HEAP_IIDS).then_some(this), + object::is(iid, &QUERY_HEAP_IIDS).then_some(this), out, ) } @@ -62,11 +128,33 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } -/// IUnknown 3, object 4, device child 1. -static FUNCTIONS: Table<24> = { - let mut f = object::d3d12_object(object::missing_table::()); +static FUNCTIONS: Table<8> = { + let mut f = object::d3d12_object(object::missing_table::()); f[0] = query as *const (); f[2] = release as *const (); - f[7] = object::parent_device as *const (); // 0x38 + f[7] = object::parent_device as *const (); Table(f) }; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn maps_standard_query_heap_and_query_types() { + assert_eq!(host_heap_type(0), Some(0)); // OCCLUSION + assert_eq!(host_heap_type(1), Some(1)); // TIMESTAMP + assert_eq!(host_heap_type(2), Some(2)); // PIPELINE_STATISTICS + assert_eq!(host_heap_type(3), Some(3)); // SO_STATISTICS + assert_eq!(host_heap_type(5), Some(5)); // COPY_QUEUE_TIMESTAMP + assert_eq!(host_heap_type(99), None); + + assert_eq!(query_type_info(0), Some((0, 8))); + assert_eq!(query_type_info(1), Some((1, 8))); + assert_eq!(query_type_info(2), Some((2, 8))); + assert_eq!(query_type_info(3), Some((3, 88))); + assert_eq!(query_type_info(4), Some((4, 16))); + assert_eq!(query_type_info(7), Some((7, 16))); + assert_eq!(query_type_info(8), None); + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 5992fad25a..fe68da90a5 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -167,13 +167,20 @@ extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { if fence.is_null() { E_INVALIDARG } else { S_OK } } -/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). +/// Ticks per second of GPU timestamps (real host queue frequency when running +/// on host D3D12, falling back to [`TIMESTAMP_FREQUENCY`] when headless). extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { if out.is_null() { return E_INVALIDARG; } + #[cfg(windows)] + let freq = crate::host::host() + .and_then(|h| h.timestamp_frequency()) + .unwrap_or(TIMESTAMP_FREQUENCY); + #[cfg(not(windows))] + let freq = TIMESTAMP_FREQUENCY; // SAFETY: checked non-null. - unsafe { out.write(TIMESTAMP_FREQUENCY) }; + unsafe { out.write(freq) }; S_OK } const TIMESTAMP_FREQUENCY: u64 = 100_000_000; @@ -209,6 +216,7 @@ impl Written { at.cast::().write_unaligned(value); } } + std::sync::atomic::fence(std::sync::atomic::Ordering::Release); } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71abf..bea0683b9e 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -156,16 +156,19 @@ pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option { l if l & !0xff == 0x100 => Swizzle(l & 0xff), _ => return None, }; - texture::Texture::new(&TextureDesc { - dimension, - width: u32::try_from(desc.width).ok()?, - height: desc.height, - depth_or_array: u32::from(desc.depth_or_array_size), - mips: u32::from(desc.mip_levels), - format: desc.format, - samples: desc.sample_count.max(1), - swizzle, - }) + texture::Texture::with_metadata( + &TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array_size), + mips: u32::from(desc.mip_levels), + format: desc.format, + samples: desc.sample_count.max(1), + swizzle, + }, + texture::MetadataFlags::from_d3d12_flags(desc.flags), + ) .ok() } @@ -763,6 +766,16 @@ pub(crate) struct HostTexture { pub(crate) state: std::sync::atomic::AtomicU32, } +#[cfg(windows)] +impl Drop for HostTexture { + fn drop(&mut self) { + // Keep the underlying D3D12 resource alive across subsequent frames + // so directly-indexed or indirect GPU commands referencing its heap + // descriptor cannot page-fault on a freed streaming texture. + crate::host::retire_resource(self.texture.clone()); + } +} + /// Moves the host texture to `wanted` (a host texture state); the host /// resource and the state it leaves, if that is a change. #[cfg(windows)] @@ -834,6 +847,11 @@ fn host_texture( if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { d.format = family(d.format); } + // 16-bit BGRA formats (`B5G6R5_UNORM`, `B5G5R5A1_UNORM`, `B4G4R4A4_UNORM`) + // have no typeless family and do not support UAV creation on PC D3D12. + if d.flags & UNORDERED != 0 && matches!(d.format, 85 | 86 | 115) { + d.flags &= !UNORDERED; + } // The clear value names the format too: format, then color or depth // and stencil (5 words). let clear_value = (!clear.is_null()).then(|| { @@ -846,25 +864,52 @@ fn host_texture( Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - let mut texture: Option = None; - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - let made = unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut texture, - ) + let try_create = |desc: &ResourceDesc| -> windows::core::Result { + let mut texture: Option = None; + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + std::ptr::from_ref(desc).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(desc.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + )?; + } + texture.ok_or_else(windows::core::Error::empty) + }; + let texture = match try_create(&d) { + Ok(t) => Some(t), + Err(e) if d.flags & UNORDERED != 0 => { + // Retry without `ALLOW_UNORDERED_ACCESS` for formats the host + // driver refuses as UAVs (such as block-compressed or narrow + // packed formats) so SRV/RTV use still gets a host texture. + d.flags &= !UNORDERED; + match try_create(&d) { + Ok(t) => { + tracing::debug!( + error = %e, + format = d.format, + "host texture created without ALLOW_UNORDERED_ACCESS" + ); + Some(t) + } + Err(e2) => { + tracing::warn!(error = %e2, desc = ?d, "no host texture"); + None + } + } + } + Err(e) => { + tracing::warn!(error = %e, desc = ?d, "no host texture"); + None + } }; - if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, "no host texture"); - } if let Some(t) = &texture { crate::host::name(t, || { format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 0cba938f0a..8a4f6143af 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -14,7 +14,7 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::emit::{ConstRootView, HostShader, StaticSampler, UserData}; use victory_shader::{HwStage, RootType}; static CACHE: OnceLock = OnceLock::new(); @@ -36,14 +36,28 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). +/// Maximum wave lane count supported by the active host GPU (64 on RDNA/Intel, +/// 32 on 32-lane GPUs; defaults to 64 off Windows or before host init). +fn host_max_wave_size() -> u32 { + #[cfg(windows)] + { + crate::host::host().map_or(64, |h| h.wave_lane_count_max()) + } + #[cfg(not(windows))] + { + 64 + } +} + +/// What identifies this build: the BLAKE3 of our executable file, the host +/// GPU's wave-size capability, and the translation settings it runs with (the +/// loop limit, which a diagnostics build can change at run time). fn build() -> &'static [u8; 32] { static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); BUILD.get_or_init(|| { let exe = std::env::current_exe().and_then(std::fs::read); let limit = victory_shader::emit::loop_limit(); + let max_wave = host_max_wave_size(); if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { tracing::warn!( limit, @@ -53,6 +67,7 @@ fn build() -> &'static [u8; 32] { match exe { Ok(mut bytes) => { bytes.extend_from_slice(&limit.to_le_bytes()); + bytes.extend_from_slice(&max_wave.to_le_bytes()); *blake3::hash(&bytes).as_bytes() } Err(e) => { @@ -70,7 +85,9 @@ fn build() -> &'static [u8; 32] { /// The translation of a console shader container, from the cache when /// there is one. pub(crate) fn host_shader(container: &[u8]) -> Result { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + let max_wave = host_max_wave_size(); + let translate = + move |c: &[u8]| victory_shader::emit::translate_for(c, max_wave).map_err(|e| e.to_string()); match CACHE.get() { Some(cache) => cached(cache, build(), container, translate), None => translate(container), @@ -131,7 +148,7 @@ fn cached( (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH1"; +const MAGIC: &[u8; 4] = b"VSH3"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -206,10 +223,19 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, v); } } - for slots in [&s.root_cbvs, &s.root_srvs] { + for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] { word(&mut out, slots.len() as u32); out.extend(slots); } + for views in [&s.const_cbvs, &s.const_srvs, &s.const_uavs] { + word(&mut out, views.len() as u32); + for v in views { + word(&mut out, u32::from(v.slot)); + word(&mut out, v.dword); + word(&mut out, v.register); + } + } + word(&mut out, s.wave_size.unwrap_or(0)); out } @@ -228,6 +254,18 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } + fn const_views(&mut self) -> Option> { + let n = self.word()? as usize; + let mut out = Vec::with_capacity(n.min(256)); + for _ in 0..n { + out.push(ConstRootView { + slot: u8::try_from(self.word()?).ok()?, + dword: self.word()?, + register: self.word()?, + }); + } + Some(out) + } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -266,6 +304,14 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let root_uavs = r.list()?; + let const_cbvs = r.const_views()?; + let const_srvs = r.const_views()?; + let const_uavs = r.const_views()?; + let wave_size = match r.word()? { + 0 => None, + w => Some(w), + }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -274,6 +320,11 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, + root_uavs, + const_cbvs, + const_srvs, + const_uavs, + wave_size, }) } @@ -300,6 +351,19 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + root_uavs: vec![1], + const_cbvs: vec![], + const_srvs: vec![ConstRootView { + slot: 4, + dword: 0, + register: 0, + }], + const_uavs: vec![ConstRootView { + slot: 4, + dword: 2, + register: 0, + }], + wave_size: Some(32), } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b1d8..b87e625f99 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -43,6 +43,8 @@ pub(crate) struct Shadow { /// The copy's bytes before the submission ran, from an offset on, /// covering the ranges its shaders write: what the GPU wrote differs. before: Mutex)>>, + /// The buffer's current host D3D12 resource state (`0`: `COMMON`). + pub(crate) state: AtomicU32, } /// Snapshot memory kept for reuse (already touched, so no page faults). @@ -83,6 +85,14 @@ unsafe impl Send for Shadow {} // SAFETY: as above. unsafe impl Sync for Shadow {} +impl Drop for Shadow { + fn drop(&mut self) { + // Defer releasing the underlying GPU buffer across subsequent frames + // so directly-indexed descriptors referencing it cannot page-fault. + crate::host::retire_resource(self.buffer.clone()); + } +} + impl Shadow { /// The host GPU address of a title address inside the buffer. pub(crate) fn gpu(&self, address: u64) -> u64 { @@ -118,6 +128,7 @@ impl Shadow { watched: AtomicU8::new(0), pending: Mutex::default(), before: Mutex::default(), + state: AtomicU32::new(0), } } @@ -125,7 +136,7 @@ impl Shadow { fn inside(&self, address: usize, len: usize) -> (usize, usize) { let (start, end) = (self.start as usize, (self.start + self.len) as usize); let from = address.clamp(start, end); - (from - start, (address + len).clamp(from, end) - start) + (from - start, address.saturating_add(len).clamp(from, end) - start) } /// Shaders of `list` may write `[address, address + len)` of the copy @@ -198,39 +209,64 @@ impl Shadow { && from < to { let before = &before[from - taken..to - taken]; - // By 64 KiB piece: the copy compared with its bytes before the - // submission, title memory read only where the GPU wrote. + // By 64 KiB piece: stage each piece out of write-combined GPU + // memory into cached RAM once using reusable thread-local scratch + // buffers so comparison and byte merging never stall on repeated + // byte-wise WC reads/writes or per-call 128 KiB heap allocations. const PIECE: usize = 64 << 10; - let mut title = vec![0u8; PIECE]; + thread_local! { + static SCRATCH: std::cell::RefCell<(Vec, Vec)> = const { + std::cell::RefCell::new((Vec::new(), Vec::new())) + }; + } let mut synced = Vec::new(); - let mut at = from; - while at < to { - let n = (PIECE - (start + at) % PIECE).min(to - at); - // SAFETY: inside the mapping; only the submitting thread - // writes it. - let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; - let title = &mut title[..n]; - if host != old && crate::host::read_into((start + at) as *const u8, title) { - // Title memory with the GPU's bytes put in; the copy - // takes the title's bytes in turn. - let mut changed = false; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - if *h != *o && *t != *h { - *t = *h; - changed = true; + SCRATCH.with(|cell| { + let mut pair = cell.borrow_mut(); + if pair.0.len() < PIECE { + pair.0.resize(PIECE, 0); + } + if pair.1.len() < PIECE { + pair.1.resize(PIECE, 0); + } + let (title_buf, host_buf) = &mut *pair; + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the mapping; only the submitting thread + // accesses it. + let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let old = &before[at - from..at - from + n]; + let host_ram = &mut host_buf[..n]; + host_ram.copy_from_slice(host); + let title = &mut title_buf[..n]; + if host_ram != old && crate::host::read_into((start + at) as *const u8, title) { + // Title memory with the GPU's bytes put in; write back + // to the host shadow buffer only if title had newer + // bytes the GPU did not overwrite. + let mut title_changed = false; + let mut host_changed = false; + for ((t, h), &o) in title.iter_mut().zip(host_ram.iter_mut()).zip(old) { + if *h != o && *t != *h { + *t = *h; + title_changed = true; + } else if *h != *t { + *h = *t; + host_changed = true; + } } - *h = *t; - } - if changed { - crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; + if title_changed { + crate::watch::writing(start + at, n); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written += n; + } + if host_changed { + host.copy_from_slice(host_ram); + } + synced.push((start + at) / PAGE); } - synced.push((start + at) / PAGE); + at += n; } - at += n; - } + }); // Pages made equal to title memory are current in the copy, so // our own write is not taken for the title's; others keep what // they had (a title write there shows at the next refresh). diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 60eab0cec4..606634dd95 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -34,8 +34,7 @@ macro_rules! once { /// texture's subresources, and what was last detiled. pub(crate) struct Staging { buffer: ID3D12Resource, - /// Its bytes. - #[cfg(feature = "diagnostics")] + /// Its bytes (`GetCopyableFootprints` total). size: u64, data: *mut u8, footprints: Vec, @@ -48,11 +47,13 @@ pub(crate) struct Staging { } /// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not watched), or the write-watch asking it was detiled after, -/// with room to read the memory into. +/// (memory not watched) along with the physical-pool write epoch at that hash, +/// or the write-watch asking it was detiled after, with room to read the +/// memory into. #[derive(Default)] struct Last { hash: Option, + epoch: u64, asked: u64, read: Vec, } @@ -201,26 +202,38 @@ impl Staging { crate::copystat::add(crate::copystat::C::TexWatched, size as u64); return size; } - if !committed(self.memory, size) { + // Fast path: if no physical-page writes or remappings occurred since + // this texture was last hashed, its contents cannot have changed. + let epoch = crate::watch::physical_epoch(); + if last.hash.is_some() && last.epoch == epoch { + return 0; + } + // Streamed textures mapped via physical-page section views may be only + // partially resident (for example, mip tail resident while top mips + // are still `MEM_RESERVE`). Read every committed region safely into + // `last.read` (zeroing uncommitted gaps) so resident mips upload + // instead of leaving the whole texture black and eliminating TOCTOU + // faults against concurrent unmaps. + last.read.resize(size, 0); + if !read_resident(self.memory, &mut last.read) { #[cfg(feature = "diagnostics")] tracing::debug!( memory = ?self.memory, size, desc = ?self.layout.desc, - "a sampled texture's memory is not committed" + "a sampled texture's memory has no committed pages" ); return 0; } - // SAFETY: committed memory of the texture's layout size. - let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); + let hash = blake3::hash(&last.read); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + last.epoch = epoch; if last.hash == Some(hash) { return size; } last.hash = Some(hash); - self.detile(tiled); + self.detile(&last.read); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); size @@ -240,8 +253,12 @@ impl Staging { let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; - let len = pitch * rows as usize * f.Depth as usize; - // SAFETY: the subresource's part of the mapped staging buffer. + let Some(len) = footprint_slice_len(self.size, footprint.Offset, f.RowPitch, rows, f.Depth) + else { + tracing::warn!(mip, slice, offset = footprint.Offset, size = self.size, "staging footprint out of bounds"); + return; + }; + // SAFETY: `footprint.Offset + len <= self.size` inside the mapped staging buffer. let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) }; @@ -256,6 +273,67 @@ impl Staging { } } +/// Byte length of one placed subresource slice inside a staging buffer of +/// `total` bytes. `GetCopyableFootprints` omits trailing alignment padding on +/// the final row, so `RowPitch * rows * depth` can exceed `total - offset`. +fn footprint_slice_len( + total: u64, + offset: u64, + row_pitch: u32, + rows: u32, + depth: u32, +) -> Option { + let avail = usize::try_from(total.checked_sub(offset)?).ok()?; + let full = (row_pitch as usize) + .checked_mul(rows as usize)? + .checked_mul(depth as usize)?; + Some(full.min(avail)) +} + +/// Copies all committed regions of `[at, at + dst.len())` into `dst`, zeroing +/// uncommitted gaps. Returns `true` if at least one byte was committed. +fn read_resident(at: *const u8, dst: &mut [u8]) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let base = at as usize; + let total = dst.len(); + let end = base + total; + let mut p = base; + let mut any = false; + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.RegionSize == 0 { + dst[p - base..].fill(0); + break; + } + let region_end = (info.BaseAddress as usize) + .saturating_add(info.RegionSize) + .min(end); + let len = region_end.saturating_sub(p); + if len == 0 { + break; + } + let off = p - base; + if info.State == MEM_COMMIT { + any = true; + // `copy_mapped` tolerates a page unmapped concurrently between + // `VirtualQuery` and the copy, zero-filling any faulting page. + crate::host::copy_mapped( + dst[off..off + len].as_mut_ptr(), + p as *const u8, + len, + false, + ); + } else { + dst[off..off + len].fill(0); + } + p = region_end; + } + any +} + /// Whether `[at, at + len)` is committed memory (streamed textures may be /// unmapped until their pages arrive). pub(crate) fn committed(at: *const u8, len: usize) -> bool { @@ -329,7 +407,6 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let s = Arc::new(Staging { buffer, - #[cfg(feature = "diagnostics")] size: total, data, footprints, @@ -342,3 +419,18 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { map.insert(resource as usize, s.clone()); Some(s) } + +#[cfg(test)] +mod tests { + use super::footprint_slice_len; + + #[test] + fn footprint_slice_is_capped_to_staging_total() { + // 4x4 RGBA8: RowPitch is 256, 4 rows, total = 3*256 + 16 = 784 < 1024. + assert_eq!(footprint_slice_len(784, 0, 256, 4, 1), Some(784)); + // Subresource at offset 512 in a 1000-byte buffer. + assert_eq!(footprint_slice_len(1000, 512, 256, 4, 1), Some(488)); + // Offset past the buffer end is rejected. + assert_eq!(footprint_slice_len(784, 800, 256, 4, 1), None); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1cbe2b7522..44d2a3c431 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -20,6 +20,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's /// 4 KiB pages fold into it). Finer units made the checks of the world's @@ -115,6 +116,27 @@ static GUARDS: Mutex = Mutex::new(Guards { clean: BTreeSet::new(), }); +/// Fast-path indicator: `true` iff `GUARDS.protected` is non-empty, allowing +/// `writing()` (`kernel_will_write`) to skip acquiring the global `GUARDS` +/// mutex when no physical-page blocks are guarded. +static HAS_GUARDS: AtomicBool = AtomicBool::new(false); + +/// Monotonic generation bumped whenever physical-page pool memory is written +/// or remapped by the runtime (DirectStorage page destinations, `xmem` +/// mappings), letting `texture::Staging` skip redundant per-submission full +/// `blake3` hashes of unchanged textures. +static PHYSICAL_EPOCH: AtomicU64 = AtomicU64::new(1); + +/// Marks that physical-page title memory has been written or remapped. +pub fn physical_memory_written() { + PHYSICAL_EPOCH.fetch_add(1, Ordering::Release); +} + +/// Current physical-page write generation. +pub(crate) fn physical_epoch() -> u64 { + PHYSICAL_EPOCH.load(Ordering::Acquire) +} + fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } @@ -174,6 +196,9 @@ fn protect(g: &mut Guards, from: usize, to: usize) { let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); g.clean.extend(from..to); + if from < to { + HAS_GUARDS.store(true, Ordering::Release); + } }; if set(from, to) { note(g, from, to); @@ -187,22 +212,59 @@ fn protect(g: &mut Guards, from: usize, to: usize) { } /// Gives write access back to the guarded blocks of `[start, end)` and -/// notes them written; true if any was guarded. +/// notes them written; true if any was guarded. Contiguous runs of guarded +/// blocks are coalesced into a single `VirtualProtect` call to avoid +/// per-64 KiB TLB shootdowns during bulk DirectStorage / kernel writes. fn open(g: &mut Guards, start: usize, end: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + if g.protected.is_empty() || start >= end { + return false; + } let blocks: Vec = g .protected .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); + if blocks.is_empty() { + return false; + } for &block in &blocks { g.protected.remove(&block); g.clean.remove(&block); + } + if g.protected.is_empty() { + HAS_GUARDS.store(false, Ordering::Release); + } + let mut i = 0; + while i < blocks.len() { + let run_start = blocks[i]; + let mut run_end = run_start + 1; + while i + 1 < blocks.len() && blocks[i + 1] == run_end { + i += 1; + run_end += 1; + } let mut old = 0; - // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + // SAFETY: contiguous blocks we made read-only. + let ok = unsafe { + VirtualProtect( + (run_start * BLOCK) as *const _, + (run_end - run_start) * BLOCK, + PAGE_READWRITE, + &mut old, + ) != 0 + }; + if !ok { + // Fall back block by block if the run spans separate views. + for block in run_start..run_end { + // SAFETY: a block we made read-only. + unsafe { + VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) + }; + } + } + i += 1; } - !blocks.is_empty() + true } /// Before our own write into title memory `[at, at + len)` through the @@ -210,12 +272,19 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// The runtime calls it (as `kernel_will_write`) before the title's kernel /// reads into its own memory. pub fn writing(at: usize, len: usize) { + if len == 0 || !HAS_GUARDS.load(Ordering::Acquire) { + return; + } open(&mut guards(), at, at + len); } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it /// shows is new and read-write, so it is no longer guarded. pub fn title_memory_remapped(at: usize, len: usize) { + physical_memory_written(); + if len == 0 || !HAS_GUARDS.load(Ordering::Acquire) { + return; + } let mut g = guards(); let blocks: Vec = g .protected @@ -226,6 +295,9 @@ pub fn title_memory_remapped(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); } + if g.protected.is_empty() { + HAS_GUARDS.store(false, Ordering::Release); + } } /// Registers the handler that takes writes to guarded blocks, once, ahead diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 8a2a8750c9..825db474d0 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -43,6 +43,7 @@ impl Default for HostPolicy { "msvcp_win.dll", "ole32.dll", "advapi32.dll", + "rpcrt4.dll", "iphlpapi.dll", // The title's crash handler writes minidumps with it (loaded by name). "dbghelp.dll", diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 0668f0dead..92ceeea89a 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -521,4 +521,129 @@ mod tests { assert_eq!(error, INVALID_STREAM); assert_eq!(XApuDisconnect(handle), S_OK); } + + #[test] + fn opus_deinterleaved_mono_trim_reset_and_bad_packet() { + let input = ConnectInput { + process: DECODE_OPUS, + streams: 4, + commands_per_stream: 4, + memory: 0x4_0000, + frames_per_output: 0, + options: DEINTERLEAVED_OUTPUT, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::(); + + // Activate stereo stream 0 and mono stream 1. + for (stream, channels) in [(0, 2u32), (1, 1u32)] { + let activate = Activate { + id: id(ACTIVATE, stream), + channels, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: initialized by dequeue. + let err = unsafe { res.assume_init() }.error; + assert_eq!(err, S_OK); + } + + // Encode left-only stereo signal and verify deinterleaved planar output + // places energy in plane 0 and keeps plane 1 quiet. + let mut stereo = vec![0f32; 960 * 2]; + for i in 0..960 { + stereo[i * 2] = (i as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.6; + } + let mut enc_st = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut pkt = [0u8; 1500]; + // Prime encoder/decoder with two frames so Opus lookahead has settled. + let mut n = 0; + for _ in 0..2 { + n = enc_st.encode(&stereo, 960, &mut pkt).unwrap(); + // SAFETY: inside connection memory. + unsafe { std::ptr::copy_nonoverlapping(pkt.as_ptr(), base, n) }; + let proc = Process { + id: id(PROCESS, 0), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 120, + frame_count: 480, + input_length: n as u32, + input: base, + output_length: 480 * 8, + output: base.wrapping_add(0x4000), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const proc).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: initialized by dequeue. + let r = unsafe { res.assume_init() }; + assert_eq!((r.error, r.frames, r.output_length), (S_OK, 480, 480 * 8)); + } + let _ = n; + // SAFETY: planar output has 480 left floats followed by 480 right floats. + let out_f = unsafe { + std::slice::from_raw_parts(base.wrapping_add(0x4000).cast::(), 960) + }; + let left_e: f32 = out_f[..480].iter().map(|s| s * s).sum(); + let right_e: f32 = out_f[480..].iter().map(|s| s * s).sum(); + assert!(left_e > 1.0 && left_e > right_e * 10.0, "left={left_e}, right={right_e}"); + + // Mono decode + RESET + corrupt packet handling. + let mono: Vec = (0..960) + .map(|i| (i as f32 * 660.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .collect(); + let mut enc_m = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); + let mn = enc_m.encode(&mono, 960, &mut pkt).unwrap(); + // SAFETY: inside connection memory. + unsafe { std::ptr::copy_nonoverlapping(pkt.as_ptr(), base, mn) }; + let proc_m = Process { + id: id(PROCESS, 1), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: mn as u32, + input: base, + output_length: 960 * 4, + output: base.wrapping_add(0x8000), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const proc_m).cast(), std::ptr::null_mut()), + S_OK + ); + let reset = id(RESET, 1); + assert_eq!( + XApuEnqueueCommand(handle, (&raw const reset).cast(), std::ptr::null_mut()), + S_OK + ); + let mut res = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: initialized by dequeue. + let rm = unsafe { res.assume_init() }; + assert_eq!((rm.error, rm.frames, rm.output_length), (S_OK, 960, 960 * 4)); + assert_eq!(XApuDequeueResult(handle, res.as_mut_ptr()), S_OK); + // SAFETY: initialized by dequeue. + let reset_err = unsafe { res.assume_init() }.error; + assert_eq!(reset_err, S_OK); + + assert_eq!(XApuDisconnect(handle), S_OK); + } } diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 0a11195536..c7f469c49e 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -623,24 +623,53 @@ fn decode(context: Context, voice: &mut Voice) -> bool { /// `VICTORY_XMA_DUMP=`: saves the context words (`-.ctx`) /// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test -/// the decoder on a title's streams outside the title. +/// the decoder on a title's streams outside the title. Refuses directories +/// inside a VIctory checkout or Git repository. #[cfg(feature = "diagnostics")] fn dump_input(index: u32, context: Context) { static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else { + static DIR: OnceLock> = OnceLock::new(); + let Some(dir) = DIR.get_or_init(|| { + let dir = std::path::PathBuf::from(std::env::var_os("VICTORY_XMA_DUMP")?); + let abs = if dir.is_absolute() { + dir.clone() + } else { + std::env::current_dir().ok()?.join(&dir) + }; + let mut cur = abs.as_path(); + let base = loop { + if let Ok(canon) = std::fs::canonicalize(cur) { + break canon; + } + match cur.parent() { + Some(p) if !p.as_os_str().is_empty() => cur = p, + _ => break abs, + } + }; + if base + .ancestors() + .any(|a| a.join(".victory-root").is_file() || a.join(".git").exists()) + { + tracing::warn!( + path = %dir.display(), + "refusing VICTORY_XMA_DUMP inside repository (keep dumps outside the source tree)" + ); + return None; + } + Some(dir) + }) else { return; }; let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); if n >= 32 { return; } - let dir = std::path::PathBuf::from(dir); let words: Vec = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect(); let input = heap_bytes( context.get(5) & !0x7ff, context.field(0, 0, 12) as usize * xma::PACKET_BYTES, ); - let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::create_dir_all(dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); } diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 41f9cbd11c..4d442200b9 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -57,13 +57,58 @@ pub const INTERFACES: &[Interface] = &[ type This = *const Object; -/// 2: disabled. We present in SDR, so the title must render SDR. -// shortcut: HDR output is not done (see the presentation items in -// `TODO.md`); report enabled, with the host display's luminance, once the -// swap chain can present HDR. -extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 { - tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); - 2 +/// `XDisplayHdrModeInfo` filled when HDR10 output is enabled. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq)] +struct HdrModeInfo { + min_tone_map_luminance: f32, + max_tone_map_luminance: f32, + max_full_frame_tone_map_luminance: f32, + game_os_max_luminance: f32, +} + +/// Evaluates whether HDR10 output should be enabled for `preference` +/// (`0 = PreferHdr`, `1 = PreferRefreshRate`, `2 = Disabled`) given host +/// display capability `hdr`. Returns `1` (Enabled) or `2` (Disabled) and +/// optionally fills `HdrModeInfo`. +fn resolve_hdr_mode(preference: u32, hdr: victory_gpu::HdrInfo) -> (u32, Option) { + // Preference 2 explicitly requests SDR; otherwise enable HDR10 whenever + // the host display reports HDR10 support (or `VICTORY_HDR=1`). + if preference == 2 || !hdr.supported { + return (2, None); + } + let info = HdrModeInfo { + min_tone_map_luminance: hdr.min_nits, + max_tone_map_luminance: hdr.max_nits, + max_full_frame_tone_map_luminance: hdr.max_full_frame_nits, + game_os_max_luminance: hdr.max_nits.min(1000.0).max(200.0), + }; + (1, Some(info)) +} + +/// `XDisplayTryEnableHdrMode(preference, out info) -> XDisplayHdrModeResult`: +/// returns `1` (Enabled) when the host display supports HDR10 (filling +/// luminance info for the title's tone mapper) and `2` (Disabled) on SDR +/// displays. +extern "system" fn try_enable_hdr(_: This, preference: u32, info: *mut c_void) -> u32 { + let hdr = victory_gpu::hdr_info(); + let (result, mode_info) = resolve_hdr_mode(preference, hdr); + if let Some(mode_info) = mode_info { + if !info.is_null() { + // SAFETY: caller passed a valid `XDisplayHdrModeInfo` out pointer. + unsafe { info.cast::().write(mode_info) }; + } + tracing::info!( + preference, + min_nits = mode_info.min_tone_map_luminance, + max_nits = mode_info.max_tone_map_luminance, + max_full_frame_nits = mode_info.max_full_frame_tone_map_luminance, + "HDR mode: enabled (HDR10 presentation)" + ); + } else { + tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); + } + result } /// Nothing launches URIs for the title: no store, browser or console app @@ -170,6 +215,34 @@ static CAPTURE_VTABLE: Methods<6> = Methods([ take_screenshot as *const (), // 0x28 ]); +#[cfg(test)] +mod hdr_tests { + use super::*; + + #[test] + fn resolve_hdr_mode_enables_hdr10_with_luminance_info() { + let sdr = victory_gpu::HdrInfo::default(); + assert_eq!(resolve_hdr_mode(0, sdr), (2, None)); + + let hdr = victory_gpu::HdrInfo { + supported: true, + min_nits: 0.005, + max_nits: 1000.0, + max_full_frame_nits: 450.0, + }; + let (res, info) = resolve_hdr_mode(0, hdr); + assert_eq!(res, 1); + let info = info.expect("HDR mode info populated"); + assert_eq!(info.min_tone_map_luminance, 0.005); + assert_eq!(info.max_tone_map_luminance, 1000.0); + assert_eq!(info.max_full_frame_tone_map_luminance, 450.0); + assert_eq!(info.game_os_max_luminance, 1000.0); + + // Explicit SDR preference disables HDR even on an HDR display. + assert_eq!(resolve_hdr_mode(2, hdr), (2, None)); + } +} + #[cfg(all(test, windows))] mod tests { use super::*; @@ -178,8 +251,19 @@ mod tests { #[test] fn sdr_and_display_deferrals() { type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32; + let expected = if victory_gpu::hdr_info().supported { 1 } else { 2 }; + let mut info = HdrModeInfo { + min_tone_map_luminance: 0.0, + max_tone_map_luminance: 0.0, + max_full_frame_tone_map_luminance: 0.0, + game_os_max_luminance: 0.0, + }; + assert_eq!( + method::(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, (&raw mut info).cast()), + expected + ); assert_eq!( - method::(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()), + method::(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 2, std::ptr::null_mut()), 2 ); type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs index 87c456aed3..f05e26dff6 100644 --- a/crates/victory-hle/src/modules/dsp.rs +++ b/crates/victory-hle/src/modules/dsp.rs @@ -9,11 +9,12 @@ //! the title checks it one block later and treats a late command as an //! overrun. Commands complete when submitted here. //! -//! The transforms themselves are not computed: the hardware takes impulse -//! responses already in its own partitioned frequency-domain layout, which -//! is not known. Outputs are silence, so reverb returns are dry. -// shortcut: no convolution or block transform; outputs are zeros. Needs the -// coprocessor's impulse response and spectrum layouts to do better. +//! Convolution streams (`kind == CONVOLUTION`) run a stereo Schroeder/Freeverb +//! algorithmic reverb calibrated from the stream's impulse-response size and +//! energy (since the hardware's partitioned frequency-domain IR encoding is +//! opaque, the IR's length drives room decay and its non-zero energy gates +//! wet return — an all-zero IR produces silence, matching mathematical +//! convolution). Non-convolution block transforms still output silence. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -29,11 +30,268 @@ const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; const CONVOLUTION: u32 = 1; /// Option bits that need a stereo stream, and one convolution refuses. -const STEREO_OPTIONS: u32 = 2 | 8; +/// Bit 2 (`0x2`) selects planar (deinterleaved) stereo channel layout. +const PLANAR_STEREO: u32 = 2; +const STEREO_OPTIONS: u32 = PLANAR_STEREO | 8; const NOT_FOR_CONVOLUTION: u32 = 4; +/// Comb filter delay lengths at 48 kHz (Freeverb primes scaled by 48000/44100). +const COMB_TUNINGS: [usize; 8] = [1215, 1293, 1388, 1479, 1551, 1624, 1694, 1761]; +/// Series allpass diffuser delay lengths at 48 kHz. +const ALLPASS_TUNINGS: [usize; 4] = [606, 480, 371, 245]; +/// Stereo spread offset (in samples) added to the right channel's delay lines. +const STEREO_SPREAD: usize = 25; + +/// Flushes tiny subnormal floats to zero to avoid denormal CPU slowdowns. +#[inline] +fn flush_denormal(x: f32) -> f32 { + if !x.is_finite() || x.abs() < 1e-20 { + 0.0 + } else { + x + } +} + +/// One lowpass-damped feedback comb filter. +struct Comb { + buf: Vec, + idx: usize, + filter: f32, +} + +impl Comb { + fn new(len: usize) -> Self { + Self { + buf: vec![0.0; len.max(1)], + idx: 0, + filter: 0.0, + } + } + + #[inline] + fn tick(&mut self, input: f32, feedback: f32, damp1: f32, damp2: f32) -> f32 { + let out = self.buf[self.idx]; + self.filter = flush_denormal(out * damp2 + self.filter * damp1); + self.buf[self.idx] = flush_denormal(input + self.filter * feedback); + self.idx += 1; + if self.idx >= self.buf.len() { + self.idx = 0; + } + out + } +} + +/// One Schroeder allpass diffuser. +struct Allpass { + buf: Vec, + idx: usize, +} + +impl Allpass { + fn new(len: usize) -> Self { + Self { + buf: vec![0.0; len.max(1)], + idx: 0, + } + } + + #[inline] + fn tick(&mut self, input: f32) -> f32 { + let delayed = self.buf[self.idx]; + let out = -input + delayed; + self.buf[self.idx] = flush_denormal(input + delayed * 0.5); + self.idx += 1; + if self.idx >= self.buf.len() { + self.idx = 0; + } + out + } +} + +/// One reverb channel (8 parallel comb filters followed by 4 series allpass +/// diffusers). +struct ReverbChannel { + combs: [Comb; 8], + allpasses: [Allpass; 4], +} + +impl ReverbChannel { + fn new(spread: usize) -> Self { + Self { + combs: COMB_TUNINGS.map(|n| Comb::new(n + spread)), + allpasses: ALLPASS_TUNINGS.map(|n| Allpass::new(n + spread)), + } + } + + #[inline] + fn tick(&mut self, input: f32, feedback: f32, damp1: f32, damp2: f32) -> f32 { + let mut sum = 0.0f32; + for comb in &mut self.combs { + sum += comb.tick(input, feedback, damp1, damp2); + } + let mut out = sum; + for ap in &mut self.allpasses { + out = ap.tick(out); + } + out + } +} + +/// Algorithmic stereo reverb backing a `CONVOLUTION` DSP stream. +struct Reverb { + channels: Vec, + feedback: f32, + damp1: f32, + damp2: f32, + /// Calibrated wet return scale (`0.0` when the supplied IR is all zeros). + ir_scale: f32, +} + +impl Reverb { + fn from_desc(desc: &StreamDesc, ir_seconds: u32) -> Self { + let ch_count = (desc.channels as usize).clamp(1, 2); + let channels = (0..ch_count) + .map(|c| ReverbChannel::new(if c == 1 { STEREO_SPREAD } else { 0 })) + .collect(); + + // Inspect the supplied impulse response buffer when present. + // An explicitly provided all-zero IR yields silence (0.0); a non-zero + // IR (or null IR pointer with non-zero stream) yields a calibrated wet + // return scaled cleanly into a safe listening range. + let ir_floats = desc.ir_floats as usize; + let ir_scale = if !desc.ir.is_null() && ir_floats > 0 { + // Sample up to 64 Ki floats to measure energy without stalling activation. + let probe = ir_floats.min(65_536); + // SAFETY: title passed an IR buffer of `ir_floats` f32 values. + let slice = unsafe { std::slice::from_raw_parts(desc.ir, probe) }; + let mut peak = 0.0f32; + let mut sum_sq = 0.0f64; + for &v in slice { + if v.is_finite() { + let a = v.abs(); + if a > peak { + peak = a; + } + sum_sq += f64::from(a) * f64::from(a); + } + } + if peak == 0.0 { + 0.0 + } else { + let rms = (sum_sq / probe as f64).sqrt() as f32; + // Normalize diverse frequency-domain/time-domain IR magnitudes + // into a gentle, musically balanced wet return scale. + (rms.sqrt() * 0.25).clamp(0.08, 0.30) + } + } else if desc.ir.is_null() && ir_floats == 0 { + 0.18 + } else { + 0.0 + }; + + // Estimate room decay from IR size (in 48 kHz samples) and connection + // budget `ir_seconds`. + let est_seconds = if ir_floats > 0 { + (ir_floats as f32 / (48_000.0 * ch_count as f32)).clamp(0.25, 6.0) + } else { + (ir_seconds as f32 * 0.25).clamp(0.5, 4.0) + }; + let norm = ((est_seconds - 0.25) / 5.75).clamp(0.0, 1.0); + let feedback = 0.72 + norm * 0.20; + let damp1 = 0.28 - norm * 0.10; + let damp2 = 1.0 - damp1; + + Self { + channels, + feedback, + damp1, + damp2, + ir_scale, + } + } + + /// Processes one audio block (`frames * channels` floats) into `output`. + fn process( + &mut self, + input: Option<&[f32]>, + output: &mut [f32], + frames: usize, + channels: usize, + planar: bool, + gains: [f32; 2], + ) { + if self.ir_scale == 0.0 { + output.fill(0.0); + return; + } + let g = [ + if gains[0].is_finite() { + gains[0].clamp(-4.0, 4.0) * self.ir_scale + } else { + 0.0 + }, + if gains[1].is_finite() { + gains[1].clamp(-4.0, 4.0) * self.ir_scale + } else { + 0.0 + }, + ]; + // Input attenuation keeps the 8 parallel combs well inside linear headroom. + const INPUT_GAIN: f32 = 0.05; + let (fb, d1, d2) = (self.feedback, self.damp1, self.damp2); + + if planar && channels == 2 { + let (out_l, out_r) = output.split_at_mut(frames); + let (in_l, in_r) = match input { + Some(inp) if inp.len() >= frames * 2 => { + let (l, r) = inp.split_at(frames); + (Some(l), Some(r)) + } + _ => (None, None), + }; + let (ch_l, ch_r) = self.channels.split_at_mut(1); + for i in 0..frames { + let xl = in_l.map_or(0.0, |s| flush_denormal(s[i])) * INPUT_GAIN; + let xr = in_r.map_or(0.0, |s| flush_denormal(s[i])) * INPUT_GAIN; + let mix = 0.5 * (xl + xr); + let yl = ch_l[0].tick(0.75 * xl + 0.25 * mix, fb, d1, d2) * g[0]; + let yr = ch_r[0].tick(0.75 * xr + 0.25 * mix, fb, d1, d2) * g[1]; + out_l[i] = yl.tanh(); + out_r[i] = yr.tanh(); + } + } else if channels == 2 { + let (ch_l, ch_r) = self.channels.split_at_mut(1); + for i in 0..frames { + let base = i * 2; + let (xl, xr) = match input { + Some(inp) if base + 1 < inp.len() => ( + flush_denormal(inp[base]) * INPUT_GAIN, + flush_denormal(inp[base + 1]) * INPUT_GAIN, + ), + _ => (0.0, 0.0), + }; + let mix = 0.5 * (xl + xr); + let yl = ch_l[0].tick(0.75 * xl + 0.25 * mix, fb, d1, d2) * g[0]; + let yr = ch_r[0].tick(0.75 * xr + 0.25 * mix, fb, d1, d2) * g[1]; + output[base] = yl.tanh(); + output[base + 1] = yr.tanh(); + } + } else { + let ch = &mut self.channels[0]; + for i in 0..frames { + let x = input + .and_then(|inp| inp.get(i)) + .map_or(0.0, |&s| flush_denormal(s) * INPUT_GAIN); + let y = ch.tick(x, fb, d1, d2) * g[0]; + output[i] = y.tanh(); + } + } + } +} + pub struct Dsp { max_streams: u32, + ir_seconds: u32, active: Mutex, } @@ -61,6 +319,8 @@ pub struct Stream { dsp: *mut Dsp, frames: u32, channels: u32, + planar: bool, + reverb: Option, status: Box, } @@ -101,6 +361,7 @@ pub extern "system" fn XDspConnectWithMaximumStreamLimit( ); let dsp = Box::new(Dsp { max_streams, + ir_seconds, active: Mutex::new(0), }); // SAFETY: checked non-null. @@ -155,7 +416,7 @@ pub extern "system" fn XDspActivate( channels, "audio DSP stream activated" ); - { + let ir_seconds = { // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. let dsp = unsafe { &*dsp }; let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); @@ -163,11 +424,15 @@ pub extern "system" fn XDspActivate( return E_OUTOFMEMORY; } *active += 1; - } + dsp.ir_seconds + }; + let reverb = (kind == CONVOLUTION).then(|| Reverb::from_desc(desc, ir_seconds)); let new = Box::new(Stream { dsp, - frames: desc.frames, - channels: desc.channels, + frames, + channels, + planar: options & PLANAR_STEREO != 0, + reverb, status: Box::new(Status { submitted: 0, completed: 0, @@ -195,7 +460,7 @@ pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { S_OK } -/// Completes the command at once: its output block is silence. +/// Processes one block of audio and marks its ticket complete. pub extern "system" fn XDspSubmitCommand( stream: *mut Stream, command: *const Command, @@ -209,7 +474,25 @@ pub extern "system" fn XDspSubmitCommand( if !command.output.is_null() { let samples = (stream.frames * stream.channels) as usize; // SAFETY: the title's output buffer holds one block of the stream. - unsafe { std::ptr::write_bytes(command.output, 0, samples) }; + let out = unsafe { std::slice::from_raw_parts_mut(command.output, samples) }; + if let Some(reverb) = &mut stream.reverb { + let input = if command.input.is_null() { + None + } else { + // SAFETY: the title's input buffer holds one block of the stream. + Some(unsafe { std::slice::from_raw_parts(command.input, samples) }) + }; + reverb.process( + input, + out, + stream.frames as usize, + stream.channels as usize, + stream.planar, + command.gains, + ); + } else { + out.fill(0.0); + } } let status = &mut *stream.status; let next = status.submitted.wrapping_add(1); @@ -284,6 +567,7 @@ mod tests { // SAFETY: the stream's status block. let (completed, result) = unsafe { ((*status).completed, (*status).result) }; assert_eq!((completed, result), (ticket, S_OK)); + // An all-zero impulse response mathematically convolves to silence. assert!(output.iter().all(|&s| s == 0.0)); assert_eq!(XDspDeactivate(stream), S_OK); @@ -311,4 +595,84 @@ mod tests { assert_eq!(XDspDeactivate(stream), S_OK); assert_eq!(XDspDisconnect(dsp), S_OK); } + + #[test] + fn non_zero_ir_produces_decaying_stereo_reverb_tail() { + let mut base = vec![0u8; 0x10_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x10_0000, + 4, + 0x10, + 2, + &mut dsp + ), + S_OK + ); + // Synthetic decaying impulse response. + let mut ir = vec![0.0f32; 0x4000]; + for (i, s) in ir.iter_mut().enumerate() { + *s = (-(i as f32) / 4096.0).exp(); + } + let desc = StreamDesc { + kind: CONVOLUTION, + options: PLANAR_STEREO, + frames: 0x400, + channels: 2, + ir_floats: ir.len() as u32, + ir: ir.as_ptr(), + }; + let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); + assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); + + // Feed an impulse on block 0, then silence on blocks 1..=8. + let mut impulse = vec![0.0f32; 0x800]; + for i in 0..64 { + impulse[i] = 1.0; + impulse[0x400 + i] = 1.0; + } + let silence = vec![0.0f32; 0x800]; + let mut output = vec![0.0f32; 0x800]; + + let mut energies = Vec::new(); + let mut stereo_diff = 0.0f32; + for block in 0..10 { + let src = if block == 0 { &impulse } else { &silence }; + let cmd = Command { + gains: [1.0, 1.0], + input: src.as_ptr(), + output: output.as_mut_ptr(), + reserved: 0, + }; + assert_eq!(XDspSubmitCommand(stream, &cmd, std::ptr::null_mut()), S_OK); + assert!(output.iter().all(|s| s.is_finite() && s.abs() <= 1.0)); + let energy: f32 = output.iter().map(|s| s * s).sum(); + energies.push(energy); + for i in 0..0x400 { + stereo_diff += (output[i] - output[0x400 + i]).abs(); + } + } + // Reverb produces non-zero wet energy after the comb delay elapses (~1215 samples = block 1-2). + let peak_tail = energies[1..6].iter().copied().fold(0.0f32, f32::max); + assert!(peak_tail > 1e-4, "expected audible reverb tail, got {energies:?}"); + // Tail decays over time. + assert!(energies[9] < peak_tail, "expected tail decay: {energies:?}"); + // Stereo spread produces distinct left and right channels. + assert!(stereo_diff > 1e-3, "expected stereo decorrelation"); + + // Zero gain silences wet output cleanly. + let cmd = Command { + gains: [0.0, 0.0], + input: impulse.as_ptr(), + output: output.as_mut_ptr(), + reserved: 0, + }; + assert_eq!(XDspSubmitCommand(stream, &cmd, std::ptr::null_mut()), S_OK); + assert!(output.iter().all(|&s| s == 0.0)); + + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c94146f80b..e887342095 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -17,7 +17,7 @@ #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::borrow::Cow; +use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ffi::{CStr, c_char, c_void}; use std::os::windows::fs::FileExt; @@ -814,26 +814,57 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) - .map_err(|hr| fail(hr, "copying")); + if options & PAGE_DESTINATION != 0 { + let offset = (request.page_offset & 0xffff) as usize; + // SAFETY: the title passes a page number per 64 KiB of destination, + // which holds at least `size` bytes from `offset`. + let pages = unsafe { + std::slice::from_raw_parts( + request.destination.cast::(), + (offset + size).div_ceil(PAGE), + ) + }; + // Stream directly into each contiguous physical-page run without + // allocating a staging copy or zero-filling multi-MiB buffers. + let ok = super::xmem::write_physical_with(pages, offset, size, |done, dst| { + read_into_at(request, done as u64, dst) + }) + .map_err(|hr| fail(hr, "copying"))?; + return if ok { + Ok(()) + } else { + Err(fail(E_INVALIDARG, "copying")) + }; + } + return into_destination(request, size, |out| { + read_into_at(request, 0, out).map(|()| size) + }) + .map_err(|hr| fail(hr, "copying")); } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; - let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; - // The console's order: zlib first, then BCPack. - let source = if bc != 0 && options & ZLIB != 0 { - let mut packed = vec![0; request.intermediate_size as usize]; - let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; - packed.truncate(n); - Cow::Owned(packed) - } else { - source - }; - into_destination(request, size, |out| match tables { - Some(tables) => bcpack::decode(bc, &source, out, tables) - .map(|()| out.len()) - .map_err(|e| fail(INVALID_DATA, &e.to_string())), - None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), - })?; + with_source(request, |raw_source| { + // The console's order: zlib first, then BCPack. + if bc != 0 && options & ZLIB != 0 { + let inter_size = request.intermediate_size as usize; + with_scratch(&SCRATCH_INTER, inter_size, |packed| { + let n = inflate(raw_source, packed).map_err(|hr| fail(hr, "zlib"))?; + let packed = &packed[..n]; + into_destination(request, size, |out| { + bcpack::decode(bc, packed, out, tables.unwrap()) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string())) + }) + }) + } else { + into_destination(request, size, |out| match tables { + Some(tables) => bcpack::decode(bc, raw_source, out, tables) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string())), + None => inflate(raw_source, out).map_err(|hr| fail(hr, "zlib")), + }) + } + }) + .map_err(|hr| fail(hr, "reading or decompressing the source"))?; tracing::trace!( options = format_args!("{options:#x}"), offset = request.offset, @@ -894,28 +925,70 @@ fn load_bcpack_tables() -> Result { Tables::parse(&bytes).map_err(|e| e.to_string()) } -/// A compressed request's source: borrowed from memory, or read from the -/// file. -fn read_source(request: &Request) -> Result, HRESULT> { +/// Cap on per-worker reusable scratch buffer retention (16 MiB); larger +/// one-off chunks are released back to the OS once completed. +const MAX_SCRATCH_RETAIN: usize = 16 << 20; + +thread_local! { + static SCRATCH_SRC: RefCell> = const { RefCell::new(Vec::new()) }; + static SCRATCH_INTER: RefCell> = const { RefCell::new(Vec::new()) }; + static SCRATCH_DST: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Lends a reusable per-worker `len`-byte buffer to `f`, avoiding per-request +/// heap allocations and OS zero-page faults during bulk world streaming. +fn with_scratch( + slot: &'static std::thread::LocalKey>>, + len: usize, + f: impl FnOnce(&mut [u8]) -> R, +) -> R { + slot.with(|cell| { + let mut buf = cell.borrow_mut(); + if buf.len() < len { + buf.resize(len, 0); + } + let result = f(&mut buf[..len]); + if buf.capacity() > MAX_SCRATCH_RETAIN { + buf.clear(); + buf.shrink_to_fit(); + } + result + }) +} + +/// Borrows a compressed request's source from memory or reads it from the file +/// into the worker's reusable source scratch buffer. +fn with_source( + request: &Request, + f: impl FnOnce(&[u8]) -> Result, +) -> Result { let size = request.source_size as usize; if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `size` bytes until completion. let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; - return Ok(Cow::Borrowed(bytes)); + return f(bytes); } - let mut bytes = vec![0; size]; - read_into(request, &mut bytes)?; - Ok(Cow::Owned(bytes)) + with_scratch(&SCRATCH_SRC, size, |buf| { + read_into_at(request, 0, buf)?; + f(buf) + }) } /// Nanoseconds workers spent reading files, for the debug summary. static READING: AtomicU64 = AtomicU64::new(0); -/// Fills `out` (the source size) from the request's file or memory. -fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { +/// Fills `out` starting `rel_offset` bytes into the request's file or memory +/// source. +fn read_into_at(request: &Request, rel_offset: u64, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { - // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + // SAFETY: the title's source holds at least `rel_offset + out.len()` bytes until completion. + let src = unsafe { + std::slice::from_raw_parts( + request.source.cast::().wrapping_add(rel_offset as usize), + out.len(), + ) + }; + out.copy_from_slice(src); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. @@ -924,11 +997,12 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { .file; let started = std::time::Instant::now(); let mut done = 0; + let base = request.offset + rel_offset; let result = loop { if done == out.len() { break Ok(()); } - match file.seek_read(&mut out[done..], request.offset + done as u64) { + match file.seek_read(&mut out[done..], base + done as u64) { Ok(0) => break Err(END_OF_FILE), Ok(n) => done += n, Err(error) => break Err(from_win32(&error)), @@ -942,7 +1016,7 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { /// many it produced. GPU-visible destinations are host memory like the /// rest (GPU address = CPU address), so an address is written in place; /// physical pages are too when they are consecutive pages of one -/// allocation, and otherwise go through a buffer. +/// allocation, and otherwise reuse the worker's scratch buffer. fn into_destination( request: &Request, len: usize, @@ -971,13 +1045,14 @@ fn into_destination( if let Some(mut window) = super::xmem::page_window(pages, offset, len) { return fill(window.bytes()).map(drop); } - let mut data = vec![0; len]; - let n = fill(&mut data)?; - if super::xmem::write_physical(pages, offset, &data[..n]) { - Ok(()) - } else { - Err(E_INVALIDARG) - } + with_scratch(&SCRATCH_DST, len, |data| { + let n = fill(data)?; + if super::xmem::write_physical(pages, offset, &data[..n]) { + Ok(()) + } else { + Err(E_INVALIDARG) + } + }) } /// Slots by the 2020 order, which the argument shapes at Grand Theft Auto diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a411bd0f4a..263adcf4b6 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -105,14 +105,45 @@ struct KeyState { const _: () = assert!(size_of::() == 12 && size_of::() == 28); +/// Normalized `[0.0, 1.0]` rumble motor intensities: low frequency (left), +/// high frequency (right), left impulse trigger, right impulse trigger. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +struct Rumble { + low: f32, + high: f32, + left_trigger: f32, + right_trigger: f32, +} + +impl Rumble { + fn from_params(params: [f32; 4]) -> Self { + let clamp = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + Self { + low: clamp(params[0]), + high: clamp(params[1]), + left_trigger: clamp(params[2]), + right_trigger: clamp(params[3]), + } + } + + /// Maps all four motors onto XInput's two-motor (`left`, `right`) model + /// when a 4-motor trigger backend (Windows.Gaming.Input) is unavailable. + fn xinput_fallback(self) -> (u16, u16) { + let to_u16 = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + let low = self.low.max(self.left_trigger * 0.65); + let high = self.high.max(self.right_trigger * 0.65); + (to_u16(low), to_u16(high)) + } +} + /// Host input, or a fake in tests. trait Source: Send { /// The pad in host slot `slot`, `None` when the slot is empty. fn pad(&mut self, slot: usize) -> Option; /// Keys held down; none while the title's window lacks focus. fn keys(&mut self) -> Vec; - /// Motor speeds: low frequency (left), high frequency (right). - fn rumble(&mut self, slot: usize, low: u16, high: u16); + /// Motor intensities: low/high frequency plus left/right impulse triggers. + fn rumble(&mut self, slot: usize, rumble: Rumble); } fn fallback(keys: &[KeyState]) -> PadState { @@ -201,8 +232,8 @@ impl Device { id, root_id: id, supported_input: kind(index), - // Low and high frequency. - rumble_motors: if index < PADS { 0x3 } else { 0 }, + // Low/high frequency plus left and right impulse trigger motors (0xF). + rumble_motors: if index < PADS { 0xF } else { 0 }, ..Default::default() }; Device { @@ -411,16 +442,30 @@ impl Hub { } /// Runs callbacks, never under our lock: they call back into us. One - /// unregistered since the event was taken does not run, and + /// unregistered since the event was taken does not run, callbacks for the + /// same registration are serialized across threads, and /// `UnregisterCallback` waits for one that runs. fn deliver(&self, events: Vec) { let me = std::thread::current().id(); - for e in events { + 'events: for e in events { let r = e.registration; { let mut state = self.state(); - if !state.callbacks.iter().any(|c| c.token == r.token) { - continue; + loop { + if !state.callbacks.iter().any(|c| c.token == r.token) { + continue 'events; + } + if !state + .running + .iter() + .any(|&(t, tid)| t == r.token && tid != me) + { + break; + } + state = self + .returned + .wait(state) + .unwrap_or_else(PoisonError::into_inner); } state.running.push((r.token, me)); } @@ -525,7 +570,7 @@ fn host() -> Box { fn keys(&mut self) -> Vec { Vec::new() } - fn rumble(&mut self, _: usize, _: u16, _: u16) {} + fn rumble(&mut self, _: usize, _: Rumble) {} } Box::new(Nothing) } @@ -754,6 +799,8 @@ extern "system" fn register_device( callback, }; let mut found = Vec::new(); + let me = std::thread::current().id(); + let mut reserved = false; { let mut state = hub.state(); if enumeration != 0 && status & STATUS_CONNECTED != 0 { @@ -772,8 +819,33 @@ extern "system" fn register_device( state.callbacks.push(registration); if enumeration == ASYNC_ENUMERATION { state.pending.append(&mut found); + } else if !found.is_empty() { + // Reserve this registration for the calling thread while blocking + // enumeration delivers, so the poll thread cannot overtake or + // run the same callback concurrently. + state.running.push((registration.token, me)); + reserved = true; } } + struct Release<'a> { + hub: &'a Hub, + token: u64, + me: ThreadId, + } + impl Drop for Release<'_> { + fn drop(&mut self) { + let mut state = self.hub.state(); + if let Some(i) = state.running.iter().position(|&x| x == (self.token, self.me)) { + state.running.swap_remove(i); + } + self.hub.returned.notify_all(); + } + } + let _guard = reserved.then_some(Release { + hub, + token: registration.token, + me, + }); if !out.is_null() { // SAFETY: checked non-null. unsafe { out.write(registration.token) }; @@ -908,24 +980,21 @@ extern "system" fn device_status(this: *const Device) -> u32 { 0 } } -// shortcut: trigger motors are dropped (XInput has none). The host API that -// drives them without a redistributable is Windows.Gaming.Input (WinRT -// `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside -// diagnostics builds; Grand Theft Auto VI sends trigger levels in slot 0x50. +/// Sends all four motor intensities (low/high frequency and left/right +/// impulse triggers) to the host controller backend. extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { // SAFETY: one of our devices. let device = unsafe { &*this }; if device.index >= PADS { return; } - let [low, high, ..] = if params.is_null() { + let raw = if params.is_null() { [0.0; 4] } else { // SAFETY: checked non-null; four motor levels. unsafe { *params } }; - let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; - lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); + lock(&device.hub().source).rumble(device.index, Rumble::from_params(raw)); } extern "system" fn unsupported(_: *const c_void) -> HRESULT { tracing::warn!( @@ -1174,7 +1243,11 @@ mod host { .collect() } - fn rumble(&mut self, slot: usize, low: u16, high: u16) { + fn rumble(&mut self, slot: usize, rumble: Rumble) { + if wgi::set_vibration(slot, rumble) { + return; + } + let (low, high) = rumble.xinput_fallback(); let speeds = XINPUT_VIBRATION { wLeftMotorSpeed: low, wRightMotorSpeed: high, @@ -1184,6 +1257,210 @@ mod host { } } + /// Drives all four motors (including Xbox impulse triggers) through the + /// built-in `Windows.Gaming.Input.Gamepad` WinRT API via `combase.dll`, + /// requiring no extra redistributable or crate dependency. + mod wgi { + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + use windows_sys::core::{PCSTR, w}; + + use super::Rumble; + use crate::modules::xgameruntime::{Guid, HRESULT}; + + const RO_INIT_MULTITHREADED: i32 = 1; + const RPC_E_CHANGED_MODE: HRESULT = 0x8001_0106_u32 as i32; + + /// `Windows.Gaming.Input.IGamepadStatics` (`8bbce529-d49c-39e9-9560-e47dde96b7c8`). + const IID_IGAMEPAD_STATICS: Guid = Guid::new( + 0x8bbc_e529, + 0xd49c, + 0x39e9, + [0x95, 0x60, 0xe4, 0x7d, 0xde, 0x96, 0xb7, 0xc8], + ); + + #[repr(C)] + struct HStringHeader([usize; 3]); + + #[repr(C)] + struct GamepadVibration { + left_motor: f64, + right_motor: f64, + left_trigger: f64, + right_trigger: f64, + } + + struct Combase { + ro_init: unsafe extern "system" fn(i32) -> HRESULT, + ro_uninit: unsafe extern "system" fn(), + create_string_ref: unsafe extern "system" fn( + *const u16, + u32, + *mut HStringHeader, + *mut *mut c_void, + ) -> HRESULT, + get_factory: unsafe extern "system" fn( + *mut c_void, + *const Guid, + *mut *mut c_void, + ) -> HRESULT, + } + + fn combase() -> Option<&'static Combase> { + static LIB: OnceLock> = OnceLock::new(); + LIB.get_or_init(|| { + // SAFETY: loading standard system `combase.dll` and resolving documented exports. + unsafe { + let module = LoadLibraryW(w!("combase.dll")); + if module.is_null() { + return None; + } + let sym = |name: PCSTR| GetProcAddress(module, name); + Some(Combase { + ro_init: std::mem::transmute(sym(c"RoInitialize".as_ptr().cast())?), + ro_uninit: std::mem::transmute(sym(c"RoUninitialize".as_ptr().cast())?), + create_string_ref: std::mem::transmute(sym( + c"WindowsCreateStringReference".as_ptr().cast(), + )?), + get_factory: std::mem::transmute(sym( + c"RoGetActivationFactory".as_ptr().cast(), + )?), + }) + } + }) + .as_ref() + } + + struct ComPtr(*mut c_void); + impl Drop for ComPtr { + fn drop(&mut self) { + if self.0.is_null() { + return; + } + // SAFETY: `self.0` is an owned COM/WinRT interface pointer; slot 2 is `Release`. + unsafe { + let vtbl = *(self.0 as *const *const *const c_void); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute(*vtbl.add(2)); + release(self.0); + } + } + } + + pub(super) fn set_vibration(slot: usize, rumble: Rumble) -> bool { + let Some(cb) = combase() else { + return false; + }; + // SAFETY: initializing WinRT apartment for the calling thread. + let init_hr = unsafe { (cb.ro_init)(RO_INIT_MULTITHREADED) }; + let should_uninit = init_hr >= 0; + if !should_uninit && init_hr != RPC_E_CHANGED_MODE { + return false; + } + struct RoGuard<'a>(&'a Combase, bool); + impl Drop for RoGuard<'_> { + fn drop(&mut self) { + if self.1 { + // SAFETY: balanced with a successful `RoInitialize`. + unsafe { (self.0.ro_uninit)() }; + } + } + } + let _ro = RoGuard(cb, should_uninit); + + let class: Vec = "Windows.Gaming.Input.Gamepad" + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut header = HStringHeader([0; 3]); + let mut hstring = std::ptr::null_mut(); + // SAFETY: `class` is NUL-terminated UTF-16 and outlives `hstring`. + if unsafe { + (cb.create_string_ref)( + class.as_ptr(), + (class.len() - 1) as u32, + &mut header, + &mut hstring, + ) + } < 0 + { + return false; + } + + let mut statics_raw = std::ptr::null_mut(); + // SAFETY: requesting `IGamepadStatics` activation factory. + if unsafe { (cb.get_factory)(hstring, &IID_IGAMEPAD_STATICS, &mut statics_raw) } < 0 + || statics_raw.is_null() + { + return false; + } + let statics = ComPtr(statics_raw); + + // IGamepadStatics::Gamepads is slot 10 (6 IInspectable + 4 event slots). + let mut list_raw = std::ptr::null_mut(); + // SAFETY: calling verified vtable slot 10 on live `IGamepadStatics`. + let list_hr = unsafe { + let vtbl = *(statics.0 as *const *const *const c_void); + let gamepads: unsafe extern "system" fn( + *mut c_void, + *mut *mut c_void, + ) -> HRESULT = std::mem::transmute(*vtbl.add(10)); + gamepads(statics.0, &mut list_raw) + }; + if list_hr < 0 || list_raw.is_null() { + return false; + } + let list = ComPtr(list_raw); + + // IVectorView::Size is slot 7; IVectorView::GetAt is slot 6. + let mut count = 0u32; + // SAFETY: calling verified vtable slot 7 on live `IVectorView`. + let size_hr = unsafe { + let vtbl = *(list.0 as *const *const *const c_void); + let size: unsafe extern "system" fn(*mut c_void, *mut u32) -> HRESULT = + std::mem::transmute(*vtbl.add(7)); + size(list.0, &mut count) + }; + if size_hr < 0 || slot >= count as usize { + return false; + } + + let mut pad_raw = std::ptr::null_mut(); + // SAFETY: calling verified vtable slot 6 with in-bounds index `slot`. + let get_hr = unsafe { + let vtbl = *(list.0 as *const *const *const c_void); + let get_at: unsafe extern "system" fn( + *mut c_void, + u32, + *mut *mut c_void, + ) -> HRESULT = std::mem::transmute(*vtbl.add(6)); + get_at(list.0, slot as u32, &mut pad_raw) + }; + if get_hr < 0 || pad_raw.is_null() { + return false; + } + let pad = ComPtr(pad_raw); + + let vibration = GamepadVibration { + left_motor: f64::from(rumble.low), + right_motor: f64::from(rumble.high), + left_trigger: f64::from(rumble.left_trigger), + right_trigger: f64::from(rumble.right_trigger), + }; + // IGamepad::SetVibration is slot 7 (6 IInspectable + Vibration getter). + // SAFETY: calling verified vtable slot 7 on live `IGamepad`. + let vib_hr = unsafe { + let vtbl = *(pad.0 as *const *const *const c_void); + let set_vib: unsafe extern "system" fn(*mut c_void, GamepadVibration) -> HRESULT = + std::mem::transmute(*vtbl.add(7)); + set_vib(pad.0, vibration) + }; + vib_hr >= 0 + } + } + /// Debugging aid: `VICTORY_KEYS=:,...` holds each key for /// 0.2 s that long after input starts, with or without focus. A key is a /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, @@ -1270,7 +1547,7 @@ mod tests { struct FakeHost { pads: [Option; PADS], keys: Vec, - rumble: Vec<(usize, u16, u16)>, + rumble: Vec<(usize, Rumble)>, } struct Fake(Arc>); @@ -1282,8 +1559,8 @@ mod tests { fn keys(&mut self) -> Vec { self.0.lock().unwrap().keys.clone() } - fn rumble(&mut self, slot: usize, low: u16, high: u16) { - self.0.lock().unwrap().rumble.push((slot, low, high)); + fn rumble(&mut self, slot: usize, rumble: Rumble) { + self.0.lock().unwrap().rumble.push((slot, rumble)); } } @@ -1605,11 +1882,106 @@ mod tests { assert_eq!(find(&hub.object, &[1; 32], &mut out), DEVICE_NOT_FOUND); assert!(out.is_null()); - type Rumble = extern "system" fn(*const Device, *const [f32; 4]); - let rumble = slot::(device, 0x50); - rumble(device, &[0.5, 1.0, 1.0, 1.0]); + type RumbleFn = extern "system" fn(*const Device, *const [f32; 4]); + let rumble = slot::(device, 0x50); + rumble(device, &[0.5, 1.0, 0.25, 0.75]); rumble(&hub.devices[FALLBACK], &[1.0; 4]); rumble(device, std::ptr::null()); - assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); + assert_eq!( + host.lock().unwrap().rumble, + [ + ( + 2, + Rumble { + low: 0.5, + high: 1.0, + left_trigger: 0.25, + right_trigger: 0.75, + } + ), + (2, Rumble::default()), + ] + ); + // Pads advertise all four motors (low, high, left trigger, right trigger). + assert_eq!(hub.devices[2].info.rumble_motors, 0xF); + assert_eq!(hub.devices[KEYBOARD].info.rumble_motors, 0); + + // XInput fallback blends trigger rumble when main motors are quiet. + let trigger_only = Rumble::from_params([0.0, 0.0, 1.0, 0.5]); + let (xlow, xhigh) = trigger_only.xinput_fallback(); + assert!(xlow > 40_000 && xhigh > 20_000); + assert_eq!( + Rumble::from_params([f32::NAN, -1.0, 2.5, f32::INFINITY]), + Rumble { + low: 0.0, + high: 0.0, + left_trigger: 1.0, + right_trigger: 0.0, + } + ); + } + + #[test] + fn callbacks_for_a_registration_do_not_overlap_across_threads() { + use std::sync::atomic::AtomicBool; + static ACTIVE: AtomicU32 = AtomicU32::new(0); + static OVERLAPPED: AtomicBool = AtomicBool::new(false); + static FIRST_IN: AtomicBool = AtomicBool::new(false); + static RELEASE: AtomicBool = AtomicBool::new(false); + static CALLS: AtomicU32 = AtomicU32::new(0); + extern "system" fn cb( + _: u64, + _: *mut c_void, + _: *const Device, + _: u64, + _: u32, + _: u32, + ) { + if ACTIVE.fetch_add(1, Ordering::SeqCst) > 0 { + OVERLAPPED.store(true, Ordering::SeqCst); + } + if CALLS.fetch_add(1, Ordering::SeqCst) == 0 { + FIRST_IN.store(true, Ordering::SeqCst); + while !RELEASE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + ACTIVE.fetch_sub(1, Ordering::SeqCst); + } + let (hub, host) = fake(); + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option, + *mut u64, + ) -> HRESULT; + let register = slot::(&hub.object, 0x48); + let reg_thread = std::thread::spawn(move || { + let mut token = 0; + // Blocking enumeration delivers pad 0 on this thread. + assert_eq!( + register(&hub.object, std::ptr::null(), GAMEPAD_KIND, STATUS_CONNECTED, 1, std::ptr::null_mut(), Some(cb), &mut token), + S_OK + ); + }); + while !FIRST_IN.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + // Connect pad 1 while blocking enumeration is still inside `cb`. + host.lock().unwrap().pads[1] = Some(PadState::default()); + let poll_thread = std::thread::spawn(move || hub.poll()); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!(CALLS.load(Ordering::SeqCst), 1, "poll thread must wait for active callback"); + RELEASE.store(true, Ordering::SeqCst); + reg_thread.join().unwrap(); + poll_thread.join().unwrap(); + assert!(!OVERLAPPED.load(Ordering::SeqCst), "callbacks ran concurrently"); + assert_eq!(CALLS.load(Ordering::SeqCst), 2); } } diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 3ab3067122..a5726bab0b 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -63,8 +63,9 @@ pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, siz let Some(path) = title_path(module) else { return host::get_module_file_name_a(module, out, size); }; + let ansi = host::encode_ansi(&path); // SAFETY: the title passes a buffer of `size` bytes. - copy_truncated(path.as_bytes(), unsafe { + copy_truncated(&ansi, unsafe { std::slice::from_raw_parts_mut(out, size as usize) }) } @@ -397,6 +398,7 @@ mod host { use std::ffi::c_void; use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; + use windows_sys::Win32::Globalization::{CP_ACP, WideCharToMultiByte}; use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; use windows_sys::Win32::System::LibraryLoader::{ DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, @@ -434,6 +436,53 @@ mod host { unsafe { GetModuleFileNameA(module, out, size) } } + /// Encodes a Rust string using the host ANSI code page (`CP_ACP`), + /// matching Windows `*A` APIs like `GetModuleFileNameA`. + pub(super) fn encode_ansi(text: &str) -> Vec { + let wide: Vec = text.encode_utf16().collect(); + let Ok(len) = i32::try_from(wide.len()) else { + return text.as_bytes().to_vec(); + }; + if len == 0 { + return Vec::new(); + } + // SAFETY: `wide` has `len` valid UTF-16 code units; querying size first. + let need = unsafe { + WideCharToMultiByte( + CP_ACP, + 0, + wide.as_ptr(), + len, + std::ptr::null_mut(), + 0, + std::ptr::null(), + std::ptr::null_mut(), + ) + }; + if need <= 0 { + return text.as_bytes().to_vec(); + } + let mut out = vec![0u8; need as usize]; + // SAFETY: `out` has `need` writable bytes matching the query above. + let wrote = unsafe { + WideCharToMultiByte( + CP_ACP, + 0, + wide.as_ptr(), + len, + out.as_mut_ptr(), + need, + std::ptr::null(), + std::ptr::null_mut(), + ) + }; + if wrote <= 0 { + return text.as_bytes().to_vec(); + } + out.truncate(wrote as usize); + out + } + pub(super) fn set_last_error(code: u32) { // SAFETY: see above. unsafe { SetLastError(code) } @@ -551,6 +600,10 @@ mod host { 0 } + pub(super) fn encode_ansi(text: &str) -> Vec { + text.as_bytes().to_vec() + } + pub(super) fn set_last_error(_: u32) {} pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs index aa6e91c5bb..d69c364ba6 100644 --- a/crates/victory-hle/src/modules/media.rs +++ b/crates/victory-hle/src/modules/media.rs @@ -455,11 +455,143 @@ pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESUL S_OK } +/// Enforces the local-file URL rule on `mfplat!MFCreateFile`. +pub extern "system" fn MFCreateFile( + access_mode: u32, + open_mode: u32, + flags: u32, + url: *const u16, + out: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(u) => u, + Err(hr) => return hr, + }; + static HOST_FN: OnceLock> = OnceLock::new(); + let Some(f) = *HOST_FN.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateFile")) + else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: matches host `MFCreateFile` signature. + let f: extern "system" fn(u32, u32, u32, *const u16, *mut Unknown) -> HRESULT = + unsafe { std::mem::transmute(f) }; + f(access_mode, open_mode, flags, url.as_ptr(), out) +} + +/// Enforces the local-file URL rule on `mfplat!MFBeginCreateFile`. +#[allow(clippy::too_many_arguments)] +pub extern "system" fn MFBeginCreateFile( + access_mode: u32, + open_mode: u32, + flags: u32, + url: *const u16, + callback: Unknown, + state: Unknown, + cancel_cookie: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(u) => u, + Err(hr) => return hr, + }; + static HOST_FN: OnceLock> = OnceLock::new(); + let Some(f) = + *HOST_FN.get_or_init(|| crate::host::function("mfplat.dll", "MFBeginCreateFile")) + else { + return UNSUPPORTED_SCHEME; + }; + type BeginCreateFileFn = extern "system" fn( + u32, + u32, + u32, + *const u16, + Unknown, + Unknown, + *mut Unknown, + ) -> HRESULT; + // SAFETY: matches host `MFBeginCreateFile` signature. + let f: BeginCreateFileFn = unsafe { std::mem::transmute(f) }; + f( + access_mode, + open_mode, + flags, + url.as_ptr(), + callback, + state, + cancel_cookie, + ) +} + +/// Enforces the local-file URL rule on `mfreadwrite!MFCreateSourceReaderFromURL`. +pub extern "system" fn MFCreateSourceReaderFromURL( + url: *const u16, + attrs: Unknown, + out: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(u) => u, + Err(hr) => return hr, + }; + static HOST_FN: OnceLock> = OnceLock::new(); + let Some(f) = *HOST_FN.get_or_init(|| { + crate::host::function("mfreadwrite.dll", "MFCreateSourceReaderFromURL") + }) else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: matches host `MFCreateSourceReaderFromURL` signature. + let f: extern "system" fn(*const u16, Unknown, *mut Unknown) -> HRESULT = + unsafe { std::mem::transmute(f) }; + f(url.as_ptr(), attrs, out) +} + +/// Enforces the local-file URL rule on `mfreadwrite!MFCreateSinkWriterFromURL`. +/// A null URL is permitted by Media Foundation when `byte_stream` is supplied. +pub extern "system" fn MFCreateSinkWriterFromURL( + url: *const u16, + byte_stream: Unknown, + attrs: Unknown, + out: *mut Unknown, +) -> HRESULT { + let owned = if url.is_null() && !byte_stream.is_null() { + None + } else { + match checked(url) { + Ok(u) => Some(u), + Err(hr) => return hr, + } + }; + static HOST_FN: OnceLock> = OnceLock::new(); + let Some(f) = *HOST_FN.get_or_init(|| { + crate::host::function("mfreadwrite.dll", "MFCreateSinkWriterFromURL") + }) else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: matches host `MFCreateSinkWriterFromURL` signature. + let f: extern "system" fn(*const u16, Unknown, Unknown, *mut Unknown) -> HRESULT = + unsafe { std::mem::transmute(f) }; + let ptr = owned.as_ref().map_or(std::ptr::null(), |u| u.as_ptr()); + f(ptr, byte_stream, attrs, out) +} + pub(crate) fn module() -> HleModule { HleModule { name: "media", dlls: &["mfplat.dll"], - exports: vec![hle_export!(MFCreateSourceResolver)], + exports: vec![ + hle_export!(MFCreateSourceResolver), + hle_export!(MFCreateFile), + hle_export!(MFBeginCreateFile), + ], + } +} + +pub(crate) fn readwrite_module() -> HleModule { + HleModule { + name: "media_readwrite", + dlls: &["mfreadwrite.dll"], + exports: vec![ + hle_export!(MFCreateSourceReaderFromURL), + hle_export!(MFCreateSinkWriterFromURL), + ], } } @@ -528,4 +660,54 @@ mod tests { assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]); } + + #[test] + fn direct_url_exports_refuse_network_urls() { + let mut url = wide("https://example.com/movie.mp4"); + url.push(0); + let mut out = std::ptr::null_mut(); + assert_eq!( + MFCreateSourceReaderFromURL(url.as_ptr(), std::ptr::null_mut(), &mut out), + UNSUPPORTED_SCHEME + ); + assert_eq!( + MFCreateSinkWriterFromURL( + url.as_ptr(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut out, + ), + UNSUPPORTED_SCHEME + ); + assert_eq!( + MFCreateFile(0, 0, 0, url.as_ptr(), &mut out), + UNSUPPORTED_SCHEME + ); + assert_eq!( + MFBeginCreateFile( + 0, + 0, + 0, + url.as_ptr(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut out, + ), + UNSUPPORTED_SCHEME + ); + assert!(module().exports.iter().any(|e| e.name == "MFCreateFile")); + assert!(module().exports.iter().any(|e| e.name == "MFBeginCreateFile")); + assert!( + readwrite_module() + .exports + .iter() + .any(|e| e.name == "MFCreateSourceReaderFromURL") + ); + assert!( + readwrite_module() + .exports + .iter() + .any(|e| e.name == "MFCreateSinkWriterFromURL") + ); + } } diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 51e3590bf1..998d5357ff 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -59,6 +59,8 @@ pub(crate) fn all() -> Vec { #[cfg(windows)] all.push(media::module()); #[cfg(windows)] + all.push(media::readwrite_module()); + #[cfg(windows)] all.push(dstorage::module()); #[cfg(windows)] all.push(files::module()); diff --git a/crates/victory-hle/src/modules/speech.rs b/crates/victory-hle/src/modules/speech.rs index 15e8eca869..89fb597370 100644 --- a/crates/victory-hle/src/modules/speech.rs +++ b/crates/victory-hle/src/modules/speech.rs @@ -1,151 +1,686 @@ -//! Accessibility: speech synthesis for the title's narration. No voice is -//! installed here, and every stream is valid WAVE audio of no length, so -//! narration is silent. -// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT -// speech synthesis) needs COM bindings this crate has only in diagnostics -// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the -// title then plays the empty stream and goes on. +//! `XSpeechSynthesizer`: text-to-speech synthesis into WAV streams. +//! +//! On Windows, synthesis delegates to the system SAPI 5 engine (`SpVoice` + +//! `SpStream` over an `HGLOBAL` `IStream`, loaded dynamically from `ole32.dll`), +//! producing 16 kHz mono 16-bit PCM wrapped in a standard RIFF/WAVE container. +//! Plain text (slot `0x68`) uses `SPF_IS_NOT_XML`; SSML (slot `0xa8`) uses +//! `SPF_IS_XML | SPF_PARSE_SSML`. If SAPI is unavailable (for example on a +//! stripped/headless host or non-Windows test runs), streams fall back cleanly +//! to a valid silent 44-byte RIFF/WAVE header so titles keep running. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{c_char, c_void}; -use super::xgameruntime::{ - Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, -}; +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put}; -/// Closed captions, high contrast, speech to text and synthesis. pub const PROVIDER: Guid = Guid::new( - 0x3e24_1977, - 0x6237, - 0x41e9, - [0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1], + 0x27be_76b2, + 0xdba1, + 0x4bd8, + [0xa0, 0x05, 0x5c, 0x0f, 0x15, 0x16, 0x18, 0x1a], ); -/// Unchanged since 2020. -pub const IID: Guid = Guid::new( - 0xd722_b373, - 0x8c4d, - 0x4692, - [0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d], +/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x40-0x80, +/// 0xa8) take the public API's arguments in the 2020 order. +pub const IID_2026: Guid = Guid::new( + 0x611e_c004, + 0xd326, + 0x4580, + [0xab, 0x90, 0xc3, 0x90, 0x39, 0x99, 0x3d, 0x3a], ); -pub static OBJECT: Object = Object::new("accessibility", &VTABLE); -pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; +pub static OBJECT: Object = Object::new("speech", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; -/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36, -/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s, -/// block 2, 16 bits), an empty data chunk. -const SILENCE: [u8; 44] = - *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; +const E_INSUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32; -/// Synthesizers and streams hold nothing, so their handles are fixed -/// addresses and closing them is free. -static SYNTHESIZER: u8 = 0; -static STREAM: u8 = 0; +const SAMPLE_RATE: u32 = 16_000; +const CHANNELS: u16 = 1; +const BITS_PER_SAMPLE: u16 = 16; type This = *const Object; -/// No voice is installed, so the callback never runs. +/// Owned synthesizer instance handed to titles by `create` (`0x48`). +struct Synthesizer { + voice_id: Option, +} + +/// Owned synthesized WAV buffer handed to titles by `create_stream` (`0x68`/`0xa8`). +struct Stream { + wav: Vec, +} + +/// Matches the GDK `XSpeechSynthesizerVoiceInformation` struct layout. +#[repr(C)] +struct VoiceInfo { + description: *const c_char, + display_name: *const c_char, + gender: u32, + voice_id: *const c_char, + language: *const c_char, +} + +const DEFAULT_DESCRIPTION: &[u8] = b"Microsoft Default Voice\0"; +const DEFAULT_DISPLAY_NAME: &[u8] = b"Default\0"; +const DEFAULT_VOICE_ID: &[u8] = b"victory-default\0"; +const DEFAULT_LANGUAGE: &[u8] = b"en-US\0"; + +type VoiceCallback = extern "system" fn(info: *const VoiceInfo, context: *mut c_void) -> bool; + +/// Wraps raw interleaved little-endian 16-bit PCM bytes in a 44-byte RIFF/WAVE +/// container. If `pcm` already begins with `"RIFF"`, returns it verbatim. +fn wrap_wav_pcm16(pcm: &[u8], sample_rate: u32, channels: u16) -> Vec { + if pcm.len() >= 12 && &pcm[..4] == b"RIFF" && &pcm[8..12] == b"WAVE" { + return pcm.to_vec(); + } + let data_len = u32::try_from(pcm.len()).unwrap_or(u32::MAX - 36); + let pcm = &pcm[..data_len as usize]; + let riff_len = 36u32.saturating_add(data_len); + let block_align = channels * (BITS_PER_SAMPLE / 8); + let byte_rate = sample_rate * u32::from(block_align); + + let mut out = Vec::with_capacity(44 + pcm.len()); + out.extend_from_slice(b"RIFF"); + out.extend_from_slice(&riff_len.to_le_bytes()); + out.extend_from_slice(b"WAVE"); + out.extend_from_slice(b"fmt "); + out.extend_from_slice(&16u32.to_le_bytes()); // PCM fmt chunk size + out.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM + out.extend_from_slice(&channels.to_le_bytes()); + out.extend_from_slice(&sample_rate.to_le_bytes()); + out.extend_from_slice(&byte_rate.to_le_bytes()); + out.extend_from_slice(&block_align.to_le_bytes()); + out.extend_from_slice(&BITS_PER_SAMPLE.to_le_bytes()); + out.extend_from_slice(b"data"); + out.extend_from_slice(&data_len.to_le_bytes()); + out.extend_from_slice(pcm); + out +} + +/// Reads a NUL-terminated UTF-8 C string from title memory, returning an empty +/// string if null or not valid UTF-8. +fn read_cstr(ptr: *const c_char) -> String { + if ptr.is_null() { + return String::new(); + } + // SAFETY: title passes a NUL-terminated string. + unsafe { std::ffi::CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned() +} + +/// Synthesizes `input` (plain text or SSML) to a RIFF/WAVE buffer. +fn synthesize_wav(input: &str, ssml: bool) -> Vec { + if !input.trim().is_empty() { + #[cfg(windows)] + if let Some(pcm) = sapi::speak_pcm16(input, ssml) { + return wrap_wav_pcm16(&pcm, SAMPLE_RATE, CHANNELS); + } + #[cfg(not(windows))] + let _ = ssml; + } + wrap_wav_pcm16(&[], SAMPLE_RATE, CHANNELS) +} + +/// `cb(info, context) -> bool` (continue). Reports our default system voice. extern "system" fn enumerate_voices( _: This, - _context: *mut c_void, - _callback: *const c_void, + context: *mut c_void, + callback: Option, ) -> HRESULT { + let Some(cb) = callback else { + return E_INVALIDARG; + }; + let info = VoiceInfo { + description: DEFAULT_DESCRIPTION.as_ptr().cast(), + display_name: DEFAULT_DISPLAY_NAME.as_ptr().cast(), + gender: 0, + voice_id: DEFAULT_VOICE_ID.as_ptr().cast(), + language: DEFAULT_LANGUAGE.as_ptr().cast(), + }; + let _ = cb(&info, context); S_OK } -extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT { - put(out, &raw const SYNTHESIZER) + +extern "system" fn create(_: This, out: *mut *mut c_void) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let synth = Box::into_raw(Box::new(Synthesizer { voice_id: None })); + // SAFETY: checked non-null; the title passes room for the handle. + unsafe { out.write(synth.cast()) }; + S_OK } -extern "system" fn close(_: This, _: *const u8) -> HRESULT { + +extern "system" fn close_synthesizer(_: This, handle: *mut c_void) -> HRESULT { + if !handle.is_null() { + // SAFETY: handle was allocated by `create` via `Box::into_raw`. + drop(unsafe { Box::from_raw(handle.cast::()) }); + } S_OK } -extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { + +extern "system" fn set_default_voice(_: This, handle: *mut c_void) -> HRESULT { + if handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: live handle from `create`. + unsafe { (*handle.cast::()).voice_id = None }; S_OK } -extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { + +extern "system" fn set_custom_voice( + _: This, + handle: *mut c_void, + voice_id: *const c_char, +) -> HRESULT { + if handle.is_null() || voice_id.is_null() { + return E_INVALIDARG; + } + let id = read_cstr(voice_id); + // SAFETY: live handle from `create`. + unsafe { (*handle.cast::()).voice_id = Some(id) }; + S_OK +} + +fn make_stream( + handle: *mut c_void, + input: *const c_char, + out: *mut *mut c_void, + ssml: bool, +) -> HRESULT { + if handle.is_null() || input.is_null() || out.is_null() { + return E_INVALIDARG; + } + let text = read_cstr(input); + let wav = synthesize_wav(&text, ssml); + let stream = Box::into_raw(Box::new(Stream { wav })); + // SAFETY: checked non-null; the title passes room for the stream handle. + unsafe { out.write(stream.cast()) }; S_OK } + extern "system" fn create_stream( _: This, - _: *const u8, - words: *const c_char, - out: *mut *const u8, + handle: *mut c_void, + text: *const c_char, + out: *mut *mut c_void, +) -> HRESULT { + make_stream(handle, text, out, false) +} + +extern "system" fn create_stream_ssml( + _: This, + handle: *mut c_void, + ssml: *const c_char, + out: *mut *mut c_void, ) -> HRESULT { - tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); - put(out, &raw const STREAM) + make_stream(handle, ssml, out, true) +} + +extern "system" fn close_stream(_: This, stream: *mut c_void) -> HRESULT { + if !stream.is_null() { + // SAFETY: handle was allocated by `make_stream` via `Box::into_raw`. + drop(unsafe { Box::from_raw(stream.cast::()) }); + } + S_OK } -extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { - put(out, SILENCE.len()) + +extern "system" fn stream_size(_: This, stream: *mut c_void, size: *mut usize) -> HRESULT { + if stream.is_null() { + return E_INVALIDARG; + } + // SAFETY: live handle from `make_stream`. + let len = unsafe { &*stream.cast::() }.wav.len(); + put(size, len) } + extern "system" fn stream_data( _: This, - _: *const u8, + stream: *mut c_void, size: usize, buffer: *mut u8, used: *mut usize, ) -> HRESULT { - if buffer.is_null() || size < SILENCE.len() { - return super::xasync::E_NOT_SUFFICIENT_BUFFER; + if stream.is_null() || buffer.is_null() { + return E_INVALIDARG; + } + // SAFETY: live handle from `make_stream`. + let wav = &unsafe { &*stream.cast::() }.wav; + if size < wav.len() { + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(wav.len()) }; + } + return E_INSUFFICIENT_BUFFER; } - // SAFETY: the buffer holds `size` bytes, checked above. - unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; + // SAFETY: the title's buffer holds at least `wav.len()` bytes. + unsafe { std::ptr::copy_nonoverlapping(wav.as_ptr(), buffer, wav.len()) }; if !used.is_null() { // SAFETY: checked non-null. - unsafe { used.write(SILENCE.len()) }; + unsafe { used.write(wav.len()) }; } S_OK } +/// Slots by the 2020 order; Grand Theft Auto VI calls 0x40-0x80 and 0xa8. static VTABLE: Methods<22> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - missing::<3> as *const (), // 0x18 closed captions - missing::<4> as *const (), // 0x20 - missing::<5> as *const (), // 0x28 high contrast - missing::<6> as *const (), // 0x30 speech to text - missing::<7> as *const (), // 0x38 - enumerate_voices as *const (), // 0x40 - create as *const (), // 0x48 - close as *const (), // 0x50 - set_default_voice as *const (), // 0x58 - set_custom_voice as *const (), // 0x60 - create_stream as *const (), // 0x68 from text - close as *const (), // 0x70 a stream - stream_size as *const (), // 0x78 - stream_data as *const (), // 0x80 - missing::<17> as *const (), // 0x88 speech to text - missing::<18> as *const (), // 0x90 - missing::<19> as *const (), // 0x98 - missing::<20> as *const (), // 0xa0 - create_stream as *const (), // 0xa8 from SSML + missing::<3> as *const (), + missing::<4> as *const (), + missing::<5> as *const (), + missing::<6> as *const (), + missing::<7> as *const (), + enumerate_voices as *const (), // 0x40 + create as *const (), // 0x48 + close_synthesizer as *const (), // 0x50 + set_default_voice as *const (), // 0x58 + set_custom_voice as *const (), // 0x60 + create_stream as *const (), // 0x68 text + close_stream as *const (), // 0x70 + stream_size as *const (), // 0x78 + stream_data as *const (), // 0x80 + missing::<17> as *const (), // 0x88 + missing::<18> as *const (), // 0x90 + missing::<19> as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + create_stream_ssml as *const (), // 0xa8 SSML ]); +/// Windows SAPI 5 speech synthesis via dynamically loaded `ole32.dll` COM +/// entry points and raw `ISpVoice`/`ISpStream` vtable calls. +#[cfg(windows)] +mod sapi { + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + use windows_sys::Win32::System::Memory::{GlobalLock, GlobalSize, GlobalUnlock}; + use windows_sys::core::{PCSTR, w}; + + use super::{BITS_PER_SAMPLE, CHANNELS, SAMPLE_RATE}; + use crate::modules::xgameruntime::{Guid, HRESULT}; + + const COINIT_MULTITHREADED: u32 = 0; + const CLSCTX_INPROC_SERVER: u32 = 1; + const RPC_E_CHANGED_MODE: HRESULT = 0x8001_0106_u32 as i32; + + const SPF_IS_XML: u32 = 8; + const SPF_IS_NOT_XML: u32 = 16; + const SPF_PARSE_SSML: u32 = 256; + + const CLSID_SP_VOICE: Guid = Guid::new( + 0x9674_9377, + 0x3391, + 0x11d2, + [0x9e, 0xe3, 0x00, 0xc0, 0x4f, 0x79, 0x73, 0x96], + ); + const IID_ISP_VOICE: Guid = Guid::new( + 0x6c44_df74, + 0x72b9, + 0x4992, + [0xa1, 0xec, 0xef, 0x99, 0x6e, 0x04, 0x22, 0xd4], + ); + const CLSID_SP_STREAM: Guid = Guid::new( + 0x715d_9c59, + 0x4442, + 0x11d2, + [0x96, 0x05, 0x00, 0xc0, 0x4f, 0x8e, 0xe6, 0x28], + ); + const IID_ISP_STREAM: Guid = Guid::new( + 0x12e3_cca9, + 0x7518, + 0x44c5, + [0xa5, 0xe7, 0xba, 0x5a, 0x79, 0xcb, 0x92, 0x9e], + ); + const SPDFID_WAVE_FORMAT_EX: Guid = Guid::new( + 0xc31a_dbae, + 0x527f, + 0x4ff5, + [0xa2, 0x30, 0xf6, 0x2b, 0xb6, 0x1f, 0xf7, 0x0c], + ); + + #[repr(C)] + struct WaveFormatEx { + format_tag: u16, + channels: u16, + samples_per_sec: u32, + avg_bytes_per_sec: u32, + block_align: u16, + bits_per_sample: u16, + cb_size: u16, + } + + struct Ole32 { + co_init: unsafe extern "system" fn(*const c_void, u32) -> HRESULT, + co_uninit: unsafe extern "system" fn(), + co_create: unsafe extern "system" fn( + *const Guid, + *mut c_void, + u32, + *const Guid, + *mut *mut c_void, + ) -> HRESULT, + create_stream: unsafe extern "system" fn(*mut c_void, i32, *mut *mut c_void) -> HRESULT, + get_hglobal: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT, + } + + fn ole32() -> Option<&'static Ole32> { + static LIB: OnceLock> = OnceLock::new(); + LIB.get_or_init(|| { + // SAFETY: loading standard system `ole32.dll` and resolving documented exports. + unsafe { + let module = LoadLibraryW(w!("ole32.dll")); + if module.is_null() { + return None; + } + let sym = |name: PCSTR| GetProcAddress(module, name); + Some(Ole32 { + co_init: std::mem::transmute(sym(c"CoInitializeEx".as_ptr().cast())?), + co_uninit: std::mem::transmute(sym(c"CoUninitialize".as_ptr().cast())?), + co_create: std::mem::transmute(sym(c"CoCreateInstance".as_ptr().cast())?), + create_stream: std::mem::transmute(sym( + c"CreateStreamOnHGlobal".as_ptr().cast(), + )?), + get_hglobal: std::mem::transmute(sym( + c"GetHGlobalFromStream".as_ptr().cast(), + )?), + }) + } + }) + .as_ref() + } + + /// Calls `IUnknown::Release` (vtable slot 2) on a non-null COM interface pointer. + unsafe fn com_release(obj: *mut c_void) { + if obj.is_null() { + return; + } + // SAFETY: `obj` is a live COM interface pointer whose slot 2 is `Release`. + unsafe { + let vtbl = *(obj as *const *const *const c_void); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute(*vtbl.add(2)); + release(obj); + } + } + + /// RAII guard for a COM interface pointer. + struct ComPtr(*mut c_void); + impl Drop for ComPtr { + fn drop(&mut self) { + // SAFETY: we own one reference to this COM interface pointer. + unsafe { com_release(self.0) }; + } + } + + /// Synthesizes `text` using SAPI 5 into raw 16 kHz mono 16-bit PCM bytes. + pub(super) fn speak_pcm16(text: &str, ssml: bool) -> Option> { + let ole = ole32()?; + // SAFETY: COM apartment initialization for this thread. + let init_hr = unsafe { (ole.co_init)(std::ptr::null(), COINIT_MULTITHREADED) }; + let should_uninit = init_hr >= 0; + if !should_uninit && init_hr != RPC_E_CHANGED_MODE { + return None; + } + struct CoGuard<'a>(&'a Ole32, bool); + impl Drop for CoGuard<'_> { + fn drop(&mut self) { + if self.1 { + // SAFETY: balanced with a successful `CoInitializeEx`. + unsafe { (self.0.co_uninit)() }; + } + } + } + let _co = CoGuard(ole, should_uninit); + + let mut mem_stream_raw = std::ptr::null_mut(); + // SAFETY: `CreateStreamOnHGlobal(NULL, TRUE, &out)` allocates an HGLOBAL-backed IStream. + if unsafe { (ole.create_stream)(std::ptr::null_mut(), 1, &mut mem_stream_raw) } < 0 + || mem_stream_raw.is_null() + { + return None; + } + let mem_stream = ComPtr(mem_stream_raw); + + let mut sp_stream_raw = std::ptr::null_mut(); + // SAFETY: instantiating standard in-process SAPI `SpStream`. + if unsafe { + (ole.co_create)( + &CLSID_SP_STREAM, + std::ptr::null_mut(), + CLSCTX_INPROC_SERVER, + &IID_ISP_STREAM, + &mut sp_stream_raw, + ) + } < 0 + || sp_stream_raw.is_null() + { + return None; + } + let sp_stream = ComPtr(sp_stream_raw); + + let mut voice_raw = std::ptr::null_mut(); + // SAFETY: instantiating standard in-process SAPI `SpVoice`. + if unsafe { + (ole.co_create)( + &CLSID_SP_VOICE, + std::ptr::null_mut(), + CLSCTX_INPROC_SERVER, + &IID_ISP_VOICE, + &mut voice_raw, + ) + } < 0 + || voice_raw.is_null() + { + return None; + } + let voice = ComPtr(voice_raw); + + let block_align = CHANNELS * (BITS_PER_SAMPLE / 8); + let wfx = WaveFormatEx { + format_tag: 1, // WAVE_FORMAT_PCM + channels: CHANNELS, + samples_per_sec: SAMPLE_RATE, + avg_bytes_per_sec: SAMPLE_RATE * u32::from(block_align), + block_align, + bits_per_sample: BITS_PER_SAMPLE, + cb_size: 0, + }; + + // ISpStream::SetBaseStream is slot 15 (3 IUnknown + 2 ISequentialStream + // + 9 IStream + 1 ISpStreamFormat). + // SAFETY: calling verified COM vtable slot 15 on live `ISpStream`. + let set_base_hr = unsafe { + let vtbl = *(sp_stream.0 as *const *const *const c_void); + let set_base: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + *const Guid, + *const WaveFormatEx, + ) -> HRESULT = std::mem::transmute(*vtbl.add(15)); + set_base(sp_stream.0, mem_stream.0, &SPDFID_WAVE_FORMAT_EX, &wfx) + }; + if set_base_hr < 0 { + return None; + } + + // ISpVoice::SetOutput is slot 13 (3 IUnknown + 7 ISpNotifySource + 3 ISpEventSource). + // SAFETY: calling verified COM vtable slot 13 on live `ISpVoice`. + let set_out_hr = unsafe { + let vtbl = *(voice.0 as *const *const *const c_void); + let set_output: unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> HRESULT = + std::mem::transmute(*vtbl.add(13)); + set_output(voice.0, sp_stream.0, 0) + }; + if set_out_hr < 0 { + return None; + } + + let wide: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); + let flags = if ssml { + SPF_IS_XML | SPF_PARSE_SSML + } else { + SPF_IS_NOT_XML + }; + + // ISpVoice::Speak is slot 20 (13 SetOutput + 7 methods). + // SAFETY: calling verified COM vtable slot 20 with NUL-terminated UTF-16 text. + let speak_hr = unsafe { + let vtbl = *(voice.0 as *const *const *const c_void); + let speak: unsafe extern "system" fn( + *mut c_void, + *const u16, + u32, + *mut u32, + ) -> HRESULT = std::mem::transmute(*vtbl.add(20)); + speak(voice.0, wide.as_ptr(), flags, std::ptr::null_mut()) + }; + if speak_hr < 0 { + return None; + } + + // ISpStream::Close is slot 18. + // SAFETY: calling verified COM vtable slot 18 to flush written audio to `mem_stream`. + let _ = unsafe { + let vtbl = *(sp_stream.0 as *const *const *const c_void); + let close: unsafe extern "system" fn(*mut c_void) -> HRESULT = + std::mem::transmute(*vtbl.add(18)); + close(sp_stream.0) + }; + + let mut hglobal = std::ptr::null_mut(); + // SAFETY: `mem_stream` was created by `CreateStreamOnHGlobal`. + if unsafe { (ole.get_hglobal)(mem_stream.0, &mut hglobal) } < 0 || hglobal.is_null() { + return None; + } + + // SAFETY: locking the stream's HGLOBAL memory block to copy out synthesized PCM. + let bytes = unsafe { + let size = GlobalSize(hglobal); + if size == 0 { + return None; + } + let ptr = GlobalLock(hglobal); + if ptr.is_null() { + return None; + } + let copied = std::slice::from_raw_parts(ptr.cast::(), size).to_vec(); + let _ = GlobalUnlock(hglobal); + copied + }; + Some(bytes) + } +} + #[cfg(test)] mod tests { use super::*; - use crate::modules::xgameruntime::method; #[test] - fn streams_are_empty_wave_files() { - let this: This = &OBJECT; - type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; - type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; - type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; - type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; - let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); - assert_eq!(method::(&OBJECT, 0x48)(this, &mut synth), S_OK); - let say = method::(&OBJECT, 0x68); - assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); - assert_eq!(method::(&OBJECT, 0x78)(this, stream, &mut size), S_OK); - let mut wav = vec![0u8; size]; - let mut used = 0; - let data = method::(&OBJECT, 0x80); - assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); + fn wrap_wav_builds_valid_16khz_mono_pcm_header() { + let pcm = [0x12u8, 0x34, 0x56, 0x78]; + let wav = wrap_wav_pcm16(&pcm, 16_000, 1); + assert_eq!(wav.len(), 48); + assert_eq!(&wav[0..4], b"RIFF"); + assert_eq!(u32::from_le_bytes(wav[4..8].try_into().unwrap()), 40); + assert_eq!(&wav[8..12], b"WAVE"); + assert_eq!(&wav[12..16], b"fmt "); + assert_eq!(u16::from_le_bytes(wav[20..22].try_into().unwrap()), 1); // PCM + assert_eq!(u16::from_le_bytes(wav[22..24].try_into().unwrap()), 1); // mono + assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); + assert_eq!(u32::from_le_bytes(wav[28..32].try_into().unwrap()), 32_000); + assert_eq!(u16::from_le_bytes(wav[32..34].try_into().unwrap()), 2); + assert_eq!(u16::from_le_bytes(wav[34..36].try_into().unwrap()), 16); + assert_eq!(&wav[36..40], b"data"); + assert_eq!(u32::from_le_bytes(wav[40..44].try_into().unwrap()), 4); + assert_eq!(&wav[44..48], &pcm); + } + + #[test] + fn wrap_wav_preserves_existing_riff_header() { + let existing = wrap_wav_pcm16(&[1, 2], 16_000, 1); + assert_eq!(wrap_wav_pcm16(&existing, 16_000, 1), existing); + } + + #[test] + fn synthesizer_and_stream_lifecycle_handles_text_and_ssml() { + let mut synth = std::ptr::null_mut(); + assert_eq!(create(&OBJECT, &mut synth), S_OK); + assert!(!synth.is_null()); + assert_eq!( - (&wav[..4], &wav[8..16], &wav[36..40]), - (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) + set_custom_voice(&OBJECT, synth, DEFAULT_VOICE_ID.as_ptr().cast()), + S_OK ); - assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); - assert_eq!(used, 44); + assert_eq!(set_default_voice(&OBJECT, synth), S_OK); + + let mut stream = std::ptr::null_mut(); + assert_eq!( + create_stream(&OBJECT, synth, c"Hello Los Santos".as_ptr(), &mut stream), + S_OK + ); + assert!(!stream.is_null()); + + let mut size = 0usize; + assert_eq!(stream_size(&OBJECT, stream, &mut size), S_OK); + assert!(size >= 44); + + let mut tiny = [0u8; 8]; + let mut needed = 0usize; + assert_eq!( + stream_data(&OBJECT, stream, tiny.len(), tiny.as_mut_ptr(), &mut needed), + E_INSUFFICIENT_BUFFER + ); + assert_eq!(needed, size); + + let mut buf = vec![0u8; size]; + let mut written = 0usize; + assert_eq!( + stream_data(&OBJECT, stream, buf.len(), buf.as_mut_ptr(), &mut written), + S_OK + ); + assert_eq!(written, size); + assert_eq!(&buf[0..4], b"RIFF"); + assert_eq!(&buf[8..12], b"WAVE"); + + assert_eq!(close_stream(&OBJECT, stream), S_OK); + + let mut ssml_stream = std::ptr::null_mut(); + assert_eq!( + create_stream_ssml( + &OBJECT, + synth, + c"Test".as_ptr(), + &mut ssml_stream + ), + S_OK + ); + assert_eq!(close_stream(&OBJECT, ssml_stream), S_OK); + assert_eq!(close_synthesizer(&OBJECT, synth), S_OK); + } + + #[test] + fn enumerate_voices_reports_default_voice() { + extern "system" fn collect(info: *const VoiceInfo, ctx: *mut c_void) -> bool { + // SAFETY: test passes a valid pointer to `usize`. + let count = unsafe { &mut *ctx.cast::() }; + // SAFETY: callback receives a live `VoiceInfo`. + let info = unsafe { &*info }; + assert!(!info.voice_id.is_null()); + assert!(!info.language.is_null()); + assert!(!info.display_name.is_null()); + assert!(!info.description.is_null()); + *count += 1; + true + } + let mut count = 0usize; + assert_eq!( + enumerate_voices(&OBJECT, (&raw mut count).cast(), Some(collect)), + S_OK + ); + assert_eq!(count, 1); } } diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 46912d7c51..eb59c5a154 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -13,7 +13,9 @@ use std::sync::atomic::{AtomicU32, Ordering}; -use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc}; +use victory_formats::texture::{ + Dimension, Error, Layout, MetadataFlags, Swizzle, Texture, TextureDesc, +}; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; @@ -147,16 +149,19 @@ fn texture(desc: &ResourceDesc) -> Option { l if l & !0xff == SWIZZLED => Swizzle(l & 0xff), _ => return None, }; - let texture = Texture::new(&TextureDesc { - dimension, - width: u32::try_from(desc.width).ok()?, - height: desc.height, - depth_or_array: u32::from(desc.depth_or_array), - mips: u32::from(desc.mips), - format: desc.format, - samples: desc.samples.max(1), - swizzle, - }) + let texture = Texture::with_metadata( + &TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array), + mips: u32::from(desc.mips), + format: desc.format, + samples: desc.samples.max(1), + swizzle, + }, + MetadataFlags::from_d3d12_flags(desc.flags), + ) .ok()?; // The layout struct has room for 15 mips. (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) @@ -193,7 +198,7 @@ pub struct MipOut { #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct PlaneOut { - /// 1 data, 7 depth, 8 stencil (metadata planes are not made). + /// 1 data, 2 CMASK, 3 FMASK, 4 HTILE, 7 depth, 8 stencil, 9 DCC. pub usage: u32, pub size: u64, pub slice_size: u64, @@ -303,7 +308,8 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { out.size = c.texture.size; out.alignment = c.texture.alignment; out.mips = c.mips; - out.planes = c.texture.planes.len() as u32; + let total_planes = (c.texture.planes.len() + c.texture.metadata.len()).min(out.plane.len()); + out.planes = total_planes as u32; out.dimension = c.desc.dimension; // The library calls a depth plane "depth" only beside stencil or // without mips. @@ -327,16 +333,31 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { *mip = mip_out(&c.desc, l, i); } } + let data_planes = c.texture.planes.len(); + for (plane, m) in out.plane[data_planes..total_planes] + .iter_mut() + .zip(&c.texture.metadata) + { + plane.usage = m.kind.xg_usage(); + plane.size = m.size; + plane.slice_size = m.slice_size; + plane.offset = m.offset; + plane.alignment = m.alignment; + plane.element_bytes = m.element_bytes; + plane.standard_mips = 1; + plane.tail_mips = 0; + } S_OK } /// The plane, its mip and array slice for a subresource index, and the -/// tiled bytes and the linear bytes the copy touches. +/// tiled offset/length and linear bytes the copy touches. struct CopyArgs<'a> { layout: &'a Layout, mip: u32, slice: u32, - tiled: usize, + tiled_offset: usize, + tiled_len: usize, linear: usize, } @@ -347,18 +368,37 @@ fn copy_args( row: u32, depth: u32, ) -> Option> { + if c.mips == 0 { + return None; + } let p = c.texture.planes.get(plane as usize)?; let l = &p.layout; let (mip, slice) = (subresource % c.mips, subresource / c.mips); + if slice >= l.slices { + return None; + } let m = l.mips.get(mip as usize)?; - let bytes = m.width as usize * l.desc.element_bytes as usize; + let bytes = (m.width as usize).checked_mul(l.desc.element_bytes as usize)?; let depths = l.subresource_depth(mip) as usize; - let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; + let height = m.height as usize; + if depths == 0 || height == 0 { + return None; + } + let depth_span = depths.checked_sub(1)?.checked_mul(depth as usize)?; + let row_span = height.checked_sub(1)?.checked_mul(row as usize)?; + let linear = depth_span.checked_add(row_span)?.checked_add(bytes)?; + let tiled_offset = usize::try_from(p.offset).ok()?; + let tiled_len = usize::try_from(l.size).ok()?; + let _ = tiled_offset.checked_add(tiled_len)?; + if tiled_len > isize::MAX as usize || linear > isize::MAX as usize { + return None; + } Some(CopyArgs { layout: l, mip, slice, - tiled: (p.offset + l.size) as usize, + tiled_offset, + tiled_len, linear, }) } @@ -388,11 +428,11 @@ extern "system" fn copy_into( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } - let offset = c.texture.planes[plane as usize].offset as usize; - // SAFETY: the title's memory holds the whole texture and its rows. + // SAFETY: checked non-null and bounded span; the title's memory holds the + // whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts_mut(tiled.add(a.tiled_offset), a.tiled_len), std::slice::from_raw_parts(linear, a.linear), ) }; @@ -425,11 +465,11 @@ extern "system" fn copy_from( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } - let offset = c.texture.planes[plane as usize].offset as usize; - // SAFETY: the title's memory holds the whole texture and its rows. + // SAFETY: checked non-null and bounded span; the title's memory holds the + // whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts(tiled.add(a.tiled_offset), a.tiled_len), std::slice::from_raw_parts_mut(linear, a.linear), ) }; @@ -484,6 +524,14 @@ extern "system" fn tiling( if l.thick { return E_NOTIMPL; } + if l.block[0] == 0 || l.block[1] == 0 { + return E_FAIL; + } + // SAFETY: caller passes null or a valid `count` pointer; reject null + // `out` when the caller asks to write `*count > 0` entries. + if !count.is_null() && unsafe { *count } > 0 && out.is_null() { + return E_INVALIDARG; + } let standard = l.first_tail_mip; let tail = standard < c.mips; let tail_tiles = match standard { @@ -492,8 +540,8 @@ extern "system" fn tiling( _ => 0, }; let block = l.desc.block; - // SAFETY: each output is null or room for its value; `out` has room - // for `*count` entries. + // SAFETY: each output is null or room for its value; `out` is non-null + // whenever `*count > 0` (checked above). unsafe { if let Some(t) = tiles.as_mut() { *t = (l.size / TILE) as u32; @@ -511,26 +559,29 @@ extern "system" fn tiling( } if let Some(n) = count.as_mut() { let slices = if tail { l.slices.min(2) } else { l.slices }; - let wanted = (standard * slices).saturating_sub(first).min(*n); - for i in 0..wanted { - let (slice, mip) = ((first + i) / standard, (first + i) % standard); - let m = &l.mips[mip as usize]; - let entry = if tail && slice > 0 { - SubresourceTiling { - width: 0, - height: 0, - depth: 0, - start: 0, - } - } else { - SubresourceTiling { - width: m.pitch / l.block[0], - height: (m.rows / l.block[1]) as u16, - depth: 1, - start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, - } - }; - out.add(i as usize).write(entry); + let total = standard.saturating_mul(slices); + let wanted = total.saturating_sub(first).min(*n); + if standard > 0 { + for i in 0..wanted { + let (slice, mip) = ((first + i) / standard, (first + i) % standard); + let m = &l.mips[mip as usize]; + let entry = if tail && slice > 0 { + SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + } + } else { + SubresourceTiling { + width: m.pitch / l.block[0], + height: (m.rows / l.block[1]) as u16, + depth: 1, + start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, + } + }; + out.add(i as usize).write(entry); + } } *n = wanted; } @@ -777,4 +828,70 @@ mod tests { assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); assert!(module().exports.len() == 2); } + + #[test] + fn render_target_and_depth_layouts_report_metadata_planes() { + let mut rt_desc = desc(1920, 1080, 1, 28, 0); + rt_desc.flags = ALLOW_RENDER_TARGET; + let c = create(&rt_desc); + let mut l = std::mem::MaybeUninit::::zeroed(); + assert_eq!(layout(c, l.as_mut_ptr()), S_OK); + // SAFETY: filled by `layout`. + let l = unsafe { l.assume_init() }; + assert_eq!(l.planes, 2); + assert_eq!(l.plane[0].usage, 1); // data + assert_eq!(l.plane[1].usage, 9); // DCC + assert!(l.plane[1].offset >= l.plane[0].size); + assert!(l.plane[1].size > 0); + assert_eq!(release(c), 0); + + let mut ds_desc = desc(1920, 1080, 1, 20, 0); + ds_desc.flags = ALLOW_DEPTH_STENCIL; + let c = create(&ds_desc); + let mut l = std::mem::MaybeUninit::::zeroed(); + assert_eq!(layout(c, l.as_mut_ptr()), S_OK); + // SAFETY: filled by `layout`. + let l = unsafe { l.assume_init() }; + assert_eq!(l.planes, 3); + assert_eq!(l.plane[0].usage, 7); // depth + assert_eq!(l.plane[1].usage, 8); // stencil + assert_eq!(l.plane[2].usage, 4); // HTILE + assert!(l.plane[2].offset >= l.plane[1].offset + l.plane[1].size); + assert_eq!(release(c), 0); + } + + #[test] + fn tiling_and_copy_reject_null_out_and_out_of_range_subresources() { + let c = create(&desc(256, 256, 2, 28, 0x109)); + let mut tiles = 0; + let mut n = 2; + assert_eq!( + tiling( + c, + &mut tiles, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut n, + 0, + std::ptr::null_mut(), + ), + E_INVALIDARG + ); + // Subresource index past `mips * slices` must be rejected cleanly. + let mut buf = [0u8; 64]; + assert_eq!( + copy_into(c, buf.as_mut_ptr(), 0, 99, buf.as_ptr(), 256, 0), + E_INVALIDARG + ); + assert_eq!( + copy_from(c, buf.as_mut_ptr(), 0, 99, 0, buf.as_ptr(), 256, 0), + E_INVALIDARG + ); + // Overflowing pitch must fail instead of wrapping slice length. + assert_eq!( + copy_into(c, buf.as_mut_ptr(), 0, 0, buf.as_ptr(), u32::MAX, u32::MAX), + E_INVALIDARG + ); + assert_eq!(release(c), 0); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 07a149acf0..8a6829d774 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -384,7 +384,36 @@ fn physical() -> MutexGuard<'static, Physical> { PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) } -/// `count` is in and out (pages wanted, pages given); all or nothing here. +/// Allocates up to `wanted` pages by asking `create` for sections of `chunk` +/// pages at a time: tries `wanted` in one section first, and on failure +/// halves the chunk size down to `min_chunk` so a host with tight commit +/// headroom still returns as many pages as it can. +fn alloc_sections( + wanted: usize, + min_chunk: usize, + mut create: impl FnMut(usize) -> Option, +) -> Vec<(T, usize)> { + let mut sections = Vec::new(); + let mut left = wanted; + let mut chunk = wanted; + let floor = min_chunk.max(1); + while left > 0 { + let ask = chunk.min(left); + if let Some(section) = create(ask) { + sections.push((section, ask)); + left -= ask; + } else if ask > floor { + chunk = (ask / 2).max(floor); + } else { + break; + } + } + sections +} + +/// `count` is in and out (pages wanted, pages given). Tries one section for +/// the whole request first, and on commit failure falls back to smaller +/// chunks (returning a partial count if the host hits its commit limit). pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, count: *mut usize, @@ -395,52 +424,85 @@ pub extern "system" fn XMemAllocatePhysicalPages( } // SAFETY: checked non-null. let n = unsafe { *count }; - let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else { + if n.checked_mul(PAGE).filter(|&s| s > 0).is_none() { return 0; - }; - // A pagefile-backed section of `size` bytes, its pages committed when - // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 - // GiB at once, which a busy host often cannot commit (error 1450). - // SAFETY: plain section creation. - let handle = unsafe { - CreateFileMappingW( - INVALID_HANDLE_VALUE, - std::ptr::null(), - // Under Wine a committed section is a sparse file, free until - // touched, and committing a reserved one page by page costs a - // wineserver request each that scans every range committed so - // far: commit it whole there. - PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, - (size as u64 >> 32) as u32, - size as u32, - std::ptr::null(), - ) - }; - if handle.is_null() { - let error = std::io::Error::last_os_error(); + } + // Under Wine a committed section is a sparse file, free until touched, + // and committing a reserved one page by page costs a wineserver request + // each that scans every range committed so far: commit it whole there. + let section_flags = PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }; + // Fall back down to 64 MiB (1024 x 64 KiB pages) chunks when the host + // cannot satisfy a multi-GiB request in a single section. + const MIN_CHUNK_PAGES: usize = (64 << 20) / PAGE; + let mut last_error = None; + let sections = alloc_sections(n, MIN_CHUNK_PAGES, |ask| { + let size = ask.checked_mul(PAGE)?; + // SAFETY: plain section creation. + let handle = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + section_flags, + (size as u64 >> 32) as u32, + size as u32, + std::ptr::null(), + ) + }; + if handle.is_null() { + last_error = Some(std::io::Error::last_os_error()); + None + } else { + Some(Arc::new(Section(handle))) + } + }); + let got: usize = sections.iter().map(|&(_, c)| c).sum(); + if got == 0 { + let error = last_error.unwrap_or_else(std::io::Error::last_os_error); tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); // SAFETY: checked non-null. unsafe { count.write(0) }; return 0; } - tracing::debug!( - n, - flags = format_args!("{flags:#x}"), - "XMemAllocatePhysicalPages" - ); - let section = Arc::new(Section(handle)); + if got < n { + tracing::warn!( + wanted = n, + got, + chunks = sections.len(), + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages: partial allocation" + ); + } else if sections.len() > 1 { + tracing::info!( + n = got, + chunks = sections.len(), + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages: satisfied in chunks" + ); + } else { + tracing::debug!( + n = got, + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages" + ); + } + // SAFETY: checked non-null; report the actual count allocated. + unsafe { count.write(got) }; let mut physical = physical(); let first = physical.next_page; - physical.next_page += n * FRAMES; - for index in 0..n { - let slice = Slice { - section: section.clone(), - index, - }; - let number = first + index * FRAMES; - physical.pages.insert(number, slice); - // SAFETY: the title passes room for `n` page numbers. - unsafe { pages.add(index).write(number) }; + physical.next_page += got * FRAMES; + let mut out = 0usize; + for (section, chunk_pages) in sections { + for index in 0..chunk_pages { + let slice = Slice { + section: section.clone(), + index, + }; + let number = first + out * FRAMES; + physical.pages.insert(number, slice); + // SAFETY: the title passes room for `n >= got` page numbers. + unsafe { pages.add(out).write(number) }; + out += 1; + } } 1 } @@ -539,19 +601,37 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { - let Some(runs) = runs(pages, offset, data.len()) else { - return false; + let Ok(ok) = write_physical_with::(pages, offset, data.len(), |at, dst| { + dst.copy_from_slice(&data[at..at + dst.len()]); + Ok(()) + }); + ok +} + +/// Maps each run of consecutive physical pages behind `[offset, offset + len)` +/// once and invokes `fill(byte_offset, run_bytes)` directly on the mapped view. +/// Avoids intermediate multi-MiB staging allocations and double copies when +/// DirectStorage writes raw data into non-consecutive physical pages. +pub(crate) fn write_physical_with( + pages: &[usize], + offset: usize, + len: usize, + mut fill: impl FnMut(usize, &mut [u8]) -> Result<(), E>, +) -> Result { + let Some(runs) = runs(pages, offset, len) else { + return Ok(false); }; let (mut within, mut done) = (offset % PAGE, 0); for (slice, n) in &runs { let Some(mut view) = View::map(slice, *n) else { - return false; + return Ok(false); }; - let k = (n * PAGE - within).min(data.len() - done); - view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + let k = (n * PAGE - within).min(len - done); + fill(done, &mut view.bytes()[within..within + k])?; (within, done) = (0, done + k); } - true + victory_gpu::physical_memory_written(); + Ok(true) } /// Bytes `[offset, offset + len)` of physical pages, writable in place @@ -563,6 +643,12 @@ pub(crate) struct PageWindow { len: usize, } +impl Drop for PageWindow { + fn drop(&mut self) { + victory_gpu::physical_memory_written(); + } +} + impl PageWindow { pub(crate) fn bytes(&mut self) -> &mut [u8] { let (within, len) = (self.within, self.len); @@ -743,8 +829,10 @@ fn commit(base: usize, len: usize) -> bool { } let error = std::io::Error::last_os_error(); if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { - let mut info = PERFORMANCE_INFORMATION::default(); - info.cb = size_of::() as u32; + let mut info = PERFORMANCE_INFORMATION { + cb: size_of::() as u32, + ..Default::default() + }; // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); @@ -1189,4 +1277,24 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + + #[test] + fn alloc_sections_halves_and_returns_partial_on_commit_limit() { + // Host caps individual sections at 4 pages and total budget at 7 pages. + let mut budget = 7usize; + let got = alloc_sections(10, 2, |ask| { + if ask <= 4 && ask <= budget { + budget -= ask; + Some(ask) + } else { + None + } + }); + assert_eq!(got, vec![(2, 2), (2, 2), (2, 2)]); + assert_eq!(got.iter().map(|&(_, c)| c).sum::(), 6); + + // Full request fits in one section: single call, no splitting. + let one = alloc_sections(8, 2, Some); + assert_eq!(one, vec![(8, 8)]); + } } diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 33c05d600e..c6e0ca5e33 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -96,6 +96,10 @@ extern "system" fn close(_: This, _: Handle) {} extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 { i32::from(a != b) } +/// One local offline user. +extern "system" fn get_max_users(_: This, out: *mut u32) -> HRESULT { + put(out, 1) +} /// The async provider for adding a user: done at once, the result is a /// handle. @@ -260,7 +264,7 @@ extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Hand USER_NOT_FOUND } -// Unset slots (no title seen calls them): maximum users, gamer pictures, +// Unset slots (no title seen calls them): gamer pictures, // the UTF-16 token calls, issue resolution. static VTABLE: Methods<35> = Methods([ missing::<0> as *const (), // 0x00 QueryInterface @@ -269,7 +273,7 @@ static VTABLE: Methods<35> = Methods([ duplicate as *const (), // 0x18 close as *const (), // 0x20 compare as *const (), // 0x28 - missing::<6> as *const (), // 0x30 maximum users + get_max_users as *const (), // 0x30 maximum users add_async as *const (), // 0x38 add_result as *const (), // 0x40 get_local_id as *const (), // 0x48 @@ -395,5 +399,11 @@ mod tests { xasync::XAsyncGetStatus(&mut block, true), FAILED_TO_GET_TOKEN ); + + type GetMaxUsers = extern "system" fn(This, *mut u32) -> HRESULT; + let get_max = slot::(&OBJECT, 0x30); + let mut max_users = 0u32; + assert_eq!(get_max(this, &mut max_users), S_OK); + assert_eq!(max_users, 1); } } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index c8479c5e22..86750ec64f 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -95,7 +95,13 @@ impl Title { .find(|(p, _)| p == path) .map(|(_, text)| text.as_str()) }; - let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let id = get("Game/TitleId").and_then(|v| { + let hex = v + .strip_prefix("0x") + .or_else(|| v.strip_prefix("0X")) + .unwrap_or(v); + u32::from_str_radix(hex, 16).ok() + }); let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); Title { id: id.unwrap_or(0), @@ -148,10 +154,20 @@ fn elements(text: &str) -> Vec<(String, String)> { .next() .unwrap_or(""); path.push(name); - let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + let body = if closed { + String::new() + } else { + let raw = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + [ + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'"), + ("&", "&"), + ] .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + .fold(raw.to_owned(), |b, (entity, c)| b.replace(entity, c)) + }; out.push((path.join("/"), body)); if closed { path.pop(); @@ -223,4 +239,21 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } + + #[test] + fn title_id_allows_0x_prefix_and_self_closing_tags_have_no_body() { + let text = "ignoredtrailing\ + S1"; + let t = Title::from_manifest(text); + assert_eq!(t.id, 0); + assert_eq!(t.store_id, "S1"); + let els = elements(text); + assert!(els.iter().any(|(p, b)| p == "Game/TitleId" && b.is_empty())); + assert!(els.iter().any(|(p, b)| p == "Game/Identity" && b.is_empty())); + + let hex_lower = "0x639aa8dd"; + assert_eq!(Title::from_manifest(hex_lower).id, 0x639A_A8DD); + let hex_upper = "0X1234ABCD"; + assert_eq!(Title::from_manifest(hex_upper).id, 0x1234_ABCD); + } } diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index c8935081bf..a8a0124845 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -50,19 +50,25 @@ pub fn prepare(original: &[u8]) -> Result { layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?; let characteristics = info.characteristics | file_flags::DLL; - write_u16( - &mut bytes, - fh + layout::FILE_HEADER_CHARACTERISTICS, - characteristics, - )?; - write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?; - write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?; + let char_off = fh + .checked_add(layout::FILE_HEADER_CHARACTERISTICS) + .ok_or(PrepareError::Patch("file header characteristics overflow"))?; + write_u16(&mut bytes, char_off, characteristics)?; + let entry_off = opt + .checked_add(layout::OPT_ADDRESS_OF_ENTRY_POINT) + .ok_or(PrepareError::Patch("optional header entry point overflow"))?; + write_u32(&mut bytes, entry_off, 0)?; + let checksum_off = opt + .checked_add(layout::OPT_CHECKSUM) + .ok_or(PrepareError::Patch("optional header checksum overflow"))?; + write_u32(&mut bytes, checksum_off, 0)?; let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY; - write_u16( - &mut bytes, - opt + layout::OPT_DLL_CHARACTERISTICS, - dll_characteristics, - )?; + let dll_char_off = opt + .checked_add(layout::OPT_DLL_CHARACTERISTICS) + .ok_or(PrepareError::Patch( + "optional header DLL characteristics overflow", + ))?; + write_u16(&mut bytes, dll_char_off, dll_characteristics)?; // Windows 10 assigns static TLS to the prepared DLL when its empty // import table is present. The parser has already walked one descriptor @@ -75,8 +81,11 @@ pub fn prepare(original: &[u8]) -> Result { .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE)) .and_then(|offset| rva.checked_add(offset)) .ok_or(PrepareError::Patch("import terminator RVA overflow"))?; + let size_off = at + .checked_add(4) + .ok_or(PrepareError::Patch("import directory size offset overflow"))?; write_u32(&mut bytes, at, terminator)?; - write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?; + write_u32(&mut bytes, size_off, IMPORT_DESCRIPTOR_SIZE)?; } } if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { @@ -89,16 +98,19 @@ pub fn prepare(original: &[u8]) -> Result { let at = info .rva_to_file_offset(tls.directory_rva) .ok_or(PrepareError::Patch("TLS directory is not file-backed"))?; - write_u64( - &mut bytes, - at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS, - 0, - )?; + let cb_off = usize::try_from(at) + .ok() + .and_then(|a| a.checked_add(layout::TLS64_ADDRESS_OF_CALLBACKS)) + .ok_or(PrepareError::Patch("TLS callbacks offset overflow"))?; + write_u64(&mut bytes, cb_off, 0)?; // The field's base relocation would turn the 0 into `delta` whenever // the loader maps the copy away from its preferred base (Wine always // does for DYNAMIC_BASE images), and the loader then reads callbacks // from there. Make that entry a no-op. - let field_rva = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + let field_rva = tls + .directory_rva + .checked_add(layout::TLS64_ADDRESS_OF_CALLBACKS as u32) + .ok_or(PrepareError::Patch("TLS callbacks RVA overflow"))?; for (entry, target) in dir64_relocations(&bytes, &info) { if target == field_rva { write_u16(&mut bytes, entry, 0)?; // IMAGE_REL_BASED_ABSOLUTE @@ -124,34 +136,56 @@ fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else { return out; }; - let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) + let Some(d_size) = d.checked_add(4) else { + return out; + }; + let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d_size)) else { return out; }; let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else { return out; }; - let (mut at, end) = (start as usize, start as usize + size as usize); - while at + 8 <= end { + let Ok(mut at) = usize::try_from(start) else { + return out; + }; + let Some(end) = at.checked_add(size as usize) else { + return out; + }; + let end = end.min(bytes.len()); + while let Some(header_end) = at.checked_add(8) + && header_end <= end + { + let Some(size_at) = at.checked_add(4) else { + break; + }; let (Some(page), Some(block)) = - (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) + (layout::read_u32(bytes, at), layout::read_u32(bytes, size_at)) else { break; }; let block = block as usize; - if block < 8 || at + block > end { + let Some(block_end) = at.checked_add(block) else { + break; + }; + if block < 8 || block_end > end { break; } - for entry in (at + 8..at + block).step_by(2) { - let Some(e) = bytes.get(entry..entry + 2) else { + for entry in (header_end..block_end).step_by(2) { + let Some(entry_end) = entry.checked_add(2) else { + break; + }; + let Some(e) = bytes.get(entry..entry_end) else { break; }; let e = u16::from_le_bytes([e[0], e[1]]); - if e >> 12 == DIR64 { - out.push((entry, page + u32::from(e & 0xFFF))); + if e >> 12 == DIR64 + && let Some(target) = page.checked_add(u32::from(e & 0xFFF)) + { + out.push((entry, target)); } } - at += block; + at = block_end; } out } @@ -166,8 +200,11 @@ fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> { write(bytes, at, &v.to_le_bytes()) } fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { + let end = at + .checked_add(v.len()) + .ok_or(PrepareError::Patch("header field offset overflow"))?; bytes - .get_mut(at..at + v.len()) + .get_mut(at..end) .ok_or(PrepareError::Patch("header field outside of file"))? .copy_from_slice(v); Ok(()) @@ -280,4 +317,11 @@ mod tests { let b = prepare(&original).unwrap(); assert_eq!(a.file_name(), b.file_name()); } + + #[test] + fn write_rejects_overflowing_offset() { + let mut buf = [0u8; 16]; + assert!(write(&mut buf, usize::MAX - 1, &[1, 2, 3, 4]).is_err()); + assert!(write(&mut buf, 14, &[1, 2, 3, 4]).is_err()); + } } diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555adb99..74b873e6b5 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -103,6 +103,9 @@ pub(crate) mod pred { pub const OGE: u8 = 3; pub const OLT: u8 = 4; pub const OLE: u8 = 5; + // Kept for predicate completeness; AMD D3D12 miscompiles `fcmp one` as + // unordered, so `v_cmp_lg` lowers as `OLT | OGT` instead. + #[allow(dead_code)] pub const ONE: u8 = 6; pub const ORD: u8 = 7; pub const UNO: u8 = 8; @@ -260,6 +263,14 @@ impl Module { pub fn int_const(&mut self, ty: Ty, v: i64) -> V { self.constant(ty, Const::Int(v)) } + /// The integer value of `v`, if it is an integer constant. + pub fn int_value(&self, v: V) -> Option { + let V::Const(i) = v else { return None }; + match self.consts.get(i as usize) { + Some(&(_, Const::Int(x))) => Some(x), + _ => None, + } + } pub fn i32(&mut self, v: u32) -> V { let t = self.int(32); self.int_const(t, i64::from(v as i32)) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa119..115f6a275e 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -14,6 +14,35 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::host::{Draw, Host, Root}; use super::{HostShader, RootType, translate}; +/// Returns `VICTORY_EMIT_DUMP` only when it resolves outside any VIctory or +/// Git checkout, preventing test shader dumps from polluting the repository. +fn emit_dump_dir() -> Option { + let dir = PathBuf::from(std::env::var_os("VICTORY_EMIT_DUMP")?); + let abs = if dir.is_absolute() { + dir.clone() + } else { + std::env::current_dir().ok()?.join(&dir) + }; + let mut cur = abs.as_path(); + let base = loop { + if let Ok(canon) = std::fs::canonicalize(cur) { + break canon; + } + match cur.parent() { + Some(p) if !p.as_os_str().is_empty() => cur = p, + _ => break abs, + } + }; + assert!( + !base + .ancestors() + .any(|a| a.join(".victory-root").is_file() || a.join(".git").exists()), + "refusing VICTORY_EMIT_DUMP inside repository: {}", + dir.display() + ); + Some(dir) +} + const RS: &str = "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), \ RootConstants(num32BitConstants=4, b0), \ DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), \ @@ -706,6 +735,9 @@ fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec { (RootType::Table, 3) => 5 * 32, // The typed views of `raw` (compute) from 9. (RootType::Table, 6) => 9 * 32, + // Root CBV (64 dwords = 256 B) and root SRV (32 dwords = 128 B). + (RootType::Descriptor, 4) => 64 * 4, + (RootType::Descriptor, 5) => 32 * 4, other => panic!("unexpected user data {other:?}"), }; } @@ -787,14 +819,14 @@ fn translated_shaders_draw_as_pc_ones() { continue; } }; - if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + if let Some(out) = emit_dump_dir() { let stem = name.replace([' ', ','], "_"); std::fs::write( - format!("{out}/{stem}.ps.cdxil"), + out.join(format!("{stem}.ps.cdxil")), compile(&console, &dir, src, "ps", "ps_6_5"), ) .unwrap(); - std::fs::write(format!("{out}/{stem}.ps.dxil"), &ps_c.dxil).unwrap(); + std::fs::write(out.join(format!("{stem}.ps.dxil")), &ps_c.dxil).unwrap(); } if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), @@ -905,10 +937,10 @@ fn translated_mesh_shaders_draw_as_pc_ones() { } }; let ps_c = translate(&compile(&console, &dir, src, "mps", "ps_6_5")).unwrap(); - if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + if let Some(out) = emit_dump_dir() { let stem = name.replace([' ', ','], "_"); - std::fs::write(format!("{out}/{stem}.ms.cdxil"), &console_ms).unwrap(); - std::fs::write(format!("{out}/{stem}.ms.dxil"), &ms_c.dxil).unwrap(); + std::fs::write(out.join(format!("{stem}.ms.cdxil")), &console_ms).unwrap(); + std::fs::write(out.join(format!("{stem}.ms.dxil")), &ms_c.dxil).unwrap(); } if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), @@ -1181,9 +1213,9 @@ fn translated_compute_matches_pc() { .filter(|c| warp || !c.0.starts_with("terminates")) { let console_cs = compile(&console, &dir, src, "cs", "cs_6_5"); - if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + if let Some(out) = emit_dump_dir() { let stem = name.replace([' ', ','], "_"); - std::fs::write(format!("{out}/{stem}.cs.cdxil"), &console_cs).unwrap(); + std::fs::write(out.join(format!("{stem}.cs.cdxil")), &console_cs).unwrap(); } let cs_c = match translate(&console_cs) { Ok(s) => s, @@ -1192,9 +1224,9 @@ fn translated_compute_matches_pc() { continue; } }; - if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + if let Some(out) = emit_dump_dir() { let stem = name.replace([' ', ','], "_"); - std::fs::write(format!("{out}/{stem}.cs.dxil"), &cs_c.dxil).unwrap(); + std::fs::write(out.join(format!("{stem}.cs.dxil")), &cs_c.dxil).unwrap(); } if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4dc5..05576acf0a 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -132,21 +132,23 @@ impl Host { ShaderVisibility: vis, }) .collect(); - let mut views: Vec<(u8, bool)> = stages + let mut views: Vec<(u8, u8)> = stages .iter() .flat_map(|(s, _)| { - let cbvs = s.root_cbvs.iter().map(|&r| (r, false)); - cbvs.chain(s.root_srvs.iter().map(|&r| (r, true))) + let cbvs = s.root_cbvs.iter().map(|&r| (r, 0u8)); + let srvs = s.root_srvs.iter().map(|&r| (r, 1u8)); + let uavs = s.root_uavs.iter().map(|&r| (r, 2u8)); + cbvs.chain(srvs).chain(uavs) }) .collect(); views.sort_unstable(); views.dedup(); - for (slot, srv) in views { + for (slot, kind) in views { params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: if srv { - D3D12_ROOT_PARAMETER_TYPE_SRV - } else { - D3D12_ROOT_PARAMETER_TYPE_CBV + ParameterType: match kind { + 0 => D3D12_ROOT_PARAMETER_TYPE_CBV, + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + _ => D3D12_ROOT_PARAMETER_TYPE_UAV, }, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -158,6 +160,34 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let mut const_views: Vec<(u32, u8)> = stages + .iter() + .flat_map(|(s, _)| { + let cbvs = s.const_cbvs.iter().map(|r| (r.register, 0u8)); + let srvs = s.const_srvs.iter().map(|r| (r.register, 1u8)); + let uavs = s.const_uavs.iter().map(|r| (r.register, 2u8)); + cbvs.chain(srvs).chain(uavs) + }) + .collect(); + const_views.sort_unstable(); + const_views.dedup(); + for (reg, kind) in const_views { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: match kind { + 0 => D3D12_ROOT_PARAMETER_TYPE_CBV, + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + _ => D3D12_ROOT_PARAMETER_TYPE_UAV, + }, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg, + RegisterSpace: super::CONST_VIEW_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -528,6 +558,11 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + const_cbvs: Vec::new(), + const_srvs: Vec::new(), + const_uavs: Vec::new(), + wave_size: None, } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e8988a2..cc6a71e051 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; -use super::UserData; +use super::{ConstRootView, UserData}; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; @@ -35,10 +35,40 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, + pub root_uavs: Vec, + pub const_cbvs: Vec, + pub const_srvs: Vec, + pub const_uavs: Vec, + pub wave_size: Option, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, } +#[derive(Clone, Copy)] +enum AtomicOp { + Bin(u32), + Sub, + CmpSwap, +} + +/// DXIL atomic operation for a `buffer_atomic_*` / `global_atomic_*` suffix. +fn atomic_op(rest: &str) -> Option { + Some(match rest { + "add" => AtomicOp::Bin(0), + "sub" => AtomicOp::Sub, + "and" => AtomicOp::Bin(1), + "or" => AtomicOp::Bin(2), + "xor" => AtomicOp::Bin(3), + "smin" => AtomicOp::Bin(4), + "smax" => AtomicOp::Bin(5), + "umin" => AtomicOp::Bin(6), + "umax" => AtomicOp::Bin(7), + "swap" => AtomicOp::Bin(8), + "cmpswap" => AtomicOp::CmpSwap, + _ => return None, + }) +} + pub(crate) struct Parts<'a> { pub native: &'a NativeProgram, pub p: &'a Program, @@ -50,6 +80,8 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, + /// Maximum wave lane count supported by the target host GPU (32 or 64). + pub max_wave_size: u32, } enum Stop { @@ -142,6 +174,12 @@ struct Lower<'a> { lane_bits: HashMap, /// IR phi location by value. phi_at: HashMap, + /// Defining instruction site per IR value (used for relative pointer + /// offset lowering). + defs: HashMap, + /// Dominance-safe DXIL phis for pointer-relative offsets `(phi_val, base)`. + addr_phis: HashMap<(Value, Value), V>, + pending_addr_phis: Vec<(V, usize, usize, Value)>, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -170,6 +208,10 @@ struct Lower<'a> { /// Compute code that reads other lanes: thread ids follow the host /// lanes, so lane n is console lane n. console_lanes: bool, + /// Single-wave64 compute shader using LDS running on a Wave32-only GPU: + /// insert group-shared memory barriers before uniform LDS reads so the + /// two 32-lane waves stay synchronized without `WaveSize(64)`. + lds_wave_sync: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option, /// Mesh: IR blocks whose `s_barrier` is left out. @@ -337,10 +379,13 @@ impl<'a> Lower<'a> { s.outputs = x.outputs.clone(); let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { - matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) - && (i.name().contains("store") || i.name().contains("atomic")) + matches!( + i.fields, + Fields::Image { .. } | Fields::Buffer { .. } | Fields::Flat { .. } + ) && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; + let mut lds_wave_sync = false; if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; @@ -381,7 +426,20 @@ impl<'a> Lower<'a> { }; let wave = if x.native.wave64 { 64 } else { 32 }; let one_wave = cs.threads.iter().product::() <= wave; - if console_lanes || one_wave && s.lds_dwords > 0 { + let max_wave = x.max_wave_size.max(32); + if wave > max_wave { + // Host GPU does not support Wave64 (e.g. 32-lane hardware): + // - Single-wave64 LDS shaders synchronize via explicit group + // shared barriers instead of requesting `WaveSize(64)`. + // - Cross-lane shaders clamp `WaveSize` to `max_wave` so PSO + // creation succeeds instead of failing with `E_INVALIDARG`. + if one_wave && s.lds_dwords > 0 { + lds_wave_sync = true; + } + if console_lanes { + s.wave_size = Some(max_wave); + } + } else if console_lanes || one_wave && s.lds_dwords > 0 { s.wave_size = Some(wave); } } @@ -442,6 +500,21 @@ impl<'a> Lower<'a> { bools: HashMap::new(), lane_bits: HashMap::new(), phi_at, + defs: p + .blocks + .iter() + .enumerate() + .flat_map(|(b, blk)| { + blk.insts + .iter() + .enumerate() + .flat_map(move |(i, inst)| { + inst.writes.iter().map(move |&(_, v)| (v, (b, i))) + }) + }) + .collect(), + addr_phis: HashMap::new(), + pending_addr_phis: Vec::new(), mask_phis: HashMap::new(), pending_masks: Vec::new(), data_phis: Vec::new(), @@ -467,12 +540,13 @@ impl<'a> Lower<'a> { writes_uavs, src0: None, console_lanes, + lds_wave_sync, flat: None, no_barrier, half_outputs: half_outputs(&x.native.io, &x.outputs), mask_data: match x.native.stage { HwStage::Cs => MaskData::Console, - HwStage::Ps | HwStage::Vs => MaskData::Host, + HwStage::Ps | HwStage::Vs | HwStage::Es | HwStage::Ls => MaskData::Host, _ => MaskData::None, }, mask_ok: false, @@ -558,13 +632,133 @@ impl<'a> Lower<'a> { Ok(self.s.m.load(c, at)) } - /// A global memory load (`global_load_*`): from the program's constant - /// table, or from a root SRV at the address the title sets. + /// A global memory access (`global_load_*`, `global_store_*`, + /// `global_atomic_*`): loads from the program's constant table or a root + /// SRV/UAV, stores and 32-bit atomics to a root UAV at the address the + /// title sets. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { - let Fields::Flat { dst, .. } = &inst.fields else { + let Fields::Flat { dst, data, .. } = &inst.fields else { unreachable!() }; let name = inst.name(); + let a = *self + .scalar + .get(&(b, i)) + .ok_or("an untracked global address")?; + let guard = self.guard(b, i)?; + let off = self.address_offset(a)?; + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + let root_size = self.root_view_size(&src); + if let Some(rest) = name.strip_prefix("global_atomic_") { + if a.param == CODE { + return Err("a global write to code"); + } + let op = atomic_op(rest).ok_or(name)?; + let d = data.as_ref().ok_or("global atomic data")?; + let vals = self.vgprs(inst, d, if matches!(op, AtomicOp::CmpSwap) { 2 } else { 1 })?; + let h = self.handle((b, i), &src, false, (11 | 0x1000, 0))?; + let iu = self.s.m.undef(self.s.t.i32); + let coords = [off, iu, iu]; + let dst_reg = match *dst { + Some(Operand::Vector { reg, .. }) => Some(reg), + None => None, + Some(_) => return Err("global atomic result"), + }; + let old = match dst_reg.and_then(|reg| inst.read(Reg::V(reg))) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let val = match op { + AtomicOp::Sub => { + let zero = self.s.m.i32(0); + self.s.m.bin(self.cur, Bin::Sub, zero, vals[0]) + } + _ => vals[0], + }; + let guard = match root_size { + Some(sz) => { + let ok = self.root_in_bounds(sz, off, 4); + self.and_guard(guard, ok) + } + None => guard, + }; + let at = self.begin_guarded(guard); + let i32t = self.s.t.i32; + let r = match op { + AtomicOp::CmpSwap => { + // cmpswap: data is (new, compare). + let mut args = vec![h]; + args.extend(coords); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } + AtomicOp::Bin(code) => { + let mut args = vec![h, self.s.m.i32(code)]; + args.extend(coords); + args.push(val); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + } + AtomicOp::Sub => { + let mut args = vec![h, self.s.m.i32(0)]; + args.extend(coords); + args.push(val); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + } + }; + if let Some(reg) = dst_reg { + let r = self.end_guarded(at, &[(r, old)])[0]; + self.write(inst, Reg::V(reg), r, None); + } else { + self.end_guarded(at, &[]); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("global_store_") { + if a.param == CODE { + return Err("a global write to code"); + } + let count = match rest { + "dword" => 1u32, + "dwordx2" => 2, + "dwordx3" => 3, + "dwordx4" => 4, + _ => return Err(name), + }; + let vals = self.vgprs(inst, data.as_ref().ok_or("global store data")?, count as u8)?; + let h = self.handle((b, i), &src, false, (11 | 0x1000, 0))?; + let iu = self.s.m.undef(self.s.t.i32); + let mut args = vec![h, off, iu]; + args.extend(&vals); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << count) - 1)); + args.push(self.s.m.i32(4)); + let guard = match root_size { + Some(sz) => { + let ok = self.root_in_bounds(sz, off, 4 * count); + self.and_guard(guard, ok) + } + None => guard, + }; + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } let rest = name .strip_prefix("global_load_") .ok_or("a global memory write")?; @@ -579,34 +773,30 @@ impl<'a> Lower<'a> { "sshort" => (1, Some((16, true))), _ => return Err(name), }; - let a = *self - .scalar - .get(&(b, i)) - .ok_or("an untracked global address")?; - let guard = self.guard(b, i)?; let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; - let c = self.cur; - let mut off = self.s.m.i32(a.offset); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; - off = self.s.m.bin(c, Bin::Add, off, d); - } let h = if a.param == CODE { None } else { - let src = Source::Built { - address: a, - bits: 0, - words: [0, 0], - }; - Some(self.handle((b, i), &src, false, (11, 0))?) + let uav = self + .used_kind(&src) + .is_some_and(|u| u.kind == ResourceType::Uav); + let props = (11 | if uav { 0x1000 } else { 0 }, 0); + Some(self.handle((b, i), &src, false, props)?) }; let dword = |l: &mut Self, byte: V| -> Result { match h { None => l.code_dword(byte), Some(h) => { + let load_guard = match root_size { + Some(sz) => { + let ok = l.root_in_bounds(sz, byte, 4); + l.and_guard(guard, ok) + } + None => None, + }; + let at_g = l.begin_guarded(load_guard); let c = l.cur; let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4)); let r = l.s.op( @@ -618,7 +808,9 @@ impl<'a> Lower<'a> { &[h, byte, u, mask, al], ); let x = l.s.m.extract(c, r, 0); - Ok(l.as_int(x)) + let x = l.as_int(x); + let zero = l.s.m.i32(0); + Ok(l.end_guarded(at_g, &[(x, zero)])[0]) } } }; @@ -626,14 +818,15 @@ impl<'a> Lower<'a> { let x = match sub { None => { let four = self.s.m.i32(4 * k); - let at = self.s.m.bin(c, Bin::Add, off, four); + let at = self.s.m.bin(self.cur, Bin::Add, off, four); dword(self, at)? } Some((width, signed)) => { // shortcut: the field is taken not to cross a dword. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); - let at = self.s.m.bin(c, Bin::And, off, not3); + let at = self.s.m.bin(self.cur, Bin::And, off, not3); let w = dword(self, at)?; + let c = self.cur; let byte = self.s.m.bin(c, Bin::And, off, three); let sh = self.s.m.bin(c, Bin::Shl, byte, three); let x = self.s.m.bin(c, Bin::LShr, w, sh); @@ -882,11 +1075,48 @@ impl<'a> Lower<'a> { self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); + let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); + let const_cbvs = self + .s + .const_cbvs + .iter() + .map(|&(slot, dword, register, _)| ConstRootView { + slot, + dword, + register, + }) + .collect(); + let const_srvs = self + .s + .const_srvs + .iter() + .map(|&(slot, dword, register, _)| ConstRootView { + slot, + dword, + register, + }) + .collect(); + let const_uavs = self + .s + .const_uavs + .iter() + .map(|&(slot, dword, register, _)| ConstRootView { + slot, + dword, + register, + }) + .collect(); + let wave_size = self.s.wave_size; let cmp_samplers = self.s.cmp_samplers; Ok(Lowered { cmp_samplers, root_cbvs, root_srvs, + root_uavs, + const_cbvs, + const_srvs, + const_uavs, + wave_size, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -1109,21 +1339,15 @@ impl<'a> Lower<'a> { } } - /// A user-data dword: a root parameter's value. - fn user(&mut self, param: usize, dword: u32) -> Val { - let rp = self.x.native.layout[param]; - match rp.root { - RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), - RootType::Constants | RootType::Table => {} - _ => return Val::Missing("a root descriptor"), - } - let index = u32::from(rp.user_data) + dword; + /// A user-data dword from the stage's user-data CBV (loaded in the entry + /// block so the value dominates the whole program). + fn user_dword(&mut self, slot: u8, root: RootType, index: u32, dword: u32) -> V { self.user_reads.insert( index, UserData { index, - slot: rp.slot, - root: rp.root, + slot, + root, dword, }, ); @@ -1146,7 +1370,55 @@ impl<'a> Lower<'a> { 59, &[h, row], ); - Val::I32(self.s.m.extract(entry, r, index % 4)) + self.s.m.extract(entry, r, index % 4) + } + + /// A user-data dword: a root parameter's value. + fn user(&mut self, param: usize, dword: u32) -> Val { + let rp = self.x.native.layout[param]; + match rp.root { + RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), + RootType::Constants | RootType::Table => {} + _ => return Val::Missing("a root descriptor"), + } + let index = u32::from(rp.user_data) + dword; + Val::I32(self.user_dword(rp.slot, rp.root, index, dword)) + } + + /// Byte length of the host root view for `src`, if `src` is a root + /// descriptor (`RootType::Descriptor`, not `CODE`). Stored in the root + /// parameter's otherwise unused `user_data` dword (`root: Descriptor`). + fn root_view_size(&mut self, src: &Source) -> Option { + let Source::Built { address, .. } = src else { + return None; + }; + if address.param == CODE { + return None; + } + let rp = self.x.native.layout.get(address.param).copied()?; + if rp.root != RootType::Descriptor { + return None; + } + Some(self.user_dword(rp.slot, RootType::Descriptor, u32::from(rp.user_data), 0)) + } + + /// Overflow-safe unsigned check that `[off, off + bytes)` lies within + /// `size`: `size >= bytes && off <= size - bytes`. + fn root_in_bounds(&mut self, size: V, off: V, bytes: u32) -> V { + let c = self.cur; + let need = self.s.m.i32(bytes); + let enough = self.s.m.cmp(c, pred::IUGE, size, need); + let limit = self.s.m.bin(c, Bin::Sub, size, need); + let ok = self.s.m.cmp(c, pred::IULE, off, limit); + self.s.m.bin(c, Bin::And, enough, ok) + } + + /// Combines an optional lane execution guard with a bounds predicate. + fn and_guard(&mut self, guard: Option, cond: V) -> Option { + Some(match guard { + Some(g) => self.s.m.bin(self.cur, Bin::And, g, cond), + None => cond, + }) } /// A dword of a lane mask as a number: the ballot of the lanes' bits, @@ -1474,13 +1746,22 @@ impl<'a> Lower<'a> { self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) } - /// `0 × anything = 0`, as in D3D9. + /// `0 × anything = 0`, as in D3D9. RDNA2 treats denormal operands of + /// `v_mul_legacy_f32` / `v_mac_legacy_f32` / `v_mad_legacy_f32` as zero, + /// so check exponent bits (`bits & 0x7F80_0000 == 0`) rather than `== 0.0` + /// to cover ±0 and all denormals regardless of host denormal mode. fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; let m = self.s.m.bin(c, Bin::Mul, a, b); let zero = self.s.m.f32(0); - let az = self.s.m.cmp(c, pred::OEQ, a, zero); - let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let zero_i = self.s.m.i32(0); + let exp_mask = self.s.m.i32(0x7F80_0000); + let ai = self.as_int(a); + let bi = self.as_int(b); + let ae = self.s.m.bin(c, Bin::And, ai, exp_mask); + let be = self.s.m.bin(c, Bin::And, bi, exp_mask); + let az = self.s.m.cmp(c, pred::EQ, ae, zero_i); + let bz = self.s.m.cmp(c, pred::EQ, be, zero_i); let z = self.s.m.bin(c, Bin::Or, az, bz); self.s.m.select(c, z, zero, m) } @@ -2023,8 +2304,14 @@ impl<'a> Lower<'a> { _ => None, }; if name == "ds_swizzle_b32" { - // Bit 15 set: each lane of a quad picks a lane of it; else lanes - // of each group of 32 combine their index with and/or/xor masks. + // Bits 15:14 == 0b11 are GFX10 rotate (0xC000..=0xDFFF) and FFT + // (0xE000..=0xFFFF) modes, not quad-permute. + if offset >= 0xC000 { + return Err("a rotate or FFT swizzle"); + } + // Bit 15 set (0x8000..=0xBFFF): each lane of a quad picks a lane + // of it; else lanes of each group of 32 combine their index with + // and/or/xor masks. let quad = offset & 0x8000 != 0 || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the @@ -2096,6 +2383,44 @@ impl<'a> Lower<'a> { ] }; if let Some(rest) = name.strip_prefix("ds_read") { + if self.lds_wave_sync && guard.is_none() { + let mode = self.s.m.i32(1 | 8); + let void = self.s.t.void; + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + let reg = dst_reg.ok_or("an LDS read result")?; + if let Some((width_bits, signed)) = match rest { + "_u8" => Some((8u32, false)), + "_i8" => Some((8, true)), + "_u16" => Some((16, false)), + "_i16" => Some((16, true)), + _ => None, + } { + let c = self.cur; + let o = self.s.m.i32(offset); + let byte_addr = self.s.m.bin(c, Bin::Add, a, o); + let two = self.s.m.i32(2); + let index = self.s.m.bin(c, Bin::LShr, byte_addr, two); + let lds = self.s.lds(); + let p = self.s.m.element(c, lds, index); + let w = self.s.m.load(c, p); + let three = self.s.m.i32(3); + let lane_byte = self.s.m.bin(c, Bin::And, byte_addr, three); + let shift = self.s.m.bin(c, Bin::Shl, lane_byte, three); + let x = if signed { + let top = self.s.m.i32(32 - width_bits); + let shl = self.s.m.bin(c, Bin::Sub, top, shift); + let hi = self.s.m.bin(c, Bin::Shl, w, shl); + self.s.m.bin(c, Bin::AShr, hi, top) + } else { + let shifted = self.s.m.bin(c, Bin::LShr, w, shift); + let mask = self.s.m.i32((1u32 << width_bits) - 1); + self.s.m.bin(c, Bin::And, shifted, mask) + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); + } let elements = if rest.starts_with('2') { pair(name) } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { @@ -2103,7 +2428,6 @@ impl<'a> Lower<'a> { } else { return Err("an LDS read of bytes or halves"); }; - let reg = dst_reg.ok_or("an LDS read result")?; let mut n = 0; for (off, w) in elements { for k in 0..w { @@ -2116,6 +2440,43 @@ impl<'a> Lower<'a> { return Ok(()); } if let Some(rest) = name.strip_prefix("ds_write") { + if let Some((width_mask, high_half)) = match rest { + "_b8" => Some((0xFFu32, false)), + "_b16" => Some((0xFFFF, false)), + "_b8_d16_hi" => Some((0xFF, true)), + "_b16_d16_hi" => Some((0xFFFF, true)), + _ => None, + } { + use super::bitcode::Rmw; + let mut val = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + let c = self.cur; + if high_half { + let k16 = self.s.m.i32(16); + val = self.s.m.bin(c, Bin::LShr, val, k16); + } + let mask_v = self.s.m.i32(width_mask); + val = self.s.m.bin(c, Bin::And, val, mask_v); + let o = self.s.m.i32(offset); + let byte_addr = self.s.m.bin(c, Bin::Add, a, o); + let two = self.s.m.i32(2); + let index = self.s.m.bin(c, Bin::LShr, byte_addr, two); + let lds = self.s.lds(); + let p = self.s.m.element(c, lds, index); + let three = self.s.m.i32(3); + let lane_byte = self.s.m.bin(c, Bin::And, byte_addr, three); + let shift = self.s.m.bin(c, Bin::Shl, lane_byte, three); + let shifted_mask = self.s.m.bin(c, Bin::Shl, mask_v, shift); + let ones = self.s.m.i32(u32::MAX); + let clear_mask = self.s.m.bin(c, Bin::Xor, shifted_mask, ones); + let bits = self.s.m.bin(c, Bin::Shl, val, shift); + // Atomic mask-and-insert avoids racing against sibling lanes + // writing other bytes or halves of the same LDS dword. + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, clear_mask); + self.s.m.atomic(self.cur, Rmw::Or, p, bits); + self.end_guarded(at, &[]); + return Ok(()); + } let elements = if rest.starts_with('2') { pair(name) } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { @@ -2143,6 +2504,38 @@ impl<'a> Lower<'a> { .strip_prefix("ds_") .map(|n| n.replace("_rtn", "")) .ok_or("an LDS operation")?; + if matches!(op.as_str(), "min_f32" | "max_f32") { + let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; + let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v))); + let outside = match old_reg { + Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)), + None => self.s.m.i32(0), + }; + let p = dword(self, offset); + let at = self.begin_guarded(guard); + let enter = self.cur; + let init = self.s.m.load(enter, p); + let loop_bb = self.s.m.new_block(); + let done_bb = self.s.m.new_block(); + self.s.m.terminate(enter, Term::Br(loop_bb)); + self.cur = loop_bb; + let cur_i = self.s.m.phi(loop_bb, self.s.t.i32); + let cur_f = self.as_float(cur_i); + let val_f = self.as_float(v0); + let dxil_op = if op == "max_f32" { 35 } else { 36 }; + let next_f = self.binary(dxil_op, val_f, cur_f); + let next_i = self.as_int(next_f); + let prev_i = self.s.m.cmpxchg(loop_bb, p, cur_i, next_i); + let eq = self.s.m.cmp(loop_bb, pred::EQ, prev_i, cur_i); + self.s.m.terminate(loop_bb, Term::CondBr(eq, done_bb, loop_bb)); + self.s.m.set_phi(cur_i, vec![(init, enter), (prev_i, loop_bb)]); + self.cur = done_bb; + let r = self.end_guarded(at, &[(prev_i, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } use super::bitcode::Rmw; let rmw = match op.as_str() { "add_u32" => Some(Rmw::Add), @@ -2710,6 +3103,19 @@ impl<'a> Lower<'a> { } fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + if self.x.res.spill_loads.contains(&site) { + // Spilled user-data loads populate `self.params` directly and are + // satisfied lazily via `self.user(param, dword)` when read. + for &(_, w) in &inst.writes { + if !self.params.contains_key(&w) { + self.vals.insert( + w, + Val::Missing("a spilled user-data dword outside the root layout"), + ); + } + } + return Ok(()); + } let Fields::Smem { data, offset, @@ -2723,6 +3129,67 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if let Some(rest) = name.strip_prefix("s_load_dword") + && let Some(a) = self.scalar.get(&site).copied() + && let Some(rp) = self.x.native.layout.get(a.param).copied() + && matches!(rp.root, RootType::Descriptor | RootType::Constants) + { + let count = match rest { + "" => 1u32, + "x2" => 2, + "x4" => 4, + "x8" => 8, + "x16" => 16, + _ => return Err("a scalar buffer load"), + }; + let Some(Operand::Scalar { code, .. }) = *data else { + return Err("a scalar buffer load"); + }; + let c = self.cur; + let mut addr = self.address_offset(a)?; + let imm = *offset as u32; + if imm != 0 { + let k = self.s.m.i32(imm); + addr = self.s.m.bin(c, Bin::Add, addr, k); + } + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(inst, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + let h = self.handle(site, &src, false, (11, 0))?; + let iu = self.s.m.undef(self.s.t.i32); + let four = self.s.m.i32(4); + let mut k = 0u32; + while k < count { + let chunk = (count - k).min(4); + let byte = if k == 0 { + addr + } else { + let b = self.s.m.i32(k * 4); + self.s.m.bin(c, Bin::Add, addr, b) + }; + let mask = self.s.m.i8(((1u32 << chunk) - 1) as u8); + let res = self.s.op( + c, + "rawBufferLoad.i32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, four], + ); + for j in 0..chunk { + let v = self.s.m.extract(c, res, j); + self.write(inst, Reg::S(code + (k + j) as u8), v, None); + } + k += chunk; + } + return Ok(()); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -2764,11 +3231,15 @@ impl<'a> Lower<'a> { } return Ok(()); } + let root_size = self.root_view_size(src); if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { let h = self.handle(site, src, false, (11, 0))?; for k in 0..count { let off = self.s.m.i32(4 * k); - let a = self.s.m.bin(c, Bin::Add, addr, off); + let a = self.s.m.bin(self.cur, Bin::Add, addr, off); + let load_guard = root_size.map(|sz| self.root_in_bounds(sz, a, 4)); + let at_g = self.begin_guarded(load_guard); + let c = self.cur; let mask = self.s.m.i8(1); let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); let r = self.s.op( @@ -2781,6 +3252,8 @@ impl<'a> Lower<'a> { ); let x = self.s.m.extract(c, r, 0); let x = self.as_int(x); + let zero = self.s.m.i32(0); + let x = self.end_guarded(at_g, &[(x, zero)])[0]; self.write(inst, Reg::S(code + k as u8), x, None); } return Ok(()); @@ -2788,7 +3261,9 @@ impl<'a> Lower<'a> { let h = self.handle(site, src, false, (13, 0x1_0000))?; let constant = match addr { V::Const(_) - if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() => + if root_size.is_none() + && matches!(soffset, Operand::Scalar { code: NULL, .. }) + && extra.is_none() => { Some(*offset as u32) } @@ -2804,7 +3279,7 @@ impl<'a> Lower<'a> { None => { let ri = self.s.m.i32(byte >> 4); let r = self.s.op( - c, + self.cur, "cbufferLoadLegacy.i32", Attr::ReadOnly, self.s.t.cbuf_ret, @@ -2815,12 +3290,16 @@ impl<'a> Lower<'a> { r } }; - self.s.m.extract(c, row, (byte >> 2) & 3) + self.s.m.extract(self.cur, row, (byte >> 2) & 3) } None => { let off = self.s.m.i32(4 * k); - let a = self.s.m.bin(c, Bin::Add, addr, off); - self.cbuffer_dword(h, a) + let a = self.s.m.bin(self.cur, Bin::Add, addr, off); + let load_guard = root_size.map(|sz| self.root_in_bounds(sz, a, 4)); + let at_g = self.begin_guarded(load_guard); + let loaded = self.cbuffer_dword(h, a); + let zero = self.s.m.i32(0); + self.end_guarded(at_g, &[(loaded, zero)])[0] } }; self.write(inst, Reg::S(code + k as u8), x, None); @@ -2899,7 +3378,12 @@ impl<'a> Lower<'a> { || un.starts_with("buffer_store_format") { (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + } else if *idxen + && format.is_none() + && !matches!(src, Source::Built { .. }) + && stride >= 4 + && stride.is_multiple_of(4) + { (12 | u, stride) } else { (11 | u, 0) @@ -2994,12 +3478,8 @@ impl<'a> Lower<'a> { Some("x16") => 16, _ => return Err("a scalar load from the code"), }; + let addr = self.address_offset(a)?; let c = self.cur; - let mut addr = self.s.m.i32(a.offset); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; - addr = self.s.m.bin(c, Bin::Add, addr, d); - } for k in 0..count { let off = self.s.m.i32(4 * k); let at = self.s.m.bin(c, Bin::Add, addr, off); @@ -3151,16 +3631,375 @@ impl<'a> Lower<'a> { Ok(out) } + /// The byte offset of an [`Address`] relative to its root parameter base. + fn address_offset(&mut self, a: Address) -> Result { + let mut off = self.s.m.i32(a.offset); + if let Some(rel) = a.rel { + let mut local = HashMap::new(); + let base_rel = self.rel_offset(rel.value, rel.base, &mut local)?; + off = self.s.m.bin(self.cur, Bin::Add, off, base_rel); + if let Some(extra) = rel.extra { + let extra_v = self.i32_of(extra)?; + off = self.s.m.bin(self.cur, Bin::Add, off, extra_v); + } + } else if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + off = self.s.m.bin(self.cur, Bin::Add, off, d); + } + Ok(off) + } + + /// Whether `v` transitively depends on `base` through pointer arithmetic + /// or phis. + fn has_base(&self, v: Value, base: Value, visiting: &mut Vec) -> bool { + if v == base { + return true; + } + if visiting.contains(&v) { + return false; + } + visiting.push(v); + let found = if let Some(&(b, pi)) = self.phi_at.get(&v) { + self.x.p.blocks[b].phis[pi] + .args + .iter() + .any(|&arg| self.has_base(arg, base, visiting)) + } else if let Some(&(b, i)) = self.defs.get(&v) { + let inst = &self.x.p.blocks[b].insts[i]; + inst.reads + .iter() + .any(|&(_, r)| self.has_base(r, base, visiting)) + } else { + false + }; + visiting.pop(); + found + } + + /// Evaluates one operand of a relative-address instruction, replacing + /// expressions derived from `base` with their offset from `base`. + fn rel_operand( + &mut self, + inst: &Inst, + op: &Operand, + base: Value, + local: &mut HashMap, + ) -> Result { + match *op { + Operand::Const(k) => { + let x = crate::resource::inline(k).ok_or("a special operand")?; + Ok(self.s.m.i32(x)) + } + Operand::Literal(x) => Ok(self.s.m.i32(x)), + Operand::Scalar { code, .. } if code != NULL => { + let v = inst.read(Reg::S(code)).ok_or("an unread operand")?; + if self.has_base(v, base, &mut Vec::new()) { + self.rel_offset(v, base, local) + } else { + self.i32_of(v) + } + } + Operand::Vector { reg, .. } => { + let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; + if self.has_base(v, base, &mut Vec::new()) { + self.rel_offset(v, base, local) + } else { + self.i32_of(v) + } + } + _ => Err("a relative address operand"), + } + } + + /// Computes `v - base` (modulo 2^32) in DXIL without materializing the + /// opaque GPU base pointer. Pointer phis are cached in `addr_phis` at + /// their IR block and resolved in `fill_phis` to preserve SSA dominance. + fn rel_offset( + &mut self, + v: Value, + base: Value, + local: &mut HashMap, + ) -> Result { + if v == base { + return Ok(self.s.m.i32(0)); + } + if let Some(&cached) = local.get(&v) { + return Ok(cached); + } + if let Some(&phi_v) = self.addr_phis.get(&(v, base)) { + return Ok(phi_v); + } + if let Some(&(b, pi)) = self.phi_at.get(&v) { + let blk = self.block[b].ok_or("an address phi in an unreachable block")?; + let phi_v = self.s.m.phi(blk, self.s.t.i32); + self.addr_phis.insert((v, base), phi_v); + self.pending_addr_phis.push((phi_v, b, pi, base)); + return Ok(phi_v); + } + let Some(&(b, i)) = self.defs.get(&v) else { + return Err("an untracked relative address term"); + }; + let inst = &self.x.p.blocks[b].insts[i]; + let name = inst.name(); + let res = match &inst.fields { + Fields::Sop { dst, src, imm } => match name { + "s_mov_b32" => self.rel_operand( + inst, + src.first().ok_or("a missing operand")?, + base, + local, + )?, + "s_add_u32" | "s_add_i32" => { + let a = self.rel_operand( + inst, + src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Add, a, b) + } + "s_addk_i32" => { + let a = self.rel_operand( + inst, + dst.as_ref().ok_or("a missing operand")?, + base, + local, + )?; + let k = self.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32); + self.s.m.bin(self.cur, Bin::Add, a, k) + } + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" + | "s_lshl4_add_u32" => { + let sh = match name { + "s_lshl1_add_u32" => 1u32, + "s_lshl2_add_u32" => 2, + "s_lshl3_add_u32" => 3, + _ => 4, + }; + let a = self.rel_operand( + inst, + src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + let sh_v = self.s.m.i32(sh); + let shifted = self.s.m.bin(self.cur, Bin::Shl, a, sh_v); + self.s.m.bin(self.cur, Bin::Add, shifted, b) + } + "s_sub_u32" | "s_sub_i32" => { + let a = self.rel_operand( + inst, + src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Sub, a, b) + } + "s_or_b32" => { + let a = self.rel_operand( + inst, + src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Or, a, b) + } + _ => return Err("an unsupported relative scalar address op"), + }, + Fields::Valu(f) => match name { + "v_mov_b32" => self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?, + "v_readfirstlane_b32" => { + let x = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + self.s.op( + self.cur, + "waveReadLaneFirst.i32", + Attr::ReadNone, + self.s.t.i32, + 118, + &[x], + ) + } + "v_readlane_b32" => { + let x = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let lane = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.read_lane(x, lane) + } + "v_add_co_u32" | "v_add_nc_u32" | "v_add_nc_i32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Add, a, b) + } + "v_add3_u32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + let c = self.rel_operand( + inst, + f.src.get(2).ok_or("a missing operand")?, + base, + local, + )?; + let ab = self.s.m.bin(self.cur, Bin::Add, a, b); + self.s.m.bin(self.cur, Bin::Add, ab, c) + } + "v_lshl_add_u32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let sh = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(2).ok_or("a missing operand")?, + base, + local, + )?; + let shifted = self.s.m.bin(self.cur, Bin::Shl, a, sh); + self.s.m.bin(self.cur, Bin::Add, shifted, b) + } + "v_sub_co_u32" | "v_sub_nc_u32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Sub, a, b) + } + "v_subrev_co_u32" | "v_subrev_nc_u32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Sub, b, a) + } + "v_or_b32" => { + let a = self.rel_operand( + inst, + f.src.first().ok_or("a missing operand")?, + base, + local, + )?; + let b = self.rel_operand( + inst, + f.src.get(1).ok_or("a missing operand")?, + base, + local, + )?; + self.s.m.bin(self.cur, Bin::Or, a, b) + } + _ => return Err("an unsupported relative vector address op"), + }, + _ => return Err("an unsupported relative address op"), + }; + local.insert(v, res); + Ok(res) + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { match src { Source::Built { address, .. } => { - let x = match address.dynamic { - Some(v) => Some(self.i32_of(v)?), - None => None, - }; - Ok((address.offset, x)) + if let Some(rel) = address.rel { + let mut local = HashMap::new(); + let mut x = self.rel_offset(rel.value, rel.base, &mut local)?; + if let Some(extra) = rel.extra { + let extra_v = self.i32_of(extra)?; + x = self.s.m.bin(self.cur, Bin::Add, x, extra_v); + } + Ok((address.offset, Some(x))) + } else { + let x = match address.dynamic { + Some(v) => Some(self.i32_of(v)?), + None => None, + }; + Ok((address.offset, x)) + } } _ => Ok((0, None)), } @@ -3258,10 +4097,22 @@ impl<'a> Lower<'a> { (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => { Ok(self.s.root_cbv_handle(rp.slot)) } - (RootType::Descriptor, Some(ResourceType::Srv), 11) => { + (RootType::Descriptor, Some(ResourceType::Srv) | None, 11) => { Ok(self.s.root_srv_handle(rp.slot)) } - _ => Err("a root UAV or typed root view"), + (RootType::Descriptor, Some(ResourceType::Uav) | None, 0x100b) => { + Ok(self.s.root_uav_handle(rp.slot)) + } + (RootType::Constants, _, 13) => { + Ok(self.s.const_cbv_handle(rp.slot, address.param_dword)) + } + (RootType::Constants, _, 11) => { + Ok(self.s.const_srv_handle(rp.slot, address.param_dword)) + } + (RootType::Constants, _, 0x100b) => { + Ok(self.s.const_uav_handle(rp.slot, address.param_dword)) + } + _ => Err("a typed root view or mismatched root descriptor"), } } Source::Phi { block, args } => { @@ -3768,12 +4619,19 @@ impl<'a> Lower<'a> { } "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { let mut a = f(self, 0)?; - if name == "v_cvt_rpi_i32_f32" { - let h = self.s.m.f32(0.5f32.to_bits()); - a = self.s.m.bin(c, Bin::Add, a, h); - } - if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" { + if name == "v_cvt_flr_i32_f32" { a = self.unary(27, a); + } else if name == "v_cvt_rpi_i32_f32" { + // Exact floor(x + 0.5) without pre-rounding `x + 0.5` + // (e.g. 0.49999997 and odd integers >= 2^23). + let fl = self.unary(27, a); + let diff = self.s.m.bin(c, Bin::Sub, a, fl); + let half = self.s.m.f32(0.5f32.to_bits()); + let up = self.s.m.cmp(c, pred::OGE, diff, half); + let one = self.s.m.f32(1.0f32.to_bits()); + let zero = self.s.m.f32(0.0f32.to_bits()); + let bump = self.s.m.select(c, up, one, zero); + a = self.s.m.bin(c, Bin::Add, fl, bump); } // D3D's conversions saturate and give 0 for NaN, as the // hardware does (checked on the RX 6700 XT and WARP). @@ -3965,11 +4823,20 @@ impl<'a> Lower<'a> { Ok(()) } "v_readlane_b32" => { - let (a, lane) = (s(self, 0)?, s(self, 1)?); - // A computed lane in a pixel or vertex program is a host lane - // (from a mask or `v_mbcnt`); a constant one is the console's. - if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + let (a, mut lane) = (s(self, 0)?, s(self, 1)?); + if self.mask_data == MaskData::Host { self.s.flags |= flags::WAVE_OPS; + // On a 64-lane host wave executing two 32-lane console + // waves, a constant console lane `k` belongs to this + // thread's own 32-lane half (`k | (lane & 32)`). + if matches!(lane, V::Const(_)) && !self.x.native.wave64 { + let me = self.lane_index(); + let k31 = self.s.m.i32(31); + let k32 = self.s.m.i32(32); + let sub = self.s.m.bin(c, Bin::And, lane, k31); + let base = self.s.m.bin(c, Bin::And, me, k32); + lane = self.s.m.bin(c, Bin::Or, sub, base); + } } else { self.cross_lane(false)?; } @@ -3978,7 +4845,7 @@ impl<'a> Lower<'a> { } "v_writelane_b32" => { // The lane given takes the scalar; the others keep their value. - let (a, lane) = (s(self, 0)?, s(self, 1)?); + let (a, mut lane) = (s(self, 0)?, s(self, 1)?); let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a lane write"); }; @@ -3986,8 +4853,22 @@ impl<'a> Lower<'a> { Some(o) => self.i32_of(o)?, None => self.s.m.i32(0), }; - self.cross_lane(false)?; + if self.mask_data == MaskData::Host { + self.s.flags |= flags::WAVE_OPS; + } else { + self.cross_lane(false)?; + } let me = self.lane_index(); + if self.mask_data == MaskData::Host + && matches!(lane, V::Const(_)) + && !self.x.native.wave64 + { + let k31 = self.s.m.i32(31); + let k32 = self.s.m.i32(32); + let sub = self.s.m.bin(c, Bin::And, lane, k31); + let base = self.s.m.bin(c, Bin::And, me, k32); + lane = self.s.m.bin(c, Bin::Or, sub, base); + } let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) @@ -3995,14 +4876,38 @@ impl<'a> Lower<'a> { "v_readfirstlane_b32" => { let a = s(self, 0)?; self.s.flags |= flags::WAVE_OPS; - let r = self.s.op( - c, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - self.s.t.i32, - 118, - &[a], - ); + let r = if self.mask_data == MaskData::Host && !self.x.native.wave64 { + // On a 64-lane host wave executing two 32-lane console + // waves, pick the first active lane in this thread's own + // 32-lane half instead of always lane 0 of the lower half. + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let yes = self.s.m.bool(true); + let ballot = self + .s + .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]); + let lo = self.s.m.extract(c, ballot, 0); + let hi = self.s.m.extract(c, ballot, 1); + let me = self.lane_index(); + let k32 = self.s.m.i32(32); + let upper = self.s.m.cmp(c, pred::IUGE, me, k32); + let active = self.s.m.select(c, upper, hi, lo); + let bit = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[active]); + let base = self.s.m.bin(c, Bin::And, me, k32); + let lane = self.s.m.bin(c, Bin::Or, bit, base); + self.read_lane(a, lane) + } else { + self.s.op( + c, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + self.s.t.i32, + 118, + &[a], + ) + }; int(self, r) } _ => { @@ -4245,7 +5150,14 @@ impl<'a> Lower<'a> { } let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { if v.omod != 0 { - return Err("an output modifier on a 16-bit operation"); + let scale = match v.omod { + 1 => 2.0f32, + 2 => 4.0f32, + 3 => 0.5f32, + _ => return Err("an output modifier on a 16-bit operation"), + }; + let k = l.s.m.f32(scale.to_bits()); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); } if v.clamp { f = l.unary(7, f); @@ -4351,22 +5263,33 @@ impl<'a> Lower<'a> { }; return float_result(self, r); } + // Float-to-16-bit-integer conversions allow float source modifiers + // (`abs`/`neg`) and saturate to the target 16-bit integer range. + if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { + if v.omod != 0 { + return Err("an output modifier on a 16-bit integer conversion"); + } + let a = self.half_fsrc(inst, 0)?; + let (lo, hi, op) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32, Cast::FpToUi) + } else { + (-32768.0f32, 32767.0f32, Cast::FpToSi) + }; + let lo_v = self.s.m.f32(lo.to_bits()); + let hi_v = self.s.m.f32(hi.to_bits()); + let zero_f = self.s.m.f32(0); + let clamped = self.binary(35, a, lo_v); + let clamped = self.binary(36, clamped, hi_v); + let is_nan = self.s.m.cmp(c, pred::UNO, a, a); + let safe = self.s.m.select(c, is_nan, zero_f, clamped); + let r = self.s.m.cast(c, op, safe, i32t); + return self.write_half(inst, r, guard); + } // 16-bit integers: computed on the low halves, the low 16 bits kept. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); } let r = match name { - "v_cvt_u16_f16" | "v_cvt_i16_f16" => { - // shortcut: converted through 32 bits, so out-of-range values - // wrap instead of saturating at 16 bits. - let a = self.half_fsrc(inst, 0)?; - let op = if name == "v_cvt_u16_f16" { - Cast::FpToUi - } else { - Cast::FpToSi - }; - self.s.m.cast(c, op, a, i32t) - } _ => { let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); let k16 = self.s.m.i32(16); @@ -4989,26 +5912,33 @@ impl<'a> Lower<'a> { } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; - let p = match op { - "f" => pred::FALSE, - "lt" => pred::OLT, - "eq" => pred::OEQ, - "le" => pred::OLE, - "gt" => pred::OGT, - "lg" => pred::ONE, - "ge" => pred::OGE, - "o" => pred::ORD, - "u" => pred::UNO, - "nge" => pred::ULT, - "nlg" => pred::UEQ, - "ngt" => pred::ULE, - "nle" => pred::UGT, - "neq" => pred::UNE, - "nlt" => pred::UGE, - "tru" => pred::TRUE, - _ => return Err(inst.name()), - }; - self.s.m.cmp(c, p, a, b) + if op == "lg" { + // AMD D3D12 drivers miscompile `fcmp one` as unordered + // (true for NaN); `olt | ogt` is ordered on every host. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } } "u64" | "i64" => { let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); @@ -5097,6 +6027,19 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { + // `v_interp_p1ll_f16` writes only the low 16 bits of its target + // VGPR; preserve its prior high 16 bits so `v_interp_p2_f16` and + // mixed-precision ops (`v_fma_mixlo_f16`) retain the high half. + if inst.name() == "v_interp_p1ll_f16" + && let Fields::Valu(v) = &inst.fields + && let Some(Operand::Vector { reg, .. }) = v.dst + && let Some(Ok(old)) = inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) + { + let high = self.s.m.i32(0xFFFF_0000); + let preserved = self.s.m.bin(self.cur, Bin::And, old, high); + self.write(inst, Reg::V(reg), preserved, None); + return Ok(()); + } return Err("the first half of an interpolation"); }; let (attribute, mode) = match interp { @@ -5242,6 +6185,9 @@ impl<'a> Lower<'a> { if *a16 && name.starts_with("image_sample_b") { return Err("a biased image sample with 16-bit coordinates"); } + if *a16 && name.ends_with("_o") && name.starts_with("image_sample") { + return Err("a 16-bit image sample with texel offset"); + } // A load or sample with no channel enabled returns the first. let dmask = if *dmask == 0 { &1 } else { dmask }; let site = (b, i); @@ -5319,11 +6265,20 @@ impl<'a> Lower<'a> { return Err("a 16-bit image atomic"); } // dmask: the data dwords (cmpswap: twice the value's). - // shortcut: 64-bit image atomics (two dwords, an R32G32 view) - // need the host's 64-bit typed atomics; they stop the program. - if *dmask != if code == u32::MAX { 3 } else { 1 } { - return Err("a 64-bit image atomic"); - } + // 32-bit: 1 (or 3 for cmpswap); 64-bit: 3 (or 0xF for cmpswap). + let is_64 = if code == u32::MAX { + match *dmask { + 3 => false, + 0xF => true, + _ => return Err("an image atomic mask"), + } + } else { + match *dmask { + 1 => false, + 3 => true, + _ => return Err("an image atomic mask"), + } + }; let iu = self.s.m.undef(self.s.t.i32); let mut cs = vec![iu; 3]; for (k, slot) in cs.iter_mut().enumerate().take(coords) { @@ -5332,6 +6287,74 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image atomic data"); }; + if is_64 { + let n = if code == u32::MAX { 4 } else { 2 }; + let vals = self.vgprs(inst, data, n)?; + let i64t = self.s.m.int(64); + let shift32 = self.s.m.int_const(i64t, 32); + let pack = |l: &mut Self, lo: V, hi: V| -> V { + let lo64 = l.s.m.cast(l.cur, Cast::ZExt, lo, i64t); + let hi64 = l.s.m.cast(l.cur, Cast::ZExt, hi, i64t); + let hi64 = l.s.m.bin(l.cur, Bin::Shl, hi64, shift32); + l.s.m.bin(l.cur, Bin::Or, lo64, hi64) + }; + let mut val0 = pack(self, vals[0], vals[1]); + let cmp64 = if code == u32::MAX { + Some(pack(self, vals[2], vals[3])) + } else { + None + }; + if op == "sub" { + let z64 = self.s.m.int_const(i64t, 0); + val0 = self.s.m.bin(self.cur, Bin::Sub, z64, val0); + } + let old64 = if cache.glc { + let lo = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let hi = match inst.read(Reg::V(reg + 1)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + pack(self, lo, hi) + } else { + self.s.m.int_const(i64t, 0) + }; + // 1-component U64 typed UAV (ComponentType::U64 = 7 -> 0x107). + let h = self.handle(site, src, false, (kind | 0x1000, 0x107))?; + self.s.flags |= flags::INT64 | flags::ATOMIC_INT64_ON_TYPED_RESOURCE; + if !matches!(src, Source::Built { .. }) { + self.s.flags |= flags::ATOMIC_INT64_ON_HEAP_RESOURCE; + } + let at = self.begin_guarded(guard); + let mut args = vec![h]; + let r = if let Some(cmp) = cmp64 { + args.extend(cs); + args.extend([cmp, val0]); + self.s.op( + self.cur, + "atomicCompareExchange.i64", + Attr::NoUnwind, + i64t, + 79, + &args, + ) + } else { + args.push(self.s.m.i32(code)); + args.extend(cs); + args.push(val0); + self.s + .op(self.cur, "atomicBinOp.i64", Attr::NoUnwind, i64t, 78, &args) + }; + let r = self.end_guarded(at, &[(r, old64)])[0]; + if cache.glc { + let (r_lo, r_hi) = self.split64(r); + self.write(inst, Reg::V(reg), r_lo, None); + self.write(inst, Reg::V(reg + 1), r_hi, None); + } + return Ok(()); + } let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; let mut value = vals[0]; if op == "sub" { @@ -5425,15 +6448,36 @@ impl<'a> Lower<'a> { return Ok(()); } let (op, sample) = match name { - "image_sample" => (60, true), - "image_sample_lz" | "image_sample_l" => (62, true), - "image_sample_b" => (61, true), - "image_sample_c_lz" => (65, true), - "image_sample_d" => (63, true), + "image_sample" | "image_sample_o" | "image_sample_cl" | "image_sample_cl_o" => { + (60, true) + } + "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" | "image_sample_l_o" => { + (62, true) + } + "image_sample_b" + | "image_sample_b_o" + | "image_sample_b_cl" + | "image_sample_b_cl_o" => (61, true), + "image_sample_c_lz" | "image_sample_c_lz_o" => (65, true), + "image_sample_d" + | "image_sample_d_o" + | "image_sample_d_cl" + | "image_sample_d_cl_o" => (63, true), "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. - "image_sample_c" if self.s.pixel => (64, true), - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true), + "image_sample_c" + | "image_sample_c_o" + | "image_sample_c_cl" + | "image_sample_c_cl_o" + if self.s.pixel => + { + (64, true) + } + "image_gather4" + | "image_gather4_lz" + | "image_gather4_lz_o" + | "image_gather4_l" + | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -5492,10 +6536,12 @@ impl<'a> Lower<'a> { } let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, - // signed (programmable offsets: gathers only). + // z in 16-21, signed (constant -8..=7 for samples; programmable + // for gathers). let offset_word = name.ends_with("_o"); - let first = - usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp); + let first = usize::from(offset_word) + + usize::from(name.starts_with("image_sample_b")) + + usize::from(cmp); // Coordinates the size divides (not the array slice); explicit // gradients (x then y) come before the coordinates. let spatial = coords - usize::from(kind == 6 || kind == 7); @@ -5566,20 +6612,42 @@ impl<'a> Lower<'a> { for o in os.iter_mut().take(offsets) { *o = zero; } + if offset_word && op != 73 { + let w = addr_val(self, 0)?; + let raw = self + .s + .m + .int_value(w) + .ok_or("a sample with a non-constant texel offset")? as u32; + for (k, o) in os.iter_mut().enumerate().take(offsets) { + let off = (((raw >> (8 * k)) & 0x3F) as i32) << 26 >> 26; + if !(-8..=7).contains(&off) { + return Err("a sample texel offset outside -8..=7"); + } + *o = self.s.m.i32(off as u32); + } + } + let has_clamp = name.ends_with("_cl") || name.contains("_cl_"); + let clamp_val = if has_clamp { + let x = addr_val(self, first + grads + coords)?; + to_float(self, x) + } else { + fu + }; let mut args = vec![h, sh]; args.extend(&cs); match op { 60 => { args.extend(&os); - args.push(fu); + args.push(clamp_val); self.s .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) } 61 => { - let bias = addr_val(self, 0)?; + let bias = addr_val(self, usize::from(offset_word))?; let bias = self.as_float(bias); args.extend(&os); - args.extend([bias, fu]); + args.extend([bias, clamp_val]); self.s.op( c, "sampleBias.f32", @@ -5599,7 +6667,7 @@ impl<'a> Lower<'a> { } args.extend(&os); args.extend(g); - args.push(fu); + args.push(clamp_val); self.s.op( c, "sampleGrad.f32", @@ -5615,7 +6683,7 @@ impl<'a> Lower<'a> { args.extend(&os); args.push(reference); let name = if op == 64 { - args.push(fu); + args.push(clamp_val); "sampleCmp.f32" } else { "sampleCmpLevelZero.f32" @@ -5624,8 +6692,10 @@ impl<'a> Lower<'a> { .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) } 62 => { - let lod = if name == "image_sample_l" { - let x = addr_val(self, coords)?; + let lod = if name.starts_with("image_sample_l") + && !name.starts_with("image_sample_lz") + { + let x = addr_val(self, first + coords)?; to_float(self, x) } else { self.s.m.f32(0) @@ -5795,36 +6865,31 @@ impl<'a> Lower<'a> { if *lds || *tfe { return Err("a buffer access to LDS or with tfe"); } - if format.is_some() && !name.starts_with("tbuffer_load_format_") { + if format.is_some() + && !name.starts_with("tbuffer_load_format_") + && !name.starts_with("tbuffer_store_format_") + { return Err(name); } let site = (b, i); let guard = self.guard(b, i)?; let c = self.cur; - let store = name.starts_with("buffer_store_"); - // DXIL atomic operations: add, and, or, xor, signed and unsigned - // min and max, exchange; compare-exchange apart. + let store = name.starts_with("buffer_store_") || name.starts_with("tbuffer_store_"); + // DXIL atomic operations: add (and sub via negated add), and, or, xor, + // signed and unsigned min and max, exchange; compare-exchange apart. let atomic = match name.strip_prefix("buffer_atomic_") { None => None, - Some("add") => Some(0), - Some("and") => Some(1), - Some("or") => Some(2), - Some("xor") => Some(3), - Some("smin") => Some(4), - Some("smax") => Some(5), - Some("umin") => Some(6), - Some("umax") => Some(7), - Some("swap") => Some(8), - Some("cmpswap") => Some(u32::MAX), - Some(_) => return Err(name), + Some(rest) => Some(atomic_op(rest).ok_or(name)?), }; // d16: two 16-bit channels per VGPR, low half first. - let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + let d16 = (name.starts_with("buffer_") || name.starts_with("tbuffer_")) + && name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); let (typed, count) = match plain .strip_prefix("buffer_load_") .or(plain.strip_prefix("buffer_store_")) .or(plain.strip_prefix("tbuffer_load_")) + .or(plain.strip_prefix("tbuffer_store_")) { _ if atomic.is_some() => (false, 1), Some("dword") => (false, 1), @@ -5871,6 +6936,7 @@ impl<'a> Lower<'a> { if let Some(x) = extra { off = self.s.m.bin(c, Bin::Add, off, x); } + let root_size = self.root_view_size(src); if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { // A constant buffer read per lane (a dynamically indexed array). // shortcut: the console's CBV descriptor is taken to have a 16-byte @@ -5879,8 +6945,8 @@ impl<'a> Lower<'a> { let byte = match index { Some(i) => { let sixteen = self.s.m.i32(16); - let rows = self.s.m.bin(c, Bin::Mul, i, sixteen); - self.s.m.bin(c, Bin::Add, rows, off) + let rows = self.s.m.bin(self.cur, Bin::Mul, i, sixteen); + self.s.m.bin(self.cur, Bin::Add, rows, off) } None => off, }; @@ -5889,8 +6955,18 @@ impl<'a> Lower<'a> { }; for k in 0..count { let four = self.s.m.i32(4 * k); - let a = self.s.m.bin(c, Bin::Add, byte, four); - let x = self.cbuffer_dword(h, a); + let a = self.s.m.bin(self.cur, Bin::Add, byte, four); + let x = match root_size { + Some(sz) => { + let ok = self.root_in_bounds(sz, a, 4); + let load_guard = self.and_guard(guard, ok); + let at_g = self.begin_guarded(load_guard); + let loaded = self.cbuffer_dword(h, a); + let zero = self.s.m.i32(0); + self.end_guarded(at_g, &[(loaded, zero)])[0] + } + None => self.cbuffer_dword(h, a), + }; self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -5898,19 +6974,44 @@ impl<'a> Lower<'a> { let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let iu = self.s.m.undef(self.s.t.i32); + // Root SRVs/UAVs and root constant-pair views have no structured view on + // the host: lower indexed accesses through their raw view at + // `index * stride + offset`. + let built_raw = matches!(src, Source::Built { .. }); + let struct_stride = |src: &Source, used: Option<&crate::native::UsedResource>| -> u32 { + if let Source::Built { bits, .. } = *src { + let s = (bits >> 16) & 0x3FFF; + if s != 0 { + return s; + } + } + used.map_or(0, |u| u.stride) + }; if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; - let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; - let (h, coords) = match index { + let vals = self.vgprs(inst, d, if matches!(op, AtomicOp::CmpSwap) { 2 } else { 1 })?; + let (h, coords, raw_off) = match index { Some(index) => { - let stride = used.map_or(0, |u| u.stride); + let stride = struct_stride(src, used); if stride < 4 || !stride.is_multiple_of(4) { return Err("a structured buffer of unknown stride"); } - let h = self.handle(site, src, false, (12 | u, stride))?; - (h, [index, off, iu]) + if built_raw { + let sv = self.s.m.i32(stride); + let mul = self.s.m.bin(self.cur, Bin::Mul, index, sv); + let byte = self.s.m.bin(self.cur, Bin::Add, mul, off); + let h = self.handle(site, src, false, (11 | u, 0))?; + (h, [byte, iu, iu], Some(byte)) + } else { + let h = self.handle(site, src, false, (12 | u, stride))?; + (h, [index, off, iu], None) + } } - None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]), + None => ( + self.handle(site, src, false, (11 | u, 0))?, + [off, iu, iu], + Some(off), + ), }; let Operand::Vector { reg, .. } = *d else { return Err("buffer atomic data"); @@ -5920,27 +7021,51 @@ impl<'a> Lower<'a> { Some(v) if returns => self.i32_of(v)?, _ => self.s.m.i32(0), }; + let val = match op { + AtomicOp::Sub => { + let zero = self.s.m.i32(0); + self.s.m.bin(self.cur, Bin::Sub, zero, vals[0]) + } + _ => vals[0], + }; + let guard = match (root_size, raw_off) { + (Some(sz), Some(byte)) => { + let ok = self.root_in_bounds(sz, byte, 4); + self.and_guard(guard, ok) + } + _ => guard, + }; let at = self.begin_guarded(guard); let i32t = self.s.t.i32; - let r = if op == u32::MAX { - // cmpswap: data is (new, compare). - let mut args = vec![h]; - args.extend(coords); - args.extend([vals[1], vals[0]]); - self.s.op( - self.cur, - "atomicCompareExchange.i32", - Attr::NoUnwind, - i32t, - 79, - &args, - ) - } else { - let mut args = vec![h, self.s.m.i32(op)]; - args.extend(coords); - args.push(vals[0]); - self.s - .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + let r = match op { + AtomicOp::CmpSwap => { + // cmpswap: data is (new, compare). + let mut args = vec![h]; + args.extend(coords); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } + AtomicOp::Bin(code) => { + let mut args = vec![h, self.s.m.i32(code)]; + args.extend(coords); + args.push(val); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + } + AtomicOp::Sub => { + let mut args = vec![h, self.s.m.i32(0)]; + args.extend(coords); + args.push(val); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + } }; let r = self.end_guarded(at, &[(r, old)])[0]; if returns { @@ -5952,6 +7077,55 @@ impl<'a> Lower<'a> { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + if let Some(f) = *format { + // `tbuffer_store_format_*` / `_d16_`: lower formats that need + // no conversion directly as a raw buffer store. + let (bits, numeric) = buffer_format(f).ok_or("a buffer format")?; + let n_ch = count.min(bits.len() as u32); + let store_dwords = if !d16 && bits.iter().all(|&b| b == 32) { + n_ch + } else if d16 + && bits.iter().all(|&b| b == 16) + && matches!(numeric, Numeric::Uint | Numeric::Sint | Numeric::Float) + && n_ch.is_multiple_of(2) + && n_ch > 0 + { + n_ch / 2 + } else { + return Err("a formatted buffer store"); + }; + let byte = match index { + Some(index) => { + let stride = struct_stride(src, used); + if stride == 0 { + return Err("a formatted buffer store of unknown stride"); + } + let sv = self.s.m.i32(stride); + let mul = self.s.m.bin(self.cur, Bin::Mul, index, sv); + self.s.m.bin(self.cur, Bin::Add, mul, off) + } + None => off, + }; + let h = self.handle(site, src, false, (11 | u, 0))?; + let mut args = vec![h, byte, iu]; + args.extend(&vals[..store_dwords as usize]); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << store_dwords) - 1)); + args.push(self.s.m.i32(4)); + let guard = match root_size { + Some(sz) => { + let ok = self.root_in_bounds(sz, byte, 4 * store_dwords); + self.and_guard(guard, ok) + } + None => guard, + }; + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } if d16 { // shortcut: d16 data is taken as f16 (integer formats would // keep 16 bits), widened for the 32-bit float store. @@ -5960,17 +7134,18 @@ impl<'a> Lower<'a> { let mut x = vals[(k / 2) as usize]; if k % 2 == 1 { let k16 = self.s.m.i32(16); - x = self.s.m.bin(c, Bin::LShr, x, k16); + x = self.s.m.bin(self.cur, Bin::LShr, x, k16); } let f32t = self.s.t.f32; let f = self .s - .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); wide.push(self.as_int(f)); } vals = wide; } let mut args = Vec::new(); + let mut raw_off = None; let (op, name) = if typed { // shortcut: typed stores are taken to write all four channels // of a float format. @@ -5986,16 +7161,26 @@ impl<'a> Lower<'a> { } else { match index { Some(index) => { - let stride = used.map_or(0, |u| u.stride); + let stride = struct_stride(src, used); if stride < 4 || !stride.is_multiple_of(4) { return Err("a structured buffer of unknown stride"); } - args.push(self.handle(site, src, false, (12 | u, stride))?); - args.extend([index, off]); + if built_raw { + let sv = self.s.m.i32(stride); + let mul = self.s.m.bin(self.cur, Bin::Mul, index, sv); + let byte = self.s.m.bin(self.cur, Bin::Add, mul, off); + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([byte, iu]); + raw_off = Some(byte); + } else { + args.push(self.handle(site, src, false, (12 | u, stride))?); + args.extend([index, off]); + } } None => { args.push(self.handle(site, src, false, (11 | u, 0))?); args.extend([off, iu]); + raw_off = Some(off); } } args.extend(&vals); @@ -6006,6 +7191,13 @@ impl<'a> Lower<'a> { if !typed { args.push(self.s.m.i32(4)); } + let guard = match (root_size, raw_off) { + (Some(sz), Some(byte)) if !typed => { + let ok = self.root_in_bounds(sz, byte, 4 * count); + self.and_guard(guard, ok) + } + _ => guard, + }; let at = self.begin_guarded(guard); let void = self.s.t.void; self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); @@ -6013,18 +7205,98 @@ impl<'a> Lower<'a> { return Ok(()); } if let Some(f) = *format { - if index.is_some() { - return Err("a typed-format load by index"); - } + let byte = match index { + Some(index) => { + let stride = struct_stride(src, used); + if stride == 0 { + return Err("a typed-format load by index"); + } + let sv = self.s.m.i32(stride); + let mul = self.s.m.bin(self.cur, Bin::Mul, index, sv); + self.s.m.bin(self.cur, Bin::Add, mul, off) + } + None => off, + }; let h = self.handle(site, src, false, (11 | u, 0))?; let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let vals = match root_size { + Some(sz) => { + let (bits, _) = buffer_format(f).ok_or("a buffer format")?; + let total_bits: u32 = bits.iter().sum(); + let access_bytes = (total_bits / 8).div_ceil(4) * 4; + let check_off = if total_bits < 32 { + let not3 = self.s.m.i32(!3); + self.s.m.bin(self.cur, Bin::And, byte, not3) + } else { + byte + }; + let ok = self.root_in_bounds(sz, check_off, access_bytes); + let load_guard = self.and_guard(guard, ok); + let at_g = self.begin_guarded(load_guard); + let loaded = self.format_load(h, byte, f, count)?; + let zero = self.s.m.i32(0); + let pairs: Vec<(V, V)> = loaded.into_iter().map(|v| (v, zero)).collect(); + self.end_guarded(at_g, &pairs) + } + None => self.format_load(h, byte, f, count)?, + }; + for (k, x) in vals.into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); } + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + let load_raw_off = if !typed { + match index { + None => Some(off), + Some(index) if built_raw => { + let stride = struct_stride(src, used); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let sv = self.s.m.i32(stride); + let mul = self.s.m.bin(self.cur, Bin::Mul, index, sv); + Some(self.s.m.bin(self.cur, Bin::Add, mul, off)) + } + Some(_) => None, + } + } else { + None + }; + if let (Some(sz), Some(byte)) = (root_size, load_raw_off) { + let h = self.handle(site, src, false, (11 | u, 0))?; + let ok = self.root_in_bounds(sz, byte, 4 * count); + let load_guard = self.and_guard(guard, ok); + let at_g = self.begin_guarded(load_guard); + let c = self.cur; + let mask = self.s.m.i8((1u8 << count) - 1); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let zero = self.s.m.i32(0); + let mut pairs = Vec::with_capacity(count as usize); + for k in 0..count { + let x = self.s.m.extract(c, r, k); + let x = self.as_int(x); + pairs.push((x, zero)); + } + let vals = self.end_guarded(at_g, &pairs); + for (k, x) in vals.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let c = self.cur; let r = if typed { if *offen || matches!(off, V::Inst(_)) || *offset != 0 { return Err("a typed buffer load at an offset"); @@ -6045,38 +7317,36 @@ impl<'a> Lower<'a> { } else { let mask = self.s.m.i8((1u8 << count) - 1); let align = self.s.m.i32(4); - match index { - Some(index) => { - let stride = used.map_or(0, |u| u.stride); - if stride < 4 || !stride.is_multiple_of(4) { - return Err("a structured buffer of unknown stride"); - } - let h = self.handle(site, src, false, (12 | u, stride))?; + match (index, load_raw_off) { + (_, Some(byte)) => { + let h = self.handle(site, src, false, (11 | u, 0))?; self.s.op( c, "rawBufferLoad.f32", Attr::ReadOnly, self.s.t.res_ret, 139, - &[h, index, off, mask, align], + &[h, byte, iu, mask, align], ) } - None => { - let h = self.handle(site, src, false, (11 | u, 0))?; + (Some(index), None) => { + let stride = struct_stride(src, used); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; self.s.op( c, "rawBufferLoad.f32", Attr::ReadOnly, self.s.t.res_ret, 139, - &[h, off, iu, mask, align], + &[h, index, off, mask, align], ) } + (None, None) => unreachable!(), } }; - let Some(Operand::Vector { reg, .. }) = *data else { - return Err("a buffer result"); - }; if d16 { // Two f16 channels per VGPR (an odd last high half 0). let k16 = self.s.m.i32(16); @@ -6119,12 +7389,10 @@ impl<'a> Lower<'a> { let guard = self.guard(b, i)?; let mesh = self.s.mesh.is_some(); let c = self.cur; + let discard_export = guard.is_some() && !mesh && e.done && self.s.pixel; if let Some(g) = guard - && !mesh + && discard_export { - if !(e.done && self.s.pixel) { - return Err("a conditional export"); - } let t = self.s.m.bool(true); let kill = self.s.m.bin(c, Bin::Xor, g, t); self.s @@ -6255,8 +7523,8 @@ impl<'a> Lower<'a> { { return Err("a 16-bit output the stage data does not mark"); } - // A mesh lane writes its own vertex or primitive, where it exports. - let at = if mesh { + // Guard mesh exports and conditional non-final (or non-pixel) exports. + let at = if !discard_export { self.begin_guarded(guard) } else { None @@ -6508,7 +7776,55 @@ impl<'a> Lower<'a> { fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; - for (v, b, i) in std::mem::take(&mut self.data_phis) { + // Resolve pointer-relative address phis BEFORE data phis so any data + // phi referenced by an incoming offset expression is recorded in + // `read_phis` before transitive liveness propagation runs. + let saved_cur = self.cur; + while let Some((phi_v, b, pi, base)) = self.pending_addr_phis.pop() { + let phi = &p.blocks[b].phis[pi]; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + self.cur = qb; + let arg = phi.args[n]; + let mut local = HashMap::new(); + let off = p.blocks[b].insts.first().map_or(0, |i| i.machine.offset); + let x = self + .rel_offset(arg, base, &mut local) + .map_err(|what| fail(off, what))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(phi_v, incoming); + } + self.cur = saved_cur; + let data_phis = std::mem::take(&mut self.data_phis); + // Propagate liveness across chained data phis: if a live phi reads + // another data phi from a reachable predecessor, that phi is live too. + let phi_values: HashSet = data_phis + .iter() + .map(|&(_, b, i)| p.blocks[b].phis[i].value) + .collect(); + let mut changed = true; + while changed { + changed = false; + for &(_, b, i) in &data_phis { + let phi = &p.blocks[b].phis[i]; + if !self.read_phis.contains(&phi.value) { + continue; + } + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + if self.tail[q].is_none() { + continue; + } + let arg = phi.args[n]; + if phi_values.contains(&arg) && self.read_phis.insert(arg) { + changed = true; + } + } + } + } + for (v, b, i) in data_phis { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; let mut incoming = Vec::new(); @@ -6559,21 +7875,27 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { - use super::{Numeric, Parts, buffer_format, lower}; - use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use super::{Lowered, Numeric, Parts, buffer_format, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; use crate::{io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; - /// Lowers a compute program of constants: whether it translates. - fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { + /// Lowers a compute program with optional root-signature layout. + fn lower_cs( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, wave64: false, vgprs: 256, - layout: vec![], - used: vec![], + layout, + used, io: StageIo::Cs(ComputeIo { rsrc2: 0, threads: [1, 1, 1], @@ -6594,8 +7916,13 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + max_wave_size: 64, }) - .map(|_| ()) + } + + /// Lowers a compute program of constants: whether it translates. + fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { + lower_cs(words, vec![], vec![]).map(|_| ()) } #[test] @@ -6630,6 +7957,201 @@ mod tests { } } + #[test] + fn root_uav_global_load_store_and_atomic_lower() { + let layout = vec![RootParam { + root: RootType::Descriptor, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 0, + slot: 3, + }]; + let used = vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 2, + user_data: 0, + slot: 3, + }]; + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 (byte offset) + 0x7E02_0281, // v_mov_b32 v1, 1 (data) + 0xDC30_8000, + 0x0200_0000, // global_load_dword v2, v0, s[0:1] + 0xDC70_8000, + 0x0000_0100, // global_store_dword v0, v1, s[0:1] + 0xDCC9_8000, + 0x0300_0100, // global_atomic_add v3, v0, v1, s[0:1] glc + S_ENDPGM, + ]; + let out = lower_cs(&words, layout, used).expect("root UAV should lower"); + assert_eq!(out.root_uavs, vec![3]); + assert!(out.root_srvs.is_empty()); + assert!(out.root_cbvs.is_empty()); + } + + #[test] + fn missing_value_through_chained_phis_is_rejected() { + // Unmapped input s2 joins twice before feeding a branch condition. + // Transitive phi liveness must reject it instead of substituting 0. + let words = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE82_0381, // s_mov_b32 s2, 1 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 (join 1: phi1(s2_in, 1)) + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE82_0382, // s_mov_b32 s2, 2 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 (join 2: phi2(phi1, 2)) + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + assert!( + matches!(lowers(&words), Err(crate::ShaderError::Unsupported { .. })), + "missing value crossing two phi joins must not silently become 0" + ); + } + + #[test] + fn ds_swizzle_rotate_and_fft_modes_are_rejected() { + // Offset 0xC020 is GFX10 rotate mode, not quad-permute. Feed the + // result into a live branch so lowering must evaluate it. + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xD8D4_C020, + 0x0100_0000, // ds_swizzle_b32 v1, v0 offset:0xC020 + 0x7E00_0501, // v_readfirstlane_b32 s0, v1 + 0xBF07_8000, // s_cmp_lg_u32 s0, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + assert!( + matches!( + lowers(&words), + Err(crate::ShaderError::Unsupported { + what: "ds_swizzle_b32 mode outside quad-permute", + .. + }) + ), + "rotate/FFT ds_swizzle_b32 must not be lowered as quad-permute" + ); + } + + #[test] + fn spill_table_compute_lowers_root_uav_and_constant() { + // Compute shader whose root parameters spill to user_data 16+: + // s[0:1] holds the spill-table pointer (high dword masked via s_and_b32). + let layout = vec![ + RootParam { + root: RootType::Descriptor, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 16, + slot: 2, + }, + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 18, + slot: 0, + }, + ]; + let used = vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 2, + user_data: 16, + slot: 2, + }]; + let words = [ + 0x8701_FF01, + 0x0000_00FF, // s_and_b32 s1, s1, 0xff + 0xF408_0100, + 0xFA00_0000, // s_load_dwordx4 s[4:7], s[0:1], null + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0206, // v_mov_b32 v1, s6 (spilled root constant) + 0xDC70_8000, + 0x0004_0100, // global_store_dword v0, v1, s[4:5] + S_ENDPGM, + ]; + let out = lower_cs(&words, layout, used).expect("spilled compute shader should lower"); + assert_eq!(out.root_uavs, vec![2]); + assert_eq!(out.user_data.len(), 2); + assert!( + out.user_data + .iter() + .any(|u| u.root == RootType::Constants && u.slot == 0 && u.dword == 0) + ); + assert!( + out.user_data + .iter() + .any(|u| u.root == RootType::Descriptor && u.slot == 2 && u.dword == 0) + ); + } + + #[test] + fn host_wave_lane_ops_lower_outside_compute() { + // Constant-lane v_readlane_b32, v_writelane_b32, and v_readfirstlane_b32 + // must lower cleanly in pixel shaders (`MaskData::Host`). + let words = [ + 0x7E00_0285, // v_mov_b32 v0, 5 + 0xD760_0000, + 0x0001_0700, // v_readlane_b32 s0, v0, 3 + 0xD761_0001, + 0x0001_0600, // v_writelane_b32 v1, s0, 3 + 0x7E02_0501, // v_readfirstlane_b32 s1, v1 + 0xBF07_8001, // s_cmp_lg_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE82_0380, // s_mov_b32 s2, 0 + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + max_wave_size: 64, + }) + .expect("host-wave lane ops in pixel shaders should lower"); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, @@ -6650,4 +8172,363 @@ mod tests { assert_eq!(buffer_format(36), None); assert_eq!(buffer_format(78), None); } + + #[test] + fn lds_byte_and_f32_min_lower() { + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0281, // v_mov_b32 v1, 1 + 0xD878_0000, + 0x0000_0100, // ds_write_b8 v0, v1 + 0xD8E8_0000, + 0x0200_0000, // ds_read_u8 v2, v0 + 0xD848_0000, + 0x0000_0100, // ds_min_f32 v0, v1 + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let out = lower(&Parts { + native: &native, + p: &p, + st: &st, + res: &res, + io: &io, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + max_wave_size: 64, + }) + .expect("LDS byte read/write and ds_min_f32 should lower"); + assert!(!out.dxil.is_empty()); + } + + #[test] + fn scaled_multi_term_root_address_lowers() { + // Root descriptor in s[0:1], constant byte offset in s2, index in s3: + // s4 = (s3 << 2) + s0; s4 = s4 + s2; global_load_dword v0, v_off(0), s[4:5] + let layout = vec![ + RootParam { + root: RootType::Descriptor, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 0, + slot: 1, + }, + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 2, + slot: 0, + }, + ]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 2, + user_data: 0, + slot: 1, + }]; + let words = [ + 0x9784_0003, // s_lshl2_add_u32 s4, s3, s0 + 0x8004_0204, // s_add_u32 s4, s4, s2 + 0x8205_8001, // s_addc_u32 s5, s1, 0 + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xDC30_8000, + 0x0104_0000, // global_load_dword v1, v0, s[4:5] + S_ENDPGM, + ]; + let out = lower_cs(&words, layout, used).expect("scaled multi-term address should lower"); + assert_eq!(out.root_srvs, vec![1]); + assert!( + out.user_data + .iter() + .any(|u| u.root == RootType::Descriptor && u.slot == 1 && u.dword == 0) + ); + } + + #[test] + fn root_constant_pair_addresses_lower_to_const_root_views() { + // One RootType::Constants parameter (slot 2, 4 dwords in s0..s3) + // holding two 64-bit buffer pointers: s[0:1] (SRV) and s[2:3] (UAV). + let layout = vec![RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 2, + }]; + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF400_0180, + 0xFA00_0000, // s_load_dword s6, s[0:1], null (const SRV pair 0) + 0xDC30_8000, + 0x0100_0000, // global_load_dword v1, v0, s[0:1] (const SRV pair 0) + 0xDC70_8000, + 0x0002_0100, // global_store_dword v0, v1, s[2:3] (const UAV pair 2) + S_ENDPGM, + ]; + let out = lower_cs(&words, layout, Vec::new()) + .expect("constant-pair 64-bit root addresses should lower"); + assert_eq!( + out.const_srvs, + vec![ConstRootView { + slot: 2, + dword: 0, + register: 0 + }] + ); + assert_eq!( + out.const_uavs, + vec![ConstRootView { + slot: 2, + dword: 2, + register: 0 + }] + ); + assert!(out.root_srvs.is_empty() && out.root_uavs.is_empty()); + } + + #[test] + fn image_atomic_64bit_lowers_with_sfi0_feature_bits() { + let layout = vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }]; + let used = vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }]; + let words = [ + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xF40C_0100, + 0xFA00_0000, // s_load_dwordx8 s[4:11], s[0:1], null + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0281, // v_mov_b32 v2, 1 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xF044_2308, + 0x0001_0200, // image_atomic_add v[2:3], v[0:1], s[4:11] dmask:0x3 dim:SQ_RSRC_IMG_2D glc + S_ENDPGM, + ]; + let out = lower_cs(&words, layout, used).expect("64-bit image atomic should lower"); + let container = crate::dxbc::Container::parse(&out.dxil).unwrap(); + let sfi0 = container.part(crate::dxbc::FourCC::SFI0).unwrap(); + let bits = u64::from_le_bytes(sfi0.data[..8].try_into().unwrap()); + assert_ne!(bits & 0x8000, 0, "Int64Ops feature bit set"); + assert_ne!(bits & 0x40_0000, 0, "AtomicInt64OnTypedResource feature bit set"); + assert_ne!(bits & 0x1000_0000, 0, "AtomicInt64OnHeapResource feature bit set"); + } + + #[test] + fn wave64_lds_compute_adapts_for_wave32_hosts() { + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0281, // v_mov_b32 v1, 1 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + 0xD8D8_0000, + 0x0200_0000, // ds_read_b32 v2, v0 + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 256, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, true, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + + let on_wave64 = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + max_wave_size: 64, + }) + .expect("wave64 target"); + assert_eq!(on_wave64.wave_size, Some(64)); + + let on_wave32 = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + max_wave_size: 32, + }) + .expect("wave32 target"); + assert_eq!(on_wave32.wave_size, None); + } + + #[test] + fn wave5a_valu_cmp_lg_legacy_mul_and_f16_mods_lower() { + // Exercises: + // - v_mul_legacy_f32 (denormal/zero exponent-bit check) + // - v_cmp_lg_f32 (ordered OLT | OGT instead of fcmp one) + // - v_add_f16 with omod mul:2 + // - v_cvt_u16_f16 with float abs/neg modifiers and saturation + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0281, // v_mov_b32 v1, 1 + 0x0E04_0300, // v_mul_legacy_f32 v2, v0, v1 + 0x7C0A_0300, // v_cmp_lg_f32 vcc_lo, v0, v1 + 0xD532_0003, + 0x0802_0300, // v_add_f16 v3, v0, v1 mul:2 + 0xD5D2_0104, + 0x2000_0103, // v_cvt_u16_f16 v4, -|v3| + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + max_wave_size: 64, + }) + .expect("v_mul_legacy_f32, v_cmp_lg_f32, f16 omod, and v_cvt_u16_f16 must lower"); + } + + #[test] + fn root_structured_buffer_and_tbuffer_store_format_lower() { + // Root UAV at user data s[2:3], descriptor built with 16-byte stride + // (0x10 << 16 = 0x10_0000 in dword 1), accessed by index via both a + // structured buffer_load_dword and a conversion-free + // tbuffer_store_format_xyzw (format 77 = 32_32_32_32_FLOAT). + let words = [ + 0xBE80_0302, // s_mov_b32 s0, s2 + 0x8801_FF03, + 0x0010_0000, // s_or_b32 s1, s3, 0x0010_0000 (stride 16) + 0xBE82_03C1, // s_mov_b32 s2, -1 + 0xBE83_03FF, + 0x1101_4FAC, // s_mov_b32 s3, 0x1101_4fac + 0x7E02_0281, // v_mov_b32 v1, 1 + 0x7E04_0282, // v_mov_b32 v2, 2 + 0x7E06_0283, // v_mov_b32 v3, 3 + 0x7E08_0280, // v_mov_b32 v4, 0 (index) + 0xE030_2000, + 0x8000_0004, // buffer_load_dword v0, v4, s[0:3], 0 idxen + 0xEA6F_2000, + 0x8000_0004, // tbuffer_store_format_xyzw v[0:3], v4, s[0:3], 0 format:77 idxen + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![RootParam { + root: RootType::Descriptor, + slot: 0, + user_data: 2, + size: 2, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 0, + stride: 16, + dwords: 4, + user_data: 2, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + max_wave_size: 64, + }) + .expect("root structured buffer load and tbuffer_store_format_xyzw must lower"); + } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df12339d8..1460ee6e03 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -95,7 +95,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use shader::{CONST_VIEW_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -137,6 +137,16 @@ fn parse_loop_limit(value: Option<&str>) -> u32 { /// A translated shader and what the host binds for it. #[derive(Debug, Clone, PartialEq, Eq)] +/// A 64-bit GPU address passed in two adjacent 32-bit root constants +/// `(slot, dword)` and `(slot, dword + 1)`, bound as a root descriptor at +/// register `register` in [`CONST_VIEW_SPACE`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ConstRootView { + pub slot: u8, + pub dword: u32, + pub register: u32, +} + pub struct HostShader { pub stage: HwStage, /// The DXIL container, hashed as D3D12 expects. @@ -154,6 +164,20 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, + /// Root UAVs (raw buffers) the shader reads or writes: `u` in + /// [`ROOT_CBV_SPACE`]. + pub root_uavs: Vec, + /// Root CBVs carried in adjacent root-constant pairs: `b` in + /// [`CONST_VIEW_SPACE`]. + pub const_cbvs: Vec, + /// Root SRVs (raw buffers) carried in adjacent root-constant pairs: + /// `t` in [`CONST_VIEW_SPACE`]. + pub const_srvs: Vec, + /// Root UAVs (raw buffers) carried in adjacent root-constant pairs: + /// `u` in [`CONST_VIEW_SPACE`]. + pub const_uavs: Vec, + /// Declared DXIL compute `WaveSize`, if any (32 or 64). + pub wave_size: Option, } impl HostShader { @@ -183,33 +207,51 @@ pub struct UserData { pub dword: u32, } -/// Translates the vertex, pixel, compute or mesh program of a console -/// shader container. +/// Translates the vertex, pixel, compute, mesh or merged geometry program of +/// a console shader container, assuming a 64-lane capable host GPU. pub fn translate(container: &[u8]) -> Result { + translate_for(container, 64) +} + +/// Like [`translate`], tailored for a host GPU whose maximum supported wave +/// width is `max_wave_size` (32 on 32-lane GPUs, 64 on RDNA/Intel GPUs). +pub fn translate_for(container: &[u8], max_wave_size: u32) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) .ok_or(ShaderError::Malformed("no DXIL part"))?; - let native = crate::native_programs(dxil.data)? - .into_iter() + let progs = crate::native_programs(dxil.data)?; + let native = progs + .iter() .find(|p| { matches!( p.stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms ) }) + .or_else(|| { + // Fall back to merged geometry front-end/NGG stages (`Es`, `Ls`, + // `Gs`) when the container has no standalone `Vs`/`Ms` variant. + progs.iter().find(|p| { + matches!( + (p.stage, &p.io), + (HwStage::Es | HwStage::Ls, crate::native::StageIo::Vs { .. }) + | (HwStage::Gs, crate::native::StageIo::Ms(_)) + ) + }) + }) .ok_or(ShaderError::Unsupported { offset: 0, - what: "a container without a vertex, pixel, compute or mesh program", + what: "a container without a vertex, pixel, compute, mesh or merged geometry program", })?; let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; let res = resource::track(&p, &native.layout, native.stage)?; - let io = io::raise(&p, &native)?; + let io = io::raise(&p, native)?; let st = structure::structure(&p)?; - emit(&c, &native, &p, &st, &io, &res) + emit_for(&c, native, &p, &st, &io, &res, max_wave_size) } -/// Emits a program whose earlier stages already ran. +/// Emits a program whose earlier stages already ran, assuming a 64-lane host. pub fn emit( c: &Container, native: &NativeProgram, @@ -217,6 +259,19 @@ pub fn emit( st: &structure::Structured, io: &io::Io, res: &resource::Resources, +) -> Result { + emit_for(c, native, p, st, io, res, 64) +} + +/// Like [`emit`], tailored to a host GPU's maximum wave lane count. +pub fn emit_for( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, + max_wave_size: u32, ) -> Result { let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { @@ -276,6 +331,7 @@ pub fn emit( outputs, prims, mesh_stride, + max_wave_size, })?; Ok(HostShader { stage: native.stage, @@ -296,6 +352,11 @@ pub fn emit( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + const_cbvs: l.const_cbvs, + const_srvs: l.const_srvs, + const_uavs: l.const_uavs, + wave_size: l.wave_size, }) } @@ -447,6 +508,7 @@ mod tests { } /// A pixel shader writing a constant colour. + #[cfg(windows)] fn constant_color() -> Vec { let mut s = Shader::new(true); s.outputs.push(SigElement { @@ -490,6 +552,11 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + const_cbvs: Vec::new(), + const_srvs: Vec::new(), + const_uavs: Vec::new(), + wave_size: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -500,6 +567,11 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + const_cbvs: Vec::new(), + const_srvs: Vec::new(), + const_uavs: Vec::new(), + wave_size: None, }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 8389c17bea..39bc41f95a 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -9,18 +9,26 @@ use super::container::{self, Binding, Psv, SigElement}; pub const USER_DATA_SPACE: u32 = 0; /// Where immediate samplers are bound: `s` in this space. pub const SAMPLER_SPACE: u32 = 0; -/// Where root CBVs and SRVs are bound: `b` and -/// `t` in this space. +/// Where root CBVs, SRVs and UAVs are bound: `b`, +/// `t` and `u` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// Where 64-bit GPU addresses carried in adjacent root-constant pairs +/// (`RootType::Constants`, `(slot, dword)` + `(slot, dword + 1)`) are bound +/// as host root CBVs/SRVs/UAVs: `b` / `t` / `u` in space 2. +pub const CONST_VIEW_SPACE: u32 = 2; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + pub const USE_64_UAVS: u64 = 1 << 15; + pub const UAVS_AT_EVERY_STAGE: u64 = 1 << 16; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; + pub const ATOMIC_INT64_ON_TYPED_RESOURCE: u64 = 1 << 27; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; + pub const ATOMIC_INT64_ON_HEAP_RESOURCE: u64 = 1 << 32; } pub(crate) struct Types { @@ -64,6 +72,17 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root UAVs (raw buffers) read or written, likewise. + pub root_uavs: Vec<(u8, V)>, + /// Root CBVs backed by adjacent 32-bit root-constant pairs `(slot, dword)`, + /// bound sequentially at `b` in [`CONST_VIEW_SPACE`]. + pub const_cbvs: Vec<(u8, u32, u32, V)>, + /// Root SRVs (raw buffers) backed by root-constant pairs, at `t` in + /// [`CONST_VIEW_SPACE`]. + pub const_srvs: Vec<(u8, u32, u32, V)>, + /// Root UAVs (raw buffers) backed by root-constant pairs, at `u` in + /// [`CONST_VIEW_SPACE`]. + pub const_uavs: Vec<(u8, u32, u32, V)>, pub flags: u64, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, @@ -117,6 +136,10 @@ impl Shader { cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + const_cbvs: Vec::new(), + const_srvs: Vec::new(), + const_uavs: Vec::new(), flags: 0, threads: None, wave_size: None, @@ -232,6 +255,119 @@ impl Shader { h } + /// The handle of the root UAV (a raw buffer) of root parameter `slot`. + pub fn root_uav_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_uavs.push((slot, h)); + h + } + + /// Root CBV handle for a 64-bit GPU address carried in root-constant pair + /// `(slot, dword)` and `(slot, dword + 1)`, bound in [`CONST_VIEW_SPACE`]. + pub fn const_cbv_handle(&mut self, slot: u8, dword: u32) -> V { + if let Some(&(_, _, _, h)) = self + .const_cbvs + .iter() + .find(|&&(s, d, _, _)| s == slot && d == dword) + { + return h; + } + let reg = self.const_cbvs.len() as u32; + let r = self.m.i32(reg); + let bind = [r, r, self.m.i32(CONST_VIEW_SPACE), self.m.i8(2)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 13, 65536); + self.const_cbvs.push((slot, dword, reg, h)); + h + } + + /// Root SRV (raw buffer) handle for a 64-bit GPU address in root-constant + /// pair `(slot, dword)` / `(slot, dword + 1)`, bound in [`CONST_VIEW_SPACE`]. + pub fn const_srv_handle(&mut self, slot: u8, dword: u32) -> V { + if let Some(&(_, _, _, h)) = self + .const_srvs + .iter() + .find(|&&(s, d, _, _)| s == slot && d == dword) + { + return h; + } + let reg = self.const_srvs.len() as u32; + let r = self.m.i32(reg); + let bind = [r, r, self.m.i32(CONST_VIEW_SPACE), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + self.const_srvs.push((slot, dword, reg, h)); + h + } + + /// Root UAV (raw buffer) handle for a 64-bit GPU address in root-constant + /// pair `(slot, dword)` / `(slot, dword + 1)`, bound in [`CONST_VIEW_SPACE`]. + pub fn const_uav_handle(&mut self, slot: u8, dword: u32) -> V { + if let Some(&(_, _, _, h)) = self + .const_uavs + .iter() + .find(|&&(s, d, _, _)| s == slot && d == dword) + { + return h; + } + let reg = self.const_uavs.len() as u32; + let r = self.m.i32(reg); + let bind = [r, r, self.m.i32(CONST_VIEW_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.const_uavs.push((slot, dword, reg, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -305,6 +441,10 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.root_uavs.is_empty() + || !self.const_cbvs.is_empty() + || !self.const_srvs.is_empty() + || !self.const_uavs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -355,20 +495,39 @@ impl Shader { dxil_kind: 13, }); } + for (_, _, reg, _) in self.const_cbvs.clone() { + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, CONST_VIEW_SPACE)), + Some(i32c(&mut self, reg)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 65536)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: CONST_VIEW_SPACE, + register: reg, + dxil_kind: 13, + }); + } if !cbv_list.is_empty() { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - if !self.root_srvs.is_empty() { + if !self.root_srvs.is_empty() || !self.const_srvs.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + for (slot, _) in self.root_srvs.clone() { let ops = vec![ - Some(i32c(&mut self, n as u32)), + Some(i32c(&mut self, list.len() as u32)), Some(self.m.md_value(u)), Some(empty), Some(i32c(&mut self, ROOT_CBV_SPACE)), @@ -386,8 +545,84 @@ impl Shader { dxil_kind: 11, }); } + for (_, _, reg, _) in self.const_srvs.clone() { + let ops = vec![ + Some(i32c(&mut self, list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, CONST_VIEW_SPACE)), + Some(i32c(&mut self, reg)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(i32c(&mut self, 0)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 4, + space: CONST_VIEW_SPACE, + register: reg, + dxil_kind: 11, + }); + } srvs = Some(self.m.md_node(list)); } + let mut uavs = None; + if !self.root_uavs.is_empty() || !self.const_uavs.is_empty() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let f = self.m.bool(false); + let no = self.m.md_value(f); + let mut list = Vec::new(); + for (slot, _) in self.root_uavs.clone() { + let ops = vec![ + Some(i32c(&mut self, list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(no), + Some(no), + Some(no), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + for (_, _, reg, _) in self.const_uavs.clone() { + let ops = vec![ + Some(i32c(&mut self, list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, CONST_VIEW_SPACE)), + Some(i32c(&mut self, reg)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(no), + Some(no), + Some(no), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + space: CONST_VIEW_SPACE, + register: reg, + dxil_kind: 11, + }); + } + uavs = Some(self.m.md_node(list)); + } let mut samplers = None; if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); @@ -417,12 +652,13 @@ impl Shader { } samplers = Some(self.m.md_node(list)); } - resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers])); - // PSV0 lists them as the module does: CBVs, samplers, SRVs. + resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. bindings.sort_by_key(|b| match b.kind { 2 => 0, 1 => 1, - _ => 2, + 3..=5 => 2, + _ => 3, }); } if let Some(r) = resources { @@ -430,6 +666,12 @@ impl Shader { } let graphics = self.threads.is_none() || self.mesh.is_some(); + if !self.root_uavs.is_empty() && graphics && !self.pixel { + self.flags |= flags::UAVS_AT_EVERY_STAGE; + } + if self.root_uavs.len() > 8 { + self.flags |= flags::USE_64_UAVS; + } if graphics { // shortcut: every output is declared to depend on every input; the // exact sets need a dependence pass. Drivers read this state. @@ -549,6 +791,12 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::UAVS_AT_EVERY_STAGE != 0 { + features |= 0x4; + } + if self.flags & flags::USE_64_UAVS != 0 { + features |= 0x8; + } if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } @@ -558,12 +806,18 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::ATOMIC_INT64_ON_TYPED_RESOURCE != 0 { + features |= 0x40_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } if self.flags & flags::SAMPLER_HEAP != 0 { features |= 0x400_0000; } + if self.flags & flags::ATOMIC_INT64_ON_HEAP_RESOURCE != 0 { + features |= 0x1000_0000; + } let sfi0 = features.to_le_bytes(); let isg1 = container::signature(&self.inputs, true); let osg1 = container::signature(&self.outputs, false); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6e40..05c11f1515 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -136,6 +136,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + max_wave_size: 64, }) .expect("lower"); @@ -147,6 +148,11 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + const_cbvs: lowered.const_cbvs, + const_srvs: lowered.const_srvs, + const_uavs: lowered.const_uavs, + wave_size: lowered.wave_size, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -181,6 +187,7 @@ fn run_cases( ud[u.index as usize] = match (u.root, u.slot) { (RootType::Constants, 0) => inputs[u.dword as usize], (RootType::Table, 1) => 0, + (RootType::Descriptor, _) => 1 << 20, other => panic!("unexpected user data {other:?}"), }; } diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index f114db132f..5fec1814c9 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -253,11 +253,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { let Some(k) = lo else { return shapes(vec, uni, wave); }; - exec = if name == "s_mov_b64" { + exec = (if name == "s_mov_b64" { k } else { exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF - }; + }) & all; continue; } if inst.write(Reg::S(EXEC + 1)).is_some() { @@ -268,7 +268,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { else { return shapes(vec, uni, wave); }; - exec = exec & 0xFFFF_FFFF | k << 32; + exec = (exec & 0xFFFF_FFFF | k << 32) & all; continue; } if let Fields::Sop { src, .. } = &inst.fields { @@ -497,8 +497,11 @@ fn constant(inst: &Inst) -> Option { match *src.first()? { Operand::Const(c) => { let x = crate::resource::inline(c)?; - Some(if (x as i32) < 0 { - u64::MAX + // Inline integers (-16..-1, codes 193..=208) sign-extend to 64 + // bits (e.g. -2 -> 0xFFFF_FFFF_FFFF_FFFE, not all-ones); other + // constants carry their 32-bit bit pattern zero-extended. + Some(if (193..=208).contains(&c) { + i64::from(x as i32) as u64 } else { u64::from(x) }) @@ -577,7 +580,8 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { }; } // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). - let mut found: Option<(Op, Value, Value, u32, bool)> = None; + let mut meta: Option<(Value, Value, u32, bool)> = None; + let mut found_op: Option = None; for (l, &s) in lanes.iter().enumerate() { let below = (1u64 << l) - 1; let (op, src, mask, ident, set) = match s { @@ -596,19 +600,22 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { if !inclusive && set != below { return None; } - let op = match (op, found) { - (Some(o), _) => o, - (None, Some(f)) => f.0, - (None, None) => continue, - }; - let me = (op, src, mask, ident, inclusive); - match found { - None => found = Some(me), - Some(f) if f == me => {} + let m = (src, mask, ident, inclusive); + match meta { + None => meta = Some(m), + Some(prev) if prev == m => {} _ => return None, } + if let Some(o) = op { + match found_op { + None => found_op = Some(o), + Some(prev) if prev == o => {} + _ => return None, + } + } } - let (op, src, mask, ident, inclusive) = found?; + let (src, mask, ident, inclusive) = meta?; + let op = found_op?; if let Sym::K(k) = lanes[0] && (inclusive || k != ident) { @@ -675,5 +682,15 @@ mod tests { per_lane(&vec![red(u64::MAX); 64], u64::MAX), Some(Shape::Active(Op::AddU, x, m, 0)) ); + // Mismatched `op: None` lane must not silently pass prefix validation. + let mut bad_prefix = inclusive.clone(); + bad_prefix[0] = Sym::Red { + op: None, + src: Value(99), + mask: m, + ident: 0, + lanes: 1, + }; + assert_eq!(per_lane(&bad_prefix, u64::MAX), None); } } diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 0b7f45b8f4..7e1b515e6f 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -202,7 +202,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { .collect(); (loaded, &inputs[..], &[][..]) } - (StageIo::Vs { inputs, outputs }, HwStage::Vs) => { + (StageIo::Vs { inputs, outputs }, HwStage::Vs | HwStage::Es | HwStage::Ls) => { let mut loaded = vec![ (Reg::V(0), Input::VertexId), (Reg::V(2), Input::PrimitiveId), @@ -234,7 +234,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo))); (loaded, &[][..], &[][..]) } - (StageIo::Ms(ms), HwStage::Ms) => { + (StageIo::Ms(ms), HwStage::Ms | HwStage::Gs) => { let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1); // The group input holds the same value in every lane only as the // first lane reads it; a VGPR write reads its old value too. diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index dd62c2f904..8fb981b72a 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -519,7 +519,7 @@ fn programs(fssm: &[u8]) -> Result, ShaderError> { let stage_data = &payload[(start + RECORD_SIZE) as usize..]; let io = match stage { HwStage::Ps => ps_io(stage_data, code.len())?, - HwStage::Vs => vs_io(stage_data)?, + HwStage::Vs | HwStage::Es | HwStage::Ls => vs_io(stage_data)?, HwStage::Cs => StageIo::Cs(ComputeIo { rsrc2: u32_at(stage_data, CS_RSRC2)?, threads: [ @@ -529,7 +529,17 @@ fn programs(fssm: &[u8]) -> Result, ShaderError> { ], }), HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, - _ => StageIo::None, + // NGG merged geometry stages (`Gs`) carry mesh-style limits when + // compiled as NGG, or vertex-style I/O tables otherwise. + HwStage::Gs => match ms_io(stage_data, u32_at(record, RECORD_LDS)?) { + Ok(StageIo::Ms(ms)) + if ms.threads > 0 && ms.max_vertices > 0 && ms.max_primitives > 0 => + { + StageIo::Ms(ms) + } + _ => vs_io(stage_data).unwrap_or(StageIo::None), + }, + HwStage::Hs => vs_io(stage_data).unwrap_or(StageIo::None), }; out.push(NativeProgram { stage, diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 46cf891627..e0e78cd4fe 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -12,6 +12,8 @@ //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. +use std::collections::HashMap; + use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{Inst, Program, Reg, Value}; @@ -20,16 +22,33 @@ use crate::native::{HwStage, RootParam, RootType}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); -/// A byte address: a root parameter's, plus a constant and at most one -/// value the program computes (an index times a stride, say). +/// A multi-term, scaled, masked, or phi-joined byte offset relative to `base`: +/// the program computes `value = base + rel_offset` (modulo 2^32), plus an +/// optional `extra` term from the instruction's offset register. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RelOffset { + pub value: Value, + pub base: Value, + pub extra: Option, +} + +/// A byte address: a root parameter's, plus a constant and optional computed +/// offset (either a single value in `dynamic`, or a general relative +/// expression in `rel` for multi-term, scaled, masked, or phi-joined pointers). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Address { /// Index into the layout, or [`CODE`]. pub param: usize, + /// First dword within `param` holding the low half of a 64-bit address + /// (always 0 for `Descriptor`/`Table`/heap parameters; the low constant + /// dword index for a 64-bit address passed in a `RootType::Constants` + /// pair). + pub param_dword: u32, /// Added modulo 2^32 (with carry into the high half of a root /// descriptor's address). pub offset: u32, pub dynamic: Option, + pub rel: Option, } /// [`Address::param`] of the program's own code: a constant table the @@ -86,9 +105,12 @@ pub struct Resources { /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, pub descriptors: Vec, - /// User SGPRs holding root parameters: value on entry, layout index, - /// dword within the parameter. + /// User SGPRs and spilled user-data loads holding root parameters: value, + /// layout index, dword within the parameter. pub params: Vec<(Value, usize, u32)>, + /// `s_load_*` sites that read spilled user-data dwords (`16+`) through + /// the spill-table pointer in user SGPRs `0..2`. + pub spill_loads: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as @@ -96,15 +118,24 @@ pub struct Resources { /// cannot trace. pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result { let t = Tracer::new(p, layout, stage)?; + let mut params: Vec<(Value, usize, u32)> = p + .inputs + .iter() + .filter_map(|&(reg, v)| { + let (param, dword) = t.param_of(reg)?; + Some((v, param, dword)) + }) + .collect(); + let mut spilled: Vec<(Value, usize, u32)> = t + .spilled + .iter() + .map(|(&v, &(param, dword))| (v, param, dword)) + .collect(); + spilled.sort_unstable_by_key(|&(v, _, _)| v.0); + params.extend(spilled); let mut out = Resources { - params: p - .inputs - .iter() - .filter_map(|&(reg, v)| { - let (param, dword) = t.param_of(reg)?; - Some((v, param, dword)) - }) - .collect(), + params, + spill_loads: t.spill_loads.clone(), ..Resources::default() }; for (b, block) in p.blocks.iter().enumerate() { @@ -136,6 +167,9 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result { + if t.spill_loads.contains(&site) { + continue; + } let address = t.smem_address(inst, base, *offset, soffset).map_err(fail)?; out.scalar.push((site, address)); } @@ -165,11 +199,57 @@ enum Term { } /// A 32-bit sum: optional root parameter (as its first dword), constant, -/// optional computed term. +/// optional computed term, and whether the expression needs general relative +/// lowering (`multi`: multiple dynamic terms, shifts, subtractions, or phis). +#[derive(Clone, Copy)] struct Sum { base: Option, offset: u32, dynamic: Option, + multi: bool, + cyclic: bool, +} + +impl Sum { + fn plain(offset: u32) -> Self { + Self { + base: None, + offset, + dynamic: None, + multi: false, + cyclic: false, + } + } + + fn dynamic(v: Value) -> Self { + Self { + base: None, + offset: 0, + dynamic: Some(v), + multi: false, + cyclic: false, + } + } + + fn base(v: Value) -> Self { + Self { + base: Some(v), + offset: 0, + dynamic: None, + multi: false, + cyclic: false, + } + } + + fn cyclic() -> Self { + Self { + base: None, + offset: 0, + dynamic: None, + multi: false, + cyclic: true, + } + } } struct Tracer<'a> { @@ -183,6 +263,15 @@ struct Tracer<'a> { /// Register per input value. inputs: Vec>, origin: Vec, + /// Values loaded from a user-data spill table (`user_data >= 16`): + /// layout index and dword within the parameter. + spilled: HashMap, + /// Values loaded from the spill table keyed by `(param, dword)` so both + /// 64-bit `RootType::Descriptor` high halves (dword 1) and 64-bit + /// `RootType::Constants` address pairs (`dword + 1`) can be verified. + spill_dwords: HashMap<(usize, u32), Vec>, + /// `s_load_*` sites that read the user-data spill table. + spill_loads: Vec, } const MAX_ROUNDS: usize = 64; @@ -226,8 +315,12 @@ impl<'a> Tracer<'a> { phis, inputs, origin: Vec::new(), + spilled: HashMap::new(), + spill_dwords: HashMap::new(), + spill_loads: Vec::new(), }; t.origin = t.propagate_copies(n)?; + t.collect_spill_loads(); Ok(t) } @@ -319,6 +412,127 @@ impl<'a> Tracer<'a> { }) } + /// Layout index and dword of spilled user-data dword `ud`. + fn param_of_user_data(&self, ud: u32) -> Option<(usize, u32)> { + self.layout.iter().enumerate().find_map(|(i, p)| { + let dword = ud.checked_sub(u32::from(p.user_data))?; + (dword < p.sgprs).then_some((i, dword)) + }) + } + + /// Layout index and dword of root parameter value `v` (either an entry + /// user SGPR or a value loaded from the user-data spill table). + fn param_of_value(&self, v: Value) -> Option<(usize, u32)> { + if let Some(reg) = self.inputs[v.0 as usize] { + return self.param_of(reg); + } + self.spilled.get(&v).copied() + } + + /// Recognizes `s_load_dword*` reads from the user-data spill table pointed + /// to by user SGPRs `0..2` when the root layout places parameters at + /// `user_data >= 16` (leaving `0..2` free for the 64-bit table pointer): + /// byte `4 * k` holds user-data dword `16 + k`. + fn collect_spill_loads(&mut self) { + let has_spill = !self.layout.is_empty() + && self.layout.iter().any(|rp| rp.user_data >= 16) + && self.layout.iter().all(|rp| rp.user_data >= 2); + if !has_spill { + return; + } + let lo_reg = Reg::S(self.stage.user_sgpr(0)); + let hi_reg = Reg::S(self.stage.user_sgpr(1)); + let Some(spill_lo) = self.p.inputs.iter().find(|i| i.0 == lo_reg).map(|i| i.1) else { + return; + }; + let Some(spill_hi) = self.p.inputs.iter().find(|i| i.0 == hi_reg).map(|i| i.1) else { + return; + }; + for (b, block) in self.p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let Fields::Smem { + data: Some(Operand::Scalar { code: dst, .. }), + base: Operand::Scalar { code, .. }, + offset, + soffset, + .. + } = &inst.fields + else { + continue; + }; + let Some(count) = smem_load_dwords(inst.name()) else { + continue; + }; + let (Some(lo), Some(hi)) = ( + inst.read(Reg::S(*code)).map(|v| self.origin(v)), + inst.read(Reg::S(code + 1)).map(|v| self.origin(v)), + ) else { + continue; + }; + let Some(lo_off) = self.spill_lo_offset(lo, spill_lo) else { + continue; + }; + if !self.is_spill_hi(hi, spill_hi) { + continue; + } + let Some(Term::Const(soff)) = self.term(inst, soffset) else { + continue; + }; + let byte_off = lo_off.wrapping_add(*offset as u32).wrapping_add(soff); + if !byte_off.is_multiple_of(4) { + continue; + } + let first_ud = 16u32.saturating_add(byte_off / 4); + for k in 0..count { + if let Some((param, dword)) = self.param_of_user_data(first_ud + k) + && let Some(v) = inst.write(Reg::S(*dst + k as u8)) + { + self.spilled.insert(v, (param, dword)); + self.spill_dwords.entry((param, dword)).or_default().push(v); + } + } + self.spill_loads.push((b, i)); + } + } + } + + /// Constant byte offset added to `spill_lo`, if `t` traces strictly to + /// `spill_lo + const`. + fn spill_lo_offset(&self, t: Term, spill_lo: Value) -> Option { + let Term::Value(v) = t else { return None }; + if v == spill_lo { + return Some(0); + } + let (_, [a, b]) = self.sop2(v, &["s_add_u32", "s_add_i32"])?; + match (a, b) { + (x, Term::Const(c)) | (Term::Const(c), x) => { + self.spill_lo_offset(x, spill_lo).map(|o| o.wrapping_add(c)) + } + _ => None, + } + } + + /// Whether `hi` is the spill-table high dword (optionally masked to a + /// 40/48-bit address via `s_and_b32` / `s_bfe_u32` or carried by 0). + fn is_spill_hi(&self, hi: Term, spill_hi: Value) -> bool { + let Term::Value(v) = hi else { return false }; + if v == spill_hi { + return true; + } + if let Some((_, [a, b])) = self.sop2(v, &["s_and_b32"]) { + return matches!(b, Term::Const(_)) && self.is_spill_hi(a, spill_hi) + || matches!(a, Term::Const(_)) && self.is_spill_hi(b, spill_hi); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_bfe_u32"]) { + return matches!(b, Term::Const(_)) && self.is_spill_hi(a, spill_hi); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return (b == Term::Const(0) && self.is_spill_hi(a, spill_hi)) + || (a == Term::Const(0) && self.is_spill_hi(b, spill_hi)); + } + false + } + /// The SOP2 operands of `v` if an `s_add` with one of `names` wrote it. fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { let inst = self.def(v)?; @@ -337,55 +551,383 @@ impl<'a> Tracer<'a> { )) } + /// Whether layout entry `param` holds a pointer/address (never root + /// constants, so a constant dword 0 added to a root pointer is treated as + /// a dynamic offset rather than a colliding second pointer base). + fn is_pointer_param(&self, param: usize) -> bool { + matches!( + self.layout[param].root, + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap | RootType::Descriptor + ) + } + fn sum(&self, t: Term) -> Sum { + self.sum_inner(t, &mut Vec::new()) + } + + fn combine_add(x: Sum, y: Sum, v: Value) -> Sum { + if x.cyclic || y.cyclic { + return Sum::cyclic(); + } + if x.base.is_some() && y.base.is_some() { + return Sum::dynamic(v); + } + let multi = x.multi || y.multi || (x.dynamic.is_some() && y.dynamic.is_some()); + Sum { + base: x.base.or(y.base), + offset: x.offset.wrapping_add(y.offset), + dynamic: if multi { + Some(v) + } else { + x.dynamic.or(y.dynamic) + }, + multi, + cyclic: false, + } + } + + fn sum_inner(&self, t: Term, visiting: &mut Vec) -> Sum { let v = match t { - Term::Const(c) => { - return Sum { - base: None, - offset: c, - dynamic: None, - }; - } + Term::Const(c) => return Sum::plain(c), Term::Value(v) => v, }; - let dynamic = Sum { - base: None, - offset: 0, - dynamic: Some(v), - }; - if let Some(reg) = self.inputs[v.0 as usize] { - return match self.param_of(reg) { - Some((_, 0)) => Sum { - base: Some(v), - offset: 0, - dynamic: None, - }, - _ => dynamic, - }; + if self + .param_of_value(v) + .is_some_and(|(p, d)| d == 0 && self.is_pointer_param(p)) + { + return Sum::base(v); + } + if self.inputs[v.0 as usize].is_some() { + return Sum::dynamic(v); } if self.getpc(v).is_some() { - return Sum { - base: Some(v), - offset: 0, - dynamic: None, - }; + return Sum::base(v); } - let Some([a, b]) = self - .sop2(v, &["s_add_u32", "s_add_i32"]) - .map(|(_, t)| t) - .or_else(|| self.vadd(v)) - else { - return dynamic; - }; - let (x, y) = (self.sum(a), self.sum(b)); - if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { - return dynamic; + if visiting.contains(&v) { + return Sum::cyclic(); } - Sum { - base: x.base.or(y.base), - offset: x.offset.wrapping_add(y.offset), - dynamic: x.dynamic.or(y.dynamic), + if let Some((b, pi)) = self.phis[v.0 as usize] { + visiting.push(v); + let mut agreed: Option = None; + let mut ok = true; + for &arg in &self.p.blocks[b].phis[pi].args { + let s = self.sum_inner(self.origin(arg), visiting); + if s.cyclic { + continue; + } + match (agreed, s.base) { + (None, Some(base)) => agreed = Some(base), + (Some(prev), Some(base)) if prev == base => {} + _ => { + ok = false; + break; + } + } + } + visiting.pop(); + if ok && let Some(base) = agreed { + return Sum { + base: Some(base), + offset: 0, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + return Sum::dynamic(v); + } + let Some(inst) = self.def(v) else { + return Sum::dynamic(v); + }; + visiting.push(v); + let out = self.sum_inst(v, inst, visiting); + visiting.pop(); + out + } + + fn sum_inst(&self, v: Value, inst: &'a Inst, visiting: &mut Vec) -> Sum { + let name = inst.name(); + match &inst.fields { + Fields::Sop { dst, src, imm } if inst.writes.first().is_some_and(|w| w.1 == v) => { + match name { + "s_mov_b32" => { + if let Some(t) = src.first().and_then(|o| self.term(inst, o)) { + return self.sum_inner(t, visiting); + } + } + "s_add_u32" | "s_add_i32" => { + if let (Some(a), Some(b)) = ( + src.first().and_then(|o| self.term(inst, o)), + src.get(1).and_then(|o| self.term(inst, o)), + ) { + let (x, y) = ( + self.sum_inner(a, visiting), + self.sum_inner(b, visiting), + ); + return Self::combine_add(x, y, v); + } + } + "s_addk_i32" => { + if let (Some(d), Some(k)) = (dst.as_ref(), *imm) + && let Some(a) = self.term(inst, d) + { + let x = self.sum_inner(a, visiting); + let off = i32::from(k as i16) as u32; + return Self::combine_add(x, Sum::plain(off), v); + } + } + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" + | "s_lshl4_add_u32" => { + let shift = match name { + "s_lshl1_add_u32" => 1u32, + "s_lshl2_add_u32" => 2, + "s_lshl3_add_u32" => 3, + _ => 4, + }; + if let (Some(a), Some(b)) = ( + src.first().and_then(|o| self.term(inst, o)), + src.get(1).and_then(|o| self.term(inst, o)), + ) { + let sb = self.sum_inner(b, visiting); + if sb.cyclic { + return Sum::cyclic(); + } + if let Term::Const(c) = a { + return Self::combine_add(sb, Sum::plain(c.wrapping_shl(shift)), v); + } + let sa = self.sum_inner(a, visiting); + if sa.cyclic { + return Sum::cyclic(); + } + if sb.base.is_some() && sa.base.is_none() { + return Sum { + base: sb.base, + offset: sb.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + "s_sub_u32" | "s_sub_i32" => { + if let (Some(a), Some(b)) = ( + src.first().and_then(|o| self.term(inst, o)), + src.get(1).and_then(|o| self.term(inst, o)), + ) { + let (sa, sb) = ( + self.sum_inner(a, visiting), + self.sum_inner(b, visiting), + ); + if sa.cyclic || sb.cyclic { + return Sum::cyclic(); + } + if sa.base.is_some() && sb.base.is_none() { + if let Term::Const(c) = b { + return Sum { + base: sa.base, + offset: sa.offset.wrapping_sub(c), + dynamic: sa.dynamic, + multi: sa.multi, + cyclic: false, + }; + } + return Sum { + base: sa.base, + offset: sa.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + "s_or_b32" => { + if let (Some(a), Some(b)) = ( + src.first().and_then(|o| self.term(inst, o)), + src.get(1).and_then(|o| self.term(inst, o)), + ) { + let (x, c) = match (a, b) { + (x, Term::Const(c)) | (Term::Const(c), x) if c < 256 => (x, c), + _ => return Sum::dynamic(v), + }; + let sx = self.sum_inner(x, visiting); + if sx.cyclic { + return Sum::cyclic(); + } + if sx.base.is_some() { + let _ = c; + return Sum { + base: sx.base, + offset: sx.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + _ => {} + } + } + Fields::Valu(f) + if f.abs == 0 && f.neg == 0 && f.sdwa.is_none() && f.dpp.is_none() => + { + let writes_v = match f.dst { + Some(Operand::Vector { reg, .. }) => inst.write(Reg::V(reg)) == Some(v), + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)) == Some(v), + _ => false, + }; + if !writes_v { + return Sum::dynamic(v); + } + match name { + "v_mov_b32" | "v_readfirstlane_b32" | "v_readlane_b32" => { + if let Some(a) = f.src.first().and_then(|o| self.vterm(inst, o)) { + let sa = self.sum_inner(a, visiting); + if sa.cyclic { + return Sum::cyclic(); + } + if sa.base.is_some() && name != "v_mov_b32" { + return Sum { + base: sa.base, + offset: sa.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + return sa; + } + } + "v_add_co_u32" | "v_add_nc_u32" | "v_add_nc_i32" => { + if let (Some(a), Some(b)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + ) { + let (x, y) = ( + self.sum_inner(a, visiting), + self.sum_inner(b, visiting), + ); + return Self::combine_add(x, y, v); + } + } + "v_add3_u32" => { + if let (Some(a), Some(b), Some(c)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + f.src.get(2).and_then(|o| self.vterm(inst, o)), + ) { + let ab = Self::combine_add( + self.sum_inner(a, visiting), + self.sum_inner(b, visiting), + v, + ); + let mut abc = + Self::combine_add(ab, self.sum_inner(c, visiting), v); + if abc.base.is_some() { + abc.multi = true; + abc.dynamic = Some(v); + } + return abc; + } + } + "v_lshl_add_u32" => { + if let (Some(a), Some(sh), Some(b)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + f.src.get(2).and_then(|o| self.vterm(inst, o)), + ) { + let sb = self.sum_inner(b, visiting); + if sb.cyclic { + return Sum::cyclic(); + } + if let (Term::Const(cv), Term::Const(sv)) = (a, sh) { + return Self::combine_add(sb, Sum::plain(cv.wrapping_shl(sv & 31)), v); + } + let sa = self.sum_inner(a, visiting); + let ss = self.sum_inner(sh, visiting); + if sa.cyclic || ss.cyclic { + return Sum::cyclic(); + } + if sb.base.is_some() && sa.base.is_none() && ss.base.is_none() { + return Sum { + base: sb.base, + offset: sb.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + "v_sub_co_u32" | "v_sub_nc_u32" | "v_subrev_co_u32" | "v_subrev_nc_u32" => { + if let (Some(s0), Some(s1)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + ) { + let (a, b) = if name.starts_with("v_subrev_") { + (s1, s0) + } else { + (s0, s1) + }; + let (sa, sb) = ( + self.sum_inner(a, visiting), + self.sum_inner(b, visiting), + ); + if sa.cyclic || sb.cyclic { + return Sum::cyclic(); + } + if sa.base.is_some() && sb.base.is_none() { + if let Term::Const(c) = b { + return Sum { + base: sa.base, + offset: sa.offset.wrapping_sub(c), + dynamic: sa.dynamic, + multi: sa.multi, + cyclic: false, + }; + } + return Sum { + base: sa.base, + offset: sa.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + "v_or_b32" => { + if let (Some(a), Some(b)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + ) { + let x = match (a, b) { + (x, Term::Const(c)) | (Term::Const(c), x) if c < 256 => x, + _ => return Sum::dynamic(v), + }; + let sx = self.sum_inner(x, visiting); + if sx.cyclic { + return Sum::cyclic(); + } + if sx.base.is_some() { + return Sum { + base: sx.base, + offset: sx.offset, + dynamic: Some(v), + multi: true, + cyclic: false, + }; + } + } + } + _ => {} + } + } + _ => {} } + Sum::dynamic(v) } /// The `s_getpc_b64` writing `lo` as its low dword. @@ -395,32 +937,6 @@ impl<'a> Tracer<'a> { .then_some(inst) } - /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`) - /// writing `v`, through VGPR copies of scalars. - fn vadd(&self, v: Value) -> Option<[Term; 2]> { - let inst = self.def(v)?; - let Fields::Valu(f) = &inst.fields else { - return None; - }; - if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32") - || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. })) - || inst.write(Reg::V(match f.dst? { - Operand::Vector { reg, .. } => reg, - _ => return None, - })) != Some(v) - || f.abs != 0 - || f.neg != 0 - || f.sdwa.is_some() - || f.dpp.is_some() - { - return None; - } - Some([ - self.vterm(inst, f.src.first()?)?, - self.vterm(inst, f.src.get(1)?)?, - ]) - } - /// The origin of a VALU operand. fn vterm(&self, inst: &Inst, op: &Operand) -> Option { match *op { @@ -477,15 +993,7 @@ impl<'a> Tracer<'a> { let (Some(lo), Some(hi)) = (word(0), word(1)) else { return Err("a global address"); }; - self.address( - lo, - hi, - Sum { - base: None, - offset: off, - dynamic: None, - }, - ) + self.address(lo, hi, Sum::plain(off)) } } } @@ -494,81 +1002,273 @@ impl<'a> Tracer<'a> { /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { let s = self.sum(lo); - if s.dynamic.is_some() && extra.dynamic.is_some() { - return Err("an address with two computed terms"); - } let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?; + let use_rel = s.multi || (s.dynamic.is_some() && extra.dynamic.is_some()); + let rel = if use_rel { + let Term::Value(lo_val) = lo else { + unreachable!("a sum with a base comes from a Value"); + }; + Some(RelOffset { + value: lo_val, + base, + extra: extra.dynamic, + }) + } else { + None + }; + let has_dynamic = s.dynamic.is_some() || extra.dynamic.is_some() || rel.is_some(); + let dynamic = s.dynamic.or(extra.dynamic); + // When `rel` is used, `lo_val` already incorporates `s.offset`; keep + // only `extra.offset` in `Address::offset` to avoid double-counting. + let byte_offset = if rel.is_some() { + extra.offset + } else { + s.offset.wrapping_add(extra.offset) + }; if let Some(pc) = self.getpc(base) { // A table in the code: the base is the next instruction's offset. let high = pc.writes.get(1).map(|w| w.1); - if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { + if !self.high_half(hi, high) + && !high.is_some_and(|h| self.carried(hi, Term::Value(h))) + { return Err("an address with an untracked high half"); } return Ok(Address { param: CODE, - offset: (pc.machine.offset as u32 + 4) - .wrapping_add(s.offset) - .wrapping_add(extra.offset), - dynamic: s.dynamic.or(extra.dynamic), + param_dword: 0, + offset: (pc.machine.offset as u32 + 4).wrapping_add(byte_offset), + dynamic, + rel, }); } - let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?; - let (param, _) = self - .param_of(reg) + let (param, param_dword) = self + .param_of_value(base) .ok_or("an address not from a root parameter")?; - let high = match self.layout[param].root { - RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None, + let matches_high_dword = |high_dword: u32| -> Result { + // shortcut: with a computed term, a high half that adds + // anything to the base's is taken as the carry of that term + // (offsets below 4 GB). + let matches_high = |h: Value| { + self.high_half(hi, Some(h)) + || (has_dynamic && self.carried(hi, Term::Value(h))) + }; + let rp = self.layout[param]; + let ud = u32::from(rp.user_data).saturating_add(high_dword); + let mut found_any = false; + if ud < 16 { + let high = Reg::S(self.stage.user_sgpr(ud as u8)); + if let Some(h) = self.p.inputs.iter().find(|i| i.0 == high).map(|i| i.1) { + found_any = true; + if matches_high(h) { + return Ok(true); + } + } + } + if let Some(highs) = self.spill_dwords.get(&(param, high_dword)) { + found_any = true; + if highs.iter().copied().any(matches_high) { + return Ok(true); + } + } + if !found_any { + return Err("a root descriptor without its high half"); + } + Ok(false) + }; + let high_ok = match self.layout[param].root { + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => { + self.high_half(hi, None) + || (has_dynamic && self.carried(hi, Term::Const(0))) + } RootType::Descriptor => { - let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1); - let input = self.p.inputs.iter().find(|i| i.0 == high); - Some(input.ok_or("a root descriptor without its high half")?.1) + if param_dword != 0 { + return Err("a root descriptor without its low half"); + } + matches_high_dword(1)? + } + // Ray-tracing builders and compute shaders can pass 64-bit GPU + // virtual addresses in adjacent 32-bit root constants + // (`dword` = lo, `dword + 1` = hi). + RootType::Constants => { + let Some(hi_dword) = param_dword.checked_add(1) else { + return Err("an address from a root parameter that is no address"); + }; + if hi_dword >= self.layout[param].sgprs { + return Err("an address from a root parameter that is no address"); + } + matches_high_dword(hi_dword)? } _ => return Err("an address from a root parameter that is no address"), }; - // shortcut: with a computed term, a high half that adds anything to the - // base's is taken as the carry of that term (offsets below 4 GB). - let dynamic = s.dynamic.or(extra.dynamic); - if !self.high_half(hi, high) - && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h))) - { + if !high_ok { return Err("an address with an untracked high half"); } Ok(Address { param, - offset: s.offset.wrapping_add(extra.offset), - dynamic: s.dynamic.or(extra.dynamic), + param_dword, + offset: byte_offset, + dynamic, + rel, }) } - /// `hi` is `high` (0 for a table), possibly plus a carry. + /// Strips VA-preserving masks (`s_and_b32`/`v_and_b32` preserving at least + /// the low byte of the high VA dword, or `s_bfe_u32`) and plain copies. + fn strip_va_mask(&self, mut t: Term) -> Term { + for _ in 0..8 { + let Term::Value(v) = t else { break }; + if let Some((_, [a, Term::Const(m)] | [Term::Const(m), a])) = + self.sop2(v, &["s_and_b32"]) + && m & 0xFF == 0xFF + { + t = a; + continue; + } + if let Some((_, [a, Term::Const(_)])) = self.sop2(v, &["s_bfe_u32"]) { + t = a; + continue; + } + if let Some(inst) = self.def(v) + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + { + if matches!( + inst.name(), + "v_mov_b32" | "v_readfirstlane_b32" | "v_readlane_b32" + ) && let Some(a) = f.src.first().and_then(|o| self.vterm(inst, o)) + { + t = a; + continue; + } + if inst.name() == "v_and_b32" + && let (Some(a), Some(b)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + ) + { + match (a, b) { + (x, Term::Const(m)) | (Term::Const(m), x) if m & 0xFF == 0xFF => { + t = x; + continue; + } + _ => {} + } + } + } + break; + } + t + } + + /// `hi` is `high` (0 for a table), possibly plus a carry or joined by phi. fn high_half(&self, hi: Term, high: Option) -> bool { let want = high.map_or(Term::Const(0), Term::Value); - hi == want - || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( - |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) - )) + self.high_half_inner(hi, want, &mut Vec::new()) } - /// `hi` adds something (with carry) to `high`: `s_addc_u32` or - /// `v_add_co_ci_u32` with `high` as an operand. - fn carried(&self, hi: Term, high: Value) -> bool { + fn high_half_inner(&self, hi: Term, want: Term, visiting: &mut Vec) -> bool { + let hi = self.strip_va_mask(hi); + if hi == want { + return true; + } let Term::Value(v) = hi else { return false }; - if v == high { + if visiting.contains(&v) { return true; } - if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { - return self.carried(a, high) || self.carried(b, high); + if let Some((b, pi)) = self.phis[v.0 as usize] { + visiting.push(v); + let mut non_cyclic = 0usize; + let mut ok = true; + for &arg in &self.p.blocks[b].phis[pi].args { + let a = self.strip_va_mask(self.origin(arg)); + if let Term::Value(av) = a + && visiting.contains(&av) + { + continue; + } + non_cyclic += 1; + if !self.high_half_inner(a, want, visiting) { + ok = false; + break; + } + } + visiting.pop(); + return ok && non_cyclic > 0; } - let Some(inst) = self.def(v) else { - return false; - }; - let Fields::Valu(f) = &inst.fields else { - return false; + visiting.push(v); + let ok = if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + (self.high_half_inner(a, want, visiting) && b == Term::Const(0)) + || (self.high_half_inner(b, want, visiting) && a == Term::Const(0)) + } else if let Some(inst) = self.def(v) + && let Fields::Valu(f) = &inst.fields + && inst.name() == "v_add_co_ci_u32" + && let (Some(a), Some(b)) = ( + f.src.first().and_then(|o| self.vterm(inst, o)), + f.src.get(1).and_then(|o| self.vterm(inst, o)), + ) + { + (self.high_half_inner(a, want, visiting) && b == Term::Const(0)) + || (self.high_half_inner(b, want, visiting) && a == Term::Const(0)) + } else { + false }; - inst.name() == "v_add_co_ci_u32" - && f.src[..2.min(f.src.len())] + visiting.pop(); + ok + } + + /// `hi` adds something (with carry) to `want`: `s_addc_u32`, + /// `v_add_co_ci_u32`, or a phi over such values. + fn carried(&self, hi: Term, want: Term) -> bool { + self.carried_inner(hi, want, &mut Vec::new()) + } + + fn carried_inner(&self, hi: Term, want: Term, visiting: &mut Vec) -> bool { + let hi = self.strip_va_mask(hi); + if hi == want { + return true; + } + let Term::Value(v) = hi else { return false }; + if visiting.contains(&v) { + return true; + } + if let Some((b, pi)) = self.phis[v.0 as usize] { + visiting.push(v); + let mut non_cyclic = 0usize; + let mut ok = true; + for &arg in &self.p.blocks[b].phis[pi].args { + let a = self.strip_va_mask(self.origin(arg)); + if let Term::Value(av) = a + && visiting.contains(&av) + { + continue; + } + non_cyclic += 1; + if !self.carried_inner(a, want, visiting) { + ok = false; + break; + } + } + visiting.pop(); + return ok && non_cyclic > 0; + } + visiting.push(v); + let ok = if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + self.carried_inner(a, want, visiting) || self.carried_inner(b, want, visiting) + } else if let Some(inst) = self.def(v) + && let Fields::Valu(f) = &inst.fields + && inst.name() == "v_add_co_ci_u32" + { + f.src[..2.min(f.src.len())] .iter() - .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high))) + .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried_inner(t, want, visiting))) + } else { + false + }; + visiting.pop(); + ok } fn why_no_base(&self, dynamic: Option) -> &'static str { @@ -664,15 +1364,7 @@ impl<'a> Tracer<'a> { { (hi, bits) = (x, bits | more); } - let address = self.address( - lo, - hi, - Sum { - base: None, - offset: 0, - dynamic: None, - }, - )?; + let address = self.address(lo, hi, Sum::plain(0))?; return Ok(Source::Built { address, bits, @@ -728,13 +1420,20 @@ impl<'a> Tracer<'a> { Ok(Some(Source::Phi { block, args: args? })) } - /// `v` as some other dword with constant bits set. + /// `v` as some other dword with constant bits set (or VA-preserving high + /// mask applied). fn set_bits(&self, v: Value) -> Option<(Term, u32)> { if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) = self.sop2(v, &["s_or_b32"]) { return Some((x, bits)); } + if let Some((_, [x, Term::Const(mask)] | [Term::Const(mask), x])) = + self.sop2(v, &["s_and_b32"]) + && mask & 0xFF == 0xFF + { + return Some((x, 0)); + } let inst = self.def(v)?; let Fields::Sop { dst: Some(Operand::Scalar { code, .. }), @@ -758,6 +1457,9 @@ impl<'a> Tracer<'a> { return None; }; let load = self.defs[v0.0 as usize]?; + if self.spill_loads.contains(&load) { + return None; + } let inst = self.inst(load); if !inst.name().starts_with("s_load_") { return None; @@ -931,8 +1633,10 @@ mod tests { fn at(param: usize, offset: u32) -> Address { Address { param, + param_dword: 0, offset, dynamic: None, + rel: None, } } @@ -1113,4 +1817,85 @@ mod tests { } ); } + + #[test] + fn spill_table_loads_map_to_root_parameters_and_addresses() { + // Compute shader whose root layout starts at user_data 16 (spilled), + // with s[0:1] holding the spill-table pointer (high dword masked to + // 40 bits via s_and_b32 s1, s1, 0xff). + let r = track_words( + &[ + 0x8701_FF01, + 0x0000_00FF, // s_and_b32 s1, s1, 0xff + 0xF408_0100, + 0xFA00_0000, // s_load_dwordx4 s[4:7], s[0:1], null (ud 16..20) + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0206, // v_mov_b32 v1, s6 (root constant from ud 18) + 0xDC70_8000, + 0x0004_0100, // global_store_dword v0, v1, s[4:5] (root desc at ud 16..18) + S_ENDPGM, + ], + &[param(Descriptor, 16, 2), param(Constants, 18, 2)], + HwStage::Cs, + ); + assert_eq!(r.spill_loads, [(0, 1)]); + assert_eq!(r.scalar, [((0, 4), at(0, 0))]); + assert!(r.params.iter().any(|&(_, p, d)| p == 0 && d == 0)); + assert!(r.params.iter().any(|&(_, p, d)| p == 0 && d == 1)); + assert!(r.params.iter().any(|&(_, p, d)| p == 1 && d == 0)); + assert!(r.params.iter().any(|&(_, p, d)| p == 1 && d == 1)); + } + + #[test] + fn root_constant_dword0_does_not_collide_with_pointer_base() { + // s[0:1] = RootType::Descriptor, s2 = RootType::Constants dword 0. + // s4 = s0 + s2; s5 = s1 + carry; s_load_dword s6, s[4:5], 0 + let r = track_words( + &[ + 0x8004_0200, // s_add_u32 s4, s0, s2 + 0x8205_8001, // s_addc_u32 s5, s1, 0 + 0xF400_0182, + 0xFA00_0000, // s_load_dword s6, s[4:5], 0 + S_ENDPGM, + ], + &[param(Descriptor, 0, 2), param(Constants, 2, 1)], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + assert_eq!(r.scalar[0].1.param, 0); + assert!(r.scalar[0].1.dynamic.is_some()); + } + + #[test] + fn scaled_multi_term_address_uses_rel_offset() { + // s[0:1] = RootType::Descriptor, s2..s3 = RootType::Constants. + // s4 = (s3 << 2) + s0; s4 = s4 + s2; s5 = s1 + carry; s_load_dword s6, s[4:5], 0x10 + let r = track_words( + &[ + 0x9784_0003, // s_lshl2_add_u32 s4, s3, s0 + 0x8004_0204, // s_add_u32 s4, s4, s2 + 0x8205_8001, // s_addc_u32 s5, s1, 0 + 0xF400_0182, + 0xFA00_0010, // s_load_dword s6, s[4:5], 0x10 + S_ENDPGM, + ], + &[param(Descriptor, 0, 2), param(Constants, 2, 2)], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + assert_eq!(r.scalar[0].1.param, 0); + assert_eq!(r.scalar[0].1.offset, 0x10); + assert!(r.scalar[0].1.rel.is_some()); + } +} + +fn smem_load_dwords(name: &str) -> Option { + match name.strip_prefix("s_load_dword")? { + "" => Some(1), + "x2" => Some(2), + "x4" => Some(4), + "x8" => Some(8), + "x16" => Some(16), + _ => None, + } }