diff --git a/HANDOFF.md b/HANDOFF.md index fe2013e..e8bd210 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -628,6 +628,22 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD itself. BCPack (and other console formats) are refused; the unlisted interface slots are logged E_NOTIMPL. The test title reads the start of its own exe through it and waits on the fence. Not yet: cancelling submitted requests, multi-stage (intermediate-size) decompression, destinations that are not plain memory. +- **Texture layout library (`xg_xs.dll`, `hle/xg.rs`)** – Fortnite imports `XGCreateTextureComputer`. XCL's own GFX10 + model behind the console's interface, checked against the console's own library (`tests/xg_oracle.rs`, + `XCL_SAMPLE_XG` = the user's console `xg_xs.dll`, 10.0.22000; nothing of it is in the repo): + - 29 700 descs (15 formats, 15 sizes incl. odd ones, mip counts, arrays, every explicit mode, the library's own + choice for textures and UAVs): every XG_RESOURCE_LAYOUT byte the same or both refuse; texel offsets of every mode × + element size match (`texel_offsets_and_the_console_pipe_configuration`); 162 subresources tile to the same bytes. + - What it took (the console's rules, now in `gpu::tiling` – the TTPF retail check still fits 909 / 912): levels are + padded from mip 0 halved rounding up (also linear, and for the mip tail decision); Z modes of 1 / 2-byte elements + have a 64 × 128 tail; the XOR modes take pipe bits from coordinates above the block and from the array slice (z of + the 2D patterns) – `Layout` / `Chain::detile_level` / `tile_level` now have them. + - **The console's pipe configuration** (`texture::console_pipes`): 32 pipes / 8 packers by default (Series X), + 8 / 4 with XGSetHardwareVersion(4) (taken to be Series S – then mip fields +0x50 / +0x58 are 0xE000 / 0x2000 instead + of 0x8000 / 0x8000 for the 64KB Z/S/D/R_X modes); it follows the reported device type. + - Modes the library takes for 2D: 1 2 5 6 9 10 17 18 21 22 25 26 27, 24 (and VAR 28) for ≤ 8-byte non-BC elements, + VAR 31; `Layout` 0 / 2 = its choice (64KB_D for 2, 4KB_S, UAVs 4KB_S_X up to 64 KB else 64KB_R_X). Not modelled + (E_NOTIMPL): render targets / depth (CMASK / HTILE planes), planar depth-stencil formats, MSAA, 1D / 3D, VAR modes. - XGameRuntime task queues: handles are looked up in a set of live ones before being read – an XAsync completing on a worker after its queue was closed read freed memory (a rare lib-test panic in `queue_from`). diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 0f1fa4f..e7e76f1 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -5,8 +5,8 @@ //! (`tiling::Chain`) into a D3D12 subresource and copied in. SW_LINEAR resources use //! the GFX10 256-byte row, level and slice alignment directly. //! -//! 2D textures, arrays and cubes, 3D textures (thick and thin modes) and linear ones. What is -//! not here yet: MSAA, the console's pipe configuration for the _X modes (`CONSOLE_PIPES`), +//! 2D textures, arrays and cubes, 3D textures (thick and thin modes) and linear ones, the _X +//! modes with the console's pipe configuration (`console_pipes`). What is not here yet: MSAA, //! and the binding to the console API that creates textures in title memory (and tells when //! the title rewrote one) – that comes with the game executable. @@ -15,10 +15,20 @@ use super::tiling::{self, Chain, PipeConfig}; use windows::Win32::Graphics::Direct3D12::*; /// Pipes / packers of the console's GB_ADDR_CONFIG – only the XOR (_X) modes depend on it. -/// Not known yet (to be found on an _X texture from the game); the non-XOR modes the -/// archives use do not need it. Series S and X differ (the console's layout library takes -/// the hardware version): the value has to follow the device type XCL reports. -pub const CONSOLE_PIPES: PipeConfig = PipeConfig { pipes_log2: 0, pkrs_log2: 0 }; +/// From the console's own layout library: every texel of every mode matches with 32 pipes / +/// 8 packers by default (Series X), 8 pipes / 4 packers with its hardware version 4 (taken +/// to be Series S). +pub const CONSOLE_PIPES: PipeConfig = PipeConfig { pipes_log2: 5, pkrs_log2: 3 }; +pub const SERIES_S_PIPES: PipeConfig = PipeConfig { pipes_log2: 3, pkrs_log2: 2 }; + +/// The pipe configuration of the console XCL reports to the title (`XSystemGetDeviceType`). +pub fn console_pipes() -> PipeConfig { + if crate::state::config().is_series_s() { + SERIES_S_PIPES + } else { + CONSOLE_PIPES + } +} /// Linear data of one subresource: `depth` slices (3D, else 1) of `rows` rows of `row_bytes` /// (elements: pixels or 4×4 blocks). @@ -93,7 +103,7 @@ pub fn subresources(t: &Image, mem: &[u8], cfg: PipeConfig) -> Result= 2 && l.height >= 2 { let mut wrong = chain.clone(); wrong.levels[k].origin = (0, 0); - let ws = Subresource { depth: 1, rows: l.height, row_bytes: subs[k].row_bytes, data: wrong.detile_level(&mem, k) }; + let ws = Subresource { depth: 1, rows: l.height, row_bytes: subs[k].row_bytes, data: wrong.detile_level(&mem, k, 0) }; tail_levels += 1; tail_err += err; wrong_err += mip_error(&subs[k - 1], &ws, ch, cb).unwrap(); diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index 8027889..75aa405 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -66,6 +66,11 @@ pub struct Layout { ox: Vec, oy: Vec, oz: Vec, + /// the in-block bits the coordinates above the block give (XOR modes with many pipes take + /// pipe bits from neighbouring blocks' coordinates), by `x >> log2(block_w)` etc. + hx: Vec, + hy: Vec, + hz: Vec, } impl Layout { @@ -79,7 +84,7 @@ impl Layout { if mode == 0 { let bw = 256 >> elem_log2; let ox = (0..bw as u32).map(|x| x << elem_log2).collect(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: vec![0], oz: vec![0] }); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: vec![0], oz: vec![0], hx: vec![0], hy: vec![0], hz: vec![0] }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -111,20 +116,37 @@ impl Layout { /// The offset tables of a block `1 << wl` × `1 << hl` × `1 << dl` elements. fn from_bits(mode: u32, elem_log2: u32, blk: u32, bits: &[u64; 20], (wl, hl, dl): (u32, u32, u32)) -> Layout { - let table = |n: usize, shift: u32| -> Vec { + // the in-block offset bits coordinate `c << lo` gives + let table = |n: usize, shift: u32, lo: u32| -> Vec { (0..n as u32) .map(|c| { let mut off = 0u32; for (i, &b) in bits[..blk as usize].iter().enumerate() { let mask = ((b >> shift) & 0xFFFF) as u32; - off |= ((mask & c).count_ones() & 1) << i; + off |= ((mask & (c << lo)).count_ones() & 1) << i; } off }) .collect() }; let (bw, bh, bd) = (1usize << wl, 1usize << hl, 1usize << dl); - Layout { mode, elem_log2, block_w: bw, block_h: bh, block_d: bd, block_bytes: 1 << blk, base_xor: 0, ox: table(bw, 0), oy: table(bh, 16), oz: table(bd, 32) } + // the pattern masks are 16 bits: coordinates above them do not matter + let high = |l: u32, shift: u32| table(1 << (16 - l.min(16)), shift, l); + Layout { + mode, + elem_log2, + block_w: bw, + block_h: bh, + block_d: bd, + block_bytes: 1 << blk, + base_xor: 0, + ox: table(bw, 0, 0), + oy: table(bh, 16, 0), + oz: table(bd, 32, 0), + hx: high(wl, 0), + hy: high(hl, 16), + hz: high(dl, 32), + } } /// surface `w` × `h` elements: (blocks per row, blocks per column) @@ -148,7 +170,9 @@ impl Layout { pub fn offset_z(&self, x: usize, y: usize, z: usize, w: usize) -> usize { let pitch_blocks = w.div_ceil(self.block_w); let block = (y / self.block_h) * pitch_blocks + x / self.block_w; - block * self.block_bytes + ((self.ox[x % self.block_w] ^ self.oy[y % self.block_h] ^ self.oz[z % self.block_d]) as usize ^ self.base_xor) + let hi = |t: &[u32], c: usize, b: usize| t[(c / b) % t.len()]; + let xor = self.ox[x % self.block_w] ^ self.oy[y % self.block_h] ^ self.oz[z % self.block_d] ^ hi(&self.hx, x, self.block_w) ^ hi(&self.hy, y, self.block_h) ^ hi(&self.hz, z, self.block_d); + block * self.block_bytes + (xor as usize ^ self.base_xor) } /// tiled → linear rows (`w << elem_log2` bytes each); bytes past the end of `src` read as 0 @@ -220,6 +244,8 @@ pub struct MipLevel { pub pitch: usize, /// where the level lies inside the mip tail block (levels in the tail), else (0, 0) pub origin: (usize, usize), + /// a level in the mip tail: its byte offset inside the tail block + pub tail: Option, } /// The mip chain of a tiled surface (addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled / @@ -251,11 +277,21 @@ impl Chain { let thick = layout.block_d > 1; let blk = layout.block_bytes.trailing_zeros() as usize; let size = |i: usize| (((width >> i).max(1)).div_ceil(side) as usize, ((height >> i).max(1)).div_ceil(side) as usize); + // what a level is padded from: mip 0's elements halved rounding up (addrlib ShiftCeil; + // the console's layout library agrees), which only differs for odd sizes + let (w0, h0) = (width.div_ceil(side) as usize, height.div_ceil(side) as usize); + let padded = |i: usize| (w0.div_ceil(1 << i), h0.div_ceil(1 << i)); let depth_of = |i: usize| (depth >> i).max(1) as usize; // the largest level the tail holds (GetMipTailDim: a thick block halves h, w or d by // log2(block) % 3) and at most this many levels in it (GetMaxNumMipsInTail) let (tw, th) = if !thick { - (bw / 2, bh) + // Z (depth) modes of 1- and 2-byte elements: 64 × 128 elements, as for 4-byte ones + // (seen on the console's layout library) + if layout.mode != 0 && layout.mode.is_multiple_of(4) && layout.elem_log2 <= 1 { + (bw / 4, bh >> (1 - layout.elem_log2)) + } else { + (bw / 2, bh) + } } else { match blk % 3 { 0 => (bw, bh / 2), @@ -272,7 +308,7 @@ impl Chain { let first_tail = if mips > 1 && max_tail > 0 { (0..mips) .find(|&i| { - let (w, h) = size(i); + let (w, h) = padded(i); w <= tw && h <= th && mips - i <= max_tail }) .unwrap_or(mips) @@ -283,8 +319,9 @@ impl Chain { let mut offset = if first_tail < mips { layout.block_bytes } else { 0 }; for i in (0..first_tail).rev() { let (w, h) = size(i); - levels[i] = MipLevel { width: w, height: h, depth: depth_of(i), offset, pitch: w.div_ceil(bw) * bw, origin: (0, 0) }; - offset += layout.size(w, h); + let (pw, ph) = padded(i); + levels[i] = MipLevel { width: w, height: h, depth: depth_of(i), offset, pitch: pw.div_ceil(bw) * bw, origin: (0, 0), tail: None }; + offset += layout.size(pw, ph); } // a level in the tail: its offset there (256-byte units, largest level first) gives its // origin, x from the odd and y from the even address bits above 256 B, in 256 B @@ -300,7 +337,7 @@ impl Chain { my |= ((at >> (8 + 2 * b)) & 1) << b; } let (w, h) = size(i); - levels[i] = MipLevel { width: w, height: h, depth: depth_of(i), offset: 0, pitch: bw, origin: (mx * w256, my * h256) }; + levels[i] = MipLevel { width: w, height: h, depth: depth_of(i), offset: 0, pitch: bw, origin: (mx * w256, my * h256), tail: Some(at) }; } Chain { layout, levels, slice_bytes: offset } } @@ -310,8 +347,10 @@ impl Chain { self.levels[0].depth.div_ceil(self.layout.block_d) } - fn element_at(&self, l: &MipLevel, x: usize, y: usize) -> usize { - l.offset + self.layout.offset(x + l.origin.0, y + l.origin.1, l.pitch) + /// element (x, y) of level `l` in array slice `slice` (from the slice's start): the slice + /// is z of the 2D patterns – the XOR modes take pipe bits from it + fn element_at(&self, l: &MipLevel, x: usize, y: usize, slice: usize) -> usize { + l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch) } /// element (x, y, z) of level `l` from the start of the texture (all its slices) @@ -353,15 +392,15 @@ impl Chain { } } - /// level `i` of one slice (`src` = the slice's bytes) → linear rows of elements; bytes - /// past the end of `src` read as 0 - pub fn detile_level(&self, src: &[u8], i: usize) -> Vec { + /// level `i` of array slice `slice` (`src` = the slice's bytes) → linear rows of elements; + /// bytes past the end of `src` read as 0 + pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; for y in 0..l.height { for x in 0..l.width { - let o = self.element_at(&l, x, y); + let o = self.element_at(&l, x, y, slice); if let Some(s) = src.get(o..o + e) { out[(y * l.width + x) * e..][..e].copy_from_slice(s); } @@ -370,13 +409,13 @@ impl Chain { out } - /// linear rows of level `i` → its place in one slice (`dst`, `slice_bytes` long) - pub fn tile_level(&self, dst: &mut [u8], i: usize, linear: &[u8]) { + /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) + pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; for y in 0..l.height { for x in 0..l.width { - let o = self.element_at(&l, x, y); + let o = self.element_at(&l, x, y, slice); dst[o..o + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); } } @@ -465,11 +504,11 @@ mod tests { (n >> 16) as u8 | 1 }) .collect(); - c.tile_level(&mut slice, i, &lin); + c.tile_level(&mut slice, i, 0, &lin); want.push(lin); } for (i, lin) in want.iter().enumerate() { - assert_eq!(&c.detile_level(&slice, i), lin, "mode {mode} e{e}: level {i} overwritten"); + assert_eq!(&c.detile_level(&slice, i, 0), lin, "mode {mode} e{e}: level {i} overwritten"); } } } @@ -544,16 +583,17 @@ mod tests { } /// Linear: rows padded to 256 bytes, levels from the smallest (addrlib - /// HwlComputeSurfaceInfoLinear). + /// HwlComputeSurfaceInfoLinear); a level is padded from mip 0 halved rounding up (as the + /// console's layout library lays it out). #[test] fn linear_rows_are_padded_to_256_bytes() { let l = Layout::new(0, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap(); assert_eq!((l.block_w, l.block_h, l.block_bytes), (64, 1, 256)); assert_eq!(l.offset(3, 2, 100), (2 * 128 + 3) * 4); // 100 px → 128 px per row let c = Chain::new(l, 100, 30, 1, 3); - // mip 2 (25×7 → 64 px rows), mip 1 (50×15), mip 0 (100×30) - assert_eq!((c.levels[2].offset, c.levels[1].offset, c.levels[0].offset), (0, 7 * 256, 7 * 256 + 15 * 256)); - assert_eq!(c.slice_bytes, 7 * 256 + 15 * 256 + 30 * 512); + // mip 2 (25×7, padded from 30 / 4 → 8 rows of 64 px), mip 1 (50×15), mip 0 (100×30) + assert_eq!((c.levels[2].height, c.levels[2].offset, c.levels[1].offset, c.levels[0].offset), (7, 0, 8 * 256, 8 * 256 + 15 * 256)); + assert_eq!(c.slice_bytes, 8 * 256 + 15 * 256 + 30 * 512); } /// SW_256B_S with bytes: a 16×16 block stored row by row (addrlib's first nibble row) diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 942250f..c8da33c 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -17,6 +17,7 @@ pub mod dxcompiler; pub mod kernelx; pub mod opus; pub mod xaudio2; +pub mod xg; pub mod xgameruntime; /// Build an export list from functions whose Rust names equal the exported names. @@ -74,6 +75,8 @@ pub const XGAMERUNTIME: &str = "xgameruntime.dll"; pub const D3D12X: &str = "d3d12_xs.dll"; pub const XAUDIO2: &str = "xaudio2_9.dll"; pub const DXCOMPILER: &str = "dxcompiler_xs.dll"; +/// the console's texture layout library (`xg`) +pub const XG: &str = "xg_xs.dll"; /// the console's DirectStorage (`dstorage`) pub const XCRDAPI: &str = "xcrdapi.dll"; /// the console's user32 subset (windows, the message loop): the PC user32 @@ -88,6 +91,7 @@ fn build(config: &Config) -> Registry { HleModule::new(DXCOMPILER, dxcompiler::exports(), &[]), HleModule::new(MINUSERX, Vec::new(), &["user32.dll"]), HleModule::new(XCRDAPI, dstorage::exports(), &[]), + HleModule::new(XG, xg::exports(), &[]), ]; let idx = |n: &str| modules.iter().position(|m| m.name == n).unwrap(); let mut routes: Vec<(String, Route)> = Vec::new(); @@ -139,6 +143,8 @@ fn build(config: &Config) -> Registry { routes.push((MINUSERX.into(), Route::Hle(u))); let s = idx(XCRDAPI); routes.push((XCRDAPI.into(), Route::Hle(s))); + let g = idx(XG); + routes.push((XG.into(), Route::Hle(g))); let c = idx(DXCOMPILER); for p in ["dxcompiler_xs.dll", "dxcompiler_x.dll"] { routes.push((p.into(), Route::Hle(c))); diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs new file mode 100644 index 0000000..ae6e79c --- /dev/null +++ b/crates/xcl/src/hle/xg.rs @@ -0,0 +1,414 @@ +//! `xg_xs.dll` – the console's texture layout library: where the mips and texels of a texture +//! go in the title's own memory (Fortnite imports `XGCreateTextureComputer`). XCL answers from +//! its own GFX10 model (`gpu::tiling::Chain`, checked on retail textures) in the console's +//! structures; `tests/xg_oracle.rs` compares the answers with the console's own library +//! (`XCL_SAMPLE_XG`). +//! +//! * `XGCreateTextureComputer(D3D12_RESOURCE_DESC*, computer**)`: 2D textures, arrays and +//! cubes with one sample. `Layout` 1 = linear, 0x100–0x11F = swizzle mode `Layout & 0x1F`, +//! 0 / 2 = the library's choice (`optimal_mode`). +//! * The computer (no QueryInterface): AddRef, Release, GetResourceLayout(XG_RESOURCE_LAYOUT*), +//! GetResourceSizeBytes, GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes(plane, mip), +//! GetTexelElementOffsetBytes(plane, mip, x, y, slice, sample, bit*), GetTexelCoordinate, +//! CopyIntoSubresource(dst, plane, subresource, src, row pitch, slice pitch), +//! CopyFromSubresource(dst, plane, subresource, src, row pitch, slice pitch), then 2 more. +//! * XG_RESOURCE_LAYOUT (0x1B40): size @0, alignment @8, mips @0x10, planes @0x14, planes +//! from 0x18, 0x6C8 bytes each (usage @0, size @8, slice size @0x10, alignment @0x20, bytes +//! per element @0x28, first mip in the tail @0x2C, mips in the tail @0x30, then 15 mips of +//! 0x70 from 0x38: size @0, offset @8, slice size @0x10, pitch in pixels @0x18 / bytes +//! @0x1C, alignment @0x20, padded width / height / depth @0x24 / 0x28 / 0x2C, width / +//! height in elements @0x30 / 0x34 and pixels @0x38 / 0x3C, depth @0x40, samples @0x44, +//! swizzle mode @0x48, 1 @0x60, in the tail @0x64), dimension @0x1B38. Levels in the mip +//! tail are reported as 256-byte tiles at their offset inside the tail block. + +#![allow(non_snake_case)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::OnceLock; + +use crate::gpu::tiling::{Chain, Layout}; +use crate::util::{HRESULT, S_OK}; + +const E_NOTIMPL: HRESULT = 0x8000_4001u32 as i32; +const E_POINTER: HRESULT = 0x8000_4003u32 as i32; +const E_INVALIDARG: HRESULT = 0x8007_0057u32 as i32; + +pub const LAYOUT_BYTES: usize = 0x1B40; +const PLANE: usize = 0x18; +const MIP: usize = 0x38; +const MIP_BYTES: usize = 0x70; +const MAX_MIPS: usize = 15; + +pub fn exports() -> Vec<(&'static str, usize)> { + crate::hle_exports![XGCreateTextureComputer] +} + +/// The swizzle mode the console's library picks for a 2D texture with `Layout` 0 / 2: 64KB_D +/// for `Layout` 2, depth 64KB_Z_X, render targets 64KB_R_X, otherwise 4KB_S – or for UAVs +/// 4KB_S_X up to 64 KB of texels, else 64KB_R_X. +pub fn optimal_mode(layout: u32, flags: u32, bits_per_pixel: u64, width: u64, height: u32) -> u32 { + let (rt, depth, uav) = (flags & 1 != 0, flags & 2 != 0, flags & 4 != 0); + if depth { + 24 + } else if layout == 2 { + 10 + } else if rt { + 27 + } else if !uav { + 5 + } else if bits_per_pixel * width * height as u64 <= 0x8_0000 { + 21 + } else { + 27 + } +} + +/// A 2D texture as the console lays it out. +pub struct Texture { + pub chain: Chain, + pub mode: u32, + pub bpe: u32, + /// pixels per element side (4 for BCn) + pub side: u32, + pub width: u32, + pub height: u32, + pub array: u32, + pub first_tail: usize, +} + +/// (log2 bytes per element, pixels per element side) of a DXGI format; None for the 96-bit +/// and packed 4:2:2 ones (not tiled) and unknown formats +pub fn element(f: u32) -> Option<(u32, u32)> { + Some(match f { + 1..=4 => (4, 1), + 9..=22 => (3, 1), + 23..=47 | 67 | 87..=93 => (2, 1), + 48..=59 | 85 | 86 | 115 => (1, 1), + 60..=65 => (0, 1), + 70..=72 | 79..=81 => (3, 4), + 73..=78 | 82..=84 | 94..=99 => (4, 4), + _ => return None, + }) +} + +/// 256-byte tile size in elements (log2 bytes per element → (w, h)) +fn micro(e: u32) -> (usize, usize) { + (1 << [4, 4, 3, 3, 2][e as usize], 1 << [4, 3, 3, 2, 2][e as usize]) +} + +impl Texture { + /// From a D3D12_RESOURCE_DESC (0x38 bytes) as the console's. + pub fn new(d: &[u8; 0x38]) -> Result { + Self::with_pipes(d, crate::gpu::texture::console_pipes()) + } + + /// `new` for a given pipe / packer configuration (only the XOR modes depend on it). + pub fn with_pipes(d: &[u8; 0x38], pipes: crate::gpu::tiling::PipeConfig) -> Result { + let u = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap()); + let w16 = |o: usize| u16::from_le_bytes(d[o..o + 2].try_into().unwrap()) as u32; + let (dim, width, height, array, mips, format, samples, layout, flags) = + (u(0), u64::from_le_bytes(d[0x10..0x18].try_into().unwrap()), u(0x18), w16(0x1C), w16(0x1E), u(0x20), u(0x24), u(0x2C), u(0x30)); + // 1D / 3D / buffers, MSAA, and render targets / depth (their metadata planes: CMASK, + // HTILE) are not modelled + if dim != 3 || samples > 1 || flags & 3 != 0 { + return Err(E_NOTIMPL); + } + if matches!(format, 19..=22 | 44..=47) { + return Err(E_NOTIMPL); // depth + stencil: two planes + } + if width == 0 || width > 16384 || height == 0 || height > 16384 || array == 0 { + return Err(E_INVALIDARG); + } + let (e, side) = element(format).ok_or(E_INVALIDARG)?; + let mode = match layout { + 1 => 0, + 0x100..=0x11F => layout & 0x1F, + 0 | 2 => optimal_mode(layout, flags, (8u64 << e) / (side * side) as u64, width, height), + _ => return Err(E_INVALIDARG), + }; + // the modes the console's library takes for a 2D texture (VAR 28 / 31: not modelled) + let bc = side > 1; + match mode { + 0 | 1 | 2 | 5 | 6 | 9 | 10 | 17 | 18 | 21 | 22 | 25 | 26 | 27 => {} + 24 if e <= 3 && !bc => {} + 28 | 31 => return Err(E_NOTIMPL), + _ => return Err(E_INVALIDARG), + } + let l = Layout::new(mode, e, pipes).ok_or(E_INVALIDARG)?; + let full = 32 - (width as u32).max(height).leading_zeros(); + let mips = if mips == 0 { full } else { mips }; + if mips as usize > MAX_MIPS { + return Err(E_INVALIDARG); + } + let chain = Chain::new(l, width as u32, height, side, mips); + let first_tail = chain.levels.iter().position(|m| m.tail.is_some()).unwrap_or(chain.levels.len()); + Ok(Texture { chain, mode, bpe: 1 << e, side, width: width as u32, height, array, first_tail }) + } + + pub fn size(&self) -> u64 { + (self.chain.slice_bytes * self.array as usize) as u64 + } + + pub fn alignment(&self) -> u64 { + self.chain.layout.block_bytes as u64 + } + + /// (padded width, padded height) in elements of level `i` + fn padded(&self, i: usize) -> (usize, usize) { + let l = &self.chain.layout; + if i < self.first_tail { + let h = (self.height.div_ceil(self.side) as usize).div_ceil(1 << i); + (self.chain.levels[i].pitch, h.div_ceil(l.block_h) * l.block_h) + } else { + let (mw, mh) = micro(l.elem_log2); + let k = i - self.first_tail; + (((l.block_w / 2) >> k).max(mw), (l.block_h >> k).max(mh)) + } + } + + /// byte offset of level `i` from the start of a slice + pub fn mip_offset(&self, i: usize) -> u64 { + let m = &self.chain.levels[i]; + m.tail.unwrap_or(m.offset) as u64 + } + + /// byte offset of element (x, y) of level `i` in slice `slice`; the slice is z of the 2D + /// patterns (the XOR modes take pipe bits from it) + pub fn element_offset(&self, i: usize, x: usize, y: usize, slice: usize) -> u64 { + let m = &self.chain.levels[i]; + (slice * self.chain.slice_bytes + m.offset + self.chain.layout.offset_z(x + m.origin.0, y + m.origin.1, slice, m.pitch)) as u64 + } + + /// XG_RESOURCE_LAYOUT + pub fn write(&self, b: &mut [u8; LAYOUT_BYTES]) { + b.fill(0); + let q = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u64| b[o..o + 8].copy_from_slice(&v.to_le_bytes()); + let w = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u32| b[o..o + 4].copy_from_slice(&v.to_le_bytes()); + let mips = self.chain.levels.len(); + q(b, 0, self.size()); + q(b, 8, self.alignment()); + w(b, 0x10, mips as u32); + w(b, 0x14, 1); + w(b, 0x1B38, 3); + w(b, PLANE, 1); + q(b, PLANE + 8, self.size()); + q(b, PLANE + 0x10, self.chain.slice_bytes as u64); + q(b, PLANE + 0x20, self.alignment()); + w(b, PLANE + 0x28, self.bpe); + w(b, PLANE + 0x2C, self.first_tail as u32); + w(b, PLANE + 0x30, (mips - self.first_tail) as u32); + for i in 0..mips { + let m = &self.chain.levels[i]; + let r = PLANE + MIP + i * MIP_BYTES; + let tail = i >= self.first_tail; + let (pw, ph) = self.padded(i); + let bytes = (pw * ph) as u64 * self.bpe as u64; + let size = bytes; + q(b, r, size); + q(b, r + 8, self.mip_offset(i)); + q(b, r + 0x10, size); + w(b, r + 0x18, pw as u32 * self.side); + w(b, r + 0x1C, pw as u32 * self.bpe); + w(b, r + 0x20, if tail { 0x100 } else { self.alignment() as u32 }); + w(b, r + 0x24, pw as u32); + w(b, r + 0x28, ph as u32); + w(b, r + 0x2C, self.array); + w(b, r + 0x30, m.width as u32); + w(b, r + 0x34, m.height as u32); + w(b, r + 0x38, (self.width >> i).max(1)); + w(b, r + 0x3C, (self.height >> i).max(1)); + w(b, r + 0x40, self.array); + w(b, r + 0x44, 1); + // the tail is in 256-byte tiles of the same kind (S 1, D 2, R 3; Z keeps its mode) + w(b, r + 0x48, if tail && !self.mode.is_multiple_of(4) { self.mode % 4 } else { self.mode }); + if !tail && (24..=27).contains(&self.mode) { + w(b, r + 0x50, 0x8000); + w(b, r + 0x58, 0x8000); + } + w(b, r + 0x60, 1); + w(b, r + 0x64, tail as u32); + } + } +} + +// --------------------------------------------------------------------------------------- +// the computer +// --------------------------------------------------------------------------------------- + +#[repr(C)] +struct Computer { + vtbl: *const usize, + refs: AtomicU32, + tex: Texture, +} + +fn vtbl() -> &'static [usize] { + static V: OnceLock<&'static [usize]> = OnceLock::new(); + V.get_or_init(|| { + let mut v = vec![ + add_ref as usize, + release as usize, + get_resource_layout as usize, + get_size as usize, + get_alignment as usize, + get_mip_offset as usize, + get_texel_offset as usize, + not_implemented as usize, + copy_into as usize, + copy_from as usize, + ]; + for i in v.len()..12 { + let (stub, _) = crate::stubs::make_stub_info("xg_xs.dll", &format!("XGTextureAddressComputer::#{i}"), E_NOTIMPL as u32 as u64); + v.push(stub); + } + Box::leak(v.into_boxed_slice()) + }) +} + +unsafe fn tex<'a>(p: *mut c_void) -> &'a Texture { + &(*(p as *const Computer)).tex +} + +/// `HRESULT XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, XGTextureAddressComputer**)` +pub unsafe extern "system" fn XGCreateTextureComputer(desc: *const u8, out: *mut *mut c_void) -> HRESULT { + if desc.is_null() || out.is_null() { + return E_POINTER; + } + *out = std::ptr::null_mut(); + match Texture::new(&*(desc as *const [u8; 0x38])) { + Ok(tex) => { + *out = Box::into_raw(Box::new(Computer { vtbl: vtbl().as_ptr(), refs: AtomicU32::new(1), tex })) as *mut c_void; + S_OK + } + Err(hr) => { + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + let d = &*(desc as *const [u8; 0x38]); + crate::xlog_warn!("XGCreateTextureComputer {hr:#x}: {:x?}", &d[..0x34]); + } + hr + } + } +} + +unsafe extern "system" fn add_ref(p: *mut c_void) -> u32 { + (*(p as *const Computer)).refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +unsafe extern "system" fn release(p: *mut c_void) -> u32 { + let n = (*(p as *const Computer)).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if n == 0 { + drop(Box::from_raw(p as *mut Computer)); + } + n +} + +unsafe extern "system" fn get_resource_layout(p: *mut c_void, out: *mut u8) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + tex(p).write(&mut *(out as *mut [u8; LAYOUT_BYTES])); + S_OK +} + +unsafe extern "system" fn get_size(p: *mut c_void) -> u64 { + tex(p).size() +} + +unsafe extern "system" fn get_alignment(p: *mut c_void) -> u64 { + tex(p).alignment() +} + +unsafe extern "system" fn get_mip_offset(p: *mut c_void, plane: u32, mip: u32) -> u64 { + let t = tex(p); + if plane != 0 || mip as usize >= t.chain.levels.len() { + return 0; + } + t.mip_offset(mip as usize) +} + +unsafe extern "system" fn get_texel_offset(p: *mut c_void, plane: u32, mip: u32, x: u64, y: u32, slice: u32, _sample: u32, bit: *mut u32) -> u64 { + let t = tex(p); + if !bit.is_null() { + *bit = 0; + } + if plane != 0 || mip as usize >= t.chain.levels.len() || slice >= t.array { + return 0; + } + t.element_offset(mip as usize, x as usize, y as usize, slice as usize) +} + +unsafe extern "system" fn not_implemented(_p: *mut c_void) -> HRESULT { + E_NOTIMPL +} + +/// (level, slice) of a subresource (mip + slice × mips) +fn subresource(t: &Texture, sub: u32) -> Option<(usize, usize)> { + let mips = t.chain.levels.len(); + let (i, s) = (sub as usize % mips, sub as usize / mips); + (s < t.array as usize).then_some((i, s)) +} + +/// rows of `src` (`row_pitch` apart) → the level's place in `dst` (the whole resource) +unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, _slice_pitch: u32) -> HRESULT { + let t = tex(p); + let Some((i, s)) = subresource(t, sub).filter(|_| plane == 0 && !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; + let m = t.chain.levels[i]; + let row = m.width * t.bpe as usize; + let mut linear = vec![0u8; row * m.height]; + for y in 0..m.height { + linear[y * row..(y + 1) * row].copy_from_slice(std::slice::from_raw_parts(src.add(y * row_pitch as usize), row)); + } + let slice = std::slice::from_raw_parts_mut(dst.add(s * t.chain.slice_bytes), t.chain.slice_bytes); + t.chain.tile_level(slice, i, s, &linear); + S_OK +} + +/// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart) +unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, _slice_pitch: u32) -> HRESULT { + let t = tex(p); + let Some((i, s)) = subresource(t, sub).filter(|_| plane == 0 && !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; + let m = t.chain.levels[i]; + let row = m.width * t.bpe as usize; + let slice = std::slice::from_raw_parts(src.add(s * t.chain.slice_bytes), t.chain.slice_bytes); + let linear = t.chain.detile_level(slice, i, s); + for y in 0..m.height { + std::ptr::copy_nonoverlapping(linear[y * row..].as_ptr(), dst.add(y * row_pitch as usize), row); + } + S_OK +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(width: u64, height: u32, array: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] { + let mut d = [0u8; 0x38]; + d[0..4].copy_from_slice(&3u32.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&width.to_le_bytes()); + d[0x18..0x1C].copy_from_slice(&height.to_le_bytes()); + d[0x1C..0x1E].copy_from_slice(&array.to_le_bytes()); + d[0x1E..0x20].copy_from_slice(&mips.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2C..0x30].copy_from_slice(&layout.to_le_bytes()); + d + } + + /// As the console's library answers (seen on it): RGBA8 256×256, full chain, 64KB_S. + #[test] + fn rgba8_64kb_s_layout() { + let t = Texture::new(&desc(256, 256, 1, 0, 28, 0x109)).unwrap(); + let mut b = [0u8; LAYOUT_BYTES]; + t.write(&mut b); + let q = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap()); + let w = |o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()); + assert_eq!((q(0), q(8), w(0x10), w(PLANE + 0x2C), w(PLANE + 0x30)), (0x60000, 0x10000, 9, 2, 7)); + let mip = |i: usize, k: usize| w(PLANE + MIP + i * MIP_BYTES + 4 * k); + let offsets: Vec = (0..9).map(|i| mip(i, 2)).collect(); + assert_eq!(offsets, [0x20000, 0x10000, 0x8000, 0x4000, 0x2000, 0x1000, 0x800, 0x600, 0x500]); + assert_eq!((mip(2, 0), mip(2, 9), mip(2, 10), mip(2, 18), mip(6, 9), mip(6, 10)), (0x8000, 0x40, 0x80, 1, 8, 8)); + assert_eq!(optimal_mode(0, 0, 32, 256, 256), 5); + } +} diff --git a/crates/xcl/tests/xg_oracle.rs b/crates/xcl/tests/xg_oracle.rs new file mode 100644 index 0000000..480939c --- /dev/null +++ b/crates/xcl/tests/xg_oracle.rs @@ -0,0 +1,444 @@ +//! The console's texture layout library as a reference (`XCL_SAMPLE_XG` = the console's own +//! `xg_xs.dll`, from the user's console files – skipped when unset): loaded through XCL's +//! loader and asked the same questions as XCL's implementation. + +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; + +use xcl::modules::MappedModule; +use xcl::pe::ExportTarget; + +fn console() -> Option<&'static Arc> { + static M: OnceLock>> = OnceLock::new(); + M.get_or_init(|| { + let path = PathBuf::from(std::env::var_os("XCL_SAMPLE_XG")?); + xcl::stubs::init_db(&Default::default()); + xcl::hle::init(&xcl::config::Config::default()); + let _ = xcl::eh::install_pc_hook(); + Some(xcl::loader::load_game_dll(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))) + }) + .as_ref() +} + +fn proc(m: &MappedModule, name: &str) -> usize { + match m.exports.by_name.get(name) { + Some(ExportTarget::Rva(r)) => m.base + *r as usize, + other => panic!("{}!{name}: {other:?}", m.name), + } +} + +/// D3D12_RESOURCE_DESC as the console's (0x38 bytes) +#[allow(clippy::too_many_arguments)] +fn desc(dim: u32, width: u64, height: u32, depth: u16, mips: u16, format: u32, layout: u32, flags: u32) -> [u8; 0x38] { + let mut d = [0u8; 0x38]; + d[0..4].copy_from_slice(&dim.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&width.to_le_bytes()); + d[0x18..0x1C].copy_from_slice(&height.to_le_bytes()); + d[0x1C..0x1E].copy_from_slice(&depth.to_le_bytes()); + d[0x1E..0x20].copy_from_slice(&mips.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2C..0x30].copy_from_slice(&layout.to_le_bytes()); + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + d +} + +type CreateFn = unsafe extern "system" fn(*const u8, *mut *mut std::ffi::c_void) -> i32; + +/// (HRESULT, the computer's resource layout) of a texture computer from `create` +unsafe fn layout(create: usize, d: &[u8; 0x38]) -> (i32, Vec) { + let mut c = std::ptr::null_mut(); + let hr = std::mem::transmute::(create)(d.as_ptr(), &mut c); + let mut out = vec![0u8; 0x1B40]; + if hr >= 0 && !c.is_null() { + let vt = *(c as *const *const usize); + let get: unsafe extern "system" fn(*mut std::ffi::c_void, *mut u8) -> i32 = std::mem::transmute(*vt.add(2)); + get(c, out.as_mut_ptr()); + let release: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = std::mem::transmute(*vt.add(1)); + release(c); + } + (hr, out) +} + +#[test] +#[ignore] +fn print_console_layouts() { + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + for (name, d) in [ + ("rgba8 256x256 full chain, 64KB_S (0x109)", desc(3, 256, 256, 1, 0, 28, 0x109, 0)), + ("bc1 1024x512 11 mips, 64KB_S", desc(3, 1024, 512, 1, 11, 71, 0x109, 0)), + ("rgba8 100x60 1 mip linear", desc(3, 100, 60, 1, 1, 28, 1, 0)), + ("rgba8 256x256 optimal", desc(3, 256, 256, 1, 0, 28, 0, 0)), + ("rgba8 3x5 full chain linear", desc(3, 3, 5, 1, 0, 28, 1, 0)), + ("rgba8 100x60 3 mips linear", desc(3, 100, 60, 1, 3, 28, 1, 0)), + ("rgba8 256x256 64KB_Z (0x108)", desc(3, 256, 256, 1, 0, 28, 0x108, 0)), + ] { + let (hr, l) = unsafe { layout(create, &d) }; + let q = |o: usize| u64::from_le_bytes(l[o..o + 8].try_into().unwrap()); + let w = |o: usize| u32::from_le_bytes(l[o..o + 4].try_into().unwrap()); + println!("{name}: hr {hr:#x} size {:#x} align {:#x} mips {} planes {} @0x1b38 {}", q(0), q(8), w(0x10), w(0x14), w(0x1B38)); + let p = 0x18; + println!(" plane: usage {} size {:#x} slice {:#x} +0x18 {:#x} align {:#x} bpe {} tail {} {}", w(p), q(p + 8), q(p + 0x10), q(p + 0x18), q(p + 0x20), w(p + 0x28), w(p + 0x2C), w(p + 0x30)); + for i in 0..(w(0x10) as usize).min(15) { + let r = p + 0x38 + i * 0x70; + let row: Vec = (0..0x70).step_by(4).map(|k| format!("{:x}", w(r + k))).collect(); + println!(" mip {i}: {}", row.join(" ")); + } + } +} + +/// Field name of an XG_RESOURCE_LAYOUT offset (for mismatch reports). +fn field(o: usize) -> String { + if o < 0x18 { + return format!("header+{o:#x}"); + } + if o >= 0x1B38 { + return format!("+{o:#x}"); + } + let (plane, r) = ((o - 0x18) / 0x6C8, (o - 0x18) % 0x6C8); + if r < 0x38 { + format!("plane{plane}+{r:#x}") + } else { + format!("plane{plane} mip{}+{:#x}", (r - 0x38) / 0x70, (r - 0x38) % 0x70) + } +} + +#[test] +fn layouts_match_the_console_library() { + let Some(m) = console() else { return }; + let theirs = proc(m, "XGCreateTextureComputer"); + let ours = xcl::hle::xg::XGCreateTextureComputer as *const () as usize; + let formats = [28u32, 71, 77, 98, 10, 41, 61, 49, 2, 80, 83, 24, 87, 40, 55]; + let sizes = [(1u64, 1u32), (3, 5), (16, 16), (100, 60), (256, 256), (1000, 333), (1024, 512), (2048, 2048), (4096, 1), (1, 4096), (640, 360), (129, 65), (257, 129), (65, 33), (1025, 513)]; + // (layout, D3D12 flags): explicit modes, and the library's own choice for textures and UAVs + // (4); render targets / depth (metadata planes) are not modelled + let mut layouts: Vec<(u32, u32)> = [1u32, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107, 0x108, 0x109, 0x10A, 0x10B, 0x114, 0x115, 0x118, 0x119, 0x11A, 0x11B].map(|l| (l, 0)).to_vec(); + layouts.extend([(0, 0), (0, 4), (2, 0), (2, 4)]); + let (mut cases, mut same, mut both_fail) = (0, 0, 0); + let mut fields: std::collections::BTreeMap = Default::default(); + for &f in &formats { + for &(w, h) in &sizes { + for &mips in &[0u16, 1, 3] { + for &array in &[1u16, 6] { + for &(lay, flags) in &layouts { + let d = desc(3, w, h, array, mips, f, lay, flags); + let (hc, lc) = unsafe { layout(theirs, &d) }; + let (ho, lo) = unsafe { layout(ours, &d) }; + cases += 1; + if hc < 0 && ho < 0 { + both_fail += 1; + continue; + } + if (hc < 0) != (ho < 0) { + let e = fields.entry(format!("HRESULT {hc:#x} vs ours {ho:#x}")).or_default(); + e.0 += 1; + if e.1.is_empty() { + e.1 = format!("fmt {f} {w}x{h} mips {mips} array {array} layout {lay:#x} flags {flags:#x}"); + } + continue; + } + let diff: Vec = (0..0x1B40).step_by(4).filter(|&o| lc[o..o + 4] != lo[o..o + 4]).collect(); + if diff.is_empty() { + same += 1; + } + for o in diff.iter().take(4) { + let e = fields.entry(field(*o)).or_default(); + e.0 += 1; + if e.1.is_empty() { + let v = |l: &[u8]| u32::from_le_bytes(l[*o..*o + 4].try_into().unwrap()); + e.1 = format!("fmt {f} {w}x{h} mips {mips} array {array} layout {lay:#x} flags {flags:#x}: console {:#x}, ours {:#x}", v(&lc), v(&lo)); + } + } + } + } + } + } + } + println!("{cases} cases: {same} identical, {both_fail} refused by both"); + for (k, (n, ex)) in fields.iter().take(40) { + println!(" {k}: {n}× – e.g. {ex}"); + } + assert_eq!(same + both_fail, cases, "layouts differ from the console library"); +} + +#[test] +#[ignore] +fn print_accepted_modes() { + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + for (bpe, f) in [(1, 61u32), (2, 49), (4, 28), (8, 10), (16, 2), (8, 71), (16, 77)] { + let ok: Vec = (1..32).filter(|&mode| unsafe { layout(create, &desc(3, 256, 256, 1, 1, f, 0x100 + mode, 0)).0 } >= 0).collect(); + println!("bpe {bpe} format {f}: {ok:?}"); + } +} + +#[test] +#[ignore] +fn print_z_tails() { + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + for f in [61u32, 49, 28, 10] { + for (w, h) in [(100u64, 60u32), (128, 128), (128, 256), (200, 200), (256, 256), (64, 64)] { + for lay in [0x118u32, 0x119] { + let (hr, l) = unsafe { layout(create, &desc(3, w, h, 1, 0, f, lay, 0)) }; + let u = |o: usize| u32::from_le_bytes(l[o..o + 4].try_into().unwrap()); + let mip0 = 0x18 + 0x38; + println!("fmt {f} {w}x{h} {lay:#x}: hr {hr:#x} first tail {} mips {} mip0 padded {}x{} size {:#x}", u(0x18 + 0x2C), u(0x10), u(mip0 + 0x24), u(mip0 + 0x28), u(0)); + } + } + } +} + +/// Texel offsets (GetTexelElementOffsetBytes) of the console's library against XCL's for every +/// mode, element size and pipe / packer configuration: the configuration that matches every +/// sampled texel of the XOR modes is the console's. +#[test] +#[ignore] +fn texel_offsets_and_the_console_pipe_configuration() { + use xcl::gpu::tiling::PipeConfig; + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + let configs: Vec = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (3, 1), (2, 2), (3, 2), (4, 2), (3, 3), (4, 3), (5, 3), (4, 4), (5, 4)] + .map(|(p, k)| PipeConfig { pipes_log2: p, pkrs_log2: k }) + .to_vec(); + let mut seed = 0x1234_5678u32; + let mut rnd = |n: u32| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) % n.max(1) + }; + for mode in [1u32, 2, 5, 6, 9, 10, 17, 18, 21, 22, 24, 25, 26, 27] { + for f in [61u32, 49, 28, 10, 2, 71] { + let d = desc(3, 300, 200, 2, 0, f, 0x100 + mode, 0); + let mut c = std::ptr::null_mut(); + if unsafe { std::mem::transmute::(create)(d.as_ptr(), &mut c) } < 0 { + continue; + } + type Offset = unsafe extern "system" fn(*mut std::ffi::c_void, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let off: Offset = unsafe { std::mem::transmute(*(*(c as *const *const usize)).add(6)) }; + let ok: Vec = configs + .iter() + .filter(|cfg| { + let t = xcl::hle::xg::Texture::with_pipes(&d, **cfg).unwrap(); + let mut good = true; + for i in 0..t.chain.levels.len() { + let l = t.chain.levels[i]; + for k in 0..24 { + let (x, y, s) = match k { + 0 => (0, 0, 0), + 1 => (l.width - 1, l.height - 1, 1), + _ => (rnd(l.width as u32) as usize, rnd(l.height as u32) as usize, rnd(2) as usize), + }; + let mut bit = 0u32; + let theirs = unsafe { off(c, 0, i as u32, x as u64, y as u32, s as u32, 0, &mut bit) }; + if theirs != t.element_offset(i, x, y, s) { + good = false; + } + } + } + good + }) + .map(|c| format!("{}/{}", c.pipes_log2, c.pkrs_log2)) + .collect(); + println!("mode {mode:2} format {f:2}: matching pipes/packers {ok:?}"); + unsafe { + let release: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = std::mem::transmute(*(*(c as *const *const usize)).add(1)); + release(c); + } + } + } +} + +#[test] +#[ignore] +fn print_xor_bits() { + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + for (mode, base) in [(25u32, 9u32), (21, 5), (27, 9)] { + for f in [28u32, 61] { + let get = |layout: u32| { + let d = desc(3, 2048, 2048, 1, 1, f, layout, 0); + let mut c = std::ptr::null_mut(); + assert!(unsafe { std::mem::transmute::(create)(d.as_ptr(), &mut c) } >= 0); + c + }; + type Offset = unsafe extern "system" fn(*mut std::ffi::c_void, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let (cx, cs) = (get(0x100 + mode), get(0x100 + base)); + let off = |c: *mut std::ffi::c_void, x: u64, y: u32| unsafe { + let f: Offset = std::mem::transmute(*(*(c as *const *const usize)).add(6)); + let mut b = 0; + f(c, 0, 0, x, y, 0, 0, &mut b) + }; + let xs: Vec = (0..11).map(|k| format!("{:x}", off(cx, 1 << k, 0) ^ off(cs, 1 << k, 0))).collect(); + let ys: Vec = (0..11).map(|k| format!("{:x}", off(cx, 0, 1 << k) ^ off(cs, 0, 1 << k))).collect(); + println!("mode {mode} vs {base} format {f}: x bits {xs:?} | y bits {ys:?}"); + } + } +} + +#[test] +#[ignore] +fn print_xor_64kb_parts() { + use xcl::gpu::tiling::PipeConfig; + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + for cfg in [PipeConfig { pipes_log2: 5, pkrs_log2: 3 }, PipeConfig { pipes_log2: 5, pkrs_log2: 4 }] { + for mode in [25u32, 27] { + let d = desc(3, 512, 512, 2, 0, 28, 0x100 + mode, 0); + let mut c = std::ptr::null_mut(); + assert!(unsafe { std::mem::transmute::(create)(d.as_ptr(), &mut c) } >= 0); + type Offset = unsafe extern "system" fn(*mut std::ffi::c_void, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let off: Offset = unsafe { std::mem::transmute(*(*(c as *const *const usize)).add(6)) }; + let t = xcl::hle::xg::Texture::with_pipes(&d, cfg).unwrap(); + let mut bad = std::collections::BTreeMap::::new(); + for i in 0..t.chain.levels.len() { + let l = t.chain.levels[i]; + for s in 0..2usize { + for y in (0..l.height).step_by(7) { + for x in (0..l.width).step_by(5) { + let mut b = 0; + let theirs = unsafe { off(c, 0, i as u32, x as u64, y as u32, s as u32, 0, &mut b) }; + let ours = t.element_offset(i, x, y, s); + if theirs != ours { + let k = format!("mip {i} slice {s}"); + let e = bad.entry(k).or_default(); + e.0 += 1; + if e.1.is_empty() { + e.1 = format!("({x},{y}) console {theirs:#x} ours {ours:#x} xor {:#x}", theirs ^ ours); + } + } + } + } + } + } + println!("cfg {}/{} mode {mode}: {} groups differ", cfg.pipes_log2, cfg.pkrs_log2, bad.len()); + for (k, (n, ex)) in bad.iter().take(6) { + println!(" {k}: {n} – {ex}"); + } + } + } +} + +#[test] +#[ignore] +fn print_hardware_versions() { + use xcl::gpu::tiling::PipeConfig; + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + let set: unsafe extern "system" fn(u32) -> i32 = unsafe { std::mem::transmute(proc(m, "XGSetHardwareVersion")) }; + let configs: Vec = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (3, 1), (2, 2), (3, 2), (4, 2), (3, 3), (4, 3), (5, 3), (4, 4), (5, 4)] + .map(|(p, k)| PipeConfig { pipes_log2: p, pkrs_log2: k }) + .to_vec(); + for v in 0..8u32 { + let hr = unsafe { set(v) }; + let d = desc(3, 512, 512, 2, 1, 28, 0x100 + 27, 0); + let mut c = std::ptr::null_mut(); + if unsafe { std::mem::transmute::(create)(d.as_ptr(), &mut c) } < 0 { + println!("version {v}: XGSetHardwareVersion {hr:#x}, create failed"); + continue; + } + type Offset = unsafe extern "system" fn(*mut std::ffi::c_void, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let off: Offset = unsafe { std::mem::transmute(*(*(c as *const *const usize)).add(6)) }; + let ok: Vec = configs + .iter() + .filter(|cfg| { + let t = xcl::hle::xg::Texture::with_pipes(&d, **cfg).unwrap(); + (0..512usize).step_by(13).all(|y| (0..512usize).step_by(11).all(|x| (0..2).all(|s| unsafe { off(c, 0, 0, x as u64, y as u32, s as u32, 0, std::ptr::null_mut()) } == t.element_offset(0, x, y, s)))) + }) + .map(|c| format!("{}/{}", c.pipes_log2, c.pkrs_log2)) + .collect(); + let (_, l) = unsafe { layout(create, &d) }; + println!("version {v}: XGSetHardwareVersion {hr:#x}; 64KB_R_X matches {ok:?}; mip0 +0x50/+0x58 {:#x}/{:#x}", u32::from_le_bytes(l[0x18 + 0x38 + 0x50..][..4].try_into().unwrap()), u32::from_le_bytes(l[0x18 + 0x38 + 0x58..][..4].try_into().unwrap())); + } + unsafe { set(0) }; +} + +/// CopyIntoSubresource / CopyFromSubresource: the console's library and XCL tile the same +/// rows to the same bytes, and read them back. +#[test] +fn subresource_copies_match_the_console_library() { + let Some(m) = console() else { return }; + let theirs = proc(m, "XGCreateTextureComputer"); + let ours = xcl::hle::xg::XGCreateTextureComputer as *const () as usize; + type Copy = unsafe extern "system" fn(*mut std::ffi::c_void, *mut u8, u32, u32, *const u8, u32, u32) -> i32; + let mut seed = 0x9E37_79B9u32; + let mut cases = 0; + for &(f, w, h, array, layout) in &[ + (28u32, 300u64, 200u32, 2u16, 0x105u32), + (28, 300, 200, 2, 0x119), + (71, 512, 256, 3, 0x109), + (10, 129, 65, 1, 0x11A), + (61, 1000, 333, 2, 0x115), + (98, 256, 256, 6, 0x11B), + (28, 100, 60, 2, 1), + ] { + let d = desc(3, w, h, array, 0, f, layout, 0); + let make = |create: usize| unsafe { + let mut c = std::ptr::null_mut(); + assert!(std::mem::transmute::(create)(d.as_ptr(), &mut c) >= 0, "{layout:#x}"); + c + }; + let (c, o) = (make(theirs), make(ours)); + let t = xcl::hle::xg::Texture::new(&d).unwrap(); + let size = t.size() as usize; + let (mut a, mut b) = (vec![0u8; size], vec![0u8; size]); + let mips = t.chain.levels.len(); + for s in 0..array as usize { + for i in 0..mips { + let l = t.chain.levels[i]; + let row = l.width * t.bpe as usize; + let pitch = row + 16; + let lin: Vec = (0..pitch * l.height) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 24) as u8 + }) + .collect(); + let sub = (i + s * mips) as u32; + unsafe { + let into = |p: *mut std::ffi::c_void| -> Copy { std::mem::transmute(*(*(p as *const *const usize)).add(8)) }; + assert_eq!(into(c)(c, a.as_mut_ptr(), 0, sub, lin.as_ptr(), pitch as u32, (pitch * l.height) as u32), 0); + assert_eq!(into(o)(o, b.as_mut_ptr(), 0, sub, lin.as_ptr(), pitch as u32, (pitch * l.height) as u32), 0); + // ours reads the console's bytes back + let from: Copy = std::mem::transmute(*(*(o as *const *const usize)).add(9)); + let mut back = vec![0u8; pitch * l.height]; + assert_eq!(from(o, back.as_mut_ptr(), 0, sub, a.as_ptr(), pitch as u32, 0), 0); + for y in 0..l.height { + assert_eq!(back[y * pitch..y * pitch + row], lin[y * pitch..y * pitch + row], "layout {layout:#x} format {f} mip {i} slice {s} row {y}"); + } + } + cases += 1; + } + } + let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count(); + assert_eq!(differ, 0, "layout {layout:#x} format {f}: {differ} bytes differ from the console's tiling"); + } + println!("{cases} subresources tiled identically"); +} + +#[test] +#[ignore] +fn print_odd_offsets() { + let Some(m) = console() else { return }; + let create = proc(m, "XGCreateTextureComputer"); + let d = desc(3, 129, 65, 1, 0, 10, 0x11A, 0); + let mut c = std::ptr::null_mut(); + assert!(unsafe { std::mem::transmute::(create)(d.as_ptr(), &mut c) } >= 0); + type Offset = unsafe extern "system" fn(*mut std::ffi::c_void, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let off: Offset = unsafe { std::mem::transmute(*(*(c as *const *const usize)).add(6)) }; + let t = xcl::hle::xg::Texture::new(&d).unwrap(); + let mut n = 0; + for y in 0..65usize { + for x in 0..129usize { + let a = unsafe { off(c, 0, 0, x as u64, y as u32, 0, 0, std::ptr::null_mut()) }; + let b = t.element_offset(0, x, y, 0); + if a != b { + if n < 6 { + println!("({x},{y}): console {a:#x} ours {b:#x}"); + } + n += 1; + } + } + } + println!("{n} texels of mip 0 differ; pitch {} block {}x{}", t.chain.levels[0].pitch, t.chain.layout.block_w, t.chain.layout.block_h); +} diff --git a/scripts/test.ps1 b/scripts/test.ps1 index b06c262..5554f7e 100644 --- a/scripts/test.ps1 +++ b/scripts/test.ps1 @@ -2,7 +2,7 @@ $ErrorActionPreference = 'Stop' Set-Location (Join-Path $PSScriptRoot '..') # tests on game data pass without running anything when their variable is not set -$missing = 'XCL_SAMPLE_RPF', 'XCL_SAMPLE_DLLS', 'XCL_SAMPLE_TTPF', 'XCL_SAMPLE_BK2', 'XCL_SAMPLE_BVH4', 'XCL_SAMPLE_AWC' | Where-Object { -not (Test-Path "env:$_") } +$missing = 'XCL_SAMPLE_RPF', 'XCL_SAMPLE_DLLS', 'XCL_SAMPLE_TTPF', 'XCL_SAMPLE_BK2', 'XCL_SAMPLE_BVH4', 'XCL_SAMPLE_AWC', 'XCL_SAMPLE_XG' | Where-Object { -not (Test-Path "env:$_") } if ($missing) { Write-Host "not set, their tests are skipped: $($missing -join ', ')" } cargo build --workspace if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }