GPU: a draw reads the swizzle it already has, and the release frame line costs nothing #3236

Open
borosf wants to merge 2 commits from upstream-pr/3238 into main
borosf commented 2026-11-26 14:14:12 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-26T14:14:12Z.


Four pieces of work in the world frame that run per draw, per list or per frame. No behaviour change: the same swizzle, the same dedup, the same count in the frame line — computed once instead of repeatedly, or only when something is going to read it.

What the diff does

A texture keeps the swizzle its description implies. memory_key needs the console layout's swizzle word, and it got it by calling texture_layout(desc) — which builds a whole texture (three allocations and the full mip chain) to return one u32. alias_source's bytes closure needed the same word. The expression is now the layout_swizzle(desc) helper and is evaluated once per resource, in hand_out_resource, into a new #[cfg(windows)] swizzle: u32 field on Resource; memory_key(address, desc, swizzle) and shared_texture take the word as a parameter, and current and alias_source — for the placed texture and for every candidate it compares — pass that resource's own. layout_swizzle still calls texture_layout, and footprint still builds its own layout at creation, so creation now pays for one more build; what the diff removes is the per-draw re-derivation.

Deferred's two dedup sets hash with Fx. refreshed: HashSet<(usize, usize, usize)> and textures: HashSet<usize> keep their type, their contents and their logic (insert before the work, clear when the list resets). What changes is the hasher: host.rs gains a private struct Fx(u64) implementing the FxHash multiply-rotate step, and type FastSet<T> = HashSet<T, BuildHasherDefault<Fx>>, which both fields now use. The comment in the diff gives the reason — keys of a few words each, SipHash costing more than the lookup it guards, and a Vec rejected because its scan is O(n) per refresh and O(n²) per list. There is no list and no first_use here, and defer_refresh/defer_heap are unchanged.

Stats::uses exists only in diagnostics builds. The map (BTreeMap<String, u64>) has one reader, the once-a-frame line that names the busiest shaders, and filling it cost a lock, a String and a BTreeMap descent per draw per memory-reading stage in every build. It is now #[cfg(feature = "diagnostics")] (diagnostics is an empty, non-default feature). The count survives without it: note_use bumps a new static USES: AtomicU64 (relaxed) in every build and fills the map only where it is compiled in, with let _ = pipeline; where it is not.

memory::log_frame asks before it builds. It still drains (stats(std::mem::take)), then returns early when nothing happened — USES swapped to zero and every counter zero — and returns again when !tracing::enabled!(Level::INFO), before the map is sorted and up to 32 pipeline strings are formatted. The line's {} draws/dispatches ({}) count now comes from USES in every build; the parenthesised list is built from the diagnostics-only map, so outside the feature it prints empty.

The numbers this diff can support

The diff adds one measurement, resource::tests::a_swizzle_costs_no_layout_per_placed_texture, which is #[ignore = "timing"]d and asserts nothing — it prints and returns. Recorded when the branch was pushed (Intel Arc B580, Windows 11, --release, --exact --ignored --nocapture, synthetic descriptions):

2048x2048, 12 mips: 290 ns to derive it, 0.00 ns to read the kept one
1920x1080 render target: 263 ns to derive it, 0.00 ns to read the kept one

The derive side is layout_swizzle per call: that is the cost the diff stops paying per draw. The read side times an index into a [u32; 8], so "0.00 ns" means "below this loop's resolution", not "a field read is free". Because the test asserts nothing, none of it fails if a later change makes the second side slower.

The dedup sets and the log_frame early return are unmeasured here: no benchmark, no counter, no before/after. Per-frame totals are not claimed either — how many placed-texture reads and texture views a world frame makes is not counted in this PR.

Verification

