diff --git a/crates/xcl/src/hle/d3d12x/alias_copy.rs b/crates/xcl/src/hle/d3d12x/alias_copy.rs new file mode 100644 index 0000000000..d964ff022e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/alias_copy.rs @@ -0,0 +1,770 @@ +//! Textures a title places at one address in two formats: written through one, read through +//! the other. +//! +//! A retail title packs light as R9G9B9E5 into R32_UINT textures (its compute programs cannot +//! store R9G9B9E5) and samples the same memory through an R9G9B9E5 texture it places at the same +//! address: its sky, its light probes, the bounced light its lighting pass adds. On the console +//! the two are one memory. Here the written one is GPU-owned (`vram`) and the sampled one is a +//! texture of its own, kept in step with the title's memory (`title_textures`), which nothing +//! writes: what is read through it is stale. +//! +//! This module keeps the title's placed textures by address. Where a sampled one lies in the +//! memory of a written one of the same size, levels, layers and texel width and of another +//! format, the written one's texels are copied into it on the GPU, through a buffer (D3D12 +//! copies between two formats of one texel width in no other way). The copy is recorded where +//! the title says the written one is written no more for now: at its transition of the written +//! texture out of RENDER_TARGET / UNORDERED_ACCESS, as the PC list gets it +//! (`list_x::resource_barrier_x`). That is a legacy `ResourceBarrier` of the title's, or an +//! enhanced barrier of list #146, which `barrier_groups` makes a transition of and sends the +//! same way (with `XCL_BARRIER_GROUPS=0` those move no texture and ask for no copy). +//! +//! The states the two are moved from for the copy, and back to, are the ones the title's +//! transitions left each of their levels and layers in, kept in the order the title records +//! them, as `barrier_groups` keeps the states it starts from. A list recorded and never +//! submitted, and two lists submitted in another order than they were recorded in, are not told +//! apart. No copy is recorded while a texture of the pair is between the two halves of a split +//! transition: nothing may touch it there. +//! +//! The title's list names the written texture only; XCL adds the sampled one and the pair's +//! buffer to it. So the buffer holds a reference to the sampled texture, and both go when the +//! written texture goes: a list the title recorded and submits later, as long as it keeps the +//! texture it named itself, finds all three. +//! +//! What a copy puts into the sampled texture is not read back into the title's memory +//! (`is_copy_destination`): it is the written texture's texels, which have their own way back, +//! and XG lays the sampled format out in more bytes than the written one has under it. +//! +//! Behind `XCL_ALIAS_COPY=1`; with the switch off nothing is kept and every hook stops at one +//! atomic load. (After the format-aliased copies of xcl-dev/xcl#1989 by raylitebull: the pairs +//! by address and shape, and the copy through a buffer.) + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// RENDER_TARGET | UNORDERED_ACCESS +const WRITTEN: u32 = 0x4 | 0x8; +const COPY_DEST: u32 = 0x400; +const COPY_SOURCE: u32 = 0x800; +/// The states a COMPUTE list can move a texture from and to (with COMMON, 0): UNORDERED_ACCESS, +/// NON_PIXEL_SHADER_RESOURCE, COPY_DEST, COPY_SOURCE. +const ON_COMPUTE: u32 = 0x8 | 0x40 | COPY_DEST | COPY_SOURCE; +const BEGIN_ONLY: u32 = 1; +const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + +/// `XCL_ALIAS_COPY=1` (read once). +pub(super) fn on() -> bool { + #[cfg(test)] + if tests::ON_FOR_TEST.with(|c| c.get()) { + return true; + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("XCL_ALIAS_COPY").is_some_and(|v| v == "1"); + if on { + crate::xlog_info!("D3D12.X: alias copies are on (XCL_ALIAS_COPY=1): a sampled texture placed in the memory of a written one of another format is copied from it where the title stops writing that one"); + } + on + }) +} + +/// What the two textures of a pair have in common. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Shape { + dimension: i32, + width: u64, + height: u32, + depth: u16, + mips: u16, + /// bytes a texel + texel: u32, +} + +struct Tex { + dev: usize, + va: usize, + shape: Shape, + /// its PC format + format: u32, + /// a render target or a UAV texture: what it holds is what the GPU wrote + written: bool, + desc: D3D12_RESOURCE_DESC, + /// the state the title's transitions left each level of each layer in (by subresource), in + /// the order they were recorded + now: Vec, + /// the subresources between the two halves of a split transition + split: Vec, + /// a sampled one a pair's buffer was made for: copies go into it (`is_copy_destination`) + copied_into: bool, +} + +/// The buffer a pair's texels go through, and each level and layer as each of the two formats +/// lays it out for a copy (the written one's first). +struct Through { + buffer: ID3D12Resource, + parts: Vec<(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>, + /// a reference to the sampled texture: a recorded copy names it, and the title's list does + /// not (the title may release it before it submits that list) + sampled: ID3D12Resource, +} + +#[derive(Default)] +struct Table { + by_res: HashMap, + /// the textures at an address + at: HashMap>, + /// by (written, sampled); None: the pair cannot be copied + through: HashMap<(usize, usize), Option>>, +} + +// D3D12 objects are free-threaded +unsafe impl Send for Table {} + +static TABLE: Mutex> = Mutex::new(None); +/// Textures kept: the gate of `plan`. +static KEPT: AtomicUsize = AtomicUsize::new(0); +static PAIRS: AtomicU64 = AtomicU64::new(0); +/// Copies recorded. +static COPIES: AtomicU64 = AtomicU64::new(0); +/// Copies left out: a texture between the halves of a split transition, a list that is neither +/// DIRECT nor COMPUTE, a pair that cannot be copied, a state a COMPUTE list cannot move a +/// texture from. +static LEFT: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// Bytes a texel of the PC format `f` (None: block-compressed, depth, video or unknown). +fn texel_bytes(f: u32) -> Option { + Some(match f { + 1..=4 => 16, + 5..=8 => 12, + 9..=18 => 8, + 23..=43 | 67 | 87..=93 => 4, + 48..=59 | 85 | 86 | 115 => 2, + 60..=65 => 1, + _ => return None, + }) +} + +fn subresources(d: &D3D12_RESOURCE_DESC) -> u32 { + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize.max(1) as u32 }; + d.MipLevels.max(1) as u32 * layers +} + +/// The title placed the texture `res` (PC description at `pc`, 0x38 bytes) at `va` in `state` +/// (`device_x::create_placed_resource_x`). +pub(super) unsafe fn note_created(dev: *mut c_void, res: *mut c_void, va: usize, pc: *const u8, state: u32) { + if on() { + keep(dev as usize, res as usize, va, &std::ptr::read_unaligned(pc as *const D3D12_RESOURCE_DESC), state); + } +} + +/// `note_created` without the switch. +fn keep(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32) { + let flags = desc.Flags.0 as u32; + if res == 0 || va == 0 || desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || desc.SampleDesc.Count > 1 || flags & 2 != 0 { + return; + } + let format = desc.Format.0 as u32; + let Some(texel) = texel_bytes(format) else { return }; + let shape = Shape { dimension: desc.Dimension.0, width: desc.Width, height: desc.Height, depth: desc.DepthOrArraySize.max(1), mips: desc.MipLevels.max(1), texel }; + let written = flags & 5 != 0; + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(Table::default); + let n = subresources(desc) as usize; + if t.by_res.insert(res, Tex { dev, va, shape, format, written, desc: *desc, now: vec![state; n], split: vec![false; n], copied_into: false }).is_none() { + KEPT.fetch_add(1, Ordering::Relaxed); + } + let here = t.at.entry(va).or_default(); + if !here.contains(&res) { + here.push(res); + } + let other = here.iter().filter(|&&o| o != res).filter_map(|o| t.by_res.get(o)).find(|o| o.shape == shape && o.written != written && o.format != format).map(|o| o.format); + if let Some(other) = other { + let n = PAIRS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let (w, r) = if written { (format, other) } else { (other, format) }; + crate::xlog_info!( + "D3D12.X: alias copy: at {va:#x} a {}x{}x{} texture of {} levels is written as format {w} and read as format {r} ({n} such pairs so far)", + shape.width, + shape.height, + shape.depth, + shape.mips + ); + } + } +} + +/// The title's last reference to `res` went. +pub(super) fn forget(res: usize) { + if KEPT.load(Ordering::Relaxed) == 0 { + return; + } + let gone = { + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { return }; + let Some(x) = t.by_res.remove(&res) else { return }; + KEPT.fetch_sub(1, Ordering::Relaxed); + if let Some(v) = t.at.get_mut(&x.va) { + v.retain(|&r| r != res); + if v.is_empty() { + t.at.remove(&x.va); + } + } + let keys: Vec<(usize, usize)> = t.through.keys().filter(|k| k.0 == res || k.1 == res).copied().collect(); + keys.into_iter().filter_map(|k| t.through.remove(&k).flatten()).collect::>() + }; + // The buffers of its pairs go as the texture itself does (`real`'s last release of it comes + // right after this): a list in flight may still copy through them, so the last reference to + // each is `late_release`'s until the queues are past the work submitted before, and so is + // the buffer's reference to the sampled texture. (Outside the table's lock.) + for th in gone { + super::late_release::hold_own(th.buffer.clone()); + super::late_release::hold_own(th.sampled.clone()); + } +} + +/// Whether `res` is a sampled texture copies go into. What the GPU puts there is its written +/// texture's texels, and XG lays the sampled format out in more bytes than the written texture +/// has under it (0x3c0000 for R9G9B9E5 where R32_UINT has 0x384000, at 1280x720): read back into +/// the title's memory as a texture the title's own work wrote is (`title_textures`), it went +/// over what the title keeps behind the pair. Found, with this way out of it, by claudetools-gh +/// (xcl-dev/xcl#3094). +pub(super) fn is_copy_destination(res: usize) -> bool { + if PAIRS.load(Ordering::Relaxed) == 0 { + return false; + } + TABLE.lock().unwrap().as_ref().is_some_and(|t| t.by_res.get(&res).is_some_and(|x| x.copied_into)) +} + +/// The sampled textures in the memory of the written texture `res`. +fn sampled_of(t: &Table, res: usize) -> Vec { + let Some(x) = t.by_res.get(&res).filter(|x| x.written) else { return Vec::new() }; + t.at.get(&x.va).map_or(Vec::new(), |v| v.iter().copied().filter(|o| t.by_res.get(o).is_some_and(|y| !y.written && y.shape == x.shape && y.format != x.format)).collect()) +} + +/// A copy to record: (the written texture, the sampled one). +pub(super) type Job = (usize, usize); + +/// The transitions among `barriers`, the PC barriers a call of the title's has become +/// (`list_x::resource_barrier_x`, its console state bits gone): the states they leave the kept +/// textures' subresources in are kept, and a written texture's transition out of RENDER_TARGET / +/// UNORDERED_ACCESS asks for the copies into its sampled ones, once a pair for the call, +/// recorded after the barriers (`record`). The first half of a split transition moves nothing +/// yet: what it names is between the halves until the second. +pub(super) fn plan(barriers: &[[u32; 8]]) -> Vec { + let mut jobs: Vec = Vec::new(); + if KEPT.load(Ordering::Relaxed) == 0 { + return jobs; + } + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { return jobs }; + for b in barriers.iter().filter(|b| b[0] == 0) { + let (res, flags, sub, before, after) = ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[1], b[4], b[5], b[6]); + let Some(x) = t.by_res.get_mut(&res) else { continue }; + // (a subresource the PC's texture does not have: `barrier_groups` sends none such) + if sub != ALL && sub as usize >= x.now.len() { + continue; + } + let named = if sub == ALL { 0..x.now.len() } else { sub as usize..sub as usize + 1 }; + if flags & BEGIN_ONLY != 0 { + x.split[named].fill(true); + continue; + } + x.split[named.clone()].fill(false); + x.now[named].fill(after); + if before & WRITTEN != 0 && after & WRITTEN == 0 && !jobs.iter().any(|j| j.0 == res) { + jobs.extend(sampled_of(t, res).into_iter().map(|r| (res, r))); + } + } + jobs +} + +/// The PC's own method `slot` of the device `dev` (past XCL's hooks when it is adopted: the +/// buffer is XCL's, not a title's). +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) + } +} + +/// `Through` for a written texture of `from` and the sampled one `sampled` of `to` on `dev`: +/// None when the two do not lay their levels and layers out alike for a copy. +unsafe fn make_through(dev: *mut c_void, from: &D3D12_RESOURCE_DESC, to: &D3D12_RESOURCE_DESC, sampled: usize) -> Option { + use windows_sys::core::GUID; + // (every level of every layer is a part: an array of 64 layers with two levels has 128) + let parts = subresources(from); + if parts == 0 || parts != subresources(to) { + return None; + } + type Footprints = unsafe extern "system" fn(*mut c_void, *const D3D12_RESOURCE_DESC, u32, u32, u64, *mut D3D12_PLACED_SUBRESOURCE_FOOTPRINT, *mut u32, *mut u64, *mut u64); + let footprints: Footprints = std::mem::transmute(dev_fn(dev, 38)); + let layout = |d: &D3D12_RESOURCE_DESC| { + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]; + let mut bytes = 0u64; + let d = D3D12_RESOURCE_DESC { Alignment: 0, ..*d }; + footprints(dev, &d, 0, parts, 0, rows.as_mut_ptr(), std::ptr::null_mut(), std::ptr::null_mut(), &mut bytes); + (rows, bytes) + }; + let ((of_from, bytes), (of_to, bytes_to)) = (layout(from), layout(to)); + let alike = of_from.iter().zip(&of_to).all(|(a, b)| { + let (fa, fb) = (a.Footprint, b.Footprint); + a.Offset == b.Offset && (fa.Width, fa.Height, fa.Depth, fa.RowPitch) == (fb.Width, fb.Height, fb.Depth, fb.RowPitch) + }); + if bytes == 0 || bytes == u64::MAX || bytes != bytes_to || !alike { + 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: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + type Create = unsafe extern "system" fn(*mut c_void, *const D3D12_HEAP_PROPERTIES, i32, *const D3D12_RESOURCE_DESC, i32, *const c_void, *const GUID, *mut *mut c_void) -> i32; + let create: Create = std::mem::transmute(dev_fn(dev, 27)); + let mut raw = std::ptr::null_mut(); + let hr = create(dev, &heap, 0, &desc, 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut raw); + if hr < 0 || raw.is_null() { + return None; + } + let buffer = ID3D12Resource::from_raw(raw); + let sampled = sampled as *mut c_void; + Some(Through { buffer, parts: of_from.into_iter().zip(of_to).collect(), sampled: ID3D12Resource::from_raw_borrowed(&sampled)?.clone() }) +} + +/// Whether a copy can start from the states `now` of a texture's subresources (`split`: the +/// ones between the halves of a split transition) on a DIRECT list or a COMPUTE one +/// (`compute`). Err: which of `LEFT` the copy is left out for. +fn can_copy(now: &[u32], split: &[bool], compute: bool) -> Result<(), usize> { + if split.iter().any(|&s| s) { + return Err(0); + } + if compute && now.iter().any(|&s| s & !ON_COMPUTE != 0) { + return Err(3); + } + Ok(()) +} + +/// The moves of the texture `res`, whose subresources are in the states `now`, to the state +/// `to` (pushed to `before`) and back (pushed to `after`): one for the whole texture when it is +/// in one state, else one a subresource. +fn moves(res: usize, now: &[u32], to: u32, before: &mut Vec<[u32; 8]>, after: &mut Vec<[u32; 8]>) { + let tr = |sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + if now.iter().all(|&s| s == now[0]) { + if now[0] != to { + before.push(tr(ALL, now[0], to)); + after.push(tr(ALL, to, now[0])); + } + return; + } + for (k, &state) in now.iter().enumerate().filter(|(_, &state)| state != to) { + before.push(tr(k as u32, state, to)); + after.push(tr(k as u32, to, state)); + } +} + +/// The copies `jobs` (`plan`) on `list`, after the title's barriers: each written texture's +/// texels into its sampled one through the pair's buffer, with the moves to the copy states and +/// back to the states the title's transitions have the two in. On a DIRECT or COMPUTE list XCL +/// keeps state for; on a COMPUTE one only from states such a list can name. +pub(super) unsafe fn record(list: *mut c_void, jobs: &[Job]) { + if jobs.is_empty() { + return; + } + let compute = match super::list_x::tracked_list_type(list) { + Some(D3D12_COMMAND_LIST_TYPE_DIRECT) => false, + Some(D3D12_COMMAND_LIST_TYPE_COMPUTE) => true, + _ => { + LEFT[1].fetch_add(jobs.len() as u64, Ordering::Relaxed); + return; + } + }; + let tr = |res: usize, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, ALL, before, after, 0]; + for &(w, r) in jobs { + let (found, w_now, r_now, dev, from, to) = { + let g = TABLE.lock().unwrap(); + let Some(t) = g.as_ref() else { return }; + let (Some(x), Some(y)) = (t.by_res.get(&w), t.by_res.get(&r)) else { continue }; + if let Err(why) = can_copy(&x.now, &x.split, compute).and(can_copy(&y.now, &y.split, compute)) { + LEFT[why].fetch_add(1, Ordering::Relaxed); + continue; + } + (t.through.get(&(w, r)).cloned(), x.now.clone(), y.now.clone(), x.dev as *mut c_void, x.desc, y.desc) + }; + let through = match found { + Some(through) => through, + // The pair's first copy. Its buffer is made with the table's lock released: the + // footprints and the buffer are calls into the PC's D3D12, and `plan` of every other + // pair waits for that lock (found by andrewDoing, xcl-dev/xcl#3094). + None => { + let made = make_through(dev, &from, &to, r).map(Arc::new); + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { return }; + // (a texture of the pair went meanwhile: the buffer just made goes with this call) + if !t.by_res.contains_key(&w) { + continue; + } + let Some(y) = t.by_res.get_mut(&r) else { continue }; + y.copied_into |= made.is_some(); + // (another list's recording made the pair's buffer first: that one is used) + t.through.entry((w, r)).or_insert(made).clone() + } + }; + let Some(through) = through else { + LEFT[2].fetch_add(1, Ordering::Relaxed); + continue; + }; + let buffer = through.buffer.as_raw() as usize; + let mut before = vec![tr(buffer, 0, COPY_DEST)]; + let mut after = vec![tr(buffer, COPY_SOURCE, 0)]; + moves(w, &w_now, COPY_SOURCE, &mut before, &mut after); + moves(r, &r_now, COPY_DEST, &mut before, &mut after); + // (the sampled one is noted as written by the GPU there: no upload from the title's + // memory goes over the copy) + super::list_x::texture_through_buffer(list, w, r, buffer, &through.parts, &before, &tr(buffer, COPY_DEST, COPY_SOURCE), &after); + let n = COPIES.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: alias copy: {w:#x} (in state {:#x}) into {r:#x} (in state {:#x}); {n} copies so far, left out: {} between the halves of a split transition, {} on a list of another kind, {} of pairs that cannot be copied, {} from a state a compute list cannot name", + w_now[0], + r_now[0], + LEFT[0].load(Ordering::Relaxed), + LEFT[1].load(Ordering::Relaxed), + LEFT[2].load(Ordering::Relaxed), + LEFT[3].load(Ordering::Relaxed) + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + thread_local! { + /// `on` for this thread: a test that goes through the hooks of a title's calls. + pub(super) static ON_FOR_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + fn texture(format: u32, width: u64, height: u32, mips: u16, flags: i32) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: width, + Height: height, + DepthOrArraySize: 1, + MipLevels: mips, + Format: DXGI_FORMAT(format as i32), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAGS(flags), + ..Default::default() + } + } + + const NONE: [Job; 0] = []; + + fn pairs_of(res: usize) -> Vec { + sampled_of(TABLE.lock().unwrap().as_ref().unwrap(), res) + } + + /// A sampled texture is the pair of a written one at its address when size, levels and + /// texel width agree and the format does not; a buffer, a depth buffer and a + /// block-compressed texture are not kept at all. + #[test] + fn a_sampled_texture_in_the_memory_of_a_written_one_of_another_format_is_its_pair() { + let (va, w, r) = (0x7AC0_0000_1000usize, 0x7AC1_0000_0010usize, 0x7AC1_0000_0020usize); + // R32_UINT with unordered access, R9G9B9E5 sampled + keep(1, w, va, &texture(42, 640, 360, 1, 4), 0x8); + keep(1, r, va, &texture(67, 640, 360, 1, 0), 0xC0); + assert_eq!(pairs_of(w), [r]); + assert_eq!(pairs_of(r), [] as [usize; 0], "asked of the sampled one: none"); + // another size, another count of levels, a wider texel, the same format, another address + for (k, (d, at)) in [(texture(67, 320, 180, 1, 0), va), (texture(67, 640, 360, 2, 0), va), (texture(10, 640, 360, 1, 0), va), (texture(42, 640, 360, 1, 0), va), (texture(67, 640, 360, 1, 0), va + 0x1_0000)] + .into_iter() + .enumerate() + { + keep(1, r + 0x100 + k, at, &d, 0xC0); + } + assert_eq!(pairs_of(w), [r], "none of those is its pair"); + // a second written one there (a render target) of the same shape is no pair of the first + keep(1, w + 0x1000, va, &texture(42, 640, 360, 1, 1), 0x4); + assert_eq!(pairs_of(w), [r]); + assert_eq!(pairs_of(w + 0x1000), [r], "the sampled one is the pair of both"); + keep(1, w + 0x2000, va, &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, ..texture(0, 4096, 1, 1, 0) }, 0); + keep(1, w + 0x2001, va, &texture(45, 640, 360, 1, 2), 0x10); + keep(1, w + 0x2002, va, &texture(71, 640, 360, 1, 0), 0xC0); + assert!(!TABLE.lock().unwrap().as_ref().unwrap().by_res.contains_key(&(w + 0x2000)), "a buffer is not kept"); + assert!((0x2001..=0x2002).all(|k| !TABLE.lock().unwrap().as_ref().unwrap().by_res.contains_key(&(w + k))), "nor a depth buffer, nor a BC1 texture"); + assert!(!is_copy_destination(r), "no copy has gone into it"); + // the sampled one gone: no pair + forget(r); + assert_eq!(pairs_of(w), [] as [usize; 0]); + for res in (0..5).map(|k| r + 0x100 + k).chain([w, w + 0x1000]) { + forget(res); + } + } + + /// A written texture's transition out of UNORDERED_ACCESS or RENDER_TARGET asks for the + /// copy; one that stays written, the first half of a split one and a transition of the + /// sampled one do not. The states are followed, also where a call names every level of a + /// texture by itself. + #[test] + fn a_written_textures_transition_out_of_a_written_state_asks_for_the_copy() { + let (va, w, r) = (0x7AC0_0000_2000usize, 0x7AC2_0000_0010usize, 0x7AC2_0000_0020usize); + keep(1, w, va, &texture(42, 128, 128, 1, 5), 0x8); + keep(1, r, va, &texture(67, 128, 128, 1, 0), 0xC0); + 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]; + let now = |res: usize| TABLE.lock().unwrap().as_ref().unwrap().by_res[&res].now.clone(); + let split = |res: usize| TABLE.lock().unwrap().as_ref().unwrap().by_res[&res].split.clone(); + assert_eq!(plan(&[tr(w, 0, ALL, 0x8, 0xC0)]), [(w, r)], "unordered access to shader resource"); + assert_eq!(now(w), [0xC0]); + assert_eq!(plan(&[tr(w, 0, 0, 0xC0, 0x4)]), NONE, "into a written state: nothing to copy yet"); + assert_eq!(now(w), [0x4], "its one subresource"); + assert_eq!(plan(&[tr(w, BEGIN_ONLY, ALL, 0x4, 0x800)]), NONE, "the first half of a split transition"); + assert_eq!((now(w), split(w)), (vec![0x4], vec![true]), "not moved yet, and between the halves"); + assert_eq!(plan(&[tr(w, 2, ALL, 0x4, 0x800), tr(w, 0, ALL, 0x800, 0x4), tr(w, 0, ALL, 0x4, 0x8)]), [(w, r)], "its end: once for the call; render target to unordered access asks for none"); + assert_eq!((now(w), split(w)), (vec![0x8], vec![false])); + assert_eq!(plan(&[tr(r, 0, ALL, 0xC0, 0x400)]), NONE, "the sampled one's transition asks for none"); + assert_eq!(now(r), [0x400]); + // a UAV barrier and an aliasing barrier ask for none + assert_eq!(plan(&[[2, 0, w as u32, (w as u64 >> 32) as u32, 0, 0, 0, 0], [1, 0, w as u32, (w as u64 >> 32) as u32, r as u32, (r as u64 >> 32) as u32, 0, 0]]), NONE); + forget(w); + forget(r); + + // two levels, named one by one (as `barrier_groups` names a range that is not the whole) + let (va, w, r) = (va + 0x10_0000, w + 0x100, r + 0x100); + keep(1, w, va, &texture(42, 128, 128, 2, 4), 0x8); + keep(1, r, va, &texture(67, 128, 128, 2, 0), 0xC0); + assert_eq!(plan(&[tr(w, 0, 1, 0x8, 0xC0), tr(w, 0, 0, 0x8, 0xC0)]), [(w, r)], "both levels leave unordered access: once for the call"); + assert_eq!(now(w), [0xC0, 0xC0]); + assert_eq!(plan(&[tr(w, 0, 0, 0xC0, 0x8)]), NONE, "one level back into a written state"); + assert_eq!(now(w), [0x8, 0xC0], "each level where the title has it"); + assert_eq!(plan(&[tr(w, 0, 0, 0x8, 0xC0)]), [(w, r)], "and out of it again"); + // the copy's moves: one for a texture in one state, one a level otherwise + let (mut before, mut after) = (Vec::new(), Vec::new()); + moves(w, &[0xC0, 0xC0], COPY_SOURCE, &mut before, &mut after); + assert_eq!((before.clone(), after.clone()), (vec![tr(w, 0, ALL, 0xC0, COPY_SOURCE)], vec![tr(w, 0, ALL, COPY_SOURCE, 0xC0)])); + (before, after) = (Vec::new(), Vec::new()); + moves(w, &[0x8, COPY_SOURCE, 0xC0], COPY_SOURCE, &mut before, &mut after); + assert_eq!(before, [tr(w, 0, 0, 0x8, COPY_SOURCE), tr(w, 0, 2, 0xC0, COPY_SOURCE)], "each level from its own state; none for one already there"); + assert_eq!(after, [tr(w, 0, 0, COPY_SOURCE, 0x8), tr(w, 0, 2, COPY_SOURCE, 0xC0)]); + forget(w); + forget(r); + } + + /// The copy on a GPU (WARP), by the calls a retail title makes: an R32_UINT array texture + /// with unordered access, 70 layers and two levels (140 parts) holds a pattern; after the + /// title's enhanced barrier of it (list #146: unordered access to shader resource) its + /// R9G9B9E5 pair, read back, holds the same bytes in every level of every layer. Then the + /// pair's buffer goes with the pair. + #[test] + fn gpu_a_written_textures_texels_reach_its_sampled_pair_at_the_titles_barrier() { + use super::super::real::{adopt, Kind}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + unsafe { + let skip = || crate::gpu::recomp::runner::skip_test("no WARP device"); + if !super::super::barrier_groups::enabled() { + return crate::gpu::recomp::runner::skip_test("XCL_BARRIER_GROUPS=0: the title's enhanced barriers move no texture"); + } + let Ok(factory) = CreateDXGIFactory1::() else { return skip() }; + let Ok(warp) = factory.EnumWarpAdapter::() else { return skip() }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return skip(); + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let committed = |d: &D3D12_RESOURCE_DESC, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, d, state, None, &mut r).expect("a resource"); + r.unwrap() + }; + let (read_states, default) = (D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_HEAP_TYPE_DEFAULT); + const PARTS: usize = 140; + let (of_written, of_sampled) = (D3D12_RESOURCE_DESC { DepthOrArraySize: 70, ..texture(42, 16, 8, 2, 4) }, D3D12_RESOURCE_DESC { DepthOrArraySize: 70, ..texture(67, 16, 8, 2, 0) }); + let written = committed(&of_written, default, D3D12_RESOURCE_STATE_COPY_DEST); + let sampled = committed(&of_sampled, default, read_states); + let layout = |d: &D3D12_RESOURCE_DESC| { + let (mut rows, mut bytes) = (vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); PARTS], 0u64); + dev.GetCopyableFootprints(d, 0, PARTS as u32, 0, Some(rows.as_mut_ptr()), None, None, Some(&mut bytes)); + (rows, bytes) + }; + let ((rows_w, bytes), (rows_r, _)) = (layout(&of_written), layout(&of_sampled)); + let buffer = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + committed( + &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() }, + heap, + state, + ) + }; + // every texel another value + let texel = |part: usize, x: usize, y: usize| ((part as u32 + 1) << 16 | (y as u32) << 8 | x as u32).wrapping_mul(0x9E37_79B1); + let up = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("map upload"); + for (level, f) in rows_w.iter().enumerate() { + for y in 0..f.Footprint.Height as usize { + for x in 0..f.Footprint.Width as usize { + ((p as *mut u8).add(f.Offset as usize + y * f.Footprint.RowPitch as usize + x * 4) as *mut u32).write_unaligned(texel(level, x, y)); + } + } + } + up.Unmap(0, None); + let lraw = list.as_raw(); + // (PC calls of the list by slot: once the list is adopted its own table is XCL's) + let pc_vt = *(lraw as *const *const usize); + let barrier = |res: &ID3D12Resource, 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, ALL, 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, f: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(b), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *f } }; + let level = |t: &ID3D12Resource, k: usize| 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 as u32 } }; + for (k, f) in rows_w.iter().enumerate() { + copy(&level(&written, k), &placed(&up, f)); + } + barrier(&written, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + // the two as a title placed them, the list as a title's + let (va, w, r) = (0x7AC0_0000_4000usize, written.as_raw() as usize, sampled.as_raw() as usize); + keep(dev.as_raw() as usize, w, va, &of_written, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32); + keep(dev.as_raw() as usize, r, va, &of_sampled, read_states.0 as u32); + adopt(lraw, Kind::CommandList); + super::super::list_x::on_create(lraw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + // the title's enhanced barrier of the written one, by its own call (list #146): layout + // and access unordered access to shader resource, all subresources + let of_the_written = D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_COMPUTE_SHADING, + SyncAfter: D3D12_BARRIER_SYNC_ALL_SHADING, + AccessBefore: D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + AccessAfter: D3D12_BARRIER_ACCESS_SHADER_RESOURCE, + LayoutBefore: D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + LayoutAfter: D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, + pResource: std::mem::transmute_copy(&written), + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE { IndexOrFirstMipLevel: u32::MAX, ..Default::default() }, + Flags: D3D12_TEXTURE_BARRIER_FLAG_NONE, + }; + let group = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &of_the_written } }; + let copies = COPIES.load(Ordering::Relaxed); + ON_FOR_TEST.with(|c| c.set(true)); + super::super::list_x::uav_barrier_x(lraw, 1, &group as *const D3D12_BARRIER_GROUP as *const c_void); + ON_FOR_TEST.with(|c| c.set(false)); + assert!(COPIES.load(Ordering::Relaxed) > copies, "the copy is recorded"); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res[&w].now.iter().all(|&s| s == read_states.0 as u32), "the written one is where the barrier left it"); + assert!(is_copy_destination(r) && !is_copy_destination(w), "the sampled one is what copies go into"); + + // the sampled one, from the state the title has it in, to a readback buffer + let back = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + barrier(&sampled, read_states, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (k, f) in rows_r.iter().enumerate() { + copy(&placed(&back, f), &level(&sampled, k)); + } + 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 = 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 = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + queue.Signal(&fence, 1).expect("signal"); + crate::gpu::fence::wait(&fence, 1, &dev, None, 5000).expect("the copies complete"); + assert!(dev.GetDeviceRemovedReason().is_ok(), "the device is there"); + + let mut p = std::ptr::null_mut(); + back.Map(0, None, Some(&mut p)).expect("map readback"); + let mut wrong = Vec::new(); + for (k, f) in rows_r.iter().enumerate() { + for y in 0..f.Footprint.Height as usize { + for x in 0..f.Footprint.Width as usize { + let got = ((p as *const u8).add(f.Offset as usize + y * f.Footprint.RowPitch as usize + x * 4) as *const u32).read_unaligned(); + if got != texel(k, x, y) && wrong.len() < 8 { + wrong.push((k, x, y, got)); + } + } + } + } + back.Unmap(0, None); + assert!(wrong.is_empty(), "(part, x, y, bits) of the sampled texture that are not the written one's: {wrong:x?}"); + + // the pair's buffer goes with the pair: no entry is left for it, and once the queues + // are past the work before it nothing of XCL's holds the buffer + let through = TABLE.lock().unwrap().as_ref().and_then(|t| t.through.get(&(w, r)).cloned().flatten()).expect("the pair's buffer").buffer.clone(); + let references = |b: &ID3D12Resource| { + let (raw, vt) = (b.as_raw(), *(b.as_raw() as *const *const usize)); + let (add, release): (unsafe extern "system" fn(*mut c_void) -> u32, unsafe extern "system" fn(*mut c_void) -> u32) = (std::mem::transmute(*vt.add(1)), std::mem::transmute(*vt.add(2))); + add(raw); + release(raw) + }; + assert!(references(&through) >= 2, "the table's and this test's"); + // (the buffer holds the sampled texture: the title's list did not name it) + let held = references(&sampled); + assert!(held >= 2, "the buffer's and this test's"); + forget(w); + assert!(TABLE.lock().unwrap().as_ref().is_some_and(|t| t.through.keys().all(|k| k.0 != w && k.1 != w)), "no buffer is kept for a pair that went"); + let t0 = std::time::Instant::now(); + while references(&through) > 1 && t0.elapsed() < std::time::Duration::from_secs(10) { + super::super::late_release::drain_known(true); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(references(&through), 1, "the buffer of a pair that went is released once the queues are past it"); + assert_eq!(references(&sampled), held - 1, "and with it the buffer's reference to the sampled texture"); + forget(r); + } + } + + /// A copy starts from the states the title has a texture's levels in; not while one of them + /// is between the halves of a split transition, and on a COMPUTE list only from states such + /// a list can name (a texture a DIRECT list left for pixel shaders is not in one). + #[test] + fn a_copy_starts_from_states_the_list_can_name() { + assert_eq!(can_copy(&[0xC0], &[false], false), Ok(()), "a DIRECT list, read by shaders"); + assert_eq!(can_copy(&[0x40, 0x0, 0x8, COPY_DEST], &[false; 4], true), Ok(()), "a COMPUTE list: read by compute shaders, COMMON, written, copied into"); + assert_eq!(can_copy(&[0x40, 0xC0], &[false; 2], true), Err(3), "one level where pixel shaders read it"); + assert_eq!(can_copy(&[0x4], &[false], true), Err(3), "a render target"); + assert_eq!(can_copy(&[0xC0, 0xC0], &[false, true], false), Err(0), "one level between the halves of a split transition"); + assert_eq!(can_copy(&[0x40], &[true], true), Err(0)); + } + + /// The reviewer's case: the sampled texture's split transition begins, the written one + /// leaves unordered access in a later call, then the split ends. No copy may touch the + /// sampled texture between the halves; the copy asked for there is left out and counted. + #[test] + fn no_copy_is_recorded_between_the_halves_of_a_split_transition() { + let (va, w, r) = (0x7AC0_0000_6000usize, 0x7AC6_0000_0010usize, 0x7AC6_0000_0020usize); + keep(1, w, va, &texture(42, 64, 64, 1, 4), 0x8); + keep(1, r, va, &texture(67, 64, 64, 1, 0), 0xC0); + let tr = |res: usize, flags: u32, before: u32, after: u32| [0, flags, res as u32, (res as u64 >> 32) as u32, ALL, before, after, 0]; + let state = |res: usize| { + let g = TABLE.lock().unwrap(); + let x = &g.as_ref().unwrap().by_res[&res]; + (x.now.clone(), x.split.clone()) + }; + assert_eq!(plan(&[tr(r, BEGIN_ONLY, 0xC0, COPY_SOURCE)]), NONE); + let jobs = plan(&[tr(w, 0, 0x8, 0x40)]); + assert_eq!(jobs, [(w, r)], "the written one's transition asks for the copy"); + let (x, y) = (state(w), state(r)); + assert_eq!(can_copy(&x.0, &x.1, false).and(can_copy(&y.0, &y.1, false)), Err(0), "which is left out: the sampled one is between the halves"); + assert_eq!(plan(&[tr(r, 2, 0xC0, COPY_SOURCE)]), NONE, "the split's end"); + let y = state(r); + assert_eq!((y.0.clone(), can_copy(&y.0, &y.1, false)), (vec![COPY_SOURCE], Ok(())), "moved, and a copy may touch it again"); + forget(w); + forget(r); + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8f2809df65..21d7da1dc2 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1290,6 +1290,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::alias_copy::note_created(this, *ppv, va as usize, d.as_ptr(), state); super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state); } return hr; @@ -1313,6 +1314,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, Ok(()) => { real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::alias_copy::note_created(this, *ppv, va as usize, d.as_ptr(), state); super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else if small_hr.is_some() { "CreatePlacedResourceX (sampled: 4 KiB placement)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state); return hr; } @@ -1331,6 +1333,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, real::note_title_address(*ppv as usize, va as usize); if !buffer { super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::alias_copy::note_created(this, *ppv, va as usize, d.as_ptr(), state); super::lut3d::created("CreatePlacedResourceX (a resource of its own: not kept in step)", *ppv, Some(&x), Some(va as usize), false, state); } } diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 1c17726248..8921e30cd3 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -34,6 +34,8 @@ enum Dead { /// a reference of XCL's own to a superseded target, whose tiles then leave the shared pages /// (`hold_unmap`) Unmap(usize), + /// a reference to a resource XCL owns (`hold_own`) + Own(usize), } struct Batch { @@ -300,6 +302,17 @@ pub fn hold_unmap(res: ID3D12Resource) { start_thread(); } +/// A resource XCL owns that lists in flight may name (the copy buffer of an alias pair whose +/// textures the title released, `alias_copy`) is let go as the title's own resources are: once +/// every queue is past a fence value signalled after this. `XCL_LATE_RELEASE=0`: now. +pub fn hold_own(res: ID3D12Resource) { + if !enabled() { + return drop(res); + } + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Own(res.into_raw() as usize)); + start_thread(); +} + /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { @@ -337,6 +350,10 @@ pub unsafe fn drain_known(seal_now: bool) { drop(ID3D12Heap::from_raw(h as *mut c_void)); continue; } + Dead::Own(r) => { + drop(ID3D12Resource::from_raw(r as *mut c_void)); + continue; + } Dead::Unmap(r) => { // (then the reference goes: the title's last one may have gone meanwhile) let r = ID3D12Resource::from_raw(r as *mut c_void); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 638b133d13..d2e0f35215 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -6453,6 +6453,9 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if uav_transition && !any_uav { out.push([2, 0, 0, 0, 0, 0, 0, 0]); } + // (a sampled texture in the memory of a written one of another format: copied from it after + // these, where they take the written one out of a written state) + let alias_jobs = if super::alias_copy::on() { super::alias_copy::plan(&out) } else { Vec::new() }; // depth buffers whose depth plane can have a twin: in PARK where the title has them in // UNORDERED_ACCESS, the twin copied around the transitions (`depth_uav`) let plane_copies = super::depth_uav::any_kept().then(|| { @@ -6492,6 +6495,32 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 plane_copies_on(this, &p.to_twin, true); stencil_copies_on(this, &p.stencil_to_twin, true); } + super::alias_copy::record(this, &alias_jobs); +} + +/// The texels of the texture `from` into the texture `to` through `buffer`, on the PC list past +/// the hooks of a title's calls (`alias_copy::record`): the barriers `before`, each level and +/// layer of `from` into the buffer by the first footprint of its `parts`, the barrier `between`, +/// each out of the buffer into `to` by the second, the barriers `after`. `to` is noted as written +/// by the GPU on this list. +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn texture_through_buffer( + list: *mut c_void, from: usize, to: usize, buffer: usize, parts: &[(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)], before: &[[u32; 8]], between: &[u32; 8], after: &[[u32; 8]], +) { + let barriers = |b: &[[u32; 8]]| pc::(list, PC_RESOURCE_BARRIER)(list, b.len() as u32, b.as_ptr()); + let copy = pc::(list, PC_COPY_TEXTURE_REGION); + let part = |res: usize, k: usize| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + let rows = |f: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&buffer), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *f } }; + barriers(before); + for (k, (written, _)) in parts.iter().enumerate() { + copy(list, &rows(written), 0, 0, 0, &part(from, k), std::ptr::null()); + } + barriers(std::slice::from_ref(between)); + for (k, (_, read)) in parts.iter().enumerate() { + copy(list, &part(to, k), 0, 0, 0, &rows(read), std::ptr::null()); + } + barriers(after); + note_texture_write(list as usize, to, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); } /// The copies between stencil planes and their twins around a title's barriers diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 943bfec115..772cffe9cd 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -9,6 +9,7 @@ #![allow(non_snake_case)] +mod alias_copy; mod alloc_pool; pub use alloc_pool::AllocatorSubmitStats; mod barrier_groups; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..4748715f9a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2545,6 +2545,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::small_tex::gone(this as usize); } super::depth_uav::forget(this as usize); + super::alias_copy::forget(this as usize); super::barrier_groups::forget(this as usize); let final_state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..9c33a732c9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -935,12 +935,15 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & return; } let mut newly_written = Vec::new(); + // (what an alias copy went into is written by the GPU, and is not read back into the title's + // memory: asked before `TEXTURES` is held) + let copied_into: Vec = if super::alias_copy::on() { writes.iter().map(|w| super::alias_copy::is_copy_destination(w.res)).collect() } else { Vec::new() }; { let mut t = TEXTURES.lock().unwrap(); // (the stamp is for the queue's page mappings: with them off, a publish takes no call count) let call = crate::hle::kernelx::mirrors::page_mappings().then(crate::hle::kernelx::mirrors::calls); if let Some(queue) = queue { - for &write in writes { + for (k, &write) in writes.iter().enumerate() { let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; let n = subresource_count(&e.tex); if write.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !(n <= 1 && write.subresource == 0) && write.subresource as usize >= n { @@ -948,7 +951,10 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & } let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; let writer = GpuWriter { epoch, queue }; - apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + // (no writer: `prepare_downloads` finds nothing of it to read back) + if !copied_into.get(k).copied().unwrap_or(false) { + apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + } if let Some(call) = call { // (`Entry::written_call`: a mapping changed by a later call is newer than this write) e.written_call = call;