GPU: detile only texture subresources affected by writes #1135

Open
github-bot wants to merge 1 commit from github-bot/gh-1135 into main AGit
Owner

@⁠divyeshganta on GitHub · 2026-11-24 16:06 UTC · original
divyeshganta:perf/partial-texture-detile → main · +296 −20 · 2 files · 1 commits · open

Fixes #915.

When title memory changes, only re-read the changed 64 KiB pages on the write-watched path (or hash individual pages on the fallback path), then detile only the mips and slices whose tiled extents overlap those pages. The first detile and full host-texture upload remain unchanged.

Patch by talakasse (af4fef40372e4e1bf75b1d1600c36656b4b3ad26), carried with its original authorship.

The contributor reports Windows 10 MSVC checks: victory-formats 24 passed / 4 ignored; GPU diagnostics 56 passed / 1 ignored, including the new texture tests. A synthetic WARP fixture covered changed mips and slices plus both hash and write-watch paths. It did not submit a draw or measure in-game performance. I have not rerun these checks locally.

Known limitation from the report: a page decommitted without a write can leave stale bytes in the kept copy, although this gap existed before the change. The refresh path also has textual overlap with #143, #388, #401, and #641, so it may need rebasing if one of those merges first.

**@⁠divyeshganta** on GitHub · 2026-11-24 16:06 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135) `divyeshganta:perf/partial-texture-detile` → `main` · +296 −20 · 2 files · 1 commits · open Fixes #915. When title memory changes, only re-read the changed 64 KiB pages on the write-watched path (or hash individual pages on the fallback path), then detile only the mips and slices whose tiled extents overlap those pages. The first detile and full host-texture upload remain unchanged. Patch by talakasse (`af4fef40372e4e1bf75b1d1600c36656b4b3ad26`), carried with its original authorship. The contributor reports Windows 10 MSVC checks: `victory-formats` 24 passed / 4 ignored; GPU diagnostics 56 passed / 1 ignored, including the new texture tests. A synthetic WARP fixture covered changed mips and slices plus both hash and write-watch paths. It did not submit a draw or measure in-game performance. I have not rerun these checks locally. Known limitation from the report: a page decommitted without a write can leave stale bytes in the kept copy, although this gap existed before the change. The refresh path also has textual overlap with #143, #388, #401, and #641, so it may need rebasing if one of those merges first.
A change to a title texture's memory detiled every mip and slice again,
and the watched path read the whole memory back first. A streamed
texture filling page by page paid for all of it at every submission
that sampled it.

Layout::extents gives the tiled byte ranges each subresource is detiled
from. Watched memory now reads again only the pages written since the
last detiling; memory that is hashed instead is hashed per 64 KiB page.
Either way only the subresources overlapping a changed page are
detiled. The first detiling, and memory whose read copy is gone, still
take the whole texture, and every subresource is still copied into the
host texture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:20:51 +00:00
Author
Owner

@⁠Zipettte on GitHub · 2026-11-24 18:01 UTC · original

Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at af4fef4: cargo test -p victory-formats -p victory-gpu passes, 77 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed).

Tested with AI assistance (Claude).

