Skip to main content

hao_il2cpp_unity/
lib.rs

1//! Typed Unity wrappers for mods of Unity Il2Cpp games, on top of
2//! [`hao_il2cpp_runtime`].
3//!
4//! The runtime crate finds and hooks methods by name. This crate wraps common
5//! Unity functionality the same way for any Unity game: game objects and
6//! components, UI, scenes, logging and time. Each Unity method is looked up the
7//! first time it's used and checked against the game's real signature, so a
8//! game whose Unity version differs gives an error rather than a crash.
9//!
10//! ```no_run
11//! use std::sync::OnceLock;
12//!
13//! use hao_il2cpp_unity::{on_scene_loaded, TextOverlay};
14//!
15//! static OVERLAY: OnceLock<TextOverlay> = OnceLock::new();
16//!
17//! hao_il2cpp_unity::on_init(|_| {
18//!     on_scene_loaded(|scene, _| {
19//!         let overlay = OVERLAY.get_or_init(|| TextOverlay::new("my mod").unwrap());
20//!         overlay.set_text(&format!("scene: {}", scene.name().unwrap())).unwrap();
21//!     })
22//! });
23//! ```
24//!
25//! Unity's API may only be used from its main thread: inside hooks of methods
26//! the game calls on it, such as [`on_scene_loaded`]'s callbacks.
27
28mod binding;
29mod bindings;
30pub mod dispatch;
31#[cfg(feature = "egui")]
32pub mod egui {
33    //! egui integration (requires the `egui` feature). See [`on_egui`].
34    pub use crate::egui_backend::on_egui;
35    pub use ::egui::*;
36}
37#[cfg(feature = "egui")]
38mod egui_backend;
39pub mod gl;
40mod lifecycle;
41mod objects;
42mod overlay;
43mod scene;
44#[cfg(feature = "reflect")]
45pub mod reflect;
46mod values;
47
48pub use hao_il2cpp_runtime as runtime;
49#[cfg(unix)]
50pub use hao_il2cpp_runtime::on_init;
51use hao_il2cpp_runtime::{Error, Il2Cpp, Result};
52pub use lifecycle::{is_shutting_down, on_render, on_update, shutdown};
53pub use objects::{
54    find_object_of_type, find_objects_of_type, Camera, Canvas, Component, ComponentType,
55    GameObject, Material, RawImage, RectTransform, RenderTexture, Shader, TextMeshPro, Texture2D,
56    Transform, UnityObject,
57};
58pub use overlay::{OverlayCanvas, OverlaySurface, TextOverlay};
59pub use scene::{on_scene_loaded, Scene};
60pub use values::{
61    Color, FilterMode, HideFlags, KeyCode, LoadSceneMode, Quaternion, RenderMode, TextureFormat,
62    Vector2, Vector3,
63};
64
65impl Quaternion {
66    /// A rotation from Euler angles in degrees (`Quaternion.Euler`).
67    pub fn euler(x: f32, y: f32, z: f32) -> Result<Self> {
68        bindings::QUATERNION_EULER.call((x, y, z))
69    }
70}
71
72use bindings::*;
73
74fn il2cpp() -> Result<&'static Il2Cpp> {
75    Il2Cpp::get().ok_or_else(|| Error::NotFound("the Il2Cpp runtime".into()))
76}
77
78/// `Debug.Log`: writes to the game's log (`Player.log`).
79pub fn log(message: &str) -> Result<()> {
80    DEBUG_LOG.call((il2cpp()?.string(message)?.0,))
81}
82
83/// `Debug.LogWarning`.
84pub fn log_warning(message: &str) -> Result<()> {
85    DEBUG_LOG_WARNING.call((il2cpp()?.string(message)?.0,))
86}
87
88/// `Debug.LogError`.
89pub fn log_error(message: &str) -> Result<()> {
90    DEBUG_LOG_ERROR.call((il2cpp()?.string(message)?.0,))
91}
92
93/// `Time`.
94pub mod time {
95    use super::*;
96
97    /// Seconds since the last frame.
98    pub fn delta() -> Result<f32> {
99        TIME_DELTA.call(())
100    }
101
102    /// The total number of frames rendered since startup.
103    pub fn frame_count() -> Result<i32> {
104        TIME_FRAME_COUNT.call(())
105    }
106
107    /// How fast game time passes; 0 pauses most games.
108    pub fn scale() -> Result<f32> {
109        TIME_GET_SCALE.call(())
110    }
111
112    pub fn set_scale(scale: f32) -> Result<()> {
113        TIME_SET_SCALE.call((scale,))
114    }
115
116    /// Seconds since the game started (scaled by [`scale`]).
117    pub fn time() -> Result<f32> {
118        TIME_GET_TIME.call(())
119    }
120
121    /// Real seconds since startup, unaffected by [`scale`].
122    pub fn realtime_since_startup() -> Result<f32> {
123        TIME_REALTIME.call(())
124    }
125}
126
127/// `UnityEngine.Screen`.
128pub mod screen {
129    use super::*;
130
131    pub fn width() -> Result<i32> {
132        SCREEN_WIDTH.call(())
133    }
134
135    pub fn height() -> Result<i32> {
136        SCREEN_HEIGHT.call(())
137    }
138
139    /// `(width, height)` in pixels.
140    pub fn size() -> Result<(i32, i32)> {
141        Ok((width()?, height()?))
142    }
143}
144
145/// `UnityEngine.Input` (the legacy input manager).
146pub mod input {
147    use super::*;
148
149    /// Whether `key` is held this frame.
150    pub fn key(key: KeyCode) -> Result<bool> {
151        INPUT_GET_KEY.call((key,))
152    }
153
154    /// Whether `key` was pressed this frame.
155    pub fn key_down(key: KeyCode) -> Result<bool> {
156        INPUT_GET_KEY_DOWN.call((key,))
157    }
158
159    /// Whether `key` was released this frame.
160    pub fn key_up(key: KeyCode) -> Result<bool> {
161        INPUT_GET_KEY_UP.call((key,))
162    }
163
164    /// Whether mouse `button` (0 left, 1 right, 2 middle) is held.
165    pub fn mouse_button(button: i32) -> Result<bool> {
166        INPUT_GET_MOUSE_BUTTON.call((button,))
167    }
168
169    /// The cursor position in pixels, origin at the bottom left.
170    pub fn mouse_position() -> Result<Vector3> {
171        INPUT_MOUSE_POSITION.call(())
172    }
173
174    /// The scroll wheel movement this frame (`x` horizontal, `y` vertical).
175    pub fn scroll_delta() -> Result<Vector2> {
176        INPUT_SCROLL_DELTA.call(())
177    }
178
179    /// The characters typed this frame (including `\b` for backspace and `\r`
180    /// for return), for driving a text field.
181    pub fn input_string() -> Result<String> {
182        Ok(INPUT_STRING.call(())?.to_rust().unwrap_or_default())
183    }
184}
185
186/// `UnityEngine.Application`.
187pub mod application {
188    use super::*;
189
190    pub fn is_playing() -> Result<bool> {
191        APPLICATION_IS_PLAYING.call(())
192    }
193
194    /// Quits the game with an exit code.
195    pub fn quit(exit_code: i32) -> Result<()> {
196        APPLICATION_QUIT.call((exit_code,))
197    }
198}
199
200/// Resolves every wrapped Unity method against the running game, returning
201/// the ones that are missing or have a different signature.
202pub fn check_bindings() -> Vec<(String, Error)> {
203    bindings::all()
204        .into_iter()
205        .filter_map(|b| b.check().err().map(|e| (b.describe(), e)))
206        .collect()
207}