From 23a4b62bbb7d05aad96e43d8c2dde638ff8e43ef Mon Sep 17 00:00:00 2001 From: Marvis Date: Wed, 25 Nov 2026 06:34:36 +0100 Subject: [PATCH] GPU: a texture is uploaded once per submission, and only when its bytes changed Every list that read a title-written texture through a table recorded the copy of its staging buffer into the host texture, changed or not: run perf7 counted 3,195 texture copy commands in one frame for 149 textures (a 64x64x32 R16 array 24 times, a 512x512 BC7 18 times), 17 ms of GPU time, the largest single GPU item. A list now only defers the texture (staging and host texture). At submission the textures of all its lists are brought up to date once, and those whose memory changed are copied by the submission's own upload list (the one heap-indexed textures already had), which runs first. For memory the change journal follows, a flagged page uploads the texture only if the texture's own bytes changed (a 64 KiB page holds other data too). As for heap-indexed textures, a title copy into texture memory recorded in the same submission shows from the next one on. Test: two lists of one submission upload a texture once, the next submission not at all, and again once the title writes it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 22 ++++- crates/victory-gpu/src/draw.rs | 45 +++++++++++ crates/victory-gpu/src/host.rs | 124 ++++++++--------------------- crates/victory-gpu/src/texture.rs | 61 +++++++++++--- 4 files changed, 142 insertions(+), 110 deletions(-) diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index e2fb5a4..974df96 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -187,13 +187,18 @@ fn left_kind(view: &View) -> (usize, u64, u64) { } /// At submission, before anything else of it: the textures the heaps of its -/// heap-indexing lists view are brought up to date, those whose title -/// memory changed copied into their host textures by a list of ours, which -/// the submission runs first (and leaves them readable by shaders). +/// heap-indexing lists view, and `textures` (staging and host texture of +/// those its lists read through tables, `crate::texture::upload`), are +/// brought up to date, those whose title memory changed copied into their +/// host textures by a list of ours, which the submission runs first (and +/// leaves them readable by shaders): each at most once. /// /// shortcut: a title copy into texture memory recorded in the same /// submission shows from the next one on. -pub(crate) fn uploads(heaps: &[Arc]) -> Option { +pub(crate) fn uploads( + heaps: &[Arc], + textures: &[(Arc, Arc)], +) -> Option { static LIST: Mutex = Mutex::new(Holder(None)); const SHADER_RESOURCE: u32 = 0x40 | 0x80; let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); @@ -205,6 +210,15 @@ pub(crate) fn uploads(heaps: &[Arc]) -> Option { } let list = guard.0.as_ref()?; let mut recorded = false; + let mut staged = std::collections::HashSet::new(); + for (staging, copy) in textures { + if staged.insert(Arc::as_ptr(staging)) && staging.refresh() { + crate::texture::record_upload(list, copy, staging); + recorded = true; + #[cfg(feature = "diagnostics")] + UPLOADED.fetch_add(1, Relaxed); + } + } let mut done = std::collections::HashSet::new(); for viewed in heaps { // Held while uploading: the title releasing a texture (and its diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a3eb0ea..a334928 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2351,6 +2351,51 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// A texture the title wrote, read through tables by two lists of one + /// submission, is uploaded once; the next submission uploads it again + /// only after the title writes it (run perf7 uploaded the same textures + /// up to 24 times a frame). + #[test] + fn a_texture_is_uploaded_once_per_submission_and_only_when_written() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // Runtime memory the change journal follows; RGBA8 64x64, linear. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let submit = |byte: Option| { + if let Some(byte) = byte { + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, byte, 64 * 64 * 4) }; + } + let lists = [host.new_list().unwrap(), host.new_list().unwrap()]; + for list in &lists { + readable(list, &used(ResourceType::Srv), &view, false); + run(list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + } + let before = crate::texture::UPLOADS.load(Ordering::Relaxed); + host.execute(&[&lists[0], &lists[1]]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::UPLOADS.load(Ordering::Relaxed) - before, texel[0]) + }; + let (n, x) = submit(Some(0x40)); + assert_eq!(n, 1, "one upload for two lists"); + assert!((x - 64.0 / 255.0).abs() < 1e-6); + assert_eq!(submit(None).0, 0, "not written: not uploaded"); + let (n, x) = submit(Some(0x80)); + assert_eq!(n, 1, "written: uploaded again"); + assert!((x - 128.0 / 255.0).abs() < 1e-6); + } + /// A depth texture with stencil (the console's 16-bit depth, the /// host's 32-bit float) written through unordered views of its planes, /// then read as depth and stencil: the 16-bit depth arrives as the diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b49b391..aaedce3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -729,7 +729,7 @@ enum Step { GpuWrite(std::sync::Arc, usize, usize, bool), /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. - Texture(std::sync::Arc), + Texture(std::sync::Arc, std::sync::Arc), /// Brings every buffer range a view heap's views reach up to date /// (`crate::bindless`). Heap(std::sync::Arc), @@ -918,10 +918,24 @@ impl Host { .collect::>() }) .collect(); + // And textures read through tables, uploaded by the same list. + let textures: Vec<_> = runs + .iter() + .flat_map(|l| { + l.deferred() + .copies + .iter() + .filter_map(|s| match s { + Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), + _ => None, + }) + .collect::>() + }) + .collect(); #[cfg(feature = "diagnostics")] let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs); - let uploads = (!heaps.is_empty()) - .then(|| crate::bindless::uploads(&heaps)) + let uploads = (!heaps.is_empty() || !textures.is_empty()) + .then(|| crate::bindless::uploads(&heaps, &textures)) .flatten(); #[cfg(feature = "diagnostics")] drop(uploading); @@ -1893,10 +1907,15 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } - /// Brings a texture's staging buffer up to date when the list is - /// submitted, keeping it alive until the list is reset. - pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { - self.deferred().copies.push(Step::Texture(staging)); + /// Brings a texture's staging buffer and host texture `copy` up to date + /// when the list is submitted (`crate::bindless::uploads`), keeping + /// both alive until the list is reset. + pub(crate) fn defer_texture( + &self, + staging: std::sync::Arc, + copy: std::sync::Arc, + ) { + self.deferred().copies.push(Step::Texture(staging, copy)); } /// Runs the list's submission-time steps; refreshes go into `batch` @@ -1915,7 +1934,7 @@ impl HostList { Step::Copy(..) | Step::Fill(..) => C::StepCopyUs, Step::Run(_) | Step::Host(_) => C::StepWorkUs, Step::GpuWrite(..) => C::StepGpuWriteUs, - Step::Texture(_) => C::StepTextureUs, + Step::Texture(..) => C::StepTextureUs, Step::Heap(_) => C::StepHeapUs, Step::Memory(_) => C::StepMemoryUs, }, @@ -1970,12 +1989,8 @@ impl HostList { shadow.writing(*address, *len, *marked); continue; } - Step::Texture(staging) => { - if batch.texture_due(staging) { - staging.refresh(); - } - continue; - } + // Brought up to date before the submission's lists were made. + Step::Texture(..) => continue, Step::Heap(viewed) => { crate::bindless::refresh(viewed, |s, a, l| batch.add(s, a, l)); continue; @@ -2013,8 +2028,6 @@ struct Batch { /// The range of each copy brought up to date since the last title /// write, by copy (held, so that its address names no other). current: std::collections::HashMap, usize, usize)>, - /// Staging buffers (by address) refreshed since the last title write. - textures: std::collections::HashSet, } impl Batch { @@ -2040,17 +2053,10 @@ impl Batch { } } - /// Whether `staging` is still to be refreshed in this submission (and - /// notes it refreshed). - fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { - self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) - } - /// Before a step that writes title memory: pending refreshes are done /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); - self.textures.clear(); self.current.clear(); } @@ -3129,38 +3135,8 @@ fn pump() { } #[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod batch { // `mod tests` is already taken at the top of this file use super::Batch; - use std::sync::Arc; - - #[test] - fn a_texture_is_checked_once_per_submission() { - let mut batch = Batch::default(); - let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); - // The first list sampling each texture checks it ... - assert!(batch.texture_due(&a)); - assert!(batch.texture_due(&b)); - // ... later lists of the same submission do not. - assert!(!batch.texture_due(&a)); - assert!(!batch.texture_due(&a.clone())); - assert!(!batch.texture_due(&b)); - } - - #[test] - fn title_writes_make_textures_due_again() { - let mut batch = Batch::default(); - let a = Arc::new(1u32); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A copy into title memory or work that may write it may have - // changed the texture's memory. - batch.title_written(); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A fresh submission starts over. - let mut next = Batch::default(); - assert!(next.texture_due(&a)); - } /// A host copy of tracked title memory: a submission whose lists all ask /// for it whole copies the one page the title wrote, once, and again @@ -3197,43 +3173,5 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at drop(copy); crate::watch::tests::free(p); } - - /// The hashing a submission does for textures in physical-page memory, - /// with every list checking the textures it samples (before) and with - /// each checked once (after). Run with - /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. - #[test] - #[ignore = "benchmark"] - fn texture_checks_per_submission() { - const TEXTURES: usize = 48; - const SIZE: usize = 4 << 20; - const LISTS: usize = 12; - let textures: Vec>> = (0..TEXTURES) - .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) - .collect(); - let submit = |dedupe: bool| { - let mut batch = Batch::default(); - let mut hashed = 0usize; - let started = std::time::Instant::now(); - for _ in 0..LISTS { - for t in &textures { - if !dedupe || batch.texture_due(t) { - std::hint::black_box(blake3::hash(t)); - hashed += 1; - } - } - } - (started.elapsed(), hashed) - }; - submit(false); // warm up - let (before, n_before) = submit(false); - let (after, n_after) = submit(true); - assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); - println!( - "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ - before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", - SIZE >> 20, - before.as_secs_f64() / after.as_secs_f64() - ); - } } + diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index cfac0d8..4627e01 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -52,8 +52,7 @@ pub(crate) struct Staging { last: Mutex, } -/// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not tracked). +/// What a texture's staging buffer holds: the hash of the memory detiled. #[derive(Default)] struct Last { hash: Option, @@ -195,10 +194,13 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { } } -/// Records, once per list, the copy of `resource`'s staging buffer into -/// its host copy, and the detiling that refreshes the staging buffer at -/// submission if the memory changed. Leaves the texture in the copy -/// destination state. +/// Has `resource`'s host copy brought up to date at the submission that +/// runs `list`: its staging buffer detiled again if the memory changed, and +/// then copied into the host texture by the submission's own upload list, +/// once for all its lists (`crate::bindless::uploads`). +/// +/// shortcut: a title copy into texture memory recorded in the same +/// submission shows from the next one on. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. @@ -220,16 +222,35 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) if !list.first_use(texture.as_raw() as usize) { return; } - let Some(staging) = staging(resource, texture) else { + let (Some(staging), Some(copy)) = (staging(resource, texture), crate::resource::host_copy(resource)) else { return; }; - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - record(list, resource, texture, &staging); - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // Each list recorded the copy before (run perf7: 149 textures uploaded + // 3,195 times in a frame, 17 ms of GPU time), changed or not. + list.defer_texture(staging, copy); } +/// Records into `list` the copy of `staging` into host texture `copy`, +/// leaving it readable by shaders. +pub(crate) fn record_upload(list: &HostList, copy: &Arc, staging: &Staging) { + const COPY_DEST: u32 = 0x400; + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let move_to = |wanted| { + if let Some(b) = list.move_texture(copy, wanted) { + // SAFETY: an open list; the barrier names a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; + } + }; + move_to(COPY_DEST); + copies(list, ©.texture, staging, String::new); + move_to(SHADER_RESOURCE); + list.keep(&staging.buffer); + UPLOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Uploads [`record_upload`] recorded. +pub(crate) static UPLOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// For textures shaders reach through the heap itself, at submission /// (`crate::bindless::uploads`): brings the staging buffer up to date and /// records its copy into `list` only if the memory changed since (or was @@ -255,6 +276,13 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) { const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); + copies(list, texture, staging, || format!("{resource:?}")); +} + +/// Records the copy of every subresource of `staging` into `texture` (in +/// the copy destination state); `name` names it in diagnostics notes. +#[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] +fn copies(list: &HostList, texture: &ID3D12Resource, staging: &Staging, name: impl Fn() -> String) { for (i, footprint) in staging.footprints.iter().enumerate() { #[cfg(feature = "diagnostics")] { @@ -265,7 +293,8 @@ fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &S list.note_read( || { format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + "texture upload {} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + name(), d.Width, d.Height, d.DepthOrArraySize, @@ -332,6 +361,12 @@ impl Staging { // double each texture's system memory. let mut read = vec![0u8; size]; crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + // Its pages also hold other data the title writes (64 KiB pages, + // small textures): its own bytes decide. + let hash = blake3::hash(&read); + if last.hash.replace(hash) == Some(hash) { + return (size, false); + } self.detile(&read); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64);