From 41b4a056d6e176656a062355d7198058d0065ca6 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:25:28 +0530 Subject: [PATCH] Pixel programs keep the console's early depth test (VICTORY_EARLY_DEPTH=1, off by default) A console pixel program whose DB_SHADER_CONTROL has DEPTH_BEFORE_SHADER (bit 12, HLSL's [earlydepthstencil]) is translated with DXIL's ForceEarlyDepthStencil flag when VICTORY_EARLY_DEPTH=1. The translator read DB_SHADER_CONTROL but never used it, so every such program ran with the late test on the host wherever it writes unordered views or discards, and its writes to unordered views landed for pixels the depth test then rejected. What that broke (capture C:\dev\captures\haze2, a character's head in front of a window): the transparent pass (list 247; pixel programs 629743ca412296d4, 8ba01719b71d1d35, 5436c45060d74ebe and others, DB_SHADER_CONTROL 0x1450) keeps the nearest transparent depth and its velocity with 64-bit atomics in texture 46225 (R32G32, 1706x960); draw 271:34 (pixel 00ae3e9b98a0ae26, depth test ALWAYS, depth write on) writes that depth into the scene depth 6481 and that velocity into the motion vectors 38269 wherever it holds one. The glass, behind the head, wrote there too: at the head's pixels in front of it the scene depth that the heat-haze and in-scattering pass 731a39171b568298 (279:303) reads holds the glass's (0.176, 0.85 m, for the head's 0.39, 0.38 m) and the motion vectors hold the glass's velocity (-24, +31 where the head's own is +43, +35). 13.7% of that frame's transparent texels lie behind the opaque depth. The haze pass picks heat haze (beyond 20 m) and in-scattering (beyond 137 m there) by each pixel's distance, in 16x16 tiles: where the false depth is far, it works on character outlines (expected cause of the blocks on hair, not yet confirmed in a run). The switch joins the shader cache's key only while it is on, so the default translation and its cache entries stay as they were. Counted at the shader cache's log line: programs given the early test, left late (switch off), left late as they write depth or stencil. Tests: the decision, and a pixel program translated with and without the switch (dxil.dll validates it). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/queue.rs | 11 ++ crates/victory-gpu/src/shader_cache.rs | 10 ++ crates/victory-shader/src/emit/lower.rs | 13 ++ crates/victory-shader/src/emit/mod.rs | 213 +++++++++++++++++++++++ crates/victory-shader/src/emit/shader.rs | 2 + 5 files changed, 249 insertions(+) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 3ae12d2..93968e1 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -977,6 +977,17 @@ extern "system" fn present( if frame >= 256 { let (hits, misses) = crate::shader_cache::counts(); tracing::info!(hits, misses, "shaders from the cache and translated so far"); + // `VICTORY_EARLY_DEPTH`: what became of the console's early depth + // test in the pixel programs translated so far. + let [given, off, exports] = victory_shader::emit::early_depth_counts(); + if given + off + exports > 0 { + tracing::info!( + given, + off, + exports, + "pixel programs translated so far whose console code tests depth before them: given the host's early test (VICTORY_EARLY_DEPTH=1), left with the late test (switch off), left with it as they write depth or stencil" + ); + } } } #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 4dd39b0..b2eb1ea 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -84,6 +84,16 @@ fn build() -> [u8; 32] { } bytes.push(0); } + // So is whether pixel programs keep the console's early depth test + // (`VICTORY_EARLY_DEPTH=1`): only while it is on, so that the + // translations cached without it are still served without it. + if victory_shader::emit::early_depth() { + tracing::info!( + "VICTORY_EARLY_DEPTH=1: pixel programs whose console code tests depth before them get the host's early depth-stencil test" + ); + bytes.extend_from_slice(b"VICTORY_EARLY_DEPTH=1"); + bytes.push(0); + } // And which clean-up passes ran over the translated code. bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); bytes diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c9defc2..e56307b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -65,6 +65,9 @@ pub(crate) struct Lowered { /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, + /// Whether the program declares D3D12's early depth-stencil test. + #[cfg(test)] + pub early_depth: bool, } pub(crate) struct Parts<'a> { @@ -1613,6 +1616,14 @@ impl<'a> Lower<'a> { let mut s = Shader::new(x.native.stage == HwStage::Ps); s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); + // The console's early depth test, where it asks for one and the + // switch is on (`VICTORY_EARLY_DEPTH`). + if let StageIo::Ps { db_shader_control, .. } = &x.native.io + && super::early_depth_of(*db_shader_control, &s.outputs, super::early_depth()) + == super::EarlyDepth::Given + { + s.flags |= flags::EARLY_DEPTH_STENCIL; + } let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) @@ -2696,6 +2707,8 @@ impl<'a> Lower<'a> { nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, + #[cfg(test)] + early_depth: self.s.flags & flags::EARLY_DEPTH_STENCIL != 0, dxil: self.s.finish(), user_data, samplers: self.samplers, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b48d0c4..e835c2c 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -159,6 +159,86 @@ pub fn helper_own() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_HELPER_OWN").is_none_or(|v| v != "0")) } +/// `DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER` of a console pixel program: the +/// depth and stencil tests (and the depth write) run before the program, as +/// HLSL's `[earlydepthstencil]` asks. +pub(crate) const DEPTH_BEFORE_SHADER: u32 = 1 << 12; +/// `DB_SHADER_CONTROL`'s Z_EXPORT_ENABLE, STENCIL_TEST_VAL_EXPORT_ENABLE and +/// STENCIL_OP_VAL_EXPORT_ENABLE: the program writes depth or stencil. +const DEPTH_STENCIL_EXPORT: u32 = 0b111; + +#[cfg(test)] +thread_local! { + /// [`early_depth`] for the tests of one thread. + static EARLY_DEPTH_FOR_TESTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `VICTORY_EARLY_DEPTH=1`: a pixel program whose console code tests depth and +/// stencil before it runs ([`DEPTH_BEFORE_SHADER`]) gets D3D12's early +/// depth-stencil test too (DXIL shader flag ForceEarlyDepthStencil). Without +/// it the host tests after the program wherever the program writes to +/// unordered views or discards, and its writes to unordered views land for +/// pixels the depth test then rejects. The title's transparent pass (glass) +/// keeps its nearest depth and motion with 64-bit atomics into a texture that +/// a later full-screen draw writes into the scene depth and motion vectors +/// with the depth test off: glass behind a character's hair took the hair's +/// place there, and the heat-haze and in-scattering pass +/// (731a39171b568298), which picks its effect by each pixel's distance, read +/// those pixels at the glass's (or the world's beyond it) distance. Off by +/// default. Part of the translation: the shader cache keys on it +/// (`victory-gpu`'s does, while it is on). +pub fn early_depth() -> bool { + #[cfg(test)] + if let Some(on) = EARLY_DEPTH_FOR_TESTS.with(std::cell::Cell::get) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_EARLY_DEPTH").is_some_and(|v| v == "1")) +} + +/// What a pixel program gets of its console code's early depth test. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EarlyDepth { + /// The console tests after the program (or it is no pixel program). + NotAsked, + /// D3D12's early test ([`early_depth`] on). + Given, + /// The late test: [`early_depth`] is off. + Off, + /// The late test: the program writes depth or stencil, which the early + /// test would not take. + Exports, +} + +/// [`EarlyDepth`] of a pixel program with `db_shader_control` and these +/// outputs, with [`early_depth`] `on`. Pure, for testing. +pub(crate) fn early_depth_of(db_shader_control: u32, outputs: &[container::SigElement], on: bool) -> EarlyDepth { + if db_shader_control & DEPTH_BEFORE_SHADER == 0 { + EarlyDepth::NotAsked + } else if db_shader_control & DEPTH_STENCIL_EXPORT != 0 + // SV_Depth, SV_DepthLessEqual, SV_DepthGreaterEqual, SV_StencilRef. + || outputs.iter().any(|o| (17..=20).contains(&o.kind)) + { + EarlyDepth::Exports + } else if on { + EarlyDepth::Given + } else { + EarlyDepth::Off + } +} + +static EARLY_DEPTH_COUNTS: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Pixel programs translated since the start whose console code tests depth +/// before them ([`early_depth`]): given D3D12's early test, left with the +/// late one because the switch is off, left with it because they write +/// depth or stencil. (Translations served from the shader cache are not +/// counted: a first run with the switch on translates every program anew.) +pub fn early_depth_counts() -> [u64; 3] { + EARLY_DEPTH_COUNTS.each_ref().map(|n| n.load(std::sync::atomic::Ordering::Relaxed)) +} + /// Which of a translated program's group barriers wait for the whole /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory /// fence and lose the wait. A wait that some thread of the group never @@ -888,6 +968,13 @@ fn emit_program( } _ => 0, }; + // (as `lower` decides it, counted for a program that translates) + let early = match &native.io { + crate::native::StageIo::Ps { db_shader_control, .. } => { + early_depth_of(*db_shader_control, &outputs, early_depth()) + } + _ => EarlyDepth::NotAsked, + }; let l = lower::lower(&lower::Parts { native, p, @@ -899,6 +986,15 @@ fn emit_program( prims, mesh_stride, })?; + let counted = match early { + EarlyDepth::NotAsked => None, + EarlyDepth::Given => Some(0), + EarlyDepth::Off => Some(1), + EarlyDepth::Exports => Some(2), + }; + if let Some(n) = counted { + EARLY_DEPTH_COUNTS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } let wave_size = l.wave_size; let shader = HostShader { stage: native.stage, @@ -1295,6 +1391,123 @@ mod tests { assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); } + /// Which pixel programs keep the console's early depth test: those whose + /// `DB_SHADER_CONTROL` asks for it and that write neither depth nor + /// stencil, with the switch on. + #[test] + fn early_depth_is_given_where_the_console_tests_before_the_program() { + let el = |kind| SigElement { + name: "X".into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let target = [el(16)]; + // The title's transparent pass: early Z then late Z, kill, run for + // no-op colour writes, depth before the program. + let glass = 0x1450; + assert_eq!(early_depth_of(glass, &target, true), EarlyDepth::Given); + assert_eq!(early_depth_of(glass, &target, false), EarlyDepth::Off); + // Early Z then late Z alone is the hardware's choice, not the title's. + assert_eq!(early_depth_of(0x50, &target, true), EarlyDepth::NotAsked); + assert_eq!(early_depth_of(0, &target, true), EarlyDepth::NotAsked); + // A depth or stencil export keeps the late test. + assert_eq!(early_depth_of(glass | 1, &target, true), EarlyDepth::Exports); + assert_eq!(early_depth_of(glass | 4, &target, true), EarlyDepth::Exports); + for kind in 17..=20 { + assert_eq!(early_depth_of(glass, &[el(16), el(kind)], true), EarlyDepth::Exports); + } + } + + /// A pixel program whose console code tests depth before it declares + /// D3D12's early depth-stencil test (ShaderFlags bit 3) with + /// `VICTORY_EARLY_DEPTH` on, and not with it off nor where the console + /// tests after it; dxil.dll, where there is one, takes the declaration. + #[test] + fn the_consoles_early_depth_test_is_declared_with_the_switch() { + let translate = |db_shader_control: u32, on: bool| { + EARLY_DEPTH_FOR_TESTS.with(|c| c.set(Some(on))); + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0xF800_180F, + 0x0000_0000, // exp mrt0, v0, v0, v0, v0 done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 1, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let outputs = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs, + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + let before = early_depth_counts(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + let after = early_depth_counts(); + EARLY_DEPTH_FOR_TESTS.with(|c| c.set(None)); + (lowered.early_depth, out.dxil, before, after) + }; + let (given, dxil, before, after) = translate(0x1450, true); + assert!(given, "asked for and switched on: declared"); + assert!(after[0] > before[0], "counted as given"); + let (off, _, before, after) = translate(0x1450, false); + assert!(!off, "switched off: the late test, as before"); + assert!(after[1] > before[1], "counted as left late"); + let (late, _, _, _) = translate(0, true); + assert!(!late, "the console tests after the program: the late test"); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil.clone()).unwrap(); + } + let _ = dxil; + } + /// A pixel program with an ordered section, as the console compiler /// makes one of rasterizer ordered views (the title's hair cards keep /// their nearest layers that way): the wait for overlapped waves is diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 4d5f921..5ce292d 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -102,6 +102,8 @@ pub const USER_DISPATCH_THREADS_X: u32 = 0x106; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { + /// ForceEarlyDepthStencil: HLSL's `[earlydepthstencil]` (no `SFI0` bit). + pub const EARLY_DEPTH_STENCIL: u64 = 1 << 3; pub const RAW_BUFFERS: u64 = 1 << 4; pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11;