primitive.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //! Console primitive types the host lacks. A rectangle list gives three
  2. //! corners per rectangle, the second the one between the other two, and
  3. //! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's
  4. //! full-screen rectangles come as top left, bottom left, bottom right); on
  5. //! the host each rectangle becomes two triangles, with the fourth vertex
  6. //! made from the other three on the CPU.
  7. //!
  8. //! shortcut: the fourth vertex is computed from vertex inputs, not from
  9. //! vertex shader outputs as the hardware does; that is the same for vertex
  10. //! shaders linear in their inputs (blits, 2D quads). Inputs in formats
  11. //! [`components`] does not know keep the first vertex's value, and so do
  12. //! components past the end of the vertex (an element that reaches into the
  13. //! next one, which the layout allows).
  14. /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
  15. /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
  16. /// triangles turn the same way. `elements` are (byte offset, format).
  17. pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) {
  18. for (rect, out) in src
  19. .chunks_exact(3 * stride)
  20. .zip(dst.chunks_exact_mut(6 * stride))
  21. {
  22. let v = |i: usize| &rect[i * stride..(i + 1) * stride];
  23. for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() {
  24. out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i));
  25. }
  26. let fourth = &mut out[5 * stride..];
  27. fourth.copy_from_slice(v(0));
  28. for &(offset, format) in elements {
  29. let at = offset as usize;
  30. let Some((n, kind)) = components(format) else {
  31. continue;
  32. };
  33. // Only the components inside the vertex: the rest belong to the
  34. // next one.
  35. let inside = stride.saturating_sub(at) / kind.bytes();
  36. for c in 0..n.min(inside) {
  37. let get = |i: usize| kind.read(&v(i)[at..], c);
  38. let value = get(0) + get(2) - get(1);
  39. kind.write(&mut fourth[at..], c, value);
  40. }
  41. }
  42. }
  43. }
  44. #[derive(Clone, Copy)]
  45. enum Kind {
  46. F32,
  47. F16,
  48. Unorm8,
  49. Unorm16,
  50. }
  51. /// Component count and kind of the vertex formats rectangles use.
  52. fn components(format: u32) -> Option<(usize, Kind)> {
  53. Some(match format {
  54. 2 => (4, Kind::F32),
  55. 6 => (3, Kind::F32),
  56. 16 => (2, Kind::F32),
  57. 41 => (1, Kind::F32),
  58. 10 => (4, Kind::F16),
  59. 34 => (2, Kind::F16),
  60. 54 => (1, Kind::F16),
  61. 11 => (4, Kind::Unorm16),
  62. 35 => (2, Kind::Unorm16),
  63. 28 | 29 | 87 | 91 => (4, Kind::Unorm8),
  64. _ => return None,
  65. })
  66. }
  67. impl Kind {
  68. fn bytes(self) -> usize {
  69. match self {
  70. Kind::F32 => 4,
  71. Kind::F16 | Kind::Unorm16 => 2,
  72. Kind::Unorm8 => 1,
  73. }
  74. }
  75. fn read(self, at: &[u8], c: usize) -> f32 {
  76. let b = &at[c * self.bytes()..];
  77. match self {
  78. Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
  79. Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
  80. Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
  81. Kind::Unorm8 => f32::from(b[0]) / 255.0,
  82. }
  83. }
  84. fn write(self, at: &mut [u8], c: usize, v: f32) {
  85. let n = self.bytes();
  86. let b = &mut at[c * n..(c + 1) * n];
  87. match self {
  88. Kind::F32 => b.copy_from_slice(&v.to_le_bytes()),
  89. Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()),
  90. Kind::Unorm16 => {
  91. b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
  92. }
  93. Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
  94. }
  95. }
  96. }
  97. fn half_to_f32(h: u16) -> f32 {
  98. let sign = u32::from(h >> 15) << 31;
  99. let exp = u32::from((h >> 10) & 0x1f);
  100. let man = u32::from(h & 0x3ff);
  101. let bits = match (exp, man) {
  102. (0, 0) => sign,
  103. // Subnormal: scale the mantissa.
  104. (0, m) => {
  105. let v = m as f32 * 2f32.powi(-24);
  106. return if sign != 0 { -v } else { v };
  107. }
  108. (31, m) => sign | 0x7f80_0000 | m << 13,
  109. (e, m) => sign | (e + 112) << 23 | m << 13,
  110. };
  111. f32::from_bits(bits)
  112. }
  113. fn f32_to_half(v: f32) -> u16 {
  114. let bits = v.to_bits();
  115. let sign = ((bits >> 16) & 0x8000) as u16;
  116. let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
  117. let man = bits & 0x7f_ffff;
  118. if exp >= 31 {
  119. return sign | 0x7c00; // too large: infinity
  120. }
  121. if exp <= 0 {
  122. return sign; // too small: zero
  123. }
  124. // Rounded to nearest: a carry out of the mantissa is added into the
  125. // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00.
  126. let half = (exp as u32) << 10;
  127. sign | (half + ((man + 0x1000) >> 13)) as u16
  128. }
  129. #[cfg(test)]
  130. mod tests {
  131. use super::*;
  132. /// A rectangle of float2 positions and RGBA8 colors, given as top
  133. /// left, bottom left, bottom right: the fourth corner completes the
  134. /// parallelogram at the top right.
  135. #[test]
  136. fn rectangles_get_their_fourth_corner() {
  137. let vertex = |x: f32, y: f32, r: u8| {
  138. let mut v = Vec::new();
  139. v.extend(x.to_le_bytes());
  140. v.extend(y.to_le_bytes());
  141. v.extend([r, 0, 0, 255]);
  142. v
  143. };
  144. let src: Vec<u8> = [
  145. vertex(-1.0, 1.0, 0),
  146. vertex(-1.0, -1.0, 100),
  147. vertex(1.0, -1.0, 150),
  148. ]
  149. .concat();
  150. let mut dst = vec![0u8; 6 * 12];
  151. expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]);
  152. assert_eq!(dst[..36], src[..]);
  153. assert_eq!(dst[36..48], src[..12]);
  154. assert_eq!(dst[48..60], src[24..36]);
  155. assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]);
  156. assert_eq!(f32_to_half(1.5), 0x3e00);
  157. assert_eq!(half_to_f32(0x3e00), 1.5);
  158. assert_eq!(half_to_f32(0xc000), -2.0);
  159. }
  160. /// A rounding that carries out of the mantissa raises the exponent
  161. /// (the carry used to be or-ed into an odd exponent, halving the value).
  162. #[test]
  163. fn halves_round_up_into_the_next_power_of_two() {
  164. assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000);
  165. assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800);
  166. assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half");
  167. // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is
  168. // 2 - 2^-12, which rounds to 2.0.
  169. let src: Vec<u8> = [0x3c00_u16, 0x0c00, 0x3c00]
  170. .iter()
  171. .flat_map(|h| h.to_le_bytes())
  172. .collect();
  173. let mut dst = vec![0u8; 6 * 2];
  174. expand_rects(&src, &mut dst, 2, &[(0, 54)]);
  175. assert_eq!(dst[10..], 0x4000_u16.to_le_bytes());
  176. }
  177. /// An element that reaches past the stride (float4 at 4 in 8-byte
  178. /// vertices, RGBA8 at the stride itself): the components inside get
  179. /// the fourth corner, the rest keep the first vertex's bytes. The old
  180. /// code indexed past the vertex and panicked.
  181. #[test]
  182. fn elements_past_the_stride_are_left_alone() {
  183. let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat();
  184. let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat();
  185. let mut dst = vec![0u8; 6 * 8];
  186. expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]);
  187. assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]);
  188. assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
  189. }
  190. }