**@⁠Zipettte** on GitHub · 2026-11-24 18:01 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7140046256) Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at af4fef4: `cargo test -p victory-formats -p victory-gpu` passes, 77 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed). _Tested with AI assistance (Claude)._
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 00:36 UTC · original

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: crates/victory-gpu/src/texture.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 00:36 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7148697613) <!-- victory-triage v1 head=af4fef40372e4e1bf75b1d1600c36656b4b3ad26 verdict=needs-rebase at=2026-11-25T00:13:20Z --> Automated triage for the maintainers. **Needs rebase.** This PR does not merge cleanly into current `main` (ac2525d). Conflicting files: `crates/victory-gpu/src/texture.rs`. The content has not been reviewed yet; it will be once the branch is rebased onto `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠wwwwwwww3333333 on GitHub · 2026-11-25 00:48 UTC · original

This PR no longer merges with main (70564ae0): main moved texture tracking to watch::Tracked, which conflicts with this PR in crates/victory-gpu/src/texture.rs. I ported your approach onto main's model and took it a bit further. Tested on AMD.

What the port does (credit for the idea and the Layout::extents part, taken as is with its test, goes to this PR):

  • Tracked memory. Tracked::take already returns the written page runs; only those are read again into the copy. The first refresh reads everything.
  • Subresources. Only the subresources whose extents overlap the written bytes are detiled again.
  • Inside a subresource. A new Layout::detile_ranges copies only the bytes in the written ranges. It skips whole rows whose tiled span misses them, through a walk_rows that walk now calls. Without this, a write into mip 0 (about 75% of a 4K texture) still costs most of a full detile.
  • Hashed (untracked) memory. One hash per 64 KiB instead of one for the whole texture, so a change re-detiles only the chunks that differ.
  • Copy to the host texture. On the upload_changed path (bindless, recorded at submission), only the subresources detiled again are copied; the host texture already holds the rest. The upload path still copies every subresource, because it records before the refresh. The module's shortcut note now says so.

Results on 70564ae0 + this, RX 6750 XT, i5-13400F, Windows 11, Rust 1.98.1 MSVC.

Timing (release, ignored test detile_one_written_page_of_a_4k_bc7_texture): a 4096x4096 BC7 texture (21 MiB, full chain) with one 64 KiB page written in the middle of mip 0.

  • Detile everything (main): 4.46 ms.
  • With this: 0.080 ms.

New tests:

  • victory-formats: extents_hold_what_a_subresource_detiles (from this PR) and detiling_ranges_matches_detiling_the_merged_memory.
  • victory-gpu: detiling_the_changed_subresources_matches_detiling_all, over 5 layouts × 6 sets of written pages, including 3D and linear. Partial detiling onto the old result is byte-identical to detiling everything.
  • victory-gpu: changed_chunks_name_the_chunks_written.

Suites and clippy:

  • victory-formats 25/25 and victory-gpu 80/80, twice each.
  • cargo clippy -p victory-formats -p victory-gpu --all-targets -- -D warnings: clean.

Not measured: how much of a frame this saves in a title. That needs a world run, which I can't do here.

Patch against 70564ae0
diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs
index 6a735b6c..54fcca3b 100644
--- a/crates/victory-formats/src/texture.rs
+++ b/crates/victory-formats/src/texture.rs
@@ -599,6 +599,88 @@ impl Layout {
         })
     }
 
+    /// As [`Layout::detile`], but only the bytes of tiled memory inside
+    /// `ranges` (sorted, disjoint) are copied; the rest of `linear` keeps
+    /// what it held. Detiling the pages written since the last detiling
+    /// into the same rows gives what [`Layout::detile`] would.
+    #[allow(clippy::too_many_arguments)]
+    pub fn detile_ranges(
+        &self,
+        tiled: &[u8],
+        mip: u32,
+        slice: u32,
+        linear: &mut [u8],
+        row_pitch: usize,
+        depth_pitch: usize,
+        ranges: &[std::ops::Range<usize>],
+    ) -> Result<(), Error> {
+        let touched = |from: usize, to: usize| {
+            ranges
+                .get(ranges.partition_point(|r| r.end <= from))
+                .is_some_and(|r| r.start < to)
+        };
+        self.walk_rows(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, touched, |t, l, len| {
+            let end = t + len;
+            let mut i = ranges.partition_point(|r| r.end <= t);
+            while let Some(r) = ranges.get(i) {
+                if r.start >= end {
+                    break;
+                }
+                let (a, b) = (r.start.max(t), r.end.min(end));
+                linear[l + (a - t)..l + (b - t)].copy_from_slice(&tiled[a..b]);
+                i += 1;
+            }
+        })
+    }
+
+    /// The byte ranges of tiled memory that [`Layout::detile`] reads for
+    /// mip `mip` of array slice `slice` (3D: every depth slice of the mip,
+    /// `slice` 0): sorted, disjoint, one per depth slice or slab at most.
+    /// A mip in the tail gets the part of the tail block its elements span,
+    /// which other tail mips may share; a write outside every range leaves
+    /// the subresource's detiled contents as they were.
+    pub fn extents(&self, mip: u32, slice: u32) -> Result<Vec<std::ops::Range<u64>>, Error> {
+        let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
+        let bytes = m.width as usize * self.desc.element_bytes as usize;
+        let depth_pitch = bytes * m.height as usize;
+        let mut spans: Vec<std::ops::Range<u64>> = Vec::new();
+        let z_of = |linear: usize| linear / depth_pitch;
+        let mut current: Option<(usize, std::ops::Range<u64>)> = None;
+        self.walk(
+            self.size as usize,
+            mip,
+            slice,
+            usize::MAX,
+            bytes,
+            depth_pitch,
+            |tiled, linear, len| {
+                let z = z_of(linear);
+                let run = tiled as u64..(tiled + len) as u64;
+                match &mut current {
+                    Some((at, r)) if *at == z => {
+                        r.start = r.start.min(run.start);
+                        r.end = r.end.max(run.end);
+                    }
+                    _ => {
+                        if let Some((_, r)) = current.replace((z, run)) {
+                            spans.push(r);
+                        }
+                    }
+                }
+            },
+        )?;
+        spans.extend(current.map(|(_, r)| r));
+        spans.sort_by_key(|r| r.start);
+        let mut merged: Vec<std::ops::Range<u64>> = Vec::with_capacity(spans.len());
+        for r in spans {
+            match merged.last_mut() {
+                Some(last) if r.start <= last.end => last.end = last.end.max(r.end),
+                _ => merged.push(r),
+            }
+        }
+        Ok(merged)
+    }
+
     /// The reverse of [`Layout::detile`]: linear rows into tiled memory.
     pub fn tile(
         &self,
@@ -625,6 +707,23 @@ impl Layout {
         row_pitch: usize,
         depth_pitch: usize,
         mut copy: impl FnMut(usize, usize, usize),
+    ) -> Result<(), Error> {
+        self.walk_rows(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, |_, _| true, &mut copy)
+    }
+
+    /// As [`Layout::walk`], visiting only the rows whose tiled bytes
+    /// `[from, to)` (the span of the row's runs) `row` accepts.
+    #[allow(clippy::too_many_arguments)]
+    fn walk_rows(
+        &self,
+        tiled_len: usize,
+        mip: u32,
+        slice: u32,
+        linear_len: usize,
+        row_pitch: usize,
+        depth_pitch: usize,
+        row: impl Fn(usize, usize) -> bool,
+        mut copy: impl FnMut(usize, usize, usize),
     ) -> Result<(), Error> {
         let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
         let depth = m.depth;
@@ -671,6 +770,9 @@ impl Layout {
             }
             runs.push((first_tiled, first_linear, bytes - first_linear));
         }
+        let (lo, hi) = runs
+            .iter()
+            .fold((usize::MAX, 0), |(lo, hi), &(t, _, len)| (lo.min(t), hi.max(t + len)));
         for z in 0..depth {
             let (s, inner) = self.split(first + z);
             let base = u64::from(s) * self.slice_size + m.offset;
@@ -678,9 +780,14 @@ impl Layout {
                 let linear_row = z as usize * depth_pitch + y as usize * row_pitch;
                 if linear {
                     let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64;
-                    copy(tiled_row as usize, linear_row, bytes);
+                    if row(tiled_row as usize, tiled_row as usize + bytes) {
+                        copy(tiled_row as usize, linear_row, bytes);
+                    }
                 } else {
                     let tiled_row = (base + self.row(m, y, inner)) as usize;
+                    if !row(tiled_row + lo, tiled_row + hi) {
+                        continue;
+                    }
                     for &(tiled, linear, len) in &runs {
                         copy(tiled_row + tiled, linear_row + linear, len);
                     }
@@ -944,6 +1051,122 @@ mod tests {
         }
     }
 
+    /// Detiling only some ranges onto an earlier detiling gives what
+    /// detiling all of memory whose other bytes are the earlier ones gives.
+    #[test]
+    fn detiling_ranges_matches_detiling_the_merged_memory() {
+        let cases = [
+            desc(256, 256, 9, 4, Swizzle::SW_64KB_D),
+            desc(300, 200, 9, 16, Swizzle::SW_4KB_S),
+            desc(100, 60, 7, 4, Swizzle::LINEAR),
+            desc(83, 31, 6, 1, Swizzle::SW_256B_S),
+        ];
+        for d in cases {
+            let l = Layout::new(&d).unwrap();
+            let size = l.size as usize;
+            let old: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
+            let mid = size / 3..(size / 3 + 5000).min(size / 2);
+            let ranges = [100..900.min(size / 4), mid, size - size / 8..size];
+            let mut merged = old.clone();
+            for r in &ranges {
+                for b in &mut merged[r.clone()] {
+                    *b = !*b;
+                }
+            }
+            for mip in 0..d.mips {
+                let m = l.mips[mip as usize];
+                let row = m.width as usize * d.element_bytes as usize;
+                let plane = row * m.height as usize;
+                let mut partial = vec![0; plane];
+                l.detile(&old, mip, 0, &mut partial, row, plane).unwrap();
+                l.detile_ranges(&merged, mip, 0, &mut partial, row, plane, &ranges)
+                    .unwrap();
+                let mut whole = vec![0; plane];
+                l.detile(&merged, mip, 0, &mut whole, row, plane).unwrap();
+                assert_eq!(partial, whole, "{d:?} mip {mip}");
+            }
+        }
+    }
+
+    /// A subresource's extents hold every element it detiles, and bytes
+    /// outside them do not change what it detiles to.
+    #[test]
+    fn extents_hold_what_a_subresource_detiles() {
+        let cases = [
+            desc(64, 64, 7, 16, Swizzle::SW_64KB_D),
+            desc(100, 60, 7, 4, Swizzle::SW_64KB_D),
+            desc(250, 175, 8, 8, Swizzle::SW_4KB_S),
+            desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
+            desc(30, 20, 5, 4, Swizzle::LINEAR),
+            desc(83, 31, 6, 1, Swizzle::SW_256B_S),
+            Desc {
+                depth: 3,
+                ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
+            },
+            Desc {
+                depth: 4,
+                ..desc(30, 20, 3, 4, Swizzle::LINEAR)
+            },
+            Desc {
+                dimension: Dimension::Tex3d,
+                depth: 16,
+                ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S)
+            },
+        ];
+        for d in cases {
+            let l = Layout::new(&d).unwrap();
+            let size = l.size as usize;
+            let tiled: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
+            let slices = if d.dimension == Dimension::Tex3d {
+                1
+            } else {
+                d.depth
+            };
+            for slice in 0..slices {
+                for mip in 0..d.mips {
+                    let e = l.extents(mip, slice).unwrap();
+                    assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}");
+                    for w in e.windows(2) {
+                        assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}");
+                    }
+                    assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size));
+                    let inside = |at: u64| e.iter().any(|r| r.contains(&at));
+                    let m = l.mips[mip as usize];
+                    let n = u64::from(d.element_bytes);
+                    // Outside the tail a 2D mip's extent is its own blocks.
+                    if m.tail.is_none() && d.dimension != Dimension::Tex3d {
+                        let total: u64 = e.iter().map(|r| r.end - r.start).sum();
+                        let own = u64::from(m.pitch) * u64::from(m.rows) * n;
+                        assert!(total <= own, "{d:?} mip {mip}: {total} > {own}");
+                    }
+                    for z in 0..m.depth {
+                        for y in 0..m.height {
+                            for x in 0..m.width {
+                                let at = l.offset(mip, x, y, slice + z).unwrap();
+                                assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}");
+                            }
+                        }
+                    }
+                    let row = m.width as usize * n as usize;
+                    let plane = row * m.height as usize;
+                    let mut before = vec![0; plane * m.depth as usize];
+                    l.detile(&tiled, mip, slice, &mut before, row, plane)
+                        .unwrap();
+                    let mut changed = tiled.clone();
+                    for (i, b) in changed.iter_mut().enumerate() {
+                        if !inside(i as u64) {
+                            *b = !*b;
+                        }
+                    }
+                    let mut after = vec![0; before.len()];
+                    l.detile(&changed, mip, slice, &mut after, row, plane)
+                        .unwrap();
+                    assert_eq!(before, after, "{d:?} mip {mip} slice {slice}");
+                }
+            }
+        }
+    }
+
     /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
     /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
     /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
index 524cc568..f1963da3 100644
--- a/crates/victory-gpu/src/texture.rs
+++ b/crates/victory-gpu/src/texture.rs
@@ -10,7 +10,11 @@
 //! same physical pages) in the runtime's memory; elsewhere, a content hash
 //! of the whole memory at every submission that samples it.
 //!
-//! shortcut: a change detiles the whole texture, not the pages written.
+//! In tracked memory only the pages written are read again and detiled
+//! again (into the subresources whose memory holds them).
+//!
+//! shortcut: hashed memory detiles the whole texture on a change; every
+//! subresource is still copied into the host texture.
 //! Textures read through descriptor tables are brought up to date, and for
 //! shaders that index the heap themselves every texture with a resource
 //! object the heap views (`crate::bindless`); textures the title placed in
@@ -18,6 +22,7 @@
 //! 0 is uploaded (every mip and array slice), depth and stencil planes are
 //! not.
 
+use std::ops::Range;
 use std::sync::{Arc, Mutex};
 
 use windows::Win32::Graphics::Direct3D12::*;
@@ -46,6 +51,9 @@ pub(crate) struct Staging {
     layout: victory_formats::texture::Layout,
     /// Mips per array slice.
     mips: u32,
+    /// Per subresource, the bytes of the memory it is detiled from
+    /// (offsets in it, sorted).
+    extents: Vec<Vec<Range<usize>>>,
     memory: *const u8,
     /// The memory's pages changed since detiled (none: not the runtime's
     /// memory, hashed instead).
@@ -53,14 +61,18 @@ pub(crate) struct Staging {
     last: Mutex<Last>,
 }
 
-/// What a texture's staging buffer holds: the hash of the memory detiled
-/// (memory not tracked), with room to read tracked memory into.
+/// What a texture's staging buffer holds: the hash of each [`HASHED`]
+/// bytes of the memory detiled (memory not tracked), with room to read
+/// tracked memory into.
 #[derive(Default)]
 struct Last {
-    hash: Option<blake3::Hash>,
+    hashes: Vec<blake3::Hash>,
     read: Vec<u8>,
 }
 
+/// The bytes one hash of untracked texture memory covers.
+const HASHED: usize = 64 << 10;
+
 // SAFETY: the staging mapping is written only at submission, under
 // `last`'s lock; the title memory is only read.
 unsafe impl Send for Staging {}
@@ -205,7 +217,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
     };
     // The staging buffer lives as long as `staging`, which the deferred
     // refresh below holds until the list is reset.
-    record(list, resource, texture, &staging);
+    record(list, resource, texture, &staging, None);
     // Once per submission however many of its lists sample the texture.
     list.defer_texture(staging);
 }
@@ -222,20 +234,25 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re
     let Some(staging) = staging(resource, texture) else {
         return false;
     };
-    if !staging.refresh() {
+    let parts = staging.refresh_parts();
+    if parts.is_empty() {
         return false;
     }
-    record(list, resource, texture, &staging);
+    // Only the subresources detiled again: the host texture holds the rest.
+    record(list, resource, texture, &staging, Some(&parts));
     list.keep(&staging.buffer);
     true
 }
 
-/// Records the copy of every subresource of `staging` into `texture`,
-/// moving it to the copy destination state first.
-fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) {
+/// Records the copy of the subresources `only` names (all with `None`) of
+/// `staging` into `texture`, moving it to the copy destination state first.
+fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging, only: Option<&[usize]>) {
     const COPY_DEST: u32 = 0x400;
     crate::list::ensure_state(list, resource, COPY_DEST);
     for (i, footprint) in staging.footprints.iter().enumerate() {
+        if only.is_some_and(|o| o.binary_search(&i).is_err()) {
+            continue;
+        }
         #[cfg(feature = "diagnostics")]
         {
             let f = footprint.Footprint;
@@ -288,33 +305,53 @@ impl Staging {
     /// Detiles the texture memory into the staging buffer if it changed
     /// since the last time (and is mapped at all): whether it did.
     pub(crate) fn refresh(&self) -> bool {
+        !self.refresh_parts().is_empty()
+    }
+
+    /// As [`Staging::refresh`]: the subresources detiled again (in order).
+    pub(crate) fn refresh_parts(&self) -> Vec<usize> {
         use std::sync::atomic::Ordering::Relaxed;
         let started = std::time::Instant::now();
-        let (read, changed) = self.refresh_now();
+        let (read, parts) = self.refresh_now();
         let preparing = &crate::host::PREPARING;
         preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
         preparing[3].fetch_add(read as u64, Relaxed);
-        changed
+        parts
     }
 
-    /// Returns the bytes of title memory read, and whether it detiled.
-    fn refresh_now(&self) -> (usize, bool) {
+    /// Returns the bytes of title memory read, and the subresources it
+    /// detiled.
+    fn refresh_now(&self) -> (usize, Vec<usize>) {
         let size = self.layout.size as usize;
         let start = self.memory as usize;
         let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
         let last = &mut *last;
         if let Some(t) = &self.tracked {
-            if t.take(start, start + size).is_empty() {
-                return (0, false);
+            let runs = t.take(start, start + size);
+            if runs.is_empty() {
+                return (0, Vec::new());
             }
             // Read through the copy, which stands unmapped pages: memory of
-            // big pools is too slow to ask page by page.
-            last.read.resize(size, 0);
-            crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
-            self.detile(&last.read);
+            // big pools is too slow to ask page by page. The first time all
+            // of it; then the pages written, the rest is as last read.
+            let changed: Vec<Range<usize>> = if last.read.len() != size {
+                last.read.resize(size, 0);
+                crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
+                std::iter::once(0..size).collect()
+            } else {
+                let changed: Vec<Range<usize>> = runs.iter().map(|&(a, b)| a - start..b - start).collect();
+                for r in &changed {
+                    // SAFETY: `r` lies inside both the memory and the copy.
+                    let (to, from) = unsafe { (last.read.as_mut_ptr().add(r.start), self.memory.add(r.start)) };
+                    crate::host::copy_mapped(to, from, r.len(), false);
+                }
+                changed
+            };
+            let read: usize = changed.iter().map(Range::len).sum();
+            let detiled = self.detile(&last.read, Some(&changed));
             #[cfg(feature = "diagnostics")]
-            crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
-            return (size, true);
+            crate::copystat::add(crate::copystat::C::TexWatched, read as u64);
+            return (read, detiled);
         }
         if !committed(self.memory, size) {
             #[cfg(feature = "diagnostics")]
@@ -324,25 +361,29 @@ impl Staging {
                 desc = ?self.layout.desc,
                 "a sampled texture's memory is not committed"
             );
-            return (0, false);
+            return (0, Vec::new());
         }
         // SAFETY: committed memory of the texture's layout size.
         let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
-        let hash = blake3::hash(tiled);
         #[cfg(feature = "diagnostics")]
         crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
-        if last.hash == Some(hash) {
-            return (size, false);
+        let (hashes, changed) = changed_chunks(tiled, &last.hashes);
+        if changed.is_empty() {
+            return (size, Vec::new());
         }
-        last.hash = Some(hash);
-        self.detile(tiled);
+        // The first time every chunk differs: all of it.
+        let first = last.hashes.is_empty();
+        last.hashes = hashes;
+        let parts = self.detile(tiled, (!first).then_some(&changed[..]));
         #[cfg(feature = "diagnostics")]
         crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
-        (size, true)
+        (size, parts)
     }
 
-    /// Detiles `tiled` (the texture's memory) into the staging buffer.
-    fn detile(&self, tiled: &[u8]) {
+    /// Detiles `tiled` (the texture's memory) into the staging buffer: the
+    /// bytes in `changed` of the subresources they reach (all with `None`).
+    /// The subresources it detiled.
+    fn detile(&self, tiled: &[u8], changed: Option<&[Range<usize>]>) -> Vec<usize> {
         #[cfg(feature = "diagnostics")]
         if tiled.iter().all(|&b| b == 0) {
             tracing::debug!(
@@ -351,24 +392,120 @@ impl Staging {
                 "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
             );
         }
-        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)
-            };
-            if let Err(e) =
-                self.layout
-                    .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
-            {
-                tracing::warn!(?e, mip, slice, "texture not detiled");
-                return;
-            }
+        let parts: Vec<Part> = self
+            .footprints
+            .iter()
+            .zip(&self.rows)
+            .map(|(footprint, &rows)| Part {
+                offset: footprint.Offset as usize,
+                pitch: footprint.Footprint.RowPitch as usize,
+                rows: rows as usize,
+                depth: footprint.Footprint.Depth as usize,
+            })
+            .collect();
+        let len = parts.iter().map(|p| p.offset + p.len()).max().unwrap_or(0);
+        // SAFETY: the mapped staging buffer holds every subresource.
+        let staging = unsafe { std::slice::from_raw_parts_mut(self.data, len) };
+        detile_parts(&self.layout, self.mips, &parts, &self.extents, tiled, staging, changed)
+    }
+}
+
+/// A subresource's place in the staging buffer.
+struct Part {
+    offset: usize,
+    pitch: usize,
+    rows: usize,
+    depth: usize,
+}
+
+impl Part {
+    fn len(&self) -> usize {
+        self.pitch * self.rows * self.depth
+    }
+}
+
+/// Whether any of `extents` overlaps any of `changed` (both sorted).
+fn overlaps(extents: &[Range<usize>], changed: &[Range<usize>]) -> bool {
+    let (mut i, mut j) = (0, 0);
+    while i < extents.len() && j < changed.len() {
+        let (e, c) = (&extents[i], &changed[j]);
+        if e.start < c.end && c.start < e.end {
+            return true;
+        }
+        if e.end <= c.end {
+            i += 1;
+        } else {
+            j += 1;
+        }
+    }
+    false
+}
+
+/// Per subresource (mip-major within each array slice), the bytes of the
+/// tiled memory it is detiled from; the whole memory where the layout
+/// cannot say.
+fn extents_of(layout: &victory_formats::texture::Layout, mips: u32, count: usize) -> Vec<Vec<Range<usize>>> {
+    (0..count as u32)
+        .map(|i| match layout.extents(i % mips, i / mips) {
+            Ok(e) => e.into_iter().map(|r| r.start as usize..r.end as usize).collect(),
+            Err(_) => std::iter::once(0..layout.size as usize).collect(),
+        })
+        .collect()
+}
+
+/// Detiles into `staging` (laid out as `parts`) the bytes in `changed` of
+/// the subresources whose `extents` overlap it (all with `None`). The
+/// subresources it detiled, in order.
+fn detile_parts(
+    layout: &victory_formats::texture::Layout,
+    mips: u32,
+    parts: &[Part],
+    extents: &[Vec<Range<usize>>],
+    tiled: &[u8],
+    staging: &mut [u8],
+    changed: Option<&[Range<usize>]>,
+) -> Vec<usize> {
+    let mut done = Vec::new();
+    for (i, part) in parts.iter().enumerate() {
+        if let (Some(c), Some(e)) = (changed, extents.get(i))
+            && !overlaps(e, c)
+        {
+            continue;
         }
+        let (mip, slice) = (i as u32 % mips, i as u32 / mips);
+        let linear = &mut staging[part.offset..part.offset + part.len()];
+        // Only the written bytes: the rest of the subresource is as detiled
+        // before.
+        let detiled = match changed {
+            Some(c) => layout.detile_ranges(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows, c),
+            None => layout.detile(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows),
+        };
+        if let Err(e) = detiled {
+            tracing::warn!(?e, mip, slice, "texture not detiled");
+            return done;
+        }
+        done.push(i);
     }
+    done
+}
+
+/// The hash of each [`HASHED`] bytes of `tiled`, and the byte ranges whose
+/// hash differs from `before` (all of it when `before` is of another size).
+fn changed_chunks(tiled: &[u8], before: &[blake3::Hash]) -> (Vec<blake3::Hash>, Vec<Range<usize>>) {
+    let hashes: Vec<blake3::Hash> = tiled.chunks(HASHED).map(blake3::hash).collect();
+    let same_size = before.len() == hashes.len();
+    let mut changed: Vec<Range<usize>> = Vec::new();
+    for (k, h) in hashes.iter().enumerate() {
+        if same_size && before[k] == *h {
+            continue;
+        }
+        let r = k * HASHED..((k + 1) * HASHED).min(tiled.len());
+        match changed.last_mut() {
+            Some(last) if last.end == r.start => last.end = r.end,
+            _ => changed.push(r),
+        }
+    }
+    (hashes, changed)
 }
 
 /// Whether `[at, at + len)` is committed memory (streamed textures may be
@@ -444,6 +581,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
     });
     tracing::debug!(?desc, total, "texture contents uploaded from title memory");
     let layout_size = layout.size as usize;
+    let extents = extents_of(&layout, u32::from(d.MipLevels), footprints.len());
     let s = Arc::new(Staging {
         buffer,
         #[cfg(feature = "diagnostics")]
@@ -453,6 +591,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
         rows,
         layout,
         mips: u32::from(d.MipLevels),
+        extents,
         memory,
         tracked: crate::watch::track(memory as usize, layout_size, true),
         last: Mutex::default(),
@@ -460,3 +599,127 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
     *held = Some(s.clone());
     Some(s)
 }
+
+#[cfg(test)]
+mod tests {
+    use super::{Part, detile_parts, extents_of};
+    use victory_formats::texture::{Desc, Dimension, Layout, Swizzle};
+
+    /// Detiling only the subresources a set of written pages reaches, onto
+    /// what the old memory detiled to, gives what detiling all of the new
+    /// memory gives.
+    #[test]
+    fn detiling_the_changed_subresources_matches_detiling_all() {
+        let cases = [
+            (Dimension::Tex2d, 256, 256, 1, 9, 4, Swizzle::SW_64KB_D),
+            (Dimension::Tex2d, 300, 200, 3, 9, 16, Swizzle::SW_4KB_S),
+            (Dimension::Tex2d, 1024, 512, 1, 11, 8, Swizzle::SW_64KB_S),
+            (Dimension::Tex3d, 64, 64, 16, 7, 4, Swizzle::SW_4KB_S),
+            (Dimension::Tex2d, 100, 60, 2, 7, 4, Swizzle::LINEAR),
+        ];
+        for (dimension, width, height, depth, mips, element_bytes, swizzle) in cases {
+            let d = Desc { dimension, width, height, depth, mips, element_bytes, block: 1, samples: 1, swizzle };
+            let layout = Layout::new(&d).unwrap();
+            let size = layout.size as usize;
+            let slices = if dimension == Dimension::Tex3d { 1 } else { depth };
+            // Linear subresources one after another, rows 256-byte aligned.
+            let mut parts = Vec::new();
+            let mut offset = 0;
+            for _ in 0..slices {
+                for mip in 0..mips {
+                    let m = &layout.mips[mip as usize];
+                    let pitch = (m.width as usize * element_bytes as usize).next_multiple_of(256);
+                    let p = Part { offset, pitch, rows: m.height as usize, depth: m.depth.max(1) as usize };
+                    offset = (offset + p.len()).next_multiple_of(512);
+                    parts.push(p);
+                }
+            }
+            let extents = extents_of(&layout, mips, parts.len());
+            let old: Vec<u8> = (0..size).map(|i| (i * 7 + i / 4093) as u8).collect();
+            for seed in 0..6usize {
+                // Pages written: a few 4 KiB pages anywhere.
+                let mut new = old.clone();
+                let mut changed = Vec::new();
+                for k in 0..3 {
+                    let page = (seed * 977 + k * 6151) % size.div_ceil(4096);
+                    let r = page * 4096..((page + 1) * 4096).min(size);
+                    for b in &mut new[r.clone()] {
+                        *b = !*b;
+                    }
+                    changed.push(r);
+                }
+                changed.sort_by_key(|r| r.start);
+                changed.dedup();
+                let mut partial = vec![0u8; offset];
+                assert_eq!(detile_parts(&layout, mips, &parts, &extents, &old, &mut partial, None).len(), parts.len());
+                detile_parts(&layout, mips, &parts, &extents, &new, &mut partial, Some(&changed));
+                let mut whole = vec![0u8; offset];
+                detile_parts(&layout, mips, &parts, &extents, &new, &mut whole, None);
+                assert!(partial == whole, "{d:?} seed {seed}");
+            }
+        }
+    }
+
+    /// Hashed memory: the chunks that changed, merged; all of it the first
+    /// time.
+    #[test]
+    fn changed_chunks_name_the_chunks_written() {
+        use super::{HASHED, changed_chunks};
+        let mut m: Vec<u8> = (0..HASHED * 5 + 100).map(|i| i as u8).collect();
+        let (first, all) = changed_chunks(&m, &[]);
+        assert_eq!(all, vec![0..m.len()]);
+        m[HASHED + 7] ^= 1;
+        m[2 * HASHED] ^= 1;
+        m[5 * HASHED + 50] ^= 1;
+        let (_, changed) = changed_chunks(&m, &first);
+        assert_eq!(changed, vec![HASHED..3 * HASHED, 5 * HASHED..m.len()]);
+        let (same, _) = changed_chunks(&m, &first);
+        assert!(changed_chunks(&m, &same).1.is_empty());
+    }
+
+    /// Timing (ignored; `--release --ignored --nocapture`): a 4096x4096
+    /// BC7 texture (1024x1024 16-byte blocks, full mip chain), one 64 KiB
+    /// page written: detiling all of it against only what the page reaches.
+    #[test]
+    #[ignore]
+    fn detile_one_written_page_of_a_4k_bc7_texture() {
+        let d = Desc {
+            dimension: Dimension::Tex2d,
+            width: 1024,
+            height: 1024,
+            depth: 1,
+            mips: 11,
+            element_bytes: 16,
+            block: 1,
+            samples: 1,
+            swizzle: Swizzle::SW_64KB_S,
+        };
+        let layout = Layout::new(&d).unwrap();
+        let size = layout.size as usize;
+        let mut parts = Vec::new();
+        let mut offset = 0;
+        for mip in 0..d.mips {
+            let m = &layout.mips[mip as usize];
+            let pitch = (m.width as usize * 16).next_multiple_of(256);
+            let p = Part { offset, pitch, rows: m.height as usize, depth: 1 };
+            offset = (offset + p.len()).next_multiple_of(512);
+            parts.push(p);
+        }
+        let extents = extents_of(&layout, d.mips, parts.len());
+        let tiled: Vec<u8> = (0..size).map(|i| (i * 13) as u8).collect();
+        let mut staging = vec![0u8; offset];
+        let page = (size / 2) & !0xFFFF..((size / 2) & !0xFFFF) + 65536;
+        let rounds = 20;
+        let t = std::time::Instant::now();
+        for _ in 0..rounds {
+            detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, None);
+        }
+        let all = t.elapsed() / rounds;
+        let t = std::time::Instant::now();
+        for _ in 0..rounds {
+            detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, Some(std::slice::from_ref(&page)));
+        }
+        let one = t.elapsed() / rounds;
+        eprintln!("4096x4096 BC7, {} MiB: all {all:?}, one written page {one:?}", size >> 20);
+    }
+}

Unit tests only, no game files. AI-assisted (Claude ported and extended it; I ran it on my machine).

**@⁠wwwwwwww3333333** on GitHub · 2026-11-25 00:48 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7148905937) This PR no longer merges with main (70564ae0): main moved texture tracking to `watch::Tracked`, which conflicts with this PR in `crates/victory-gpu/src/texture.rs`. I ported your approach onto main's model and took it a bit further. Tested on AMD. **What the port does** (credit for the idea and the `Layout::extents` part, taken as is with its test, goes to this PR): - **Tracked memory.** `Tracked::take` already returns the written page runs; only those are read again into the copy. The first refresh reads everything. - **Subresources.** Only the subresources whose `extents` overlap the written bytes are detiled again. - **Inside a subresource.** A new `Layout::detile_ranges` copies only the bytes in the written ranges. It skips whole rows whose tiled span misses them, through a `walk_rows` that `walk` now calls. Without this, a write into mip 0 (about 75% of a 4K texture) still costs most of a full detile. - **Hashed (untracked) memory.** One hash per 64 KiB instead of one for the whole texture, so a change re-detiles only the chunks that differ. - **Copy to the host texture.** On the `upload_changed` path (bindless, recorded at submission), only the subresources detiled again are copied; the host texture already holds the rest. The `upload` path still copies every subresource, because it records before the refresh. The module's shortcut note now says so. **Results** on 70564ae0 + this, RX 6750 XT, i5-13400F, Windows 11, Rust 1.98.1 MSVC. Timing (release, ignored test `detile_one_written_page_of_a_4k_bc7_texture`): a 4096x4096 BC7 texture (21 MiB, full chain) with one 64 KiB page written in the middle of mip 0. - Detile everything (main): **4.46 ms**. - With this: **0.080 ms**. New tests: - victory-formats: `extents_hold_what_a_subresource_detiles` (from this PR) and `detiling_ranges_matches_detiling_the_merged_memory`. - victory-gpu: `detiling_the_changed_subresources_matches_detiling_all`, over 5 layouts × 6 sets of written pages, including 3D and linear. Partial detiling onto the old result is byte-identical to detiling everything. - victory-gpu: `changed_chunks_name_the_chunks_written`. Suites and clippy: - victory-formats 25/25 and victory-gpu 80/80, twice each. - `cargo clippy -p victory-formats -p victory-gpu --all-targets -- -D warnings`: clean. **Not measured:** how much of a frame this saves in a title. That needs a world run, which I can't do here. <details><summary>Patch against 70564ae0</summary> ```diff diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 6a735b6c..54fcca3b 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -599,6 +599,88 @@ impl Layout { }) } + /// As [`Layout::detile`], but only the bytes of tiled memory inside + /// `ranges` (sorted, disjoint) are copied; the rest of `linear` keeps + /// what it held. Detiling the pages written since the last detiling + /// into the same rows gives what [`Layout::detile`] would. + #[allow(clippy::too_many_arguments)] + pub fn detile_ranges( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + row_pitch: usize, + depth_pitch: usize, + ranges: &[std::ops::Range<usize>], + ) -> Result<(), Error> { + let touched = |from: usize, to: usize| { + ranges + .get(ranges.partition_point(|r| r.end <= from)) + .is_some_and(|r| r.start < to) + }; + self.walk_rows(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, touched, |t, l, len| { + let end = t + len; + let mut i = ranges.partition_point(|r| r.end <= t); + while let Some(r) = ranges.get(i) { + if r.start >= end { + break; + } + let (a, b) = (r.start.max(t), r.end.min(end)); + linear[l + (a - t)..l + (b - t)].copy_from_slice(&tiled[a..b]); + i += 1; + } + }) + } + + /// The byte ranges of tiled memory that [`Layout::detile`] reads for + /// mip `mip` of array slice `slice` (3D: every depth slice of the mip, + /// `slice` 0): sorted, disjoint, one per depth slice or slab at most. + /// A mip in the tail gets the part of the tail block its elements span, + /// which other tail mips may share; a write outside every range leaves + /// the subresource's detiled contents as they were. + pub fn extents(&self, mip: u32, slice: u32) -> Result<Vec<std::ops::Range<u64>>, Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let bytes = m.width as usize * self.desc.element_bytes as usize; + let depth_pitch = bytes * m.height as usize; + let mut spans: Vec<std::ops::Range<u64>> = Vec::new(); + let z_of = |linear: usize| linear / depth_pitch; + let mut current: Option<(usize, std::ops::Range<u64>)> = None; + self.walk( + self.size as usize, + mip, + slice, + usize::MAX, + bytes, + depth_pitch, + |tiled, linear, len| { + let z = z_of(linear); + let run = tiled as u64..(tiled + len) as u64; + match &mut current { + Some((at, r)) if *at == z => { + r.start = r.start.min(run.start); + r.end = r.end.max(run.end); + } + _ => { + if let Some((_, r)) = current.replace((z, run)) { + spans.push(r); + } + } + } + }, + )?; + spans.extend(current.map(|(_, r)| r)); + spans.sort_by_key(|r| r.start); + let mut merged: Vec<std::ops::Range<u64>> = Vec::with_capacity(spans.len()); + for r in spans { + match merged.last_mut() { + Some(last) if r.start <= last.end => last.end = last.end.max(r.end), + _ => merged.push(r), + } + } + Ok(merged) + } + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. pub fn tile( &self, @@ -625,6 +707,23 @@ impl Layout { row_pitch: usize, depth_pitch: usize, mut copy: impl FnMut(usize, usize, usize), + ) -> Result<(), Error> { + self.walk_rows(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, |_, _| true, &mut copy) + } + + /// As [`Layout::walk`], visiting only the rows whose tiled bytes + /// `[from, to)` (the span of the row's runs) `row` accepts. + #[allow(clippy::too_many_arguments)] + fn walk_rows( + &self, + tiled_len: usize, + mip: u32, + slice: u32, + linear_len: usize, + row_pitch: usize, + depth_pitch: usize, + row: impl Fn(usize, usize) -> bool, + mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -671,6 +770,9 @@ impl Layout { } runs.push((first_tiled, first_linear, bytes - first_linear)); } + let (lo, hi) = runs + .iter() + .fold((usize::MAX, 0), |(lo, hi), &(t, _, len)| (lo.min(t), hi.max(t + len))); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -678,9 +780,14 @@ impl Layout { let linear_row = z as usize * depth_pitch + y as usize * row_pitch; if linear { let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + if row(tiled_row as usize, tiled_row as usize + bytes) { + copy(tiled_row as usize, linear_row, bytes); + } } else { let tiled_row = (base + self.row(m, y, inner)) as usize; + if !row(tiled_row + lo, tiled_row + hi) { + continue; + } for &(tiled, linear, len) in &runs { copy(tiled_row + tiled, linear_row + linear, len); } @@ -944,6 +1051,122 @@ mod tests { } } + /// Detiling only some ranges onto an earlier detiling gives what + /// detiling all of memory whose other bytes are the earlier ones gives. + #[test] + fn detiling_ranges_matches_detiling_the_merged_memory() { + let cases = [ + desc(256, 256, 9, 4, Swizzle::SW_64KB_D), + desc(300, 200, 9, 16, Swizzle::SW_4KB_S), + desc(100, 60, 7, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let old: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let mid = size / 3..(size / 3 + 5000).min(size / 2); + let ranges = [100..900.min(size / 4), mid, size - size / 8..size]; + let mut merged = old.clone(); + for r in &ranges { + for b in &mut merged[r.clone()] { + *b = !*b; + } + } + for mip in 0..d.mips { + let m = l.mips[mip as usize]; + let row = m.width as usize * d.element_bytes as usize; + let plane = row * m.height as usize; + let mut partial = vec![0; plane]; + l.detile(&old, mip, 0, &mut partial, row, plane).unwrap(); + l.detile_ranges(&merged, mip, 0, &mut partial, row, plane, &ranges) + .unwrap(); + let mut whole = vec![0; plane]; + l.detile(&merged, mip, 0, &mut whole, row, plane).unwrap(); + assert_eq!(partial, whole, "{d:?} mip {mip}"); + } + } + } + + /// A subresource's extents hold every element it detiles, and bytes + /// outside them do not change what it detiles to. + #[test] + fn extents_hold_what_a_subresource_detiles() { + let cases = [ + desc(64, 64, 7, 16, Swizzle::SW_64KB_D), + desc(100, 60, 7, 4, Swizzle::SW_64KB_D), + desc(250, 175, 8, 8, Swizzle::SW_4KB_S), + desc(33, 17, 6, 1, Swizzle::SW_4KB_D), + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + Desc { + depth: 4, + ..desc(30, 20, 3, 4, Swizzle::LINEAR) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let tiled: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; + for slice in 0..slices { + for mip in 0..d.mips { + let e = l.extents(mip, slice).unwrap(); + assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}"); + for w in e.windows(2) { + assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}"); + } + assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size)); + let inside = |at: u64| e.iter().any(|r| r.contains(&at)); + let m = l.mips[mip as usize]; + let n = u64::from(d.element_bytes); + // Outside the tail a 2D mip's extent is its own blocks. + if m.tail.is_none() && d.dimension != Dimension::Tex3d { + let total: u64 = e.iter().map(|r| r.end - r.start).sum(); + let own = u64::from(m.pitch) * u64::from(m.rows) * n; + assert!(total <= own, "{d:?} mip {mip}: {total} > {own}"); + } + for z in 0..m.depth { + for y in 0..m.height { + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap(); + assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}"); + } + } + } + let row = m.width as usize * n as usize; + let plane = row * m.height as usize; + let mut before = vec![0; plane * m.depth as usize]; + l.detile(&tiled, mip, slice, &mut before, row, plane) + .unwrap(); + let mut changed = tiled.clone(); + for (i, b) in changed.iter_mut().enumerate() { + if !inside(i as u64) { + *b = !*b; + } + } + let mut after = vec![0; before.len()]; + l.detile(&changed, mip, slice, &mut after, row, plane) + .unwrap(); + assert_eq!(before, after, "{d:?} mip {mip} slice {slice}"); + } + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 524cc568..f1963da3 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -10,7 +10,11 @@ //! same physical pages) in the runtime's memory; elsewhere, a content hash //! of the whole memory at every submission that samples it. //! -//! shortcut: a change detiles the whole texture, not the pages written. +//! In tracked memory only the pages written are read again and detiled +//! again (into the subresources whose memory holds them). +//! +//! shortcut: hashed memory detiles the whole texture on a change; every +//! subresource is still copied into the host texture. //! Textures read through descriptor tables are brought up to date, and for //! shaders that index the heap themselves every texture with a resource //! object the heap views (`crate::bindless`); textures the title placed in @@ -18,6 +22,7 @@ //! 0 is uploaded (every mip and array slice), depth and stencil planes are //! not. +use std::ops::Range; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::*; @@ -46,6 +51,9 @@ pub(crate) struct Staging { layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, + /// Per subresource, the bytes of the memory it is detiled from + /// (offsets in it, sorted). + extents: Vec<Vec<Range<usize>>>, memory: *const u8, /// The memory's pages changed since detiled (none: not the runtime's /// memory, hashed instead). @@ -53,14 +61,18 @@ pub(crate) struct Staging { last: Mutex<Last>, } -/// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not tracked), with room to read tracked memory into. +/// What a texture's staging buffer holds: the hash of each [`HASHED`] +/// bytes of the memory detiled (memory not tracked), with room to read +/// tracked memory into. #[derive(Default)] struct Last { - hash: Option<blake3::Hash>, + hashes: Vec<blake3::Hash>, read: Vec<u8>, } +/// The bytes one hash of untracked texture memory covers. +const HASHED: usize = 64 << 10; + // SAFETY: the staging mapping is written only at submission, under // `last`'s lock; the title memory is only read. unsafe impl Send for Staging {} @@ -205,7 +217,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) }; // The staging buffer lives as long as `staging`, which the deferred // refresh below holds until the list is reset. - record(list, resource, texture, &staging); + record(list, resource, texture, &staging, None); // Once per submission however many of its lists sample the texture. list.defer_texture(staging); } @@ -222,20 +234,25 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re let Some(staging) = staging(resource, texture) else { return false; }; - if !staging.refresh() { + let parts = staging.refresh_parts(); + if parts.is_empty() { return false; } - record(list, resource, texture, &staging); + // Only the subresources detiled again: the host texture holds the rest. + record(list, resource, texture, &staging, Some(&parts)); list.keep(&staging.buffer); true } -/// Records the copy of every subresource of `staging` into `texture`, -/// moving it to the copy destination state first. -fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) { +/// Records the copy of the subresources `only` names (all with `None`) of +/// `staging` into `texture`, moving it to the copy destination state first. +fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging, only: Option<&[usize]>) { const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); for (i, footprint) in staging.footprints.iter().enumerate() { + if only.is_some_and(|o| o.binary_search(&i).is_err()) { + continue; + } #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; @@ -288,33 +305,53 @@ impl Staging { /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all): whether it did. pub(crate) fn refresh(&self) -> bool { + !self.refresh_parts().is_empty() + } + + /// As [`Staging::refresh`]: the subresources detiled again (in order). + pub(crate) fn refresh_parts(&self) -> Vec<usize> { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); - let (read, changed) = self.refresh_now(); + let (read, parts) = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); - changed + parts } - /// Returns the bytes of title memory read, and whether it detiled. - fn refresh_now(&self) -> (usize, bool) { + /// Returns the bytes of title memory read, and the subresources it + /// detiled. + fn refresh_now(&self) -> (usize, Vec<usize>) { let size = self.layout.size as usize; let start = self.memory as usize; let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some(t) = &self.tracked { - if t.take(start, start + size).is_empty() { - return (0, false); + let runs = t.take(start, start + size); + if runs.is_empty() { + return (0, Vec::new()); } // Read through the copy, which stands unmapped pages: memory of - // big pools is too slow to ask page by page. - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + // big pools is too slow to ask page by page. The first time all + // of it; then the pages written, the rest is as last read. + let changed: Vec<Range<usize>> = if last.read.len() != size { + last.read.resize(size, 0); + crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); + std::iter::once(0..size).collect() + } else { + let changed: Vec<Range<usize>> = runs.iter().map(|&(a, b)| a - start..b - start).collect(); + for r in &changed { + // SAFETY: `r` lies inside both the memory and the copy. + let (to, from) = unsafe { (last.read.as_mut_ptr().add(r.start), self.memory.add(r.start)) }; + crate::host::copy_mapped(to, from, r.len(), false); + } + changed + }; + let read: usize = changed.iter().map(Range::len).sum(); + let detiled = self.detile(&last.read, Some(&changed)); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return (size, true); + crate::copystat::add(crate::copystat::C::TexWatched, read as u64); + return (read, detiled); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -324,25 +361,29 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is not committed" ); - return (0, false); + return (0, Vec::new()); } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); - if last.hash == Some(hash) { - return (size, false); + let (hashes, changed) = changed_chunks(tiled, &last.hashes); + if changed.is_empty() { + return (size, Vec::new()); } - last.hash = Some(hash); - self.detile(tiled); + // The first time every chunk differs: all of it. + let first = last.hashes.is_empty(); + last.hashes = hashes; + let parts = self.detile(tiled, (!first).then_some(&changed[..])); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, true) + (size, parts) } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `tiled` (the texture's memory) into the staging buffer: the + /// bytes in `changed` of the subresources they reach (all with `None`). + /// The subresources it detiled. + fn detile(&self, tiled: &[u8], changed: Option<&[Range<usize>]>) -> Vec<usize> { #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -351,24 +392,120 @@ impl Staging { "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); } - 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) - }; - if let Err(e) = - self.layout - .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) - { - tracing::warn!(?e, mip, slice, "texture not detiled"); - return; - } + let parts: Vec<Part> = self + .footprints + .iter() + .zip(&self.rows) + .map(|(footprint, &rows)| Part { + offset: footprint.Offset as usize, + pitch: footprint.Footprint.RowPitch as usize, + rows: rows as usize, + depth: footprint.Footprint.Depth as usize, + }) + .collect(); + let len = parts.iter().map(|p| p.offset + p.len()).max().unwrap_or(0); + // SAFETY: the mapped staging buffer holds every subresource. + let staging = unsafe { std::slice::from_raw_parts_mut(self.data, len) }; + detile_parts(&self.layout, self.mips, &parts, &self.extents, tiled, staging, changed) + } +} + +/// A subresource's place in the staging buffer. +struct Part { + offset: usize, + pitch: usize, + rows: usize, + depth: usize, +} + +impl Part { + fn len(&self) -> usize { + self.pitch * self.rows * self.depth + } +} + +/// Whether any of `extents` overlaps any of `changed` (both sorted). +fn overlaps(extents: &[Range<usize>], changed: &[Range<usize>]) -> bool { + let (mut i, mut j) = (0, 0); + while i < extents.len() && j < changed.len() { + let (e, c) = (&extents[i], &changed[j]); + if e.start < c.end && c.start < e.end { + return true; + } + if e.end <= c.end { + i += 1; + } else { + j += 1; + } + } + false +} + +/// Per subresource (mip-major within each array slice), the bytes of the +/// tiled memory it is detiled from; the whole memory where the layout +/// cannot say. +fn extents_of(layout: &victory_formats::texture::Layout, mips: u32, count: usize) -> Vec<Vec<Range<usize>>> { + (0..count as u32) + .map(|i| match layout.extents(i % mips, i / mips) { + Ok(e) => e.into_iter().map(|r| r.start as usize..r.end as usize).collect(), + Err(_) => std::iter::once(0..layout.size as usize).collect(), + }) + .collect() +} + +/// Detiles into `staging` (laid out as `parts`) the bytes in `changed` of +/// the subresources whose `extents` overlap it (all with `None`). The +/// subresources it detiled, in order. +fn detile_parts( + layout: &victory_formats::texture::Layout, + mips: u32, + parts: &[Part], + extents: &[Vec<Range<usize>>], + tiled: &[u8], + staging: &mut [u8], + changed: Option<&[Range<usize>]>, +) -> Vec<usize> { + let mut done = Vec::new(); + for (i, part) in parts.iter().enumerate() { + if let (Some(c), Some(e)) = (changed, extents.get(i)) + && !overlaps(e, c) + { + continue; } + let (mip, slice) = (i as u32 % mips, i as u32 / mips); + let linear = &mut staging[part.offset..part.offset + part.len()]; + // Only the written bytes: the rest of the subresource is as detiled + // before. + let detiled = match changed { + Some(c) => layout.detile_ranges(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows, c), + None => layout.detile(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows), + }; + if let Err(e) = detiled { + tracing::warn!(?e, mip, slice, "texture not detiled"); + return done; + } + done.push(i); } + done +} + +/// The hash of each [`HASHED`] bytes of `tiled`, and the byte ranges whose +/// hash differs from `before` (all of it when `before` is of another size). +fn changed_chunks(tiled: &[u8], before: &[blake3::Hash]) -> (Vec<blake3::Hash>, Vec<Range<usize>>) { + let hashes: Vec<blake3::Hash> = tiled.chunks(HASHED).map(blake3::hash).collect(); + let same_size = before.len() == hashes.len(); + let mut changed: Vec<Range<usize>> = Vec::new(); + for (k, h) in hashes.iter().enumerate() { + if same_size && before[k] == *h { + continue; + } + let r = k * HASHED..((k + 1) * HASHED).min(tiled.len()); + match changed.last_mut() { + Some(last) if last.end == r.start => last.end = r.end, + _ => changed.push(r), + } + } + (hashes, changed) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -444,6 +581,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let layout_size = layout.size as usize; + let extents = extents_of(&layout, u32::from(d.MipLevels), footprints.len()); let s = Arc::new(Staging { buffer, #[cfg(feature = "diagnostics")] @@ -453,6 +591,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { rows, layout, mips: u32::from(d.MipLevels), + extents, memory, tracked: crate::watch::track(memory as usize, layout_size, true), last: Mutex::default(), @@ -460,3 +599,127 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { *held = Some(s.clone()); Some(s) } + +#[cfg(test)] +mod tests { + use super::{Part, detile_parts, extents_of}; + use victory_formats::texture::{Desc, Dimension, Layout, Swizzle}; + + /// Detiling only the subresources a set of written pages reaches, onto + /// what the old memory detiled to, gives what detiling all of the new + /// memory gives. + #[test] + fn detiling_the_changed_subresources_matches_detiling_all() { + let cases = [ + (Dimension::Tex2d, 256, 256, 1, 9, 4, Swizzle::SW_64KB_D), + (Dimension::Tex2d, 300, 200, 3, 9, 16, Swizzle::SW_4KB_S), + (Dimension::Tex2d, 1024, 512, 1, 11, 8, Swizzle::SW_64KB_S), + (Dimension::Tex3d, 64, 64, 16, 7, 4, Swizzle::SW_4KB_S), + (Dimension::Tex2d, 100, 60, 2, 7, 4, Swizzle::LINEAR), + ]; + for (dimension, width, height, depth, mips, element_bytes, swizzle) in cases { + let d = Desc { dimension, width, height, depth, mips, element_bytes, block: 1, samples: 1, swizzle }; + let layout = Layout::new(&d).unwrap(); + let size = layout.size as usize; + let slices = if dimension == Dimension::Tex3d { 1 } else { depth }; + // Linear subresources one after another, rows 256-byte aligned. + let mut parts = Vec::new(); + let mut offset = 0; + for _ in 0..slices { + for mip in 0..mips { + let m = &layout.mips[mip as usize]; + let pitch = (m.width as usize * element_bytes as usize).next_multiple_of(256); + let p = Part { offset, pitch, rows: m.height as usize, depth: m.depth.max(1) as usize }; + offset = (offset + p.len()).next_multiple_of(512); + parts.push(p); + } + } + let extents = extents_of(&layout, mips, parts.len()); + let old: Vec<u8> = (0..size).map(|i| (i * 7 + i / 4093) as u8).collect(); + for seed in 0..6usize { + // Pages written: a few 4 KiB pages anywhere. + let mut new = old.clone(); + let mut changed = Vec::new(); + for k in 0..3 { + let page = (seed * 977 + k * 6151) % size.div_ceil(4096); + let r = page * 4096..((page + 1) * 4096).min(size); + for b in &mut new[r.clone()] { + *b = !*b; + } + changed.push(r); + } + changed.sort_by_key(|r| r.start); + changed.dedup(); + let mut partial = vec![0u8; offset]; + assert_eq!(detile_parts(&layout, mips, &parts, &extents, &old, &mut partial, None).len(), parts.len()); + detile_parts(&layout, mips, &parts, &extents, &new, &mut partial, Some(&changed)); + let mut whole = vec![0u8; offset]; + detile_parts(&layout, mips, &parts, &extents, &new, &mut whole, None); + assert!(partial == whole, "{d:?} seed {seed}"); + } + } + } + + /// Hashed memory: the chunks that changed, merged; all of it the first + /// time. + #[test] + fn changed_chunks_name_the_chunks_written() { + use super::{HASHED, changed_chunks}; + let mut m: Vec<u8> = (0..HASHED * 5 + 100).map(|i| i as u8).collect(); + let (first, all) = changed_chunks(&m, &[]); + assert_eq!(all, vec![0..m.len()]); + m[HASHED + 7] ^= 1; + m[2 * HASHED] ^= 1; + m[5 * HASHED + 50] ^= 1; + let (_, changed) = changed_chunks(&m, &first); + assert_eq!(changed, vec![HASHED..3 * HASHED, 5 * HASHED..m.len()]); + let (same, _) = changed_chunks(&m, &first); + assert!(changed_chunks(&m, &same).1.is_empty()); + } + + /// Timing (ignored; `--release --ignored --nocapture`): a 4096x4096 + /// BC7 texture (1024x1024 16-byte blocks, full mip chain), one 64 KiB + /// page written: detiling all of it against only what the page reaches. + #[test] + #[ignore] + fn detile_one_written_page_of_a_4k_bc7_texture() { + let d = Desc { + dimension: Dimension::Tex2d, + width: 1024, + height: 1024, + depth: 1, + mips: 11, + element_bytes: 16, + block: 1, + samples: 1, + swizzle: Swizzle::SW_64KB_S, + }; + let layout = Layout::new(&d).unwrap(); + let size = layout.size as usize; + let mut parts = Vec::new(); + let mut offset = 0; + for mip in 0..d.mips { + let m = &layout.mips[mip as usize]; + let pitch = (m.width as usize * 16).next_multiple_of(256); + let p = Part { offset, pitch, rows: m.height as usize, depth: 1 }; + offset = (offset + p.len()).next_multiple_of(512); + parts.push(p); + } + let extents = extents_of(&layout, d.mips, parts.len()); + let tiled: Vec<u8> = (0..size).map(|i| (i * 13) as u8).collect(); + let mut staging = vec![0u8; offset]; + let page = (size / 2) & !0xFFFF..((size / 2) & !0xFFFF) + 65536; + let rounds = 20; + let t = std::time::Instant::now(); + for _ in 0..rounds { + detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, None); + } + let all = t.elapsed() / rounds; + let t = std::time::Instant::now(); + for _ in 0..rounds { + detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, Some(std::slice::from_ref(&page))); + } + let one = t.elapsed() / rounds; + eprintln!("4096x4096 BC7, {} MiB: all {all:?}, one written page {one:?}", size >> 20); + } +} ``` </details> Unit tests only, no game files. AI-assisted (Claude ported and extended it; I ran it on my machine).
Author
Owner

