Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 182 additions & 13 deletions crates/xcl/src/hle/d3d12x/depth_uav.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
//! 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.
//!
//! Behind `XCL_DEPTH_UAV_TWIN=1`; with the switch off nothing is registered, a UAV of a depth
//! 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.
//!
//! (After the depth+UAV twins of xcl-dev/xcl#1989 by raylitebull: registering at creation, DSVs,
Expand All @@ -36,7 +36,7 @@ use windows::Win32::Graphics::Dxgi::Common::*;
use super::sharded::Sharded;

/// The switch's value when `XCL_DEPTH_UAV_TWIN` is not set.
const DEFAULT_ON: bool = false;
const DEFAULT_ON: bool = true;

/// Whether depth buffers with unordered access are kept (`XCL_DEPTH_UAV_TWIN`).
pub(super) fn enabled() -> bool {
Expand Down Expand Up @@ -81,6 +81,9 @@ struct Cell {
/// the plane (a copy, or the two known to hold the same): only then is the twin copied back
/// (`plan_barriers`)
entered: AtomicBool,
/// 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,
inner: Mutex<Inner>,
}

Expand All @@ -101,6 +104,10 @@ struct Twin {
res: ID3D12Resource,
/// its number in the log (`#n`)
n: u64,
/// 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
through: Option<ID3D12Resource>,
}

// D3D12 resources are free-threaded
Expand Down Expand Up @@ -198,7 +205,7 @@ fn register(res: usize, x: &[u8; 0x38], at: Option<usize>, 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), 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), inner: Mutex::new(Inner::default()) }))
.clone();
{
let mut inner = cell.inner.lock().unwrap();
Expand Down Expand Up @@ -353,7 +360,8 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D
let t = make_twin(dev, &key, twin_format(key.format, plane))?;
TWINS.fetch_add(1, Ordering::Relaxed);
let n = MADE.fetch_add(1, Ordering::Relaxed) + 1;
inner.twins[plane] = Some(Twin { res: t.clone(), n });
let through = if plane == 1 { make_through(dev, &key) } else { None };
inner.twins[plane] = Some(Twin { res: t.clone(), n, through });
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);
Expand Down Expand Up @@ -420,11 +428,32 @@ pub(super) struct PlaneCopy {
pub twin: ID3D12Resource,
}

/// A copy between stencil plane subresources of a title's object and the same ones of the
/// stencil twin, through the twin's buffer.
pub(super) struct StencilCopy {
/// the object the title's transition names
pub depth: usize,
/// the stencil plane's subresources it copies, as the twin numbers them (the buffer's are
/// these + `first`)
pub subs: Vec<u32>,
/// the buffer's first stencil plane subresource
pub first: u32,
pub twin: ID3D12Resource,
pub through: ID3D12Resource,
pub width: u32,
pub height: u32,
pub mips: u16,
}

