Skip to main content

unityrs_texture/
select.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/TextureSwizzler.py's is_switch_swizzled, and export/Texture2DConverter.py's XBOX_SWAP_FORMATS and the order parse_image_data reads a texture's fields in. See THIRD_PARTY_LICENSES.
2//! Which textures are exported, and which are skipped with which reason
3//! (`docs/plans/extract.md` E66, `docs/BATCH_SPEC.md` section 3): a pure
4//! function of a `Texture2D`'s fields, [`select()`].
5//!
6//! It lives here, beside the decoders, because its rules are UnityPy's
7//! texture rules (`TextureSwizzler.is_switch_swizzled`,
8//! `Texture2DConverter.XBOX_SWAP_FORMATS`, the `TextureFormat` names) and
9//! must agree with what the decoders accept: a texture [`select()`] exports is
10//! one [`crate::decode()`] decodes as UnityPy does, and a skipped one is never
11//! decoded as another format. It exports the five formats version 1 exports
12//! ([`Format::EXPORTED`]): the other formats [`crate::decode()`] also
13//! decodes, the rest of Pillow's raw and `bcn` formats, the ETC and EAC
14//! formats and the ASTC LDR formats, are `unsupported_format` to it, as `docs/BATCH_SPEC.md` section
15//! 3 says, until a spec version exports them. The engine reads the fields
16//! (the object's `m_TextureFormat`, `m_Width`, `m_Height` and
17//! `m_PlatformBlob`, and the platform of the SerializedFile that holds it,
18//! as `get_image_from_texture2d` reads them,
19//! `export/Texture2DConverter.py:237-251`) and records the skip.
20//!
21//! **Order.** Where more than one skip applies, the first of: a side of 0
22//! (`empty_image`), because `parse_image_data` returns its empty image
23//! before it looks at the format or the platform
24//! (`export/Texture2DConverter.py:265-266`), so the oracle records
25//! `empty_image` for such a texture in any format; then the format
26//! (`unsupported_format`); then the platform (`unsupported_platform`).
27//! Switch layouts without a referenced texel block retain a platform refusal.
28//! A negative side is no skip: UnityPy raises for it while decoding
29//! (Pillow's "Width and height must be >= 0", or a crop or tile error), and
30//! [`crate::decode()`] returns [`crate::DecodeError::NegativeSize`].
31//!
32//! **What it does not read.** `Texture2D.image` fetches the data before
33//! `parse_image_data` sees the size (`get_image_data`,
34//! `classes/legacy_patch/Texture2D.py:63-75`: the object's `image_data`, else
35//! what its `m_StreamData` names), and raises there for a texture with
36//! neither, or whose resource file is not loaded. A side of 0 is
37//! `empty_image` without any fetch (`docs/BATCH_SPEC.md` section 3): the
38//! extractor skips a zero width before it reads the image, and the oracle
39//! records a zero height's raise as `empty_image` (`docs/plans/extract.md`
40//! section 5). [`select()`] reads no data, so for any other texture the
41//! fetch, and its failure, are the engine's to record.
42
43use std::fmt;
44
45use crate::format::{Format, texture_format_name};
46use crate::formats::Formats;
47
48/// `BuildTarget.XBOX360` (`enums/BuildTarget.py:16`).
49pub const XBOX360: i32 = 11;
50/// `BuildTarget.Switch` (`enums/BuildTarget.py:39`).
51pub const SWITCH: i32 = 38;
52
53/// The formats UnityPy byte-swaps on Xbox 360: `RGB565`, `DXT1`,
54/// `DXT1Crunched`, `DXT5`, `DXT5Crunched`
55/// (`export/Texture2DConverter.py:569`). Of the five exported, DXT1 and
56/// DXT5.
57pub const XBOX_SWAP_FORMATS: [i32; 5] = [7, 10, 28, 12, 29];
58
59/// What [`select()`] reads of a `Texture2D`.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct TextureFields<'a> {
62    /// `m_TextureFormat`.
63    pub texture_format: i32,
64    /// `m_Width`.
65    pub width: i32,
66    /// `m_Height`.
67    pub height: i32,
68    /// The target platform of the SerializedFile that holds the texture
69    /// (`object_reader.platform`, a `BuildTarget` value).
70    pub platform: i32,
71    /// `m_PlatformBlob`'s bytes, or `None` where the texture has no such
72    /// field (UnityPy's `getattr(..., None)`); an empty blob reads as `None`
73    /// does.
74    pub platform_blob: Option<&'a [u8]>,
75}
76
77const _: () = crate::send_sync::<TextureFields<'static>>();
78
79impl TextureFields<'_> {
80    /// The decoded mode, including empty images and Switch's RGB promotion,
81    /// without validating sizes, reading data or allocating.
82    #[must_use]
83    pub fn image_mode(&self) -> Option<crate::Mode> {
84        if self.width == 0 || self.height == 0 {
85            return Some(crate::Mode::Rgba);
86        }
87        let format = if is_switch_swizzled(self.platform, self.platform_blob) {
88            match self.texture_format {
89                3 => 4,
90                8 => 14,
91                other => other,
92            }
93        } else {
94            self.texture_format
95        };
96        Format::from_texture_format(format).map(Format::mode)
97    }
98}
99
100/// What [`select()`] decides.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub enum Selection {
103    /// Decode it as this format.
104    Export(Format),
105    /// Skip it for this reason.
106    Skip(Skip),
107}
108
109const _: () = crate::send_sync::<Selection>();
110
111/// Why a texture is skipped (`docs/BATCH_SPEC.md` section 3). Its
112/// [`Display`](fmt::Display) form is the manifest's reason
113/// (`docs/BATCH_SPEC.md` 9.3).
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum Skip {
116    /// A side of 0: `empty_image`.
117    EmptyImage,
118    /// A format outside the set exported (version 1's five,
119    /// [`Format::EXPORTED`]), by its `TextureFormat` value:
120    /// `unsupported_format(<name>)`, UnityPy's member name, or the decimal
121    /// value where its enum has none.
122    UnsupportedFormat(i32),
123    /// A Switch texture without a referenced texel block:
124    /// `unsupported_platform(switch | xbox360)`.
125    UnsupportedPlatform(SkippedPlatform),
126}
127
128const _: () = crate::send_sync::<Skip>();
129
130/// The platform an [`Skip::UnsupportedPlatform`] names.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum SkippedPlatform {
133    /// A Switch texture `is_switch_swizzled` holds for.
134    Switch,
135    /// Retained reason vocabulary for callers; Xbox byte swapping is implemented.
136    Xbox360,
137}
138
139const _: () = crate::send_sync::<SkippedPlatform>();
140
141impl fmt::Display for Skip {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            Self::EmptyImage => f.write_str("empty_image"),
145            Self::UnsupportedFormat(value) => match texture_format_name(*value) {
146                Some(name) => write!(f, "unsupported_format({name})"),
147                None => write!(f, "unsupported_format({value})"),
148            },
149            Self::UnsupportedPlatform(SkippedPlatform::Switch) => {
150                f.write_str("unsupported_platform(switch)")
151            }
152            Self::UnsupportedPlatform(SkippedPlatform::Xbox360) => {
153                f.write_str("unsupported_platform(xbox360)")
154            }
155        }
156    }
157}
158
159/// Whether UnityPy deswizzles a texture as a Switch texture
160/// (`TextureSwizzler.is_switch_swizzled`,
161/// `helpers/TextureSwizzler.py:121-127`): the platform is Switch, the
162/// platform blob holds at least 12 bytes, and `1 << n` is more than one GOB
163/// per block, `n` being the little-endian `u32` at bytes 8 to 12 of the blob
164/// (`get_switch_gobs_per_block`, `helpers/TextureSwizzler.py:117-118`), so
165/// whenever `n` is not 0.
166#[must_use]
167pub fn is_switch_swizzled(platform: i32, platform_blob: Option<&[u8]>) -> bool {
168    if platform != SWITCH {
169        return false;
170    }
171    match platform_blob.and_then(|blob| blob.get(8..12)) {
172        Some(gobs) => gobs.iter().any(|&b| b != 0),
173        None => false,
174    }
175}
176
177/// Whether a texture is exported, and as what, or skipped, and why
178/// (module docs), under version 1's five formats ([`Formats::V1`]).
179#[must_use]
180pub fn select(texture: &TextureFields<'_>) -> Selection {
181    select_in(texture, Formats::V1, (0, 0))
182}
183
184/// [`select()`] under the formats a spec names (`docs/BATCH_SPEC.md` 1.5):
185/// a format outside `formats` is `unsupported_format`, as one this crate
186/// does not decode is. Unity's names in `formats` allow both DXT crunch
187/// variants: before Unity 2017.3 the decoder is legacy, from 2017.3 it is
188/// Unity's fork. An unknown version `(u16::MAX, u16::MAX)` uses the fork.
189/// Crunched ETC always uses the fork (`export/Texture2DConverter.py:297-306`).
190#[must_use]
191pub fn select_in(
192    texture: &TextureFields<'_>,
193    formats: Formats,
194    unity_version: (u16, u16),
195) -> Selection {
196    if texture.width == 0 || texture.height == 0 {
197        return Selection::Skip(Skip::EmptyImage);
198    }
199    if texture.texture_format == 6 || (texture.texture_format == 21 && texture.width % 2 != 0) {
200        return Selection::Skip(Skip::UnsupportedFormat(texture.texture_format));
201    }
202    // Version 1 exports the five of E15, version 2 the formats its spec
203    // names; the other formats this crate also decodes are
204    // `unsupported_format` to it (`docs/BATCH_SPEC.md` section 3).
205    let Some(format) = Format::from_texture_format(texture.texture_format)
206        .filter(|f| formats.contains(*f))
207        .map(|f| match f {
208            Format::Dxt1Crunched if unity_version >= (2017, 3) => Format::UnityDxt1Crunched,
209            Format::Dxt5Crunched if unity_version >= (2017, 3) => Format::UnityDxt5Crunched,
210            other => other,
211        })
212    else {
213        return Selection::Skip(Skip::UnsupportedFormat(texture.texture_format));
214    };
215    let switch_format = match texture.texture_format {
216        3 => 4,
217        8 => 14,
218        other => other,
219    };
220    if is_switch_swizzled(texture.platform, texture.platform_blob)
221        && crate::platform::switch_block(switch_format).is_none()
222    {
223        return Selection::Skip(Skip::UnsupportedPlatform(SkippedPlatform::Switch));
224    }
225    Selection::Export(format)
226}
227
228/// Select crunched DXT/ETC with an explicit Unity `(major, minor)`.
229/// The version split and ETC exception are UnityPy's
230/// `export/Texture2DConverter.py:297-306`. Empty images precede it, and
231/// the existing Switch/Xbox gates still apply. Other formats use
232/// version 1's five formats, as [`select()`] does.
233#[must_use]
234pub fn select_crunch(texture: &TextureFields<'_>, unity_version: (u16, u16)) -> Selection {
235    select_in(
236        texture,
237        Formats::V1
238            .with(Format::Dxt1Crunched)
239            .with(Format::Dxt5Crunched)
240            .with(Format::EtcRgb4Crunched)
241            .with(Format::Etc2Rgba8Crunched),
242        unity_version,
243    )
244}