Skip to main content

unityrs_meshdecode/
lib.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/MeshHelper.py's MeshHandler, UnityPy/helpers/PackedBitVector.py and UnityPyBoost/Mesh.cpp's unpack_vertexdata, the vertex-data unpack sprites and meshes share. See THIRD_PARTY_LICENSES.
2//! A Mesh's or a sprite's vertex arrays, index buffer and triangles, as
3//! UnityPy 1.25.2's `MeshHandler` gives them (`docs/plans/extract.md` E16;
4//! `PARITY.md` section 15.3's rows marked P1b): the same values, the same
5//! types (`float` as `f64`, `int`), and the same exceptions where it
6//! raises.
7//!
8//! - [`Source`]: what the handler reads, a Mesh object's value or a
9//!   Sprite's render data, from the core's typetree read, viewed as
10//!   UnityPy's object mode builds it ([`unityrs_core::objmode`]).
11//! - [`MeshHandler::process`]: the channels and streams by version, a
12//!   Mesh's `m_StreamData` through [`Resources`], the index size and
13//!   buffer, and each channel's data, through the three `VertexFormat`
14//!   tables ([`get_channel_dtype`]) and UnityPyBoost's strided gather
15//!   ([`unpack_vertexdata`]), into a [`Processed`].
16//!   A Mesh's `CompressedMesh` is unpacked (`PackedBitVector`'s
17//!   `unpack_ints` and `unpack_floats`, then `decompress_compressed_mesh`)
18//!   with UnityPy's two Tier C errors there corrected (`compressed`'s
19//!   module docs).
20//! - [`Processed::get_triangles`]: each submesh's triangles, for triangle
21//!   lists, strips and quads, with UnityPy's errors for the rest.
22//!
23//! **What is not here** (`docs/plans/extract.md` E16). A Mesh's own vertex
24//! arrays and a sprite's own `vertices`, which no version's typetree holds
25//! beside `m_VertexData`, are P4's (docs/plans/static3d.md, decision 2); below Unity 4, `get_channels`'
26//! fixed layout is P4. Each is [`MeshError::Unsupported`], returned where
27//! UnityPy would begin it, so every failure before it is UnityPy's.
28//!
29//! **Divergences** (`PARITY.md` sections 15.3, 19.1 and 19.3): a compressed
30//! mesh's third and later UV channels read from where the ones before end,
31//! a skin's fourth weight in 31sts, and a Mesh's `UNorm`, `SNorm` and byte
32//! colour channels normalised to `float`s (its blend indices, and a
33//! Sprite's channels, kept as UnityPy's integers), where UnityPy errs
34//! (Tier C); a
35//! packed item wider than 32 bits is [`MeshError::Malformed`]; an array or a
36//! loop past the caller's meter is [`MeshError::Charge`]; a gather whose
37//! 32-bit offsets wrap past UnityPyBoost's check, where UnityPy reads or
38//! writes out of bounds, is [`MeshError::WrappedAccess`]; a field of a type
39//! or range no version's typetree gives it, or a class node of another
40//! type, is [`MeshError::Malformed`]; and the core's resource read reports
41//! its own errors ([`MeshError::Resource`]). The handler changes nothing it
42//! reads: UnityPy's `process` sets a streamed Mesh's `m_DataSize` and leaves
43//! its results on the handler for a second call to read, and its
44//! `get_triangles` rewrites a strip's `indexCount`, which
45//! [`SubMeshTriangles::index_count`] returns instead; so each call here
46//! gives the first's answer.
47//!
48//! **No panics, bounded work** (`docs/plans/core.md` section 3.15): indexing,
49//! `unwrap` and the like are denied outside tests; offsets are computed as
50//! UnityPyBoost computes them, in wrapping `u32`s, and checked. Every array
51//! sized by the input (the values, the index buffer, the triangles, the
52//! derived streams) is charged to the caller's meter, at its element count,
53//! before it is allocated, and a message echoes at most 64 bytes of a type
54//! name. Every loop's work is counted on the meter before the loop runs, and
55//! after the charge that loop's output needs, so a refused charge counts no
56//! work: a unit per byte or element of output, per channel (those skipped
57//! included), per submesh, and for every name a scan of a class's fields may
58//! compare, counted before it, so the work is in proportion to the input or
59//! the output.
60//! `tests/oracle.rs` replays what the oracle recorded
61//! (`tools/fixtures/meshdecode.py`); `tests/limits.rs` runs each recorded
62//! case under smaller meters and work bounds, and with its bytes changed;
63//! `tests/charges.rs` counts the allocations each case makes against its
64//! charges; and `tests/work.rs` measures the work against the channels,
65//! submeshes and fields read.
66
67#![forbid(unsafe_code)]
68// No panics on a mesh's contents (plan section 3.15). Tests may opt out.
69#![cfg_attr(
70    not(test),
71    deny(
72        clippy::unwrap_used,
73        clippy::expect_used,
74        clippy::panic,
75        clippy::todo,
76        clippy::unimplemented,
77        clippy::unreachable,
78        clippy::indexing_slicing
79    )
80)]
81
82mod compressed;
83mod error;
84mod format;
85mod handler;
86mod owned;
87mod packed;
88mod triangles;
89mod unpack;
90mod version;
91mod vertex;
92
93pub use error::{IndexKind, MeshError, StructError, Unsupported};
94pub use format::{
95    FormatTable, GfxPrimitiveType, MeshTopology, Norm, StructCode, VertexChannelFormat,
96    VertexFormat, VertexFormat2017, get_channel_component_size, get_channel_dtype,
97};
98pub use handler::{FileResources, IndexBuffer, MeshHandler, Processed, Resources, Source};
99pub use owned::ProcessedOwned;
100pub use triangles::{SubMeshTriangles, Triangles};
101pub use unpack::{Component, ComponentBytes, Gather, Values, VertexArray, unpack_vertexdata};
102pub use version::Version;
103
104/// Asserts at compile time that `T` is `Send + Sync` (plan section 3.16).
105pub(crate) const fn send_sync<T: Send + Sync + ?Sized>() {}
106
107#[cfg(test)]
108mod tests {
109    use std::path::Path;
110
111    /// Plan 3.16: every public type is `Send + Sync`, so the engine's pool
112    /// threads may move and share them.
113    #[test]
114    fn every_public_type_is_asserted() {
115        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
116        let missing = unityrs_testkit::public_types::unasserted(&src);
117        assert!(missing.is_empty(), "not asserted Send + Sync: {missing:?}");
118    }
119
120    /// Plan 4.1: no thread, no wait; the handler runs on the engine's
121    /// threads.
122    #[test]
123    fn the_handler_starts_no_thread_and_never_waits() {
124        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
125        let found = unityrs_testkit::waits::waits(&src);
126        assert!(found.is_empty(), "waits or starts a thread: {found:?}");
127    }
128}