From 99b981676647f85882d322e2b2941e35d2abc7af Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 22:59:54 -0500 Subject: [PATCH 1/9] D3D12.X: execute two-pass mesh shaders on DispatchMesh and ExecuteIndirect Console mesh shaders translated to a two-pass pair (compute + mesh/PS, TwoPassPso) were built by CreatePipelineState but had no execution path: DispatchMesh was not hooked on the console command list vtable, and ExecuteIndirect did not dispatch the compute pass or bind the record buffer (u1) before invoking the mesh pass. Hook DispatchMesh (slot 127, newer layout slot 129) and handle TwoPassPso in ExecuteIndirect: - Track console mesh root-argument layout (s[8:9] spill table, inline arguments from s16 across 16 SGPRs) in console_list::user_data_ms. - Create a companion DISPATCH command signature alongside non-root-changing DISPATCH_MESH command signatures in device_x::create_command_signature_x. - Allocate/recycle a DEFAULT-heap UAV record buffer per command list (recycled on allocator reset), bind u0 (io), u1 (res), u2..u5 (UMA), run the compute pass -> UAV barrier -> mesh pass -> UAV barrier, and scale indirect DispatchMesh group counts on the GPU when mesh_groups_per_record > 1. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/bind.rs | 387 +++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 38 ++- crates/xcl/src/hle/d3d12x/device_x.rs | 31 +- crates/xcl/src/hle/d3d12x/real.rs | 15 +- 4 files changed, 462 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef4..1d0d8858f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,28 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + res_buf: Option<(ID3D12Resource, u64, usize)>, + res_retired: Vec<(ID3D12Resource, u64, usize)>, +} + +static ALLOC_RES: Mutex>>> = Mutex::new(None); +static FREE_RES: Mutex> = Mutex::new(Vec::new()); + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +pub(super) fn release_allocator_res(allocator: usize) { + let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; + let mut free = FREE_RES.lock().unwrap(); + for b in bufs { + if free.len() < 16 { + free.push(b); + } + } } static STATES: Mutex>> = Mutex::new(None); @@ -73,7 +95,7 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { + let (old, blocks, res_bufs) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; @@ -82,9 +104,14 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + (old, std::mem::take(&mut s.uma), res_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -123,8 +150,12 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + if let Some(mut s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + hold_res_until_reset(s.allocator, s.res_retired); } } @@ -225,6 +256,15 @@ fn note_address(va: u64) { /// command signatures that change root arguments (they need the title's root signature) static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); + pub(super) fn note_root_changing_signature(sig: usize) { ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); } @@ -247,15 +287,338 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); +} + +fn dispatch_mesh_sig_of(sig: usize) -> Option { + DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() +} + +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(res.cloned()), + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = 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::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + res.ok_or_else(|| format!("null {what}")) +} + +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + if let Some((buf, _cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va)); + } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= need).map(|i| free.swap_remove(i)) + }; + let entry = match picked { + Some(e) => e, + None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), + }; + let buf = entry.0.clone(); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); + } + }); + Ok((buf, va)) +} + +unsafe fn bind_two_pass_stage( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: 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_gfx.clone(), s.args_gfx.clone())); + let copy = |bytes: &[u8]| -> Result { + let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + Ok(p as usize) + }; + let inline = layout + .as_ref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let table_at = copy(&args[inline..])?; + let mut io = match layout.as_ref() { + Some(l) if compute_pass => console_list::user_data_ms(l, &args, table_at as u64), + Some(l) => console_list::user_data_gfx(l, &args, table_at as u64), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v + } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; + let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); + let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; + let views = [va(io_at), res_va].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + if compute_pass { + list.SetComputeRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + let pso_raw = tp.compute as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass compute pipeline")?; + list.SetPipelineState(pc); + } else { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + let pso_raw = real_mesh_pso as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass mesh pipeline")?; + list.SetPipelineState(pc); + } + Ok(()) +} + +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let hlsl = "cbuffer C : register(b0) { uint count; uint stride; uint offset; uint mult; };\nByteAddressBuffer src : register(t0);\nRWByteAddressBuffer dst : register(u0);\n[numthreads(64, 1, 1)]\nvoid main(uint tid : SV_DispatchThreadID) {\n if (tid >= count) return;\n uint base = tid * stride;\n uint dwords = stride / 4u;\n for (uint i = 0u; i < dwords; ++i) {\n uint w = src.Load(base + i * 4u);\n if (i * 4u == offset) w = w * mult;\n dst.Store(base + i * 4u, w);\n }\n}\n"; + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("scale rs serialize: {e}"))?; + let blob = blob.ok_or("scale rs blob")?; + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("scale rs create: {e}"))?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, mult: u32) -> Result { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = scale_indirect_pipeline(&dev)?; + let src_ptr = src_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&src_ptr).ok_or("indirect args buffer")?; + let bytes = (max as u64).saturating_mul(stride as u64).max(256).next_multiple_of(256); + let dst = default_uav_buffer(&dev, bytes, "scaled args buffer")?; + emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + let consts = [max, stride, mesh_offset, mult]; + list.SetComputeRoot32BitConstants(0, 4, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootShaderResourceView(1, src.GetGPUVirtualAddress() + src_off); + list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress()); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + emit_transition(list, src, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + let dev_key = dev.as_raw() as usize; + with(this, |s| s.res_retired.push((dst.clone(), bytes, dev_key))); + Ok(dst) +} + +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + if let Some(tp) = super::real::two_pass_of(pso) { + let groups = x.saturating_mul(y.max(1)).saturating_mul(z.max(1)); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let need = (groups as u64).saturating_mul(tp.record.record_dwords() as u64).saturating_mul(4); + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, need)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + list.Dispatch(groups, 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc_dm(this, groups.saturating_mul(tp.mesh_groups_per_record), 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + if super::pso_async::is_pending(raw_pso) { + count(DRAWS_SKIPPED); + return; + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { + list.SetGraphicsRootSignature(r); + } + count(DRAWS_PC); + pc_dm(this, x, y, z); +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); - let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + if let Some(tp) = super::real::two_pass_of(pso) { + if let Some(msig) = dispatch_mesh_sig_of(sig) { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, 32 << 20)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + pc(this, msig.companion_dispatch, max, args, args_off, count_buf, count_off); + emit_uav_barrier(list, Some(&res_buf)); + if tp.mesh_groups_per_record > 1 && max > 0 && args != 0 { + let scaled = make_scaled_args_buffer(this, list, args, args_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, scaled.as_raw() as usize, 0, count_buf, count_off); + } else { + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, args, args_off, count_buf, count_off); + } + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; + } + } + let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and // the list may hold XCL's ABI root signature from a translated draw before it – the PC @@ -1531,4 +1894,18 @@ void main(uint t : SV_GroupIndex) { let _ = pso_async::released(standin); } } + + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); + assert_eq!( + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) + ); + DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18..988fa6650 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,6 +74,7 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + pub inline_ms: u32, } /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the @@ -81,8 +82,10 @@ pub struct Layout { /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Most bytes of root arguments a layout has. The PC's limit is 64 DWORDs (256 bytes: a /// constant or a table 1, a root descriptor 2, D3D12 "Root Signature Limits"); the console's /// is not known, so 16 times that. A malformed blob (a count of 0x3FFF_FFFF constants) gets no @@ -104,7 +107,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, mut spilled_gfx) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, 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 { @@ -127,6 +130,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size = size; l.params.push(p); } @@ -170,6 +177,19 @@ pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) } +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { let mut s = vec![0u32; first]; s[0] = table_at as u32; @@ -331,6 +351,7 @@ pub fn allocator_reset(allocator: *mut c_void) { if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -1016,4 +1037,19 @@ mod tests { 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]); } + + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (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(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8dec7b1c2..ec9fd0bfa 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1029,6 +1029,19 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( /// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's /// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments /// that need one (constants, CBV / SRV / UAV) +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { return E_INVALIDARG; @@ -1046,8 +1059,22 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !ppv.is_null() { + if needs_root { + super::bind::note_root_changing_signature(*ppv as usize); + } else if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fed31e622..4bfad13a8 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1028,6 +1028,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (127, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -5467,7 +5468,19 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; + +pub(super) unsafe fn list_device(list: *mut c_void) -> Option { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). From d41d2f32142923fdbe299306c6950faa9b63513b Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:44:40 +0200 Subject: [PATCH 2/9] D3D12.X: give the two-pass io block the unified memory base Without IO_UMA_BASE_HI the pair picked no memory window for any access. --- crates/xcl/src/hle/d3d12x/bind.rs | 46 +++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 1d0d8858f..4314296b5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -382,6 +382,26 @@ unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D1 Ok((buf, va)) } +/// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the +/// argument table at `table_at`, and the high dword of unified memory's base, as the other binds +/// write it (the translated pair picks each access's memory window from it). +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize) -> Vec { + let mut io = match layout { + Some(l) if compute_pass => console_list::user_data_ms(l, args, table_at), + Some(l) => console_list::user_data_gfx(l, args, table_at), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v + } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io +} + unsafe fn bind_two_pass_stage( this: *mut c_void, list: &ID3D12GraphicsCommandList, @@ -404,18 +424,7 @@ unsafe fn bind_two_pass_stage( .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) .min(args.len()); let table_at = copy(&args[inline..])?; - let mut io = match layout.as_ref() { - Some(l) if compute_pass => console_list::user_data_ms(l, &args, table_at as u64), - Some(l) => console_list::user_data_gfx(l, &args, table_at as u64), - None if compute_pass => { - let mut v = vec![0u32; 16]; - v[8] = table_at as u32; - v[9] = (table_at >> 32) as u32; - v - } - None => vec![table_at as u32, (table_at >> 32) as u32], - }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + let io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base()); let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; @@ -1908,4 +1917,17 @@ void main(uint t : SV_GroupIndex) { DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); assert_eq!(dispatch_mesh_sig_of(sig), None); } + + #[test] + fn two_pass_io_carries_the_unified_memory_base() { + use crate::gpu::recomp::{IO_UMA_BASE_HI, KERNEL_SGPRS}; + let base = 0x4_0000_0000usize; + for compute_pass in [true, false] { + let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base); + assert_eq!(io.len(), KERNEL_SGPRS); + assert_eq!(io[IO_UMA_BASE_HI], 4, "compute pass {compute_pass}"); + } + let io = two_pass_io(None, &[], 0x4_1234_5600, true, base); + assert_eq!((io[8], io[9]), (0x1234_5600, 4)); + } } From ee561d030682ba9bffe91b611bd1ada67a8f47bf Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:47:15 +0200 Subject: [PATCH 3/9] D3D12.X: keep two-pass groups inside the record buffer DispatchMesh runs at most the groups the buffer holds; ExecuteIndirect's arguments are rewritten on the GPU with the same bound for both passes. --- crates/xcl/src/gpu/recomp/runner.rs | 5 +- crates/xcl/src/hle/d3d12x/bind.rs | 184 ++++++++++++++++++---------- 2 files changed, 125 insertions(+), 64 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index f647dbd2c..bfff7bc8e 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1544,7 +1544,10 @@ fn dispatch_with( list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + // every window (u2..u5) is `mem`, as in the heap above + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, mem_buf.GetGPUVirtualAddress()); + } // `reps` dispatches, each between two timestamps when `timed` let stamps = 2 * reps as u32; let queries = if timed { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 4314296b5..212ae42ed 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -356,11 +356,19 @@ unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Resu res.ok_or_else(|| format!("null {what}")) } -unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64), String> { +/// Groups of a two-pass dispatch that have a record: one record a group in `cap_bytes` of +/// records of `record_bytes`, and every group in X, the mesh pass's `split` times as many (at most +/// 65 535 a dimension). The compute pass writes record `gid.x` with no bound of its own. +fn record_groups(cap_bytes: u64, record_bytes: u64, split: u32) -> u32 { + (cap_bytes / record_bytes.max(1)).min(65_535 / split.max(1) as u64) as u32 +} + +/// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); - if let Some((buf, _cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + if let Some((buf, cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { let va = buf.GetGPUVirtualAddress(); - return Ok((buf, va)); + return Ok((buf, va, cap)); } let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; let dev_key = dev.as_raw() as usize; @@ -372,14 +380,14 @@ unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D1 Some(e) => e, None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), }; - let buf = entry.0.clone(); + let (buf, cap) = (entry.0.clone(), entry.1); let va = buf.GetGPUVirtualAddress(); with(this, |s| { if let Some(old) = s.res_buf.replace(entry) { s.res_retired.push(old); } }); - Ok((buf, va)) + Ok((buf, va, cap)) } /// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the @@ -450,48 +458,37 @@ unsafe fn bind_two_pass_stage( Ok(()) } +/// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, +/// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and +/// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute +/// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups. +pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); + if (tid >= count) return; + uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint n = min(src.Load(s + offset), cap); + dst.Store(d + offset, n); + dst.Store(m + offset, n * split); +} +"#; + unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); let key = dev.as_raw() as usize; if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { return Ok(pair); } - let hlsl = "cbuffer C : register(b0) { uint count; uint stride; uint offset; uint mult; };\nByteAddressBuffer src : register(t0);\nRWByteAddressBuffer dst : register(u0);\n[numthreads(64, 1, 1)]\nvoid main(uint tid : SV_DispatchThreadID) {\n if (tid >= count) return;\n uint base = tid * stride;\n uint dwords = stride / 4u;\n for (uint i = 0u; i < dwords; ++i) {\n uint w = src.Load(base + i * 4u);\n if (i * 4u == offset) w = w * mult;\n dst.Store(base + i * 4u, w);\n }\n}\n"; - let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; - let params = [ - D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }, - D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }, - D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }, - ]; - let desc = D3D12_ROOT_SIGNATURE_DESC { - NumParameters: params.len() as u32, - pParameters: params.as_ptr(), - ..Default::default() - }; - let mut blob = None; - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("scale rs serialize: {e}"))?; - let blob = blob.ok_or("scale rs blob")?; - let rs: ID3D12RootSignature = dev - .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) - .map_err(|e| format!("scale rs create: {e}"))?; + let dxil = crate::gpu::recomp::dxc::compile_cached(SCALE_ARGS_HLSL, "main", "cs_6_6")?.0; + let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, @@ -504,23 +501,31 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna Ok((rs, pso)) } -unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, mult: u32) -> Result { +/// The arguments of `max` commands at `src_off` in `src_raw`, rewritten for the two passes +/// (`SCALE_ARGS_HLSL`): the buffer, with the compute pass's commands at 0 and the mesh pass's +/// after them. +#[allow(clippy::too_many_arguments)] +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result { let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = scale_indirect_pipeline(&dev)?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; let src_ptr = src_raw as *mut c_void; let src = ID3D12Resource::from_raw_borrowed(&src_ptr).ok_or("indirect args buffer")?; - let bytes = (max as u64).saturating_mul(stride as u64).max(256).next_multiple_of(256); + let bytes = (max as u64).saturating_mul(stride as u64).saturating_mul(2).max(256).next_multiple_of(256); let dst = default_uav_buffer(&dev, bytes, "scaled args buffer")?; - emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); - let consts = [max, stride, mesh_offset, mult]; - list.SetComputeRoot32BitConstants(0, 4, consts.as_ptr() as *const c_void, 0); - list.SetComputeRootShaderResourceView(1, src.GetGPUVirtualAddress() + src_off); - list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(2, src.GetGPUVirtualAddress() + src_off); + list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress()); list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); - emit_transition(list, src, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + emit_transition(list, src, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); let dev_key = dev.as_raw() as usize; with(this, |s| s.res_retired.push((dst.clone(), bytes, dev_key))); Ok(dst) @@ -537,14 +542,25 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - let need = (groups as u64).saturating_mul(tp.record.record_dwords() as u64).saturating_mul(4); + let record_bytes = tp.record.record_dwords() as u64 * 4; + let need = (groups as u64).saturating_mul(record_bytes); let run = (|| -> Result<(), String> { - let (res_buf, res_va) = ensure_res_buffer(this, need)?; + let (res_buf, res_va, cap) = ensure_res_buffer(this, need)?; + let n = groups.min(record_groups(cap, record_bytes, tp.mesh_groups_per_record)); + if n == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + if n < groups { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh of {groups} groups: {} past the record buffer dropped", groups - n); + } + } bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; - list.Dispatch(groups, 1, 1); + list.Dispatch(n, 1, 1); emit_uav_barrier(list, Some(&res_buf)); bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; - pc_dm(this, groups.saturating_mul(tp.mesh_groups_per_record), 1, 1); + pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); emit_uav_barrier(list, Some(&res_buf)); Ok(()) })(); @@ -592,18 +608,23 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let Some(msig) = dispatch_mesh_sig_of(sig) { let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; let run = (|| -> Result<(), String> { - let (res_buf, res_va) = ensure_res_buffer(this, 32 << 20)?; + if max == 0 || args == 0 { + return Ok(()); + } + let record_bytes = tp.record.record_dwords() as u64 * 4; + let (res_buf, res_va, cap) = ensure_res_buffer(this, 32 << 20)?; + let cap = record_groups(cap, record_bytes, tp.mesh_groups_per_record); + if cap == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + // the groups past the record buffer are dropped on the GPU (`SCALE_ARGS_HLSL`) + let scaled = make_scaled_args_buffer(this, list, args, args_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; + let mesh_args = max as u64 * msig.byte_stride as u64; bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; - pc(this, msig.companion_dispatch, max, args, args_off, count_buf, count_off); + pc(this, msig.companion_dispatch, max, scaled.as_raw() as usize, 0, count_buf, count_off); emit_uav_barrier(list, Some(&res_buf)); - if tp.mesh_groups_per_record > 1 && max > 0 && args != 0 { - let scaled = make_scaled_args_buffer(this, list, args, args_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record)?; - bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; - pc(this, sig, max, scaled.as_raw() as usize, 0, count_buf, count_off); - } else { - bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; - pc(this, sig, max, args, args_off, count_buf, count_off); - } + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, scaled.as_raw() as usize, mesh_args, count_buf, count_off); emit_uav_barrier(list, Some(&res_buf)); Ok(()) })(); @@ -1930,4 +1951,41 @@ void main(uint t : SV_GroupIndex) { let io = two_pass_io(None, &[], 0x4_1234_5600, true, base); assert_eq!((io[8], io[9]), (0x1234_5600, 4)); } + + #[test] + fn two_pass_groups_stay_inside_the_record_buffer() { + // #304's transform record: 11 908 dwords + let record = 11_908 * 4; + assert_eq!(record_groups(32 << 20, record, 1), 704); + assert_eq!(record_groups(128 << 20, record, 1), 2817); + // the mesh pass's groups, `split` a record, all in X + assert_eq!(record_groups(1 << 30, 64, 7), 65_535 / 7); + assert_eq!(record_groups(1 << 20, 2 << 20, 1), 0); + } + + /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): + /// the compute pass's and the mesh pass's commands. + fn scale_args(commands: &[[u32; 4]], split: u32, cap: u32) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return None; + } + let dxil = crate::gpu::recomp::dxc::compile(SCALE_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let n = commands.len(); + let (src, dst) = (0u32, 256u32); + let mut mem: Vec = commands.iter().flatten().copied().collect(); + mem.resize(64 + 2 * 4 * n, 0xDEAD); + let io = [n as u32, 16, 4, split, cap, src, dst]; + let out = runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap(); + let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; + Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) + } + + #[test] + fn gpu_indirect_two_pass_groups_stay_inside_the_record_buffer() { + let Some((compute, mesh)) = scale_args(&[[7, 100, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]], 2, 10) else { return }; + assert_eq!(compute, [[7, 10, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]]); + assert_eq!(mesh, [[7, 20, 1, 1], [8, 6, 1, 1], [9, 0, 1, 1]]); + } } From ccfe5c10abb5fbe3ba5134339d3e18b17771e1e6 Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:47:41 +0200 Subject: [PATCH 4/9] D3D12.X: run indirect two-pass groups of Y and Z too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both passes index records by gid.x, so the rewritten arguments put x·y·z in X. --- crates/xcl/src/hle/d3d12x/bind.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 212ae42ed..ed020962f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -461,7 +461,8 @@ unsafe fn bind_two_pass_stage( /// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, /// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and /// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute -/// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups. +/// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups, all in X: +/// both passes find a group's record by `gid.x` alone. pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); RWByteAddressBuffer src : register(u2); RWByteAddressBuffer dst : register(u3); @@ -475,9 +476,15 @@ void main(uint tid : SV_DispatchThreadID) { dst.Store(d + i, w); dst.Store(m + i, w); } - uint n = min(src.Load(s + offset), cap); - dst.Store(d + offset, n); - dst.Store(m + offset, n * split); + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); } "#; @@ -537,7 +544,7 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: let raw_pso = with(this, |s| s.pso); let pso = super::pso_async::resolve_wait(raw_pso); if let Some(tp) = super::real::two_pass_of(pso) { - let groups = x.saturating_mul(y.max(1)).saturating_mul(z.max(1)); + let groups = x.saturating_mul(y).saturating_mul(z); if groups == 0 { return; } @@ -1988,4 +1995,12 @@ void main(uint t : SV_GroupIndex) { assert_eq!(compute, [[7, 10, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]]); assert_eq!(mesh, [[7, 20, 1, 1], [8, 6, 1, 1], [9, 0, 1, 1]]); } + + #[test] + fn gpu_indirect_two_pass_groups_go_in_x() { + let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000]]; + let Some((compute, mesh)) = scale_args(&commands, 3, 1000) else { return }; + assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1]]); + } } From e284043242b08e720d834e3036521a7e5dded70f Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:49:58 +0200 Subject: [PATCH 5/9] D3D12.X: read two-pass indirect arguments through memory, cap their scratch The rewrite reads the commands through the memory window, not the title's buffer in a guessed state, into shared scratch blocks capped at 16 MiB a recording. --- crates/xcl/src/hle/d3d12x/bind.rs | 156 +++++++++++++++++++++++++----- 1 file changed, 131 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ed020962f..37e355f5a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -36,8 +36,20 @@ struct State { arena: crate::gpu::uma::Arena, res_buf: Option<(ID3D12Resource, u64, usize)>, res_retired: Vec<(ID3D12Resource, u64, usize)>, + /// rewritten indirect arguments (`scratch_args`): the block, its bytes in use, and the + /// bytes of blocks this recording took + scratch: Option<(ID3D12Resource, u64, usize)>, + scratch_used: u64, + scratch_taken: u64, } +/// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its +/// two-pass ExecuteIndirects are skipped) +const SCRATCH_BLOCK: u64 = 1 << 20; +const SCRATCH_CAP: u64 = 16 << 20; +/// Most bytes of buffers kept for reuse (`FREE_RES`) +const FREE_RES_CAP: u64 = 256 << 20; + static ALLOC_RES: Mutex>>> = Mutex::new(None); static FREE_RES: Mutex> = Mutex::new(Vec::new()); @@ -52,12 +64,18 @@ pub(super) fn release_allocator_res(allocator: usize) { let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; let mut free = FREE_RES.lock().unwrap(); for b in bufs { - if free.len() < 16 { + let held: u64 = free.iter().map(|f| f.1).sum(); + if pool_keeps(free.len(), held, b.1) { free.push(b); } } } +/// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. +fn pool_keeps(count: usize, held: u64, bytes: u64) -> bool { + count < 16 && held + bytes <= FREE_RES_CAP +} + static STATES: Mutex>> = Mutex::new(None); /// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one @@ -104,6 +122,8 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + // (the scratch blocks are in `res_retired` already) + (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -508,34 +528,72 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna Ok((rs, pso)) } -/// The arguments of `max` commands at `src_off` in `src_raw`, rewritten for the two passes -/// (`SCALE_ARGS_HLSL`): the buffer, with the compute pass's commands at 0 and the mesh pass's -/// after them. +/// `bytes` of this recording's scratch blocks (COMMON between uses): the block and the offset. +/// Past `SCRATCH_CAP` a recording gets no more. +unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let (b, cap, _) = s.scratch.as_ref()?; + (s.scratch_used + bytes <= *cap).then(|| { + s.scratch_used += bytes; + (b.clone(), s.scratch_used - bytes) + }) + }) { + return Ok(r); + } + let size = bytes.max(SCRATCH_BLOCK); + if with(this, |s| s.scratch_taken) + size > SCRATCH_CAP { + return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + } + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= SCRATCH_CAP).map(|i| free.swap_remove(i)) + }; + let block = match picked { + Some(e) => e, + None => (default_uav_buffer(dev, size, "two-pass argument scratch")?, size, dev_key), + }; + let b = block.0.clone(); + with(this, |s| { + s.scratch_taken += block.1; + s.scratch_used = bytes; + s.scratch = Some(block.clone()); + s.res_retired.push(block); + }); + Ok((b, 0)) +} + +/// The arguments of `max` commands at UMA address `src`, rewritten for the two passes +/// (`SCALE_ARGS_HLSL`) into a scratch block: the block (INDIRECT_ARGUMENT until the caller puts +/// it back to COMMON) and where the compute pass's commands are; the mesh pass's follow them. +/// +/// They are read through the memory window over them, as translated shaders read memory, not +/// through the title's buffer: its state on the PC is the title's and not known here. #[allow(clippy::too_many_arguments)] -unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result { +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(ID3D12Resource, u64), String> { let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let src_ptr = src_raw as *mut c_void; - let src = ID3D12Resource::from_raw_borrowed(&src_ptr).ok_or("indirect args buffer")?; - let bytes = (max as u64).saturating_mul(stride as u64).saturating_mul(2).max(256).next_multiple_of(256); - let dst = default_uav_buffer(&dev, bytes, "scaled args buffer")?; + let commands = (max as u64).saturating_mul(stride as u64); + super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; - emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_barrier(list, None); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); - list.SetComputeRootUnorderedAccessView(2, src.GetGPUVirtualAddress() + src_off); - list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, src_va); + list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); - emit_transition(list, src, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); - let dev_key = dev.as_raw() as usize; - with(this, |s| s.res_retired.push((dst.clone(), bytes, dev_key))); - Ok(dst) + Ok((dst, dst_off)) } pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -610,6 +668,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); let pso = super::pso_async::resolve_wait(raw_pso); + // where the commands are in unified memory (a console buffer's offsets are the title's) + let commands_at = super::real::console_buffer(args).map(|(p, n)| (p + args_off as usize, n.saturating_sub(args_off as usize))); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { if let Some(msig) = dispatch_mesh_sig_of(sig) { @@ -618,6 +678,11 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if max == 0 || args == 0 { return Ok(()); } + let commands = max as usize * msig.byte_stride as usize; + let src = match commands_at { + Some((p, n)) if commands <= n => p, + _ => return Err("its arguments are not in a console buffer in unified memory".into()), + }; let record_bytes = tp.record.record_dwords() as u64 * 4; let (res_buf, res_va, cap) = ensure_res_buffer(this, 32 << 20)?; let cap = record_groups(cap, record_bytes, tp.mesh_groups_per_record); @@ -625,15 +690,18 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return Err(format!("a record of {record_bytes} B does not fit the record buffer")); } // the groups past the record buffer are dropped on the GPU (`SCALE_ARGS_HLSL`) - let scaled = make_scaled_args_buffer(this, list, args, args_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; - let mesh_args = max as u64 * msig.byte_stride as u64; - bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; - pc(this, msig.companion_dispatch, max, scaled.as_raw() as usize, 0, count_buf, count_off); - emit_uav_barrier(list, Some(&res_buf)); - bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; - pc(this, sig, max, scaled.as_raw() as usize, mesh_args, count_buf, count_off); - emit_uav_barrier(list, Some(&res_buf)); - Ok(()) + let (scaled, at) = make_scaled_args_buffer(this, list, src, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; + let passes = (|| -> Result<(), String> { + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + pc(this, msig.companion_dispatch, max, scaled.as_raw() as usize, at, count_buf, count_off); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, scaled.as_raw() as usize, at + commands as u64, count_buf, count_off); + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + passes })(); match run { Ok(()) => { @@ -2003,4 +2071,42 @@ void main(uint t : SV_GroupIndex) { assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1]]); assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1]]); } + + #[test] + fn freed_two_pass_buffers_kept_for_reuse_are_capped() { + assert!(pool_keeps(0, 0, 128 << 20)); + assert!(pool_keeps(1, 128 << 20, 128 << 20)); + assert!(!pool_keeps(2, 256 << 20, 4 << 20)); + assert!(!pool_keeps(16, 0, 1 << 20)); + } + + #[test] + fn gpu_two_pass_argument_scratch_is_shared_and_capped() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let list = 0x7500_0001usize as *mut c_void; + unsafe { + // small rewrites share one block + let (a, at_a) = scratch_args(list, &dev, 100).unwrap(); + let (b, at_b) = scratch_args(list, &dev, 300).unwrap(); + assert_eq!((a.as_raw(), at_a), (b.as_raw(), 0)); + assert_eq!(at_b, 256); + // a recording takes at most SCRATCH_CAP of blocks + let mut taken = 1; + while scratch_args(list, &dev, SCRATCH_BLOCK).is_ok() { + taken += 1; + assert!(taken <= SCRATCH_CAP / SCRATCH_BLOCK, "past the cap"); + } + assert!(with(list, |s| s.scratch_taken) <= SCRATCH_CAP); + // the next recording starts again + reset(list, 0, 0); + assert!(scratch_args(list, &dev, SCRATCH_BLOCK).is_ok()); + } + forget(list); + } } From b7189555dc9b1bbe274f50047361325dae8a491a Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:17:12 +0200 Subject: [PATCH 6/9] Tests: cover a capped X-only two-pass indirect dispatch --- crates/xcl/src/hle/d3d12x/bind.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 37e355f5a..aee31f799 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2066,10 +2066,10 @@ void main(uint t : SV_GroupIndex) { #[test] fn gpu_indirect_two_pass_groups_go_in_x() { - let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000]]; + let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000], [6, 1000, 1, 1], [7, 5000, 1, 1], [8, 5000, 1, 0]]; let Some((compute, mesh)) = scale_args(&commands, 3, 1000) else { return }; - assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1]]); - assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1]]); + assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1], [6, 1000, 1, 1], [7, 1000, 1, 1], [8, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1], [6, 3000, 1, 1], [7, 3000, 1, 1], [8, 0, 1, 1]]); } #[test] From 3442b585c4437847bcb8e739e989ccafa5461d9a Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:23 +0200 Subject: [PATCH 7/9] D3D12.X: run a two-pass ExecuteIndirect one command at a time Each command's records start at record 0, so its mesh pass draws them before the next command's compute pass; commands past a count buffer's count get no groups. --- crates/xcl/src/hle/d3d12x/bind.rs | 185 +++++++++++++++++++++++++++--- 1 file changed, 171 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index aee31f799..cf03d5a49 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -383,6 +383,13 @@ fn record_groups(cap_bytes: u64, record_bytes: u64, split: u32) -> u32 { (cap_bytes / record_bytes.max(1)).min(65_535 / split.max(1) as u64) as u32 } +/// The ExecuteIndirects of a two-pass ExecuteIndirect of `max` commands, each of one command and +/// followed by a UAV barrier on the records: (command, compute pass). Each command's compute pass +/// writes its records from record 0, so the next one goes only after the mesh pass drew them. +fn two_pass_steps(max: u32) -> impl Iterator { + (0..max).flat_map(|k| [(k, true), (k, false)]) +} + /// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); @@ -482,14 +489,18 @@ unsafe fn bind_two_pass_stage( /// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and /// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute /// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups, all in X: -/// both passes find a group's record by `gid.x` alone. +/// both passes find a group's record by `gid.x` alone. With a count buffer (u0 dword 7 set: the +/// count at dword 8's byte offset in u4), the commands past its count get no groups: they are run +/// one by one (`two_pass_steps`), so without one. pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); RWByteAddressBuffer src : register(u2); RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer cnt : register(u4); [numthreads(64, 1, 1)] void main(uint tid : SV_DispatchThreadID) { uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); if (tid >= count) return; + uint live = io.Load(28) != 0u ? min(count, cnt.Load(io.Load(32))) : count; uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; for (uint i = 0u; i < stride; i += 4u) { uint w = src.Load(s + i); @@ -498,7 +509,7 @@ void main(uint tid : SV_DispatchThreadID) { } uint3 g = src.Load3(s + offset); uint n = 0u; - if (g.x != 0u && g.y != 0u && g.z != 0u) { + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { n = min(g.x, cap); n = g.y > cap / n ? cap : n * g.y; n = g.z > cap / n ? cap : n * g.z; @@ -569,17 +580,25 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res /// it back to COMMON) and where the compute pass's commands are; the mesh pass's follow them. /// /// They are read through the memory window over them, as translated shaders read memory, not -/// through the title's buffer: its state on the PC is the title's and not known here. +/// through the title's buffer: its state on the PC is the title's and not known here. So is the +/// count (`count`: its UMA address, when the title gave a count buffer). #[allow(clippy::too_many_arguments)] -unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(ID3D12Resource, u64), String> { +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(ID3D12Resource, u64), String> { let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; let commands = (max as u64).saturating_mul(stride as u64); super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let count_va = match count { + Some(p) => { + super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; + Some(super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?) + } + None => None, + }; let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; - let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0, count_va.is_some() as u32, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; @@ -591,6 +610,9 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman list.SetComputeRootUnorderedAccessView(0, consts_va); list.SetComputeRootUnorderedAccessView(2, src_va); list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); + if let Some(va) = count_va { + list.SetComputeRootUnorderedAccessView(4, va); + } list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); Ok((dst, dst_off)) @@ -670,6 +692,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pso = super::pso_async::resolve_wait(raw_pso); // where the commands are in unified memory (a console buffer's offsets are the title's) let commands_at = super::real::console_buffer(args).map(|(p, n)| (p + args_off as usize, n.saturating_sub(args_off as usize))); + let count_at = super::real::console_buffer(count_buf).filter(|&(_, n)| count_off as usize + 4 <= n).map(|(p, _)| p + count_off as usize); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { if let Some(msig) = dispatch_mesh_sig_of(sig) { @@ -689,15 +712,21 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if cap == 0 { return Err(format!("a record of {record_bytes} B does not fit the record buffer")); } - // the groups past the record buffer are dropped on the GPU (`SCALE_ARGS_HLSL`) - let (scaled, at) = make_scaled_args_buffer(this, list, src, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; + let count = match (count_buf, count_at) { + (0, _) => None, + (_, Some(p)) => Some(p), + _ => return Err("its count is not in a console buffer in unified memory".into()), + }; + // the groups past the record buffer, and the commands past the count, are dropped + // on the GPU (`SCALE_ARGS_HLSL`) + let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; let passes = (|| -> Result<(), String> { - bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; - pc(this, msig.companion_dispatch, max, scaled.as_raw() as usize, at, count_buf, count_off); - emit_uav_barrier(list, Some(&res_buf)); - bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; - pc(this, sig, max, scaled.as_raw() as usize, at + commands as u64, count_buf, count_off); - emit_uav_barrier(list, Some(&res_buf)); + for (k, compute) in two_pass_steps(max) { + bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; + let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + emit_uav_barrier(list, Some(&res_buf)); + } Ok(()) })(); emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); @@ -2041,6 +2070,11 @@ void main(uint t : SV_GroupIndex) { /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): /// the compute pass's and the mesh pass's commands. fn scale_args(commands: &[[u32; 4]], split: u32, cap: u32) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + scale_args_counted(commands, split, cap, None) + } + + /// `scale_args` with a count buffer holding `count` + fn scale_args_counted(commands: &[[u32; 4]], split: u32, cap: u32, count: Option) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { use crate::gpu::recomp::runner; if runner::adapter().is_err() { runner::skip_test("no GPU"); @@ -2051,7 +2085,10 @@ void main(uint t : SV_GroupIndex) { let (src, dst) = (0u32, 256u32); let mut mem: Vec = commands.iter().flatten().copied().collect(); mem.resize(64 + 2 * 4 * n, 0xDEAD); - let io = [n as u32, 16, 4, split, cap, src, dst]; + // the count at dword 60 (u4 is the same memory in the runner) + assert!(4 * n <= 60); + mem[60] = count.unwrap_or(0); + let io = [n as u32, 16, 4, split, cap, src, dst, count.is_some() as u32, 240]; let out = runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap(); let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) @@ -2109,4 +2146,124 @@ void main(uint t : SV_GroupIndex) { } forget(list); } + + #[test] + fn gpu_indirect_two_pass_commands_past_the_count_get_no_groups() { + let commands = [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]; + let Some((compute, mesh)) = scale_args_counted(&commands, 2, 1000, Some(2)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 4, 1, 1], [3, 0, 1, 1]]); + let Some((compute, _)) = scale_args_counted(&commands, 2, 1000, Some(7)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]); + } + + /// Commands of one two-pass ExecuteIndirect run in `two_pass_steps` order on the GPU, with + /// stand-ins for the two passes: the "compute pass" writes each group's record (from record 0) + /// with its command's constant, the "mesh pass" copies the records it reads out by command. + #[test] + fn gpu_two_pass_indirect_commands_keep_their_own_records() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let src = r#" +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint v; }; +RWByteAddressBuffer rec : register(u0); +RWByteAddressBuffer o : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, v); } +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)); } +"#; + // (constant, groups) of each command + let commands = [(1u32, 3u32), (2, 2), (3, 4)]; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let ms = crate::gpu::recomp::dxc::compile(src, "ms", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let pso = |dxil: &[u8]| -> ID3D12PipelineState { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState(&desc).unwrap() + }; + let (pass1, pass2) = (pso(&cs), pso(&ms)); + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 0, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 1 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, + ]; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }, &rs, &mut sig).unwrap(); + let sig = sig.unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + 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, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (indirect, rec, out) = (buffer(256, true), buffer(256, false), buffer(1024, true)); + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (a, o) = (map(&indirect), map(&out)); + for (k, &(v, x)) in commands.iter().enumerate() { + std::ptr::copy_nonoverlapping([v, x, 1, 1].as_ptr(), a.add(4 * k), 4); + } + std::ptr::write_bytes(o, 0, 256); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pass1).unwrap(); + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, rec.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + for (k, compute) in two_pass_steps(commands.len() as u32) { + list.SetPipelineState(if compute { &pass1 } else { &pass2 }); + list.ExecuteIndirect(&sig, 1, &indirect, k as u64 * 16, None::<&ID3D12Resource>, 0); + emit_uav_barrier(&list, Some(&rec)); + } + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(v, x) in &commands { + let got: Vec = (0..x).map(|g| *o.add((v * 16 + g) as usize)).collect(); + assert_eq!(got, vec![v; x as usize], "the records the mesh pass of command {v} read"); + } + indirect.Unmap(0, None); + out.Unmap(0, None); + } + } } From e9471c51ddfeef2019a7f3a9f43d194e77a90287 Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:01:54 +0200 Subject: [PATCH 8/9] D3D12.X: two-pass binds set the shared view heap first With XCL_HEAP_WINDOWS=1 the pair reads the memory windows from the shared heap, as bind_abi's programs do; a list that set none got no heap. --- crates/xcl/src/hle/d3d12x/bind.rs | 72 +++++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 11 +++++ 2 files changed, 83 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index cf03d5a49..8c4c8197e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -445,6 +445,8 @@ unsafe fn bind_two_pass_stage( res_va: u64, compute_pass: bool, ) -> Result<(), String> { + // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` + super::list_x::ensure_view_heap(this); 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")?; @@ -2266,4 +2268,74 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) out.Unmap(0, None); } } + + /// With heap windows the two-pass programs read the memory windows from the shared heap + /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. + /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) + #[test] + fn two_pass_binds_set_the_shared_view_heap() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + if !crate::gpu::recomp::pso::heap_windows() { + skip_test("no heap windows (opt-in: XCL_HEAP_WINDOWS=1)"); + return; + } + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + // the shared heap with a window view, unless the backend made it already + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1 << 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut window: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut window).unwrap(); + let window = window.unwrap(); + if super::super::console_heap::global_heap().is_none() && !super::super::console_heap::set_window_views(&dev, &[(window.as_raw() as usize, 1 << 16)]) { + skip_test("no shared heap"); + return; + } + let g = super::super::console_heap::global_heap().unwrap().as_raw() as usize; + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: ext_vt.as_ptr().add(1), calls: Mutex::new(Vec::new()) }); + let this = &*fake as *const FakeList as *mut c_void; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this).unwrap(); + // no root signatures: the bind stops before it records anything else + let tp = super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; + for compute_pass in [true, false] { + super::super::list_x::set_descriptor_heaps_x(this, 0, std::ptr::null()); + assert!(super::super::list_x::bound_heaps(this, false).is_empty()); + assert!(bind_two_pass_stage(this, list, 0, &tp, 0, compute_pass).is_err()); + assert_eq!(super::super::list_x::bound_heaps(this, false), vec![g], "compute pass {compute_pass}: the shared heap is bound"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&vec![g]), "compute pass {compute_pass}"); + } + super::super::list_x::bound_heaps(this, true); + forget(this); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0fdfb7827..1a60a7f04 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -426,6 +426,17 @@ fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); } +/// (tests) The view heaps XCL counts as bound on `list`; forgetting the list with `forget`. +#[cfg(test)] +pub(super) fn bound_heaps(list: *mut c_void, forget: bool) -> Vec { + let mut heaps = Vec::new(); + with_bindings(list, |b| heaps = b.heaps.clone()); + if forget { + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + heaps +} + const PC_IA_SET_PRIMITIVE_TOPOLOGY: usize = 20; const PC_RS_SET_VIEWPORTS: usize = 21; const PC_RS_SET_SCISSOR_RECTS: usize = 22; From 47c7cc13c1b872ae5f45e4c9ffed6332ca74a4d0 Mon Sep 17 00:00:00 2001 From: PracticalStudios <267216072+PracticalStudios@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:13:18 +0200 Subject: [PATCH 9/9] D3D12.X: pooled two-pass scratch stays within the recording's budget Found and fixed by @WebIdentity1 in #2092. --- crates/xcl/src/hle/d3d12x/bind.rs | 60 +++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8c4c8197e..2bfa18928 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -555,13 +555,14 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res return Ok(r); } let size = bytes.max(SCRATCH_BLOCK); - if with(this, |s| s.scratch_taken) + size > SCRATCH_CAP { + let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); } let dev_key = dev.as_raw() as usize; let picked = { let mut free = FREE_RES.lock().unwrap(); - free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= SCRATCH_CAP).map(|i| free.swap_remove(i)) + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) }; let block = match picked { Some(e) => e, @@ -2338,4 +2339,59 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) forget(this); } } + + + /// A reusable block must fit the recording's remaining budget, not just its request. + #[test] + fn gpu_two_pass_pooled_scratch_respects_remaining_budget() { + use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let wanted = std::env::var("XCL_ADAPTER").unwrap_or_default(); + let mut chosen = None; + for i in 0.. { + let Ok(adapter) = factory.EnumAdapters1(i) else { break }; + let desc = adapter.GetDesc1().unwrap(); + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + if !wanted.is_empty() && !name.contains(&wanted) { continue; } + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() { + chosen = Some((name, dev.unwrap())); + break; + } + } + let Some((name, dev)) = chosen else { + crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter"); + return; + }; + println!("POOLED_SCRATCH_ADAPTER={name}"); + let key = dev.as_raw() as usize; + // These are state keys only; scratch_args does not call through a list pointer. + let (consumer, producer, empty) = (0x7500_1011usize as *mut c_void, 0x7500_1012usize as *mut c_void, 0x7500_1013usize as *mut c_void); + let allocator = 0x7500_1014usize; + let first = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + assert_eq!(with(consumer, |s| s.scratch_taken), SCRATCH_BLOCK); + reset(producer, allocator, 0); + let large = scratch_args(producer, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(large.0.GetDesc().Width, SCRATCH_CAP); + reset(producer, 0, 0); + release_allocator_res(allocator); + let second = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + let taken = with(consumer, |s| s.scratch_taken); + println!("POOLED_SCRATCH taken={taken} second_bytes={} cap={SCRATCH_CAP}", second.0.GetDesc().Width); + // If it was too large for consumer, the cached block remains reusable by an empty recording. + let reused = if taken <= SCRATCH_CAP { + let r = scratch_args(empty, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(r.0.as_raw(), large.0.as_raw()); + assert_eq!(with(empty, |s| s.scratch_taken), SCRATCH_CAP); + assert!(scratch_args(empty, &dev, 256).is_err()); + Some(r) + } else { None }; + drop((first, second, large, reused)); + for list in [consumer, producer, empty] { forget(list); } + FREE_RES.lock().unwrap().retain(|(_, _, d)| *d != key); + assert!(taken <= SCRATCH_CAP, "pooled block exceeds recording budget: {taken} > {SCRATCH_CAP}"); + } + } }