Skip to main content

unityrs_meshdecode/
format.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/enums/VertexFormat.py's three format enums and their struct-code tables, UnityPy/enums/MeshTopology.py, UnityPy/enums/GfxPrimitiveType.py, and helpers/MeshHelper.py's get_channel_dtype and get_channel_component_size. See THIRD_PARTY_LICENSES.
2//! The vertex formats, by version, as the struct codes UnityPy reads them
3//! with, and the topology enums.
4//!
5//! **Which table** (`MeshHandler.get_channel_dtype`,
6//! `helpers/MeshHelper.py:451-462`): [`VertexChannelFormat`] below Unity
7//! 2017, [`VertexFormat2017`] below 2019, [`VertexFormat`] from 2019, by
8//! the version's major alone. A format the table's enum lacks raises
9//! `ValueError` (`12 is not a valid VertexFormat`), which
10//! [`get_channel_dtype`] returns as [`MeshError::InvalidFormat`].
11//!
12//! **What a struct code reads** (`enums/VertexFormat.py:43-80`): UnityPy
13//! reads `UNorm`, `SNorm` and the byte colour formats as the raw integers,
14//! never scaled, and `Float16` through Python's `e` code
15//! (`StructCode::F16`). [`get_channel_component_size`] is
16//! `struct.Struct(code).size` (`helpers/MeshHelper.py:464-466`).
17//!
18//! **Normalised** (`PARITY.md` section 19.1, Tier C): unityrs reads a
19//! Mesh's channel in a normalised format ([`Norm`]: each table's `UNorm8`,
20//! `SNorm8`, `UNorm16` and `SNorm16`, and the byte colour formats
21//! `kChannelFormatColor` and `kVertexFormatColor`) as a `float`, where
22//! UnityPy leaves the integer (`enums/VertexFormat.py:46`, `:54-58`,
23//! `:70-73`, read by `helpers/MeshHelper.py:392`). The reference is the
24//! normalised fixed-point conversion of the Vulkan specification
25//! ("Fixed-Point Data Conversions", its "Conversion from Normalized
26//! Fixed-Point to Floating-Point") and of Direct3D 10 and later's data
27//! conversion rules (`SNORM` and `UNORM` to `FLOAT`): an n-bit `UNorm` value
28//! `v` is `v / (2^n - 1)`, in [0, 1], and an n-bit `SNorm` value
29//! `max(v / (2^(n-1) - 1), -1)`, in [-1, 1], so the most negative value
30//! and the one above it both give -1. A compressed mesh's packed colours
31//! are already bytes over 255 in UnityPy (`helpers/MeshHelper.py:618-628`),
32//! the `UNorm8` rule. `kChannelFormatByte` and the integer formats stay
33//! integers, and so do the blend indices (channel 13 from 2018), which are
34//! bone indices whatever their format; the blend weights are normalised.
35//! A Sprite's render data is read as UnityPy reads it, its integers kept,
36//! whatever its formats: a deliberate compatibility policy, not Unity's
37//! meaning (a GPU would normalise a `UNorm` sprite UV), so that the sprite
38//! renderer (`unityrs-texture`), which ports `get_image_from_sprite` at
39//! Tier A on UnityPy's values, reads bit for bit what it reads there. A
40//! Tier C correction of the sprite path is deferred (`PARITY.md` section
41//! 19.1).
42
43use crate::Version;
44use crate::error::MeshError;
45
46/// A `struct` code `get_channel_dtype` gives: how one component is read.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum StructCode {
49    /// `f`: a 32-bit float.
50    F32,
51    /// `e`: a 16-bit float.
52    F16,
53    /// `B`: an unsigned byte.
54    U8,
55    /// `b`: a signed byte.
56    I8,
57    /// `H`: an unsigned 16-bit integer.
58    U16,
59    /// `h`: a signed 16-bit integer.
60    I16,
61    /// `I`: an unsigned 32-bit integer.
62    U32,
63    /// `i`: a signed 32-bit integer.
64    I32,
65}
66
67const _: () = crate::send_sync::<StructCode>();
68
69impl StructCode {
70    /// The code's character.
71    #[must_use]
72    pub const fn code(self) -> char {
73        match self {
74            Self::F32 => 'f',
75            Self::F16 => 'e',
76            Self::U8 => 'B',
77            Self::I8 => 'b',
78            Self::U16 => 'H',
79            Self::I16 => 'h',
80            Self::U32 => 'I',
81            Self::I32 => 'i',
82        }
83    }
84
85    /// `struct.Struct(code).size`: the component's bytes.
86    #[must_use]
87    pub const fn size(self) -> u32 {
88        match self {
89            Self::U8 | Self::I8 => 1,
90            Self::F16 | Self::U16 | Self::I16 => 2,
91            Self::F32 | Self::U32 | Self::I32 => 4,
92        }
93    }
94
95    /// Whether Python reads it as a `float` (else an `int`).
96    #[must_use]
97    pub const fn is_float(self) -> bool {
98        matches!(self, Self::F32 | Self::F16)
99    }
100}
101
102/// A normalised format's rule (module docs, Tier C): how unityrs reads a
103/// Mesh's integer of that format as a `float`.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
105pub enum Norm {
106    /// `UNorm`, and the byte colour formats: `v / (2^n - 1)`, in [0, 1].
107    UNorm,
108    /// `SNorm`: `max(v / (2^(n-1) - 1), -1)`, in [-1, 1].
109    SNorm,
110}
111
112const _: () = crate::send_sync::<Norm>();
113
114impl Norm {
115    /// The `float` an integer `raw` of `code` normalises to, by the
116    /// Vulkan and Direct3D rule (module docs): for an 8-bit `SNorm`, -128
117    /// and -127 give -1.0, 0 gives 0.0 and 127 gives 1.0; for an 8-bit
118    /// `UNorm`, 255 gives 1.0. Each value is the correctly rounded
119    /// quotient of two integers an `f64` holds exactly.
120    #[must_use]
121    #[allow(clippy::cast_precision_loss)] // A struct code's integer: at most 32 bits, exact.
122    pub fn value(self, code: StructCode, raw: i64) -> f64 {
123        let bits = code.size() * 8;
124        let v = raw as f64;
125        match self {
126            Self::UNorm => v / f64::from(u32::MAX >> (32 - bits)),
127            Self::SNorm => (v / f64::from(u32::MAX >> (33 - bits))).max(-1.0),
128        }
129    }
130}
131
132/// `VertexChannelFormat`, the formats below Unity 2017
133/// (`enums/VertexFormat.py:4-9`).
134#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
135#[allow(non_camel_case_types)]
136pub enum VertexChannelFormat {
137    /// 0, read as `f`.
138    kChannelFormatFloat = 0,
139    /// 1, read as `e`.
140    kChannelFormatFloat16 = 1,
141    /// 2, read as `B`.
142    kChannelFormatColor = 2,
143    /// 3, read as `B`.
144    kChannelFormatByte = 3,
145    /// 4, read as `I`.
146    kChannelFormatUInt32 = 4,
147}
148
149const _: () = crate::send_sync::<VertexChannelFormat>();
150
151impl VertexChannelFormat {
152    /// Every member, in UnityPy's order.
153    pub const ALL: [Self; 5] = [
154        Self::kChannelFormatFloat,
155        Self::kChannelFormatFloat16,
156        Self::kChannelFormatColor,
157        Self::kChannelFormatByte,
158        Self::kChannelFormatUInt32,
159    ];
160
161    /// The member of this value, as `VertexChannelFormat(value)` finds it.
162    #[must_use]
163    pub fn from_value(value: u8) -> Option<Self> {
164        Self::ALL.into_iter().find(|m| *m as u8 == value)
165    }
166
167    /// Its code in `VERTEX_CHANNEL_FORMAT_STRUCT_TYPE_MAP`
168    /// (`enums/VertexFormat.py:43-49`).
169    #[must_use]
170    pub const fn struct_code(self) -> StructCode {
171        match self {
172            Self::kChannelFormatFloat => StructCode::F32,
173            Self::kChannelFormatFloat16 => StructCode::F16,
174            Self::kChannelFormatColor | Self::kChannelFormatByte => StructCode::U8,
175            Self::kChannelFormatUInt32 => StructCode::U32,
176        }
177    }
178
179    /// Its rule, if unityrs normalises it (module docs): the colour bytes
180    /// only.
181    #[must_use]
182    pub const fn norm(self) -> Option<Norm> {
183        match self {
184            Self::kChannelFormatColor => Some(Norm::UNorm),
185            _ => None,
186        }
187    }
188}
189
190/// `VertexFormat2017`, the formats of Unity 2017 and 2018
191/// (`enums/VertexFormat.py:12-25`).
192#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
193#[allow(non_camel_case_types)]
194pub enum VertexFormat2017 {
195    /// 0, read as `f`.
196    kVertexFormatFloat = 0,
197    /// 1, read as `e`.
198    kVertexFormatFloat16 = 1,
199    /// 2, read as `B`.
200    kVertexFormatColor = 2,
201    /// 3, read as `B`.
202    kVertexFormatUNorm8 = 3,
203    /// 4, read as `b`.
204    kVertexFormatSNorm8 = 4,
205    /// 5, read as `H`.
206    kVertexFormatUNorm16 = 5,
207    /// 6, read as `h`.
208    kVertexFormatSNorm16 = 6,
209    /// 7, read as `B`.
210    kVertexFormatUInt8 = 7,
211    /// 8, read as `b`.
212    kVertexFormatSInt8 = 8,
213    /// 9, read as `H`.
214    kVertexFormatUInt16 = 9,
215    /// 10, read as `h`.
216    kVertexFormatSInt16 = 10,
217    /// 11, read as `I`.
218    kVertexFormatUInt32 = 11,
219    /// 12, read as `i`.
220    kVertexFormatSInt32 = 12,
221}
222
223const _: () = crate::send_sync::<VertexFormat2017>();
224
225impl VertexFormat2017 {
226    /// Every member, in UnityPy's order.
227    pub const ALL: [Self; 13] = [
228        Self::kVertexFormatFloat,
229        Self::kVertexFormatFloat16,
230        Self::kVertexFormatColor,
231        Self::kVertexFormatUNorm8,
232        Self::kVertexFormatSNorm8,
233        Self::kVertexFormatUNorm16,
234        Self::kVertexFormatSNorm16,
235        Self::kVertexFormatUInt8,
236        Self::kVertexFormatSInt8,
237        Self::kVertexFormatUInt16,
238        Self::kVertexFormatSInt16,
239        Self::kVertexFormatUInt32,
240        Self::kVertexFormatSInt32,
241    ];
242
243    /// The member of this value, as `VertexFormat2017(value)` finds it.
244    #[must_use]
245    pub fn from_value(value: u8) -> Option<Self> {
246        Self::ALL.into_iter().find(|m| *m as u8 == value)
247    }
248
249    /// Its code in `VERTEX_FORMAT_2017_STRUCT_TYPE_MAP`
250    /// (`enums/VertexFormat.py:51-65`).
251    #[must_use]
252    pub const fn struct_code(self) -> StructCode {
253        match self {
254            Self::kVertexFormatFloat => StructCode::F32,
255            Self::kVertexFormatFloat16 => StructCode::F16,
256            Self::kVertexFormatColor | Self::kVertexFormatUNorm8 | Self::kVertexFormatUInt8 => {
257                StructCode::U8
258            }
259            Self::kVertexFormatSNorm8 | Self::kVertexFormatSInt8 => StructCode::I8,
260            Self::kVertexFormatUNorm16 | Self::kVertexFormatUInt16 => StructCode::U16,
261            Self::kVertexFormatSNorm16 | Self::kVertexFormatSInt16 => StructCode::I16,
262            Self::kVertexFormatUInt32 => StructCode::U32,
263            Self::kVertexFormatSInt32 => StructCode::I32,
264        }
265    }
266
267    /// Its rule, if unityrs normalises it (module docs): the colour
268    /// bytes, `UNorm` and `SNorm`.
269    #[must_use]
270    pub const fn norm(self) -> Option<Norm> {
271        match self {
272            Self::kVertexFormatColor | Self::kVertexFormatUNorm8 | Self::kVertexFormatUNorm16 => {
273                Some(Norm::UNorm)
274            }
275            Self::kVertexFormatSNorm8 | Self::kVertexFormatSNorm16 => Some(Norm::SNorm),
276            _ => None,
277        }
278    }
279}
280
281/// `VertexFormat`, the formats from Unity 2019 (`enums/VertexFormat.py:28-40`).
282#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
283#[allow(non_camel_case_types)]
284pub enum VertexFormat {
285    /// 0, read as `f`.
286    kVertexFormatFloat = 0,
287    /// 1, read as `e`.
288    kVertexFormatFloat16 = 1,
289    /// 2, read as `B`.
290    kVertexFormatUNorm8 = 2,
291    /// 3, read as `b`.
292    kVertexFormatSNorm8 = 3,
293    /// 4, read as `H`.
294    kVertexFormatUNorm16 = 4,
295    /// 5, read as `h`.
296    kVertexFormatSNorm16 = 5,
297    /// 6, read as `B`.
298    kVertexFormatUInt8 = 6,
299    /// 7, read as `b`.
300    kVertexFormatSInt8 = 7,
301    /// 8, read as `H`.
302    kVertexFormatUInt16 = 8,
303    /// 9, read as `h`.
304    kVertexFormatSInt16 = 9,
305    /// 10, read as `I`.
306    kVertexFormatUInt32 = 10,
307    /// 11, read as `i`.
308    kVertexFormatSInt32 = 11,
309}
310
311const _: () = crate::send_sync::<VertexFormat>();
312
313impl VertexFormat {
314    /// Every member, in UnityPy's order.
315    pub const ALL: [Self; 12] = [
316        Self::kVertexFormatFloat,
317        Self::kVertexFormatFloat16,
318        Self::kVertexFormatUNorm8,
319        Self::kVertexFormatSNorm8,
320        Self::kVertexFormatUNorm16,
321        Self::kVertexFormatSNorm16,
322        Self::kVertexFormatUInt8,
323        Self::kVertexFormatSInt8,
324        Self::kVertexFormatUInt16,
325        Self::kVertexFormatSInt16,
326        Self::kVertexFormatUInt32,
327        Self::kVertexFormatSInt32,
328    ];
329
330    /// The member of this value, as `VertexFormat(value)` finds it.
331    #[must_use]
332    pub fn from_value(value: u8) -> Option<Self> {
333        Self::ALL.into_iter().find(|m| *m as u8 == value)
334    }
335
336    /// Its code in `VERTEX_FORMAT_STRUCT_TYPE_MAP`
337    /// (`enums/VertexFormat.py:67-80`).
338    #[must_use]
339    pub const fn struct_code(self) -> StructCode {
340        match self {
341            Self::kVertexFormatFloat => StructCode::F32,
342            Self::kVertexFormatFloat16 => StructCode::F16,
343            Self::kVertexFormatUNorm8 | Self::kVertexFormatUInt8 => StructCode::U8,
344            Self::kVertexFormatSNorm8 | Self::kVertexFormatSInt8 => StructCode::I8,
345            Self::kVertexFormatUNorm16 | Self::kVertexFormatUInt16 => StructCode::U16,
346            Self::kVertexFormatSNorm16 | Self::kVertexFormatSInt16 => StructCode::I16,
347            Self::kVertexFormatUInt32 => StructCode::U32,
348            Self::kVertexFormatSInt32 => StructCode::I32,
349        }
350    }
351
352    /// Its rule, if unityrs normalises it (module docs): `UNorm` and
353    /// `SNorm`.
354    #[must_use]
355    pub const fn norm(self) -> Option<Norm> {
356        match self {
357            Self::kVertexFormatUNorm8 | Self::kVertexFormatUNorm16 => Some(Norm::UNorm),
358            Self::kVertexFormatSNorm8 | Self::kVertexFormatSNorm16 => Some(Norm::SNorm),
359            _ => None,
360        }
361    }
362}
363
364/// The three tables, as `get_channel_dtype` picks one by version.
365#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
366pub enum FormatTable {
367    /// [`VertexChannelFormat`]: a major below 2017.
368    Channel,
369    /// [`VertexFormat2017`]: a major of 2017 or 2018.
370    V2017,
371    /// [`VertexFormat`]: a major of 2019 or more.
372    V2019,
373}
374
375const _: () = crate::send_sync::<FormatTable>();
376
377impl FormatTable {
378    /// The table a version's major reads (`helpers/MeshHelper.py:452-460`).
379    #[must_use]
380    pub const fn for_major(major: u16) -> Self {
381        if major < 2017 {
382            Self::Channel
383        } else if major < 2019 {
384            Self::V2017
385        } else {
386            Self::V2019
387        }
388    }
389
390    /// The enum's name, as its `ValueError` gives it.
391    #[must_use]
392    pub const fn python_name(self) -> &'static str {
393        match self {
394            Self::Channel => "VertexChannelFormat",
395            Self::V2017 => "VertexFormat2017",
396            Self::V2019 => "VertexFormat",
397        }
398    }
399
400    /// The rule unityrs normalises `format` of this table by, if any
401    /// (module docs): `None` for a format the enum lacks, too.
402    #[must_use]
403    pub fn norm(self, format: u8) -> Option<Norm> {
404        match self {
405            Self::Channel => {
406                VertexChannelFormat::from_value(format).and_then(VertexChannelFormat::norm)
407            }
408            Self::V2017 => VertexFormat2017::from_value(format).and_then(VertexFormat2017::norm),
409            Self::V2019 => VertexFormat::from_value(format).and_then(VertexFormat::norm),
410        }
411    }
412
413    /// The struct code of `format` in this table, if the enum has it.
414    #[must_use]
415    pub fn struct_code(self, format: u8) -> Option<StructCode> {
416        match self {
417            Self::Channel => {
418                VertexChannelFormat::from_value(format).map(VertexChannelFormat::struct_code)
419            }
420            Self::V2017 => VertexFormat2017::from_value(format).map(VertexFormat2017::struct_code),
421            Self::V2019 => VertexFormat::from_value(format).map(VertexFormat::struct_code),
422        }
423    }
424}
425
426/// `MeshHandler.get_channel_dtype` (`helpers/MeshHelper.py:451-462`): the
427/// struct code of a channel's `format` under `version`'s table, or
428/// UnityPy's `ValueError` for a format the table's enum lacks.
429pub fn get_channel_dtype(version: Version, format: u8) -> Result<StructCode, MeshError> {
430    let table = FormatTable::for_major(version.major()?);
431    table
432        .struct_code(format)
433        .ok_or(MeshError::InvalidFormat { format, table })
434}
435
436/// `MeshHandler.get_channel_component_size`
437/// (`helpers/MeshHelper.py:464-466`): the bytes of one component of a
438/// channel in `format`.
439pub fn get_channel_component_size(version: Version, format: u8) -> Result<u32, MeshError> {
440    get_channel_dtype(version, format).map(StructCode::size)
441}
442
443/// `MeshTopology` (`enums/MeshTopology.py:4-10`), a `SubMesh`'s
444/// `topology`, which `get_triangles` compares with
445/// (`helpers/MeshHelper.py:646`, `:651`, `:668`).
446#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
447pub enum MeshTopology {
448    /// 0.
449    Triangles = 0,
450    /// 1.
451    TriangleStrip = 1,
452    /// 2.
453    Quads = 2,
454    /// 3.
455    Lines = 3,
456    /// 4.
457    LineStrip = 4,
458    /// 5.
459    Points = 5,
460}
461
462const _: () = crate::send_sync::<MeshTopology>();
463
464impl MeshTopology {
465    /// Every member, in UnityPy's order.
466    pub const ALL: [Self; 6] = [
467        Self::Triangles,
468        Self::TriangleStrip,
469        Self::Quads,
470        Self::Lines,
471        Self::LineStrip,
472        Self::Points,
473    ];
474
475    /// The member's value.
476    #[must_use]
477    pub const fn value(self) -> i64 {
478        self as i64
479    }
480
481    /// The member of this value.
482    #[must_use]
483    pub fn from_value(value: i64) -> Option<Self> {
484        Self::ALL.into_iter().find(|m| m.value() == value)
485    }
486}
487
488/// `GfxPrimitiveType` (`enums/GfxPrimitiveType.py:4-10`), the same values
489/// under the engine's names; nothing in UnityPy reads it.
490#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
491#[allow(non_camel_case_types)]
492pub enum GfxPrimitiveType {
493    /// 0.
494    kPrimitiveTriangles = 0,
495    /// 1.
496    kPrimitiveTriangleStrip = 1,
497    /// 2.
498    kPrimitiveQuads = 2,
499    /// 3.
500    kPrimitiveLines = 3,
501    /// 4.
502    kPrimitiveLineStrip = 4,
503    /// 5.
504    kPrimitivePoints = 5,
505}
506
507const _: () = crate::send_sync::<GfxPrimitiveType>();
508
509impl GfxPrimitiveType {
510    /// Every member, in UnityPy's order.
511    pub const ALL: [Self; 6] = [
512        Self::kPrimitiveTriangles,
513        Self::kPrimitiveTriangleStrip,
514        Self::kPrimitiveQuads,
515        Self::kPrimitiveLines,
516        Self::kPrimitiveLineStrip,
517        Self::kPrimitivePoints,
518    ];
519
520    /// The member's value.
521    #[must_use]
522    pub const fn value(self) -> i64 {
523        self as i64
524    }
525
526    /// The member of this value.
527    #[must_use]
528    pub fn from_value(value: i64) -> Option<Self> {
529        Self::ALL.into_iter().find(|m| m.value() == value)
530    }
531}