/// What goes on the PC list with a title's barriers (`plan_barriers`).
#[derive(Default)]
pub(super) struct Plan {
/// before them: twins into depth planes (the buffer goes PARK → COPY_DEST, the title's
/// transition takes it on from COPY_DEST; the twin UNORDERED_ACCESS → COPY_SOURCE and back)
/// before them, and before `to_plane`: stencil twins into stencil planes (the buffer in PARK)
pub stencil_to_plane: Vec<StencilCopy>,
/// after them, and after `to_twin`: stencil planes into their twins (the buffer in PARK)
pub stencil_to_twin: Vec<StencilCopy>,
/// before them: twins into depth planes (the buffer goes PARK → COPY_DEST / DEPTH_WRITE, the
/// title's transition takes it on from there; the twin UNORDERED_ACCESS → COPY_SOURCE/SRV and back)
pub to_plane: Vec<PlaneCopy>,
/// after them: depth planes into twins (the buffer rests in PARK; the twin
/// UNORDERED_ACCESS → COPY_DEST and back)
Expand All @@ -437,6 +466,13 @@ fn plane_twinnable(o: &Object) -> bool {
matches!(o.cell.key.format, 19 | 39 | 53) && o.state & UNORDERED_ACCESS == 0
}

/// Whether the title's transitions of `o` into and out of UNORDERED_ACCESS are parked: those of
/// a buffer whose depth plane can have a twin, and of a D24S8 one (its stencil plane can; the PC
/// has no depth-stencil buffer in UNORDERED_ACCESS).
fn parked(o: &Object) -> bool {
plane_twinnable(o) || (o.cell.key.format == 44 && o.state & UNORDERED_ACCESS == 0)
}

/// The title's barriers `barriers` (PC D3D12_RESOURCE_BARRIERs as words, the console's bits
/// dropped) on a list (`direct`: a DIRECT one) as they go to the PC, and the copies around
/// them. A transition of an object whose depth plane can have a twin into or out of
Expand Down Expand Up @@ -467,7 +503,7 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec<u64>,
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(plane_twinnable) else {
let Some(o) = (b[0] == 0).then(|| OBJECTS.get(res)).flatten().filter(parked) else {
out.push(b);
continue;
};
Expand All @@ -490,14 +526,56 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec<u64>,
b[1] = flags & !END_ONLY;
// the depth plane's subresources the transition names (the stencil plane's come after them)
let n = o.cell.key.mips.max(1) as u32 * o.cell.key.array.max(1) as u32;
let subs: Vec<u32> = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub < n).then_some(sub).into_iter().collect() };
// (none for a D24S8: its depth plane has no twin)
let subs: Vec<u32> = if !plane_twinnable(&o) {
Vec::new()
} else if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES {
(0..n).collect()
} else {
(sub < n).then_some(sub).into_iter().collect()
};
let entered = &o.cell.entered;
if !direct && o.cell.inner.lock().unwrap().twins[0].is_some() {
static SAID: AtomicBool = AtomicBool::new(false);
if !SAID.swap(true, Ordering::Relaxed) {
crate::xlog_warn!("D3D12.X: a buffer with a depth UAV twin goes into or out of UNORDERED_ACCESS on a compute or copy list: the twin is not copied there");
}
}
let key = o.cell.key;
// the stencil plane's subresources the transition names, and its twin when shaders were
// given one: what they store there (a title's masks for its lighting) reaches the plane
// on the way out of UNORDERED_ACCESS, and what was drawn into the plane reaches the twin
// on the way in
let stencil_subs: Vec<u32> = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub >= n && sub < 2 * n).then(|| sub - n).into_iter().collect() };
let names_stencil = !stencil_subs.is_empty();
let stencil = (direct && names_stencil && matches!(key.format, 19 | 44)).then(|| stencil_twin_if_made(&o)).flatten().map(|(twin, through)| StencilCopy {
depth: res,
subs: stencil_subs,
first: n,
twin,
through,
width: key.width,
height: key.height,
mips: key.mips.max(1),
});
// (a twin whose last way in was not copied – on a compute list, or made since – holds
// something else than the plane: not copied back, as for the depth plane)
let stencil_entered = &o.cell.stencil_entered;
if entering && names_stencil {
stencil_entered.store(stencil.is_some(), Ordering::Relaxed);
}
let stencil = stencil.filter(|_| !leaving || stencil_entered.load(Ordering::Relaxed));
if let Some(s) = stencil {
let c = STENCIL_COPIES[leaving as usize].fetch_add(1, Ordering::Relaxed) + 1;
if c <= 2 || c.is_power_of_two() {
crate::xlog_info!("D3D12.X: depth UAV twin: the stencil plane of depth buffer {res:#x} ({}x{}) and its twin: {} ({c} such copies so far)", key.width, key.height, if leaving { "the twin is copied into the plane on the way out of UNORDERED_ACCESS" } else { "the plane is copied into the twin on the way into UNORDERED_ACCESS" });
}
if leaving {
plan.stencil_to_plane.push(s);
} else {
plan.stencil_to_twin.push(s);
}
}
if leaving {
before = PARK;
// (a twin whose last way in was not copied holds something else than the plane: not
Expand Down Expand Up @@ -554,6 +632,57 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec<u64>,
plan
}

/// Copies of a stencil plane into its twin, and of a twin into its plane.
static STENCIL_COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];

/// Copies of stencil planes into their twins, and of twins into their planes, so far.
pub(super) fn stencil_copies() -> (u64, u64) {
(STENCIL_COPIES[0].load(Ordering::Relaxed), STENCIL_COPIES[1].load(Ordering::Relaxed))
}

/// The stencil twin of `o`'s buffer and the buffer the two are copied through, when it has both.
fn stencil_twin_if_made(o: &Object) -> Option<(ID3D12Resource, ID3D12Resource)> {
let inner = o.cell.inner.lock().unwrap();
let t = inner.twins[1].as_ref()?;
Some((t.res.clone(), t.through.clone()?))
}

/// The row pitch of an 8-bit plane `width` texels wide in a buffer (D3D12_TEXTURE_DATA_PITCH_ALIGNMENT).
pub(super) fn stencil_pitch(width: u32) -> u32 {
width.max(1).next_multiple_of(256)
}

/// The buffer a stencil plane of `key`'s shape and its twin are copied through: room for the
/// largest subresource (one is copied at a time), resting in COPY_DEST.
unsafe fn make_through(dev: *mut c_void, key: &Key) -> Option<ID3D12Resource> {
if dev.is_null() {
return None;
}
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: (stencil_pitch(key.width) as u64 * key.height.max(1) as u64).next_multiple_of(0x1_0000),
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut out = std::ptr::null_mut();
let hr = super::real::dev_create_committed_resource(
dev,
&heap as *const _ as usize,
0,
&desc as *const _ as usize,
D3D12_RESOURCE_STATE_COPY_DEST.0 as usize,
0,
&ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID,
&mut out,
);
(hr >= 0 && !out.is_null()).then(|| ID3D12Resource::from_raw(out))
}