@⁠wwwwwwww3333333 on GitHub · 2026-11-25 01:03 UTC · original

Update: main has moved to 42363ab6, and the port above conflicted with two changes merged since:

  • #603's copy_runs in Layout::walk.
  • subresource_len (4fc9d70), which keeps the staging slice inside the buffer when the last row isn't padded.

Here it is rebased. walk_rows keeps the copy_runs specialisation and only adds the row-span skip. Part now carries its length from subresource_len, and the staging slice is self.size, so the partial path keeps that bounds fix. Without it, the port would have read past the buffer on such textures.

Results on 42363ab6 + this, RX 6750 XT, i5-13400F, Windows 11, Rust 1.98.1 MSVC:

victory-formats victory-gpu
main 42363ab6 38 passed 141 passed
main + this 40 passed 143 passed
  • The new tests (2 in victory-formats, 2 in victory-gpu) pass, and so do main's subresource_len and committed tests.
  • Timing (release, ignored test): a 4096x4096 BC7 texture with one 64 KiB page written in mip 0 takes 4.59 ms to detile in full and 0.080 ms with this.
  • cargo clippy -p victory-formats -p victory-gpu --all-targets -- -D warnings: clean.
Patch against 42363ab6
diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs
index 76afb0bd..95c1ba8e 100644
--- a/crates/victory-formats/src/texture.rs
+++ b/crates/victory-formats/src/texture.rs
@@ -617,6 +617,88 @@ impl Layout {
         })
     }
 
