Просмотр исходного кода

Textures shaders write that the title reads on the CPU are copied back into title memory (from fxceless f5c03f3b, pull request 999: Geckomacabre 895c0b8f, 04df4350); on by default

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 день назад
Родитель
Сommit
23925a4aa2

+ 2 - 0
crates/victory-gpu/src/draw.rs

@@ -4171,6 +4171,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
         (View::Unordered(resource, _, _), ResourceType::Uav) => {
             #[cfg(feature = "diagnostics")]
             crate::capture::note_target(*resource as This);
+            // Some compute-written textures are also read by the title CPU.
+            list.texture_written(*resource as This);
             // Unordered access to a depth texture is its colour twin's.
             if !list.twin_use(*resource as This, true, true) {
                 crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);

+ 68 - 5
crates/victory-gpu/src/host.rs

@@ -2194,6 +2194,11 @@ struct Deferred {
     /// memory they go to, the bytes of a row, the rows, the title's row
     /// pitch.
     backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
+    /// Title textures of the kinds copied back ([`crate::texback`]) that
+    /// the list's shaders write, copied when the list closes.
+    back_wanted: Vec<crate::texback::Target>,
+    /// Those copies, whose texels go to title memory once the list has run.
+    texture_backs: Vec<crate::texback::Back>,
     /// Whether the indirect-work budget is zeroed for this recording (a
     /// step on the CPU, or in the list for the card's copy).
     budget_zeroed: bool,
@@ -2532,6 +2537,8 @@ struct Sent {
     back: Vec<Declared>,
     /// What was taken off it to be done on the card.
     own: Option<card_steps::Taken>,
+    /// Title-memory ranges written when its shader textures are copied back.
+    texture_back_ranges: Vec<(usize, usize)>,
     /// Its bottom-of-pipe writes.
     writes: Vec<(usize, crate::queue::Written, usize)>,
 }
@@ -2549,6 +2556,7 @@ struct Flight {
     back: Vec<Declared>,
     /// The list of ours that ran ahead of them ([`card_steps`]).
     own: Option<card_steps::Taken>,
+    texture_back_ranges: Vec<(usize, usize)>,
 }
 
 /// One thing in the line of what waits for the card, in order.
@@ -2562,8 +2570,8 @@ enum Late {
 
 struct Line {
     line: Vec<Late>,
-    /// The title memory the flights' shaders may write (address, end), in
-    /// order and joined.
+    /// The title memory the flights' shaders and texture readbacks may write
+    /// (address, end), in order and joined.
     written: Vec<(usize, usize)>,
     /// Host lists in the flights.
     lists: usize,
@@ -3725,6 +3733,11 @@ pub(crate) fn walls_trace() -> bool {
 /// without it, so the title read a buffer nobody wrote, as before read-backs
 /// were made (the exposure metering's two small float targets, every frame).
 fn read_backs(list: &HostList) {
+    // Textures shaders wrote that the title reads on the CPU
+    // ([`crate::texback`]).
+    for back in &list.deferred().texture_backs {
+        crate::texback::land(back);
+    }
     for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
         let mut data = std::ptr::null_mut();
         // SAFETY: a read-back buffer of ours, written by the list that has
@@ -4838,6 +4851,7 @@ impl Host {
                 if let Late::Run(flight) = item {
                     *lists += flight.order.len().max(1);
                     ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
+                    ranges.extend(flight.texture_back_ranges.iter().copied());
                 }
             }
             join_ranges(written, ranges);
@@ -5045,7 +5059,13 @@ impl Host {
         let most = {
             let mut line = line();
             let Line { line: items, written, lists: flying, target, .. } = &mut *line;
-            join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
+            join_ranges(
+                written,
+                sent.back
+                    .iter()
+                    .flat_map(|(_, ranges)| ranges.iter().copied())
+                    .chain(sent.texture_back_ranges.iter().copied()),
+            );
             *flying += order.len();
             *target = *submitted;
             items.push(Late::Run(Flight {
@@ -5056,6 +5076,7 @@ impl Host {
                 card: sent.card,
                 back: sent.back,
                 own: sent.own,
+                texture_back_ranges: sent.texture_back_ranges,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
             *flying >= late_most()
@@ -5093,7 +5114,13 @@ impl Host {
         {
             let mut line = line();
             let Line { line: items, written, lists: flying, target, .. } = &mut *line;
-            join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
+            join_ranges(
+                written,
+                sent.back
+                    .iter()
+                    .flat_map(|(_, ranges)| ranges.iter().copied())
+                    .chain(sent.texture_back_ranges.iter().copied()),
+            );
             *flying += 1;
             *target = *submitted;
             items.push(Late::Run(Flight {
@@ -5104,6 +5131,7 @@ impl Host {
                 card: sent.card,
                 back: sent.back,
                 own: sent.own,
+                texture_back_ranges: sent.texture_back_ranges,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
         }
@@ -5571,6 +5599,10 @@ impl Host {
             #[cfg(feature = "diagnostics")]
             split.part(5);
             let back = crate::picked::with(declared, &picked.written);
+            let mut texture_back_ranges = Vec::new();
+            for list in runs {
+                texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range));
+            }
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
             submitting(0, 0);
@@ -5581,6 +5613,7 @@ impl Host {
                 card,
                 back,
                 own,
+                texture_back_ranges,
                 writes,
             };
             working(was_working);
@@ -6035,6 +6068,7 @@ impl HostList {
     pub(crate) fn close(&self) {
         let _closing = crate::timeline::span("closing a host list");
         self.twins_to_depth();
+        self.textures_back();
         let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
         if let Some((scratch, _)) = scratch {
             self.indirect_common(&scratch);
@@ -6351,6 +6385,34 @@ impl HostList {
         }
     }
 
+    /// A draw or dispatch being prepared writes title texture `resource`
+    /// through unordered access: if it is of a kind copied back
+    /// ([`crate::texback`]), the list copies it when it closes.
+    pub(crate) fn texture_written(&self, resource: crate::object::This) {
+        if !crate::texback::wanted(resource) {
+            return;
+        }
+        let mut deferred = self.deferred();
+        if !deferred.back_wanted.iter().any(|target| target.owner() == resource as usize)
+            && let Some(target) = crate::texback::Target::new(resource)
+        {
+            deferred.back_wanted.push(target);
+        }
+    }
+
+    /// Before the list closes: the textures its shaders wrote that are copied
+    /// back go into read-back buffers ([`crate::texback::record`]).
+    fn textures_back(&self) {
+        const COPY_SOURCE: u32 = 0x800;
+        let wanted = std::mem::take(&mut self.deferred().back_wanted);
+        for target in wanted {
+            self.settle(&target.copy, COPY_SOURCE);
+            if let Some(back) = crate::texback::record(&self.list, target) {
+                self.deferred().texture_backs.push(back);
+            }
+        }
+    }
+
     /// The draw or dispatch just prepared is recorded: the twins it writes
     /// now hold what their depth textures lack.
     pub(crate) fn twins_written(&self) {
@@ -6518,7 +6580,8 @@ impl HostList {
                 && deferred.kept.is_empty()
                 && deferred.textures.is_empty()
                 && deferred.writes.is_empty()
-                && deferred.backs.is_empty())
+                && deferred.backs.is_empty()
+                && deferred.texture_backs.is_empty())
             {
                 return false;
             }

+ 2 - 0
crates/victory-gpu/src/lib.rs

@@ -87,6 +87,8 @@ pub mod titlewrite;
 mod upload;
 #[cfg(windows)]
 mod watch;
+#[cfg(windows)]
+mod texback;
 
 #[cfg(windows)]
 pub use host::on_failure;

+ 36 - 1
crates/victory-gpu/src/resource.rs

@@ -2690,6 +2690,7 @@ fn hand_out_resource(
     if desc.dimension != BUFFER {
         let at = std::ptr::from_ref::<Resource>(&resource) as usize;
         textures().insert(at);
+        crate::texback::replaced(resource.data() as usize);
         if !fills(&desc) {
             TARGETS_AT
                 .lock()
@@ -2714,7 +2715,9 @@ impl Drop for Resource {
         // Out of the table of textures first: the sweep looks at the ones
         // in it, under its lock.
         if self.desc.dimension != BUFFER {
-            textures().remove(&(std::ptr::from_ref::<Resource>(self) as usize));
+            let address = std::ptr::from_ref::<Resource>(self) as usize;
+            crate::texback::released(address);
+            textures().remove(&address);
             if !fills(&self.desc) {
                 let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
                 let at = self.data() as u64;
@@ -2946,6 +2949,38 @@ pub(crate) fn placed_filler_twins() -> u64 {
     PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
 }
 
+/// Width, height and format of texture `this` (`None` for a buffer), for
+/// `crate::texback`'s kinds.
+#[cfg(windows)]
+pub(crate) fn texture_kind(this: This) -> Option<(u64, u32, u32)> {
+    if this.is_null() {
+        return None;
+    }
+    let r = resource(this);
+    const TEXTURE_2D: u32 = 3;
+    (r.desc.dimension == TEXTURE_2D && r.desc.sample_count <= 1)
+        .then_some((r.desc.width, r.desc.height, r.desc.format))
+}
+
+/// Texture `this`'s console layout (one plane), where it lies in title
+/// memory and the bytes that layout takes, for `crate::texback`; `None` for
+/// a buffer or a texture with planes.
+#[cfg(windows)]
+pub(crate) fn title_texture(this: This) -> Option<(victory_formats::texture::Layout, usize, usize)> {
+    if this.is_null() {
+        return None;
+    }
+    let r = resource(this);
+    if r.desc.dimension == BUFFER {
+        return None;
+    }
+    let t = texture_layout(&r.desc)?;
+    let [plane] = &t.planes[..] else {
+        return None;
+    };
+    Some((plane.layout.clone(), r.data() as usize, t.size as usize))
+}
+
 /// The bytes of title memory a texture with the resource description
 /// `desc` (as words) takes where the title placed it; `None` for a buffer
 /// and for a description without a size.

+ 273 - 0
crates/victory-gpu/src/texback.rs

@@ -0,0 +1,273 @@
+//! Textures shaders write that the title's own code then reads on the CPU.
+//! On the console the CPU and the GPU share memory, so what a compute pass
+//! stores into a texture is in title memory for the CPU to read. Here it stays
+//! in the texture's host copy. The title's ocean is one: its wave passes write
+//! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and
+//! its CPU code samples both, which is what boats float on; it read memory
+//! nothing had written (run rw1, `VICTORY_READ_WATCH=1`: about 30 places in
+//! the title read those two kinds), and boats sank.
+//!
+//! For textures of the kinds in `VICTORY_TEXTURE_BACK` (comma-separated
+//! `<width>x<height>f<format>`; unset or `1`: the four water formats found by
+//! the upstream trace; `0`: none), a list in which shaders write one copies it
+//! into a read-back buffer of ours when it closes, and once the list has run
+//! the texels are tiled into the texture's title memory in the console's
+//! layout, as the console's GPU would have left them.
+//!
+//! shortcut: by kind, not by texture: textures of those kinds the title never
+//! reads are copied back too (about a megabyte per such list). The copy shows
+//! what the list's last write left; a title read in between sees the frame
+//! before, as it would before the console's GPU has run.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::object::This;
+
+/// The kinds copied back: (width, height, format).
+fn kinds() -> &'static [(u64, u32, u32)] {
+    static KINDS: OnceLock<Vec<(u64, u32, u32)>> = OnceLock::new();
+    KINDS.get_or_init(|| {
+        const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36";
+        let list = match std::env::var("VICTORY_TEXTURE_BACK").as_deref() {
+            Ok("1") | Err(_) => DEFAULT.to_owned(),
+            Ok(spec) => spec.to_owned(),
+        };
+        let kinds: Vec<(u64, u32, u32)> = list
+            .split(',')
+            .filter_map(|k| {
+                let (size, format) = k.trim().split_once('f')?;
+                let (w, h) = size.split_once('x')?;
+                Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?))
+            })
+            .collect();
+        if !kinds.is_empty() {
+            tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (VICTORY_TEXTURE_BACK)");
+        }
+        kinds
+    })
+}
+
+/// Whether title texture `resource` is of a kind copied back.
+pub(crate) fn wanted(resource: This) -> bool {
+    let kinds = kinds();
+    !kinds.is_empty()
+        && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k))
+}
+
+/// An outstanding write to a specific allocation. Mapping and resource
+/// changes invalidate only the writes that could touch the replaced memory.
+struct Ticket {
+    owner: usize,
+    at: usize,
+    end: usize,
+    valid: AtomicBool,
+}
+
+static TICKETS: Mutex<Vec<Weak<Ticket>>> = Mutex::new(Vec::new());
+static TRACKING: AtomicBool = AtomicBool::new(false);
+
+fn track(owner: usize, at: usize, end: usize) -> Arc<Ticket> {
+    let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) });
+    let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
+    tickets.retain(|weak| weak.strong_count() != 0);
+    tickets.push(Arc::downgrade(&ticket));
+    TRACKING.store(true, Ordering::Relaxed);
+    ticket
+}
+
+fn invalidate(matches: impl Fn(&Ticket) -> bool) {
+    if !TRACKING.load(Ordering::Relaxed) {
+        return;
+    }
+    TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| {
+        let Some(ticket) = weak.upgrade() else { return false };
+        if matches(&ticket) {
+            ticket.valid.store(false, Ordering::Release);
+        }
+        true
+    });
+}
+
+pub(crate) fn released(owner: usize) {
+    invalidate(|ticket| ticket.owner == owner);
+}
+
+pub(crate) fn replaced(at: usize) {
+    invalidate(|ticket| ticket.at == at);
+}
+
+pub(crate) fn remapped(at: usize, len: usize) {
+    let end = at.saturating_add(len);
+    invalidate(|ticket| at < ticket.end && ticket.at < end);
+}
+
+pub(crate) struct Target {
+    pub(crate) copy: Arc<crate::resource::HostTexture>,
+    layout: victory_formats::texture::Layout,
+    ticket: Arc<Ticket>,
+}
+
+impl Target {
+    pub(crate) fn new(resource: This) -> Option<Self> {
+        // Keep the host copy independently of the title's resource lifetime.
+        let copy = crate::resource::host_copy(resource)?;
+        let _mapping = crate::watch::title_memory_reading();
+        let (layout, at, size) = crate::resource::title_texture(resource)?;
+        let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?;
+        let ticket = track(resource as usize, at, end);
+        Some(Self { copy, layout, ticket })
+    }
+
+    pub(crate) fn owner(&self) -> usize { self.ticket.owner }
+}
+
+/// The readback resources and the allocation the pixels belong to.
+pub(crate) struct Back {
+    buffer: ID3D12Resource,
+    footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
+    rows: Vec<u32>,
+    mips: u32,
+    layout: victory_formats::texture::Layout,
+    ticket: Arc<Ticket>,
+}
+
+impl Back {
+    pub(crate) fn range(&self) -> (usize, usize) {
+        (self.ticket.at, self.ticket.end)
+    }
+}
+
+/// Records a host copy from a texture already in COPY_SOURCE.
+pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option<Back> {
+    if !target.ticket.valid.load(Ordering::Acquire) {
+        return None;
+    }
+    let host = crate::host::host()?;
+    let texture = &target.copy.texture;
+    // SAFETY: a live texture kept through the command list's state tracking.
+    let desc = unsafe { texture.GetDesc() };
+    let mips = u32::from(desc.MipLevels.max(1));
+    let subresources = mips * u32::from(desc.DepthOrArraySize.max(1));
+    let n = subresources as usize;
+    let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n];
+    let mut rows = vec![0u32; n];
+    let mut total = 0u64;
+    // SAFETY: out arrays of `n` entries.
+    unsafe {
+        host.device.GetCopyableFootprints(
+            &desc,
+            0,
+            subresources,
+            0,
+            Some(footprints.as_mut_ptr()),
+            Some(rows.as_mut_ptr()),
+            None,
+            Some(&mut total),
+        )
+    };
+    // The last footprint's advertised extent can omit row-end padding.
+    // The tiler reads a pitched slice, so the mapped buffer must include it.
+    for (footprint, &rows) in footprints.iter().zip(&rows) {
+        let format = footprint.Footprint;
+        let pitched = u64::from(format.RowPitch)
+            .checked_mul(u64::from(rows))?
+            .checked_mul(u64::from(format.Depth))?;
+        total = total.max(footprint.Offset.checked_add(pitched)?);
+    }
+    let buffer = host.read_back_buffer(total)?;
+    for (i, footprint) in footprints.iter().enumerate() {
+        let to = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: a borrowed pointer the location never releases.
+            pResource: unsafe { std::mem::transmute_copy(&buffer) },
+            Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint },
+        };
+        let from = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: as above.
+            pResource: unsafe { std::mem::transmute_copy(texture) },
+            Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 },
+        };
+        // SAFETY: an open list; the texture is in the copy-source state.
+        unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
+    }
+    Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket })
+}
+
+/// Once the list has run, tile its texels back into the same title allocation.
+pub(crate) fn land(back: &Back) {
+    static COPIED: AtomicU64 = AtomicU64::new(0);
+    static STALE: AtomicU64 = AtomicU64::new(0);
+    let _mapping = crate::watch::title_memory_reading();
+    let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
+    if !back.ticket.valid.load(Ordering::Acquire) {
+        let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1;
+        if skipped.is_power_of_two() {
+            tracing::info!(skipped, "skipping texture readbacks whose title allocation changed");
+        }
+        return;
+    }
+    let (at, end) = back.range();
+    let size = end - at;
+    let mut tiled = vec![0u8; size];
+    // Keep title bytes the subresources do not cover.
+    if !crate::host::read_into(at as *const u8, &mut tiled) {
+        return;
+    }
+    let mut data = std::ptr::null_mut();
+    // SAFETY: our read-back buffer, written by the list that has run.
+    unsafe {
+        if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() {
+            return;
+        }
+    }
+    for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() {
+        let (mip, slice) = (i as u32 % back.mips, i as u32 / back.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 buffer.
+        let linear = unsafe { std::slice::from_raw_parts(data.cast::<u8>().add(footprint.Offset as usize), len) };
+        if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) {
+            static ONCE: std::sync::Once = std::sync::Once::new();
+            ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled"));
+            // SAFETY: mapped above.
+            unsafe { back.buffer.Unmap(0, None) };
+            return;
+        }
+    }
+    // SAFETY: mapped above.
+    unsafe { back.buffer.Unmap(0, None) };
+    crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true);
+    let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1;
+    if copied == 1 || copied.is_multiple_of(128) {
+        tracing::info!(copied, bytes = size, "texture readback landed");
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn only_readbacks_for_changed_allocations_are_invalidated() {
+        let first = track(91, 0x1000, 0x2000);
+        let next = track(92, 0x2000, 0x3000);
+        let far = track(93, 0x4000, 0x5000);
+
+        remapped(0x0f00, 0x200);
+        assert!(!first.valid.load(Ordering::Acquire));
+        assert!(next.valid.load(Ordering::Acquire));
+        replaced(0x2000);
+        assert!(!next.valid.load(Ordering::Acquire));
+        assert!(far.valid.load(Ordering::Acquire));
+
+        released(93);
+        assert!(!far.valid.load(Ordering::Acquire));
+        assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire));
+    }
+}

+ 2 - 0
crates/victory-gpu/src/watch.rs

@@ -2317,6 +2317,7 @@ pub fn title_memory_reading_now() -> Option<Reading> {
 /// neither guarded nor writable) and a kernel read into it fail, so the
 /// write access is given back.
 pub fn title_memory_remapped(at: usize, len: usize) {
+    crate::texback::remapped(at, len);
     open(&mut title_memory_changed(at, len), at, at.saturating_add(len));
 }
 
@@ -2326,6 +2327,7 @@ pub fn title_memory_remapped(at: usize, len: usize) {
 /// before the unmapping would leave the address guarded, clean and known by
 /// its bits ([`PUBLISHED`]) with no view behind it.
 pub fn title_memory_unmapping(at: usize, len: usize) {
+    crate::texback::remapped(at, len);
     let mut g = title_memory_changed(at, len);
     if CHANGING.get().0 && len != 0 {
         CHANGING.set((true, true));