From b0a3feb0c2867b34053bb2ca669a7daba798fd9f Mon Sep 17 00:00:00 2001 From: imnicho Date: Sat, 28 Nov 2026 01:21:09 +0100 Subject: [PATCH 1/3] D3D12.X: the depth plane of an R24G8 buffer has a twin, drawn into the plane before its DSV is bound A retail title's tiled lighting tests a console D16_UNORM_S8_UINT buffer (R24G8 on the PC) with EQUAL, after a compute program wrote a count for each pixel into its depth plane through a UAV. The title keeps the buffer in a depth state all the while, so no transition says when the plane was written, and a D3D12 copy cannot put a colour texture into a 24-bit plane. With XCL_DEPTH_UAV_TWIN_R24=1 (off by default; the other depth twins stay as they are) the depth plane of an R24G8 buffer gets a twin in depth_uav: R16 for the console's 16-bit depth formats, else R32. resolve_uav makes the title's UAV a view of it, and before_dsv_bind draws it into the plane, by a pass of XCL's own that writes SV_Depth, before the title's bind of a DSV of the buffer, when a dispatch was recorded since the buffer's last pass. A 16-bit twin is read as a count and written as count * (1.0f / 65535), the product the title's vertex shader makes. The planes' states are followed as the PC gets the title's transitions (PARK where the title has the buffer in UNORDERED_ACCESS); the pass moves the depth plane to DEPTH_WRITE and back and does not move the stencil plane. After review of the first version on nvidia-dev: - a clear of the twin makes the next bind draw it again (thehollowedone); - the pass's views are kept one set an object of the buffer, and the object itself keeps their two heaps until the PC destroys it, so a recorded list never names a heap that is gone (thehollowedone); - the pass's pipelines are made on a thread of their own where the twin is made, not on the recording thread at the first bind; a bind that comes before they are ready is left out and the next one draws (CharlyRien). The SV_Depth pass and the 16-bit steps are raylitebull's, from #1989 and its follow-up on amd-dev (3cda5bea). Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 573 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/list_x.rs | 58 +++ crates/xcl/src/hle/d3d12x/real.rs | 396 ++++++++++++++++- 3 files changed, 989 insertions(+), 38 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 959d7faa85..c9d18a6c3c 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -17,6 +17,16 @@ //! the shaders wrote reaches the next depth test or sampling). A transition names the state it //! leaves and the one it enters, so each copy starts and ends in states the title gave. //! +//! The depth plane of an R24G8 buffer (a console D16S8 or D24S8) has a twin as well, with +//! `XCL_DEPTH_UAV_TWIN_R24=1`: R16 for the console's 16-bit depth, else R32. A D3D12 copy cannot +//! put either into a 24-bit plane, and a retail title keeps such a buffer in a depth state while +//! its compute program writes it, so this twin is not copied at transitions: it is drawn into +//! the plane, by a pass of XCL's own that writes `SV_Depth`, before the title binds a DSV of the +//! buffer (`before_dsv_bind`). That is the case of a title whose compute program writes a number +//! for each pixel into such a plane and whose lighting draws then test it with EQUAL. (The pass +//! and the 16-bit steps after xcl-dev/xcl#1989 by raylitebull and its follow-up on `amd-dev`, +//! 3cda5bea.) What a draw or a clear writes into that plane does not reach the twin. +//! //! On unless `XCL_DEPTH_UAV_TWIN=0`; with the switch off nothing is registered, a UAV of a depth //! buffer stays a null view and every hook stops at one atomic load. //! @@ -44,6 +54,14 @@ pub(super) fn enabled() -> bool { *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_UAV_TWIN").ok().as_deref(), DEFAULT_ON)) } +/// Whether the depth plane of an R24G8 buffer gets a twin, drawn into the plane before a DSV of +/// the buffer is bound (`XCL_DEPTH_UAV_TWIN_R24=1`; off unless asked for). +fn r24_plane_twins() -> bool { + static ON: OnceLock = OnceLock::new(); + // (the tests of that twin run with it) + *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_UAV_TWIN_R24").ok().as_deref(), cfg!(test))) +} + /// "0" off, "1" on, anything else (or nothing) `default`. fn on(v: Option<&str>, default: bool) -> bool { match v.map(str::trim) { @@ -96,6 +114,11 @@ struct Inner { made_in: Option, /// [depth, stencil] twins: [Option; 2], + /// an R24G8 buffer's depth twin: the views `before_dsv_bind` draws it into the plane with, + /// by the object of the buffer whose plane they name + passes: HashMap, + /// `bind::activity`'s count of dispatches when the twin was last drawn into the plane + drawn_at: Option, } /// A plane's twin: a colour texture of the plane's size with unordered access, resting in @@ -104,6 +127,10 @@ struct Twin { res: ID3D12Resource, /// its number in the log (`#n`) n: u64, + /// the device it was made on + dev: usize, + /// the depth twin of an R24G8 buffer (counted in `R24_TWINS`) + r24: bool, /// a stencil plane's twin: the buffer the two are copied through (no colour format shares /// a family with a depth-stencil one, but the PC copies between a buffer and one plane); /// it rests in COPY_DEST @@ -117,6 +144,9 @@ unsafe impl Sync for Twin {} impl Drop for Twin { fn drop(&mut self) { TWINS.fetch_sub(1, Ordering::Relaxed); + if self.r24 { + R24_TWINS.fetch_sub(1, Ordering::Relaxed); + } } } @@ -125,10 +155,12 @@ struct Object { cell: Arc, /// the PC state the object was created in state: u32, + /// the PC states the title's transitions left the object's depth plane and its stencil plane + /// in (`note_plane_state`); `STATE_UNKNOWN` once a transition named a part of the plane only + now: Arc<[AtomicU32; 2]>, } #[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 @@ -156,6 +188,16 @@ static UAV_CLEARS: AtomicU64 = AtomicU64::new(0); static CLEARS_NOT_DONE: AtomicU64 = AtomicU64::new(0); /// Cell numbers given. static CELL_IDS: AtomicU64 = AtomicU64::new(1); +/// Depth twins of R24G8 buffers alive: the gate of `before_dsv_bind`. +static R24_TWINS: AtomicUsize = AtomicUsize::new(0); +/// Passes that drew a twin into its R24G8 depth plane, DSV binds that needed none (nothing was +/// dispatched since the last one), and binds left without one (the plane's state not known, or +/// the pass could not be made). +static PLANE_PASSES: AtomicU64 = AtomicU64::new(0); +static PLANE_PASSES_SPARED: AtomicU64 = AtomicU64::new(0); +static PLANE_PASSES_LEFT: AtomicU64 = AtomicU64::new(0); +/// `Object::now`: the depth plane's state is not known. +const STATE_UNKNOWN: u32 = u32::MAX; /// Copies of a depth plane into its twin, of a twin into its plane, and copies into the twin not /// done since the two were in step (`plan_barriers`). static TO_TWIN: AtomicU64 = AtomicU64::new(0); @@ -233,13 +275,13 @@ fn register(res: usize, x: &[u8; 0x38], at: Option, pc_state: u32) -> boo ); } } - let gone = match OBJECTS.insert(res, Object { cell, state: pc_state }) { + let gone = match OBJECTS.insert(res, Object { cell, state: pc_state, now: Arc::new([AtomicU32::new(pc_state), AtomicU32::new(pc_state)]) }) { None => { REGISTERED.fetch_add(1, Ordering::Relaxed); Default::default() } // (an object XCL did not see released: its membership goes back) - Some(old) => leave(cells, &old.cell), + Some(old) => leave(cells, &old.cell, res), }; drop(g); drop(gone); @@ -263,11 +305,14 @@ pub(super) fn by_address(f: impl FnOnce() -> R) -> R { /// One object of `cell` is gone; the last one takes the Cell with it, and its twins, which the /// caller drops outside every lock (their Release goes through `real::res_release`). #[must_use] -fn leave(cells: &mut HashMap>, cell: &Arc) -> [Option; 2] { +fn leave(cells: &mut HashMap>, cell: &Arc, res: usize) -> [Option; 2] { let mut inner = cell.inner.lock().unwrap(); + // (the object keeps its pass's heaps itself until it is destroyed: `retain_pass_views`) + inner.passes.remove(&res); inner.members = inner.members.saturating_sub(1); if inner.members == 0 && cells.get(&cell.key).is_some_and(|c| Arc::ptr_eq(c, cell)) { cells.remove(&cell.key); + (inner.passes, inner.drawn_at) = (HashMap::new(), None); return std::mem::take(&mut inner.twins); } Default::default() @@ -280,7 +325,7 @@ pub(super) fn forget(res: usize) { } let Some(o) = OBJECTS.remove(res) else { return }; REGISTERED.fetch_sub(1, Ordering::Relaxed); - let gone = CELLS.lock().unwrap().as_mut().map(|cells| leave(cells, &o.cell)); + let gone = CELLS.lock().unwrap().as_mut().map(|cells| leave(cells, &o.cell, res)); drop(gone); } @@ -296,7 +341,7 @@ pub(super) enum Resolve { /// CreateUnorderedAccessView of `res` (description `rd`) with the title's view `view` as it came: /// a UAV of the stencil plane of a kept two-plane depth buffer, or of the depth plane of a kept -/// D32, D16 or D32S8 one, is made on the plane's twin (made now when there is none yet). +/// buffer, is made on the plane's twin (made now when there is none yet). pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option<&D3D12_RESOURCE_DESC>, view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> Resolve { let Some(rd) = rd.filter(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 && d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0) else { return Resolve::NotOurs; @@ -335,18 +380,21 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< } } let stencil = stencil_view(view); - // (a D24S8's depth plane: no UAV format holds it as a shader reads it) - if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 53) } { - return Resolve::Null("its depth plane has no twin yet"); + if stencil && !matches!(key.format, 19 | 44) { + return Resolve::Null("it has no stencil plane"); + } + if !stencil && key.format == 44 && !r24_plane_twins() { + return Resolve::Null("the depth plane of an R24G8 buffer has a twin only with XCL_DEPTH_UAV_TWIN_R24=1"); } - // (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 { + // (its states stay the title's: the twin would never be copied. An R24G8 buffer's twin is + // not copied at transitions but drawn into the plane, `before_dsv_bind`) + if !stencil && key.format != 44 && (o.cell.inner.lock().unwrap().made_in.unwrap_or(o.state) | o.state) & UNORDERED_ACCESS != 0 { 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") }; 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) }) + Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, depth_twin_r16(key.format, o.cell.console_format)) }) } /// The twin of `plane` (0 depth, 1 stencil) of the buffer `o` is in, and its number: the one it @@ -357,11 +405,19 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D if let Some(t) = &inner.twins[plane] { return Some((t.res.clone(), t.n)); } - let t = make_twin(dev, &key, twin_format(key.format, plane))?; + let t = make_twin(dev, &key, twin_format(key.format, o.cell.console_format, plane))?; TWINS.fetch_add(1, Ordering::Relaxed); + let r24 = plane == 0 && key.format == 44; + if r24 { + R24_TWINS.fetch_add(1, Ordering::Relaxed); + } let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; let through = if plane == 1 { make_through(dev, &key) } else { None }; - inner.twins[plane] = Some(Twin { res: t.clone(), n, through }); + inner.twins[plane] = Some(Twin { res: t.clone(), n, dev: dev as usize, r24, through }); + if r24 { + // (its pass's pipelines are made now, on a thread of their own: not at the first bind) + start_pass_pipelines(dev); + } o.cell.twinned.store(true, Ordering::Relaxed); // (the state of the title's object; that of the UAV's own when the title made none) let state = inner.made_in.unwrap_or(o.state); @@ -377,6 +433,18 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D key.at, state ); + } else if r24 { + crate::xlog_info!( + "D3D12.X: depth UAV twin #{n}: the depth plane of a {}x{}x{} depth buffer (PC format {}, console format {}) at {:#x} is an R{} texture, drawn into the plane before the title binds a DSV of the buffer; the buffer was made in state {:#x}", + key.width, + key.height, + key.array, + key.format, + o.cell.console_format, + key.at, + if depth_twin_r16(key.format, o.cell.console_format) { 16 } else { 32 }, + state + ); } else { crate::xlog_info!( "D3D12.X: depth UAV twin #{n}: the depth plane of a {}x{}x{} depth buffer (PC format {}, console format {}) at {:#x} is an R{} texture, copied from the plane when the title moves the buffer into UNORDERED_ACCESS and back when it moves it out; the buffer was made in state {:#x}", @@ -394,16 +462,24 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D Some((t, n)) } -/// The format of the twin of `plane` of a buffer of the PC format `format`: R8 for the stencil -/// plane, R16 for D16's depth, R32 for D32's and D32S8's (the plane copies as R32_TYPELESS). -fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { - match (plane, format) { - (1, _) => DXGI_FORMAT_R8_TYPELESS, - (_, 53) => DXGI_FORMAT_R16_TYPELESS, +/// The format of the twin of `plane` of a buffer of the PC format `format` made for the +/// console format `console`: R8 for the stencil plane, R16 for a 16-bit depth (`depth_twin_r16`), +/// R32 for D32's and D32S8's (the plane copies as R32_TYPELESS) and for a console D24S8's. +fn twin_format(format: u32, console: u32, plane: usize) -> DXGI_FORMAT { + match plane { + 1 => DXGI_FORMAT_R8_TYPELESS, + _ if depth_twin_r16(format, console) => DXGI_FORMAT_R16_TYPELESS, _ => DXGI_FORMAT_R32_TYPELESS, } } +/// The depth plane of a buffer of the PC format `format` made for the console format `console` +/// holds 16 bits: a D16, or the console's D16S8 family (118 – 120), which the PC has as R24G8 +/// (`device_x::pc_resource_desc`). +fn depth_twin_r16(format: u32, console: u32) -> bool { + format == 53 || (format == 44 && matches!(console, 118..=120)) +} + /// Where a buffer whose depth plane can have a twin rests while the title has it in /// UNORDERED_ACCESS: COPY_SOURCE, the state the plane is copied into the twin from. pub(super) const PARK: u32 = 0x800; @@ -503,7 +579,12 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, let mut out = Vec::with_capacity(barriers.len()); for mut b in barriers.drain(..) { let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; - let Some(o) = (b[0] == 0).then(|| OBJECTS.get(res)).flatten().filter(parked) else { + let kept = (b[0] == 0).then(|| OBJECTS.get(res)).flatten(); + // (an object whose transitions are not parked: its planes are where the title has them) + if let Some(o) = kept.as_ref().filter(|o| !parked(o)) { + note_plane_state(o, &b); + } + let Some(o) = kept.filter(parked) else { out.push(b); continue; }; @@ -515,6 +596,7 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if writes(after) { in_step.retain(|&c| c != id); } + note_plane_state(&o, &b); out.push(b); continue; } @@ -624,6 +706,8 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, } } (b[5], b[6]) = (before, after); + // (the state the PC's buffer is left in: `PARK` where the title has it in UNORDERED_ACCESS) + note_plane_state(&o, &b); if before != after { out.push(b); } @@ -688,6 +772,364 @@ 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)) } +/// A title's transition `b` of `o` as the PC gets it (`plan_with`): the states it leaves the depth +/// plane and the stencil plane in are kept (`Object::now`), for `before_dsv_bind`. The stencil plane's subresources follow the depth +/// plane's in the buffer; a transition of a part of a plane leaves that plane's state unknown. +fn note_plane_state(o: &Object, b: &[u32; 8]) { + let (flags, sub, after) = (b[1], b[4], b[6]); + // (a split transition counts at its end) + if flags & BEGIN_ONLY != 0 { + return; + } + let n = o.cell.key.mips.max(1) as u32 * o.cell.key.array.max(1) as u32; + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + o.now.iter().for_each(|p| p.store(after, Ordering::Relaxed)); + } else if let Some(p) = o.now.get((sub / n) as usize) { + p.store(if n == 1 { after } else { STATE_UNKNOWN }, Ordering::Relaxed); + } +} + +/// What draws an R24G8 buffer's depth twin into the plane of one object of the buffer: an SRV of +/// the twin in a view heap of its own, and a DSV of each level and slice of that object's depth +/// plane (level `m`, slice `a` at `m * array + a`), then each once more with the stencil plane +/// read only. Heaps of the PC's own, not adopted. +#[derive(Clone)] +struct PassViews { + srv_heap: ID3D12DescriptorHeap, + dsv_heap: ID3D12DescriptorHeap, + dsv_inc: usize, +} + +// D3D12 objects are free-threaded +unsafe impl Send for PassViews {} +unsafe impl Sync for PassViews {} + +/// The pass's root signature (two root constants: slice, level; the twin's SRV) and pipelines +/// on a device: `float` writes an R32_FLOAT twin's value, `steps` a 16-bit twin's. +struct PassPipelines { + rs: ID3D12RootSignature, + float: ID3D12PipelineState, + steps: ID3D12PipelineState, +} + +unsafe impl Send for PassPipelines {} +unsafe impl Sync for PassPipelines {} + +/// By device, once made; None: they could not be made there (said once). +static PASS_PIPELINES: Mutex>>>> = Mutex::new(None); +/// The devices whose pipelines were asked for (`start_pass_pipelines`). +static PASS_PIPELINES_ASKED: Mutex> = Mutex::new(Vec::new()); + +const PASS_VS: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0, visibility=SHADER_VISIBILITY_PIXEL), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL)" +[RootSignature(RS)] +float4 main(uint id : SV_VertexID) : SV_Position { + return float4(id == 2u ? 3.0 : -1.0, id == 1u ? 3.0 : -1.0, 0.0, 1.0); +} +"#; + +const PASS_PS_FLOAT: &str = r#" +Texture2DArray src : register(t0); +cbuffer C : register(b0) { uint slice; uint level; }; +float main(float4 pos : SV_Position) : SV_Depth { + return src.Load(int4(int2(pos.xy), int(slice), int(level))); +} +"#; + +/// A 16-bit twin's texel is a count of 1/65535 steps, and the depth written is that count times +/// the float nearest 1/65535 (0x37800080), which is how a title's vertex shader makes the depth +/// of the draw that tests the plane with EQUAL. Read as R16_UNORM the same texel can come out +/// one unit in the last place off; in 24 bits that is another value for some counts, and the +/// test fails for them. (After the follow-up of xcl-dev/xcl#1989 on `amd-dev`, 3cda5bea.) +const PASS_PS_STEPS: &str = r#" +Texture2DArray src : register(t0); +cbuffer C : register(b0) { uint slice; uint level; }; +float main(float4 pos : SV_Position) : SV_Depth { + return float(src.Load(int4(int2(pos.xy), int(slice), int(level)))) * asfloat(0x37800080u); +} +"#; + +/// The PC's own method `slot` of the device `dev`: past XCL's hooks when the device is adopted +/// (what the pass makes is XCL's, not a title's: no stand-ins, no bookkeeping). +unsafe fn dev_fn(dev: *mut c_void, slot: usize) -> usize { + if super::real::is_adopted(dev) { + super::real::orig_fn(dev, slot) + } else { + *(*(dev as *const *const usize)).add(slot) + } +} + +/// The pass's pipelines for `dev` are made, once a device, on a thread of their own: the three +/// programs go through DXC and the driver, which a title's thread that records a list must not +/// wait for (on a retail title's first bind of such a DSV that took the driver over 30 s on a +/// PC short of memory, and the title's own watchdog ended it: found by CharlyRien, +/// xcl-dev/xcl#3089). Called where an R24G8 buffer's depth twin is made, which a title does long +/// before it binds a DSV of the buffer. +fn start_pass_pipelines(dev: *mut c_void) { + let dev = dev as usize; + { + let mut asked = PASS_PIPELINES_ASKED.lock().unwrap(); + if asked.contains(&dev) { + return; + } + asked.push(dev); + } + let make = move || unsafe { + let t0 = std::time::Instant::now(); + let made = make_pass_pipelines(dev as *mut c_void); + match &made { + Ok(_) => crate::xlog_info!("D3D12.X: depth UAV twins: the pass that draws a twin into an R24G8 depth plane was made in {} ms", t0.elapsed().as_millis()), + Err(e) => crate::xlog_warn!("D3D12.X: depth UAV twins: the pass that draws a twin into an R24G8 depth plane cannot be made ({e}): those planes keep what they hold"), + } + PASS_PIPELINES.lock().unwrap().get_or_insert_with(HashMap::new).insert(dev, made.ok().map(Arc::new)); + }; + if std::thread::Builder::new().name("xcl-depth-pass".into()).spawn(make).is_err() { + // (no thread: asked for again at the next twin or bind) + PASS_PIPELINES_ASKED.lock().unwrap().retain(|&d| d != dev); + } +} + +/// `PassPipelines` of `dev` once `start_pass_pipelines` has made them (`Some(None)`: they could +/// not be made). None: not made yet. +fn pass_pipelines_if_made(dev: *mut c_void) -> Option>> { + PASS_PIPELINES.lock().unwrap().as_ref()?.get(&(dev as usize)).cloned() +} + +/// (tests) Whether the pass's pipelines of `dev` are made (or could not be). +#[cfg(test)] +pub(super) fn pass_made(dev: *mut c_void) -> bool { + pass_pipelines_if_made(dev).is_some() +} + +unsafe fn make_pass_pipelines(dev: *mut c_void) -> Result { + use crate::gpu::recomp::dxc::compile; + use windows_sys::core::GUID; + let vs = compile(PASS_VS, "main", "vs_6_0", &[])?; + let float = compile(PASS_PS_FLOAT, "main", "ps_6_0", &[])?; + let steps = compile(PASS_PS_STEPS, "main", "ps_6_0", &[])?; + // (the root signature is in the vertex shader's container) + type CreateRs = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const GUID, *mut *mut c_void) -> i32; + let create_rs: CreateRs = std::mem::transmute(dev_fn(dev, 16)); + let mut raw = std::ptr::null_mut(); + let hr = create_rs(dev, 0, vs.as_ptr() as *const c_void, vs.len(), &ID3D12RootSignature::IID as *const _ as *const GUID, &mut raw); + if hr < 0 || raw.is_null() { + return Err(format!("root signature: {hr:#x}")); + } + let rs = ID3D12RootSignature::from_raw(raw); + type CreatePso = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const GUID, *mut *mut c_void) -> i32; + let create_pso: CreatePso = std::mem::transmute(dev_fn(dev, 10)); + let pipeline = |ps: &[u8]| -> Result { + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const c_void, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const c_void, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 0, + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = false.into(); + // every texel's depth is written, whatever the plane holds; the stencil plane is left + pd.DepthStencilState.DepthEnable = true.into(); + pd.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pd.DepthStencilState.StencilEnable = false.into(); + let mut raw = std::ptr::null_mut(); + let hr = create_pso(dev, &pd, &ID3D12PipelineState::IID as *const _ as *const GUID, &mut raw); + std::mem::ManuallyDrop::drop(&mut pd.pRootSignature); + if hr < 0 || raw.is_null() { + return Err(format!("pipeline: {hr:#x}")); + } + Ok(ID3D12PipelineState::from_raw(raw)) + }; + Ok(PassPipelines { float: pipeline(&float)?, steps: pipeline(&steps)?, rs }) +} + +/// `PassViews` of the twin `twin` (`r16`: a 16-bit one) for the depth plane of `of`, a buffer of +/// `key`, on `dev`. +unsafe fn make_pass_views(dev: *mut c_void, of: usize, twin: &ID3D12Resource, key: &Key, r16: bool) -> Option { + use windows_sys::core::GUID; + type CreateHeap = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const GUID, *mut *mut c_void) -> i32; + let create_heap: CreateHeap = std::mem::transmute(dev_fn(dev, 14)); + let heap = |ty: D3D12_DESCRIPTOR_HEAP_TYPE, n: u32, flags: D3D12_DESCRIPTOR_HEAP_FLAGS| -> Option { + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: n, Flags: flags, NodeMask: 0 }; + let mut out = std::ptr::null_mut(); + let hr = create_heap(dev, &d, &ID3D12DescriptorHeap::IID as *const _ as *const GUID, &mut out); + (hr >= 0 && !out.is_null()).then(|| ID3D12DescriptorHeap::from_raw(out)) + }; + let (mips, array) = (key.mips.max(1) as u32, key.array.max(1) as u32); + let srv_heap = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + let dsv_heap = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2 * mips * array, D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?; + let increment: unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32 = std::mem::transmute(dev_fn(dev, 15)); + let dsv_inc = increment(dev, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: if r16 { DXGI_FORMAT_R16_UINT } else { DXGI_FORMAT_R32_FLOAT }, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: array, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + let create_srv: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize) = std::mem::transmute(dev_fn(dev, 18)); + create_srv(dev, twin.as_raw(), &srv, srv_heap.GetCPUDescriptorHandleForHeapStart().ptr); + let create_dsv: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize) = std::mem::transmute(dev_fn(dev, 21)); + let base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + for (k, flags) in [D3D12_DSV_FLAG_NONE, D3D12_DSV_FLAG_READ_ONLY_STENCIL].into_iter().enumerate() { + for m in 0..mips { + for a in 0..array { + let v = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Flags: flags, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_DSV { MipSlice: m, FirstArraySlice: a, ArraySize: 1 } }, + }; + create_dsv(dev, of as *mut c_void, &v, base + (k as u32 * mips * array + m * array + a) as usize * dsv_inc); + } + } + } + Some(PassViews { srv_heap, dsv_heap, dsv_inc }) +} + +/// The private data of an object of an R24G8 buffer under which it keeps its pass's view heap and +/// DSV heap (`retain_pass_views`). +pub(super) const PASS_HEAP_KEYS: [u128; 2] = [0x5d0c7e31_8a44_4b0e_9c55_2f6b1d7a9e01, 0x5d0c7e31_8a44_4b0e_9c55_2f6b1d7a9e02]; + +/// The heaps of `pass` are kept by `of`, the object whose plane its DSVs name, until the PC +/// destroys that object: a recorded list names their descriptors, and D3D12 lists hold no +/// reference to what they name. XCL puts off a title's last release of a resource until the +/// queues are past the work in flight (`late_release`), so the heaps live as long as a pass +/// recorded with them can run, also after the Cell has let the views go (another object of the +/// buffer bound, the object forgotten). Found, with this way of keeping them, by thehollowedone +/// (xcl-dev/xcl#3089). False: the object did not take them. +unsafe fn retain_pass_views(of: usize, pass: &PassViews) -> bool { + use windows_sys::core::GUID; + // (ID3D12Object::SetPrivateDataInterface of the PC's own, past the hook of a title's call) + let set: unsafe extern "system" fn(*mut c_void, *const GUID, *mut c_void) -> i32 = std::mem::transmute(dev_fn(of as *mut c_void, 5)); + let (srv, dsv) = (GUID::from_u128(PASS_HEAP_KEYS[0]), GUID::from_u128(PASS_HEAP_KEYS[1])); + set(of as *mut c_void, &srv, pass.srv_heap.as_raw()) >= 0 && set(of as *mut c_void, &dsv, pass.dsv_heap.as_raw()) >= 0 +} + +/// Before OMSetRenderTargets binds the DSV at `dsv` on `list` (`real::cl_om_set_render_targets`). +/// When the DSV names an R24G8 buffer whose depth plane has a twin, the twin is drawn into the +/// plane first, so the draws that follow test what the title's compute programs wrote through +/// the twin. Not when no dispatch was recorded since the last such pass of the buffer +/// (`bind::activity`): then nothing wrote the twin. The pass is recorded where the bind is, so +/// it runs after everything recorded before on this list and on the lists submitted before it. +/// +/// On a DIRECT list XCL keeps state for; the title's own state of the list (view heaps, +/// viewports, scissors, topology, vertex buffers, render targets, pipeline) is set again after +/// it (`list_x::depth_only_pass`). +pub(super) unsafe fn before_dsv_bind(list: *mut c_void, dsv: usize) { + if R24_TWINS.load(Ordering::Relaxed) == 0 { + return; + } + let Some(d) = DSVS.get(dsv) else { return }; + let Some(cell) = d.cell.upgrade() else { return }; + if cell.key.format != 44 || super::list_x::tracked_list_type(list) != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let Some(o) = OBJECTS.get(d.res) else { return }; + let key = cell.key; + let r16 = depth_twin_r16(key.format, cell.console_format); + let now = super::bind::activity().1; + let left = |why: &str| { + let n = PLANE_PASSES_LEFT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: depth UAV twins: the twin of depth buffer {:#x} is not drawn into its plane ({why}): {n} such binds so far", d.res); + } + }; + // (the depth plane's state, which the pass moves, and the stencil plane's, which it reads) + let state = [o.now[0].load(Ordering::Relaxed), o.now[1].load(Ordering::Relaxed)]; + if state[0] == STATE_UNKNOWN { + return left("the title moved a part of the depth plane to a state of its own"); + } + // (`_views`: this call's own reference to the heaps while it records with them) + let (twin, n, pl, srv_heap, table, dsv_base, dsv_inc, _views) = { + let mut inner = cell.inner.lock().unwrap(); + let Some(t) = inner.twins[0].as_ref() else { return }; + if inner.drawn_at == Some(now) { + PLANE_PASSES_SPARED.fetch_add(1, Ordering::Relaxed); + return; + } + let (twin, n, dev) = (t.res.clone(), t.n, t.dev as *mut c_void); + // (before `drawn_at` is set: a bind left out here leaves the next one to draw) + let pl = match pass_pipelines_if_made(dev) { + Some(Some(pl)) => pl, + Some(None) => { + drop(inner); + return left("the pass could not be made"); + } + None => { + drop(inner); + start_pass_pipelines(dev); + return left("its pipelines are still being made"); + } + }; + if !inner.passes.contains_key(&d.res) { + let Some(pass) = make_pass_views(dev, d.res, &twin, &key, r16) else { + drop(inner); + return left("its views could not be made"); + }; + if !retain_pass_views(d.res, &pass) { + drop(inner); + return left("its views could not be kept by the buffer"); + } + inner.passes.insert(d.res, pass); + } + let p = inner.passes[&d.res].clone(); + let views = (p.srv_heap.as_raw() as usize, p.srv_heap.GetGPUDescriptorHandleForHeapStart().ptr, p.dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr, p.dsv_inc); + inner.drawn_at = Some(now); + (twin, n, pl, views.0, views.1, views.2, views.3, p) + }; + let (mips, array) = (key.mips.max(1) as u32, key.array.max(1) as u32); + let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + let (shader, depth_write) = (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32, D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32); + let twin_raw = twin.as_raw() as usize; + // the twin rests in UNORDERED_ACCESS; the stencil plane's subresources follow the depth plane's + let mut before = vec![tr(twin_raw, all, UNORDERED_ACCESS, shader)]; + let mut after = vec![tr(twin_raw, all, shader, UNORDERED_ACCESS)]; + // The pass writes the depth plane: in DEPTH_WRITE for it. The stencil plane it neither + // writes nor moves: where the title has that plane in DEPTH_READ (it binds the buffer to + // test it) the pass's DSV is the one with the stencil plane read only. + let stencil_read_only = state[1] != STATE_UNKNOWN && state[1] != depth_write && state[1] & D3D12_RESOURCE_STATE_DEPTH_READ.0 as u32 != 0; + let first_dsv = if stencil_read_only { mips * array } else { 0 }; + if state[0] != depth_write { + for sub in 0..mips * array { + before.push(tr(d.res, sub, state[0], depth_write)); + after.push(tr(d.res, sub, depth_write, state[0])); + } + } + let draws: Vec<(usize, u32, u32, [u32; 2])> = (0..mips) + .flat_map(|m| (0..array).map(move |a| (m, a))) + .map(|(m, a)| (dsv_base + (first_dsv + m * array + a) as usize * dsv_inc, (key.width >> m).max(1), (key.height >> m).max(1), [a, m])) + .collect(); + super::list_x::barrier_words(list, &before); + super::list_x::depth_only_pass(list, srv_heap, pl.rs.as_raw() as usize, if r16 { pl.steps.as_raw() } else { pl.float.as_raw() } as usize, table, &draws); + super::list_x::barrier_words(list, &after); + let c = PLANE_PASSES.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth UAV twin #{n}: drawn into the depth plane of {:#x} before a DSV of it is bound (the title has its planes in states {:#x} and {:#x}; {c} such passes so far, {} binds needed none)", + d.res, + state[0], + state[1], + PLANE_PASSES_SPARED.load(Ordering::Relaxed) + ); + } +} + +/// (tests) Passes that drew a twin into an R24G8 depth plane, binds that needed none, binds left +/// without one. +#[cfg(test)] +pub(super) fn plane_passes() -> (u64, u64, u64) { + (PLANE_PASSES.load(Ordering::Relaxed), PLANE_PASSES_SPARED.load(Ordering::Relaxed), PLANE_PASSES_LEFT.load(Ordering::Relaxed)) +} + /// A UAV of a depth buffer stays a null view (`Resolve::Null`). pub(super) fn null_view(why: &'static str) { #[cfg(test)] @@ -722,8 +1164,18 @@ pub(super) fn clear_target(res: usize, named: Option) -> Clear { return Clear::AsIs; } let Some(o) = OBJECTS.get(res) else { return Clear::AsIs }; - let twins = o.cell.inner.lock().unwrap().twins.each_ref().map(|t| t.as_ref().map(|t| t.res.as_raw() as usize)); + let mut inner = o.cell.inner.lock().unwrap(); + let twins = inner.twins.each_ref().map(|t| t.as_ref().map(|t| t.res.as_raw() as usize)); let c = clear_choice(twins, named); + // (a clear of an R24G8 buffer's depth twin writes it as a dispatch does, and + // `bind::activity` does not count it: the next bind of a DSV of the buffer draws the twin + // into the plane again. Found by thehollowedone, xcl-dev/xcl#3089) + if let Clear::Twin(t) = &c { + if o.cell.key.format == 44 && twins[0] == Some(*t) { + inner.drawn_at = None; + } + } + drop(inner); match c { Clear::Twin(_) => UAV_CLEARS.fetch_add(1, Ordering::Relaxed), Clear::NotDone => CLEARS_NOT_DONE.fetch_add(1, Ordering::Relaxed), @@ -1265,11 +1717,24 @@ mod tests { #[test] fn a_depth_view_is_a_view_of_a_twin_of_the_planes_size() { + // (the PC format, the console's, the plane) assert_eq!( - [twin_format(39, 0), twin_format(19, 0), twin_format(53, 0), twin_format(44, 1), twin_format(19, 1)], - [DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_TYPELESS], - "D32, D32S8, D16 depth; stencil" + [twin_format(39, 40, 0), twin_format(19, 20, 0), twin_format(53, 55, 0), twin_format(44, 45, 0), twin_format(44, 118, 0), twin_format(44, 45, 1), twin_format(19, 20, 1)], + [ + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R8_TYPELESS, + DXGI_FORMAT_R8_TYPELESS + ], + "D32, D32S8, D16, D24S8, the console's D16S8 depth; stencil" ); + // 16 bits: a D16, and the console's D16S8 family, which the PC has as R24G8 + for (format, console, r16) in [(53, 55, true), (44, 118, true), (44, 119, true), (44, 120, true), (44, 45, false), (44, 46, false), (39, 40, false), (19, 20, false)] { + assert_eq!(depth_twin_r16(format, console), r16, "PC format {format}, console format {console}"); + } // an R32 twin: the depth as a float unless the title asked for another R32 class for (asked, got) in [ (DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_FLOAT), @@ -1301,9 +1766,54 @@ mod tests { assert_eq!(twin_view(None, 1).Format, DXGI_FORMAT_R8_UINT); } + /// The states a title's transitions leave the depth plane and the stencil plane of a buffer + /// in whose twin is not copied at transitions: a transition of the whole buffer sets both, one + /// of a whole plane that plane's, the first half of a split one neither, and one of a part of + /// a plane makes that plane's unknown. + #[test] + fn the_states_of_an_r24g8_buffers_planes_follow_the_titles_transitions() { + let (one, two) = (0x7B50_0000_1000usize, 0x7B50_0000_2000usize); + assert!(register(one, &desc(3, 64, 64, 118, 1, 6), None, 0x10)); + // (two levels) + let mut levels = desc(3, 64, 64, 45, 1, 6); + levels[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(two, &levels, None, 0x10)); + let tr = |res: usize, flags: u32, sub: u32, before: u32, after: u32| [0, flags, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + // [the depth plane's, the stencil plane's] + let now = |res: usize| OBJECTS.get(res).unwrap().now.each_ref().map(|p| p.load(Ordering::Relaxed)); + assert_eq!((now(one), now(two)), ([0x10; 2], [0x10; 2]), "the state they were made in"); + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + // (through the walk of a title's barriers: the barriers go on as they came) + let walk = |b: [u32; 8]| { + let mut v = vec![b]; + let plan = plan_with(&mut v, true, &mut Vec::new(), &mut |_, _| None); + assert!(plan.to_plane.is_empty() && plan.to_twin.is_empty()); + assert_eq!(v, [b], "an R24G8 buffer's transition goes to the PC as it came"); + }; + walk(tr(one, 0, all, 0x10, 0x20)); + assert_eq!(now(one), [0x20, 0x20], "the whole buffer"); + walk(tr(one, 0, 0, 0x20, 0xA0)); + assert_eq!(now(one), [0xA0, 0x20], "its one depth subresource"); + walk(tr(one, 0, 1, 0x20, 0x10)); + assert_eq!(now(one), [0xA0, 0x10], "its one stencil subresource"); + walk(tr(one, BEGIN_ONLY, all, 0xA0, 0x10)); + assert_eq!(now(one), [0xA0, 0x10], "the first half of a split transition"); + walk(tr(one, END_ONLY, all, 0xA0, 0x10)); + assert_eq!(now(one), [0x10, 0x10], "its end"); + // two levels: a transition of one of the depth plane's, then of one of the stencil plane's + walk(tr(two, 0, 1, 0x10, 0x20)); + assert_eq!(now(two), [STATE_UNKNOWN, 0x10], "a part of the depth plane"); + walk(tr(two, 0, 3, 0x10, 0x20)); + assert_eq!(now(two), [STATE_UNKNOWN, STATE_UNKNOWN], "a part of the stencil plane"); + walk(tr(two, 0, all, 0x10, 0x20)); + assert_eq!(now(two), [0x20, 0x20], "the whole buffer again: known"); + forget(one); + forget(two); + } + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). #[test] - fn a_depth_uav_of_a_d32_or_d16_buffer_asks_for_a_twin_and_a_d24s8_one_stays_null() { + fn a_depth_uav_of_a_kept_buffer_asks_for_a_twin() { let rd = |format| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, @@ -1316,12 +1826,13 @@ mod tests { ..Default::default() }; let base = 0x7B30_0000_1000usize; - // console D32, D16, D32S8, D24S8; the PC formats of the buffers; the views of their depth + // console D32, D16, D32S8, D24S8, D16S8; the PC formats of the buffers; the views of their depth for (k, (console, pc, view, on)) in [ (40u32, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, "the twin could not be made"), (55, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), (20, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, "the twin could not be made"), - (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "its depth plane has no twin yet"), + (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "the twin could not be made"), + (118, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), ] .into_iter() .enumerate() @@ -1368,7 +1879,7 @@ mod tests { { let o = OBJECTS.get(buffer).unwrap(); TWINS.fetch_add(1, Ordering::Relaxed); - o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0, through: None }); + o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0, dev: 0, r24: false, through: None }); } let t = fake as usize; let before = clears(); @@ -1399,7 +1910,7 @@ mod tests { fn plant_depth_twin(res: usize, t: &ID3D12Resource) { let o = OBJECTS.get(res).unwrap(); TWINS.fetch_add(1, Ordering::Relaxed); - o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0, through: None }); + o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0, dev: 0, r24: false, through: None }); } fn tr(res: usize, sub: u32, before: u32, after: u32) -> [u32; 8] { @@ -1531,7 +2042,7 @@ mod tests { { let o = OBJECTS.get(res).unwrap(); TWINS.fetch_add(1, Ordering::Relaxed); - o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: t.clone(), n: 0, through: Some(through) }); + o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: t.clone(), n: 0, dev: 0, r24: false, through: Some(through) }); } let tw = t.as_raw() as usize; // made since the way in: not copied back diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 638b133d13..b1952849a9 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -40,7 +40,12 @@ const PC_RESET: usize = 10; const PC_COPY_BUFFER_REGION: usize = 15; const PC_COPY_TEXTURE_REGION: usize = 16; const PC_COPY_RESOURCE: usize = 17; +const PC_DRAW_INSTANCED: usize = 12; const PC_SET_PIPELINE_STATE: usize = 25; +const PC_SET_DESCRIPTOR_HEAPS: usize = 28; +const PC_SET_GRAPHICS_ROOT_SIGNATURE: usize = 30; +const PC_SET_GRAPHICS_ROOT_DESCRIPTOR_TABLE: usize = 32; +const PC_SET_GRAPHICS_ROOT_32BIT_CONSTANTS: usize = 36; const PC_RESOURCE_BARRIER: usize = 26; const PC_IA_SET_INDEX_BUFFER: usize = 43; const PC_BEGIN_QUERY: usize = 52; @@ -93,6 +98,59 @@ fn once(counter: &AtomicU64, n: u64) -> bool { counter.fetch_add(1, Ordering::Relaxed) < n } +/// A pass of XCL's own on a title's DIRECT list that only writes depth (`depth_uav::before_dsv_bind`): +/// for each of `draws` (a DSV, the size of its level, two root constants) one triangle over the +/// whole target with the pipeline `pso` under the root signature `rs`, its texture at `table` in +/// the view heap `heap`. Past the hooks of a title's calls: nothing of it is kept as the +/// title's, and what the title had set is set again (`restore_after_own_pass`). +pub(super) unsafe fn depth_only_pass(list: *mut c_void, heap: usize, rs: usize, pso: usize, table: u64, draws: &[(usize, u32, u32, [u32; 2])]) { + pc::(list, PC_SET_DESCRIPTOR_HEAPS)(list, 1, &heap); + pc::(list, PC_SET_GRAPHICS_ROOT_SIGNATURE)(list, rs); + pc::(list, PC_SET_PIPELINE_STATE)(list, pso); + pc::(list, PC_IA_SET_PRIMITIVE_TOPOLOGY)(list, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + pc::(list, PC_SET_GRAPHICS_ROOT_DESCRIPTOR_TABLE)(list, 1, table); + for &(dsv, w, h, constants) in draws { + let viewport = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + let scissor = windows::Win32::Foundation::RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }; + pc::(list, PC_RS_SET_VIEWPORTS)(list, 1, &viewport); + pc::(list, PC_RS_SET_SCISSOR_RECTS)(list, 1, &scissor); + pc::(list, PC_OM_SET_RENDER_TARGETS)(list, 0, std::ptr::null(), 0, &dsv); + pc::(list, PC_SET_GRAPHICS_ROOT_32BIT_CONSTANTS)(list, 0, 2, constants.as_ptr() as *const c_void, 0); + pc::(list, PC_DRAW_INSTANCED)(list, 3, 1, 0, 0); + } + restore_after_own_pass(list); +} + +/// After a graphics pass of XCL's own on `list` that set a view heap, a root signature, a +/// pipeline, a topology, viewports, scissors and targets of its own: what the title had set is +/// set again (`restore_bindings`), the title's pipeline is bound again, and the next translated +/// draw or dispatch sets XCL's view heap (`bind::heaps_changed`). Root signatures and root +/// arguments need nothing: every translated draw and dispatch binds its own (`bind::rebind`), +/// and a draw with a PC pipeline the title's (`bind::bind_title_root_signature`). +unsafe fn restore_after_own_pass(list: *mut c_void) { + let key = list as usize; + let (bindings, pso, ty) = { + let g = LISTS.lock().unwrap(); + match g.as_ref().and_then(|m| m.get(&key)) { + Some(s) => (s.bindings.clone(), s.bound_pso, s.list_type.unwrap_or(D3D12_COMMAND_LIST_TYPE_DIRECT)), + None => return, + } + }; + restore_bindings(list, &bindings, ty); + super::bind::heaps_changed(list); + if pso != 0 { + pc::(list, PC_SET_PIPELINE_STATE)(list, super::pso_async::resolve_for_bind(pso)); + } +} + +/// Barriers of XCL's own on the PC list, as PC words (type, flags, resource, subresource, state +/// before, state after). +pub(super) unsafe fn barrier_words(list: *mut c_void, b: &[[u32; 8]]) { + if !b.is_empty() { + pc::(list, PC_RESOURCE_BARRIER)(list, b.len() as u32, b.as_ptr()); + } +} + /// a PC method of the list (its runtime's own) unsafe fn pc(list: *mut c_void, slot: usize) -> F { transmute_copy(&real::orig_fn(list, slot)) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..b9b1896c09 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11398,6 +11398,10 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt ); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "OMSetRenderTargets"))); + // (a depth buffer whose plane shaders write through a twin: the twin into the plane first) + if !dsv.is_null() { + super::depth_uav::before_dsv_bind(this, *dsv); + } f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); let _ = super::capture::op(this, || Some(super::capture::targets_op(this))); @@ -14934,8 +14938,8 @@ mod depth_uav_twin_tests { /// A stencil UAV of a console depth buffer with unordered access, made through the device /// calls (`XCL_DEPTH_UAV_TWIN=1`, the shared view heap): the slot's UAV and its companion SRV - /// name the buffer's R8 twin and the T# reads as 8-bit uint; a depth UAV stays a null view - /// with its reason; the DSV is known; the twin goes with the buffer. On WARP, in a child + /// name the buffer's R8 twin and the T# reads as 8-bit uint; a depth UAV is a view of the + /// depth plane's R32 twin; the DSV is known; the twins go with the buffer. On WARP, in a child /// process. #[test] fn gpu_a_stencil_uav_of_a_console_depth_buffer_is_a_view_of_its_twin() { @@ -14957,8 +14961,8 @@ mod depth_uav_twin_tests { // a second stencil UAV takes the same twin dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R8_UINT, 0), slot_cpu(2)); let (made2, alive2, redirected2, nulls) = depth_uav::counts(); - assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (1, 1, 2), "one twin, two views of it"); - assert_eq!(nulls, ["its depth plane has no twin yet"], "the depth view is a null view, with its reason"); + assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (2, 2, 3), "a stencil twin with two views of it, a depth twin with one"); + assert!(nulls.is_empty(), "no null view: {nulls:?}"); let twin = depth_uav::twin_of(raw as usize).expect("a stencil twin"); let t = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().GetDesc(); @@ -14973,8 +14977,12 @@ mod depth_uav_twin_tests { std::ptr::copy_nonoverlapping(slot_cpu(k) as *const u32, w.as_mut_ptr(), 8); assert_eq!((w[0], (w[1] >> 20) & 0x1FF), (s.index, 5), "slot {k}: the T# of an R8_UINT image"); } + // the depth plane's UAV: a view of an R32 twin of the plane's size (a console D24S8) + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); + let t = ID3D12Resource::from_raw_borrowed(&(depth_twin as *mut c_void)).unwrap().GetDesc(); + assert_eq!((t.Format, t.Width, t.Height, t.DepthOrArraySize, t.MipLevels), (DXGI_FORMAT_R32_TYPELESS, 16, 16, 1, 1)); let s = console_heap::slot(slot_cpu(1)).unwrap(); - assert_eq!(console_heap::names_of(&s).1, 0, "the depth plane's UAV is a null view"); + assert_eq!(console_heap::names_of(&s), (depth_twin, depth_twin), "the depth plane's UAV and its companion SRV name the depth twin"); drop(heap); drop(depth); @@ -15042,6 +15050,379 @@ mod depth_uav_twin_tests { } } + /// The depth twin of a console D24S8 buffer (R24G8 on the PC) is drawn into the depth plane + /// before a DSV of the buffer is bound: each texel of the plane then holds the twin's value + /// in 24 bits; a second bind with nothing dispatched in between draws nothing. The list is + /// the title's (adopted, kept), and the pass is recorded past its hooks. On WARP, in a child + /// process. + #[test] + fn gpu_a_depth_twin_is_drawn_into_the_r24g8_plane_before_its_dsv_is_bound() { + if !in_child("gpu_a_depth_twin_is_drawn_into_the_r24g8_plane_before_its_dsv_is_bound") { + return; + } + use super::super::{depth_uav, list_x}; + unsafe { + let Some(f) = Fixture::new() else { return }; + let (d, raw) = (f.dev.as_raw(), f.depth.as_raw()); + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), f.base); + let twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); + let twin = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().clone(); + + // the twin's texels: (x + 16 y) / 300, uploaded on the PC list + let value = |x: usize, y: usize| (x + 16 * y) as f32 / 300.0; + let buffer = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, bytes: u64| -> ID3D12Resource { + let mut b: Option = None; + f.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + state, + None, + &mut b, + ) + .expect("a buffer"); + b.unwrap() + }; + // (16 rows of 256 bytes: the row pitch D3D12 asks for) + let fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R32_TYPELESS, Width: 16, Height: 16, Depth: 1, RowPitch: 256 } }; + let up = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, 16 * 256); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("map upload"); + for y in 0..16 { + for x in 0..16 { + ((p as *mut u8).add(y * 256 + x * 4) as *mut f32).write_unaligned(value(x, y)); + } + } + up.Unmap(0, None); + let l = &f.list; + let lraw = l.as_raw(); + // (PC calls of the list by slot: after the list is adopted its own table is XCL's) + let pc_vt = *(lraw as *const *const usize); + let barrier = |res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| { + let r = res.as_raw() as usize; + let b = [0u32, 0, r as u32, (r as u64 >> 32) as u32, sub, before.0 as u32, after.0 as u32, 0]; + let call: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(*pc_vt.add(26)); + call(lraw, 1, &b); + }; + let copy = |dst: &D3D12_TEXTURE_COPY_LOCATION, src: &D3D12_TEXTURE_COPY_LOCATION| { + let call: unsafe extern "system" fn(*mut c_void, *const D3D12_TEXTURE_COPY_LOCATION, u32, u32, u32, *const D3D12_TEXTURE_COPY_LOCATION, *const c_void) = std::mem::transmute(*pc_vt.add(16)); + call(lraw, dst, 0, 0, 0, src, std::ptr::null()); + }; + let placed = |b: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(b), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let sub0 = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier(&twin, all, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + copy(&sub0(&twin), &placed(&up)); + barrier(&twin, all, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + // the list as a title's, and the bind of the buffer's DSV + adopt(lraw, Kind::CommandList); + list_x::on_create(lraw, f._alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + // (the pass's pipelines are made on a thread of their own, from the twin's making on) + let asked = std::time::Instant::now(); + while !depth_uav::pass_made(f.dev.as_raw()) { + assert!(asked.elapsed() < std::time::Duration::from_secs(120), "the pass's pipelines are made"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let (passes, spared, left) = depth_uav::plane_passes(); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + assert_eq!(depth_uav::plane_passes(), (passes + 1, spared, left), "the twin is drawn into the plane"); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + assert_eq!(depth_uav::plane_passes(), (passes + 1, spared + 1, left), "nothing was dispatched since: no second pass"); + // a clear of the twin writes it with no dispatch: the next bind draws it again + let (d, t) = (f.depth.as_raw() as usize, twin.as_raw() as usize); + assert_eq!(depth_uav::clear_target(d, Some(t)), depth_uav::Clear::Twin(t)); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + assert_eq!(depth_uav::plane_passes(), (passes + 2, spared + 1, left), "after a clear of the twin it is drawn into the plane again"); + // the buffer keeps the pass's two heaps itself (a recorded list names their descriptors) + let kept = |key: u128| { + let (mut size, mut heap) = (8u32, std::ptr::null_mut::()); + let got = f.depth.GetPrivateData(&windows::core::GUID::from_u128(key), &mut size, Some(&mut heap as *mut *mut c_void as *mut c_void)).is_ok() && !heap.is_null(); + if got { + // (the reference GetPrivateData gave) + drop(ID3D12DescriptorHeap::from_raw(heap)); + } + got + }; + assert!(depth_uav::PASS_HEAP_KEYS.iter().all(|&k| kept(k)), "the buffer holds the pass's view heap and DSV heap"); + + // the depth plane (the buffer was made in DEPTH_WRITE and is there again) to a + // readback buffer + let rb = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, 16 * 256); + barrier(&f.depth, 0, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy(&placed(&rb), &sub0(&f.depth)); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*pc_vt.add(9)); + assert!(close(lraw) >= 0, "close list"); + // (the PC queue's own call with the list as it is: no reference of the list changes hands) + let q = f.queue.as_raw(); + let execute: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(*(*(q as *const *const usize)).add(10)); + execute(q, 1, &lraw); + let fence: ID3D12Fence = f.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + f.queue.Signal(&fence, 1).expect("signal"); + crate::gpu::fence::wait(&fence, 1, &f.dev, None, 5000).expect("the pass and the copies complete"); + assert!(f.dev.GetDeviceRemovedReason().is_ok(), "the device is there"); + + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).expect("map readback"); + let mut distinct = std::collections::BTreeSet::new(); + for y in 0..16 { + for x in 0..16 { + // (24 bits of depth in the low bytes of each 32-bit texel) + let got = ((p as *const u8).add(y * 256 + x * 4) as *const u32).read_unaligned() & 0xFF_FFFF; + let want = (value(x, y) as f64 * 16_777_215.0).round() as i64; + assert!((got as i64 - want).abs() <= 1, "texel {x},{y}: {got:#x}, the twin's value is {want:#x}"); + distinct.insert(got); + } + } + rb.Unmap(0, None); + assert_eq!(distinct.len(), 256, "every texel its own value"); + // and still when XCL has forgotten the buffer: until the PC destroys it + depth_uav::forget(d); + assert!(depth_uav::PASS_HEAP_KEYS.iter().all(|&k| kept(k)), "the heaps live as long as the buffer"); + } + } + + /// The case of a retail title's lighting: a console D16_UNORM_S8_UINT buffer (R24G8 on the + /// PC) whose depth plane a compute program writes through its UAV, one count of 1/65535 steps + /// a texel, and draws that test the plane with EQUAL at the depth `count * (1.0 / 65535.0)`. + /// The R16 twin holds a count for each texel; after the pass that draws it into the plane, + /// a draw at a count's depth passes on exactly the texels that hold that count (seen in the + /// stencil plane, which each passing draw counts up). On WARP, in a child process. + #[test] + fn gpu_an_equal_test_at_a_counts_depth_passes_where_the_16_bit_twin_holds_the_count() { + if !in_child("gpu_an_equal_test_at_a_counts_depth_passes_where_the_16_bit_twin_holds_the_count") { + return; + } + use super::super::{depth_uav, list_x}; + unsafe { + let Some(f) = Fixture::new() else { return }; + let d = f.dev.as_raw(); + // a console D16S8 with unordered access, and the fixture's DSV handle for it + let console = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(118), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let hr = dev_create_committed_resource_x( + d, + &props as *const _ as usize, + 0, + &console as *const _ as usize, + D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as usize, + 0, + &ID3D12Resource::IID as *const _ as *const GUID, + &mut raw, + ); + assert!(hr >= 0 && !raw.is_null(), "the D16S8 buffer: {hr:#x}"); + let depth = ID3D12Resource::from_raw(raw); + assert_eq!(depth.GetDesc().Format, DXGI_FORMAT_R24G8_TYPELESS, "R24G8 on the PC"); + dev_create_dsv_x(d, raw, &D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT_D24_UNORM_S8_UINT, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }, f.dsv); + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R16_UNORM, 0), f.base); + let twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); + let twin = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().clone(); + assert_eq!(twin.GetDesc().Format, DXGI_FORMAT_R16_TYPELESS, "16 bits a texel"); + + // each row holds the 16 counts around one of these (the count itself at x = 8). At + // the first twelve the product and the correctly rounded count / 65535 are floats + // one unit in the last place apart, and 24-bit values one apart: the first eight + // when the float is rounded to 24 bits, the next four when it is cut off + const ROWS: [u32; 16] = [385, 642, 898, 1156, 1412, 1668, 1924, 2184, 257, 514, 770, 1028, 8, 128, 32768, 65528]; + let count = |x: usize, y: usize| (ROWS[y] + x as u32 - 8) as u16; + let buffer = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, bytes: u64| -> ID3D12Resource { + let mut b: Option = None; + f.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + state, + None, + &mut b, + ) + .expect("a buffer"); + b.unwrap() + }; + let footprint = |format: DXGI_FORMAT| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: 16, Height: 16, Depth: 1, RowPitch: 256 } }; + let up = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, 16 * 256); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("map upload"); + for y in 0..16 { + for x in 0..16 { + ((p as *mut u8).add(y * 256 + x * 2) as *mut u16).write_unaligned(count(x, y)); + } + } + up.Unmap(0, None); + + // the draws' pipeline: one triangle over the target at the depth of the count in b0, + // depth test EQUAL without a write, the stencil counted up where it passes + let vs = crate::gpu::recomp::dxc::compile( + r#" +#define RS "RootConstants(num32BitConstants=1, b0)" +cbuffer C : register(b0) { uint count; }; +[RootSignature(RS)] +float4 main(uint id : SV_VertexID) : SV_Position { + return float4(id == 2u ? 3.0 : -1.0, id == 1u ? 3.0 : -1.0, float(count) * (1.0 / 65535.0), 1.0); +} +"#, + "main", + "vs_6_0", + &[], + ) + .expect("the vertex shader"); + type CreateRs = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const GUID, *mut *mut c_void) -> i32; + let create_rs: CreateRs = std::mem::transmute(orig_fn(d, 16)); + let mut rs_raw = std::ptr::null_mut(); + assert!(create_rs(d, 0, vs.as_ptr() as *const c_void, vs.len(), &ID3D12RootSignature::IID as *const _ as *const GUID, &mut rs_raw) >= 0, "root signature"); + let rs = ID3D12RootSignature::from_raw(rs_raw); + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const c_void, BytecodeLength: vs.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 0, + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = false.into(); + pd.DepthStencilState.DepthEnable = true.into(); + pd.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; + pd.DepthStencilState.StencilEnable = true.into(); + pd.DepthStencilState.StencilReadMask = 0xFF; + pd.DepthStencilState.StencilWriteMask = 0xFF; + let face = D3D12_DEPTH_STENCILOP_DESC { StencilFailOp: D3D12_STENCIL_OP_KEEP, StencilDepthFailOp: D3D12_STENCIL_OP_KEEP, StencilPassOp: D3D12_STENCIL_OP_INCR_SAT, StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS }; + (pd.DepthStencilState.FrontFace, pd.DepthStencilState.BackFace) = (face, face); + type CreatePso = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const GUID, *mut *mut c_void) -> i32; + let create_pso: CreatePso = std::mem::transmute(orig_fn(d, 10)); + let mut pso_raw = std::ptr::null_mut(); + let hr = create_pso(d, &pd, &ID3D12PipelineState::IID as *const _ as *const GUID, &mut pso_raw); + std::mem::ManuallyDrop::drop(&mut pd.pRootSignature); + assert!(hr >= 0 && !pso_raw.is_null(), "the draws' pipeline: {hr:#x}"); + let pso = ID3D12PipelineState::from_raw(pso_raw); + + let l = &f.list; + let lraw = l.as_raw(); + // (PC calls of the list by slot: after the list is adopted its own table is XCL's) + let pc_vt = *(lraw as *const *const usize); + let barrier = |res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| { + let r = res.as_raw() as usize; + let b = [0u32, 0, r as u32, (r as u64 >> 32) as u32, sub, before.0 as u32, after.0 as u32, 0]; + let call: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(*pc_vt.add(26)); + call(lraw, 1, &b); + }; + let copy = |dst: &D3D12_TEXTURE_COPY_LOCATION, src: &D3D12_TEXTURE_COPY_LOCATION| { + let call: unsafe extern "system" fn(*mut c_void, *const D3D12_TEXTURE_COPY_LOCATION, u32, u32, u32, *const D3D12_TEXTURE_COPY_LOCATION, *const c_void) = std::mem::transmute(*pc_vt.add(16)); + call(lraw, dst, 0, 0, 0, src, std::ptr::null()); + }; + let placed = |b: &ID3D12Resource, format: DXGI_FORMAT| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(b), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(format) } }; + let sub = |t: &ID3D12Resource, k: u32| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier(&twin, all, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + copy(&sub(&twin, 0), &placed(&up, DXGI_FORMAT_R16_TYPELESS)); + barrier(&twin, all, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + // the list as a title's; the twin into the plane as the DSV is bound + adopt(lraw, Kind::CommandList); + list_x::on_create(lraw, f._alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + // (the pass's pipelines are made on a thread of their own, from the twin's making on) + let asked = std::time::Instant::now(); + while !depth_uav::pass_made(f.dev.as_raw()) { + assert!(asked.elapsed() < std::time::Duration::from_secs(120), "the pass's pipelines are made"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let (passes, _, left) = depth_uav::plane_passes(); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + let (passes2, _, left2) = depth_uav::plane_passes(); + assert_eq!((passes2 - passes, left2 - left), (1, 0), "the twin is drawn into the plane"); + + // the stencil plane to 0, then a draw for each row's count, for 0 and for 65535 + let drawn: Vec = ROWS.iter().copied().chain([0, 65535]).collect(); + let dsv = f.dsv as usize; + let clear: unsafe extern "system" fn(*mut c_void, usize, u32, f32, u8, u32, *const c_void) = std::mem::transmute(*pc_vt.add(47)); + clear(lraw, dsv, D3D12_CLEAR_FLAG_STENCIL.0 as u32, 0.0, 0, 0, std::ptr::null()); + let set_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(*pc_vt.add(30)); + set_rs(lraw, rs.as_raw()); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(*pc_vt.add(25)); + set_pso(lraw, pso.as_raw()); + let topology: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(*pc_vt.add(20)); + topology(lraw, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + let viewport = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: 16.0, Height: 16.0, MinDepth: 0.0, MaxDepth: 1.0 }; + let set_viewports: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(*pc_vt.add(21)); + set_viewports(lraw, 1, &viewport); + let scissor = windows::Win32::Foundation::RECT { left: 0, top: 0, right: 16, bottom: 16 }; + let set_scissors: unsafe extern "system" fn(*mut c_void, u32, *const windows::Win32::Foundation::RECT) = std::mem::transmute(*pc_vt.add(22)); + set_scissors(lraw, 1, &scissor); + let targets: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(*pc_vt.add(46)); + targets(lraw, 0, std::ptr::null(), 0, &dsv); + let constants: unsafe extern "system" fn(*mut c_void, u32, u32, *const c_void, u32) = std::mem::transmute(*pc_vt.add(36)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(*pc_vt.add(12)); + for k in &drawn { + constants(lraw, 0, 1, k as *const u32 as *const c_void, 0); + draw(lraw, 3, 1, 0, 0); + } + + // the stencil plane (subresource 1) to a readback buffer + let rb = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, 16 * 256); + barrier(&depth, 1, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy(&placed(&rb, DXGI_FORMAT_R8_TYPELESS), &sub(&depth, 1)); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*pc_vt.add(9)); + assert!(close(lraw) >= 0, "close list"); + // (the PC queue's own call with the list as it is: no reference of the list changes hands) + let q = f.queue.as_raw(); + let execute: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(*(*(q as *const *const usize)).add(10)); + execute(q, 1, &lraw); + let fence: ID3D12Fence = f.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + f.queue.Signal(&fence, 1).expect("signal"); + crate::gpu::fence::wait(&fence, 1, &f.dev, None, 5000).expect("the pass, the draws and the copy complete"); + assert!(f.dev.GetDeviceRemovedReason().is_ok(), "the device is there"); + + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).expect("map readback"); + let mut wrong = Vec::new(); + for y in 0..16 { + for x in 0..16 { + let got = *(p as *const u8).add(y * 256 + x); + let want = drawn.contains(&(count(x, y) as u32)) as u8; + if got != want { + wrong.push((count(x, y), got)); + } + } + } + rb.Unmap(0, None); + assert!(wrong.is_empty(), "(count, draws that passed there) where it is not 1 for a drawn count and 0 for any other: {wrong:?}"); + } + } + /// ClearUnorderedAccessViewUint of console code with the console handles of a stencil UAV /// and the depth buffer as its resource: the PC clear goes to the twin the slot's view names, /// and the twin reads back the value. On WARP, in a child process. @@ -15086,13 +15467,14 @@ mod depth_uav_twin_tests { let (done2, not_done2) = depth_uav::clears(); assert_eq!((done2 - done, not_done2 - not_done), (1, 0), "the clear went to the twin"); assert_eq!(GOT.load(Ordering::Relaxed), twin.as_raw() as usize, "the PC clear gets the twin as its resource, not the depth buffer"); - // a depth-plane UAV of the buffer is a null view: its clear is not done, nothing reaches the PC + // a depth-plane UAV of the buffer is a view of the depth twin: its clear goes there let depth_slot = slot + console_heap::SLOT as u64; dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), depth_slot); + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); GOT.store(0, Ordering::Relaxed); list_x::clear_uav_uint_x(stand_in.as_ptr() as *mut c_void, depth_slot, depth_slot, raw as usize, [0x11u32; 4].as_ptr(), 0, std::ptr::null()); let (done3, not_done3) = depth_uav::clears(); - assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (0, 1, 0), "a clear through the null view is not done"); + assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (1, 0, depth_twin), "a clear through the depth view goes to the depth twin"); // the twin to a readback buffer let td = twin.GetDesc(); From e228ed5da75ca7ef661149cee358985a5b263cc6 Mon Sep 17 00:00:00 2001 From: imnicho Date: Tue, 1 Dec 2026 08:39:34 +0100 Subject: [PATCH 2/3] D3D12.X: an R24G8 twin's pass is spared only within the recording that drew it After the review of 8de5808d8 (thehollowedone): the note that a buffer's twin was drawn into its plane was the buffer's, set while recording. A recording that was reset and never submitted then spared the next recording its pass, and a pass for one object of a buffer spared another object's. The proof is now the list's live recording's and the object's (list_x::plane_drawn): which object's plane was drawn, at which count of dispatches and of clears of the twin. A Reset and a KickoffX clear it, as they clear depth_in_step. The WARP test resets its list and binds again: the new recording draws. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 63 ++++++++++++++------------ crates/xcl/src/hle/d3d12x/list_x.rs | 22 +++++++++ crates/xcl/src/hle/d3d12x/real.rs | 10 ++++ 3 files changed, 65 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index c9d18a6c3c..2bdb6a7d90 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -117,8 +117,9 @@ struct Inner { /// an R24G8 buffer's depth twin: the views `before_dsv_bind` draws it into the plane with, /// by the object of the buffer whose plane they name passes: HashMap, - /// `bind::activity`'s count of dispatches when the twin was last drawn into the plane - drawn_at: Option, + /// clears of an R24G8 buffer's depth twin so far: they write the twin as a dispatch does + /// (`before_dsv_bind`) + twin_clears: u64, } /// A plane's twin: a colour texture of the plane's size with unordered access, resting in @@ -312,7 +313,7 @@ fn leave(cells: &mut HashMap>, cell: &Arc, res: usize) -> [ inner.members = inner.members.saturating_sub(1); if inner.members == 0 && cells.get(&cell.key).is_some_and(|c| Arc::ptr_eq(c, cell)) { cells.remove(&cell.key); - (inner.passes, inner.drawn_at) = (HashMap::new(), None); + inner.passes = HashMap::new(); return std::mem::take(&mut inner.twins); } Default::default() @@ -1016,9 +1017,13 @@ unsafe fn retain_pass_views(of: usize, pass: &PassViews) -> bool { /// Before OMSetRenderTargets binds the DSV at `dsv` on `list` (`real::cl_om_set_render_targets`). /// When the DSV names an R24G8 buffer whose depth plane has a twin, the twin is drawn into the /// plane first, so the draws that follow test what the title's compute programs wrote through -/// the twin. Not when no dispatch was recorded since the last such pass of the buffer -/// (`bind::activity`): then nothing wrote the twin. The pass is recorded where the bind is, so -/// it runs after everything recorded before on this list and on the lists submitted before it. +/// the twin. Not when this recording of the list already drew it into the plane of the same +/// object and no dispatch was recorded and no clear of the twin made since (`bind::activity`, +/// `Inner::twin_clears`): then nothing wrote the twin. That proof is the recording's +/// (`list_x::plane_drawn`): a recording that is reset and never submitted spares no later pass, +/// and neither does a pass for another object of the buffer (found by thehollowedone, +/// xcl-dev/xcl#3089). The pass is recorded where the bind is, so it runs after everything +/// recorded before on this list and on the lists submitted before it. /// /// On a DIRECT list XCL keeps state for; the title's own state of the list (view heaps, /// viewports, scissors, topology, vertex buffers, render targets, pipeline) is set again after @@ -1047,28 +1052,27 @@ pub(super) unsafe fn before_dsv_bind(list: *mut c_void, dsv: usize) { if state[0] == STATE_UNKNOWN { return left("the title moved a part of the depth plane to a state of its own"); } - // (`_views`: this call's own reference to the heaps while it records with them) - let (twin, n, pl, srv_heap, table, dsv_base, dsv_inc, _views) = { - let mut inner = cell.inner.lock().unwrap(); + let (twin, n, dev, held) = { + let inner = cell.inner.lock().unwrap(); let Some(t) = inner.twins[0].as_ref() else { return }; - if inner.drawn_at == Some(now) { - PLANE_PASSES_SPARED.fetch_add(1, Ordering::Relaxed); - return; + (t.res.clone(), t.n, t.dev as *mut c_void, (now, inner.twin_clears)) + }; + if super::list_x::plane_drawn(list, d.res, held) { + PLANE_PASSES_SPARED.fetch_add(1, Ordering::Relaxed); + return; + } + // (a bind left out here notes nothing: the next one draws) + let pl = match pass_pipelines_if_made(dev) { + Some(Some(pl)) => pl, + Some(None) => return left("the pass could not be made"), + None => { + start_pass_pipelines(dev); + return left("its pipelines are still being made"); } - let (twin, n, dev) = (t.res.clone(), t.n, t.dev as *mut c_void); - // (before `drawn_at` is set: a bind left out here leaves the next one to draw) - let pl = match pass_pipelines_if_made(dev) { - Some(Some(pl)) => pl, - Some(None) => { - drop(inner); - return left("the pass could not be made"); - } - None => { - drop(inner); - start_pass_pipelines(dev); - return left("its pipelines are still being made"); - } - }; + }; + // (`_views`: this call's own reference to the heaps while it records with them) + let (srv_heap, table, dsv_base, dsv_inc, _views) = { + let mut inner = cell.inner.lock().unwrap(); if !inner.passes.contains_key(&d.res) { let Some(pass) = make_pass_views(dev, d.res, &twin, &key, r16) else { drop(inner); @@ -1081,9 +1085,7 @@ pub(super) unsafe fn before_dsv_bind(list: *mut c_void, dsv: usize) { inner.passes.insert(d.res, pass); } let p = inner.passes[&d.res].clone(); - let views = (p.srv_heap.as_raw() as usize, p.srv_heap.GetGPUDescriptorHandleForHeapStart().ptr, p.dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr, p.dsv_inc); - inner.drawn_at = Some(now); - (twin, n, pl, views.0, views.1, views.2, views.3, p) + (p.srv_heap.as_raw() as usize, p.srv_heap.GetGPUDescriptorHandleForHeapStart().ptr, p.dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr, p.dsv_inc, p) }; let (mips, array) = (key.mips.max(1) as u32, key.array.max(1) as u32); let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; @@ -1111,6 +1113,7 @@ pub(super) unsafe fn before_dsv_bind(list: *mut c_void, dsv: usize) { super::list_x::barrier_words(list, &before); super::list_x::depth_only_pass(list, srv_heap, pl.rs.as_raw() as usize, if r16 { pl.steps.as_raw() } else { pl.float.as_raw() } as usize, table, &draws); super::list_x::barrier_words(list, &after); + super::list_x::note_plane_drawn(list, d.res, held); let c = PLANE_PASSES.fetch_add(1, Ordering::Relaxed) + 1; if c <= 4 || c.is_power_of_two() { crate::xlog_info!( @@ -1172,7 +1175,7 @@ pub(super) fn clear_target(res: usize, named: Option) -> Clear { // into the plane again. Found by thehollowedone, xcl-dev/xcl#3089) if let Clear::Twin(t) = &c { if o.cell.key.format == 44 && twins[0] == Some(*t) { - inner.drawn_at = None; + inner.twin_clears += 1; } } drop(inner); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b1952849a9..4dea0b5489 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -143,6 +143,22 @@ unsafe fn restore_after_own_pass(list: *mut c_void) { } } +/// Whether the recording `list` is on drew the depth twin of an R24G8 buffer into the plane of +/// its object `res` when the twin held what `held` says (`depth_uav::before_dsv_bind`). The +/// proof is the recording's: a Reset ends it, whether or not the recording was submitted, and +/// so does a KickoffX, after which other queues' work may come in between. +pub(super) fn plane_drawn(list: *mut c_void, res: usize, held: (u64, u64)) -> bool { + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.plane_drawn.contains(&(res, held.0, held.1))) +} + +/// The recording `list` is on drew the depth twin into the plane of `res` (`plane_drawn`). +pub(super) fn note_plane_drawn(list: *mut c_void, res: usize, held: (u64, u64)) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.plane_drawn.retain(|d| d.0 != res); + s.plane_drawn.push((res, held.0, held.1)); + } +} + /// Barriers of XCL's own on the PC list, as PC words (type, flags, resource, subresource, state /// before, state after). pub(super) unsafe fn barrier_words(list: *mut c_void, b: &[[u32; 8]]) { @@ -1007,6 +1023,10 @@ 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, + /// objects of R24G8 buffers whose depth twin this recording drew into the plane, each with + /// what the twin held then (`depth_uav::before_dsv_bind`: the dispatches recorded and the + /// twin's clears so far) + plane_drawn: Vec<(usize, u64, u64)>, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -5600,6 +5620,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.pso_dirty = false; // (other queues may run between what went and what follows) s.depth_in_step.clear(); + s.plane_drawn.clear(); } if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; @@ -6396,6 +6417,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.plane_drawn.clear(); (s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), old_generations) }; drop(old_generations); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b9b1896c09..0410aabbb2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -15144,6 +15144,8 @@ mod depth_uav_twin_tests { assert_eq!(depth_uav::clear_target(d, Some(t)), depth_uav::Clear::Twin(t)); depth_uav::before_dsv_bind(lraw, f.dsv as usize); assert_eq!(depth_uav::plane_passes(), (passes + 2, spared + 1, left), "after a clear of the twin it is drawn into the plane again"); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + assert_eq!(depth_uav::plane_passes(), (passes + 2, spared + 2, left), "and not once more on this recording"); // the buffer keeps the pass's two heaps itself (a recorded list names their descriptors) let kept = |key: u128| { let (mut size, mut heap) = (8u32, std::ptr::null_mut::()); @@ -15186,6 +15188,14 @@ mod depth_uav_twin_tests { } rb.Unmap(0, None); assert_eq!(distinct.len(), 256, "every texel its own value"); + // The list is reset for a new recording (what was recorded on the first is done here; + // a recording that was never submitted is reset the same way). Nothing of the first + // recording spares the new one its pass: no dispatch and no clear came in between. + assert!(list_x::reset_pc(lraw, f._alloc.as_raw() as usize, 0) >= 0, "reset list"); + let (passes, spared, left) = depth_uav::plane_passes(); + depth_uav::before_dsv_bind(lraw, f.dsv as usize); + assert_eq!(depth_uav::plane_passes(), (passes + 1, spared, left), "a new recording draws the twin into the plane again"); + assert!(close(lraw) >= 0, "close list"); // and still when XCL has forgotten the buffer: until the PC destroys it depth_uav::forget(d); assert!(depth_uav::PASS_HEAP_KEYS.iter().all(|&k| kept(k)), "the heaps live as long as the buffer"); From a9aa32db588abd94983482346bc2d06b44d46acf Mon Sep 17 00:00:00 2001 From: imnicho Date: Tue, 1 Dec 2026 10:39:24 +0100 Subject: [PATCH 3/3] D3D12.X: an R24G8 twin's pass runs with the title's predicate off After the review of e228ed5da (thehollowedone): the pass's draws were recorded while a predicate the title set with SetPredicationBufferX was on, so a failing predicate left the pass undrawn while the recording noted the plane as drawn. depth_only_pass takes the predicate off for its draws and sets it again after them from the list's own copy of the value the title's call latched (pred_buf), not from the title's memory. A predicate the title sets by the PC's own SetPredication, which XCL does not follow, still decides the pass's draws. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/list_x.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4dea0b5489..f62703622e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -103,7 +103,18 @@ fn once(counter: &AtomicU64, n: u64) -> bool { /// whole target with the pipeline `pso` under the root signature `rs`, its texture at `table` in /// the view heap `heap`. Past the hooks of a title's calls: nothing of it is kept as the /// title's, and what the title had set is set again (`restore_after_own_pass`). +/// +/// A predicate the title set with SetPredicationBufferX would decide these draws too: it is +/// taken off for the pass and set again after it from the list's own copy of its value +/// (`pred_buf`), which is what the title's call latched, whatever the title's memory holds by +/// then (found by thehollowedone, xcl-dev/xcl#3089). A predicate the title sets by the PC's own +/// call, which XCL does not follow, still decides them. pub(super) unsafe fn depth_only_pass(list: *mut c_void, heap: usize, rs: usize, pso: usize, table: u64, draws: &[(usize, u32, u32, [u32; 2])]) { + let predicate = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).and_then(|s| Some((s.predication?, s.pred_buf.as_ref()?.as_raw() as usize)).filter(|_| s.pred_in_state)); + let set_predication = pc::(list, PC_SET_PREDICATION); + if predicate.is_some() { + set_predication(list, 0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + } pc::(list, PC_SET_DESCRIPTOR_HEAPS)(list, 1, &heap); pc::(list, PC_SET_GRAPHICS_ROOT_SIGNATURE)(list, rs); pc::(list, PC_SET_PIPELINE_STATE)(list, pso); @@ -119,6 +130,9 @@ pub(super) unsafe fn depth_only_pass(list: *mut c_void, heap: usize, rs: usize, pc::(list, PC_DRAW_INSTANCED)(list, 3, 1, 0, 0); } restore_after_own_pass(list); + if let Some((op, buffer)) = predicate { + set_predication(list, buffer, 0, op); + } } /// After a graphics pass of XCL's own on `list` that set a view heap, a root signature, a