Skip to main content

unityrs_texture/
formats.rs

1//! A set of [`Format`]s: the formats a batch spec lets [`crate::select_in`]
2//! export (`docs/BATCH_SPEC.md` 1.5 and section 3). Version 1 exports
3//! [`Formats::V1`], the five of `docs/plans/extract.md` E15; version 2 names
4//! its own, any of the formats this crate decodes. Crunched formats keep
5//! Unity's four names; [`crate::select_in`] uses the Unity version to choose
6//! the legacy or Unity fork DXT decoder. Crunched ETC always uses the fork.
7
8use std::fmt;
9
10use crate::format::{Format, TEXTURE_FORMATS};
11
12/// A set of formats, by `TextureFormat` value. Every value UnityPy 1.25.2
13/// names is below 128 ([`TEXTURE_FORMATS`]).
14#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
15pub struct Formats(u128);
16
17const _: () = crate::send_sync::<Formats>();
18const _: () = {
19    let mut rest: &[(i32, &str)] = &TEXTURE_FORMATS;
20    while let [(value, _), tail @ ..] = rest {
21        assert!(*value >= 0 && *value < 128);
22        rest = tail;
23    }
24};
25
26impl Formats {
27    /// No format.
28    pub const NONE: Self = Self(0);
29
30    /// The five version 1 exports ([`Format::EXPORTED`]).
31    pub const V1: Self = Self::of(&Format::EXPORTED);
32
33    /// Every format this crate decodes ([`Format::ALL`]).
34    pub const DECODED: Self = Self::of(&Format::ALL);
35
36    /// The set of `formats`.
37    const fn of(mut formats: &[Format]) -> Self {
38        let mut set = Self::NONE;
39        while let [first, rest @ ..] = formats {
40            set = set.with(*first);
41            formats = rest;
42        }
43        set
44    }
45
46    /// The set with `format`'s Unity value added, including both DXT crunch variants.
47    #[must_use]
48    pub const fn with(self, format: Format) -> Self {
49        Self(self.0 | bit(format))
50    }
51
52    /// Whether `format`'s Unity value is in the set, for either DXT crunch variant.
53    #[must_use]
54    pub const fn contains(self, format: Format) -> bool {
55        self.0 & bit(format) != 0
56    }
57
58    /// Whether the set is empty.
59    #[must_use]
60    pub const fn is_empty(self) -> bool {
61        self.0 == 0
62    }
63
64    /// One canonical format per Unity value, in `TextureFormat` order.
65    /// DXT crunch entries are legacy; selection chooses the versioned decoder.
66    pub fn iter(self) -> impl Iterator<Item = Format> {
67        Format::ALL.into_iter().filter(move |f| self.contains(*f))
68    }
69
70    /// The format UnityPy 1.25.2 names `name` (a `TextureFormat` member
71    /// name), when this crate decodes it: `Err(true)` for a name UnityPy
72    /// names that this crate does not decode, `Err(false)` for any other.
73    pub fn decoded(name: &str) -> Result<Format, bool> {
74        let Some(&(value, _)) = TEXTURE_FORMATS.iter().find(|(_, n)| *n == name) else {
75            return Err(false);
76        };
77        Format::from_texture_format(value).ok_or(true)
78    }
79}
80
81const fn bit(format: Format) -> u128 {
82    // Every value is below 128 (the assertion above).
83    1 << (format.texture_format().unsigned_abs() & 127)
84}
85
86impl fmt::Debug for Formats {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.debug_set()
89            .entries(self.iter().map(Format::name))
90            .finish()
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::{Format, Formats};
97
98    #[test]
99    fn version_1_is_the_five_in_texture_format_order() {
100        let names: Vec<_> = Formats::V1.iter().map(Format::name).collect();
101        assert_eq!(names, ["RGB24", "RGBA32", "DXT1", "DXT5", "BC7"]);
102        for f in Format::ALL {
103            assert_eq!(Formats::V1.contains(f), f.exported(), "{f:?}");
104            assert!(Formats::DECODED.contains(f));
105        }
106        assert!(Formats::NONE.is_empty());
107        assert_eq!(
108            format!("{:?}", Formats::NONE.with(Format::Bc4)),
109            r#"{"BC4"}"#
110        );
111    }
112
113    /// A name is decoded exactly when it names one of [`Format::ALL`],
114    /// including PVRTC/ATC and all four crunched Unity values.
115    #[test]
116    fn the_decoded_names_are_format_all() {
117        for (value, name) in crate::TEXTURE_FORMATS {
118            let listed = Format::ALL.iter().find(|f| f.texture_format() == value);
119            match Formats::decoded(name) {
120                Ok(f) => assert_eq!(Some(&f), listed, "{name}"),
121                Err(known) => {
122                    assert!(known, "{name}");
123                    assert_eq!(listed, None, "{name}");
124                }
125            }
126        }
127        assert_eq!(Format::ALL.len(), 75);
128        assert_eq!(Formats::DECODED.iter().count(), Format::ALL.len());
129        assert!(
130            Format::ALL
131                .windows(2)
132                .all(|pair| { pair[0].texture_format() < pair[1].texture_format() })
133        );
134        assert!(Formats::DECODED.contains(Format::UnityDxt1Crunched));
135        assert!(Formats::DECODED.contains(Format::UnityDxt5Crunched));
136        assert_eq!(Formats::decoded("ASTC_RGBA_8x8"), Ok(Format::AstcRgba8x8));
137    }
138
139    #[test]
140    fn all_formats_iterate_in_texture_format_order() {
141        let values: Vec<_> = Formats::DECODED
142            .iter()
143            .map(Format::texture_format)
144            .collect();
145        assert!(
146            values.windows(2).all(|pair| pair[0] < pair[1]),
147            "{values:?}"
148        );
149    }
150
151    #[test]
152    fn a_name_is_decoded_known_or_unknown() {
153        assert_eq!(Formats::decoded("RGB565"), Ok(Format::Rgb565));
154        assert_eq!(Formats::decoded("ETC2_RGBA8"), Ok(Format::Etc2Rgba8));
155        for f in [
156            Format::PvrtcRgb2,
157            Format::PvrtcRgba2,
158            Format::PvrtcRgb4,
159            Format::PvrtcRgba4,
160            Format::AtcRgb4,
161            Format::AtcRgba8,
162            Format::Dxt1Crunched,
163            Format::Dxt5Crunched,
164            Format::EtcRgb4Crunched,
165            Format::Etc2Rgba8Crunched,
166        ] {
167            assert_eq!(Formats::decoded(f.name()), Ok(f));
168        }
169        assert_eq!(Formats::decoded("RHalf"), Ok(Format::RHalf));
170        assert_eq!(Formats::decoded("RGB48"), Ok(Format::Rgb48));
171        // UnityPy names these; this crate does not decode them.
172        assert_eq!(Formats::decoded("ARGBFloat"), Err(true));
173        assert_eq!(Formats::decoded("ETC_RGB4_3DS"), Err(true));
174        // Names are UnityPy's, case and all.
175        assert_eq!(Formats::decoded("rgb565"), Err(false));
176        assert_eq!(Formats::decoded("Unknown"), Err(false));
177        assert_eq!(Formats::decoded(""), Err(false));
178    }
179}