From fddfa2675a3ffc722a7a0dcf2ed8da1938b97713 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:19:24 -0800 Subject: [PATCH 1/2] Tiling: detile_level copies contiguous runs (16 B in swizzled modes) in one go RGBA8 2048x2048 on the console pipe config: 22 ms -> 10 ms; BC 8/16 B ~10%. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/tiling.rs | 62 ++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index e91d2ba89..3aade898c 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -152,6 +152,22 @@ impl Layout { } } + /// Elements in a row that lie next to each other in memory, in aligned groups: x bits below + /// `log2(run)` give the low address bits directly (`x << elem_log2`) and no other coordinate + /// or swizzle touches those bits, so `run` elements from an aligned x are one copy. + pub fn run(&self) -> usize { + let mut r = 1; + while r * 2 <= self.block_w && self.ox[r] == (r << self.elem_log2) as u32 { + let mask = ((2 * r) << self.elem_log2) as u32 - 1; + let aligned = self.ox.iter().step_by(2 * r).chain(&self.oy).chain(&self.oz).chain(&self.hx).chain(&self.hy).chain(&self.hz); + if self.base_xor as u32 & mask != 0 || aligned.clone().any(|&v| v & mask != 0) { + break; + } + r *= 2; + } + r + } + /// surface `w` × `h` elements: (blocks per row, blocks per column) pub fn blocks(&self, w: usize, h: usize) -> (usize, usize) { (w.div_ceil(self.block_w), h.div_ceil(self.block_h)) @@ -428,14 +444,24 @@ impl Chain { }) .collect(); let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d); + let run = if l.origin.0 % t.run() == 0 { t.run() } else { 1 }; for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() { let y = y + l.origin.1; let row_blocks = (y / t.block_h) * pitch_blocks; let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z; - for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) { - let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); - if let Some(s) = src.get(o..o + e) { + // `run` neighbouring elements from an aligned x are contiguous (16 B in the swizzled + // modes): one copy each, element by element only where a run leaves `src` + for (cols, dst) in columns.chunks(run).zip(row.chunks_mut(run * e)) { + let o = l.offset + (row_blocks + cols[0].0) * t.block_bytes + ((cols[0].1 ^ yz) as usize ^ t.base_xor); + if let Some(s) = src.get(o..o + dst.len()) { dst.copy_from_slice(s); + continue; + } + for (&(block_x, x), dst) in cols.iter().zip(dst.chunks_exact_mut(e)) { + let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); + if let Some(s) = src.get(o..o + e) { + dst.copy_from_slice(s); + } } } } @@ -468,6 +494,36 @@ pub fn image_chain(t: &super::desc::Image, cfg: PipeConfig) -> Option { #[cfg(test)] mod tests { + /// `detile_level` copies contiguous runs: the same bytes as element by element, for every + /// mode, element size, pipe config and mip, also when `src` ends inside the level + #[test] + fn detile_level_runs_match_elements() { + for cfg in [crate::gpu::texture::CONSOLE_PIPES, crate::gpu::texture::SERIES_S_PIPES, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }] { + for mode in 0..32 { + for e in 0..5 { + let Some(layout) = Layout::new(mode, e, cfg) else { continue }; + let c = Chain::new(layout, 300, 77, 2, 7); + let bytes: Vec = (0..c.slice_bytes as u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); + for i in 0..c.levels.len() { + let l = c.levels[i]; + for src in [&bytes[..], &bytes[..bytes.len() * 2 / 3]] { + let mut want = vec![0u8; l.width * l.height << e]; + for y in 0..l.height { + for x in 0..l.width { + let o = c.element_at(&l, x, y, 1); + if let Some(s) = src.get(o..o + (1 << e)) { + want[(y * l.width + x) << e..][..1 << e].copy_from_slice(s); + } + } + } + assert!(c.detile_level(src, i, 1) == want, "mode {mode} elem {e} level {i} src {}", src.len()); + } + } + } + } + } + } + use super::*; const MODES: [u32; 14] = [1, 2, 5, 6, 9, 10, 17, 18, 21, 22, 24, 25, 26, 27]; From 82bd5bc89e9388b2d5540f9c1354f73d8bc656a2 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:36:34 -0800 Subject: [PATCH 2/2] D3D12.X: title textures are detiled on the GPU The tiled bytes and the layout's tables (only the entries the texture reaches) go to the upload buffer as they are; a compute shader (detile_gpu, DXC cs_6_0, root constants + root SRV/UAV) writes each subresource's rows into the uploader's scratch UAV buffer at its GetCopyableFootprints place, and the copies into the texture read from there. Same formula as Layout::offset_z, out-of-range reads as 0. CPU path kept: XCL_GPU_DETILE=0, no DXC or pipeline, a texture the plan cannot take, and frame tracing. Test: gpu_detile_matches_the_cpu - 78 textures (every 2D mode x element size, mips, 2 slices, tiled bytes cut short, 3D) read back identical to the CPU detile. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/detile_gpu.rs | 273 ++++++++++++++++++++ crates/xcl/src/gpu/mod.rs | 1 + crates/xcl/src/gpu/texture.rs | 195 ++++++++++++-- crates/xcl/src/gpu/tiling.rs | 6 + crates/xcl/src/hle/d3d12x/title_textures.rs | 42 ++- 5 files changed, 494 insertions(+), 23 deletions(-) create mode 100644 crates/xcl/src/gpu/detile_gpu.rs diff --git a/crates/xcl/src/gpu/detile_gpu.rs b/crates/xcl/src/gpu/detile_gpu.rs new file mode 100644 index 000000000..0d3c97bf7 --- /dev/null +++ b/crates/xcl/src/gpu/detile_gpu.rs @@ -0,0 +1,273 @@ +//! Console texture detiling on the GPU: a title texture's tiled bytes go to the upload buffer +//! as they are (one copy) and a compute shader writes its subresources as linear rows into a +//! scratch buffer at their `GetCopyableFootprints` places; the copies into the texture read +//! from there. The CPU did it element by element (`Chain::detile_level`) – most of a retail +//! game's render thread while it streamed textures. The same formula as `Layout::offset_z`. +//! `XCL_GPU_DETILE=0` keeps the CPU path, which is also taken when DXC or the pipeline is +//! missing and for textures the plan cannot take. + +use super::tiling::{Chain, MipLevel}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use windows::Win32::Graphics::Direct3D12::*; + +/// One subresource's detile: the shader's root constants, in its cbuffer order. `src_off` is +/// from the start of the texture's bytes and the `t_*` from the start of its tables until +/// `upload_batch` places them; `dst_*` are filled there from the footprints. +#[repr(C)] +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub struct Params { + pub src_off: u32, + pub src_len: u32, + pub lvl_off: u32, + pub pitch_blocks: u32, + pub ox0: u32, + pub oy0: u32, + pub width: u32, + pub height: u32, + pub bw_log2: u32, + pub bh_log2: u32, + pub bd_log2: u32, + pub block_bytes: u32, + pub base_xor: u32, + pub e_log2: u32, + pub t_ox: u32, + pub t_oy: u32, + pub t_oz: u32, + pub t_hx: u32, + pub t_hy: u32, + pub t_hz: u32, + pub m_hx: u32, + pub m_hy: u32, + pub m_hz: u32, + pub z0: u32, + pub zstride: u32, + pub dst_off: u32, + pub row_pitch: u32, + pub slice_pitch: u32, + pub row_dwords: u32, + pub depth: u32, +} + +pub const PARAMS: u32 = (std::mem::size_of::() / 4) as u32; + +/// A texture to detile on the GPU: its tiled bytes, the tables its subresources index (only +/// the entries its extent reaches) and one `Params` per subresource (D3D12 order). +pub struct Tiled { + pub raw: Vec, + pub tables: Vec, + pub subs: Vec, +} + +const HLSL: &str = r#" +ByteAddressBuffer Src : register(t0); +ByteAddressBuffer Tab : register(t1); +RWByteAddressBuffer Dst : register(u0); +cbuffer P : register(b0) { + uint src_off, src_len, lvl_off, pitch_blocks, ox0, oy0, width, height, bw_log2, bh_log2, bd_log2, + block_bytes, base_xor, e_log2, t_ox, t_oy, t_oz, t_hx, t_hy, t_hz, m_hx, m_hy, m_hz, z0, zstride, + dst_off, row_pitch, slice_pitch, row_dwords, depth; +}; +uint tab(uint i) { return Tab.Load(i * 4); } +uint tiled(uint x, uint y, uint z) { + x += ox0; + y += oy0; + uint block = (y >> bh_log2) * pitch_blocks + (x >> bw_log2); + uint xr = tab(t_ox + (x & ((1u << bw_log2) - 1))) ^ tab(t_oy + (y & ((1u << bh_log2) - 1))) ^ tab(t_oz + (z & ((1u << bd_log2) - 1))) + ^ tab(t_hx + ((x >> bw_log2) & m_hx)) ^ tab(t_hy + ((y >> bh_log2) & m_hy)) ^ tab(t_hz + ((z >> bd_log2) & m_hz)); + return (z >> bd_log2) * zstride + lvl_off + block * block_bytes + (xr ^ base_xor); +} +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= row_dwords) return; + uint z = z0 + id.z; + uint e = 1u << e_log2; + uint b0 = id.x * 4; + uint v = 0; + if (e_log2 >= 2) { + uint o = tiled(b0 >> e_log2, id.y, z); + if (o + e <= src_len) v = Src.Load(src_off + o + (b0 & (e - 1))); + } else { + for (uint k = 0; k < 4; k++) { + uint el = (b0 + k) >> e_log2; + if (el >= width) break; + uint o = tiled(el, id.y, z); + if (o + e <= src_len) { + uint a = src_off + o + ((b0 + k) & (e - 1)); + v |= ((Src.Load(a & ~3u) >> ((a & 3) * 8)) & 0xff) << (k * 8); + } + } + } + Dst.Store(dst_off + id.z * slice_pitch + id.y * row_pitch + b0, v); +} +"#; + +/// The plan of detiling a texture (`raw` = its bytes, all slices) of `array` slices (or a +/// volume when `volume`) with elements of `bpe` bytes; `None` when the GPU path cannot take it +/// (the CPU path does). +pub fn plan(c: &Chain, bpe: usize, array: usize, volume: bool, raw: Vec) -> Option { + let t = &c.layout; + let e = 1usize << t.elem_log2; + if e != bpe || raw.len() >= 1 << 31 || c.levels.is_empty() { + return None; + } + let log2 = |n: usize| n.is_power_of_two().then_some(n.trailing_zeros()); + let (bw, bh, bd) = (log2(t.block_w)?, log2(t.block_h)?, log2(t.block_d)?); + // element loads are whole dwords from 4 B elements up: their offsets must stay aligned + if e >= 4 && (t.base_xor | c.slice_bytes | c.levels.iter().fold(0, |a, l| a | l.offset)) & 3 != 0 { + return None; + } + // the tables, the high ones only as far as this texture reaches + let max_x = c.levels.iter().map(|l| l.origin.0 + l.width).max()?.max(1); + let max_y = c.levels.iter().map(|l| l.origin.1 + l.height).max()?.max(1); + let max_z = if volume { c.levels[0].depth } else { array }.max(1); + let all = t.tables(); + let reach = |k: usize, max: usize, l2: u32| all[k].len().min(((max - 1) >> l2) + 1); + let lens = [all[0].len(), all[1].len(), all[2].len(), reach(3, max_x, bw), reach(4, max_y, bh), reach(5, max_z, bd)]; + let mut tables = Vec::new(); + let mut at = [0u32; 6]; + for (k, tab) in all.iter().enumerate() { + if !tab.len().is_power_of_two() { + return None; + } + at[k] = tables.len() as u32; + tables.extend_from_slice(&tab[..lens[k]]); + } + let mask = |k: usize| all[k].len() as u32 - 1; + let level = |l: &MipLevel| Params { + lvl_off: l.offset as u32, + pitch_blocks: l.pitch.div_ceil(t.block_w) as u32, + ox0: l.origin.0 as u32, + oy0: l.origin.1 as u32, + width: l.width as u32, + height: l.height as u32, + bw_log2: bw, + bh_log2: bh, + bd_log2: bd, + block_bytes: t.block_bytes as u32, + base_xor: t.base_xor as u32, + e_log2: t.elem_log2, + t_ox: at[0], + t_oy: at[1], + t_oz: at[2], + t_hx: at[3], + t_hy: at[4], + t_hz: at[5], + m_hx: mask(3), + m_hy: mask(4), + m_hz: mask(5), + row_dwords: (l.width * e).div_ceil(4) as u32, + ..Default::default() + }; + let mut subs = Vec::new(); + if volume { + for l in &c.levels { + subs.push(Params { src_off: 0, src_len: raw.len() as u32, z0: 0, zstride: c.slice_bytes as u32, depth: l.depth as u32, ..level(l) }); + } + } else { + for s in 0..array { + let src_off = s * c.slice_bytes; + let src_len = c.slice_bytes.min(raw.len().saturating_sub(src_off)); + for l in &c.levels { + subs.push(Params { src_off: src_off as u32, src_len: src_len as u32, z0: s as u32, zstride: 0, depth: 1, ..level(l) }); + } + } + } + Some(Tiled { raw, tables, subs }) +} + +pub struct Pipe { + pub root: ID3D12RootSignature, + pub pso: ID3D12PipelineState, +} + +// D3D12 objects are free-threaded +unsafe impl Send for Pipe {} +unsafe impl Sync for Pipe {} + +/// device (raw pointer) → its detile pipeline, or `None` when it could not be made +static PIPES: Mutex>>>> = Mutex::new(None); + +/// GPU detiling is on (`XCL_GPU_DETILE`, default on) +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_DETILE").map_or(true, |v| v != "0")) +} + +/// The detile pipeline of `dev`, made once; `None` when GPU detiling is off or failed. +pub unsafe fn pipe(dev: &ID3D12Device) -> Option> { + if !enabled() { + return None; + } + let key = windows::core::Interface::as_raw(dev) as usize; + let mut m = PIPES.lock().unwrap(); + let m = m.get_or_insert_with(Default::default); + if let Some(p) = m.get(&key) { + return p.clone(); + } + let made = make_pipe(dev); + match &made { + Ok(_) => crate::xlog_info!("title textures: detiled on the GPU (XCL_GPU_DETILE=0: on the CPU)"), + Err(e) => crate::xlog_warn!("title textures: GPU detiling unavailable, detiled on the CPU: {e}"), + } + let p = made.ok().map(Arc::new); + m.insert(key, p.clone()); + p +} + +unsafe fn make_pipe(dev: &ID3D12Device) -> Result { + let (dxil, _) = super::recomp::dxc::compile_cached(HLSL, "main", "cs_6_0")?; + let descriptor = |register| D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: register, RegisterSpace: 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: PARAMS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, Anonymous: descriptor(0), ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }, + D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, Anonymous: descriptor(1), ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }, + D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: descriptor(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!("root signature: {e}"))?; + let blob = blob.ok_or("root signature: no blob")?; + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()); + let root: ID3D12RootSignature = dev.CreateRootSignature(0, bytes).map_err(|e| format!("root signature: {e}"))?; + let pd = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pd).map_err(|e| format!("pipeline: {e}"))?; + Ok(Pipe { root, pso }) +} + +/// Record the detiles of `t` (its bytes at `raw_at`, its tables at u32 index `tab_at` of the +/// buffer `src` at `src_va`) into the scratch buffer `dst_va`, its subresources at `fps` + +/// `dst_base` with `nrows` rows each. The pipeline and root signature are set by the caller. +pub unsafe fn record(list: &ID3D12GraphicsCommandList, t: &Tiled, raw_at: u32, tab_at: u32, fps: &[D3D12_PLACED_SUBRESOURCE_FOOTPRINT], nrows: &[u32], dst_base: u64) { + for ((p, fp), &rows) in t.subs.iter().zip(fps).zip(nrows) { + let pitch = fp.Footprint.RowPitch; + let p = Params { + src_off: p.src_off + raw_at, + t_ox: p.t_ox + tab_at, + t_oy: p.t_oy + tab_at, + t_oz: p.t_oz + tab_at, + t_hx: p.t_hx + tab_at, + t_hy: p.t_hy + tab_at, + t_hz: p.t_hz + tab_at, + dst_off: (dst_base + fp.Offset) as u32, + row_pitch: pitch, + slice_pitch: pitch * rows, + ..*p + }; + let height = p.height.min(rows); + let depth = p.depth.min(fp.Footprint.Depth); + if p.row_dwords == 0 || height == 0 || depth == 0 { + continue; + } + list.SetComputeRoot32BitConstants(0, PARAMS, &p as *const Params as *const _, 0); + list.Dispatch(p.row_dwords.div_ceil(64), height, depth); + } +} diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 06ebeedc0..d6858e9d9 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -5,6 +5,7 @@ pub mod adapter; pub mod agility; pub mod bvh; pub mod desc; +pub mod detile_gpu; pub mod dxbc; pub(crate) mod fence; pub mod pack; diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 5d6026d6e..43c5b9df5 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -213,6 +213,8 @@ struct Uploader { value: u64, /// (buffer, its mapped bytes, capacity) staging: Option<(ID3D12Resource, *mut u8, u64)>, + /// (default-heap UAV buffer the GPU detiles into, capacity) + scratch: Option<(ID3D12Resource, u64)>, } // D3D12 objects are free-threaded; the mapped pointer is only used by the holder of the uploader @@ -231,7 +233,7 @@ impl Uploader { let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; list.Close().map_err(err)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; - Ok(Uploader { alloc, list, fence, value: 0, staging: None }) + Ok(Uploader { alloc, list, fence, value: 0, staging: None, scratch: None }) } /// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one. @@ -248,6 +250,33 @@ impl Uploader { self.staging = Some((b.clone(), p as *mut u8, cap)); Ok((b, p as *mut u8)) } + + /// A default-heap buffer the GPU can write (UAV) of at least `bytes`: the one kept, or a + /// bigger one. It is in the common state between batches. + unsafe fn scratch(&mut self, dev: &ID3D12Device, bytes: u64) -> Result { + if let Some((b, cap)) = &self.scratch { + if *cap >= bytes { + return Ok(b.clone()); + } + } + let cap = bytes.max(STAGING_MIN).next_power_of_two(); + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: cap, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + 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, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut r).map_err(err)?; + let b = r.ok_or("scratch buffer: none made")?; + self.scratch = Some((b.clone(), cap)); + Ok(b) + } } /// Several uploads on one list, one wait: (resource, subresources, states) each – the states @@ -255,6 +284,19 @@ impl Uploader { /// order). A failure of one is returned with its index; the others still run. The texels go /// through the queue's kept upload buffer (`Uploader`). pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + let items: Vec = items.iter().map(|(r, subs, states)| (r, subs.as_slice(), states.as_slice(), None)).collect(); + upload_batch_with(dev, queue, &items) +} + +/// One texture of `upload_batch_with`: (resource, subresources, states, its tiled bytes to +/// detile on the GPU – then the subresources give only their sizes, no data). +pub type BatchItem<'a> = (&'a ID3D12Resource, &'a [Subresource], &'a [D3D12_RESOURCE_STATES], Option<&'a super::detile_gpu::Tiled>); + +/// `upload_batch` where textures may come tiled (`BatchItem`): their bytes and tables go to the +/// upload buffer as they are, a compute pass (`detile_gpu`) writes their rows into the +/// uploader's scratch buffer and their copies read from there. A tiled texture without the +/// device's detile pipeline fails (the caller asks `detile_gpu::pipe` first). +pub unsafe fn upload_batch_with(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[BatchItem]) -> Result, String> { if items.is_empty() { return Ok(Vec::new()); } @@ -266,15 +308,31 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items }; // where each texture's texels go in the upload buffer let mut failed = Vec::new(); + // (item, layout, base in the upload buffer (rows) or in the scratch buffer (tiled), where a + // tiled one's bytes and tables are in the upload buffer) let mut planned = Vec::with_capacity(items.len()); let mut total = 0u64; - for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } + let mut scratch_total = 0u64; + let pipe = if items.iter().any(|i| i.3.is_some()) { super::detile_gpu::pipe(dev) } else { None }; + for (k, (res, subs, states, tiled)) in items.iter().enumerate() { + match layout(dev, res, subs, states, states, tiled.is_none()) { + Ok(_) if tiled.is_some() && pipe.is_none() => failed.push((k, "no GPU detile pipeline".to_string())), + Ok(l) => match tiled { + None => { + let base = total.div_ceil(PLACEMENT) * PLACEMENT; + total = base + l.total; + planned.push((k, l, base, (0, 0))); + } + Some(t) => { + let base = scratch_total.div_ceil(PLACEMENT) * PLACEMENT; + // a row's last dword may run up to 3 B past its bytes + scratch_total = base + l.total + 4; + let raw_at = total.div_ceil(256) * 256; + let tab_at = (raw_at + t.raw.len() as u64).div_ceil(256) * 256; + total = tab_at + 4 * t.tables.len() as u64; + planned.push((k, l, base, (raw_at, tab_at))); + } + }, Err(e) => failed.push((k, e)), } } @@ -282,12 +340,40 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items put_back(key, up); return Ok(failed); } + if total >= 1 << 32 || scratch_total >= 1 << 32 { + put_back(key, up); + return Err(format!("texture batch too big for one upload ({total} B, {scratch_total} B detiled)")); + } let (staging, mapped) = up.staging(dev, total)?; + let scratch = if scratch_total > 0 { Some(up.scratch(dev, scratch_total)?) } else { None }; up.alloc.Reset().map_err(err)?; up.list.Reset(&up.alloc, None).map_err(err)?; - for (k, l, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base); + if let (Some(scratch), Some(pipe)) = (&scratch, &pipe) { + // the tiled textures: bytes and tables into the upload buffer, then one compute pass + let list = &up.list; + list.SetComputeRootSignature(&pipe.root); + list.SetPipelineState(&pipe.pso); + list.SetComputeRootShaderResourceView(1, staging.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(2, staging.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, scratch.GetGPUVirtualAddress()); + list.ResourceBarrier(&[transition(scratch, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + for (k, l, base, (raw_at, tab_at)) in &planned { + let Some(t) = items[*k].3 else { continue }; + std::ptr::copy_nonoverlapping(t.raw.as_ptr(), mapped.add(*raw_at as usize), t.raw.len()); + std::ptr::copy_nonoverlapping(t.tables.as_ptr() as *const u8, mapped.add(*tab_at as usize), 4 * t.tables.len()); + super::detile_gpu::record(list, t, *raw_at as u32, (*tab_at / 4) as u32, &l.fps, &l.rows, *base); + } + list.ResourceBarrier(&[transition(scratch, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + } + for (k, l, base, _) in &planned { + let (res, subs, states, tiled) = &items[*k]; + match (tiled, &scratch) { + (Some(_), Some(scratch)) => record_copies(&up.list, res, l, states, states, scratch, *base), + _ => record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base), + } + } + if let Some(scratch) = &scratch { + up.list.ResourceBarrier(&[transition(scratch, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); } up.list.Close().map_err(err)?; queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); @@ -325,7 +411,7 @@ pub unsafe fn record_upload_states( before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], ) -> Result { - let l = layout(dev, res, subs, before, after)?; + let l = layout(dev, res, subs, before, after, true)?; let up = buffer(dev, l.total)?; let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(err)?; @@ -343,8 +429,12 @@ struct Layout { } /// The `Layout` of uploading `subs` into `res`, checked against the resource. -unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result { - validate_subresources(subs)?; +unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], with_data: bool) -> Result { + if with_data { + validate_subresources(subs)?; + } else if subs.is_empty() || subs.iter().any(|s| s.depth == 0 || s.rows == 0 || s.row_bytes == 0) { + return Err("texture upload without subresources, or one of zero size".into()); + } let rd = res.GetDesc(); let n = subs.len(); validate_subresource_count(&rd, n)?; @@ -374,7 +464,6 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], /// `res` on `list` (barriers from `before` and back to `after`). #[allow(clippy::too_many_arguments)] unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) { - let n = subs.len(); for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) { let pitch = fp.Footprint.RowPitch as usize; let row = s.row_bytes.min(pitch); @@ -387,6 +476,13 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su } } } + record_copies(list, res, l, before, after, up, base); +} + +/// Record the copies of `l`'s subresources from the buffer `src` (from `base`) into `res`, +/// with the barriers from `before` and back to `after`. +unsafe fn record_copies(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, base: u64) { + let n = l.fps.len(); let to_copy = transitions(res, before, &[D3D12_RESOURCE_STATE_COPY_DEST], n); if !to_copy.is_empty() { list.ResourceBarrier(&to_copy); @@ -738,6 +834,75 @@ mod tests { } } + /// GPU detiling (`detile_gpu`) writes the same texels as the CPU (`Chain::detile_level` / + /// `detile_volume`): every 2D mode and element size (mips, 2 array slices, odd sizes, the + /// tiled bytes cut short) and a 3D texture, uploaded in one batch and read back. + #[test] + fn gpu_detile_matches_the_cpu() { + let Some((dev, queue)) = device() else { + println!("no D3D12 device – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + unsafe { + if crate::gpu::detile_gpu::pipe(&dev).is_none() { + println!("no GPU detile pipeline (DXC?) – skipping"); + return; + } + let format = |e: u32| [DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32B32A32_UINT][e as usize]; + let make = |dim, w: usize, h: usize, d: usize, mips: usize, f| -> ID3D12Resource { + let rd = D3D12_RESOURCE_DESC { Dimension: dim, Width: w as u64, Height: h as u32, DepthOrArraySize: d as u16, MipLevels: mips as u16, Format: f, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, SHADER_READ, None, &mut r).unwrap(); + r.unwrap() + }; + let bytes = |n: usize, seed: u32| -> Vec { (0..n as u32).map(|i| (i.wrapping_add(seed).wrapping_mul(2654435761) >> 13) as u8).collect() }; + // (name, resource, CPU subresources, GPU plan) + let mut cases = Vec::new(); + let (w, h, mips) = (150usize, 37usize, 6usize); + for mode in 0..32 { + for e in 0..5u32 { + let Some(layout) = tiling::Layout::new(mode, e, CONSOLE_PIPES) else { continue }; + let c = Chain::new(layout, w as u32, h as u32, 1, mips as u32); + let mut raw = bytes(2 * c.slice_bytes, mode * 8 + e); + if mode % 3 == 1 { + raw.truncate(raw.len() * 3 / 4); + } + let mut want = Vec::new(); + for sl in 0..2 { + let at = (sl * c.slice_bytes).min(raw.len()); + let slice = &raw[at..(at + c.slice_bytes).min(raw.len())]; + for (i, l) in c.levels.iter().enumerate() { + want.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width << e, data: c.detile_level(slice, i, sl) }); + } + } + let Some(plan) = crate::gpu::detile_gpu::plan(&c, 1 << e, 2, false, raw) else { panic!("mode {mode} elem {e}: no plan") }; + cases.push((format!("2D mode {mode} elem {e}"), make(D3D12_RESOURCE_DIMENSION_TEXTURE2D, w, h, 2, mips, format(e)), want, plan)); + } + } + for mode in [25u32, 26, 9] { + let Some(layout) = tiling::Layout::new_3d(mode, 2, CONSOLE_PIPES) else { continue }; + let c = Chain::new_3d(layout, 40, 24, 12, 1, 3); + let raw = bytes(c.slice_bytes * c.layers(), mode); + let want = c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * 4, data: c.detile_volume(&raw, i) }).collect(); + let plan = crate::gpu::detile_gpu::plan(&c, 4, 1, true, raw).expect("3D plan"); + cases.push((format!("3D mode {mode}"), make(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 40, 24, 12, 3, DXGI_FORMAT_R32_UINT), want, plan)); + } + let dims: Vec> = cases.iter().map(|(_, _, want, _)| want.iter().map(|s| Subresource { depth: s.depth, rows: s.rows, row_bytes: s.row_bytes, data: Vec::new() }).collect()).collect(); + let states = [SHADER_READ]; + let items: Vec = cases.iter().zip(&dims).map(|((_, r, _, plan), d)| (r, d.as_slice(), &states[..], Some(plan))).collect(); + let failed = upload_batch_with(&dev, &queue, &items).unwrap(); + assert!(failed.is_empty(), "uploads failed: {failed:?}"); + for (name, r, want, _) in &cases { + let got = read_back(&dev, &queue, r, want); + for (k, (g, w)) in got.iter().zip(want).enumerate() { + assert!(g == w, "{name}: subresource {k} differs from the CPU detile"); + } + } + println!("GPU detile matched the CPU in {} textures", cases.len()); + } + } + /// Batches through one queue share its upload buffer (`Uploader`): two batches of three /// textures (mips, an odd size, BC7) each read back what was uploaded, and the second batch /// made no new upload buffer. diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index 3aade898c..49e6c0335 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -168,6 +168,12 @@ impl Layout { r } + /// The offset tables (ox, oy, oz, hx, hy, hz) for detiling elsewhere (the GPU, + /// `gpu::detile_gpu`): `offset_z` XORs them, the h tables indexed modulo their length. + pub fn tables(&self) -> [&[u32]; 6] { + [&self.ox, &self.oy, &self.oz, &self.hx, &self.hy, &self.hz] + } + /// surface `w` × `h` elements: (blocks per row, blocks per column) pub fn blocks(&self, w: usize, h: usize) -> (usize, usize) { (w.div_ceil(self.block_w), h.div_ceil(self.block_h)) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..ec20e3328 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -853,16 +853,28 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { bytes += tex.size() as usize; picked.push((r, va, tex, states)); } - let subs = subresources_of_all(&picked, bytes); + let d = device as *mut c_void; + let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; + // detiled on the GPU where the device has the pipeline and the texture fits the plan + // (not while tracing frames: that looks at the detiled bytes), the rest on the CPU + let gpu = !super::present::trace_frame() && crate::gpu::detile_gpu::pipe(dev).is_some(); + let tiled: Vec<_> = picked.iter().map(|(_, va, tex, _)| if gpu { plan_gpu(*va, tex) } else { None }).collect(); + let on_cpu: Vec<_> = picked.iter().zip(&tiled).filter(|(_, t)| t.is_none()).map(|(p, _)| p.clone()).collect(); + let cpu_bytes = on_cpu.iter().map(|p| p.2.size() as usize).sum(); + let mut cpu_subs = subresources_of_all(&on_cpu, cpu_bytes).into_iter(); let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { - if super::present::trace_frame() { - note_content(va, &r, &subs); + for ((r, va, _, states), t) in picked.into_iter().zip(tiled) { + match t { + Some((dims, t)) => batch.push((r, dims, states, Some(t))), + None => { + let subs = cpu_subs.next().unwrap_or_default(); + if super::present::trace_frame() { + note_content(va, &r, &subs); + } + batch.push((r, subs, states, None)); + } } - batch.push((r, subs, states)); } - let d = device as *mut c_void; - let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { @@ -872,7 +884,8 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { }; match own_work(|| { super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) + let items: Vec = batch.iter().map(|(r, subs, states, t)| (r, subs.as_slice(), states.as_slice(), t.as_ref())).collect(); + texture::upload_batch_with(dev, &queue, &items) }) { Ok(failed) => { for (_, e) in failed { @@ -1166,6 +1179,19 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> } } +/// The GPU detile of a texture at `va` (`detile_gpu::plan`) and its subresources' sizes (D3D12 +/// order, no data); `None`: detiled on the CPU (`subresources`). +unsafe fn plan_gpu(va: usize, tex: &xg::Texture) -> Option<(Vec, crate::gpu::detile_gpu::Tiled)> { + let tex = tex.texels()?; + let c = &tex.chain; + let bpe = tex.bpe as usize; + let volume = tex.depth > 0; + let array = if volume { 1 } else { tex.array as usize }; + let t = crate::gpu::detile_gpu::plan(c, bpe, array, volume, read_committed(va, tex.size() as usize))?; + let dims = (0..array).flat_map(|_| c.levels.iter().map(|l| Subresource { depth: if volume { l.depth } else { 1 }, rows: l.height, row_bytes: l.width * bpe, data: Vec::new() })).collect(); + Some((dims, t)) +} + /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() };