unityrs_meshdecode/error.rs
1// Ported from UnityPy 1.25.2 (MIT): the exceptions UnityPy/helpers/MeshHelper.py's MeshHandler, UnityPy/helpers/PackedBitVector.py's unpack_ints and unpack_floats, and UnityPyBoost/Mesh.cpp's unpack_vertexdata raise. See THIRD_PARTY_LICENSES.
2//! What [`crate::MeshHandler::process`] and
3//! [`crate::Processed::get_triangles`] return when they fail.
4//!
5//! Each variant but the last five is an exception UnityPy raises, and
6//! [`MeshError::python`] gives its class name and message as UnityPy gives
7//! them (`type(e).__name__`, `str(e)`), matching `CPython` 3.11's messages for
8//! the struct, list and str errors they reach, which the oracle's fixtures
9//! record
10//! and `tests/oracle.rs` compares. The last five are where the crate stops
11//! and UnityPy does not, each a divergence `PARITY.md` states (section 15.3,
12//! section 19.3): a work or memory bound ([`MeshError::Charge`]), an access
13//! UnityPyBoost makes out of bounds after its `uint32_t` arithmetic wraps
14//! ([`MeshError::WrappedAccess`]), a part of `MeshHandler` that a later
15//! phase ports ([`MeshError::Unsupported`]), a value of a type or range the
16//! class's typetree never declares ([`MeshError::Malformed`]), and the
17//! core's own resource error ([`MeshError::Resource`]), which is the
18//! core's port of `get_resource_data`'s failures.
19
20use std::fmt;
21
22use unityrs_core::limits::ChargeError;
23
24use crate::format::FormatTable;
25
26/// A failure of the mesh handler (module docs).
27#[derive(Debug, thiserror::Error)]
28#[non_exhaustive]
29pub enum MeshError {
30 /// `AssertionError`: one of `process`'s or `get_triangles`'s asserts
31 /// (`helpers/MeshHelper.py:113`, `:119-124`, `:134`, `:138`, `:148`,
32 /// `:631-632`). The message is the assert's own, empty for a bare one.
33 #[error("{0}")]
34 Assertion(&'static str),
35 /// `AttributeError`: a field read on an `UnknownObject`, the class
36 /// UnityPyBoost's object mode builds when the class named by the
37 /// node's type cannot take its fields (`PARITY.md` section 9.2), that
38 /// lacks it (`'UnknownObject' object has no attribute 'm_Streams'`).
39 #[error("'UnknownObject' object has no attribute '{0}'")]
40 NoAttribute(&'static str),
41 /// `ValueError`: the source is neither a `Mesh` nor a
42 /// `SpriteRenderData`, because object mode built it as an
43 /// `UnknownObject` (`helpers/MeshHelper.py:171-172`).
44 #[error("Unknown mesh type <class 'UnityPy.classes.UnknownObject.UnknownObject'>")]
45 UnknownMeshType,
46 /// `ValueError`: the version's type byte is no `UnityVersionType`, which
47 /// its first index raises (`helpers/UnityVersion.py:41-42`, `:99-107`).
48 #[error("{0} is not a valid UnityVersionType")]
49 VersionType(u8),
50 /// `ValueError`: a channel's format is not a member of the version's
51 /// format enum (`helpers/MeshHelper.py:451-462`).
52 #[error("{format} is not a valid {}", table.python_name())]
53 InvalidFormat {
54 /// The channel's `format`.
55 format: u8,
56 /// The enum the version picks.
57 table: FormatTable,
58 },
59 /// `ValueError`: a channel past the version's last
60 /// (`helpers/MeshHelper.py:395-449`).
61 #[error("Unknown channel {0}")]
62 UnknownChannel(u64),
63 /// `ValueError`: `get_streams`'s `max` over no channels
64 /// (`helpers/MeshHelper.py:257`).
65 #[error("max() arg is an empty sequence")]
66 NoChannels,
67 /// `ValueError`: UnityPyBoost's bounds check
68 /// (`UnityPyBoost/Mesh.cpp:50-56`).
69 #[error("Vertex data access out of bounds")]
70 OutOfBounds,
71 /// `struct.error` (its class's name is `error`).
72 #[error("{0}")]
73 Struct(StructError),
74 /// `IndexError`.
75 #[error("{0}")]
76 Index(IndexKind),
77 /// `ValueError`: a strip's or a quad's indices unpacked from a slice
78 /// the index buffer cuts short (`helpers/MeshHelper.py:655`, `:673`),
79 /// or a compressed normal's or tangent's pair, or a tangent's pair of
80 /// signs, that its vector's odd count cuts short (`:534`, `:552-553`).
81 #[error("not enough values to unpack (expected {expected}, got {got})")]
82 Unpack {
83 /// 3 for a strip, 4 for a quad, 2 for a pair.
84 expected: u8,
85 /// What the slice held.
86 got: u8,
87 },
88 /// `StopIteration`: a compressed skin whose bone indices end where a
89 /// vertex's fourth is read (`next`, `helpers/MeshHelper.py:605`).
90 #[error("")]
91 StopIteration,
92 /// `OverflowError`: `normalize`'s square of a finite component past
93 /// the largest `float` (`v**2`, `helpers/MeshHelper.py:64`), the
94 /// message `CPython`'s `float_pow` gives `ERANGE`.
95 #[error("(34, 'Numerical result out of range')")]
96 Overflow,
97 /// `ValueError`: `bytes()` of an index list holding a value past a
98 /// byte (`helpers/MeshHelper.py:175`).
99 #[error("bytes must be in range(0, 256)")]
100 ByteRange,
101 /// `ValueError`: a submesh of lines, points or another topology
102 /// (`helpers/MeshHelper.py:678-679`).
103 #[error("Failed getting triangles. Submesh topology is lines or points.")]
104 Topology,
105 /// The core's error reading `m_StreamData`'s bytes (`Environment::resource`,
106 /// its port of `get_resource_data`), as the core reports it.
107 #[error("resource: {0}")]
108 Resource(#[source] unityrs_core::Error),
109 /// A charge the caller's meter refused: an array's memory, or the
110 /// work counted before a loop (`docs/plans/extract.md` E59). UnityPy
111 /// has no such bound (`PARITY.md` section 19.3).
112 #[error("{0}")]
113 Charge(#[from] ChargeError),
114 /// UnityPyBoost's `uint32_t` arithmetic wrapped and its check passed,
115 /// so it would read outside the vertex data or write past the buffer
116 /// it allocated, which is undefined behaviour in UnityPy
117 /// (`UnityPyBoost/Mesh.cpp:47-75`); the crate refuses before reading
118 /// (`PARITY.md` section 19.3).
119 #[error("vertex data access wraps the 32-bit offsets UnityPyBoost computes")]
120 WrappedAccess,
121 /// A part of `MeshHandler` a later phase ports (module docs of
122 /// [`crate::Unsupported`]).
123 #[error("unsupported: {0}")]
124 Unsupported(Unsupported),
125 /// A field whose value has a type or a range no version's typetree
126 /// gives it, or a node whose type is not the class the field's
127 /// typetree names, which UnityPy's arithmetic or object mode would take
128 /// in ways no test characterises (`PARITY.md` section 15.3, Tier U).
129 #[error("malformed mesh: {0}")]
130 Malformed(String),
131}
132
133const _: () = crate::send_sync::<MeshError>();
134
135impl MeshError {
136 /// The exception UnityPy raises for this failure: its class's
137 /// `__name__` and `str(e)`. `None` for the crate's own refusals (the
138 /// last five variants, module docs).
139 #[must_use]
140 pub fn python(&self) -> Option<(&'static str, String)> {
141 let class = match self {
142 Self::Assertion(_) => "AssertionError",
143 Self::NoAttribute(_) => "AttributeError",
144 Self::UnknownMeshType
145 | Self::VersionType(_)
146 | Self::InvalidFormat { .. }
147 | Self::UnknownChannel(_)
148 | Self::NoChannels
149 | Self::OutOfBounds
150 | Self::Unpack { .. }
151 | Self::ByteRange
152 | Self::Topology => "ValueError",
153 Self::Struct(_) => "error",
154 Self::StopIteration => "StopIteration",
155 Self::Overflow => "OverflowError",
156 Self::Index(_) => "IndexError",
157 Self::Resource(_)
158 | Self::Charge(_)
159 | Self::WrappedAccess
160 | Self::Unsupported(_)
161 | Self::Malformed(_) => return None,
162 };
163 Some((class, self.to_string()))
164 }
165
166 /// A [`MeshError::Malformed`] naming what was wrong.
167 pub(crate) fn malformed(
168 detail: fmt::Arguments<'_>,
169 meter: &unityrs_core::limits::Meter,
170 ) -> Self {
171 unityrs_core::objmode::ViewError::malformed(detail, meter).into()
172 }
173}
174
175/// A `struct.error` Python 3.11 raises, by its message.
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177#[non_exhaustive]
178pub enum StructError {
179 /// `struct.iter_unpack` of a format of zero bytes (a channel whose
180 /// dimension's low four bits are 0, `helpers/MeshHelper.py:392`):
181 /// "cannot iteratively unpack with a struct of length 0".
182 ZeroLength,
183 /// `struct.unpack` of an index buffer whose length is not a multiple
184 /// of the index size (`helpers/MeshHelper.py:183-186`): "unpack
185 /// requires a buffer of N bytes", N the bytes the count asks for.
186 UnpackSize(u64),
187}
188
189const _: () = crate::send_sync::<StructError>();
190
191impl fmt::Display for StructError {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 match self {
194 Self::ZeroLength => f.write_str("cannot iteratively unpack with a struct of length 0"),
195 Self::UnpackSize(n) => write!(f, "unpack requires a buffer of {n} bytes"),
196 }
197 }
198}
199
200/// An `IndexError`, by its message.
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202#[non_exhaustive]
203pub enum IndexKind {
204 /// "list index out of range": a 4.x channel's `stream` past the
205 /// file's streams (`helpers/MeshHelper.py:341`), a packed vector's
206 /// item past its `m_Data` list (`helpers/PackedBitVector.py:56`), or a
207 /// compressed skin's vertex past the vertex count
208 /// (`helpers/MeshHelper.py:587`).
209 List,
210 /// "index out of range": a packed vector's item past its `m_Data`
211 /// where that is `bytes` (`TypelessData`, `helpers/PackedBitVector.py:56`).
212 Bytes,
213 /// "string index out of range": a 4.x channel's index past its
214 /// stream's `bin(channelMask)` (`helpers/MeshHelper.py:346-347`).
215 Str,
216 /// "list assignment index out of range": a quad submesh whose index
217 /// count is not a multiple of 4 (`helpers/MeshHelper.py:674-675`).
218 ListAssignment,
219}
220
221const _: () = crate::send_sync::<IndexKind>();
222
223impl fmt::Display for IndexKind {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str(match self {
226 Self::List => "list index out of range",
227 Self::Bytes => "index out of range",
228 Self::Str => "string index out of range",
229 Self::ListAssignment => "list assignment index out of range",
230 })
231 }
232}
233
234/// A part of `MeshHandler` this crate leaves to a later phase
235/// (`docs/plans/extract.md` E16, `PARITY.md` section 15.3).
236#[derive(Clone, Copy, Debug, PartialEq, Eq)]
237#[non_exhaustive]
238pub enum Unsupported {
239 /// A version below 4: `get_channels`' fixed layout
240 /// (`helpers/MeshHelper.py:283-321`), P4.
241 FixedChannels,
242 /// A Mesh's own vertex arrays (`m_Vertices`, `m_Normals`,
243 /// `m_Tangents`, `m_UV`, `m_UV1`, `m_Colors`), which `copy_from_mesh`
244 /// copies (`helpers/MeshHelper.py:206-224`): a Mesh has them only below
245 /// 3.5 (as AssetStudio v0.16.47's MIT `Classes/Mesh.cs` reads them),
246 /// where `process` has already failed its assert, so only a tree no
247 /// Unity version writes holds them beside `m_VertexData`. P2a, with the
248 /// rest of `copy_from_mesh`'s legacy part.
249 MeshArray(&'static str),
250 /// A sprite's own `vertices` (`helpers/MeshHelper.py:246-251`): a
251 /// render data has them only below 5.6 (AssetStudio v0.16.47's
252 /// `Classes/Sprite.cs`), which has no `m_VertexData`, so the same holds.
253 /// P2a.
254 SpriteVertices,
255}
256
257const _: () = crate::send_sync::<Unsupported>();
258
259impl fmt::Display for Unsupported {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 match self {
262 Self::FixedChannels => f.write_str("the fixed channels of a version below 4 (P4)"),
263 Self::MeshArray(field) => write!(f, "a Mesh's own {field} array (P2a)"),
264 Self::SpriteVertices => f.write_str("a sprite's own vertices (P2a)"),
265 }
266 }
267}
268
269impl From<unityrs_core::objmode::ViewError> for MeshError {
270 fn from(error: unityrs_core::objmode::ViewError) -> Self {
271 use unityrs_core::objmode::ViewError;
272 match error {
273 ViewError::NoAttribute(name) => Self::NoAttribute(name),
274 ViewError::Malformed(detail) => Self::Malformed(detail),
275 ViewError::ByteRange => Self::ByteRange,
276 ViewError::Charge(error) => Self::Charge(error),
277 }
278 }
279}