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