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
28#![cfg_attr(docsrs, feature(doc_cfg))]
29#![warn(missing_docs)]
30
31mod binding;
32mod bindings;
33pub mod dispatch;
34#[cfg(feature = "egui")]
35pub mod egui {
36    //! egui integration (requires the `egui` feature). See [`on_egui`].
37    //!
38    //! ```no_run
39    //! use hao_il2cpp_unity::egui;
40    //!
41    //! egui::on_egui(|ctx| {
42    //!     egui::Window::new("my mod").show(ctx, |ui| {
43    //!         ui.label("hello from Rust");
44    //!     });
45    //! })?;
46    //! # Ok::<(), hao_il2cpp_unity::runtime::Error>(())
47    //! ```
48    pub use crate::egui_backend::{
49        on_egui, register_user_texture, set_ui_scale, unregister_user_texture,
50    };
51    pub use ::egui::*;
52}
53#[cfg(feature = "egui")]
54mod egui_backend;
55pub mod gl;
56mod lifecycle;
57mod objects;
58mod overlay;
59#[cfg(feature = "reflect")]
60pub mod reflect;
61mod scene;
62mod values;
63
64pub use hao_il2cpp_runtime as runtime;
65#[cfg(unix)]
66pub use hao_il2cpp_runtime::on_init;
67use hao_il2cpp_runtime::{Error, Il2Cpp, Result};
68pub use lifecycle::{is_shutting_down, on_render, on_update, shutdown};
69pub use objects::{
70    find_object_of_type, find_objects_of_type, Camera, Canvas, Component, ComponentType,
71    GameObject, Material, RawImage, RectTransform, RenderTexture, Shader, TextMeshPro, Texture2D,
72    Transform, UnityObject,
73};
74pub use overlay::{OverlayCanvas, OverlaySurface, TextOverlay};
75pub use scene::{on_scene_loaded, Scene};
76pub use values::{
77    Color, FilterMode, HideFlags, KeyCode, LoadSceneMode, Quaternion, RenderMode, TextureFormat,
78    Vector2, Vector3,
79};
80
81impl Quaternion {
82    /// A rotation from Euler angles in degrees (`Quaternion.Euler`).
83    pub fn euler(x: f32, y: f32, z: f32) -> Result<Self> {
84        bindings::QUATERNION_EULER.call((x, y, z))
85    }
86}
87
88use bindings::*;
89
90fn il2cpp() -> Result<&'static Il2Cpp> {
91    Il2Cpp::get().ok_or_else(|| Error::NotFound("the Il2Cpp runtime".into()))
92}
93
94/// `Debug.Log`: writes to the game's log (`Player.log`).
95pub fn log(message: &str) -> Result<()> {
96    DEBUG_LOG.call((il2cpp()?.string(message)?.0,))
97}
98
99/// `Debug.LogWarning`.
100pub fn log_warning(message: &str) -> Result<()> {
101    DEBUG_LOG_WARNING.call((il2cpp()?.string(message)?.0,))
102}
103
104/// `Debug.LogError`.
105pub fn log_error(message: &str) -> Result<()> {
106    DEBUG_LOG_ERROR.call((il2cpp()?.string(message)?.0,))
107}
108
109/// `Time`.
110pub mod time {
111    use super::*;
112
113    /// Seconds since the last frame.
114    pub fn delta() -> Result<f32> {
115        TIME_DELTA.call(())
116    }
117
118    /// The total number of frames rendered since startup.
119    pub fn frame_count() -> Result<i32> {
120        TIME_FRAME_COUNT.call(())
121    }
122
123    /// How fast game time passes; 0 pauses most games.
124    pub fn scale() -> Result<f32> {
125        TIME_GET_SCALE.call(())
126    }
127
128    /// Sets [`scale`]: 1 is normal speed, 0.5 half speed, 0 pauses.
129    pub fn set_scale(scale: f32) -> Result<()> {
130        TIME_SET_SCALE.call((scale,))
131    }
132
133    /// Seconds since the game started (scaled by [`scale`]).
134    pub fn time() -> Result<f32> {
135        TIME_GET_TIME.call(())
136    }
137
138    /// Real seconds since startup, unaffected by [`scale`].
139    pub fn realtime_since_startup() -> Result<f32> {
140        TIME_REALTIME.call(())
141    }
142}
143
144/// `UnityEngine.Screen`.
145pub mod screen {
146    use super::*;
147
148    /// The window's width in pixels.
149    pub fn width() -> Result<i32> {
150        SCREEN_WIDTH.call(())
151    }
152
153    /// The window's height in pixels.
154    pub fn height() -> Result<i32> {
155        SCREEN_HEIGHT.call(())
156    }
157
158    /// `(width, height)` in pixels.
159    pub fn size() -> Result<(i32, i32)> {
160        Ok((width()?, height()?))
161    }
162}
163
164/// `UnityEngine.Input` (the legacy input manager).
165///
166/// Poll it from [`on_update`], once per frame:
167///
168/// ```no_run
169/// use hao_il2cpp_unity::{input, on_update, time, KeyCode};
170///
171/// on_update(|| {
172///     // F2 toggles slow motion.
173///     if input::key_down(KeyCode::F2).unwrap_or(false) {
174///         let scale = time::scale().unwrap_or(1.0);
175///         let _ = time::set_scale(if scale < 1.0 { 1.0 } else { 0.25 });
176///     }
177/// })?;
178/// # Ok::<(), hao_il2cpp_unity::runtime::Error>(())
179/// ```
180pub mod input {
181    use super::*;
182
183    /// Whether `key` is held this frame.
184    pub fn key(key: KeyCode) -> Result<bool> {
185        INPUT_GET_KEY.call((key,))
186    }
187
188    /// Whether `key` was pressed this frame.
189    pub fn key_down(key: KeyCode) -> Result<bool> {
190        INPUT_GET_KEY_DOWN.call((key,))
191    }
192
193    /// Whether `key` was released this frame.
194    pub fn key_up(key: KeyCode) -> Result<bool> {
195        INPUT_GET_KEY_UP.call((key,))
196    }
197
198    /// Whether mouse `button` (0 left, 1 right, 2 middle) is held.
199    pub fn mouse_button(button: i32) -> Result<bool> {
200        INPUT_GET_MOUSE_BUTTON.call((button,))
201    }
202
203    /// The cursor position in pixels, origin at the bottom left.
204    pub fn mouse_position() -> Result<Vector3> {
205        INPUT_MOUSE_POSITION.call(())
206    }
207
208    /// The scroll wheel movement this frame (`x` horizontal, `y` vertical).
209    pub fn scroll_delta() -> Result<Vector2> {
210        INPUT_SCROLL_DELTA.call(())
211    }
212
213    /// The characters typed this frame (including `\b` for backspace and `\r`
214    /// for return), for driving a text field.
215    pub fn input_string() -> Result<String> {
216        Ok(INPUT_STRING.call(())?.to_rust().unwrap_or_default())
217    }
218}
219
220/// `UnityEngine.Application`.
221pub mod application {
222    use super::*;
223
224    /// Whether the game is running (always true in a built game; false in
225    /// the editor outside play mode).
226    pub fn is_playing() -> Result<bool> {
227        APPLICATION_IS_PLAYING.call(())
228    }
229
230    /// Quits the game with an exit code.
231    pub fn quit(exit_code: i32) -> Result<()> {
232        APPLICATION_QUIT.call((exit_code,))
233    }
234}
235
236/// Resolves every wrapped Unity method against the running game, returning
237/// the ones that are missing or have a different signature.
238pub fn check_bindings() -> Vec<(String, Error)> {
239    bindings::all()
240        .into_iter()
241        .filter_map(|b| b.check().err().map(|e| (b.describe(), e)))
242        .collect()
243}