Skip to main content

unityrs_export/ngui/sprites/
mod.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/export/SpriteHelper.py's get_image and get_image_from_sprite (which Sprites read and render, the sheet and alpha texture each takes, in that order), and export/Texture2DConverter.py's parse_image_data for a side of 0. See THIRD_PARTY_LICENSES.
2//! The `sprites` output kind (`outputs.sprites`, `docs/BATCH_SPEC.md` 1.5;
3//! `docs/plans/extract.md` E17): one PNG per Sprite of the input's own
4//! `SerializedFile`s (section 3), rendered by `unityrs_texture::sprite` from
5//! a sheet that may be in a dependency (`docs/plans/batch.md` 2.6).
6//!
7//! - **The plan** ([`plan`], 4.4, in plan order between the textures kind
8//!   and the atlases): each Sprite's name (step 1, `duplicate_name` among
9//!   Sprites), the skips that need no pixels (step 2: the Sprite's checked
10//!   read as UnityPy constructs it, then E17's fields ([`object`]), its
11//!   render data ([`atlas`]), then its texture's dereference, object read
12//!   and, for a sheet with no side of 0, section 3's answers 2 and 3, and
13//!   then its alpha texture's), then its key from the `sprites` template
14//!   (step 3), from the attempt's one key table.
15//! - **Sprite groups** (4.4): the planned Sprites grouped by their sheet,
16//!   the texture's file ([`files`]: the row chain it was opened from) and
17//!   path id, and the alpha texture's or none ([`SheetId`]), in the order
18//!   of each group's first Sprite (a counting sort, linear and counted),
19//!   whose pointers to its sheet the group keeps ([`GroupSheet`]).
20//! - **The export** ([`export`]), first in 4.4's export order: each group's
21//!   sheet dereferenced from its record and decoded once (section 3's
22//!   answers 4 to 10, 12 and 13; a side of 0 is UnityPy's 0 x 0 `RGBA`
23//!   image; a failure every Sprite's of the group), its alpha texture with
24//!   it and merged in (`sprite::Sheet`), then each Sprite rendered, in plan
25//!   order, and its PNG made (E19) with its visible hash (E20).
26//!
27//! The textures a Sprite renders from are found by dereferencing, so every
28//! such read is an Environment call checked as 2.6 step 7 says, its target's
29//! top-level bundle held while it is used and dropped when the read ends:
30//! the plan keeps no handle into another bundle (a group keeps its first
31//! Sprite's own file and pointers, an atlas's index keeps render data, not
32//! the atlas). Every buffer is charged to `M_X` before it is allocated,
33//! every core call is under the refusal probe on its own, and each pixel
34//! buffer is counted as export work (`docs/plans/batch.md` 2.6 step 10): a
35//! decoded sheet's and a merged sheet's before they are made, a rendered
36//! image's once the render returns it, after answer 11 and before its PNG
37//! (the canvases inside the render are charged to `M_X` and its loops
38//! counted as decode work, E59).
39
40mod atlas;
41mod export;
42mod files;
43mod object;
44mod plan;
45
46use std::sync::Arc;
47
48use unityrs_core::ObjectRef;
49use unityrs_core::env::PPtr;
50use unityrs_core::files::{BundleFile, SerializedFile};
51use unityrs_core::limits::{Meter, MeteredVec};
52use unityrs_texture::sprite::{SpriteData, SpriteError};
53
54use super::MemberPath;
55use super::classify::{self, Class, Reason};
56use super::read;
57use super::seam::Seam;
58use super::table::Map;
59use object::{Ids, RenderData};
60
61/// `Sprite`'s class id.
62pub(super) const SPRITE: i32 = 213;
63/// `SpriteAtlas`'s class id.
64pub(super) const SPRITE_ATLAS: i32 = 687_078_895;
65
66impl From<SpriteError> for Class {
67    fn from(e: SpriteError) -> Self {
68        classify::render(&e)
69    }
70}
71
72/// A texture's identity in 4.4's sprite groups: its file's number in the
73/// attempt ([`files::Files`]) and its path id.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
75pub(super) struct SheetId {
76    file: u32,
77    path_id: i64,
78}
79
80/// A sprite group's sheet: the texture's identity, and its alpha
81/// texture's or none.
82pub(super) type GroupKey = (SheetId, Option<SheetId>);
83
84/// Where a group's export finds its sheet (recorded at the plan, from the
85/// group's first Sprite): the Sprite's own file; the `m_SpriteAtlas`
86/// pointer of it, where its render data is that atlas's (the textures'
87/// pointers are then the atlas's file's); and the texture's and alpha
88/// texture's pointers.
89pub(super) struct GroupSheet {
90    from: Arc<SerializedFile>,
91    atlas: Option<PPtr>,
92    texture: PPtr,
93    alpha: Option<PPtr>,
94}
95
96/// A planned Sprite: its object, what it renders from, its group and its
97/// key.
98pub(super) struct SpritePlan {
99    pub plan_index: u64,
100    /// The Sprite.
101    pub obj: ObjectRef,
102    /// Its render data's rectangle and settings, with its
103    /// `m_PixelsToUnits`.
104    pub data: SpriteData,
105    /// Its group's index in [`Sprites::groups`].
106    pub group: u32,
107    /// Its key.
108    pub key: String,
109    /// Its archive member paths.
110    pub members: MeteredVec<MemberPath>,
111}
112
113/// The sprites kind's plan: the planned Sprites in plan order, and their
114/// groups' sheets in the order of each one's first Sprite.
115pub(super) struct Sprites {
116    /// The planned Sprites, in plan order.
117    pub planned: MeteredVec<SpritePlan>,
118    /// The groups' sheets.
119    pub groups: MeteredVec<GroupSheet>,
120    /// Each group's index, by its key.
121    index: Map<GroupKey, u32>,
122}
123
124impl Sprites {
125    /// No Sprite planned.
126    pub fn new(meter: &Arc<Meter>) -> Self {
127        Self {
128            planned: MeteredVec::new(meter),
129            groups: MeteredVec::new(meter),
130            index: Map::new(meter),
131        }
132    }
133}
134
135/// A Sprite's render data, resolved (E17): its rectangle and settings
136/// with its `m_PixelsToUnits`; the render data; the file its pointers are
137/// read from; the `m_SpriteAtlas` pointer, where the render data is that
138/// atlas's; and the atlas's top-level bundle, held while the caller uses
139/// them (2.6 step 7).
140pub(super) struct Resolved {
141    /// The render data's rectangle and settings, and `m_PixelsToUnits`.
142    pub data: SpriteData,
143    /// The render data.
144    rd: RenderData,
145    /// The file that holds it.
146    pub holder: Arc<SerializedFile>,
147    /// `m_SpriteAtlas`, where the render data is its atlas's.
148    pub atlas: Option<PPtr>,
149    _held: Option<Arc<BundleFile>>,
150}
151
152fn bad_pointer() -> Class {
153    Class::Skip(Reason::plain("bad_pointer"))
154}
155
156/// A `PPtr`'s ids followed from `from` (`PPtr.deref`), with the core
157/// pointer they are: an `m_FileID` outside an `int` names no external,
158/// `bad_pointer` (the core's `FileIdPastEnd`); an `m_PathID` outside an
159/// `i64` (a `UInt64` past `2^63`) names no object of any file, so its file
160/// is found as any id's is (its failure the pointer's) and then none is
161/// there, `bad_pointer` (UnityPy's `KeyError`, the core's `MissingObject`;
162/// B3's review round 3, S3a).
163fn follow(
164    seam: &Seam<'_>,
165    from: &Arc<SerializedFile>,
166    ids: Ids,
167) -> Result<(ObjectRef, PPtr), Class> {
168    let file_id = i32::try_from(ids.file_id).map_err(|_| bad_pointer())?;
169    let Ok(path_id) = i64::try_from(ids.path_id) else {
170        let any = PPtr {
171            file_id,
172            path_id: 1,
173        };
174        drop(read::deref(seam, from, any)?);
175        return Err(bad_pointer());
176    };
177    let pptr = PPtr { file_id, path_id };
178    Ok((read::deref(seam, from, pptr)?, pptr))
179}