Skip to main content

unityrs_testkit/ngui/
objects.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/classes/generated.py. See THIRD_PARTY_LICENSES.
2//! The objects of an NGUI scene, each a [`super::V`] of its class's fields
3//! in the 2022.3 layout: the atlas MonoBehaviour and its sprites, the
4//! `MonoScript`, the `Material` and the `Texture2D`, inline or streamed.
5
6use super::{Object, V, pair, pptr, s, st, vector};
7
8/// The MonoBehaviour head every MonoBehaviour starts with, in the field
9/// order of UnityPy's generated `MonoBehaviour` class (`generated.py`, MIT),
10/// so UnityPy's `parse_monobehaviour_head` reads it from a file with or
11/// without typetrees: `m_GameObject`, `m_Enabled`, `m_Script`, `m_Name`.
12fn head(script: (i32, i64), name: &[u8]) -> Vec<(String, V)> {
13    vec![
14        ("m_GameObject".to_owned(), pptr("GameObject", (0, 0))),
15        ("m_Enabled".to_owned(), V::Bool(true)),
16        ("m_Script".to_owned(), pptr("MonoScript", script)),
17        ("m_Name".to_owned(), V::Str(name.to_vec())),
18    ]
19}
20
21/// A MonoBehaviour (class 114): the head, then `fields`.
22#[must_use]
23pub fn mono_behaviour(
24    path_id: i64,
25    name: &[u8],
26    script: (i32, i64),
27    fields: Vec<(&str, V)>,
28) -> Object {
29    let mut all = head(script, name);
30    all.extend(fields.into_iter().map(|(n, v)| (n.to_owned(), v)));
31    Object::new(path_id, 114, V::Struct("MonoBehaviour".to_owned(), all))
32}
33
34/// A MonoScript (class 115) of `class_name`, in no namespace, with the
35/// 2022.3 fields of UnityPy's generated `MonoScript` class (`generated.py`,
36/// MIT) and AssetStudio's `MonoScript` reader (MIT), the layout a stripped
37/// one is read by, `m_PropertiesHash` (a `Hash128`) among them.
38#[must_use]
39pub fn mono_script(path_id: i64, class_name: &str) -> Object {
40    let hash = V::Struct(
41        "Hash128".to_owned(),
42        (0..16u8)
43            .map(|i| (format!("bytes[{i}]"), V::UInt8(i)))
44            .collect(),
45    );
46    Object::new(
47        path_id,
48        115,
49        st(
50            "MonoScript",
51            vec![
52                ("m_Name", s(class_name)),
53                ("m_ExecutionOrder", V::Int(0)),
54                ("m_PropertiesHash", hash),
55                ("m_ClassName", s(class_name)),
56                ("m_Namespace", s("")),
57                ("m_AssemblyName", s("Assembly-CSharp.dll")),
58            ],
59        ),
60    )
61}
62
63/// An NGUI `UISpriteData`: `name`, its rectangle, then the borders and
64/// paddings, which the cutter does not apply (`docs/BATCH_SPEC.md` section 5).
65#[must_use]
66pub fn sprite(name: &[u8], rect: (i32, i32, i32, i32), trim: [i32; 8]) -> V {
67    let (x, y, width, height) = rect;
68    let names = [
69        "borderLeft",
70        "borderRight",
71        "borderTop",
72        "borderBottom",
73        "paddingLeft",
74        "paddingRight",
75        "paddingTop",
76        "paddingBottom",
77    ];
78    let mut fields = vec![
79        ("name".to_owned(), V::Str(name.to_vec())),
80        ("x".to_owned(), V::Int(x)),
81        ("y".to_owned(), V::Int(y)),
82        ("width".to_owned(), V::Int(width)),
83        ("height".to_owned(), V::Int(height)),
84    ];
85    fields.extend(
86        names
87            .iter()
88            .zip(trim)
89            .map(|(n, v)| ((*n).to_owned(), V::Int(v))),
90    );
91    V::Struct("UISpriteData".to_owned(), fields)
92}
93
94/// An NGUI atlas: a MonoBehaviour whose `m_Script` is `script`, with
95/// `material`, `mSprites` (`sprites`, each shaped as the first or as
96/// [`sprite`]'s), `mPixelSize` 1, and `extra` fields after them.
97#[must_use]
98pub fn atlas(
99    path_id: i64,
100    name: &[u8],
101    script: (i32, i64),
102    material: (i32, i64),
103    sprites: Vec<V>,
104    extra: Vec<(&str, V)>,
105) -> Object {
106    let shape = sprites
107        .first()
108        .cloned()
109        .unwrap_or_else(|| sprite(b"", (0, 0, 0, 0), [0; 8]));
110    let mut fields = vec![
111        ("material", pptr("Material", material)),
112        ("mSprites", vector(shape, sprites)),
113        ("mPixelSize", V::Float(1.0)),
114    ];
115    fields.extend(extra);
116    mono_behaviour(path_id, name, script, fields)
117}
118
119/// A `_MainTex`-style property name: a plain string, or a
120/// `FastPropertyName` struct with a `name`.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum PropName {
123    /// `first` a `string`.
124    Plain,
125    /// `first` a `FastPropertyName { name }`.
126    Fast,
127}
128
129fn prop(kind: PropName, name: &str) -> V {
130    match kind {
131        PropName::Plain => s(name),
132        PropName::Fast => st("FastPropertyName", vec![("name", s(name))]),
133    }
134}
135
136/// A Material (class 21) whose `m_SavedProperties.m_TexEnvs` holds `envs`,
137/// each a property name and its texture pointer, the names written as `kind`.
138#[must_use]
139pub fn material(path_id: i64, name: &str, kind: PropName, envs: &[(&str, (i32, i64))]) -> Object {
140    let vec2 = || st("Vector2f", vec![("x", V::Float(1.0)), ("y", V::Float(1.0))]);
141    let env = |texture: (i32, i64)| {
142        st(
143            "UnityTexEnv",
144            vec![
145                ("m_Texture", pptr("Texture", texture)),
146                ("m_Scale", vec2()),
147                ("m_Offset", vec2()),
148            ],
149        )
150    };
151    let map = |shape: V, items: Vec<V>| V::Vector("map".to_owned(), Box::new(shape), items);
152    let tex_envs = map(
153        pair(prop(kind, ""), env((0, 0))),
154        envs.iter()
155            .map(|(n, at)| pair(prop(kind, n), env(*at)))
156            .collect(),
157    );
158    let floats = map(
159        pair(prop(kind, ""), V::Float(0.0)),
160        vec![pair(prop(kind, "_Cutoff"), V::Float(0.5))],
161    );
162    let color = st(
163        "ColorRGBA",
164        vec![
165            ("r", V::Float(1.0)),
166            ("g", V::Float(1.0)),
167            ("b", V::Float(1.0)),
168            ("a", V::Float(1.0)),
169        ],
170    );
171    let colors = map(
172        pair(prop(kind, ""), color.clone()),
173        vec![pair(prop(kind, "_Color"), color)],
174    );
175    let sheet = st(
176        "UnityPropertySheet",
177        vec![
178            ("m_TexEnvs", tex_envs),
179            ("m_Floats", floats),
180            ("m_Colors", colors),
181        ],
182    );
183    Object::new(
184        path_id,
185        21,
186        st(
187            "Material",
188            vec![
189                ("m_Name", s(name)),
190                ("m_Shader", pptr("Shader", (0, 0))),
191                ("m_SavedProperties", sheet),
192            ],
193        ),
194    )
195}
196
197/// A Material (class 21) of every field of the 2022.3 layout, the one a
198/// stripped Material is read by, its `m_TexEnvs` holding `envs` (plain
199/// names): [`material`]'s value with the keyword lists, flags, tag map,
200/// shader passes, `m_Ints` and texture stacks between, all empty. The
201/// fields and their order are UnityPy's generated `Material` class's
202/// (`generated.py`, MIT); the two flags are a `UInt8` and an aligned
203/// `bool`, as AssetStudio's `Material` reader (MIT) reads them.
204#[must_use]
205pub fn material_tpk(path_id: i64, name: &str, envs: &[(&str, (i32, i64))]) -> Object {
206    let mut value = material(path_id, name, PropName::Plain, envs).value;
207    let strings = || vector(s(""), Vec::new());
208    let map = |shape: V| V::Vector("map".to_owned(), Box::new(shape), Vec::new());
209    if let V::Struct(_, fields) = &mut value {
210        let sheet = fields.pop();
211        fields.extend(
212            [
213                ("m_ValidKeywords", strings()),
214                ("m_InvalidKeywords", strings()),
215                ("m_LightmapFlags", V::UInt(4)),
216                ("m_EnableInstancingVariants", V::UInt8(0)),
217                ("m_DoubleSidedGI", V::Bool(false)),
218                ("m_CustomRenderQueue", V::Int(-1)),
219                ("stringTagMap", map(pair(s(""), s("")))),
220                ("disabledShaderPasses", strings()),
221            ]
222            .map(|(n, v)| (n.to_owned(), v)),
223        );
224        if let Some((n, V::Struct(ty, mut sheet))) = sheet {
225            sheet.insert(1, ("m_Ints".to_owned(), map(pair(s(""), V::Int(0)))));
226            fields.push((n, V::Struct(ty, sheet)));
227        }
228        let stack = st(
229            "BuildTextureStackReference",
230            vec![("groupName", s("")), ("itemName", s(""))],
231        );
232        fields.push(("m_BuildTextureStacks".to_owned(), vector(stack, Vec::new())));
233    }
234    Object::new(path_id, 21, value)
235}
236
237/// `TextureFormat` values the scenes use.
238pub mod format {
239    /// `Alpha8`, outside E15's five.
240    pub const ALPHA8: i32 = 1;
241    /// `RGB24`.
242    pub const RGB24: i32 = 3;
243    /// `RGBA32`.
244    pub const RGBA32: i32 = 4;
245    /// `DXT1`.
246    pub const DXT1: i32 = 10;
247    /// `BC4`, which decodes to `L`.
248    pub const BC4: i32 = 26;
249}
250
251/// A `Texture2D`'s fields up to `image_data`, which UnityPy 1.25.2's class
252/// requires, so `obj.read().image` decodes it.
253fn texture_fields(name: &[u8], fmt: i32, size: (i32, i32), complete: u32) -> Vec<(String, V)> {
254    let settings = st(
255        "GLTextureSettings",
256        vec![
257            ("m_FilterMode", V::Int(1)),
258            ("m_Aniso", V::Int(1)),
259            ("m_MipBias", V::Float(0.0)),
260            ("m_WrapU", V::Int(1)),
261            ("m_WrapV", V::Int(1)),
262            ("m_WrapW", V::Int(1)),
263        ],
264    );
265    vec![
266        ("m_Name".to_owned(), V::Str(name.to_vec())),
267        ("m_ForcedFallbackFormat".to_owned(), V::Int(4)),
268        ("m_DownscaleFallback".to_owned(), V::Bool(false)),
269        ("m_Width".to_owned(), V::Int(size.0)),
270        ("m_Height".to_owned(), V::Int(size.1)),
271        ("m_CompleteImageSize".to_owned(), V::UInt(complete)),
272        ("m_TextureFormat".to_owned(), V::Int(fmt)),
273        ("m_MipCount".to_owned(), V::Int(1)),
274        ("m_IsReadable".to_owned(), V::Bool(false)),
275        ("m_ImageCount".to_owned(), V::Int(1)),
276        ("m_TextureDimension".to_owned(), V::Int(2)),
277        ("m_TextureSettings".to_owned(), settings),
278        ("m_LightmapFormat".to_owned(), V::Int(0)),
279        ("m_ColorSpace".to_owned(), V::Int(1)),
280    ]
281}
282
283/// A `Texture2D` (class 28) with `data` inline in `image_data`, and no
284/// `m_StreamData` (a tree from before 5.3).
285#[must_use]
286pub fn texture(path_id: i64, name: &[u8], fmt: i32, size: (i32, i32), data: Vec<u8>) -> Object {
287    let complete = u32::try_from(data.len()).unwrap_or(u32::MAX);
288    let mut fields = texture_fields(name, fmt, size, complete);
289    fields.push(("image_data".to_owned(), V::Bytes(data)));
290    Object::new(path_id, 28, V::Struct("Texture2D".to_owned(), fields))
291}
292
293/// A `Texture2D` (class 28) with an empty `image_data` and an `m_StreamData`
294/// naming `len` bytes at `offset` of the resource `path` (empty: no stream).
295#[must_use]
296pub fn texture_streamed(
297    path_id: i64,
298    name: &[u8],
299    fmt: i32,
300    size: (i32, i32),
301    path: &str,
302    offset: u64,
303    len: u32,
304) -> Object {
305    let mut fields = texture_fields(name, fmt, size, len);
306    fields.push(("image_data".to_owned(), V::Bytes(Vec::new())));
307    let stream = st(
308        "StreamingInfo",
309        vec![
310            ("offset", V::UInt64(offset)),
311            ("size", V::UInt(len)),
312            ("path", s(path)),
313        ],
314    );
315    fields.push(("m_StreamData".to_owned(), stream));
316    Object::new(path_id, 28, V::Struct("Texture2D".to_owned(), fields))
317}
318
319/// `object` with its field `name` set to `value` (in place, keeping its
320/// position) and renamed `rename` when that is set; a field it lacks is
321/// appended. A scene's way to give a builder's object another shape.
322#[must_use]
323pub fn set_field(mut object: Object, name: &str, value: V, rename: Option<&str>) -> Object {
324    if let V::Struct(_, fields) = &mut object.value {
325        let to = rename.unwrap_or(name).to_owned();
326        match fields.iter_mut().find(|(n, _)| n == name) {
327            Some(f) => *f = (to, value),
328            None => fields.push((to, value)),
329        }
330    }
331    object
332}