From ebd07c1dbb159b57447de6e42c4ac53e203ce75f Mon Sep 17 00:00:00 2001 From: theme613 <66501763+theme613@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:02:30 +0800 Subject: [PATCH] gpu/launcher: direct in-place CBVs, CBV dedup, coalesced fills, and cutscene texture-pass optimizations --- crates/victory-gpu/src/draw.rs | 61 ++++++-- crates/victory-gpu/src/host.rs | 163 +++++++++++++++++++++- crates/victory-gpu/src/host/card_steps.rs | 27 +++- crates/victory-gpu/src/texture.rs | 17 ++- scripts/play-6gb.ps1 | 11 +- 5 files changed, 245 insertions(+), 34 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7f3c078..e6ea901 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3187,6 +3187,25 @@ impl State { if FRAME.swap(frame, Ordering::Relaxed) != frame { SPENT.store(0, Ordering::Relaxed); } + let baking = crate::texture::BAKING.get(); + let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); + let frame_pass = !required && !baking && sync.is_none(); + // If an earlier pass in this same frame already exhausted the + // `VICTORY_TEXSPK_PASS_MS` budget, still flip any newly-completed + // texture uploads visible, then bail before taking the global + // texture-queue lock and scanning tens of thousands of slots for a + // loop that would immediately time out on iteration 0. + if frame_pass + && let Some(cap) = texspk_pass_ms() + && PASS_FRAME.load(Ordering::Relaxed) == frame + && PASS_FRAME_NANOS.load(Ordering::Relaxed) >= cap.saturating_mul(1_000_000) + { + before(1, || { + host.texture_views_remade(); + host.texture_slots_flip(); + }); + return false; + } // No more of them are made while the card has no room // (`resource::room`): by what is alive now, not by what was ever // staged (4 GB in all, after which later textures stayed empty for @@ -3205,7 +3224,6 @@ impl State { once!("textures picked by index: the card has no room for more; they wait"); } let mut refused = 0; - let baking = crate::texture::BAKING.get(); before(0, || { // Room again: the slots held back while the card was full are // due now (`full_card_pass`). @@ -3233,10 +3251,15 @@ impl State { if room { before(0, || host.texture_slots_waiting(frame)); } - let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); // (And what the queue knew of each, `known`: see `Tells`.) - let (mut due, mut known, census) = - before(2, || host.texture_slots_due_known(frame, if baking { 1 << 16 } else { 4096 })); + let due_cap = if baking { + 1 << 16 + } else if !room && !required { + 1024 + } else { + 4096 + }; + let (mut due, mut known, census) = before(2, || host.texture_slots_due_known(frame, due_cap)); // (Those that are due later after all that are due.) let on_time = due.len(); if baking { @@ -3322,7 +3345,6 @@ impl State { // A frame's runs of the pass (its own and the early ones, not those // before a bake) within `VICTORY_TEXSPK_PASS_MS` together // ([`texspk_pass_ms`]). - let frame_pass = !required && !baking && sync.is_none(); let span = match texspk_pass_ms() { Some(cap) if frame_pass => { if PASS_FRAME.swap(frame, Ordering::Relaxed) != frame { @@ -3489,10 +3511,11 @@ impl State { outcome(slot_outcome::HELD); if full_card_pass() { // Held back for the frames of about four seconds - // (`most`), or until the card has room; the pass - // goes on, within a count that bounds one pass. + // (`most`), or until the card has room; cap refusals + // per pass at 256 so full-card cutscenes do not thrash + // thousands of held-slot tells under the queue lock. tells.tell(index, write, Told::Held(frame + most)); - if refused > 1024 { + if refused > 256 { break; } } else if refused > 256 { @@ -4820,12 +4843,28 @@ impl State { let used = group.entry(k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { - let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { + // Direct 256-byte-aligned in-place CBV fast path: when + // `VICTORY_PORT_CONSTANTS=1` already has the constant heap + // in place on the card and `gpu` is 256-byte aligned, bind + // directly with zero scratch alloc, zero `Step::Fill`, and + // zero CPU copy (`VICTORY_DIRECT_CBV=0` disables). + static DIRECT_CBV: std::sync::OnceLock = std::sync::OnceLock::new(); + if *DIRECT_CBV.get_or_init(|| std::env::var_os("VICTORY_DIRECT_CBV").is_none_or(|v| v != "0")) + && crate::port::on() + && let Some(shadow) = crate::shadow::find(address, u64::from(size)).filter(|s| s.in_place()) + { + let gpu = shadow.gpu(address); + let aligned = u64::from(size).next_multiple_of(256); + if gpu.is_multiple_of(256) && shadow.left(address) >= aligned { + host.constant_at(index, &shadow.buffer, gpu, size); + continue; + } + } + let slot = (std::ptr::from_ref(heap) as usize, index); + let Some((buffer, gpu)) = list.constant_scratch(address as *const u8, size, slot) else { host.make_null(index); continue; }; - let slot = (std::ptr::from_ref(heap) as usize, index); - list.defer_constants(to, address as *const u8, size as usize, slot); host.constant_at(index, &buffer, gpu, size); } Some(view) => { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 81eebe7..72716f5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2715,6 +2715,9 @@ struct Deferred { /// 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>, + /// Constant-buffer upload copies [`HostList::constant_scratch`] made since + /// the list last wrote title memory (`(src, len)` -> `(buffer, gpu, step)`). + constants: std::collections::HashMap<(usize, usize), (ID3D12Resource, u64, usize), std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet>, /// Whether `copies` contains at least one `Step::GpuWrite` (lets @@ -2759,6 +2762,7 @@ impl Deferred { self.refreshed.clear(); self.gpu_written.clear(); self.filled.clear(); + self.constants.clear(); } } @@ -7689,8 +7693,50 @@ impl HostList { Some(gpu) } + /// Upload memory for a table's constant buffer (`len` bytes at `src`, + /// viewed by `slot`), deduplicated within this list until the list next + /// writes title memory: repeated binds of the same `(src, len)` share one + /// upload copy and one `Step::Fill`, attaching every slot so `card_steps` + /// retargets all of them. + pub(crate) fn constant_scratch( + &self, + src: *const u8, + len: u32, + slot: (usize, u32), + ) -> Option<(ID3D12Resource, u64)> { + let key = (src as usize, len as usize); + { + let mut deferred = self.deferred(); + if let Some((buffer, gpu, step_idx)) = deferred.constants.get(&key).cloned() { + if let Some(Step::Fill(_, _, _, Some(to))) = deferred.copies.get_mut(step_idx) { + match to { + card_steps::FillTo::Slot(h0, i0) => { + let first = (*h0, *i0); + *to = card_steps::FillTo::Slots(vec![first, slot]); + } + card_steps::FillTo::Slots(slots) => slots.push(slot), + card_steps::FillTo::Buffer(_) => {} + } + } + return Some((buffer, gpu)); + } + } + let (buffer, gpu, to) = self.scratch_held(u64::from(len))?; + let mut deferred = self.deferred(); + let step_idx = deferred.copies.len(); + deferred.copies.push(Step::Fill( + to as usize, + src as usize, + len as usize, + Some(card_steps::FillTo::Slot(slot.0, slot.1)), + )); + deferred.constants.insert(key, (buffer.clone(), gpu, step_idx)); + Some((buffer, gpu)) + } + /// As [`HostList::defer_fill`], for upload memory that only `slot` (a /// title heap's address, and the slot) shows. + #[allow(dead_code)] pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { self.deferred() .copies @@ -8248,21 +8294,22 @@ impl HostList { continue; } Step::Run(work) | Step::Host(work, _) => { - batch.fill(); - #[cfg(feature = "diagnostics")] - let started = std::time::Instant::now(); - if matches!(step, Step::Run(_)) { + let is_run = matches!(step, Step::Run(_)); + if is_run { + batch.fill(); batch.title_written(); // (It may write anywhere, a heap's records too.) if crate::heap_marks::on() { crate::heap_marks::prep_wrote(); } } + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); let _step = crate::timeline::span("a step of ours"); work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. - if matches!(step, Step::Run(_)) { + if is_run { crate::watch::ask_once_end(); } #[cfg(feature = "diagnostics")] @@ -9202,11 +9249,33 @@ impl Batch { // Below this many the threads cost more than they save. const FEW: usize = 96; const PART: usize = 64; + const RUN_PART: usize = 16; + const MAX_RUN: usize = 256 << 10; if self.fills.is_empty() { return; } let started = std::time::Instant::now(); - if self.fills.len() < FEW { + if fill_batch() && self.fills.len() >= 2 { + let mut fills = std::mem::take(&mut self.fills); + fills.sort_unstable_by(|a, b| a.1.cmp(&b.1).then(a.2.cmp(&b.2))); + // With userspace `safecopy`, only coalesce overlapping/duplicate `src` + // ranges (avoids double-copying non-overlapping adjacent fills through + // scratch while still keeping sorted-address cache locality). With + // kernel `ReadProcessMemory`, coalesce within a 4 KiB page to save syscalls. + let max_gap = if crate::safecopy::on() { None } else { Some(4096) }; + let runs = coalesce_fill_runs(&fills, max_gap, MAX_RUN); + if fills.len() < FEW || runs.len() < RUN_PART || !wide_fills() { + for run in runs { + run_fill_chunk(&fills, run); + } + } else { + crate::shadow::wide_each(runs.len().div_ceil(RUN_PART), move |i| { + for &run in runs.iter().skip(i * RUN_PART).take(RUN_PART) { + run_fill_chunk(&fills, run); + } + }); + } + } else if self.fills.len() < FEW || !wide_fills() { for (dst, src, len) in self.fills.drain(..) { copy_mapped(dst as *mut u8, src as *const u8, len, false); } @@ -9359,6 +9428,88 @@ impl Batch { } } +/// Whether [`Batch::fill`] sorts fills by source address and coalesces +/// duplicate/adjacent source ranges into one staging read (`VICTORY_FILL_BATCH=0` +/// disables; on by default). +fn fill_batch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_BATCH").is_none_or(|v| v != "0")) +} + +/// Groups `fills` (sorted by `(src, len)`) into coalesced runs +/// `(idx_start, idx_end, run_src_start, run_src_end)` with total span `<= max_run`. +/// When `max_gap` is `None`, only strictly overlapping/duplicate ranges (`src < last.3`) +/// are merged; when `Some(g)`, ranges separated by `<= g` bytes are also merged. +fn coalesce_fill_runs( + fills: &[(usize, usize, usize)], + max_gap: Option, + max_run: usize, +) -> Vec<(usize, usize, usize, usize)> { + let mut runs: Vec<(usize, usize, usize, usize)> = Vec::new(); + for (idx, &(_, src, len)) in fills.iter().enumerate() { + if len == 0 { + continue; + } + let end = src.saturating_add(len); + if let Some(last) = runs.last_mut() { + let new_end = last.3.max(end); + let close = match max_gap { + None => src < last.3, + Some(g) => src <= last.3.saturating_add(g), + }; + if len <= max_run + && close + && new_end.saturating_sub(last.2) <= max_run + && idx == last.1 + { + last.1 = idx + 1; + last.3 = new_end; + continue; + } + } + runs.push((idx, idx + 1, src, end)); + } + runs +} + +/// Executes one coalesced run of fills using a thread-local staging buffer +/// when multiple fills share or border the same source memory. +fn run_fill_chunk(fills: &[(usize, usize, usize)], run: (usize, usize, usize, usize)) { + thread_local! { + static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let slice = &fills[run.0..run.1]; + if slice.len() == 1 { + let (dst, src, len) = slice[0]; + copy_mapped(dst as *mut u8, src as *const u8, len, false); + return; + } + let (run_start, run_end) = (run.2, run.3); + let run_len = run_end - run_start; + let ok = SCRATCH.with_borrow_mut(|buf| { + if buf.len() < run_len { + buf.resize(run_len, 0); + } + if !read(run_start as *const u8, buf.as_mut_ptr(), run_len) { + return false; + } + for &(dst, src, len) in slice { + let off = src - run_start; + // SAFETY: `dst` is writable upload scratch of `len` bytes; + // `off + len <= run_len <= buf.len()`; non-overlapping. + unsafe { + std::ptr::copy_nonoverlapping(buf.as_ptr().add(off), dst as *mut u8, len); + } + } + true + }); + if !ok { + for &(dst, src, len) in slice { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + } +} + /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 9a7b349..519d22c 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -225,6 +225,8 @@ pub(super) enum FillTo { /// A descriptor slot that shows the fill's memory, and nothing else does /// (title heap, slot): it is made to show our buffer instead. Slot(usize, u32), + /// Multiple deduplicated descriptor slots sharing the same fill. + Slots(Vec<(usize, u32)>), /// A buffer the card can write, filled from its beginning. Buffer(ID3D12Resource), } @@ -659,6 +661,8 @@ enum To { Copy(Arc, usize), /// A descriptor slot (title heap, slot). Slot(usize, u32), + /// Multiple deduplicated descriptor slots sharing one fill. + Slots(Vec<(usize, u32)>), /// A buffer's beginning. Buffer(ID3D12Resource), } @@ -900,6 +904,7 @@ impl Host { } _ => match fill_to(runs, steps[i]) { Some(FillTo::Slot(heap, index)) => To::Slot(heap, index), + Some(FillTo::Slots(slots)) => To::Slots(slots), Some(FillTo::Buffer(buffer)) => To::Buffer(buffer), None => continue, }, @@ -957,7 +962,7 @@ impl Host { match &op.to { To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)), To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)), - To::Slot(..) => {} + To::Slot(..) | To::Slots(..) => {} } } record(level == 0, &own.list.list, &own.between, &reads, &writes); @@ -972,11 +977,19 @@ impl Host { let parts = if ops.len() < 256 { 1 } else { 8 }; crate::land::each_under(parts, &|part| { for op in &ops { - if let To::Slot(heap, index) = &op.to - && *index as usize / 4 % parts == part - { - // (A heap that is gone: nothing can read the slot.) - crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); + match &op.to { + To::Slot(heap, index) if *index as usize / 4 % parts == part => { + // (A heap that is gone: nothing can read the slot.) + crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); + } + To::Slots(slots) => { + for &(heap, index) in slots { + if index as usize / 4 % parts == part { + crate::descriptor::constant_slot(heap, index, &own.between, gpu + op.at, op.len as u32); + } + } + } + _ => {} } } }); @@ -1023,7 +1036,7 @@ fn noted(ops: &[Op]) { for op in ops { let (to, dst) = match &op.to { To::Copy(to, dst) => (to.span(), *dst), - To::Slot(..) | To::Buffer(_) => ((0, 0), 0), + To::Slot(..) | To::Slots(..) | To::Buffer(_) => ((0, 0), 0), }; let e = noted.entry((op.len, op.from.0.span(), to)).or_default(); *e = (e.0 + 1, op.from.1, dst); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 4dfb02b..993fef6 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -116,10 +116,16 @@ struct Last { not_watched: bool, } -/// Frames a guarded texture is hashed at every check from its first check, -/// and after the hash found a change the guard did not see. +/// Frames a guarded texture is hashed at every check after the hash found +/// a change the guard did not see. const HOT_FRAMES: u64 = 64; +/// Initial hot frames on a guarded texture's very first check: long enough +/// to catch ring-of-3 animated/video textures (which then promote to full +/// [`HOT_FRAMES`] via `found_blind`), without forcing hundreds of megabytes +/// of static cutscene/world textures to be re-hashed every frame for 64 frames. +const START_HOT_FRAMES: u64 = 4; + /// Whether a guarded texture whose memory the hash found changed although /// the guard saw no write is hashed at every check for a while /// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a @@ -1498,10 +1504,11 @@ impl Staging { let turn = frame .wrapping_add((start >> 16) as u64) .is_multiple_of(HASH_EVERY); - // A texture starts hot: one written that way from its first - // frames on changes before the hash has ever caught it. + // A texture starts hot briefly: one written through an alias view + // from its first frames on changes within 1-3 frames and is then + // promoted to full `HOT_FRAMES` by `found_blind`. if last.hot_until == 0 { - last.hot_until = frame + HOT_FRAMES; + last.hot_until = frame + START_HOT_FRAMES; } let hot = hot_textures() && frame < last.hot_until; if !exact && unwritten && !turn && !hot { diff --git a/scripts/play-6gb.ps1 b/scripts/play-6gb.ps1 index 3a81a74..4e2e9bb 100644 --- a/scripts/play-6gb.ps1 +++ b/scripts/play-6gb.ps1 @@ -162,8 +162,9 @@ $settings = [ordered]@{ VICTORY_HEAP_SYNC_AT_SUBMIT = '1' # Visuals (windowed by default; toggleable in F1 menu) - VICTORY_AMBIENT = '0.65' + VICTORY_AMBIENT = '0.8' VICTORY_AMBIENT_AIR = '1.5' + VICTORY_AMBIENT_SHADE = '0.5,0.5' VICTORY_AMBIENT_SPECULAR = '1' VICTORY_WATER_LIGHT = '1' VICTORY_EARLY_DEPTH = '1' @@ -173,10 +174,10 @@ $settings = [ordered]@{ VICTORY_PIPELINE_BOOK = '1' VICTORY_PIPELINE_WAIT_MS = '50' - # Memory stack (SLOT_EVICT aligned above ROOM% to prevent eviction thrashing) + # Memory stack (SLOT_EVICT sits just above ROOM% so idle textures evict cleanly when roaming) VICTORY_SLOT_EVICT = '1' - VICTORY_SLOT_EVICT_PERCENT = '92' - VICTORY_SLOT_EVICT_LOW_PERCENT = '82' + VICTORY_SLOT_EVICT_PERCENT = '88' + VICTORY_SLOT_EVICT_LOW_PERCENT = '78' VICTORY_ALLOCATOR_TRIM = '1' VICTORY_BUDGET_PACK = '1' VICTORY_TEARING = '1' @@ -198,7 +199,7 @@ if ($dlssMode -ne 'off' -and (Test-Path (Join-Path $slDir 'sl.interposer.dll'))) } $barMb = if ($DropMips -ge 2) { '768' } elseif ($fgOn) { '128' } else { '256' } -$roomPct = if ($DropMips -ge 2) { if ($fgOn) { '72' } else { '75' } } elseif ($fgOn) { '82' } else { '85' } +$roomPct = if ($DropMips -ge 2) { if ($fgOn) { '75' } else { '78' } } else { '86' } if ($dlssMode -ne 'off' -and $fgOn) { if ($fgKind -ne 'dlss' -and (Test-Path (Join-Path $fxDir 'amd_fidelityfx_framegeneration_dx12.dll'))) {