Skip to main content

unityrs_export/ngui/
read.rs

1// Ported from UnityPy 1.25.2 (MIT): the names a Sprite's or a Texture2D's attribute cannot be set under (UnityPyBoost/TypeTreeHelper.cpp's parse_class, classes/legacy_patch/Sprite.py, classes/legacy_patch/Texture2D.py and classes/Object.py), for SETTERLESS; crunched texture version indexing (export/Texture2DConverter.py and helpers/UnityVersion.py). See THIRD_PARTY_LICENSES.
2//! The cutter's reads (`docs/BATCH_SPEC.md` 4.4 steps 1 and 2, section 5):
3//! a MonoBehaviour's head, a peeked name, a texture's fields, an atlas's
4//! material name, each as the shape the cutter reads or a [`Class`].
5//!
6//! **The head** (the second carried question). UnityPy reads a
7//! MonoBehaviour's head with its TPK's MonoBehaviour tree for the file's
8//! version, `check_read` off, whatever typetree the object stores
9//! (`parse_monobehaviour_head`). Version 1 configures no typetree provider
10//! (`docs/plans/batch.md` A8), so the cutter reads it with fixed rows of
11//! its own instead, nothing in them taken from a TPK (`docs/plans/core.md`
12//! Q2). UnityPy 1.25.2's MIT class definitions name the four fields
13//! (`classes/generated.py`: `MonoBehaviour`'s `m_GameObject`, a
14//! `PPtr[GameObject]` it has from `Component`, `m_Enabled`, `m_Script`, a
15//! `PPtr[MonoScript]`, and `m_Name`, a `str`), but type `m_Enabled` only as
16//! an `int`. Its width and alignment, the rows' type names and their order
17//! are format facts from Perfare/AssetStudio's release v0.16.47 (MIT; no
18//! AssetStudio code is ported or kept here): `Component` reads
19//! `m_GameObject` (`AssetStudio/Classes/Component.cs`; `EditorExtension`
20//! before it reads only in an editor file), `Behaviour` one byte,
21//! `m_Enabled`, then aligns (`Classes/Behaviour.cs`), and `MonoBehaviour`
22//! `m_Script`, then the aligned string `m_Name` (`Classes/MonoBehaviour.cs`);
23//! `AssetStudioUtility/SerializedTypeHelper.cs`'s `AddMonoBehaviour` names
24//! the rows `PPtr<GameObject> m_GameObject`, `UInt8 m_Enabled` (aligned),
25//! `PPtr<MonoScript> m_Script`, `string m_Name` (its `Array` aligned). Each
26//! pointer is an `int m_FileID` and an `m_PathID` that is an `SInt64` from
27//! SerializedFile format 14 on and an `int` before it, as UnityPy reads an
28//! identifier in a file (`files/SerializedFile.py`'s
29//! `LocalSerializedObjectIdentifier`) and AssetStudio a pointer
30//! (`Classes/PPtr.cs`). Of each row's meta flags only the align bit is set,
31//! the one the reader acts on ([`head_rows`]). Two tests pin the rows: one
32//! reads them back from a file whose stored typetree is written from those
33//! facts, at formats 9 and 22, and the reference's reads of the testkit's
34//! atlases (format 22 files), which UnityPy makes with its TPK's tree at
35//! run time, are recorded (`tools/fixtures/ngui.py`) and replayed against
36//! these rows (X5); no scene has a file before format 14. No UnityPy sample
37//! holds a MonoBehaviour to measure them against.
38//! A head read that fails is the `m_Script` read's failure.
39//! UnityPy chooses the head's tree by the file's Unity version through its
40//! bundled typetree package, so the two can differ for a file whose version
41//! string disagrees with its format: a divergence (`PARITY.md` 19.3,
42//! `docs/BATCH_SPEC.md` 4.4 step 1), which no scene records.
43//!
44//! **Fields.** UnityPy reads only the `Texture2D` as an object, whose
45//! attributes are its children's cleaned names ([`attr`], the core's
46//! [`Parsed::attr`]); the atlas, its elements, the Material, the MonoScript,
47//! a pointer and a peeked name are typetree dicts, keyed by the children's
48//! raw names, a repeated one keeping its last value ([`field`], the core's
49//! [`Parsed::field`]; review round 2's C2). Integers are kept wide
50//! ([`integer`]).
51
52use std::sync::Arc;
53
54use unityrs_core::env::{DerefError, PPtr};
55use unityrs_core::files::{BundleFile, ParentKind, SerializedFile};
56use unityrs_core::limits::{Limits, Meter, MeteredVec};
57use unityrs_core::typetree::{NodeList, NodeRow, Tree};
58use unityrs_core::{Bytes, Map, ObjectRef, Parsed, PrimArray, RawStr, Value};
59use unityrs_texture::{Format, Formats, SWITCH, Selection, Skip, TextureFields, select_in};
60
61use super::classify::{self, Class, Reason};
62use super::seam::Seam;
63use super::table;
64
65/// The format from which a pointer's `m_PathID` is 64 bits.
66const WIDE_PATH_ID: u32 = 14;
67
68/// A value of another shape than the cutter reads: a `ParseError`'s `Read`
69/// (4.4 step 2's rule).
70#[must_use]
71pub fn shape() -> Class {
72    Class::Skip(Reason::decode_error("read"))
73}
74
75/// The bundle a SerializedFile or bundle's parent link names, while alive.
76#[must_use]
77pub fn parent_bundle(kind: Option<&ParentKind>) -> Option<Arc<BundleFile>> {
78    match kind? {
79        ParentKind::Bundle { bundle, .. } => bundle.upgrade(),
80        ParentKind::Web { .. } => None,
81    }
82}
83
84/// The top-level bundle that holds `file`, held while a read uses it
85/// (`docs/plans/batch.md` 2.6 step 7).
86#[must_use]
87pub fn top_bundle(file: &SerializedFile) -> Option<Arc<BundleFile>> {
88    let mut top = parent_bundle(file.parent().map(|p| &p.kind))?;
89    while let Some(up) = parent_bundle(top.parent().map(|p| &p.kind)) {
90        top = up;
91    }
92    Some(top)
93}
94
95/// A dict's field by its raw name, as `parse_as_dict` keys it: of children
96/// of one name, the last one's value.
97#[must_use]
98pub fn field<'a>(parsed: &'a Parsed, value: &'a Value, name: &[u8]) -> Option<&'a Value> {
99    parsed.field(value.as_dict()?, name)
100}
101
102/// An object's attribute, as UnityPy's object mode keys it: the last child
103/// whose cleaned name is `name` ([`Parsed::attr`]). The `Texture2D`'s only.
104#[must_use]
105pub fn attr<'a>(parsed: &'a Parsed, value: &'a Value, name: &[u8]) -> Option<&'a Value> {
106    parsed.attr(value.as_dict()?, name)
107}
108
109/// A pointer struct: an integer `m_FileID` and `m_PathID`.
110#[must_use]
111pub fn pptr(parsed: &Parsed, value: &Value) -> Option<PPtr> {
112    let file_id = field(parsed, value, b"m_FileID")?.as_i64()?;
113    let path_id = field(parsed, value, b"m_PathID")?.as_i64()?;
114    Some(PPtr {
115        file_id: i32::try_from(file_id).ok()?,
116        path_id,
117    })
118}
119
120fn string(value: &Value) -> Option<&RawStr> {
121    match value {
122        Value::Str(s) => Some(s),
123        _ => None,
124    }
125}
126
127/// A MonoBehaviour's head: `m_Script` and `m_Name`.
128#[derive(Clone, Debug)]
129pub struct Head {
130    /// `m_Script`.
131    pub script: PPtr,
132    /// `m_Name`.
133    pub name: RawStr,
134}
135
136/// `m_MetaFlag`'s align bit, the one bit of a row the core's reader acts on
137/// (UnityPy's `m_MetaFlag & 0x4000`, the core's [`NodeRow::aligned`]).
138const ALIGN: i64 = 0x4000;
139
140/// The head's rows (the module docs' **The head**): each a level, a type
141/// and a name, its `m_MetaFlag` the align bit where the value is aligned
142/// (`m_Enabled`, and a string's `Array`) and 0 elsewhere, its `m_ByteSize`
143/// left 0 as UnityPy's `from_list` leaves it (the reader reads neither the
144/// other bits nor the size).
145fn head_rows(wide: bool) -> Vec<NodeRow> {
146    let id_ty = if wide { "SInt64" } else { "int" };
147    let row = |level, ty: &str, name: &str| NodeRow::new(level, ty, name).with_meta_flag(0);
148    let aligned = |level, ty: &str, name: &str| NodeRow::new(level, ty, name).with_meta_flag(ALIGN);
149    vec![
150        row(0, "MonoBehaviour", "Base"),
151        row(1, "PPtr<GameObject>", "m_GameObject"),
152        row(2, "int", "m_FileID"),
153        row(2, id_ty, "m_PathID"),
154        aligned(1, "UInt8", "m_Enabled"),
155        row(1, "PPtr<MonoScript>", "m_Script"),
156        row(2, "int", "m_FileID"),
157        row(2, id_ty, "m_PathID"),
158        row(1, "string", "m_Name"),
159        aligned(2, "Array", "Array"),
160        row(3, "int", "size"),
161        row(3, "char", "data"),
162    ]
163}
164
165/// A peek tree kept for one type of X's own files, under its full tree's
166/// address: that tree (kept alive, so the address is not reused while the
167/// entry lives) and its peek tree, or none.
168type Peek = (Arc<Tree>, Option<Arc<Tree>>);
169
170/// The cutter's reader: the head trees, and the peek tree of each type of
171/// X's own files, built once, in a hash table by the type's tree, charged
172/// to `M_X` (one entry per type a name is read of: as many as the input
173/// has objects, so a sorted table's inserts would be quadratic, B3's review
174/// round 1). A dependency's tree is never kept: its peek tree is built,
175/// read with and dropped in the read (`docs/plans/batch.md` 2.6 step 7;
176/// review round 2's S3).
177#[derive(Debug)]
178pub struct Reader {
179    wide: Arc<Tree>,
180    narrow: Arc<Tree>,
181    peeks: table::Map<usize, Peek>,
182}
183
184impl Reader {
185    /// The reader, its head trees compiled. They are fixed rows, so their
186    /// failing is the cutter's own fault, `internal`, whatever the core says.
187    pub fn new(meter: &Arc<Meter>) -> Result<Self, Class> {
188        fn internal<E>(_: E) -> Class {
189            Class::Run(Reason::plain("internal"))
190        }
191        let tree = |wide| {
192            let list = NodeList::trusted(head_rows(wide)).map_err(internal)?;
193            Tree::compile(list.into_shared().map_err(internal)?, &Limits::default())
194                .map_err(internal)
195        };
196        Ok(Self {
197            wide: tree(true)?,
198            narrow: tree(false)?,
199            peeks: table::Map::new(meter),
200        })
201    }
202
203    /// `obj`'s head, read with the fixed rows ([`head_rows`]), `check_read` off.
204    pub fn head(&self, obj: &ObjectRef) -> Result<Head, Class> {
205        let tree = if obj.file().header().version >= WIDE_PATH_ID {
206            &self.wide
207        } else {
208            &self.narrow
209        };
210        let parsed = obj
211            .read_typetree(Some(tree), false)
212            .map_err(|e| classify::parse(&e))?;
213        let root = parsed.value();
214        let script = field(&parsed, root, b"m_Script")
215            .and_then(|v| pptr(&parsed, v))
216            .ok_or_else(shape)?;
217        let name = field(&parsed, root, b"m_Name")
218            .and_then(string)
219            .ok_or_else(shape)?
220            .clone();
221        Ok(Head { script, name })
222    }
223
224    /// `peek_name` (4.4 step 1): the object's root's children up to and
225    /// including the first named `m_Name` or `name`, read `check_read` off
226    /// over the object's own nodes, and that child's value under its raw
227    /// name (`parse_as_dict(peek_node)[key]`; review round 2's C3); a type
228    /// with no typetree fails as its object read does (`asset_bundle`), one
229    /// with no name field, or a name that is no string, as a `read`. Each
230    /// core call is under the refusal probe on its own (review round 2's
231    /// S4).
232    pub(super) fn peek_name(&mut self, seam: &Seam<'_>, obj: &ObjectRef) -> Result<RawStr, Class> {
233        self.peek(seam, obj)?.ok_or_else(shape)
234    }
235
236    /// [`Self::peek`] of an atlas's name for the sprites kind's tag walk
237    /// (`sprites::atlas`): a frame of its own, so a reservation refused in
238    /// it is named for the walk (the tests' `site`, B3's review round 5, Q6).
239    #[inline(never)]
240    pub(super) fn atlas_name(
241        &mut self,
242        seam: &Seam<'_>,
243        obj: &ObjectRef,
244    ) -> Result<Option<RawStr>, Class> {
245        self.peek(seam, obj)
246    }
247
248    /// `peek_name` as a `SpriteAtlas`'s is compared with a Sprite's tag
249    /// (`sprites::atlas`): as [`Self::peek_name`], but a type
250    /// with no name field (UnityPy's `None`) and a name that is no string
251    /// (no tag equals it) are `None`, no failure.
252    pub(super) fn peek(
253        &mut self,
254        seam: &Seam<'_>,
255        obj: &ObjectRef,
256    ) -> Result<Option<RawStr>, Class> {
257        let _sample = Sample(obj.file().meter(), seam.hooks);
258        let found = seam.probe(|| obj.tree(None).map_err(|e| classify::parse(&e)))?;
259        let Some(tree) = found else {
260            return Err(Class::Skip(Reason::decode_error("asset_bundle")));
261        };
262        let own = top_bundle(obj.file()).is_some_and(|b| Arc::ptr_eq(&b, &seam.registered.own));
263        let peek = if own {
264            self.kept(seam, &tree.tree, obj.file())?
265        } else {
266            peek_tree(seam, &tree.tree, obj.file())?
267        };
268        drop(tree);
269        let Some(peek) = peek else {
270            return Ok(None);
271        };
272        let parsed = seam.probe(|| {
273            obj.read_typetree(Some(&peek), false)
274                .map_err(|e| classify::parse(&e))
275        })?;
276        // The peek tree ends with the selected child: the root's last.
277        let list = peek.list();
278        let key = list
279            .children(list.root())
280            .last()
281            .map(|c| list.name(*c))
282            .ok_or_else(shape)?;
283        Ok(field(&parsed, parsed.value(), key)
284            .and_then(string)
285            .cloned())
286    }
287
288    /// The peek tree of one of X's own types, built once and kept.
289    fn kept(
290        &mut self,
291        seam: &Seam<'_>,
292        tree: &Arc<Tree>,
293        file: &SerializedFile,
294    ) -> Result<Option<Arc<Tree>>, Class> {
295        let at = Arc::as_ptr(tree) as usize;
296        if let Some((_, peek)) = self.peeks.get(&at) {
297            return Ok(peek.clone());
298        }
299        let peek = peek_tree(seam, tree, file)?;
300        let peeks = &mut self.peeks;
301        seam.probe(|| peeks.insert(at, (tree.clone(), peek.clone())))?;
302        Ok(peek)
303    }
304}
305
306/// The peek tree of `tree` (UnityPy's `get_name_peek_node`), or none when
307/// its root has no `m_Name` or `name` child: the rows up to the end of the
308/// first such child's subtree, so that child is the peek root's last. Its
309/// four core calls (the rows' charge and copy, the list, its compile) are
310/// each under the probe on its own (review round 4's S3).
311fn peek_tree(
312    seam: &Seam<'_>,
313    tree: &Arc<Tree>,
314    file: &SerializedFile,
315) -> Result<Option<Arc<Tree>>, Class> {
316    let list = tree.list();
317    let root = list.root();
318    let children = list.children(root);
319    let Some(pos) = children
320        .iter()
321        .position(|c| matches!(list.name(*c), b"m_Name" | b"name"))
322    else {
323        return Ok(None);
324    };
325    let end = children
326        .get(pos + 1)
327        .map_or(list.rows().len(), |next| next.index());
328    let rows = list.rows().get(..end).unwrap_or_default();
329    let mut kept = seam.probe(|| {
330        MeteredVec::with_capacity(file.meter(), rows.len()).map_err(|e| classify::charge(&e))
331    })?;
332    seam.probe(|| {
333        kept.extend_from_slice(rows)
334            .map_err(|e| classify::charge(&e))
335    })?;
336    let peek = seam.probe(|| NodeList::from_rows(kept).map_err(|e| classify::tree(&e)))?;
337    let limits = &file.context().limits;
338    let compiled = seam.probe(|| {
339        Tree::compile(peek.into_shared().map_err(|e| classify::tree(&e))?, limits)
340            .map_err(|e| classify::tree(&e))
341    })?;
342    Ok(Some(compiled))
343}
344
345/// Shared streamed texture spans and Python slicing.
346pub use unityrs_texture::fetch::{Span, Stream, python_slice};
347
348/// `m_PlatformBlob`, any list (4.4 step 2): what `is_switch_swizzled` reads
349/// of it, its length and its elements 8 to 12 as bytes, and no copy.
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
351pub struct Blob {
352    /// The element count (`len(platform_blob)`).
353    pub len: usize,
354    /// Elements 8 to 12 as the bytes `int.from_bytes` takes them for, when
355    /// the blob has 12: each an integer in `0..=255` (or a bool, which
356    /// Python's `bytes()` reads as 0 or 1); `None` when one is not
357    /// ([`BLOB_ELEMENT`]).
358    pub gobs: Option<[u8; 4]>,
359}
360
361/// Section 3's rule for a Switch blob element among bytes 8 to 12 that is
362/// not a byte: UnityPy's `int.from_bytes(platform_blob[8:12], "little")`
363/// raises, so the texture's answer is `decode_error`, detail `read`.
364pub const BLOB_ELEMENT: &str = "read";
365
366/// Element `i` of a primitive run as a byte, when it is one (a float is
367/// not: `bytes()` refuses it).
368fn prim_byte(p: &PrimArray, i: usize) -> Option<u8> {
369    let int = |v: Option<i128>| v.and_then(|v| u8::try_from(v).ok());
370    match p {
371        PrimArray::Bool(v) => v.get(i).map(|b| u8::from(*b)),
372        PrimArray::U8(v) => v.get(i).copied(),
373        PrimArray::I8(v) => int(v.get(i).map(|x| i128::from(*x))),
374        PrimArray::U16(v) => int(v.get(i).map(|x| i128::from(*x))),
375        PrimArray::I16(v) => int(v.get(i).map(|x| i128::from(*x))),
376        PrimArray::U32(v) => int(v.get(i).map(|x| i128::from(*x))),
377        PrimArray::I32(v) => int(v.get(i).map(|x| i128::from(*x))),
378        PrimArray::U64(v) => int(v.get(i).map(|x| i128::from(*x))),
379        PrimArray::I64(v) => int(v.get(i).map(|x| i128::from(*x))),
380        PrimArray::F32(_) | PrimArray::F64(_) => None,
381    }
382}
383
384impl Blob {
385    fn of(value: &Value) -> Option<Self> {
386        let byte = |v: &Value| match v {
387            Value::Bool(b) => Some(u8::from(*b)),
388            other => u8::try_from(other.as_i64()?).ok(),
389        };
390        let (len, gobs) = match value {
391            Value::Prims(p) => {
392                let gobs = (8..12)
393                    .map(|i| prim_byte(p, i))
394                    .collect::<Option<Vec<u8>>>();
395                (p.len(), gobs)
396            }
397            Value::List(items) => {
398                let gobs = items
399                    .get(8..12)
400                    .map(|four| four.iter().map(byte).collect::<Option<Vec<u8>>>())
401                    .unwrap_or_default();
402                (items.len(), gobs)
403            }
404            _ => return None,
405        };
406        let gobs = gobs.and_then(|g| <[u8; 4]>::try_from(g).ok());
407        Some(Self { len, gobs })
408    }
409}
410
411/// A `Texture2D`'s fields, as the cutter reads them: the integers wide, as
412/// read, narrowed only where section 3's answers use them ([`answer`]).
413#[derive(Clone, Debug)]
414pub struct Texture {
415    /// `m_Width`.
416    pub width: i128,
417    /// `m_Height`.
418    pub height: i128,
419    /// `m_TextureFormat`.
420    pub format: i128,
421    /// `image_data`.
422    pub image_data: Bytes,
423    /// `m_StreamData`, when present.
424    pub stream: Option<Stream>,
425    /// `m_PlatformBlob`, when present.
426    pub platform_blob: Option<Blob>,
427}
428
429impl Texture {
430    /// Shared decoder fields, with the blob's checked bytes held on the stack.
431    pub(crate) fn fields<'a>(
432        &self,
433        format: i32,
434        platform: i32,
435        blob: &'a mut [u8; 12],
436    ) -> TextureFields<'a> {
437        let platform_blob = self
438            .platform_blob
439            .filter(|b| b.len >= 12)
440            .and_then(|b| b.gobs)
441            .map(|g| {
442                blob.fill(0);
443                blob[8..].copy_from_slice(&g);
444                blob.as_slice()
445            });
446        let (width, height) = self.sides();
447        TextureFields {
448            texture_format: format,
449            width,
450            height,
451            platform,
452            platform_blob,
453        }
454    }
455    /// The sides as the decoder takes them: a side outside `i32` is clamped
456    /// to it, which keeps section 3's order (a negative side is answer 6,
457    /// a side past `i32::MAX` more pixels than answer 7's bound).
458    #[must_use]
459    pub fn sides(&self) -> (i32, i32) {
460        let narrow = |v: i128| {
461            i32::try_from(v.clamp(i128::from(i32::MIN), i128::from(i32::MAX))).unwrap_or(i32::MAX)
462        };
463        (narrow(self.width), narrow(self.height))
464    }
465}
466
467/// Section 3's answers 1 to 3 for `t` on `platform`, exporting the formats
468/// of `allowed` (the spec's, `docs/BATCH_SPEC.md` 1.5): its format, or the
469/// skip. A format outside `i32` is `unsupported_format(<decimal>)`; a Switch
470/// blob is read as bytes ([`Blob`], [`BLOB_ELEMENT`]).
471pub fn answer(
472    t: &Texture,
473    platform: i32,
474    allowed: Formats,
475    unity_version: (u16, u16),
476) -> Result<Format, Class> {
477    if t.width == 0 || t.height == 0 {
478        return Err(Class::Skip(Reason::plain(Skip::EmptyImage.to_string())));
479    }
480    formats(t, platform, allowed, unity_version)
481}
482
483/// Select without indexing the version; data retrieval must precede that read.
484pub(crate) fn object_answer(
485    t: &Texture,
486    obj: Option<&ObjectRef>,
487    allowed: Formats,
488) -> Result<Format, Class> {
489    let platform = obj
490        .and_then(|o| o.file().target_platform())
491        .unwrap_or(super::attempt::UNKNOWN_PLATFORM);
492    answer(t, platform, allowed, (u16::MAX, u16::MAX))
493}
494
495mod crunch;
496pub(super) use crunch::data_format;
497
498/// Section 3's answers 2 and 3 for `t`, whose sides are not 0, on
499/// `platform`: [`answer`] past its first.
500pub(crate) fn formats(
501    t: &Texture,
502    platform: i32,
503    allowed: Formats,
504    unity_version: (u16, u16),
505) -> Result<Format, Class> {
506    let Ok(format) = i32::try_from(t.format) else {
507        return Err(Class::Skip(Reason::plain(format!(
508            "unsupported_format({})",
509            t.format
510        ))));
511    };
512    let mut blob = [0u8; 12];
513    match select_in(
514        &t.fields(format, platform, &mut blob),
515        allowed,
516        unity_version,
517    ) {
518        Selection::Export(_)
519            if platform == SWITCH
520                && t.platform_blob
521                    .is_some_and(|b| b.len >= 12 && b.gobs.is_none()) =>
522        {
523            Err(Class::Skip(Reason::decode_error(BLOB_ELEMENT)))
524        }
525        Selection::Export(f) => Ok(f),
526        Selection::Skip(s) => Err(Class::Skip(Reason::plain(s.to_string()))),
527    }
528}
529
530/// The fields UnityPy 1.25.2's `Texture2D` needs (`classes/generated.py`).
531const TEXTURE_FIELDS: [&[u8]; 11] = [
532    b"image_data",
533    b"m_CompleteImageSize",
534    b"m_Height",
535    b"m_ImageCount",
536    b"m_IsReadable",
537    b"m_LightmapFormat",
538    b"m_Name",
539    b"m_TextureDimension",
540    b"m_TextureFormat",
541    b"m_TextureSettings",
542    b"m_Width",
543];
544
545/// Any integer, signed or not (not a bool, which UnityPy's dict keeps
546/// apart), as read.
547#[must_use]
548pub fn integer(value: &Value) -> Option<i128> {
549    match value {
550        Value::Int(i) => Some(i128::from(*i)),
551        Value::UInt(u) => Some(i128::from(*u)),
552        _ => None,
553    }
554}
555
556/// The names an extra field of a `Sprite` or a `Texture2D` cannot be set
557/// under, so that `parse_class`'s set of it fails and the value is an
558/// `UnknownObject` (`UnityPyBoost/TypeTreeHelper.cpp:538-574`; B3's review
559/// rounds 3 and 4, S3b and R4): the data descriptors on each class and its
560/// bases that refuse the set, `image` (`classes/legacy_patch/Sprite.py:10`,
561/// a property of no setter; `classes/legacy_patch/Texture2D.py:78`, whose
562/// setter raises for any value but an image or a path Pillow opens,
563/// `classes/legacy_patch/Texture2D.py:25-26`: unityrs refuses every value,
564/// since a sealed attempt never opens a host path a file's data names, a
565/// stated divergence, `PARITY.md`, B3's review round 5, Q2) and `assets_file`
566/// (`classes/Object.py:23-27`), and the three every instance of a class with
567/// a `__dict__` refuses, `__class__`, `__dict__` and `__weakref__` (Python's
568/// own). `SpriteAtlas` refuses the same but `image`; its class changes
569/// nothing (an atlas is used whatever its class). `test_sprites_kind.py`
570/// checks the list against UnityPy's classes.
571pub(crate) const SETTERLESS: [&[u8]; 5] = [
572    b"image",
573    b"assets_file",
574    b"__class__",
575    b"__dict__",
576    b"__weakref__",
577];
578
579/// Whether a child of `map`'s node cleans to one of [`SETTERLESS`].
580#[must_use]
581pub(crate) fn setterless(parsed: &Parsed, map: &Map) -> bool {
582    SETTERLESS.iter().any(|n| parsed.attr(map, n).is_some())
583}
584
585/// Whether a child of `map`'s node cleans to `set_object_reader`: UnityPy
586/// sets the child as an attribute of whatever class it builds, then its
587/// object read calls that attribute as the method it shadows
588/// (`files/ObjectReader.py`'s `read`), so the read fails, `read` (B3's
589/// review round 3, S3b), for any object read.
590#[must_use]
591pub(crate) fn shadowed(parsed: &Parsed, map: &Map) -> bool {
592    parsed.attr(map, b"set_object_reader").is_some()
593}
594
595/// A texture's object read (4.4 step 2): the checked read, then the class
596/// UnityPy builds (a `Texture2D` lacking a field of no default, or with a
597/// field it cannot be given, is an `UnknownObject`; one that shadows
598/// `set_object_reader` fails its read), then the shape.
599pub fn texture(obj: &ObjectRef) -> Result<Texture, Class> {
600    let parsed = obj
601        .read_typetree(None, true)
602        .map_err(|e| classify::parse(&e))?;
603    let root = parsed.value();
604    let map: &Map = root.as_dict().ok_or_else(shape)?;
605    if TEXTURE_FIELDS.iter().any(|f| parsed.attr(map, f).is_none())
606        || setterless(&parsed, map)
607        || shadowed(&parsed, map)
608    {
609        return Err(shape());
610    }
611    let get = |name: &[u8]| parsed.attr(map, name);
612    let width = get(b"m_Width").and_then(integer).ok_or_else(shape)?;
613    let height = get(b"m_Height").and_then(integer).ok_or_else(shape)?;
614    let format = get(b"m_TextureFormat")
615        .and_then(integer)
616        .ok_or_else(shape)?;
617    let stream = match get(b"m_StreamData") {
618        None => None,
619        Some(s) => {
620            let path = attr(&parsed, s, b"path")
621                .and_then(string)
622                .ok_or_else(shape)?;
623            let int = |name: &[u8]| attr(&parsed, s, name).and_then(integer);
624            Some(Stream {
625                path: path.clone(),
626                offset: int(b"offset").ok_or_else(shape)?,
627                size: int(b"size").ok_or_else(shape)?,
628            })
629        }
630    };
631    let image_data = match get(b"image_data") {
632        Some(Value::Bytes(b)) => b.clone(),
633        _ => return Err(shape()),
634    };
635    let platform_blob = match get(b"m_PlatformBlob") {
636        None => None,
637        Some(v) => Some(Blob::of(v).ok_or_else(shape)?),
638    };
639    Ok(Texture {
640        width,
641        height,
642        format,
643        image_data,
644        stream,
645        platform_blob,
646    })
647}
648
649/// Dereferences `pptr` from `from`: an Environment call, checked as
650/// 2.6 step 7 says ([`Seam::env_call`]).
651pub(super) fn deref(
652    seam: &Seam<'_>,
653    from: &Arc<SerializedFile>,
654    pptr: PPtr,
655) -> Result<ObjectRef, Class> {
656    seam.env_call(|| {
657        seam.env()
658            .deref(from, pptr)
659            .map_err(|e: DerefError| classify::deref(&e))
660    })
661}
662
663/// Section 5 step 1: the name of the texture the atlas's `material` names
664/// as its `_MainTex`, or none. A failure is returned for the caller, which
665/// swallows an object's skip.
666pub(super) fn material_name(
667    seam: &Seam<'_>,
668    reader: &mut Reader,
669    atlas: &ObjectRef,
670    parsed: &Parsed,
671) -> Result<Option<RawStr>, Class> {
672    let Some(material) = field(parsed, parsed.value(), b"material") else {
673        return Ok(None);
674    };
675    let at = pptr(parsed, material).ok_or_else(shape)?;
676    let target = deref(seam, atlas.file(), at)?;
677    let _top = top_bundle(target.file());
678    let _sample = Sample(target.file().meter(), seam.hooks);
679    let mat = seam.probe(|| {
680        target
681            .read_typetree(None, true)
682            .map_err(|e| classify::parse(&e))
683    })?;
684    let envs = field(&mat, mat.value(), b"m_SavedProperties")
685        .and_then(|p| field(&mat, p, b"m_TexEnvs"))
686        .ok_or_else(shape)?;
687    let Value::List(pairs) = envs else {
688        return match envs {
689            Value::Prims(p) if p.is_empty() => Ok(None),
690            _ => Err(shape()),
691        };
692    };
693    for pair in pairs {
694        // A pair, or a two-element list (section 5 step 1).
695        let two: &[Value] = match pair {
696            Value::Tuple(t) => t,
697            Value::List(l) => l,
698            _ => return Err(shape()),
699        };
700        let [first, second] = two else {
701            return Err(shape());
702        };
703        let key = match first {
704            Value::Str(s) => Some(s),
705            Value::Dict(_) => field(&mat, first, b"name").and_then(string),
706            _ => None,
707        };
708        if key.map(RawStr::as_bytes) != Some(b"_MainTex".as_slice()) {
709            continue;
710        }
711        let tex = field(&mat, second, b"m_Texture")
712            .and_then(|t| pptr(&mat, t))
713            .ok_or_else(shape)?;
714        let texture = deref(seam, target.file(), tex)?;
715        let _held = top_bundle(texture.file());
716        return reader.peek_name(seam, &texture).map(Some);
717    }
718    Ok(None)
719}
720
721/// Observation ends before the file handle drops; no retained dependency pin.
722pub(super) struct Sample<'a>(pub &'a Meter, pub &'a dyn super::Hooks);
723impl Drop for Sample<'_> {
724    fn drop(&mut self) {
725        self.1.meter(self.0);
726    }
727}
728
729#[cfg(test)]
730mod tests;