diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index cc62dd5..c87e5ae 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -113,7 +113,7 @@ impl TableGroup { } /// A root argument as the title set it. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, PartialEq)] enum Root { #[default] None, @@ -125,7 +125,7 @@ enum Root { } #[repr(C)] -#[derive(Debug, Clone, Copy, Default)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] pub(crate) struct VertexView { address: u64, size: u32, @@ -133,7 +133,7 @@ pub(crate) struct VertexView { } #[repr(C)] -#[derive(Debug, Clone, Copy, Default)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] pub(crate) struct IndexView { address: u64, size: u32, @@ -558,6 +558,8 @@ pub(crate) struct State { /// This recording, for [`crate::descriptor::host::HostHeap::make_listed`] /// (0: it has none yet). recording: u64, + /// See [`State::rebinds`]. + rebinds: [u64; 2], } impl Drop for State { @@ -972,14 +974,21 @@ macro_rules! once { }}; } -fn set(roots: &mut Vec, slot: u32, root: Root) { +/// Sets root argument `slot`: whether that changed it. +fn set(roots: &mut Vec, slot: u32, root: Root) -> bool { let slot = slot as usize; if roots.len() <= slot { roots.resize(slot + 1, Root::None); } + let changed = roots[slot] != root; roots[slot] = root; + changed } +/// [`State::rebinds`]'s counts: of root constants, of the rest. +const CONSTANTS: usize = 0; +const OTHERS: usize = 1; + /// The pass over the buffer views of `heap` that shaders pick by index /// ([`State::heap_buffers`]): their host slots are made, and the host copies /// they show are to be refreshed. @@ -1168,17 +1177,33 @@ impl State { } pub(crate) fn set_pipeline(&mut self, pipeline: This) { + self.rebound(OTHERS, self.pipeline != pipeline as usize); self.pipeline = pipeline as usize; } pub(crate) fn set_heaps(&mut self, heaps: &[This]) { - self.heaps = [0; 2]; + let was = std::mem::take(&mut self.heaps); for &h in heaps { if !h.is_null() { let samplers = crate::descriptor::heap(h).samplers(); self.heaps[usize::from(samplers)] = h as usize; } } + self.rebound(OTHERS, was != self.heaps); + } + + /// The title changed (`changed`) what the next draw or dispatch binds: + /// root constants ([`CONSTANTS`]) or the rest ([`OTHERS`]). + fn rebound(&mut self, what: usize, changed: bool) { + self.rebinds[what] += u64::from(changed); + } + + /// The times the title changed what the next draw or dispatch binds: + /// root constants, and the rest (pipeline, heaps, tables, root views, + /// vertex and index buffers). Setting what is set changes nothing + /// ([`crate::indirect::merge`]). + pub(crate) fn rebinds(&self) -> [u64; 2] { + self.rebinds } fn roots(&mut self, compute: bool) -> &mut Vec { @@ -1190,44 +1215,58 @@ impl State { } pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) { - set(self.roots(compute), slot, Root::Table(handle)); + let changed = set(self.roots(compute), slot, Root::Table(handle)); + self.rebound(OTHERS, changed); } pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) { - set(self.roots(compute), slot, Root::View(address)); + let changed = set(self.roots(compute), slot, Root::View(address)); + self.rebound(OTHERS, changed); } pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) { let roots = self.roots(compute); let s = slot as usize; + let mut changed = false; if !matches!(roots.get(s), Some(Root::Constants(_))) { - set(roots, slot, Root::Constants(Vec::new())); + changed = set(roots, slot, Root::Constants(Vec::new())); } if let Root::Constants(c) = &mut roots[s] { let end = offset as usize + values.len(); if c.len() < end { c.resize(end, 0); + changed = true; } + changed |= c[offset as usize..end] != *values; c[offset as usize..end].copy_from_slice(values); } + self.rebound(CONSTANTS, changed); } pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) { + let mut changed = false; for (i, v) in views.iter().enumerate() { if let Some(slot) = self.vertex.get_mut(start as usize + i) { + changed |= *slot != *v; *slot = *v; } } + self.rebound(OTHERS, changed); } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + let mut changed = false; for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + changed |= *slot != VertexView::default(); *slot = VertexView::default(); } + self.rebound(OTHERS, changed); } pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { - self.index = view.copied().unwrap_or_default(); + let index = view.copied().unwrap_or_default(); + self.rebound(OTHERS, self.index != index); + self.index = index; } /// Render targets and depth, set on the host list at once, unless it has @@ -4507,7 +4546,9 @@ impl State { } /// Where the clamped record of `kind` at `arguments` of the copy `args` - /// is, from the open batch or a new one ([`batches`]). `None` if it + /// is, from the open batch or a new one ([`batches`]): the scratch + /// buffer, the offset, the step between records there (a slot), and + /// whether the pass of a new batch was recorded for it. `None` if it /// cannot be clamped in one. fn batched( &mut self, @@ -4515,7 +4556,8 @@ impl State { args: &std::sync::Arc, arguments: u64, kind: u32, - ) -> Option<(ID3D12Resource, u64)> { + ) -> Option<(ID3D12Resource, u64, u32, bool)> { + const SLOT: u32 = crate::indirect::batch::SLOT; const BATCH_USE: usize = usize::MAX - 0x78; const DISPATCH: u32 = 2; // Another host list, or this one after its reset ([`windows`]). @@ -4530,15 +4572,17 @@ impl State { if let Some(b) = &mut self.batch && let Some(at) = b.table.place(id, offset, kind) { - return Some((b.scratch.clone(), at)); + return Some((b.scratch.clone(), at, SLOT, false)); } self.batch = None; + // What is held back runs before the new batch's pass. + unsettle_indirect(list); let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?; self.host_pipeline = 0; self.host_roots[1] = 0; let at = table.place(id, offset, kind)?; self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false }); - Some((scratch, at)) + Some((scratch, at, SLOT, true)) } /// Indirect execution of a one-argument signature of `kind` (PC @@ -4664,8 +4708,10 @@ impl State { .as_ref() .filter(|w| same(w) && offset >= w.base) .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) - .map(|w| (w.scratch.clone(), offset - w.base)); - let (bounded, at) = match batch.or(hit) { + .map(|w| (w.scratch.clone(), offset - w.base, w.step, false)); + // The scratch buffer, the record's offset there, the step to the + // next record there, and whether a clamp pass was recorded for it. + let (bounded, at, step, clamped) = match batch.or(hit) { Some(hit) => hit, None => { // A record a short step after the last window's last one @@ -4695,7 +4741,8 @@ impl State { } // Bounded first: the clamp binds a compute pipeline of its // own and copies clamped active records into a scratch - // buffer at offset 0. + // buffer at offset 0. What is held back runs before it. + unsettle_indirect(list); let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); // More than the record asked for: a window clamped ahead, // whose unfilled slots must not spend the list's budget. @@ -4720,43 +4767,108 @@ impl State { records, scratch: bounded.clone(), }); - (bounded, 0) + (bounded, 0, step, true) } }; - let ran = match kind { - DRAW | INDEXED => self.prepare(list, kind == INDEXED), - MESH => self.prepare_for(list, false, true), - DISPATCH => self.bind(list, p, true), - _ => false, + // Joined to the run before it, or weighed for the frame line + // (`crate::indirect::merge`). + use crate::indirect::merge; + let call = merge::Call { + calls: list.title_calls(), + rebinds: self.rebinds(), + kind, + pipeline: p.pso.as_raw() as usize, + single: max == 1 && count.is_none(), + alone: crate::pipeline::is_builder(self.pipeline as This) || kind == MESH && mesh_test() == 2, + clamped, + epoch: list.epoch(), + buffer: bounded.as_raw() as usize, + at, + step, }; - if !ran { - why("prepare failed"); - return false; + let joining = merge::on(); + let verdict; + let joined = { + let mut run = list.indirect_run(); + verdict = merge::verdict(run.as_ref().map(|(r, _)| r), &call); + // One record more for the execution held back, recorded with a + // signature of the run's step; this one's binding would be the + // same as the run's. + let joined = verdict == merge::Verdict::Joins + && joining + && match run.as_mut() { + Some((r, Some(held))) => match host_signature(kind, r.step) { + Some(signature) => { + held.signature = signature; + r.join(&call, call.epoch); + true + } + None => false, + }, + _ => false, + }; + if !joined { + // What is held back runs before this binding; a binding + // that fails halfway leaves the list as no run's. + list.record_held(&mut run); + if let Some((r, _)) = run.as_mut() { + r.settled = false; + } + } + joined + }; + merge::count(verdict, joined); + if !joined { + let ran = match kind { + DRAW | INDEXED => self.prepare(list, kind == INDEXED), + MESH => self.prepare_for(list, false, true), + DISPATCH => self.bind(list, p, true), + _ => false, + }; + if !ran { + why("prepare failed"); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) + }); + let epoch = list.epoch(); + if joining && call.single && !call.alone { + // Held back for the next ones to join. + *list.indirect_run() = Some(( + merge::Run::of(&call, epoch), + Some(merge::Held { signature: signature.clone(), buffer: bounded.clone() }), + )); + list.hold_indirect(); + } else { + if kind == MESH { + self.mesh_scissor(list, true); + } + // SAFETY: an open list with everything set; the scratch buffer and + // host copies are kept alive by the list, and the signature is cached. + unsafe { + list.list.ExecuteIndirect( + &signature, + max, + &bounded, + at, + counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + ) + }; + if kind == MESH { + self.mesh_scissor(list, false); + } + let mut run = list.indirect_run(); + match run.as_mut() { + Some((r, _)) if verdict == merge::Verdict::Joins => r.join(&call, epoch), + _ => *run = Some((merge::Run::of(&call, epoch), None)), + } + } } #[cfg(feature = "diagnostics")] - list.note_op(|| { - self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) - }); - #[cfg(feature = "diagnostics")] list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user); - if kind == MESH { - self.mesh_scissor(list, true); - } - // SAFETY: an open list with everything set; the scratch buffer and - // host copies are kept alive by the list, and the signature is cached. - unsafe { - list.list.ExecuteIndirect( - &signature, - max, - &bounded, - at, - counter.as_ref().map(|(s, _)| &s.buffer), - counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), - ) - }; - if kind == MESH { - self.mesh_scissor(list, false); - } if kind == DISPATCH { self.buffers_written(); } else { @@ -4774,6 +4886,17 @@ impl State { } } +/// Before something is recorded into `list` for an indirect execution (a +/// clamp pass, a binding): the execution held back is recorded first, and +/// the list's run is no longer one the next execution can join without +/// binding again ([`crate::indirect::merge`]). +fn unsettle_indirect(list: &HostList) { + list.flush_indirect(); + if let Some((run, _)) = list.indirect_run().as_mut() { + run.settled = false; + } +} + /// `DispatchX`: the counts are threads (the console's dispatch initiator bit /// "use thread dimensions"; DexNom/VIctory bc3cd4b0). Taken for groups, a /// rehydration stage of the structure builder ran up to 64 times its threads diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9f04e85..09404e3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1210,6 +1210,13 @@ pub(crate) struct HostList { /// depends on ([`HostList::changed_something`]); no two lists have the /// same. epoch: std::sync::atomic::AtomicU64, + /// The title calls that may record into the list ([`HostList::title_call`]). + title_calls: std::sync::atomic::AtomicU64, + /// The run of indirect executions the list's last one belongs to + /// ([`crate::indirect::merge`]), and its execution if it is held back. + indirect_run: Mutex)>>, + /// Whether an execution is held back. + holding: std::sync::atomic::AtomicBool, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -4118,6 +4125,9 @@ impl Host { batch_args: Mutex::default(), coming: Mutex::default(), epoch: std::sync::atomic::AtomicU64::new(next_epoch()), + title_calls: std::sync::atomic::AtomicU64::new(0), + indirect_run: Mutex::default(), + holding: std::sync::atomic::AtomicBool::new(false), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -6279,6 +6289,7 @@ impl HostList { pub(crate) fn close(&self) { let _closing = crate::timeline::span("closing a host list"); + self.flush_indirect(); self.twins_to_depth(); self.textures_back(); let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); @@ -6331,6 +6342,8 @@ impl HostList { /// for). pub(crate) fn reset(&self) { self.changed_something(); + self.holding.store(false, Ordering::Relaxed); + *self.indirect_run.lock().unwrap_or_else(|e| e.into_inner()) = None; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); let _resetting = crate::timeline::span("resetting a host list"); @@ -6378,6 +6391,53 @@ impl HostList { self.epoch.load(Ordering::Relaxed) } + /// A title call that may record into the list (all but indirect + /// executions and calls that only change what the next draw or dispatch + /// binds, `crate::list`): the indirect execution held back, if one is, + /// is recorded first ([`crate::indirect::merge`]). + pub(crate) fn title_call(&self) { + self.title_calls.fetch_add(1, Ordering::Relaxed); + self.flush_indirect(); + } + + /// The title calls recorded into the list so far. + pub(crate) fn title_calls(&self) -> u64 { + self.title_calls.load(Ordering::Relaxed) + } + + /// Records the indirect execution held back, if one is: before + /// anything else is recorded into the list. + pub(crate) fn flush_indirect(&self) { + if self.holding.load(Ordering::Relaxed) { + self.record_held(&mut self.indirect_run()); + } + } + + /// As [`HostList::flush_indirect`], with the list's run in hand. + pub(crate) fn record_held( + &self, + run: &mut Option<(crate::indirect::merge::Run, Option)>, + ) { + if let Some((run, held)) = run.as_mut() + && let Some(held) = held.take() + { + self.holding.store(false, Ordering::Relaxed); + held.record(&self.list, run); + } + } + + /// The list's run of indirect executions ([`crate::indirect::merge`]). + pub(crate) fn indirect_run( + &self, + ) -> std::sync::MutexGuard<'_, Option<(crate::indirect::merge::Run, Option)>> { + self.indirect_run.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The list's run holds its execution back from here on. + pub(crate) fn hold_indirect(&self) { + self.holding.store(true, Ordering::Relaxed); + } + /// Whether any deferred steps or texture state transitions have been /// recorded into this list since creation or its last [`HostList::reset`]. pub(crate) fn has_recorded_work(&self) -> bool { @@ -8754,6 +8814,7 @@ impl Meter { tracing::info!( "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame; {refused:.2} indirect records a frame ran empty for want of their list's budget (2^27), the largest cost of one {biggest} (0: under 2^22)" ); + crate::indirect::merge::line(frames); crate::shadow::exact_line(frames); crate::descriptor::sync_line(frames); late_line(frames); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index e50f572..4670740 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -41,6 +41,7 @@ use windows::core::s; use crate::host::{HostList, host, transition}; pub(crate) mod batch; +pub(crate) mod merge; const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" @@ -3262,6 +3263,101 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { } } + /// Runs of executions joined ([`merge`]): a run held back is recorded + /// by the next title call before anything else, and by the list's close + /// at the latest, as one execution of its records a batch's slots apart + /// with a signature of that stride; each record runs once. With the + /// debug layer on, nothing recorded is invalid. + #[test] + fn host_list_records_held_runs() { + let Some(host) = super::host() else { + return; + }; + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + let one = one_argument(&host.device, 2, 12); + let joined = one_argument(&host.device, 2, batch::SLOT); + let Some((source, ptr)) = host.shared_buffer(1024) else { + return; + }; + // Dispatch records 32 bytes apart, of 1 to 8 groups. + for i in 0..8u32 { + for (w, word) in [i + 1, 1, 1].into_iter().enumerate() { + // SAFETY: inside the mapping. + unsafe { ptr.cast::().add(i as usize * 8 + w).write_volatile(word) }; + } + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: a live buffer; the mapping holds 256 bytes and nothing runs. + let hits_gpu = unsafe { + std::ptr::write_bytes(hits_ptr, 0, 256); + hits_buf.GetGPUVirtualAddress() + }; + let (mut table, scratch) = open_batch(&list, (1, &source), &[(1, source.clone())]).unwrap(); + // SAFETY: an open list; the worker's root signature and pipeline; + // buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + } + let call = |calls, at| merge::Call { + calls, + rebinds: [0; 2], + kind: 2, + pipeline: 1, + single: true, + alone: false, + clamped: false, + epoch: 0, + buffer: scratch.as_raw() as usize, + at, + step: batch::SLOT, + }; + // Records 0 to 2 held as one run, then 3 and 4. + for records in [0..3u64, 3..5] { + let calls = list.title_calls(); + for r in records.clone() { + let at = table.place(1, r * 32, 2).unwrap(); + let mut run = list.indirect_run(); + if r == records.start { + *run = Some(( + merge::Run::of(&call(calls, at), 0), + Some(merge::Held { signature: one.clone(), buffer: scratch.clone() }), + )); + drop(run); + list.hold_indirect(); + continue; + } + let Some((held_run, Some(held))) = run.as_mut() else { + panic!("the run is held"); + }; + assert_eq!(merge::verdict(Some(held_run), &call(calls, at)), merge::Verdict::Joins); + held_run.join(&call(calls, at), 0); + held.signature = joined.clone(); + } + if records.start == 0 { + list.title_call(); + assert_eq!(list.title_calls(), calls + 1); + assert!(list.indirect_run().as_ref().is_some_and(|(r, held)| r.records == 3 && held.is_none())); + } + } + list.close(); + assert!(list.indirect_run().as_ref().is_some_and(|(r, held)| r.records == 2 && held.is_none())); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + assert!(list.indirect_run().is_none()); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, 1 + 2 + 3 + 4 + 5, "every record of both runs runs once"); + } + /// What clamps of a frame cost on the card one by one and in batches /// (ignored: a measurement): 2,355 executions of an empty dispatch, in /// 49 lists' worth of runs, as in the captured frame. @@ -3406,6 +3502,12 @@ void work() { /// The same between two waits for every earlier shader write, as /// the clamp records them. ComputeWithWaits, + /// Nothing, and each draw an indirect execution of one record (the + /// records a batch's slots apart, as the layer runs the title's). + Indirect, + /// The same records in one indirect execution of them all + /// (`super::merge`'s joining). + Joined, } struct Rig { @@ -3432,6 +3534,10 @@ void work() { depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, stamps: ID3D12QueryHeap, back: ID3D12Resource, + /// [`DRAWS`] draw records of one triangle, [`super::batch::SLOT`] + /// bytes apart, and a draw signature of that stride. + records: ID3D12Resource, + signature: ID3D12CommandSignature, card: String, } @@ -3656,6 +3762,41 @@ void work() { D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, ); + let slot = super::batch::SLOT; + let records = buffer( + &device, + u64::from(DRAWS) * u64::from(slot), + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let mut data = std::ptr::null_mut(); + records.Map(0, None, Some(&mut data)).ok()?; + for i in 0..DRAWS as usize { + // Three vertices, one instance, from 0. + for (w, word) in [3u32, 1, 0, 0].into_iter().enumerate() { + data.cast::().add(i * slot as usize / 4 + w).write(word); + } + } + records.Unmap(0, None); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let mut signature: Option = None; + device + .CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: slot, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }, + None::<&ID3D12RootSignature>, + &mut signature, + ) + .ok()?; + let signature = signature?; let mut stamps: Option = None; device .CreateQueryHeap( @@ -3740,6 +3881,8 @@ void work() { depth_tested, stamps, back, + records, + signature, card, }; rig.finish(); @@ -3853,10 +3996,21 @@ void work() { } l.SetPipelineState(&self.pipelines[0]); } + Between::Indirect | Between::Joined => {} + } + match between { + Between::Indirect => { + let at = u64::from(drawn % DRAWS) * u64::from(super::batch::SLOT); + l.ExecuteIndirect(&self.signature, 1, &self.records, at, None, 0); + } + Between::Joined => {} + _ => l.DrawInstanced(3, 1, 0, 0), } - l.DrawInstanced(3, 1, 0, 0); drawn += 1; } + if between == Between::Joined { + l.ExecuteIndirect(&self.signature, DRAWS / lists, &self.records, 0, None, 0); + } if part + 1 < lists { // The next list of the batch: this one is sent on // its own and the list is opened again at once @@ -3910,6 +4064,8 @@ void work() { ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ("(j) nothing changes, each draw an indirect execution of one record", Between::Indirect, 1), + ("(k) the same records in one indirect execution of them all", Between::Joined, 1), ]; let mut least = Vec::new(); for (name, between, lists) in variants { diff --git a/crates/victory-gpu/src/indirect/merge.rs b/crates/victory-gpu/src/indirect/merge.rs new file mode 100644 index 0000000..2df5b16 --- /dev/null +++ b/crates/victory-gpu/src/indirect/merge.rs @@ -0,0 +1,388 @@ +//! Indirect executions joined (`VICTORY_INDIRECT_MERGE=1`, off by default): +//! an execution of one record that comes right after another on the same +//! host list is recorded with it, as one `ExecuteIndirect` of more records, +//! when nothing could tell the two apart: +//! +//! - no title call that records into the list came between them (a draw, +//! a barrier, a copy, a target or viewport set), and the calls between +//! them that set what the next draw or dispatch binds (pipeline, heaps, +//! root constants, tables and views, vertex and index buffers: recorded +//! only at that binding) set what was set +//! ([`crate::draw::State::rebinds`]); +//! - neither has a count buffer, and each asks for one record (the title's +//! records with a count are clamped one execution at a time, by a pass +//! that writes the count the host reads: two would need a pass of their +//! own that adds the counts); +//! - the same kind and host pipeline; +//! - its record needed no clamp pass of its own (it was placed in an open +//! batch, or found in a window clamped ahead): a pass recorded for it +//! would run before the executions held back; +//! - the binding of the run's last execution left the list's epoch +//! ([`crate::host::HostList::epoch`]) where it found it, and nothing moved +//! it since: no texture changed state, no twin was written, nothing was +//! refreshed or copied, so binding again would record the same state; +//! - its record lies right after the run's last in the same scratch buffer, +//! the run's step apart (a window's step, or a batch's slot). The run is +//! recorded with a signature of that stride. +//! +//! The run's execution is held back ([`Held`]) until the list records +//! anything else: every title call that may record into the list, the +//! list's close, and the clamp passes and bindings of later executions +//! record it first ([`crate::host::HostList::flush_indirect`]). An +//! execution that joins records nothing: not its binding (as above, the +//! same), not the execution. +//! +//! shortcut: what a binding reads when it is recorded (descriptors copied +//! into host slots, title memory refreshed by address) is for a joined +//! execution as the run's first found it; the title's processor could have +//! written it between the two calls (on the console the card reads it when +//! the commands run, for both). +//! +//! The counters run with the switch off too: the frame line says how many +//! executions could have joined the one before them, and what kept the +//! others apart. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; + +/// Whether executions are joined (`VICTORY_INDIRECT_MERGE=1`). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_MERGE").is_some_and(|v| v == "1")) +} + +/// An indirect execution as the joining weighs it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Call { + /// The list's title calls before it ([`crate::host::HostList::title_calls`]). + pub(crate) calls: u64, + /// The title's changes of the binding before it, of root constants and + /// of the rest ([`crate::draw::State::rebinds`]). + pub(crate) rebinds: [u64; 2], + /// PC numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch. + pub(crate) kind: u32, + /// The host pipeline (its object's address). + pub(crate) pipeline: usize, + /// One record and no count buffer. + pub(crate) single: bool, + /// Kept alone whatever comes before or after it: structure builders, + /// and mesh dispatches under `VICTORY_MESH_TEST=scissor` (scissors set + /// around each). + pub(crate) alone: bool, + /// A clamp pass was recorded for its record (its own, a window's or a + /// batch's that it opened). + pub(crate) clamped: bool, + /// The list's epoch before its binding. + pub(crate) epoch: u64, + /// The scratch buffer its record is in (the object's address), the + /// record's offset there, and the bytes from one record to the next + /// there. + pub(crate) buffer: usize, + pub(crate) at: u64, + pub(crate) step: u32, +} + +/// Executions recorded as one, or that could have been: the joining's +/// view of a list's last indirect executions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Run { + pub(crate) kind: u32, + pub(crate) pipeline: usize, + pub(crate) single: bool, + pub(crate) alone: bool, + pub(crate) buffer: usize, + /// The first record's offset, the step between records, and the + /// records. + pub(crate) at: u64, + pub(crate) step: u32, + pub(crate) records: u32, + /// The list's title calls, the title's changes of the binding, and the + /// list's epoch, after the last execution. + pub(crate) calls: u64, + pub(crate) rebinds: [u64; 2], + pub(crate) epoch: u64, + /// The last execution's binding left the epoch where it found it. + pub(crate) settled: bool, +} + +impl Run { + /// A run of `call` alone, which left the list's epoch at `epoch`. + pub(crate) fn of(call: &Call, epoch: u64) -> Run { + Run { + kind: call.kind, + pipeline: call.pipeline, + single: call.single, + alone: call.alone, + buffer: call.buffer, + at: call.at, + step: call.step, + records: 1, + calls: call.calls, + rebinds: call.rebinds, + epoch, + settled: epoch == call.epoch, + } + } + + /// `call` (which [`Verdict::Joins`] it) is the run's last execution + /// now; its binding left the epoch at `epoch` (its call's own when it + /// was not bound again). + pub(crate) fn join(&mut self, call: &Call, epoch: u64) { + self.records += 1; + self.calls = call.calls; + self.rebinds = call.rebinds; + self.settled = epoch == call.epoch; + self.epoch = epoch; + } + + /// Where the next record of the run would be. + pub(crate) fn next(&self) -> u64 { + self.at + u64::from(self.records) * u64::from(self.step) + } +} + +/// Whether an execution joins a list's run, and if not, why. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Verdict { + Joins, + /// The first indirect execution of the list (since its reset). + First, + /// A title call that records into the list came between. + Between, + /// It or the run has a count buffer or more than one record. + Counted, + /// It or the run is kept alone ([`Call::alone`]). + Alone, + /// Another kind of execution, or another pipeline. + Differs, + /// A clamp pass was recorded for it. + Clamped, + /// The title changed the binding between (pipeline, heaps, tables, + /// views, buffers). + Rebound, + /// The title changed root constants between, and nothing else of the + /// binding (a signature that sets root constants per record could + /// join these). + Constants, + /// The run's last binding moved the list's epoch, or something moved + /// it since. + Unsettled, + /// Its record is not the one after the run's last in the same buffer, + /// the run's step apart. + Apart, +} + +/// The rules (the module's): whether `call` joins `run`, the list's run +/// when the call came. +pub(crate) fn verdict(run: Option<&Run>, call: &Call) -> Verdict { + let Some(run) = run else { + return Verdict::First; + }; + if call.calls != run.calls { + Verdict::Between + } else if !call.single || !run.single { + Verdict::Counted + } else if call.alone || run.alone { + Verdict::Alone + } else if call.kind != run.kind || call.pipeline != run.pipeline { + Verdict::Differs + } else if call.clamped { + Verdict::Clamped + } else if call.rebinds[1] != run.rebinds[1] { + Verdict::Rebound + } else if call.rebinds[0] != run.rebinds[0] { + Verdict::Constants + } else if !run.settled || call.epoch != run.epoch { + Verdict::Unsettled + } else if call.buffer != run.buffer || call.step != run.step || call.at != run.next() { + Verdict::Apart + } else { + Verdict::Joins + } +} + +/// A run's execution not recorded yet: the signature it is recorded with +/// (of the title's stride for one record, of the run's step for more) and +/// the scratch buffer it reads. +pub(crate) struct Held { + pub(crate) signature: ID3D12CommandSignature, + pub(crate) buffer: ID3D12Resource, +} + +impl Held { + /// Records the execution of `run`. + pub(crate) fn record(&self, list: &ID3D12GraphicsCommandList, run: &Run) { + // SAFETY: an open list with the run's binding set (nothing was + // recorded since: everything that records records this first); the + // run's records are in `buffer`, which `self` holds; the signature + // is cached for the process. + unsafe { list.ExecuteIndirect(&self.signature, run.records, &self.buffer, run.at, None, 0) }; + } +} + +/// Of indirect executions run, by [`Verdict`], then those joined. +static COUNTS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12]; +const JOINED: usize = 11; + +/// An execution ran with `verdict`; `joined` if it was recorded with the +/// run before it. +pub(crate) fn count(verdict: Verdict, joined: bool) { + COUNTS[verdict as usize].fetch_add(1, Ordering::Relaxed); + if joined { + COUNTS[JOINED].fetch_add(1, Ordering::Relaxed); + } +} + +/// The frame line of the joining: per frame of the last `frames`. +pub(crate) fn line(frames: f64) { + let [joins, first, between, counted, alone, differs, clamped, rebound, constants, unsettled, apart, joined] = + std::array::from_fn::(|i| COUNTS[i].swap(0, Ordering::Relaxed) as f64 / frames); + let all = joins + first + between + counted + alone + differs + clamped + rebound + constants + unsettled + apart; + if all == 0.0 { + return; + } + tracing::info!( + "indirect executions per frame: {all:.0}, {joins:.0} could join the one before them in one execution \ + (VICTORY_INDIRECT_MERGE=1 joins them: now {}), {joined:.0} joined; of the others {first:.0} first on their \ + list, {between:.0} after a title call that records, {counted:.0} with a count buffer or more records (theirs \ + or the one's before), {alone:.0} kept alone, {differs:.0} of another kind or pipeline, {clamped:.0} clamped \ + by a pass of their own, {rebound:.0} after the title changed their binding, {constants:.0} after it changed \ + root constants only, {unsettled:.0} after a binding that changed the list, {apart:.0} with their record apart", + if on() { "on" } else { "off" } + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + const DRAW: u32 = 0; + const DISPATCH: u32 = 2; + + /// A batched dispatch record in slot `slot` of buffer 0x100, after + /// `calls` title calls, at epoch 7. + fn call(calls: u64, slot: u64) -> Call { + Call { + calls, + rebinds: [2, 5], + kind: DISPATCH, + pipeline: 0x5000, + single: true, + alone: false, + clamped: false, + epoch: 7, + buffer: 0x100, + at: 64 + slot * 32, + step: 32, + } + } + + #[test] + fn the_next_record_with_nothing_between_joins() { + let first = call(3, 0); + let mut run = Run::of(&first, 7); + assert!(run.settled); + let second = call(3, 1); + assert_eq!(verdict(Some(&run), &second), Verdict::Joins); + run.join(&second, second.epoch); + assert_eq!((run.records, run.next()), (2, 64 + 2 * 32)); + // The third follows the second. + assert_eq!(verdict(Some(&run), &call(3, 2)), Verdict::Joins); + // Not the second again, nor one past the next. + assert_eq!(verdict(Some(&run), &call(3, 1)), Verdict::Apart); + assert_eq!(verdict(Some(&run), &call(3, 3)), Verdict::Apart); + } + + #[test] + fn the_first_of_a_list_joins_nothing() { + assert_eq!(verdict(None, &call(0, 0)), Verdict::First); + } + + #[test] + fn a_title_call_between_keeps_them_apart() { + let run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &call(4, 1)), Verdict::Between); + } + + #[test] + fn counts_and_more_records_keep_them_apart() { + let run = Run::of(&call(3, 0), 7); + let counted = Call { single: false, ..call(3, 1) }; + assert_eq!(verdict(Some(&run), &counted), Verdict::Counted); + // Nor does a single record join a run of a counted one. + let run = Run::of(&Call { single: false, ..call(3, 0) }, 7); + assert_eq!(verdict(Some(&run), &call(3, 1)), Verdict::Counted); + } + + #[test] + fn executions_kept_alone_join_nothing() { + let run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &Call { alone: true, ..call(3, 1) }), Verdict::Alone); + let run = Run::of(&Call { alone: true, ..call(3, 0) }, 7); + assert_eq!(verdict(Some(&run), &call(3, 1)), Verdict::Alone); + } + + #[test] + fn another_kind_or_pipeline_keeps_them_apart() { + let run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &Call { kind: DRAW, ..call(3, 1) }), Verdict::Differs); + assert_eq!(verdict(Some(&run), &Call { pipeline: 0x6000, ..call(3, 1) }), Verdict::Differs); + } + + #[test] + fn a_binding_the_title_changed_keeps_them_apart() { + let run = Run::of(&call(3, 0), 7); + // Another table or view between: not joined. + assert_eq!(verdict(Some(&run), &Call { rebinds: [2, 6], ..call(3, 1) }), Verdict::Rebound); + // Root constants only: what a signature with root constants could join. + assert_eq!(verdict(Some(&run), &Call { rebinds: [3, 5], ..call(3, 1) }), Verdict::Constants); + assert_eq!(verdict(Some(&run), &Call { rebinds: [3, 6], ..call(3, 1) }), Verdict::Rebound); + // A joined execution carries the counts on. + let mut run = Run::of(&call(3, 0), 7); + run.join(&call(3, 1), 7); + assert_eq!(verdict(Some(&run), &call(3, 2)), Verdict::Joins); + } + + #[test] + fn a_record_clamped_by_a_pass_of_its_own_does_not_join() { + let run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &Call { clamped: true, ..call(3, 1) }), Verdict::Clamped); + } + + #[test] + fn a_binding_that_changed_the_list_keeps_the_next_apart() { + // Its binding moved the epoch from 7 to 8 (a texture changed state). + let mut run = Run::of(&call(3, 0), 8); + assert!(!run.settled); + assert_eq!(verdict(Some(&run), &Call { epoch: 8, ..call(3, 1) }), Verdict::Unsettled); + // Settled, but something moved the epoch since. + run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &Call { epoch: 9, ..call(3, 1) }), Verdict::Unsettled); + // A second execution whose binding settles starts a run the third + // can join. + let second = Call { epoch: 8, ..call(3, 1) }; + let mut run = Run::of(&second, 8); + assert_eq!(verdict(Some(&run), &Call { epoch: 8, ..call(3, 2) }), Verdict::Joins); + // A joined execution whose binding moved the epoch unsettles the run. + run.join(&Call { epoch: 8, ..call(3, 2) }, 9); + assert_eq!(verdict(Some(&run), &Call { epoch: 9, ..call(3, 3) }), Verdict::Unsettled); + } + + #[test] + fn records_must_follow_in_the_same_buffer_at_the_same_step() { + let run = Run::of(&call(3, 0), 7); + assert_eq!(verdict(Some(&run), &Call { buffer: 0x200, ..call(3, 1) }), Verdict::Apart); + // A window walked at 48 bytes is not a run of 32-byte slots. + assert_eq!(verdict(Some(&run), &Call { step: 48, at: 64 + 48, ..call(3, 1) }), Verdict::Apart); + // The same record again (a batch gives a repeated record its slot). + assert_eq!(verdict(Some(&run), &call(3, 0)), Verdict::Apart); + } + + #[test] + fn the_title_calls_come_first_among_the_reasons() { + let run = Run::of(&call(3, 0), 8); + let other = Call { kind: DRAW, clamped: true, single: false, epoch: 9, buffer: 0x200, ..call(4, 5) }; + assert_eq!(verdict(Some(&run), &other), Verdict::Between); + } +} diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index a18363d..54de11f 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -150,7 +150,27 @@ const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); /// is a host GPU. #[cfg(windows)] fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { - let Some(list) = host_list(this) else { return }; + with_state_on(host_list(this), this, f); +} + +/// As [`with_state`], for a call that only changes what the next draw or +/// dispatch binds, which records nothing until then: not counted as a title +/// call ([`crate::host::HostList::title_call`]); an indirect execution held +/// back may still be joined if the binding stays as it was +/// ([`crate::indirect::merge`]). +#[cfg(windows)] +fn with_binding(this: This, f: impl FnOnce(&mut crate::draw::State)) { + with_state_on(host_list_held(this), this, |_, s| f(s)); +} + +/// As [`with_state`], with `list`, the host list of `this` as it was taken. +#[cfg(windows)] +fn with_state_on( + list: Option<&crate::host::HostList>, + this: This, + f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State), +) { + let Some(list) = list else { return }; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // SAFETY: the title passes one of our lists. @@ -177,9 +197,22 @@ pub(crate) fn tables_done(lists: &[This]) { } } -/// The host list behind a title list, if there is a host GPU. +/// The host list behind a title list, if there is a host GPU, for a call +/// that records into it: counted as a title call, which records an +/// indirect execution held back first ([`crate::host::HostList::title_call`]). #[cfg(windows)] pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { + let list = host_list_held(this)?; + list.title_call(); + Some(list) +} + +/// As [`host_list`], not counted as a title call and recording nothing: +/// for an indirect execution, which may join the one held back +/// ([`crate::indirect::merge`]), and for calls that only change the binding +/// ([`with_binding`]). +#[cfg(windows)] +fn host_list_held<'a>(this: This) -> Option<&'a crate::host::HostList> { if this.is_null() { return None; } @@ -1544,7 +1577,7 @@ static ALLOCATOR_FUNCTIONS: Table<24> = { extern "system" fn set_pipeline(this: This, pipeline: This) { crate::pipeline::bound(pipeline); #[cfg(windows)] - with_state(this, |_, state| state.set_pipeline(pipeline)); + with_binding(this, |state| state.set_pipeline(pipeline)); #[cfg(not(windows))] let _ = this; } @@ -1646,7 +1679,7 @@ extern "system" fn ignored_state(_: This) {} /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] mod state { - use super::{This, with_state}; + use super::{This, with_binding, with_state}; use crate::draw::{IndexView, VertexView}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; @@ -1688,16 +1721,16 @@ mod state { with_state(this, |list, s| s.set_depth_bounds(list, min, max)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { - with_state(this, |_, s| s.set_heaps(items(heaps, count))); + with_binding(this, |s| s.set_heaps(items(heaps, count))); } pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) { - with_state(this, |_, s| s.set_table(true, slot, handle)); + with_binding(this, |s| s.set_table(true, slot, handle)); } pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) { - with_state(this, |_, s| s.set_table(false, slot, handle)); + with_binding(this, |s| s.set_table(false, slot, handle)); } pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) { - with_state(this, |_, s| s.set_constants(true, slot, &[value], offset)); + with_binding(this, |s| s.set_constants(true, slot, &[value], offset)); } pub(super) extern "system" fn graphics_constant( this: This, @@ -1705,7 +1738,7 @@ mod state { value: u32, offset: u32, ) { - with_state(this, |_, s| s.set_constants(false, slot, &[value], offset)); + with_binding(this, |s| s.set_constants(false, slot, &[value], offset)); } pub(super) extern "system" fn compute_constants( this: This, @@ -1714,9 +1747,7 @@ mod state { values: *const u32, offset: u32, ) { - with_state(this, |_, s| { - s.set_constants(true, slot, items(values, count), offset) - }); + with_binding(this, |s| s.set_constants(true, slot, items(values, count), offset)); } pub(super) extern "system" fn graphics_constants( this: This, @@ -1725,20 +1756,18 @@ mod state { values: *const u32, offset: u32, ) { - with_state(this, |_, s| { - s.set_constants(false, slot, items(values, count), offset) - }); + with_binding(this, |s| s.set_constants(false, slot, items(values, count), offset)); } /// Root constant buffer, shader resource and unordered access views. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) { - with_state(this, |_, s| s.set_view(true, slot, address)); + with_binding(this, |s| s.set_view(true, slot, address)); } pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) { - with_state(this, |_, s| s.set_view(false, slot, address)); + with_binding(this, |s| s.set_view(false, slot, address)); } pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) { // SAFETY: the title passes a view or null. - with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() })); + with_binding(this, |s| s.set_index_buffer(unsafe { view.as_ref() })); } pub(super) extern "system" fn vertex_buffers( this: This, @@ -1746,7 +1775,7 @@ mod state { count: u32, views: *const VertexView, ) { - with_state(this, |_, s| { + with_binding(this, |s| { if views.is_null() { s.clear_vertex_buffers(start, count); } else { @@ -1905,7 +1934,7 @@ extern "system" fn execute_indirect( const DISPATCH: u32 = 2; const DISPATCH_SINGLE: u32 = 105; let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; - with_state(this, |list, s| { + with_state_on(host_list_held(this), this, |list, s| { ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); } else {