From 8b2efa9f292cf477a52ed3bd4982c673803a9185 Mon Sep 17 00:00:00 2001 From: pablogonz12 Date: Wed, 25 Nov 2026 20:54:09 +0100 Subject: [PATCH 1/3] Shaders: view slots the title made itself stay below the host's dynamic slots The host's view heap mirrors the title's slots first and then keeps the dynamic slots tables are made afresh in. Translated shaders clamped every view index at the heap's end only, so an index the title made itself (a descriptor pointer read out of its memory: root type `ResourceHeap`, not a table) that lay past the title's slots named a live dynamic descriptor of ours: another table's constant buffer, or a raw view. The title's heap is larger than a host that caps heaps at 1,000,000 views takes (1,245,184 views here), so the title's slots give way there and such indices are exactly the ones past the mirror. Shaders now clamp an index whose every path comes from the resource heap itself below the dynamic slots, to the heap's null slot; a table's index keeps the heap-wide clamp, because a table made afresh lies at a dynamic slot. The dynamic slots also sit a fixed 2^18 below the null slot rather than right after the title's, which is a place a shader knows before the title makes its heap (shaders are translated first): `view_layout` does both and asserts the count the shaders assume. `VICTORY_TITLE_VIEW_CLAMP=0` leaves the clamp out and the dynamic slots right after the title's, as before. Reimplemented from Marvisak/VIctory PR #2628 (moe-miau), which clamps the same two ways on the portable heap. Co-authored-by: moe-miau <358733453+moe-miau@users.noreply.github.com> --- CREDITS.md | 5 ++ crates/victory-gpu/src/descriptor/host.rs | 98 +++++++++++++++------ crates/victory-shader/src/emit/bitcode.rs | 41 +++++++++ crates/victory-shader/src/emit/intersect.rs | 2 +- crates/victory-shader/src/emit/lower.rs | 16 ++-- crates/victory-shader/src/emit/mod.rs | 9 +- crates/victory-shader/src/emit/shader.rs | 53 ++++++++++- crates/victory-shader/src/resource.rs | 7 ++ 8 files changed, 196 insertions(+), 35 deletions(-) diff --git a/CREDITS.md b/CREDITS.md index 8f3df631..313eaf2c 100644 --- a/CREDITS.md +++ b/CREDITS.md @@ -37,6 +37,11 @@ BlueKaiman. GPL-3.0: narrowing a host shader resource view of a streamed texture to the mips whose memory is there, and remaking it when more levels arrive or a host copy fills the chain (`crates/victory-gpu/src/texture.rs`, `crates/victory-gpu/src/descriptor/host.rs`). +- **Marvisak/VIctory** ([#2628](https://github.com/Marvisak/VIctory/pull/2628)), GPL-3.0, by moe-miau: + the host's dynamic view-heap slots stay a fixed distance below the heap's null slot, and a view + index the title made itself is clamped below them, so a title whose heap is larger than the host's + cannot name one of the host's own tables (`crates/victory-shader/src/emit/shader.rs`, + `crates/victory-shader/src/emit/lower.rs`, `crates/victory-gpu/src/descriptor/host.rs`). ## Tools diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 28994fb5..cc783755 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -19,6 +19,9 @@ pub(crate) struct HostHeap { step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, + /// The first dynamic slot: the title's slots, then unused ones up to + /// this, then the dynamic range (see [`view_layout`]). + base: u32, /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) @@ -603,6 +606,36 @@ pub(crate) fn probe_view_limit() { /// table past them is made afresh in these slots like any other. pub(crate) const DYNAMIC: u32 = 1 << 18; +/// The title slots a view heap that the title asked `requested` slots of has +/// room for, the first dynamic slot, and the heap's size; `null` is the last +/// slot of the heap, which shaders clamp view indices to (0: no host limit +/// probed). +/// +/// The dynamic slots sit a fixed distance below the null slot, not right +/// after the title's: shaders are translated before the title makes its heap +/// and clamp the view slots the title made itself below them +/// (`victory_shader`'s `title_view_limit`), so a title heap larger than the +/// room left must not put the title's slots where the dynamic ones are. +/// Upstream PR #2628 (moe-miau) for the same layout. +fn view_layout(requested: u32, null: u32) -> (u32, u32, u32) { + view_layout_with(requested, null, victory_shader::emit::title_view_clamp()) +} + +/// [`view_layout`], with the title clamp's switch given. +fn view_layout_with(requested: u32, null: u32, clamp: bool) -> (u32, u32, u32) { + if null == 0 { + return (requested, requested, requested + DYNAMIC); + } + let size = null + 1; + let base = null.saturating_sub(DYNAMIC); + if !clamp { + // Switched off: the dynamic slots follow the title's, as before. + let fitted = if requested + DYNAMIC <= null { requested } else { base }; + return (fitted, fitted, size); + } + (requested.min(base), base, size) +} + /// A slot the host made from a view narrowed to a part-resident texture's /// mips ([`narrow_to_resident`]): the texture, the window the title asked /// for and the one the host view names. @@ -651,30 +684,18 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; - let (heap, count, size) = if null == 0 { - match make(count + extra) { - Ok(heap) => (heap, count, count + extra), - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } - } else { - let size = null + 1; - let fitted = if count + extra <= null { - count - } else { - // shortcut: descriptors past the host's limit are left out; a title that reaches - // them needs remapping. They read the null slot instead. - tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); - null - extra - }; - match make(size) { - Ok(heap) => (heap, fitted, size), - Err(e) => { - tracing::warn!(error = %e, count, size, "no host view heap"); - return None; - } + let requested = count; + let (count, base, size) = view_layout(requested, null); + if null != 0 && count < requested { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(requested, count, size, "host view heap capped at {size}; views past it read a null slot"); + } + let heap = match make(size) { + Ok(heap) => heap, + Err(e) => { + tracing::warn!(error = %e, count, size, sampler, "no host descriptor heap"); + return None; } }; // SAFETY: a live heap. @@ -711,12 +732,13 @@ impl HostHeap { cpu, step, count, + base, dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), narrowed: Mutex::default(), narrowed_count: std::sync::atomic::AtomicUsize::new(0), - kept: Mutex::new(vec![None; (count + extra) as usize]), + kept: Mutex::new(vec![None; size as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), free: std::sync::atomic::AtomicU32::new(DYNAMIC), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), @@ -854,7 +876,7 @@ impl HostHeap { taken[first..first + n].fill(true); self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); *next = ((first + n) % DYNAMIC as usize) as u32; - Some(self.count + first as u32) + Some(self.base + first as u32) } /// The title slots this heap has host slots for; fewer than the title's @@ -1182,7 +1204,7 @@ impl HostHeap { /// /// [`dynamic`]: HostHeap::dynamic pub(crate) fn release(&self, first: u32, n: u32) { - let Some(at) = first.checked_sub(self.count) else { + let Some(at) = first.checked_sub(self.base) else { return; }; let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); @@ -2632,6 +2654,28 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// The host's dynamic slots sit below the null slot that shaders clamp + /// view indices to, never right after the title's, so an index the title + /// made itself past its slots cannot name one of them. The count shaders + /// assume is the GPU's `DYNAMIC`. + #[test] + fn dynamic_slots_sit_below_the_null_slot() { + assert_eq!(DYNAMIC, victory_shader::emit::DYNAMIC_VIEWS); + let limit = (1 << 21) - 1; + // A title heap that fits: its own slots stay, the dynamic ones below null. + assert_eq!(view_layout_with(1_245_184, limit, true), (1_245_184, limit - DYNAMIC, limit + 1)); + // A capped host (1,000,000 slots): the title's slots give way. + let portable = 1_000_000 - 1; + let (count, base, size) = view_layout_with(1_245_184, portable, true); + assert_eq!((count, base, size), (portable - DYNAMIC, portable - DYNAMIC, portable + 1)); + // A small title heap: the dynamic slots still lie below null. + assert_eq!(view_layout_with(100, limit, true), (100, limit - DYNAMIC, limit + 1)); + // No host heap probed: the dynamic slots follow the title's. + assert_eq!(view_layout_with(100, 0, true), (100, 100, 100 + DYNAMIC)); + // Switched off: as before, the dynamic slots follow the title's. + assert_eq!(view_layout_with(100, limit, false), (100, 100, limit + 1)); + } + /// A null texture UAV keeps the title's dimension (3D for the world's /// wind field), and is 2D when the title names none. #[test] diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index eff0ac08..1165f443 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -1047,6 +1047,47 @@ impl Writer { mod tests { use super::*; + /// A view slot the title made itself, on a host heap whose dynamic slots + /// follow the title's, reads the heap's null slot instead of one of the + /// host's tables (upstream PR #2628, moe-miau). + #[test] + fn title_view_indices_past_the_title_slots_read_the_null_slot() { + use crate::emit::DYNAMIC_VIEWS; + use crate::emit::shader::Shader; + + let mut s = Shader::new(false); + let index = s.m.undef(s.t.i32); + // No host heap probed: an index is left as the title made it. + assert_eq!(s.clamp_title_heap_index(s.entry, index), index); + // A heap of 1,000,000 slots (NVIDIA's cap): the title's slots, then + // the host's dynamic ones, then the null slot. + let limit = 1_000_000 - 1; + s.view_limit = limit; + let V::Inst(selected) = s.clamp_title_heap_index(s.entry, index) else { + panic!("a select") + }; + // A constant's value, as the module holds it. + fn value(m: &Module, v: V) -> i64 { + match v { + V::Const(i) => match m.consts[i as usize].1 { + Const::Int(x) => x, + _ => panic!("an integer constant"), + }, + _ => panic!("a constant"), + } + } + let Op::Select(over, t, f) = s.m.insts[selected as usize].op else { + panic!("a select") + }; + assert_eq!((value(&s.m, t), f), (i64::from(limit as i32), index)); + let V::Inst(over) = over else { panic!("a compare") }; + let Op::Cmp(pred, a, b) = s.m.insts[over as usize].op else { + panic!("a compare") + }; + assert_eq!((pred, a), (pred::IUGT, index)); + assert_eq!(value(&s.m, b), i64::from((limit - DYNAMIC_VIEWS - 1) as i32)); + } + #[test] fn vbr_and_blocks() { let mut w = Writer::default(); diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 78a1d99e..1e51a9fc 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -233,7 +233,7 @@ impl<'a> Lower<'a> { // which is zeros. let c = self.cur; let slot = self.s.m.i32(slot); - let handle = self.s.heap_handle(c, slot, false, false, (11, 0)); + let handle = self.s.heap_handle(c, slot, false, false, (11, 0), false); let (base_low, base_high) = (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32)); let at = self.s.m.bin(c, Bin::Sub, low, base_low); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d066b662..a6b54ff5 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2865,7 +2865,7 @@ impl<'a> Lower<'a> { ); let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); - let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0), false); let k64k = k(self, 0xFFFF); let within = self.s.m.bin(c, Bin::And, lo, k64k); let byte = self.s.m.bin(c, Bin::Add, start, within); @@ -6361,6 +6361,12 @@ impl<'a> Lower<'a> { sampler: bool, props: (u32, u32), ) -> Result { + // An index the title made itself may not name a host slot. + let from_heap = !sampler && src.heap_only(|s| { + matches!(s, Source::Loaded { load, .. } if self + .scalar.get(load).and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap)) + }); match src { Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props); @@ -6373,7 +6379,7 @@ impl<'a> Lower<'a> { let per_lane = self.x.res.waterfall.loads.contains(load); let h = self .s - .heap_handle(self.cur, index, sampler, per_lane, props); + .heap_handle(self.cur, index, sampler, per_lane, props, from_heap); self.handles.insert(key, h); Ok(h) } @@ -6434,7 +6440,7 @@ impl<'a> Lower<'a> { Source::Phi { block, args } => { let _ = site; let phi = self.descriptor_phi(*block, args, sampler, 8)?; - Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props, from_heap)) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -6452,14 +6458,14 @@ impl<'a> Lower<'a> { let set = self.heap_index(a, fa, sampler)?; let clear = self.heap_index(b, fb, sampler)?; let index = self.s.m.select(self.cur, cond, set, clear); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + Ok(self.s.heap_handle(self.cur, index, sampler, false, props, from_heap)) } Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. let index = self.lane_heap_index(src, sampler)?; - Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + Ok(self.s.heap_handle(self.cur, index, sampler, true, props, from_heap)) } } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d7641587..711c3566 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -115,9 +115,16 @@ pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, - set_view_heap_limit, view_heap_limit, + set_view_heap_limit, title_view_clamp, title_view_limit, view_heap_limit, }; +/// The host's dynamic slots in a view heap (`victory-gpu`'s `DYNAMIC`): tables +/// a draw needs made afresh are made there. They follow the title's slots, at +/// a place shaders know before the title's heap is made, so a shader that +/// names a view slot the title made itself is clamped below them +/// ([`title_view_limit`]) instead of naming one of the host's tables. +pub const DYNAMIC_VIEWS: u32 = 1 << 18; + /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 1b31b6eb..5efffc06 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -130,10 +130,38 @@ pub fn view_heap_limit() -> u32 { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) } +/// Whether shaders clamp the view slots the title made itself below the +/// host's dynamic slots ([`title_view_limit`]). `VICTORY_TITLE_VIEW_CLAMP=0` +/// turns it off, and `victory-gpu` then keeps its dynamic slots right after +/// the title's, as before. +pub fn title_view_clamp() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TITLE_VIEW_CLAMP").is_none_or(|v| v != "0")) +} + +/// The slots a view index the title made itself may name: the host's view +/// heap less its dynamic slots ([`super::DYNAMIC_VIEWS`]), which follow the +/// title's. 0: no separate limit (no host heap probed, a heap with no room +/// for both, or the clamp is off). +pub fn title_view_limit() -> u32 { + if !title_view_clamp() { + return 0; + } + title_view_limit_of(view_heap_limit()) +} + +/// [`title_view_limit`] for a heap whose last slot is `limit`. +fn title_view_limit_of(limit: u32) -> u32 { + if limit > super::DYNAMIC_VIEWS + 1 { limit - super::DYNAMIC_VIEWS } else { 0 } +} + pub(crate) struct Shader { pub m: Module, pub t: Types, pub pixel: bool, + /// The last slot of the host's view heap when this shader is translated + /// ([`view_heap_limit`]; 0: none), which its view indices are clamped to. + pub view_limit: u32, pub inputs: Vec, pub outputs: Vec, /// A mesh shader's per-primitive outputs. @@ -200,6 +228,7 @@ impl Shader { res_ret, }, pixel, + view_limit: VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed), inputs: Vec::new(), outputs: Vec::new(), prims: Vec::new(), @@ -392,6 +421,25 @@ impl Shader { ) } + /// A view index the title made itself (every path to the descriptor is the + /// resource heap itself, not a table): on a host whose dynamic slots + /// follow the title's ([`title_view_limit`]), an index past the title's + /// slots reads the heap's null slot instead of naming one of the host's + /// tables. A table's index may name a dynamic slot and is not clamped + /// here, only at the heap's end ([`Self::heap_handle`]). + pub fn clamp_title_heap_index(&mut self, block: usize, index: V) -> V { + let limit = if title_view_clamp() { title_view_limit_of(self.view_limit) } else { 0 }; + if limit == 0 { + return index; + } + let last = self.m.i32(limit - 1); + let over = self.m.cmp(block, super::bitcode::pred::IUGT, index, last); + let null = self.m.i32(self.view_limit); + let v = self.m.select(block, over, null, index); + self.m.tag(v, super::bitcode::Tag::Clamp); + v + } + /// A descriptor heap handle, annotated with `props`; `nonuniform` when /// the index may differ between lanes (`NonUniformResourceIndex`). pub fn heap_handle( @@ -401,9 +449,12 @@ impl Shader { sampler: bool, nonuniform: bool, props: (u32, u32), + from_heap: bool, ) -> V { + // An index the title made itself (not a table's) may not name a host slot. + let index = if from_heap && !sampler { self.clamp_title_heap_index(block, index) } else { index }; // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead - let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + let limit = self.view_limit; // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) let index = if !sampler && limit != 0 { let null = self.m.i32(limit); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2b6edd46..76db123c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -109,6 +109,13 @@ impl Source { s => vec![s], } } + + /// Whether every path to this descriptor reads the resource heap itself + /// (an index the title made, not a table), when `heap` says so of a leaf. + pub fn heap_only(&self, heap: impl Fn(&Self) -> bool) -> bool { + let l = self.leaves(); + !l.is_empty() && l.iter().all(|s| heap(s)) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] From b57ca4f31a40c06ec5b58672bfdceb6b03707912 Mon Sep 17 00:00:00 2001 From: pablogonz12 Date: Wed, 25 Nov 2026 21:30:21 +0100 Subject: [PATCH 2/3] GPU tests: dynamic slots are counted from their own base The dynamic slots no longer follow the title's mirrored slots, so the test that holds and gives back a run reads the heap's `base` instead of its count (`4` for a 4-slot title heap). --- crates/victory-gpu/src/descriptor/host.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index a700768e..5cebbf05 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -3161,13 +3161,15 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; + // The dynamic slots start at `base`, not right after the title's 4. + let base = heap.base; let a = heap.dynamic(heap.dynamic - 100).unwrap(); let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + assert_eq!((a, b), (base, base + heap.dynamic - 100)); // 40 left at the end: 50 do not fit until something is given back. assert_eq!(heap.dynamic(50), None); heap.release(a, 50); - assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + assert_eq!(heap.dynamic(50), Some(base)); + assert_eq!(heap.dynamic(40), Some(base + heap.dynamic - 40)); } } From 17bbc44b10ebf67164cf0498fa831be89df770ec Mon Sep 17 00:00:00 2001 From: pablogonz12 Date: Thu, 26 Nov 2026 12:11:27 +0100 Subject: [PATCH 3/3] Shaders: VICTORY_TITLE_VIEW_CLAMP joins the translation switches The switch changes emitted DXIL (the title view clamp), so it belongs in the cache's key: the key test failed on it. --- crates/victory-shader/src/emit/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 17487426..5f612c06 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -280,6 +280,7 @@ pub const SWITCHES: &[&str] = &[ "VICTORY_SHADER_LOOP_LIMIT_CS", "VICTORY_SHADER_OPT", "VICTORY_STRICT_JOINS", + "VICTORY_TITLE_VIEW_CLAMP", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_LOCAL", "VICTORY_WAVE_OWN_BITS",