Merge day/light

This commit is contained in:
local committed 2026-11-25 12:55:58 -06:00
commit 7eb1850719
11 files changed
+854 -13

No files matched your search

+530
View File
@@ -0,0 +1,530 @@
//! 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:<level>`: the constant, as beloooo's fork has it.
//!
//! `VICTORY_AMBIENT_SHADE=<strength>,<radius in metres>` 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};
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,
/// 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.
pub(crate) fn role(container: &[u8]) -> Option<Role> {
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 if has(b"CS_AccumulateLocalLightInscatteringVolume") {
Some(Role::Air)
} 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);
/// Where the light the air scatters is.
pub(crate) const AIR: (u8, u32) = (1, 32);
#[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::<f32>().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<Set> = 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()
}
/// The most the air scatters, as a multiple of the light around
/// (`VICTORY_AMBIENT_AIR=<multiple>`; unset or 0: what the title has).
fn air() -> f32 {
static SET: OnceLock<f32> = 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();
*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 air; float unused;
};
Texture2D<float> depth : register(t0);
// Cells: the light they send out (then, at CELLS, the slow mean), from
// CELLS + 1 on where they are.
RWStructuredBuffer<float4> cells : register(u1);
// Three a point: red, green and blue, each a mean and a direction.
RWStructuredBuffer<float4> 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<float3> 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 AIR
RWTexture3D<float3> 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<uint> 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,
air: 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<ID3D12Resource>) -> windows::core::Result<Pass> {
let mut root: Option<ID3D12RootSignature> = None;
let mut pipeline = |part: &str, entry| -> windows::core::Result<ID3D12PipelineState> {
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 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)?,
keep,
mean,
place,
gather,
raise,
air,
cells: made(CELL_BYTES)?,
points: made(POINT_BYTES)?,
})
}
fn pass() -> Option<&'static Pass> {
static PASS: OnceLock<Option<Pass>> = 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 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
/// 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::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<u32> = 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();
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
// 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, z| {
l.SetPipelineState(pso);
l.Dispatch(x, y, z);
uav_barrier(l);
};
match role {
Role::Radiance => {
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, 1);
run(&pass.gather, 20, 45, 1);
}
run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1);
}
}
}
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_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air));
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");
}
}
+76 -1
View File
@@ -321,6 +321,10 @@ pub(crate) struct State {
/// report of a removed device, `crate::host::indirects`).
#[cfg(feature = "diagnostics")]
user: Vec<u32>,
/// 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.
@@ -1284,7 +1288,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`.
@@ -1473,6 +1477,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())
@@ -2647,6 +2655,73 @@ 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::{AIR, 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 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 | Role::Air => 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 };
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],
slices: u32::from(of.DepthOrArraySize),
})
}
/// What a draw or dispatch runs, for the device-removed report
+3
View File
@@ -5013,6 +5013,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;
@@ -5035,6 +5036,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());
+2
View File
@@ -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;
+157 -2
View File
@@ -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<bool> = 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<Item = &'a HostList>) -> 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<u64> {
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<Ready> {
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<u64, (u64, u64)>,
said: u32,
}
fn on() -> bool {
static ON: std::sync::OnceLock<bool> = 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=<folder>`: when a file `go` appears there, the arenas
/// as the card holds them are copied out and written (`arena-<n>.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);
+5
View File
@@ -61,6 +61,9 @@ pub(crate) struct Shader {
/// The first 8 bytes of its BLAKE3, as logged.
pub(crate) hash: String,
container: Vec<u8>,
/// Its part in the stand-in for the indirect light.
#[cfg(windows)]
pub(crate) ambient: Option<crate::ambient::Role>,
#[cfg(windows)]
translated: OnceLock<Option<Translated>>,
}
@@ -112,6 +115,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
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(),
})
})
+5 -1
View File
@@ -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<ID3D12Resource> = None;
let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
// SAFETY: 20 bytes that were a clear value.
+1
View File
@@ -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'=');
+20
View File
@@ -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) {
+8
View File
@@ -182,6 +182,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<bool> = 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
+47 -9
View File
@@ -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=<folder>` | 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=<share>` 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:<level>` is that
fork's constant.
| variable | does |
|---|---|
| `VICTORY_AMBIENT=<share>` | the estimate, 1 all of it (unset: the title's own) |
| `VICTORY_AMBIENT=constant:<level>` | the same light everywhere |
| `VICTORY_AMBIENT_SHADE=<strength>,<metres>` | the creases (1,0.6) |
| `VICTORY_AMBIENT_AIR=<multiple>` | 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.