diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc4ad..4923c37db6 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -21,7 +21,7 @@ use windows::core::Interface; use crate::host::HostList; use crate::object::This; -use crate::pipeline::host::HostPipeline; +use crate::pipeline::host::{HostPipeline, Stage}; /// A root argument as the title set it. #[derive(Debug, Clone, Default)] @@ -143,6 +143,7 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { .min(if srv { 1 << 20 } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { + list.shadow_state(&shadow.buffer, D3D12_RESOURCE_STATE_GENERIC_READ); shadow.refresh(list, address, len); return Some(gpu); } @@ -370,6 +371,7 @@ impl State { let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { continue; }; + list.shadow_state(&shadow.buffer, D3D12_RESOURCE_STATE_GENERIC_READ); shadow.refresh(list, v.address, u64::from(v.size)); *view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -388,6 +390,7 @@ impl State { let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { return false; }; + list.shadow_state(&shadow.buffer, D3D12_RESOURCE_STATE_GENERIC_READ); shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: shadow.gpu(v.address), @@ -416,6 +419,17 @@ impl State { /// False if the draw or dispatch must not run: a table it reads could /// not be made. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + self.bind_objects(list, p, compute); + for stage in &p.stages { + let Some(tables) = self.stage_tables(list, stage, compute) else { + return false; + }; + self.bind_arguments(list, stage, compute, &tables); + } + true + } + + fn bind_objects(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -456,64 +470,75 @@ impl State { list.keep(&p.pso); list.keep(&p.root); } - for stage in &p.stages { - let t = stage.translated(); - self.table_failed = false; - let made = self.tables(list, &t.used, compute); - if self.table_failed { - static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); - let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - tracing::warn!( - dropped = n, - "a draw or dispatch dropped: no dynamic slots for its tables" - ); - } - return false; + } + + fn stage_tables( + &mut self, + list: &HostList, + stage: &Stage, + compute: bool, + ) -> Option> { + let t = stage.translated(); + self.table_failed = false; + let made = self.tables(list, &t.used, compute); + if self.table_failed { + static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0); + let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::warn!( + dropped = n, + "a draw or dispatch dropped: no dynamic slots for its tables" + ); } - if let Some((param, dwords)) = stage.user_data { - let mut values = vec![0u32; dwords as usize]; - for u in &t.host.user_data { - let fresh = made - .iter() - .find(|m| m.0 == u.slot && u.root == RootType::Table); - values[u.index as usize] = match fresh { - Some(&(_, offset)) => offset, - None => self.user_value(compute, u.slot, u.root, u.dword), - }; - } - // SAFETY: an open list; `values` covers the parameter. - unsafe { - if compute { - l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); - } else { - l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); - } + return None; + } + Some(made) + } + + fn bind_arguments(&self, list: &HostList, stage: &Stage, compute: bool, made: &[(u8, u32)]) { + let l = &list.list; + let t = stage.translated(); + if let Some((param, dwords)) = stage.user_data { + let mut values = vec![0u32; dwords as usize]; + for u in &t.host.user_data { + let fresh = made + .iter() + .find(|m| m.0 == u.slot && u.root == RootType::Table); + values[u.index as usize] = match fresh { + Some(&(_, offset)) => offset, + None => self.user_value(compute, u.slot, u.root, u.dword), + }; + } + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } else { + l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); } } - for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { - for &(slot, param) in views { - let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) - else { - once!(slot, "a shader reads a root view the title did not set"); - continue; - }; - let Some(gpu) = root_view(list, *address, srv) else { - continue; - }; - // SAFETY: an open list; the address is in live memory. - unsafe { - match (compute, srv) { - (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), - (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), - (true, false) => l.SetComputeRootConstantBufferView(param, gpu), - (true, true) => l.SetComputeRootShaderResourceView(param, gpu), - } + } + for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { + for &(slot, param) in views { + let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + else { + once!(slot, "a shader reads a root view the title did not set"); + continue; + }; + let Some(gpu) = root_view(list, *address, srv) else { + continue; + }; + // SAFETY: an open list; the address is in live memory. + unsafe { + match (compute, srv) { + (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), + (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), + (true, false) => l.SetComputeRootConstantBufferView(param, gpu), + (true, true) => l.SetComputeRootShaderResourceView(param, gpu), } } } } - true } /// Runs a dispatch on the host. @@ -971,7 +996,7 @@ impl State { arguments: u64, count: Option, ) -> bool { - // Skip before the argument clamp can mutate the indirect buffer. + // A skipped pipeline must not spend any of the list budget. #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { crate::pipeline::note_drop(self.pipeline as This); @@ -985,8 +1010,23 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; - let len = u64::from(stride) * u64::from(max.max(1)); - let Some(args) = crate::shadow::find(arguments, len) else { + let Some(layout) = crate::indirect::Layout::new(kind, stride, max) else { + why("unsupported argument layout"); + return false; + }; + if max == 0 { + return true; + } + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + return false; + }; + let Some(signature) = host_signature(kind, layout.width) else { + why("no host signature"); + return false; + }; + let Some(args) = crate::shadow::find(arguments, layout.span()) else { why("arguments outside title buffers"); return false; }; @@ -1000,59 +1040,73 @@ impl State { }, None => None, }; - let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) - .then(|| host_signature(kind, stride)) - .flatten() - else { - why("no host signature"); + if kind == INDEXED && (self.index.address == 0 || self.index.size == 0) { + why("no index buffer for an indexed indirect draw"); + return false; + } + // Finish every fallible bind before recording work against the list budget. + // A compute pipeline has one stage. Keep its resolved tables while the + // private dispatch borrows the compute root, then bind its arguments once. + let compute = match kind { + DISPATCH if p.compute => { + let [stage] = p.stages.as_slice() else { + return false; + }; + let Some(tables) = self.stage_tables(list, stage, true) else { + return false; + }; + Some((stage, tables)) + } + DRAW | INDEXED + if self.topology != RECTANGLES && self.prepare(list, kind == INDEXED) => + { + None + } + MESH if self.prepare_for(list, false, true) => None, + _ => { + why("pipeline or draw state cannot execute this signature"); + return false; + } + }; + let count_view = counter.as_ref().map(|(s, at)| (&s.buffer, s.gpu(*at))); + let Some(clamp) = crate::indirect::prepare( + list, + layout, + args.gpu(arguments), + count_view.map(|(_, gpu)| gpu), + ) else { + why("cannot prepare indirect argument clamp"); return false; }; - args.refresh(list, arguments, len); + args.refresh(list, arguments, layout.span()); if let Some((s, at)) = &counter { s.refresh(list, *at, 4); } - // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { - why("not bounded (no clamp, or arguments not 4-byte aligned)"); - return false; + clamp.record( + list, + layout, + (&args.buffer, args.gpu(arguments)), + count_view, + ); + if self.host_pipeline == p.pso.as_raw() as usize { + // The private dispatch displaced a title PSO already retained by this list. + // Restore it without taking two further COM references for every indirect call. + // SAFETY: the list is open and retains the pipeline. + unsafe { list.list.SetPipelineState(&p.pso) }; } - self.host_pipeline = 0; self.host_roots[1] = 0; - let ran = match kind { - DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), - MESH => self.prepare_for(list, false, true), - DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => self.bind(list, p, true), - _ => false, - }, - _ => false, - }; - if !ran { - crate::indirect::done(list, &args.buffer); - #[cfg(feature = "diagnostics")] - match crate::pipeline::host_pipeline(self.pipeline as This) { - None => crate::pipeline::note_drop(self.pipeline as This), - Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)), - } - return false; + self.bind_objects(list, p, p.compute); + if let Some((stage, tables)) = compute { + self.bind_arguments(list, stage, true, &tables); } #[cfg(feature = "diagnostics")] list.note_op(|| { - self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) - }); - // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. - unsafe { - list.list.ExecuteIndirect( - &signature, - max, - &args.buffer, - args.offset(arguments), - counter.as_ref().map(|(s, _)| &s.buffer), - counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + self.op_text( + format!("indirect kind {kind} max {max} at {arguments:#x}"), + kind == DISPATCH, ) - }; - crate::indirect::done(list, &args.buffer); + }); + clamp.execute(list, &signature, max); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { @@ -1114,9 +1168,13 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) { && let Some(shadow) = crate::shadow::find(address, len) { shadow.refresh(list, address, len); - if u.kind == ResourceType::Uav { + let state = if u.kind == ResourceType::Uav { shadow.gpu_writes(list, address, len); - } + D3D12_RESOURCE_STATE_UNORDERED_ACCESS + } else { + D3D12_RESOURCE_STATE_GENERIC_READ + }; + list.shadow_state(&shadow.buffer, state); } match (view, u.kind) { (View::Shader(resource, _), ResourceType::Srv) => { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1ed11..8bdaf689fa 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -298,9 +298,12 @@ pub(crate) struct HostList { prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, - /// The work its indirect executions may still do (`indirect`): a - /// shader-writable word, zeroed when the list is submitted. - budget: OnceLock>, + /// Per-execution work tally and its immutable zero upload. + budget: OnceLock>, + /// Private argument storage reused in GPU command order, grown on demand. + pub(crate) indirect_scratch: Mutex>, + /// Explicit states of shadow buffers in this list. Lists start and end in COMMON. + shadow_states: Mutex>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -481,6 +484,8 @@ impl Host { prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), + indirect_scratch: Mutex::default(), + shadow_states: Mutex::default(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -494,6 +499,26 @@ impl Host { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + if runs.len() > 1 { + // A repeated native list (including its prelude and scratch) can only + // be submitted again after its preceding execution has completed. + let mut seen = std::collections::HashSet::new(); + let mut start = 0; + for (i, &list) in runs.iter().enumerate() { + if !seen.insert(list.list.as_raw()) { + self.execute_group(&runs[start..i], &mut submitted); + seen.clear(); + seen.insert(list.list.as_raw()); + start = i; + } + } + self.execute_group(&runs[start..], &mut submitted); + } else if !runs.is_empty() { + self.execute_group(runs, &mut submitted); + } + } + + fn execute_group(&self, runs: &[&HostList], submitted: &mut u64) { let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); @@ -859,7 +884,42 @@ impl HostList { times } + /// Moves a host copy to its next use and returns the previous state. + /// Reads share GENERIC_READ so an argument buffer may also supply vertex data. + pub(crate) fn shadow_state( + &self, + buffer: &ID3D12Resource, + wanted: D3D12_RESOURCE_STATES, + ) -> D3D12_RESOURCE_STATES { + let mut states = self.shadow_states.lock().unwrap_or_else(|e| e.into_inner()); + let (_, state) = states + .entry(buffer.as_raw() as usize) + .or_insert_with(|| (buffer.clone(), D3D12_RESOURCE_STATE_COMMON)); + let before = std::mem::replace(state, wanted); + if before != wanted { + // SAFETY: an open list; the map retains the buffer. + unsafe { + self.list + .ResourceBarrier(&[transition(buffer, before, wanted)]) + }; + } + before + } + pub(crate) fn close(&self) { + // A submission can batch several lists without decay between them. + let barriers: Vec<_> = self + .shadow_states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .filter(|(_, state)| *state != D3D12_RESOURCE_STATE_COMMON) + .map(|(buffer, state)| transition(buffer, *state, D3D12_RESOURCE_STATE_COMMON)) + .collect(); + if !barriers.is_empty() { + // SAFETY: the state map keeps all named buffers alive until reset. + unsafe { self.list.ResourceBarrier(&barriers) }; + } #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -882,6 +942,10 @@ impl HostList { pub(crate) fn reset(&self) { *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.shadow_states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -1107,24 +1171,25 @@ impl HostList { Some((gpu + at, (data + at as usize) as *mut u8)) } - /// The host address of the list's indirect-work budget, zeroed at each - /// submission of the list from the first use after a reset on. + /// Reset on the GPU so two executions of the same recorded list in one + /// submission each start with their own budget. pub(crate) fn budget(&self) -> Option { - let (buffer, data) = self + let (buffer, zero) = self .budget .get_or_init(|| { - let (b, d) = host()?.shared_buffer(256)?; - Some((b, d as usize)) + let host = host()?; + let (b, _) = host.shared_buffer(4)?; + let (zero, data) = host.upload_buffer(4)?; + // SAFETY: the upload is mapped and has room for one dword. + unsafe { data.cast::().write(0) }; + Some((b, zero)) }) .as_ref()?; - let mut deferred = self.deferred(); - if !deferred.budget_zeroed { - deferred.budget_zeroed = true; - let at = *data; - // SAFETY: the list's own mapped word, written before it runs. - deferred - .copies - .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); + if !std::mem::replace(&mut self.deferred().budget_zeroed, true) { + self.shadow_state(buffer, D3D12_RESOURCE_STATE_COPY_DEST); + // SAFETY: both buffers stay alive with the list. + unsafe { self.list.CopyBufferRegion(buffer, 0, zero, 0, 4) }; + self.shadow_state(buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index c0236d8229..e0c85335db 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2,9 +2,9 @@ //! title's own compute passes write most of them; a pass we drop or //! translate wrongly leaves whatever the memory held, and a draw of four //! billion vertices or a dispatch past the host's limits runs until the -//! host resets the display driver. So every record is clamped on the GPU, -//! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler; a 5.1 shader with its root signature inside). +//! host resets the display driver. A compute shader copies the active records +//! into a private buffer, clamps them, and saves the count that selects them. +//! ExecuteIndirect consumes that snapshot on the same list. //! //! Each list also has a budget (2^27 vertex instances or threads, groups //! counted as 64 threads, mesh groups as 128): records past it run empty, @@ -19,53 +19,87 @@ use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); -// The list's work so far (vertex instances, threads): past the budget, -// records run empty. +// GPU-produced inputs may return to a writable state between bindings. +#define RS "RootConstants(num32BitConstants=9, b0), SRV(t0, flags=DATA_VOLATILE), SRV(t1, flags=DATA_VOLATILE), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind, stride, maximum, first, window, src_offset, dst_offset, counted, count_offset; +}; +ByteAddressBuffer source : register(t0); +ByteAddressBuffer counter : register(t1); +RWByteAddressBuffer output_args : register(u0); RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; -// Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; + +// One group owns this window's budget. All lanes load and store in parallel; +// the group leader admits records in command order, without cross-group atomics. +groupshared uint live; +groupshared uint remaining; +groupshared uint costs[64]; + [RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; - uint at = id.x * stride; - uint cost; - if (kind <= 1) { - // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); - cost = count * instances; - args.Store2(at, uint2(count, instances)); - } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); - // x * y fits 32 bits; the whole count may not. - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { - g = uint3(0, 0, 0); - } - cost = g.x * g.y * g.z * 64; - args.Store3(at, g); - } else { - // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; - args.Store3(at, g); +void main(uint lane : SV_GroupIndex) { + if (lane == 0) { + uint active = counted ? min(maximum, counter.Load(count_offset)) : maximum; + if (first == 0) output_args.Store(0, active); + live = first < active ? min(window, active - first) : 0; + remaining = BUDGET - min(budget.Load(0), BUDGET); } - uint before; - budget.InterlockedAdd(0, cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + GroupMemoryBarrierWithGroupSync(); + for (uint tile = 0; tile < live; tile += 64) { + uint index = tile + lane; + uint4 args = 0; + uint start_instance = 0; + uint cost = 0; + if (index < live) { + uint at = src_offset + index * stride; + if (kind <= 1) { + args = source.Load4(at); + if (kind == 1) start_instance = source.Load(at + 16); + args.x = min(args.x, 1u << 24); + args.y = min(args.y, (1u << 26) / max(args.x, 1u)); + cost = args.x * args.y; + } else { + args.xyz = min(source.Load3(at), uint3(65535, 65535, 65535)); + if (kind == 2) { + if (args.z != 0 && args.x * args.y > GROUPS / args.z) args.xyz = 0; + } else { + args.yz = min(args.yz, uint2(1, 1)); + } + cost = args.x * args.y * args.z * (kind == 2 ? 64u : 128u); + } + } + costs[lane] = cost; + GroupMemoryBarrierWithGroupSync(); + if (lane == 0) { + uint left = remaining; + for (uint i = 0; i < min(64u, live - tile); ++i) { + if (costs[i] <= left) left -= costs[i]; + else costs[i] = 0xffffffff; + } + remaining = left; + } + GroupMemoryBarrierWithGroupSync(); + if (index < live) { + if (costs[lane] == 0xffffffff) args.x = 0; + if (kind <= 1) { + uint dst = dst_offset + index * (kind == 0 ? 16u : 20u); + output_args.Store4(dst, args); + if (kind == 1) output_args.Store(dst + 16, start_instance); + } else { + output_args.Store3(dst_offset + index * 12, args.xyz); + } + } + GroupMemoryBarrierWithGroupSync(); } + if (lane == 0 && live != 0) budget.Store(0, BUDGET - remaining); } "#; @@ -139,59 +173,202 @@ fn make() -> windows::core::Result { } } -/// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. -pub(crate) fn bound( +/// Only the signature payload is interpreted; the title stride can include padding. +#[derive(Clone, Copy)] +pub(crate) struct Layout { + kind: u32, + stride: u32, + maximum: u32, + pub(crate) width: u32, +} + +impl Layout { + pub(crate) fn new(kind: u32, stride: u32, maximum: u32) -> Option { + let width = match kind { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + _ => return None, + }; + (stride >= width && stride.is_multiple_of(4)).then_some(Self { + kind, + stride, + maximum, + width, + }) + } + + pub(crate) fn span(self) -> u64 { + if self.maximum == 0 { + return 0; + } + u64::from(self.maximum - 1) * u64::from(self.stride) + u64::from(self.width) + } +} + +// Space for the count, then packed records. Root SRV/UAV addresses are +// 16-byte aligned even when a guest buffer offset is only dword aligned. +const HEADER: u64 = 16; +const WINDOW_RECORDS: u32 = 4096; +pub(crate) struct Prepared { + clamp: &'static Clamp, + budget: u64, + scratch: ID3D12Resource, +} + +pub(crate) fn prepare( list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - (kind, stride, records): (u32, u32, u32), -) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { - return false; - }; - if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { - return false; + layout: Layout, + args: u64, + count: Option, +) -> Option { + if !args.is_multiple_of(4) || count.is_some_and(|at| !at.is_multiple_of(4)) { + return None; } - let l = &list.list; - let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. - unsafe { - // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); - l.SetComputeRootSignature(&c.root); - l.SetPipelineState(&c.pso); - l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); - l.SetComputeRootUnorderedAccessView(2, budget); - l.Dispatch(records.div_ceil(64), 1, 1); - l.ResourceBarrier(&[ - uav_barrier(), - transition( - buffer, + let clamp = clamp()?; + let size = HEADER + u64::from(layout.maximum) * u64::from(layout.width); + let mut slot = list + .indirect_scratch + .lock() + .unwrap_or_else(|e| e.into_inner()); + if slot.as_ref().is_none_or(|buffer| { + // SAFETY: the list keeps the cached buffer alive. + unsafe { buffer.GetDesc().Width < size } + }) { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.next_multiple_of(64 << 10), + 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 heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut buffer = None; + // SAFETY: valid descriptions and an owned out pointer. + unsafe { + host()? + .device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .ok()?; + } + if let Some(old) = slot.replace(buffer?) { + list.keep(&old); + } + } + Some(Prepared { + clamp, + budget: list.budget()?, + scratch: slot.as_ref()?.clone(), + }) +} + +impl Prepared { + pub(crate) fn record( + &self, + list: &HostList, + layout: Layout, + (args, address): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + ) { + let read = D3D12_RESOURCE_STATE_GENERIC_READ; + let was = list.shadow_state(args, read); + let other = count + .filter(|(b, _)| *b != args) + .map(|(b, _)| (b, list.shadow_state(b, read))); + let counter = count.map_or(address, |(_, at)| at); + let l = &list.list; + // SAFETY: the list owns the scratch and budget; refresh holds both input shadows. + unsafe { + let base = self.scratch.GetGPUVirtualAddress(); + l.ResourceBarrier(&[ + uav_barrier(), + transition( + &self.scratch, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]); + l.SetComputeRootSignature(&self.clamp.root); + l.SetPipelineState(&self.clamp.pso); + l.SetComputeRootShaderResourceView(2, counter & !15); + l.SetComputeRootUnorderedAccessView(4, self.budget); + // Rebase each window so the shader's byte offsets stay 32-bit and + // each workgroup has a bounded number of records. + let mut first = 0; + while first < layout.maximum { + let src = address + u64::from(first) * u64::from(layout.stride); + let dst = HEADER + u64::from(first) * u64::from(layout.width); + let dst_base = if first == 0 { 0 } else { dst & !15 }; + let fit = 1 + (u32::MAX - (src & 15) as u32 - layout.width) / layout.stride; + let window = (layout.maximum - first).min(WINDOW_RECORDS).min(fit); + let constants = [ + layout.kind, + layout.stride, + layout.maximum, + first, + window, + (src & 15) as u32, + (dst - dst_base) as u32, + u32::from(count.is_some()), + (counter & 15) as u32, + ]; + l.SetComputeRoot32BitConstants(0, 9, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src & !15); + l.SetComputeRootUnorderedAccessView(3, base + dst_base); + if first != 0 { + // Successive windows read the preceding window's updated work tally. + l.ResourceBarrier(&[uav_barrier()]); + } + l.Dispatch(1, 1, 1); + first += window; + } + l.ResourceBarrier(&[transition( + &self.scratch, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), - ]); + )]); + } + // The title pipeline can also bind an input shadow for writes. + list.shadow_state(args, was); + if let Some((buffer, prior)) = other { + list.shadow_state(buffer, prior); + } } - true -} -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { - // SAFETY: an open list and a live buffer. - unsafe { - list.list.ResourceBarrier(&[transition( - buffer, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]) - }; + pub(crate) fn execute( + &self, + list: &HostList, + signature: &ID3D12CommandSignature, + maximum: u32, + ) { + // SAFETY: the private count and arguments were produced together and both are indirect-readable. + unsafe { + list.list + .ExecuteIndirect(signature, maximum, &self.scratch, HEADER, &self.scratch, 0); + list.list.ResourceBarrier(&[transition( + &self.scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } } fn uav_barrier() -> D3D12_RESOURCE_BARRIER { @@ -206,6 +383,25 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { + #[test] + fn layout_ends_at_the_last_payload() { + use super::Layout; + assert_eq!(Layout::new(0, 24, 0).unwrap().span(), 0); + assert_eq!(Layout::new(0, 24, 4).unwrap().span(), 88); + assert_eq!( + Layout::new(1, 20, u32::MAX).unwrap().span(), + 20 * u64::from(u32::MAX) + ); + assert!(Layout::new(1, 16, 1).is_none()); + assert!(Layout::new(2, 13, 1).is_none()); + assert!(Layout::new(99, 16, 1).is_none()); + let stride = u32::MAX - 3; + assert_eq!( + Layout::new(2, stride, u32::MAX).unwrap().span(), + (u64::from(u32::MAX) - 1) * u64::from(stride) + 12 + ); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { @@ -214,4 +410,171 @@ mod tests { } assert!(super::clamp().is_some()); } + + #[test] + fn packed_arguments_preserve_the_source_and_budget_on_replay() { + use super::*; + let Some(host) = host() else { return }; + let list = host.new_list().unwrap(); + // These records only go through the clamp. Read back its output without issuing their work. + // After the first large draw fits, the second is over budget; a small draw still fits. + const LARGE: [u32; 5] = [1 << 24, 4, 0, 0, 0]; + const CASES: [(u32, [u32; 5], [u32; 5]); 9] = [ + ( + 1, + [3, 2, 7, (-3i32) as u32, 11], + [3, 2, 7, (-3i32) as u32, 11], + ), + (2, [2, 3, 4, 0, 0], [2, 3, 4, 0, 0]), + (10, [2, 3, 4, 0, 0], [2, 1, 1, 0, 0]), + (0, LARGE, LARGE), + (0, LARGE, [0, 4, 0, 0, 0]), + (0, [3, 1, 0, 0, 0], [3, 1, 0, 0, 0]), + (2, [u32::MAX, u32::MAX, u32::MAX, 0, 0], [0; 5]), + (2, [65535, 65535, 0, 0, 0], [65535, 65535, 0, 0, 0]), + (10, [u32::MAX, u32::MAX, 0, 0, 0], [65535, 1, 0, 0, 0]), + ]; + let bytes = (CASES.len() * size_of::<[u32; 5]>()) as u64; + let (source, input) = host.shared_buffer(bytes).unwrap(); + let (readback, output) = host.shared_buffer(bytes).unwrap(); + list.shadow_state(&readback, D3D12_RESOURCE_STATE_COPY_DEST); + for (i, &(kind, words, _)) in CASES.iter().enumerate() { + let offset = (i * size_of::<[u32; 5]>()) as u64; + // SAFETY: the map has one five-dword slot per case; no GPU work is in flight. + let address = unsafe { + input.cast::<[u32; 5]>().add(i).write(words); + source.GetGPUVirtualAddress() + offset + }; + let layout = Layout::new(kind, 20, 1).unwrap(); + let prepared = prepare(&list, layout, address, None).unwrap(); + prepared.record(&list, layout, (&source, address), None); + // SAFETY: copy only the packed payload, then return the scratch to its reusable state. + unsafe { + list.list.ResourceBarrier(&[transition( + &prepared.scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.list.CopyBufferRegion( + &readback, + offset, + &prepared.scratch, + HEADER, + u64::from(layout.width), + ); + list.list.ResourceBarrier(&[transition( + &prepared.scratch, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } + list.close(); + for _ in 0..2 { + host.execute(&[&list]); + for (i, &(kind, before, expected)) in CASES.iter().enumerate() { + let words = Layout::new(kind, 20, 1).unwrap().width as usize / 4; + // SAFETY: the submission has completed; each range is within its mapped buffer. + unsafe { + assert_eq!(input.cast::<[u32; 5]>().add(i).read(), before); + assert_eq!( + std::slice::from_raw_parts(output.cast::().add(i * 5), words), + &expected[..words] + ); + } + } + } + } + + #[test] + fn ordered_budget_and_count_across_a_window_boundary() { + use super::*; + let Some(host) = host() else { return }; + const RECORDS: usize = 4101; + const STRIDE: usize = 6; + let bytes = (4 + (RECORDS - 1) * STRIDE + 4) * 4; + let list = host.new_list().unwrap(); + let (source, src) = host.shared_buffer(bytes as u64).unwrap(); + let total = HEADER as usize + RECORDS * 16; + let (readback, dst) = host.shared_buffer(total as u64).unwrap(); + // Two safe, unexecuted inputs leave room for 128 single-vertex records. + // Each record has an observable ID, including the first record of the second window. + let mut initial = vec![0xdeadbeef; bytes / 4]; + initial[1] = u32::MAX; + for i in 0..RECORDS { + let (x, y) = match i { + 0 => (1 << 24, 4), + 1 => ((1 << 24) - 32, 4), + 2 => (129, 1), + 3..=129 => (1, 1), + 130..=4095 => (0, 1), + _ => (1, 1), + }; + initial[4 + i * STRIDE..8 + i * STRIDE].copy_from_slice(&[x, y, i as u32, 93]); + } + // SAFETY: one mapped allocation of exactly bytes, no work in flight. + let base = unsafe { + std::ptr::copy_nonoverlapping(initial.as_ptr(), src.cast::(), initial.len()); + source.GetGPUVirtualAddress() + }; + let layout = Layout::new(0, 24, RECORDS as u32).unwrap(); + assert!(prepare(&list, layout, base + 2, None).is_none()); + assert!(prepare(&list, layout, base + 16, Some(base + 2)).is_none()); + let prepared = prepare(&list, layout, base + 16, Some(base + 4)).unwrap(); + prepared.record( + &list, + layout, + (&source, base + 16), + Some((&source, base + 4)), + ); + list.shadow_state(&readback, D3D12_RESOURCE_STATE_COPY_DEST); + // SAFETY: both allocations cover total, and the list owns them through the fence. + unsafe { + list.list.ResourceBarrier(&[transition( + &prepared.scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.list + .CopyBufferRegion(&readback, 0, &prepared.scratch, 0, total as u64); + list.list.ResourceBarrier(&[transition( + &prepared.scratch, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + list.close(); + let check = |count: usize| { + // SAFETY: all host submissions have finished. Only initialized dwords are read. + unsafe { + assert_eq!(dst.cast::().read(), count as u32); + for i in 0..count { + let mut expected: [u32; 4] = + initial[4 + i * STRIDE..8 + i * STRIDE].try_into().unwrap(); + if i == 2 || i >= 4097 { + expected[0] = 0; + } + assert_eq!( + dst.add(HEADER as usize).cast::<[u32; 4]>().add(i).read(), + expected, + "record {i}" + ); + } + assert_eq!( + std::slice::from_raw_parts(src.cast::().add(4), initial.len() - 4), + &initial[4..] + ); + } + }; + for count in [u32::MAX, 4097, 0, 1, u32::MAX] { + // SAFETY: the previous submission completed before this CPU write. + unsafe { + src.cast::().add(1).write(count); + } + host.execute(&[&list]); + check((count as usize).min(RECORDS)); + } + host.execute(&[&list, &list]); + check(RECORDS); + } } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7adb4e4f62..ef6e4c5d9d 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1162,19 +1162,31 @@ extern "system" fn execute_indirect( let Some((stride, args)) = crate::signature::layout(signature) else { return; }; - let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); - let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); + let address = crate::resource::buffer_bytes(arguments).and_then(|(p, size)| { + offset.is_multiple_of(4).then_some(())?; + Some(((p as u64).checked_add(offset)?, size.checked_sub(offset)?)) + }); + let counter = crate::resource::buffer_bytes(count).and_then(|(p, size)| { + (count_offset.is_multiple_of(4) && count_offset.checked_add(4)? <= size).then_some(())?; + (p as u64).checked_add(count_offset) + }); let mut ran = false; #[cfg(windows)] - if let ([[kind, ..]], Some(address)) = (args, address) + if let ([[kind, ..]], Some((address, available))) = (args, address) && (count.is_null() || counter.is_some()) { const DISPATCH: u32 = 2; const DISPATCH_SINGLE: u32 = 105; - let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; - with_state(this, |list, s| { - ran = s.execute_indirect(list, (kind, stride, max), address, counter); - }); + let kind = if *kind == DISPATCH_SINGLE { + DISPATCH + } else { + *kind + }; + if crate::indirect::Layout::new(kind, stride, max).is_some_and(|l| l.span() <= available) { + with_state(this, |list, s| { + ran = s.execute_indirect(list, (kind, stride, max), address, counter); + }); + } } else { #[cfg(all(windows, feature = "diagnostics"))] crate::pipeline::note_why(format!( @@ -1195,7 +1207,7 @@ extern "system" fn execute_indirect( stride, ?args, max, - address = ?address.map(|a| format!("{a:#x}")), + address = ?address.map(|(a, _)| format!("{a:#x}")), counted = !count.is_null(), "indirect execution dropped (first time for this signature)" ); diff --git a/crates/victory-gpu/src/pipeline/indirect_tests.rs b/crates/victory-gpu/src/pipeline/indirect_tests.rs new file mode 100644 index 0000000000..f0de90a4fc --- /dev/null +++ b/crates/victory-gpu/src/pipeline/indirect_tests.rs @@ -0,0 +1,653 @@ +use super::Pending; +use crate::draw::State; +use crate::host::{HostList, host, transition}; +use crate::object::Object; +use crate::pipeline::{FUNCTIONS, Pipeline, host::HostPipeline}; +use std::sync::{Arc, atomic::AtomicBool}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::{Fxc::D3DCompile, ID3DBlob}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{PCSTR, s}; + +const TRIANGLE: &str = r#" +[RootSignature("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)")] +float4 vs(uint id : SV_VertexID) : SV_Position { + float2 p = id == 0 ? float2(-1,-1) : (id == 1 ? float2(-1,3) : float2(3,-1)); + return float4(p, 0.5, 1); +} +[RootSignature("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)")] +float4 ps() : SV_Target { return float4(0,1,0,1); } +"#; + +fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { + let mut blob: Option = None; + let mut diagnostics: Option = None; + // SAFETY: input and output objects are live across the compile. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("triangle"), + None, + None, + entry, + target, + 0, + 0, + &mut blob, + Some(&mut diagnostics), + ) + .unwrap(); + let blob = blob.unwrap(); + std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize()).to_vec() + } +} + +// Only the two test shaders are supplied by the fixture. Root binding, indirect signatures, +// clamp, argument refresh, copy-back and queue submission run the port's implementation. +fn ready_triangle(device: &ID3D12Device) -> Box { + let vs = compile(TRIANGLE, s!("vs"), s!("vs_5_1")); + let ps = compile(TRIANGLE, s!("ps"), s!("ps_5_1")); + let bytecode = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + // SAFETY: the blobs, root and pipeline description live through the calls. + let (root, pso) = unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: bytecode(&vs), + PS: bytecode(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso = device.CreateGraphicsPipelineState(&desc).unwrap(); + (root, pso) + }; + ready(HostPipeline { + compute: false, + mesh: false, + root, + pso, + stages: Vec::new(), + slots: 0, + inputs: Vec::new(), + name: "audit triangle".to_owned(), + }) +} + +fn ready(pipeline: HostPipeline) -> Box { + let p = Pending::new(Vec::new(), None); + assert!(p.made.set(Some(pipeline)).is_ok()); + Box::new(Pipeline { + object: Object::new(&FUNCTIONS), + packet: [0; 8], + shaders: Vec::new(), + bound: AtomicBool::new(false), + host: Arc::new(p), + }) +} + +// Heap storage remains stable across moves; lists only use it within the fixture lifetime. +struct TitleBuffer(Box<[std::cell::UnsafeCell]>); + +impl TitleBuffer { + fn new(words: Vec) -> Self { + let b = Self(words.into_iter().map(std::cell::UnsafeCell::new).collect()); + crate::shadow::register(b.at(0) as usize, b.at(0), (b.0.len() * 4) as u64); + b + } + fn at(&self, word: usize) -> u64 { + self.0[word].get() as u64 + } +} + +impl Drop for TitleBuffer { + fn drop(&mut self) { + crate::shadow::unregister(self.at(0) as usize, self.at(0)); + } +} + +// Host selection is process-wide. A machine without a hardware device +// can still run the same assertions on WARP in a fresh process. +fn have_adapter() -> bool { + if host().is_some() { + return true; + } + assert!( + std::env::var_os("VICTORY_D3D12_WARP").is_none(), + "WARP device unavailable" + ); + let thread = std::thread::current(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", thread.name().unwrap(), "--nocapture"]) + .env("VICTORY_D3D12_WARP", "1") + .status() + .unwrap(); + assert!(result.success()); + false +} + +fn render( + ready: &Pipeline, + producer: Option<&HostList>, + record: impl FnOnce(&mut State, &HostList), +) -> (Vec<[u8; 4]>, D3D12_QUERY_DATA_PIPELINE_STATISTICS) { + const SIZE: u32 = 4; + let host = host().unwrap(); + let list = host.new_list().unwrap(); + let mut state = State::default(); + let fixture = (&ready.object) as *const Object; + state.reset(fixture); + state.set_topology(&list, 4); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let texture_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: SIZE.into(), + Height: SIZE, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option = None; + // SAFETY: open list and live texture and viewport descriptions. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &texture_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&D3D12_CLEAR_VALUE { + Format: texture_desc.Format, + Anonymous: D3D12_CLEAR_VALUE_0 { + Color: [0., 0., 0., 1.], + }, + }), + &mut target, + ) + .unwrap(); + } + let target = target.unwrap(); + let rtv = host.rtv(&target, None); + // SAFETY: a live RTV and an open list. + unsafe { + list.list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.list + .ClearRenderTargetView(rtv, &[0., 0., 0., 1.], None); + list.list.RSSetViewports(&[D3D12_VIEWPORT { + Width: SIZE as f32, + Height: SIZE as f32, + MaxDepth: 1., + ..Default::default() + }]); + list.list.RSSetScissorRects(&[RECT { + right: SIZE as i32, + bottom: SIZE as i32, + ..Default::default() + }]); + } + let mut query: Option = None; + let query_desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, + Count: 1, + NodeMask: 0, + }; + let (stats, mapped) = host + .shared_buffer(size_of::() as u64) + .unwrap(); + // SAFETY: the query and its destination outlive the submission. + unsafe { + host.device + .CreateQueryHeap(&query_desc, &mut query) + .unwrap(); + } + let query = query.unwrap(); + // SAFETY: a pipeline statistics query on a direct list. + unsafe { + list.list + .BeginQuery(&query, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + } + record(&mut state, &list); + list.shadow_state(&stats, D3D12_RESOURCE_STATE_COPY_DEST); + // SAFETY: the active query is ended before its result is copied. + unsafe { + list.list + .EndQuery(&query, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + list.list.ResolveQueryData( + &query, + D3D12_QUERY_TYPE_PIPELINE_STATISTICS, + 0, + 1, + &stats, + 0, + ); + } + // SAFETY: target is still in RENDER_TARGET; GPU is done before Map. + unsafe { + list.list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]) + }; + let (readback, footprint) = + crate::capture::read_back(&host.device, &list.list, &target).unwrap(); + list.close(); + if let Some(producer) = producer { + host.execute(&[producer, &list]); + } else { + host.execute(&[&list]); + } + let mut ptr = std::ptr::null_mut(); + let mut pixels = Vec::new(); + // SAFETY: the fence completed, and the footprint covers these pixels. + unsafe { + readback.Map(0, None, Some(&mut ptr)).unwrap(); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let offset = + footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize + 4 * x; + pixels.push( + ptr.cast::() + .add(offset) + .cast::<[u8; 4]>() + .read_unaligned(), + ); + } + } + readback.Unmap(0, None); + } + // SAFETY: Host::execute waited for the fence before the CPU reads the query. + let statistics = unsafe { mapped.cast::().read() }; + (pixels, statistics) +} + +const GREEN: [u8; 4] = [0, 255, 0, 255]; + +#[test] +fn audit_render_indirect() { + if !have_adapter() { + return; + } + const RECORDS: usize = 2048; + let fixture = ready_triangle(&host().unwrap().device); + let untranslated = crate::pipeline::shader("vertex", b"fixture with no translatable shader"); + let mut rejected = std::ptr::null(); + assert_eq!( + crate::pipeline::hand_out( + vec![untranslated], + Some(Box::default()), + &crate::pipeline::PIPELINE_IIDS[0], + &mut rejected + ), + crate::object::S_OK + ); + assert!(crate::pipeline::host_pipeline(rejected).is_none()); + for (name, counted, populated) in [ + ("omit inactive batch", None, true), + ("count=0, empty tail", Some(true), false), + ("count=0, populated tail", Some(true), true), + ("rejected pipeline, empty tail", Some(false), false), + ("rejected pipeline, populated tail", Some(false), true), + ] { + let mut words = vec![0; 4 * (RECORDS + 1) + 1]; + if populated { + words[..4 * RECORDS] + .as_chunks_mut::<4>() + .0 + .fill([512, 128, 0, 0]); + } + words[4 * RECORDS..4 * (RECORDS + 1)].copy_from_slice(&[3, 1, 0, 0]); + let args = TitleBuffer::new(words); + let (pixels, stats) = render(&fixture, None, |state, list| { + let sig = (0, 16, RECORDS as u32); + match counted { + Some(true) => assert!(state.execute_indirect( + list, + sig, + args.at(0), + Some(args.at(4 * (RECORDS + 1))) + )), + Some(false) => { + state.set_pipeline(rejected); + assert!(!state.execute_indirect(list, sig, args.at(0), None)); + state.set_pipeline(&fixture.object); + } + None => {} + } + assert!(state.execute_indirect(list, (0, 16, 1), args.at(4 * RECORDS), None)); + }); + let verts = stats.IAVertices; + let green = pixels.iter().filter(|p| **p == GREEN).count(); + eprintln!("{name}: {green}/16 green, {verts} vertices"); + assert_eq!((green, verts), (16, 3), "{name}"); + } + crate::pipeline::release(rejected); +} + +/// A producer runs after the CPU refresh. Reading the count on the CPU would get zero. +fn gpu_store(list: &HostList, at: u64, value: u32) { + const PRODUCER: &str = r#" + RWByteAddressBuffer dest : register(u0); + cbuffer Params : register(b0) { uint offset; uint value; }; + [RootSignature("UAV(u0), RootConstants(num32BitConstants=2,b0)")] + [numthreads(1,1,1)] void main() { dest.Store(offset, value); }"#; + let host = host().unwrap(); + let code = compile(PRODUCER, s!("main"), s!("cs_5_1")); + let shadow = crate::shadow::find(at, 4).unwrap(); + shadow.refresh(list, at, 4); + shadow.gpu_writes(list, at, 4); + list.shadow_state(&shadow.buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + // SAFETY: live shader, root and destination. The list retains its bindings. + unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).unwrap(); + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .unwrap(); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .SetComputeRootUnorderedAccessView(0, shadow.buffer.GetGPUVirtualAddress()); + let constants = [shadow.offset(at) as u32, value]; + list.list + .SetComputeRoot32BitConstants(1, 2, constants.as_ptr().cast(), 0); + list.list.Dispatch(1, 1, 1); + list.keep(&root); + list.keep(&pso); + } +} + +#[test] +fn counted_prefix_draws_exactly_the_live_records() { + if !have_adapter() { + return; + } + let fixture = ready_triangle(&host().unwrap().device); + for (name, count, max, producer, separate, zero_tail, expected) in [ + ("partially filled", Some(2), 4, false, false, true, 9), + ( + "live prefix with drawable tail", + Some(1), + 4, + false, + true, + false, + 3, + ), + ( + "GPU count in argument buffer", + Some(2), + 4, + true, + false, + false, + 9, + ), + ( + "GPU count in separate buffer", + Some(3), + 4, + true, + true, + false, + 21, + ), + ("count equals maximum", Some(4), 4, false, false, false, 45), + ("count above maximum", Some(9), 2, false, false, false, 9), + ("uncounted", None, 3, false, false, false, 21), + ("zero maximum", Some(4), 0, false, false, false, 0), + ] { + // Count at +4 and arguments at +20. Padded 24-byte source stride, + // with only the 16-byte payload present at the end of the buffer. + let initial = if producer { 0 } else { count.unwrap_or(0) }; + let mut words = vec![0; 5 + 3 * 6 + 4]; + words[1] = initial; + for i in 0..4 { + if !zero_tail || i < 2 { + words[5 + i * 6..9 + i * 6].copy_from_slice(&[3, 1 << i, 0, 0]); + } + } + let args = TitleBuffer::new(words); + let external = TitleBuffer::new(vec![0, 0, 0, initial]); + let at = if separate { external.at(3) } else { args.at(1) }; + let (_, stats) = render(&fixture, None, |state, list| { + if producer { + gpu_store(list, at, count.unwrap()); + } + assert!(state.execute_indirect(list, (0, 24, max), args.at(5), count.map(|_| at))); + }); + let vertices = stats.IAVertices; + eprintln!("{name}: {vertices} vertices"); + assert_eq!(vertices, expected, "{name}"); + } +} + +fn ready_compute() -> Box { + let code = compile( + r#"[RootSignature("")] [numthreads(2,1,1)] void main() {}"#, + s!("main"), + s!("cs_5_1"), + ); + let device = &host().unwrap().device; + // SAFETY: the shader and its embedded root signature live through creation. + let (root, pso) = unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code).unwrap(); + let pso = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .unwrap(); + (root, pso) + }; + let shader = crate::pipeline::shader("compute", &code); + shader.translated.get_or_init(|| { + Some(crate::pipeline::Translated { + host: victory_shader::emit::HostShader { + stage: victory_shader::native::HwStage::Cs, + dxil: code, + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![], + }, + used: vec![victory_shader::UsedResource { + kind: victory_shader::ResourceType::Cbv, + root: victory_shader::RootType::Table, + slot: 0, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + }], + }) + }); + ready(HostPipeline { + root, + pso, + compute: true, + mesh: false, + stages: vec![crate::pipeline::host::Stage { + shader, + user_data: None, + root_cbvs: vec![], + root_srvs: vec![], + }], + slots: 0, + inputs: vec![], + name: "audit compute".to_owned(), + }) +} + +#[test] +fn dispatch_restores_the_title_compute_pipeline() { + if !have_adapter() { + return; + } + let pipeline = ready_compute(); + let args = TitleBuffer::new(vec![1, 3, 1, 1, 9, 1, 1]); + let (_, stats) = render(&pipeline, None, |state, list| { + assert!(state.execute_indirect(list, (2, 12, 2), args.at(1), Some(args.at(0)))); + state.dispatch(list, 1, 1, 1); + }); + // One 64-thread clamp group, three indirect title groups, one direct title group. + assert_eq!(stats.CSInvocations, 64 + (3 + 1) * 2); +} + +#[test] +fn a_failed_descriptor_bind_leaves_the_next_draw_its_budget() { + if !have_adapter() { + return; + } + let triangle = ready_triangle(&host().unwrap().device); + let compute = ready_compute(); + // A shader-visible view heap with one guest descriptor and no placement address. + let desc = [0u32, 1, 1, 0, 0, 0, 0, 0]; + let mut handle = std::ptr::null(); + assert_eq!( + crate::descriptor::create_heap( + std::ptr::null(), + desc.as_ptr().cast(), + &crate::resource::PAGEABLE_IIDS[0], + &mut handle + ), + crate::object::S_OK + ); + let heap = crate::descriptor::heap(handle); + let slots = heap.host().unwrap(); + while slots.dynamic(4096).is_some() {} + while slots.dynamic(1).is_some() {} + let dispatches = TitleBuffer::new([1024, 1, 1].repeat(2048)); + let draw = TitleBuffer::new(vec![3, 1, 0, 0]); + let (pixels, stats) = render(&triangle, None, |state, list| { + state.set_pipeline(&compute.object); + state.set_heaps(&[handle]); + state.set_table(true, 0, heap.start); + assert!(!state.execute_indirect(list, (2, 12, 2048), dispatches.at(0), None)); + state.set_heaps(&[]); + state.set_pipeline(&triangle.object); + assert!(state.execute_indirect(list, (0, 16, 1), draw.at(0), None)); + }); + crate::object::release_boxed::(handle); + assert_eq!(pixels, [GREEN; 16]); + assert_eq!(stats.IAVertices, 3); + assert_eq!(stats.CSInvocations, 64); // only the successful draw's clamp +} + +#[test] +fn a_prior_list_can_produce_both_arguments_and_count() { + if !have_adapter() { + return; + } + let host = host().unwrap(); + let fixture = ready_triangle(&host.device); + let args = TitleBuffer::new(vec![0, 1, 0, 0, 3, 8, 0, 0]); + let count = TitleBuffer::new(vec![0]); + let producer = host.new_list().unwrap(); + gpu_store(&producer, args.at(0), 3); + gpu_store(&producer, count.at(0), 1); + producer.close(); + let (pixels, stats) = render(&fixture, Some(&producer), |state, list| { + assert!(state.execute_indirect(list, (0, 16, 2), args.at(0), Some(count.at(0)))); + }); + assert_eq!(pixels, [GREEN; 16]); + assert_eq!(stats.IAVertices, 3); +} + +#[test] +fn switches_between_draw_indexed_compute_and_draw() { + if !have_adapter() { + return; + } + let triangle = ready_triangle(&host().unwrap().device); + let compute = ready_compute(); + let draw = TitleBuffer::new(vec![3, 1, 0, 0]); + let indexed = TitleBuffer::new(vec![3, 1, 1, (-1i32) as u32, 0]); + let dispatch = TitleBuffer::new(vec![2, 1, 1]); + let indices = TitleBuffer::new(vec![19, 1, 2, 3]); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: indices.at(0), + SizeInBytes: 16, + Format: DXGI_FORMAT_R32_UINT, + }; + // SAFETY: both views are repr(C) with the same three integer fields in the same order. + let view: crate::draw::IndexView = unsafe { std::mem::transmute(view) }; + let (pixels, stats) = render(&triangle, None, |state, list| { + assert!(!state.execute_indirect(list, (1, 20, 1), indexed.at(0), None)); + state.set_index_buffer(Some(&view)); + assert!(state.execute_indirect(list, (1, 20, 1), indexed.at(0), None)); + state.set_pipeline(&compute.object); + assert!(!state.execute_indirect(list, (0, 16, 1), draw.at(0), None)); + assert!(state.execute_indirect(list, (2, 12, 1), dispatch.at(0), None)); + state.set_pipeline(&triangle.object); + assert!(state.execute_indirect(list, (0, 16, 1), draw.at(0), None)); + assert!(!state.execute_indirect(list, (10, 12, 1), dispatch.at(0), None)); + }); + assert_eq!(pixels, [GREEN; 16]); + assert_eq!(stats.IAVertices, 6); + assert_eq!(stats.CSInvocations, 3 * 64 + 4); +} + +#[test] +fn parallel_lists_use_independent_counts_and_arguments() { + if !have_adapter() { + return; + } + let barrier = std::sync::Barrier::new(2); + std::thread::scope(|scope| { + for active in [1, 2] { + let barrier = &barrier; + scope.spawn(move || { + let fixture = ready_triangle(&host().unwrap().device); + let args = TitleBuffer::new(vec![active, 3, 1, 0, 0, 3, 2, 0, 0]); + let (pixels, stats) = render(&fixture, None, |state, list| { + assert!(state.execute_indirect(list, (0, 16, 2), args.at(1), Some(args.at(0)))); + barrier.wait(); + }); + assert_eq!(pixels, [GREEN; 16]); + assert_eq!(stats.IAVertices, if active == 1 { 3 } else { 9 }); + }); + } + }); +} diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 6ffc032877..8807dfbc27 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -236,3 +236,7 @@ mod tests { assert!(matches!(p.made.get(), Some(None))); } } + +#[cfg(all(test, feature = "diagnostics"))] +#[path = "indirect_tests.rs"] +mod indirect_tests;