Skip to main content

unityrs_meshdecode/
handler.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/MeshHelper.py's MeshHandler (its constructor, process, copy_from_mesh and copy_from_spriterenderdata), with export/SpriteHelper.py's read of a Sprite's m_RD. See THIRD_PARTY_LICENSES.
2//! `MeshHandler`: a Mesh's, or a sprite's render data's, vertex arrays and
3//! index buffer (`process`, `helpers/MeshHelper.py:110-195`), and its
4//! triangles ([`Processed::get_triangles`]).
5//!
6//! [`MeshHandler::process`] runs UnityPy's steps in order, so the first
7//! failure is UnityPy's:
8//!
9//! 1. `m_VertexData`, asserted present (`MeshHelper.py:112-113`); then the channels and
10//!    streams by version (`:118-140`): below 4 the four fixed streams,
11//!    asserted present, then `get_channels`, which is P4
12//!    ([`Unsupported::FixedChannels`]); at 4 the file's `m_Streams` and
13//!    `m_Channels`, asserted present; from 5 `m_Channels`, asserted
14//!    present, and the streams [`crate::vertex`] derives.
15//! 2. A Mesh's `m_StreamData`, when it names a path: its bytes, through
16//!    the caller's [`Resources`], take the place of `m_DataSize`
17//!    (`MeshHelper.py:142-155`). With no resources, UnityPy's assert for a Mesh with no
18//!    object reader.
19//! 3. The index size (`MeshHelper.py:158-167`): `m_Use16BitIndices` when the Mesh has
20//!    it; else, from 2017.4 or at 2017.3 for a mesh whose `m_MeshCompression`
21//!    is 0, whether `m_IndexFormat` is 0 (a Mesh without it is 32-bit
22//!    there); else 16-bit. Then `copy_from_mesh` or
23//!    `copy_from_spriterenderdata`, or, for a source object mode built as
24//!    an `UnknownObject`, `ValueError` (`:168-172`).
25//! 4. The index buffer, when non-empty: `bytes()` of the list, unpacked as
26//!    `H` or `I` (`MeshHelper.py:174-186`).
27//! 5. The vertex data (`MeshHelper.py:188-189`, [`crate::vertex`]), a
28//!    Mesh's normalised formats read as `float`s (Tier C).
29//! 6. A Mesh's compressed mesh (`MeshHelper.py:191-192`,
30//!    [`crate::compressed`]): the vertex count, always, and each array it
31//!    holds, over the vertex data's; its triangles' indices replace the
32//!    index buffer.
33//! 7. The vertex count, when 0, from the positions (`MeshHelper.py:194-195`).
34//!
35//! **What differs from UnityPy's object: the handler changes nothing it
36//! reads** (`PARITY.md` section 19.3). `process` returns its results rather
37//! than setting them on the handler, and reads its source without changing
38//! it: UnityPy's sets a streamed Mesh's `m_DataSize` to the resource's bytes
39//! (`MeshHelper.py:155`), and its `get_triangles` writes a strip's new count into
40//! the `SubMesh` (`:666`). So a second `process` gives the first's answer,
41//! where UnityPy's reads what its first left on the handler: `copy_from_mesh`
42//! keeps the index tuple it unpacked, which `bytes()` then refuses past 255
43//! (`ValueError`) or packs again. The constructor's `ValueError` for a
44//! missing version cannot arise: [`MeshHandler::new`] takes one, as every
45//! UnityPy caller passes one or a Mesh's reader holds one
46//! (`MeshHelper.py:95-108`).
47//!
48//! **Work.** Every read of a field counts its scans on the meter `process`
49//! is given ([`unityrs_core::objmode`]), so the source is resolved there, not
50//! when the [`Source`] is made.
51
52use std::sync::Arc;
53
54use unityrs_core::env::Environment;
55use unityrs_core::limits::{Charge, Meter, MeteredVec};
56use unityrs_core::{Bytes, Parsed, RawStr, SerializedFile};
57
58use crate::compressed::decompress_compressed_mesh;
59use crate::error::{MeshError, StructError, Unsupported};
60use crate::triangles::{Triangles, get_triangles};
61use crate::unpack::{Values, VertexArray, widen};
62use crate::vertex::{Attributes, Streams, VertexData, field, get_streams, read_vertex_data};
63use crate::{ProcessedOwned, Version};
64use unityrs_core::Value;
65use unityrs_core::objmode::{
66    BONE_WEIGHTS, CHANNEL_INFO, Ints, List, MESH, MESH_6000, Obj, SPRITE, SPRITE_RENDER_DATA,
67    STREAM_INFO, STREAMING_INFO, VERTEX_DATA,
68};
69
70/// Where a Mesh's `m_StreamData` bytes come from: UnityPy's
71/// `get_resource_data(path, assets_file, offset, size)`
72/// (`helpers/ResourceReader.py:10-38`) from the Mesh's own file.
73pub trait Resources: Send + Sync {
74    /// The `size` bytes at `offset` of the resource `path` names.
75    fn resource(&self, path: &RawStr, offset: u64, size: u64)
76    -> Result<Bytes, unityrs_core::Error>;
77}
78
79const _: () = crate::send_sync::<dyn Resources>();
80
81/// The core's resource read from an object's file: [`Environment::resource`],
82/// its port of `get_resource_data`.
83#[derive(Clone, Copy, Debug)]
84pub struct FileResources<'a> {
85    /// The Environment that loaded the file.
86    pub env: &'a Environment,
87    /// The file holding the Mesh (UnityPy's `object_reader.assets_file`).
88    pub file: &'a Arc<SerializedFile>,
89}
90
91const _: () = crate::send_sync::<FileResources<'static>>();
92
93impl Resources for FileResources<'_> {
94    fn resource(
95        &self,
96        path: &RawStr,
97        offset: u64,
98        size: u64,
99    ) -> Result<Bytes, unityrs_core::Error> {
100        self.env.resource(self.file, path, offset, size)
101    }
102}
103
104/// What the handler is given: a Mesh, or a Sprite's render data, read
105/// when the handler runs.
106#[derive(Clone, Copy, Debug)]
107pub struct Source<'a> {
108    parsed: &'a Parsed,
109    kind: Kind,
110}
111
112const _: () = crate::send_sync::<Source<'static>>();
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115enum Kind {
116    Mesh,
117    RenderData,
118}
119
120impl<'a> Source<'a> {
121    /// A Mesh object's value (its tree's root a `Mesh` node, which
122    /// `process` checks).
123    #[must_use]
124    pub const fn mesh(parsed: &'a Parsed) -> Self {
125        Self {
126            parsed,
127            kind: Kind::Mesh,
128        }
129    }
130
131    /// A Sprite object's render data, `m_Sprite.m_RD`, as `SpriteHelper`
132    /// hands it to the handler (`export/SpriteHelper.py:117`): `process`
133    /// returns an `AttributeError` where object mode built the Sprite as an
134    /// `UnknownObject` without one.
135    #[must_use]
136    pub const fn sprite(parsed: &'a Parsed) -> Self {
137        Self {
138            parsed,
139            kind: Kind::RenderData,
140        }
141    }
142
143    /// The object the handler reads, its reads counted on `meter`, as
144    /// UnityPy 1.25.2's object mode builds it.
145    fn root<'m>(&self, meter: &'m Meter) -> Result<Obj<'m>, MeshError>
146    where
147        'a: 'm,
148    {
149        match self.kind {
150            Kind::Mesh => Ok(Obj::root(self.parsed, &MESH, meter)?),
151            Kind::RenderData => Obj::root(self.parsed, &SPRITE, meter)?
152                .class("m_RD", &SPRITE_RENDER_DATA)?
153                .ok_or(MeshError::NoAttribute("m_RD")),
154        }
155    }
156
157    /// `root`, except that from Unity 6000 a Mesh 1.25.2 builds as an
158    /// `UnknownObject` is built again as UnityPy git 417d595 builds it,
159    /// without a required `m_MeshUsageFlags` ([`MESH_6000`], Tier C). Called
160    /// after `m_VertexData`'s assertion, so the version is compared where
161    /// `process` first compares it.
162    fn upgrade<'m>(
163        &self,
164        obj: Obj<'m>,
165        version: Version,
166        meter: &'m Meter,
167    ) -> Result<Obj<'m>, MeshError>
168    where
169        'a: 'm,
170    {
171        if self.kind == Kind::Mesh && !obj.built() && version.at_least(&[6000])? {
172            return Ok(Obj::root(self.parsed, &MESH_6000, meter)?);
173        }
174        Ok(obj)
175    }
176
177    /// `isinstance(mesh, Mesh)` (`helpers/MeshHelper.py:143`, `:158`).
178    fn is_mesh(&self, obj: &Obj<'_>) -> bool {
179        self.kind == Kind::Mesh && obj.built()
180    }
181
182    /// `isinstance(mesh, SpriteRenderData)` (`helpers/MeshHelper.py:169`).
183    fn is_render_data(&self, obj: &Obj<'_>) -> bool {
184        self.kind == Kind::RenderData && obj.built()
185    }
186}
187
188/// `MeshHandler(src, version)` (`helpers/MeshHelper.py:71-108`).
189#[derive(Clone, Copy, Debug)]
190pub struct MeshHandler<'a> {
191    src: Source<'a>,
192    version: Version,
193    little: bool,
194}
195
196const _: () = crate::send_sync::<MeshHandler<'static>>();
197
198impl<'a> MeshHandler<'a> {
199    /// A handler of `src` at `version`, little-endian (UnityPy's default,
200    /// and every caller's).
201    #[must_use]
202    pub fn new(src: Source<'a>, version: Version) -> Self {
203        Self {
204            src,
205            version,
206            little: true,
207        }
208    }
209
210    /// The handler with `endianess` other than `<` (`little` false):
211    /// components are then not swapped, and read big-endian
212    /// (`helpers/MeshHelper.py:363`).
213    #[must_use]
214    pub fn little_endian(mut self, little: bool) -> Self {
215        self.little = little;
216        self
217    }
218
219    /// `process()` (module docs). `resources` reads `m_StreamData`;
220    /// `None` is a Mesh with no object reader. Every array is charged to
221    /// `meter` before it is allocated, and every loop's work counted on it
222    /// before the loop runs (the crate's docs). It changes nothing, so a
223    /// second call gives the first's answer.
224    pub fn process(
225        &self,
226        resources: Option<&dyn Resources>,
227        meter: &Arc<Meter>,
228    ) -> Result<Processed<'a>, MeshError> {
229        let version = self.version;
230        let mesh = self.src.root(meter)?;
231        // UnityPy MeshHelper.py:112-113
232        let vd = mesh
233            .class("m_VertexData", &VERTEX_DATA)?
234            .ok_or(MeshError::Assertion(""))?;
235        let mesh = self.src.upgrade(mesh, version, meter)?;
236        let (channels, streams) = channels_and_streams(version, &vd, meter)?;
237
238        // UnityPy MeshHelper.py:142-155
239        let streamed = if self.src.is_mesh(&mesh) {
240            stream_data(&mesh, resources)?
241        } else {
242            None
243        };
244
245        let mut use_16bit = true;
246        let mut attrs = Attributes::default();
247        let index = if self.src.is_mesh(&mesh) {
248            // UnityPy MeshHelper.py:159-167
249            if let Some(v) = mesh.int32("m_Use16BitIndices")? {
250                use_16bit = v != 0;
251            } else if version.at_least(&[2017, 4])?
252                || (version.minor_is(2017, 3)?
253                    && field(&mesh, "m_MeshCompression", u64::from(u8::MAX))? == 0)
254            {
255                use_16bit = mesh.int32("m_IndexFormat")? == Some(0);
256            }
257            copy_from_mesh(&mesh, &mut attrs, meter)?
258        } else if self.src.is_render_data(&mesh) {
259            copy_from_spriterenderdata(&mesh, meter)?
260        } else {
261            return Err(MeshError::UnknownMeshType);
262        };
263
264        // UnityPy MeshHelper.py:174-186
265        let mut index_buffer = match index {
266            Some(ints) => Some(unpack_indices(ints, use_16bit, meter)?),
267            None => None,
268        };
269
270        // UnityPy MeshHelper.py:188-189
271        let mut vertex_count = 0;
272        if version.at_least(&[3, 5])? {
273            let data = VertexData {
274                obj: vd,
275                streamed: streamed.as_deref(),
276            };
277            let read = read_vertex_data(
278                version,
279                self.little,
280                self.src.is_mesh(&mesh),
281                data,
282                &channels,
283                &streams,
284                &mut attrs,
285                meter,
286            )?;
287            if let Some(n) = read {
288                vertex_count = n;
289            }
290        }
291
292        // UnityPy MeshHelper.py:191-192
293        if self.src.is_mesh(&mesh) && version.at_least(&[2, 6])? {
294            let done = decompress_compressed_mesh(version, &mesh, &mut attrs, meter)?;
295            vertex_count = done.vertex_count;
296            if let Some((values, charge)) = done.triangles {
297                index_buffer = Some(IndexBuffer {
298                    values,
299                    _charge: charge,
300                });
301            }
302        }
303
304        // UnityPy MeshHelper.py:194-195
305        if vertex_count == 0
306            && let Some(v) = attrs.vertices.as_ref().filter(|v| !v.is_empty())
307        {
308            vertex_count = u64::try_from(v.len()).unwrap_or(u64::MAX);
309        }
310
311        Ok(Processed {
312            src: self.src,
313            version,
314            vertex_count,
315            use_16bit,
316            index_buffer,
317            attrs,
318        })
319    }
320}
321
322/// The channels and the streams, by version (`helpers/MeshHelper.py:118-140`).
323fn channels_and_streams<'a>(
324    version: Version,
325    vd: &Obj<'a>,
326    meter: &Arc<Meter>,
327) -> Result<(List<'a>, Streams<'a>), MeshError> {
328    let major = version.major()?;
329    if major < 4 {
330        // UnityPy MeshHelper.py:119-124: each `is not None`, in order.
331        for name in [
332            "m_Streams_0_",
333            "m_Streams_1_",
334            "m_Streams_2_",
335            "m_Streams_3_",
336        ] {
337            if vd.class(name, &STREAM_INFO)?.is_none() {
338                return Err(MeshError::Assertion(""));
339            }
340        }
341        // UnityPy MeshHelper.py:132
342        return Err(MeshError::Unsupported(Unsupported::FixedChannels));
343    }
344    if major == 4 {
345        // UnityPy MeshHelper.py:134-136
346        let streams = vd
347            .list("m_Streams", &STREAM_INFO)?
348            .ok_or(MeshError::Assertion(""))?;
349        let channels = vd
350            .list("m_Channels", &CHANNEL_INFO)?
351            .ok_or(MeshError::Assertion(""))?;
352        return Ok((channels, Streams::File(streams)));
353    }
354    // UnityPy MeshHelper.py:138-140
355    let channels = vd
356        .list("m_Channels", &CHANNEL_INFO)?
357        .ok_or(MeshError::Assertion(""))?;
358    let count = field(vd, "m_VertexCount", u64::from(u32::MAX))?;
359    let streams = get_streams(version, &channels, count, meter)?;
360    Ok((channels, streams))
361}
362
363/// A Mesh's `m_StreamData` bytes, when it names a path
364/// (`helpers/MeshHelper.py:142-155`).
365fn stream_data(
366    mesh: &Obj<'_>,
367    resources: Option<&dyn Resources>,
368) -> Result<Option<Bytes>, MeshError> {
369    let Some(sd) = mesh.class("m_StreamData", &STREAMING_INFO)? else {
370        return Ok(None);
371    };
372    let path = sd.string("path")?.ok_or(MeshError::NoAttribute("path"))?;
373    if path.is_empty() {
374        return Ok(None);
375    }
376    let resources = resources.ok_or(MeshError::Assertion(
377        "No object reader assigned to the input Mesh!",
378    ))?;
379    let offset = field(&sd, "offset", u64::MAX)?;
380    let size = field(&sd, "size", u64::MAX)?;
381    resources
382        .resource(path, offset, size)
383        .map(Some)
384        .map_err(MeshError::Resource)
385}
386
387/// The length of a list-valued field, which Python tests for truth.
388fn list_len(v: &Value, name: &'static str, meter: &Meter) -> Result<usize, MeshError> {
389    match v {
390        Value::List(items) => Ok(items.len()),
391        Value::Tuple(items) => Ok(items.len()),
392        Value::Prims(p) => Ok(p.len()),
393        Value::Bytes(b) => Ok(b.len()),
394        _ => Err(MeshError::malformed(
395            format_args!("{name} is not a list"),
396            meter,
397        )),
398    }
399}
400
401/// `copy_from_mesh()` (`helpers/MeshHelper.py:197-233`): the index buffer
402/// to unpack, and the skin's bone indices and weights into `attrs`.
403fn copy_from_mesh<'a>(
404    mesh: &Obj<'a>,
405    attrs: &mut Attributes,
406    meter: &Arc<Meter>,
407) -> Result<Option<Ints<'a>>, MeshError> {
408    // UnityPy MeshHelper.py:203-204
409    let index = mesh.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
410    // UnityPy MeshHelper.py:206-224: the Mesh's own arrays (P2a).
411    for name in [
412        "m_Vertices",
413        "m_Normals",
414        "m_Tangents",
415        "m_UV",
416        "m_UV1",
417        "m_Colors",
418    ] {
419        if let Some((_, v)) = mesh.get(name)?
420            && list_len(v, name, meter)? > 0
421        {
422            return Err(MeshError::Unsupported(Unsupported::MeshArray(name)));
423        }
424    }
425    // UnityPy MeshHelper.py:226-233
426    if let Some(skin) = mesh.list("m_Skin", &BONE_WEIGHTS)?
427        && !skin.is_empty()
428    {
429        let (indices, weights) = copy_skin(&skin, meter)?;
430        attrs.bone_indices = Some(indices);
431        attrs.bone_weights = Some(weights);
432    }
433    Ok(index)
434}
435
436/// The skin's bone indices, then its weights, each a list of 4-tuples
437/// (`helpers/MeshHelper.py:228-233`).
438fn copy_skin(skin: &List<'_>, meter: &Arc<Meter>) -> Result<(VertexArray, VertexArray), MeshError> {
439    const INDICES: [&str; 4] = [
440        "boneIndex_0_",
441        "boneIndex_1_",
442        "boneIndex_2_",
443        "boneIndex_3_",
444    ];
445    const WEIGHTS: [&str; 4] = ["weight_0_", "weight_1_", "weight_2_", "weight_3_"];
446    let n = skin.len().saturating_mul(4);
447    // Charged, then counted: a refused charge counts no work. One unit a
448    // value, 8 a bone (its four indices and four weights).
449    let mut indices = MeteredVec::<i64>::with_capacity(meter, n)?;
450    let mut weights = MeteredVec::<f64>::with_capacity(meter, n)?;
451    meter.count_decode(u64::try_from(n).unwrap_or(u64::MAX).saturating_mul(2))?;
452    for bone in skin.iter() {
453        let bone = bone?;
454        for name in INDICES {
455            let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
456            match v {
457                Value::Int(i) if i32::try_from(*i).is_ok() => indices.push(*i)?,
458                _ => {
459                    return Err(MeshError::malformed(
460                        format_args!("{name} is not an int"),
461                        meter,
462                    ));
463                }
464            }
465        }
466    }
467    for bone in skin.iter() {
468        let bone = bone?;
469        for name in WEIGHTS {
470            let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
471            match v {
472                Value::F32(bits) => weights.push(widen(*bits))?,
473                Value::F64(bits) => weights.push(f64::from_bits(*bits))?,
474                _ => {
475                    return Err(MeshError::malformed(
476                        format_args!("{name} is not a float"),
477                        meter,
478                    ));
479                }
480            }
481        }
482    }
483    let (indices, c1) = indices.into_parts();
484    let (weights, c2) = weights.into_parts();
485    Ok((
486        VertexArray::new(4, Values::Int(indices), c1),
487        VertexArray::new(4, Values::Float(weights), c2),
488    ))
489}
490
491/// `copy_from_spriterenderdata()` (`helpers/MeshHelper.py:235-251`): the
492/// index buffer to unpack.
493fn copy_from_spriterenderdata<'a>(
494    rd: &Obj<'a>,
495    meter: &Meter,
496) -> Result<Option<Ints<'a>>, MeshError> {
497    // UnityPy MeshHelper.py:240-244: `m_IndexBuffer`, else `indices`.
498    let mut index = rd.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
499    if index.is_none() {
500        index = rd.ints("indices")?.filter(|i| !i.is_empty());
501    }
502    // UnityPy MeshHelper.py:246-251: the sprite's own vertices (P2a).
503    if let Some((_, v)) = rd.get("vertices")?
504        && list_len(v, "vertices", meter)? > 0
505    {
506        return Err(MeshError::Unsupported(Unsupported::SpriteVertices));
507    }
508    Ok(index)
509}
510
511/// `bytes(index)` unpacked as `<{n}H` or `<{n}I`
512/// (`helpers/MeshHelper.py:174-186`).
513fn unpack_indices(
514    ints: Ints<'_>,
515    use_16bit: bool,
516    meter: &Arc<Meter>,
517) -> Result<IndexBuffer, MeshError> {
518    let len = ints.len();
519    let size = if use_16bit { 2 } else { 4 };
520    let count = len / size;
521    // Charged, then counted: a refused charge counts no work.
522    let mut out = MeteredVec::<u32>::with_capacity(meter, count)?;
523    meter.count_decode(u64::try_from(len).unwrap_or(u64::MAX).saturating_mul(2))?;
524    // UnityPy MeshHelper.py:175: `bytes()` checks every value first.
525    if ints.as_u8().is_none() {
526        for i in 0..len {
527            ints.byte(i)?;
528        }
529    }
530    if !len.is_multiple_of(size) {
531        let wanted = u64::try_from(count * size).unwrap_or(u64::MAX);
532        return Err(MeshError::Struct(StructError::UnpackSize(wanted)));
533    }
534    for k in 0..count {
535        let at = k * size;
536        let byte = |j: usize| ints.byte(at + j).map(u32::from);
537        let v = if use_16bit {
538            byte(0)? | byte(1)? << 8
539        } else {
540            byte(0)? | byte(1)? << 8 | byte(2)? << 16 | byte(3)? << 24
541        };
542        out.push(v)?;
543    }
544    let (values, charge) = out.into_parts();
545    Ok(IndexBuffer {
546        values,
547        _charge: charge,
548    })
549}
550
551/// The unpacked index buffer (`m_IndexBuffer` after `process`).
552#[derive(Debug)]
553pub struct IndexBuffer {
554    values: Vec<u32>,
555    // Declared last: the charge is returned after the values are freed.
556    _charge: Charge,
557}
558
559const _: () = crate::send_sync::<IndexBuffer>();
560
561impl IndexBuffer {
562    /// The indices.
563    #[must_use]
564    pub fn as_slice(&self) -> &[u32] {
565        &self.values
566    }
567}
568
569/// What `process()` leaves on the handler: the vertex count, the index
570/// size and buffer, and the attributes the channels and the skin filled.
571#[derive(Debug)]
572pub struct Processed<'a> {
573    src: Source<'a>,
574    version: Version,
575    vertex_count: u64,
576    use_16bit: bool,
577    index_buffer: Option<IndexBuffer>,
578    attrs: Attributes,
579}
580
581const _: () = crate::send_sync::<Processed<'static>>();
582
583impl Processed<'_> {
584    /// Moves every array and its charge, without allocating or retaining the source.
585    /// Compute triangles before this conversion if they are needed.
586    #[must_use]
587    pub fn into_owned(self) -> ProcessedOwned {
588        ProcessedOwned {
589            vertex_count: self.vertex_count,
590            use_16bit: self.use_16bit,
591            index_buffer: self.index_buffer,
592            attrs: self.attrs,
593        }
594    }
595
596    /// `m_VertexCount`.
597    #[must_use]
598    pub fn vertex_count(&self) -> u64 {
599        self.vertex_count
600    }
601
602    /// `m_Use16BitIndices`.
603    #[must_use]
604    pub fn use_16bit_indices(&self) -> bool {
605        self.use_16bit
606    }
607
608    /// `m_IndexBuffer`: `None` where the source had none.
609    #[must_use]
610    pub fn index_buffer(&self) -> Option<&IndexBuffer> {
611        self.index_buffer.as_ref()
612    }
613
614    /// `m_Vertices`.
615    #[must_use]
616    pub fn vertices(&self) -> Option<&VertexArray> {
617        self.attrs.vertices.as_ref()
618    }
619
620    /// `m_Normals`.
621    #[must_use]
622    pub fn normals(&self) -> Option<&VertexArray> {
623        self.attrs.normals.as_ref()
624    }
625
626    /// `m_Tangents`.
627    #[must_use]
628    pub fn tangents(&self) -> Option<&VertexArray> {
629        self.attrs.tangents.as_ref()
630    }
631
632    /// `m_Colors`.
633    #[must_use]
634    pub fn colors(&self) -> Option<&VertexArray> {
635        self.attrs.colors.as_ref()
636    }
637
638    /// `m_UV0` to `m_UV7`: `uv(i)`, `None` past 7.
639    #[must_use]
640    pub fn uv(&self, i: usize) -> Option<&VertexArray> {
641        self.attrs.uv.get(i).and_then(Option::as_ref)
642    }
643
644    /// `m_BoneWeights`.
645    #[must_use]
646    pub fn bone_weights(&self) -> Option<&VertexArray> {
647        self.attrs.bone_weights.as_ref()
648    }
649
650    /// `m_BoneIndices`.
651    #[must_use]
652    pub fn bone_indices(&self) -> Option<&VertexArray> {
653        self.attrs.bone_indices.as_ref()
654    }
655
656    /// `m_BindPose`, which a compressed mesh below 5 sets: each matrix's
657    /// 16 `float`s flat, row by row, so a tuple of 16 (UnityPy's
658    /// `reshape(shape=(4, 4))` gives each as four rows of 4, the last
659    /// matrix's rows cut short, then empty, where the count is no multiple
660    /// of 16).
661    #[must_use]
662    pub fn bind_pose(&self) -> Option<&VertexArray> {
663        self.attrs.bind_pose.as_ref()
664    }
665
666    /// `get_triangles()` ([`crate::triangles`]): the triangles charged to
667    /// `meter`, and the work of reading the submeshes counted on it. It
668    /// changes nothing, so each call reads the submeshes' `indexCount`s as
669    /// the source holds them, where UnityPy's second call reads the counts
670    /// its first wrote into a strip's `SubMesh`.
671    pub fn get_triangles(&self, meter: &Arc<Meter>) -> Result<Triangles, MeshError> {
672        get_triangles(
673            &self
674                .src
675                .upgrade(self.src.root(meter)?, self.version, meter)?,
676            self.version,
677            self.use_16bit,
678            self.index_buffer.as_ref().map(IndexBuffer::as_slice),
679            meter,
680        )
681    }
682}