diff --git a/HANDOFF.md b/HANDOFF.md index 0e37eee..e65f243 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1088,6 +1088,24 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 resources (the list failed to Close with E_INVALIDARG); console state bits the PC does not know are dropped. - **Result**: the title runs – in one minute 957 presents, 3 443 pipelines from translated console shaders, 966 of 966 programs translated, no failed pipeline, no crash. Whether the picture is right is not checked yet. +- **Graphics root arguments** (`bind`, measured with the console compiler – `print_graphics_root_argument_placement` + / `_capacity`): a VS / PS gets root arguments in user SGPRs **s8…s31** (s0…s7 the driver's, s[4:5] of a VS the + fetch shader), 24 SGPRs, the rest in the table at s[0:1] (`Layout::inline_gfx`, `user_data_gfx`). Set*Graphics* + (#34–#46) are kept like the compute ones; DrawInstanced / DrawIndexedInstanced (#12 / #13) with a translated pipeline + bind the ABI root signature and io first (a pipeline still building is waited for). +- **Resources in title memory**: Map of a resource in unified memory returns its console address (also for textures + the PC cannot map); a buffer at an address that is not 64 KiB-aligned is placed from the 64 KiB below it and XCL adds + the difference in CopyBufferRegion / CopyTextureRegion / CopyResource (`buffer_delta`); graphics reservations come + from unified memory when it has room (`Uma::reserve`, not zeroed). +- **Why XDefiant's picture is black (open)**: its main pool is one **8 GB reservation** (VirtualAlloc flags + 0x20402000 = MEM_RESERVE | 0x400000 | MEM_LARGE_PAGES, no MEM_GRAPHICS – `XCL_TRACE_MEM=1`), committed in 64 KiB + steps, and it places D3D12 resources in it: on the console all of it is GPU-visible. XCL's unified memory is at most + 4 windows of 4095 MiB, each fully committed (D3D12's rule for OpenExistingHeapFromAddress), and translated shaders + reach memory only through those windows – the pool does not fit (and 12+ GB committed is near this PC's commit + limit). Options: a much larger UMA (commit cost), or a GPU page table in translated shaders (title memory stays where + it is, per-chunk heaps) – the general one, larger work. Until then Map of such a buffer fails and the title stops. +- Diagnostics: `XCL_FRAME_DUMP=1` writes every 120th presented frame (a quarter of each side) as `frame_.bmp` in + the logs folder; `XCL_TRACE_MEM=1` logs allocations ≥ 64 KiB outside unified memory. - **Safety nets** (after a GPU hang that needed a PC restart – it came from a diagnostic run that skipped barriers): every loop of a translated shader has a per-lane budget (`LOOP_GUARD`, 4 M iterations); when the D3D12 device is removed (after ExecuteCommandLists, at PresentX) the title is stopped with the reason in the log and the report. diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 8323db6..688fb06 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -113,16 +113,22 @@ impl Uma { /// Zeroed block of `size` bytes aligned to `align` (at least 64 KiB), first fit (window 0 /// first). pub fn alloc(&self, size: usize, align: usize) -> Option<*mut u8> { - self.alloc_where(size, align, None) + self.alloc_where(size, align, None, true) + } + + /// `alloc` for reserved address space: not zeroed (a large reservation is not touched – + /// what the title commits or maps there it writes; never-used memory is zero anyway). + pub fn reserve(&self, size: usize, align: usize) -> Option<*mut u8> { + self.alloc_where(size, align, None, false) } /// `alloc` inside window `k` (memory the console addresses with 32 bits, e.g. descriptor /// heaps: window 0). pub fn alloc_in(&self, k: usize, size: usize, align: usize) -> Option<*mut u8> { - self.alloc_where(size, align, Some(k)) + self.alloc_where(size, align, Some(k), true) } - fn alloc_where(&self, size: usize, align: usize, window: Option) -> Option<*mut u8> { + fn alloc_where(&self, size: usize, align: usize, window: Option, zero: bool) -> Option<*mut u8> { let size = (size.max(1) + GRAIN - 1) & !(GRAIN - 1); let align = align.max(GRAIN).next_power_of_two(); let mut g = self.inner.lock().unwrap(); @@ -140,7 +146,9 @@ impl Uma { g.used.insert(at, size); drop(g); let p = (self.base + at) as *mut u8; - unsafe { std::ptr::write_bytes(p, 0, size) }; + if zero { + unsafe { std::ptr::write_bytes(p, 0, size) }; + } Some(p) } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d1bfa41..2031236 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -10,6 +10,7 @@ use std::collections::HashMap; use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -21,6 +22,9 @@ use super::console_list::{self, Layout, Param}; struct State { layout: Option>, args: Vec, + /// the graphics root signature's layout and arguments + layout_gfx: Option>, + args_gfx: Vec, pso: usize, allocator: usize, /// unified memory of this recording (io, argument tables) @@ -29,6 +33,25 @@ struct State { static STATES: Mutex>> = Mutex::new(None); +/// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one +static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +const DRAWS: usize = 0; +const DRAWS_SKIPPED: usize = 1; +const DRAWS_PC: usize = 2; +const DISPATCHES: usize = 3; +const DISPATCHES_SKIPPED: usize = 4; + +fn count(k: usize) { + let n = COUNTS[k].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + let c: Vec = COUNTS.iter().map(|c| c.load(Ordering::Relaxed)).collect(); + crate::xlog_info!( + "D3D12.X: console code so far: {} draws with translated pipelines ({} skipped, {} with PC pipelines), {} dispatches ({} skipped)", + c[DRAWS], c[DRAWS_SKIPPED], c[DRAWS_PC], c[DISPATCHES], c[DISPATCHES_SKIPPED] + ); + } +} + fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } @@ -50,21 +73,100 @@ pub(super) fn forget(list: *mut c_void) { } } -/// bytes of parameter `i` at constant `offset` -fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { +/// bytes of parameter `i` at constant `offset` (of the compute or the graphics arguments) +fn put_in(list: *mut c_void, gfx: bool, i: u32, offset: u32, bytes: &[u8]) { with(list, |s| { - let Some(at) = s.layout.as_ref().and_then(|l| l.params.get(i as usize)).map(|p| match *p { + let (layout, args) = if gfx { (&s.layout_gfx, &mut s.args_gfx) } else { (&s.layout, &mut s.args) }; + let Some(at) = layout.as_ref().and_then(|l| l.params.get(i as usize)).map(|p| match *p { Param::Constants { at, .. } => at as usize + 4 * offset as usize, Param::Descriptor { at } | Param::Table { at } => at as usize, }) else { return; }; - if let Some(t) = s.args.get_mut(at..at + bytes.len()) { + if let Some(t) = args.get_mut(at..at + bytes.len()) { t.copy_from_slice(bytes); } }) } +fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { + put_in(list, false, i, offset, bytes) +} + +/// #34 SetGraphicsRootSignature (PC #30) +pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { + let layout = console_list::layout_of(rs as usize); + with(this, |s| { + s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + s.layout_gfx = layout; + }); +} + +/// #36 SetGraphicsRootDescriptorTable (PC #32) +pub(super) unsafe extern "system" fn set_graphics_root_table(this: *mut c_void, i: u32, handle: u64) { + put_in(this, true, i, 0, &(handle as u32).to_le_bytes()); +} + +/// #38 SetGraphicsRoot32BitConstant (PC #34) +pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + put_in(this, true, i, offset, &value.to_le_bytes()); +} + +/// #40 SetGraphicsRoot32BitConstants (PC #36) +pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + if !data.is_null() { + let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + put_in(this, true, i, offset, &bytes); + } +} + +/// #42 / #44 / #46 SetGraphicsRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #38 / +/// #40 / #42) +pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { + put_in(this, true, i, 0, &va.to_le_bytes()); +} + +/// #12 DrawInstanced +pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + if let Some(list) = graphics_bound(this) { + list.DrawInstanced(vertices, instances, first_vertex, first_instance); + } +} + +/// #13 DrawIndexedInstanced +pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + if let Some(list) = graphics_bound(this) { + list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); + } +} + +/// Before a draw: with a translated pipeline its ABI root signature and the kept graphics +/// arguments are bound (None: the draw is skipped – a console pipeline without a +/// translation, or no unified memory). +unsafe fn graphics_bound(this: *mut c_void) -> Option { + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); + let pso = with(this, |s| s.pso); + // a pipeline still being built in the background is waited for (its stand-in draws nothing) + if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + count(DRAWS_PC); + return Some(list); // a PC pipeline: its own root signature and arguments + } + match bind_abi(this, &list, pso, true) { + Ok(()) => { + count(DRAWS); + Some(list) + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: draw with a translated pipeline skipped: {e}"); + } + None + } + } +} + /// #33 SetComputeRootSignature (PC #29) pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { let layout = console_list::layout_of(rs as usize); @@ -115,8 +217,10 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); } + count(DISPATCHES_SKIPPED); return; } + count(DISPATCHES); if let Err(e) = translated_dispatch(this, list, pso, x, y, z) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { @@ -126,10 +230,19 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, } unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { + bind_abi(this, list, pso, false)?; + list.Dispatch(x, y, z); + Ok(()) +} + +/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept +/// arguments the console's way – compute or graphics) and the argument table in unified +/// memory, u1 res, u2… the memory windows; then the pipeline. +unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); let mut owned = Vec::new(); let mut copy = |bytes: &[u8]| -> Result { let p = u.alloc_in(0, bytes.len().max(16), 256).ok_or("unified memory is full")?; // 32-bit console addresses: window 0 @@ -137,9 +250,10 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis owned.push(p as usize); Ok(p as usize) }; - let inline = layout.as_ref().map_or(0, |l| l.inline as usize).min(args.len()); + let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { l.inline } as usize).min(args.len()); let table_at = copy(&args[inline..])?; let mut io = match layout.as_ref() { + Some(l) if gfx => console_list::user_data_gfx(l, &args, table_at as u64), Some(l) => console_list::user_data(l, &args, table_at as u64), None => vec![table_at as u32, (table_at >> 32) as u32], }; @@ -153,15 +267,20 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - list.SetComputeRootSignature(rs); - list.SetComputeRootUnorderedAccessView(0, va(io_at)); - list.SetComputeRootUnorderedAccessView(1, va(res_at)); - for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(first)); + let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + if gfx { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + } else { + list.SetComputeRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } } let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; list.SetPipelineState(pc); - list.Dispatch(x, y, z); Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index c412d18..0a2cc52 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -66,16 +66,23 @@ pub enum Param { } /// Where a root signature's arguments go: all of them packed in order (`at`, `size` bytes); -/// the first `inline` bytes of that are passed in user SGPRs from s4, the rest is the table. +/// the first `inline` bytes of that are passed in user SGPRs (compute from s4, graphics +/// stages from s8: `inline_gfx` bytes), the rest is the table. #[derive(Debug, Default)] pub struct Layout { pub params: Vec, pub size: u32, pub inline: u32, + pub inline_gfx: u32, } -/// User SGPRs the console's compiler gives root arguments: s4…s15 (s0…s3 are the driver's). +/// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the +/// driver's), graphics stages (VS, PS) s8…s31 (s0…s7: the driver's, s[4:5] of a VS the +/// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; +const INLINE_SGPRS_GFX: u32 = 24; +const FIRST_SGPR: usize = 4; +const FIRST_SGPR_GFX: usize = 8; /// Layout from a serialized root signature: a DXBC container with RTS0 or a bare RTS0. pub fn layout_from_blob(blob: &[u8]) -> Option { @@ -92,7 +99,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's // compiler expects them (HANDOFF: root argument binding) - let mut spilled = false; + let (mut spilled, mut spilled_gfx) = (false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -109,6 +116,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled { l.inline += bytes; } + spilled_gfx |= l.inline_gfx + bytes > 4 * INLINE_SGPRS_GFX; + if !spilled_gfx { + l.inline_gfx += bytes; + } l.size += bytes; l.params.push(p); } @@ -118,8 +129,19 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { /// The user SGPRs of a dispatch: s[0:1] = `table_at` (where the bytes of `args` past the /// inline part are), from s4 the inline part of `args` (all arguments packed by `l`). pub fn user_data(l: &Layout, args: &[u8], table_at: u64) -> Vec { - let mut s = vec![table_at as u32, (table_at >> 32) as u32, 0, 0]; - let inline = &args[..(l.inline as usize).min(args.len())]; + sgprs(FIRST_SGPR, l.inline, args, table_at) +} + +/// `user_data` of a draw: the vertex and pixel shader's user SGPRs (inline from s8). +pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { + sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) +} + +fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; first]; + s[0] = table_at as u32; + s[1] = (table_at >> 32) as u32; + let inline = &args[..(inline as usize).min(args.len())]; s.extend(inline.chunks(4).map(|c| { let mut w = [0u8; 4]; w[..c.len()].copy_from_slice(c); @@ -859,4 +881,17 @@ mod tests { let args: Vec = [7u32, 0x1000, 4].iter().flat_map(|w| w.to_le_bytes()).chain([0u8; 44]).collect(); assert_eq!(user_data(&l, &args, 0x4_0000_0100), vec![0x100, 4, 0, 0, 7, 0x1000, 4]); } + + /// The same for a vertex / pixel shader: from s8, 24 SGPRs (the console compiler's output). + #[test] + fn graphics_arguments_go_in_user_sgprs_from_s8() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_gfx; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 22), (2, 0)]), 96); + assert_eq!(inline(&[(1, 23), (2, 0)]), 92, "the CBV goes to the table"); + assert_eq!(inline(&[(1, 25), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 58653fb..6565db9 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -308,9 +308,9 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 /// command list #84 CopyResourceX(destination, source, flags); in place (the console's /// compression operations) there is nothing to do on PC -pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { +pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { if dst != src { - pc::(this, PC_COPY_RESOURCE)(this, dst, src); + copy_resource_x(this, dst, src); } } @@ -486,23 +486,6 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } -/// A D3D12_TEXTURE_COPY_LOCATION for the log. -unsafe fn location(l: *const D3D12_TEXTURE_COPY_LOCATION) -> String { - if l.is_null() { - return "null".into(); - } - let l = &*l; - let res = transmute_copy::<_, usize>(&l.pResource); - if l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT { - let p = l.Anonymous.PlacedFootprint; - let f = p.Footprint; - format!("buffer {res:#x} +{:#x} format {} {}x{}x{} pitch {}", p.Offset, f.Format.0, f.Width, f.Height, f.Depth, f.RowPitch) - } else { - let d = ID3D12Resource::from_raw_borrowed(&(res as *mut c_void)).map(|r| r.GetDesc()); - format!("texture {res:#x} subresource {} ({:?})", l.Anonymous.SubresourceIndex, d.map(|d| (d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0))) - } -} - /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { let hr = pc:: i32>(this, 9)(this); @@ -513,13 +496,36 @@ pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { hr } -/// DMA list #12 CopyTextureRegion(dst, x, y, z, src, box) (PC #16) -pub(super) unsafe extern "system" fn dma_copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { - static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 8 { - crate::xlog_info!("D3D12.X: DMA CopyTextureRegion to {} at ({x}, {y}, {z}) from {}{}", location(dst), location(src), if bx.is_null() { String::new() } else { format!(" box {:?}", { let b = *bx; (b.left, b.top, b.front, b.right, b.bottom, b.back) }) }); +/// a copy location with the offset of a buffer placed below its console address added +unsafe fn pc_location(l: *const D3D12_TEXTURE_COPY_LOCATION) -> Option { + let mut l = std::ptr::read(l.as_ref()?); + if l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT { + l.Anonymous.PlacedFootprint.Offset += real::buffer_delta(transmute_copy::<_, usize>(&l.pResource)); } - pc::(this, PC_COPY_TEXTURE_REGION)(this, dst, x, y, z, src, bx) + Some(l) +} + +/// CopyBufferRegion(dst, dst offset, src, src offset, bytes) (PC #15; DMA list #11) +pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + pc::(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) +} + +/// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) +pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { + let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; + pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + std::mem::forget((d, s)); // borrowed resource pointers +} + +/// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address +/// are copied as their own bytes (the PC resources also hold what lies before them) +pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { + let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); + if dd == 0 && sd == 0 { + return pc::(this, PC_COPY_RESOURCE)(this, dst, src); + } + let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); + copy_buffer_region_x(this, dst, 0, src, 0, n); } /// command list #28 BeginQuery(heap, type, index) (PC #52) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d993e6f..ee98ea8 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -408,6 +408,7 @@ unsafe fn present_now(min_interval: Duration) { let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; p.list.ResourceBarrier(&b1); p.list.CopyResource(&bb, src); + let dump = frame_dump_due().then(|| readback_copy(&p.list, src, &desc)).flatten(); let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; p.list.ResourceBarrier(&b2); if p.list.Close().is_err() { @@ -421,12 +422,121 @@ unsafe fn present_now(min_interval: Duration) { let _ = q.Signal(&p.fence, p.value); let _ = sc.Present(0, DXGI_PRESENT(0)); p.last = Instant::now(); + if let Some((rb, fp)) = dump { + if p.fence.GetCompletedValue() < p.value { + let _ = p.fence.SetEventOnCompletion(p.value, p.event); + WaitForSingleObject(p.event, 2000); + } + write_frame(&rb, &fp, desc.Format); + } let n = PRESENTS.fetch_add(1, Ordering::Relaxed); if n == 0 { crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); } } +/// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder +/// (`frame_.bmp`, a quarter of each side) – what the title presented, before the window. +fn frame_dump_due() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_FRAME_DUMP").is_some()) && PRESENTS.load(Ordering::Relaxed) % 120 == 60 +} + +/// a copy of subresource 0 of `src` into a new readback buffer, recorded on `list` +unsafe fn readback_copy(list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + let dev: ID3D12Device = { + let mut d: Option = None; + src.GetDevice(&mut d).ok()?; + d? + }; + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(desc, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .ok()?; + let rb = rb?; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let s = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &s, None); + Some((rb, fp)) +} + +/// texel → 8-bit RGB for the formats titles present in (None: not decoded) +fn rgb(format: DXGI_FORMAT, t: u32) -> Option<[u8; 3]> { + Some(match format { + DXGI_FORMAT_R10G10B10A2_UNORM => [(t >> 2 & 0xFF) as u8, (t >> 12 & 0xFF) as u8, (t >> 22 & 0xFF) as u8], + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => [t as u8, (t >> 8) as u8, (t >> 16) as u8], + DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => [(t >> 16) as u8, (t >> 8) as u8, t as u8], + _ => return None, + }) +} + +unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT) { + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let (w, h, pitch) = (fp.Footprint.Width as usize, fp.Footprint.Height as usize, fp.Footprint.RowPitch as usize); + let (ow, oh) = ((w / 4).max(1), (h / 4).max(1)); + let row = (ow * 3).div_ceil(4) * 4; + let mut bmp = Vec::with_capacity(54 + row * oh); + let size = (54 + row * oh) as u32; + bmp.extend_from_slice(b"BM"); + for v in [size, 0, 54, 40, ow as u32, oh as u32] { + bmp.extend_from_slice(&v.to_le_bytes()); + } + bmp.extend_from_slice(&1u16.to_le_bytes()); + bmp.extend_from_slice(&24u16.to_le_bytes()); + for _ in 0..6 { + bmp.extend_from_slice(&0u32.to_le_bytes()); + } + let (mut lit, mut decoded) = (0usize, true); + for y in (0..oh).rev() { + let start = bmp.len(); + for x in 0..ow { + let t = ((p as *const u8).add(fp.Offset as usize + 4 * y * pitch + 16 * x) as *const u32).read_unaligned(); + let c = rgb(format, t).unwrap_or_else(|| { + decoded = false; + [0; 3] + }); + if c.iter().map(|&v| v as u32).sum::() > 30 { + lit += 1; + } + bmp.extend_from_slice(&[c[2], c[1], c[0]]); + } + bmp.resize(start + row, 0); + } + rb.Unmap(0, None); + let n = PRESENTS.load(Ordering::Relaxed); + let Some(boot) = crate::state::boot() else { return }; + let path = boot.logs_dir().join(format!("frame_{n}.bmp")); + let _ = std::fs::write(&path, &bmp); + crate::xlog_info!( + "present: frame {n} ({w}x{h}, format {}) written to {} – {lit} of {} samples not black{}", + format.0, + path.display(), + ow * oh, + if decoded { "" } else { " (format not decoded)" } + ); +} + impl Drop for Presenter { fn drop(&mut self) { unsafe { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index eb1071c..96efdfb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -674,13 +674,28 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { Kind::DescriptorHeap => vec![(9, heap_cpu_start_x as usize), (10, heap_gpu_start_x as usize)], Kind::Resource => vec![(11, res_gpu_va_x as usize)], Kind::CommandQueue => vec![(30, super::present::present_x as usize)], - Kind::DmaList => vec![(9, super::list_x::dma_close_x as usize), (10, super::list_x::reset_x as usize), (12, super::list_x::dma_copy_texture_region_x as usize)], + Kind::DmaList => { + use super::list_x as l; + vec![(9, l::dma_close_x as usize), (10, l::reset_x as usize), (11, l::copy_buffer_region_x as usize), (12, l::copy_texture_region_x as usize), (13, l::copy_resource_x as usize)] + } Kind::CommandList => { use super::bind as b; use super::list_x as l; vec![ // compute root arguments of console code: kept for translated dispatches + (12, b::draw_instanced as usize), + (15, l::copy_buffer_region_x as usize), + (16, l::copy_texture_region_x as usize), + (17, l::copy_resource_x as usize), + (13, b::draw_indexed_instanced as usize), (14, b::dispatch as usize), + (34, b::set_graphics_root_signature as usize), + (36, b::set_graphics_root_table as usize), + (38, b::set_graphics_root_constant as usize), + (40, b::set_graphics_root_constants as usize), + (42, b::set_graphics_root_descriptor as usize), + (44, b::set_graphics_root_descriptor as usize), + (46, b::set_graphics_root_descriptor as usize), (26, l::resource_barrier_x as usize), (25, b::set_pipeline_state as usize), (33, b::set_compute_root_signature as usize), @@ -704,7 +719,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (70, l::write64_bottom_x as usize), (78, l::dispatch_x as usize), (81, l::draw_indexed_x as usize), - (84, l::copy_resource_x as usize), + (84, l::copy_resource_flags_x as usize), (85, l::set_predication_buffer_x as usize), (88, l::write32_top_x as usize), (89, l::write64_top_x as usize), @@ -946,26 +961,96 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: let (base, size) = u.window(k); let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; - if !va.is_multiple_of(0x1_0000) || bytes == 0 || va - base + bytes > size { + // a placed PC buffer starts at 64 KiB: one at another address starts below it and XCL adds + // the difference where PC methods take an offset into it (`buffer_delta`) + let start = va & !0xFFFF; + let delta = va - start; + if bytes == 0 || va - base + bytes > size { return None; } let heap = *UMA_HEAPS.lock().unwrap().get(k)?; d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; - let hr = dev_create_placed_resource(this, heap, va - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); + d.Width = (delta + bytes) as u64; + let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { return None; } UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + if delta != 0 { + BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + } Some(hr) } +/// buffers placed below their console address: resource → bytes before it +static BUFFER_DELTA: Mutex>> = Mutex::new(None); + +/// Where offset 0 of a console buffer is in its PC resource (0 for most). +pub fn buffer_delta(res: usize) -> u64 { + BUFFER_DELTA.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) +} + /// resource Release (every caller): a console buffer's unified memory goes with it +/// Map: on the console every resource is CPU-visible memory. One in unified memory that the +/// PC cannot map (a texture XCL keeps in step with it) gives its unified-memory address – what +/// the console gives; the CPU's writes there reach the texture (`title_textures`). +unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_void, data: *mut *mut c_void) -> HRESULT { + // a resource in unified memory: its console address (no PC mapping – the PC's would be + // the start of the PC resource, before the address for a buffer placed below it) + if let Some((p, _)) = console_buffer(this as usize) { + if !data.is_null() { + *data = p as *mut c_void; + } + UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + return S_OK; + } + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Map"))); + let hr = f(this, sub, range, data); + if hr >= 0 { + return hr; + } + match super::title_textures::address(this as usize) { + Some(p) => { + if !data.is_null() { + *data = p as *mut c_void; + } + UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + S_OK + } + None => { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + let d = ID3D12Resource::from_raw_borrowed(&this).map(|r| r.GetDesc()); + crate::xlog_warn!("D3D12.X: Map of a resource not in unified memory → {:#x} ({:?})", hr as u32, d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0, d.Flags.0))); + } + hr + } + } +} + +/// resources whose Map gave their unified-memory address (no PC mapping to undo) +static UNMAPPABLE: Mutex>> = Mutex::new(None); + +unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c_void) { + if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { + return; + } + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); + f(this, sub, range) +} + unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { + if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { + s.remove(&(this as usize)); + } + if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { + m.remove(&(this as usize)); + } super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { @@ -991,6 +1076,14 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { /// compute pipelines that run a translated console shader static TRANSLATED_COMPUTE: Mutex>> = Mutex::new(None); +/// graphics pipelines built from translated console shaders +static TRANSLATED_GRAPHICS: Mutex>> = Mutex::new(None); + +/// Whether `pso` is a graphics pipeline of translated console shaders. +pub fn is_translated_graphics(pso: usize) -> bool { + pso != 0 && TRANSLATED_GRAPHICS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) +} + /// Whether `pso` runs a translated console compute shader. pub fn is_translated_compute(pso: usize) -> bool { pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) @@ -1000,6 +1093,9 @@ fn forget_pso(pso: usize) { if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); } + if let Some(s) = TRANSLATED_GRAPHICS.lock().unwrap().as_mut() { + s.remove(&pso); + } if let Some(m) = PSO_RS.lock().unwrap().as_mut() { m.remove(&pso); } @@ -1325,7 +1421,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::CommandList => v.extend_from_slice(&[("OMSetRenderTargets", cl_om_set_render_targets as usize), ("SetPipelineState", cl_set_pipeline_state as usize), ("Close", cl_close as usize)]), Kind::CommandQueue => v.push(("ExecuteCommandLists", q_execute_command_lists as usize)), Kind::CommandAllocator => v.push(("Reset", alloc_reset as usize)), - Kind::Resource => v.push(("Release", res_release as usize)), + Kind::Resource => v.extend_from_slice(&[("Release", res_release as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize)]), Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), _ => {} @@ -1775,6 +1871,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics PSO from translated console shaders (#{})", n + 1); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index cfd52ba..811615e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -77,6 +77,11 @@ pub fn forget(res: usize) { TEXTURES.lock().unwrap().remove(&res); } +/// The title-memory address of a texture kept in step with it. +pub fn address(res: usize) -> Option { + TEXTURES.lock().unwrap().get(&res).map(|e| e.va) +} + /// Before the title's GPU work: textures whose memory the CPU wrote since the last look are /// uploaded again. pub(super) unsafe fn refresh() { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0515006..9aa8d12 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -126,9 +126,9 @@ pub fn sanitize_protect(p: u32) -> u32 { } } -/// Graphics address space the title reserved (no commit) – where it maps physical pages (a -/// texture streaming pool): base → size. Write-watched, like unified memory, so textures in it -/// follow CPU writes (`d3d12x::title_textures`). +/// Graphics address space the title reserved (no commit) that unified memory had no room for +/// – where it maps physical pages (a texture streaming pool): base → size. Write-watched, like +/// unified memory, so textures in it follow CPU writes (`d3d12x::title_textures`). static GRAPHICS_RESERVATIONS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// The title's graphics reservations (base, size). @@ -153,13 +153,30 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } } if addr.is_null() && t & MEM_GRAPHICS != 0 && t & 0x2000 != 0 { + // on the console all graphics memory is GPU-visible, reserved address space too (titles + // reserve a range, then commit or map pages and place resources in it): a range of + // unified memory, which is committed already + if let Some(q) = crate::gpu::uma::get().and_then(|u| u.reserve(size, 0x1_0000)) { + return q as *mut c_void; + } let q = mem::VirtualAlloc(addr, size, mem::MEM_RESERVE | MEM_WRITE_WATCH, sanitize_protect(p)); if !q.is_null() { GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); return q; } } - mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)) + let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); + trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); + q +} + +/// `XCL_TRACE_MEM=1`: allocations of 64 KiB or more that are not unified memory (first 60) +fn trace_mem(what: &str, addr: usize, size: usize, flags: u64, protect: u32, got: usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static N: AtomicUsize = AtomicUsize::new(0); + if size >= 0x1_0000 && *ON.get_or_init(|| std::env::var_os("XCL_TRACE_MEM").is_some()) && N.fetch_add(1, Ordering::Relaxed) < 60 { + crate::xlog_info!("mem: {what}({addr:#x}, {size:#x}, flags {flags:#x}, protect {protect:#x}) → {got:#x}"); + } } /// Blocks of the unified memory region go back to it (MEM_RELEASE) or stay (MEM_DECOMMIT @@ -243,7 +260,9 @@ unsafe fn aligned_heap_free(p: *mut c_void) { pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut c_void { let a = XAllocAttrs::decode(attrs); if a.memory_type == 0 { - aligned_heap_alloc(size, 1usize << a.alignment.max(4)) + let q = aligned_heap_alloc(size, 1usize << a.alignment.max(4)); + trace_mem("XMemAlloc", 0, size, attrs, 0, q as usize); + q } else if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(size, 1usize << a.alignment.min(30))) { q as *mut c_void // graphics memory types: GPU-visible } else { diff --git a/crates/xcl/tests/console_shaders.rs b/crates/xcl/tests/console_shaders.rs index cabd686..0ae2997 100644 --- a/crates/xcl/tests/console_shaders.rs +++ b/crates/xcl/tests/console_shaders.rs @@ -439,3 +439,69 @@ fn print_root_argument_placement() { } } } + +/// Where the console puts root arguments for a vertex and a pixel shader: the first +/// instructions of each and the user SGPR counts of their hardware stages. +#[test] +#[ignore] +fn print_graphics_root_argument_placement() { + let Some(c) = console_compiler() else { return }; + let rs = "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0)), StaticSampler(s0)"; + let common = format!("cbuffer k : register(b0) {{ uint k0; uint k1; }};\ncbuffer m : register(b1) {{ float4 m0; }};\nTexture2D t : register(t0);\nSamplerState s : register(s0);\n#define ROOT [RootSignature(\"{rs}\")]\n"); + let shaders = [ + ("VS", "vs_6_6", "struct O { float4 p : SV_Position; float2 uv : TEXCOORD0; };\nROOT O main(float3 pos : POSITION, float2 uv : TEXCOORD0) { O o; o.p = float4(pos * m0.xyz, (float)k0); o.uv = uv + (float)k1; return o; }\n"), + ("PS", "ps_6_6", "ROOT float4 main(float4 p : SV_Position, float2 uv : TEXCOORD0) : SV_Target { return t.Sample(s, uv) * m0 + (float)(k0 ^ k1); }\n"), + ]; + for (name, profile, body) in shaders { + let src = format!("{common}{body}"); + let blob = match console_compile(&c, &src, &["-E", "main", "-T", profile]) { + Ok(b) => b, + Err(e) => { + println!("{name}: {e}"); + continue; + } + }; + let Some(sh) = xcl::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + println!("{name}: FSSM stages {:?}", f.stages.iter().map(|s| xcl::gpu::xbox::hw_stage_name(s.hw)).collect::>()); + for st in &f.stages { + // SPI_SHADER_PGM_RSRC2 user SGPR count: bits 5:1 (graphics stages too) + let rd = |o: usize| f.data.get(st.offset + o..st.offset + o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + println!(" stage {} descriptor words: {:x?}", xcl::gpu::xbox::hw_stage_name(st.hw), (0..24).map(|k| rd(4 * k).unwrap_or(0)).collect::>()); + } + if let Some(p) = f.programs.first() { + for l in xcl::gpu::rdna2::disassemble(&f.data[p.offset..p.offset + p.len], 0, true).iter().skip(2).take(40) { + println!(" {}", l.text); + } + } + } + } +} + +/// The inline / table split of graphics root arguments: n constants + a CBV, for a few n. +#[test] +#[ignore] +fn print_graphics_root_argument_capacity() { + let Some(c) = console_compiler() else { return }; + for n in [20u32, 22, 23, 24, 25, 40] { + let rs = format!("RootConstants(num32BitConstants={n}, b0), CBV(b1)"); + let src = format!( + "cbuffer k : register(b0) {{ uint k[{n}]; }};\ncbuffer m : register(b1) {{ float4 m0; }};\n[RootSignature(\"{rs}\")]\nfloat4 main(float4 p : SV_Position) : SV_Target {{ return m0 + (float)(k[0] + k[{}]); }}\n", + n - 1 + ); + let blob = match console_compile(&c, &src, &["-E", "main", "-T", "ps_6_6"]) { + Ok(b) => b, + Err(e) => { + println!("{n}: {e}"); + continue; + } + }; + let Some(sh) = xcl::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + if let Some(p) = f.programs.first() { + let lines: Vec = xcl::gpu::rdna2::disassemble(&f.data[p.offset..p.offset + p.len], 0, true).iter().skip(2).take(14).map(|l| l.text.clone()).collect(); + println!("{n} constants + CBV: {}", lines.join(" | ")); + } + } + } +}