Skip to main content

hao_il2cpp_unity/
objects.rs

1//! Typed handles to Unity objects.
2
3use hao_il2cpp_runtime::{Il2CppValue, Object, Result, TypeInfo};
4
5use crate::{
6    bindings::*,
7    il2cpp,
8    values::{Color, Quaternion, RenderMode, Vector2, Vector3},
9};
10
11macro_rules! object_type {
12    ($(#[$doc:meta])* $name:ident = $assembly:literal $namespace:literal $class:literal) => {
13        $(#[$doc])*
14        #[repr(transparent)]
15        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16        pub struct $name(pub Object);
17
18        unsafe impl Il2CppValue for $name {
19            fn is_reference() -> bool {
20                true
21            }
22
23            fn matches(ty: TypeInfo) -> bool {
24                <Object as Il2CppValue>::matches(ty) && ty.namespace == $namespace && ty.name == $class
25            }
26        }
27
28        impl $name {
29            /// The assembly (`.dll` name without the extension) that defines the class.
30            pub const ASSEMBLY: &'static str = $assembly;
31            /// The class's namespace.
32            pub const NAMESPACE: &'static str = $namespace;
33            /// The class's name, without its namespace.
34            pub const NAME: &'static str = $class;
35
36            /// The untyped managed object, for the [`runtime`](crate::runtime) API.
37            pub fn object(&self) -> Object {
38                self.0
39            }
40
41            /// Whether this is a null reference. A destroyed object isn't null;
42            /// check [`is_alive`](Self::is_alive) for that.
43            pub fn is_null(&self) -> bool {
44                self.0.is_null()
45            }
46
47            /// `Object.name`: the name shown in Unity's hierarchy.
48            pub fn name(&self) -> Result<String> {
49                let name = OBJECT_GET_NAME.call((UnityObject(self.0),))?;
50                Ok(name.to_rust().unwrap_or_default())
51            }
52
53            /// Sets `Object.name`.
54            pub fn set_name(&self, name: &str) -> Result<()> {
55                OBJECT_SET_NAME.call((UnityObject(self.0), il2cpp()?.string(name)?))
56            }
57
58            /// Keeps the object when a new scene loads. Only works for GameObjects;
59            /// for assets (`Material`, `Texture2D`) use [`set_hide_flags`](Self::set_hide_flags).
60            pub fn dont_destroy_on_load(&self) -> Result<()> {
61                OBJECT_DONT_DESTROY_ON_LOAD.call((UnityObject(self.0),))
62            }
63
64            /// Sets the object's `HideFlags`. `HideFlags::HIDE_AND_DONT_SAVE` keeps a
65            /// runtime-created asset from being unloaded on scene load.
66            pub fn set_hide_flags(&self, flags: crate::HideFlags) -> Result<()> {
67                OBJECT_SET_HIDE_FLAGS.call((UnityObject(self.0), flags))
68            }
69
70            /// Whether the object is still alive (Unity's `(bool)obj`): `false` once
71            /// it has been destroyed, even though the managed wrapper still exists.
72            pub fn is_alive(&self) -> Result<bool> {
73                OBJECT_IS_ALIVE.call((UnityObject(self.0),))
74            }
75
76            /// Destroys the object at the end of the frame.
77            pub fn destroy(&self) -> Result<()> {
78                OBJECT_DESTROY.call((UnityObject(self.0),))
79            }
80        }
81    };
82}
83
84/// A component type, for [`GameObject::add_component`].
85///
86/// Every component wrapper in this crate implements it. A mod can wrap its
87/// own (or the game's) `MonoBehaviour` the same way by naming the class.
88pub trait ComponentType: Il2CppValue {
89    /// The assembly (`.dll` name without the extension) that defines the class.
90    const ASSEMBLY: &'static str;
91    /// The class's namespace.
92    const NAMESPACE: &'static str;
93    /// The class's name, without its namespace.
94    const NAME: &'static str;
95
96    /// Wraps a managed object known to be of this class.
97    fn from_object(object: Object) -> Self;
98    /// The untyped managed object.
99    fn object(&self) -> Object;
100
101    /// `Component.gameObject`: the game object this component is attached to.
102    fn game_object(&self) -> Result<GameObject> {
103        COMPONENT_GAME_OBJECT.call((Component(self.object()),))
104    }
105
106    /// `Component.transform`: the transform of this component's game object.
107    fn transform(&self) -> Result<Transform> {
108        COMPONENT_TRANSFORM.call((Component(self.object()),))
109    }
110
111    /// `GetComponent<U>()` on this component's game object, or `None` if absent.
112    fn get_component<U: ComponentType>(&self) -> Result<Option<U>> {
113        let found =
114            COMPONENT_GET_COMPONENT.call((Component(self.object()), component_type::<U>()?))?;
115        Ok((!found.is_null()).then(|| U::from_object(found.0)))
116    }
117
118    /// Whether the component is enabled. For `Behaviour`-derived components
119    /// (`MonoBehaviour`, `Canvas`, …); meaningless on a plain `Transform`.
120    fn is_enabled(&self) -> Result<bool> {
121        BEHAVIOUR_GET_ENABLED.call((Component(self.object()),))
122    }
123
124    /// Enables or disables the component (`Behaviour.enabled`); a disabled
125    /// `MonoBehaviour` gets no `Update` calls.
126    fn set_enabled(&self, enabled: bool) -> Result<()> {
127        BEHAVIOUR_SET_ENABLED.call((Component(self.object()), enabled))
128    }
129}
130
131/// The `System.Type` of a component type `T`, for the Unity query methods.
132fn component_type<T: ComponentType>() -> Result<Object> {
133    Ok(il2cpp()?
134        .class(T::ASSEMBLY, T::NAMESPACE, T::NAME)?
135        .type_object())
136}
137
138/// Collects the elements of a managed `T[]` whose object is `array`.
139fn read_object_array<T: ComponentType>(array: Object) -> Vec<T> {
140    if array.is_null() {
141        return Vec::new();
142    }
143    let Some(il2cpp) = il2cpp().ok() else {
144        return Vec::new();
145    };
146    let length = unsafe { (il2cpp.api().il2cpp_array_length)(array.as_ptr()) };
147    // Elements follow the array header (object header, bounds, length): 4 pointers.
148    let base = 4 * std::mem::size_of::<usize>();
149    (0..length)
150        .map(|i| {
151            T::from_object(unsafe {
152                hao_il2cpp_runtime::read_field(array, base + i * std::mem::size_of::<usize>())
153            })
154        })
155        .collect()
156}
157
158/// Every active object of type `T` in the loaded scenes (`Object.FindObjectsOfType`).
159///
160/// Call this on Unity's main thread (e.g. in [`on_update`](crate::on_update) or
161/// [`on_scene_loaded`](crate::on_scene_loaded)).
162pub fn find_objects_of_type<T: ComponentType>() -> Result<Vec<T>> {
163    let array = OBJECT_FIND_OBJECTS_OF_TYPE.call((component_type::<T>()?,))?;
164    Ok(read_object_array(array))
165}
166
167/// The first active object of type `T`, or `None` (`Object.FindObjectOfType`).
168pub fn find_object_of_type<T: ComponentType>() -> Result<Option<T>> {
169    Ok(find_objects_of_type::<T>()?.into_iter().next())
170}
171
172macro_rules! component_type {
173    ($(#[$doc:meta])* $name:ident = $assembly:literal $namespace:literal $class:literal) => {
174        object_type!($(#[$doc])* $name = $assembly $namespace $class);
175
176        impl ComponentType for $name {
177            const ASSEMBLY: &'static str = $assembly;
178            const NAMESPACE: &'static str = $namespace;
179            const NAME: &'static str = $class;
180
181            fn from_object(object: Object) -> Self {
182                Self(object)
183            }
184
185            fn object(&self) -> Object {
186                self.0
187            }
188        }
189    };
190}
191
192object_type!(
193    /// `UnityEngine.Object`, the base of everything Unity manages.
194    UnityObject = "UnityEngine.CoreModule" "UnityEngine" "Object"
195);
196object_type!(
197    /// `UnityEngine.GameObject`: an object in the scene, which holds components.
198    ///
199    /// ```no_run
200    /// use hao_il2cpp_unity::{ComponentType, GameObject, Transform, Vector3};
201    ///
202    /// // A new object, parented under the game's player.
203    /// let marker = GameObject::new("marker")?;
204    /// if let Some(player) = GameObject::find("Player")? {
205    ///     marker.transform()?.set_parent(player.transform()?, false)?;
206    ///     marker.transform()?.set_local_position(Vector3::UP * 2.0)?;
207    ///     let tf: Option<Transform> = player.get_component()?;
208    ///     println!("player at {:?}", tf.unwrap().position()?);
209    /// }
210    /// # Ok::<(), hao_il2cpp_unity::runtime::Error>(())
211    /// ```
212    GameObject = "UnityEngine.CoreModule" "UnityEngine" "GameObject"
213);
214component_type!(
215    /// `UnityEngine.Component`.
216    Component = "UnityEngine.CoreModule" "UnityEngine" "Component"
217);
218component_type!(
219    /// `UnityEngine.Transform`: position in the scene and the parent/child hierarchy.
220    Transform = "UnityEngine.CoreModule" "UnityEngine" "Transform"
221);
222component_type!(
223    /// `UnityEngine.RectTransform`, the transform of UI elements.
224    RectTransform = "UnityEngine.CoreModule" "UnityEngine" "RectTransform"
225);
226component_type!(
227    /// `UnityEngine.Canvas`, the root of a UI.
228    Canvas = "UnityEngine.UIModule" "UnityEngine" "Canvas"
229);
230component_type!(
231    /// `TMPro.TextMeshProUGUI`, TextMeshPro text in a UI.
232    TextMeshPro = "Unity.TextMeshPro" "TMPro" "TextMeshProUGUI"
233);
234component_type!(
235    /// `UnityEngine.Camera`, passed to [`on_render`](crate::on_render) callbacks.
236    Camera = "UnityEngine.CoreModule" "UnityEngine" "Camera"
237);
238object_type!(
239    /// `UnityEngine.Shader`.
240    Shader = "UnityEngine.CoreModule" "UnityEngine" "Shader"
241);
242object_type!(
243    /// `UnityEngine.Material`, e.g. for a [`gl`](crate::gl) drawing pass.
244    Material = "UnityEngine.CoreModule" "UnityEngine" "Material"
245);
246
247impl Shader {
248    /// `Shader.Find(name)`, or `None` if the shader isn't present.
249    pub fn find(name: &str) -> Result<Option<Shader>> {
250        let shader = SHADER_FIND.call((il2cpp()?.string(name)?,))?;
251        Ok((!shader.is_null()).then_some(shader))
252    }
253}
254
255impl Material {
256    /// `new Material(shader)`.
257    pub fn new(shader: Shader) -> Result<Material> {
258        let object = Material(
259            il2cpp()?
260                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
261                .new_object(),
262        );
263        MATERIAL_CTOR.call((object, shader))?;
264        Ok(object)
265    }
266
267    /// Activates pass `pass` for drawing (returns whether it can be rendered).
268    /// Call this before a [`gl`](crate::gl) primitive so it has a material.
269    pub fn set_pass(&self, pass: i32) -> Result<bool> {
270        MATERIAL_SET_PASS.call((*self, pass))
271    }
272
273    /// `Material.color`: the shader's main colour (`_Color`), which tints what it draws.
274    pub fn set_color(&self, color: Color) -> Result<()> {
275        MATERIAL_SET_COLOR.call((*self, color))
276    }
277
278    /// `Material.mainTexture`: the shader's main texture (`_MainTex`).
279    pub fn set_main_texture(&self, texture: Texture2D) -> Result<()> {
280        MATERIAL_SET_MAIN_TEXTURE.call((*self, texture.0))
281    }
282}
283
284object_type!(
285    /// `UnityEngine.Texture2D`.
286    Texture2D = "UnityEngine.CoreModule" "UnityEngine" "Texture2D"
287);
288
289impl Texture2D {
290    /// `new Texture2D(width, height, format, mipChain: false)`.
291    pub fn new(width: i32, height: i32, format: crate::TextureFormat) -> Result<Texture2D> {
292        let object = Texture2D(
293            il2cpp()?
294                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
295                .new_object(),
296        );
297        TEXTURE2D_CTOR.call((object, width, height, format, false))?;
298        Ok(object)
299    }
300
301    /// Uploads raw pixel bytes (matching the texture's format), then applies them.
302    pub fn load_raw(&self, bytes: &[u8]) -> Result<()> {
303        TEXTURE2D_LOAD_RAW.call((*self, il2cpp()?.byte_array(bytes)?))?;
304        TEXTURE2D_APPLY.call((*self,))
305    }
306
307    /// How the texture is sampled (`Point` avoids blending neighbouring texels).
308    pub fn set_filter_mode(&self, mode: crate::FilterMode) -> Result<()> {
309        TEXTURE_SET_FILTER_MODE.call((*self, mode))
310    }
311}
312
313object_type!(
314    /// `UnityEngine.RenderTexture`, an off-screen render target.
315    RenderTexture = "UnityEngine.CoreModule" "UnityEngine" "RenderTexture"
316);
317
318impl RenderTexture {
319    /// `new RenderTexture(width, height, depth)` (depth is the depth-buffer bits,
320    /// e.g. 0 for a colour-only target).
321    pub fn new(width: i32, height: i32, depth: i32) -> Result<RenderTexture> {
322        let object = RenderTexture(
323            il2cpp()?
324                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
325                .new_object(),
326        );
327        RENDER_TEXTURE_CTOR.call((object, width, height, depth))?;
328        Ok(object)
329    }
330
331    /// `RenderTexture.active`, the target GL and camera drawing goes to.
332    pub fn active() -> Result<Option<RenderTexture>> {
333        let rt = RENDER_TEXTURE_GET_ACTIVE.call(())?;
334        Ok((!rt.is_null()).then_some(rt))
335    }
336
337    /// Sets `RenderTexture.active`. Pass `None` to restore the back buffer.
338    pub fn set_active(target: Option<RenderTexture>) -> Result<()> {
339        RENDER_TEXTURE_SET_ACTIVE.call((target.unwrap_or(RenderTexture(Object::NULL)),))
340    }
341
342    /// How the texture is sampled (inherited from `Texture`).
343    pub fn set_filter_mode(&self, mode: crate::FilterMode) -> Result<()> {
344        TEXTURE_SET_FILTER_MODE.call((Texture2D(self.0), mode))
345    }
346}
347
348component_type!(
349    /// `UnityEngine.UI.RawImage`, a UI element that draws a raw [`Texture2D`] or
350    /// [`RenderTexture`].
351    RawImage = "UnityEngine.UI" "UnityEngine.UI" "RawImage"
352);
353
354impl RawImage {
355    /// The texture the image displays.
356    pub fn set_texture(&self, texture: Object) -> Result<()> {
357        RAW_IMAGE_SET_TEXTURE.call((*self, texture))
358    }
359}
360
361impl GameObject {
362    /// `new GameObject(name)`.
363    pub fn new(name: &str) -> Result<Self> {
364        let il2cpp = il2cpp()?;
365        let object = GameObject(
366            il2cpp
367                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
368                .new_object(),
369        );
370        GAME_OBJECT_CTOR.call((object, il2cpp.string(name)?))?;
371        Ok(object)
372    }
373
374    /// `GameObject.Find(name)`: an active object by name or path, such as `Canvas/Menu`.
375    pub fn find(name: &str) -> Result<Option<Self>> {
376        let found = GAME_OBJECT_FIND.call((il2cpp()?.string(name)?,))?;
377        Ok((!found.is_null()).then_some(found))
378    }
379
380    /// `AddComponent(typeof(T))`.
381    pub fn add_component<T: ComponentType>(&self) -> Result<T> {
382        let class = il2cpp()?.class(T::ASSEMBLY, T::NAMESPACE, T::NAME)?;
383        let component = GAME_OBJECT_ADD_COMPONENT.call((*self, class.type_object()))?;
384        Ok(T::from_object(component.0))
385    }
386
387    /// `GetComponent<T>()`, or `None` if the object has no such component.
388    pub fn get_component<T: ComponentType>(&self) -> Result<Option<T>> {
389        let found = GAME_OBJECT_GET_COMPONENT.call((*self, component_type::<T>()?))?;
390        Ok((!found.is_null()).then(|| T::from_object(found.0)))
391    }
392
393    /// The object's transform, which every game object has.
394    pub fn transform(&self) -> Result<Transform> {
395        GAME_OBJECT_TRANSFORM.call((*self,))
396    }
397
398    /// The transform as a [`RectTransform`], which objects with UI components have.
399    pub fn rect_transform(&self) -> Result<Option<RectTransform>> {
400        let transform = self.transform()?;
401        let class = unsafe { il2cpp()?.class_of(transform.0) };
402        Ok((class.name() == RectTransform::NAME).then_some(RectTransform(transform.0)))
403    }
404
405    /// `SetActive`: shows or hides the object and its children; inactive
406    /// objects aren't updated or drawn.
407    pub fn set_active(&self, active: bool) -> Result<()> {
408        GAME_OBJECT_SET_ACTIVE.call((*self, active))
409    }
410
411    /// Whether the object itself is active (its own flag, ignoring parents).
412    pub fn is_active(&self) -> Result<bool> {
413        GAME_OBJECT_ACTIVE_SELF.call((*self,))
414    }
415
416    /// Whether the object is active, taking its parents into account.
417    pub fn is_active_in_hierarchy(&self) -> Result<bool> {
418        GAME_OBJECT_ACTIVE_IN_HIERARCHY.call((*self,))
419    }
420
421    /// The object's tag, which games use to label kinds of objects (`"Player"`).
422    pub fn tag(&self) -> Result<String> {
423        Ok(GAME_OBJECT_GET_TAG
424            .call((*self,))?
425            .to_rust()
426            .unwrap_or_default())
427    }
428
429    /// Sets the tag; it must be one defined in the game's tag manager.
430    pub fn set_tag(&self, tag: &str) -> Result<()> {
431        GAME_OBJECT_SET_TAG.call((*self, il2cpp()?.string(tag)?))
432    }
433
434    /// Whether the object has tag `tag` (`CompareTag`).
435    pub fn compare_tag(&self, tag: &str) -> Result<bool> {
436        GAME_OBJECT_COMPARE_TAG.call((*self, il2cpp()?.string(tag)?))
437    }
438
439    /// The object's layer (0 to 31), which cameras and physics filter on.
440    pub fn layer(&self) -> Result<i32> {
441        GAME_OBJECT_GET_LAYER.call((*self,))
442    }
443
444    /// Moves the object to layer `layer` (0 to 31).
445    pub fn set_layer(&self, layer: i32) -> Result<()> {
446        GAME_OBJECT_SET_LAYER.call((*self, layer))
447    }
448}
449
450impl Transform {
451    /// Re-parents this transform under `parent`. With `world_position_stays`
452    /// the object keeps its place in the world; without, its local position,
453    /// rotation and scale are kept relative to the new parent.
454    pub fn set_parent(&self, parent: Transform, world_position_stays: bool) -> Result<()> {
455        TRANSFORM_SET_PARENT.call((*self, parent, world_position_stays))
456    }
457
458    /// Scale relative to the parent.
459    pub fn set_local_scale(&self, scale: Vector3) -> Result<()> {
460        TRANSFORM_SET_LOCAL_SCALE.call((*self, scale))
461    }
462
463    /// World-space position.
464    pub fn position(&self) -> Result<Vector3> {
465        TRANSFORM_GET_POSITION.call((*self,))
466    }
467
468    /// Moves the transform to a world-space position.
469    pub fn set_position(&self, position: Vector3) -> Result<()> {
470        TRANSFORM_SET_POSITION.call((*self, position))
471    }
472
473    /// Position relative to the parent.
474    pub fn local_position(&self) -> Result<Vector3> {
475        TRANSFORM_GET_LOCAL_POSITION.call((*self,))
476    }
477
478    /// Moves the transform to a position relative to its parent.
479    pub fn set_local_position(&self, position: Vector3) -> Result<()> {
480        TRANSFORM_SET_LOCAL_POSITION.call((*self, position))
481    }
482
483    /// World-space rotation as Euler angles in degrees.
484    pub fn euler_angles(&self) -> Result<Vector3> {
485        TRANSFORM_GET_EULER_ANGLES.call((*self,))
486    }
487
488    /// World-space rotation.
489    pub fn rotation(&self) -> Result<Quaternion> {
490        TRANSFORM_GET_ROTATION.call((*self,))
491    }
492
493    /// Sets the world-space rotation; see [`Quaternion::euler`].
494    pub fn set_rotation(&self, rotation: Quaternion) -> Result<()> {
495        TRANSFORM_SET_ROTATION.call((*self, rotation))
496    }
497
498    /// The parent transform, or `None` at the scene root.
499    pub fn parent(&self) -> Result<Option<Transform>> {
500        let parent = TRANSFORM_GET_PARENT.call((*self,))?;
501        Ok((!parent.is_null()).then_some(parent))
502    }
503
504    /// The number of direct children.
505    pub fn child_count(&self) -> Result<i32> {
506        TRANSFORM_GET_CHILD_COUNT.call((*self,))
507    }
508
509    /// The direct child at `index`, from 0 to [`child_count`](Self::child_count).
510    pub fn child(&self, index: i32) -> Result<Transform> {
511        TRANSFORM_GET_CHILD.call((*self, index))
512    }
513
514    /// A descendant by name or path (e.g. `"HUD/Health"`), or `None`.
515    pub fn find(&self, path: &str) -> Result<Option<Transform>> {
516        let found = TRANSFORM_FIND.call((*self, il2cpp()?.string(path)?))?;
517        Ok((!found.is_null()).then_some(found))
518    }
519}
520
521impl RectTransform {
522    /// This as a plain [`Transform`] (a `RectTransform` is one), for parenting
523    /// and hierarchy queries.
524    pub fn as_transform(&self) -> Transform {
525        Transform(self.0)
526    }
527
528    /// Anchors and pivot, each from (0, 0) at the bottom left of the parent to (1, 1) at the top right.
529    pub fn set_anchors(&self, min: Vector2, max: Vector2, pivot: Vector2) -> Result<()> {
530        RECT_SET_ANCHOR_MIN.call((*self, min))?;
531        RECT_SET_ANCHOR_MAX.call((*self, max))?;
532        RECT_SET_PIVOT.call((*self, pivot))
533    }
534
535    /// The pivot's position relative to the anchors, in pixels with y up.
536    pub fn set_anchored_position(&self, position: Vector2) -> Result<()> {
537        RECT_SET_ANCHORED_POSITION.call((*self, position))
538    }
539
540    /// Sets `sizeDelta`: the element's size in pixels when its anchors meet,
541    /// otherwise how much bigger it is than the area between them.
542    pub fn set_size(&self, size: Vector2) -> Result<()> {
543        RECT_SET_SIZE_DELTA.call((*self, size))
544    }
545}
546
547impl Canvas {
548    /// Whether the canvas draws over the screen, through a camera, or in the world.
549    pub fn set_render_mode(&self, mode: RenderMode) -> Result<()> {
550        CANVAS_SET_RENDER_MODE.call((*self, mode))
551    }
552
553    /// Canvases with a higher order draw on top.
554    pub fn set_sorting_order(&self, order: i32) -> Result<()> {
555        CANVAS_SET_SORTING_ORDER.call((*self, order))
556    }
557}
558
559impl TextMeshPro {
560    /// Replaces the displayed text (TextMeshPro rich-text tags are honoured).
561    pub fn set_text(&self, text: &str) -> Result<()> {
562        TMP_SET_TEXT.call((*self, il2cpp()?.string(text)?))
563    }
564
565    /// The font size in points.
566    pub fn set_font_size(&self, size: f32) -> Result<()> {
567        TMP_SET_FONT_SIZE.call((*self, size))
568    }
569
570    /// The text's colour.
571    pub fn set_color(&self, color: Color) -> Result<()> {
572        TMP_SET_COLOR.call((*self, color))
573    }
574}