/// The depth twin of `o`'s buffer when it has one, and its number.
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))
Expand Down Expand Up @@ -1240,7 +1369,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 });
o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0, through: None });
}
let t = fake as usize;
let before = clears();
Expand Down Expand Up @@ -1271,7 +1400,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 });
o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0, through: None });
}

fn tr(res: usize, sub: u32, before: u32, after: u32) -> [u32; 8] {
Expand Down Expand Up @@ -1369,19 +1498,59 @@ mod tests {
assert_eq!(plan(tr(res, 1, DEPTH_WRITE, UA)), (vec![tr(res, 1, DEPTH_WRITE, PARK)], vec![(res, 1, vec![1], tw)]));
assert_eq!(plan(tr(res, 2, DEPTH_WRITE, UA)), (vec![tr(res, 2, DEPTH_WRITE, PARK)], vec![]), "a stencil subresource: parked, not copied");

// a D24S8 (its depth plane has no twin), an object made in UNORDERED_ACCESS, one XCL does
// not keep, a UAV barrier: as they came
// a D24S8 (its depth plane has no twin): parked, its depth plane not copied
assert!(register(d24, &desc(3, 64, 64, 45, 1, 6), None, DEPTH_WRITE));
assert_eq!(plan(tr(d24, ALL, DEPTH_WRITE, UA)), (vec![tr(d24, ALL, DEPTH_WRITE, PARK)], vec![]));
// an object made in UNORDERED_ACCESS, one XCL does not keep, a UAV barrier: as they came
assert!(register(in_ua, &desc(3, 64, 64, 40, 1, 6), None, UA));
let uav_barrier = [2, 0, res as u32, (res as u64 >> 32) as u32, 0, 0, 0, 0];
for b in [tr(d24, ALL, DEPTH_WRITE, UA), tr(in_ua, ALL, UA, DEPTH_WRITE), tr(unknown, ALL, DEPTH_WRITE, UA), uav_barrier] {
for b in [tr(in_ua, ALL, UA, DEPTH_WRITE), tr(unknown, ALL, DEPTH_WRITE, UA), uav_barrier] {
assert_eq!(plan(b), (vec![b], vec![]), "{b:x?}");
}
forget(res);
forget(d24);
forget(in_ua);
}

/// The stencil twin of a D24S8 (console D16S8) and of a D32S8: the plane is copied into it on
/// a DIRECT list's way into UNORDERED_ACCESS and back on the way out, only after such a way in
/// (not after one on a compute list, nor before the twin was made); the buffer is parked.
#[test]
fn a_stencil_twin_is_copied_around_unordered_access_after_a_copied_way_in() {
let stencil = |c: &[StencilCopy]| c.iter().map(|c| (c.depth, c.subs.clone(), c.first, c.twin.as_raw() as usize)).collect::<Vec<_>>();
for (k, console) in [118u32, 20].into_iter().enumerate() {
let res = 0x7E30_0000_1000usize + k * 0x1000;
assert!(register(res, &desc(3, 64, 64, console, 1, 6), None, DEPTH_WRITE));
let plan = |b: [u32; 8], direct: bool| {
let mut v = vec![b];
let p = plan_with(&mut v, direct, &mut Vec::new(), &mut |_, _| None);
(v, stencil(&p.stencil_to_twin), stencil(&p.stencil_to_plane))
};
// no twin yet: parked, nothing copied
assert_eq!(plan(tr(res, ALL, DEPTH_WRITE, UA), true), (vec![tr(res, ALL, DEPTH_WRITE, PARK)], vec![], vec![]), "console {console}");
let (t, through) = (stand_in(), stand_in());
{
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) });
}
let tw = t.as_raw() as usize;
// made since the way in: not copied back
assert_eq!(plan(tr(res, ALL, UA, DEPTH_READ), true), (vec![tr(res, ALL, PARK, DEPTH_READ)], vec![], vec![]), "console {console}");
// a DIRECT list's way in and out: copied both ways (the stencil plane is subresource 1)
let one = vec![(res, vec![0], 1, tw)];
assert_eq!(plan(tr(res, ALL, DEPTH_READ, UA), true).1, one, "console {console}");
assert_eq!(plan(tr(res, ALL, UA, DEPTH_READ), true).2, one, "console {console}");
// a compute list's way in: the twin is not copied back after it
assert_eq!(plan(tr(res, ALL, DEPTH_READ, UA), false), (vec![tr(res, ALL, DEPTH_READ, PARK)], vec![], vec![]), "console {console}");
assert_eq!(plan(tr(res, ALL, UA, DEPTH_READ), true).2, vec![], "console {console}");
// the stencil subresource alone
assert_eq!(plan(tr(res, 1, DEPTH_READ, UA), true).1, one, "console {console}");
assert_eq!(plan(tr(res, 1, UA, DEPTH_READ), true).2, one, "console {console}");
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() {
Expand Down
Loading
Loading