diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 46cf638c05..0f5e000a66 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -498,6 +498,8 @@ struct Deferred { refreshed: std::collections::HashSet<(usize, usize, usize)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// Staging for host textures that this list may upload before first use. + texture_uploads: std::collections::HashMap>, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, @@ -1066,25 +1068,34 @@ impl HostList { } } - /// At submission: the list that moves each texture this list uses from - /// its real state to the one the list starts with; the textures' real - /// states become those the list ends with. + /// Uploads changed textures and moves each texture from its real state + /// to the one the list starts with. This list leaves the ending states. fn prelude(&self) -> Option { + let deferred = self.deferred(); let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states - .values() - .filter_map(|(first, last, copy)| { - let real = copy.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - ) - }) - }) - .collect(); - if barriers.is_empty() { + let mut to_copy = Vec::new(); + let mut uploads = Vec::new(); + let mut barriers = Vec::new(); + for (key, (first, last, copy)) in states.iter() { + let first = D3D12_RESOURCE_STATES(*first as i32); + let real = D3D12_RESOURCE_STATES(copy.state.swap(*last, Ordering::Relaxed) as i32); + let before_first = if let Some(staging) = deferred.texture_uploads.get(key) + && staging.needs_upload() + { + let copy_dest = D3D12_RESOURCE_STATE_COPY_DEST; + if real != copy_dest { + to_copy.push(transition(©.texture, real, copy_dest)); + } + uploads.push((staging, ©.texture)); + copy_dest + } else { + real + }; + if before_first != first { + barriers.push(transition(©.texture, before_first, first)); + } + } + if barriers.is_empty() && uploads.is_empty() { return None; } let (allocator, list) = &self.prelude; @@ -1093,7 +1104,15 @@ impl HostList { let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; - list.ResourceBarrier(&barriers); + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (staging, texture) in uploads { + staging.record_copy(list, texture); + } + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); + } list.Close() }) }; @@ -1299,10 +1318,16 @@ 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)); + /// Refreshes staging at submission and uploads it in the prelude if + /// needed. The caller records the texture's intended first state. + pub(crate) fn defer_texture_upload( + &self, + copy: &std::sync::Arc, + staging: std::sync::Arc, + ) { + let mut deferred = self.deferred(); + deferred.copies.push(Step::Texture(staging.clone())); + deferred.texture_uploads.insert(std::sync::Arc::as_ptr(copy) as usize, staging); } /// Runs the list's submission-time steps; refreshes go into `batch` diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 20d529e46d..af3a1672d2 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -17,6 +17,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; use windows::Win32::Graphics::Direct3D12::*; @@ -35,7 +36,6 @@ macro_rules! once { pub(crate) struct Staging { buffer: ID3D12Resource, /// Its bytes. - #[cfg(feature = "diagnostics")] size: u64, data: *mut u8, footprints: Vec, @@ -45,6 +45,7 @@ pub(crate) struct Staging { mips: u32, memory: *const u8, last: Mutex, + pending_upload: AtomicBool, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -96,10 +97,8 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0 } -/// 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. +/// Prepares a title-written texture for the list's first use. The prelude +/// copies refreshed staging into the host texture before that use. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { let host_written = HOST_WRITTEN .lock() @@ -114,13 +113,9 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) let Some(staging) = staging(resource, texture) else { return; }; - const COPY_DEST: u32 = 0x400; - crate::list::ensure_state(list, resource, COPY_DEST); - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - for (i, footprint) in staging.footprints.iter().enumerate() { + if let Some(copy) = crate::resource::host_copy(resource) { #[cfg(feature = "diagnostics")] - { + for (i, footprint) in staging.footprints.iter().enumerate() { let f = footprint.Footprint; // SAFETY: live resources. let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; @@ -128,7 +123,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) 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 staging {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", d.Width, d.Height, d.DepthOrArraySize, @@ -146,34 +141,47 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) (gpu + footprint.Offset, len), ); } - let to = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(texture) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: i as u32, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: *footprint, - }, - }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + list.defer_texture_upload(©, staging); } - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); +} + +/// A copy footprint may leave the final row's trailing padding outside the +/// allocation returned by GetCopyableFootprints. +fn staging_subresource(data: &mut [u8], offset: u64, padded_bytes: usize) -> Option<&mut [u8]> { + let offset = usize::try_from(offset).ok()?; + let end = offset.saturating_add(padded_bytes).min(data.len()); + data.get_mut(offset..end) } impl Staging { + pub(crate) fn needs_upload(&self) -> bool { + self.pending_upload.load(Relaxed) + } + + /// Copies the staged subresources into a texture in COPY_DEST. + pub(crate) fn record_copy(&self, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) { + for (i, footprint) in self.footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&self.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + // SAFETY: an open list and both resources held through execution. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + self.pending_upload.store(false, Relaxed); + } + /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). pub(crate) fn refresh(&self) { - use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); let read = self.refresh_now(); let preparing = &crate::host::PREPARING; @@ -236,23 +244,28 @@ impl Staging { "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); } + // SAFETY: the mapped upload buffer is at least this large and is + // written only by the staging refresh. + let data = unsafe { std::slice::from_raw_parts_mut(self.data, self.size as usize) }; for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; - let len = pitch * rows as usize * f.Depth as usize; - // SAFETY: the subresource's part of the mapped staging buffer. - let linear = unsafe { - std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) + let depth_pitch = pitch * rows as usize; + let bytes = depth_pitch.saturating_mul(f.Depth as usize); + let Some(linear) = staging_subresource(data, footprint.Offset, bytes) else { + tracing::warn!(mip, slice, "texture footprint starts beyond its staging buffer"); + return; }; if let Err(e) = self.layout - .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) + .detile(tiled, mip, slice, linear, pitch, depth_pitch) { tracing::warn!(?e, mip, slice, "texture not detiled"); return; } } + self.pending_upload.store(true, Relaxed); } } @@ -335,7 +348,6 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let s = Arc::new(Staging { buffer, - #[cfg(feature = "diagnostics")] size: total, data, footprints, @@ -344,7 +356,163 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { mips: u32::from(d.MipLevels), memory, last: Mutex::default(), + pending_upload: AtomicBool::new(true), }); map.insert(resource as usize, s.clone()); Some(s) } + +#[cfg(test)] +mod staging_bounds_tests { + use super::staging_subresource; + + #[test] + fn final_staging_row_does_not_include_unallocated_padding() { + let mut data = [0xff; 48]; + let last = staging_subresource(&mut data, 16, 256).unwrap(); + assert_eq!(last.len(), 32); + last.fill(0); + assert_eq!(&data[..16], &[0xff; 16]); + assert_eq!(&data[16..], &[0; 32]); + assert!(staging_subresource(&mut data, 49, 256).is_none()); + } + + #[test] + #[ignore = "requires a D3D12 device with BC7 support"] + fn staged_bc7_mips_read_back_without_tail_padding() { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_BC7_UNORM_SRGB, DXGI_SAMPLE_DESC, + }; + + const MIPS: usize = 8; + let host = host().expect("native D3D12 device"); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 512, + DepthOrArraySize: 1, + MipLevels: MIPS as u16, + Format: DXGI_FORMAT_BC7_UNORM_SRGB, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut footprints = [D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); MIPS]; + let mut rows = [0; MIPS]; + let mut row_sizes = [0; MIPS]; + let mut bytes = 0; + // SAFETY: the outputs each have one entry per mip in desc. + unsafe { + host.device.GetCopyableFootprints( + &desc, 0, MIPS as u32, 0, Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), Some(row_sizes.as_mut_ptr()), Some(&mut bytes), + ); + } + let last = footprints[MIPS - 1]; + assert_eq!(bytes - last.Offset, row_sizes[MIPS - 1]); + assert!(row_sizes[MIPS - 1] < u64::from(last.Footprint.RowPitch)); + // SAFETY: these words are the console's heap and resource descriptors. + let (heap, title_desc) = unsafe { + ( + std::mem::transmute::<[u32; 5], crate::resource::HeapProperties>([1, 0, 0, 1, 1]), + std::mem::transmute::<[u32; 14], crate::resource::ResourceDesc>([ + 3, 0, 0, 0, 1024, 0, 512, 8 << 16 | 1, 99, 1, 0, 0, 0, 0, + ]), + ) + }; + let iid = crate::object::guid( + 0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ); + let mut resource = std::ptr::null(); + assert_eq!(crate::resource::create_committed( + std::ptr::null(), &heap, 0, &title_desc, 0, std::ptr::null(), &iid, &mut resource, + ), crate::object::S_OK); + let texture = crate::resource::host_resource(resource).expect("host texture"); + let staged = staging(resource, texture).expect("texture staging"); + let (memory, _) = crate::resource::texture_memory(resource).unwrap(); + let fill_title = |seed: u8| { + // SAFETY: the resource owns this allocation and no submission is running. + let tiled = unsafe { std::slice::from_raw_parts_mut(memory.cast_mut(), staged.layout.size as usize) }; + for (i, footprint) in footprints.iter().enumerate() { + let pitch = footprint.Footprint.RowPitch as usize; + let size = pitch * rows[i] as usize; + let linear = vec![seed + i as u8; size]; + staged.layout.tile(tiled, i as u32, 0, &linear, pitch, size).unwrap(); + } + }; + + let read_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: desc.SampleDesc, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: a readback heap accepts a buffer in COPY_DEST. + unsafe { + host.device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &read_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, + ).unwrap(); + } + let readback = readback.unwrap(); + let check = |seed: u8| { + let list = host.new_list().unwrap(); + let second = host.new_list().unwrap(); + for next in [&list, &second] { + upload(next, resource, texture); + crate::list::ensure_state(next, resource, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + } + for (i, footprint) in footprints.iter().enumerate() { + // SAFETY: the same footprints and live resources are used for readback. + unsafe { + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + } + list.close(); + second.close(); + host.execute(&[&list, &second]); + // SAFETY: execute waited for the copies before mapping the live buffer. + let copied = unsafe { + let mut mapped = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + std::slice::from_raw_parts(mapped.cast::(), bytes as usize) + }; + for (i, footprint) in footprints.iter().enumerate() { + for row in 0..rows[i] as usize { + let start = footprint.Offset as usize + row * footprint.Footprint.RowPitch as usize; + assert!(copied[start..start + row_sizes[i] as usize].iter().all(|&b| b == seed + i as u8), + "unexpected bytes in mip {i}, row {row}"); + } + } + // SAFETY: the contents were read while no submission was active. + unsafe { readback.Unmap(0, None) }; + }; + + fill_title(0x11); + check(0x11); + // A redundant copy would replace the texture with these sentinel bytes. + // SAFETY: the staging buffer is mapped, idle and writable. + unsafe { staged.data.write_bytes(0xff, staged.size as usize) }; + check(0x11); + fill_title(0x22); + check(0x22); + + let release = crate::object::slot:: u32>(resource, 0x10); + assert_eq!(release(resource), 0); + } +}