+    /// As [`Layout::detile`], but only the bytes of tiled memory inside
+    /// `ranges` (sorted, disjoint) are copied; the rest of `linear` keeps
+    /// what it held. Detiling the pages written since the last detiling
+    /// into the same rows gives what [`Layout::detile`] would.
+    #[allow(clippy::too_many_arguments)]
+    pub fn detile_ranges(
+        &self,
+        tiled: &[u8],
+        mip: u32,
+        slice: u32,
+        linear: &mut [u8],
+        row_pitch: usize,
+        depth_pitch: usize,
+        ranges: &[std::ops::Range<usize>],
+    ) -> Result<(), Error> {
+        let touched = |from: usize, to: usize| {
+            ranges
+                .get(ranges.partition_point(|r| r.end <= from))
+                .is_some_and(|r| r.start < to)
+        };
+        self.walk_rows(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, touched, |t, l, len| {
+            let end = t + len;
+            let mut i = ranges.partition_point(|r| r.end <= t);
+            while let Some(r) = ranges.get(i) {
+                if r.start >= end {
+                    break;
+                }
+                let (a, b) = (r.start.max(t), r.end.min(end));
+                linear[l + (a - t)..l + (b - t)].copy_from_slice(&tiled[a..b]);
+                i += 1;
+            }
+        })
+    }
+
+    /// The byte ranges of tiled memory that [`Layout::detile`] reads for
+    /// mip `mip` of array slice `slice` (3D: every depth slice of the mip,
+    /// `slice` 0): sorted, disjoint, one per depth slice or slab at most.
+    /// A mip in the tail gets the part of the tail block its elements span,
+    /// which other tail mips may share; a write outside every range leaves
+    /// the subresource's detiled contents as they were.
+    pub fn extents(&self, mip: u32, slice: u32) -> Result<Vec<std::ops::Range<u64>>, Error> {
+        let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
+        let bytes = m.width as usize * self.desc.element_bytes as usize;
+        let depth_pitch = bytes * m.height as usize;
+        let mut spans: Vec<std::ops::Range<u64>> = Vec::new();
+        let z_of = |linear: usize| linear / depth_pitch;
+        let mut current: Option<(usize, std::ops::Range<u64>)> = None;
+        self.walk(
+            self.size as usize,
+            mip,
+            slice,
+            usize::MAX,
+            bytes,
+            depth_pitch,
+            |tiled, linear, len| {
+                let z = z_of(linear);
+                let run = tiled as u64..(tiled + len) as u64;
+                match &mut current {
+                    Some((at, r)) if *at == z => {
+                        r.start = r.start.min(run.start);
+                        r.end = r.end.max(run.end);
+                    }
+                    _ => {
+                        if let Some((_, r)) = current.replace((z, run)) {
+                            spans.push(r);
+                        }
+                    }
+                }
+            },
+        )?;
+        spans.extend(current.map(|(_, r)| r));
+        spans.sort_by_key(|r| r.start);
+        let mut merged: Vec<std::ops::Range<u64>> = Vec::with_capacity(spans.len());
+        for r in spans {
+            match merged.last_mut() {
+                Some(last) if r.start <= last.end => last.end = last.end.max(r.end),
+                _ => merged.push(r),
+            }
+        }
+        Ok(merged)
+    }
+
     /// The reverse of [`Layout::detile`]: linear rows into tiled memory.
     pub fn tile(
         &self,
@@ -643,6 +725,23 @@ impl Layout {
         row_pitch: usize,
         depth_pitch: usize,
         mut copy: impl FnMut(usize, usize, usize),
+    ) -> Result<(), Error> {
+        self.walk_rows(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, |_, _| true, &mut copy)
+    }
+
+    /// As [`Layout::walk`], visiting only the rows whose tiled bytes
+    /// `[from, to)` (the span of the row's runs) `row` accepts.
+    #[allow(clippy::too_many_arguments)]
+    fn walk_rows(
+        &self,
+        tiled_len: usize,
+        mip: u32,
+        slice: u32,
+        linear_len: usize,
+        row_pitch: usize,
+        depth_pitch: usize,
+        row: impl Fn(usize, usize) -> bool,
+        mut copy: impl FnMut(usize, usize, usize),
     ) -> Result<(), Error> {
         let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
         let depth = m.depth;
@@ -704,6 +803,9 @@ impl Layout {
             .first()
             .map(|run| run.2)
             .filter(|&len| body.iter().all(|run| run.2 == len));
+        let (lo, hi) = runs
+            .iter()
+            .fold((usize::MAX, 0), |(lo, hi), &(t, _, len)| (lo.min(t), hi.max(t + len)));
         for z in 0..depth {
             let (s, inner) = self.split(first + z);
             let base = u64::from(s) * self.slice_size + m.offset;
@@ -711,9 +813,14 @@ impl Layout {
                 let linear_row = z as usize * depth_pitch + y as usize * row_pitch;
                 if linear {
                     let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64;
-                    copy(tiled_row as usize, linear_row, bytes);
+                    if row(tiled_row as usize, tiled_row as usize + bytes) {
+                        copy(tiled_row as usize, linear_row, bytes);
+                    }
                 } else {
                     let tiled_row = (base + self.row(m, y, inner)) as usize;
+                    if !row(tiled_row + lo, tiled_row + hi) {
+                        continue;
+                    }
                     match run_len {
                         Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy),
                         Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy),
@@ -1014,6 +1121,122 @@ mod tests {
         }
     }
 
+    /// Detiling only some ranges onto an earlier detiling gives what
+    /// detiling all of memory whose other bytes are the earlier ones gives.
+    #[test]
+    fn detiling_ranges_matches_detiling_the_merged_memory() {
+        let cases = [
+            desc(256, 256, 9, 4, Swizzle::SW_64KB_D),
+            desc(300, 200, 9, 16, Swizzle::SW_4KB_S),
+            desc(100, 60, 7, 4, Swizzle::LINEAR),
+            desc(83, 31, 6, 1, Swizzle::SW_256B_S),
+        ];
+        for d in cases {
+            let l = Layout::new(&d).unwrap();
+            let size = l.size as usize;
+            let old: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
+            let mid = size / 3..(size / 3 + 5000).min(size / 2);
+            let ranges = [100..900.min(size / 4), mid, size - size / 8..size];
+            let mut merged = old.clone();
+            for r in &ranges {
+                for b in &mut merged[r.clone()] {
+                    *b = !*b;
+                }
+            }
+            for mip in 0..d.mips {
+                let m = l.mips[mip as usize];
+                let row = m.width as usize * d.element_bytes as usize;
+                let plane = row * m.height as usize;
+                let mut partial = vec![0; plane];
+                l.detile(&old, mip, 0, &mut partial, row, plane).unwrap();
+                l.detile_ranges(&merged, mip, 0, &mut partial, row, plane, &ranges)
+                    .unwrap();
+                let mut whole = vec![0; plane];
+                l.detile(&merged, mip, 0, &mut whole, row, plane).unwrap();
+                assert_eq!(partial, whole, "{d:?} mip {mip}");
+            }
+        }
+    }
+
+    /// A subresource's extents hold every element it detiles, and bytes
+    /// outside them do not change what it detiles to.
+    #[test]
+    fn extents_hold_what_a_subresource_detiles() {
+        let cases = [
+            desc(64, 64, 7, 16, Swizzle::SW_64KB_D),
+            desc(100, 60, 7, 4, Swizzle::SW_64KB_D),
+            desc(250, 175, 8, 8, Swizzle::SW_4KB_S),
+            desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
+            desc(30, 20, 5, 4, Swizzle::LINEAR),
+            desc(83, 31, 6, 1, Swizzle::SW_256B_S),
+            Desc {
+                depth: 3,
+                ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
+            },
+            Desc {
+                depth: 4,
+                ..desc(30, 20, 3, 4, Swizzle::LINEAR)
+            },
+            Desc {
+                dimension: Dimension::Tex3d,
+                depth: 16,
+                ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S)
+            },
+        ];
+        for d in cases {
+            let l = Layout::new(&d).unwrap();
+            let size = l.size as usize;
+            let tiled: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
+            let slices = if d.dimension == Dimension::Tex3d {
+                1
+            } else {
+                d.depth
+            };
+            for slice in 0..slices {
+                for mip in 0..d.mips {
+                    let e = l.extents(mip, slice).unwrap();
+                    assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}");
+                    for w in e.windows(2) {
+                        assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}");
+                    }
+                    assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size));
+                    let inside = |at: u64| e.iter().any(|r| r.contains(&at));
+                    let m = l.mips[mip as usize];
+                    let n = u64::from(d.element_bytes);
+                    // Outside the tail a 2D mip's extent is its own blocks.
+                    if m.tail.is_none() && d.dimension != Dimension::Tex3d {
+                        let total: u64 = e.iter().map(|r| r.end - r.start).sum();
+                        let own = u64::from(m.pitch) * u64::from(m.rows) * n;
+                        assert!(total <= own, "{d:?} mip {mip}: {total} > {own}");
+                    }
+                    for z in 0..m.depth {
+                        for y in 0..m.height {
+                            for x in 0..m.width {
+                                let at = l.offset(mip, x, y, slice + z).unwrap();
+                                assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}");
+                            }
+                        }
+                    }
+                    let row = m.width as usize * n as usize;
+                    let plane = row * m.height as usize;
+                    let mut before = vec![0; plane * m.depth as usize];
+                    l.detile(&tiled, mip, slice, &mut before, row, plane)
+                        .unwrap();
+                    let mut changed = tiled.clone();
+                    for (i, b) in changed.iter_mut().enumerate() {
+                        if !inside(i as u64) {
+                            *b = !*b;
+                        }
+                    }
+                    let mut after = vec![0; before.len()];
+                    l.detile(&changed, mip, slice, &mut after, row, plane)
+                        .unwrap();
+                    assert_eq!(before, after, "{d:?} mip {mip} slice {slice}");
+                }
+            }
+        }
+    }
+
     /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
     /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
     /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