Recorded for this branch (not re-run for this body edit):

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings — clean.
  • cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings — clean.
  • cargo test -p victory-gpu --lib --locked --no-fail-fast — 229 passed, 2 failed. Both failures are this card's known baseline failures that pristine main also fails on the same machine: descriptor::host::tests::dynamic_slots_are_held_until_released and memory::tests::lists_share_a_table_and_copies_keep_their_views (#1744/#1829, the Intel view-heap cap).
  • rustfmt --edition 2024 --check per file, hunks against main (re-checked for this body edit with the same command on a main tree at the same paths): resource.rs 64/64, host.rs 85/85, memory.rs 30/30 — no new formatting hunks (the tree is deliberately not rustfmt-clean).

Synthetic descriptions and tests only; no game data was used, and none enters the repo.

Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.

<!-- greyfinch-sync:Marvisak/VIctory:issue:5511609787 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3238). Originally posted by [borosf](https://github.com/borosf) on 2026-11-26T14:14:12Z. --- Four pieces of work in the world frame that run per draw, per list or per frame. No behaviour change: the same swizzle, the same dedup, the same count in the frame line — computed once instead of repeatedly, or only when something is going to read it. ## What the diff does **A texture keeps the swizzle its description implies.** `memory_key` needs the console layout's swizzle word, and it got it by calling `texture_layout(desc)` — which builds a whole texture (three allocations and the full mip chain) to return one `u32`. `alias_source`'s `bytes` closure needed the same word. The expression is now the `layout_swizzle(desc)` helper and is evaluated once per resource, in `hand_out_resource`, into a new `#[cfg(windows)] swizzle: u32` field on `Resource`; `memory_key(address, desc, swizzle)` and `shared_texture` take the word as a parameter, and `current` and `alias_source` — for the placed texture and for every candidate it compares — pass that resource's own. `layout_swizzle` still calls `texture_layout`, and `footprint` still builds its own layout at creation, so creation now pays for one more build; what the diff removes is the per-draw re-derivation. **`Deferred`'s two dedup sets hash with Fx.** `refreshed: HashSet<(usize, usize, usize)>` and `textures: HashSet<usize>` keep their type, their contents and their logic (`insert` before the work, `clear` when the list resets). What changes is the hasher: `host.rs` gains a private `struct Fx(u64)` implementing the FxHash multiply-rotate step, and `type FastSet<T> = HashSet<T, BuildHasherDefault<Fx>>`, which both fields now use. The comment in the diff gives the reason — keys of a few words each, SipHash costing more than the lookup it guards, and a `Vec` rejected because its scan is O(n) per refresh and O(n²) per list. There is no list and no `first_use` here, and `defer_refresh`/`defer_heap` are unchanged. **`Stats::uses` exists only in diagnostics builds.** The map (`BTreeMap<String, u64>`) has one reader, the once-a-frame line that names the busiest shaders, and filling it cost a lock, a `String` and a `BTreeMap` descent per draw per memory-reading stage in every build. It is now `#[cfg(feature = "diagnostics")]` (`diagnostics` is an empty, non-default feature). The count survives without it: `note_use` bumps a new `static USES: AtomicU64` (relaxed) in every build and fills the map only where it is compiled in, with `let _ = pipeline;` where it is not. **`memory::log_frame` asks before it builds.** It still drains (`stats(std::mem::take)`), then returns early when nothing happened — `USES` swapped to zero and every counter zero — and returns again when `!tracing::enabled!(Level::INFO)`, before the map is sorted and up to 32 pipeline strings are formatted. The line's `{} draws/dispatches ({})` count now comes from `USES` in every build; the parenthesised list is built from the diagnostics-only map, so outside the feature it prints empty. ## The numbers this diff can support The diff adds one measurement, `resource::tests::a_swizzle_costs_no_layout_per_placed_texture`, which is `#[ignore = "timing"]`d and asserts nothing — it prints and returns. Recorded when the branch was pushed (Intel Arc B580, Windows 11, `--release`, `--exact --ignored --nocapture`, synthetic descriptions): ``` 2048x2048, 12 mips: 290 ns to derive it, 0.00 ns to read the kept one 1920x1080 render target: 263 ns to derive it, 0.00 ns to read the kept one ``` The derive side is `layout_swizzle` per call: that is the cost the diff stops paying per draw. The read side times an index into a `[u32; 8]`, so "0.00 ns" means "below this loop's resolution", not "a field read is free". Because the test asserts nothing, none of it fails if a later change makes the second side slower. The dedup sets and the `log_frame` early return are unmeasured here: no benchmark, no counter, no before/after. Per-frame totals are not claimed either — how many placed-texture reads and texture views a world frame makes is not counted in this PR. ## Verification Recorded for this branch (not re-run for this body edit): - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` — clean. - `cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings` — clean. - `cargo test -p victory-gpu --lib --locked --no-fail-fast` — 229 passed, 2 failed. Both failures are this card's known baseline failures that pristine `main` also fails on the same machine: `descriptor::host::tests::dynamic_slots_are_held_until_released` and `memory::tests::lists_share_a_table_and_copies_keep_their_views` (#1744/#1829, the Intel view-heap cap). - `rustfmt --edition 2024 --check` per file, hunks against `main` (re-checked for this body edit with the same command on a `main` tree at the same paths): `resource.rs` 64/64, `host.rs` 85/85, `memory.rs` 30/30 — no new formatting hunks (the tree is deliberately not `rustfmt`-clean). Synthetic descriptions and tests only; no game data was used, and none enters the repo. Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.
Dukestar69 commented 2026-11-26 14:34:14 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T14:34:14Z.

Review: APPROVED


Reviewed the diff and verified locally on Windows 11 x64 (RTX 5090):

  • Caching layout_swizzle on Resource at creation avoids rebuilding the full console mip layout per memory_key / lias_source lookup; gating Stats::uses behind diagnostics with an atomic USES counter and racing::enabled!(INFO) guard removes per-draw global lock/allocation overhead in non-diagnostics builds; small Vec lookups for Deferred::{refreshed, textures} are clean.
  • cargo test -p victory-gpu --lib resource:: -- --test-threads=1 (RTX 5090): 18 passed, 0 failed, 1 ignored (_swizzle_costs_no_layout_per_placed_texture).
  • cargo test -p victory-gpu --lib memory::tests:: -- --test-threads=1 --skip lists_share_a_table_and_copies_keep_their_views (RTX 5090): 7 passed, 0 failed (pre-existing #1744 test skipped).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo clippy -p victory-gpu --features diagnostics --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6075910299 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3238#pullrequestreview-6075910299). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T14:34:14Z. **Review:** APPROVED --- Reviewed the diff and verified locally on Windows 11 x64 (RTX 5090): - Caching layout_swizzle on Resource at creation avoids rebuilding the full console mip layout per memory_key / lias_source lookup; gating Stats::uses behind diagnostics with an atomic USES counter and racing::enabled!(INFO) guard removes per-draw global lock/allocation overhead in non-diagnostics builds; small Vec lookups for Deferred::{refreshed, textures} are clean. - cargo test -p victory-gpu --lib resource:: -- --test-threads=1 (RTX 5090): 18 passed, 0 failed, 1 ignored (_swizzle_costs_no_layout_per_placed_texture). - cargo test -p victory-gpu --lib memory::tests:: -- --test-threads=1 --skip lists_share_a_table_and_copies_keep_their_views (RTX 5090): 7 passed, 0 failed (pre-existing #1744 test skipped). - cargo clippy -p victory-gpu --all-targets -- -D warnings: clean. - cargo clippy -p victory-gpu --features diagnostics --all-targets -- -D warnings: clean. - cargo xtask policy: 191 files ok. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
KainanP commented 2026-11-26 15:02:35 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-26T14:50:07Z.


Measured on main 63bcca4 with this PR merged (RTX 4060 Laptop, release, median of 7 interleaved runs; method in https://github.com/Marvisak/VIctory/issues/2586#issuecomment-7195391455):

  • alias_source: 120 → 14 ns, and an indexed draw reading six textures: 2713 → 1966 ns. Good.
  • But Deferred::refreshed as a Vec with contains grows with the list. In a sequence where each draw binds a new constant-ring position (root CBV, 4 root constants, index buffer, draw; lists reset every 2,000 calls), the sequence costs 2388 ns per draw, against 1966 for the bare draw. On main and on every other build measured, the setters add ~70 ns. A world frame's lists refresh thousands of distinct ranges, so the scan is O(n) per refresh and O(n²) per list. A set with a cheap hash (#2102's FxHash) keeps the gain without that cost. #1978 has the same alias_source change alone.

AI use: Claude Code (Claude Opus 5.5) ran the measurements and drafted this comment.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7195398489 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3238#issuecomment-7195398489). Originally posted by [KainanP](https://github.com/KainanP) on 2026-11-26T14:50:07Z. --- Measured on main 63bcca4 with this PR merged (RTX 4060 Laptop, release, median of 7 interleaved runs; method in https://github.com/Marvisak/VIctory/issues/2586#issuecomment-7195391455): - `alias_source`: 120 → 14 ns, and an indexed draw reading six textures: 2713 → 1966 ns. Good. - But `Deferred::refreshed` as a `Vec` with `contains` grows with the list. In a sequence where each draw binds a new constant-ring position (root CBV, 4 root constants, index buffer, draw; lists reset every 2,000 calls), the sequence costs **2388 ns per draw, against 1966 for the bare draw**. On main and on every other build measured, the setters add ~70 ns. A world frame's lists refresh thousands of distinct ranges, so the scan is O(n) per refresh and O(n²) per list. A set with a cheap hash (#2102's FxHash) keeps the gain without that cost. #1978 has the same `alias_source` change alone. _AI use: Claude Code (Claude Opus 5.5) ran the measurements and drafted this comment._
borosf commented 2026-11-26 15:02:37 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-26T14:59:09Z.


Fixed at b5e79ab9b7999caef232e4025e17397f0919080a: Deferred::refreshed and Deferred::textures are now FastSet — a HashSet with an in-tree FxHash (the same multiply-rotate step as victory-shader's structure.rs; no new dependency) — so insert is O(1) at any list length instead of the O(n) Vec scan your sequence measured (2388 ns vs 1966 ns bare draw). The alias_source change is untouched and keeps your 120 → 14 ns. Clippy clean on both feature sets, 229 passed / 2 failed (the known #1744/#1829 baseline), rustfmt hunks host.rs 85/85. Synthetic tests only; no game data.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7195615146 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3238#issuecomment-7195615146). Originally posted by [borosf](https://github.com/borosf) on 2026-11-26T14:59:09Z. --- Fixed at `b5e79ab9b7999caef232e4025e17397f0919080a`: `Deferred::refreshed` and `Deferred::textures` are now `FastSet` — a `HashSet` with an in-tree FxHash (the same multiply-rotate step as victory-shader's `structure.rs`; no new dependency) — so insert is O(1) at any list length instead of the O(n) Vec scan your sequence measured (2388 ns vs 1966 ns bare draw). The alias_source change is untouched and keeps your 120 → 14 ns. Clippy clean on both feature sets, 229 passed / 2 failed (the known #1744/#1829 baseline), rustfmt hunks host.rs 85/85. Synthetic tests only; no game data.
borosf commented 2026-11-27 11:43:21 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-27T11:43:21Z.


Built my open PRs as one stack (main 63bcca43 + 20 of mine) to check they hold together on the title, and this one conflicts with #3215-era code in memory.rs — worth recording because the conflict resolution is better than either side alone.

Both sides end up in note_use:

  • This PR adds USES.fetch_add, puts the s.uses map behind #[cfg(feature = "diagnostics")], and keeps let _ = pipeline; for release builds — so a release build pays one atomic and no mutex per draw.
  • The other side keeps stats(...) unconditional but avoids a String per call with get_mut + insert only on the miss (to_owned on every call was allocating and freeing a String a draw).

stats is not gated (fn stats<R>(f: impl FnOnce(&mut Stats) -> R) -> R, unconditional STATS mutex), so the two are not exclusive — the merged form keeps the atomic and the allocation-free map update:

pub(crate) fn note_use(pipeline: &str) {
    USES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    #[cfg(feature = "diagnostics")]
    stats(|s| match s.uses.get_mut(pipeline) {
        Some(n) => *n += 1,
        None => {
            s.uses.insert(pipeline.to_owned(), 1);
        }
    });
    #[cfg(not(feature = "diagnostics"))]
    let _ = pipeline;
}

That is my whole point in writing it down: whichever of the two lands first, the other should not revert the atomic or the get_mut — a release build should not take STATS's mutex for a counter it does not print, and a diagnostics build should not allocate a key that is almost always already there.

I have not changed this PR; the stack is a local branch. With the resolution above the stack builds, cargo test -p victory-gpu --lib is 243 passed with the same two failures this host has on main (dynamic_slots_are_held_until_released, lists_share_a_table_and_copies_keep_their_views — both need a heap that reaches HEAP_VIEWS, which Arc caps), and the title boots to its menus exactly as main does (30 fps, 13 draws, 0 device removals, 0 title crashes in 110 s).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7217399328 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3238#issuecomment-7217399328). Originally posted by [borosf](https://github.com/borosf) on 2026-11-27T11:43:21Z. --- Built my open PRs as one stack (`main` 63bcca43 + 20 of mine) to check they hold together on the title, and this one conflicts with **#3215**-era code in `memory.rs` — worth recording because the conflict resolution is better than either side alone. Both sides end up in `note_use`: - **This PR** adds `USES.fetch_add`, puts the `s.uses` map behind `#[cfg(feature = "diagnostics")]`, and keeps `let _ = pipeline;` for release builds — so a release build pays one atomic and no mutex per draw. - **The other side** keeps `stats(...)` unconditional but avoids a `String` per call with `get_mut` + `insert` only on the miss (`to_owned` on every call was allocating and freeing a `String` a draw). `stats` is not gated (`fn stats<R>(f: impl FnOnce(&mut Stats) -> R) -> R`, unconditional `STATS` mutex), so the two are not exclusive — the merged form keeps the atomic *and* the allocation-free map update: ```rust pub(crate) fn note_use(pipeline: &str) { USES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); #[cfg(feature = "diagnostics")] stats(|s| match s.uses.get_mut(pipeline) { Some(n) => *n += 1, None => { s.uses.insert(pipeline.to_owned(), 1); } }); #[cfg(not(feature = "diagnostics"))] let _ = pipeline; } ``` That is my whole point in writing it down: whichever of the two lands first, the other should not revert the atomic or the `get_mut` — a release build should not take `STATS`'s mutex for a counter it does not print, and a diagnostics build should not allocate a key that is almost always already there. I have not changed this PR; the stack is a local branch. With the resolution above the stack builds, `cargo test -p victory-gpu --lib` is 243 passed with the same two failures this host has on `main` (`dynamic_slots_are_held_until_released`, `lists_share_a_table_and_copies_keep_their_views` — both need a heap that reaches `HEAP_VIEWS`, which Arc caps), and the title boots to its menus exactly as `main` does (30 fps, 13 draws, 0 device removals, 0 title crashes in 110 s).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3238:upstream-pr/3238'
git switch 'upstream-pr/3238'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3238'
git switch 'upstream-pr/3238'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3238'
git switch 'upstream-pr/3238'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3238'
git switch 'main'
git merge --squash 'upstream-pr/3238'
git switch 'main'
git merge --ff-only 'upstream-pr/3238'
git switch 'main'
git merge 'upstream-pr/3238'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
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.

Reference
Marvisak/VIctory!3236
No description provided.