upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Play-VIctory.cmd40
-rw-r--r--README.md13
-rw-r--r--crates/victory-gpu/src/descriptor/host.rs489
-rw-r--r--crates/victory-gpu/src/draw.rs469
-rw-r--r--crates/victory-gpu/src/host.rs25
-rw-r--r--crates/victory-gpu/src/indirect.rs10
-rw-r--r--crates/victory-gpu/src/list.rs6
-rw-r--r--crates/victory-gpu/src/pipeline/host.rs1
-rw-r--r--crates/victory-gpu/src/pool.rs16
-rw-r--r--crates/victory-gpu/src/residency.rs116
-rw-r--r--crates/victory-gpu/src/texture.rs34
-rw-r--r--crates/victory-gpu/src/texture/ahead.rs70
-rw-r--r--crates/victory-shader/src/emit/diff_tests.rs39
-rw-r--r--crates/victory-shader/src/emit/host.rs46
-rw-r--r--crates/victory-shader/src/emit/lower.rs34
-rw-r--r--crates/victory-shader/src/emit/mod.rs67
-rw-r--r--crates/victory-shader/src/emit/shader.rs5
-rw-r--r--crates/victory-shader/src/emit/valu_tests.rs334
-rw-r--r--crates/victory-shader/src/resource.rs68
-rw-r--r--docs/bug-journal.md4
20 files changed, 1670 insertions, 216 deletions
diff --git a/Play-VIctory.cmd b/Play-VIctory.cmd
new file mode 100644
index 0000000..38410dd
--- /dev/null
+++ b/Play-VIctory.cmd
@@ -0,0 +1,40 @@
1@echo off
2setlocal EnableExtensions DisableDelayedExpansion
3if not "%~1"=="" if /i not "%~1"=="pareto-residency" (
4 echo Usage: Play-VIctory.cmd pareto-residency 1>&2
5 exit /b 2
6)
7if not defined VICTORY_GAME_DIR set "VICTORY_GAME_DIR=%~dp0..\GTA6.Xbox.v1.0.2.1"
8if not exist "%VICTORY_GAME_DIR%\game_scarlett_master.exe" (
9 echo Set VICTORY_GAME_DIR to your own dump folder containing game_scarlett_master.exe. 1>&2
10 exit /b 2
11)
12set "runner=%~dp0victory-3d-rtx-pareto-residency.exe"
13if not exist "%runner%" set "runner=%~dp0target\release\victory.exe"
14if not exist "%runner%" (
15 echo Extract the Windows release or run cargo build --release --locked -p victory. 1>&2
16 exit /b 2
17)
18if not defined VICTORY_AMBIENT_AIR set "VICTORY_AMBIENT_AIR=1.5"
19if not defined VICTORY_CACHE_DIR set "VICTORY_CACHE_DIR=%LOCALAPPDATA%\VIctory\cache-pareto"
20if not defined VICTORY_TEXTURE_NO_WAIT set "VICTORY_TEXTURE_NO_WAIT=1"
21if not defined VICTORY_RELAY set "VICTORY_RELAY=2"
22if not defined VICTORY_WIDE_BACK set "VICTORY_WIDE_BACK=1"
23if not defined VICTORY_CARD_REHASH_RUNS set "VICTORY_CARD_REHASH_RUNS=1"
24if not defined VICTORY_JOIN_COPIES set "VICTORY_JOIN_COPIES=1"
25if not defined VICTORY_INDIRECT_WINDOW set "VICTORY_INDIRECT_WINDOW=1"
26if not defined VICTORY_RELAY_COPY set "VICTORY_RELAY_COPY=1"
27if not defined VICTORY_CARD_STEPS set "VICTORY_CARD_STEPS=2"
28if not defined VICTORY_INDIRECT_BATCH set "VICTORY_INDIRECT_BATCH=2"
29if not defined VICTORY_MAP_THREADS set "VICTORY_MAP_THREADS=1"
30if not defined VICTORY_CARD_AWAKE set "VICTORY_CARD_AWAKE=1"
31if not defined VICTORY_SHOW_AFTER set "VICTORY_SHOW_AFTER=1"
32if not defined VICTORY_AMBIENT set "VICTORY_AMBIENT=0.8"
33if not defined VICTORY_THIN set "VICTORY_THIN=1"
34if not defined VICTORY_JOIN_PARTS set "VICTORY_JOIN_PARTS=8"
35if not defined VICTORY_UPLOAD_AHEAD set "VICTORY_UPLOAD_AHEAD=1"
36if not defined VICTORY_LEVELS_ON_DEMAND set "VICTORY_LEVELS_ON_DEMAND=1"
37if not defined VICTORY_CARD_BUFFERS_MIN_KB set "VICTORY_CARD_BUFFERS_MIN_KB=64"
38if not defined VICTORY_LOG if not defined RUST_LOG set "VICTORY_LOG=warn"
39"%runner%" run "%VICTORY_GAME_DIR%\game_scarlett_master.exe" --console series-s --execute
40exit /b %errorlevel%
diff --git a/README.md b/README.md
index 9bc1b7b..284bf55 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,18 @@
1# VIctory on an RX 7900 XTX 1# VIctory on an RX 7900 XTX
2 2
3## Run the codec_d Windows build
4
5Download and extract the Windows x64 ZIP from the [private releases](https://github.com/codec-d/cool_fox/releases/latest). Open PowerShell in the extracted folder and point the launcher at your own complete Xbox dump.
6
7```powershell
8$env:VICTORY_GAME_DIR = 'D:\Games\MyDump'
9.\Play-VIctory.cmd pareto-residency
10```
11
12The launcher selects Series S and the RTX-tested residency settings. It builds its shader cache locally under `%LOCALAPPDATA%\VIctory\cache-pareto`. Set `VICTORY_CACHE_DIR` to reuse an existing cache outside the checkout. Windows x64, an AVX2 CPU, and a Direct3D 12 GPU with shader model 6.6 and mesh shader support are required.
13
14To build from this checkout, install the pinned Rust toolchain and the MSVC C++ build tools with a Windows SDK, then run `cargo build --release --locked -p victory`. The same launcher finds `target\release\victory.exe`. The sections below describe the upstream AMD fork and its separate launcher.
15
3A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer 16A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer
4that runs an Xbox Series title natively on Windows from files the user supplies. 17that runs an Xbox Series title natively on Windows from files the user supplies.
5This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on 18This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on
diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs
index 9cbae6f..176970b 100644
--- a/crates/victory-gpu/src/descriptor/host.rs
+++ b/crates/victory-gpu/src/descriptor/host.rs
@@ -426,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
426 426
427static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new()); 427static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
428 428
429/// Deferred slot flips recorded into an open or not-yet-submitted command
430/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can
431/// promote them out of the `neutral()` gray stand-in before sampling them.
432pub(crate) struct PendingListFlip {
433 id: u64,
434 pub(crate) origin: (usize, u64),
435 flip: Flip,
436}
437
438impl PendingListFlip {
439 pub(crate) fn index(&self) -> u32 {
440 self.flip.index
441 }
442
443 pub(crate) fn handle(&self) -> u64 {
444 self.flip.handle
445 }
446
447 pub(crate) fn key(&self) -> u64 {
448 self.flip.key
449 }
450}
451
452static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
453static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new());
454static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
455
456fn take_pending_list_flip(id: u64) -> Option<Flip> {
457 if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
458 return None;
459 }
460 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
461 let pos = pending.iter().position(|p| p.id == id)?;
462 let entry = pending.swap_remove(pos);
463 PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
464 Some(entry.flip)
465}
466
467fn remove_pending_list_flip(id: u64) {
468 let _ = take_pending_list_flip(id);
469}
470
429/// Makes the slots whose new texture's upload has run 471/// Makes the slots whose new texture's upload has run
430/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at 472/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
431/// something else: the next texture pass does. 473/// something else: the next texture pass does.
@@ -714,6 +756,12 @@ impl Spans {
714/// pass last took the ranges ([`page_written`]). Kept apart from 756/// pass last took the ranges ([`page_written`]). Kept apart from
715/// [`REMAPPED`] so that what such writes do is counted by itself. 757/// [`REMAPPED`] so that what such writes do is counted by itself.
716static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); 758static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
759/// Physical-page writes retained specifically for one-shot decoration/ped
760/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal
761/// frames stay free of queue flooding while every bake still sees freshly
762/// DirectStorage-streamed texture bytes immediately instead of waiting on
763/// `RECHECK_FRAMES`.
764static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
717 765
718/// Since the start: such ranges kept for a pass; ranges dropped because no 766/// Since the start: such ranges kept for a pass; ranges dropped because no
719/// pass took them; slots of placed textures that held bytes of them when a 767/// pass took them; slots of placed textures that held bytes of them when a
@@ -1105,29 +1153,46 @@ pub(crate) fn device_removed() -> Option<String> {
1105pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); 1153pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1106pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); 1154pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1107 1155
1108/// Bytes per element of a buffer view, as the console's descriptor holds 1156/// Bytes per element and typed integer format bits of a buffer view, decoded
1109/// them for indexed reads (structured: the stride; raw: 1, the index is the 1157/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view.
1110/// byte; typed: the format's); `None` if `view` is not a buffer view. 1158fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) {
1111fn view_stride(view: &View) -> Option<u32> { 1159 use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
1112 let (stride, raw, format) = view_elements(view)?; 1160 let Some((stride, raw, format)) = view_elements(view) else {
1113 Some(if stride > 0 { 1161 return (None, 0);
1162 };
1163 let bytes = if stride > 0 {
1114 stride 1164 stride
1115 } else if raw { 1165 } else if raw {
1116 1 1166 1
1117 } else { 1167 } else {
1118 crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) 1168 crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
1119 }) 1169 };
1170 let kind = if stride == 0 && !raw {
1171 match format {
1172 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER,
1173 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED,
1174 _ => 0,
1175 }
1176 } else {
1177 0
1178 };
1179 (Some(bytes), kind)
1180}
1181
1182/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`.
1183fn view_stride_word(view: &View) -> u32 {
1184 let (stride, kind) = view_stride_and_kind(view);
1185 stride.unwrap_or(0) | kind
1120} 1186}
1121 1187
1122/// What else the table of strides says of a typed buffer view of an integer 1188#[cfg(test)]
1123/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view. 1189fn view_stride(view: &View) -> Option<u32> {
1190 view_stride_and_kind(view).0
1191}
1192
1193#[cfg(test)]
1124fn view_kind(view: &View) -> u32 { 1194fn view_kind(view: &View) -> u32 {
1125 use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; 1195 view_stride_and_kind(view).1
1126 match view_elements(view) {
1127 Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
1128 Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
1129 _ => 0,
1130 }
1131} 1196}
1132 1197
1133/// A buffer view's structure stride, whether it is raw, and its format; 1198/// A buffer view's structure stride, whether it is raw, and its format;
@@ -1740,7 +1805,7 @@ impl HostHeap {
1740 pub(crate) fn texture_news(&self) -> (u64, bool) { 1805 pub(crate) fn texture_news(&self) -> (u64, bool) {
1741 let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; 1806 let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
1742 let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); 1807 let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
1743 (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) 1808 (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN))
1744 } 1809 }
1745 1810
1746 /// Every title slot of the queue that is due at `frame`, and whether 1811 /// Every title slot of the queue that is due at `frame`, and whether
@@ -1888,7 +1953,48 @@ impl HostHeap {
1888 if ranges.is_empty() { 1953 if ranges.is_empty() {
1889 return 0; 1954 return 0;
1890 } 1955 }
1891 self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] 1956 let due = crate::watch::page_writes() & 2 != 0;
1957 let made_due = self.slots_written_under(&ranges, frame, due)[2];
1958 if !due {
1959 let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
1960 kept.extend(ranges);
1961 if kept.len() > 256 {
1962 join(&mut kept);
1963 const MOST: usize = 1 << 14;
1964 if kept.len() > MOST {
1965 let drop_n = kept.len() - MOST;
1966 kept.drain(..drop_n);
1967 }
1968 }
1969 }
1970 made_due
1971 }
1972
1973 /// Wakes uploaded placed-texture slots touched by recent physical-page
1974 /// writes (DirectStorage completions) immediately (`due = frame`) right
1975 /// before a one-shot ped/decoration bake draw.
1976 pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize {
1977 let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
1978 if ranges.is_empty() {
1979 return 0;
1980 }
1981 join(&mut ranges);
1982 let mut slots: Vec<u32> = {
1983 let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
1984 ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
1985 };
1986 if slots.is_empty() {
1987 return 0;
1988 }
1989 slots.sort_unstable();
1990 slots.dedup();
1991 slots.retain(|&slot| !self.tabled_lately(slot, frame));
1992 let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
1993 slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
1994 for &slot in &slots {
1995 textures.changed(slot, frame, frame);
1996 }
1997 slots.len()
1892 } 1998 }
1893 1999
1894 /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): 2000 /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
@@ -2183,6 +2289,7 @@ impl HostHeap {
2183 /// reads the table's dynamic slots). 2289 /// reads the table's dynamic slots).
2184 pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { 2290 pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
2185 if show_after() 2291 if show_after()
2292 && !crate::texture::BAKING.get()
2186 && index < self.count 2293 && index < self.count
2187 && !self.texture_slot_made_from(index, handle) 2294 && !self.texture_slot_made_from(index, handle)
2188 && let Some(view) = super::view(handle) 2295 && let Some(view) = super::view(handle)
@@ -2197,14 +2304,143 @@ impl HostHeap {
2197 } 2304 }
2198 2305
2199 fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) { 2306 fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) {
2307 use std::sync::atomic::Ordering::{Relaxed, Release};
2200 let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); 2308 let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
2309 let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed);
2310 let origin = (std::ptr::from_ref(list) as usize, list.epoch());
2311 {
2312 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
2313 pending.push(PendingListFlip {
2314 id,
2315 origin,
2316 flip: Flip { after: 0, heap, index, handle, key, late },
2317 });
2318 PENDING_LIST_COUNT.store(pending.len(), Release);
2319 }
2320 struct PendingGuard(u64);
2321 impl PendingGuard {
2322 fn id(&self) -> u64 {
2323 self.0
2324 }
2325 }
2326 impl Drop for PendingGuard {
2327 fn drop(&mut self) {
2328 remove_pending_list_flip(self.0);
2329 }
2330 }
2331 let guard = PendingGuard(id);
2201 list.defer_host(move || { 2332 list.defer_host(move || {
2202 let after = crate::host::submissions().0; 2333 // Call a `&self` method so Rust 2021+ moves the whole `guard`
2203 let flip = Flip { after, heap, index, handle, key, late }; 2334 // into this closure rather than copying `guard.0` and dropping
2335 // `guard` immediately at the end of `flip()`.
2336 let Some(mut flip) = take_pending_list_flip(guard.id()) else {
2337 return;
2338 };
2339 flip.after = crate::host::submissions().0;
2204 FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); 2340 FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
2205 }); 2341 });
2206 } 2342 }
2207 2343
2344 /// Whether any deferred slot flip or view remake for this heap requires
2345 /// settling in-flight GPU submissions before exposing real textures to a
2346 /// one-shot decoration bake draw.
2347 pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool {
2348 let own = std::ptr::from_ref(self) as usize;
2349 let finished = crate::host::submissions().1;
2350 if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 {
2351 let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
2352 if pending.iter().any(|p| p.flip.heap == own) {
2353 return true;
2354 }
2355 }
2356 {
2357 let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
2358 if flips.iter().any(|f| f.heap == own && f.after > finished) {
2359 return true;
2360 }
2361 }
2362 let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
2363 after.iter().any(|&(at, _)| at > finished)
2364 }
2365
2366 /// Drains deferred flips still sitting in unsubmitted command lists for
2367 /// this heap so a decoration bake can mirror them out of `neutral()`.
2368 /// Entries that cannot be promoted yet (unmapped memory or deferred
2369 /// staging) must be returned via [`HostHeap::restore_pending_list_flip`].
2370 pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> {
2371 if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
2372 return Vec::new();
2373 }
2374 let own = std::ptr::from_ref(self) as usize;
2375 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
2376 let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) =
2377 pending.drain(..).partition(|p| p.flip.heap == own);
2378 *pending = rest;
2379 PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
2380 mine
2381 }
2382
2383 /// Re-queues an unpromoted deferred flip drained by
2384 /// [`HostHeap::take_pending_list_flips`] so its originating command list
2385 /// still flips it out of `neutral()` once submitted.
2386 pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) {
2387 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
2388 pending.push(item);
2389 PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
2390 }
2391
2392 /// Whether title descriptor slot `handle` still holds record `key`.
2393 pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool {
2394 key != 0 && record_key(handle) == key
2395 }
2396
2397 /// Looks up `(view, key)` for slot `index` prior to a synchronous bake
2398 /// upload without replacing its current host descriptor with `neutral()`;
2399 /// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and
2400 /// updates `Spans`/stride tracking once the GPU copy finishes.
2401 pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> {
2402 if index >= self.count {
2403 return None;
2404 }
2405 let key = record_key(handle);
2406 let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?;
2407 Some((view, key))
2408 }
2409
2410 /// Exposes the real host descriptor for slot `index` after its synchronous
2411 /// bake upload has completed on the GPU, updating `Spans`/stride tracking
2412 /// without re-queuing the slot in `TextureQueue`.
2413 pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool {
2414 if index >= self.count || key == 0 {
2415 return false;
2416 }
2417 let (published, stale) = {
2418 let _made = self.made.lock(index);
2419 if self.made.get(index) == Some(key) {
2420 return false;
2421 }
2422 if record_key(handle) != key {
2423 return false;
2424 }
2425 let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
2426 return false;
2427 };
2428 let stale = self.note_buffer(index, Some(&view), true);
2429 if let Some(kept) = make(&view, self.at(index)) {
2430 self.put(index);
2431 self.quick_is(index, 0);
2432 self.clear_twin(index);
2433 self.made.set(index, key);
2434 self.keep(index, kept);
2435 (true, stale)
2436 } else {
2437 (false, stale)
2438 }
2439 };
2440 self.unmake_stale(index, stale);
2441 published
2442 }
2443
2208 /// Makes the slots whose new view's upload has run 2444 /// Makes the slots whose new view's upload has run
2209 /// ([`HostHeap::texture_slot_flip`]); returns how many. 2445 /// ([`HostHeap::texture_slot_flip`]); returns how many.
2210 pub(crate) fn texture_slots_flip(&self) -> usize { 2446 pub(crate) fn texture_slots_flip(&self) -> usize {
@@ -2222,6 +2458,7 @@ impl HostHeap {
2222 ready 2458 ready
2223 }; 2459 };
2224 let mut flipped = 0; 2460 let mut flipped = 0;
2461 let mut late_flipped = 0;
2225 for f in ready { 2462 for f in ready {
2226 let _made = self.made.lock(f.index); 2463 let _made = self.made.lock(f.index);
2227 let Some(shown) = self.made.get(f.index) else { 2464 let Some(shown) = self.made.get(f.index) else {
@@ -2264,6 +2501,7 @@ impl HostHeap {
2264 same_bytes(was, f.key); 2501 same_bytes(was, f.key);
2265 } 2502 }
2266 if let Some(since) = f.late { 2503 if let Some(since) = f.late {
2504 late_flipped += 1;
2267 let frames = crate::frame::current().saturating_sub(since); 2505 let frames = crate::frame::current().saturating_sub(since);
2268 let n = LATE[0].fetch_add(1, Relaxed) + 1; 2506 let n = LATE[0].fetch_add(1, Relaxed) + 1;
2269 let all = LATE[1].fetch_add(frames, Relaxed) + frames; 2507 let all = LATE[1].fetch_add(frames, Relaxed) + frames;
@@ -2282,7 +2520,7 @@ impl HostHeap {
2282 } 2520 }
2283 } 2521 }
2284 FLIPPED[0].fetch_add(flipped as u64, Relaxed); 2522 FLIPPED[0].fetch_add(flipped as u64, Relaxed);
2285 flipped 2523 flipped + late_flipped
2286 } 2524 }
2287 2525
2288 /// The memory of the texture title slot `index` views is there (again): 2526 /// The memory of the texture title slot `index` views is there (again):
@@ -2311,6 +2549,7 @@ impl HostHeap {
2311 } 2549 }
2312 self.put(index); 2550 self.put(index);
2313 self.clear_twin(index); 2551 self.clear_twin(index);
2552 self.write_stride(index, 0);
2314 self.keep(index, None); 2553 self.keep(index, None);
2315 } 2554 }
2316 2555
@@ -2506,15 +2745,8 @@ impl HostHeap {
2506 textures.remove(slot); 2745 textures.remove(slot);
2507 } 2746 }
2508 } 2747 }
2509 let stride = view.and_then(view_stride); 2748 let (stride, kind) = view.map_or((None, 0), view_stride_and_kind);
2510 let kind = view.map_or(0, view_kind); 2749 self.write_stride(index, stride.unwrap_or(0) | kind);
2511 if let Some((_, _, data)) = &self.strides
2512 && index < victory_shader::emit::SLOT_STRIDES_COUNT
2513 {
2514 // SAFETY: inside the mapping; shaders read it while we write (a
2515 // dword, either value is one the slot had).
2516 unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
2517 }
2518 let was = if stride.is_some() { 2750 let was = if stride.is_some() {
2519 self.buffers.put(index); 2751 self.buffers.put(index);
2520 true 2752 true
@@ -2527,6 +2759,20 @@ impl HostHeap {
2527 stale 2759 stale
2528 } 2760 }
2529 2761
2762 /// Writes `word` (stride | format kind) for view-heap slot `index` into
2763 /// the host's [`victory_shader::emit::SLOT_STRIDES`] table.
2764 #[inline]
2765 fn write_stride(&self, index: u32, word: u32) {
2766 if let Some((_, _, data)) = &self.strides
2767 && index < victory_shader::emit::SLOT_STRIDES_COUNT
2768 {
2769 // SAFETY: inside the mapping; shaders read it while we write (a
2770 // single aligned dword: either value is one the slot had, and
2771 // dynamic slots are exclusively owned until submission finishes).
2772 unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) };
2773 }
2774 }
2775
2530 /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] 2776 /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
2531 /// returned). 2777 /// returned).
2532 /// 2778 ///
@@ -2554,6 +2800,7 @@ impl HostHeap {
2554 } 2800 }
2555 self.put(index); 2801 self.put(index);
2556 self.twin_made(index, kept.is_some() && twinned(view)); 2802 self.twin_made(index, kept.is_some() && twinned(view));
2803 self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 });
2557 self.keep(index, kept.flatten()); 2804 self.keep(index, kept.flatten());
2558 } 2805 }
2559 2806
@@ -2586,13 +2833,14 @@ impl HostHeap {
2586 } 2833 }
2587 let twin = twinned(&view); 2834 let twin = twinned(&view);
2588 let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; 2835 let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
2836 let stride_word = view_stride_word(&view);
2589 let listed = Listed { 2837 let listed = Listed {
2590 kind: crate::draw::view_kind(&view), 2838 kind: crate::draw::view_kind(&view),
2591 texture: is_texture_view(&view), 2839 texture: is_texture_view(&view),
2592 ready: (0, 0, false), 2840 ready: (0, 0, false),
2593 tabled: None, 2841 tabled: None,
2594 }; 2842 };
2595 views.made.insert(words, ListView { view, at, twin, kept, listed }); 2843 views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
2596 } 2844 }
2597 let made = &views.made[&words]; 2845 let made = &views.made[&words];
2598 self.copy_from(index, views.slot(made.at)); 2846 self.copy_from(index, views.slot(made.at));
@@ -2602,6 +2850,7 @@ impl HostHeap {
2602 } else { 2850 } else {
2603 self.clear_twin(index); 2851 self.clear_twin(index);
2604 } 2852 }
2853 self.write_stride(index, made.stride_word);
2605 self.keep(index, made.kept.clone()); 2854 self.keep(index, made.kept.clone());
2606 Some(made.listed) 2855 Some(made.listed)
2607 }) 2856 })
@@ -2626,6 +2875,7 @@ impl HostHeap {
2626 } else { 2875 } else {
2627 null_view(self.at(index)); 2876 null_view(self.at(index));
2628 self.put(index); 2877 self.put(index);
2878 self.write_stride(index, 0);
2629 } 2879 }
2630 self.clear_twin(index); 2880 self.clear_twin(index);
2631 self.keep(index, None); 2881 self.keep(index, None);
@@ -2712,6 +2962,7 @@ impl HostHeap {
2712 self.put(index); 2962 self.put(index);
2713 // (Bound by its handle, not read by index.) 2963 // (Bound by its handle, not read by index.)
2714 self.clear_twin(index); 2964 self.clear_twin(index);
2965 self.write_stride(index, 1);
2715 self.keep(index, Some(buffer.clone())); 2966 self.keep(index, Some(buffer.clone()));
2716 } 2967 }
2717 2968
@@ -2721,6 +2972,7 @@ impl HostHeap {
2721 null_buffer_view(self.at(index)); 2972 null_buffer_view(self.at(index));
2722 self.put(index); 2973 self.put(index);
2723 self.clear_twin(index); 2974 self.clear_twin(index);
2975 self.write_stride(index, 0);
2724 self.keep(index, None); 2976 self.keep(index, None);
2725 } 2977 }
2726 2978
@@ -2755,6 +3007,7 @@ impl HostHeap {
2755 }; 3007 };
2756 self.put(index); 3008 self.put(index);
2757 self.clear_twin(index); 3009 self.clear_twin(index);
3010 self.write_stride(index, 1);
2758 self.keep(index, Some(buffer.clone())); 3011 self.keep(index, Some(buffer.clone()));
2759 } 3012 }
2760 3013
@@ -2784,6 +3037,7 @@ impl HostHeap {
2784 }; 3037 };
2785 self.put(index); 3038 self.put(index);
2786 self.clear_twin(index); 3039 self.clear_twin(index);
3040 self.write_stride(index, 0);
2787 self.keep(index, None); 3041 self.keep(index, None);
2788 } 3042 }
2789 3043
@@ -2841,6 +3095,7 @@ impl HostHeap {
2841 unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; 3095 unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
2842 } 3096 }
2843 self.twin_made(index, twin.is_some()); 3097 self.twin_made(index, twin.is_some());
3098 self.write_stride(index, 0);
2844 // After the descriptor: what it showed is let go when nothing shows 3099 // After the descriptor: what it showed is let go when nothing shows
2845 // it any more. 3100 // it any more.
2846 self.keep(index, holds.then(|| buffer.clone())); 3101 self.keep(index, holds.then(|| buffer.clone()));
@@ -4084,24 +4339,27 @@ fn make_twinned(
4084 } 4339 }
4085 const BUFFER: u32 = 1; 4340 const BUFFER: u32 = 1;
4086 if resource[0] != BUFFER { 4341 if resource[0] != BUFFER {
4087 // shortcut: unordered access to a texture the title placed
4088 // itself is not mirrored; give it a resource as shader
4089 // views of such textures get when a dispatch writes one.
4090 // Each texture is said once (the first 64), with how many times
4091 // such a view was asked for so far: what shaders write through
4092 // them is lost.
4093 static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
4094 static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4095 let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
4096 let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; 4342 let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
4097 let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); 4343 if *unordered || at != 0 {
4098 if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { 4344 // shortcut: unordered access to a texture the title placed
4099 tracing::warn!( 4345 // itself is not mirrored; give it a resource as shader
4100 address = format_args!("{at:#x}"), 4346 // views of such textures get when a dispatch writes one.
4101 times, 4347 // Each texture is said once (the first 64), with how many times
4102 "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}", 4348 // such a view was asked for so far: what shaders write through
4103 &desc[..10] 4349 // them is lost.
4104 ); 4350 static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
4351 static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4352 let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
4353 let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
4354 if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
4355 tracing::warn!(
4356 address = format_args!("{at:#x}"),
4357 unordered = *unordered,
4358 times,
4359 "placed texture view not mirrored (null): resource {resource:?}, view {:?}",
4360 &desc[..10]
4361 );
4362 }
4105 } 4363 }
4106 return None; 4364 return None;
4107 } 4365 }
@@ -5446,6 +5704,71 @@ mod tests {
5446 heap.release(last, 1); 5704 heap.release(last, 1);
5447 assert_eq!(heap.dynamic(2), None); 5705 assert_eq!(heap.dynamic(2), None);
5448 } 5706 }
5707
5708 #[test]
5709 fn dynamic_slots_populate_and_clear_stride_table() {
5710 use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
5711 let Some(heap) = HostHeap::new(false, 4) else {
5712 return; // no host GPU
5713 };
5714 let Some((_, _, data)) = heap.strides else {
5715 panic!("view heap should allocate strides table");
5716 };
5717 let read_stride = |slot: u32| -> u32 {
5718 // SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`.
5719 unsafe { *(data as *const u32).add(slot as usize) }
5720 };
5721 let memory = vec![0u64; 1 << 11];
5722 let addr = (memory.as_ptr() as u64).next_multiple_of(4096);
5723 let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| {
5724 let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
5725 let mut desc = [0u32; 16];
5726 // [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8]
5727 let words = if uav {
5728 [dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0]
5729 } else {
5730 [dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0]
5731 };
5732 desc[..10].copy_from_slice(&words);
5733 (desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32);
5734 View::Placed(uav, resource, desc)
5735 };
5736
5737 let s0 = heap.dynamic(4).unwrap();
5738 // R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER
5739 let u16x4 = placed_typed(true, 12, 64);
5740 heap.make_at(s0, &u16x4);
5741 assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
5742
5743 // R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED
5744 let s16 = placed_typed(false, 59, 64);
5745 heap.make_at(s0 + 1, &s16);
5746 assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED);
5747
5748 // R16G16B16A16_FLOAT (10): 8 bytes, no integer bits
5749 let f16x4 = placed_typed(true, 10, 64);
5750 heap.make_at(s0 + 2, &f16x4);
5751 assert_eq!(read_stride(s0 + 2), 8);
5752
5753 // Clearing / nulling / raw views overwrite stale bits cleanly.
5754 heap.make_null(s0);
5755 assert_eq!(read_stride(s0), 0);
5756 heap.null_raw_at(s0 + 1);
5757 assert_eq!(read_stride(s0 + 1), 0);
5758 heap.null_raw_uav_at(s0 + 2);
5759 assert_eq!(read_stride(s0 + 2), 0);
5760
5761 // `make_listed` (both cold creation and cached copy hit) must populate strides.
5762 let mut slot_mem = [0u32; 8];
5763 crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4);
5764 let rec = [slot_mem[0], slot_mem[1], slot_mem[2]];
5765 assert!(heap.make_listed(0x1234, rec, s0).is_some());
5766 assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
5767 heap.make_null(s0 + 3);
5768 assert_eq!(read_stride(s0 + 3), 0);
5769 assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some());
5770 assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER);
5771 }
5449} 5772}
5450 5773
5451/// What is known of a record a list's tables hold, in that recording of the 5774/// What is known of a record a list's tables hold, in that recording of the
@@ -5466,6 +5789,7 @@ struct ListView {
5466 /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. 5789 /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next.
5467 at: u32, 5790 at: u32,
5468 twin: bool, 5791 twin: bool,
5792 stride_word: u32,
5469 kept: Kept, 5793 kept: Kept,
5470 listed: Listed, 5794 listed: Listed,
5471} 5795}
@@ -5544,3 +5868,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
5544pub(crate) fn list_views() -> bool { 5868pub(crate) fn list_views() -> bool {
5545 crate::toggled!("VICTORY_LIST_VIEWS") 5869 crate::toggled!("VICTORY_LIST_VIEWS")
5546} 5870}
5871
5872#[cfg(test)]
5873mod bake_flip_tests {
5874 use super::*;
5875
5876 #[test]
5877 fn pending_list_flips_promote_once_and_clean_up() {
5878 let heap = 0xdead_beefusize;
5879 let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5880 let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5881 {
5882 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
5883 pending.push(PendingListFlip {
5884 id: id1,
5885 origin: (1, 1),
5886 flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) },
5887 });
5888 pending.push(PendingListFlip {
5889 id: id2,
5890 origin: (2, 1),
5891 flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) },
5892 });
5893 PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
5894 }
5895 let taken = take_pending_list_flip(id1).expect("id1 should be present");
5896 assert_eq!(taken.index, 7);
5897 assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op");
5898 remove_pending_list_flip(id2);
5899 assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone");
5900 }
5901
5902 #[test]
5903 fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() {
5904 let heap = 0xcafe_babeusize;
5905 let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5906 let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5907 {
5908 let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
5909 for (id, idx) in [(id1, 10), (id2, 11)] {
5910 pending.push(PendingListFlip {
5911 id,
5912 origin: (3, 1),
5913 flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) },
5914 });
5915 }
5916 PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
5917 }
5918 struct TestGuard(u64);
5919 impl TestGuard {
5920 fn id(&self) -> u64 {
5921 self.0
5922 }
5923 }
5924 impl Drop for TestGuard {
5925 fn drop(&mut self) {
5926 remove_pending_list_flip(self.0);
5927 }
5928 }
5929 let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> {
5930 let guard = TestGuard(id);
5931 Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index))
5932 };
5933 let cb1 = make_cb(id1);
5934 let cb2 = make_cb(id2);
5935 // Must still be present after make_cb returns (guard moved, not dropped).
5936 assert_eq!(cb1(), Some(10));
5937 assert_eq!(cb1(), None);
5938 drop(cb2);
5939 assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry");
5940 }
5941}
diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs
index 38b8fe7..e05304c 100644
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -217,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2];
217/// until something is new, the next bakes of the frame need no pass. 217/// until something is new, the next bakes of the frame need no pass.
218static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); 218static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
219 219
220/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected
221/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM
222/// resources are free-threaded when externally synchronized.
223struct BakeList(HostList);
224// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex.
225unsafe impl Send for BakeList {}
226
227/// Serializes synchronous one-shot ped/decoration bake uploads across
228/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable
229/// upload-only host command list.
230static BAKE_UPLOAD: std::sync::Mutex<Option<BakeList>> = std::sync::Mutex::new(None);
231
232/// Pending descriptor publications for a synchronous bake upload pass: slots
233/// stay on `neutral()` (or their previous compatible view) until the dedicated
234/// upload list has finished executing on the host GPU.
235struct BakeSync {
236 publish: Vec<(u32, u64, u64)>,
237 keep: Vec<std::sync::Arc<crate::resource::HostTexture>>,
238}
239
220/// The pixel shaders of the title's decoration bake (the title: 240/// The pixel shaders of the title's decoration bake (the title:
221/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the 241/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
222/// frame listings print it. They draw into a 256x256 corner of 2048x2048 242/// frame listings print it. They draw into a 256x256 corner of 2048x2048
223/// targets and name no texture in a table. 243/// targets and name no texture in a table.
224pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] = 244pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [
225 ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; 245 "c0a7fe77b1862e10",
246 "0d1575a396dfe513",
247 "b7cfd8dda91ebb6b",
248 "280967ad158cee0b",
249 "fa455c8a3c32577b",
250 "d126bcae5d5d8d26",
251 "fcee612943c008e0",
252];
253
254/// Geometry stages shared by every ped texture compositor / decoration bake
255/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and
256/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader
257/// permutations beyond `BAKE_PIXEL_SHADERS`.
258const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"];
226 259
227/// Since the start: early runs of the texture pass, and those of them 260/// Since the start: early runs of the texture pass, and those of them
228/// made for a bake draw. 261/// made for a bake draw.
@@ -1714,6 +1747,24 @@ impl State {
1714 } 1747 }
1715 continue; 1748 continue;
1716 } 1749 }
1750 if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES {
1751 // Ours: the shader inspects typed view kinds for its
1752 // descriptor tables only (already mirrored by `tables`),
1753 // so bind the strides buffer without sweeping the heap.
1754 match self.heap_strides(list) {
1755 // SAFETY: an open list; the table lives as long
1756 // as the heap the list holds.
1757 Some(gpu) => unsafe {
1758 if compute {
1759 l.SetComputeRootShaderResourceView(param, gpu);
1760 } else {
1761 l.SetGraphicsRootShaderResourceView(param, gpu);
1762 }
1763 },
1764 None => once!("a shader inspects table view kinds without a view heap set"),
1765 }
1766 continue;
1767 }
1717 let tabled = srv && crate::pipeline::host::bounded_root_srvs(); 1768 let tabled = srv && crate::pipeline::host::bounded_root_srvs();
1718 let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) 1769 let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
1719 else { 1770 else {
@@ -1872,7 +1923,10 @@ impl State {
1872 Some((index, shadow)) => (*index, address.zip(shadow.clone())), 1923 Some((index, shadow)) => (*index, address.zip(shadow.clone())),
1873 None => { 1924 None => {
1874 let shadow = address.and_then(|a| find(a).map(|s| (a, s))); 1925 let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
1875 let Some(index) = host.dynamic(1) else { 1926 let Some(index) = host.dynamic(1).or_else(|| {
1927 crate::host::settle_for_fence();
1928 host.dynamic(1)
1929 }) else {
1876 return false; 1930 return false;
1877 }; 1931 };
1878 self.dynamic.push((key.0, index, 1)); 1932 self.dynamic.push((key.0, index, 1));
@@ -1943,7 +1997,10 @@ impl State {
1943 Some((index, shadow)) => (*index, address.zip(shadow.clone())), 1997 Some((index, shadow)) => (*index, address.zip(shadow.clone())),
1944 None => { 1998 None => {
1945 let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); 1999 let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
1946 let Some(index) = host.dynamic(1) else { 2000 let Some(index) = host.dynamic(1).or_else(|| {
2001 crate::host::settle_for_fence();
2002 host.dynamic(1)
2003 }) else {
1947 return false; 2004 return false;
1948 }; 2005 };
1949 self.dynamic.push((key.0, index, 1)); 2006 self.dynamic.push((key.0, index, 1));
@@ -2053,7 +2110,7 @@ impl State {
2053 #[cfg(feature = "diagnostics")] 2110 #[cfg(feature = "diagnostics")]
2054 let refreshed = std::time::Instant::now(); 2111 let refreshed = std::time::Instant::now();
2055 stage.next("the heap pass: textures"); 2112 stage.next("the heap pass: textures");
2056 self.heap_textures(list, heap, host); 2113 let _ = self.heap_textures(list, heap, host, None);
2057 stage.end(); 2114 stage.end();
2058 #[cfg(feature = "diagnostics")] 2115 #[cfg(feature = "diagnostics")]
2059 HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); 2116 HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
@@ -2062,20 +2119,179 @@ impl State {
2062 Some(gpu) 2119 Some(gpu)
2063 } 2120 }
2064 2121
2122 /// The GPU address of the bound view heap's stride/kind table without
2123 /// running the bindless heap buffer/texture sweep (for shaders that only
2124 /// inspect descriptors already mirrored via their descriptor tables).
2125 fn heap_strides(&self, list: &HostList) -> Option<u64> {
2126 let heap = self
2127 .heaps
2128 .iter()
2129 .filter(|&&h| h != 0)
2130 .map(|&h| crate::descriptor::heap(h as This))
2131 .find(|h| !h.samplers())?;
2132 let host = heap.host()?;
2133 let gpu = host.strides_gpu()?;
2134 // Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers).
2135 if list.first_use(gpu as usize | 2)
2136 && let Some(buffer) = host.strides_buffer()
2137 {
2138 list.keep(buffer);
2139 }
2140 Some(gpu)
2141 }
2142
2143 /// Ensures textures claimed by background copy-queue uploads
2144 /// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray
2145 /// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished
2146 /// uploading and flipped to their real descriptors before a one-shot
2147 /// decoration bake draw samples them.
2148 fn flush_for_bake(
2149 &self,
2150 list: &HostList,
2151 host: &crate::descriptor::host::HostHeap,
2152 mut sync: Option<&mut BakeSync>,
2153 ) {
2154 static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
2155 let drained = crate::texture::ahead::drain();
2156 let mut settled = false;
2157 let mut flipped = 0usize;
2158 for _ in 0..4 {
2159 let need_settle = host.needs_gpu_settle_for_bake();
2160 if need_settle {
2161 settled = true;
2162 crate::host::settle_for_fence();
2163 }
2164 flipped += host.texture_views_remade();
2165 flipped += host.texture_slots_flip();
2166 if !need_settle || !host.needs_gpu_settle_for_bake() {
2167 break;
2168 }
2169 }
2170 let pending = host.take_pending_list_flips();
2171 let mut promoted = 0usize;
2172 if !pending.is_empty() {
2173 let this_list = (std::ptr::from_ref(list) as usize, list.epoch());
2174 let sampled = UsedResource {
2175 kind: ResourceType::Srv,
2176 root: RootType::Table,
2177 table_offset_dwords: 0,
2178 lower_bound: 0,
2179 stride: 0,
2180 dwords: 8,
2181 user_data: 0,
2182 slot: 0,
2183 };
2184 for item in pending {
2185 let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key());
2186 if !host.slot_still_at(handle, key) {
2187 continue;
2188 }
2189 let Some(view) = crate::descriptor::view(handle) else {
2190 continue;
2191 };
2192 if let View::Placed(_, resource, desc) = &view {
2193 let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
2194 let len = crate::resource::placed_bytes(resource).unwrap_or(1);
2195 if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 {
2196 host.restore_pending_list_flip(item);
2197 continue;
2198 }
2199 }
2200 if sync.is_some() || origin != this_list {
2201 let placed = crate::descriptor::host::placed_texture(&view);
2202 if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) {
2203 let resource = resource as This;
2204 let texture = crate::resource::host_resource(resource);
2205 let title_fills = texture.is_some_and(crate::texture::title_written);
2206 let first = match (&placed, &view) {
2207 (Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc),
2208 _ => 0,
2209 };
2210 if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) {
2211 sync.keep.push(copy);
2212 }
2213 if title_fills
2214 && !crate::texture::ahead::there(resource)
2215 && (sync.is_some() || !crate::texture::unchanged(resource, first))
2216 {
2217 let was_staged = crate::texture::is_staged(resource);
2218 let _ = crate::residency::take_staging_deferred();
2219 readable(list, sampled.kind, &view);
2220 let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused();
2221 if !was_staged {
2222 crate::texture::unstage(resource);
2223 }
2224 if failed {
2225 host.restore_pending_list_flip(item);
2226 continue;
2227 }
2228 }
2229 }
2230 }
2231 if let Some(sync) = sync.as_deref_mut() {
2232 sync.publish.push((index, handle, key));
2233 } else {
2234 let _ = host.mirror(index, handle, true);
2235 }
2236 promoted += 1;
2237 }
2238 }
2239 if drained > 0 || settled || flipped > 0 || promoted > 0 {
2240 let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1;
2241 let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64;
2242 let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64;
2243 let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64;
2244 if n.is_power_of_two() {
2245 tracing::info!(
2246 frame = crate::frame::current(),
2247 flushes = n,
2248 drained_ahead = all_drained,
2249 flipped = all_flipped,
2250 promoted_from_lists = all_promoted,
2251 settled,
2252 "flushed deferred texture stand-ins before decoration bake"
2253 );
2254 }
2255 }
2256 }
2257
2258 /// Whether a graphics draw is a one-shot texture compositor / decoration
2259 /// bake whose bindless texture inputs must be flushed and up to date
2260 /// before recording the draw. Matches known bake pixel/geometry shaders
2261 /// and structurally detects depth-less 4+ MRT square atlas bakes
2262 /// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never
2263 /// bake `neutral()` or `null` stand-ins into permanent ped textures.
2264 fn is_bake_draw(&self, p: &HostPipeline) -> bool {
2265 if p.stages.iter().any(|s| {
2266 let h = s.shader.hash.as_str();
2267 BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h)
2268 }) {
2269 return true;
2270 }
2271 self.depth == 0
2272 && self.targets.len() >= 4
2273 && self
2274 .targets
2275 .first()
2276 .and_then(|&t| crate::resource::texture_kind(t as This))
2277 .is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h))
2278 }
2279
2065 /// Runs the pass that uploads textures picked by index 2280 /// Runs the pass that uploads textures picked by index
2066 /// ([`State::heap_textures`]) where nothing has asked for it yet 2281 /// ([`State::heap_textures`]) where nothing has asked for it yet
2067 /// ([`early_budgets`]): once a frame for a few milliseconds, at the 2282 /// ([`early_budgets`]): once a frame for a few milliseconds, at the
2068 /// frame's first draw with a view heap set, and with a larger budget 2283 /// frame's first draw with a view heap set, and with a larger budget
2069 /// of its own before every draw whose pixel shader is one of the 2284 /// of its own before every draw whose pixel shader is one of the
2070 /// title's bake programs. The uploads are recorded into `list` ahead 2285 /// title's bake programs. For decoration bakes, uploads run synchronously
2071 /// of the draw being bound, as the world's pass records them. 2286 /// on a dedicated internal command list and descriptors are published only
2287 /// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can
2288 /// never submit a bake draw ahead of its texture uploads.
2072 fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { 2289 fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
2073 let (early_ms, bake_ms) = early_budgets(); 2290 let (early_ms, bake_ms) = early_budgets();
2074 if compute || (early_ms == 0 && bake_ms == 0) { 2291 if compute || (early_ms == 0 && bake_ms == 0) {
2075 return; 2292 return;
2076 } 2293 }
2077 let bake = bake_ms > 0 2294 let is_bake = bake_ms > 0 && self.is_bake_draw(p);
2078 && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
2079 static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); 2295 static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
2080 // The milliseconds this frame's bake draws have taken so far: a 2296 // The milliseconds this frame's bake draws have taken so far: a
2081 // frame has several, and together they get `bake_ms`. 2297 // frame has several, and together they get `bake_ms`.
@@ -2085,15 +2301,9 @@ impl State {
2085 if first { 2301 if first {
2086 BAKED_MS.store(0, Ordering::Relaxed); 2302 BAKED_MS.store(0, Ordering::Relaxed);
2087 } 2303 }
2088 let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); 2304 if !is_bake && !(first && early_ms > 0) {
2089 let budget = if bake && left > 0 {
2090 // What a bake may read must be there now: up to 2 GiB.
2091 (left, 2 << 30)
2092 } else if first && early_ms > 0 {
2093 (early_ms, 64 << 20)
2094 } else {
2095 return; 2305 return;
2096 }; 2306 }
2097 let Some(heap) = self 2307 let Some(heap) = self
2098 .heaps 2308 .heaps
2099 .iter() 2309 .iter()
@@ -2106,34 +2316,102 @@ impl State {
2106 let Some(host) = heap.host() else { 2316 let Some(host) = heap.host() else {
2107 return; 2317 return;
2108 }; 2318 };
2109 let bake = bake && left > 0; 2319 if is_bake {
2110 if bake && !first && bake_exact() { 2320 let began = std::time::Instant::now();
2111 let (writes, noted) = host.texture_news(); 2321 let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner());
2112 if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { 2322 let gpu = crate::host::host();
2323 if bake_slot.is_none()
2324 && let Some(gpu) = gpu
2325 {
2326 match gpu.new_list() {
2327 Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)),
2328 Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"),
2329 }
2330 }
2331 let exact = bake_exact();
2332 if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) {
2333 let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() };
2334 crate::texture::BAKING.set(exact);
2335 self.flush_for_bake(bake_list, host, Some(&mut sync));
2336 let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
2337 let run_pass = left > 0
2338 && (first
2339 || !exact
2340 || {
2341 let (writes, noted) = host.texture_news();
2342 noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1
2343 });
2344 let mut served = false;
2345 if run_pass {
2346 let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1;
2347 if n.is_power_of_two() {
2348 let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
2349 tracing::info!(
2350 frame,
2351 bakes = n,
2352 queued_at_the_last_pass = slots,
2353 due_at_the_last_pass = due,
2354 uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
2355 "a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)"
2356 );
2357 }
2358 BAKE_SERVED.store(0, Ordering::Relaxed);
2359 PASS_BUDGET.set(Some((left, 2 << 30, true)));
2360 served = self.heap_textures(bake_list, heap, host, Some(&mut sync));
2361 PASS_BUDGET.set(None);
2362 }
2363 crate::texture::BAKING.set(false);
2364 if bake_list.has_recorded_work() {
2365 bake_list.close();
2366 gpu.execute_sync_internal(bake_list);
2367 bake_list.reset();
2368 } else if !sync.publish.is_empty() {
2369 crate::host::settle_for_fence();
2370 }
2371 for (index, handle, key) in sync.publish {
2372 let _ = host.publish_uploaded_slot(index, handle, key);
2373 }
2374 host.texture_views_remade();
2375 host.texture_slots_flip();
2376 drop(sync.keep);
2377 if run_pass && served && exact {
2378 BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
2379 }
2380 BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
2113 return; 2381 return;
2114 } 2382 }
2115 } 2383 // Fallback when no host GPU list can be created (e.g. headless tests).
2116 let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; 2384 crate::texture::BAKING.set(exact);
2117 if bake && n.is_power_of_two() { 2385 self.flush_for_bake(list, host, None);
2118 let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); 2386 crate::texture::BAKING.set(false);
2119 tracing::info!( 2387 let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
2120 frame, 2388 if left == 0 {
2121 bakes = n, 2389 return;
2122 queued_at_the_last_pass = slots, 2390 }
2123 due_at_the_last_pass = due, 2391 if !first && exact {
2124 uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), 2392 let (writes, noted) = host.texture_news();
2125 "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" 2393 if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
2126 ); 2394 return;
2127 } 2395 }
2128 let began = std::time::Instant::now(); 2396 }
2129 PASS_BUDGET.set(Some((budget.0, budget.1, bake))); 2397 EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed);
2130 crate::texture::BAKING.set(bake && bake_exact()); 2398 PASS_BUDGET.set(Some((left, 2 << 30, true)));
2131 self.heap_textures(list, heap, host); 2399 crate::texture::BAKING.set(exact);
2132 crate::texture::BAKING.set(false); 2400 let _ = self.heap_textures(list, heap, host, None);
2133 PASS_BUDGET.set(None); 2401 crate::texture::BAKING.set(false);
2134 if bake { 2402 PASS_BUDGET.set(None);
2135 BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); 2403 BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
2404 return;
2136 } 2405 }
2406 let budget = if first && early_ms > 0 {
2407 (early_ms, 64 << 20)
2408 } else {
2409 return;
2410 };
2411 EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed);
2412 PASS_BUDGET.set(Some((budget.0, budget.1, false)));
2413 let _ = self.heap_textures(list, heap, host, None);
2414 PASS_BUDGET.set(None);
2137 } 2415 }
2138 2416
2139 /// The queue's side of the card accounting line 2417 /// The queue's side of the card accounting line
@@ -2230,10 +2508,11 @@ impl State {
2230 list: &HostList, 2508 list: &HostList,
2231 heap: &crate::descriptor::Heap, 2509 heap: &crate::descriptor::Heap,
2232 host: &crate::descriptor::host::HostHeap, 2510 host: &crate::descriptor::host::HostHeap,
2233 ) { 2511 mut sync: Option<&mut BakeSync>,
2512 ) -> bool {
2234 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); 2513 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2235 if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { 2514 if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
2236 return; 2515 return true;
2237 } 2516 }
2238 let memory = crate::host::host().and_then(|h| h.video_memory()); 2517 let memory = crate::host::host().and_then(|h| h.video_memory());
2239 // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of 2518 // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
@@ -2285,6 +2564,10 @@ impl State {
2285 // Slots whose texture's memory the runtime mapped, unmapped or 2564 // Slots whose texture's memory the runtime mapped, unmapped or
2286 // wrote since the last pass are due again. 2565 // wrote since the last pass are due again.
2287 host.texture_slots_remapped(frame); 2566 host.texture_slots_remapped(frame);
2567 let baking = crate::texture::BAKING.get();
2568 if baking {
2569 host.texture_slots_bake_written(frame);
2570 }
2288 host.texture_slots_short(frame); 2571 host.texture_slots_short(frame);
2289 // The slots of textures whose first level with memory (levels on 2572 // The slots of textures whose first level with memory (levels on
2290 // demand), or whose host copy for one with more levels, changed since 2573 // demand), or whose host copy for one with more levels, changed since
@@ -2298,11 +2581,6 @@ impl State {
2298 host.texture_slots_waiting(frame); 2581 host.texture_slots_waiting(frame);
2299 } 2582 }
2300 let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); 2583 let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
2301 if !crate::residency::admit_texture_pass(required) {
2302 BAKE_SERVED.store(0, Ordering::Relaxed);
2303 return;
2304 }
2305 let baking = crate::texture::BAKING.get();
2306 let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); 2584 let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
2307 // (Those that are due later after all that are due.) 2585 // (Those that are due later after all that are due.)
2308 let on_time = due.len(); 2586 let on_time = due.len();
@@ -2370,17 +2648,22 @@ impl State {
2370 let bytes_at_most = if required || asked.is_some() { 2648 let bytes_at_most = if required || asked.is_some() {
2371 bytes_at_most 2649 bytes_at_most
2372 } else { 2650 } else {
2373 crate::residency::prefetch_limit(bytes_at_most, crate::residency::pressured(), 2651 crate::residency::prefetch_limit(
2374 crate::residency::limited_host_ram(), crate::texture::live_staging_bytes()) 2652 bytes_at_most,
2653 crate::residency::pressured(),
2654 crate::residency::critical_commit(),
2655 crate::residency::limited_host_ram(),
2656 crate::texture::live_staging_bytes(),
2657 )
2375 }; 2658 };
2376 2659
2377 let began = std::time::Instant::now(); 2660 let began = std::time::Instant::now();
2378 BAKE_SERVED.store(0, Ordering::Relaxed); 2661 if sync.is_none() {
2662 BAKE_SERVED.store(0, Ordering::Relaxed);
2663 }
2379 let mut served = true; 2664 let mut served = true;
2380 for (index, write) in due { 2665 for (index, write) in due {
2381 if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span 2666 if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
2382 || !crate::residency::admit_texture_pass(required)
2383 {
2384 served = false; 2667 served = false;
2385 break; 2668 break;
2386 } 2669 }
@@ -2524,23 +2807,41 @@ impl State {
2524 ); 2807 );
2525 } 2808 }
2526 } 2809 }
2810 // Gate new host texture creation / staging on commit reserve after
2811 // `mapped == 0` reclamation (`texture_slot_gone`) has run, and
2812 // before mirroring a slot to an unuploaded texture.
2813 if !crate::residency::admit_texture_pass(required) {
2814 served = false;
2815 break;
2816 }
2527 // A slot that shows the texture by an earlier view of it (one 2817 // A slot that shows the texture by an earlier view of it (one
2528 // from another level) goes on doing so until the upload of what 2818 // from another level) goes on doing so until the upload of what
2529 // the new one shows has run. 2819 // the new one shows has run.
2820 let sync_bake = sync.is_some();
2530 let shows_other = !baking 2821 let shows_other = !baking
2822 && !sync_bake
2531 && crate::resource::held_only() 2823 && crate::resource::held_only()
2532 && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); 2824 && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
2533 // A slot that shows nothing of it yet, or something else, shows it 2825 // A slot that shows nothing of it yet, or something else, shows it
2534 // when the upload has run too. 2826 // when the upload has run too.
2535 let late = !shows_other 2827 let late = !shows_other
2536 && !baking 2828 && !baking
2829 && !sync_bake
2537 && crate::descriptor::host::show_after() 2830 && crate::descriptor::host::show_after()
2538 && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); 2831 && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle));
2539 let view = heap.handle(index).and_then(|handle| { 2832 let (view, bake_key) = if sync_bake {
2540 if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } 2833 match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) {
2541 }); 2834 Some((view, key)) => (Some(view), Some(key)),
2835 None => (None, None),
2836 }
2837 } else {
2838 let view = heap.handle(index).and_then(|handle| {
2839 if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
2840 });
2841 (view, None)
2842 };
2542 let at_once = || { 2843 let at_once = || {
2543 if late && let Some(handle) = heap.handle(index) { 2844 if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) {
2544 let _ = host.mirror(index, handle, true); 2845 let _ = host.mirror(index, handle, true);
2545 } 2846 }
2546 }; 2847 };
@@ -2581,16 +2882,23 @@ impl State {
2581 let same = !tabled && crate::texture::unchanged(resource, first); 2882 let same = !tabled && crate::texture::unchanged(resource, first);
2582 if same { 2883 if same {
2583 HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); 2884 HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
2584 if shows_other && let Some(handle) = heap.handle(index) { 2885 if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
2585 let _ = host.mirror(index, handle, true); 2886 if let Some(copy) = crate::resource::host_copy(resource) {
2586 } 2887 sync.keep.push(copy);
2587 // Its bytes are in, or on the way there in a list before.
2588 if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
2589 if let Some(handle) = heap.handle(index) {
2590 host.texture_slot_show_after(list, index, handle);
2591 } 2888 }
2889 sync.publish.push((index, handle, key));
2592 } else { 2890 } else {
2593 at_once(); 2891 if shows_other && let Some(handle) = heap.handle(index) {
2892 let _ = host.mirror(index, handle, true);
2893 }
2894 // Its bytes are in, or on the way there in a list before.
2895 if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
2896 if let Some(handle) = heap.handle(index) {
2897 host.texture_slot_show_after(list, index, handle);
2898 }
2899 } else {
2900 at_once();
2901 }
2594 } 2902 }
2595 let again = partly.map(|mapped| (frame + 1, mapped)); 2903 let again = partly.map(|mapped| (frame + 1, mapped));
2596 let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; 2904 let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
@@ -2625,6 +2933,7 @@ impl State {
2625 break; 2933 break;
2626 } 2934 }
2627 let late = late && ahead.is_none(); 2935 let late = late && ahead.is_none();
2936 let _ = crate::residency::take_staging_deferred();
2628 if let Some(view) = &view 2937 if let Some(view) = &view
2629 && ahead.is_none() 2938 && ahead.is_none()
2630 { 2939 {
@@ -2634,12 +2943,21 @@ impl State {
2634 readable(list, sampled.kind, view); 2943 readable(list, sampled.kind, view);
2635 crate::texture::PICKING.set(None); 2944 crate::texture::PICKING.set(None);
2636 } 2945 }
2637 // A failed allocation leaves this slot due. Publishing it or 2946 // A failed or deferred staging allocation leaves this slot due.
2638 // marking it served would lose the only retry for some materials. 2947 // Publishing it or marking it served would lose the only retry for
2639 if ahead.is_none() && crate::residency::upload_refused() { 2948 // some materials.
2949 if ahead.is_none()
2950 && (crate::residency::take_staging_deferred() || crate::residency::upload_refused())
2951 {
2640 served = false; 2952 served = false;
2641 break; 2953 break;
2642 } 2954 }
2955 if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
2956 if let Some(copy) = crate::resource::host_copy(resource) {
2957 sync.keep.push(copy);
2958 }
2959 sync.publish.push((index, handle, key));
2960 }
2643 if shows_other && let Some(handle) = heap.handle(index) { 2961 if shows_other && let Some(handle) = heap.handle(index) {
2644 host.texture_slot_flip(list, index, handle); 2962 host.texture_slot_flip(list, index, handle);
2645 } 2963 }
@@ -2672,7 +2990,7 @@ impl State {
2672 let text: String = format!("{view:?}").chars().take(300).collect(); 2990 let text: String = format!("{view:?}").chars().take(300).collect();
2673 tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); 2991 tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
2674 crate::host::log_removal_context(); 2992 crate::host::log_removal_context();
2675 return; 2993 return false;
2676 } 2994 }
2677 let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); 2995 let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
2678 // Not all of it there: looked at again next frame, and from 2996 // Not all of it there: looked at again next frame, and from
@@ -2723,9 +3041,10 @@ impl State {
2723 None => host.texture_slot_done(index, write, again), 3041 None => host.texture_slot_done(index, write, again),
2724 } 3042 }
2725 } 3043 }
2726 if baking && served { 3044 if sync.is_none() && baking && served {
2727 BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); 3045 BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
2728 } 3046 }
3047 served
2729 } 3048 }
2730 3049
2731 /// For the frame listing, after a dropped dispatch's line: its group 3050 /// For the frame listing, after a dropped dispatch's line: its group
@@ -3440,7 +3759,10 @@ impl State {
3440 made.push((slot, first * 32)); 3759 made.push((slot, first * 32));
3441 continue; 3760 continue;
3442 } 3761 }
3443 let Some(first) = host.dynamic(n) else { 3762 let Some(first) = host.dynamic(n).or_else(|| {
3763 crate::host::settle_for_fence();
3764 host.dynamic(n)
3765 }) else {
3444 // No room: the draw must not run with the title's own 3766 // No room: the draw must not run with the title's own
3445 // offsets (slots never made for it); `bind` drops it. 3767 // offsets (slots never made for it); `bind` drops it.
3446 made.push((slot, u32::MAX)); 3768 made.push((slot, u32::MAX));
@@ -3488,11 +3810,12 @@ impl State {
3488 TESTED_DEPTH.set((tested.0, true)); 3810 TESTED_DEPTH.set((tested.0, true));
3489 } 3811 }
3490 } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { 3812 } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
3813 let _ = crate::residency::take_staging_deferred();
3491 TESTED_DEPTH.set((tested.0, false)); 3814 TESTED_DEPTH.set((tested.0, false));
3492 readable(list, kind, &view); 3815 readable(list, kind, &view);
3493 let depth = TESTED_DEPTH.get().1; 3816 let depth = TESTED_DEPTH.get().1;
3494 TESTED_DEPTH.set((tested.0, tested.1 || depth)); 3817 TESTED_DEPTH.set((tested.0, tested.1 || depth));
3495 if kind == ResourceType::Srv { 3818 if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() {
3496 listed.ready = (list.epoch(), tested.0, depth); 3819 listed.ready = (list.epoch(), tested.0, depth);
3497 } 3820 }
3498 } 3821 }
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 8d4fad1..d1088cc 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -4912,7 +4912,7 @@ impl Host {
4912 let mut telling = std::time::Instant::now(); 4912 let mut telling = std::time::Instant::now();
4913 for item in items { 4913 for item in items {
4914 telling = match item { 4914 telling = match item {
4915 Late::Run(flight) => { 4915 Late::Run(mut flight) => {
4916 last = flight.number; 4916 last = flight.number;
4917 for &i in &flight.order { 4917 for &i in &flight.order {
4918 read_backs(flight.lists[i].host()); 4918 read_backs(flight.lists[i].host());
@@ -4923,6 +4923,9 @@ impl Host {
4923 if let Some(own) = flight.own { 4923 if let Some(own) = flight.own {
4924 own.landed(); 4924 own.landed();
4925 } 4925 }
4926 for detached in &mut flight.lists {
4927 detached.release_tables();
4928 }
4926 landed.push((flight.lists, flight.order)); 4929 landed.push((flight.lists, flight.order));
4927 crate::land::spent(crate::land::stat::READ_BACKS, telling) 4930 crate::land::spent(crate::land::stat::READ_BACKS, telling)
4928 } 4931 }
@@ -5125,6 +5128,14 @@ impl Host {
5125 let _ = self.submit(runs, &[], false); 5128 let _ = self.submit(runs, &[], false);
5126 } 5129 }
5127 5130
5131 /// Runs a closed internal upload-only host list synchronously without
5132 /// draining title queues (`queue::before_sync`), so it is deadlock-safe
5133 /// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight
5134 /// GPU work and waits for the upload list's fence before returning.
5135 pub(crate) fn execute_sync_internal(&self, list: &HostList) {
5136 let _ = self.submit(&[list], &[], false);
5137 }
5138
5128 /// A queue's submission with [`late`]: the host lists `lists`, taken 5139 /// A queue's submission with [`late`]: the host lists `lists`, taken
5129 /// from the title's, go to the card in `order` and are not waited for. 5140 /// from the title's, go to the card in `order` and are not waited for.
5130 /// They join the line of flights and are settled, with the others in 5141 /// They join the line of flights and are settled, with the others in
@@ -5382,7 +5393,7 @@ impl Host {
5382 let mut landed = Vec::new(); 5393 let mut landed = Vec::new();
5383 for item in items { 5394 for item in items {
5384 match item { 5395 match item {
5385 Late::Run(flight) => { 5396 Late::Run(mut flight) => {
5386 last = flight.number; 5397 last = flight.number;
5387 for &i in &flight.order { 5398 for &i in &flight.order {
5388 read_backs(flight.lists[i].host()); 5399 read_backs(flight.lists[i].host());
@@ -5390,6 +5401,9 @@ impl Host {
5390 if let Some(card) = flight.card { 5401 if let Some(card) = flight.card {
5391 self.card_done(card); 5402 self.card_done(card);
5392 } 5403 }
5404 for detached in &mut flight.lists {
5405 detached.release_tables();
5406 }
5393 landed.push((flight.lists, flight.order)); 5407 landed.push((flight.lists, flight.order));
5394 } 5408 }
5395 Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), 5409 Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
@@ -6348,6 +6362,13 @@ impl HostList {
6348 self.epoch.load(Ordering::Relaxed) 6362 self.epoch.load(Ordering::Relaxed)
6349 } 6363 }
6350 6364
6365 /// Whether any deferred steps or texture state transitions have been
6366 /// recorded into this list since creation or its last [`HostList::reset`].
6367 pub(crate) fn has_recorded_work(&self) -> bool {
6368 !self.deferred().copies.is_empty()
6369 || !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
6370 }
6371
6351 /// Moves a title texture's host copy to `wanted` (a host state) in this 6372 /// Moves a title texture's host copy to `wanted` (a host state) in this
6352 /// list: the host texture and the state it leaves, if that is a change. 6373 /// list: the host texture and the state it leaves, if that is a change.
6353 /// The list's first use of a texture records nothing: its prelude brings 6374 /// The list's first use of a texture records nothing: its prelude brings
diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs
index 5c13842..e50f572 100644
--- a/crates/victory-gpu/src/indirect.rs
+++ b/crates/victory-gpu/src/indirect.rs
@@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool {
295 295
296/// Whether a record that does not fit in what is left of its list's budget 296/// Whether a record that does not fit in what is left of its list's budget
297/// takes the rest, so that every record after it runs empty too 297/// takes the rest, so that every record after it runs empty too
298/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits 298/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes
299/// runs). A list whose budget one garbage record empties loses all its later 299/// nothing and later valid draws still run).
300/// draws, and which record that is may differ from frame to frame. The frame
301/// line says how many records a frame are refused.
302fn rest() -> u32 { 300fn rest() -> u32 {
303 u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) 301 u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1"))
304} 302}
305 303
306/// The clamp compiled from `source` (ours, or in the benchmark the one it 304/// The clamp compiled from `source` (ours, or in the benchmark the one it
@@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
2607 /// left then, and the records as clamped. 2605 /// left then, and the records as clamped.
2608 fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> { 2606 fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> {
2609 let mut warp = WarpHarness::new()?; 2607 let mut warp = WarpHarness::new()?;
2610 let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; 2608 let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" });
2611 let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); 2609 let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP");
2612 const KIND_DRAW: u32 = 0; 2610 const KIND_DRAW: u32 = 0;
2613 const STRIDE: u32 = 16; 2611 const STRIDE: u32 = 16;
diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs
index 8a17ddb..a18363d 100644
--- a/crates/victory-gpu/src/list.rs
+++ b/crates/victory-gpu/src/list.rs
@@ -203,6 +203,12 @@ impl Detached {
203 pub(crate) fn host(&self) -> &crate::host::HostList { 203 pub(crate) fn host(&self) -> &crate::host::HostList {
204 &self.host 204 &self.host
205 } 205 }
206
207 /// Releases this list's dynamic descriptor slots once its GPU submission
208 /// has completed, without waiting for the full `bury_lag` allocator delay.
209 pub(crate) fn release_tables(&mut self) {
210 self._state.tables_done();
211 }
206} 212}
207 213
208/// A host list that has run and waits to be used again, and the bytes of 214/// A host list that has run and waits to be used again, and the bytes of
diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs
index f1de86c..9c68fd6 100644
--- a/crates/victory-gpu/src/pipeline/host.rs
+++ b/crates/victory-gpu/src/pipeline/host.rs
@@ -524,6 +524,7 @@ impl HostPipeline {
524 slot == victory_shader::emit::SLOT_FAULTS 524 slot == victory_shader::emit::SLOT_FAULTS
525 } else { 525 } else {
526 slot == victory_shader::emit::SLOT_STRIDES 526 slot == victory_shader::emit::SLOT_STRIDES
527 || slot == victory_shader::emit::SLOT_TABLE_STRIDES
527 || slot == victory_shader::emit::SLOT_MEMORY 528 || slot == victory_shader::emit::SLOT_MEMORY
528 }; 529 };
529 if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { 530 if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs
index dabb3d6..cde4cdb 100644
--- a/crates/victory-gpu/src/pool.rs
+++ b/crates/victory-gpu/src/pool.rs
@@ -52,7 +52,14 @@ pub(crate) fn room(memory: Option<[u64; 4]>) {
52 pool.reclaim(tick, limit, true); 52 pool.reclaim(tick, limit, true);
53 } 53 }
54 if let Ok(mut pool) = STAGING.try_lock() { 54 if let Ok(mut pool) = STAGING.try_lock() {
55 pool.reclaim(tick, if pressure { 0 } else { limit }, true); 55 let staging_limit = if crate::residency::critical_commit() {
56 0
57 } else if pressure {
58 1
59 } else {
60 limit
61 };
62 pool.reclaim(tick, staging_limit, true);
56 } 63 }
57} 64}
58 65
@@ -379,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
379 // Copies from a buffer begin at multiples of 512. 386 // Copies from a buffer begin at multiples of 512.
380 let bytes = bytes.next_multiple_of(512); 387 let bytes = bytes.next_multiple_of(512);
381 let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { 388 let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
389 // Only gate speculative bindless prefetch on staging-pool growth
390 // headroom; table-bound textures and decoration bakes are sampled
391 // immediately and would otherwise read uninitialized/reused VRAM.
392 let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get();
393 if speculative && !crate::residency::allow_staging_growth(false) {
394 return None;
395 }
382 let (buffer, data) = host.upload_buffer(BLOCK)?; 396 let (buffer, data) = host.upload_buffer(BLOCK)?;
383 crate::host::name(&buffer, || "staging of textures (a block)".into()); 397 crate::host::name(&buffer, || "staging of textures (a block)".into());
384 Some(Upload(buffer, data)) 398 Some(Upload(buffer, data))
diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs
index de5c6dc..0e701e5 100644
--- a/crates/victory-gpu/src/residency.rs
+++ b/crates/victory-gpu/src/residency.rs
@@ -3,6 +3,7 @@ use std::sync::OnceLock;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; 4use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
5 5
6const MIB: u64 = 1 << 20;
6const GIB: u64 = 1 << 30; 7const GIB: u64 = 1 << 30;
7static PRESSURED: AtomicBool = AtomicBool::new(false); 8static PRESSURED: AtomicBool = AtomicBool::new(false);
8static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); 9static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
@@ -25,30 +26,68 @@ pub(crate) fn allocation_error(error: &windows::core::Error) {
25 } 26 }
26} 27}
27 28
29thread_local! {
30 static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
31}
32
33pub(crate) fn note_staging_deferred() {
34 STAGING_DEFERRED.set(true);
35}
36
37pub(crate) fn take_staging_deferred() -> bool {
38 STAGING_DEFERRED.replace(false)
39}
40
28pub(crate) fn upload_refused() -> bool { 41pub(crate) fn upload_refused() -> bool {
29 crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed) 42 crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
30} 43}
31 44
45fn sample_commit(now: u64) -> u64 {
46 let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
47 if now >= next
48 && NEXT_COMMIT_SAMPLE
49 .compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed)
50 .is_ok()
51 && let Some(status) = memory_status()
52 {
53 AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
54 }
55 AVAILABLE_COMMIT.load(Ordering::Relaxed)
56}
57
32fn has_upload_reserve(commit: u64, bake: bool) -> bool { 58fn has_upload_reserve(commit: u64, bake: bool) -> bool {
33 commit >= if bake { 2 * GIB } else { 4 * GIB } 59 // Keep a protective floor against Rust/game OOM aborts without starving
60 // bindless world textures or one-shot ped decoration bakes when steady-state
61 // commit headroom sits in the 1-4 GiB range on 32 GiB hosts.
62 commit >= if bake { 256 * MIB } else { 512 * MIB }
63}
64
65fn has_growth_reserve(commit: u64, bake: bool) -> bool {
66 // Growing a fresh 64 MiB upload block for speculative bindless prefetch
67 // requires more headroom than reusing slices already committed inside the
68 // staging pool.
69 commit >= if bake { 256 * MIB } else { 1024 * MIB }
34} 70}
35 71
36/// Leave commit for game allocations and submissions already in flight. Direct 72/// Leave commit for game allocations and submissions already in flight while
37/// texture consumers bypass this gate. Bake prefetch gets priority over lookahead. 73/// still letting bindless textures and one-shot material bakes upload.
38pub(crate) fn admit_texture_pass(bake: bool) -> bool { 74pub(crate) fn admit_texture_pass(bake: bool) -> bool {
39 let now = crate::host::coarse_ms(); 75 let now = crate::host::coarse_ms();
40 if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { 76 if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
41 return false; 77 return false;
42 } 78 }
43 let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed); 79 has_upload_reserve(sample_commit(now), bake)
44 if now >= next && NEXT_COMMIT_SAMPLE.compare_exchange( 80}
45 next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed, 81
46 ).is_ok() { 82/// Whether the staging allocator may commit a brand-new OS upload buffer
47 if let Some(status) = memory_status() { 83/// (reusing existing free ranges in already-committed pool blocks stays open
48 AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed); 84/// whenever `admit_texture_pass` is true).
49 } 85pub(crate) fn allow_staging_growth(bake: bool) -> bool {
86 let now = crate::host::coarse_ms();
87 if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
88 return false;
50 } 89 }
51 has_upload_reserve(AVAILABLE_COMMIT.load(Ordering::Relaxed), bake) 90 has_growth_reserve(sample_commit(now), bake)
52} 91}
53 92
54pub(crate) fn limited_host_ram() -> bool { 93pub(crate) fn limited_host_ram() -> bool {
@@ -58,9 +97,9 @@ pub(crate) fn limited_host_ram() -> bool {
58 97
59fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { 98fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
60 if was { 99 if was {
61 physical < 6 * GIB || commit < 8 * GIB 100 physical < 5 * GIB || commit < 6 * GIB
62 } else { 101 } else {
63 physical <= 4 * GIB || commit <= 6 * GIB 102 physical <= 3 * GIB || commit <= 4 * GIB
64 } 103 }
65} 104}
66 105
@@ -100,13 +139,20 @@ pub(crate) fn pressured() -> bool {
100 PRESSURED.load(Ordering::Relaxed) 139 PRESSURED.load(Ordering::Relaxed)
101} 140}
102 141
142/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
143/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
144pub(crate) fn critical_commit() -> bool {
145 let now = crate::host::coarse_ms();
146 now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
147}
148
103/// A soft per-frame admission limit. A single texture can cross it. The 149/// A soft per-frame admission limit. A single texture can cross it. The
104/// queue retains unserved slots so they can be retried on later frames. 150/// queue retains unserved slots so they can be retried on later frames.
105pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging: u64) -> u64 { 151pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
106 if pressure { 152 if critical {
107 bytes.min(16 << 20) 153 bytes.min(16 << 20)
108 } else if limited && staging >= GIB { 154 } else if pressure || (limited && staging >= GIB) {
109 bytes.min(32 << 20) 155 bytes.min(64 << 20)
110 } else { 156 } else {
111 bytes 157 bytes
112 } 158 }
@@ -118,32 +164,38 @@ mod tests {
118 164
119 #[test] 165 #[test]
120 fn bake_and_lookahead_leave_room_for_live_game_allocations() { 166 fn bake_and_lookahead_leave_room_for_live_game_allocations() {
121 for (commit, bake, lookahead) in [ 167 for (commit, bake, lookahead, growth) in [
122 (277 << 20, false, false), (2 * GIB, true, false), (4 * GIB, true, true), 168 (128 * MIB, false, false, false),
169 (256 * MIB, true, false, false),
170 (512 * MIB, true, true, false),
171 (768 * MIB, true, true, false),
172 (1024 * MIB, true, true, true),
123 ] { 173 ] {
124 assert_eq!(has_upload_reserve(commit, true), bake); 174 assert_eq!(has_upload_reserve(commit, true), bake);
125 assert_eq!(has_upload_reserve(commit, false), lookahead); 175 assert_eq!(has_upload_reserve(commit, false), lookahead);
176 assert_eq!(has_growth_reserve(commit, false), growth);
126 } 177 }
127 } 178 }
128 179
129 #[test] 180 #[test]
130 fn either_constraint_enters_pressure_and_both_must_recover() { 181 fn either_constraint_enters_pressure_and_both_must_recover() {
131 assert!(next_pressure(false, 12 * GIB, 6 * GIB)); 182 assert!(next_pressure(false, 12 * GIB, 4 * GIB));
132 assert!(next_pressure(false, 4 * GIB, 16 * GIB)); 183 assert!(next_pressure(false, 3 * GIB, 16 * GIB));
133 assert!(next_pressure(true, 5 * GIB, 9 * GIB)); 184 assert!(next_pressure(true, 4 * GIB, 7 * GIB));
134 assert!(next_pressure(true, 7 * GIB, 7 * GIB)); 185 assert!(next_pressure(true, 6 * GIB, 5 * GIB));
135 assert!(!next_pressure(true, 6 * GIB, 8 * GIB)); 186 assert!(!next_pressure(true, 5 * GIB, 6 * GIB));
136 assert!(!next_pressure(false, 5 * GIB, 7 * GIB)); 187 assert!(!next_pressure(false, 4 * GIB, 5 * GIB));
137 } 188 }
138 189
139 #[test] 190 #[test]
140 fn prefetch_respects_existing_budgets_and_resumes_after_recovery() { 191 fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
141 assert_eq!(prefetch_limit(512 << 20, false, true, GIB), 32 << 20); 192 assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20);
142 assert_eq!(prefetch_limit(512 << 20, false, true, GIB - 1), 512 << 20); 193 assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20);
143 assert_eq!(prefetch_limit(512 << 20, false, false, 2 * GIB), 512 << 20); 194 assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20);
144 assert_eq!(prefetch_limit(0, true, false, 0), 0); 195 assert_eq!(prefetch_limit(0, true, true, false, 0), 0);
145 assert_eq!(prefetch_limit(8 << 20, true, false, 0), 8 << 20); 196 assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20);
146 assert_eq!(prefetch_limit(512 << 20, true, false, 0), 16 << 20); 197 assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20);
147 assert_eq!(prefetch_limit(192 << 20, false, false, 0), 192 << 20); 198 assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
199 assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
148 } 200 }
149} 201}
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
index 61bd6bc..e749738 100644
--- a/crates/victory-gpu/src/texture.rs
+++ b/crates/victory-gpu/src/texture.rs
@@ -91,6 +91,11 @@ pub(crate) struct Staging {
91 /// recorded again about a second later if the card has room by then 91 /// recorded again about a second later if the card has room by then
92 /// ([`upload`]). 92 /// ([`upload`]).
93 waiting: std::sync::atomic::AtomicU64, 93 waiting: std::sync::atomic::AtomicU64,
94 /// Recorded for a one-shot decoration bake (`BAKING`): submission-time
95 /// refresh must wait for title memory to stop remapping
96 /// (`title_memory_reading`) instead of taking `no_wait()` /
97 /// `refresh_unlocked()` or the 30-frame partial-read throttle.
98 exact: std::sync::atomic::AtomicBool,
94} 99}
95 100
96/// What a texture's staging buffer holds: the hash of the memory detiled 101/// What a texture's staging buffer holds: the hash of the memory detiled
@@ -756,6 +761,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
756 return; 761 return;
757 }; 762 };
758 use std::sync::atomic::Ordering::Relaxed; 763 use std::sync::atomic::Ordering::Relaxed;
764 let baking = BAKING.get();
765 if baking {
766 staging.exact.store(true, Relaxed);
767 }
759 let picking = PICKING.get(); 768 let picking = PICKING.get();
760 if picking.is_none() { 769 if picking.is_none() {
761 // A draw samples it through a table: kept and checked from here on. 770 // A draw samples it through a table: kept and checked from here on.
@@ -810,8 +819,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
810 // The host texture has the staging buffer's contents: only the check 819 // The host texture has the staging buffer's contents: only the check
811 // at submission is left, and what it finds changed the next list that 820 // at submission is left, and what it finds changed the next list that
812 // samples the texture uploads (a frame late where every list of the 821 // samples the texture uploads (a frame late where every list of the
813 // frame was recorded before that check). 822 // frame was recorded before that check). During a one-shot bake we
814 if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { 823 // always record the copy so any change found at submission lands in
824 // VRAM before the bake draw executes.
825 if !baking && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
815 #[cfg(feature = "diagnostics")] 826 #[cfg(feature = "diagnostics")]
816 crate::copystat::add(crate::copystat::C::TexSkipped, 1); 827 crate::copystat::add(crate::copystat::C::TexSkipped, 1);
817 list.defer_texture(staging); 828 list.defer_texture(staging);
@@ -1254,12 +1265,13 @@ impl Staging {
1254 let start = self.memory as usize; 1265 let start = self.memory as usize;
1255 let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); 1266 let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
1256 let last = &mut *last; 1267 let last = &mut *last;
1268 let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed);
1257 let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); 1269 let alone = self.once.load(std::sync::atomic::Ordering::Relaxed);
1258 if alone && last.hash.is_some() { 1270 if alone && !exact && last.hash.is_some() {
1259 return 0; 1271 return 0;
1260 } 1272 }
1261 if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { 1273 if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
1262 if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { 1274 if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
1263 return 0; 1275 return 0;
1264 } 1276 }
1265 last.asked = now; 1277 last.asked = now;
@@ -1303,7 +1315,7 @@ impl Staging {
1303 last.hot_until = frame + HOT_FRAMES; 1315 last.hot_until = frame + HOT_FRAMES;
1304 } 1316 }
1305 let hot = hot_textures() && frame < last.hot_until; 1317 let hot = hot_textures() && frame < last.hot_until;
1306 if unwritten && !turn && !hot { 1318 if !exact && unwritten && !turn && !hot {
1307 return 0; 1319 return 0;
1308 } 1320 }
1309 blind = unwritten; 1321 blind = unwritten;
@@ -1322,7 +1334,7 @@ impl Staging {
1322 // stays mapped (see `crate::watch::title_memory_reading`; without 1334 // stays mapped (see `crate::watch::title_memory_reading`; without
1323 // it a page went between the asking and the read in runs 71 and 1335 // it a page went between the asking and the read in runs 71 and
1324 // 74). 1336 // 74).
1325 let _mapped = if no_wait() { 1337 let _mapped = if no_wait() && !exact {
1326 // Not waited for: while the runtime remaps title memory the 1338 // Not waited for: while the runtime remaps title memory the
1327 // texture is read through the kernel instead, whole or not at 1339 // texture is read through the kernel instead, whole or not at
1328 // all (`no_wait`). 1340 // all (`no_wait`).
@@ -1342,7 +1354,7 @@ impl Staging {
1342 // unmapped pages is slow, and nothing tells us when pages 1354 // unmapped pages is slow, and nothing tells us when pages
1343 // arrive): a mip that streams in shows up to 30 frames late. 1355 // arrive): a mip that streams in shows up to 30 frames late.
1344 let frame = crate::frame::current(); 1356 let frame = crate::frame::current();
1345 if last.partial.is_some_and(|at| frame < at + 30) { 1357 if !exact && last.partial.is_some_and(|at| frame < at + 30) {
1346 return 0; 1358 return 0;
1347 } 1359 }
1348 last.partial = Some(frame); 1360 last.partial = Some(frame);
@@ -1878,6 +1890,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
1878 let (piece, buffer, base, data) = match crate::pool::staging(host, total) { 1890 let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
1879 Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), 1891 Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
1880 None => { 1892 None => {
1893 let speculative = PICKING.get().is_some() && !BAKING.get();
1894 if crate::residency::upload_refused()
1895 || (speculative && !crate::residency::allow_staging_growth(false))
1896 {
1897 crate::residency::note_staging_deferred();
1898 return None;
1899 }
1881 let (buffer, data) = host.upload_buffer(total)?; 1900 let (buffer, data) = host.upload_buffer(total)?;
1882 crate::host::name(&buffer, || { 1901 crate::host::name(&buffer, || {
1883 format!( 1902 format!(
@@ -1919,6 +1938,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
1919 detiled: std::sync::atomic::AtomicU32::new(0), 1938 detiled: std::sync::atomic::AtomicU32::new(0),
1920 judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], 1939 judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
1921 waiting: std::sync::atomic::AtomicU64::new(0), 1940 waiting: std::sync::atomic::AtomicU64::new(0),
1941 exact: std::sync::atomic::AtomicBool::new(BAKING.get()),
1922 }); 1942 });
1923 map.insert(resource as usize, s.clone()); 1943 map.insert(resource as usize, s.clone());
1924 Some(s) 1944 Some(s)
diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs
index e71b4e9..2cfdde6 100644
--- a/crates/victory-gpu/src/texture/ahead.rs
+++ b/crates/victory-gpu/src/texture/ahead.rs
@@ -13,7 +13,7 @@
13//! it as any texture. 13//! it as any texture.
14 14
15use std::collections::VecDeque; 15use std::collections::VecDeque;
16use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; 16use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
17use std::sync::{Arc, Condvar, Mutex, OnceLock}; 17use std::sync::{Arc, Condvar, Mutex, OnceLock};
18 18
19use windows::Win32::Graphics::Direct3D12::*; 19use windows::Win32::Graphics::Direct3D12::*;
@@ -80,6 +80,7 @@ pub(crate) enum Taken {
80static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); 80static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
81/// Those on their way, by host copy ([`HostTexture::serial`]). 81/// Those on their way, by host copy ([`HostTexture::serial`]).
82static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new()); 82static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
83static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
83static LANDED: Condvar = Condvar::new(); 84static LANDED: Condvar = Condvar::new();
84static BYTES: AtomicU64 = AtomicU64::new(0); 85static BYTES: AtomicU64 = AtomicU64::new(0);
85/// Since the start: uploads, bytes, microseconds from the asking until the 86/// Since the start: uploads, bytes, microseconds from the asking until the
@@ -104,7 +105,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
104 return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); 105 return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
105 } 106 }
106 let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; 107 let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
107 if crate::residency::pressured() 108 if !crate::residency::allow_staging_growth(false)
108 || BYTES.load(Relaxed) >= most 109 || BYTES.load(Relaxed) >= most
109 || copy.flags() & 0x7 != 0 110 || copy.flags() & 0x7 != 0
110 || copy.state.load(Relaxed) != 0 111 || copy.state.load(Relaxed) != 0
@@ -134,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
134 } 135 }
135 let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) }); 136 let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
136 BYTES.fetch_add(job.staging.read as u64, Relaxed); 137 BYTES.fetch_add(job.staging.read as u64, Relaxed);
137 ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone())); 138 {
139 let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
140 way.push((job.copy.serial, job.clone()));
141 IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
142 }
138 Some(Taken::New(job)) 143 Some(Taken::New(job))
139} 144}
140 145
@@ -144,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) {
144 QUEUE.1.notify_one(); 149 QUEUE.1.notify_one();
145} 150}
146 151
152/// Waits until every upload currently on its way here has finished copying
153/// and run its completion callbacks (queuing slot flips into `FLIPS`).
154/// Returns how many jobs were waited for.
155pub(crate) fn drain() -> usize {
156 if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 {
157 return 0;
158 }
159 let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
160 let waiting = way.len();
161 let started = std::time::Instant::now();
162 while !way.is_empty() && started.elapsed().as_millis() < 2000 {
163 way = LANDED
164 .wait_timeout(way, std::time::Duration::from_millis(50))
165 .unwrap_or_else(|e| e.into_inner())
166 .0;
167 }
168 waiting
169}
170
147/// A list is about to record an upload into `copy`: one on its way here runs 171/// A list is about to record an upload into `copy`: one on its way here runs
148/// first, and no other is taken after it. 172/// first, and no other is taken after it.
149pub(crate) fn listed(copy: &HostTexture) { 173pub(crate) fn listed(copy: &HostTexture) {
@@ -293,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) {
293 job.copy.ahead.store(DONE, Relaxed); 317 job.copy.ahead.store(DONE, Relaxed);
294 BYTES.fetch_sub(job.staging.read as u64, Relaxed); 318 BYTES.fetch_sub(job.staging.read as u64, Relaxed);
295 } 319 }
296 {
297 let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
298 way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
299 LANDED.notify_all();
300 }
301 for job in &jobs { 320 for job in &jobs {
302 let us = job.asked.elapsed().as_micros() as u64; 321 let us = job.asked.elapsed().as_micros() as u64;
303 let n = STATS[0].fetch_add(1, Relaxed) + 1; 322 let n = STATS[0].fetch_add(1, Relaxed) + 1;
@@ -319,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) {
319 f(); 338 f();
320 } 339 }
321 } 340 }
341 // Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued
342 // their `FLIPS` entries so `drain()` observes every flip ready to apply.
343 {
344 let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
345 way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
346 IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
347 LANDED.notify_all();
348 }
322 crate::descriptor::host::flip_now(); 349 crate::descriptor::host::flip_now();
323} 350}
324 351
@@ -416,4 +443,31 @@ mod tests {
416 back.Unmap(0, None); 443 back.Unmap(0, None);
417 } 444 }
418 } 445 }
446
447 #[test]
448 fn drain_waits_until_then_callbacks_have_run() {
449 use std::sync::atomic::AtomicBool;
450 use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
451 let Some(_host) = crate::host::host() else { return };
452 let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
453 let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
454 // SAFETY: memory of our own that stays for the test.
455 let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
456 // SAFETY: as above.
457 unsafe { std::ptr::write_bytes(at, 0x5a, whole) };
458 let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
459 crate::resource::want_level(texture, 0);
460 let copy = crate::resource::host_copy(texture).unwrap();
461 if !crate::pool::fresh(&copy.texture) {
462 return;
463 }
464 let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
465 let ran = Arc::new(AtomicBool::new(false));
466 let flag = ran.clone();
467 job.then(move || flag.store(true, std::sync::atomic::Ordering::Release));
468 send(&job);
469 assert!(drain() >= 1);
470 assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns");
471 assert_eq!(drain(), 0);
472 }
419} 473}
diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs
index 21b4d03..68115d7 100644
--- a/crates/victory-shader/src/emit/diff_tests.rs
+++ b/crates/victory-shader/src/emit/diff_tests.rs
@@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() {
1228 let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); 1228 let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
1229 root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); 1229 root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
1230 root_views.sort_unstable(); 1230 root_views.sort_unstable();
1231 let view_strides: Vec<u32> = views
1232 .iter()
1233 .map(|v| match *v {
1234 View::RawUav(_) => 1,
1235 View::HalfUav(_) => 8,
1236 View::Buffer { stride, .. } => match stride {
1237 Stride::Raw => 1,
1238 Stride::Typed => 16,
1239 Stride::Structured(s) => s,
1240 Stride::Format(f, bytes) => {
1241 let kind = match f.0 as u32 {
1242 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => {
1243 super::VIEW_INTEGER
1244 }
1245 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => {
1246 super::VIEW_INTEGER | super::VIEW_SIGNED
1247 }
1248 _ => 0,
1249 };
1250 bytes | kind
1251 }
1252 },
1253 _ => 0,
1254 })
1255 .collect();
1231 for (n, (slot, srv)) in root_views.into_iter().enumerate() { 1256 for (n, (slot, srv)) in root_views.into_iter().enumerate() {
1232 assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); 1257 let data = if srv
1233 let data = if srv { 1258 && (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES)
1234 root_srv.clone() 1259 {
1260 view_strides.clone()
1235 } else { 1261 } else {
1236 root_cbv.clone() 1262 assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
1263 if srv {
1264 root_srv.clone()
1265 } else {
1266 root_cbv.clone()
1267 }
1237 }; 1268 };
1238 roots.push((1 + n as u32, Root::View { srv, data })); 1269 roots.push((1 + n as u32, Root::View { srv, data }));
1239 } 1270 }
diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs
index 9196f51..8bfb9d7 100644
--- a/crates/victory-shader/src/emit/host.rs
+++ b/crates/victory-shader/src/emit/host.rs
@@ -1004,6 +1004,12 @@ pub enum View<'a> {
1004 UintTextureUav(u32, u32), 1004 UintTextureUav(u32, u32),
1005 /// A typed RGBA16F buffer UAV of this many elements, zeroed. 1005 /// A typed RGBA16F buffer UAV of this many elements, zeroed.
1006 HalfUav(u32), 1006 HalfUav(u32),
1007 /// A typed buffer UAV pre-filled with `data` (`format`, bytes per element).
1008 TypedUav {
1009 data: &'a [u32],
1010 format: DXGI_FORMAT,
1011 elem_bytes: u32,
1012 },
1007 /// A constant buffer of these dwords. 1013 /// A constant buffer of these dwords.
1008 Cbv(&'a [u32]), 1014 Cbv(&'a [u32]),
1009 /// A buffer SRV over these dwords. 1015 /// A buffer SRV over these dwords.
@@ -1279,6 +1285,46 @@ impl Host {
1279 )?; 1285 )?;
1280 uavs.push((b, None, n, rb)); 1286 uavs.push((b, None, n, rb));
1281 } 1287 }
1288 View::TypedUav {
1289 data,
1290 format,
1291 elem_bytes,
1292 } => {
1293 let n = data.len() as u32;
1294 let bytes = u64::from(n) * 4;
1295 let elements = (bytes / u64::from(elem_bytes)) as u32;
1296 let b = make(
1297 D3D12_HEAP_TYPE_DEFAULT,
1298 &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
1299 D3D12_RESOURCE_STATE_COPY_DEST,
1300 )?;
1301 let up = upload(data)?;
1302 list.CopyBufferRegion(&b, 0, &up, 0, bytes);
1303 list.ResourceBarrier(&[transition(
1304 &b,
1305 D3D12_RESOURCE_STATE_COPY_DEST,
1306 D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
1307 )]);
1308 keep.push(up);
1309 let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
1310 Format: format,
1311 ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
1312 Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
1313 Buffer: D3D12_BUFFER_UAV {
1314 NumElements: elements,
1315 Flags: D3D12_BUFFER_UAV_FLAG_NONE,
1316 ..Default::default()
1317 },
1318 },
1319 };
1320 dev.CreateUnorderedAccessView(&b, None, Some(&desc), at);
1321 let rb = make(
1322 D3D12_HEAP_TYPE_READBACK,
1323 &buffer(bytes, D3D12_RESOURCE_FLAG_NONE),
1324 D3D12_RESOURCE_STATE_COPY_DEST,
1325 )?;
1326 uavs.push((b, None, n, rb));
1327 }
1282 View::TextureUav(w, h) => { 1328 View::TextureUav(w, h) => {
1283 let t = make( 1329 let t = make(
1284 D3D12_HEAP_TYPE_DEFAULT, 1330 D3D12_HEAP_TYPE_DEFAULT,
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 7f3b8f7..72af2be 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -7501,7 +7501,7 @@ impl<'a> Lower<'a> {
7501 /// `ResourceHeap`): read from the host's table by heap slot in the 7501 /// `ResourceHeap`): read from the host's table by heap slot in the
7502 /// current block. 7502 /// current block.
7503 fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> { 7503 fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
7504 let word = self.slot_word(src)?; 7504 let word = self.slot_word(src, false)?;
7505 Ok(word.map(|word| { 7505 Ok(word.map(|word| {
7506 let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); 7506 let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
7507 self.s.m.bin(self.cur, Bin::And, word, bits) 7507 self.s.m.bin(self.cur, Bin::And, word, bits)
@@ -7509,10 +7509,9 @@ impl<'a> Lower<'a> {
7509 } 7509 }
7510 7510
7511 /// Whether the typed buffer view `src` names is one of an integer format, 7511 /// Whether the typed buffer view `src` names is one of an integer format,
7512 /// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the 7512 /// and whether a signed one (`ResourceHeap` or `Table`).
7513 /// program does not pick from the heap).
7514 fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> { 7513 fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
7515 let Some(word) = self.slot_word(src)? else { 7514 let Some(word) = self.slot_word(src, true)? else {
7516 return Ok(None); 7515 return Ok(None);
7517 }; 7516 };
7518 let c = self.cur; 7517 let c = self.cur;
@@ -7526,19 +7525,22 @@ impl<'a> Lower<'a> {
7526 } 7525 }
7527 7526
7528 /// The host's word for the buffer view `src` names: its stride and 7527 /// The host's word for the buffer view `src` names: its stride and
7529 /// format kind ([`super::shader::SLOT_STRIDES`]). 7528 /// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`,
7530 fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> { 7529 /// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`).
7530 fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> {
7531 let Source::Loaded { load, first } = src else { 7531 let Source::Loaded { load, first } = src else {
7532 return Ok(None); 7532 return Ok(None);
7533 }; 7533 };
7534 let heap = self 7534 let srv_slot = match self
7535 .scalar 7535 .scalar
7536 .get(load) 7536 .get(load)
7537 .and_then(|a| self.x.native.layout.get(a.param)) 7537 .and_then(|a| self.x.native.layout.get(a.param))
7538 .is_some_and(|p| p.root == RootType::ResourceHeap); 7538 .map(|p| p.root)
7539 if !heap { 7539 {
7540 return Ok(None); 7540 Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES,
7541 } 7541 Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES,
7542 _ => return Ok(None),
7543 };
7542 let key = (self.cur, *load, *first); 7544 let key = (self.cur, *load, *first);
7543 if let Some(&v) = self.strides.get(&key) { 7545 if let Some(&v) = self.strides.get(&key) {
7544 return Ok(Some(v)); 7546 return Ok(Some(v));
@@ -7553,7 +7555,7 @@ impl<'a> Lower<'a> {
7553 self.s.m.tag(slot, Tag::Clamp); 7555 self.s.m.tag(slot, Tag::Clamp);
7554 let two = self.s.m.i32(2); 7556 let two = self.s.m.i32(2);
7555 let byte = self.s.m.bin(c, Bin::Shl, slot, two); 7557 let byte = self.s.m.bin(c, Bin::Shl, slot, two);
7556 let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); 7558 let h = self.s.root_srv_handle(srv_slot);
7557 let iu = self.s.m.undef(self.s.t.i32); 7559 let iu = self.s.m.undef(self.s.t.i32);
7558 let mask = self.s.m.i8(1); 7560 let mask = self.s.m.i8(1);
7559 let align = self.s.m.i32(4); 7561 let align = self.s.m.i32(4);
@@ -11901,9 +11903,11 @@ impl<'a> Lower<'a> {
11901 // store; through a view of an integer format it is a 16-bit 11903 // store; through a view of an integer format it is a 16-bit
11902 // integer, zero- or sign-extended (VIctory 4243a96a: the face 11904 // integer, zero- or sign-extended (VIctory 4243a96a: the face
11903 // network keeps its halves in UINT views; its output was 11905 // network keeps its halves in UINT views; its output was
11904 // noise). shortcut: that is known of the views a program 11906 // noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table`
11905 // picks from the heap, not of those in its tables; and the 11907 // (`SLOT_TABLE_STRIDES`, dynamic table snapshots included)
11906 // handle stays a float one, whose bits the drivers pass. 11908 // populate the view-kind bits, while the handle stays a float
11909 // one (`0x409`), whose raw bits RTX and WARP pass bit-exact
11910 // without extra CFG blocks or touching non-d16 shaders.
11907 let integer = if typed { self.integer_view(src)? } else { None }; 11911 let integer = if typed { self.integer_view(src)? } else { None };
11908 let mut wide = Vec::new(); 11912 let mut wide = Vec::new();
11909 for k in 0..count { 11913 for k in 0..count {
diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs
index 356bc49..9aeeaf5 100644
--- a/crates/victory-shader/src/emit/mod.rs
+++ b/crates/victory-shader/src/emit/mod.rs
@@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
122pub use rect::rect_list_gs; 122pub use rect::rect_list_gs;
123pub use shader::{ 123pub use shader::{
124 MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, 124 MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
125 SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, 125 SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
126 raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, 126 raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
127}; 127};
128 128
@@ -485,17 +485,45 @@ pub fn emit(
485 }; 485 };
486 // The program in two other forms: without its early-outs, and 486 // The program in two other forms: without its early-outs, and
487 // without any branch that only skips code no lane is left for. 487 // without any branch that only skips code no lane is left for.
488 let form = |p: Option<ir::Program>| { 488 let form = |label: &str, p: Option<ir::Program>| {
489 p.and_then(|p| { 489 let Some(p) = p else {
490 let st = structure::structure(&p).ok()?; 490 if why {
491 let io = io::raise(&p, native).ok()?; 491 eprintln!("WAVE64-FORM {label}: ir returned None");
492 let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; 492 }
493 Some((p, st, io, res)) 493 return None;
494 }) 494 };
495 let st = match structure::structure(&p) {
496 Ok(st) => st,
497 Err(e) => {
498 if why {
499 eprintln!("WAVE64-FORM {label}: structure failed: {e}");
500 }
501 return None;
502 }
503 };
504 let io = match io::raise(&p, native) {
505 Ok(io) => io,
506 Err(e) => {
507 if why {
508 eprintln!("WAVE64-FORM {label}: io::raise failed: {e}");
509 }
510 return None;
511 }
512 };
513 let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) {
514 Ok(res) => res,
515 Err(e) => {
516 if why {
517 eprintln!("WAVE64-FORM {label}: resource::track failed: {e}");
518 }
519 return None;
520 }
521 };
522 Some((p, st, io, res))
495 }; 523 };
496 let forms = [ 524 let forms = [
497 ("without early-outs", form(ir::without_early_outs(p))), 525 ("without early-outs", form("without early-outs", ir::without_early_outs(p))),
498 ("without skips", form(ir::without_skips(p, false))), 526 ("without skips", form("without skips", ir::without_skips(p, false))),
499 ]; 527 ];
500 for (name, f) in &forms { 528 for (name, f) in &forms {
501 if let Some((p, st, io, res)) = f { 529 if let Some((p, st, io, res)) = f {
@@ -539,7 +567,7 @@ pub fn emit(
539 // lane runs, where the two host waves can exchange. 567 // lane runs, where the two host waves can exchange.
540 // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) 568 // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
541 let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); 569 let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
542 let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; 570 let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None };
543 if let Some((p, st, io, res)) = &deep { 571 if let Some((p, st, io, res)) = &deep {
544 let again = emit_program(c, native, p, st, io, res); 572 let again = emit_program(c, native, p, st, io, res);
545 report("without skips, scalars followed", &again); 573 report("without skips, scalars followed", &again);
@@ -700,7 +728,22 @@ fn widen(
700 || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); 728 || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
701 if !stuck { 729 if !stuck {
702 if why { 730 if why {
703 eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); 731 let order = ir::reverse_postorder(&p.blocks);
732 let mut rpo = vec![0usize; p.blocks.len()];
733 for (i, &b) in order.iter().enumerate() {
734 rpo[b] = i;
735 }
736 let mut sorted: Vec<usize> = wide.iter().copied().collect();
737 sorted.sort_unstable();
738 let desc: Vec<String> = sorted
739 .iter()
740 .map(|&b| {
741 let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]);
742 let nm = p.blocks[b].insts.last().map_or("?", |i| i.name());
743 format!("B{b}({nm}{})", if back { ",BACK" } else { "" })
744 })
745 .collect();
746 eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", "));
704 } 747 }
705 return r; 748 return r;
706 } 749 }
diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs
index 1f6585f..4d5f921 100644
--- a/crates/victory-shader/src/emit/shader.rs
+++ b/crates/victory-shader/src/emit/shader.rs
@@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1;
24/// root SRV also tells the host that the buffer views of the whole heap 24/// root SRV also tells the host that the buffer views of the whole heap
25/// must be ready when it runs, not only those its tables name. 25/// must be ready when it runs, not only those its tables name.
26pub const SLOT_STRIDES: u8 = 255; 26pub const SLOT_STRIDES: u8 = 255;
27/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for
28/// shaders that only inspect views from descriptor tables (`RootType::Table`).
29/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without
30/// running the full bindless heap buffer sweep.
31pub const SLOT_TABLE_STRIDES: u8 = 252;
27/// The bits of a [`SLOT_STRIDES`] dword that hold the stride. 32/// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
28pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; 33pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
29/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format 34/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs
index 4a2d829..6622452 100644
--- a/crates/victory-shader/src/emit/valu_tests.rs
+++ b/crates/victory-shader/src/emit/valu_tests.rs
@@ -2057,3 +2057,337 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
2057 } 2057 }
2058 } 2058 }
2059} 2059}
2060
2061/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
2062const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
2063 [
2064 0x38 << 26 | (op as u32) << 18 | 1 << 13,
2065 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
2066 ]
2067}
2068
2069/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
2070const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] {
2071 [
2072 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
2073 (125 << 25) | (byte_offset & 0x1F_FFFF),
2074 ]
2075}
2076
2077/// Builds a compute shader whose descriptors live in a `RootType::Table` at
2078/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`).
2079fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader {
2080 let mut words = Vec::new();
2081 words.push(s_mov_b32(5, 0x80)); // s5 = 0
2082 words.extend_from_slice(body);
2083 words.push(S_ENDPGM);
2084 let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
2085 let native = NativeProgram {
2086 stage: HwStage::Cs,
2087 wave64: false,
2088 vgprs: 8,
2089 layout: vec![RootParam {
2090 root: RootType::Table,
2091 table_offset_dwords: 0,
2092 sgprs: 1,
2093 base_register: 0,
2094 user_data: 4,
2095 slot: 0,
2096 }],
2097 used,
2098 io: StageIo::Cs(ComputeIo {
2099 rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
2100 threads: [4, 1, 1],
2101 }),
2102 code,
2103 };
2104 let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
2105 let st = structure::structure(&p).expect("structure");
2106 let res =
2107 resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
2108 let io = io::raise(&p, &native).expect("io::raise");
2109 let lowered = lower::lower(&lower::Parts {
2110 native: &native,
2111 p: &p,
2112 st: &st,
2113 io: &io,
2114 res: &res,
2115 inputs: Vec::new(),
2116 outputs: Vec::new(),
2117 prims: Vec::new(),
2118 mesh_stride: 0,
2119 })
2120 .expect("lower");
2121 let shader = HostShader {
2122 stage: HwStage::Cs,
2123 dxil: lowered.dxil,
2124 user_data: lowered.user_data,
2125 samplers: lowered.samplers,
2126 static_samplers: Vec::new(),
2127 root_cbvs: lowered.root_cbvs,
2128 root_srvs: lowered.root_srvs,
2129 root_uavs: lowered.root_uavs,
2130 root_indexed_views: res.root_indexed_views,
2131 };
2132 if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
2133 let mut copy = shader.dxil.clone();
2134 v.validate(&mut copy).expect("DXIL validation failed");
2135 }
2136 shader
2137}
2138
2139/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds
2140/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA
2141/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit
2142/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`.
2143/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including
2144/// non-zero table offsets matching dynamic descriptor snapshots) on hardware
2145/// GPU and WARP.
2146#[test]
2147fn typed_d16_table_uav_roundtrip_uint_sint_and_float() {
2148 use windows::Win32::Graphics::Dxgi::Common::{
2149 DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT,
2150 DXGI_FORMAT_R16G16B16A16_UINT,
2151 };
2152 let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
2153 let mut body = Vec::new();
2154 // s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV),
2155 // s[16:19] = table[2] (raw UAV dump of loaded v[2:3]).
2156 body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
2157 body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
2158 body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64));
2159 // buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83)
2160 body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8));
2161 // buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87)
2162 body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12));
2163 // Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself.
2164 // v4 = v0 << 3 (byte offset = thread * 8)
2165 body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0
2166 // buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12)
2167 body.extend_from_slice(&[
2168 0x38 << 26 | 0x1D << 18 | 1 << 12,
2169 0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32,
2170 ]);
2171 let used = (0..3u32)
2172 .map(|k| UsedResource {
2173 kind: ResourceType::Uav,
2174 root: RootType::Table,
2175 table_offset_dwords: k * 8,
2176 lower_bound: k,
2177 stride: 4,
2178 dwords: 4,
2179 user_data: 4,
2180 slot: 0,
2181 })
2182 .collect();
2183 let shader = build_table_typed_cs(&body, used);
2184 assert!(
2185 shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
2186 "table typed d16 shader should request SLOT_TABLE_STRIDES"
2187 );
2188 assert!(
2189 !shader.root_srvs.contains(&super::SLOT_STRIDES),
2190 "table-only shader must not trigger the bindless SLOT_STRIDES sweep"
2191 );
2192
2193 // 4 elements x 4 u16 channels = 8 u32 dwords.
2194 // Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00),
2195 // NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns.
2196 let uint_bits: [u32; 8] = [
2197 0x3C00_0001, 0x7E00_BC00,
2198 0xFFFF_8000, 0xABCD_1234,
2199 0x0002_0000, 0x7BFF_FBFF,
2200 0xDEAD_BEEF, 0xCAFE_BABE,
2201 ];
2202 let sint_bits: [u32; 8] = [
2203 0xFFFF_8000, 0x7FFF_0001,
2204 0xC000_0000, 0x8001_7FFE,
2205 0xFFFF_FFFF, 0x0000_0000,
2206 0xFEDC_BA98, 0x7654_3210,
2207 ];
2208 // Normal finite FP16 values that round-trip cleanly through f32.
2209 let float_bits: [u32; 8] = [
2210 0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5
2211 0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0
2212 0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0
2213 0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0
2214 ];
2215 let zeros = [0u32; 8];
2216
2217 let cases = [
2218 ("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32),
2219 ("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32),
2220 ("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32),
2221 ("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32),
2222 ];
2223
2224 for (backend, warp) in [("hardware", false), ("warp", true)] {
2225 let Ok(host) = Host::new(warp) else { continue };
2226 let (root, pso) = host
2227 .compute_pipeline(&shader)
2228 .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
2229 for &(label, format, stride_word, input, base_slot) in &cases {
2230 let mut views = Vec::new();
2231 let mut strides = Vec::new();
2232 for _ in 0..base_slot {
2233 views.push(View::RawUav(1));
2234 strides.push(0u32);
2235 }
2236 let uav_base = base_slot as usize;
2237 views.push(View::TypedUav { data: input, format, elem_bytes: 8 });
2238 strides.push(stride_word);
2239 views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 });
2240 strides.push(stride_word);
2241 views.push(View::RawUav(8));
2242 strides.push(1);
2243
2244 let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
2245 for u in &shader.user_data {
2246 if u.root == RootType::Table && u.slot == 0 {
2247 ud[u.index as usize] = base_slot * 32;
2248 }
2249 }
2250 let out = host
2251 .dispatch(
2252 &root,
2253 &pso,
2254 &Dispatch {
2255 roots: vec![
2256 (0, Root::Constants(ud)),
2257 (1, Root::View { srv: true, data: strides }),
2258 ],
2259 views: &views,
2260 samplers: &[],
2261 groups: [1, 1, 1],
2262 },
2263 )
2264 .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
2265 assert_eq!(
2266 out[uav_base + 2],
2267 input,
2268 "{backend} {label}: buffer_load_format_d16_xyzw mismatch"
2269 );
2270 assert_eq!(
2271 out[uav_base + 1],
2272 input,
2273 "{backend} {label}: buffer_store_format_d16_xyzw mismatch"
2274 );
2275 }
2276 }
2277}
2278
2279/// Non-`d16` typed loads (`buffer_load_format_x`) are used by
2280/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut`
2281/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify
2282/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`.
2283#[test]
2284fn typed_non_d16_table_load_preserves_integer_bits() {
2285 use windows::Win32::Graphics::Dxgi::Common::{
2286 DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT,
2287 };
2288 let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
2289 let mut body = Vec::new();
2290 // s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out)
2291 body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
2292 body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
2293 // buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00)
2294 body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8));
2295 // v4 = v0 << 2 (byte offset = thread * 4)
2296 body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0
2297 // buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12)
2298 body.extend_from_slice(&[
2299 0x38 << 26 | 0x1C << 18 | 1 << 12,
2300 0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32,
2301 ]);
2302 let used = vec![
2303 UsedResource {
2304 kind: ResourceType::Srv,
2305 root: RootType::Table,
2306 table_offset_dwords: 0,
2307 lower_bound: 0,
2308 stride: 4,
2309 dwords: 4,
2310 user_data: 4,
2311 slot: 0,
2312 },
2313 UsedResource {
2314 kind: ResourceType::Uav,
2315 root: RootType::Table,
2316 table_offset_dwords: 8,
2317 lower_bound: 1,
2318 stride: 4,
2319 dwords: 4,
2320 user_data: 4,
2321 slot: 0,
2322 },
2323 ];
2324 let shader = build_table_typed_cs(&body, used);
2325 // Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no
2326 // CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep
2327 // identical DXIL and pipeline cache keys while still preserving raw bits.
2328 assert!(
2329 !shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
2330 "non-d16 typed load should not add SLOT_TABLE_STRIDES"
2331 );
2332
2333 let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32];
2334 let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF];
2335 let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [
2336 (
2337 "R16_UINT",
2338 DXGI_FORMAT_R16_UINT,
2339 2,
2340 &r16_data,
2341 [0x0001, 0x3C00, 0xBC00, 0xFFFF],
2342 ),
2343 (
2344 "R16_SINT",
2345 DXGI_FORMAT_R16_SINT,
2346 2,
2347 &r16_data,
2348 [0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF],
2349 ),
2350 (
2351 "R32_UINT",
2352 DXGI_FORMAT_R32_UINT,
2353 4,
2354 &r32_data,
2355 r32_data,
2356 ),
2357 ];
2358
2359 for (backend, warp) in [("hardware", false), ("warp", true)] {
2360 let Ok(host) = Host::new(warp) else { continue };
2361 let (root, pso) = host
2362 .compute_pipeline(&shader)
2363 .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
2364 for &(label, format, elem_bytes, input, want) in &cases {
2365 let views = [
2366 View::Buffer {
2367 data: input,
2368 stride: super::host::Stride::Format(format, elem_bytes),
2369 },
2370 View::RawUav(4),
2371 ];
2372 let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
2373 for u in &shader.user_data {
2374 if u.root == RootType::Table && u.slot == 0 {
2375 ud[u.index as usize] = 0;
2376 }
2377 }
2378 let out = host
2379 .dispatch(
2380 &root,
2381 &pso,
2382 &Dispatch {
2383 roots: vec![(0, Root::Constants(ud))],
2384 views: &views,
2385 samplers: &[],
2386 groups: [1, 1, 1],
2387 },
2388 )
2389 .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
2390 assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch");
2391 }
2392 }
2393}
diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs
index 6b7f861..ddc03dd 100644
--- a/crates/victory-shader/src/resource.rs
+++ b/crates/victory-shader/src/resource.rs
@@ -227,9 +227,9 @@ pub fn track(
227 let mut offset_at = 227 let mut offset_at =
228 std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new(); 228 std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
229 for (b, block) in p.blocks.iter().enumerate() { 229 for (b, block) in p.blocks.iter().enumerate() {
230 t.at.set(Some(b));
231 for (i, inst) in block.insts.iter().enumerate() { 230 for (i, inst) in block.insts.iter().enumerate() {
232 let site = (b, i); 231 let site = (b, i);
232 t.at.set(Some(site));
233 if let Some(value) = t.restored(inst, Some(b)) { 233 if let Some(value) = t.restored(inst, Some(b)) {
234 out.restored_lanes.insert(site, value); 234 out.restored_lanes.insert(site, value);
235 } 235 }
@@ -240,7 +240,7 @@ pub fn track(
240 let mut first_lane = Vec::new(); 240 let mut first_lane = Vec::new();
241 let mut offset = Vec::new(); 241 let mut offset = Vec::new();
242 let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { 242 let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
243 let source = t.descriptor(inst, op, b).map_err(fail)?; 243 let source = t.descriptor(inst, op, site).map_err(fail)?;
244 // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) 244 // A descriptor the code keeps per lane ([`Tracer::lane_copies`])
245 // is the same in every lane: its loop is lowered as it stands 245 // is the same in every lane: its loop is lowered as it stands
246 // and needs no proof. 246 // and needs no proof.
@@ -417,8 +417,8 @@ struct Tracer<'a> {
417 meets: std::cell::RefCell<Meets>, 417 meets: std::cell::RefCell<Meets>,
418 /// Reverse-postorder index per block. 418 /// Reverse-postorder index per block.
419 rpo: Vec<usize>, 419 rpo: Vec<usize>,
420 /// The block of the access being traced ([`Self::live`]). 420 /// The instruction site of the access being traced ([`Self::live`]).
421 at: std::cell::Cell<Option<usize>>, 421 at: std::cell::Cell<Option<Site>>,
422} 422}
423 423
424/// What lanes are known to satisfy: each [`Bool`] where its flag is set, 424/// What lanes are known to satisfy: each [`Bool`] where its flag is set,
@@ -1119,8 +1119,8 @@ impl<'a> Tracer<'a> {
1119 self.address(lo, hi, extra) 1119 self.address(lo, hi, extra)
1120 } 1120 }
1121 1121
1122 /// The source of the descriptor operand `op` of `inst`, in block `at`. 1122 /// The source of the descriptor operand `op` of `inst`, at `at`.
1123 fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> { 1123 fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> {
1124 let Operand::Scalar { code, dwords } = *op else { 1124 let Operand::Scalar { code, dwords } = *op else {
1125 return Err("a descriptor not in SGPRs"); 1125 return Err("a descriptor not in SGPRs");
1126 }; 1126 };
@@ -1135,8 +1135,14 @@ impl<'a> Tracer<'a> {
1135 { 1135 {
1136 words = raw.to_vec(); 1136 words = raw.to_vec();
1137 } 1137 }
1138 // Only the lanes that reach the access read the descriptor. 1138 // Only the lanes that reach and run the access read the descriptor.
1139 let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); 1139 let mut known = Vec::new();
1140 if let Some(l) = self.lanes {
1141 known.push((l.reach[at.0], true));
1142 if let Some(guard) = l.guards[at.0][at.1] {
1143 known.push((guard, true));
1144 }
1145 }
1140 self.classify(&words, &mut Vec::new(), &mut known) 1146 self.classify(&words, &mut Vec::new(), &mut known)
1141 } 1147 }
1142 1148
@@ -1288,7 +1294,10 @@ impl<'a> Tracer<'a> {
1288 let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { 1294 let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
1289 return t; 1295 return t;
1290 }; 1296 };
1291 let mut known = vec![(lanes.reach[at], true)]; 1297 let mut known = vec![(lanes.reach[at.0], true)];
1298 if let Some(guard) = lanes.guards[at.0][at.1] {
1299 known.push((guard, true));
1300 }
1292 for _ in 0..MAX_JOINS { 1301 for _ in 0..MAX_JOINS {
1293 let Term::Value(v) = t else { break }; 1302 let Term::Value(v) = t else { break };
1294 let Some((block, i)) = self.phis[v.0 as usize] else { 1303 let Some((block, i)) = self.phis[v.0 as usize] else {
@@ -4098,4 +4107,45 @@ pub(crate) mod tests {
4098 assert_eq!(r.waterfall.compares.len(), 2); 4107 assert_eq!(r.waterfall.compares.len(), 2);
4099 assert_eq!(r.waterfall.reads.len(), 4); 4108 assert_eq!(r.waterfall.reads.len(), 4);
4100 } 4109 }
4110
4111 #[test]
4112 fn a_guarded_access_excludes_dead_lane_edges_at_a_join() {
4113 // Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz`
4114 // directly to the join block without initializing the immediate
4115 // sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC,
4116 // so only the arm where `s[8:11]` was built can execute it.
4117 let code: Vec<u8> = [
4118 0xBE84_0300u32, // s_mov_b32 s4, s0
4119 0xBE85_0380, // s_mov_b32 s5, 0
4120 0xF40C_0302,
4121 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
4122 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
4123 0x7E06_0302, // v_mov_b32 v3, v2
4124 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
4125 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
4126 0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo
4127 0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords)
4128 0xBE88_0380, // s_mov_b32 s8, 0
4129 0xBE89_0380, // s_mov_b32 s9, 0
4130 0xBE8A_0380, // s_mov_b32 s10, 0
4131 0xBE8B_0380, // s_mov_b32 s11, 0
4132 0xF09C_0F08,
4133 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
4134 S_ENDPGM,
4135 ]
4136 .iter()
4137 .flat_map(|w| w.to_le_bytes())
4138 .collect();
4139 let p = crate::ir::build(&code, false, 256).unwrap();
4140 let structured = lanes(&p).expect("structured form");
4141 assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard");
4142 let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap();
4143 assert!(
4144 r.descriptors
4145 .iter()
4146 .any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])),
4147 "guarded join should resolve the immediate sampler from the live arm: {:?}",
4148 r.descriptors
4149 );
4150 }
4101} 4151}
diff --git a/docs/bug-journal.md b/docs/bug-journal.md
index 5922a6f..f41e72a 100644
--- a/docs/bug-journal.md
+++ b/docs/bug-journal.md
@@ -13,3 +13,7 @@
13- **15:56–15:59, reproducer and repair.** Replayed eight reported upload sizes through the release pool with a failing block allocator. The unpatched test made eight block creation attempts in one burst. Each pool now backs off growth for 500 ms after a failed creation while still reusing space in its existing blocks. An out-of-memory return from host upload or texture allocation interrupts the descriptor texture sweep, leaving interrupted work eligible for retry. The sweep checks available Windows commit at most once per 32 ms, including during a long pass. It defers ordinary prefetch below 4 GiB and bake prefetch below 2 GiB; explicitly bound textures can still request upload memory. GPU unit and device suite: 331 passed, 34 ignored. 13- **15:56–15:59, reproducer and repair.** Replayed eight reported upload sizes through the release pool with a failing block allocator. The unpatched test made eight block creation attempts in one burst. Each pool now backs off growth for 500 ms after a failed creation while still reusing space in its existing blocks. An out-of-memory return from host upload or texture allocation interrupts the descriptor texture sweep, leaving interrupted work eligible for retry. The sweep checks available Windows commit at most once per 32 ms, including during a long pass. It defers ordinary prefetch below 4 GiB and bake prefetch below 2 GiB; explicitly bound textures can still request upload memory. GPU unit and device suite: 331 passed, 34 ignored.
14- **16:00–16:03, first opening-save retest.** Windows Graphics Capture showed a character, textured buildings and street lighting. The log contained no failed upload-buffer allocations or Rust allocation aborts. The harness timed out during shutdown and lost its timing receipt. The renderer logged a dropped draw due to exhausted dynamic descriptor slots. 14- **16:00–16:03, first opening-save retest.** Windows Graphics Capture showed a character, textured buildings and street lighting. The log contained no failed upload-buffer allocations or Rust allocation aborts. The harness timed out during shutdown and lost its timing receipt. The renderer logged a dropped draw due to exhausted dynamic descriptor slots.
15- **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`. 15- **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`.
16- **16:50–18:20, facial deformation & wrapped meshes (`d16` + table strides).** Added zero-sweep table view-kind lookup (`SLOT_TABLE_STRIDES = 252`, `heap_strides`) and dynamic descriptor slot stride population in `descriptor/host.rs`, plus NVIDIA-valid typed integer lowering (`bufferLoad.i32`/`bufferStore.i32` on `VIEW_INTEGER`/`VIEW_SIGNED`). Initially applying typed integer branching to non-`d16` typed loads caused shader regressions; restricting integer branching to `buffer_load_format_d16_*` and `buffer_store_format_d16_*` restored clean shading while keeping `VICTORY_TRANSLATOR` cache-compatible with `tools/cache-pareto` (`made=0`).
17- **19:15–20:30, commit-gate starvation & synchronous bake uploads.** Lowered commit reserves (`has_upload_reserve`: 256 MiB bake / 512 MiB non-bake; `has_growth_reserve`: 256 MiB bake / 1024 MiB speculative bindless; pressure entry 3 GiB RAM / 4 GiB commit, recovery 5 GiB / 6 GiB), scoped 64 MiB staging-block growth gating in `pool.rs` (`REST = 2500 ms`) to speculative bindless only, expanded bake detection (`BAKE_GEOMETRY_SHADERS`, `ahead::drain`, `BAKE_PAGE_WRITTEN`), and routed one-shot ped/decoration bake uploads through a dedicated synchronous host list (`BAKE_UPLOAD` / `execute_sync_internal`) with post-upload descriptor publication (`prepare_bake_slot` / `publish_uploaded_slot`). GPU suite: 335 passed, 34 ignored.
18- **20:50–21:10, alias-flood experiment reverted & clean release built.** Propagating aliased view maps/unmaps into `REMAPPED` and widening bake lookahead caused 2–4 GiB bake-pass truncations on frames 1368–1369 (`cap_alias_fix_rel`, median 70.5 ms in diagnostics capture, face-mask/shorts regression) and was reverted. Rebuilt clean release binary `target/release/victory.exe` without the alias flood (SHA-256 `38e99f1b1d6bafda2ff8de74d6566af06bc7e8cab70594d841af01752e501d73`); installation into `Downloads/leonida/victory-3d-rtx-pareto-residency.exe` deferred while user-launched PID 13544 holds the file open.
19- **21:30–22:28, transmission prefilter Wave32 recovery, texture-starvation & scene-blinking fixes.** Diagnosed four linked regressions on RTX 5090 (32 GiB RAM): (1) `alphaResolve:CS_AlphTransmissionPrefilterMip_610a2fad` (`2da4beb386509b77`) was dropped under Wave32 `without_early_outs` because `resource::Tracer::descriptor()` and `live()` omitted per-instruction `lanes.guards[b][i]` when pruning dead join edges, leaving transmission buffer `0x17dff443d70` zeroed and causing `ptfx_PS_Transmission_aba1527f` (dual-source blend) and transmissive eye/alpha shaders to output black squares / corrupted blending; fixed in `crates/victory-shader/src/resource.rs` (`VICTORY_WAVE_WIDE` intentionally kept off due to known loop-widening TDR risk). (2) Completed submissions kept `Detached._state` dynamic descriptor slots pinned across `bury_lag()` (`16` submissions) in `host.rs` (`relay_land`, `settle`), exhausting NVIDIA's 262k dynamic slot pool and dropping draws; added `Detached::release_tables()` right on GPU completion plus a `settle_for_fence()` retry in `draw.rs`, and defaulted `VICTORY_INDIRECT_REST=0` in `indirect.rs` so one oversized indirect record does not zero out subsequent draws. (3) Split residency throttling into mild pressure vs. `critical_commit()` (`< 1536 MiB` commit or upload refusal) across `residency.rs`, `texture/ahead.rs`, and `pool.rs` so `VICTORY_UPLOAD_AHEAD`, `64 MiB/frame` prefetch, and one spare staging block stay active under mild 32 GiB pressure instead of stalling tens of thousands of textures on `neutral()`; fixed `descriptor/host.rs` (`prepare_bake_slot`, `publish_uploaded_slot`) and `draw.rs` (`flush_for_bake`) so pending bake slots are never prematurely overwritten with `neutral()` or silently dropped on defer/unmapped pages, and removed false `address=0x0` unordered-SRV warning spam. (4) Scoped `VICTORY_AMBIENT_AIR=1.5` to `pareto-residency` in `Downloads/leonida/Play-VIctory.cmd` to clear milky indoor ambient haze. Verification: `victory-shader` lib suite 281 passed, 0 failed, 4 ignored (including new `a_guarded_access_excludes_dead_lane_edges_at_a_join`); targeted `victory-gpu` suite 20 passed, 0 failed; RTX 5090 `translate --jobs 1 --validate --pipelines` on 154 VFX/particle/eye shaders emitted & validated 43/43 graphics + 96/111 compute pipelines (recovering `CS_AlphTransmissionPrefilterMip`, 0 regressions). Deployed release binary to `Downloads/leonida/victory-3d-rtx-pareto-residency.exe`, SHA-256 `37a410b13fcd5ef4cecfe2c27761b7132af64b00019a07c9256529b96892d7da`.