From 4a6f61bf6619a3a392ec284acfa9e7e039d22a2c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:39:39 +0100 Subject: [PATCH 1/2] D3D12.X: draws that test a depth buffer left in UAV get its twin first A depth buffer that shaders write keeps those writes in a twin, which depth_uav copies into the depth plane only where the title moves the buffer out of UNORDERED_ACCESS. A draw that tests against the buffer before that, with the title leaving it in UNORDERED_ACCESS, tests the plane as it was before the shaders wrote the twin. VIctory-Neo (7da5c9d, "the depth image a pixel program wrote is brought up to date before the draws that test against it") found this in a retail title's mirrors: a pixel program (PS_Prepass_StencilCulling) writes the depth of the mirror's view through unordered access, and the draws of that view, in the same list, test against it. With the copy left for later every one of them tested the old plane and the mirror showed the sky. Neo does the copy (its plane pass) right before such a draw and sets the title's state again after it. Here, for a stretch that begins with a transition of all of a buffer into UNORDERED_ACCESS on a DIRECT list (the twin then holds the plane), the list follows which side was written last and copies it into the other before the work that uses that one (depth_uav::before_work): - a draw whose depth target names the buffer: the twin into the plane first, once until other work may have written the twin again; - any other draw or dispatch (it may write the twin: XCL does not see which views a translated shader reaches): the plane into the twin first when such a draw tested (and may have written) the plane; - the way out of UNORDERED_ACCESS after such draws does not copy the twin over the plane. These are whole-plane CopyTextureRegion calls between states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS), so nothing bound on the list changes and nothing needs to be set again. A stretch without such a draw copies exactly as before. A list that did not see the stretch begin follows it from its first draw that tests against the buffer. Not seen in an XCL run yet: whether the title leaves the mirror's depth in UNORDERED_ACCESS for those draws (Neo follows uses, not transitions). Port onto main (depth twins on by default, stencil twins, parked D24S8): no R24G8 depth twin here, so its exclusion and copy pass are gone (a D24S8 never starts a stretch); the work is seen at the PC DrawInstanced / DrawIndexedInstanced hooks, the title's Dispatch/DispatchX, ExecuteIndirect and DispatchMesh (which go past those hooks) and the UAV clears, not at set_compute_pipeline (XCL's own passes) nor the PC ExecuteIndirect hook (XCL's split dispatches would count as draws there); copies name the object the list saw go into PARK; a buffer leaving UNORDERED_ACCESS in parts after a draw wrote its plane keeps the plane for every part. The XCL_DEPTH_PLANE_NOW and XCL_TWIN_TRACE switches are in the next commit. (cherry picked from commit 77dfb95595855fca9c8360f73031e45061faee72) (cherry picked from commit 0e68d6065eb097364e705a8aa366524966930a68) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 8 + crates/xcl/src/hle/d3d12x/depth_uav.rs | 365 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 36 +++ crates/xcl/src/hle/d3d12x/real.rs | 2 + 4 files changed, 406 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0c064f8f93..4ad0600ec9 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3381,6 +3381,8 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DrawRecord); let _c = capture_work(this, || super::capture::WorkKind::DispatchMesh([x, y, z]), true); + // (past the PC list's hook of draws: `depth_uav::before_work`) + super::list_x::depth_twins_before_work(this, true); type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); let (raw_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); @@ -3575,6 +3577,9 @@ unsafe fn execute_indirect_snapshot( type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let dispatches = signature.dispatches(); + // (its PC call goes past the PC list's hook, which XCL's own dispatches through + // ExecuteIndirect take: `depth_uav::before_work` here) + super::list_x::depth_twins_before_work(this, !dispatches); let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); let _t = super::look_stats::deep().then(|| { crate::hle::api_cost::time(if dispatches { @@ -4798,6 +4803,9 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DispatchRecord); let (bound_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); let _c = capture_work(this, || captured_dispatch(bound_pso, [x, y, z], flags), false); + // (it may write a depth twin: `depth_uav::before_work`; where the title put it, also when + // it is recorded at the submit) + super::list_x::depth_twins_before_work(this, false); // (recorded at the submit through this call, with everything below: counted there) if let Some(resolution) = &resolution { if super::list_x::defer_retained(this, resolution, super::list_x::Deferred::Dispatch(x, y, z, flags)) { diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 959d7faa85..009de7f337 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -26,7 +26,7 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::core::Interface; @@ -84,9 +84,23 @@ struct Cell { /// the same for the stencil plane's twin: the last transition into UNORDERED_ACCESS copied /// the plane into it, so it holds the plane and what shaders wrote since (`plan_barriers`) stencil_entered: AtomicBool, + /// the number of the stretch the title has had the buffer in UNORDERED_ACCESS since a + /// transition of all of it that put the depth twin in step (0: none): draws that test against + /// the buffer then are watched (`before_work`) + live: AtomicU64, + /// which of the depth plane and its twin holds what was written last in that stretch (`Side`) + side: AtomicU8, inner: Mutex, } +impl Drop for Cell { + fn drop(&mut self) { + if *self.live.get_mut() != 0 { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + } +} + #[derive(Default)] struct Inner { /// registered objects of this buffer @@ -128,7 +142,6 @@ struct Object { } #[derive(Clone)] -#[allow(dead_code)] // (read once DSV binds are followed) struct Dsv { res: usize, /// D3D12_DSV_FLAGS of the view: 1 read-only depth, 2 read-only stencil @@ -161,6 +174,14 @@ static CELL_IDS: AtomicU64 = AtomicU64::new(1); static TO_TWIN: AtomicU64 = AtomicU64::new(0); static TO_PLANE: AtomicU64 = AtomicU64::new(0); static IN_STEP: AtomicU64 = AtomicU64::new(0); +/// Cells with a `live` stretch, and the stretches numbered. +static LIVE: AtomicUsize = AtomicUsize::new(0); +static STRETCHES: AtomicU64 = AtomicU64::new(1); +/// Copies made before draws and dispatches inside such a stretch (`before_work`): [into the +/// twin, into the plane]; copies out of UNORDERED_ACCESS not made because a draw's depth test +/// left the plane the newer side. +static WORK_COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +static PLANE_KEPT: AtomicU64 = AtomicU64::new(0); /// Whether a twin is alive: the gate of the paths that record. pub(super) fn any() -> bool { @@ -205,7 +226,7 @@ fn register(res: usize, x: &[u8; 0x38], at: Option, pc_state: u32) -> boo let cells = g.get_or_insert_with(HashMap::new); let cell = cells .entry(key) - .or_insert_with(|| Arc::new(Cell { key, id: CELL_IDS.fetch_add(1, Ordering::Relaxed), console_format: u32_at(x, 0x20), twinned: AtomicBool::new(false), entered: AtomicBool::new(false), stencil_entered: AtomicBool::new(false), inner: Mutex::new(Inner::default()) })) + .or_insert_with(|| Arc::new(Cell { key, id: CELL_IDS.fetch_add(1, Ordering::Relaxed), console_format: u32_at(x, 0x20), twinned: AtomicBool::new(false), entered: AtomicBool::new(false), stencil_entered: AtomicBool::new(false), live: AtomicU64::new(0), side: AtomicU8::new(Side::Both as u8), inner: Mutex::new(Inner::default()) })) .clone(); { let mut inner = cell.inner.lock().unwrap(); @@ -458,6 +479,10 @@ pub(super) struct Plan { /// after them: depth planes into twins (the buffer rests in PARK; the twin /// UNORDERED_ACCESS → COPY_DEST and back) pub to_twin: Vec, + /// buffers whose `live` stretch these barriers began: the list follows them (`Owed::apply`) + pub live: Vec, + /// Cells whose stretch these barriers ended + pub settled: Vec, } /// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16 or D32S8 buffer, and the @@ -579,9 +604,18 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if leaving { before = PARK; // (a twin whose last way in was not copied holds something else than the plane: not - // copied back – what the shaders wrote into it is lost, as without a twin) + // copied back – what the shaders wrote into it is lost, as without a twin; nor one + // whose plane draws tested and wrote since the twin was last copied into it there, + // `before_work`: the plane holds the newer depth) + let plane_newer = o.cell.live.load(Ordering::Relaxed) != 0 && Side::of(&o.cell) == Side::Plane; let t = (direct && !subs.is_empty()).then(|| twin_if_made(&o)).flatten(); - if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed)) { + if plane_newer && t.is_some() { + let c = PLANE_KEPT.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!("D3D12.X: depth UAV twin: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x} after draws tested against its plane: the twin is not copied into it ({c} such transitions so far)"); + } + } + if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed) && !plane_newer) { before = COPY_DEST; let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; if c <= 4 || c.is_power_of_two() { @@ -595,9 +629,19 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if writes(after) { in_step.retain(|&c| c != id); } + if end_stretch(&o.cell) { + plan.settled.push(id); + // (the plane holds the newer depth of every subresource – the copies before draws + // are whole: the twin is not copied over what is left of it in UNORDERED_ACCESS + // either when that leaves) + if plane_newer { + entered.store(false, Ordering::Relaxed); + } + } } if entering { after = PARK; + let whole = direct && sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !subs.is_empty(); if !direct { entered.store(false, Ordering::Relaxed); } else if !subs.is_empty() { @@ -622,6 +666,14 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, entered.store(false, Ordering::Relaxed); } } + // all of a buffer whose twin now holds its depth plane, on a DIRECT list: a stretch + // whose draws that test against the buffer are watched (`before_work`) + if whole && entered.load(Ordering::Relaxed) { + let stretch = begin_stretch(&o.cell); + plan.live.push(Acting { id, stretch, cell: Arc::downgrade(&o.cell), res }); + } else if end_stretch(&o.cell) { + plan.settled.push(id); + } } (b[5], b[6]) = (before, after); if before != after { @@ -688,6 +740,177 @@ fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) } +// --------------------------------------------------------------------------------------- +// Draws that test against a buffer the title has in UNORDERED_ACCESS +// +// The twin is copied into the plane where the title moves the buffer out of UNORDERED_ACCESS. +// A draw that tests against the buffer before that – with no transition in between, the title +// leaving it in UNORDERED_ACCESS – tested the plane as it was before the shaders wrote the twin. +// (VIctory-Neo, https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later, 7da5c9d "the depth +// image a pixel program wrote is brought up to date before the draws that test against it": +// the title marks a mirror's pixels with a pixel program writing the depth of the mirror's view +// through unordered access, then draws that view against it in the same list; with the copy +// left for later the mirror showed the sky.) Here, in such a stretch, the list that began it +// follows which side was written last and copies it into the other before the work that uses +// that one: the twin into the plane before a draw whose depth target names the buffer, the plane +// into the twin before any other draw or dispatch (it may write the twin: XCL does not see which +// views a translated shader reaches). Both are copies of whole planes between resources in +// states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS): nothing bound on +// the list changes. A D24S8 buffer's depth plane has no twin: its stretches are not followed. +// --------------------------------------------------------------------------------------- + +/// The stretch of `cell` in UNORDERED_ACCESS begins; its number. The two sides hold the same. +fn begin_stretch(cell: &Cell) -> u64 { + let n = STRETCHES.fetch_add(1, Ordering::Relaxed); + cell.side.store(Side::Both as u8, Ordering::Relaxed); + if cell.live.swap(n, Ordering::Relaxed) == 0 { + LIVE.fetch_add(1, Ordering::Relaxed); + } + n +} + +/// The stretch of `cell` ends; false: it had none. +fn end_stretch(cell: &Cell) -> bool { + let had = cell.live.swap(0, Ordering::Relaxed) != 0; + if had { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + had +} + +/// Whether a buffer is in a `live` stretch: the gate of the draw and dispatch hooks. +pub(super) fn any_live() -> bool { + LIVE.load(Ordering::Relaxed) != 0 +} + +/// Which of a depth plane and its twin holds what was written last in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +enum Side { + /// the same (the twin was copied from the plane, or the other way) + Both = 0, + /// shaders may have written the twin since + Twin = 1, + /// a draw tested against the plane, and may have written it + Plane = 2, +} + +impl Side { + fn of(cell: &Cell) -> Side { + match cell.side.load(Ordering::Relaxed) { + 1 => Side::Twin, + 2 => Side::Plane, + _ => Side::Both, + } + } +} + +/// What a draw or dispatch does with a buffer in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Use { + /// tests against its plane (its depth target names the buffer); `write`: the view does not + /// make the depth read only + Depth { write: bool }, + /// anything else: it may write the twin through a UAV + Shader, +} + +/// The copy a use `u` of a buffer whose newer side is `side` needs first (Some(true): the plane +/// into the twin, Some(false): the twin into the plane), and the newer side after it. +fn step(side: Side, u: Use) -> (Option, Side) { + match u { + // (a read-only depth target leaves the two as they were after the copy) + Use::Depth { write } => ((side == Side::Twin).then_some(false), if write || side == Side::Plane { Side::Plane } else { Side::Both }), + Use::Shader => ((side == Side::Plane).then_some(true), Side::Twin), + } +} + +/// A buffer a list follows in its `live` stretch. +#[derive(Clone)] +pub(super) struct Acting { + id: u64, + stretch: u64, + cell: Weak, + /// the object the title's transition named + res: usize, +} + +/// The buffers a list follows in their `live` stretches (`before_work`). It is the list's, and +/// goes with its recording. +#[derive(Default)] +pub(super) struct Owed(Vec); + +impl Owed { + /// The buffers whose stretches `plan`'s barriers began are followed, those they ended not. + pub(super) fn apply(&mut self, plan: &Plan) { + if plan.live.is_empty() && plan.settled.is_empty() { + return; + } + self.0.retain(|a| !plan.settled.contains(&a.id) && !plan.live.iter().any(|l| l.id == a.id)); + self.0.extend(plan.live.iter().cloned()); + } +} + +/// A copy to record before a draw or dispatch (`before_work`): of the plane into the twin +/// (`to_twin`) or of the twin into the plane, all the plane's subresources. +pub(super) struct WorkCopy { + pub copy: PlaneCopy, + pub to_twin: bool, +} + +/// All of the depth plane of `res` (an object of `cell`) and its twin, and the twin's number. +fn whole_copy(cell: &Cell, res: usize) -> Option<(PlaneCopy, u64)> { + let (twin, k) = cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n))?; + let n = cell.key.mips.max(1) as u32 * cell.key.array.max(1) as u32; + Some((PlaneCopy { depth: res, sub: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, subs: (0..n).collect(), twin }, k)) +} + +/// A draw whose depth target is the DSV at `dsv` (None: none, or a dispatch) is about to be +/// recorded on a DIRECT list that follows the buffers `owed`: the copies to record before it, +/// so that the side each buffer's use reads holds what was written last. A depth target of a +/// buffer in a stretch the list does not follow yet (begun on another list) is followed from +/// here on. +pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec { + let tested = dsv.filter(|_| DSV_ENTRIES.load(Ordering::Relaxed) != 0).and_then(|h| DSVS.get(h)).and_then(|d| Some((d.res, d.flags, d.cell.upgrade()?))); + if let Some((res, _, cell)) = &tested { + let stretch = cell.live.load(Ordering::Relaxed); + if stretch != 0 && !owed.0.iter().any(|a| a.id == cell.id) { + owed.0.push(Acting { id: cell.id, stretch, cell: Arc::downgrade(cell), res: *res }); + } + } + let mut out = Vec::new(); + owed.0.retain(|a| { + let Some(cell) = a.cell.upgrade() else { return false }; + if cell.live.load(Ordering::Relaxed) != a.stretch { + return false; + } + // (the copies name the object the list knows in PARK: another object of the buffer, a + // DSV's, may be in another PC state) + let target = a.res; + let u = match &tested { + Some((_, flags, c)) if Arc::ptr_eq(c, &cell) => Use::Depth { write: flags & 1 == 0 }, + _ => Use::Shader, + }; + let (copy, side) = step(Side::of(&cell), u); + if let Some(to_twin) = copy { + // (no twin: the side stays as it was) + let Some((c, k)) = whole_copy(&cell, target) else { return true }; + let n = WORK_COPIES[(!to_twin) as usize].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + if to_twin { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: work after draws that tested against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS: its depth plane is copied into the twin first ({n} such copies so far)"); + } else { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: a draw tests against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS, after shaders may have written its twin: the twin is copied into the depth plane first ({n} such copies so far)"); + } + } + out.push(WorkCopy { copy: c, to_twin }); + } + cell.side.store(side as u8, Ordering::Relaxed); + true + }); + out +} + /// A UAV of a depth buffer stays a null view (`Resolve::Null`). pub(super) fn null_view(why: &'static str) { #[cfg(test)] @@ -1550,6 +1773,138 @@ mod tests { } } + #[test] + fn a_draws_depth_test_and_other_work_each_get_the_side_written_last() { + let depth = |write| Use::Depth { write }; + // a draw that tests against the buffer: the twin into the plane when shaders may have + // written it; the plane is the newer side after (unless the view is read only) + assert_eq!(step(Side::Twin, depth(true)), (Some(false), Side::Plane)); + assert_eq!(step(Side::Both, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Plane, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Twin, depth(false)), (Some(false), Side::Both)); + assert_eq!(step(Side::Both, depth(false)), (None, Side::Both)); + assert_eq!(step(Side::Plane, depth(false)), (None, Side::Plane)); + // any other work: the plane into the twin after such draws; the twin is the newer side after + assert_eq!(step(Side::Plane, Use::Shader), (Some(true), Side::Twin)); + assert_eq!(step(Side::Both, Use::Shader), (None, Side::Twin)); + assert_eq!(step(Side::Twin, Use::Shader), (None, Side::Twin)); + } + + /// (the copies before work: (object, into the twin, subresources)) + fn work(c: &[WorkCopy]) -> Vec<(usize, bool, Vec)> { + c.iter().map(|c| (c.copy.depth, c.to_twin, c.copy.subs.clone())).collect() + } + + /// A title's barrier on a DIRECT list that follows `owed`: the plan's copies into the plane + /// and the stretches it ended. + fn barrier(b: [u32; 8], owed: &mut Owed) -> (Vec<(usize, u32, Vec, usize)>, Vec) { + let mut v = vec![b]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + owed.apply(&p); + (copies(&p.to_plane), p.settled) + } + + #[test] + fn draws_that_test_against_a_buffer_left_in_unordered_access_get_what_shaders_wrote() { + let (res, dsv, ro_dsv) = (0x7E50_0000_1000usize, 0x7E50_0001_0000usize, 0x7E50_0001_0040usize); + // a console D32 of 2 mips with unordered access and a depth twin, two DSVs of it + let mut x = desc(3, 1280, 736, 40, 1, 6); + x[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(res, &x, None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + note_dsv(dsv, res, 0); + note_dsv(ro_dsv, res, 1); + let id = cell_of(res).unwrap().id; + let mut owed = Owed::default(); + + // into UNORDERED_ACCESS: followed; a pixel program writes the twin (any other draw) + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut owed); + assert!(any_live()); + assert!(before_work(&mut owed, None).is_empty(), "the two hold the same"); + // the draws that test against it: the twin into the plane first, once + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(dsv)).is_empty(), "the plane holds it now"); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + // work after them may read the twin: the plane, which those draws wrote, into the twin + assert_eq!(work(&before_work(&mut owed, None)), [(res, true, vec![0, 1])]); + assert!(before_work(&mut owed, None).is_empty()); + // a read-only depth target after it: the twin into the plane, and the two hold the same + assert_eq!(work(&before_work(&mut owed, Some(ro_dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + assert!(before_work(&mut owed, Some(dsv)).is_empty()); + // out of UNORDERED_ACCESS after a draw tested (and wrote) the plane: the twin is not + // copied over it; the stretch ends + let kept = PLANE_KEPT.load(Ordering::Relaxed); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_READ), &mut owed), (vec![], vec![id])); + assert!(PLANE_KEPT.load(Ordering::Relaxed) > kept); + assert!(before_work(&mut owed, Some(dsv)).is_empty() && owed.0.is_empty(), "no longer followed"); + + // in and out with shaders only: copied back as before + barrier(tr(res, ALL, DEPTH_READ, UA), &mut owed); + assert!(before_work(&mut owed, None).is_empty()); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut owed), (vec![(res, ALL, vec![0, 1], t.as_raw() as usize)], vec![id])); + + // a stretch begun on another list: this one follows it from a draw that tests against it + let mut other = Owed::default(); + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut other); + assert!(before_work(&mut owed, None).is_empty(), "not followed here: nothing"); + assert!(before_work(&mut other, None).is_empty()); + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert_eq!(owed.0.len(), 1); + barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut other); + + // not followed: one subresource, or into UNORDERED_ACCESS on a compute list + barrier(tr(res, 1, DEPTH_WRITE, UA), &mut owed); + assert!(cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + barrier(tr(res, 1, UA, DEPTH_WRITE), &mut owed); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, false, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + forget_dsv(dsv); + forget_dsv(ro_dsv); + } + + #[test] + fn a_plane_newer_than_its_twin_is_kept_when_the_buffer_leaves_unordered_access_in_parts() { + let (res, dsv) = (0x7E60_0000_1000usize, 0x7E60_0001_0000usize); + // a console D32 of 2 mips with a depth twin + let mut x = desc(3, 64, 64, 40, 1, 6); + x[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(res, &x, None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + note_dsv(dsv, res, 0); + let id = cell_of(res).unwrap().id; + let mut owed = Owed::default(); + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut owed); + // a draw tests against it and writes the plane + assert!(before_work(&mut owed, Some(dsv)).is_empty()); + // out of UNORDERED_ACCESS one mip at a time: the first ends the stretch, and the twin + // is not copied over either mip + assert_eq!(barrier(tr(res, 0, UA, DEPTH_READ), &mut owed), (vec![], vec![id])); + assert_eq!(barrier(tr(res, 1, UA, DEPTH_READ), &mut owed), (vec![], vec![])); + // the next way in copies the plane into the twin again, the way out back + let mut v = vec![tr(res, ALL, DEPTH_READ, UA)]; + assert_eq!(copies(&plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)).to_twin).len(), 1); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_READ), &mut owed).0.len(), 1); + forget(res); + forget_dsv(dsv); + } + + #[test] + fn a_d24s8_buffer_in_unordered_access_is_not_followed() { + let res = 0x7E70_0000_1000usize; + // a console D16S8 (PC R24G8): parked, its depth plane has no twin + assert!(register(res, &desc(3, 64, 64, 118, 1, 6), None, DEPTH_WRITE)); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert_eq!(v, [tr(res, ALL, DEPTH_WRITE, PARK)]); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + } + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). #[test] fn with_the_switch_off_the_titles_barriers_go_as_they_came() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4f3dae2265..60f187d60b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -949,6 +949,9 @@ struct ListState { own_alloc: Option, /// depth buffers whose depth plane and twin hold the same on this recording (`depth_uav::plan_barriers`) depth_in_step: Vec, + /// depth buffers the title has in UNORDERED_ACCESS whose draws this recording follows + /// (`depth_uav::before_work`) + depth_owed: super::depth_uav::Owed, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -5683,6 +5686,35 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } } +/// Before a draw (`draw`: its depth target the one bound) or a dispatch on `list`: the copies +/// between depth planes and their twins that the buffers the title has in UNORDERED_ACCESS need +/// first (`depth_uav::before_work`). Copies and barriers only: nothing bound on the list changes. +pub(super) unsafe fn depth_twins_before_work(list: *mut c_void, draw: bool) { + if !super::depth_uav::any_live() { + return; + } + let (mut owed, dsv) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return }; + if s.list_type != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + (std::mem::take(&mut s.depth_owed), if draw { s.bindings.render_targets.as_ref().and_then(|rt| rt.dsv) } else { None }) + }; + let copies = super::depth_uav::before_work(&mut owed, dsv); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.depth_owed = owed; + } + for c in copies { + plane_copies_on(list, std::slice::from_ref(&c.copy), c.to_twin); + // (into the plane: it is left in COPY_DEST there, back where the title has it) + if !c.to_twin { + let tr = [0, 0, c.copy.depth as u32, (c.copy.depth as u64 >> 32) as u32, c.copy.sub, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32, super::depth_uav::PARK, 0]; + pc::(list, PC_RESOURCE_BARRIER)(list, 1, &tr); + } + } +} + /// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { if !DEPTH_BIAS_USED.load(Ordering::Acquire) { @@ -6338,6 +6370,7 @@ unsafe fn reset_pc_inner(this: *mut c_void, alloc: usize, pso: usize) -> i32 { s.pred_in_state = false; s.bindings = Bindings::default(); s.depth_in_step.clear(); + s.depth_owed = Default::default(); (s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), old_generations) }; drop(old_generations); @@ -6461,6 +6494,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 let plan = super::depth_uav::plan_barriers(&mut out, direct, &mut in_step); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.depth_in_step = in_step; + s.depth_owed.apply(&plan); } plan }); @@ -7185,6 +7219,8 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi } }; let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; + // (a clear of a depth twin writes it) + depth_twins_before_work(this, false); pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..a74e40ecb9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11433,6 +11433,7 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { } unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { + super::list_x::depth_twins_before_work(this, true); super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32); let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "DrawInstanced"))); @@ -11440,6 +11441,7 @@ unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icou } unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u32, inst: u32, si: u32, bv: i32, sinst: u32) { + super::list_x::depth_twins_before_work(this, true); super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32); let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "DrawIndexedInstanced"))); From ae2976f6e6924ec4f15d52232f61d46e1837abe8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:14:47 +0100 Subject: [PATCH 2/2] D3D12.X: XCL_DEPTH_PLANE_NOW and XCL_TWIN_TRACE for depth twins in UAV The switch and the trace that came with "draws that test a depth buffer left in UAV get its twin first" (raylitebull, 0e68d606 on amd-dev), split from it as CONTRIBUTING asks for diagnostics and env-var switches. XCL_DEPTH_PLANE_NOW=0 turns the following of draws inside a stretch in UNORDERED_ACCESS off (on by default): no stretch begins, so the copies are made around the title's transitions only, as before it. XCL_TWIN_TRACE= logs, for depth buffers of that height (736: a mirror's view in a retail title), the title's transitions into and out of UNORDERED_ACCESS, the UAVs made on twins, the twin copies, the DSV binds and the draws that test against them (first 600 lines), so a game run shows which of these the title does. Port onto main: the trace lines of the R24G8 copy pass are gone (main has no R24G8 depth twin); the rest is as in the original. (cherry picked from commit 77dfb95595855fca9c8360f73031e45061faee72) (cherry picked from commit 0e68d6065eb097364e705a8aa366524966930a68) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 70 ++++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/list_x.rs | 3 ++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 009de7f337..263b626031 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -362,10 +362,12 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< } // (its states stay the title's: the twin would never be copied) if !stencil && (o.cell.inner.lock().unwrap().made_in.unwrap_or(o.state) | o.state) & UNORDERED_ACCESS != 0 { + twin_trace(&key, || format!("a UAV of object {:#x} stays a null view: the buffer was made in UNORDERED_ACCESS", res as usize)); return Resolve::Null("the buffer was made in UNORDERED_ACCESS"); } // (the Cell holds the twin) - let Some((twin, _)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + let Some((twin, n)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + twin_trace(&key, || format!("a UAV of the {} plane of object {:#x} is a view of twin #{n}", if stencil { "stencil" } else { "depth" }, res as usize)); REDIRECTED.fetch_add(1, Ordering::Relaxed); Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, key.format == 53) }) } @@ -615,6 +617,7 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, crate::xlog_info!("D3D12.X: depth UAV twin: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x} after draws tested against its plane: the twin is not copied into it ({c} such transitions so far)"); } } + twin_trace(&key, || format!("out of UNORDERED_ACCESS into {after:#x} (subresource {sub:#x}, direct {direct}): {}", if t.is_none() { "no twin copy (no twin, or a compute list)" } else if plane_newer { "the plane is newer, not copied" } else if entered.load(Ordering::Relaxed) { "the twin is copied into the plane" } else { "the twin's way in was not copied: not copied back" })); if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed) && !plane_newer) { before = COPY_DEST; let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; @@ -668,12 +671,14 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, } // all of a buffer whose twin now holds its depth plane, on a DIRECT list: a stretch // whose draws that test against the buffer are watched (`before_work`) - if whole && entered.load(Ordering::Relaxed) { + let watched = whole && entered.load(Ordering::Relaxed) && plane_now(); + if watched { let stretch = begin_stretch(&o.cell); plan.live.push(Acting { id, stretch, cell: Arc::downgrade(&o.cell), res }); } else if end_stretch(&o.cell) { plan.settled.push(id); } + twin_trace(&key, || format!("into UNORDERED_ACCESS from {before:#x} (subresource {sub:#x}, direct {direct}): the twin {}; draws testing against it are {}watched", if entered.load(Ordering::Relaxed) { "holds the plane" } else { "does not hold the plane" }, if watched { "" } else { "not " })); } (b[5], b[6]) = (before, after); if before != after { @@ -757,8 +762,15 @@ fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { // views a translated shader reaches). Both are copies of whole planes between resources in // states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS): nothing bound on // the list changes. A D24S8 buffer's depth plane has no twin: its stretches are not followed. +// On unless `XCL_DEPTH_PLANE_NOW=0`. // --------------------------------------------------------------------------------------- +/// Whether draws inside a `live` stretch are followed (`XCL_DEPTH_PLANE_NOW`, on unless "0"). +fn plane_now() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_PLANE_NOW").ok().as_deref(), true)) +} + /// The stretch of `cell` in UNORDERED_ACCESS begins; its number. The two sides hold the same. fn begin_stretch(cell: &Cell) -> u64 { let n = STRETCHES.fetch_add(1, Ordering::Relaxed); @@ -875,6 +887,7 @@ pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec if let Some((res, _, cell)) = &tested { let stretch = cell.live.load(Ordering::Relaxed); if stretch != 0 && !owed.0.iter().any(|a| a.id == cell.id) { + twin_trace(&cell.key, || format!("a list follows the stretch begun elsewhere from a draw that tests against object {res:#x}")); owed.0.push(Acting { id: cell.id, stretch, cell: Arc::downgrade(cell), res: *res }); } } @@ -891,7 +904,8 @@ pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec Some((_, flags, c)) if Arc::ptr_eq(c, &cell) => Use::Depth { write: flags & 1 == 0 }, _ => Use::Shader, }; - let (copy, side) = step(Side::of(&cell), u); + let was = Side::of(&cell); + let (copy, side) = step(was, u); if let Some(to_twin) = copy { // (no twin: the side stays as it was) let Some((c, k)) = whole_copy(&cell, target) else { return true }; @@ -903,7 +917,10 @@ pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec crate::xlog_info!("D3D12.X: depth UAV twin #{k}: a draw tests against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS, after shaders may have written its twin: the twin is copied into the depth plane first ({n} such copies so far)"); } } + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the {} first", if to_twin { "plane is copied into the twin" } else { "twin is copied into the plane" })); out.push(WorkCopy { copy: c, to_twin }); + } else if was != side && matches!(u, Use::Depth { .. }) { + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the sides held the same, no copy")); } cell.side.store(side as u8, Ordering::Relaxed); true @@ -911,6 +928,53 @@ pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec out } +/// `XCL_TWIN_TRACE=` (a test aid): what XCL does with the depth buffers of that height +/// that shaders write – the title's transitions into and out of UNORDERED_ACCESS, the copies of +/// their twins, the DSVs bound and the draws that test against them – a line each for the first +/// 600 (a mirror's view is 736 high in a retail title). +fn twin_trace(key: &Key, what: impl FnOnce() -> String) { + let h = trace_height(); + if h == 0 || key.height != h { + return; + } + static SAID: AtomicU32 = AtomicU32::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) >= 600 { + return; + } + crate::xlog_info!( + "D3D12.X: XCL_TWIN_TRACE: frame {}: depth buffer at {:#x} ({}x{}x{}, PC format {}): {}", + super::present::counters().1, + key.at, + key.width, + key.height, + key.array, + key.format, + what() + ); +} + +fn trace_height() -> u32 { + static HEIGHT: OnceLock = OnceLock::new(); + *HEIGHT.get_or_init(|| std::env::var("XCL_TWIN_TRACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `XCL_TWIN_TRACE`: list `list` binds the DSV at `dsv`. +pub(super) fn trace_dsv_bind(list: usize, dsv: usize) { + if trace_height() == 0 || DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return; + } + let Some(d) = DSVS.get(dsv) else { return }; + let Some(cell) = d.cell.upgrade() else { return }; + twin_trace(&cell.key, || { + format!( + "list {list:#x} binds a DSV of object {:#x} (flags {:#x}); {}", + d.res, + d.flags, + if cell.live.load(Ordering::Relaxed) != 0 { format!("in a followed stretch in UNORDERED_ACCESS, the newer side {:?}", Side::of(&cell)) } else { "not in UNORDERED_ACCESS as far as XCL followed it".to_owned() } + ) + }); +} + /// A UAV of a depth buffer stays a null view (`Resolve::Null`). pub(super) fn null_view(why: &'static str) { #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 60f187d60b..57e730577b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -703,6 +703,9 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const let handles = if read_count == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_count).to_vec() }; let d = dsv.as_ref().copied(); with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); + if let Some(d) = d { + super::depth_uav::trace_dsv_bind(this as usize, d); + } } /// The render target views bound on `list` (each one of a single descriptor range too).