Skip to main content

unityrs_texture/
platform.rs

1// Ported from UnityPy 1.25.2 (MIT): helpers/TextureSwizzler.py and export/Texture2DConverter.py's platform preprocessing. See THIRD_PARTY_LICENSES.
2//! Switch GOB layout and Xbox byte pairs, before crunch/decode/crop.
3//! The table and GOB order are `helpers/TextureSwizzler.py:6-10`,
4//! `:73-103`; padding is `:106-114`, deswizzle `:17-41`.
5//! Converter ordering and RGB promotion: `export/Texture2DConverter.py:254-320`.
6use std::sync::Arc;
7
8use unityrs_core::limits::{Meter, MeteredVec, heap_cost};
9
10use crate::{DecodeError, Format, Image, MAX_CROP_PIXELS, MAX_PIXELS, Plan, TextureFields};
11
12/// Platform requests with no reference, or sizes that cannot be processed safely.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
14pub enum PlatformError {
15    /// The Switch table has no 16-byte texel block for this format (Tier U).
16    #[error("unsupported Switch texel block for TextureFormat {0}")]
17    SwitchFormat(i32),
18    /// No decoder for this `TextureFormat` is linked.
19    #[error("unsupported TextureFormat {0}")]
20    TextureFormat(i32),
21    /// The blob's exponent cannot be shifted or its padded size represented.
22    #[error("Switch GOB exponent {0} exceeds the bounded layout")]
23    GobsExponent(u32),
24    /// An image's dimensions or buffer length cannot be represented.
25    #[error("image buffer size overflow")]
26    SizeOverflow,
27    /// The helper only grows images; shrinking has no padding interpretation.
28    #[error("padding dimensions must include the original image")]
29    PaddingSize,
30}
31const _: () = crate::send_sync::<PlatformError>();
32
33/// The complete 29-entry 16-byte texel table, independent of linked decoders.
34#[must_use]
35pub const fn switch_block(format: i32) -> Option<(u32, u32)> {
36    match format {
37        1 | 63 => Some((16, 1)),
38        2 | 7 | 9 | 13 | 62 => Some((8, 1)),
39        4 | 5 | 14 => Some((4, 1)),
40        6 => Some((1, 1)),
41        10 | 26 => Some((8, 4)),
42        12 | 24 | 25 | 27 | 48 | 54 => Some((4, 4)),
43        49 | 55 => Some((5, 5)),
44        50 | 56 => Some((6, 6)),
45        51 | 57 => Some((8, 8)),
46        52 | 58 => Some((10, 10)),
47        53 | 59 => Some((12, 12)),
48        _ => None,
49    }
50}
51
52/// Checked dimensions and strides for Switch's 4 by 8 GOBs of 16-byte texels.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct SwitchLayout {
55    width: u32,
56    height: u32,
57    block: (u32, u32),
58    gobs: u32,
59    bytes: usize,
60}
61const _: () = crate::send_sync::<SwitchLayout>();
62impl SwitchLayout {
63    /// Dimensions padded to whole GOB blocks.
64    #[must_use]
65    pub const fn padded_size(&self) -> (u32, u32) {
66        (self.width, self.height)
67    }
68    /// Pixels held by one 16-byte texel.
69    #[must_use]
70    pub const fn block(&self) -> (u32, u32) {
71        self.block
72    }
73    /// Number of bytes in the padded top level.
74    #[must_use]
75    pub const fn input_bytes(&self) -> usize {
76        self.bytes
77    }
78}
79
80/// Pad to whole GOB blocks using the blob's little-endian exponent.
81pub fn switch_layout(
82    format: i32,
83    width: i32,
84    height: i32,
85    exponent: u32,
86) -> Result<SwitchLayout, DecodeError> {
87    let block = switch_block(format).ok_or(PlatformError::SwitchFormat(format))?;
88    if width < 0 || height < 0 {
89        return Err(DecodeError::NegativeSize { width, height });
90    }
91    let gobs = 1u32
92        .checked_shl(exponent)
93        .ok_or(PlatformError::GobsExponent(exponent))?;
94    let x = u64::from(block.0) * 4;
95    let y = u64::from(block.1) * 8 * u64::from(gobs);
96    let w = u64::from(width.unsigned_abs()).div_ceil(x) * x;
97    let h = u64::from(height.unsigned_abs()).div_ceil(y) * y;
98    let pixels = w.checked_mul(h).ok_or(PlatformError::SizeOverflow)?;
99    if pixels > MAX_PIXELS {
100        return Err(DecodeError::TooLarge {
101            pixels,
102            max: MAX_PIXELS,
103        });
104    }
105    let bytes = w / u64::from(block.0) * (h / u64::from(block.1)) * 16;
106    Ok(SwitchLayout {
107        width: u32::try_from(w).map_err(|_| PlatformError::SizeOverflow)?,
108        height: u32::try_from(h).map_err(|_| PlatformError::SizeOverflow)?,
109        block,
110        gobs,
111        bytes: usize::try_from(bytes).map_err(|_| PlatformError::SizeOverflow)?,
112    })
113}
114
115/// Deswizzle mip zero; preserve UnityPy's output length and zeroed tail.
116/// Short padded data is refused before allocating; Python's resizing slice
117/// assignments on truncated data have no bounded texture interpretation.
118pub fn deswizzle(
119    data: &[u8],
120    layout: &SwitchLayout,
121    meter: &Arc<Meter>,
122) -> Result<MeteredVec<u8>, DecodeError> {
123    if data.len() < layout.bytes {
124        return Err(DecodeError::NotEnoughData {
125            needed: layout.bytes as u64,
126            got: data.len() as u64,
127        });
128    }
129    meter.count_decode((data.len() as u64).saturating_add(layout.bytes as u64))?;
130    let mut out = MeteredVec::with_capacity(meter, data.len())?;
131    for _ in 0..data.len() {
132        out.push(0)?;
133    }
134    let bx = u64::from(layout.width / layout.block.0);
135    let by = u64::from(layout.height / layout.block.1);
136    let gobs = u64::from(layout.gobs);
137    let mut src = data.as_chunks::<16>().0.iter();
138    for i in 0..by / 8 / gobs {
139        for j in 0..bx / 4 {
140            for k in 0..gobs {
141                for v in 0..32u64 {
142                    let x = ((v >> 3) & 2) | ((v >> 1) & 1);
143                    let y = ((v >> 1) & 6) | (v & 1);
144                    let offset = (((i * gobs + k) * 8 + y) * bx + j * 4 + x) * 16;
145                    let at = usize::try_from(offset).map_err(|_| PlatformError::SizeOverflow)?;
146                    let dst = out
147                        .as_mut_slice()
148                        .get_mut(at..at + 16)
149                        .ok_or(PlatformError::SizeOverflow)?;
150                    dst.copy_from_slice(src.next().ok_or(PlatformError::SizeOverflow)?);
151                }
152            }
153        }
154    }
155    Ok(out)
156}
157
158/// Inverse of `deswizzle`, using the same checked layout and GOB order.
159/// UnityPy's write loop is `helpers/TextureSwizzler.py:44-69`.
160pub fn swizzle(
161    data: &[u8],
162    layout: &SwitchLayout,
163    meter: &Arc<Meter>,
164) -> Result<MeteredVec<u8>, DecodeError> {
165    if data.len() < layout.bytes {
166        return Err(DecodeError::NotEnoughData {
167            needed: layout.bytes as u64,
168            got: data.len() as u64,
169        });
170    }
171    meter.count_decode(data.len() as u64)?;
172    let mut out = MeteredVec::with_capacity(meter, data.len())?;
173    let bx = u64::from(layout.width / layout.block.0);
174    let by = u64::from(layout.height / layout.block.1);
175    let gobs = u64::from(layout.gobs);
176    for i in 0..by / 8 / gobs {
177        for j in 0..bx / 4 {
178            for k in 0..gobs {
179                for v in 0..32u64 {
180                    let x = ((v >> 3) & 2) | ((v >> 1) & 1);
181                    let y = ((v >> 1) & 6) | (v & 1);
182                    let offset = (((i * gobs + k) * 8 + y) * bx + j * 4 + x) * 16;
183                    let at = usize::try_from(offset).map_err(|_| PlatformError::SizeOverflow)?;
184                    out.extend_from_slice(
185                        data.get(at..at + 16).ok_or(PlatformError::SizeOverflow)?,
186                    )?;
187                }
188            }
189        }
190    }
191    while out.len() < data.len() {
192        out.push(0)?;
193    }
194    Ok(out)
195}
196
197/// Swap every pair, keeping an odd last byte (`export/Texture2DConverter.py:323-328`).
198pub fn swap_bytes_for_xbox(data: &[u8], meter: &Arc<Meter>) -> Result<MeteredVec<u8>, DecodeError> {
199    meter.count_decode(data.len() as u64)?;
200    let mut out = MeteredVec::with_capacity(meter, data.len())?;
201    for pair in data.chunks(2) {
202        for &byte in pair.iter().rev() {
203            out.push(byte)?;
204        }
205    }
206    Ok(out)
207}
208
209/// Unpacks mip zero before an extension-supplied texture converter is called.
210/// The format selects the same Crunch fork as the ordinary decode path.
211pub fn unpack_crunch(
212    data: &[u8],
213    format: Format,
214    width: usize,
215    height: usize,
216    meter: &Arc<Meter>,
217) -> Result<MeteredVec<u8>, DecodeError> {
218    if format.is_unity_crunched() {
219        Ok(crate::crunch::unity::unpack(
220            data,
221            format,
222            (width, height),
223            0,
224            meter,
225        )?)
226    } else {
227        Ok(crate::crunch::unpack(
228            data,
229            format == Format::Dxt5Crunched,
230            (width, height),
231            0,
232            meter,
233        )?)
234    }
235}
236
237fn effective(format: i32) -> i32 {
238    match format {
239        3 => 4,
240        8 => 14,
241        other => other,
242    }
243}
244
245fn prepared(
246    t: &TextureFields<'_>,
247    len: usize,
248    selected: Option<Format>,
249) -> Result<(Format, Plan, Option<SwitchLayout>), DecodeError> {
250    // Empty sides precede even format/platform checks in the converter.
251    if t.width == 0 || t.height == 0 {
252        return Ok((
253            Format::Rgba32,
254            crate::plan(Format::Rgba32, len, 0, 0)?,
255            None,
256        ));
257    }
258    if t.texture_format == 6 || (t.texture_format == 21 && t.width % 2 != 0) {
259        return Err(DecodeError::Unsupported {
260            format: if t.texture_format == 6 {
261                Format::ArgbFloat
262            } else {
263                Format::Yuy2
264            },
265            width: t.width,
266        });
267    }
268    if len == 0 {
269        return Err(DecodeError::NoImageData);
270    }
271    let switch = crate::is_switch_swizzled(t.platform, t.platform_blob);
272    let value = if switch {
273        effective(t.texture_format)
274    } else {
275        t.texture_format
276    };
277    let layout = if switch {
278        let blob = t
279            .platform_blob
280            .and_then(|b| b.get(8..12))
281            .ok_or(PlatformError::SizeOverflow)?;
282        let exponent =
283            u32::from_le_bytes(blob.try_into().map_err(|_| PlatformError::SizeOverflow)?);
284        Some(switch_layout(value, t.width, t.height, exponent)?)
285    } else {
286        None
287    };
288    let format = selected
289        .filter(|f| f.texture_format() == value)
290        .or_else(|| Format::from_texture_format(value))
291        .ok_or(PlatformError::TextureFormat(value))?;
292    let (w, h) = layout.map_or((t.width, t.height), |l| {
293        (
294            i32::try_from(l.width).unwrap_or(i32::MAX),
295            i32::try_from(l.height).unwrap_or(i32::MAX),
296        )
297    });
298    if let Some(l) = layout
299        && len < l.bytes
300    {
301        return Err(DecodeError::NotEnoughData {
302            needed: l.bytes as u64,
303            got: len as u64,
304        });
305    }
306    let base = crate::plan(format, len, w, h)?;
307    Ok((format, base, layout))
308}
309
310/// Platform-aware counterpart of [`crate::plan`]. Scratch includes the
311/// transformed input, padded image, final crop and decoder tables while live.
312pub fn plan_in(t: &TextureFields<'_>, data_len: usize) -> Result<Plan, DecodeError> {
313    platform_plan(t, data_len, None)
314}
315
316/// Platform-aware planning retaining the decoder chosen by [`crate::select_in`].
317/// In particular, Unity and legacy DXT Crunch share a numeric format value.
318pub fn plan_in_as(
319    format: Format,
320    t: &TextureFields<'_>,
321    data_len: usize,
322) -> Result<Plan, DecodeError> {
323    platform_plan(t, data_len, Some(format))
324}
325
326fn platform_plan(
327    t: &TextureFields<'_>,
328    data_len: usize,
329    selected: Option<Format>,
330) -> Result<Plan, DecodeError> {
331    let (_, mut p, layout) = prepared(t, data_len, selected)?;
332    if p.output_bytes == 0 {
333        return Ok(p);
334    }
335    if t.platform == crate::XBOX360 && crate::XBOX_SWAP_FORMATS.contains(&t.texture_format)
336        || layout.is_some()
337    {
338        p.scratch = p.scratch.saturating_add(heap_cost(data_len as u64));
339    }
340    if let Some(l) = layout {
341        p.input_bytes = l.bytes as u64;
342        let w = t.width.unsigned_abs();
343        let h = t.height.unsigned_abs();
344        if (w, h) != l.padded_size() {
345            let shown = u64::from(w) * u64::from(h);
346            if shown > MAX_CROP_PIXELS {
347                return Err(DecodeError::DecompressionBomb {
348                    pixels: shown,
349                    max: MAX_CROP_PIXELS,
350                });
351            }
352            p.scratch = p.scratch.saturating_add(p.charge());
353            p.width = w;
354            p.height = h;
355            p.output_bytes = shown * p.mode.bytes_per_pixel();
356        }
357    }
358    Ok(p)
359}
360
361/// Apply platform transforms before crunch/unpacking, then decode, crop and
362/// flip as UnityPy does. Ordinary callers keep using [`crate::decode`].
363pub fn decode_in(
364    t: &TextureFields<'_>,
365    data: &[u8],
366    meter: &Arc<Meter>,
367) -> Result<Image, DecodeError> {
368    platform_decode(t, data, meter, None)
369}
370
371/// Apply platform transforms while retaining a selected Crunch fork.
372/// Switch RGB24/BGR24 promotion still chooses the four-channel decoder.
373pub fn decode_in_as(
374    format: Format,
375    t: &TextureFields<'_>,
376    data: &[u8],
377    meter: &Arc<Meter>,
378) -> Result<Image, DecodeError> {
379    platform_decode(t, data, meter, Some(format))
380}
381
382fn platform_decode(
383    t: &TextureFields<'_>,
384    data: &[u8],
385    meter: &Arc<Meter>,
386    selected: Option<Format>,
387) -> Result<Image, DecodeError> {
388    let p = platform_plan(t, data.len(), selected)?;
389    let (format, base, layout) = prepared(t, data.len(), selected)?;
390    if p.output_bytes == 0 {
391        return crate::decode(format, data, 0, 0, meter);
392    }
393    let transformed;
394    let input = if let Some(l) = layout {
395        transformed = deswizzle(data, &l, meter)?;
396        transformed.as_slice()
397    } else if t.platform == crate::XBOX360 && crate::XBOX_SWAP_FORMATS.contains(&t.texture_format) {
398        transformed = swap_bytes_for_xbox(data, meter)?;
399        transformed.as_slice()
400    } else {
401        data
402    };
403    let image = crate::decode(
404        format,
405        input,
406        i32::try_from(base.width).map_err(|_| PlatformError::SizeOverflow)?,
407        i32::try_from(base.height).map_err(|_| PlatformError::SizeOverflow)?,
408        meter,
409    )?;
410    if (base.width, base.height) == (p.width, p.height) {
411        return Ok(image);
412    }
413    // The decoder already flipped the padded image. Its bottom h rows are
414    // the top-left crop flipped, preserving crop-before-flip ordering.
415    crate::image::crop_flipped(&image, p.width, p.height, meter)
416}
417
418/// Standalone ASTC context decompression with top-down output, for all legal 2D footprints.
419pub fn astc_context_decode(
420    data: &[u8],
421    width: u32,
422    height: u32,
423    block: (u8, u8),
424    meter: &Arc<Meter>,
425) -> Result<Image, DecodeError> {
426    let footprint =
427        crate::astc::Footprint::new(block.0, block.1).ok_or(PlatformError::SizeOverflow)?;
428    let pixels = u64::from(width) * u64::from(height);
429    if pixels > MAX_PIXELS {
430        return Err(DecodeError::TooLarge {
431            pixels,
432            max: MAX_PIXELS,
433        });
434    }
435    let needed = u64::from(width.div_ceil(u32::from(block.0)))
436        * u64::from(height.div_ceil(u32::from(block.1)))
437        * 16;
438    if (data.len() as u64) < needed {
439        return Err(DecodeError::NotEnoughData {
440            needed,
441            got: data.len() as u64,
442        });
443    }
444    meter.count_decode(pixels.saturating_mul(4))?;
445    let length = usize::try_from(pixels * 4).map_err(|_| PlatformError::SizeOverflow)?;
446    let (mut output, charge) = MeteredVec::<u8>::with_capacity(meter, length)?.into_parts();
447    output.resize(length, 0);
448    let mut tables = crate::astc::Tables::new(footprint, meter)?;
449    crate::contain(std::panic::AssertUnwindSafe(|| {
450        crate::astc::decode_image(
451            &mut tables,
452            data,
453            (width as usize, height as usize),
454            false,
455            crate::astc::ERROR,
456            &mut output,
457        );
458        Ok(())
459    }))?;
460    Ok(Image::from_parts(
461        crate::Mode::Rgba,
462        width,
463        height,
464        output,
465        charge,
466    ))
467}