| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071 |
- //! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and
- //! alignment, where each mip and array slice starts, the address of each
- //! element, and copies between tiled memory and linear rows.
- //!
- //! Units: an element is a texel, or a 4x4 block of a block-compressed
- //! format. Mips of one array slice (or one depth slab of a thick 3D texture)
- //! are stored together, smallest first: the mip tail (the small mips sharing
- //! one block) at offset 0, mip 0 last.
- //!
- //! The algorithm follows AMD's address library (addrlib), as shipped in Mesa
- //! under `src/amd/addrlib`: block dimensions, mip placement and mip tails
- //! from `gfx10addrlib.cpp` and `addrlib2.cpp`
- //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`,
- //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`,
- //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile
- //! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on
- //! RDNA2). addrlib carries this notice:
- //!
- //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
- //! SPDX-License-Identifier: MIT
- //!
- //! Permission is hereby granted, free of charge, to any person obtaining a
- //! copy of this software and associated documentation files (the
- //! "Software"), to deal in the Software without restriction, including
- //! without limitation the rights to use, copy, modify, merge, publish,
- //! distribute, sublicense, and/or sell copies of the Software, and to permit
- //! persons to whom the Software is furnished to do so, subject to the
- //! following conditions: the above copyright notice and this permission
- //! notice shall be included in all copies or substantial portions of the
- //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- //! EXPRESS OR IMPLIED.
- /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order).
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
- pub struct Swizzle(pub u32);
- impl Swizzle {
- pub const LINEAR: Swizzle = Swizzle(0);
- pub const SW_256B_S: Swizzle = Swizzle(1);
- pub const SW_256B_D: Swizzle = Swizzle(2);
- pub const SW_4KB_S: Swizzle = Swizzle(5);
- pub const SW_4KB_D: Swizzle = Swizzle(6);
- pub const SW_64KB_S: Swizzle = Swizzle(9);
- pub const SW_64KB_D: Swizzle = Swizzle(10);
- pub const SW_64KB_S_T: Swizzle = Swizzle(17);
- pub const SW_64KB_D_T: Swizzle = Swizzle(18);
- pub const SW_4KB_S_X: Swizzle = Swizzle(21);
- pub const SW_4KB_D_X: Swizzle = Swizzle(22);
- pub const SW_4KB_R_X: Swizzle = Swizzle(23);
- pub const SW_64KB_Z_X: Swizzle = Swizzle(24);
- pub const SW_64KB_S_X: Swizzle = Swizzle(25);
- pub const SW_64KB_D_X: Swizzle = Swizzle(26);
- pub const SW_64KB_R_X: Swizzle = Swizzle(27);
- /// log2 of the block size in bytes (0 for linear); `None` for modes
- /// GFX10 does not have.
- pub fn block_log2(self) -> Option<u32> {
- Some(match self.0 {
- 0 => 0,
- 1 | 2 => 8,
- 5 | 6 | 21..=23 => 12,
- 9 | 10 | 17 | 18 | 24..=27 => 16,
- _ => return None,
- })
- }
- fn standard(self) -> bool {
- matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25)
- }
- fn display(self) -> bool {
- matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26)
- }
- fn z_order(self) -> bool {
- self.0 == 24
- }
- /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the
- /// GPU's pipe configuration.
- pub fn xor(self) -> bool {
- self.0 >= 16
- }
- }
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub enum Dimension {
- Tex1d,
- Tex2d,
- Tex3d,
- }
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub enum Error {
- /// The description makes no texture (zero size, bad element size, a
- /// mode this dimension cannot use, too many mips).
- Invalid,
- /// A valid layout whose addressing is not implemented here.
- Unsupported,
- /// A buffer is smaller than the layout or the rows need.
- TooSmall,
- }
- /// One plane of a texture.
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub struct Desc {
- pub dimension: Dimension,
- /// In texels.
- pub width: u32,
- pub height: u32,
- /// Depth of a 3D texture, else the array size.
- pub depth: u32,
- pub mips: u32,
- /// 1, 2, 4, 8 or 16.
- pub element_bytes: u32,
- /// Texels per element side: 1, or 4 for block compression.
- pub block: u32,
- pub samples: u32,
- pub swizzle: Swizzle,
- }
- /// Elements along one side of mip `mip`, as data and copies see it: texels
- /// halve rounding down (to at least 1), then round up to whole elements.
- fn dim(texels: u32, mip: u32, block: u32) -> u32 {
- (texels >> mip).max(1).div_ceil(block)
- }
- /// Elements along one side of mip `mip` for placement (padding, tail,
- /// offsets): addrlib halves mip 0's elements rounding up, which can be one
- /// more than [`dim`] for odd sizes.
- fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 {
- texels.max(1).div_ceil(block).div_ceil(1 << mip)
- }
- /// Where one mip lives inside a slice.
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub struct Mip {
- /// Size in elements (depth 1 unless the texture is 3D).
- pub width: u32,
- pub height: u32,
- pub depth: u32,
- /// Padded size in elements: whole blocks, or the tail's share of one.
- pub pitch: u32,
- pub rows: u32,
- pub depth_pitch: u32,
- /// Byte offset of its first block in the slice (0 in the tail).
- pub offset: u64,
- /// In the mip tail: byte offset inside the tail block and the element
- /// position the mip starts at.
- pub tail: Option<Tail>,
- }
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub struct Tail {
- pub offset: u32,
- pub x: u32,
- pub y: u32,
- }
- #[derive(Debug, Clone, PartialEq, Eq)]
- pub struct Layout {
- pub desc: Desc,
- /// Block dimensions in elements (linear: the pitch alignment, 1, 1).
- pub block: [u32; 3],
- /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes).
- pub thick: bool,
- /// Array slices, depth slabs of `block[2]` slices (thick), or depth
- /// slices (thin and linear 3D).
- pub slices: u32,
- /// Bytes of one slice: its whole mip chain.
- pub slice_size: u64,
- pub size: u64,
- pub alignment: u64,
- /// The first mip in the tail; `mips.len()` without one.
- pub first_tail_mip: u32,
- pub mips: Vec<Mip>,
- /// Byte offsets inside a block of each element coordinate bit, per
- /// axis; empty for linear and unsupported modes.
- pattern: [Vec<u32>; 3],
- }
- /// Micro tile (256 bytes) patterns by log2 of the element size: for each
- /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...),
- /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S`
- /// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`,
- /// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger
- /// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn.
- const MICRO: [[&[u8; 16]; 5]; 3] = [
- [
- b"x0x1x2x3y0y1y2y3",
- b"--x0x1x2y0y1y2x3",
- b"----x0x1y0y1y2x2",
- b"------x0y0y1x1x2",
- b"--------y0y1x0x1",
- ],
- [
- b"x0x1x2y1y0y2x3y3",
- b"--x0x1x2y0y1y2x3",
- b"----x0x1y0y1x2y2",
- b"------x0y0x1x2y1",
- b"--------x0y0x1y1",
- ],
- [
- b"x0x1z0y0z1y1x2z2",
- b"--x0z0y0z1y1x1z2",
- b"----x0y0z0y1x1z1",
- b"------x0z0y0x1z1",
- b"--------z0y0x0z1",
- ],
- ];
- /// For each axis, the address bit each coordinate bit lands on.
- fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec<u32>; 3] {
- let mut axes: [Vec<u32>; 3] = Default::default();
- let micro = MICRO[kind][element_log2 as usize];
- for bit in 0..8u32 {
- let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]);
- let axis = match axis {
- b'x' => 0,
- b'y' => 1,
- b'z' => 2,
- _ => continue,
- };
- let index = usize::from(index - b'0');
- let to = &mut axes[axis];
- if to.len() <= index {
- to.resize(index + 1, 0);
- }
- to[index] = bit;
- }
- let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] };
- for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) {
- axes[*axis].push(bit);
- }
- axes
- }
- /// Byte offsets inside a block for coordinates 0..2^bits of one axis.
- fn spread(bits: &[u32]) -> Vec<u32> {
- (0..1u32 << bits.len())
- .map(|c| {
- bits.iter()
- .enumerate()
- .map(|(i, &to)| ((c >> i) & 1) << to)
- .sum()
- })
- .collect()
- }
- const MAX_MIPS: u32 = 16;
- /// The largest width, height and depth (or array size) accepted, in texels.
- /// GFX10's image descriptors hold at most 16384 texels per side, so no
- /// texture the GPU can use is refused. The bound also keeps every size
- /// computed below within `u64` (and its `u32` steps), which unchecked
- /// values from a title would otherwise overflow.
- const MAX_EXTENT: u32 = 1 << 14;
- /// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
- const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]];
- const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]];
- const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]];
- impl Layout {
- pub fn new(desc: &Desc) -> Result<Layout, Error> {
- let d = *desc;
- let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?;
- let valid = (1..=MAX_EXTENT).contains(&d.width)
- && (1..=MAX_EXTENT).contains(&d.height)
- && (1..=MAX_EXTENT).contains(&d.depth)
- && (1..=MAX_MIPS).contains(&d.mips)
- && d.element_bytes.is_power_of_two()
- && d.element_bytes <= 16
- && matches!(d.block, 1 | 4)
- && d.samples.is_power_of_two()
- && d.samples <= 8
- && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1))
- && (d.dimension != Dimension::Tex1d || d.height == 1)
- && (d.dimension != Dimension::Tex3d
- || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27));
- if !valid {
- return Err(Error::Invalid);
- }
- if block_log2 == 0 {
- Ok(Layout::linear(d))
- } else {
- Ok(Layout::tiled(d, block_log2))
- }
- }
- /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed
- /// smallest first, a 3D texture's depth slices each hold the chain.
- fn linear(d: Desc) -> Layout {
- let bpe = u64::from(d.element_bytes);
- let align = 256 / d.element_bytes;
- let three_d = d.dimension == Dimension::Tex3d;
- let mut mips = vec![];
- let mut offset = 0;
- for i in (0..d.mips).rev() {
- let h = padded_dim(d.height, i, d.block);
- let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align);
- mips.push(Mip {
- width: dim(d.width, i, d.block),
- height: dim(d.height, i, d.block),
- depth: if three_d { dim(d.depth, i, 1) } else { 1 },
- pitch,
- rows: h,
- depth_pitch: if three_d { d.depth } else { 1 },
- offset,
- tail: None,
- });
- offset += u64::from(pitch) * u64::from(h) * bpe;
- }
- mips.reverse();
- Layout {
- desc: d,
- block: [align, 1, 1],
- thick: false,
- slices: d.depth,
- slice_size: offset,
- size: offset * u64::from(d.depth),
- alignment: 256,
- first_tail_mip: d.mips,
- mips,
- pattern: Default::default(),
- }
- }
- fn tiled(d: Desc, block_log2: u32) -> Layout {
- let element_log2 = d.element_bytes.trailing_zeros();
- let bpe = u64::from(d.element_bytes);
- let block_bytes = 1u64 << block_log2;
- let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display());
- let block = if thick {
- // ComputeThickBlockDimension
- let amp = (block_log2 - 10) / 3;
- let rest = (block_log2 - 10) % 3;
- let b = BLOCK_1K_3D[element_log2 as usize];
- [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))]
- } else {
- // ComputeThinBlockDimension
- let samples_log2 = d.samples.trailing_zeros();
- let elements_log2 = block_log2 - element_log2 - samples_log2;
- let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0;
- let w = (elements_log2 + u32::from(wide)) / 2;
- [1 << w, 1 << (elements_log2 - w), 1]
- };
- let slices = d.depth.next_multiple_of(block[2]);
- let three_d = d.dimension == Dimension::Tex3d;
- // Mip depths placed by a thick layout (thin ones store depth as
- // slices).
- let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 };
- let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 };
- let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block));
- let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block));
- let mut mips = Vec::with_capacity(d.mips as usize);
- let mut first_tail_mip = d.mips;
- let mut slice_size = 0u64;
- if d.mips == 1 {
- mips.push(Mip {
- width: width(0),
- height: height(0),
- depth: depth_of(0),
- pitch: width(0).next_multiple_of(block[0]),
- rows: height(0).next_multiple_of(block[1]),
- depth_pitch: if three_d { slices } else { 1 },
- offset: 0,
- tail: None,
- });
- slice_size = u64::from(mips[0].pitch)
- * u64::from(mips[0].rows)
- * bpe
- * u64::from(d.samples);
- } else {
- // GetMipTailDim: the largest mip the tail takes.
- let mut tail_max = block;
- if thick {
- match block_log2 % 3 {
- 0 => tail_max[1] >>= 1,
- 1 => tail_max[0] >>= 1,
- _ => tail_max[2] >>= 1,
- }
- } else {
- tail_max[0] >>= 1;
- }
- // GetMaxNumMipsInTail; 256-byte blocks have no tail
- // (`ComputeSurfaceInfoMicroTiled`).
- let effective = if thick {
- block_log2 - (block_log2 - 8) / 3
- } else {
- block_log2
- };
- let max_in_tail = match effective {
- 8 => 0,
- 9..=11 => 1 + (1 << (effective - 9)),
- _ => effective - 4,
- };
- // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit.
- let mut fixed = tail_max;
- if d.swizzle.z_order() && element_log2 <= 1 {
- let b = BLOCK_256_2D[element_log2 as usize];
- fixed[0] /= b[0] / BLOCK_256_2D[2][0];
- fixed[1] /= b[1] / BLOCK_256_2D[2][1];
- }
- let mut sizes = vec![];
- for i in 0..d.mips {
- let (w, h) = padded(i);
- if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail {
- first_tail_mip = i;
- slice_size += block_bytes / u64::from(block[2]);
- break;
- }
- let pitch = w.next_multiple_of(block[0]);
- let rows = h.next_multiple_of(block[1]);
- let depth = mip_depth(i).next_multiple_of(block[2]);
- let one = u64::from(pitch) * u64::from(rows) * bpe;
- slice_size += one;
- sizes.push(one * u64::from(block[2]));
- mips.push(Mip {
- width: width(i),
- height: height(i),
- depth: depth_of(i),
- pitch,
- rows,
- depth_pitch: if three_d { depth } else { 1 },
- offset: 0,
- tail: None,
- });
- }
- // Standard mips from the smallest up, after the tail block.
- let mut offset = if first_tail_mip < d.mips {
- block_bytes
- } else {
- 0
- };
- for i in (0..first_tail_mip as usize).rev() {
- mips[i].offset = offset;
- offset += sizes[i];
- }
- let micro = if thick {
- let b = BLOCK_256_3D[element_log2 as usize];
- [b[0], b[1]]
- } else {
- BLOCK_256_2D[element_log2 as usize]
- };
- let (mut pitch, mut rows) = (tail_max[0], tail_max[1]);
- for i in first_tail_mip..d.mips {
- let m = max_in_tail - 1 - (i - first_tail_mip);
- let offset = if m > 6 { 16 << m } else { m << 8 };
- // Address bits 8.. of the offset, odd ones x, even ones y.
- let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum();
- let (mut x, mut y): (u32, u32) = (bits(9), bits(8));
- if block_log2 & 1 != 0 {
- std::mem::swap(&mut x, &mut y);
- if element_log2 & 1 != 0 {
- y = (y << 1) | (x & 1);
- x >>= 1;
- }
- }
- mips.push(Mip {
- width: width(i),
- height: height(i),
- depth: depth_of(i),
- pitch,
- rows,
- depth_pitch: if thick {
- mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2])
- } else {
- 1
- },
- offset: 0,
- tail: Some(Tail {
- offset,
- x: x * micro[0],
- y: y * micro[1],
- }),
- });
- pitch = (pitch >> 1).max(micro[0]);
- rows = (rows >> 1).max(micro[1]);
- }
- }
- // Thick layouts store each depth slab's chain together.
- let slab = if thick { u64::from(block[2]) } else { 1 };
- let slice_size = slice_size * slab;
- let slices = slices / block[2];
- let addressable = !d.swizzle.xor() && d.samples == 1;
- let pattern = if addressable {
- let kind = if thick {
- 2
- } else {
- usize::from(d.swizzle.display())
- };
- pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))
- } else {
- Default::default()
- };
- Layout {
- desc: d,
- block,
- thick,
- slices,
- slice_size,
- size: slice_size * u64::from(slices),
- alignment: block_bytes,
- first_tail_mip,
- mips,
- pattern,
- }
- }
- /// Whether [`Layout::offset`] and the copies work for this layout:
- /// linear and the modes without pipe or bank XOR, single-sampled.
- ///
- /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA;
- /// they need the GPU's pipe and bank configuration (Series X and S
- /// differ). Titles use them for render targets and depth, which the
- /// host renders; add them when a title copies into or out of one.
- pub fn addressable(&self) -> bool {
- self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty()
- }
- /// The slice and the depth inside it for `z` (an array slice or a 3D
- /// depth slice).
- fn split(&self, z: u32) -> (u32, u32) {
- if self.thick {
- (z / self.block[2], z % self.block[2])
- } else {
- (z, 0)
- }
- }
- /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or
- /// depth slice `z`. Coordinates must lie inside the mip.
- pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result<u64, Error> {
- let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
- let depth = if self.desc.dimension == Dimension::Tex3d {
- m.depth
- } else {
- self.slices
- };
- let inside = x < m.width && y < m.height && z < depth;
- if !inside || !self.addressable() {
- return Err(if inside {
- Error::Unsupported
- } else {
- Error::Invalid
- });
- }
- let (slice, z) = self.split(z);
- let base = u64::from(slice) * self.slice_size + m.offset;
- if self.desc.swizzle == Swizzle::LINEAR {
- let row = u64::from(y) * u64::from(m.pitch) + u64::from(x);
- return Ok(base + row * u64::from(self.desc.element_bytes));
- }
- Ok(base + self.row(m, y, z) + self.column(m, x))
- }
- /// The part of an address that depends on the row (and depth in a
- /// thick block).
- fn row(&self, m: &Mip, y: u32, z: u32) -> u64 {
- let [bw, bh, _] = self.block;
- let log2 = self.alignment.trailing_zeros();
- // In the tail the pattern of the shifted position gives the mip's
- // offset inside the tail block.
- let y = y + m.tail.map_or(0, |t| t.y);
- let blocks = u64::from(y / bh) * u64::from(m.pitch / bw);
- (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize])
- }
- /// The part of an address that depends on the column.
- fn column(&self, m: &Mip, x: u32) -> u64 {
- let bw = self.block[0];
- let x = x + m.tail.map_or(0, |t| t.x);
- (u64::from(x / bw) << self.alignment.trailing_zeros())
- + u64::from(self.pattern[0][(x % bw) as usize])
- }
- /// Depth slices a subresource of mip `mip` covers: the mip's depth for
- /// 3D textures, else 1 (one array slice).
- pub fn subresource_depth(&self, mip: u32) -> u32 {
- self.mips.get(mip as usize).map_or(0, |m| m.depth)
- }
- /// Copies one subresource out of tiled memory (the whole texture,
- /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice
- /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are
- /// `row_pitch` bytes apart, depth slices `depth_pitch`.
- pub fn detile(
- &self,
- tiled: &[u8],
- mip: u32,
- slice: u32,
- linear: &mut [u8],
- row_pitch: usize,
- depth_pitch: usize,
- ) -> Result<(), Error> {
- let n = self.desc.element_bytes as usize;
- self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
- for (i, len) in runs(t, count, n) {
- linear[l + i * n..][..len].copy_from_slice(&tiled[t[i] as usize..][..len]);
- }
- })
- }
- /// The reverse of [`Layout::detile`]: linear rows into tiled memory.
- pub fn tile(
- &self,
- tiled: &mut [u8],
- mip: u32,
- slice: u32,
- linear: &[u8],
- row_pitch: usize,
- depth_pitch: usize,
- ) -> Result<(), Error> {
- let n = self.desc.element_bytes as usize;
- self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
- for (i, len) in runs(t, count, n) {
- tiled[t[i] as usize..][..len].copy_from_slice(&linear[l + i * n..][..len]);
- }
- })
- }
- /// Calls `row(tiled offsets, linear offset, elements)` for each row of a
- /// subresource, after checking both buffers are large enough.
- #[allow(clippy::too_many_arguments)]
- fn walk(
- &self,
- tiled_len: usize,
- mip: u32,
- slice: u32,
- linear_len: usize,
- row_pitch: usize,
- depth_pitch: usize,
- mut row: impl FnMut(&[u64], usize, usize),
- ) -> Result<(), Error> {
- let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
- let depth = m.depth;
- let first = if self.desc.dimension == Dimension::Tex3d {
- if slice != 0 {
- return Err(Error::Invalid);
- }
- 0
- } else {
- slice
- };
- if first >= self.slices {
- return Err(Error::Invalid);
- }
- if !self.addressable() {
- return Err(Error::Unsupported);
- }
- let n = self.desc.element_bytes as usize;
- let bytes = m.width as usize * n;
- let need = (depth as usize - 1)
- .checked_mul(depth_pitch)
- .zip((m.height as usize - 1).checked_mul(row_pitch))
- .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset))
- .and_then(|offset| offset.checked_add(bytes))
- .ok_or(Error::TooSmall)?;
- if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes {
- return Err(Error::TooSmall);
- }
- let linear = self.desc.swizzle == Swizzle::LINEAR;
- let columns: Vec<u64> = (0..m.width)
- .map(|x| {
- if linear {
- u64::from(x) * n as u64
- } else {
- self.column(m, x)
- }
- })
- .collect();
- let mut offsets = vec![0u64; m.width as usize];
- for z in 0..depth {
- let (s, inner) = self.split(first + z);
- let base = u64::from(s) * self.slice_size + m.offset;
- for y in 0..m.height {
- let start = if linear {
- base + u64::from(y) * u64::from(m.pitch) * n as u64
- } else {
- base + self.row(m, y, inner)
- };
- for (o, c) in offsets.iter_mut().zip(&columns) {
- *o = start + c;
- }
- row(&offsets, z as usize * depth_pitch + y as usize * row_pitch, m.width as usize);
- }
- }
- Ok(())
- }
- }
- /// The first `count` element offsets as runs of contiguous memory: (first
- /// element, bytes), so a linear row (or a swizzle's contiguous columns) is
- /// copied at once rather than element by element.
- fn runs(t: &[u64], count: usize, n: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
- let mut i = 0;
- std::iter::from_fn(move || {
- if i >= count {
- return None;
- }
- let start = i;
- i += 1;
- while i < count && t[i] == t[i - 1] + n as u64 {
- i += 1;
- }
- Some((start, (i - start) * n))
- })
- }
- /// What a DXGI format stores per element: bytes, texels per element side
- /// (4 for block compression), and whether its stencil is a second plane
- /// (the GPU keeps depth and stencil apart).
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub struct Format {
- pub bytes: u32,
- pub block: u32,
- pub stencil: bool,
- }
- /// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video
- /// formats.
- ///
- /// shortcut: those formats have no layout here; add them when a title uses
- /// one.
- pub fn format(dxgi: u32) -> Option<Format> {
- let (bytes, block, stencil) = match dxgi {
- 1..=4 => (16, 1, false),
- 9..=18 => (8, 1, false),
- 19..=22 | 44..=47 => (4, 1, true),
- 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false),
- 48..=59 | 85 | 86 | 115 => (2, 1, false),
- 118..=120 => (2, 1, true),
- 60..=65 => (1, 1, false),
- 70..=72 | 79..=81 => (8, 4, false),
- 73..=78 | 82..=84 | 94..=99 => (16, 4, false),
- _ => return None,
- };
- Some(Format {
- bytes,
- block,
- stencil,
- })
- }
- /// A texture as the console allocates it: a D3D12-style description with
- /// a swizzle mode.
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub struct TextureDesc {
- pub dimension: Dimension,
- /// In texels.
- pub width: u32,
- pub height: u32,
- /// Depth of a 3D texture, else the array size.
- pub depth_or_array: u32,
- /// 0: the full chain.
- pub mips: u32,
- /// DXGI format number.
- pub format: u32,
- pub samples: u32,
- pub swizzle: Swizzle,
- }
- #[derive(Debug, Clone, PartialEq, Eq)]
- pub struct Plane {
- /// From the start of the texture.
- pub offset: u64,
- pub stencil: bool,
- pub layout: Layout,
- }
- /// Every data plane of a texture (depth, then stencil), placed one after
- /// the other.
- ///
- /// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC);
- /// the console adds them to render targets and depth buffers unless the
- /// description denies them, so those are smaller here than on the console.
- /// The host GPU renders them, so nothing reads that memory; add the planes
- /// if a title sizes a pool from console sizes and runs out.
- #[derive(Debug, Clone, PartialEq, Eq)]
- pub struct Texture {
- pub planes: Vec<Plane>,
- pub size: u64,
- pub alignment: u64,
- }
- impl Texture {
- pub fn new(desc: &TextureDesc) -> Result<Texture, Error> {
- let f = format(desc.format).ok_or(Error::Invalid)?;
- let depth3d = if desc.dimension == Dimension::Tex3d {
- desc.depth_or_array
- } else {
- 1
- };
- let mips = match desc.mips {
- 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(),
- n => n,
- };
- let plane = |bytes| Desc {
- dimension: desc.dimension,
- width: desc.width,
- height: desc.height,
- depth: desc.depth_or_array,
- mips,
- element_bytes: bytes,
- block: f.block,
- samples: desc.samples.max(1),
- swizzle: desc.swizzle,
- };
- let mut planes = vec![Plane {
- offset: 0,
- stencil: false,
- layout: Layout::new(&plane(f.bytes))?,
- }];
- if f.stencil {
- let layout = Layout::new(&plane(1))?;
- let offset = planes[0].layout.size.next_multiple_of(layout.alignment);
- planes.push(Plane {
- offset,
- stencil: true,
- layout,
- });
- }
- let last = &planes[planes.len() - 1];
- let size = last.offset + last.layout.size;
- let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1);
- Ok(Texture {
- planes,
- size,
- alignment,
- })
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc {
- Desc {
- dimension: Dimension::Tex2d,
- width: w,
- height: h,
- depth: 1,
- mips,
- element_bytes: bpe,
- block: 1,
- samples: 1,
- swizzle,
- }
- }
- /// Sizes past the hardware's 16384 texels per side are refused instead
- /// of overflowing the size arithmetic (found by random-input testing).
- #[test]
- fn extents_past_the_hardware_limit_are_invalid() {
- for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] {
- let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap();
- assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16);
- for (w, h) in [
- (MAX_EXTENT + 1, 1),
- (1, MAX_EXTENT + 1),
- (u32::MAX, u32::MAX),
- ] {
- let result = Layout::new(&desc(w, h, 1, 16, swizzle));
- assert_eq!(result, Err(Error::Invalid), "{w}x{h}");
- }
- let mut deep = desc(1, 1, 1, 16, swizzle);
- deep.depth = u32::MAX;
- assert_eq!(Layout::new(&deep), Err(Error::Invalid));
- }
- }
- #[test]
- fn blocks_hold_their_size_in_elements() {
- for log2 in [8u32, 12, 16] {
- let swizzle = match log2 {
- 8 => Swizzle::SW_256B_S,
- 12 => Swizzle::SW_4KB_S,
- _ => Swizzle::SW_64KB_D,
- };
- for e in 0..5 {
- let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap();
- let [w, h, d] = l.block;
- assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}");
- // The pattern covers exactly the block's coordinates.
- assert_eq!(l.pattern[0].len() as u32, w);
- assert_eq!(l.pattern[1].len() as u32, h);
- }
- }
- // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture).
- let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap();
- assert_eq!(l.block, [64, 64, 1]);
- assert_eq!((l.size, l.alignment), (65536, 65536));
- }
- /// Every element of every mip and slice lands on its own address, inside
- /// the texture, and tiling then detiling gives the rows back.
- #[test]
- fn addresses_are_a_bijection_and_copies_round_trip() {
- let cases = [
- desc(64, 64, 7, 16, Swizzle::SW_64KB_D),
- desc(100, 60, 7, 4, Swizzle::SW_64KB_D),
- desc(250, 175, 8, 8, Swizzle::SW_4KB_S),
- desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
- desc(40, 9, 3, 2, Swizzle::SW_64KB_S),
- desc(30, 20, 5, 4, Swizzle::LINEAR),
- Desc {
- depth: 3,
- ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
- },
- Desc {
- dimension: Dimension::Tex3d,
- depth: 16,
- ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S)
- },
- ];
- for d in cases {
- let l = Layout::new(&d).unwrap();
- let mut seen = vec![false; l.size as usize];
- let mut tiled = vec![0u8; l.size as usize];
- let n = d.element_bytes as usize;
- let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth };
- for slice in 0..slices {
- for mip in 0..d.mips {
- let m = l.mips[mip as usize];
- let row = m.width as usize * n;
- let plane = row * m.height as usize;
- let linear: Vec<u8> = (0..plane * m.depth as usize)
- .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8)
- .collect();
- l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap();
- let mut back = vec![0u8; linear.len()];
- l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap();
- assert_eq!(back, linear, "{d:?} mip {mip}");
- for z in 0..m.depth {
- for y in 0..m.height {
- for x in 0..m.width {
- let at = l.offset(mip, x, y, slice + z).unwrap() as usize;
- assert!(at + n <= seen.len(), "{d:?} mip {mip} outside");
- assert!(at.is_multiple_of(n));
- assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice");
- seen[at] = true;
- }
- }
- }
- }
- }
- }
- }
- /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
- /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
- /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
- #[test]
- fn hand_checked_addresses() {
- let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap();
- assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2));
- assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6));
- assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7));
- assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8));
- assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14)));
- let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap();
- assert_eq!(l.block, [16, 16, 1]);
- assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4));
- assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6));
- // Blocks row by row: (16, 0) is the second block, (0, 16) the third.
- assert_eq!(l.offset(0, 16, 0, 0), Ok(4096));
- assert_eq!(l.offset(0, 0, 16, 0), Ok(8192));
- }
- /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8,
- /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail.
- #[test]
- fn mip_tail_comes_first() {
- let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap();
- assert_eq!(l.first_tail_mip, 1);
- assert_eq!(l.size, 2 * 65536);
- assert_eq!(l.mips[0].offset, 65536);
- assert_eq!(
- l.mips[1].tail,
- Some(Tail {
- offset: 32768,
- x: 32,
- y: 0
- })
- );
- assert_eq!(l.offset(1, 0, 0, 0), Ok(32768));
- // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside.
- let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap();
- assert_eq!(l.first_tail_mip, 3);
- assert_eq!(l.mips[2].offset, 4096);
- assert_eq!(l.mips[1].offset, 8192);
- assert_eq!(l.mips[0].offset, 8192 + 16384);
- }
- #[test]
- fn depth_stencil_is_two_planes() {
- let t = Texture::new(&TextureDesc {
- dimension: Dimension::Tex2d,
- width: 1920,
- height: 1080,
- depth_or_array: 1,
- mips: 1,
- format: 20,
- samples: 1,
- swizzle: Swizzle::SW_64KB_Z_X,
- })
- .unwrap();
- assert_eq!(t.planes.len(), 2);
- // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks.
- assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4);
- assert_eq!(t.planes[1].offset, t.planes[0].layout.size);
- assert_eq!(t.planes[1].layout.size, 2048 * 1280);
- assert!(!t.planes[0].layout.addressable());
- }
- #[test]
- fn texture_copies_reject_overflowing_pitches() {
- let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap();
- let mut tiled = vec![0; layout.size as usize];
- let mut linear = [0; 32];
- assert_eq!(
- layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0),
- Err(Error::TooSmall)
- );
- assert_eq!(
- layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0),
- Err(Error::TooSmall)
- );
- }
- #[test]
- fn volume_copy_rejects_overflowing_depth_pitch() {
- let layout = Layout::new(&Desc {
- dimension: Dimension::Tex3d,
- depth: 3,
- ..desc(4, 2, 1, 4, Swizzle::LINEAR)
- })
- .unwrap();
- let tiled = vec![0; layout.size as usize];
- let mut linear = [0; 96];
- assert_eq!(
- layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX),
- Err(Error::TooSmall)
- );
- }
- #[test]
- fn bad_descriptions_and_buffers_are_refused() {
- assert_eq!(
- Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)),
- Err(Error::Invalid)
- );
- assert_eq!(
- Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)),
- Err(Error::Invalid)
- );
- assert_eq!(
- Layout::new(&desc(4, 4, 1, 4, Swizzle(3))),
- Err(Error::Invalid)
- );
- let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap();
- let mut out = vec![0; 64 * 64 * 4];
- assert_eq!(
- l.detile(&[0; 100], 0, 0, &mut out, 256, 0),
- Err(Error::TooSmall)
- );
- assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid));
- }
- }
|