index 9b3d38e6..b50d1f73 100644
--- a/crates/victory-gpu/src/texture.rs
+++ b/crates/victory-gpu/src/texture.rs
@@ -10,7 +10,11 @@
 //! same physical pages) in the runtime's memory; elsewhere, a content hash
 //! of the whole memory at every submission that samples it.
 //!
-//! shortcut: a change detiles the whole texture, not the pages written.
+//! In tracked memory only the pages written are read again and detiled
+//! again (into the subresources whose memory holds them).
+//!
+//! shortcut: hashed memory detiles the whole texture on a change; every
+//! subresource is still copied into the host texture.
 //! Textures read through descriptor tables are brought up to date, and for
 //! shaders that index the heap themselves every texture with a resource
 //! object the heap views (`crate::bindless`); textures the title placed in
@@ -18,6 +22,7 @@
 //! 0 is uploaded (every mip and array slice), depth and stencil planes are
 //! not.
 
+use std::ops::Range;
 use std::sync::{Arc, Mutex};
 
 use windows::Win32::Graphics::Direct3D12::*;
@@ -45,6 +50,9 @@ pub(crate) struct Staging {
     layout: victory_formats::texture::Layout,
     /// Mips per array slice.
     mips: u32,
+    /// Per subresource, the bytes of the memory it is detiled from
+    /// (offsets in it, sorted).
+    extents: Vec<Vec<Range<usize>>>,
     memory: *const u8,
     /// The memory's pages changed since detiled (none: not the runtime's
     /// memory, hashed instead).
@@ -52,14 +60,18 @@ pub(crate) struct Staging {
     last: Mutex<Last>,
 }
 
-/// What a texture's staging buffer holds: the hash of the memory detiled
-/// (memory not tracked), with room to read tracked memory into.
+/// What a texture's staging buffer holds: the hash of each [`HASHED`]
+/// bytes of the memory detiled (memory not tracked), with room to read
+/// tracked memory into.
 #[derive(Default)]
 struct Last {
-    hash: Option<blake3::Hash>,
+    hashes: Vec<blake3::Hash>,
     read: Vec<u8>,
 }
 
+/// The bytes one hash of untracked texture memory covers.
+const HASHED: usize = 64 << 10;
+
 // SAFETY: the staging mapping is written only at submission, under
 // `last`'s lock; the title memory is only read.
 unsafe impl Send for Staging {}
@@ -204,7 +216,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
     };
     // The staging buffer lives as long as `staging`, which the deferred
     // refresh below holds until the list is reset.
-    record(list, resource, texture, &staging);
+    record(list, resource, texture, &staging, None);
     // Once per submission however many of its lists sample the texture.
     list.defer_texture(staging);
 }
@@ -221,20 +233,25 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re
     let Some(staging) = staging(resource, texture) else {
         return false;
     };
-    if !staging.refresh() {
+    let parts = staging.refresh_parts();
+    if parts.is_empty() {
         return false;
     }
-    record(list, resource, texture, &staging);
+    // Only the subresources detiled again: the host texture holds the rest.
+    record(list, resource, texture, &staging, Some(&parts));
     list.keep(&staging.buffer);
     true
 }
 
-/// Records the copy of every subresource of `staging` into `texture`,
-/// moving it to the copy destination state first.
-fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) {
+/// Records the copy of the subresources `only` names (all with `None`) of
+/// `staging` into `texture`, moving it to the copy destination state first.
+fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging, only: Option<&[usize]>) {
     const COPY_DEST: u32 = 0x400;
     crate::list::ensure_state(list, resource, COPY_DEST);
     for (i, footprint) in staging.footprints.iter().enumerate() {
+        if only.is_some_and(|o| o.binary_search(&i).is_err()) {
+            continue;
+        }
         #[cfg(feature = "diagnostics")]
         {
             let f = footprint.Footprint;
@@ -287,33 +304,53 @@ impl Staging {
     /// Detiles the texture memory into the staging buffer if it changed
     /// since the last time (and is mapped at all): whether it did.
     pub(crate) fn refresh(&self) -> bool {
+        !self.refresh_parts().is_empty()
+    }
+
+    /// As [`Staging::refresh`]: the subresources detiled again (in order).
+    pub(crate) fn refresh_parts(&self) -> Vec<usize> {
         use std::sync::atomic::Ordering::Relaxed;
         let started = std::time::Instant::now();
-        let (read, changed) = self.refresh_now();
+        let (read, parts) = self.refresh_now();
         let preparing = &crate::host::PREPARING;
         preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
         preparing[3].fetch_add(read as u64, Relaxed);
-        changed
+        parts
     }
 
-    /// Returns the bytes of title memory read, and whether it detiled.
-    fn refresh_now(&self) -> (usize, bool) {
+    /// Returns the bytes of title memory read, and the subresources it
+    /// detiled.
+    fn refresh_now(&self) -> (usize, Vec<usize>) {
         let size = self.layout.size as usize;
         let start = self.memory as usize;
         let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
         let last = &mut *last;
         if let Some(t) = &self.tracked {
-            if t.take(start, start + size).is_empty() {
-                return (0, false);
+            let runs = t.take(start, start + size);
+            if runs.is_empty() {
+                return (0, Vec::new());
             }
             // Read through the copy, which stands unmapped pages: memory of
-            // big pools is too slow to ask page by page.
-            last.read.resize(size, 0);
-            crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
-            self.detile(&last.read);
+            // big pools is too slow to ask page by page. The first time all
+            // of it; then the pages written, the rest is as last read.
+            let changed: Vec<Range<usize>> = if last.read.len() != size {
+                last.read.resize(size, 0);
+                crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
+                std::iter::once(0..size).collect()
+            } else {
+                let changed: Vec<Range<usize>> = runs.iter().map(|&(a, b)| a - start..b - start).collect();
+                for r in &changed {
+                    // SAFETY: `r` lies inside both the memory and the copy.
+                    let (to, from) = unsafe { (last.read.as_mut_ptr().add(r.start), self.memory.add(r.start)) };
+                    crate::host::copy_mapped(to, from, r.len(), false);
+                }
+                changed
+            };
+            let read: usize = changed.iter().map(Range::len).sum();
+            let detiled = self.detile(&last.read, Some(&changed));
             #[cfg(feature = "diagnostics")]
-            crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
-            return (size, true);
+            crate::copystat::add(crate::copystat::C::TexWatched, read as u64);
+            return (read, detiled);
         }
         if !committed(self.memory, size) {
             #[cfg(feature = "diagnostics")]
@@ -323,25 +360,29 @@ impl Staging {
                 desc = ?self.layout.desc,
                 "a sampled texture's memory is not committed"
             );
-            return (0, false);
+            return (0, Vec::new());
         }
         // SAFETY: committed memory of the texture's layout size.
         let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
-        let hash = blake3::hash(tiled);
         #[cfg(feature = "diagnostics")]
         crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
-        if last.hash == Some(hash) {
-            return (size, false);
+        let (hashes, changed) = changed_chunks(tiled, &last.hashes);
+        if changed.is_empty() {
+            return (size, Vec::new());
         }
-        last.hash = Some(hash);
-        self.detile(tiled);
+        // The first time every chunk differs: all of it.
+        let first = last.hashes.is_empty();
+        last.hashes = hashes;
+        let parts = self.detile(tiled, (!first).then_some(&changed[..]));
         #[cfg(feature = "diagnostics")]
         crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
-        (size, true)
+        (size, parts)
     }
 
-    /// Detiles `tiled` (the texture's memory) into the staging buffer.
-    fn detile(&self, tiled: &[u8]) {
+    /// Detiles `tiled` (the texture's memory) into the staging buffer: the
+    /// bytes in `changed` of the subresources they reach (all with `None`).
+    /// The subresources it detiled.
+    fn detile(&self, tiled: &[u8], changed: Option<&[Range<usize>]>) -> Vec<usize> {
         #[cfg(feature = "diagnostics")]
         if tiled.iter().all(|&b| b == 0) {
             tracing::debug!(
@@ -350,26 +391,120 @@ impl Staging {
                 "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
             );
         }
-        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 = subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size);
-            // SAFETY: `subresource_len` clamps `len` to `self.size - footprint.Offset`,
-            // keeping the slice strictly inside the mapped staging buffer even when
-            // GetCopyableFootprints does not pad the final row of the last subresource.
-            let linear = unsafe {
-                std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
-            };
-            if let Err(e) =
-                self.layout
-                    .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
-            {
-                tracing::warn!(?e, mip, slice, "texture not detiled");
-                return;
-            }
+        let parts: Vec<Part> = self
+            .footprints
+            .iter()
+            .zip(&self.rows)
+            .map(|(footprint, &rows)| {
+                let f = footprint.Footprint;
+                let pitch = f.RowPitch as usize;
+                Part {
+                    offset: footprint.Offset as usize,
+                    pitch,
+                    rows: rows as usize,
+                    // Inside the staging buffer even when its last row is
+                    // not padded (`subresource_len`).
+                    len: subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size),
+                }
+            })
+            .collect();
+        // SAFETY: the mapped staging buffer, `self.size` bytes.
+        let staging = unsafe { std::slice::from_raw_parts_mut(self.data, self.size as usize) };
+        detile_parts(&self.layout, self.mips, &parts, &self.extents, tiled, staging, changed)
+    }
+}
+
+/// A subresource's place in the staging buffer: offset, row pitch, rows
+/// per depth slice, and bytes.
+struct Part {
+    offset: usize,
+    pitch: usize,
+    rows: usize,
+    len: usize,
+}
+
+/// Whether any of `extents` overlaps any of `changed` (both sorted).
+fn overlaps(extents: &[Range<usize>], changed: &[Range<usize>]) -> bool {
+    let (mut i, mut j) = (0, 0);
+    while i < extents.len() && j < changed.len() {
+        let (e, c) = (&extents[i], &changed[j]);
+        if e.start < c.end && c.start < e.end {
+            return true;
+        }
+        if e.end <= c.end {
+            i += 1;
+        } else {
+            j += 1;
         }
     }
+    false
+}
+
+/// Per subresource (mip-major within each array slice), the bytes of the
+/// tiled memory it is detiled from; the whole memory where the layout
+/// cannot say.
+fn extents_of(layout: &victory_formats::texture::Layout, mips: u32, count: usize) -> Vec<Vec<Range<usize>>> {
+    (0..count as u32)
+        .map(|i| match layout.extents(i % mips, i / mips) {
+            Ok(e) => e.into_iter().map(|r| r.start as usize..r.end as usize).collect(),
+            Err(_) => std::iter::once(0..layout.size as usize).collect(),
+        })
+        .collect()
+}
+
+/// Detiles into `staging` (laid out as `parts`) the bytes in `changed` of
+/// the subresources whose `extents` overlap it (all with `None`). The
+/// subresources it detiled, in order.
+fn detile_parts(
+    layout: &victory_formats::texture::Layout,
+    mips: u32,
+    parts: &[Part],
+    extents: &[Vec<Range<usize>>],
+    tiled: &[u8],
+    staging: &mut [u8],
+    changed: Option<&[Range<usize>]>,
+) -> Vec<usize> {
+    let mut done = Vec::new();
+    for (i, part) in parts.iter().enumerate() {
+        if let (Some(c), Some(e)) = (changed, extents.get(i))
+            && !overlaps(e, c)
+        {
+            continue;
+        }
+        let (mip, slice) = (i as u32 % mips, i as u32 / mips);
+        let linear = &mut staging[part.offset..part.offset + part.len];
+        // Only the written bytes: the rest of the subresource is as detiled
+        // before.
+        let detiled = match changed {
+            Some(c) => layout.detile_ranges(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows, c),
+            None => layout.detile(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows),
+        };
+        if let Err(e) = detiled {
+            tracing::warn!(?e, mip, slice, "texture not detiled");
+            return done;
+        }
+        done.push(i);
+    }
+    done
+}
+
+/// The hash of each [`HASHED`] bytes of `tiled`, and the byte ranges whose
+/// hash differs from `before` (all of it when `before` is of another size).
+fn changed_chunks(tiled: &[u8], before: &[blake3::Hash]) -> (Vec<blake3::Hash>, Vec<Range<usize>>) {
+    let hashes: Vec<blake3::Hash> = tiled.chunks(HASHED).map(blake3::hash).collect();
+    let same_size = before.len() == hashes.len();
+    let mut changed: Vec<Range<usize>> = Vec::new();
+    for (k, h) in hashes.iter().enumerate() {
+        if same_size && before[k] == *h {
+            continue;
+        }
+        let r = k * HASHED..((k + 1) * HASHED).min(tiled.len());
+        match changed.last_mut() {
+            Some(last) if last.end == r.start => last.end = r.end,
+            _ => changed.push(r),
+        }
+    }
+    (hashes, changed)
 }
 
 /// Bytes available in the staging buffer for a subresource at `offset`.
@@ -467,6 +602,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
     });
     tracing::debug!(?desc, total, "texture contents uploaded from title memory");
     let layout_size = layout.size as usize;
+    let extents = extents_of(&layout, u32::from(d.MipLevels), footprints.len());
     let s = Arc::new(Staging {
         buffer,
         size: total,
@@ -475,6 +611,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
         rows,
         layout,
         mips: u32::from(d.MipLevels),
+        extents,
         memory,
         tracked: crate::watch::track(memory as usize, layout_size, true),
         last: Mutex::default(),
@@ -520,4 +657,124 @@ mod tests {
         // SAFETY: freeing the allocation above.
         unsafe { VirtualFree(rw, 0, MEM_RELEASE) };
     }
+
+    use victory_formats::texture::{Desc, Dimension, Layout, Swizzle};
+
+    /// Detiling only the subresources a set of written pages reaches, onto
+    /// what the old memory detiled to, gives what detiling all of the new
+    /// memory gives.
+    #[test]
+    fn detiling_the_changed_subresources_matches_detiling_all() {
+        let cases = [
+            (Dimension::Tex2d, 256, 256, 1, 9, 4, Swizzle::SW_64KB_D),
+            (Dimension::Tex2d, 300, 200, 3, 9, 16, Swizzle::SW_4KB_S),
+            (Dimension::Tex2d, 1024, 512, 1, 11, 8, Swizzle::SW_64KB_S),
+            (Dimension::Tex3d, 64, 64, 16, 7, 4, Swizzle::SW_4KB_S),
+            (Dimension::Tex2d, 100, 60, 2, 7, 4, Swizzle::LINEAR),
+        ];
+        for (dimension, width, height, depth, mips, element_bytes, swizzle) in cases {
+            let d = Desc { dimension, width, height, depth, mips, element_bytes, block: 1, samples: 1, swizzle };
+            let layout = Layout::new(&d).unwrap();
+            let size = layout.size as usize;
+            let slices = if dimension == Dimension::Tex3d { 1 } else { depth };
+            // Linear subresources one after another, rows 256-byte aligned.
+            let mut parts = Vec::new();
+            let mut offset = 0;
+            for _ in 0..slices {
+                for mip in 0..mips {
+                    let m = &layout.mips[mip as usize];
+                    let pitch = (m.width as usize * element_bytes as usize).next_multiple_of(256);
+                    let len = pitch * m.height as usize * m.depth.max(1) as usize;
+                    let p = Part { offset, pitch, rows: m.height as usize, len };
+                    offset = (offset + p.len).next_multiple_of(512);
+                    parts.push(p);
+                }
+            }
+            let extents = extents_of(&layout, mips, parts.len());
+            let old: Vec<u8> = (0..size).map(|i| (i * 7 + i / 4093) as u8).collect();
+            for seed in 0..6usize {
+                // Pages written: a few 4 KiB pages anywhere.
+                let mut new = old.clone();
+                let mut changed = Vec::new();
+                for k in 0..3 {
+                    let page = (seed * 977 + k * 6151) % size.div_ceil(4096);
+                    let r = page * 4096..((page + 1) * 4096).min(size);
+                    for b in &mut new[r.clone()] {
+                        *b = !*b;
+                    }
+                    changed.push(r);
+                }
+                changed.sort_by_key(|r| r.start);
+                changed.dedup();
+                let mut partial = vec![0u8; offset];
+                assert_eq!(detile_parts(&layout, mips, &parts, &extents, &old, &mut partial, None).len(), parts.len());
+                detile_parts(&layout, mips, &parts, &extents, &new, &mut partial, Some(&changed));
+                let mut whole = vec![0u8; offset];
+                detile_parts(&layout, mips, &parts, &extents, &new, &mut whole, None);
+                assert!(partial == whole, "{d:?} seed {seed}");
+            }
+        }
+    }
+
+    /// Hashed memory: the chunks that changed, merged; all of it the first
+    /// time.
+    #[test]
+    fn changed_chunks_name_the_chunks_written() {
+                let mut m: Vec<u8> = (0..HASHED * 5 + 100).map(|i| i as u8).collect();
+        let (first, all) = changed_chunks(&m, &[]);
+        assert_eq!(all, vec![0..m.len()]);
+        m[HASHED + 7] ^= 1;
+        m[2 * HASHED] ^= 1;
+        m[5 * HASHED + 50] ^= 1;
+        let (_, changed) = changed_chunks(&m, &first);
+        assert_eq!(changed, vec![HASHED..3 * HASHED, 5 * HASHED..m.len()]);
+        let (same, _) = changed_chunks(&m, &first);
+        assert!(changed_chunks(&m, &same).1.is_empty());
+    }
+
+    /// Timing (ignored; `--release --ignored --nocapture`): a 4096x4096
+    /// BC7 texture (1024x1024 16-byte blocks, full mip chain), one 64 KiB
+    /// page written: detiling all of it against only what the page reaches.
+    #[test]
+    #[ignore]
+    fn detile_one_written_page_of_a_4k_bc7_texture() {
+        let d = Desc {
+            dimension: Dimension::Tex2d,
+            width: 1024,
+            height: 1024,
+            depth: 1,
+            mips: 11,
+            element_bytes: 16,
+            block: 1,
+            samples: 1,
+            swizzle: Swizzle::SW_64KB_S,
+        };
+        let layout = Layout::new(&d).unwrap();
+        let size = layout.size as usize;
+        let mut parts = Vec::new();
+        let mut offset = 0;
+        for mip in 0..d.mips {
+            let m = &layout.mips[mip as usize];
+            let pitch = (m.width as usize * 16).next_multiple_of(256);
+            let p = Part { offset, pitch, rows: m.height as usize, len: pitch * m.height as usize };
+            offset = (offset + p.len).next_multiple_of(512);
+            parts.push(p);
+        }
+        let extents = extents_of(&layout, d.mips, parts.len());
+        let tiled: Vec<u8> = (0..size).map(|i| (i * 13) as u8).collect();
+        let mut staging = vec![0u8; offset];
+        let page = (size / 2) & !0xFFFF..((size / 2) & !0xFFFF) + 65536;
+        let rounds = 20;
+        let t = std::time::Instant::now();
+        for _ in 0..rounds {
+            detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, None);
+        }
+        let all = t.elapsed() / rounds;
+        let t = std::time::Instant::now();
+        for _ in 0..rounds {
+            detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, Some(std::slice::from_ref(&page)));
+        }
+        let one = t.elapsed() / rounds;
+        eprintln!("4096x4096 BC7, {} MiB: all {all:?}, one written page {one:?}", size >> 20);
+    }
 }

Unit tests only, no game files. AI-assisted (Claude rebased it; I ran it on my machine).

**@⁠wwwwwwww3333333** on GitHub · 2026-11-25 01:03 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7149160095) Update: main has moved to 42363ab6, and the port above conflicted with two changes merged since: - #603's `copy_runs` in `Layout::walk`. - `subresource_len` (4fc9d70), which keeps the staging slice inside the buffer when the last row isn't padded. Here it is rebased. `walk_rows` keeps the `copy_runs` specialisation and only adds the row-span skip. `Part` now carries its length from `subresource_len`, and the staging slice is `self.size`, so the partial path keeps that bounds fix. Without it, the port would have read past the buffer on such textures. Results on 42363ab6 + this, RX 6750 XT, i5-13400F, Windows 11, Rust 1.98.1 MSVC: | | victory-formats | victory-gpu | |---|---|---| | main 42363ab6 | 38 passed | 141 passed | | main + this | 40 passed | 143 passed | - The new tests (2 in victory-formats, 2 in victory-gpu) pass, and so do main's `subresource_len` and `committed` tests. - Timing (release, ignored test): a 4096x4096 BC7 texture with one 64 KiB page written in mip 0 takes **4.59 ms** to detile in full and **0.080 ms** with this. - `cargo clippy -p victory-formats -p victory-gpu --all-targets -- -D warnings`: clean. <details><summary>Patch against 42363ab6</summary> ```diff diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 76afb0bd..95c1ba8e 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -617,6 +617,88 @@ impl Layout { }) } + /// As [`Layout::detile`], but only the bytes of tiled memory inside + /// `ranges` (sorted, disjoint) are copied; the rest of `linear` keeps + /// what it held. Detiling the pages written since the last detiling + /// into the same rows gives what [`Layout::detile`] would. + #[allow(clippy::too_many_arguments)] + pub fn detile_ranges( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + row_pitch: usize, + depth_pitch: usize, + ranges: &[std::ops::Range<usize>], + ) -> Result<(), Error> { + let touched = |from: usize, to: usize| { + ranges + .get(ranges.partition_point(|r| r.end <= from)) + .is_some_and(|r| r.start < to) + }; + self.walk_rows(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, touched, |t, l, len| { + let end = t + len; + let mut i = ranges.partition_point(|r| r.end <= t); + while let Some(r) = ranges.get(i) { + if r.start >= end { + break; + } + let (a, b) = (r.start.max(t), r.end.min(end)); + linear[l + (a - t)..l + (b - t)].copy_from_slice(&tiled[a..b]); + i += 1; + } + }) + } + + /// The byte ranges of tiled memory that [`Layout::detile`] reads for + /// mip `mip` of array slice `slice` (3D: every depth slice of the mip, + /// `slice` 0): sorted, disjoint, one per depth slice or slab at most. + /// A mip in the tail gets the part of the tail block its elements span, + /// which other tail mips may share; a write outside every range leaves + /// the subresource's detiled contents as they were. + pub fn extents(&self, mip: u32, slice: u32) -> Result<Vec<std::ops::Range<u64>>, Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let bytes = m.width as usize * self.desc.element_bytes as usize; + let depth_pitch = bytes * m.height as usize; + let mut spans: Vec<std::ops::Range<u64>> = Vec::new(); + let z_of = |linear: usize| linear / depth_pitch; + let mut current: Option<(usize, std::ops::Range<u64>)> = None; + self.walk( + self.size as usize, + mip, + slice, + usize::MAX, + bytes, + depth_pitch, + |tiled, linear, len| { + let z = z_of(linear); + let run = tiled as u64..(tiled + len) as u64; + match &mut current { + Some((at, r)) if *at == z => { + r.start = r.start.min(run.start); + r.end = r.end.max(run.end); + } + _ => { + if let Some((_, r)) = current.replace((z, run)) { + spans.push(r); + } + } + } + }, + )?; + spans.extend(current.map(|(_, r)| r)); + spans.sort_by_key(|r| r.start); + let mut merged: Vec<std::ops::Range<u64>> = Vec::with_capacity(spans.len()); + for r in spans { + match merged.last_mut() { + Some(last) if r.start <= last.end => last.end = last.end.max(r.end), + _ => merged.push(r), + } + } + Ok(merged) + } + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. pub fn tile( &self, @@ -643,6 +725,23 @@ impl Layout { row_pitch: usize, depth_pitch: usize, mut copy: impl FnMut(usize, usize, usize), + ) -> Result<(), Error> { + self.walk_rows(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, |_, _| true, &mut copy) + } + + /// As [`Layout::walk`], visiting only the rows whose tiled bytes + /// `[from, to)` (the span of the row's runs) `row` accepts. + #[allow(clippy::too_many_arguments)] + fn walk_rows( + &self, + tiled_len: usize, + mip: u32, + slice: u32, + linear_len: usize, + row_pitch: usize, + depth_pitch: usize, + row: impl Fn(usize, usize) -> bool, + mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -704,6 +803,9 @@ impl Layout { .first() .map(|run| run.2) .filter(|&len| body.iter().all(|run| run.2 == len)); + let (lo, hi) = runs + .iter() + .fold((usize::MAX, 0), |(lo, hi), &(t, _, len)| (lo.min(t), hi.max(t + len))); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -711,9 +813,14 @@ impl Layout { let linear_row = z as usize * depth_pitch + y as usize * row_pitch; if linear { let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + if row(tiled_row as usize, tiled_row as usize + bytes) { + copy(tiled_row as usize, linear_row, bytes); + } } else { let tiled_row = (base + self.row(m, y, inner)) as usize; + if !row(tiled_row + lo, tiled_row + hi) { + continue; + } match run_len { Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), @@ -1014,6 +1121,122 @@ mod tests { } } + /// Detiling only some ranges onto an earlier detiling gives what + /// detiling all of memory whose other bytes are the earlier ones gives. + #[test] + fn detiling_ranges_matches_detiling_the_merged_memory() { + let cases = [ + desc(256, 256, 9, 4, Swizzle::SW_64KB_D), + desc(300, 200, 9, 16, Swizzle::SW_4KB_S), + desc(100, 60, 7, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let old: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let mid = size / 3..(size / 3 + 5000).min(size / 2); + let ranges = [100..900.min(size / 4), mid, size - size / 8..size]; + let mut merged = old.clone(); + for r in &ranges { + for b in &mut merged[r.clone()] { + *b = !*b; + } + } + for mip in 0..d.mips { + let m = l.mips[mip as usize]; + let row = m.width as usize * d.element_bytes as usize; + let plane = row * m.height as usize; + let mut partial = vec![0; plane]; + l.detile(&old, mip, 0, &mut partial, row, plane).unwrap(); + l.detile_ranges(&merged, mip, 0, &mut partial, row, plane, &ranges) + .unwrap(); + let mut whole = vec![0; plane]; + l.detile(&merged, mip, 0, &mut whole, row, plane).unwrap(); + assert_eq!(partial, whole, "{d:?} mip {mip}"); + } + } + } + + /// A subresource's extents hold every element it detiles, and bytes + /// outside them do not change what it detiles to. + #[test] + fn extents_hold_what_a_subresource_detiles() { + let cases = [ + desc(64, 64, 7, 16, Swizzle::SW_64KB_D), + desc(100, 60, 7, 4, Swizzle::SW_64KB_D), + desc(250, 175, 8, 8, Swizzle::SW_4KB_S), + desc(33, 17, 6, 1, Swizzle::SW_4KB_D), + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + Desc { + depth: 4, + ..desc(30, 20, 3, 4, Swizzle::LINEAR) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let tiled: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; + for slice in 0..slices { + for mip in 0..d.mips { + let e = l.extents(mip, slice).unwrap(); + assert!(!e.is_empty(), "{d:?} mip {mip} slice {slice}"); + for w in e.windows(2) { + assert!(w[0].end < w[1].start, "{d:?} mip {mip}: {e:?}"); + } + assert!(e.iter().all(|r| r.start < r.end && r.end <= l.size)); + let inside = |at: u64| e.iter().any(|r| r.contains(&at)); + let m = l.mips[mip as usize]; + let n = u64::from(d.element_bytes); + // Outside the tail a 2D mip's extent is its own blocks. + if m.tail.is_none() && d.dimension != Dimension::Tex3d { + let total: u64 = e.iter().map(|r| r.end - r.start).sum(); + let own = u64::from(m.pitch) * u64::from(m.rows) * n; + assert!(total <= own, "{d:?} mip {mip}: {total} > {own}"); + } + for z in 0..m.depth { + for y in 0..m.height { + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap(); + assert!(inside(at) && inside(at + n - 1), "{d:?} mip {mip}"); + } + } + } + let row = m.width as usize * n as usize; + let plane = row * m.height as usize; + let mut before = vec![0; plane * m.depth as usize]; + l.detile(&tiled, mip, slice, &mut before, row, plane) + .unwrap(); + let mut changed = tiled.clone(); + for (i, b) in changed.iter_mut().enumerate() { + if !inside(i as u64) { + *b = !*b; + } + } + let mut after = vec![0; before.len()]; + l.detile(&changed, mip, slice, &mut after, row, plane) + .unwrap(); + assert_eq!(before, after, "{d:?} mip {mip} slice {slice}"); + } + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 9b3d38e6..b50d1f73 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -10,7 +10,11 @@ //! same physical pages) in the runtime's memory; elsewhere, a content hash //! of the whole memory at every submission that samples it. //! -//! shortcut: a change detiles the whole texture, not the pages written. +//! In tracked memory only the pages written are read again and detiled +//! again (into the subresources whose memory holds them). +//! +//! shortcut: hashed memory detiles the whole texture on a change; every +//! subresource is still copied into the host texture. //! Textures read through descriptor tables are brought up to date, and for //! shaders that index the heap themselves every texture with a resource //! object the heap views (`crate::bindless`); textures the title placed in @@ -18,6 +22,7 @@ //! 0 is uploaded (every mip and array slice), depth and stencil planes are //! not. +use std::ops::Range; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::*; @@ -45,6 +50,9 @@ pub(crate) struct Staging { layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, + /// Per subresource, the bytes of the memory it is detiled from + /// (offsets in it, sorted). + extents: Vec<Vec<Range<usize>>>, memory: *const u8, /// The memory's pages changed since detiled (none: not the runtime's /// memory, hashed instead). @@ -52,14 +60,18 @@ pub(crate) struct Staging { last: Mutex<Last>, } -/// What a texture's staging buffer holds: the hash of the memory detiled -/// (memory not tracked), with room to read tracked memory into. +/// What a texture's staging buffer holds: the hash of each [`HASHED`] +/// bytes of the memory detiled (memory not tracked), with room to read +/// tracked memory into. #[derive(Default)] struct Last { - hash: Option<blake3::Hash>, + hashes: Vec<blake3::Hash>, read: Vec<u8>, } +/// The bytes one hash of untracked texture memory covers. +const HASHED: usize = 64 << 10; + // SAFETY: the staging mapping is written only at submission, under // `last`'s lock; the title memory is only read. unsafe impl Send for Staging {} @@ -204,7 +216,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) }; // The staging buffer lives as long as `staging`, which the deferred // refresh below holds until the list is reset. - record(list, resource, texture, &staging); + record(list, resource, texture, &staging, None); // Once per submission however many of its lists sample the texture. list.defer_texture(staging); } @@ -221,20 +233,25 @@ pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Re let Some(staging) = staging(resource, texture) else { return false; }; - if !staging.refresh() { + let parts = staging.refresh_parts(); + if parts.is_empty() { return false; } - record(list, resource, texture, &staging); + // Only the subresources detiled again: the host texture holds the rest. + record(list, resource, texture, &staging, Some(&parts)); list.keep(&staging.buffer); true } -/// Records the copy of every subresource of `staging` into `texture`, -/// moving it to the copy destination state first. -fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) { +/// Records the copy of the subresources `only` names (all with `None`) of +/// `staging` into `texture`, moving it to the copy destination state first. +fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging, only: Option<&[usize]>) { const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); for (i, footprint) in staging.footprints.iter().enumerate() { + if only.is_some_and(|o| o.binary_search(&i).is_err()) { + continue; + } #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; @@ -287,33 +304,53 @@ impl Staging { /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all): whether it did. pub(crate) fn refresh(&self) -> bool { + !self.refresh_parts().is_empty() + } + + /// As [`Staging::refresh`]: the subresources detiled again (in order). + pub(crate) fn refresh_parts(&self) -> Vec<usize> { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); - let (read, changed) = self.refresh_now(); + let (read, parts) = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); - changed + parts } - /// Returns the bytes of title memory read, and whether it detiled. - fn refresh_now(&self) -> (usize, bool) { + /// Returns the bytes of title memory read, and the subresources it + /// detiled. + fn refresh_now(&self) -> (usize, Vec<usize>) { let size = self.layout.size as usize; let start = self.memory as usize; let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some(t) = &self.tracked { - if t.take(start, start + size).is_empty() { - return (0, false); + let runs = t.take(start, start + size); + if runs.is_empty() { + return (0, Vec::new()); } // Read through the copy, which stands unmapped pages: memory of - // big pools is too slow to ask page by page. - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + // big pools is too slow to ask page by page. The first time all + // of it; then the pages written, the rest is as last read. + let changed: Vec<Range<usize>> = if last.read.len() != size { + last.read.resize(size, 0); + crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); + std::iter::once(0..size).collect() + } else { + let changed: Vec<Range<usize>> = runs.iter().map(|&(a, b)| a - start..b - start).collect(); + for r in &changed { + // SAFETY: `r` lies inside both the memory and the copy. + let (to, from) = unsafe { (last.read.as_mut_ptr().add(r.start), self.memory.add(r.start)) }; + crate::host::copy_mapped(to, from, r.len(), false); + } + changed + }; + let read: usize = changed.iter().map(Range::len).sum(); + let detiled = self.detile(&last.read, Some(&changed)); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return (size, true); + crate::copystat::add(crate::copystat::C::TexWatched, read as u64); + return (read, detiled); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -323,25 +360,29 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is not committed" ); - return (0, false); + return (0, Vec::new()); } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); - if last.hash == Some(hash) { - return (size, false); + let (hashes, changed) = changed_chunks(tiled, &last.hashes); + if changed.is_empty() { + return (size, Vec::new()); } - last.hash = Some(hash); - self.detile(tiled); + // The first time every chunk differs: all of it. + let first = last.hashes.is_empty(); + last.hashes = hashes; + let parts = self.detile(tiled, (!first).then_some(&changed[..])); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, true) + (size, parts) } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `tiled` (the texture's memory) into the staging buffer: the + /// bytes in `changed` of the subresources they reach (all with `None`). + /// The subresources it detiled. + fn detile(&self, tiled: &[u8], changed: Option<&[Range<usize>]>) -> Vec<usize> { #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -350,26 +391,120 @@ impl Staging { "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); } - 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 = subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size); - // SAFETY: `subresource_len` clamps `len` to `self.size - footprint.Offset`, - // keeping the slice strictly inside the mapped staging buffer even when - // GetCopyableFootprints does not pad the final row of the last subresource. - let linear = unsafe { - std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) - }; - if let Err(e) = - self.layout - .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) - { - tracing::warn!(?e, mip, slice, "texture not detiled"); - return; - } + let parts: Vec<Part> = self + .footprints + .iter() + .zip(&self.rows) + .map(|(footprint, &rows)| { + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + Part { + offset: footprint.Offset as usize, + pitch, + rows: rows as usize, + // Inside the staging buffer even when its last row is + // not padded (`subresource_len`). + len: subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size), + } + }) + .collect(); + // SAFETY: the mapped staging buffer, `self.size` bytes. + let staging = unsafe { std::slice::from_raw_parts_mut(self.data, self.size as usize) }; + detile_parts(&self.layout, self.mips, &parts, &self.extents, tiled, staging, changed) + } +} + +/// A subresource's place in the staging buffer: offset, row pitch, rows +/// per depth slice, and bytes. +struct Part { + offset: usize, + pitch: usize, + rows: usize, + len: usize, +} + +/// Whether any of `extents` overlaps any of `changed` (both sorted). +fn overlaps(extents: &[Range<usize>], changed: &[Range<usize>]) -> bool { + let (mut i, mut j) = (0, 0); + while i < extents.len() && j < changed.len() { + let (e, c) = (&extents[i], &changed[j]); + if e.start < c.end && c.start < e.end { + return true; + } + if e.end <= c.end { + i += 1; + } else { + j += 1; } } + false +} + +/// Per subresource (mip-major within each array slice), the bytes of the +/// tiled memory it is detiled from; the whole memory where the layout +/// cannot say. +fn extents_of(layout: &victory_formats::texture::Layout, mips: u32, count: usize) -> Vec<Vec<Range<usize>>> { + (0..count as u32) + .map(|i| match layout.extents(i % mips, i / mips) { + Ok(e) => e.into_iter().map(|r| r.start as usize..r.end as usize).collect(), + Err(_) => std::iter::once(0..layout.size as usize).collect(), + }) + .collect() +} + +/// Detiles into `staging` (laid out as `parts`) the bytes in `changed` of +/// the subresources whose `extents` overlap it (all with `None`). The +/// subresources it detiled, in order. +fn detile_parts( + layout: &victory_formats::texture::Layout, + mips: u32, + parts: &[Part], + extents: &[Vec<Range<usize>>], + tiled: &[u8], + staging: &mut [u8], + changed: Option<&[Range<usize>]>, +) -> Vec<usize> { + let mut done = Vec::new(); + for (i, part) in parts.iter().enumerate() { + if let (Some(c), Some(e)) = (changed, extents.get(i)) + && !overlaps(e, c) + { + continue; + } + let (mip, slice) = (i as u32 % mips, i as u32 / mips); + let linear = &mut staging[part.offset..part.offset + part.len]; + // Only the written bytes: the rest of the subresource is as detiled + // before. + let detiled = match changed { + Some(c) => layout.detile_ranges(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows, c), + None => layout.detile(tiled, mip, slice, linear, part.pitch, part.pitch * part.rows), + }; + if let Err(e) = detiled { + tracing::warn!(?e, mip, slice, "texture not detiled"); + return done; + } + done.push(i); + } + done +} + +/// The hash of each [`HASHED`] bytes of `tiled`, and the byte ranges whose +/// hash differs from `before` (all of it when `before` is of another size). +fn changed_chunks(tiled: &[u8], before: &[blake3::Hash]) -> (Vec<blake3::Hash>, Vec<Range<usize>>) { + let hashes: Vec<blake3::Hash> = tiled.chunks(HASHED).map(blake3::hash).collect(); + let same_size = before.len() == hashes.len(); + let mut changed: Vec<Range<usize>> = Vec::new(); + for (k, h) in hashes.iter().enumerate() { + if same_size && before[k] == *h { + continue; + } + let r = k * HASHED..((k + 1) * HASHED).min(tiled.len()); + match changed.last_mut() { + Some(last) if last.end == r.start => last.end = r.end, + _ => changed.push(r), + } + } + (hashes, changed) } /// Bytes available in the staging buffer for a subresource at `offset`. @@ -467,6 +602,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let layout_size = layout.size as usize; + let extents = extents_of(&layout, u32::from(d.MipLevels), footprints.len()); let s = Arc::new(Staging { buffer, size: total, @@ -475,6 +611,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { rows, layout, mips: u32::from(d.MipLevels), + extents, memory, tracked: crate::watch::track(memory as usize, layout_size, true), last: Mutex::default(), @@ -520,4 +657,124 @@ mod tests { // SAFETY: freeing the allocation above. unsafe { VirtualFree(rw, 0, MEM_RELEASE) }; } + + use victory_formats::texture::{Desc, Dimension, Layout, Swizzle}; + + /// Detiling only the subresources a set of written pages reaches, onto + /// what the old memory detiled to, gives what detiling all of the new + /// memory gives. + #[test] + fn detiling_the_changed_subresources_matches_detiling_all() { + let cases = [ + (Dimension::Tex2d, 256, 256, 1, 9, 4, Swizzle::SW_64KB_D), + (Dimension::Tex2d, 300, 200, 3, 9, 16, Swizzle::SW_4KB_S), + (Dimension::Tex2d, 1024, 512, 1, 11, 8, Swizzle::SW_64KB_S), + (Dimension::Tex3d, 64, 64, 16, 7, 4, Swizzle::SW_4KB_S), + (Dimension::Tex2d, 100, 60, 2, 7, 4, Swizzle::LINEAR), + ]; + for (dimension, width, height, depth, mips, element_bytes, swizzle) in cases { + let d = Desc { dimension, width, height, depth, mips, element_bytes, block: 1, samples: 1, swizzle }; + let layout = Layout::new(&d).unwrap(); + let size = layout.size as usize; + let slices = if dimension == Dimension::Tex3d { 1 } else { depth }; + // Linear subresources one after another, rows 256-byte aligned. + let mut parts = Vec::new(); + let mut offset = 0; + for _ in 0..slices { + for mip in 0..mips { + let m = &layout.mips[mip as usize]; + let pitch = (m.width as usize * element_bytes as usize).next_multiple_of(256); + let len = pitch * m.height as usize * m.depth.max(1) as usize; + let p = Part { offset, pitch, rows: m.height as usize, len }; + offset = (offset + p.len).next_multiple_of(512); + parts.push(p); + } + } + let extents = extents_of(&layout, mips, parts.len()); + let old: Vec<u8> = (0..size).map(|i| (i * 7 + i / 4093) as u8).collect(); + for seed in 0..6usize { + // Pages written: a few 4 KiB pages anywhere. + let mut new = old.clone(); + let mut changed = Vec::new(); + for k in 0..3 { + let page = (seed * 977 + k * 6151) % size.div_ceil(4096); + let r = page * 4096..((page + 1) * 4096).min(size); + for b in &mut new[r.clone()] { + *b = !*b; + } + changed.push(r); + } + changed.sort_by_key(|r| r.start); + changed.dedup(); + let mut partial = vec![0u8; offset]; + assert_eq!(detile_parts(&layout, mips, &parts, &extents, &old, &mut partial, None).len(), parts.len()); + detile_parts(&layout, mips, &parts, &extents, &new, &mut partial, Some(&changed)); + let mut whole = vec![0u8; offset]; + detile_parts(&layout, mips, &parts, &extents, &new, &mut whole, None); + assert!(partial == whole, "{d:?} seed {seed}"); + } + } + } + + /// Hashed memory: the chunks that changed, merged; all of it the first + /// time. + #[test] + fn changed_chunks_name_the_chunks_written() { + let mut m: Vec<u8> = (0..HASHED * 5 + 100).map(|i| i as u8).collect(); + let (first, all) = changed_chunks(&m, &[]); + assert_eq!(all, vec![0..m.len()]); + m[HASHED + 7] ^= 1; + m[2 * HASHED] ^= 1; + m[5 * HASHED + 50] ^= 1; + let (_, changed) = changed_chunks(&m, &first); + assert_eq!(changed, vec![HASHED..3 * HASHED, 5 * HASHED..m.len()]); + let (same, _) = changed_chunks(&m, &first); + assert!(changed_chunks(&m, &same).1.is_empty()); + } + + /// Timing (ignored; `--release --ignored --nocapture`): a 4096x4096 + /// BC7 texture (1024x1024 16-byte blocks, full mip chain), one 64 KiB + /// page written: detiling all of it against only what the page reaches. + #[test] + #[ignore] + fn detile_one_written_page_of_a_4k_bc7_texture() { + let d = Desc { + dimension: Dimension::Tex2d, + width: 1024, + height: 1024, + depth: 1, + mips: 11, + element_bytes: 16, + block: 1, + samples: 1, + swizzle: Swizzle::SW_64KB_S, + }; + let layout = Layout::new(&d).unwrap(); + let size = layout.size as usize; + let mut parts = Vec::new(); + let mut offset = 0; + for mip in 0..d.mips { + let m = &layout.mips[mip as usize]; + let pitch = (m.width as usize * 16).next_multiple_of(256); + let p = Part { offset, pitch, rows: m.height as usize, len: pitch * m.height as usize }; + offset = (offset + p.len).next_multiple_of(512); + parts.push(p); + } + let extents = extents_of(&layout, d.mips, parts.len()); + let tiled: Vec<u8> = (0..size).map(|i| (i * 13) as u8).collect(); + let mut staging = vec![0u8; offset]; + let page = (size / 2) & !0xFFFF..((size / 2) & !0xFFFF) + 65536; + let rounds = 20; + let t = std::time::Instant::now(); + for _ in 0..rounds { + detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, None); + } + let all = t.elapsed() / rounds; + let t = std::time::Instant::now(); + for _ in 0..rounds { + detile_parts(&layout, d.mips, &parts, &extents, &tiled, &mut staging, Some(std::slice::from_ref(&page))); + } + let one = t.elapsed() / rounds; + eprintln!("4096x4096 BC7, {} MiB: all {all:?}, one written page {one:?}", size >> 20); + } } ``` </details> Unit tests only, no game files. AI-assisted (Claude rebased it; I ran it on my machine).
Author
Owner

@⁠akimfomin on GitHub · 2026-11-25 03:21 UTC · original · edited 2026-11-25 04:39 UTC

The selective detile work by talakasse and wwwwwwww3333333 suggests a separate step for upload_changed: use the dirty tiled page ranges to limit the GPU copy after the destination already has valid prior contents. PortBridge prototyped that mapping with the existing open GFX10 layout as the oracle.

On a synthetic 512×512 RGBA8 texture, one 64 KiB dirty tile generated one CopyTextureRegion box. D3D12 on RTX 4070 Ti SUPER issued a 65,536-byte update instead of 1,048,576 bytes, and full readback matched on every byte. The CPU verifier covered 1,592 dirty-range cases including unchanged slices, odd dimensions and mip tails. The prototype keeps full copies for uncertain eligibility, dense changes, and the first upload.

Planner source, GPU fixture and raw results. This is a standalone follow-up for a persistent staging buffer and initialized texture. Runtime integration remains open.

Follow-up on the same RTX card: four fresh processes and 48 order-balanced pairs per RGBA8 shape. The warmed GPU copy medians were 25.648 → 2.080 µs for one box, 24.256 → 5.616 µs for four adjacent tiles merged to one box, 24.400 → 5.728 µs for four separate boxes, and 24.640 → 10.176 µs for eight. Both final textures matched their whole reference in every shape. The four-separated set retains one slow outlier. Timing source and raw pairs.

An independent BC7 fixture also requested 64 KiB instead of 1 MiB for one aligned box in slice 1, mip 0. All 2,621,440 bytes per arm matched across both slices and both mips, including the 159,744 untouched compressed blocks. BC7 fixture and guarded readback. The timings cover repeated GPU copy commands on initialized resources. They do not include staging, detiling, or frame time. AI-assisted PortBridge verification (OpenAI Codex).

A CPU follow-up updates just one 64 KiB tile in already initialized staging. The 160 tile positions gave identical full images and row padding both against main 940d32f and against 0xkn0wh3r3's faster whole detile in #2026. On 1024×1024 RGBA8 the #2026 whole CPU detile was 320.00 µs versus 279.55 µs for the partial step with a byte check outside the tile, or 7.10 µs for that tile alone. On 2048×2048 BC7 those were 324.80, 276.15 and 7.10 µs. Additive helper, pin and eight process logs. These timings start with snapshots already in memory. The regional caller still needs an initialized staging buffer and a confirmed prior copy.

**@⁠akimfomin** on GitHub · 2026-11-25 03:21 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7151843889) · edited 2026-11-25 04:39 UTC The selective detile work by talakasse and wwwwwwww3333333 suggests a separate step for `upload_changed`: use the dirty tiled page ranges to limit the GPU copy after the destination already has valid prior contents. [PortBridge](https://github.com/akimfomin/PortBridge) prototyped that mapping with the existing open GFX10 layout as the oracle. On a synthetic 512×512 RGBA8 texture, one 64 KiB dirty tile generated one `CopyTextureRegion` box. D3D12 on RTX 4070 Ti SUPER issued a 65,536-byte update instead of 1,048,576 bytes, and full readback matched on every byte. The CPU verifier covered 1,592 dirty-range cases including unchanged slices, odd dimensions and mip tails. The prototype keeps full copies for uncertain eligibility, dense changes, and the first upload. [Planner source, GPU fixture and raw results](https://github.com/akimfomin/PortBridge/blob/ea79193b5271a146da3e8506f470b83b12207db1/research/rendering-night/victory-regional-upload/README.md). This is a standalone follow-up for a persistent staging buffer and initialized texture. Runtime integration remains open. Follow-up on the same RTX card: four fresh processes and 48 order-balanced pairs per RGBA8 shape. The warmed GPU copy medians were 25.648 → 2.080 µs for one box, 24.256 → 5.616 µs for four adjacent tiles merged to one box, 24.400 → 5.728 µs for four separate boxes, and 24.640 → 10.176 µs for eight. Both final textures matched their whole reference in every shape. The four-separated set retains one slow outlier. [Timing source and raw pairs](https://github.com/akimfomin/PortBridge/blob/76cab7e78fe434355308f1beca264eee064875d2/research/rendering-night/victory-regional-upload/TIMING.md). An independent BC7 fixture also requested 64 KiB instead of 1 MiB for one aligned box in slice 1, mip 0. All 2,621,440 bytes per arm matched across both slices and both mips, including the 159,744 untouched compressed blocks. [BC7 fixture and guarded readback](https://github.com/akimfomin/PortBridge/blob/5a16d149c861fd32040f6a34390cd86e0574559d/research/rendering-night/victory-regional-bc7/README.md). The timings cover repeated GPU copy commands on initialized resources. They do not include staging, detiling, or frame time. AI-assisted PortBridge verification (OpenAI Codex). A CPU follow-up updates just one 64 KiB tile in already initialized staging. The 160 tile positions gave identical full images and row padding both against main `940d32f` and against 0xkn0wh3r3's faster whole detile in #2026. On 1024×1024 RGBA8 the #2026 whole CPU detile was 320.00 µs versus 279.55 µs for the partial step with a byte check outside the tile, or 7.10 µs for that tile alone. On 2048×2048 BC7 those were 324.80, 276.15 and 7.10 µs. [Additive helper, pin and eight process logs](https://github.com/akimfomin/PortBridge/blob/d8951ea361805da14f6cc870178ba4d08f66b772/research/rendering-night/victory-tile-detile/README.md). These timings start with snapshots already in memory. The regional caller still needs an initialized staging buffer and a confirmed prior copy.
Author
Owner

@⁠wwwwwwww3333333 on GitHub · 2026-11-26 02:19 UTC · original

Main (63bcca4) now detiles only the subresources a tracked write reaches, which covers most of this PR. I opened #2985 on top of it for the part that is left: inside such a subresource, only the rows the written pages touch are read, detiled and copied to the host texture (a D3D12_BOX, since staging buffers now come from a shared pool). On an RX 6750 XT, one 64 KiB page written into mip 0 of a 4096x4096 BC7 texture: whole mip 2.73 ms, touched rows 0.086 ms (CPU detile only).

@⁠akimfomin that is also the GPU copy you suggested limiting, done per row band rather than per tiled page range. If your upload_changed step goes further, I am happy to rebase #2985 on it or drop the copy part.

**@⁠wwwwwwww3333333** on GitHub · 2026-11-26 02:19 UTC · [original](https://github.com/Marvisak/VIctory/pull/1135#issuecomment-7180695931) Main (63bcca4) now detiles only the subresources a tracked write reaches, which covers most of this PR. I opened #2985 on top of it for the part that is left: inside such a subresource, only the rows the written pages touch are read, detiled and copied to the host texture (a `D3D12_BOX`, since staging buffers now come from a shared pool). On an RX 6750 XT, one 64 KiB page written into mip 0 of a 4096x4096 BC7 texture: whole mip 2.73 ms, touched rows 0.086 ms (CPU detile only). @⁠akimfomin that is also the GPU copy you suggested limiting, done per row band rather than per tiled page range. If your `upload_changed` step goes further, I am happy to rebase #2985 on it or drop the copy part.
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/texture.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1135/head:github-bot/gh-1135'
git switch 'github-bot/gh-1135'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1135'
git switch 'github-bot/gh-1135'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1135'
git switch 'github-bot/gh-1135'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1135'
git switch 'main'
git merge --squash 'github-bot/gh-1135'
git switch 'main'
git merge --ff-only 'github-bot/gh-1135'
git switch 'main'
git merge 'github-bot/gh-1135'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!1135
No description provided.