texture.rs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. //! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and
  2. //! alignment, where each mip and array slice starts, the address of each
  3. //! element, and copies between tiled memory and linear rows.
  4. //!
  5. //! Units: an element is a texel, or a 4x4 block of a block-compressed
  6. //! format. Mips of one array slice (or one depth slab of a thick 3D texture)
  7. //! are stored together, smallest first: the mip tail (the small mips sharing
  8. //! one block) at offset 0, mip 0 last.
  9. //!
  10. //! The algorithm follows AMD's address library (addrlib), as shipped in Mesa
  11. //! under `src/amd/addrlib`: block dimensions, mip placement and mip tails
  12. //! from `gfx10addrlib.cpp` and `addrlib2.cpp`
  13. //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`,
  14. //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`,
  15. //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile
  16. //! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on
  17. //! RDNA2). addrlib carries this notice:
  18. //!
  19. //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
  20. //! SPDX-License-Identifier: MIT
  21. //!
  22. //! Permission is hereby granted, free of charge, to any person obtaining a
  23. //! copy of this software and associated documentation files (the
  24. //! "Software"), to deal in the Software without restriction, including
  25. //! without limitation the rights to use, copy, modify, merge, publish,
  26. //! distribute, sublicense, and/or sell copies of the Software, and to permit
  27. //! persons to whom the Software is furnished to do so, subject to the
  28. //! following conditions: the above copyright notice and this permission
  29. //! notice shall be included in all copies or substantial portions of the
  30. //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. //! EXPRESS OR IMPLIED.
  32. /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order).
  33. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  34. pub struct Swizzle(pub u32);
  35. impl Swizzle {
  36. pub const LINEAR: Swizzle = Swizzle(0);
  37. pub const SW_256B_S: Swizzle = Swizzle(1);
  38. pub const SW_256B_D: Swizzle = Swizzle(2);
  39. pub const SW_4KB_S: Swizzle = Swizzle(5);
  40. pub const SW_4KB_D: Swizzle = Swizzle(6);
  41. pub const SW_64KB_S: Swizzle = Swizzle(9);
  42. pub const SW_64KB_D: Swizzle = Swizzle(10);
  43. pub const SW_64KB_S_T: Swizzle = Swizzle(17);
  44. pub const SW_64KB_D_T: Swizzle = Swizzle(18);
  45. pub const SW_4KB_S_X: Swizzle = Swizzle(21);
  46. pub const SW_4KB_D_X: Swizzle = Swizzle(22);
  47. pub const SW_4KB_R_X: Swizzle = Swizzle(23);
  48. pub const SW_64KB_Z_X: Swizzle = Swizzle(24);
  49. pub const SW_64KB_S_X: Swizzle = Swizzle(25);
  50. pub const SW_64KB_D_X: Swizzle = Swizzle(26);
  51. pub const SW_64KB_R_X: Swizzle = Swizzle(27);
  52. /// log2 of the block size in bytes (0 for linear); `None` for modes
  53. /// GFX10 does not have.
  54. pub fn block_log2(self) -> Option<u32> {
  55. Some(match self.0 {
  56. 0 => 0,
  57. 1 | 2 => 8,
  58. 5 | 6 | 21..=23 => 12,
  59. 9 | 10 | 17 | 18 | 24..=27 => 16,
  60. _ => return None,
  61. })
  62. }
  63. fn standard(self) -> bool {
  64. matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25)
  65. }
  66. fn display(self) -> bool {
  67. matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26)
  68. }
  69. fn z_order(self) -> bool {
  70. self.0 == 24
  71. }
  72. /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the
  73. /// GPU's pipe configuration.
  74. pub fn xor(self) -> bool {
  75. self.0 >= 16
  76. }
  77. }
  78. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  79. pub enum Dimension {
  80. Tex1d,
  81. Tex2d,
  82. Tex3d,
  83. }
  84. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  85. pub enum Error {
  86. /// The description makes no texture (zero size, bad element size, a
  87. /// mode this dimension cannot use, too many mips).
  88. Invalid,
  89. /// A valid layout whose addressing is not implemented here.
  90. Unsupported,
  91. /// A buffer is smaller than the layout or the rows need.
  92. TooSmall,
  93. }
  94. /// One plane of a texture.
  95. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  96. pub struct Desc {
  97. pub dimension: Dimension,
  98. /// In texels.
  99. pub width: u32,
  100. pub height: u32,
  101. /// Depth of a 3D texture, else the array size.
  102. pub depth: u32,
  103. pub mips: u32,
  104. /// 1, 2, 4, 8 or 16.
  105. pub element_bytes: u32,
  106. /// Texels per element side: 1, or 4 for block compression.
  107. pub block: u32,
  108. pub samples: u32,
  109. pub swizzle: Swizzle,
  110. }
  111. /// Elements along one side of mip `mip`, as data and copies see it: texels
  112. /// halve rounding down (to at least 1), then round up to whole elements.
  113. fn dim(texels: u32, mip: u32, block: u32) -> u32 {
  114. (texels >> mip).max(1).div_ceil(block)
  115. }
  116. /// Elements along one side of mip `mip` for placement (padding, tail,
  117. /// offsets): addrlib halves mip 0's elements rounding up, which can be one
  118. /// more than [`dim`] for odd sizes.
  119. fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 {
  120. texels.max(1).div_ceil(block).div_ceil(1 << mip)
  121. }
  122. /// Where one mip lives inside a slice.
  123. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  124. pub struct Mip {
  125. /// Size in elements (depth 1 unless the texture is 3D).
  126. pub width: u32,
  127. pub height: u32,
  128. pub depth: u32,
  129. /// Padded size in elements: whole blocks, or the tail's share of one.
  130. pub pitch: u32,
  131. pub rows: u32,
  132. pub depth_pitch: u32,
  133. /// Byte offset of its first block in the slice (0 in the tail).
  134. pub offset: u64,
  135. /// In the mip tail: byte offset inside the tail block and the element
  136. /// position the mip starts at.
  137. pub tail: Option<Tail>,
  138. }
  139. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  140. pub struct Tail {
  141. pub offset: u32,
  142. pub x: u32,
  143. pub y: u32,
  144. }
  145. #[derive(Debug, Clone, PartialEq, Eq)]
  146. pub struct Layout {
  147. pub desc: Desc,
  148. /// Block dimensions in elements (linear: the pitch alignment, 1, 1).
  149. pub block: [u32; 3],
  150. /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes).
  151. pub thick: bool,
  152. /// Array slices, depth slabs of `block[2]` slices (thick), or depth
  153. /// slices (thin and linear 3D).
  154. pub slices: u32,
  155. /// Bytes of one slice: its whole mip chain.
  156. pub slice_size: u64,
  157. pub size: u64,
  158. pub alignment: u64,
  159. /// The first mip in the tail; `mips.len()` without one.
  160. pub first_tail_mip: u32,
  161. pub mips: Vec<Mip>,
  162. /// Byte offsets inside a block of each element coordinate bit, per
  163. /// axis; empty for linear and unsupported modes.
  164. pattern: [Vec<u32>; 3],
  165. }
  166. /// Micro tile (256 bytes) patterns by log2 of the element size: for each
  167. /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...),
  168. /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S`
  169. /// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`,
  170. /// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger
  171. /// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn.
  172. const MICRO: [[&[u8; 16]; 5]; 3] = [
  173. [
  174. b"x0x1x2x3y0y1y2y3",
  175. b"--x0x1x2y0y1y2x3",
  176. b"----x0x1y0y1y2x2",
  177. b"------x0y0y1x1x2",
  178. b"--------y0y1x0x1",
  179. ],
  180. [
  181. b"x0x1x2y1y0y2x3y3",
  182. b"--x0x1x2y0y1y2x3",
  183. b"----x0x1y0y1x2y2",
  184. b"------x0y0x1x2y1",
  185. b"--------x0y0x1y1",
  186. ],
  187. [
  188. b"x0x1z0y0z1y1x2z2",
  189. b"--x0z0y0z1y1x1z2",
  190. b"----x0y0z0y1x1z1",
  191. b"------x0z0y0x1z1",
  192. b"--------z0y0x0z1",
  193. ],
  194. ];
  195. /// For each axis, the address bit each coordinate bit lands on.
  196. fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec<u32>; 3] {
  197. let mut axes: [Vec<u32>; 3] = Default::default();
  198. let micro = MICRO[kind][element_log2 as usize];
  199. for bit in 0..8u32 {
  200. let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]);
  201. let axis = match axis {
  202. b'x' => 0,
  203. b'y' => 1,
  204. b'z' => 2,
  205. _ => continue,
  206. };
  207. let index = usize::from(index - b'0');
  208. let to = &mut axes[axis];
  209. if to.len() <= index {
  210. to.resize(index + 1, 0);
  211. }
  212. to[index] = bit;
  213. }
  214. let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] };
  215. for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) {
  216. axes[*axis].push(bit);
  217. }
  218. axes
  219. }
  220. /// Byte offsets inside a block for coordinates 0..2^bits of one axis.
  221. fn spread(bits: &[u32]) -> Vec<u32> {
  222. (0..1u32 << bits.len())
  223. .map(|c| {
  224. bits.iter()
  225. .enumerate()
  226. .map(|(i, &to)| ((c >> i) & 1) << to)
  227. .sum()
  228. })
  229. .collect()
  230. }
  231. const MAX_MIPS: u32 = 16;
  232. /// The largest width, height and depth (or array size) accepted, in texels.
  233. /// GFX10's image descriptors hold at most 16384 texels per side, so no
  234. /// texture the GPU can use is refused. The bound also keeps every size
  235. /// computed below within `u64` (and its `u32` steps), which unchecked
  236. /// values from a title would otherwise overflow.
  237. const MAX_EXTENT: u32 = 1 << 14;
  238. /// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
  239. const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]];
  240. const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]];
  241. const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]];
  242. impl Layout {
  243. pub fn new(desc: &Desc) -> Result<Layout, Error> {
  244. let d = *desc;
  245. let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?;
  246. let valid = (1..=MAX_EXTENT).contains(&d.width)
  247. && (1..=MAX_EXTENT).contains(&d.height)
  248. && (1..=MAX_EXTENT).contains(&d.depth)
  249. && (1..=MAX_MIPS).contains(&d.mips)
  250. && d.element_bytes.is_power_of_two()
  251. && d.element_bytes <= 16
  252. && matches!(d.block, 1 | 4)
  253. && d.samples.is_power_of_two()
  254. && d.samples <= 8
  255. && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1))
  256. && (d.dimension != Dimension::Tex1d || d.height == 1)
  257. && (d.dimension != Dimension::Tex3d
  258. || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27));
  259. if !valid {
  260. return Err(Error::Invalid);
  261. }
  262. if block_log2 == 0 {
  263. Ok(Layout::linear(d))
  264. } else {
  265. Ok(Layout::tiled(d, block_log2))
  266. }
  267. }
  268. /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed
  269. /// smallest first, a 3D texture's depth slices each hold the chain.
  270. fn linear(d: Desc) -> Layout {
  271. let bpe = u64::from(d.element_bytes);
  272. let align = 256 / d.element_bytes;
  273. let three_d = d.dimension == Dimension::Tex3d;
  274. let mut mips = vec![];
  275. let mut offset = 0;
  276. for i in (0..d.mips).rev() {
  277. let h = padded_dim(d.height, i, d.block);
  278. let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align);
  279. mips.push(Mip {
  280. width: dim(d.width, i, d.block),
  281. height: dim(d.height, i, d.block),
  282. depth: if three_d { dim(d.depth, i, 1) } else { 1 },
  283. pitch,
  284. rows: h,
  285. depth_pitch: if three_d { d.depth } else { 1 },
  286. offset,
  287. tail: None,
  288. });
  289. offset += u64::from(pitch) * u64::from(h) * bpe;
  290. }
  291. mips.reverse();
  292. Layout {
  293. desc: d,
  294. block: [align, 1, 1],
  295. thick: false,
  296. slices: d.depth,
  297. slice_size: offset,
  298. size: offset * u64::from(d.depth),
  299. alignment: 256,
  300. first_tail_mip: d.mips,
  301. mips,
  302. pattern: Default::default(),
  303. }
  304. }
  305. fn tiled(d: Desc, block_log2: u32) -> Layout {
  306. let element_log2 = d.element_bytes.trailing_zeros();
  307. let bpe = u64::from(d.element_bytes);
  308. let block_bytes = 1u64 << block_log2;
  309. let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display());
  310. let block = if thick {
  311. // ComputeThickBlockDimension
  312. let amp = (block_log2 - 10) / 3;
  313. let rest = (block_log2 - 10) % 3;
  314. let b = BLOCK_1K_3D[element_log2 as usize];
  315. [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))]
  316. } else {
  317. // ComputeThinBlockDimension
  318. let samples_log2 = d.samples.trailing_zeros();
  319. let elements_log2 = block_log2 - element_log2 - samples_log2;
  320. let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0;
  321. let w = (elements_log2 + u32::from(wide)) / 2;
  322. [1 << w, 1 << (elements_log2 - w), 1]
  323. };
  324. let slices = d.depth.next_multiple_of(block[2]);
  325. let three_d = d.dimension == Dimension::Tex3d;
  326. // Mip depths placed by a thick layout (thin ones store depth as
  327. // slices).
  328. let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 };
  329. let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 };
  330. let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block));
  331. let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block));
  332. let mut mips = Vec::with_capacity(d.mips as usize);
  333. let mut first_tail_mip = d.mips;
  334. let mut slice_size = 0u64;
  335. if d.mips == 1 {
  336. mips.push(Mip {
  337. width: width(0),
  338. height: height(0),
  339. depth: depth_of(0),
  340. pitch: width(0).next_multiple_of(block[0]),
  341. rows: height(0).next_multiple_of(block[1]),
  342. depth_pitch: if three_d { slices } else { 1 },
  343. offset: 0,
  344. tail: None,
  345. });
  346. slice_size = u64::from(mips[0].pitch)
  347. * u64::from(mips[0].rows)
  348. * bpe
  349. * u64::from(d.samples);
  350. } else {
  351. // GetMipTailDim: the largest mip the tail takes.
  352. let mut tail_max = block;
  353. if thick {
  354. match block_log2 % 3 {
  355. 0 => tail_max[1] >>= 1,
  356. 1 => tail_max[0] >>= 1,
  357. _ => tail_max[2] >>= 1,
  358. }
  359. } else {
  360. tail_max[0] >>= 1;
  361. }
  362. // GetMaxNumMipsInTail; 256-byte blocks have no tail
  363. // (`ComputeSurfaceInfoMicroTiled`).
  364. let effective = if thick {
  365. block_log2 - (block_log2 - 8) / 3
  366. } else {
  367. block_log2
  368. };
  369. let max_in_tail = match effective {
  370. 8 => 0,
  371. 9..=11 => 1 + (1 << (effective - 9)),
  372. _ => effective - 4,
  373. };
  374. // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit.
  375. let mut fixed = tail_max;
  376. if d.swizzle.z_order() && element_log2 <= 1 {
  377. let b = BLOCK_256_2D[element_log2 as usize];
  378. fixed[0] /= b[0] / BLOCK_256_2D[2][0];
  379. fixed[1] /= b[1] / BLOCK_256_2D[2][1];
  380. }
  381. let mut sizes = vec![];
  382. for i in 0..d.mips {
  383. let (w, h) = padded(i);
  384. if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail {
  385. first_tail_mip = i;
  386. slice_size += block_bytes / u64::from(block[2]);
  387. break;
  388. }
  389. let pitch = w.next_multiple_of(block[0]);
  390. let rows = h.next_multiple_of(block[1]);
  391. let depth = mip_depth(i).next_multiple_of(block[2]);
  392. let one = u64::from(pitch) * u64::from(rows) * bpe;
  393. slice_size += one;
  394. sizes.push(one * u64::from(block[2]));
  395. mips.push(Mip {
  396. width: width(i),
  397. height: height(i),
  398. depth: depth_of(i),
  399. pitch,
  400. rows,
  401. depth_pitch: if three_d { depth } else { 1 },
  402. offset: 0,
  403. tail: None,
  404. });
  405. }
  406. // Standard mips from the smallest up, after the tail block.
  407. let mut offset = if first_tail_mip < d.mips {
  408. block_bytes
  409. } else {
  410. 0
  411. };
  412. for i in (0..first_tail_mip as usize).rev() {
  413. mips[i].offset = offset;
  414. offset += sizes[i];
  415. }
  416. let micro = if thick {
  417. let b = BLOCK_256_3D[element_log2 as usize];
  418. [b[0], b[1]]
  419. } else {
  420. BLOCK_256_2D[element_log2 as usize]
  421. };
  422. let (mut pitch, mut rows) = (tail_max[0], tail_max[1]);
  423. for i in first_tail_mip..d.mips {
  424. let m = max_in_tail - 1 - (i - first_tail_mip);
  425. let offset = if m > 6 { 16 << m } else { m << 8 };
  426. // Address bits 8.. of the offset, odd ones x, even ones y.
  427. let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum();
  428. let (mut x, mut y): (u32, u32) = (bits(9), bits(8));
  429. if block_log2 & 1 != 0 {
  430. std::mem::swap(&mut x, &mut y);
  431. if element_log2 & 1 != 0 {
  432. y = (y << 1) | (x & 1);
  433. x >>= 1;
  434. }
  435. }
  436. mips.push(Mip {
  437. width: width(i),
  438. height: height(i),
  439. depth: depth_of(i),
  440. pitch,
  441. rows,
  442. depth_pitch: if thick {
  443. mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2])
  444. } else {
  445. 1
  446. },
  447. offset: 0,
  448. tail: Some(Tail {
  449. offset,
  450. x: x * micro[0],
  451. y: y * micro[1],
  452. }),
  453. });
  454. pitch = (pitch >> 1).max(micro[0]);
  455. rows = (rows >> 1).max(micro[1]);
  456. }
  457. }
  458. // Thick layouts store each depth slab's chain together.
  459. let slab = if thick { u64::from(block[2]) } else { 1 };
  460. let slice_size = slice_size * slab;
  461. let slices = slices / block[2];
  462. let addressable = !d.swizzle.xor() && d.samples == 1;
  463. let pattern = if addressable {
  464. let kind = if thick {
  465. 2
  466. } else {
  467. usize::from(d.swizzle.display())
  468. };
  469. pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))
  470. } else {
  471. Default::default()
  472. };
  473. Layout {
  474. desc: d,
  475. block,
  476. thick,
  477. slices,
  478. slice_size,
  479. size: slice_size * u64::from(slices),
  480. alignment: block_bytes,
  481. first_tail_mip,
  482. mips,
  483. pattern,
  484. }
  485. }
  486. /// Whether [`Layout::offset`] and the copies work for this layout:
  487. /// linear and the modes without pipe or bank XOR, single-sampled.
  488. ///
  489. /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA;
  490. /// they need the GPU's pipe and bank configuration (Series X and S
  491. /// differ). Titles use them for render targets and depth, which the
  492. /// host renders; add them when a title copies into or out of one.
  493. pub fn addressable(&self) -> bool {
  494. self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty()
  495. }
  496. /// The slice and the depth inside it for `z` (an array slice or a 3D
  497. /// depth slice).
  498. fn split(&self, z: u32) -> (u32, u32) {
  499. if self.thick {
  500. (z / self.block[2], z % self.block[2])
  501. } else {
  502. (z, 0)
  503. }
  504. }
  505. /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or
  506. /// depth slice `z`. Coordinates must lie inside the mip.
  507. pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result<u64, Error> {
  508. let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
  509. let depth = if self.desc.dimension == Dimension::Tex3d {
  510. m.depth
  511. } else {
  512. self.slices
  513. };
  514. let inside = x < m.width && y < m.height && z < depth;
  515. if !inside || !self.addressable() {
  516. return Err(if inside {
  517. Error::Unsupported
  518. } else {
  519. Error::Invalid
  520. });
  521. }
  522. let (slice, z) = self.split(z);
  523. let base = u64::from(slice) * self.slice_size + m.offset;
  524. if self.desc.swizzle == Swizzle::LINEAR {
  525. let row = u64::from(y) * u64::from(m.pitch) + u64::from(x);
  526. return Ok(base + row * u64::from(self.desc.element_bytes));
  527. }
  528. Ok(base + self.row(m, y, z) + self.column(m, x))
  529. }
  530. /// The part of an address that depends on the row (and depth in a
  531. /// thick block).
  532. fn row(&self, m: &Mip, y: u32, z: u32) -> u64 {
  533. let [bw, bh, _] = self.block;
  534. let log2 = self.alignment.trailing_zeros();
  535. // In the tail the pattern of the shifted position gives the mip's
  536. // offset inside the tail block.
  537. let y = y + m.tail.map_or(0, |t| t.y);
  538. let blocks = u64::from(y / bh) * u64::from(m.pitch / bw);
  539. (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize])
  540. }
  541. /// The part of an address that depends on the column.
  542. fn column(&self, m: &Mip, x: u32) -> u64 {
  543. let bw = self.block[0];
  544. let x = x + m.tail.map_or(0, |t| t.x);
  545. (u64::from(x / bw) << self.alignment.trailing_zeros())
  546. + u64::from(self.pattern[0][(x % bw) as usize])
  547. }
  548. /// Depth slices a subresource of mip `mip` covers: the mip's depth for
  549. /// 3D textures, else 1 (one array slice).
  550. pub fn subresource_depth(&self, mip: u32) -> u32 {
  551. self.mips.get(mip as usize).map_or(0, |m| m.depth)
  552. }
  553. /// Copies one subresource out of tiled memory (the whole texture,
  554. /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice
  555. /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are
  556. /// `row_pitch` bytes apart, depth slices `depth_pitch`.
  557. pub fn detile(
  558. &self,
  559. tiled: &[u8],
  560. mip: u32,
  561. slice: u32,
  562. linear: &mut [u8],
  563. row_pitch: usize,
  564. depth_pitch: usize,
  565. ) -> Result<(), Error> {
  566. let n = self.desc.element_bytes as usize;
  567. self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
  568. for (i, len) in runs(t, count, n) {
  569. linear[l + i * n..][..len].copy_from_slice(&tiled[t[i] as usize..][..len]);
  570. }
  571. })
  572. }
  573. /// The reverse of [`Layout::detile`]: linear rows into tiled memory.
  574. pub fn tile(
  575. &self,
  576. tiled: &mut [u8],
  577. mip: u32,
  578. slice: u32,
  579. linear: &[u8],
  580. row_pitch: usize,
  581. depth_pitch: usize,
  582. ) -> Result<(), Error> {
  583. let n = self.desc.element_bytes as usize;
  584. self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
  585. for (i, len) in runs(t, count, n) {
  586. tiled[t[i] as usize..][..len].copy_from_slice(&linear[l + i * n..][..len]);
  587. }
  588. })
  589. }
  590. /// Calls `row(tiled offsets, linear offset, elements)` for each row of a
  591. /// subresource, after checking both buffers are large enough.
  592. #[allow(clippy::too_many_arguments)]
  593. fn walk(
  594. &self,
  595. tiled_len: usize,
  596. mip: u32,
  597. slice: u32,
  598. linear_len: usize,
  599. row_pitch: usize,
  600. depth_pitch: usize,
  601. mut row: impl FnMut(&[u64], usize, usize),
  602. ) -> Result<(), Error> {
  603. let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
  604. let depth = m.depth;
  605. let first = if self.desc.dimension == Dimension::Tex3d {
  606. if slice != 0 {
  607. return Err(Error::Invalid);
  608. }
  609. 0
  610. } else {
  611. slice
  612. };
  613. if first >= self.slices {
  614. return Err(Error::Invalid);
  615. }
  616. if !self.addressable() {
  617. return Err(Error::Unsupported);
  618. }
  619. let n = self.desc.element_bytes as usize;
  620. let bytes = m.width as usize * n;
  621. let need = (depth as usize - 1)
  622. .checked_mul(depth_pitch)
  623. .zip((m.height as usize - 1).checked_mul(row_pitch))
  624. .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset))
  625. .and_then(|offset| offset.checked_add(bytes))
  626. .ok_or(Error::TooSmall)?;
  627. if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes {
  628. return Err(Error::TooSmall);
  629. }
  630. let linear = self.desc.swizzle == Swizzle::LINEAR;
  631. let columns: Vec<u64> = (0..m.width)
  632. .map(|x| {
  633. if linear {
  634. u64::from(x) * n as u64
  635. } else {
  636. self.column(m, x)
  637. }
  638. })
  639. .collect();
  640. let mut offsets = vec![0u64; m.width as usize];
  641. for z in 0..depth {
  642. let (s, inner) = self.split(first + z);
  643. let base = u64::from(s) * self.slice_size + m.offset;
  644. for y in 0..m.height {
  645. let start = if linear {
  646. base + u64::from(y) * u64::from(m.pitch) * n as u64
  647. } else {
  648. base + self.row(m, y, inner)
  649. };
  650. for (o, c) in offsets.iter_mut().zip(&columns) {
  651. *o = start + c;
  652. }
  653. row(&offsets, z as usize * depth_pitch + y as usize * row_pitch, m.width as usize);
  654. }
  655. }
  656. Ok(())
  657. }
  658. }
  659. /// The first `count` element offsets as runs of contiguous memory: (first
  660. /// element, bytes), so a linear row (or a swizzle's contiguous columns) is
  661. /// copied at once rather than element by element.
  662. fn runs(t: &[u64], count: usize, n: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
  663. let mut i = 0;
  664. std::iter::from_fn(move || {
  665. if i >= count {
  666. return None;
  667. }
  668. let start = i;
  669. i += 1;
  670. while i < count && t[i] == t[i - 1] + n as u64 {
  671. i += 1;
  672. }
  673. Some((start, (i - start) * n))
  674. })
  675. }
  676. /// What a DXGI format stores per element: bytes, texels per element side
  677. /// (4 for block compression), and whether its stencil is a second plane
  678. /// (the GPU keeps depth and stencil apart).
  679. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  680. pub struct Format {
  681. pub bytes: u32,
  682. pub block: u32,
  683. pub stencil: bool,
  684. }
  685. /// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video
  686. /// formats.
  687. ///
  688. /// shortcut: those formats have no layout here; add them when a title uses
  689. /// one.
  690. pub fn format(dxgi: u32) -> Option<Format> {
  691. let (bytes, block, stencil) = match dxgi {
  692. 1..=4 => (16, 1, false),
  693. 9..=18 => (8, 1, false),
  694. 19..=22 | 44..=47 => (4, 1, true),
  695. 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false),
  696. 48..=59 | 85 | 86 | 115 => (2, 1, false),
  697. 118..=120 => (2, 1, true),
  698. 60..=65 => (1, 1, false),
  699. 70..=72 | 79..=81 => (8, 4, false),
  700. 73..=78 | 82..=84 | 94..=99 => (16, 4, false),
  701. _ => return None,
  702. };
  703. Some(Format {
  704. bytes,
  705. block,
  706. stencil,
  707. })
  708. }
  709. /// A texture as the console allocates it: a D3D12-style description with
  710. /// a swizzle mode.
  711. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  712. pub struct TextureDesc {
  713. pub dimension: Dimension,
  714. /// In texels.
  715. pub width: u32,
  716. pub height: u32,
  717. /// Depth of a 3D texture, else the array size.
  718. pub depth_or_array: u32,
  719. /// 0: the full chain.
  720. pub mips: u32,
  721. /// DXGI format number.
  722. pub format: u32,
  723. pub samples: u32,
  724. pub swizzle: Swizzle,
  725. }
  726. #[derive(Debug, Clone, PartialEq, Eq)]
  727. pub struct Plane {
  728. /// From the start of the texture.
  729. pub offset: u64,
  730. pub stencil: bool,
  731. pub layout: Layout,
  732. }
  733. /// Every data plane of a texture (depth, then stencil), placed one after
  734. /// the other.
  735. ///
  736. /// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC);
  737. /// the console adds them to render targets and depth buffers unless the
  738. /// description denies them, so those are smaller here than on the console.
  739. /// The host GPU renders them, so nothing reads that memory; add the planes
  740. /// if a title sizes a pool from console sizes and runs out.
  741. #[derive(Debug, Clone, PartialEq, Eq)]
  742. pub struct Texture {
  743. pub planes: Vec<Plane>,
  744. pub size: u64,
  745. pub alignment: u64,
  746. }
  747. impl Texture {
  748. pub fn new(desc: &TextureDesc) -> Result<Texture, Error> {
  749. let f = format(desc.format).ok_or(Error::Invalid)?;
  750. let depth3d = if desc.dimension == Dimension::Tex3d {
  751. desc.depth_or_array
  752. } else {
  753. 1
  754. };
  755. let mips = match desc.mips {
  756. 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(),
  757. n => n,
  758. };
  759. let plane = |bytes| Desc {
  760. dimension: desc.dimension,
  761. width: desc.width,
  762. height: desc.height,
  763. depth: desc.depth_or_array,
  764. mips,
  765. element_bytes: bytes,
  766. block: f.block,
  767. samples: desc.samples.max(1),
  768. swizzle: desc.swizzle,
  769. };
  770. let mut planes = vec![Plane {
  771. offset: 0,
  772. stencil: false,
  773. layout: Layout::new(&plane(f.bytes))?,
  774. }];
  775. if f.stencil {
  776. let layout = Layout::new(&plane(1))?;
  777. let offset = planes[0].layout.size.next_multiple_of(layout.alignment);
  778. planes.push(Plane {
  779. offset,
  780. stencil: true,
  781. layout,
  782. });
  783. }
  784. let last = &planes[planes.len() - 1];
  785. let size = last.offset + last.layout.size;
  786. let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1);
  787. Ok(Texture {
  788. planes,
  789. size,
  790. alignment,
  791. })
  792. }
  793. }
  794. #[cfg(test)]
  795. mod tests {
  796. use super::*;
  797. fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc {
  798. Desc {
  799. dimension: Dimension::Tex2d,
  800. width: w,
  801. height: h,
  802. depth: 1,
  803. mips,
  804. element_bytes: bpe,
  805. block: 1,
  806. samples: 1,
  807. swizzle,
  808. }
  809. }
  810. /// Sizes past the hardware's 16384 texels per side are refused instead
  811. /// of overflowing the size arithmetic (found by random-input testing).
  812. #[test]
  813. fn extents_past_the_hardware_limit_are_invalid() {
  814. for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] {
  815. let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap();
  816. assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16);
  817. for (w, h) in [
  818. (MAX_EXTENT + 1, 1),
  819. (1, MAX_EXTENT + 1),
  820. (u32::MAX, u32::MAX),
  821. ] {
  822. let result = Layout::new(&desc(w, h, 1, 16, swizzle));
  823. assert_eq!(result, Err(Error::Invalid), "{w}x{h}");
  824. }
  825. let mut deep = desc(1, 1, 1, 16, swizzle);
  826. deep.depth = u32::MAX;
  827. assert_eq!(Layout::new(&deep), Err(Error::Invalid));
  828. }
  829. }
  830. #[test]
  831. fn blocks_hold_their_size_in_elements() {
  832. for log2 in [8u32, 12, 16] {
  833. let swizzle = match log2 {
  834. 8 => Swizzle::SW_256B_S,
  835. 12 => Swizzle::SW_4KB_S,
  836. _ => Swizzle::SW_64KB_D,
  837. };
  838. for e in 0..5 {
  839. let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap();
  840. let [w, h, d] = l.block;
  841. assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}");
  842. // The pattern covers exactly the block's coordinates.
  843. assert_eq!(l.pattern[0].len() as u32, w);
  844. assert_eq!(l.pattern[1].len() as u32, h);
  845. }
  846. }
  847. // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture).
  848. let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap();
  849. assert_eq!(l.block, [64, 64, 1]);
  850. assert_eq!((l.size, l.alignment), (65536, 65536));
  851. }
  852. /// Every element of every mip and slice lands on its own address, inside
  853. /// the texture, and tiling then detiling gives the rows back.
  854. #[test]
  855. fn addresses_are_a_bijection_and_copies_round_trip() {
  856. let cases = [
  857. desc(64, 64, 7, 16, Swizzle::SW_64KB_D),
  858. desc(100, 60, 7, 4, Swizzle::SW_64KB_D),
  859. desc(250, 175, 8, 8, Swizzle::SW_4KB_S),
  860. desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
  861. desc(40, 9, 3, 2, Swizzle::SW_64KB_S),
  862. desc(30, 20, 5, 4, Swizzle::LINEAR),
  863. Desc {
  864. depth: 3,
  865. ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
  866. },
  867. Desc {
  868. dimension: Dimension::Tex3d,
  869. depth: 16,
  870. ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S)
  871. },
  872. ];
  873. for d in cases {
  874. let l = Layout::new(&d).unwrap();
  875. let mut seen = vec![false; l.size as usize];
  876. let mut tiled = vec![0u8; l.size as usize];
  877. let n = d.element_bytes as usize;
  878. let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth };
  879. for slice in 0..slices {
  880. for mip in 0..d.mips {
  881. let m = l.mips[mip as usize];
  882. let row = m.width as usize * n;
  883. let plane = row * m.height as usize;
  884. let linear: Vec<u8> = (0..plane * m.depth as usize)
  885. .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8)
  886. .collect();
  887. l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap();
  888. let mut back = vec![0u8; linear.len()];
  889. l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap();
  890. assert_eq!(back, linear, "{d:?} mip {mip}");
  891. for z in 0..m.depth {
  892. for y in 0..m.height {
  893. for x in 0..m.width {
  894. let at = l.offset(mip, x, y, slice + z).unwrap() as usize;
  895. assert!(at + n <= seen.len(), "{d:?} mip {mip} outside");
  896. assert!(at.is_multiple_of(n));
  897. assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice");
  898. seen[at] = true;
  899. }
  900. }
  901. }
  902. }
  903. }
  904. }
  905. }
  906. /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
  907. /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
  908. /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
  909. #[test]
  910. fn hand_checked_addresses() {
  911. let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap();
  912. assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2));
  913. assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6));
  914. assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7));
  915. assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8));
  916. assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14)));
  917. let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap();
  918. assert_eq!(l.block, [16, 16, 1]);
  919. assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4));
  920. assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6));
  921. // Blocks row by row: (16, 0) is the second block, (0, 16) the third.
  922. assert_eq!(l.offset(0, 16, 0, 0), Ok(4096));
  923. assert_eq!(l.offset(0, 0, 16, 0), Ok(8192));
  924. }
  925. /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8,
  926. /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail.
  927. #[test]
  928. fn mip_tail_comes_first() {
  929. let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap();
  930. assert_eq!(l.first_tail_mip, 1);
  931. assert_eq!(l.size, 2 * 65536);
  932. assert_eq!(l.mips[0].offset, 65536);
  933. assert_eq!(
  934. l.mips[1].tail,
  935. Some(Tail {
  936. offset: 32768,
  937. x: 32,
  938. y: 0
  939. })
  940. );
  941. assert_eq!(l.offset(1, 0, 0, 0), Ok(32768));
  942. // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside.
  943. let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap();
  944. assert_eq!(l.first_tail_mip, 3);
  945. assert_eq!(l.mips[2].offset, 4096);
  946. assert_eq!(l.mips[1].offset, 8192);
  947. assert_eq!(l.mips[0].offset, 8192 + 16384);
  948. }
  949. #[test]
  950. fn depth_stencil_is_two_planes() {
  951. let t = Texture::new(&TextureDesc {
  952. dimension: Dimension::Tex2d,
  953. width: 1920,
  954. height: 1080,
  955. depth_or_array: 1,
  956. mips: 1,
  957. format: 20,
  958. samples: 1,
  959. swizzle: Swizzle::SW_64KB_Z_X,
  960. })
  961. .unwrap();
  962. assert_eq!(t.planes.len(), 2);
  963. // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks.
  964. assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4);
  965. assert_eq!(t.planes[1].offset, t.planes[0].layout.size);
  966. assert_eq!(t.planes[1].layout.size, 2048 * 1280);
  967. assert!(!t.planes[0].layout.addressable());
  968. }
  969. #[test]
  970. fn texture_copies_reject_overflowing_pitches() {
  971. let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap();
  972. let mut tiled = vec![0; layout.size as usize];
  973. let mut linear = [0; 32];
  974. assert_eq!(
  975. layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0),
  976. Err(Error::TooSmall)
  977. );
  978. assert_eq!(
  979. layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0),
  980. Err(Error::TooSmall)
  981. );
  982. }
  983. #[test]
  984. fn volume_copy_rejects_overflowing_depth_pitch() {
  985. let layout = Layout::new(&Desc {
  986. dimension: Dimension::Tex3d,
  987. depth: 3,
  988. ..desc(4, 2, 1, 4, Swizzle::LINEAR)
  989. })
  990. .unwrap();
  991. let tiled = vec![0; layout.size as usize];
  992. let mut linear = [0; 96];
  993. assert_eq!(
  994. layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX),
  995. Err(Error::TooSmall)
  996. );
  997. }
  998. #[test]
  999. fn bad_descriptions_and_buffers_are_refused() {
  1000. assert_eq!(
  1001. Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)),
  1002. Err(Error::Invalid)
  1003. );
  1004. assert_eq!(
  1005. Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)),
  1006. Err(Error::Invalid)
  1007. );
  1008. assert_eq!(
  1009. Layout::new(&desc(4, 4, 1, 4, Swizzle(3))),
  1010. Err(Error::Invalid)
  1011. );
  1012. let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap();
  1013. let mut out = vec![0; 64 * 64 * 4];
  1014. assert_eq!(
  1015. l.detile(&[0; 100], 0, 0, &mut out, 256, 0),
  1016. Err(Error::TooSmall)
  1017. );
  1018. assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid));
  1019. }
  1020. }