diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index e6e91e4..1008d76 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -201,9 +201,10 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 r } -/// Several uploads on one list, one wait: (resource, subresources, before, after) each. A -/// failure of one is returned with its index; the others still run. -pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)]) -> Result, String> { +/// Several uploads on one list, one wait: (resource, subresources, states) each – the states +/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 +/// order). A failure of one is returned with its index; the others still run. +pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { if items.is_empty() { return Ok(Vec::new()); } @@ -211,8 +212,8 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; let mut staging = Vec::with_capacity(items.len()); let mut failed = Vec::new(); - for (k, (res, subs, before, after)) in items.iter().enumerate() { - match record_upload(dev, &list, res, subs, *before, *after) { + for (k, (res, subs, states)) in items.iter().enumerate() { + match record_upload_states(dev, &list, res, subs, states, states) { Ok(s) => staging.push(s), Err(e) => failed.push((k, e)), } @@ -227,10 +228,29 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items /// Record the copy of `subs` into `res` on `list` (barriers from `before` and back to `after`); /// the staging buffer returned must live until the list has run. pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> Result { + record_upload_states(dev, list, res, subs, &[before], &[after]) +} + +/// `record_upload` with the states per subresource: `before` / `after` hold one state for every +/// subresource or one per subresource (D3D12 order; a title can leave its mips in different +/// states). +pub unsafe fn record_upload_states( + dev: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + res: &ID3D12Resource, + subs: &[Subresource], + before: &[D3D12_RESOURCE_STATES], + after: &[D3D12_RESOURCE_STATES], +) -> Result { validate_subresources(subs)?; let rd = res.GetDesc(); let n = subs.len(); validate_subresource_count(&rd, n)?; + for s in [before, after] { + if s.len() != 1 && s.len() != n { + return Err(format!("{} subresource states for {n} subresources", s.len())); + } + } let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; let mut rows = vec![0u32; n]; let mut row_bytes = vec![0u64; n]; @@ -260,8 +280,9 @@ pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList } } up.Unmap(0, None); - if before != D3D12_RESOURCE_STATE_COPY_DEST { - list.ResourceBarrier(&[transition(res, before, D3D12_RESOURCE_STATE_COPY_DEST)]); + let to_copy = transitions(res, before, &[D3D12_RESOURCE_STATE_COPY_DEST], n); + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); } for (k, fp) in fps.iter().enumerate() { let dst = D3D12_TEXTURE_COPY_LOCATION { @@ -272,12 +293,24 @@ pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); } - if after != D3D12_RESOURCE_STATE_COPY_DEST { - list.ResourceBarrier(&[transition(res, D3D12_RESOURCE_STATE_COPY_DEST, after)]); + let back = transitions(res, &[D3D12_RESOURCE_STATE_COPY_DEST], after, n); + if !back.is_empty() { + list.ResourceBarrier(&back); } Ok(up) } +/// The transitions of `r`'s `n` subresources from `from` to `to` (each one state for all, or one +/// per subresource): one for all subresources when both are uniform, else one per subresource +/// that changes. +fn transitions(r: &ID3D12Resource, from: &[D3D12_RESOURCE_STATES], to: &[D3D12_RESOURCE_STATES], n: usize) -> Vec { + if from.len() == 1 && to.len() == 1 { + return if from[0] == to[0] { Vec::new() } else { vec![transition(r, from[0], to[0])] }; + } + let at = |s: &[D3D12_RESOURCE_STATES], k: usize| if s.len() == 1 { s[0] } else { s[k] }; + (0..n).filter(|&k| at(from, k) != at(to, k)).map(|k| transition_sub(r, k as u32, at(from, k), at(to, k))).collect() +} + /// Wait until `queue` has run everything submitted so far. pub unsafe fn wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result<(), String> { let copy_error = |e| format!("texture copy: {e}"); @@ -305,13 +338,17 @@ unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result D3D12_RESOURCE_BARRIER { + transition_sub(r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after) +} + +fn transition_sub(r: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: unsafe { std::mem::transmute_copy(r) }, - Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + Subresource: sub, StateBefore: before, StateAfter: after, }), diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b92d755..b728c5c 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -660,6 +660,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { return Err("the UMA buffer is not open on the GPU".into()); } let _ = u; + // the whole recording is replayed into the PC list here: its transitions of textures kept + // in step are these + super::title_textures::list_reset(st.pc); let windows = super::real::uma_window_vas(); let va = |p: usize| super::real::uma_va_of(p).unwrap_or(uma_va); let mut out = Translation::default(); @@ -700,6 +703,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // borrowed (ManuallyDrop fields, nothing released) let mut b: Vec = vec![0; 4 * n]; std::ptr::copy_nonoverlapping(words.as_ptr() as *const u8, b.as_mut_ptr() as *mut u8, 32 * n); + if super::title_textures::any() { + // each barrier: type | flags, resource, subresource | before, after + let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = + b.chunks_exact(4).filter(|c| c[0] as u32 == 0).map(|c| (c[1] as usize, c[2] as u32, D3D12_RESOURCE_STATES(c[3] as u32 as i32))).collect(); + super::title_textures::note_transitions(st.pc, &t); + } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, n)); } out.barriers += n as u32; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 5fb7404..6c7c829 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -642,6 +642,7 @@ pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: } m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); } + super::title_textures::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -657,6 +658,7 @@ pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { + super::title_textures::list_reset(list); if let Some(old) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)) { if !old.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); @@ -1261,6 +1263,9 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); let one = [this]; exec(q_raw, 1, one.as_ptr()); + // what ran is in the textures' states; the list records anew after its Reset below + super::title_textures::submitted(&one); + super::title_textures::list_reset(this as usize); if !sparse_writes.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { super::sparse::readback_after_execute(q, &sparse_writes); @@ -1656,6 +1661,7 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; + super::title_textures::list_reset(this as usize); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { @@ -1748,6 +1754,12 @@ 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]); } + // the states uploads into textures kept in step start from once this list has run + if super::title_textures::any() { + let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = + out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); + super::title_textures::note_transitions(this as usize, &t); + } if !out.is_empty() { pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9548e8c..5b6dc96 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3783,6 +3783,8 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis f(this, chunk.len() as u32, chunk.as_ptr()); super::list_x::readback_sparse_writes(this, chunk); }); + // the next uploads into textures kept in step start from the states these lists leave + super::title_textures::submitted(&mapped); super::present::note_execute(this, &mapped); stop_if_device_removed(); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d1632a..f757637 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -14,6 +14,11 @@ //! The copy waits for the GPU on an XCL queue of the device. Memory that is not readable //! (reserved, not mapped yet) reads as zero. GPU writes into the title's memory (copies to the //! address) are not seen; the title's own GPU work on the texture goes to the PC texture. +//! +//! A copy starts and ends in the state the title's submitted work left the texture in: its +//! transitions of these textures are noted per PC command list as they are recorded +//! (`note_transitions`) and applied, in submission order, when the list is submitted +//! (`submitted`) – per subresource once a transition names one. use std::collections::BTreeMap; use std::ffi::c_void; @@ -33,15 +38,17 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address, layout, state) of an upload -type Upload = (usize, usize, Arc, D3D12_RESOURCE_STATES); +/// (device, address, layout, states) of an upload +type Upload = (usize, usize, Arc, Vec); struct Entry { device: usize, va: usize, tex: Arc, - /// the state the texture was created in (uploads leave it there) - state: D3D12_RESOURCE_STATES, + /// the state the title's submitted work leaves the texture in (uploads leave it there): + /// the creation state, then what its transitions give – one state for every subresource, + /// or one per subresource (D3D12 order) while they differ + states: Vec, /// not uploaded yet (made since the last submit) pending: bool, /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from @@ -83,7 +90,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let e = Entry { device: device as usize, va, tex: Arc::new(tex), state, pending: true, gpu_written: false }; + let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -141,6 +148,89 @@ pub fn address(res: usize) -> Option { TEXTURES.lock().unwrap().get(&res).map(|e| e.va) } +/// (texture, subresource or ALL_SUBRESOURCES, state after) of a transition the title recorded +type Transition = (usize, u32, D3D12_RESOURCE_STATES); + +/// PC command list → the transitions of textures kept in step it recorded since it was made or +/// last reset, in order. They apply when the list is submitted – each time: a closed list may +/// run again. +static LIST_NOTES: Mutex>> = Mutex::new(BTreeMap::new()); + +/// Whether any texture is kept in step (callers skip collecting transitions otherwise). +pub fn any() -> bool { + TEXTURES_LEN.load(Ordering::Relaxed) != 0 +} + +/// The title recorded `transitions` on PC list `list`: those of textures kept in step are noted +/// for when the list is submitted. +pub fn note_transitions(list: usize, transitions: &[Transition]) { + if !any() || transitions.is_empty() { + return; + } + let kept: Vec = { + let t = TEXTURES.lock().unwrap(); + transitions.iter().filter(|(r, _, _)| t.contains_key(r)).copied().collect() + }; + if !kept.is_empty() { + LIST_NOTES.lock().unwrap().entry(list).or_default().extend(kept); + } +} + +/// PC list `list` starts a new recording (made, reset, released): its noted transitions go. +pub fn list_reset(list: usize) { + let mut g = LIST_NOTES.lock().unwrap(); + if !g.is_empty() { + g.remove(&list); + } +} + +/// The PC lists `lists` were submitted, in this order: the textures kept in step are in the +/// states their transitions leave them in. +pub fn submitted(lists: &[*mut c_void]) { + let notes: Vec = { + let g = LIST_NOTES.lock().unwrap(); + if g.is_empty() { + return; + } + lists.iter().filter_map(|&l| g.get(&(l as usize))).flatten().copied().collect() + }; + if notes.is_empty() { + return; + } + let mut t = TEXTURES.lock().unwrap(); + for (res, sub, after) in notes { + if let Some(e) = t.get_mut(&res) { + let n = subresource_count(&e.tex); + apply_transition(&mut e.states, n, sub, after); + } + } +} + +/// Subresources of a texture kept in step (as `subresources` makes them). +fn subresource_count(tex: &xg::Texture) -> usize { + tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) +} + +/// `states` (one for all `n` subresources, or one each) after a transition of subresource `sub` +/// (or all of them) to `after`; a subresource the texture does not have is ignored. +fn apply_transition(states: &mut Vec, n: usize, sub: u32, after: D3D12_RESOURCE_STATES) { + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES || (n <= 1 && sub == 0) { + *states = vec![after]; + return; + } + let k = sub as usize; + if k >= n { + return; + } + if states.len() != n { + *states = vec![states[0]; n]; + } + states[k] = after; + if states.iter().all(|&s| s == after) { + states.truncate(1); + } +} + thread_local! { /// XCL's own submits on this thread (texture uploads): they read no title memory on the GPU, /// so they do not look for CPU writes first – that look is the title's submits' job @@ -295,7 +385,7 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.state))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); @@ -322,14 +412,14 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } - let (r, (dev, va, tex, state)) = todo.next().unwrap(); + let (r, (dev, va, tex, states)) = todo.next().unwrap(); device = dev; bytes += tex.size() as usize; let subs = subresources(va, &tex); if super::present::trace_frame() { note_content(va, &r, &subs); } - batch.push((r, subs, state, state)); + batch.push((r, subs, states)); } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; @@ -541,6 +631,80 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { mod tests { use super::*; + const SRV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); + const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + /// One state while every subresource has it, one each while they differ. + #[test] + fn transitions_per_subresource_and_back_to_one_state() { + let mut s = vec![D3D12_RESOURCE_STATE_COMMON]; + apply_transition(&mut s, 4, ALL, SRV); + assert_eq!(s, vec![SRV]); + apply_transition(&mut s, 4, 2, D3D12_RESOURCE_STATE_COPY_SOURCE); + assert_eq!(s, vec![SRV, SRV, D3D12_RESOURCE_STATE_COPY_SOURCE, SRV]); + apply_transition(&mut s, 4, 9, D3D12_RESOURCE_STATE_COPY_DEST); // no subresource 9 + assert_eq!(s, vec![SRV, SRV, D3D12_RESOURCE_STATE_COPY_SOURCE, SRV]); + apply_transition(&mut s, 4, 2, SRV); + assert_eq!(s, vec![SRV]); + apply_transition(&mut s, 4, 1, D3D12_RESOURCE_STATE_COPY_DEST); + apply_transition(&mut s, 4, ALL, D3D12_RESOURCE_STATE_COMMON); + assert_eq!(s, vec![D3D12_RESOURCE_STATE_COMMON]); + // a texture of one subresource: subresource 0 is all of it + let mut one = vec![SRV]; + apply_transition(&mut one, 1, 0, D3D12_RESOURCE_STATE_COPY_SOURCE); + assert_eq!(one, vec![D3D12_RESOURCE_STATE_COPY_SOURCE]); + } + + /// A texture kept in step: the title's transitions count once their list is submitted, in + /// submission order, each time it is; a Reset forgets them; other resources are not noted. + #[test] + fn transitions_apply_when_their_list_is_submitted() { + // RGBA8 64×64, 3 mips, 2 slices (6 subresources), 4KB_S + let mut d = [0u8; 0x38]; + d[0..4].copy_from_slice(&3u32.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + d[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + d[0x1C..0x1E].copy_from_slice(&2u16.to_le_bytes()); + d[0x1E..0x20].copy_from_slice(&3u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); + let tex = Arc::new(xg::Texture::new(&d).unwrap()); + assert_eq!(subresource_count(&tex), 6); + // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it + let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); + let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); + + note_transitions(l1, &[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + assert_eq!(LIST_NOTES.lock().unwrap().get(&l1).map(|v| v.len()), Some(2), "only the texture kept in step is noted"); + assert_eq!(states(), vec![D3D12_RESOURCE_STATE_COMMON], "recorded, not run yet"); + note_transitions(l2, &[(res, 4, SRV), (res, 0, D3D12_RESOURCE_STATE_COPY_DEST)]); + submitted(&[p1]); + let mut want = vec![SRV; 6]; + want[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; + assert_eq!(states(), want); + submitted(&[p2]); + want[4] = SRV; + want[0] = D3D12_RESOURCE_STATE_COPY_DEST; + assert_eq!(states(), want); + // l1 runs again (a closed list may): its transitions again, after l2's + submitted(&[p2, p1]); + assert_eq!(states(), { + let mut w = vec![SRV; 6]; + w[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; + w + }); + list_reset(l1); + list_reset(l2); + submitted(&[p1, p2]); + assert_eq!(states()[4], D3D12_RESOURCE_STATE_COPY_SOURCE, "a reset list has nothing to apply"); + forget(res); + assert!(LIST_NOTES.lock().unwrap().get(&l1).is_none()); + } + /// Only the wanted parts of the watched regions are scanned, merged, one region each. #[test] fn watch_ranges_clip_and_merge() { diff --git a/crates/xcl/tests/texture_states.rs b/crates/xcl/tests/texture_states.rs new file mode 100644 index 0000000..28d4e9b --- /dev/null +++ b/crates/xcl/tests/texture_states.rs @@ -0,0 +1,112 @@ +//! Uploads into a texture whose subresources are in different states (#104): the barriers +//! `gpu::texture::upload_batch` records start from each subresource's own state and return to +//! it, checked by the D3D12 debug layer's state tracking. Its own process: the debug layer has +//! to be on before the first device exists. + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + +use xcl::gpu::texture::{self, Subresource}; + +const SRV: D3D12_RESOURCE_STATES = texture::SHADER_READ; + +/// The debug layer's error and corruption messages since the last call (then cleared). +unsafe fn errors(q: &ID3D12InfoQueue) -> Vec { + let mut out = Vec::new(); + for i in 0..q.GetNumStoredMessages() { + let mut len = 0usize; + if q.GetMessage(i, None, &mut len).is_err() || len == 0 { + continue; + } + let mut buf = vec![0u64; len.div_ceil(8)]; + let m = buf.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() && matches!((*m).Severity, D3D12_MESSAGE_SEVERITY_ERROR | D3D12_MESSAGE_SEVERITY_CORRUPTION) { + let d = std::slice::from_raw_parts((*m).pDescription as *const u8, (*m).DescriptionByteLength.saturating_sub(1)); + out.push(String::from_utf8_lossy(d).into_owned()); + } + } + q.ClearStoredMessages(); + out +} + +unsafe fn transition(r: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: sub, StateBefore: before, StateAfter: after }), + }, + } +} + +/// A texture in shader-resource states with mip 1 moved to COPY_SOURCE (as a title moves one +/// mip to copy from it), then uploaded again: with each subresource's state no error; with the +/// creation state for all of them (what uploads used before), the debug layer sees the +/// mismatch – so the check is a real one. +#[test] +fn uploads_start_from_each_subresources_state() { + unsafe { + match xcl::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + println!("SKIPPED uploads_start_from_each_subresources_state: no D3D12 debug layer ({e})"); + return; + } + } + let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + println!("SKIPPED uploads_start_from_each_subresources_state: no GPU"); + return; + }; + let Ok(q) = dev.cast::() else { + println!("SKIPPED uploads_start_from_each_subresources_state: the device has no debug layer"); + return; + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let mips = 4u16; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: mips, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r).unwrap(); + let r = r.unwrap(); + let subs = |v: u8| -> Vec { (0..mips as usize).map(|m| Subresource { rows: 64 >> m, row_bytes: (64 >> m) * 4, depth: 1, data: vec![v; (64 >> m) * (64 >> m) * 4] }).collect() }; + + // made in COPY_DEST, left in the shader-resource states + let up = |states: Vec, v: u8| texture::upload_batch(&dev, &queue, &[(r.clone(), subs(v), states)]).unwrap(); + assert!(up(vec![D3D12_RESOURCE_STATE_COPY_DEST], 1).is_empty()); + 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(); + list.ResourceBarrier(&[transition(&r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, SRV)]); + list.ResourceBarrier(&[transition(&r, 1, SRV, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&dev, &queue).unwrap(); + let setup = errors(&q); + assert!(setup.is_empty(), "setup: {setup:?}"); + + // each subresource's state: no error, and it is left in it + let mut states = vec![SRV; mips as usize]; + states[1] = D3D12_RESOURCE_STATE_COPY_SOURCE; + assert!(up(states.clone(), 2).is_empty()); + let right = errors(&q); + println!("per-subresource states: {} debug-layer errors", right.len()); + assert!(right.is_empty(), "uploads with each subresource's state: {right:?}"); + assert!(up(states, 3).is_empty()); + assert!(errors(&q).is_empty(), "the upload did not leave the subresources in their states"); + + // one state for all of them, as uploads did before: mip 1 is not in it + assert!(up(vec![SRV], 4).is_empty()); + let wrong = errors(&q); + println!("one state for all: {} debug-layer errors, first: {:?}", wrong.len(), wrong.first()); + assert!(!wrong.is_empty(), "the debug layer did not see a transition from the wrong state – the check above proves nothing"); + } +}