From 0e48b1d10209408b8a561ce87a0ce16e53296ab7 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 13:58:16 +0000 Subject: [PATCH 1/4] gpu: hold incomplete or Wave32 BVH builder dispatches atomically --- apps/victory/src/run.rs | 14 +- crates/victory-gpu/src/draw.rs | 13 + crates/victory-gpu/src/pipeline.rs | 111 ++++++-- crates/victory-gpu/src/pipeline/builder.rs | 254 ++++++++++++++++++ crates/victory-gpu/src/pipeline/make.rs | 43 ++- .../src/pipeline/placed_uav_tests.rs | 8 +- 6 files changed, 417 insertions(+), 26 deletions(-) create mode 100644 crates/victory-gpu/src/pipeline/builder.rs diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 25661c7b..af5ba7e7 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -77,7 +77,10 @@ pub fn run( } // Rosetta cannot resume these when they fault partway (#14, #50). let masked = victory_loader::masked::masked_stores(&prepared.info, &original); - println!("masked stores {}", victory_loader::masked::summary(&masked)); + println!( + "masked stores {}", + victory_loader::masked::summary(&masked) + ); // Under Rosetta, tracking is off unless asked for, and the stores it // cannot resume are patched when it is on (`victory_gpu::fault_tracking`). println!( @@ -102,7 +105,8 @@ pub fn run( && requested.is_none() && hash.as_str() == "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93" { - requested = Some("all,1e09b31,1e09b37,259509f,25950a5,1e759f0,1e759f7,1e759fe,1e75a05".into()); + requested = + Some("all,1e09b31,1e09b37,259509f,25950a5,1e759f0,1e759f7,1e759fe,1e75a05".into()); } let patching = victory_loader::masked::choice(requested, needs_patch); let original = patching.is_some().then_some(original); @@ -214,6 +218,7 @@ pub fn run( for (name, dll) in &dlls { println!("title dll {name} at {:#x}", dll.base()); victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); + victory_gpu::pipeline::note_title_dll(name, dll.base(), dll.info().size_of_image as usize); } let imported: Vec<&str> = image .info() @@ -504,6 +509,11 @@ impl LateDlls { ); show(name, dll.bind_imports(&resolver, self.policy)?); set_image_path(dll.base(), &self.title_dir.join(name)); + victory_gpu::pipeline::note_title_dll( + name, + dll.base(), + dll.info().size_of_image as usize, + ); } // Visible before their `DllMain`s run, which may load more. mapped.extend(new.iter().cloned()); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e774813a..92f9d8c7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1168,6 +1168,15 @@ impl State { dropped(list, self.pipeline, "dispatch"); return; } + // The acceleration-structure builder runs whole or not at all + // (`pipeline::builder`). + if crate::pipeline::held_back(self.pipeline as This) { + once!("a dispatch of the BVH builder held back"); + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(list, self.pipeline, "dispatch"); + return; + } let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { once!( pipeline = format_args!("{:#x}", self.pipeline), @@ -1800,6 +1809,10 @@ impl State { // the arguments and dispatch a compute shader for records nothing // reads. Same order as the `is_skipped` check above, for the same // reason. + if crate::pipeline::held_back(self.pipeline as This) { + why("the BVH builder held back"); + return false; + } if crate::pipeline::host_pipeline(self.pipeline as This).is_none() { #[cfg(feature = "diagnostics")] crate::pipeline::note_drop(self.pipeline as This); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7e877964..eeff0a11 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -282,7 +282,10 @@ impl Shader { fn thread_cpu() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut t = [FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; 4]; + let mut t = [FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; 4]; let [created, exited, kernel, user] = &mut t; // SAFETY: four times of our own thread into our own variables. unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; @@ -303,7 +306,10 @@ fn thread_cpu_since(then: (u64, u64)) -> (u64, u64) { #[cfg(windows)] fn translate(container: &[u8]) -> (Result, bool) { let (host, cached) = crate::shader_cache::host_shader(container); - (host.and_then(|host| with_resources(container, host)), cached) + ( + host.and_then(|host| with_resources(container, host)), + cached, + ) } #[cfg(windows)] @@ -473,6 +479,10 @@ struct Pipeline { /// (by a worker: the title may release the pipeline meanwhile). #[cfg(windows)] host: Arc, + /// Whether it is one of the title's acceleration-structure builder's + /// ([`builder`]). + #[cfg(windows)] + builder: bool, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); @@ -511,6 +521,31 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// Whether a dispatch with the title pipeline is held back: it is the +/// acceleration-structure builder's, which does not run this frame +/// ([`builder::runs`]). +#[cfg(windows)] +pub(crate) fn held_back(this: This) -> bool { + !this.is_null() && pipeline(this).builder && !builder::runs() +} + +/// Whether the title's acceleration-structure builder runs this frame. +#[cfg(windows)] +#[allow(dead_code)] +pub(crate) fn builder_runs() -> bool { + builder::runs() +} + +/// A title DLL was mapped at `base`, `size` bytes (the acceleration- +/// structure builder's pipelines are known by its image). +#[cfg(windows)] +pub fn note_title_dll(file: &str, base: usize, size: usize) { + builder::note_title_dll(file, base, size); +} + +#[cfg(not(windows))] +pub fn note_title_dll(_file: &str, _base: usize, _size: usize) {} + /// Host pipelines queued and not made yet. #[cfg(windows)] pub(crate) fn making() -> u64 { @@ -629,14 +664,21 @@ fn code_of(code: &Bytecode) -> Option<*const [u8]> { .then(|| std::ptr::slice_from_raw_parts(code.code, code.size)) } +/// `code`: the title's bytecode pointers (by which a pipeline of the +/// acceleration-structure builder is known, [`builder`]). fn hand_out( shaders: Vec>, #[cfg(windows)] graphics: Option>, + code: &[*const u8], iid: *const Iid, out: *mut This, ) -> HRESULT { tracing::trace!(?shaders, "pipeline state"); #[cfg(windows)] + let builder = !code.is_empty() && builder::created_by_builder(code); + #[cfg(not(windows))] + let _ = code; + #[cfg(windows)] let host = Arc::new(make::Pending::new( shaders.clone(), graphics, @@ -645,11 +687,17 @@ fn hand_out( )); #[cfg(windows)] make::early(&host); + #[cfg(windows)] + if builder { + builder::note(&host); + } let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], #[cfg(windows)] host, + #[cfg(windows)] + builder, shaders, bound: std::sync::atomic::AtomicBool::new(false), }); @@ -673,6 +721,7 @@ pub(crate) extern "system" fn create_graphics( shaders, #[cfg(windows)] None, + &[], iid, out, ) @@ -693,6 +742,7 @@ pub(crate) extern "system" fn create_compute( copy("compute", &desc.stage).into_iter().collect(), #[cfg(windows)] None, + &[desc.stage.code], iid, out, ) @@ -772,6 +822,7 @@ pub(crate) extern "system" fn create_stream( shaders, #[cfg(windows)] Some(Box::new(graphics)), + &[], iid, out, ) @@ -809,7 +860,13 @@ fn read_stream( if let Some(stage) = stage { // SAFETY: a shader subobject has its bytecode at +8, which the // slice does not promise to be aligned. - let code = unsafe { stream.as_ptr().add(at + 8).cast::().read_unaligned() }; + let code = unsafe { + stream + .as_ptr() + .add(at + 8) + .cast::() + .read_unaligned() + }; shaders.extend(shader(stage, &code)); } #[cfg(windows)] @@ -839,6 +896,8 @@ static FUNCTIONS: Table<24> = { Table(f) }; +#[cfg(windows)] +mod builder; #[cfg(windows)] pub(crate) mod host; #[cfg(windows)] @@ -917,7 +976,11 @@ impl Prebuild { /// Its shaders and state as a diagnostics build logs them. pub fn describe(&self) -> String { - let state = self.graphics.as_ref().map(|g| g.describe()).unwrap_or_default(); + let state = self + .graphics + .as_ref() + .map(|g| g.describe()) + .unwrap_or_default(); format!("{:?}\t{state}", self.shaders) } @@ -942,10 +1005,12 @@ impl Prebuild { library::save(false); match made { Some(_) => Ok(()), - None => Err(match self.shaders.iter().find(|s| s.translated().is_none()) { - Some(s) => format!("{} shader does not translate", s.stage), - None => "the host refuses it".into(), - }), + None => Err( + match self.shaders.iter().find(|s| s.translated().is_none()) { + Some(s) => format!("{} shader does not translate", s.stage), + None => "the host refuses it".into(), + }, + ), } } } @@ -991,14 +1056,16 @@ mod tests { fn a_stream_of_any_alignment_is_read() { let mut backing = [0u64; 5]; // SAFETY: the 40 bytes of `backing`, one off its (aligned) start. - let stream = unsafe { std::slice::from_raw_parts_mut(backing.as_mut_ptr().cast::().add(1), 32) }; + let stream = + unsafe { std::slice::from_raw_parts_mut(backing.as_mut_ptr().cast::().add(1), 32) }; stream[..4].copy_from_slice(&1u32.to_le_bytes()); // vertex shader stream[8..16].copy_from_slice(&0x1000usize.to_le_bytes()); stream[16..24].copy_from_slice(&7usize.to_le_bytes()); assert_ne!(stream.as_ptr() as usize % 8, 0); let seen = std::cell::RefCell::new(Vec::new()); read_stream(stream, |stage, code| { - seen.borrow_mut().push((stage, code.code as usize, code.size)); + seen.borrow_mut() + .push((stage, code.code as usize, code.size)); None }); assert_eq!(*seen.borrow(), [("vertex", 0x1000, 7)]); @@ -1016,7 +1083,10 @@ mod tests { spill_to(dir.path(), &s, &full); assert!(s.container.lock().unwrap().is_empty(), "left memory"); assert_eq!(s.spilled.get(), Some(&full)); - assert_eq!(crate::read_file(&spill_path(dir.path(), &full)).unwrap(), bytes); + assert_eq!( + crate::read_file(&spill_path(dir.path(), &full)).unwrap(), + bytes + ); let again = Shader::new("pixel", &bytes); spill_to(dir.path(), &again, &full); assert!(again.container.lock().unwrap().is_empty() && again.spilled.get() == Some(&full)); @@ -1150,10 +1220,16 @@ mod tests { element[8 + 4 * i..12 + 4 * i].copy_from_slice(&w.to_le_bytes()); } let mut stream = vec![0u8; 0x2b0]; - let put = |s: &mut Vec, at: usize, v: u64| { - s[at..at + 8].copy_from_slice(&v.to_le_bytes()) - }; - let kinds = [(0x10, 1), (0x28, 2), (0x40, 3), (0x58, 4), (0x70, 5), (0x88, 8)]; + let put = + |s: &mut Vec, at: usize, v: u64| s[at..at + 8].copy_from_slice(&v.to_le_bytes()); + let kinds = [ + (0x10, 1), + (0x28, 2), + (0x40, 3), + (0x58, 4), + (0x70, 5), + (0x88, 8), + ]; for (at, kind) in kinds.into_iter().chain([(0x210, 21), (0x250, 17)]) { put(&mut stream, at, kind); } @@ -1177,7 +1253,10 @@ mod tests { stream: stream.as_ptr(), }; let mut p = std::ptr::null(); - assert_eq!(create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), S_OK); + assert_eq!( + create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), + S_OK + ); // SAFETY: the stream points at live code and elements. let pre = unsafe { Prebuild::graphics(&stream) }; let title = pipeline(p); diff --git a/crates/victory-gpu/src/pipeline/builder.rs b/crates/victory-gpu/src/pipeline/builder.rs new file mode 100644 index 00000000..4c2dabe4 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/builder.rs @@ -0,0 +1,254 @@ +//! The title's acceleration-structure builder runs whole or not at all. +//! +//! `XboxBvhBuilder.dll` builds and refits the ray-tracing structures in +//! title memory every frame through some fifty compute programs, one +//! dispatch after another. A dispatch whose host pipeline is missing is +//! dropped on its own (`State::dispatch`), and some of the builder's are +//! missing while pipelines are still being made; on a host of 32-lane waves +//! (`Host::wave32`), its 64-lane programs exchange across halves and hung +//! Wave32 GPUs (`Marvisak/VIctory#2711`). So the builder's dispatches run +//! only in frames where every pipeline it has created has its host pipeline +//! and either the host runs 64-lane waves whole or `VICTORY_BVH_BUILDER=1` +//! opts in; otherwise none of them run (the structures keep what they held). +//! +//! Its pipelines are known by where they come from: created by its code (a +//! return address in its image on the stack) or from bytecode in its image. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, Weak}; + +use super::make::{self, Pending}; + +/// The builder's image, `[start, end)`, once mapped. +static IMAGE: Mutex> = Mutex::new(None); + +/// The builder's file name. +const FILE: &str = "XboxBvhBuilder.dll"; + +/// A title DLL was mapped at `base`, `size` bytes: noted if it is the +/// builder. +pub fn note_title_dll(file: &str, base: usize, size: usize) { + if file.eq_ignore_ascii_case(FILE) { + tracing::info!(base = format_args!("{base:#x}"), size, "BVH builder mapped"); + *IMAGE.lock().unwrap_or_else(|e| e.into_inner()) = Some((base, base + size)); + } +} + +fn image() -> Option<(usize, usize)> { + *IMAGE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether the pipeline being created is the builder's: `code` (the title's +/// bytecode pointers) lies in its image, or its code is among our callers. +#[inline(never)] +pub(crate) fn created_by_builder(code: &[*const u8]) -> bool { + let Some((start, end)) = image() else { + return false; + }; + let inside = |a: usize| (start..end).contains(&a); + if code.iter().any(|&c| inside(c as usize)) { + return true; + } + callers().into_iter().any(inside) +} + +/// Return addresses on the stack, ours first. +fn callers() -> Vec { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let mut frames = [std::ptr::null_mut(); 24]; + // SAFETY: room for that many frames. + let n = unsafe { + RtlCaptureStackBackTrace( + 1, + frames.len() as u32, + frames.as_mut_ptr(), + std::ptr::null_mut(), + ) + }; + frames[..usize::from(n)] + .iter() + .map(|&f| f as usize) + .collect() +} + +/// The builder's pipelines (alive while the title holds them). +static PIPELINES: Mutex>> = Mutex::new(Vec::new()); + +/// The builder created pipeline `p`: it counts towards [`runs`], and is +/// made at once (no frame's wait budget holds it back). +pub(crate) fn note(p: &Arc) { + PIPELINES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arc::downgrade(p)); + make::begin(p); +} + +/// The frame [`runs`] last decided for, and its decision. +static DECIDED: Mutex<(u64, bool)> = Mutex::new((u64::MAX, true)); + +/// Whether `VICTORY_BVH_BUILDER=1` opts in to running the builder on 32-lane +/// wave hosts. +fn allow_halves() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_BVH_BUILDER")) +} + +/// Whether the builder's dispatches run in the current frame: decided once +/// per frame, so that a frame never runs part of the builder. +pub(crate) fn runs() -> bool { + static SAID: AtomicBool = AtomicBool::new(false); + let frame = crate::frame::current(); + let mut decided = DECIDED.lock().unwrap_or_else(|e| e.into_inner()); + if decided.0 == frame { + return decided.1; + } + let states: Vec> = { + let mut pipelines = PIPELINES.lock().unwrap_or_else(|e| e.into_inner()); + pipelines.retain(|p| p.strong_count() > 0); + pipelines + .iter() + .filter_map(Weak::upgrade) + .map(|p| make::state(&p)) + .collect() + }; + let halves = crate::host::host().is_some_and(crate::host::Host::wave32); + let open = opens(&states, halves, allow_halves()); + if open != decided.1 || !SAID.swap(true, Ordering::Relaxed) { + let (made, refused) = ( + states.iter().filter(|s| **s == Some(true)).count(), + states.iter().filter(|s| **s == Some(false)).count(), + ); + tracing::info!( + frame, + pipelines = states.len(), + made, + refused, + "BVH builder {}", + if open { + "runs" + } else if halves && !allow_halves() { + "held back: 64-lane programs run as 32-lane halves here (VICTORY_BVH_BUILDER=1 overrides)" + } else { + "held back: not all its pipelines are made" + } + ); + } + *decided = (frame, open); + open +} + +/// Whether every pipeline is made (`Some(true)`); refused ones are +/// `Some(false)`, those still being made `None`. +fn all_made(states: &[Option]) -> bool { + states.iter().all(|s| *s == Some(true)) +} + +/// Whether the builder runs: every pipeline made, and either 64-lane waves +/// run whole or `VICTORY_BVH_BUILDER=1` opts in (`allow_halves`). +fn opens(states: &[Option], halves: bool, allow_halves: bool) -> bool { + (!halves || allow_halves) && all_made(states) +} + +/// Tests that set the builder's image, one at a time; each starts with +/// no decision made. +#[cfg(test)] +pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + *DECIDED.lock().unwrap_or_else(|e| e.into_inner()) = (u64::MAX, true); + guard +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + use crate::pipeline::{ + Bytecode, ComputeHead, PIPELINE_IIDS, This, builder_runs, create_compute, held_back, + pipeline, + }; + + #[test] + fn the_builder_runs_only_with_every_pipeline_made() { + assert!(all_made(&[]), "no builder: nothing to hold back"); + assert!(all_made(&[Some(true), Some(true)])); + assert!(!all_made(&[Some(true), Some(false)]), "one refused"); + assert!(!all_made(&[Some(true), None]), "one still being made"); + assert!(opens(&[Some(true)], false, false)); + assert!( + !opens(&[Some(true)], true, false), + "64-lane programs run as halves" + ); + assert!( + opens(&[Some(true)], true, true), + "VICTORY_BVH_BUILDER=1 override" + ); + assert!( + !opens(&[Some(false)], true, true), + "override still requires all made" + ); + assert!(!opens(&[], true, false)); + } + + #[test] + fn builder_pipelines_are_known_by_their_origin() { + let _one = test_lock(); + let here = builder_pipelines_are_known_by_their_origin as *const () as usize; + let elsewhere = [0x7_0000_0000usize as *const u8]; + *IMAGE.lock().unwrap() = None; + assert!(!created_by_builder(&elsewhere), "no builder mapped"); + *IMAGE.lock().unwrap() = Some((0x7_0000_0000, 0x7_0001_0000)); + assert!(created_by_builder(&elsewhere)); + assert!(!created_by_builder(&[0x8_0000_0000usize as *const u8])); + *IMAGE.lock().unwrap() = Some((here - 0x10_0000, here + 0x10_0000)); + assert!(created_by_builder(&[])); + *IMAGE.lock().unwrap() = None; + } + + #[test] + fn builder_dispatches_wait_for_every_builder_pipeline() { + let _one = test_lock(); + let code = [0xB0u8; 64]; + let create = |code: &[u8]| { + let desc = ComputeHead { + root: std::ptr::null(), + stage: Bytecode { + code: code.as_ptr(), + size: code.len(), + }, + }; + let mut p: This = std::ptr::null(); + assert_eq!( + create_compute(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), + S_OK + ); + p + }; + note_title_dll("xboxbvhbuilder.DLL", code.as_ptr() as usize, code.len()); + let p = create(&code); + let other_code = [0xC0u8; 64]; + let other = create(&other_code); + note_title_dll("XboxBvhBuilder.dll", 0, 0); + assert!( + pipeline(p).builder, + "its bytecode is in the builder's image" + ); + assert!(!pipeline(other).builder); + let refused = (0..500).any(|_| { + std::thread::sleep(std::time::Duration::from_millis(10)); + make::state(&pipeline(p).host).is_some() + }); + assert!(refused, "the builder's pipeline was started"); + assert_eq!(make::state(&pipeline(p).host), Some(false)); + assert!(!builder_runs()); + assert!( + held_back(p), + "one builder pipeline missing: the builder waits" + ); + assert!(!held_back(other)); + for q in [p, other] { + slot:: u32>(q, 0x10)(q); + } + } +} diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 004ba3f2..f4c50c81 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -114,7 +114,12 @@ pub(crate) fn key(shaders: &[Arc], graphics: Option<&GraphicsState>) -> key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update(graphics.map(|g| g.describe()).unwrap_or_default().as_bytes()); + key.update( + graphics + .map(|g| g.describe()) + .unwrap_or_default() + .as_bytes(), + ); key.finalize().to_hex()[..32].to_owned() } @@ -146,7 +151,9 @@ pub(crate) fn missing(p: &Pending) -> Option { #[cfg(feature = "diagnostics")] pub(crate) fn log_built(key: &str) { if let Some((name, loaded)) = super::library::LAST.take() { - log("built", key, || format!("{name}\t{}", if loaded { "loaded" } else { "made" })); + log("built", key, || { + format!("{name}\t{}", if loaded { "loaded" } else { "made" }) + }); } } @@ -166,9 +173,13 @@ fn log(what: &str, key: &str, rest: impl FnOnce() -> String) { }; let mut log = LOG.lock().unwrap_or_else(|e| e.into_inner()); if log.is_none() { - *log = std::fs::File::create(path).ok().map(|f| (f, HashSet::new())); + *log = std::fs::File::create(path) + .ok() + .map(|f| (f, HashSet::new())); } - let Some((file, seen)) = log.as_mut() else { return }; + let Some((file, seen)) = log.as_mut() else { + return; + }; if seen.insert(format!("{what} {key}")) { let _ = writeln!(file, "{what}\t{key}\t{}", rest()); } @@ -205,6 +216,19 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { p.made.get()?.as_ref() } +/// Starts making `p` now, without waiting for it. +pub(crate) fn begin(p: &Arc) { + if !p.shaders.is_empty() { + start(p, false); + } +} + +/// Whether `p`'s host pipeline is made (`Some(true)`), refused or not +/// translated (`Some(false)`), or not yet (`None`); never waits. +pub(crate) fn state(p: &Pending) -> Option { + p.made.get().map(Option::is_some) +} + /// Queues `p` for the workers: once, and once more ahead of the early /// starts if a draw waits for it (`now`) while it is still queued. fn start(p: &Arc, now: bool) { @@ -217,7 +241,10 @@ fn start(p: &Arc, now: bool) { fn enqueue(p: &Pending, now: bool) -> Option { let first = !p.queued.swap(true, Ordering::Relaxed); if first { - PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + PEAK.fetch_max( + WAITING.fetch_add(1, Ordering::Relaxed) + 1, + Ordering::Relaxed, + ); } let ahead = now && !p.now.swap(true, Ordering::Relaxed); (first || ahead && !p.taken.load(Ordering::Relaxed)).then_some(ahead) @@ -259,8 +286,10 @@ fn wait(p: &Pending, frame: u64) { /// Pipelines for the workers: those draws wait for, then those started /// early. -static QUEUES: (Mutex<[VecDeque>; 2]>, Condvar) = - (Mutex::new([VecDeque::new(), VecDeque::new()]), Condvar::new()); +static QUEUES: (Mutex<[VecDeque>; 2]>, Condvar) = ( + Mutex::new([VecDeque::new(), VecDeque::new()]), + Condvar::new(), +); /// Hands `p` to the workers (half the logical processors, 2 to 8), started /// on first use. diff --git a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs index 5a900378..9ca2599d 100644 --- a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs +++ b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs @@ -124,7 +124,13 @@ fn placed_uav_dispatch_writes_its_texture() { let mut pipeline = std::ptr::null(); assert_eq!( - hand_out(vec![store_shader()], None, &PIPELINE_IIDS[0], &mut pipeline), + hand_out( + vec![store_shader()], + None, + &[], + &PIPELINE_IIDS[0], + &mut pipeline + ), S_OK ); let pipeline = Guest(pipeline); From a2aa0d246bfa73c6d53807f3655b46ef7bc06d00 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 09:53:30 +0000 Subject: [PATCH 2/4] gpu: copy card-written texture aliases, add RTV format variants, and add opt-in ambient passes --- crates/victory-gpu/src/ambient.rs | 619 ++++++++++++++++++ crates/victory-gpu/src/compute.rs | 26 +- crates/victory-gpu/src/draw.rs | 132 +++- crates/victory-gpu/src/host.rs | 12 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline.rs | 26 +- crates/victory-gpu/src/pipeline/host.rs | 162 +++++ crates/victory-gpu/src/pipeline/make.rs | 91 ++- .../src/pipeline/placed_uav_tests.rs | 2 + crates/victory-gpu/src/resource.rs | 183 ++++++ crates/victory-gpu/src/texture.rs | 31 +- 11 files changed, 1262 insertions(+), 24 deletions(-) create mode 100644 crates/victory-gpu/src/ambient.rs diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs new file mode 100644 index 00000000..a6c2dc1d --- /dev/null +++ b/crates/victory-gpu/src/ambient.rs @@ -0,0 +1,619 @@ +//! Opt-in stand-in for the indirect light the title traces rays for. +//! +//! With the ray-tracing structure builder held back +//! (`!crate::pipeline::builder_runs()`), the title's probe rays find nothing: +//! `CS_ScreenProbes_TemporalResolve_*` leaves sky light outdoors, dark +//! silhouettes indoors where no direct lamp or sun reaches, and unoccluded sky +//! inscattering inside rooms (`CS_AccumulateLocalLightInscatteringVolume_*`). +//! +//! Adapted from `archive-cool-fox` (`82ca1347`, `7da523a9`, after beloooo's +//! `VIctory-Belobug-AMD`) to compile cleanly through Wine's `vkd3d-shader` +//! (`crate::compute`, explicit serialized root signature, `ByteAddressBuffer` +//! loads + `RWByteAddressBuffer` stores): +//! +//! * `VICTORY_AMBIENT`: +//! - unset or `0`/`off` (default): disabled; the title's own output is kept. +//! - `` (e.g. `0.8` or `1.0`): screen-space bounce-light estimate +//! from `CS_CacheScreenSpaceRadiance` averaged over 64x36 cells with slow +//! temporal adaptation and first-order directional harmonics at 160x90 +//! points interpolated by depth. +//! - `constant:`: constant ambient fill with screen-space crease AO. +//! * `VICTORY_AMBIENT_SHADE=,`: crease occlusion parameters +//! (defaults `1.0,0.6`). +//! * `VICTORY_AMBIENT_AIR=`: caps local-light air-scattering luma in +//! `CS_AccumulateLocalLightInscatteringVolume` by `` of the room +//! and view-direction surface luma (unset or `0`: disabled). + +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::core::s; + +use crate::compute::{Param, pipeline_with_root, root_signature, srv, uav}; +use crate::host::{HostList, host}; + +/// Programs of the title the stand-in follows. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + /// Resolves the diffuse light (`CS_ScreenProbes_TemporalResolve_*`). + Resolve, + /// Keeps the light visible surfaces send out (`CS_CacheScreenSpaceRadiance_*`). + Radiance, + /// Accumulates local-light inscattering (`CS_AccumulateLocalLightInscatteringVolume_*`). + Air, +} + +/// The program's part in this, by its debug name in the container. +pub(crate) fn role(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"CS_ScreenProbes_TemporalResolve") { + Some(Role::Resolve) + } else if has(b"CS_CacheScreenSpaceRadiance") { + Some(Role::Radiance) + } else if has(b"CS_AccumulateLocalLightInscatteringVolume") { + Some(Role::Air) + } else { + None + } +} + +/// Root parameter and table offset in dwords for each bound resource. +pub(crate) const LIGHT: (u8, u32) = (1, 176); +pub(crate) const DEPTH: (u8, u32) = (0, 464); +pub(crate) const RADIANCE: (u8, u32) = (1, 16); +pub(crate) const AIR: (u8, u32) = (1, 32); + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Set { + Off, + Estimate(f32), + Constant(f32), +} + +fn parse(set: &str) -> Set { + let set = set.trim(); + if matches!(set, "" | "0" | "off" | "false") { + return Set::Off; + } + let number = |t: &str| { + t.trim() + .parse::() + .ok() + .filter(|v| v.is_finite() && *v > 0.0) + }; + match set.strip_prefix("constant:") { + Some(level) => number(level).map_or(Set::Off, Set::Constant), + None => number(set).map_or(Set::Off, Set::Estimate), + } +} + +fn set() -> Set { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| parse(&std::env::var("VICTORY_AMBIENT").unwrap_or_default())) +} + +/// Whether the stand-in is active: enabled via `VICTORY_AMBIENT`, and the +/// title's BVH builder is held back. +pub(crate) fn on() -> bool { + set() != Set::Off && !crate::pipeline::builder_runs() +} + +/// Maximum air-scattering luma multiple (`VICTORY_AMBIENT_AIR=`). +fn air() -> f32 { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_AIR").unwrap_or_default(); + set.trim() + .parse() + .ok() + .filter(|v: &f32| v.is_finite() && *v > 0.0) + .unwrap_or(0.0) + }) +} + +/// Strength and radius (in metres) of screen-space crease shading. +fn shade() -> [f32; 2] { + static SET: OnceLock<[f32; 2]> = OnceLock::new(); + *SET.get_or_init(|| { + let mut shade = [1.0, 0.6]; + let set = std::env::var("VICTORY_AMBIENT_SHADE").unwrap_or_default(); + for (to, v) in shade.iter_mut().zip(set.split(',')) { + if let Ok(v) = v.trim().parse::() + && v.is_finite() + { + *to = v; + } + } + shade + }) +} + +const SOURCE: &str = r#" +#define CX 64 +#define CY 36 +#define CELLS (CX * CY) +#define PX 160 +#define PY 90 +cbuffer Set : register(b0) { + float level; float constant; float strength; float radius; + float near; float tan_y; uint width; uint height; + float follow; float most; float air; uint slices; +}; +StructuredBuffer cells_in : register(t1); +StructuredBuffer points_in : register(t2); +RWByteAddressBuffer cells_out : register(u1); +RWByteAddressBuffer points_out : register(u2); +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); + +float4 load_cell(uint i) { return cells_in[i]; } +void store_cell(uint i, float4 v) { + uint4 u = asuint(v); + uint b = i * 16; + cells_out.Store(b, u.x); + cells_out.Store(b + 4, u.y); + cells_out.Store(b + 8, u.z); + cells_out.Store(b + 12, u.w); +} +float4 load_point(uint i) { return points_in[i]; } +void store_point(uint i, float4 v) { + uint4 u = asuint(v); + uint b = i * 16; + points_out.Store(b, u.x); + points_out.Store(b + 4, u.y); + points_out.Store(b + 8, u.z); + points_out.Store(b + 12, u.w); +} + +#if defined(PLACE) || defined(GATHER) || defined(RAISE) +Texture2D depth : register(t0); +// The point seen at a texel, in metres from the eye (x right, y up, z away). +float3 seen(int2 p, float2 size) { + float d = depth.Load(int3(clamp(p, int2(0, 0), int2(size) - 1), 0)); + float z = min(near / max(d, 1e-7), 1000.0); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * tan_y * size.x / size.y * z, -ndc.y * tan_y * z, z); +} +#endif + +#ifdef KEEP +RWTexture2D radiance : register(u0); +[numthreads(8, 4, 1)] +void main(uint3 at : SV_DispatchThreadID) { + uint w = width, h = height; + float3 sum = 0; + for (uint y = 0; y < 5; y++) { + for (uint x = 0; x < 5; x++) { + uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY)); + float3 c = max(radiance[p].rgb, 0.0); + uint3 bits = asuint(c); + bool bad = (bits.x & 0x7f800000u) == 0x7f800000u + || (bits.y & 0x7f800000u) == 0x7f800000u + || (bits.z & 0x7f800000u) == 0x7f800000u; + c = bad ? 0.0 : c; + sum += c / max(1.0, dot(c, LUMA) / 20.0); + } + } + store_cell(at.y * CX + at.x, float4(sum / 25.0, 1.0)); +} +#endif + +#ifdef MEAN +[numthreads(1, 1, 1)] +void main() { + float3 sum = 0; + for (uint i = 0; i < CELLS; i++) { + sum += load_cell(i).rgb; + } + float4 was = load_cell(CELLS); + float3 now = sum / CELLS; + store_cell(CELLS, float4(was.a > 0.0 ? lerp(was.rgb, now, follow) : now, 1.0)); +} +#endif + +#ifdef PLACE +[numthreads(8, 4, 1)] +void main(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size); + store_cell(CELLS + 1 + at.y * CX + at.x, float4(p, p.z * p.z)); +} +#endif + +#ifdef GATHER +[numthreads(8, 2, 1)] +void main(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size); + float r2 = 0.25 + 0.0025 * p.z * p.z; + float whole = 0; + float3 toward = 0, light = 0, red = 0, green = 0, blue = 0; + for (uint i = 0; i < CELLS; i++) { + float4 c = load_cell(CELLS + 1 + i); + float3 L = load_cell(i).rgb; + float3 d = c.xyz - p; + float dd = dot(d, d); + float w = c.w / (dd + r2); + float3 dir = d / sqrt(dd + 0.25 * r2); + whole += w; + toward += w * dir; + light += w * L; + red += w * L.r * dir; + green += w * L.g * dir; + blue += w * L.b * dir; + } + whole = max(whole, 1e-6); + light /= whole; + toward /= whole; + uint at0 = (at.y * PX + at.x) * 3; + store_point(at0, float4(red / whole - light.r * toward, light.r)); + store_point(at0 + 1, float4(green / whole - light.g * toward, light.g)); + store_point(at0 + 2, float4(blue / whole - light.b * toward, light.b)); +} +#endif + +#ifdef AIR +RWTexture3D scattered : register(u0); +[numthreads(8, 8, 2)] +void main(uint3 at : SV_DispatchThreadID) { + uint w = width, h = height, d = slices; + if (at.x >= w || at.y >= h || at.z >= d) return; + uint2 q = min(uint2((float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY)), uint2(PX - 1, PY - 1)); + uint at0 = (q.y * PX + q.x) * 3; + float3 seen_there = float3(load_point(at0).w, load_point(at0 + 1).w, load_point(at0 + 2).w); + float far = float(at.z) / float(d); + float cap = air * lerp(dot(load_cell(CELLS).rgb, LUMA), dot(seen_there, LUMA), far); + float4 s = scattered[at]; + float has = dot(s.rgb, LUMA); + if (has > cap) { + scattered[at] = float4(s.rgb * (cap / has), s.a); + } +} +#endif + +#ifdef RAISE +RWTexture2D light : register(u0); +float3 unpack_rgb9e5(uint v) { + return float3(v & 511u, (v >> 9) & 511u, (v >> 18) & 511u) * exp2(float(v >> 27) - 24.0); +} +uint pack_rgb9e5(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float scale = exp2(float(24 - e)); + if (top * scale >= 511.5) { + e = min(e + 1, 31); + scale = exp2(float(24 - e)); + } + uint3 m = min(uint3(c * scale + 0.5), 511u); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + if (at.x >= width || at.y >= height) return; + int2 p = int2(at.xy); + float3 c = seen(p, size); + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0, 0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + float open = 1.0; + float px = min(radius * size.y / (2.0 * tan_y * c.z), 128.0); + float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + if (strength > 0.0 && px >= 1.5 && c.z < 400.0) { + float sum = 0.0; + const int N = 12; + for (int i = 0; i < N; i++) { + float a = i * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((i + 0.5) / N) * px); + float3 v = seen(p + int2(floor(o + 0.5)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + open = saturate(1.0 - strength * 2.0 * sum / N); + } + float3 found; + if (constant > 0.0) { + found = float3(1.0, 0.98, 0.94) * constant * open; + light[p] = pack_rgb9e5(found); + return; + } + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = 0, sg = 0, sb = 0; + float sum = 0; + for (int k = 0; k < 4; k++) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 b = float2((k & 1) != 0 ? f.x : 1.0 - f.x, (k >> 1) != 0 ? f.y : 1.0 - f.y); + float w = (b.x * b.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = (q.y * PX + q.x) * 3; + sr += w * load_point(at0); + sg += w * load_point(at0 + 1); + sb += w * load_point(at0 + 2); + sum += w; + } + float3 all = float3(sr.w, sg.w, sb.w) / sum; + found = all + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum; + found = clamp(found, 0.2 * all, 2.5 * all); + found = lerp(found, load_cell(CELLS).rgb, 0.2) * level * open; + float3 was = unpack_rgb9e5(light[p]); + float top = max(dot(found, LUMA) * most, 1e-6); + float has = dot(was, LUMA); + was *= min(1.0, top / max(has, 1e-6)); + light[p] = pack_rgb9e5(max(was, found)); +} +#endif +"#; + +const CELLS: u64 = 64 * 36; +const CELL_BYTES: u64 = (2 * CELLS + 1) * 16; +const POINT_BYTES: u64 = 160 * 90 * 48; + +struct Pass { + root: ID3D12RootSignature, + keep: ID3D12PipelineState, + mean: ID3D12PipelineState, + place: ID3D12PipelineState, + gather: ID3D12PipelineState, + raise: ID3D12PipelineState, + air: ID3D12PipelineState, + cells: ID3D12Resource, + points: ID3D12Resource, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Pass {} +// SAFETY: as above. +unsafe impl Sync for Pass {} + +fn uav_buffer(device: &ID3D12Device, size: u64) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(16), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: valid heap and buffer descriptions; out pointer ours. + unsafe { + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + )?; + } + buffer.ok_or_else(windows::core::Error::empty) +} + +fn make(device: &ID3D12Device) -> windows::core::Result { + let depth_range = [srv(0, 1)]; + let image_range = [uav(0, 1)]; + let params = [ + Param::Constants { + register: 0, + count: 12, + }, + Param::Table(&depth_range), + Param::Table(&image_range), + Param::Srv { + register: 1, + space: 0, + }, + Param::Srv { + register: 2, + space: 0, + }, + Param::Uav { register: 1 }, + Param::Uav { register: 2 }, + ]; + let root = root_signature(device, ¶ms)?; + let build = |part: &str, label| { + pipeline_with_root( + device, + &root, + &format!("#define {part}\n{SOURCE}"), + label, + 0, + ) + }; + Ok(Pass { + keep: build("KEEP", s!("ambient_keep"))?, + mean: build("MEAN", s!("ambient_mean"))?, + place: build("PLACE", s!("ambient_place"))?, + gather: build("GATHER", s!("ambient_gather"))?, + raise: build("RAISE", s!("ambient_raise"))?, + air: build("AIR", s!("ambient_air"))?, + root, + cells: uav_buffer(device, CELL_BYTES)?, + points: uav_buffer(device, POINT_BYTES)?, + }) +} + +fn pass() -> Option<&'static Pass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + make(&host.device) + .inspect_err(|e| tracing::warn!(error = %e, "no stand-in for the indirect light")) + .ok() + }) + .as_ref() +} + +fn uav_barrier(list: &ID3D12GraphicsCommandList) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + ..Default::default() + }; + // SAFETY: an open list; the barrier names no resource. + unsafe { list.ResourceBarrier(&[barrier]) }; +} + +static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Views in the currently bound shader-visible heap that [`after`] reads/writes. +pub(crate) struct Views { + pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE, + pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE, + pub(crate) size: [u32; 2], + pub(crate) slices: u32, +} + +/// Records the stand-in compute dispatches after the title's `role` shader. +pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { + use std::sync::atomic::Ordering; + let (level, constant) = match set() { + Set::Off => return false, + Set::Estimate(level) => (level, 0.0f32), + Set::Constant(level) => (0.0, level), + }; + if role != Role::Radiance && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + return false; + } + if role == Role::Air && (constant > 0.0 || air() == 0.0) { + return false; + } + let Some(pass) = pass() else { + return false; + }; + static SAID: Mutex = Mutex::new(0); + { + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if *said < 4 { + *said += 1; + tracing::info!( + ?role, + size = ?views.size, + slices = views.slices, + level, + constant, + air = air(), + "stand-in for the indirect light" + ); + } + } + list.keep(&pass.cells); + list.keep(&pass.points); + let [strength, radius] = shade(); + let floats = [level, constant, strength, radius, 0.1, 0.45]; + let mut words = [0u32; 12]; + for (to, v) in words.iter_mut().zip(floats) { + *to = v.to_bits(); + } + words[6] = views.size[0]; + words[7] = views.size[1]; + words[8] = 0.04f32.to_bits(); + words[9] = 4.0f32.to_bits(); + words[10] = air().to_bits(); + words[11] = views.slices; + let l = &list.list; + // SAFETY: an open list with the view heap bound; textures and buffers are + // live and kept until reset. + unsafe { + let cells_gpu = pass.cells.GetGPUVirtualAddress(); + let points_gpu = pass.points.GetGPUVirtualAddress(); + uav_barrier(l); + l.SetComputeRootSignature(&pass.root); + l.SetComputeRoot32BitConstants(0, 12, words.as_ptr().cast(), 0); + l.SetComputeRootDescriptorTable(1, views.depth); + l.SetComputeRootDescriptorTable(2, views.image); + l.SetComputeRootShaderResourceView(3, cells_gpu); + l.SetComputeRootShaderResourceView(4, points_gpu); + l.SetComputeRootUnorderedAccessView(5, cells_gpu); + l.SetComputeRootUnorderedAccessView(6, points_gpu); + let run = |pso: &ID3D12PipelineState, x, y, z| { + l.SetPipelineState(pso); + l.Dispatch(x, y, z); + uav_barrier(l); + }; + match role { + Role::Radiance => { + run(&pass.keep, 8, 9, 1); + run(&pass.mean, 1, 1, 1); + KEPT.store(true, Ordering::Relaxed); + } + Role::Air => run( + &pass.air, + views.size[0].div_ceil(8), + views.size[1].div_ceil(8), + views.slices.div_ceil(2), + ), + Role::Resolve => { + if constant == 0.0 { + run(&pass.place, 8, 9, 1); + run(&pass.gather, 20, 45, 1); + } + run( + &pass.raise, + views.size[0].div_ceil(8), + views.size[1].div_ceil(8), + 1, + ); + } + } + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings() { + assert_eq!(parse(""), Set::Off); + assert_eq!(parse("off"), Set::Off); + assert_eq!(parse("0"), Set::Off); + assert_eq!(parse("0.8"), Set::Estimate(0.8)); + assert_eq!(parse("constant:0.3"), Set::Constant(0.3)); + assert_eq!(parse("constant:nan"), Set::Off); + } + + #[test] + fn roles_by_name() { + assert_eq!( + role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), + Some(Role::Resolve) + ); + assert_eq!( + role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), + Some(Role::Radiance) + ); + assert_eq!( + role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), + Some(Role::Air) + ); + assert_eq!(role(b"CS_TemporalResolve"), None); + } + + /// All six passes compile through the host's HLSL compiler (`vkd3d-shader` + /// under Wine) and build compute PSOs on D3D12 / D3DMetal. + #[test] + fn the_passes_build() { + let Some(host) = host() else { + return; + }; + make(&host.device).expect("all 6 ambient compute PSOs build"); + } +} diff --git a/crates/victory-gpu/src/compute.rs b/crates/victory-gpu/src/compute.rs index 15af69f2..f2fee71c 100644 --- a/crates/victory-gpu/src/compute.rs +++ b/crates/victory-gpu/src/compute.rs @@ -61,6 +61,20 @@ pub(crate) fn pipeline( params: &[Param], ) -> Result<(ID3D12RootSignature, ID3D12PipelineState)> { let device = &crate::host::host().ok_or_else(Error::empty)?.device; + let root = root_signature(device, params)?; + let pso = pipeline_with_root(device, &root, source, name, flags)?; + Ok((root, pso)) +} + +/// Compiles `source`'s `main` for `cs_5_1` with `flags` against an existing +/// `root` signature. +pub(crate) fn pipeline_with_root( + device: &ID3D12Device, + root: &ID3D12RootSignature, + source: &str, + name: PCSTR, + flags: u32, +) -> Result { let (mut code, mut errors): (Option, Option) = (None, None); // SAFETY: the source and names live through the call; out pointers ours. let compiled = unsafe { @@ -86,25 +100,25 @@ pub(crate) fn pipeline( errors.GetBufferPointer().cast::(), errors.GetBufferSize(), ); - tracing::warn!("{}: {}", name.display(), String::from_utf8_lossy(text)); + let msg = String::from_utf8_lossy(text); + tracing::warn!("{}: {}", name.display(), msg); + return Err(Error::new(e.code(), msg.as_ref())); } } return Err(e); } let code = code.ok_or_else(Error::empty)?; - let root = root_signature(device, params)?; // SAFETY: the bytecode and the root signature live through the call. - let pso = unsafe { + unsafe { device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), + pRootSignature: std::mem::transmute_copy(root), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.GetBufferPointer(), BytecodeLength: code.GetBufferSize(), }, ..Default::default() }) - }?; - Ok((root, pso)) + } } pub(crate) fn root_signature(device: &ID3D12Device, params: &[Param]) -> Result { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 92f9d8c7..93430816 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -66,6 +66,14 @@ pub(crate) struct State { depth: usize, /// Last render target and depth keys set on the host list. host_targets: Option<(Vec, Option)>, + /// The formats of the views [`State::set_targets`] bound on the host + /// list: a draw's pipeline is one for them + /// (`crate::pipeline::host_pipeline_for`). + target_formats: crate::pipeline::host::TargetFormats, + /// The tables the last bind made afresh for a program the stand-in for + /// the indirect light follows (`crate::ambient`): root parameter, bytes + /// into the view heap. + ambient_tables: Vec<(u8, u32)>, /// None leaves the host list's default bounds (0..1) in place. depth_bounds: Option<(f32, f32)>, /// The title's primitive topology (the host's may differ). @@ -254,6 +262,17 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } +/// The format of a host view of `texture` whose description names +/// `described` (none without a description): that one, or the texture's +/// own, which is what the host gives a view without a format. +fn bound_format(texture: &ID3D12Resource, described: Option) -> u32 { + match described { + Some(format) if format.0 != 0 => format.0 as u32, + // SAFETY: a live texture. + _ => unsafe { texture.GetDesc() }.Format.0 as u32, + } +} + impl State { pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); @@ -431,6 +450,8 @@ impl State { return; }; self.targets.clear(); + // The formats of the host views, for the draws' pipelines. + let mut formats = [0; 9]; let mut rtv_views = Vec::with_capacity(handles.len()); let mut rtv_keys = Vec::with_capacity(handles.len()); for &h in handles { @@ -447,8 +468,12 @@ impl State { self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); + let desc = record.desc(); + if rtv_views.len() < 8 { + formats[rtv_views.len()] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); + } rtv_keys.push((texture.as_raw() as usize, record.key())); - rtv_views.push((texture, record.desc())); + rtv_views.push((texture, desc)); } self.depth = 0; let mut dsv_view = None; @@ -457,11 +482,14 @@ impl State { && let Some(texture) = crate::resource::host_resource(record.resource) { self.depth = record.resource as usize; + let desc = record.depth_desc(); + formats[8] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); dsv_key = Some((texture.as_raw() as usize, record.key())); - dsv_view = Some((texture, record.depth_desc())); + dsv_view = Some((texture, desc)); } + self.target_formats = formats; if bind_cache_enabled() && self .host_targets @@ -571,7 +599,8 @@ impl State { if crate::pipeline::is_skipped(self.pipeline as This) { return false; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; if p.compute || p.mesh != mesh { @@ -784,6 +813,10 @@ impl State { not_run("no dynamic slots for its tables"); return false; } + if stage.shader.ambient.is_some() { + self.ambient_tables.clear(); + self.ambient_tables.extend(made.iter().copied()); + } // Root views a shader reads as title memory: the copies holding // their addresses go into the page table. let mut roots = Vec::new(); @@ -1206,6 +1239,88 @@ impl State { #[cfg(feature = "diagnostics")] self.probe_written(list); DISPATCHED.fetch_add(1, Ordering::Relaxed); + if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) + && crate::ambient::on() + && self.ambient(list, p, role) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + } + + /// The stand-in for the indirect light after a dispatch of `p` + /// (`crate::ambient`). Whether it recorded anything. + fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { + use crate::ambient::{AIR, DEPTH, LIGHT, RADIANCE, Role, Views}; + let Some(t) = p.stages.first().map(|s| s.translated()) else { + return false; + }; + let Some(heap) = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten() + else { + return false; + }; + let entry = |kind: ResourceType, (slot, offset): (u8, u32)| { + t.used.iter().find(|u| { + u.kind == kind + && u.root == RootType::Table + && (u.slot, u.table_offset_dwords) == (slot, offset) + })?; + let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(slot)) else { + return None; + }; + let resource = match *crate::descriptor::view(table + u64::from(offset) * 4)? { + View::Shader(r, _) | View::Unordered(r, ..) => r, + _ => return None, + }; + let start = match self.ambient_tables.iter().find(|m| m.0 == slot) { + Some(m) => m.1, + None => self.user_value(true, slot, RootType::Table, 0), + }; + let host = crate::resource::host_resource(resource as This)?; + // SAFETY: a live resource. + let desc = unsafe { host.GetDesc() }; + Some((desc, heap.gpu((start + offset * 4) / 32))) + }; + let at = match role { + Role::Resolve => LIGHT, + Role::Radiance => RADIANCE, + Role::Air => AIR, + }; + let image = entry(ResourceType::Uav, at); + let depth = match role { + Role::Resolve => entry(ResourceType::Srv, DEPTH), + Role::Radiance | Role::Air => image, + }; + let (Some((of, image)), Some((seen, depth))) = (image, depth) else { + once!(?role, "no stand-in for the indirect light: other tables"); + return false; + }; + // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) + let format = if role == Role::Resolve { 42 } else { 26 }; + let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if of.Format.0 != format + || (seen.Width, seen.Height) != (of.Width, of.Height) + || volume != (role == Role::Air) + { + once!( + ?role, + format = of.Format.0, + "no stand-in for the indirect light: another image" + ); + return false; + } + crate::ambient::after( + list, + role, + &Views { + image, + depth, + size: [of.Width as u32, of.Height], + slices: u32::from(of.DepthOrArraySize), + }, + ) } /// What a draw or dispatch runs, for the device-removed report @@ -1681,7 +1796,8 @@ impl State { /// Binds vertex buffers holding the rectangles of vertices `first..first /// + count` as triangles, made when the list is submitted. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; let rects = u64::from(count / 3); @@ -2008,10 +2124,10 @@ fn readable(list: &HostList, u: &UsedResource, view: &View, marked: bool) { (View::Shader(resource, _), ResourceType::Srv) => { // A view of memory the GPU writes through another title texture // whose host copy this one could not share reads that copy. - if let Some(a) = crate::resource::alias_source(*resource as This) { - crate::texture::alias_copy(list, a, *resource as This); - } - if let Some(t) = crate::resource::host_copy(*resource as This) + let copied = crate::resource::alias_source(*resource as This) + .is_some_and(|a| crate::texture::alias_copy(list, a, *resource as This)); + if !copied + && let Some(t) = crate::resource::host_copy(*resource as This) && t.title_written() { crate::texture::upload(list, *resource as This, &t.texture); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5d7ad469..ac208f9f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1410,6 +1410,8 @@ struct Deferred { slots: std::collections::HashSet<(usize, u32)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// Last GPU source copied into each aliased host texture in this list. + texture_aliases: std::collections::HashMap, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, @@ -3345,6 +3347,16 @@ impl HostList { self.deferred().textures.insert(key) } + pub(crate) fn alias_source_changed( + &self, + view: &ID3D12Resource, + source: &ID3D12Resource, + ) -> bool { + let view = view.as_raw() as usize; + let source = source.as_raw() as usize; + self.deferred().texture_aliases.insert(view, source) != Some(source) + } + /// Runs `work` on host memory at submission, in order with the copies. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Host(Box::new(work))); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index ed3eb24f..ca2116a5 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -19,6 +19,8 @@ #[cfg(windows)] mod alias; #[cfg(windows)] +mod ambient; +#[cfg(windows)] mod bindless; #[cfg(all(windows, feature = "diagnostics"))] mod capture; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index eeff0a11..f570936f 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -74,6 +74,9 @@ pub(crate) struct Shader { /// (`VICTORY_SPILL_SHADERS`, [`spill`]). #[cfg(windows)] spilled: OnceLock<[u8; 32]>, + /// Its part in the stand-in for the indirect light (`crate::ambient`). + #[cfg(windows)] + pub(crate) ambient: Option, #[cfg(windows)] translated: OnceLock>, } @@ -176,6 +179,10 @@ impl Shader { #[cfg(windows)] spilled: OnceLock::new(), #[cfg(windows)] + ambient: (stage == "compute") + .then(|| crate::ambient::role(bytes)) + .flatten(), + #[cfg(windows)] translated: OnceLock::new(), } } @@ -382,6 +389,7 @@ impl Shader { size: self.size, container: Mutex::new(Vec::new()), spilled: OnceLock::new(), + ambient: self.ambient, translated: cell, }) } @@ -521,6 +529,23 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// As [`host_pipeline`], for a draw into render target and depth views of +/// the formats `bound`. +#[cfg(windows)] +pub(crate) fn host_pipeline_for<'a>( + this: This, + bound: &host::TargetFormats, +) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = &pipeline(this).host; + if p.formats != *bound && host::formats_differ(&p.formats, bound) { + return make::for_formats(p, bound); + } + make::ready(p) +} + /// Whether a dispatch with the title pipeline is held back: it is the /// acceleration-structure builder's, which does not run this frame /// ([`builder::runs`]). @@ -531,7 +556,6 @@ pub(crate) fn held_back(this: This) -> bool { /// Whether the title's acceleration-structure builder runs this frame. #[cfg(windows)] -#[allow(dead_code)] pub(crate) fn builder_runs() -> bool { builder::runs() } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index bb417c32..9cd06ea2 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -91,6 +91,44 @@ impl Default for GraphicsState { } } +#[cfg(test)] +impl GraphicsState { + /// A state that declares one render target, of format `format` (tests). + pub(crate) fn declaring(format: i32) -> Self { + let mut g = Self::default(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT(format); + g + } +} + +/// The formats of what a draw draws into, as the host has them: the eight +/// render targets (0 where there is none), then depth (0 for none). +pub(crate) type TargetFormats = [u32; 9]; + +/// Whether a draw into views of the formats `bound` cannot go to the host +/// with a pipeline that declares `declared`: a render target slot for which +/// the pipeline declares a format has a view of another format bound to it. +pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool { + declared[..8] + .iter() + .zip(&bound[..8]) + .any(|(&d, &b)| d != 0 && b != 0 && b != d) +} + +/// The formats a pipeline for a draw into `bound` declares +/// ([`formats_differ`]): the title's own, except declared render target slots +/// with a bound view take the bound view's format. +pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats { + let mut formats = *declared; + for i in 0..8 { + if declared[i] != 0 && bound[i] != 0 { + formats[i] = bound[i]; + } + } + formats +} + /// Integer render target formats: D3D12 cannot blend into them. fn integer_format(f: DXGI_FORMAT) -> bool { matches!( @@ -151,6 +189,53 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 } impl GraphicsState { + /// The formats the state declares ([`TargetFormats`]): nothing past its + /// count of render targets. + pub(crate) fn formats(&self) -> TargetFormats { + let mut formats = [0; 9]; + let n = (self.targets.NumRenderTargets as usize).min(8); + for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) { + *to = from.0 as u32; + } + formats[8] = self.depth_format.0 as u32; + formats + } + + /// The same state for a draw into views of the formats `bound` + /// ([`formats_differ`]): the render target formats come from `bound`, + /// everything else stays the title's. + pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState { + let names = self.names.clone(); + let inputs: Vec = self + .inputs + .iter() + .zip(&names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + let mut targets = self.targets; + let n = (targets.NumRenderTargets as usize).min(8); + for (to, &from) in targets.RTFormats[..n].iter_mut().zip(bound) { + *to = DXGI_FORMAT(from as i32); + } + GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + depth_bounds: self.depth_bounds, + inputs, + names, + strip_cut: self.strip_cut, + topology: self.topology, + targets, + depth_format: self.depth_format, + samples: self.samples, + } + } + /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// @@ -1181,4 +1266,81 @@ mod tests { ]; let _ = offsets(&inputs); } + + #[test] + fn bound_formats_are_compared_slot_by_slot() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.targets.RTFormats[2] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + let declared = g.formats(); + assert_eq!(declared, [24, 28, 0, 0, 0, 0, 0, 0, 40]); + assert!(!formats_differ(&declared, &declared)); + assert!(!formats_differ(&declared, &[24, 0, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 0])); + assert!(!formats_differ(&declared, &[0; 9])); + assert!(formats_differ(&declared, &[26, 28, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 28, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 45])); + assert!(!formats_differ( + &[24, 0, 0, 0, 0, 0, 0, 0, 0], + &[24, 0, 0, 0, 0, 0, 0, 0, 40] + )); + assert_eq!( + formats_for(&declared, &[26, 28, 28, 0, 0, 0, 0, 0, 45]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!( + formats_for(&declared, &[26, 0, 0, 0, 0, 0, 0, 0, 0]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!(formats_for(&declared, &declared), declared); + } + + #[test] + fn a_state_for_the_bound_formats() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + g.sample_mask = 0x55; + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.blend.RenderTarget[0].BlendEnable = true.into(); + g.blend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; + g.names = vec![c"POSITION".to_owned()]; + g.inputs = vec![D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(g.names[0].as_ptr().cast()), + Format: DXGI_FORMAT_R32G32B32_FLOAT, + ..Default::default() + }]; + + let g_blend = host_blend(&g.blend, &g.targets); + assert!(!g_blend.RenderTarget[1].BlendEnable.as_bool()); + + let bound = formats_for(&g.formats(), &[26, 26, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(bound, [26, 26, 0, 0, 0, 0, 0, 0, 40]); + let v = g.with_formats(&bound); + assert_eq!(v.formats(), bound); + assert_eq!(v.targets.NumRenderTargets, 2); + assert_eq!(v.depth_format, DXGI_FORMAT_D32_FLOAT); + let v_blend = host_blend(&v.blend, &v.targets); + assert!(v_blend.RenderTarget[0].BlendEnable.as_bool()); + assert_ne!(v.describe(), g.describe()); + assert_eq!( + (v.sample_mask, v.rasterizer.CullMode), + (0x55, D3D12_CULL_MODE_NONE) + ); + assert_eq!(v.inputs.len(), 1); + assert_eq!(v.inputs[0].SemanticName.0, v.names[0].as_ptr().cast::()); + assert_ne!(v.inputs[0].SemanticName.0, g.inputs[0].SemanticName.0); + + let bound_int = [36, 24, 0, 0, 0, 0, 0, 0, 40]; + let v_int = g.with_formats(&bound_int); + let v_int_blend = host_blend(&v_int.blend, &v_int.targets); + assert!(!v_int_blend.RenderTarget[0].BlendEnable.as_bool()); + assert!(v_int_blend.RenderTarget[1].BlendEnable.as_bool()); + } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index f4c50c81..87155994 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -24,7 +24,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; -use super::host::{GraphicsState, HostPipeline}; +use super::host::{GraphicsState, HostPipeline, TargetFormats}; /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { @@ -42,6 +42,13 @@ pub(crate) struct Pending { /// whether a draw has used it yet. pub(crate) key: String, used: AtomicBool, + /// The formats its state declares for what a draw draws into (zeros + /// without a graphics state). + pub(crate) formats: TargetFormats, + /// The same shaders and state for other formats, bound at a draw + /// ([`for_formats`]): a chain from the title's pipeline, one link per + /// set of formats met, never shortened. + variant: OnceLock>, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -71,6 +78,8 @@ impl Pending { let _ = made.set(None); } Pending { + formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + variant: OnceLock::new(), key, shaders, graphics, @@ -216,6 +225,60 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { p.made.get()?.as_ref() } +/// Pipelines made again for the formats bound at a draw, since the start. +static VARIANTS: AtomicU64 = AtomicU64::new(0); + +/// Whether a draw into views of other formats than its pipeline declares +/// gets a host pipeline for those formats ([`for_formats`]). On by +/// default; `VICTORY_TARGET_VARIANTS=0` sends such a draw to the host with +/// the title's pipeline, as before. +fn variants_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0")) +} + +/// The host pipeline for a draw with `p` into views of the formats +/// `bound`, which `p` does not declare (`host::formats_differ`). +#[cold] +pub(crate) fn for_formats<'a>( + p: &'a Arc, + bound: &TargetFormats, +) -> Option<&'a HostPipeline> { + match p.graphics.as_deref() { + Some(g) if variants_on() => { + ready(variant(p, g, &super::host::formats_for(&p.formats, bound))) + } + _ => ready(p), + } +} + +fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc { + let mut at = p; + for _ in 0..64 { + let next = at.variant.get_or_init(|| { + let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + pipeline = ?p.shaders, + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (VICTORY_TARGET_VARIANTS=0 disables)" + ); + Arc::new(Pending::new( + p.shaders.clone(), + Some(Box::new(g.with_formats(bound))), + #[cfg(feature = "diagnostics")] + &[], + )) + }); + if next.formats == *bound { + return next; + } + at = next; + } + p +} + /// Starts making `p` now, without waiting for it. pub(crate) fn begin(p: &Arc) { if !p.shaders.is_empty() { @@ -438,6 +501,31 @@ mod tests { assert!(matches!(p.made.get(), Some(None))); } + #[test] + fn a_pipeline_for_bound_formats_is_made_once() { + let p = Arc::new(Pending::new( + Vec::new(), + Some(Box::new(GraphicsState::declaring(24))), + #[cfg(feature = "diagnostics")] + &[], + )); + assert_eq!(p.formats, [24, 0, 0, 0, 0, 0, 0, 0, 0]); + let g = p.graphics.as_deref().unwrap(); + let (a, b) = ([26, 0, 0, 0, 0, 0, 0, 0, 0], [28, 0, 0, 0, 0, 0, 0, 0, 0]); + let first = variant(&p, g, &a); + assert_eq!(first.formats, a); + assert_ne!(first.key, p.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + let second = variant(&p, g, &b); + assert_eq!(second.formats, b); + assert!(!Arc::ptr_eq(first, second)); + assert_ne!(second.key, first.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + assert!(Arc::ptr_eq(second, variant(&p, g, &b))); + assert!(!first.queued.load(Ordering::Relaxed)); + assert!(!p.queued.load(Ordering::Relaxed)); + } + #[cfg(feature = "diagnostics")] #[test] fn skipped_pipeline_stays_off_the_queue() { @@ -448,6 +536,7 @@ mod tests { full_hash: [0; 32], size: 0, container: std::sync::Mutex::new(Vec::new()), + ambient: None, translated: OnceLock::new(), spilled: OnceLock::new(), }); diff --git a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs index 9ca2599d..1c7f5851 100644 --- a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs +++ b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs @@ -86,6 +86,8 @@ fn store_shader() -> Arc { host, used: native.used, })), + #[cfg(windows)] + ambient: None, }) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 9940fb6f..660d4b66 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -3472,4 +3472,187 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + /// An earlier title-memory upload in a command list must not suppress a + /// later alias copy from a GPU-written atlas (`R32_UINT` -> `R9G9B9E5`), + /// and a subsequent GPU write to the source in the same list must copy + /// again into the sampled view. + #[cfg(windows)] + #[test] + fn alias_after_title_upload_and_mid_list_gpu_write_copies_the_gpu_atlas() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let Some(host) = crate::host::host() else { + return; + }; + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |desc: &ResourceDesc| { + let mut out = null; + assert_eq!( + create_placed( + null, + h, + 0, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut out + ), + S_OK + ); + out + }; + // 4x4 R32G32_UINT (format 17, 8 bytes/texel) and 16x16 BC1_UNORM + // (format 71, 4x4 blocks of 8 bytes) cannot share a host texture + // across uncompressed/compressed families, so `alias_source` pairs them. + let source = place(&ResourceDesc { + flags: UNORDERED, + ..texture(4, 4, 17, 1) + }); + let view = place(&texture(16, 16, 71, 1)); + let written = host_resource(source).expect("written host texture"); + let sampled = host_resource(view).expect("sampled host texture"); + assert_eq!(alias_source(view), Some(source)); + + let (upload, data) = host.upload_buffer(2048).unwrap(); + let first_light = 0x8c02_0100_55aa_1122_u64; + let second_light = 0x9d04_0200_cc33_7788_u64; + // SAFETY: two 1024-byte 4-row footprints inside the 2048-byte upload buffer. + unsafe { + for row in 0..4 { + for x in 0..4 { + data.add(row * 256 + x * 8) + .cast::() + .write_unaligned(first_light); + data.add(1024 + row * 256 + x * 8) + .cast::() + .write_unaligned(second_light); + } + } + } + let copy_into_source = |list: &crate::host::HostList, offset: u64| { + // SAFETY: borrowed COM pointers live through CopyTextureRegion. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&written), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: written.GetDesc().Format, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + crate::list::ensure_state(list, source, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + }; + + let seed = host.new_list().unwrap(); + copy_into_source(&seed, 0); + seed.close(); + host.execute(&[&seed]); + + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + let list = host.new_list().unwrap(); + crate::texture::upload(&list, view, &sampled); + assert!(crate::texture::alias_copy(&list, source, view)); + copy_into_source(&list, 1024); + assert!(crate::texture::alias_copy(&list, source, view)); + + crate::list::ensure_state(&list, view, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + // SAFETY: open list; valid readback footprint for 16x16 BC1 texture. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: sampled.GetDesc().Format, + Width: 16, + Height: 16, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&sampled), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + list.close(); + host.execute(&[&list]); + + let mut mapped = std::ptr::null_mut(); + // SAFETY: completed GPU copy into a 1024-byte readback buffer. + let actual = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let texel = mapped.cast::().read_unaligned(); + readback.Unmap(0, None); + texel + }; + for r in [view, source, h] { + assert_eq!(slot::(r, 0x10)(r), 0); + } + assert_eq!( + actual, second_light, + "sampled alias view did not reflect the latest GPU-written atlas" + ); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 99924b37..6c50ae51 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -312,7 +312,7 @@ pub(crate) static ALIAS_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic /// subresource with its own format, as many as have the same bytes per /// row and rows in both; `to` no longer takes its contents from title /// memory. -pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { +pub(crate) fn alias_copy(list: &HostList, from: This, to: This) -> bool { const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; let (Some(a), Some(b), Some(host)) = ( @@ -320,11 +320,26 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { crate::resource::host_resource(to), host(), ) else { - return; + return false; }; - // An odd key: textures' own first uses are keyed by the host texture. - if !list.first_use(to as usize | 1) { - return; + // An upload from title memory can have already used this view; only a + // copy from the same GPU source with no intervening state change on the + // source can satisfy this read. + list.first_use(to as usize | 1); + let new_source = list.alias_source_changed(&b, &a); + let before = list.transition(from, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(&texture, COPY_SOURCE); + let barrier = crate::host::transition( + &texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !new_source && before.is_none() { + return true; } // SAFETY: live resources. let (da, db) = unsafe { (a.GetDesc(), b.GetDesc()) }; @@ -358,12 +373,11 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { .count() as u32; if n == 0 { once!(?da, ?db, "an aliased texture not copied: its layouts differ on the host"); - return; + return false; } - let Some(buffer) = host.default_buffer(total) else { return }; + let Some(buffer) = host.default_buffer(total) else { return false }; list.keep(&buffer); crate::texture::host_writes(list, to); - crate::list::ensure_state(list, from, COPY_SOURCE); crate::list::ensure_state(list, to, COPY_DEST); let place = |r: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the copy does not release. @@ -399,6 +413,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { logged.push((from as usize, to as usize)); tracing::info!(from = ?from, to = ?to, a = da.Format.0, b = db.Format.0, w = da.Width, h = da.Height, subresources = n, "aliased texture copied"); } + true } /// Has `resource`'s host copy brought up to date at the submission that From f58e5640ff6820e11ad639e5a194d82fda8c9542 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 10:24:01 +0000 Subject: [PATCH 3/4] gpu: skip RT resolve passes without BVH and make structured SRVs raw --- crates/victory-gpu/src/descriptor/host.rs | 306 ++++++++++++++++++ crates/victory-gpu/src/host.rs | 19 ++ crates/victory-gpu/src/pipeline.rs | 8 + crates/victory-gpu/src/pipeline/builder.rs | 6 + crates/victory-gpu/src/pipeline/make.rs | 126 +++++++- .../src/pipeline/placed_uav_tests.rs | 2 + 6 files changed, 466 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index fa2c471e..9ffb5031 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1570,6 +1570,30 @@ fn buffer_srv( Some(HeldSource::Widened(widened, shadow.clone())), ))); } + let stride = u64::from(buffer.StructureByteStride); + if stride > 0 && raw_structured() { + // Scalar and offset-only buffer reads emit `rawBufferLoad` on a raw + // handle (`victory_shader::emit`), which D3D12 leaves undefined on a + // structured SRV (NVIDIA treats the byte offset as an element index, + // hanging `WindNew` loops). NVIDIA, WARP and D3DMetal all read both + // raw handles and structured handles accurately from a raw view of the + // same bytes; under Wine/D3DMetal any dword-aligned start (`+8B` or + // `+680B`) works too, while native D3D12 requires 16-byte alignment. + let (byte, dwords) = (first * stride, u64::from(count) * stride / 4); + let align = if crate::shader_cache::under_wine() { 4 } else { 16 }; + match u32::try_from(dwords) { + Ok(dwords) if byte.is_multiple_of(align) && stride.is_multiple_of(4) => { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: byte / 4, + NumElements: dwords, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + _ => once!(byte, stride, "structured buffer view not made raw: unaligned"), + } + } // SAFETY: a live buffer and a slot of our heap. unsafe { host.device @@ -1581,6 +1605,23 @@ fn buffer_srv( ))) } +/// Whether structured buffer views are made raw ([`buffer_srv`]): under Wine +/// (D3DMetal) and on NVIDIA hosts, both of which serve structured-handle and +/// raw-handle `rawBufferLoad`s from a raw view of the same bytes. +/// `VICTORY_RAW_STRUCTURED=0` or `=1` overrides. +fn raw_structured() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = match std::env::var("VICTORY_RAW_STRUCTURED").as_deref() { + Ok("0" | "false" | "off") => false, + Ok("1" | "true" | "on") => true, + _ => crate::shader_cache::under_wine() || crate::host::host_vendor() == 0x10DE, + }; + tracing::info!(on, "structured buffer views made raw"); + on + }) +} + /// Whether `count` elements of `element` bytes from element `first` lie in /// `buffer`. The console takes a view that is empty or runs past its /// memory; the host removes the device for one. @@ -3264,4 +3305,269 @@ mod tests { crate::object::release(resource); let _ = title_heap.as_mut_ptr(); } + + /// End-to-end test of [`buffer_srv`] converting a structured buffer SRV + /// (`StructureByteStride = 680`, starting at `FirstElement = 1` = `+680` + /// bytes, `8 mod 16`) into a raw SRV and reading it through a translated + /// DXIL compute shader via MUBUF raw byte offset (`0xC4`), SMEM scalar + /// byte offset (`0xC4`), and MUBUF structured element+field (`[2] + 12`). + #[test] + fn structured_buffer_srv_made_raw_reads_byte_and_element_offsets() { + use crate::pipeline::{Shader, Translated, host::HostPipeline}; + use victory_shader::native::{ComputeIo, StageIo}; + use victory_shader::{ + Container, HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, + emit, io, ir, resource, structure, + }; + + let Some(host) = host() else { + return; + }; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: valid feature support query. + let ok = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + }; + if ok.is_err() || sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return; + } + + let code_words: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (SRV slot 0) + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 (UAV slot 1) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF420_0404, + 0xFA00_00C4, // s_buffer_load_dword s16, s[8:11], 0xC4 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0210, // v_mov_b32 v4, s16 + 0xE030_00C4, + 0x8002_0100, // buffer_load_dword v1, off, s[8:11], 0 offset:196 + 0x7E04_0282, // v_mov_b32 v2, 2 + 0xE030_200C, + 0x8002_0302, // buffer_load_dword v3, v2, s[8:11], 0 idxen offset:12 + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_0000, + 0x8003_0100, // buffer_store_dword v1, off, s[12:15], 0 offset:0 + 0xE070_0004, + 0x8003_0400, // buffer_store_dword v4, off, s[12:15], 0 offset:4 + 0xE070_0008, + 0x8003_0300, // buffer_store_dword v3, off, s[12:15], 0 offset:8 + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: (0..2) + .map(|slot| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: slot, + slot, + }) + .collect(), + used: vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 680, + dwords: 4, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 1, + slot: 1, + }, + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: code_words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut container = vec![0; 32]; + container[..4].copy_from_slice(b"DXBC"); + container[20..24].copy_from_slice(&1u32.to_le_bytes()); + container[24..28].copy_from_slice(&32u32.to_le_bytes()); + let c = Container::parse(&container).unwrap(); + let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let hs = emit::emit(&c, &native, &p, &st, &io, &res).unwrap(); + let ud_spec = hs.user_data.clone(); + let shader = Shader::for_test( + "compute", + Translated { + host: hs, + used: native.used, + }, + ); + let Some(hp) = HostPipeline::new(&[shader], None) else { + panic!("synthetic structured-SRV pipeline"); + }; + + // Allocate 8 KiB of title memory (2048 dwords) filled with distinct words. + let bytes_len = 8192usize; + let mut backing: Vec = (0..(bytes_len / 4) as u32) + .map(|i| 0x2000_0000 + i) + .collect(); + let mem = backing.as_mut_ptr(); + crate::shadow::register(mem as usize, mem as u64, bytes_len as u64); + + // SAFETY: shader-visible heap with 2 slots. + let d3d_heap: ID3D12DescriptorHeap = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .unwrap() + }; + // SAFETY: live descriptor heap. + let cpu = unsafe { d3d_heap.GetCPUDescriptorHandleForHeapStart() }; + // SAFETY: plain device query. + let step = unsafe { + host.device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } as usize; + + // Structured SRV: stride = 680, FirstElement = 1 (+680B = +170 dwords), NumElements = 4. + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 1, + NumElements: 4, + StructureByteStride: 680, + Flags: D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, + }; + let _kept = buffer_srv(mem as u64, bytes_len as u64, srv_desc, cpu) + .expect("buffer_srv succeeds") + .expect("holds shadow buffer"); + + let list = host.new_list().unwrap(); + let shadow = crate::shadow::find(mem as u64, bytes_len as u64).expect("registered shadow"); + shadow.refresh(&list, mem as u64, bytes_len as u64); + + let mut uav_buf: Option = None; + // SAFETY: valid default UAV buffer description. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut uav_buf, + ) + .unwrap(); + } + let uav_buf = uav_buf.unwrap(); + let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 8, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: valid UAV slot 1. + unsafe { + host.device.CreateUnorderedAccessView( + &uav_buf, + None, + Some(&uav_desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + step, + }, + ); + } + + let mut ud = vec![0u32; hp.stages[0].user_data.map_or(1, |(_, n)| n as usize)]; + for u in &ud_spec { + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let (readback, rb_ptr) = list.readback(host, 256).unwrap(); + // SAFETY: open list with heap, root signature, constants, and PSO bound. + unsafe { + list.list.SetDescriptorHeaps(&[Some(d3d_heap.clone())]); + list.list.SetComputeRootSignature(&hp.root); + list.list + .SetComputeRoot32BitConstants(0, ud.len() as u32, ud.as_ptr().cast(), 0); + list.list.SetPipelineState(&hp.pso); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[crate::host::transition( + &uav_buf, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.list.CopyResource(&readback, &uav_buf); + } + list.close(); + host.execute(&[&list]); + + // SAFETY: GPU execution finished; read 3 dwords from mapped readback. + let got = unsafe { *rb_ptr.cast::<[u32; 3]>() }; + // SAFETY: plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + crate::shadow::unregister(mem as usize, mem as u64); + drop(backing); + + let expected = [ + 0x2000_0000 + 170 + 49, // MUBUF raw @ 0xC4 + 0x2000_0000 + 170 + 49, // SMEM scalar raw @ 0xC4 + 0x2000_0000 + 170 + 343, // MUBUF structured [2] + 12 + ]; + assert_eq!(got, expected); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index ac208f9f..00452186 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -404,6 +404,25 @@ fn process_memory() -> (u64, u64) { (c.PagefileUsage as u64, c.WorkingSetSize as u64) } +/// The PCI vendor id of the host device's adapter (NVIDIA 0x10DE), 0 if it +/// cannot be told. +pub(crate) fn host_vendor() -> u32 { + static VENDOR: OnceLock = OnceLock::new(); + *VENDOR.get_or_init(|| { + let Some(host) = host() else { return 0 }; + // SAFETY: plain DXGI queries for the device's own adapter. + let vendor = unsafe { + let luid = host.device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(luid)) + .and_then(|a| a.GetDesc1()) + .map_or(0, |d| d.VendorId) + }; + tracing::info!(vendor = format_args!("{vendor:#x}"), "host adapter vendor"); + vendor + }) +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index f570936f..2de1d279 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -77,6 +77,9 @@ pub(crate) struct Shader { /// Its part in the stand-in for the indirect light (`crate::ambient`). #[cfg(windows)] pub(crate) ambient: Option, + /// Ray-tracing pass skipped when the BVH builder does not run (`make`). + #[cfg(windows)] + pub(crate) without_bvh: Option, #[cfg(windows)] translated: OnceLock>, } @@ -183,6 +186,10 @@ impl Shader { .then(|| crate::ambient::role(bytes)) .flatten(), #[cfg(windows)] + without_bvh: (stage == "compute") + .then(|| make::without_bvh(bytes)) + .flatten(), + #[cfg(windows)] translated: OnceLock::new(), } } @@ -390,6 +397,7 @@ impl Shader { container: Mutex::new(Vec::new()), spilled: OnceLock::new(), ambient: self.ambient, + without_bvh: self.without_bvh, translated: cell, }) } diff --git a/crates/victory-gpu/src/pipeline/builder.rs b/crates/victory-gpu/src/pipeline/builder.rs index 4c2dabe4..fe8a324d 100644 --- a/crates/victory-gpu/src/pipeline/builder.rs +++ b/crates/victory-gpu/src/pipeline/builder.rs @@ -94,6 +94,12 @@ fn allow_halves() -> bool { *ON.get_or_init(|| crate::switch::on("VICTORY_BVH_BUILDER")) } +/// Whether the builder cannot run on this host at all (32-lane waves without +/// `VICTORY_BVH_BUILDER=1`), even before its pipelines are created. +pub(crate) fn disabled() -> bool { + crate::host::host().is_some_and(crate::host::Host::wave32) && !allow_halves() +} + /// Whether the builder's dispatches run in the current frame: decided once /// per frame, so that a frame never runs part of the builder. pub(crate) fn runs() -> bool { diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 87155994..d46189ed 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -49,6 +49,80 @@ pub(crate) struct Pending { /// ([`for_formats`]): a chain from the title's pipeline, one link per /// set of formats met, never shortened. variant: OnceLock>, + /// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH). + left_out: Option<&'static str>, +} + +/// Compute shaders whose work depends on populated BVHs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WithoutBvh { + /// Shades ray-tracing hits (`CS_RaytracingResolve_*`). + RaytracingResolve, + /// Activates probe rays (`CS_ScreenProbes_ActivateRays_*`). + ActivateRays, +} + +/// Classifies a compute shader container by its debug name. +pub(crate) fn without_bvh(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"CS_RaytracingResolve") { + Some(WithoutBvh::RaytracingResolve) + } else if has(b"CS_ScreenProbes_ActivateRays") { + Some(WithoutBvh::ActivateRays) + } else { + None + } +} + +fn left_out_with( + kind: WithoutBvh, + builder_runs: bool, + skip_master: bool, + rt_resolve: Option<&str>, + activate_rays: Option<&str>, +) -> Option<&'static str> { + if !skip_master { + return None; + } + match kind { + WithoutBvh::RaytracingResolve => { + if builder_runs || matches!(rt_resolve, Some("1" | "true" | "on")) { + None + } else { + Some("shades ray-tracing hits without BVH, left out") + } + } + WithoutBvh::ActivateRays => match activate_rays { + Some("0" | "false" | "off") => Some("ray activation shader without BVH, left out"), + Some("1" | "true" | "on") => None, + _ if builder_runs => None, + _ => Some("ray activation shader without BVH, left out"), + }, + } +} + +fn left_out_for(shaders: &[Arc], builder_runs: bool) -> Option<&'static str> { + let kind = shaders.iter().find_map(|s| s.without_bvh)?; + static FLAGS: OnceLock<(bool, Option, Option)> = OnceLock::new(); + let (skip_master, rt_resolve, activate_rays) = FLAGS.get_or_init(|| { + let master = std::env::var("VICTORY_SKIP_RT_RESOLVE") + .ok() + .is_none_or(|v| !matches!(v.trim(), "0" | "false" | "off")); + let rt = std::env::var("VICTORY_RT_RESOLVE") + .ok() + .map(|v| v.trim().to_owned()); + let act = std::env::var("VICTORY_ACTIVATE_RAYS") + .ok() + .map(|v| v.trim().to_owned()); + (master, rt, act) + }); + left_out_with( + kind, + builder_runs, + *skip_master, + rt_resolve.as_deref(), + activate_rays.as_deref(), + ) } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -71,8 +145,12 @@ impl Pending { }); #[cfg(feature = "diagnostics")] let skipped_shader = super::skipped_shader(&shaders, skip_hashes).map(str::to_owned); + let left_out = left_out_for(&shaders, !super::builder::disabled()); let made = OnceLock::new(); // Publish the completed result before the pipeline can be queued. + if left_out.is_some() { + let _ = made.set(None); + } #[cfg(feature = "diagnostics")] if skipped_shader.is_some() { let _ = made.set(None); @@ -80,6 +158,7 @@ impl Pending { Pending { formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), variant: OnceLock::new(), + left_out, key, shaders, graphics, @@ -140,6 +219,9 @@ pub(crate) fn missing(p: &Pending) -> Option { Some(Some(_)) => None, None => Some("being made".into()), Some(None) => { + if let Some(why) = p.left_out { + return Some(why.into()); + } let failed: Vec = p .shaders .iter() @@ -211,6 +293,9 @@ pub(crate) fn waiting() -> u64 { /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + if p.left_out.is_some() || left_out_for(&p.shaders, super::builder::runs()).is_some() { + return None; + } // Listed for an early start in later runs from its first use, made or // not: one a run never got made is the one it should start early. if !p.used.swap(true, Ordering::Relaxed) { @@ -281,7 +366,7 @@ fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> /// Starts making `p` now, without waiting for it. pub(crate) fn begin(p: &Arc) { - if !p.shaders.is_empty() { + if p.left_out.is_none() && !p.shaders.is_empty() { start(p, false); } } @@ -526,6 +611,44 @@ mod tests { assert!(!p.queued.load(Ordering::Relaxed)); } + #[test] + fn rt_resolve_and_activate_rays_are_left_out_without_bvh() { + assert_eq!( + without_bvh(b"..CS_RaytracingResolve_1234.."), + Some(WithoutBvh::RaytracingResolve) + ); + assert_eq!( + without_bvh(b"..CS_ScreenProbes_ActivateRays_5678.."), + Some(WithoutBvh::ActivateRays) + ); + assert_eq!(without_bvh(b"..CS_ScreenProbes_TemporalResolve.."), None); + + assert_eq!( + left_out_with(WithoutBvh::RaytracingResolve, false, true, None, None), + Some("shades ray-tracing hits without BVH, left out") + ); + assert_eq!( + left_out_with(WithoutBvh::ActivateRays, false, true, None, None), + Some("ray activation shader without BVH, left out") + ); + assert_eq!( + left_out_with(WithoutBvh::RaytracingResolve, true, true, None, None), + None + ); + assert_eq!( + left_out_with(WithoutBvh::RaytracingResolve, false, false, None, None), + None + ); + assert_eq!( + left_out_with(WithoutBvh::RaytracingResolve, false, true, Some("1"), None), + None + ); + assert_eq!( + left_out_with(WithoutBvh::ActivateRays, true, true, None, Some("0")), + Some("ray activation shader without BVH, left out") + ); + } + #[cfg(feature = "diagnostics")] #[test] fn skipped_pipeline_stays_off_the_queue() { @@ -537,6 +660,7 @@ mod tests { size: 0, container: std::sync::Mutex::new(Vec::new()), ambient: None, + without_bvh: None, translated: OnceLock::new(), spilled: OnceLock::new(), }); diff --git a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs index 1c7f5851..5937f8f9 100644 --- a/crates/victory-gpu/src/pipeline/placed_uav_tests.rs +++ b/crates/victory-gpu/src/pipeline/placed_uav_tests.rs @@ -88,6 +88,8 @@ fn store_shader() -> Arc { })), #[cfg(windows)] ambient: None, + #[cfg(windows)] + without_bvh: None, }) } From 5823d3551d1e51e572ce4d64ff9f567a85cc302d Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Fri, 27 Nov 2026 08:19:57 +0530 Subject: [PATCH 4/4] Re-apply the alias copy sync, render target format variants and raw structured buffer views on top of main's BVH hold and ambient light --- crates/victory-gpu/src/descriptor/host.rs | 306 ++++++++++++++++++++++ crates/victory-gpu/src/draw.rs | 42 ++- crates/victory-gpu/src/host.rs | 31 +++ crates/victory-gpu/src/pipeline.rs | 17 ++ crates/victory-gpu/src/pipeline/host.rs | 162 ++++++++++++ crates/victory-gpu/src/pipeline/make.rs | 90 ++++++- crates/victory-gpu/src/resource.rs | 184 +++++++++++++ crates/victory-gpu/src/texture.rs | 31 ++- 8 files changed, 846 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 477c6410..0b51e472 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1722,6 +1722,30 @@ fn buffer_srv( Some(HeldSource::Widened(widened, shadow.clone())), ))); } + let stride = u64::from(buffer.StructureByteStride); + if stride > 0 && raw_structured() { + // Scalar and offset-only buffer reads emit `rawBufferLoad` on a raw + // handle (`victory_shader::emit`), which D3D12 leaves undefined on a + // structured SRV (NVIDIA treats the byte offset as an element index, + // hanging `WindNew` loops). NVIDIA, WARP and D3DMetal all read both + // raw handles and structured handles accurately from a raw view of the + // same bytes; under Wine/D3DMetal any dword-aligned start (`+8B` or + // `+680B`) works too, while native D3D12 requires 16-byte alignment. + let (byte, dwords) = (first * stride, u64::from(count) * stride / 4); + let align = if crate::shader_cache::under_wine() { 4 } else { 16 }; + match u32::try_from(dwords) { + Ok(dwords) if byte.is_multiple_of(align) && stride.is_multiple_of(4) => { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: byte / 4, + NumElements: dwords, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + _ => once!(byte, stride, "structured buffer view not made raw: unaligned"), + } + } // SAFETY: a live buffer and a slot of our heap. unsafe { host.device @@ -1733,6 +1757,23 @@ fn buffer_srv( ))) } +/// Whether structured buffer views are made raw ([`buffer_srv`]): under Wine +/// (D3DMetal) and on NVIDIA hosts, both of which serve structured-handle and +/// raw-handle `rawBufferLoad`s from a raw view of the same bytes. +/// `VICTORY_RAW_STRUCTURED=0` or `=1` overrides. +fn raw_structured() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = match std::env::var("VICTORY_RAW_STRUCTURED").as_deref() { + Ok("0" | "false" | "off") => false, + Ok("1" | "true" | "on") => true, + _ => crate::shader_cache::under_wine() || crate::host::host_vendor() == 0x10DE, + }; + tracing::info!(on, "structured buffer views made raw"); + on + }) +} + /// Whether `count` elements of `element` bytes from element `first` lie in /// `buffer`. The console takes a view that is empty or runs past its /// memory; the host removes the device for one. @@ -3661,4 +3702,269 @@ void main(uint3 id : SV_DispatchThreadID) { "patterns unchanged, moved as unsigned integers" ); } + + /// End-to-end test of [`buffer_srv`] converting a structured buffer SRV + /// (`StructureByteStride = 680`, starting at `FirstElement = 1` = `+680` + /// bytes, `8 mod 16`) into a raw SRV and reading it through a translated + /// DXIL compute shader via MUBUF raw byte offset (`0xC4`), SMEM scalar + /// byte offset (`0xC4`), and MUBUF structured element+field (`[2] + 12`). + #[test] + fn structured_buffer_srv_made_raw_reads_byte_and_element_offsets() { + use crate::pipeline::{Shader, Translated, host::HostPipeline}; + use victory_shader::native::{ComputeIo, StageIo}; + use victory_shader::{ + Container, HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, + emit, io, ir, resource, structure, + }; + + let Some(host) = host() else { + return; + }; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: valid feature support query. + let ok = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + }; + if ok.is_err() || sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return; + } + + let code_words: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (SRV slot 0) + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 (UAV slot 1) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF420_0404, + 0xFA00_00C4, // s_buffer_load_dword s16, s[8:11], 0xC4 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0210, // v_mov_b32 v4, s16 + 0xE030_00C4, + 0x8002_0100, // buffer_load_dword v1, off, s[8:11], 0 offset:196 + 0x7E04_0282, // v_mov_b32 v2, 2 + 0xE030_200C, + 0x8002_0302, // buffer_load_dword v3, v2, s[8:11], 0 idxen offset:12 + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_0000, + 0x8003_0100, // buffer_store_dword v1, off, s[12:15], 0 offset:0 + 0xE070_0004, + 0x8003_0400, // buffer_store_dword v4, off, s[12:15], 0 offset:4 + 0xE070_0008, + 0x8003_0300, // buffer_store_dword v3, off, s[12:15], 0 offset:8 + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: (0..2) + .map(|slot| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: slot, + slot, + }) + .collect(), + used: vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 680, + dwords: 4, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 1, + slot: 1, + }, + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: code_words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut container = vec![0; 32]; + container[..4].copy_from_slice(b"DXBC"); + container[20..24].copy_from_slice(&1u32.to_le_bytes()); + container[24..28].copy_from_slice(&32u32.to_le_bytes()); + let c = Container::parse(&container).unwrap(); + let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let hs = emit::emit(&c, &native, &p, &st, &io, &res).unwrap(); + let ud_spec = hs.user_data.clone(); + let shader = Shader::for_test( + "compute", + Translated { + host: hs, + used: native.used, + }, + ); + let Some(hp) = HostPipeline::new(&[shader], None, |_, _| {}) else { + panic!("synthetic structured-SRV pipeline"); + }; + + // Allocate 8 KiB of title memory (2048 dwords) filled with distinct words. + let bytes_len = 8192usize; + let mut backing: Vec = (0..(bytes_len / 4) as u32) + .map(|i| 0x2000_0000 + i) + .collect(); + let mem = backing.as_mut_ptr(); + crate::shadow::register(mem as usize, mem as u64, bytes_len as u64); + + // SAFETY: shader-visible heap with 2 slots. + let d3d_heap: ID3D12DescriptorHeap = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .unwrap() + }; + // SAFETY: live descriptor heap. + let cpu = unsafe { d3d_heap.GetCPUDescriptorHandleForHeapStart() }; + // SAFETY: plain device query. + let step = unsafe { + host.device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } as usize; + + // Structured SRV: stride = 680, FirstElement = 1 (+680B = +170 dwords), NumElements = 4. + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 1, + NumElements: 4, + StructureByteStride: 680, + Flags: D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, + }; + let _kept = buffer_srv(mem as u64, bytes_len as u64, srv_desc, cpu) + .expect("buffer_srv succeeds") + .expect("holds shadow buffer"); + + let list = host.new_list().unwrap(); + let shadow = crate::shadow::find(mem as u64, bytes_len as u64).expect("registered shadow"); + shadow.refresh(&list, mem as u64, bytes_len as u64); + + let mut uav_buf: Option = None; + // SAFETY: valid default UAV buffer description. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut uav_buf, + ) + .unwrap(); + } + let uav_buf = uav_buf.unwrap(); + let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 8, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: valid UAV slot 1. + unsafe { + host.device.CreateUnorderedAccessView( + &uav_buf, + None, + Some(&uav_desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + step, + }, + ); + } + + let mut ud = vec![0u32; hp.stages[0].user_data.map_or(1, |(_, n)| n as usize)]; + for u in &ud_spec { + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let (readback, rb_ptr) = list.readback(host, 256).unwrap(); + // SAFETY: open list with heap, root signature, constants, and PSO bound. + unsafe { + list.list.SetDescriptorHeaps(&[Some(d3d_heap.clone())]); + list.list.SetComputeRootSignature(&hp.root); + list.list + .SetComputeRoot32BitConstants(0, ud.len() as u32, ud.as_ptr().cast(), 0); + list.list.SetPipelineState(&hp.pso); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[crate::host::transition( + &uav_buf, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.list.CopyResource(&readback, &uav_buf); + } + list.close(); + host.execute(&[&list]); + + // SAFETY: GPU execution finished; read 3 dwords from mapped readback. + let got = unsafe { *rb_ptr.cast::<[u32; 3]>() }; + // SAFETY: plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + crate::shadow::unregister(mem as usize, mem as u64); + drop(backing); + + let expected = [ + 0x2000_0000 + 170 + 49, // MUBUF raw @ 0xC4 + 0x2000_0000 + 170 + 49, // SMEM scalar raw @ 0xC4 + 0x2000_0000 + 170 + 343, // MUBUF structured [2] + 12 + ]; + assert_eq!(got, expected); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2cddd6d9..fdfffbc3 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -66,6 +66,10 @@ pub(crate) struct State { depth: usize, /// Last render target and depth keys set on the host list. host_targets: Option<(Vec, Option)>, + /// The formats of the views [`State::set_targets`] bound on the host + /// list: a draw's pipeline is one for them + /// (`crate::pipeline::host_pipeline_for`). + target_formats: crate::pipeline::host::TargetFormats, /// None leaves the host list's default bounds (0..1) in place. depth_bounds: Option<(f32, f32)>, /// The title's primitive topology (the host's may differ). @@ -261,6 +265,17 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } +/// The format of a host view of `texture` whose description names +/// `described` (none without a description): that one, or the texture's +/// own, which is what the host gives a view without a format. +fn bound_format(texture: &ID3D12Resource, described: Option) -> u32 { + match described { + Some(format) if format.0 != 0 => format.0 as u32, + // SAFETY: a live texture. + _ => unsafe { texture.GetDesc() }.Format.0 as u32, + } +} + impl State { pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); @@ -438,6 +453,8 @@ impl State { return; }; self.targets.clear(); + // The formats of the host views, for the draws' pipelines. + let mut formats = [0; 9]; let mut rtv_views = Vec::with_capacity(handles.len()); let mut rtv_keys = Vec::with_capacity(handles.len()); for &h in handles { @@ -454,8 +471,12 @@ impl State { self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); + let desc = record.desc(); + if rtv_views.len() < 8 { + formats[rtv_views.len()] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); + } rtv_keys.push((texture.as_raw() as usize, record.key())); - rtv_views.push((texture, record.desc())); + rtv_views.push((texture, desc)); } if self .hdr_rtvs @@ -471,11 +492,14 @@ impl State { && let Some(texture) = crate::resource::host_resource(record.resource) { self.depth = record.resource as usize; + let desc = record.depth_desc(); + formats[8] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); dsv_key = Some((texture.as_raw() as usize, record.key())); - dsv_view = Some((texture, record.depth_desc())); + dsv_view = Some((texture, desc)); } + self.target_formats = formats; if bind_cache_enabled() && self .host_targets @@ -585,7 +609,8 @@ impl State { if crate::pipeline::is_skipped(self.pipeline as This) { return false; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; if p.compute || p.mesh != mesh { @@ -1947,7 +1972,8 @@ impl State { /// Binds vertex buffers holding the rectangles of vertices `first..first /// + count` as triangles, made when the list is submitted. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; let rects = u64::from(count / 3); @@ -2332,10 +2358,10 @@ fn readable(list: &HostList, u: &UsedResource, view: &View, marked: bool) { (View::Shader(resource, _), ResourceType::Srv) => { // A view of memory the GPU writes through another title texture // whose host copy this one could not share reads that copy. - if let Some(a) = crate::resource::alias_source(*resource as This) { - crate::texture::alias_copy(list, a.get(), *resource as This); - } - if let Some(t) = crate::resource::host_copy(*resource as This) + let copied = crate::resource::alias_source(*resource as This) + .is_some_and(|a| crate::texture::alias_copy(list, a.get(), *resource as This)); + if !copied + && let Some(t) = crate::resource::host_copy(*resource as This) && t.title_written() { crate::texture::upload(list, *resource as This, &t.texture); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f22a0859..230bed23 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -414,6 +414,25 @@ pub(crate) fn device_removed() -> bool { host().is_some_and(|h| unsafe { h.device.GetDeviceRemovedReason() }.is_err()) } +/// The PCI vendor id of the host device's adapter (NVIDIA 0x10DE), 0 if it +/// cannot be told. +pub(crate) fn host_vendor() -> u32 { + static VENDOR: OnceLock = OnceLock::new(); + *VENDOR.get_or_init(|| { + let Some(host) = host() else { return 0 }; + // SAFETY: plain DXGI queries for the device's own adapter. + let vendor = unsafe { + let luid = host.device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(luid)) + .and_then(|a| a.GetDesc1()) + .map_or(0, |d| d.VendorId) + }; + tracing::info!(vendor = format_args!("{vendor:#x}"), "host adapter vendor"); + vendor + }) +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { @@ -1590,6 +1609,8 @@ struct Deferred { slots: std::collections::HashSet<(usize, u32)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// Last GPU source copied into each aliased host texture in this list. + texture_aliases: std::collections::HashMap, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, @@ -3729,6 +3750,16 @@ impl HostList { self.deferred().textures.insert(key) } + pub(crate) fn alias_source_changed( + &self, + view: &ID3D12Resource, + source: &ID3D12Resource, + ) -> bool { + let view = view.as_raw() as usize; + let source = source.as_raw() as usize; + self.deferred().texture_aliases.insert(view, source) != Some(source) + } + /// Runs `work` on host memory at submission, in order with the copies. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Host(Box::new(work))); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index a8208ba7..50f68d67 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -530,6 +530,23 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// As [`host_pipeline`], for a draw into render target and depth views of +/// the formats `bound`. +#[cfg(windows)] +pub(crate) fn host_pipeline_for<'a>( + this: This, + bound: &host::TargetFormats, +) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = &pipeline(this).host; + if p.formats != *bound && host::formats_differ(&p.formats, bound) { + return make::for_formats(p, bound); + } + make::ready(p) +} + /// Whether a dispatch with the title pipeline is held back: it is the /// acceleration-structure builder's, which does not run this frame /// ([`builder::runs`]). diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 0b043032..04b2f255 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -94,6 +94,44 @@ impl Default for GraphicsState { } } +#[cfg(test)] +impl GraphicsState { + /// A state that declares one render target, of format `format` (tests). + pub(crate) fn declaring(format: i32) -> Self { + let mut g = Self::default(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT(format); + g + } +} + +/// The formats of what a draw draws into, as the host has them: the eight +/// render targets (0 where there is none), then depth (0 for none). +pub(crate) type TargetFormats = [u32; 9]; + +/// Whether a draw into views of the formats `bound` cannot go to the host +/// with a pipeline that declares `declared`: a render target slot for which +/// the pipeline declares a format has a view of another format bound to it. +pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool { + declared[..8] + .iter() + .zip(&bound[..8]) + .any(|(&d, &b)| d != 0 && b != 0 && b != d) +} + +/// The formats a pipeline for a draw into `bound` declares +/// ([`formats_differ`]): the title's own, except declared render target slots +/// with a bound view take the bound view's format. +pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats { + let mut formats = *declared; + for i in 0..8 { + if declared[i] != 0 && bound[i] != 0 { + formats[i] = bound[i]; + } + } + formats +} + /// Integer render target formats: D3D12 cannot blend into them. fn integer_format(f: DXGI_FORMAT) -> bool { matches!( @@ -154,6 +192,53 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 } impl GraphicsState { + /// The formats the state declares ([`TargetFormats`]): nothing past its + /// count of render targets. + pub(crate) fn formats(&self) -> TargetFormats { + let mut formats = [0; 9]; + let n = (self.targets.NumRenderTargets as usize).min(8); + for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) { + *to = from.0 as u32; + } + formats[8] = self.depth_format.0 as u32; + formats + } + + /// The same state for a draw into views of the formats `bound` + /// ([`formats_differ`]): the render target formats come from `bound`, + /// everything else stays the title's. + pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState { + let names = self.names.clone(); + let inputs: Vec = self + .inputs + .iter() + .zip(&names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + let mut targets = self.targets; + let n = (targets.NumRenderTargets as usize).min(8); + for (to, &from) in targets.RTFormats[..n].iter_mut().zip(bound) { + *to = DXGI_FORMAT(from as i32); + } + GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + depth_bounds: self.depth_bounds, + inputs, + names, + strip_cut: self.strip_cut, + topology: self.topology, + targets, + depth_format: self.depth_format, + samples: self.samples, + } + } + /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// @@ -1117,4 +1202,81 @@ mod tests { ]; let _ = offsets(&inputs); } + + #[test] + fn bound_formats_are_compared_slot_by_slot() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.targets.RTFormats[2] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + let declared = g.formats(); + assert_eq!(declared, [24, 28, 0, 0, 0, 0, 0, 0, 40]); + assert!(!formats_differ(&declared, &declared)); + assert!(!formats_differ(&declared, &[24, 0, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 0])); + assert!(!formats_differ(&declared, &[0; 9])); + assert!(formats_differ(&declared, &[26, 28, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 28, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 45])); + assert!(!formats_differ( + &[24, 0, 0, 0, 0, 0, 0, 0, 0], + &[24, 0, 0, 0, 0, 0, 0, 0, 40] + )); + assert_eq!( + formats_for(&declared, &[26, 28, 28, 0, 0, 0, 0, 0, 45]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!( + formats_for(&declared, &[26, 0, 0, 0, 0, 0, 0, 0, 0]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!(formats_for(&declared, &declared), declared); + } + + #[test] + fn a_state_for_the_bound_formats() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + g.sample_mask = 0x55; + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.blend.RenderTarget[0].BlendEnable = true.into(); + g.blend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; + g.names = vec![c"POSITION".to_owned()]; + g.inputs = vec![D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(g.names[0].as_ptr().cast()), + Format: DXGI_FORMAT_R32G32B32_FLOAT, + ..Default::default() + }]; + + let g_blend = host_blend(&g.blend, &g.targets); + assert!(!g_blend.RenderTarget[1].BlendEnable.as_bool()); + + let bound = formats_for(&g.formats(), &[26, 26, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(bound, [26, 26, 0, 0, 0, 0, 0, 0, 40]); + let v = g.with_formats(&bound); + assert_eq!(v.formats(), bound); + assert_eq!(v.targets.NumRenderTargets, 2); + assert_eq!(v.depth_format, DXGI_FORMAT_D32_FLOAT); + let v_blend = host_blend(&v.blend, &v.targets); + assert!(v_blend.RenderTarget[0].BlendEnable.as_bool()); + assert_ne!(v.describe(), g.describe()); + assert_eq!( + (v.sample_mask, v.rasterizer.CullMode), + (0x55, D3D12_CULL_MODE_NONE) + ); + assert_eq!(v.inputs.len(), 1); + assert_eq!(v.inputs[0].SemanticName.0, v.names[0].as_ptr().cast::()); + assert_ne!(v.inputs[0].SemanticName.0, g.inputs[0].SemanticName.0); + + let bound_int = [36, 24, 0, 0, 0, 0, 0, 0, 40]; + let v_int = g.with_formats(&bound_int); + let v_int_blend = host_blend(&v_int.blend, &v_int.targets); + assert!(!v_int_blend.RenderTarget[0].BlendEnable.as_bool()); + assert!(v_int_blend.RenderTarget[1].BlendEnable.as_bool()); + } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 38886e79..22a2577a 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -23,7 +23,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; -use super::host::{GraphicsState, HostPipeline}; +use super::host::{GraphicsState, HostPipeline, TargetFormats}; use super::schedule::{ COMPUTE_BUDGET, Lane, PriorityQueue, WaitBudgets, lane_for, sync_compute_enabled, }; @@ -53,6 +53,13 @@ pub(crate) struct Pending { /// whether a draw has used it yet. pub(crate) key: String, used: AtomicBool, + /// The formats its state declares for what a draw draws into (zeros + /// without a graphics state). + pub(crate) formats: TargetFormats, + /// The same shaders and state for other formats, bound at a draw + /// ([`for_formats`]): a chain from the title's pipeline, one link per + /// set of formats met, never shortened. + variant: OnceLock>, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -85,6 +92,8 @@ impl Pending { && shaders.first().is_some_and(|s| s.stage == "compute") && sync_compute_enabled(); Pending { + formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + variant: OnceLock::new(), key, shaders, graphics, @@ -240,6 +249,60 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { p.made.get()?.as_ref() } +/// Pipelines made again for the formats bound at a draw, since the start. +static VARIANTS: AtomicU64 = AtomicU64::new(0); + +/// Whether a draw into views of other formats than its pipeline declares +/// gets a host pipeline for those formats ([`for_formats`]). On by +/// default; `VICTORY_TARGET_VARIANTS=0` sends such a draw to the host with +/// the title's pipeline, as before. +fn variants_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0")) +} + +/// The host pipeline for a draw with `p` into views of the formats +/// `bound`, which `p` does not declare (`host::formats_differ`). +#[cold] +pub(crate) fn for_formats<'a>( + p: &'a Arc, + bound: &TargetFormats, +) -> Option<&'a HostPipeline> { + match p.graphics.as_deref() { + Some(g) if variants_on() => { + ready(variant(p, g, &super::host::formats_for(&p.formats, bound))) + } + _ => ready(p), + } +} + +fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc { + let mut at = p; + for _ in 0..64 { + let next = at.variant.get_or_init(|| { + let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + pipeline = ?p.shaders, + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (VICTORY_TARGET_VARIANTS=0 disables)" + ); + Arc::new(Pending::new( + p.shaders.clone(), + Some(Box::new(g.with_formats(bound))), + #[cfg(feature = "diagnostics")] + &[], + )) + }); + if next.formats == *bound { + return next; + } + at = next; + } + p +} + /// Starts making `p` now, without waiting for it. pub(crate) fn begin(p: &Arc) { if !p.shaders.is_empty() { @@ -533,6 +596,31 @@ mod tests { ); } + #[test] + fn a_pipeline_for_bound_formats_is_made_once() { + let p = Arc::new(Pending::new( + Vec::new(), + Some(Box::new(GraphicsState::declaring(24))), + #[cfg(feature = "diagnostics")] + &[], + )); + assert_eq!(p.formats, [24, 0, 0, 0, 0, 0, 0, 0, 0]); + let g = p.graphics.as_deref().unwrap(); + let (a, b) = ([26, 0, 0, 0, 0, 0, 0, 0, 0], [28, 0, 0, 0, 0, 0, 0, 0, 0]); + let first = variant(&p, g, &a); + assert_eq!(first.formats, a); + assert_ne!(first.key, p.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + let second = variant(&p, g, &b); + assert_eq!(second.formats, b); + assert!(!Arc::ptr_eq(first, second)); + assert_ne!(second.key, first.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + assert!(Arc::ptr_eq(second, variant(&p, g, &b))); + assert!(!first.queued.load(Ordering::Relaxed)); + assert!(!p.queued.load(Ordering::Relaxed)); + } + #[cfg(feature = "diagnostics")] #[test] fn skipped_pipeline_stays_off_the_queue() { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 6563bd19..ea698e26 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -3982,4 +3982,188 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + /// An earlier title-memory upload in a command list must not suppress a + /// later alias copy from a GPU-written atlas (`R32_UINT` -> `R9G9B9E5`), + /// and a subsequent GPU write to the source in the same list must copy + /// again into the sampled view. + #[cfg(windows)] + #[test] + fn alias_after_title_upload_and_mid_list_gpu_write_copies_the_gpu_atlas() { + use crate::backend::{HostGpu, HostMemory}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let Some(host) = crate::host::host() else { + return; + }; + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |desc: &ResourceDesc| { + let mut out = null; + assert_eq!( + create_placed( + null, + h, + 0, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut out + ), + S_OK + ); + out + }; + // 4x4 R32G32_UINT (format 17, 8 bytes/texel) and 16x16 BC1_UNORM + // (format 71, 4x4 blocks of 8 bytes) cannot share a host texture + // across uncompressed/compressed families, so `alias_source` pairs them. + let source = place(&ResourceDesc { + flags: UNORDERED, + ..texture(4, 4, 17, 1) + }); + let view = place(&texture(16, 16, 71, 1)); + let written = host_resource(source).expect("written host texture"); + let sampled = host_resource(view).expect("sampled host texture"); + assert_eq!(alias_source(view).map(|a| a.get()), Some(source)); + + let (upload, data) = host.upload_buffer(2048).unwrap(); + let first_light = 0x8c02_0100_55aa_1122_u64; + let second_light = 0x9d04_0200_cc33_7788_u64; + // SAFETY: two 1024-byte 4-row footprints inside the 2048-byte upload buffer. + unsafe { + for row in 0..4 { + for x in 0..4 { + data.add(row * 256 + x * 8) + .cast::() + .write_unaligned(first_light); + data.add(1024 + row * 256 + x * 8) + .cast::() + .write_unaligned(second_light); + } + } + } + let copy_into_source = |list: &crate::host::HostList, offset: u64| { + // SAFETY: borrowed COM pointers live through CopyTextureRegion. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&written), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: written.GetDesc().Format, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + crate::list::ensure_state(list, source, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + }; + + let seed = host.new_list().unwrap(); + copy_into_source(&seed, 0); + seed.close(); + host.execute(&[&seed]); + + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + let list = host.new_list().unwrap(); + crate::texture::upload(&list, view, &sampled); + assert!(crate::texture::alias_copy(&list, source, view)); + copy_into_source(&list, 1024); + assert!(crate::texture::alias_copy(&list, source, view)); + + crate::list::ensure_state(&list, view, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + // SAFETY: open list; valid readback footprint for 16x16 BC1 texture. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: sampled.GetDesc().Format, + Width: 16, + Height: 16, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&sampled), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + list.close(); + host.execute(&[&list]); + + let mut mapped = std::ptr::null_mut(); + // SAFETY: completed GPU copy into a 1024-byte readback buffer. + let actual = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let texel = mapped.cast::().read_unaligned(); + readback.Unmap(0, None); + texel + }; + for r in [view, source, h] { + assert_eq!(slot::(r, 0x10)(r), 0); + } + assert_eq!( + actual, second_light, + "sampled alias view did not reflect the latest GPU-written atlas" + ); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 035ec1de..ce69a3d8 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -331,7 +331,7 @@ pub(crate) static ALIAS_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic /// subresource with its own format, as many as have the same bytes per /// row and rows in both; `to` no longer takes its contents from title /// memory. -pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { +pub(crate) fn alias_copy(list: &HostList, from: This, to: This) -> bool { const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; let (Some(a), Some(b), Some(host)) = ( @@ -339,11 +339,26 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { crate::resource::host_resource(to), host(), ) else { - return; + return false; }; - // An odd key: textures' own first uses are keyed by the host texture. - if !list.first_use(to as usize | 1) { - return; + // An upload from title memory can have already used this view; only a + // copy from the same GPU source with no intervening state change on the + // source can satisfy this read. + list.first_use(to as usize | 1); + let new_source = list.alias_source_changed(&b, &a); + let before = list.transition(from, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(&texture, COPY_SOURCE); + let barrier = crate::host::transition( + &texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !new_source && before.is_none() { + return true; } // SAFETY: live resources. let (da, db) = unsafe { (a.GetDesc(), b.GetDesc()) }; @@ -377,12 +392,11 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { .count() as u32; if n == 0 { once!(?da, ?db, "an aliased texture not copied: its layouts differ on the host"); - return; + return false; } - let Some(buffer) = host.default_buffer(total) else { return }; + let Some(buffer) = host.default_buffer(total) else { return false }; list.keep(&buffer); crate::texture::host_writes(list, to); - crate::list::ensure_state(list, from, COPY_SOURCE); crate::list::ensure_state(list, to, COPY_DEST); let place = |r: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the copy does not release. @@ -418,6 +432,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { logged.push((from as usize, to as usize)); tracing::info!(from = ?from, to = ?to, a = da.Format.0, b = db.Format.0, w = da.Width, h = da.Height, subresources = n, "aliased texture copied"); } + true } /// Has `resource`'s host copy brought up to date at the submission that