From c8ede5088694260bb9ef90b258f26dfdae5ac782 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:42:04 -0600 Subject: [PATCH 1/5] A range shaders write is declared once until the list next writes title memory (from Belobug dd799aad, romainhedouin); VICTORY_DECLARE_ONCE=0 for the old way Dispatches declare the same few ranges again and again: 4,003 to 5,550 steps a frame of fork-b1-fast, each a flush of its copy's pending refreshes and two locks on the thread that submits (the snapshots alone 1.7 to 2.0 ms a frame). The ranges and their order stay what they were. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 36 +++++++++++++++++++++++----- crates/victory-gpu/src/host/place.rs | 2 +- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2aa4178..bbb733b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2184,6 +2184,10 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Ranges declared written by shaders since the list last wrote title + /// memory (host copy, address, bytes): declaring them again would + /// change nothing. + gpu_written: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -2218,6 +2222,13 @@ impl Deferred { self.upload_bytes += size; self.uploads.push(buffer); } + + /// The steps recorded last write title memory: what was brought up to + /// date before them is not any more. + fn title_written(&mut self) { + self.refreshed.clear(); + self.gpu_written.clear(); + } } impl Drop for Deferred { @@ -3685,6 +3696,12 @@ fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) } +/// See [`HostList::defer_gpu_write`]. +fn declare_once() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_DECLARE_ONCE").map_or(true, |v| v != "0")) +} + /// The ranges the shaders of `runs` may write, per host copy, as declared. /// One list's lock at a time: a submission may name a list twice. fn declared_writes(runs: &[&HostList]) -> Vec { @@ -6630,7 +6647,7 @@ impl HostList { deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); - deferred.refreshed.clear(); + deferred.title_written(); self.changed_something(); } @@ -6677,15 +6694,20 @@ impl HostList { /// Shaders of the list write `[address, address + len)` of a buffer's /// host copy: copied back into title memory once the list has run. + /// Declared once until the list next writes title memory (but with + /// `VICTORY_DECLARE_ONCE=0`): the dispatches of a frame declared the + /// same ranges thousands of times, each a step of its own. pub(crate) fn defer_gpu_write( &self, shadow: &std::sync::Arc, address: usize, len: usize, ) { - self.deferred() - .copies - .push(Step::GpuWrite(shadow.clone(), address, len)); + let mut deferred = self.deferred(); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + if deferred.gpu_written.insert(key) || !declare_once() { + deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); + } } /// A read back: once the list has run, `rows` rows of `row` bytes go @@ -7012,8 +7034,10 @@ impl HostList { /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Run(Box::new(work))); - self.deferred().refreshed.clear(); + let mut deferred = self.deferred(); + deferred.copies.push(Step::Run(Box::new(work))); + deferred.title_written(); + drop(deferred); self.changed_something(); } diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index cde0149..9e815d4 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -255,7 +255,7 @@ impl HostList { shadow: to, from: scratch.map(|s| s.2 as usize), })); - deferred.refreshed.clear(); + deferred.title_written(); self.changed_something(); true } From 14692d11ff487b75e8254c3dd35cde99d03f3060 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:42:59 -0600 Subject: [PATCH 2/5] A pipeline a list binds again is not kept and named again (from Belobug 92d353f8, romainhedouin) Two queries for an interface, three locks and a name looked up at every change of pipeline; now one lookup by address. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 4 +--- crates/victory-gpu/src/host.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 88729fc..2641d9c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1460,10 +1460,8 @@ impl State { // SAFETY: an open list and a live pipeline. unsafe { l.SetPipelineState(&p.pso) }; self.host_pipeline = p.pso.as_raw() as usize; - list.used_pipeline(&p.name); // The title may release the pipeline before it submits the list. - list.keep(&p.pso); - list.keep(&p.root); + list.bind_pipeline(&p.name, &p.pso, &p.root); } for stage in &p.stages { let t = stage.translated(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bbb733b..da8f6da 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2181,6 +2181,8 @@ struct Deferred { /// descriptor heaps): the title may release its objects before it /// submits the list. kept: Vec, + /// The pipelines [`HostList::bind_pipeline`] kept, by address. + bound: std::collections::HashSet>, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, @@ -6624,6 +6626,21 @@ impl HostList { } } + /// The list binds a pipeline: it and its root signature are kept until + /// the list is reset, and its name noted, the first time only (a kept + /// pipeline's address names no other). + pub(crate) fn bind_pipeline(&self, name: &str, pso: &ID3D12PipelineState, root: &ID3D12RootSignature) { + { + let mut deferred = self.deferred(); + if !deferred.bound.insert(pso.as_raw() as usize) { + return; + } + deferred.kept.push(pso.clone().into()); + deferred.kept.push(root.clone().into()); + } + self.used_pipeline(name); + } + fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { self.deferred.lock().unwrap_or_else(|e| e.into_inner()) } From a869d90e3ace11549565b7a32af05ccf4622625b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:43:00 -0600 Subject: [PATCH 3/5] A root constant buffer not 256-byte aligned is copied into scratch memory once for the draws of a list that bind it (from Belobug 84ea9c12, romainhedouin) Until the list next writes title memory, as for refreshes: up to 64 KiB of fill less for every repeat. How often this title binds one was not measured. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 4 +--- crates/victory-gpu/src/host.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2641d9c..04aa40e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -713,9 +713,7 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { crate::book::root(gpu, len); return Some(gpu); } - let (gpu, to) = list.scratch(len)?; - list.defer_fill(to, address as *const u8, len as usize); - Some(gpu) + list.fill_scratch(address as *const u8, len) } macro_rules! once { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index da8f6da..1d83029 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2190,6 +2190,9 @@ struct Deferred { /// memory (host copy, address, bytes): declaring them again would /// change nothing. gpu_written: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Scratch memory [`HostList::fill_scratch`] fills since the list last + /// wrote title memory (source, bytes): its host address. + filled: std::collections::HashMap<(usize, usize), u64, std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -2230,6 +2233,7 @@ impl Deferred { fn title_written(&mut self) { self.refreshed.clear(); self.gpu_written.clear(); + self.filled.clear(); } } @@ -6676,6 +6680,21 @@ impl HostList { .push(Step::Fill(dst as usize, src as usize, len, None)); } + /// The host address of `len` bytes of scratch memory that hold the title + /// memory at `src` as of the list's submission: one fill for every ask + /// until the list next writes title memory. + pub(crate) fn fill_scratch(&self, src: *const u8, len: u64) -> Option { + let key = (src as usize, len as usize); + let known = self.deferred().filled.get(&key).copied(); + if known.is_some() { + return known; + } + let (gpu, to) = self.scratch(len)?; + self.defer_fill(to, src, len as usize); + self.deferred().filled.insert(key, gpu); + Some(gpu) + } + /// As [`HostList::defer_fill`], for upload memory that only `slot` (a /// title heap's address, and the slot) shows. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { From 5e2394c2f4233a38ee3afa2eb76f01f9ed4e5396 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:44:14 -0600 Subject: [PATCH 4/5] The same render targets are not set again (after ZJOU acf478b8, author local); VICTORY_BIND_CACHE=0 sets them every time Theirs compares the handles, which a title may write other views behind; here the views themselves (resource, host texture, description) are compared. A call with the same ones saves a host view per target and the driver's call. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 9 +++++++ crates/victory-gpu/src/draw.rs | 36 ++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index cabe5a1..7ca72cb 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -643,6 +643,15 @@ const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); const _: () = assert!(size_of::() <= 112); impl RtvRecord { + /// All the view it records is made from: records with equal keys have + /// equal views (of the same host texture). + #[cfg(windows)] + pub(crate) fn key(&self) -> (usize, [u32; 7]) { + let mut words = [self.described; 7]; + words[1..].copy_from_slice(&self.desc); + (self.resource as usize, words) + } + /// The view description in the host's type (the same layout). #[cfg(windows)] pub(crate) fn desc( diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 04aa40e..f04fe53 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -306,6 +306,10 @@ pub(crate) struct State { target_handles: Vec, depth_handle: u64, targets_set: bool, + /// The render target views and the depth view the host list has, once + /// it has any ([`State::set_targets`]): per view the host texture (0: + /// a null view) and what its descriptor says. + host_targets: Option<(Vec, Option)>, viewports: Vec, scissors: Vec, blend: Option<[f32; 4]>, @@ -685,6 +689,10 @@ pub(crate) fn dispatched() -> u64 { DISPATCHED.load(Ordering::Relaxed) } +/// What a render target or depth view of the host is made from: the host +/// texture, and [`crate::descriptor::RtvRecord::key`]. +type TargetKey = (usize, (usize, [u32; 7])); + /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. @@ -993,7 +1001,11 @@ impl State { self.index = view.copied().unwrap_or_default(); } - /// Render targets and depth, set on the host list at once. + /// Render targets and depth, set on the host list at once, unless it has + /// the same ones already: the title sets the same targets again and + /// again, each time a host view per target and a call of the driver + /// (25,662 times in a frame of another fork). `VICTORY_BIND_CACHE=0` + /// sets them every time. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { let Some(host) = crate::host::host() else { return; @@ -1003,7 +1015,8 @@ impl State { self.depth_handle = depth; self.targets_set = true; self.targets.clear(); - let mut rtvs = Vec::new(); + let mut views = Vec::with_capacity(handles.len()); + let mut keys = Vec::with_capacity(handles.len()); for &h in handles { let Some(record) = crate::descriptor::rtv_record(h) else { once!( @@ -1023,14 +1036,16 @@ impl State { .desc() .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); if let Some(desc) = null { - rtvs.push(host.rtv(None, Some(&desc))); + views.push((None, Some(desc))); + keys.push((0, record.key())); } continue; }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); + views.push((Some(texture), record.desc())); + keys.push((texture.as_raw() as usize, record.key())); } self.depth = 0; self.depth_state = DEPTH_WRITE; @@ -1043,8 +1058,18 @@ impl State { } #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - Some(host.dsv(texture, record.depth_desc().as_ref())) + Some((texture, record)) }); + let now = (keys, dsv.as_ref().map(|(texture, record)| (texture.as_raw() as usize, record.key()))); + static CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *CACHE.get_or_init(|| std::env::var("VICTORY_BIND_CACHE").map_or(true, |v| v != "0")) + && self.host_targets.as_ref() == Some(&now) + { + return; + } + self.host_targets = Some(now); + let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect(); + let dsv = dsv.map(|(texture, record)| host.dsv(texture, record.depth_desc().as_ref())); // SAFETY: an open list; the views were just made. unsafe { list.list.OMSetRenderTargets( @@ -1121,6 +1146,7 @@ impl State { if self.topology_set { self.set_topology(list, self.topology); } + self.host_targets = None; if self.targets_set { let handles = std::mem::take(&mut self.target_handles); self.set_targets(list, &handles, self.depth_handle); From 49f9aa034dac0b1a114abb7d4a9910f8a7201a06 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:46:34 -0600 Subject: [PATCH 5/5] The frame line says how many indirect records ran empty for want of their list's budget, and the largest cost; VICTORY_INDIRECT_REST=0: a record that does not fit takes nothing from the ones after it Belobug (76387c2d) found draws flickering because the records past a list's budget were not the same ones from frame to frame. Whether ours are refused is not known: the count says it (atomics only when there is something to say). Off by default; the records' order and costs stay what they were. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 20 +++++-- crates/victory-gpu/src/indirect.rs | 68 ++++++++++++++++++++---- crates/victory-gpu/src/indirect/batch.rs | 17 +++++- 3 files changed, 87 insertions(+), 18 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1d83029..8a18af2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1707,6 +1707,10 @@ fn list_number(name: &str) -> Option { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Indirect records that ran empty for want of their list's budget, and the +/// largest cost of one (told from 2^22 on), likewise. +static BUDGET_NOTES: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Whether a list's indirect-work budget lives in the card's own memory /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as /// before). The clamp charges it with atomics, at least two in a row for @@ -6846,14 +6850,18 @@ impl HostList { // SAFETY: the list's own mapped words, written before it runs. // The words after the budget hold what the clamp noted about the // list's last run (mesh dispatches: the largest group count - // asked for, the groups asked in all; with the card's copy, as + // asked for, the groups asked in all; the records refused, the + // largest cost; with the card's copy, as // the list's end copied them here): taken, then zeroed. let notes = Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); - for k in 0..3 { + let (refused, biggest) = (words.add(3).read_volatile(), words.add(4).read_volatile()); + BUDGET_NOTES[0].fetch_add(u64::from(refused), Ordering::Relaxed); + BUDGET_NOTES[1].fetch_max(u64::from(biggest), Ordering::Relaxed); + for k in 0..5 { words.add(k).write_volatile(0); } }); @@ -6888,7 +6896,7 @@ impl HostList { }; // SAFETY: a live buffer. let at = unsafe { card.GetGPUVirtualAddress() }; - let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + let zeros = [0u64, 4, 8, 12, 16].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + offset, Value: 0, }); @@ -6929,7 +6937,7 @@ impl HostList { D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); - self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.CopyBufferRegion(mapped, 4, card, 4, 16); self.list.ResourceBarrier(&[transition( card, D3D12_RESOURCE_STATE_COPY_SOURCE, @@ -8516,8 +8524,10 @@ impl Meter { let indirect = crate::list::take_indirect() as f64 / frames; let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + let refused = BUDGET_NOTES[0].swap(0, Ordering::Relaxed) as f64 / frames; + let biggest = BUDGET_NOTES[1].swap(0, Ordering::Relaxed); tracing::info!( - "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" + "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::shadow::exact_line(frames); crate::descriptor::sync_line(frames); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index d74b748..5c13842 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -157,7 +157,8 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { uint n = eff_count > first ? min(64u, eff_count - first) : 0u; if (gi == 0 && n > 0) { // What the records charge, from `before` on, in lane order: a - // record that does not fit whole runs empty and takes the rest. + // record that does not fit whole runs empty and takes the rest + // (`rest`). // Only the group's own records are walked (one, clamped alone). uint before; budget.InterlockedOr(0, 0, before); @@ -167,7 +168,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { for (uint j = 0; j < n; j++) { uint c = costs[j]; if (c > 0 && next < BUDGET) { - next = (BUDGET - next <= c) ? BUDGET : (next + c); + next = (BUDGET - next < c) ? (REST ? BUDGET : next) : (next + c); } } if (next == before) break; @@ -177,15 +178,28 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { before = prev; } uint at = before; + uint refused = 0; + uint biggest = 0; for (uint k = 0; k < n; k++) { uint c = costs[k]; uint fit = 1; if (c > 0) { fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; - at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + at = (at >= BUDGET || BUDGET - at < c) ? (REST ? BUDGET : at) : (at + c); + refused += 1 - fit; + biggest = max(biggest, c); } fits[k] = fit; } + // Diagnostics: the records that run empty for want of budget, and + // the largest cost there was (small ones are not told). + uint told; + if (refused > 0) { + budget.InterlockedAdd(12, refused, told); + } + if (biggest >= (1u << 22)) { + budget.InterlockedMax(16, biggest, told); + } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && kind > 2 && n > 0) { @@ -279,12 +293,22 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool { } } +/// Whether a record that does not fit in what is left of its list's budget +/// takes the rest, so that every record after it runs empty too +/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits +/// runs). A list whose budget one garbage record empties loses all its later +/// draws, and which record that is may differ from frame to frame. The frame +/// line says how many records a frame are refused. +fn rest() -> u32 { + u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) +} + /// The clamp compiled from `source` (ours, or in the benchmark the one it /// replaced). fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { #[cfg(feature = "diagnostics")] let batched = source == batch::SOURCE; - let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device))); + let source = &format!("#define WIDEST {}u\n#define REST {}\n{source}", widest(amd(device)), rest()); let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -2556,9 +2580,35 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// word record by record, which of them fitted was up to the GPU.) #[test] fn warp_a_group_charges_its_records_in_lane_order() { - let Some(mut warp) = WarpHarness::new() else { + let Some((left, out)) = four_records_of_a_group(true) else { return; }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..4 { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(left, 0, "the record that did not fit took the rest"); + } + + /// As above where a record that does not fit takes nothing + /// (`VICTORY_INDIRECT_REST=0`): those after it that fit run. + #[test] + fn warp_a_record_that_does_not_fit_may_take_nothing() { + let Some((left, out)) = four_records_of_a_group(false) else { + return; + }; + for (i, count) in [100, 0, 50, 100].into_iter().enumerate() { + assert_eq!(out[i * 4..i * 4 + 4], [count, count.min(1), 7, 9], "record {i}"); + } + assert_eq!(left, 50); + } + + /// Draws of 100, 250, 50 and 100 with 300 left of the budget: what is + /// left then, and the records as clamped. + fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec)> { + let mut warp = WarpHarness::new()?; + let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; + let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); const KIND_DRAW: u32 = 0; const STRIDE: u32 = 16; const BUDGET_CAP: u32 = 1 << 27; @@ -2582,7 +2632,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); } assert!(record_clamp_as( - &warp.clamp, + &clamp, &warp.list, (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, @@ -2609,11 +2659,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { .to_vec(), ) }; - assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); - for i in 1..counts.len() { - assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); - } - assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + Some((BUDGET_CAP - spent, out)) } /// The list's budget starts empty at each submission, wherever it diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index e6da6a1..d4f192d 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -124,7 +124,7 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { for (uint j = 0; j < n; j++) { uint c = costs[j]; if (c > 0 && next < BUDGET) { - next = (BUDGET - next <= c) ? BUDGET : (next + c); + next = (BUDGET - next < c) ? (REST ? BUDGET : next) : (next + c); } } if (next == before) break; @@ -134,15 +134,28 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { before = prev; } uint at = before; + uint refused = 0; + uint biggest = 0; for (uint k = 0; k < n; k++) { uint c = costs[k]; uint fit = 1; if (c > 0) { fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; - at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + at = (at >= BUDGET || BUDGET - at < c) ? (REST ? BUDGET : at) : (at + c); + refused += 1 - fit; + biggest = max(biggest, c); } fits[k] = fit; } + // Diagnostics: the records that run empty for want of budget, and + // the largest cost there was (small ones are not told). + uint told; + if (refused > 0) { + budget.InterlockedAdd(12, refused, told); + } + if (biggest >= (1u << 22)) { + budget.InterlockedMax(16, biggest, told); + } } GroupMemoryBarrierWithGroupSync(); if (gi == 0 && n > 0 && all_asked > 0) {