From 30f46c92a974514ba0a90acc36c814c237c002bc Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:40 -0600 Subject: [PATCH 1/6] Structure builder: fences around its buffer atomics (VICTORY_BVH_FENCES=0: none) Its threads take turns through atomics; what one wrote before its atomic has to be seen by the one after it. The console's waits for writes are not in the translated code. After beloooo's 72e748ea (VIctory-Belobug-AMD). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-shader/src/emit/lower.rs | 20 ++++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 8 ++++++++ 3 files changed, 29 insertions(+) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index d5cf03f..35b5446 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -73,6 +73,7 @@ fn build() -> [u8; 32] { "VICTORY_FIRST_HALF", "VICTORY_STRICT_JOINS", "VICTORY_MESH_OUTPUT_STRICT", + "VICTORY_BVH_FENCES", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..ecad742 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5230,6 +5230,17 @@ impl<'a> Lower<'a> { let void = self.s.t.void; self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } + // The structure builder's threads take turns through atomics (a tree + // built from its leaves up): what one wrote before its atomic is + // seen by the thread that comes after it. The console's program + // waits for its writes there, and those waits are not in the code + // here (after beloooo's 72e748ea, VIctory-Belobug-AMD). + let ordered = (name.starts_with("buffer_atomic") || name.starts_with("global_atomic")) + && crate::spill::is_spilled(self.x.native) + && super::builder_fences(); + if ordered { + self.memory_fence(); + } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), @@ -5275,6 +5286,9 @@ impl<'a> Lower<'a> { Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), Fields::Flat { .. } => Err("flat memory"), }; + if ordered && r.is_ok() { + self.memory_fence(); + } match r { Ok(()) => Ok(()), Err(why) if effect => Err(unsupported(offset, why)), @@ -5287,6 +5301,12 @@ impl<'a> Lower<'a> { } } + /// Writes to buffers made before are seen, by every group, before those made after. + fn memory_fence(&mut self) { + let (mode, void) = (self.s.m.i32(2), self.s.t.void); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + /// The two host waves of a console wave meet (a group barrier with a shared-memory /// fence): LDS writes before are seen by reads after. fn lds_meeting(&mut self) { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..b714dc6 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -180,6 +180,14 @@ pub fn group_sync() -> u8 { }) } +/// Whether buffer atomics of the ray-tracing structure builder stand between +/// two fences (`VICTORY_BVH_FENCES=0`: they do not). Part of the +/// translation: the shader cache keys on it. +pub fn builder_fences() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_FENCES").is_none_or(|v| v != "0")) +} + /// The clean-up passes that run over a translated program before it is /// written (`bitcode::opt`): a set of that module's pass bits. Every pass /// is exact, so the switch is for telling a translator fault from a From a50c7fdeb55eca4a27c70151b4154665c32e22e9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:41 -0600 Subject: [PATCH 2/6] Replay: buffers in heaps opened from memory are made again (without the cross-adapter flag) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/replay/play.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b823576..b157414 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -735,7 +735,11 @@ impl Player { let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64)); *m = (m.0 + 1, m.1 + r.desc.width); } - let desc = gpu::to_desc(&r.desc); + let mut desc = gpu::to_desc(&r.desc); + // (Heaps are made without what let others open them.) + if matches!(r.place, Place::Placed { .. }) { + desc.Flags &= !D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } let mut made: Option = None; let clear: Option = r.clear.map(|c| { // SAFETY: 20 bytes that were a clear value. From 2c20d7a6e31f8bcfa3d9d0b62942ee7df0a7edc2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:43 -0600 Subject: [PATCH 3/6] Structure builder: submissions that ask for structures' sizes are waited for (VICTORY_BVH_SIZES_WAIT=0: not); a packed structure is one node longer; VICTORY_BVH_TRACE The title reads a new structure's compacted size a frame or two after it asked, takes memory of that size and copies the structure there. It read the size the slot held before: the copies wrote over their neighbours (run light-11). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/host.rs | 3 + crates/victory-gpu/src/memory.rs | 159 ++++++++++++++++++++++++++++++- 3 files changed, 161 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9889269..c1bbae5 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1260,7 +1260,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &written, &constants, use_) + crate::memory::ready(list, heap, &addresses, &written, &constants, use_, t.threads) } /// The bound heap holding `handle`. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..58c8171 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4906,6 +4906,7 @@ impl Host { return; }; let told = !sent.writes.is_empty(); + let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; @@ -4928,6 +4929,8 @@ impl Host { RELAY_MOVED.notify_one(); if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); + } else if sizes { + self.settle(&mut submitted, WHY_READ); } else if most && relay_exact() { // Until there are fewer, not until there are none. relay_wait(WHY_MOST, |line| line.lists < late_most()); diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 65a2cd7..441990a 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -181,6 +181,8 @@ struct Memory { stats: Stats, #[cfg(feature = "diagnostics")] dump: dump::Dump, + #[cfg(feature = "diagnostics")] + trace: trace::Trace, } /// Since the last report. @@ -254,6 +256,8 @@ impl Memory { stats: Stats::default(), #[cfg(feature = "diagnostics")] dump: Default::default(), + #[cfg(feature = "diagnostics")] + trace: Default::default(), }) } @@ -789,6 +793,49 @@ impl Memory { } } +/// A list with this key ([`HostList::used`]) asks the builder for sizes. +const SIZES: usize = usize::MAX - (9 << 33); + +/// Whether a submission that asks for the sizes of structures is waited for, +/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=0`: it is +/// not). +/// +/// The title asks for a new structure's compacted size (a program of one +/// thread stores it into a small buffer), reads it a frame or two later +/// without looking whether it is there, takes memory of that size and copies +/// the structure into it. With submissions that land up to two frames late it +/// read what the slot held before, some other structure's size, and the copy +/// wrote over its neighbours: of 230 such copies of run light-11, 99 were +/// asked for two frames earlier and landed in that frame, none of those with +/// the right size. +fn sizes_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a dispatch of the builder is its program of a structure's size: +/// one thread, the structure's address and what to store (1: the compacted +/// size) as constants, a small title buffer to store into. +fn asks_size(written: &[u64], constants: &[u32], threads: Option<[u32; 3]>) -> bool { + threads == Some([1, 1, 1]) + && matches!(*constants, [_, hi, 1..=3, ..] if (1..0x20).contains(&hi)) + && written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK)) +} + +/// Whether one of `lists` asks for sizes. +pub(crate) fn asked_sizes<'a>(lists: impl Iterator) -> bool { + let mut lists = lists; + let asked = sizes_wait() && lists.any(|l| l.used(SIZES)); + if asked { + static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() || n.is_multiple_of(100) { + tracing::info!(n, frame = crate::frame::current(), "submissions that ask for structures' sizes, waited for"); + } + } + asked +} + /// [`fill`] of a page stores by address do not reach. fn close(entry: *mut u32, n: usize, offset: u64) { fill(entry, n | MEMORY_READ_ONLY as usize, offset); @@ -809,7 +856,10 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { fn packed_len(header: u64) -> Option { let (version, nodes) = (header as u32, header >> 32); let marks = version >> 16; - (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && nodes * 64 <= PACKED).then_some(nodes * 64) + // The header counts its nodes of 64 bytes without the last one: the + // builder's own program of a structure's size stores one more. + let len = (nodes + 1) * 64; + (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len) } /// Puts what `title` holds into `ours` (what was last taken): the dwords that @@ -845,6 +895,7 @@ pub(crate) fn ready( written: &[u64], constants: &[u32], use_: Use, + threads: Option<[u32; 3]>, ) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { @@ -858,8 +909,17 @@ pub(crate) fn ready( m.take_faults(); m.look_again(); m.report(); + #[cfg(feature = "diagnostics")] + m.trace.look(frame); + } + #[cfg(feature = "diagnostics")] + if use_ != Use::Reads { + m.trace.dispatch(frame, list, addresses, written, constants, threads); } let builds = use_ != Use::Reads; + if builds && sizes_wait() && asks_size(written, constants, threads) { + list.first_use(SIZES); + } while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {} m.stats.uses[usize::from(builds)] += 1; // Once per list and page named: the builder dispatches hundreds of times @@ -1004,6 +1064,101 @@ pub(crate) fn ready( }) } +/// `VICTORY_BVH_TRACE=1`: the sizes the builder is asked for (its program of +/// one thread that stores a structure's compacted size) and when title memory +/// has them, and the copies to a place of that size. +#[cfg(feature = "diagnostics")] +mod trace { + use super::*; + + #[derive(Default)] + pub(super) struct Trace { + /// Frame, where the size goes, the structure, what title memory had. + asked: Vec<(u64, u64, u64, u64)>, + /// By structure, what its size was when last seen to change. + sizes: HashMap, + said: u32, + } + + fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_TRACE").is_some_and(|v| v == "1")) + } + + fn value(at: u64) -> u64 { + let mut b = [0u8; 8]; + crate::host::copy_mapped(b.as_mut_ptr(), at as *const u8, 8, false); + u64::from_le_bytes(b) + } + + impl Trace { + fn say(&mut self, text: String) { + self.said += 1; + if self.said < 6000 { + tracing::info!("bvh trace: {text}"); + } + } + + pub(super) fn look(&mut self, frame: u64) { + if !on() { + return; + } + let mut gone = Vec::new(); + for i in 0..self.asked.len() { + let (then, at, structure, was) = self.asked[i]; + let now = value(at); + if now != was { + self.sizes.insert(structure, (now, frame)); + gone.push(i); + self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: {was:#x} -> {now:#x}")); + } else if frame > then + 60 { + gone.push(i); + self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: still {was:#x}")); + } + } + for i in gone.into_iter().rev() { + self.asked.swap_remove(i); + } + } + + pub(super) fn dispatch( + &mut self, + frame: u64, + list: &HostList, + addresses: &[u64], + written: &[u64], + constants: &[u32], + threads: Option<[u32; 3]>, + ) { + if !on() { + return; + } + let _ = addresses; + let list = std::ptr::from_ref(list) as usize & 0xFFFF_FFFF; + if threads == Some([1, 1, 1]) + && let [lo, hi, mode, ..] = *constants + && (1..=3).contains(&mode) + && hi < 0x20 + && let Some(&at) = written.first() + && crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK) + { + let structure = u64::from(lo) | u64::from(hi) << 32; + let was = value(at); + self.say(format!("frame {frame} list {list:x}: asks mode {mode} of {structure:#x} to {at:#x}, there {was:#x}")); + if mode == 1 { + self.asked.push((frame, at, structure, was)); + } + } else if threads == Some([32, 1, 1]) + && let [from, to] = *written + && [from, to].iter().all(|&a| a >= 1 << 32 && crate::shadow::in_buffer(a, 1).is_none()) + { + let known = self.sizes.get(&from).copied(); + self.say(format!("frame {frame} list {list:x}: copies {from:#x} to {to:#x} constants {:x?}, its size was {known:x?}", &constants[..constants.len().min(4)])); + } + } + } +} + /// `VICTORY_MEMORY_DUMP=`: when a file `go` appears there, the arenas /// as the card holds them are copied out and written (`arena-.bin`), with /// `pages.txt` (title page, arena, offset) and the structures the walking @@ -1132,7 +1287,7 @@ mod tests { #[test] fn a_packed_structure_is_known_by_its_header() { let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32; - assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1a * 64)); + assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1b * 64)); // Unpacked, a top level, another version, no size, too big. assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None); assert_eq!(packed_len(header(0x0000_0006, 5)), None); From 82ca13473857d578f6febed48620f23075b16e88 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:43 -0600 Subject: [PATCH 4/6] A stand-in for the title's traced indirect light (VICTORY_AMBIENT, off): estimated from the light visible surfaces send out After beloooo's constant (VIctory-Belobug-AMD 06031237, 4f45ab88, cd9f78ce). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/ambient.rs | 477 +++++++++++++++++++++++++++++ crates/victory-gpu/src/draw.rs | 64 ++++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline.rs | 5 + 4 files changed, 548 insertions(+) create mode 100644 crates/victory-gpu/src/ambient.rs diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs new file mode 100644 index 0000000..fb45f90 --- /dev/null +++ b/crates/victory-gpu/src/ambient.rs @@ -0,0 +1,477 @@ +//! A stand-in for the indirect light the title traces rays for. +//! +//! With the ray-tracing structure builder off (`crate::pipeline::builder_runs`) +//! the title's rays find nothing. Its program that resolves the diffuse light +//! of its screen probes (`CS_ScreenProbes_TemporalResolve_*`) then leaves the +//! sky's light outdoors, nothing indoors (walls are black where no lamp or +//! sun reaches) and, in blocks of the picture's tiles, what the probes' +//! memory held. Right after that program the light is raised to an estimate +//! and bounded by a multiple of it. +//! +//! That a stand-in can be put there, and in which of the program's images, +//! is beloooo's find (VIctory-Belobug-AMD, 06031237, 4f45ab88, cd9f78ce, +//! GPL-3.0-or-later), which puts a constant there, shaded in creases from the +//! scene's depth. The estimate here is worked out from the frame instead, so +//! it follows the hour, the room and its lamps by itself: the light the +//! visible surfaces send out (the title keeps it for its own screen traces: +//! `CS_CacheScreenSpaceRadiance`, the frame before) is averaged in 64x36 +//! cells, and every point gets the mean of the cells weighted by the share of +//! its surroundings they cover, as a directional value (first-order harmonics +//! at 160x90 points, taken between them by depth). +//! +//! What it assumes: what is not on screen sends out what is (with a slow +//! mean of the last seconds, so that turning into a dark corner is not black +//! at once). No occlusion but the creases'. +//! +//! `VICTORY_AMBIENT`: +//! - unset or `0`/`off`: the title's own output. +//! - a number: that share of the estimate (1: all of it). +//! - `constant:`: the constant, as beloooo's fork has it. +//! +//! `VICTORY_AMBIENT_SHADE=,` sets the creases. + +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{HostList, host}; + +/// Programs of the title the stand-in follows. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + /// Resolves the diffuse light. + Resolve, + /// Keeps the light visible surfaces send out. + Radiance, +} + +/// The program's part in this, by its name in the container. +pub(crate) fn role(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"CS_ScreenProbes_TemporalResolve") { + Some(Role::Resolve) + } else if has(b"CS_CacheScreenSpaceRadiance") { + Some(Role::Radiance) + } else { + None + } +} + +/// Where the resolve writes the diffuse light (R9G9B9E5 as 32-bit integers) +/// and reads the scene's depth, and where the other writes the light of +/// visible surfaces: root parameter and place in its table, in dwords. +pub(crate) const LIGHT: (u8, u32) = (1, 176); +pub(crate) const DEPTH: (u8, u32) = (0, 464); +pub(crate) const RADIANCE: (u8, u32) = (1, 16); + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Set { + Off, + Estimate(f32), + Constant(f32), +} + +fn parse(set: &str) -> Set { + let set = set.trim(); + let number = |t: &str| t.trim().parse::().ok().filter(|v| v.is_finite() && *v > 0.0); + match set.strip_prefix("constant:") { + Some(level) => number(level).map_or(Set::Off, Set::Constant), + None => number(set).map_or(Set::Off, Set::Estimate), + } +} + +fn set() -> Set { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| parse(&std::env::var("VICTORY_AMBIENT").unwrap_or_default())) +} + +/// Whether the stand-in is on: set, and the title's rays find nothing. +pub(crate) fn on() -> bool { + set() != Set::Off && !crate::pipeline::builder_runs() +} + +/// Strength and radius of the creases' shade. +fn shade() -> [f32; 2] { + static SET: OnceLock<[f32; 2]> = OnceLock::new(); + *SET.get_or_init(|| { + let mut shade = [1.0, 0.6]; + let set = std::env::var("VICTORY_AMBIENT_SHADE").unwrap_or_default(); + for (to, v) in shade.iter_mut().zip(set.split(',')) { + if let Ok(v) = v.trim().parse() { + *to = v; + } + } + shade + }) +} + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=12, b0), DescriptorTable(SRV(t0)), DescriptorTable(UAV(u0)), UAV(u1), UAV(u2)" +#define CX 64 +#define CY 36 +#define CELLS (CX * CY) +#define PX 160 +#define PY 90 +cbuffer Set : register(b0) { + float level; float constant; float strength; float radius; + float near; float tan_y; uint width; uint height; + float follow; float most; float unused0; float unused1; +}; +Texture2D depth : register(t0); +// Cells: the light they send out (then, at CELLS, the slow mean), from +// CELLS + 1 on where they are. +RWStructuredBuffer cells : register(u1); +// Three a point: red, green and blue, each a mean and a direction. +RWStructuredBuffer points : register(u2); +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); + +// The point seen at a texel, in metres from the eye (x right, y up, z away). +float3 seen(int2 p, float2 size) { + float d = depth.Load(int3(clamp(p, int2(0, 0), int2(size) - 1), 0)); + float z = min(near / max(d, 1e-7), 1000.0); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * tan_y * size.x / size.y * z, -ndc.y * tan_y * z, z); +} + +#ifdef KEEP +RWTexture2D radiance : register(u0); +[RootSignature(RS)] +[numthreads(8, 4, 1)] +void keep(uint3 at : SV_DispatchThreadID) { + uint w, h; + radiance.GetDimensions(w, h); + float3 sum = 0; + for (uint y = 0; y < 5; y++) for (uint x = 0; x < 5; x++) { + uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY)); + float3 c = max(radiance[p], 0.0); + c = any(isnan(c)) || any(isinf(c)) ? 0.0 : c; + // Lamps and glints count, but not for everything. + sum += c / max(1.0, dot(c, LUMA) / 20.0); + } + cells[at.y * CX + at.x] = float4(sum / 25.0, 1.0); +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void mean() { + float3 sum = 0; + for (uint i = 0; i < CELLS; i++) sum += cells[i].rgb; + float4 was = cells[CELLS]; + float3 now = sum / CELLS; + cells[CELLS] = float4(was.a > 0.0 ? lerp(was.rgb, now, follow) : now, 1.0); +} +#endif + +#ifdef PLACE +[RootSignature(RS)] +[numthreads(8, 4, 1)] +void place(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size); + cells[CELLS + 1 + at.y * CX + at.x] = float4(p, p.z * p.z); +} +#endif + +#ifdef GATHER +[RootSignature(RS)] +[numthreads(8, 2, 1)] +void gather(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size); + float r2 = 0.25 + 0.0025 * p.z * p.z; + float whole = 0; + float3 toward = 0, light = 0, red = 0, green = 0, blue = 0; + for (uint i = 0; i < CELLS; i++) { + float4 c = cells[CELLS + 1 + i]; + float3 L = cells[i].rgb; + float3 d = c.xyz - p; + float dd = dot(d, d); + float w = c.w / (dd + r2); + float3 dir = d / sqrt(dd + 0.25 * r2); + whole += w; + toward += w * dir; + light += w * L; + red += w * L.r * dir; + green += w * L.g * dir; + blue += w * L.b * dir; + } + whole = max(whole, 1e-6); + light /= whole; + toward /= whole; + uint at0 = (at.y * PX + at.x) * 3; + points[at0] = float4(red / whole - light.r * toward, light.r); + points[at0 + 1] = float4(green / whole - light.g * toward, light.g); + points[at0 + 2] = float4(blue / whole - light.b * toward, light.b); +} +#endif + +#ifdef RAISE +RWTexture2D light : register(u0); +float3 unpack(uint v) { + return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0); +} +uint pack(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float scale = exp2(float(24 - e)); + if (top * scale >= 511.5) { e = min(e + 1, 31); scale = exp2(float(24 - e)); } + uint3 m = min(uint3(c * scale + 0.5), 511u); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void raise(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + if (at.x >= width || at.y >= height) return; + int2 p = int2(at.xy); + float3 c = seen(p, size); + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0, 0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + // How open it is (as in beloooo's cd9f78ce). + float open = 1.0; + float px = min(radius * size.y / (2.0 * tan_y * c.z), 128.0); + float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + if (strength > 0.0 && px >= 1.5 && c.z < 400.0) { + float sum = 0.0; + const int N = 12; + for (int i = 0; i < N; i++) { + float a = i * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((i + 0.5) / N) * px); + float3 v = seen(p + int2(round(o)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + open = saturate(1.0 - strength * 2.0 * sum / N); + } + float3 found; + if (constant > 0.0) { + found = float3(1.0, 0.98, 0.94) * constant * open; + light[p] = pack(found); + return; + } + // Between the four points around, those at its own depth first; which + // four is dithered a little. + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = 0, sg = 0, sb = 0; + float sum = 0; + for (int k = 0; k < 4; k++) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 b = float2(k & 1 ? f.x : 1 - f.x, k >> 1 ? f.y : 1 - f.y); + float w = (b.x * b.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = (q.y * PX + q.x) * 3; + sr += w * points[at0]; + sg += w * points[at0 + 1]; + sb += w * points[at0 + 2]; + sum += w; + } + float3 all = float3(sr.w, sg.w, sb.w) / sum; + found = all + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum; + found = clamp(found, 0.2 * all, 2.5 * all); + found = lerp(found, cells[CELLS].rgb, 0.2) * level * open; + float3 was = unpack(light[p]); + // What the program left counts as far as it can be true: the sky's light + // outdoors, not the blocks of other memory. + float top = max(dot(found, LUMA) * most, 1e-6); + float has = dot(was, LUMA); + was *= min(1.0, top / max(has, 1e-6)); + light[p] = pack(max(was, found)); +} +#endif +"#; + +/// Bytes of the cells' buffer and of the points'. +const CELLS: u64 = 64 * 36; +const CELL_BYTES: u64 = (2 * CELLS + 1) * 16; +const POINT_BYTES: u64 = 160 * 90 * 48; + +struct Pass { + root: ID3D12RootSignature, + keep: ID3D12PipelineState, + mean: ID3D12PipelineState, + place: ID3D12PipelineState, + gather: ID3D12PipelineState, + raise: ID3D12PipelineState, + cells: ID3D12Resource, + points: ID3D12Resource, +} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Pass {} +// SAFETY: as above. +unsafe impl Sync for Pass {} + +fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) -> windows::core::Result { + let mut root: Option = None; + let mut pipeline = |part: &str, entry| -> windows::core::Result { + let code = crate::host::compile(&format!("#define {part}\n{SOURCE}"), entry, s!("cs_5_1"))?; + // SAFETY: the root signature is inside the shader; plain creations. + unsafe { + if root.is_none() { + root = Some(device.CreateRootSignature(0, &code)?); + } + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, + ..Default::default() + }; + device.CreateComputePipelineState(&desc) + } + }; + let keep = pipeline("KEEP", s!("keep"))?; + let mean = pipeline("KEEP", s!("mean"))?; + let place = pipeline("PLACE", s!("place"))?; + let gather = pipeline("GATHER", s!("gather"))?; + let raise = pipeline("RAISE", s!("raise"))?; + let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); + Ok(Pass { + root: root.ok_or_else(windows::core::Error::empty)?, + keep, + mean, + place, + gather, + raise, + cells: made(CELL_BYTES)?, + points: made(POINT_BYTES)?, + }) +} + +fn pass() -> Option<&'static Pass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + make(&host.device, |bytes| host.uav_buffer(bytes)) + .inspect_err(|e| tracing::warn!(error = %e, "no stand-in for the indirect light")) + .ok() + }) + .as_ref() +} + +fn uav_barrier(list: &ID3D12GraphicsCommandList) { + let barrier = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }; + // SAFETY: an open list; the barrier names no resource. + unsafe { list.ResourceBarrier(&[barrier]) }; +} + +/// Whether the light of a frame has been kept: the estimate has something +/// to begin with. +static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// What the passes read and write, as views in the heap the list has set. +pub(crate) struct Views { + /// The image the title's program just wrote. + pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE, + /// The scene's depth, for [`Role::Resolve`]. + pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE, + /// The size of the light's image. + pub(crate) size: [u32; 2], +} + +/// After the title's program of that role, in `list` with the program's view +/// heap set. Replaces the list's compute root signature and pipeline; false +/// if it recorded nothing. +pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { + use std::sync::atomic::Ordering; + let Some(pass) = pass() else { + return false; + }; + let (level, constant) = match set() { + Set::Off => return false, + Set::Estimate(level) => (level, 0.0f32), + Set::Constant(level) => (0.0, level), + }; + if role == Role::Resolve && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + return false; + } + static SAID: Mutex = Mutex::new(0); + { + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if *said < 4 { + *said += 1; + tracing::info!(?role, size = ?views.size, level, constant, "a stand-in for the indirect light"); + } + } + list.keep(&pass.cells); + list.keep(&pass.points); + let [strength, radius] = shade(); + let floats = [level, constant, strength, radius, 0.1, 0.45]; + let mut words = [0u32; 12]; + for (to, v) in words.iter_mut().zip(floats) { + *to = v.to_bits(); + } + words[6] = views.size[0]; + words[7] = views.size[1]; + words[8] = 0.04f32.to_bits(); + words[9] = 4.0f32.to_bits(); + let l = &list.list; + // SAFETY: an open list with the heap of the views set; the title's + // program has just used both views, so their textures are in the states + // these views need; buffers the list keeps. + unsafe { + uav_barrier(l); + l.SetComputeRootSignature(&pass.root); + l.SetComputeRoot32BitConstants(0, 12, words.as_ptr().cast(), 0); + l.SetComputeRootDescriptorTable(1, views.depth); + l.SetComputeRootDescriptorTable(2, views.image); + l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); + let run = |pso: &ID3D12PipelineState, x, y| { + l.SetPipelineState(pso); + l.Dispatch(x, y, 1); + uav_barrier(l); + }; + match role { + Role::Radiance => { + run(&pass.keep, 8, 9); + run(&pass.mean, 1, 1); + KEPT.store(true, Ordering::Relaxed); + } + Role::Resolve => { + if constant == 0.0 { + run(&pass.place, 8, 9); + run(&pass.gather, 20, 45); + } + run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8)); + } + } + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings() { + assert_eq!(parse(""), Set::Off); + assert_eq!(parse("off"), Set::Off); + assert_eq!(parse("0"), Set::Off); + assert_eq!(parse("0.8"), Set::Estimate(0.8)); + assert_eq!(parse("constant:0.3"), Set::Constant(0.3)); + assert_eq!(parse("constant:nan"), Set::Off); + } + + #[test] + fn roles_by_name() { + assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); + assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); + assert_eq!(role(b"CS_TemporalResolve"), None); + } + + /// The passes compile with the system's compiler and the host takes them. + #[test] + fn the_passes_build() { + let Some(host) = host() else { + return; + }; + make(&host.device, |bytes| host.uav_buffer(bytes)).expect("the passes"); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c1bbae5..4ef4340 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -321,6 +321,10 @@ pub(crate) struct State { /// report of a removed device, `crate::host::indirects`). #[cfg(feature = "diagnostics")] user: Vec, + /// The tables the last bind made afresh for a program the stand-in for + /// the indirect light follows (`crate::ambient`): root parameter, bytes + /// into the view heap. + ambient_tables: Vec<(u8, u32)>, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -1449,6 +1453,10 @@ impl State { once!("a draw whose descriptor table found no free slots is dropped"); return false; } + if stage.shader.ambient.is_some() { + self.ambient_tables.clear(); + self.ambient_tables.extend(made.iter().copied()); + } // What the shader stores through root views and raw addresses is // copied back into title memory afterwards. let writes = (t.stores || !write_skip()) @@ -2603,6 +2611,62 @@ impl State { unsafe { list.list.Dispatch(x, y, z) }; self.buffers_written(); DISPATCHED.fetch_add(1, Ordering::Relaxed); + if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) + && crate::ambient::on() + && self.ambient(list, p, role) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + } + + /// The stand-in for the indirect light after a dispatch of `p` + /// (`crate::ambient`). Whether it recorded anything. + fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { + use crate::ambient::{DEPTH, LIGHT, RADIANCE, Role, Views}; + let Some(t) = p.stages.first().map(|s| s.translated()) else { + return false; + }; + let Some(heap) = (self.heaps[0] != 0).then(|| crate::descriptor::heap(self.heaps[0] as This).host()).flatten() + else { + return false; + }; + let entry = |kind: ResourceType, (slot, offset): (u8, u32)| { + t.used.iter().find(|u| { + u.kind == kind && u.root == RootType::Table && (u.slot, u.table_offset_dwords) == (slot, offset) + })?; + let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(slot)) else { + return None; + }; + let resource = match crate::descriptor::view(table + u64::from(offset) * 4)? { + View::Shader(r, _) | View::Unordered(r, ..) => r, + _ => return None, + }; + let start = match self.ambient_tables.iter().find(|m| m.0 == slot) { + Some(m) => m.1, + None => self.user_value(true, slot, RootType::Table, 0), + }; + let host = crate::resource::host_resource(resource as This)?; + // SAFETY: a live resource. + let desc = unsafe { host.GetDesc() }; + Some((desc, heap.gpu_handle((start + offset * 4) / 32))) + }; + let image = entry(ResourceType::Uav, if role == Role::Resolve { LIGHT } else { RADIANCE }); + let depth = match role { + Role::Resolve => entry(ResourceType::Srv, DEPTH), + Role::Radiance => image, + }; + let (Some((of, image)), Some((seen, depth))) = (image, depth) else { + once!(?role, "no stand-in for the indirect light: other tables"); + return false; + }; + // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) + let format = if role == Role::Resolve { 42 } else { 26 }; + if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) { + once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); + return false; + } + crate::ambient::after(list, role, &Views { image, depth, size: [of.Width as u32, of.Height] }) } /// What a draw or dispatch runs, for the device-removed report diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 29947a7..604f298 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -15,6 +15,8 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). +#[cfg(windows)] +mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; pub mod console; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7a00633..d64b06b 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -61,6 +61,9 @@ pub(crate) struct Shader { /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, container: Vec, + /// Its part in the stand-in for the indirect light. + #[cfg(windows)] + pub(crate) ambient: Option, #[cfg(windows)] translated: OnceLock>, } @@ -112,6 +115,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { hash: full.to_hex()[..16].to_owned(), container: bytes.to_vec(), #[cfg(windows)] + ambient: (stage == "compute").then(|| crate::ambient::role(bytes)).flatten(), + #[cfg(windows)] translated: OnceLock::new(), }) }) From 7da523a9d962c7458dfddf713645580db6b079cf Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:45:56 -0600 Subject: [PATCH 5/6] The stand-in for the indirect light can bound what the air scatters (VICTORY_AMBIENT_AIR, off) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/ambient.rs | 73 ++++++++++++++++++++++++++----- crates/victory-gpu/src/draw.rs | 21 ++++++--- 2 files changed, 79 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index fb45f90..8a3d46e 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -29,6 +29,10 @@ //! - `constant:`: the constant, as beloooo's fork has it. //! //! `VICTORY_AMBIENT_SHADE=,` sets the creases. +//! +//! The air of a room is lit by the same probes: without rays they hold the +//! sky's light indoors too, a brown veil at sunset. `VICTORY_AMBIENT_AIR` +//! bounds what the air scatters by a multiple of the light around. use std::sync::{Mutex, OnceLock}; @@ -44,6 +48,9 @@ pub(crate) enum Role { Resolve, /// Keeps the light visible surfaces send out. Radiance, + /// Adds the lamps' light to what the air scatters (the last program + /// that writes that volume before it is summed up along the view). + Air, } /// The program's part in this, by its name in the container. @@ -53,6 +60,8 @@ pub(crate) fn role(container: &[u8]) -> Option { Some(Role::Resolve) } else if has(b"CS_CacheScreenSpaceRadiance") { Some(Role::Radiance) + } else if has(b"CS_AccumulateLocalLightInscatteringVolume") { + Some(Role::Air) } else { None } @@ -64,6 +73,8 @@ pub(crate) fn role(container: &[u8]) -> Option { pub(crate) const LIGHT: (u8, u32) = (1, 176); pub(crate) const DEPTH: (u8, u32) = (0, 464); pub(crate) const RADIANCE: (u8, u32) = (1, 16); +/// Where the light the air scatters is. +pub(crate) const AIR: (u8, u32) = (1, 32); #[derive(Clone, Copy, PartialEq, Debug)] enum Set { @@ -91,6 +102,16 @@ pub(crate) fn on() -> bool { set() != Set::Off && !crate::pipeline::builder_runs() } +/// The most the air scatters, as a multiple of the light around +/// (`VICTORY_AMBIENT_AIR=`; unset or 0: what the title has). +fn air() -> f32 { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_AIR").unwrap_or_default(); + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) + }) +} + /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -116,7 +137,7 @@ const SOURCE: &str = r#" cbuffer Set : register(b0) { float level; float constant; float strength; float radius; float near; float tan_y; uint width; uint height; - float follow; float most; float unused0; float unused1; + float follow; float most; float air; float unused; }; Texture2D depth : register(t0); // Cells: the light they send out (then, at CELLS, the slow mean), from @@ -205,6 +226,28 @@ void gather(uint3 at : SV_DispatchThreadID) { } #endif +#ifdef AIR +RWTexture3D scattered : register(u0); +// No more than a multiple of the light around: of the room as the last +// seconds showed it, and of the surface seen in this direction (towards a +// window the air outside may be as bright as the sky is). +[RootSignature(RS)] +[numthreads(8, 8, 2)] +void clear_air(uint3 at : SV_DispatchThreadID) { + uint w, h, d; + scattered.GetDimensions(w, h, d); + if (at.x >= w || at.y >= h || at.z >= d) return; + uint2 q = min(uint2((float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY)), uint2(PX - 1, PY - 1)); + uint at0 = (q.y * PX + q.x) * 3; + float3 seen_there = float3(points[at0].w, points[at0 + 1].w, points[at0 + 2].w); + float far = float(at.z) / float(d); + float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far); + float3 c = scattered[at]; + float has = dot(c, LUMA); + if (has > cap) scattered[at] = c * (cap / has); +} +#endif + #ifdef RAISE RWTexture2D light : register(u0); float3 unpack(uint v) { @@ -300,6 +343,7 @@ struct Pass { place: ID3D12PipelineState, gather: ID3D12PipelineState, raise: ID3D12PipelineState, + air: ID3D12PipelineState, cells: ID3D12Resource, points: ID3D12Resource, } @@ -330,6 +374,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - let place = pipeline("PLACE", s!("place"))?; let gather = pipeline("GATHER", s!("gather"))?; let raise = pipeline("RAISE", s!("raise"))?; + let air = pipeline("AIR", s!("clear_air"))?; let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); Ok(Pass { root: root.ok_or_else(windows::core::Error::empty)?, @@ -338,6 +383,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - place, gather, raise, + air, cells: made(CELL_BYTES)?, points: made(POINT_BYTES)?, }) @@ -370,8 +416,9 @@ pub(crate) struct Views { pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE, /// The scene's depth, for [`Role::Resolve`]. pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE, - /// The size of the light's image. + /// The size of the image, and how many slices it has. pub(crate) size: [u32; 2], + pub(crate) slices: u32, } /// After the title's program of that role, in `list` with the program's view @@ -387,7 +434,10 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { Set::Estimate(level) => (level, 0.0f32), Set::Constant(level) => (0.0, level), }; - if role == Role::Resolve && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + if role != Role::Radiance && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + return false; + } + if role == Role::Air && (constant > 0.0 || air() == 0.0) { return false; } static SAID: Mutex = Mutex::new(0); @@ -410,6 +460,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[7] = views.size[1]; words[8] = 0.04f32.to_bits(); words[9] = 4.0f32.to_bits(); + words[10] = air().to_bits(); let l = &list.list; // SAFETY: an open list with the heap of the views set; the title's // program has just used both views, so their textures are in the states @@ -422,23 +473,24 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { l.SetComputeRootDescriptorTable(2, views.image); l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); - let run = |pso: &ID3D12PipelineState, x, y| { + let run = |pso: &ID3D12PipelineState, x, y, z| { l.SetPipelineState(pso); - l.Dispatch(x, y, 1); + l.Dispatch(x, y, z); uav_barrier(l); }; match role { Role::Radiance => { - run(&pass.keep, 8, 9); - run(&pass.mean, 1, 1); + run(&pass.keep, 8, 9, 1); + run(&pass.mean, 1, 1, 1); KEPT.store(true, Ordering::Relaxed); } + Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), Role::Resolve => { if constant == 0.0 { - run(&pass.place, 8, 9); - run(&pass.gather, 20, 45); + run(&pass.place, 8, 9, 1); + run(&pass.gather, 20, 45, 1); } - run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8)); + run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } } } @@ -463,6 +515,7 @@ mod tests { fn roles_by_name() { assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); + assert_eq!(role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air)); assert_eq!(role(b"CS_TemporalResolve"), None); } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4ef4340..8264a58 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2623,7 +2623,7 @@ impl State { /// The stand-in for the indirect light after a dispatch of `p` /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { - use crate::ambient::{DEPTH, LIGHT, RADIANCE, Role, Views}; + use crate::ambient::{AIR, DEPTH, LIGHT, RADIANCE, Role, Views}; let Some(t) = p.stages.first().map(|s| s.translated()) else { return false; }; @@ -2651,10 +2651,15 @@ impl State { let desc = unsafe { host.GetDesc() }; Some((desc, heap.gpu_handle((start + offset * 4) / 32))) }; - let image = entry(ResourceType::Uav, if role == Role::Resolve { LIGHT } else { RADIANCE }); + let at = match role { + Role::Resolve => LIGHT, + Role::Radiance => RADIANCE, + Role::Air => AIR, + }; + let image = entry(ResourceType::Uav, at); let depth = match role { Role::Resolve => entry(ResourceType::Srv, DEPTH), - Role::Radiance => image, + Role::Radiance | Role::Air => image, }; let (Some((of, image)), Some((seen, depth))) = (image, depth) else { once!(?role, "no stand-in for the indirect light: other tables"); @@ -2662,11 +2667,17 @@ impl State { }; // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) let format = if role == Role::Resolve { 42 } else { 26 }; - if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) { + let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) || volume != (role == Role::Air) { once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); return false; } - crate::ambient::after(list, role, &Views { image, depth, size: [of.Width as u32, of.Height] }) + crate::ambient::after(list, role, &Views { + image, + depth, + size: [of.Width as u32, of.Height], + slices: u32::from(of.DepthOrArraySize), + }) } /// What a draw or dispatch runs, for the device-removed report From 72f7f13242612ed0fab2937c0a55274de3439552 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:19:01 -0600 Subject: [PATCH 6/6] Ray tracing document: the stand-in, the sizes, what is known Co-Authored-By: Claude Opus 5.5 --- docs/fork-ray-tracing.md | 56 +++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index 6c05d8d..ec4a1ea 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -1,10 +1,10 @@ # Ray tracing in this fork: what the title does and what has been built -Status, 2026-11-25, 06:00: **with `VICTORY_BVH_BUILDER=1` the builder runs on -the RX 7900 XTX and rooms get their indirect light** (run light-6, the dorm: -bunk, locker, window frame, posters; 100-116 ms a frame against 84-95 without). -Some structures are still wrong; one run of four with it lost the device early, -in a list without a builder stage. Off by default. +Status, 2026-11-25, midday: **with `VICTORY_BVH_BUILDER=1` rooms get their +indirect light** (runs light-10, light-11, n19), for some 40 ms more of the +card's time a frame (the dorm: 75 of 90 ms busy against 34 of 64). Off by +default. **`VICTORY_AMBIENT=1`** puts an estimate of that light in its place +for next to nothing (below). ## What the title does @@ -92,6 +92,9 @@ after it was given them as an unordered access view. | variable | does | |---|---| | `VICTORY_BVH_BUILDER=1` | the builder's stages run | +| `VICTORY_BVH_FENCES=0` | no fences around the builder's buffer atomics (beloooo's 72e748ea has them too) | +| `VICTORY_BVH_SIZES_WAIT=0` | submissions that ask for structures' sizes are not waited for | +| `VICTORY_BVH_TRACE=1` | logs what sizes are asked, when they came, and the copies (diagnostics) | | `VICTORY_BVH_QUARANTINE=1` | nothing it stores comes back to title memory | | `VICTORY_MEMORY_CARD_MB` | the most of it on the card (4096) | | `VICTORY_MEMORY_DUMP=` | a file `go` there writes the arenas out (diagnostics) | @@ -102,10 +105,18 @@ dispatches, faults and what came. ## Known gaps -- About 4,000 pages a frame that are not there are still touched (the notes' - limit): some structures are wrong and rays go anywhere in them. Guess: sizes - that came back late or not (fixed after light-6, not seen working), so places - overlap. +- Dynamic structures overlap each other (8 of 65 good in run light-10). Cause, + run light-11's trace (`VICTORY_BVH_TRACE=1`): the title asks for a new + structure's compacted size, reads it one or two frames later without looking + whether it is there, takes memory of that size and has the structure copied + into it. Our submissions land up to two frames late; the title read what the + slot held before, another structure's size, and the copy wrote over the + neighbours. A submission that asks is waited for now + (`VICTORY_BVH_SIZES_WAIT=0`: not). +- Some 2,500 pages a frame that are not there are still touched (the notes' + limit): rays in structures that were written over. +- A capture of a frame with the builder on cannot be replayed: the card hangs + (cause unknown; do not try). - Five shadow-mask trace programs do not translate (a structure's address out of a descriptor picked from the heap by a computed index: the host would have to give a table of addresses by slot). The title did not create them in any @@ -116,6 +127,33 @@ dispatches, faults and what came. of two boxes entered at the same distance, and the result for a ray exactly through an edge. +## Without rays: the stand-in (`crates/victory-gpu/src/ambient.rs`) + +Without structures every ray misses. The title's program that resolves the +diffuse light of its screen probes (`CS_ScreenProbes_TemporalResolve_*`, list +184 of a frame) then leaves the sky's light outdoors, nothing indoors, and in +blocks of tiles what the probes' memory held. `VICTORY_AMBIENT=` raises +it to an estimate right after that program: the title keeps, for its own screen +traces, the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`, +1280x720, the frame before); its mean in 64x36 cells is gathered at 160x90 +points, each cell weighted by the share of the surroundings it covers, as a +directional value; each pixel takes it between the points by depth, with its +normal and a shade in creases. So level and tint follow the hour, the room and +its lamps. What the program left counts up to four times the estimate. + +Where it can be put, and the crease shade, are beloooo's (VIctory-Belobug-AMD +06031237, 4f45ab88, cd9f78ce); `VICTORY_AMBIENT=constant:` is that +fork's constant. + +| variable | does | +|---|---| +| `VICTORY_AMBIENT=` | the estimate, 1 all of it (unset: the title's own) | +| `VICTORY_AMBIENT=constant:` | the same light everywhere | +| `VICTORY_AMBIENT_SHADE=,` | the creases (1,0.6) | +| `VICTORY_AMBIENT_AIR=` | what the air scatters is bounded by a multiple of the light around (off) | + +It is off while the builder runs. + ## Where to look - `crates/victory-shader/src/bvh.rs`: the reference for the node test.