diff --git a/HANDOFF.md b/HANDOFF.md index cb144ad..6ebc0a7 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -466,14 +466,26 @@ nieznanych rekordów), wynik czytany `bvh::Bvh::trace` = brute force na 500 prom T# w ABI XCL (`desc::xcl_image_for_view`: słowo 0 = 2k, format/rozmiar/typ/mipy jak w T#; UAV 2D dostaje też SRV pod 2k, bo RDNA nie rozróżnia). Lista: #32 SetDescriptorHeaps, #26 ResourceBarrier (przejścia przekazane na PC), #15 CopyBufferRegion. Test sondy sprawdza, że tabele ze strumienia wskazują sloty z teksturami wejściowymi (formaty 71/22/29). - - Brakuje: **bufory w UMA** (V# dostaje adres tylko z UMA; dziś pusty V#, log „widok bufora … nie jest w UMA”), - CBV przez #17 (nie widziany), sterty samplerów, zwalnianie slotów przy Release sterty, CopyDescriptors. + - **Bufory w UMA (zrobione):** bufor tworzony przez kod konsoli (#76, wymiar BUFFER) = zasób umieszczony + (CreatePlacedResource) na stercie UMA (`UMA_HEAP`, flaga ALLOW_CROSS_ADAPTER, wyrównanie 64 KB); zasób #11 + GetGPUVirtualAddress (konsola) zwraca adres w UMA (= adres CPU, młodsze 32 bity = offset w `mem`); **Map na PC zwraca + ten sam adres** (sprawdzane raz, log); Release (wszyscy wołający) zwalnia blok. Widoki buforów (SRV/UAV) dostają V# + (`desc::buffer_words`: raw → stride 0, num_records w bajtach; structured/typed → stride, num_records w elementach, + format GFX10). FSR: 3 bufory w UMA, wszystkie V# w tabelach wskazują UMA. + - Uwaga na przyszłość: wszystkie bufory konsoli (też DEFAULT) leżą w pamięci systemowej (UMA) – GPU czyta je przez + PCIe; dla dużych buforów gry może to być wolne. + - Brakuje: CBV przez #17 (nie widziany), sterty samplerów, zwalnianie slotów przy Release sterty, CopyDescriptors. - **PSO FSR4 = ACCC (kontener „FSPX”)** – CreateComputePipelineState (NewBE) dostaje blob SFI0/ISG1/OSG1/PSV0/RTS0/HASH/ACCC bez DXIL. FSPX: nagłówek 'FSPX', wersja 1, n wpisów, rozmiar; wpisy 16 B (typ, offset, rozmiar, 0): **0** (0x1C B: numthreads u16×3 @+0x0C (256,1,1), RSRC1 @+0x14, RSRC2 @+0x18), **1** (0x14, skrót), **6 = kod RDNA2** (początek 0x24 B = nagłówek ze skrótem), **7** (deklaracje zasobów: rekordy 32 B typ 0x41/0x42/0x43, offset w dwordach = slot·8). Tłumacz jeszcze ich nie czyta → dispatche pominięte. Pomocnik: `raw_rdna2_listing` (`XCL_RAW=`). -- Sloty listy jeszcze nieznane: #85 (wskaźnik struktury), #53 (struktura z polami +0x8C..0x94) – zaślepki. +- Sloty listy rozpoznane z kodu FSR: **#53 / #54 = ClearUnorderedAccessViewUint / Float** (uchwyt GPU, uchwyt CPU, zasób, + wartości[4], 0, NULL; FSR wybiera #54 dla celu w formacie 0x12) i **#85 = CopyTextureRegion** (cel: COPY_LOCATION + SUBRESOURCE_INDEX, źródło: PLACED_FOOTPRINT, x/y/z = 0, box NULL; PC #16 – konsola ma tę metodę gdzie indziej). + Rekordy → PC przy Close (uchwyty konsoli → deskryptory PC slotu: UAV 2k+1). FSR: 2 czyszczenia, 4 kopie, 0 pominiętych. +- **Tytuł testowy** woła #9 sterty jak kod konsoli (uchwyt w rax) – wcześniej przez windows-rs (ABI PC) i od 7919cdc padał. + Test XAudio2: dolna granica XMA2 80 → 70 ms (jitter kwantu 10 ms, raz wyszło 79 ms). ### (archiwum) TLAS na GPU – blokada rozmiarem jednego shadera - Test `xbox_bvh_builder_builds_a_tlas_on_the_gpu` (`XCL_CONSOLE_LISTS=1 XCL_PROBE_BVH_TLAS=1`): 2 BLAS + 16 instancji diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 7569bc2..157a18c 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -419,5 +419,28 @@ mod view_tests { assert_eq!((i.format, i.width, i.height, i.depth, i.ty, i.last_level, i.max_mip), (71, 1920, 1080, 1, ImageType::D2, 2, 2)); assert_eq!(i.dst_sel, [4, 5, 6, 7]); assert_eq!(t[0], 14); + let v = buffer(&buffer_words(0x5_1234_5670, 16, 100, 77)); + assert_eq!((v.address, v.stride, v.num_records, v.format, v.dst_sel), (0x5_1234_5670, 16, 100, 77, [4, 5, 6, 7])); + assert_eq!((format_bytes(22), format_bytes(29), format_bytes(71), format_bytes(77)), (4, 4, 8, 16)); } } + +/// Bytes per element of a GFX10 buffer / image format (0–77: 8, 16, 32, 64, 96, 128 bits). +pub fn format_bytes(f: u32) -> u32 { + match f { + 1..=6 => 1, + 7..=19 => 2, + 20..=61 => 4, + 62..=71 => 8, + 72..=74 => 12, + 75..=77 => 16, + _ => 4, + } +} + +/// A V# for a buffer view: `stride` 0 = raw (num_records in bytes), else structured / typed +/// (num_records in elements); `format` = GFX10 format for typed loads (raw: 32_FLOAT). +pub fn buffer_words(address: u64, stride: u32, num_records: u32, format: u32) -> [u32; 4] { + let oob = if stride == 0 { 3 } else { 0 }; + [address as u32, (address >> 32) as u32 & 0xFFFF | (stride & 0x3FFF) << 16, num_records, 0xFAC | (format & 0x7F) << 12 | 1 << 24 | oob << 28] +} diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 7fbfdff..c2afe97 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -17,18 +17,20 @@ struct Heap { shadow: usize, n: u32, pc_cpu: u64, + /// 0: not shader visible + pc_gpu: u64, inc: u32, } static HEAPS: Mutex> = Mutex::new(Vec::new()); -/// `obj` is a PC heap with 2·`n` descriptors from `pc_cpu` (increment `inc`): give it `n` -/// console slots in unified memory. -pub fn register(obj: usize, n: u32, pc_cpu: u64, inc: u32) -> bool { +/// `obj` is a PC heap with 2·`n` descriptors from `pc_cpu` / `pc_gpu` (increment `inc`; +/// `pc_gpu` 0 when not shader visible): give it `n` console slots in unified memory. +pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32) -> bool { let Some(u) = crate::gpu::uma::get() else { return false }; let Some(p) = u.alloc((n.max(1) * SLOT) as usize, 256) else { return false }; unsafe { std::ptr::write_bytes(p, 0, (n * SLOT) as usize) }; - HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, inc }); + HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc }); true } @@ -45,6 +47,8 @@ pub struct Slot { pub index: u32, pub pc_srv: u64, pub pc_uav: u64, + /// PC GPU handle of the UAV (0: heap not shader visible) + pub pc_gpu_uav: u64, } /// The slot behind a console CPU handle (None: not one of XCL's console heaps). @@ -52,7 +56,14 @@ pub fn slot(cpu: u64) -> Option { let heaps = HEAPS.lock().unwrap(); let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * SLOT) as usize) as u64)?; let k = ((cpu - h.shadow as u64) / SLOT as u64) as u32; - Some(Slot { at: h.shadow + (k * SLOT) as usize, index: 2 * k, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + ((2 * k + 1) * h.inc) as u64 }) + let uav = ((2 * k + 1) * h.inc) as u64; + Some(Slot { + at: h.shadow + (k * SLOT) as usize, + index: 2 * k, + pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, + pc_uav: h.pc_cpu + uav, + pc_gpu_uav: if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, + }) } pub fn write(s: &Slot, words: &[u32]) { diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index fbffe35..33427da 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -31,6 +31,8 @@ const BARRIER_MARKER: u32 = 0x8C0F_E005; const HEAPS_MARKER: u32 = 0x8C0F_E006; const TRANSITIONS_MARKER: u32 = 0x8C0F_E007; const COPY_BUFFER_MARKER: u32 = 0x8C0F_E008; +const CLEAR_UAV_MARKER: u32 = 0x8C0F_E009; +const COPY_TEXTURE_MARKER: u32 = 0x8C0F_E00A; /// root parameter header: 0xC0000000 | i << 10 (bits 31:30 set: the inline code leaves its /// dirty flag alone); the inline code adds the constant offset · 4 (bits 9:2) and /// (count − 1) << 16 @@ -389,6 +391,36 @@ unsafe extern "system" fn cl_copy_buffer_region(this: *mut c_void, dst: usize, d } push(this as usize, &w); } +/// #53 / #54 ClearUnorderedAccessViewUint / Float(gpu handle, cpu handle, resource, values[4], +/// rect count, rects) – amd_fidelityfx_upscaler_xbox.dll picks #54 for float targets +unsafe fn clear_uav(this: *mut c_void, float: bool, gpu: u64, cpu: u64, res: usize, values: *const u32, rects: u32) { + if rects != 0 { + crate::xlog_warn!("lista konsoli: ClearUnorderedAccessView z {rects} prostokątami – czyszczę całość"); + } + let mut w = vec![CLEAR_UAV_MARKER, float as u32]; + for v in [gpu, cpu, res as u64] { + w.extend([v as u32, (v >> 32) as u32]); + } + w.extend_from_slice(std::slice::from_raw_parts(values, 4)); + push(this as usize, &w); +} +unsafe extern "system" fn cl_clear_uav_uint(this: *mut c_void, gpu: u64, cpu: u64, res: usize, values: *const u32, rects: u32, _r: *const c_void) { + clear_uav(this, false, gpu, cpu, res, values, rects); +} +unsafe extern "system" fn cl_clear_uav_float(this: *mut c_void, gpu: u64, cpu: u64, res: usize, values: *const u32, rects: u32, _r: *const c_void) { + clear_uav(this, true, gpu, cpu, res, values, rects); +} +/// #85 CopyTextureRegion(dst location, x, y, z, src location, box) – 48-byte +/// D3D12_TEXTURE_COPY_LOCATION, 24-byte D3D12_BOX +unsafe extern "system" fn cl_copy_texture_region(this: *mut c_void, dst: *const [u32; 12], x: u32, y: u32, z: u32, src: *const [u32; 12], bx: *const [u32; 6]) { + let mut w = vec![COPY_TEXTURE_MARKER]; + w.extend_from_slice(&*dst); + w.extend([x, y, z]); + w.extend_from_slice(&*src); + w.push(!bx.is_null() as u32); + w.extend_from_slice(&bx.as_ref().copied().unwrap_or([0; 6])); + push(this as usize, &w); +} unsafe extern "system" fn cl_barrier(this: *mut c_void, _n: u32, _barriers: *const c_void) { push(this as usize, &[BARRIER_MARKER]); } @@ -425,6 +457,9 @@ fn list_vtable() -> usize { (25, cl_set_pipeline_state as usize), (26, cl_resource_barrier as usize), (32, cl_set_descriptor_heaps as usize), + (53, cl_clear_uav_uint as usize), + (54, cl_clear_uav_float as usize), + (85, cl_copy_texture_region as usize), (33, cl_set_compute_root_signature as usize), (37, cl_set_root_constant as usize), (39, cl_set_root_constants as usize), @@ -509,6 +544,10 @@ pub struct Translation { pub dispatches: u32, pub skipped_dispatches: u32, pub barriers: u32, + pub clears: u32, + pub copies: u32, + /// records whose resources / descriptors were not XCL's (skipped) + pub skipped: u32, pub unknown: Option<(u32, usize)>, } @@ -574,8 +613,55 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let (dst, src) = (q(0) as *mut c_void, q(2) as *mut c_void); if let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dst), ID3D12Resource::from_raw_borrowed(&src)) { list.CopyBufferRegion(d, q(1), s, q(3), q(4)); + out.copies += 1; + } else { + out.skipped += 1; } at += 11; + } else if w0 == CLEAR_UAV_MARKER { + let q = |k: usize| get(2 + 2 * k) as u64 | (get(3 + 2 * k) as u64) << 32; + let values = [get(8), get(9), get(10), get(11)]; + let res = q(2) as *mut c_void; + let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); + match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { + (Some(g), Some(c), Some(r)) if g.pc_gpu_uav != 0 => { + let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); + if get(1) != 0 { + let f = values.map(f32::from_bits); + list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + } else { + list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + } + out.clears += 1; + } + _ => out.skipped += 1, + } + at += 12; + } else if w0 == COPY_TEXTURE_MARKER { + // aligned copies of the two 48-byte locations and the box (borrowed pointers) + let loc = |from: usize| -> [u64; 6] { + let mut b = [0u64; 6]; + let src = &words[(at + from).min(words.len())..(at + from + 12).min(words.len())]; + std::ptr::copy_nonoverlapping(src.as_ptr() as *const u8, b.as_mut_ptr() as *mut u8, 4 * src.len()); + b + }; + let (dst, src) = (loc(1), loc(16)); + let bx: [u32; 6] = [get(29), get(30), get(31), get(32), get(33), get(34)]; + let (pd, ps) = (dst[0] as *mut c_void, src[0] as *mut c_void); + if ID3D12Resource::from_raw_borrowed(&pd).is_some() && ID3D12Resource::from_raw_borrowed(&ps).is_some() { + list.CopyTextureRegion( + dst.as_ptr() as *const D3D12_TEXTURE_COPY_LOCATION, + get(13), + get(14), + get(15), + src.as_ptr() as *const D3D12_TEXTURE_COPY_LOCATION, + if get(28) != 0 { Some(bx.as_ptr() as *const D3D12_BOX) } else { None }, + ); + out.copies += 1; + } else { + out.skipped += 1; + } + at += 35; } else if w0 == BARRIER_MARKER { list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -649,7 +735,15 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } drop(guard); if std::env::var_os("XCL_CONSOLE_LISTS_LOG").is_some() { - crate::xlog_info!("lista konsoli: {} dispatchy, {} pominiętych (PSO bez tłumaczenia), {} barier", out.dispatches, out.skipped_dispatches, out.barriers); + crate::xlog_info!( + "lista konsoli: {} dispatchy, {} pominiętych (PSO bez tłumaczenia), {} barier, {} czyszczeń, {} kopii, {} pominiętych rekordów", + out.dispatches, + out.skipped_dispatches, + out.barriers, + out.clears, + out.copies, + out.skipped + ); } if let Some((w, at)) = out.unknown { crate::xlog_warn!("lista konsoli: nieznany rekord {w:#010x} (słowo {at}) – reszta pominięta"); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fae2510..3a9a8b3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -18,7 +18,7 @@ #![allow(non_snake_case)] -use std::collections::{BTreeSet, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; @@ -152,6 +152,20 @@ pub fn abi_root_signature() -> Option { /// UMA as one D3D12 buffer (placed in a heap opened over the process memory): the `mem` /// of recompiled shaders. Kept for the process lifetime. static UMA_BUFFER: Mutex> = Mutex::new(None); +/// the unified memory opened as a D3D12 heap (console buffers are placed in it) +static UMA_HEAP: AtomicU64 = AtomicU64::new(0); +/// console buffers placed in unified memory: resource → (address, bytes) +static UMA_BUFFERS: Mutex>> = Mutex::new(None); + +/// Where a console-created buffer lives in unified memory (its console GPU address). +pub fn console_buffer(res: usize) -> Option<(usize, usize)> { + UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).copied() +} + +/// Number of live console buffers in unified memory. +pub fn console_buffers() -> usize { + UMA_BUFFERS.lock().unwrap().as_ref().map_or(0, |m| m.len()) +} static UMA_ERROR: Mutex = Mutex::new(String::new()); /// GPU virtual address of the unified memory buffer (0: not available). @@ -182,7 +196,7 @@ unsafe fn open_uma(device: &ID3D12Device) { device.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; let buf = buf.ok_or("CreatePlacedResource")?; let va = buf.GetGPUVirtualAddress(); - std::mem::forget(heap); + UMA_HEAP.store(heap.into_raw() as u64, Ordering::Release); Ok((buf.into_raw() as usize, va)) })(); match r { @@ -453,6 +467,8 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { /// riid, ppv) as on PC #27 (PC #76 = CreateCommittedResource3); the console resource desc /// carries more after the 52 PC bytes (amd_fidelityfx_upscaler_xbox.dll writes 3 at +52). /// * descriptor heap #9 / #10: the heap start handles come back in rax on the console. +/// * resource #11 GetGPUVirtualAddress: console buffers live in unified memory; their console +/// address (= CPU address, low 32 bits = offset in `mem`) is what console code gets. /// * device #14 / #15 / #18 / #19 (CreateDescriptorHeap, GetDescriptorHandleIncrementSize, /// CreateShaderResourceView, CreateUnorderedAccessView): CBV/SRV/UAV heaps of console code /// get 32-byte slots in unified memory (`console_heap`). @@ -475,6 +491,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { v } 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)], _ => vec![], } } @@ -514,8 +531,9 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: let heap = ID3D12DescriptorHeap::from_raw_borrowed(&raw).unwrap(); let dev = ID3D12Device::from_raw_borrowed(&this).unwrap(); let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let gpu = if d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0 { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - if !super::console_heap::register(raw as usize, d[1], cpu, inc) { + if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc) { crate::xlog_warn!("sterta deskryptorów konsoli: brak miejsca w UMA na {} slotów", d[1]); } } @@ -582,6 +600,97 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +/// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: +/// stride = element size, num_records in elements); empty when the buffer is not in UMA. +fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { + let Some((at, bytes)) = console_buffer(res) else { + note_buffer_view(); + return [0; 4]; + }; + let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); + let (stride, elem) = if raw { + (0, 4) + } else if stride > 0 { + (stride, stride) + } else { + let e = crate::gpu::desc::format_bytes(fmt); + (e, e) + }; + let base = at as u64 + first * elem as u64; + let room = (bytes as u64).saturating_sub(first * elem as u64); + let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + crate::gpu::desc::buffer_words(base, stride, records as u32, fmt) +} + +/// Console buffer → a placed resource in the unified memory heap, so its console address is +/// what the recompiled shaders read through `mem`. None: not placed (fall back to committed). +unsafe fn place_console_buffer(this: *mut c_void, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + let heap = UMA_HEAP.load(Ordering::Acquire) as usize; + let u = crate::gpu::uma::get()?; + if heap == 0 || ppv.is_null() { + return None; + } + let mut d: D3D12_RESOURCE_DESC = std::ptr::read(desc as *const D3D12_RESOURCE_DESC); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.Width == 0 { + return None; + } + // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + this flag + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Alignment = 0; + let bytes = d.Width as usize; + let p = u.alloc((bytes + 0xFFFF) & !0xFFFF, 0x1_0000)? as usize; + let hr = dev_create_placed_resource(this, heap, p - u.base(), &d as *const _ as usize, state, clear, riid, ppv); + if hr < 0 || (*ppv).is_null() { + u.free(p); + static ONCE: AtomicU64 = AtomicU64::new(0); + if ONCE.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_warn!("bufor konsoli w UMA: CreatePlacedResource {hr:#x} – zostaje zasób osobny (shader go nie zobaczy)"); + } + return None; + } + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes)); + // Map must hand out the same memory the shaders read (checked once) + static CHECKED: AtomicU64 = AtomicU64::new(0); + if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { + let raw = *ppv; + if let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) { + let mut m: *mut c_void = std::ptr::null_mut(); + if r.Map(0, None, Some(&mut m)).is_ok() { + r.Unmap(0, None); + if m as usize != p { + crate::xlog_warn!("bufor konsoli w UMA: Map zwraca {m:?}, a nie {p:#x} – zapisy CPU nie trafią pod adres konsoli"); + } else { + crate::xlog_info!("bufory konsoli w UMA: Map = adres konsoli ({p:#x})"); + } + } + } + } + Some(hr) +} + +/// resource Release (every caller): a console buffer's unified memory goes with it +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 { + let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); + if let (Some((p, _)), Some(u)) = (gone, crate::gpu::uma::get()) { + u.free(p); + } + } + n +} + +/// resource #11 GetGPUVirtualAddress for console code +unsafe extern "system" fn res_gpu_va_x(this: *mut c_void) -> u64 { + if let Some((p, _)) = console_buffer(this as usize) { + return p as u64; + } + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, 11)); + f(this) +} + fn note_buffer_view() { if NON_UMA_BUFFER_VIEWS.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_warn!("widok bufora w stercie konsoli: bufor nie jest w UMA – shader dostanie pusty V# (num_records 0)"); @@ -595,6 +704,11 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { return super::console_heap::write(&slot, &[0; 8]); }; + if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + let b = &v.Anonymous.Buffer; + let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + } let (format, dim, array, mips) = match desc.as_ref() { Some(v) => { let a = &v.Anonymous; @@ -632,6 +746,11 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, return super::console_heap::write(&slot, &[0; 8]); }; let rd = r.GetDesc(); + if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + let b = &v.Anonymous.Buffer; + let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d let (format, dim, array, mip) = match desc.as_ref() { Some(v) => { @@ -696,6 +815,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro desc = pc_desc.as_ptr() as usize; } } + if desc != 0 { + if let Some(hr) = place_console_buffer(this, desc, state, clear, riid, ppv) { + return hr; + } + } let hr = dev_create_committed_resource(this, props, flags, desc, state, clear, riid, ppv); if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; @@ -763,6 +887,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::CommandList => v.push(("OMSetRenderTargets", cl_om_set_render_targets 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)), _ => {} } v diff --git a/crates/xcl/tests/console_dlls_e2e.rs b/crates/xcl/tests/console_dlls_e2e.rs index d7acdc7..5945d58 100644 --- a/crates/xcl/tests/console_dlls_e2e.rs +++ b/crates/xcl/tests/console_dlls_e2e.rs @@ -971,6 +971,8 @@ fn fsr4_console_upscaler_creates_a_context_probe() { let words = console_list::recorded_words(console); let mut tables = 0; let mut formats = std::collections::BTreeSet::new(); + let (mut buffers, mut buffers_in_uma) = (0, 0); + let uma = xcl::gpu::uma::get().unwrap(); for &w in &words { if console_heap::words_at(w).is_none() { continue; @@ -981,11 +983,24 @@ fn fsr4_console_upscaler_creates_a_context_probe() { if d[3] >> 28 == 9 { assert_eq!(d[0] % 2, 0, "słowo 0 = indeks SRV w stercie PC (parzysty)"); formats.insert((d[1] >> 20) & 0x1FF); + } else if d[3] & 0xFFF == 0xFAC && d[3] >> 30 == 0 { + // V#: base address in UMA, num_records set + buffers += 1; + let a = d[0] as usize | ((d[1] & 0xFFFF) as usize) << 32; + if uma.contains(a) && d[2] != 0 { + buffers_in_uma += 1; + } } } } } - println!("strumień FSR: {} słów, {tables} wskaźników tabel, formaty obrazów 2D w tabelach: {formats:?}", words.len()); + println!( + "strumień FSR: {} słów, {tables} wskaźników tabel, formaty obrazów 2D w tabelach: {formats:?}, V# w tabelach: {buffers} (w UMA: {buffers_in_uma}), bufory konsoli w UMA: {}", + words.len(), + xcl::hle::d3d12x::real::console_buffers() + ); + assert!(xcl::hle::d3d12x::real::console_buffers() > 0, "bufory FSR w UMA"); + assert_eq!(buffers, buffers_in_uma, "każdy V# w tabelach wskazuje bufor w UMA"); assert!(tables > 0); for f in [71, 22, 29] { assert!(formats.contains(&f), "format {f} (wejście FSR) w tabelach"); @@ -993,5 +1008,6 @@ fn fsr4_console_upscaler_creates_a_context_probe() { let t = console_list::close(console).unwrap(); println!("lista konsoli → PC: {t:?}"); assert!(t.unknown.is_none(), "wszystkie rekordy FSR rozpoznane"); + assert!(t.clears > 0 && t.copies > 0 && t.skipped == 0, "czyszczenia UAV i kopie przełożone na PC"); } } diff --git a/tests/testtitle/src/audio.rs b/tests/testtitle/src/audio.rs index 0ecbc2f..a3f34e0 100644 --- a/tests/testtitle/src/audio.rs +++ b/tests/testtitle/src/audio.rs @@ -238,8 +238,9 @@ pub fn xaudio2_console_voices() -> Result<(), String> { return Err("OnVoiceError".into()); } // the XMA2 buffer (PlayLength 4800 = 0.1 s) must take as long as the title expects + // (± one 10 ms engine quantum: the clock starts mid-quantum; 79 ms was seen) let ms = XMA_END_MS.load(Ordering::SeqCst); - if !(80..=2000).contains(&ms) { + if !(70..=2000).contains(&ms) { return Err(format!("XMA2 buffer ended after {ms} ms (expected ≈100)")); } println!(" (bufor XMA2 skończył się po {ms} ms)"); diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index b46f9ca..5c40b99 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -269,7 +269,10 @@ pub fn render_triangle() -> Result<(), String> { let heap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) .map_err(e)?; - let rtv = heap.GetCPUDescriptorHandleForHeapStart(); + // D3D12.X: the heap start handle comes back in rax (the PC method returns it through + // a hidden pointer) – console code calls slot 9 like this + let start: unsafe extern "system" fn(*mut c_void) -> usize = transmute_copy(&(*(*(heap.as_raw() as *const *const usize)).add(9))); + let rtv = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start(heap.as_raw()) }; dev.CreateRenderTargetView(&rt, None, rtv); let mut layout = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();