Skip to main content

unityrs_testkit/ngui/
sprite_atlases.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/classes/generated.py. See THIRD_PARTY_LICENSES.
2//! The `sprites` kind's scenes of atlases, file identities and fields
3//! (`docs/plans/extract.md` E17; B3's review round 1, R2, R4, R8 and T1):
4//! Sprites whose render data is a `SpriteAtlas`'s, found by `m_SpriteAtlas`
5//! or by a tag, in the Sprite's file or a dependency; two files of one CAB
6//! name, one nested; and Sprites whose fields UnityPy's class or E17 does
7//! not take.
8//!
9//! A `SpriteAtlas` ([`sprite_atlas`]) holds the fields
10//! `tools/fixtures/sprite_build.py`'s atlas tree holds, in its order, from
11//! the same sources (nothing from a TPK or a dump, `docs/plans/core.md`
12//! section 9, Q2): of the fields UnityPy 1.25.2's MIT `SpriteAtlas`
13//! (`classes/generated.py`) declares, those without a default: `m_Name`,
14//! `m_PackedSprites`, `m_PackedSpriteNamesToIndex`, `m_RenderDataMap` (a
15//! `map` of a `pair<GUID, SInt64>` to a `SpriteAtlasData`), `m_Tag` and
16//! `m_IsVariant`. Its `SpriteAtlasData` is the tree's: `texture`,
17//! `alphaTexture`, `textureRect`, `textureRectOffset`, `uvTransform`,
18//! `downscaleMultiplier` and `settingsRaw`.
19
20use super::scenes::{one, scene};
21use super::sprites::{RECT, SpriteSpec, alone, floats_of, key, rectf, rgba, sprites};
22use super::{AtlasScene, BuildError, Object, V, file, pptr, s, st, vector};
23use crate::env::bundle;
24
25/// `SpriteAtlas`'s class id.
26const SPRITE_ATLAS: i32 = 687_078_895;
27
28/// One entry of an atlas's `m_RenderDataMap`: its key (a `GUID`'s words
29/// and an id) and its `SpriteAtlasData`'s texture, alpha texture (null:
30/// none), rectangle and settings.
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct AtlasEntry {
33    /// `first`: the `GUID`'s words and the id.
34    pub key: ([u32; 4], i64),
35    /// `texture`.
36    pub texture: (i32, i64),
37    /// `alphaTexture`.
38    pub alpha: (i32, i64),
39    /// `textureRect`.
40    pub rect: [f32; 4],
41    /// `settingsRaw`.
42    pub settings: u32,
43}
44
45impl AtlasEntry {
46    /// A rectangle entry of `key` on `texture`, no alpha texture.
47    #[must_use]
48    pub fn rect(key: ([u32; 4], i64), texture: (i32, i64), rect: [f32; 4]) -> Self {
49        Self {
50            key,
51            texture,
52            alpha: (0, 0),
53            rect,
54            settings: RECT,
55        }
56    }
57}
58
59/// The `SpriteAtlasData` of `e`.
60pub(super) fn atlas_data(e: &AtlasEntry) -> V {
61    st(
62        "SpriteAtlasData",
63        vec![
64            ("texture", pptr("Texture2D", e.texture)),
65            ("alphaTexture", pptr("Texture2D", e.alpha)),
66            ("textureRect", rectf(e.rect)),
67            (
68                "textureRectOffset",
69                floats_of("Vector2f", &["x", "y"], &[0.0; 2]),
70            ),
71            (
72                "uvTransform",
73                floats_of("Vector4f", &["x", "y", "z", "w"], &[0.0; 4]),
74            ),
75            ("downscaleMultiplier", V::Float(1.0)),
76            ("settingsRaw", V::UInt(e.settings)),
77        ],
78    )
79}
80
81/// A `SpriteAtlas` named `name` (none: no `m_Name` field, so `peek_name`
82/// finds none) of `entries`, in order.
83#[must_use]
84pub fn sprite_atlas(name: Option<&str>, entries: &[AtlasEntry]) -> V {
85    let shape = super::pair(
86        key([0; 4], 0),
87        atlas_data(&AtlasEntry::rect(([0; 4], 0), (0, 0), [0.0; 4])),
88    );
89    let map = V::Vector(
90        "map".to_owned(),
91        Box::new(shape),
92        entries
93            .iter()
94            .map(|e| super::pair(key(e.key.0, e.key.1), atlas_data(e)))
95            .collect(),
96    );
97    let mut fields = Vec::new();
98    if let Some(n) = name {
99        fields.push(("m_Name", s(n)));
100    }
101    fields.extend([
102        (
103            "m_PackedSprites",
104            vector(pptr("Sprite", (0, 0)), Vec::new()),
105        ),
106        ("m_PackedSpriteNamesToIndex", vector(s(""), Vec::new())),
107        ("m_RenderDataMap", map),
108        ("m_Tag", s(name.unwrap_or(""))),
109        ("m_IsVariant", V::Bool(false)),
110    ]);
111    st("SpriteAtlas", fields)
112}
113
114fn atlas_object(path_id: i64, name: Option<&str>, entries: &[AtlasEntry]) -> Object {
115    Object::new(path_id, SPRITE_ATLAS, sprite_atlas(name, entries))
116}
117
118const K1: ([u32; 4], i64) = ([9, 8, 7, 6], 21);
119const K2: ([u32; 4], i64) = ([9, 8, 7, 6], 22);
120const K3: ([u32; 4], i64) = ([5, 5, 5, 5], 21);
121
122/// Atlases in the Sprites' own file (`{name}.png`). The file's atlases, in
123/// object order: `other` (another tag), one with no name, `packs` (its
124/// entries `K1` and `K2` on the sheet `packed`), and one whose name's read
125/// fails (cut short). `by_tag` and `by_tag_2` find `packs` by their tag
126/// past the first two and render its entries (the atlas read once), never
127/// reading the last; `missing_key`'s key is no entry's (`render`);
128/// `unmatched`'s tag is none's, so every name is read, the last's failure
129/// its own (`read`); `direct` names `packs` by `m_SpriteAtlas`;
130/// `unresolved`'s `m_SpriteAtlas` names no object (`bad_pointer`) and
131/// `not_an_atlas`'s a texture, which has no `m_RenderDataMap` (`render`).
132pub fn atlas_lookup() -> Result<AtlasScene, BuildError> {
133    let packs = [
134        AtlasEntry::rect(K1, (0, 2), [1.0, 1.0, 3.0, 2.0]),
135        AtlasEntry::rect(K2, (0, 2), [4.0, 4.0, 2.0, 3.0]),
136    ];
137    let other = [AtlasEntry::rect(K1, (0, 1), [0.0, 0.0, 1.0, 1.0])];
138    let own = |name: &str| SpriteSpec::rect(name, [0.0, 0.0, 2.0, 2.0], (0, 1));
139    alone(
140        "CAB-a1",
141        &[
142            rgba(1, "own", 0x01, 8, 8),
143            rgba(2, "packed", 0x41, 8, 8),
144            atlas_object(3, Some("other"), &other),
145            atlas_object(4, None, &other),
146            atlas_object(5, Some("packs"), &packs),
147            atlas_object(6, Some("broken"), &other).cut_to(6),
148            own("by_tag")
149                .tagged(&["packs", "other"])
150                .keyed(K1)
151                .object(10),
152            own("by_tag_2").tagged(&["packs"]).keyed(K2).object(11),
153            own("missing_key").tagged(&["packs"]).keyed(K3).object(12),
154            own("unmatched").tagged(&["nothing"]).keyed(K1).object(13),
155            own("direct").in_atlas((0, 5)).keyed(K2).object(14),
156            own("unresolved").in_atlas((0, 99)).keyed(K1).object(15),
157            own("not_an_atlas").in_atlas((0, 1)).keyed(K1).object(16),
158        ],
159        "{name}.png",
160    )
161}
162
163/// An atlas in a dependency: `far` and `far_2` name it by `m_SpriteAtlas`,
164/// its entries' textures (one with an alpha texture) the dependency's; a
165/// tag is looked for in the Sprite's own file only, so `tag_elsewhere`
166/// (the dependency's atlas's name) and `fallback` (no atlas's) render
167/// their own `m_RD`.
168pub fn atlas_dependency() -> Result<AtlasScene, BuildError> {
169    let entries = [
170        AtlasEntry {
171            alpha: (0, 2),
172            ..AtlasEntry::rect(K1, (0, 1), [0.0, 0.0, 4.0, 4.0])
173        },
174        AtlasEntry::rect(K2, (0, 1), [2.0, 2.0, 3.0, 3.0]),
175    ];
176    let dep = file(
177        &[],
178        &[
179            rgba(1, "dep_packed", 0x51, 8, 8),
180            rgba(2, "dep_alpha", 0x91, 8, 8),
181            atlas_object(3, Some("dep"), &entries),
182        ],
183        true,
184    )?;
185    let local = [AtlasEntry::rect(K1, (0, 1), [0.0, 0.0, 1.0, 1.0])];
186    let own = |name: &str| SpriteSpec::rect(name, [1.0, 0.0, 2.0, 3.0], (0, 1));
187    let cab = file(
188        &["archive:/CAB-a3/CAB-a3"],
189        &[
190            rgba(1, "own", 0x21, 4, 4),
191            atlas_object(2, Some("local"), &local),
192            own("far").in_atlas((1, 3)).keyed(K1).object(3),
193            own("far_2").in_atlas((1, 3)).keyed(K2).object(4),
194            own("tag_elsewhere").tagged(&["dep"]).keyed(K1).object(5),
195            own("fallback").tagged(&["zzz"]).keyed(K1).object(6),
196        ],
197        true,
198    )?;
199    Ok(scene(
200        vec![
201            one("d.bundle", &[("CAB-a3", dep)], &[]),
202            one("x.bundle", &[("CAB-a2", cab)], &["d.bundle"]),
203        ],
204        &["x.bundle"],
205        sprites("{name}.png"),
206    ))
207}
208
209/// Two files of one CAB name in one input (B3's review round 1, R4): the
210/// input's rows are `CAB-x` (a texture at path id 1), `CAB-n1` (the
211/// Sprites) and a nested bundle whose rows are another `CAB-x` (another
212/// texture at path id 1) and `CAB-n2` (an atlas whose entry is on its
213/// sibling's texture). `top` renders from the top-level `CAB-x` (its
214/// sibling); `nested`, by the atlas, from the nested one: two sheets, two
215/// groups.
216pub fn nested_cabs() -> Result<AtlasScene, BuildError> {
217    let top_x = file(&[], &[rgba(1, "top", 0x23, 4, 4)], true)?;
218    let inner_x = file(&[], &[rgba(1, "inner", 0xA3, 4, 4)], true)?;
219    let entries = [AtlasEntry::rect(K1, (1, 1), [0.0, 0.0, 3.0, 3.0])];
220    let inner_atlas = file(
221        &["archive:/CAB-x/CAB-x"],
222        &[atlas_object(1, Some("inner_atlas"), &entries)],
223        true,
224    )?;
225    let sprites_file = file(
226        &["archive:/CAB-x/CAB-x", "archive:/CAB-n2/CAB-n2"],
227        &[
228            SpriteSpec::rect("top", [0.0, 0.0, 3.0, 3.0], (1, 1)).object(1),
229            SpriteSpec::rect("nested", [0.0, 0.0, 1.0, 1.0], (1, 1))
230                .in_atlas((2, 1))
231                .keyed(K1)
232                .object(2),
233        ],
234        true,
235    )?;
236    let inner = bundle(&[("CAB-x", inner_x), ("CAB-n2", inner_atlas)]);
237    Ok(scene(
238        vec![one(
239            "x.bundle",
240            &[("CAB-x", top_x), ("CAB-n1", sprites_file), ("inner", inner)],
241            &[],
242        )],
243        &["x.bundle"],
244        sprites("{name}_{path_id}.png"),
245    ))
246}
247
248/// `v`, a struct, with a field `name` of `value` after its others.
249pub(super) fn add(v: V, name: &str, value: V) -> V {
250    match v {
251        V::Struct(ty, mut fields) => {
252            fields.push((name.to_owned(), value));
253            V::Struct(ty, fields)
254        }
255        other => other,
256    }
257}
258
259/// `v`, a struct, with its field `name` replaced by `with` (none: removed).
260pub(super) fn edit(v: V, name: &str, with: Option<V>) -> V {
261    let V::Struct(ty, fields) = v else {
262        return v;
263    };
264    let mut with = with;
265    let fields = fields
266        .into_iter()
267        .filter_map(|(n, f)| {
268            if n == name {
269                with.take().map(|w| (n, w))
270            } else {
271                Some((n, f))
272            }
273        })
274        .collect();
275    V::Struct(ty, fields)
276}
277
278/// Sprites whose fields UnityPy's class or E17 does not take (B3's review
279/// round 1, R8), each `read`, before any pointer is followed: no
280/// `m_Extrude` (UnityPy's `Sprite` requires it), an `m_PixelsToUnits` that
281/// is an `int` and `m_RD`'s `settingsRaw` a `float`; and `fine`. (A vector
282/// of `int`s as `m_AtlasTags` is `sprite_objects.rs`'s `int_tags`, beside
283/// an atlas: B3's review round 3, T2.)
284pub fn sprite_fields() -> Result<AtlasScene, BuildError> {
285    let spec = |name: &str| SpriteSpec::rect(name, [0.0, 0.0, 2.0, 2.0], (0, 1));
286    let sprite = |path_id: i64, v: V| Object::new(path_id, 213, v);
287    let rd = |v: &V| match v {
288        V::Struct(_, fields) => fields
289            .iter()
290            .find(|(n, _)| n == "m_RD")
291            .map(|(_, f)| f.clone()),
292        _ => None,
293    };
294    let base = spec("settings_float").value();
295    let settings = rd(&base).map(|r| edit(r, "settingsRaw", Some(V::Float(2.0))));
296    alone(
297        "CAB-f1",
298        &[
299            rgba(1, "sheet", 0x33, 4, 4),
300            sprite(2, edit(spec("no_extrude").value(), "m_Extrude", None)),
301            sprite(
302                3,
303                edit(spec("ppu_int").value(), "m_PixelsToUnits", Some(V::Int(1))),
304            ),
305            sprite(4, edit(base, "m_RD", settings)),
306            spec("fine").object(6),
307        ],
308        "{name}.png",
309    )
310}
311
312/// A tag that raises beside a later name's kept failure (B3's review round
313/// 4, R3; `{name}.png`): the file's atlases are `a` (2) and one whose name's
314/// read fails (3, cut short). `unmatched`'s tag is none's, so its walk reads
315/// both names and fails at the second's, which is kept; `pointer_tags`'
316/// `m_AtlasTags` is a true `PPtr`, not indexable, which raises after the
317/// first name's read, before the kept failure is reached: `render`, as in
318/// UnityPy's loop. `swapped` puts `pointer_tags` first, so the answers do
319/// not hang on the Sprites' order.
320fn raised_tags_in(cab: &str, swapped: bool) -> Result<AtlasScene, BuildError> {
321    let entries = [AtlasEntry::rect(K1, (0, 1), [0.0, 0.0, 1.0, 1.0])];
322    let spec = |name: &str| SpriteSpec::rect(name, [0.0, 0.0, 2.0, 2.0], (0, 1)).keyed(K1);
323    let unmatched = spec("unmatched").tagged(&["zzz"]).value();
324    let pointer = edit(
325        spec("pointer_tags").value(),
326        "m_AtlasTags",
327        Some(pptr("SpriteAtlas", (0, 2))),
328    );
329    let (first, second) = if swapped {
330        (pointer, unmatched)
331    } else {
332        (unmatched, pointer)
333    };
334    alone(
335        cab,
336        &[
337            rgba(1, "own", 0x2E, 4, 4),
338            atlas_object(2, Some("a"), &entries),
339            atlas_object(3, Some("broken"), &entries).cut_to(6),
340            Object::new(10, 213, first),
341            Object::new(11, 213, second),
342        ],
343        "{name}.png",
344    )
345}
346
347/// [`raised_tags_in`], the unmatched tag's Sprite first.
348pub fn raised_tags() -> Result<AtlasScene, BuildError> {
349    raised_tags_in("CAB-a4", false)
350}
351
352/// [`raised_tags_in`], the raising tag's Sprite first.
353pub fn raised_tags_swapped() -> Result<AtlasScene, BuildError> {
354    raised_tags_in("CAB-a5", true)
355}