From 0c34ab4348060f69595a824243c036bc453ce30b Mon Sep 17 00:00:00 2001 From: HumanlyDev Date: Thu, 26 Nov 2026 22:44:15 +0200 Subject: [PATCH] perf(gpu): batch descriptor copies/releases, bitset dynamic slots, and AVX2 shadow merge --- crates/victory-gpu/src/descriptor/host.rs | 305 +++++++++++++++++++--- crates/victory-gpu/src/draw.rs | 74 ++++-- crates/victory-gpu/src/host.rs | 33 ++- crates/victory-gpu/src/land.rs | 2 +- crates/victory-gpu/src/pipeline/host.rs | 18 ++ crates/victory-gpu/src/shadow.rs | 143 ++++++++++ 6 files changed, 499 insertions(+), 76 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 4cb70c9..b619e7f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -158,8 +158,8 @@ pub(crate) struct HostHeap { /// made for a draw takes it, and lets go of what the slot held under it). kept: Box<[Mutex>]>, /// Where the search for free dynamic slots starts, and which are taken - /// (by lists not yet reset). - next: Mutex<(u32, Vec)>, + /// (by lists not yet reset), packed 64 slots per `u64` word. + next: Mutex, /// How many dynamic slots are free (changed under `next`'s lock): with /// fewer than a table needs, the search is not made. Once the world /// had taken them all, every later table of the frame searched every @@ -1611,7 +1611,7 @@ impl HostHeap { waiting: Mutex::default(), away: Mutex::default(), kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), - next: Mutex::new((0, vec![false; extra as usize])), + next: Mutex::new(DynamicSlots::new(extra)), free: std::sync::atomic::AtomicU32::new(extra), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, @@ -1715,6 +1715,90 @@ fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { unsafe { host.device.CreateSampler(&desc, at) }; } +struct DynamicSlots { + cursor: u32, + len: u32, + words: Vec, +} + +impl DynamicSlots { + fn new(len: u32) -> Self { + Self { + cursor: 0, + len, + words: vec![0; len.div_ceil(64) as usize], + } + } + + fn scan_range(&self, from: u32, to: u32, n: u32) -> Option { + let mut at = from; + let mut run = 0u32; + while at < to { + let wi = (at / 64) as usize; + let bi = at % 64; + let avail = (64 - bi).min(to - at); + let w = self.words[wi] >> bi; + if bi == 0 && avail == 64 && w == !0u64 { + run = 0; + at += 64; + continue; + } + let free_prefix = w.trailing_zeros().min(avail); + run += free_prefix; + if run >= n { + return Some(at + free_prefix - run); + } + at += free_prefix; + if free_prefix == avail { + continue; + } + run = 0; + let rem = to - at; + let w2 = self.words[wi] >> (at % 64); + at += w2.trailing_ones().min(rem); + } + None + } + + fn alloc(&mut self, n: u32) -> Option { + if n == 0 || n > self.len { + return None; + } + let second_end = self.cursor.saturating_add(n - 1).min(self.len); + let first = self + .scan_range(self.cursor, self.len, n) + .or_else(|| self.scan_range(0, second_end, n))?; + let mut at = first; + let end = first + n; + while at < end { + let wi = (at / 64) as usize; + let bi = at % 64; + let k = (64 - bi).min(end - at); + let mask = if k == 64 { !0u64 } else { ((1u64 << k) - 1) << bi }; + self.words[wi] |= mask; + at += k; + } + self.cursor = end % self.len; + Some(first) + } + + fn free_range(&mut self, at: u32, end: u32) -> u32 { + let mut cur = at.min(self.len); + let end = end.min(self.len); + let mut given = 0u32; + while cur < end { + let wi = (cur / 64) as usize; + let bi = cur % 64; + let k = (64 - bi).min(end - cur); + let mask = if k == 64 { !0u64 } else { ((1u64 << k) - 1) << bi }; + given += (self.words[wi] & mask).count_ones(); + self.words[wi] &= !mask; + cur += k; + } + given + } +} + impl HostHeap { /// `n` consecutive free dynamic slots (view heaps only), taken until /// [`HostHeap::release`]: the first's index. @@ -1727,34 +1811,12 @@ impl HostHeap { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::DynamicAsked, 1); let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let (next, taken) = &mut *guard; let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); - let n = n as usize; - // Search from `next` on, then from the start (extending past cursor by - // n - 1 so contiguous runs crossing the cursor are not missed). - let cursor = *next as usize; - let end = self.dynamic as usize; - let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); - let starts = (cursor..end).chain(0..second_end); - let mut run = 0; - let mut found = None; - let mut last = usize::MAX; - for at in starts.take(if enough { usize::MAX } else { 0 }) { - // A run cannot wrap past the end. - if at != last.wrapping_add(1) { - run = 0; - } - last = at; - run = if taken[at] { 0 } else { run + 1 }; - if run == n { - found = Some(at + 1 - n); - break; - } - } + let found = if enough { guard.alloc(n) } else { None }; let Some(first) = found else { if enough { - self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + self.too_long.fetch_min(n, std::sync::atomic::Ordering::Relaxed); } static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); @@ -1768,10 +1830,8 @@ impl HostHeap { }; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); - taken[first..first + n].fill(true); - self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); - *next = ((first + n) % end) as u32; - Some(self.count + first as u32) + self.free.fetch_sub(n, std::sync::atomic::Ordering::Relaxed); + Some(self.count + first) } /// The title slots this heap has host slots for; fewer than the title's @@ -2781,19 +2841,20 @@ impl HostHeap { let Some(at) = first.checked_sub(self.count) else { return; }; - let end = (at + n).min(self.dynamic) as usize; + let end = (at + n).min(self.dynamic); // Release COM references pinned in dynamic slots before marking the // slots reusable so dead textures/buffers are not held in VRAM until // those exact indices are overwritten. - for slot in at as usize..end { - self.keep(self.count + slot as u32, None); + let mut retired = Vec::new(); + for slot in at..end { + self.keep_into(self.count + slot, None, &mut retired); } + crate::host::retire_resources(retired); let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slots) = guard.1.get_mut(at as usize..end) { - let given = slots.iter().filter(|taken| **taken).count() as u32; + let given = guard.free_range(at, end); + if given > 0 { self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); - slots.fill(false); } } @@ -2810,6 +2871,124 @@ impl HostHeap { self.keep(index, kept.flatten()); } + /// Like [`HostHeap::make_listed`], but processes an entire table's slice + /// of descriptor records in one `LIST_VIEWS` borrow, one batched + /// `CopyDescriptors` call per heap type, and one batched `retire_resources`. + pub(crate) fn make_listed_batch( + &self, + recording: u64, + first: u32, + words: &[Option<[u32; 3]>], + out: &mut [Option], + ) { + out.fill(None); + if self.sampler || words.is_empty() { + return; + } + let Some(host) = host() else { return }; + let mut retired = Vec::new(); + LIST_VIEWS.with(|views| { + let mut views = views.borrow_mut(); + if views.is_none() { + *views = Some(ListViews::new()?); + } + let views = views.as_mut()?; + if views.recording != recording { + views.recording = recording; + views.made.clear(); + } + COPY_BATCH.with(|batch| { + let mut batch = batch.borrow_mut(); + batch.clear(); + let has_twins = !self.twins.is_empty(); + #[cfg(feature = "diagnostics")] + let coarse = crate::host::coarse_ms() as u32; + for (k, maybe_words) in words.iter().enumerate() { + let Some(w) = *maybe_words else { + continue; + }; + let index = first + k as u32; + let twins = has_twins && (index as usize) < self.twins.len(); + if !views.made.contains_key(&w) { + let Some(view) = super::view_at(w[1], w[2]) else { + continue; + }; + let at = 2 * views.made.len() as u32; + if at >= ListViews::SLOTS || matches!(view, View::Constant(..)) { + continue; + } + let twin = twinned(&view); + let Some(kept) = make_twinned(&view, views.slot(at), Some(views.slot(at + 1))) else { + continue; + }; + let stride_word = view_stride_word(&view); + let listed = Listed { + kind: crate::draw::view_kind(&view), + texture: is_texture_view(&view), + ready: (0, 0, false), + tabled: None, + }; + views.made.insert(w, ListView { view, at, twin, stride_word, kept, listed }); + } + let made = &views.made[&w]; + batch.dst_primary.push(self.cpu(index)); + batch.src_primary.push(views.slot(made.at)); + #[cfg(feature = "diagnostics")] + if let Some(written) = self.written.get(index as usize) { + written.store(coarse, std::sync::atomic::Ordering::Relaxed); + } + if made.twin && twins { + let twin_idx = self.raw + index; + batch.dst_twin.push(self.cpu(twin_idx)); + batch.src_twin.push(views.slot(made.at + 1)); + #[cfg(feature = "diagnostics")] + if let Some(written) = self.written.get(twin_idx as usize) { + written.store(coarse, std::sync::atomic::Ordering::Relaxed); + } + self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); + } else { + self.clear_twin(index); + } + self.write_stride(index, made.stride_word); + self.keep_into(index, made.kept.clone(), &mut retired); + out[k] = Some(made.listed); + } + if !batch.dst_primary.is_empty() { + let n = batch.dst_primary.len() as u32; + // SAFETY: all handles point to live slots in our heaps; null sizes mean 1 per range. + unsafe { + host.device.CopyDescriptors( + n, + batch.dst_primary.as_ptr(), + None, + n, + batch.src_primary.as_ptr(), + None, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + } + } + if !batch.dst_twin.is_empty() { + let n = batch.dst_twin.len() as u32; + // SAFETY: all handles point to live twin slots in our heaps; null sizes mean 1 per range. + unsafe { + host.device.CopyDescriptors( + n, + batch.dst_twin.as_ptr(), + None, + n, + batch.src_twin.as_ptr(), + None, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + } + } + }); + Some(()) + }); + crate::host::retire_resources(retired); + } + /// Makes slot `index` (a dynamic one) the view the record `words` names, /// from this thread's descriptor of it if the recording `recording` has /// made one, else as [`HostHeap::make_at`] does, and keeps that @@ -2936,6 +3115,12 @@ impl HostHeap { /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { + let mut retired = Vec::new(); + self.keep_into(index, resource, &mut retired); + crate::host::retire_resources(retired); + } + + fn keep_into(&self, index: u32, resource: Option, retired: &mut Vec) { let Some(slot) = self.kept.get(index as usize) else { return; }; @@ -2951,7 +3136,7 @@ impl HostHeap { // A running submission may still read the old resource through // this slot. if let Some(old) = old { - crate::host::retire_resource(old); + retired.push(old); } } @@ -5809,6 +5994,27 @@ mod tests { assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some()); assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER); } + + #[test] + fn dynamic_slots_bitset_handles_boundaries_wrap_and_free() { + let mut ds = super::DynamicSlots::new(200); + // Single and multi-slot allocations across 64-bit word boundary + let a = ds.alloc(60).unwrap(); + assert_eq!(a, 0); + let b = ds.alloc(10).unwrap(); + assert_eq!(b, 60); // spans word 0 -> word 1 (60..70) + // Free first 60, allocate 130 (fits in 70..200) + assert_eq!(ds.free_range(0, 60), 60); + let c = ds.alloc(130).unwrap(); + assert_eq!(c, 70); + // Cursor is at 200 % 200 == 0; 0..60 is free, 60..200 is taken + assert_eq!(ds.alloc(61), None); + assert_eq!(ds.alloc(60), Some(0)); + // Free 60..70, verify exact freed count even if called twice + assert_eq!(ds.free_range(60, 70), 10); + assert_eq!(ds.free_range(60, 70), 0); + assert_eq!(ds.alloc(10), Some(60)); + } } /// What is known of a record a list's tables hold, in that recording of the @@ -5879,8 +6085,31 @@ impl ListViews { } } +#[derive(Default)] +struct CopyBatch { + dst_primary: Vec, + src_primary: Vec, + dst_twin: Vec, + src_twin: Vec, +} + +impl CopyBatch { + fn clear(&mut self) { + self.dst_primary.clear(); + self.src_primary.clear(); + self.dst_twin.clear(); + self.src_twin.clear(); + } +} + thread_local! { static LIST_VIEWS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static COPY_BATCH: std::cell::RefCell = const { std::cell::RefCell::new(CopyBatch { + dst_primary: Vec::new(), + src_primary: Vec::new(), + dst_twin: Vec::new(), + src_twin: Vec::new(), + }) }; } /// The view the record `words` names, as this thread made it for `recording`. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f94d2be..872eb6c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -255,7 +255,7 @@ pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [ /// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and /// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader /// permutations beyond `BAKE_PIXEL_SHADERS`. -const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"]; +pub(crate) const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"]; /// Since the start: early runs of the texture pass, and those of them /// made for a bake draw. @@ -466,9 +466,13 @@ pub(crate) struct State { /// address; 0 for none) → dynamic slot, and the host copy the slot /// shows: later draws of the list bring that one up to date, whatever /// copy the address would find by then (`shadow.rs` `tails`). - root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>, + root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot, std::hash::BuildHasherDefault>, /// Root UAVs bound as one-view tables in this list, likewise. - root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, + root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot, std::hash::BuildHasherDefault>, + /// Reusable scratch buffers for `State::tables()` to avoid per-draw allocations. + selected_scratch: Vec, + listed_words: Vec>, + listed_out: Vec>, /// The list ran and its dynamic slots were given back. tables_gone: bool, /// This recording, for [`crate::descriptor::host::HostHeap::make_listed`] @@ -1600,18 +1604,21 @@ impl State { if sampler_heap.is_none() { sampler_heap = crate::host::host().and_then(|h| h.fallback_sampler_heap().cloned()); } - let mut heaps: Vec> = Vec::with_capacity(2); + let mut heaps: [Option; 2] = [None, None]; + let mut heap_count = 0; if let Some(h) = view_heap { list.keep(&h); - heaps.push(Some(h)); + heaps[heap_count] = Some(h); + heap_count += 1; } if let Some(h) = sampler_heap { list.keep(&h); - heaps.push(Some(h)); + heaps[heap_count] = Some(h); + heap_count += 1; } - if !heaps.is_empty() { + if heap_count > 0 { // SAFETY: an open list and shader-visible heaps. - unsafe { l.SetDescriptorHeaps(&heaps) }; + unsafe { l.SetDescriptorHeaps(&heaps[..heap_count]) }; } self.host_heaps = self.heaps; self.host_heaps_set = true; @@ -2277,10 +2284,7 @@ impl State { /// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never /// bake `neutral()` or `null` stand-ins into permanent ped textures. fn is_bake_draw(&self, p: &HostPipeline) -> bool { - if p.stages.iter().any(|s| { - let h = s.shader.hash.as_str(); - BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h) - }) { + if p.is_bake_shader { return true; } self.depth == 0 @@ -3701,20 +3705,18 @@ impl State { let Some(host) = heap.host() else { continue; }; - let mut selected: Vec = group - .indexed - .iter() - .map(|index| { - let constant = self.user_value( - compute, - index.constant_slot, - RootType::Constants, - index.constant_dword, - ); - // The shader adds i32 byte offsets and shifts by 5. - index.byte_offset.wrapping_add(constant << index.shift) / 32 - }) - .collect(); + let mut selected = std::mem::take(&mut self.selected_scratch); + selected.clear(); + selected.extend(group.indexed.iter().map(|index| { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + // The shader adds i32 byte offsets and shifts by 5. + index.byte_offset.wrapping_add(constant << index.shift) / 32 + })); selected.sort_unstable(); selected.dedup(); let n = (group.max_dword / 8).max(selected.last().copied().unwrap_or(0)) + 1; @@ -3723,6 +3725,7 @@ impl State { || last.and_then(|handle| heap.index(handle)).is_none() { once!(slot, n, "fresh descriptor table exceeds the available span"); + self.selected_scratch = selected; continue; } // The table and what its entries hold (record words). @@ -3760,7 +3763,7 @@ impl State { readable(list, u.kind, &view); } } - for k in selected { + for &k in &selected { if group.entry(k).is_some() { continue; } @@ -3786,6 +3789,7 @@ impl State { } } made.push((slot, first * 32)); + self.selected_scratch = selected; continue; } let Some(first) = host.dynamic(n).or_else(|| { @@ -3795,6 +3799,7 @@ impl State { // No room: the draw must not run with the title's own // offsets (slots never made for it); `bind` drops it. made.push((slot, u32::MAX)); + self.selected_scratch = selected; continue; }; self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() }); @@ -3817,6 +3822,14 @@ impl State { self.recording = NEXT.fetch_add(1, Ordering::Relaxed); } let recording = self.recording; + let mut listed_words = std::mem::take(&mut self.listed_words); + let mut listed_out = std::mem::take(&mut self.listed_out); + if list_views { + listed_words.clear(); + listed_words.extend((0..n).map(|k| crate::descriptor::record_at(table + u64::from(k) * 32))); + listed_out.resize(n as usize, None); + host.make_listed_batch(recording, first, &listed_words, &mut listed_out); + } // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -3824,8 +3837,8 @@ impl State { // A view this list has made before: its descriptor copied, // and nothing more if nothing changed in the list since. if list_views - && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) - && let Some(mut listed) = host.make_listed(recording, words, index) + && let Some(words) = listed_words[k as usize] + && let Some(mut listed) = listed_out[k as usize] { let kind = group .entry(k) @@ -3905,6 +3918,9 @@ impl State { } } } + self.selected_scratch = selected; + self.listed_words = listed_words; + self.listed_out = listed_out; made.push((slot, first * 32)); } made diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5e451bb..7b0893d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -491,6 +491,25 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } +/// [`retire_resource`] for a batch of resources under a single lock acquisition. +pub(crate) fn retire_resources(objects: Vec) { + if objects.is_empty() { + return; + } + let count = objects.len() as u64; + let queued = crate::queue::queued(); + let started = STARTED.load(Ordering::Acquire) + queued; + if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(count, Ordering::Relaxed); + drop(objects); + return; + } + RETIREMENTS[1].fetch_add(count, Ordering::Relaxed); + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + retired.reserve(objects.len()); + retired.extend(objects.into_iter().map(|r| (started, Retired::Resource(r)))); +} + /// How many submissions later than it could (the last one that may use it /// has finished) an object let go is dropped, and a host list that has run /// is reset, about two frames: the device losses of the night of 2026-11-25 @@ -3463,6 +3482,7 @@ fn relay_worker() { fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); }; let mut fetch: Option = None; + let mut fences: Vec> = Vec::new(); loop { let next = { let mut line = line(); @@ -3471,14 +3491,11 @@ fn relay_worker() { line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); continue; } - let fences: Vec> = line - .line - .iter() - .map(|l| match l { - Late::Run(flight) => Some(flight.fence), - _ => None, - }) - .collect(); + fences.clear(); + fences.extend(line.line.iter().map(|l| match l { + Late::Run(flight) => Some(flight.fence), + _ => None, + })); // SAFETY: a plain query. let completed = unsafe { host.fence.GetCompletedValue() }; let n = landable(&fences, completed); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 2bde585..2bb6a1a 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -52,7 +52,7 @@ fn threads() -> usize { static THREADS: OnceLock = OnceLock::new(); *THREADS.get_or_init(|| { let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok()); - asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16) + asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8))).clamp(1, 16) }) } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index abf8e12..04e3f1e 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -392,6 +392,9 @@ pub(crate) struct HostPipeline { /// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out /// as the title gives them, three vertices a rectangle. pub(crate) rects: bool, + /// Precomputed check for whether any stage's shader hash is in + /// `BAKE_PIXEL_SHADERS` or `BAKE_GEOMETRY_SHADERS`. + pub(crate) is_bake_shader: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, /// Its depth, stencil, cull and blend state in short, for the frame @@ -633,6 +636,10 @@ impl HostPipeline { }; tracing::info!(?shaders, "host pipeline"); crate::host::name(&pso, || format!("{shaders:?}")); + let is_bake_shader = bound.iter().any(|s| { + let h = s.shader.hash.as_str(); + crate::draw::BAKE_PIXEL_SHADERS.contains(&h) || crate::draw::BAKE_GEOMETRY_SHADERS.contains(&h) + }); return Some(HostPipeline { compute: true, mesh: false, @@ -643,6 +650,7 @@ impl HostPipeline { slots: 0, inputs: Vec::new(), rects: false, + is_bake_shader, state: String::new(), }); } @@ -686,6 +694,10 @@ impl HostPipeline { }; tracing::info!(?shaders, "host mesh pipeline"); crate::host::name(&pso, || format!("{shaders:?}")); + let is_bake_shader = bound.iter().any(|s| { + let h = s.shader.hash.as_str(); + crate::draw::BAKE_PIXEL_SHADERS.contains(&h) || crate::draw::BAKE_GEOMETRY_SHADERS.contains(&h) + }); return Some(HostPipeline { compute: false, mesh: true, @@ -696,6 +708,7 @@ impl HostPipeline { slots: 0, inputs: Vec::new(), rects: false, + is_bake_shader, state: String::new(), }); } @@ -802,6 +815,10 @@ impl HostPipeline { cull = g.rasterizer.CullMode.0, "host graphics state" ); + let is_bake_shader = bound.iter().any(|s| { + let h = s.shader.hash.as_str(); + crate::draw::BAKE_PIXEL_SHADERS.contains(&h) || crate::draw::BAKE_GEOMETRY_SHADERS.contains(&h) + }); Some(HostPipeline { compute: false, mesh: false, @@ -812,6 +829,7 @@ impl HostPipeline { slots: g.slots(), inputs: g.elements(), rects: rect_gs.is_some(), + is_bake_shader, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 14dc160..0f85d86 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1005,6 +1005,15 @@ impl Flights { /// read, could undo that write. (The merge of a waited-for submission /// stores every byte of a differing stretch back into the copy.) fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + #[cfg(target_arch = "x86_64")] + if std::is_x86_feature_detected!("avx2") { + // SAFETY: AVX2 is detected; slices are valid for their lengths. + return unsafe { merge_piece_avx2(now, held, title) }; + } + merge_piece_scalar(now, held, title) +} + +fn merge_piece_scalar(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { let mut differs = 0u8; for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { let wrote = if *n != *h { 0xffu8 } else { 0 }; @@ -1016,6 +1025,39 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { differs != 0 } +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn merge_piece_avx2(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + use std::arch::x86_64::{ + __m256i, _mm256_blendv_epi8, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, + _mm256_or_si256, _mm256_setzero_si256, _mm256_storeu_si256, _mm256_testz_si256, + _mm256_xor_si256, + }; + let len = now.len().min(held.len()).min(title.len()); + let mut diff_acc = _mm256_setzero_si256(); + let mut i = 0; + while i + 32 <= len { + // SAFETY: `i + 32 <= len` so all three pointers are valid for 32-byte unaligned access. + unsafe { + let n = _mm256_loadu_si256(now.as_ptr().add(i).cast::<__m256i>()); + let h = _mm256_loadu_si256(held.as_ptr().add(i).cast::<__m256i>()); + let eq = _mm256_cmpeq_epi8(n, h); + if _mm256_movemask_epi8(eq) != -1 { + let t_ptr = title.as_mut_ptr().add(i).cast::<__m256i>(); + let t = _mm256_loadu_si256(t_ptr); + let merged = _mm256_blendv_epi8(n, t, eq); + diff_acc = _mm256_or_si256(diff_acc, _mm256_xor_si256(merged, t)); + _mm256_storeu_si256(t_ptr, merged); + _mm256_storeu_si256(held.as_mut_ptr().add(i).cast::<__m256i>(), n); + } + } + i += 32; + } + let simd_differs = _mm256_testz_si256(diff_acc, diff_acc) == 0; + let tail_differs = merge_piece_scalar(&now[i..len], &mut held[i..len], &mut title[i..len]); + simd_differs || tail_differs +} + /// `[from, to)` without the ranges of `skip`, in order. fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { skip.sort_unstable(); @@ -1980,6 +2022,15 @@ pub(crate) fn merged_stats() -> [u64; 3] { /// (offset, bytes) in order: every differing byte is in a run and no equal /// byte is. fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + #[cfg(target_arch = "x86_64")] + if std::is_x86_feature_detected!("avx2") { + // SAFETY: AVX2 is detected; slices are valid for their lengths. + return unsafe { changed_runs_avx2(now, was) }; + } + changed_runs_scalar(now, was) +} + +fn changed_runs_scalar(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { let n = now.len().min(was.len()); let mut runs = Vec::new(); let mut i = 0; @@ -2007,6 +2058,67 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn changed_runs_avx2(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + use std::arch::x86_64::{__m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8}; + let n = now.len().min(was.len()); + let mut runs = Vec::new(); + let mut run_start: Option = None; + let mut i = 0; + while i + 32 <= n { + // SAFETY: `i + 32 <= n` so both slices are valid for 32-byte unaligned loads. + let diff = unsafe { + let a = _mm256_loadu_si256(now.as_ptr().add(i).cast::<__m256i>()); + let b = _mm256_loadu_si256(was.as_ptr().add(i).cast::<__m256i>()); + !(_mm256_movemask_epi8(_mm256_cmpeq_epi8(a, b)) as u32) + }; + if diff == 0 { + if let Some(start) = run_start.take() { + runs.push((start, i - start)); + } + } else if diff == u32::MAX { + if run_start.is_none() { + run_start = Some(i); + } + } else { + let mut bit = 0u32; + while bit < 32 { + let rem = diff >> bit; + if let Some(start) = run_start { + let ones = rem.trailing_ones().min(32 - bit); + bit += ones; + if bit < 32 { + runs.push((start, i + bit as usize - start)); + run_start = None; + } + } else { + let zeros = rem.trailing_zeros().min(32 - bit); + bit += zeros; + if bit < 32 { + run_start = Some(i + bit as usize); + } + } + } + } + i += 32; + } + while i < n { + if now[i] != was[i] { + if run_start.is_none() { + run_start = Some(i); + } + } else if let Some(start) = run_start.take() { + runs.push((start, i - start)); + } + i += 1; + } + if let Some(start) = run_start { + runs.push((start, n - start)); + } + runs +} + /// The kernel's page. const KERNEL_PAGE: usize = 4096; @@ -2473,6 +2585,37 @@ mod merge_tests { } assert!(changed_runs(&[], &[]).is_empty()); } + + #[test] + fn avx2_changed_runs_and_merge_piece_match_scalar() { + for len in [0usize, 1, 31, 32, 33, 63, 64, 65, 127, 128, 257] { + let base: Vec = (0..len).map(|i| (i * 13 + 7) as u8).collect(); + let mut now = base.clone(); + let mut title_scalar = base.clone(); + let mut title_simd = base.clone(); + let mut held_scalar = base.clone(); + let mut held_simd = base.clone(); + for i in 0..len { + if i % 5 == 0 || (30..=35).contains(&i) || (62..=66).contains(&i) { + now[i] ^= 0x5a; + } + if i % 7 == 0 { + title_scalar[i] = 0xee; + title_simd[i] = 0xee; + } + } + assert_eq!( + super::changed_runs(&now, &base), + super::changed_runs_scalar(&now, &base), + "changed_runs mismatch at len={len}" + ); + let r_scalar = super::merge_piece_scalar(&now, &mut held_scalar, &mut title_scalar); + let r_simd = super::merge_piece(&now, &mut held_simd, &mut title_simd); + assert_eq!(r_simd, r_scalar, "merge_piece return mismatch at len={len}"); + assert_eq!(held_simd, held_scalar, "held mismatch at len={len}"); + assert_eq!(title_simd, title_scalar, "title mismatch at len={len}"); + } + } } /// Host copies alive (also those only a list, a descriptor pass or a