Skip to main content

hao_il2cpp_unity/
egui_backend.rs

1//! Draw an [`egui`] UI over the game from the render hook. Enable with the
2//! `egui` feature.
3//!
4//! egui is rendered with Unity's immediate-mode [`gl`](crate::gl): its font atlas
5//! is uploaded to a [`Texture2D`] (point-sampled, so solid fills stay opaque),
6//! bound through a `Material`, and each tessellated triangle is emitted (with its
7//! colours converted from gamma to linear) into an [`OverlaySurface`], which draws
8//! it on top of the game's own UI. See [`on_egui`].
9
10use std::collections::HashMap;
11use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
12use std::sync::{Arc, Mutex};
13
14use hao_il2cpp_runtime::{GcHandle, Object, Result};
15
16use crate::{gl, input, screen, Color, Material, OverlaySurface, Shader, Texture2D, TextureFormat};
17
18static UI_SCALE: AtomicU32 = AtomicU32::new(0);
19static NEXT_USER_TEX: AtomicU64 = AtomicU64::new(1);
20static USER_TEXTURES: std::sync::LazyLock<Mutex<HashMap<u64, GcHandle>>> =
21    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
22
23/// Scales the egui overlay UI. A value of 0.5 makes the UI half-size; 2.0 makes
24/// it double-size. Font rasterization quality is preserved — only the coordinate
25/// space is scaled. Pass 0.0 to reset to the default (1.0).
26pub fn set_ui_scale(scale: f32) {
27    if scale <= 0.0 {
28        UI_SCALE.store(0, Ordering::Relaxed);
29    } else {
30        UI_SCALE.store(scale.to_bits(), Ordering::Relaxed);
31    }
32}
33
34fn ui_scale() -> f32 {
35    let bits = UI_SCALE.load(Ordering::Relaxed);
36    if bits == 0 {
37        1.0
38    } else {
39        f32::from_bits(bits)
40    }
41}
42
43/// Registers a Unity texture object for use in egui as a user texture.
44///
45/// Returns a [`egui::TextureId::User`] id that can be passed to egui's
46/// `Image` widget via `SizedTexture`. The texture object is GC-pinned so it
47/// won't be collected while registered.
48pub fn register_user_texture(object: Object) -> Result<egui::TextureId> {
49    let id = NEXT_USER_TEX.fetch_add(1, Ordering::Relaxed);
50    let handle = GcHandle::new(crate::il2cpp()?, object);
51    USER_TEXTURES.lock().unwrap().insert(id, handle);
52    Ok(egui::TextureId::User(id))
53}
54
55/// Removes a previously registered user texture.
56pub fn unregister_user_texture(id: egui::TextureId) {
57    if let egui::TextureId::User(n) = id {
58        USER_TEXTURES.lock().unwrap().remove(&n);
59    }
60}
61
62/// Runs `ui` every frame to build and draw an egui interface over the game.
63///
64/// Call it once (e.g. from `on_init`). The egui context, font texture and
65/// material are created on the render thread on the first frame. Mouse input is
66/// fed from `UnityEngine.Input`.
67pub fn on_egui(ui: impl Fn(&egui::Context) + Send + Sync + 'static) -> Result<()> {
68    let ui = Arc::new(ui);
69    let state: Mutex<Option<EguiState>> = Mutex::new(None);
70    // The render hook fires once per camera, so several times per frame. Run egui
71    // (input + layout) only on the first callback of each frame: otherwise a click
72    // edge is read in whichever camera's pass happened to catch it, so presses get
73    // dropped. The render target persists, so one draw per frame is enough.
74    let last_frame = std::sync::atomic::AtomicI32::new(-1);
75    crate::on_render(move |_camera| {
76        match crate::time::frame_count() {
77            Ok(frame) if last_frame.swap(frame, std::sync::atomic::Ordering::Relaxed) == frame => {
78                return
79            }
80            _ => {}
81        }
82        let mut guard = state.lock().unwrap_or_else(|e| e.into_inner());
83        let state = match guard.as_mut() {
84            Some(state) => state,
85            None => match EguiState::new() {
86                Ok(state) => guard.insert(state),
87                Err(e) => {
88                    tracing::error!("egui init failed: {}", e);
89                    return;
90                }
91            },
92        };
93        if let Err(e) = state.frame(&*ui) {
94            tracing::error!("egui frame failed: {}", e);
95        }
96    })
97}
98
99struct EguiState {
100    ctx: egui::Context,
101    /// Kept alive across frames: the GC doesn't scan Rust memory.
102    material: GcHandle,
103    texture: Option<(GcHandle, [usize; 2])>,
104    /// A CPU copy of the font atlas (RGBA), patched from egui's texture deltas.
105    atlas: Vec<u8>,
106    /// Previous state of the left/right mouse buttons, so a press or release is
107    /// sent to egui only on the edge (egui is event-based, not level-based).
108    pointer_down: [bool; 2],
109    /// Previous held state of each key in [`KEYS`], for the same edge detection
110    /// (read from the held state, as GetKeyDown is unreliable off the main thread).
111    keys_down: [bool; KEYS.len()],
112    /// Previous held state of typeable keys for the fallback text input path.
113    text_keys_down: [bool; TEXT_KEYS.len()],
114    /// Whether `Input.inputString` has ever returned a non-empty string. Once
115    /// it does, the fallback key-to-char path is disabled.
116    input_string_works: bool,
117    /// The top-most render target egui draws into and is composited from.
118    surface: OverlaySurface,
119}
120
121/// Non-text keys forwarded to egui for editing and navigation. Typed characters
122/// go through `Input.inputString` instead (see [`EguiState::raw_input`]).
123const KEYS: &[(crate::KeyCode, egui::Key)] = {
124    use crate::KeyCode as K;
125    use egui::Key;
126    &[
127        (K::BACKSPACE, Key::Backspace),
128        (K::DELETE, Key::Delete),
129        (K::RETURN, Key::Enter),
130        (K::TAB, Key::Tab),
131        (K::ESCAPE, Key::Escape),
132        (K::LEFT, Key::ArrowLeft),
133        (K::RIGHT, Key::ArrowRight),
134        (K::UP, Key::ArrowUp),
135        (K::DOWN, Key::ArrowDown),
136        (K::HOME, Key::Home),
137        (K::END, Key::End),
138        (K::PAGE_UP, Key::PageUp),
139        (K::PAGE_DOWN, Key::PageDown),
140        (K::SPACE, Key::Space),
141        // With a held ctrl/cmd these drive select-all/copy/paste/cut/undo.
142        (K::A, Key::A),
143        (K::C, Key::C),
144        (K::V, Key::V),
145        (K::X, Key::X),
146        (K::Z, Key::Z),
147    ]
148};
149
150/// Typeable keys for the fallback text input path. Each entry is a key code, the
151/// lowercase char, and the shifted char. Used only when `Input.inputString` is
152/// unavailable — it doesn't handle non-US layouts, but covers the common case.
153const TEXT_KEYS: &[(crate::KeyCode, char, char)] = {
154    use crate::KeyCode as K;
155    &[
156        (K::A, 'a', 'A'),
157        (K::B, 'b', 'B'),
158        (K::C, 'c', 'C'),
159        (K::D, 'd', 'D'),
160        (K::E, 'e', 'E'),
161        (K::F, 'f', 'F'),
162        (K::G, 'g', 'G'),
163        (K::H, 'h', 'H'),
164        (K::I, 'i', 'I'),
165        (K::J, 'j', 'J'),
166        (K::K, 'k', 'K'),
167        (K::L, 'l', 'L'),
168        (K::M, 'm', 'M'),
169        (K::N, 'n', 'N'),
170        (K::O, 'o', 'O'),
171        (K::P, 'p', 'P'),
172        (K::Q, 'q', 'Q'),
173        (K::R, 'r', 'R'),
174        (K::S, 's', 'S'),
175        (K::T, 't', 'T'),
176        (K::U, 'u', 'U'),
177        (K::V, 'v', 'V'),
178        (K::W, 'w', 'W'),
179        (K::X, 'x', 'X'),
180        (K::Y, 'y', 'Y'),
181        (K::Z, 'z', 'Z'),
182        (K::ALPHA0, '0', ')'),
183        (K::ALPHA1, '1', '!'),
184        (K::ALPHA2, '2', '@'),
185        (K::ALPHA3, '3', '#'),
186        (K(52), '4', '$'),
187        (K(53), '5', '%'),
188        (K(54), '6', '^'),
189        (K(55), '7', '&'),
190        (K(56), '8', '*'),
191        (K(57), '9', '('),
192        (K::SPACE, ' ', ' '),
193    ]
194};
195
196/// Builds the egui material: a textured, vertex-coloured, alpha-blended shader.
197/// `HideAndDontSave` keeps Unity from destroying it (and throwing NRE on later
198/// use) when a scene loads, which `DontDestroyOnLoad` does not do for assets.
199fn make_material() -> Result<Material> {
200    let (name, shader) = match Shader::find("Sprites/Default")? {
201        Some(shader) => ("Sprites/Default", shader),
202        None => (
203            "UI/Default",
204            Shader::find("UI/Default")?.ok_or_else(|| {
205                hao_il2cpp_runtime::Error::NotFound("a sprite/UI shader for egui".into())
206            })?,
207        ),
208    };
209    tracing::debug!(shader = name, "egui material shader");
210    let material = Material::new(shader)?;
211    material.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
212    Ok(material)
213}
214
215impl EguiState {
216    fn new() -> Result<Self> {
217        let ctx = egui::Context::default();
218        if let Ok((w, h)) = screen::size() {
219            tracing::info!(w, h, scale = ui_scale(), "egui overlay: screen size");
220        }
221        let material = make_material()?;
222        Ok(Self {
223            ctx,
224            material: GcHandle::new(crate::il2cpp()?, material.object()),
225            texture: None,
226            atlas: Vec::new(),
227            pointer_down: [false; 2],
228            keys_down: [false; KEYS.len()],
229            text_keys_down: [false; TEXT_KEYS.len()],
230            input_string_works: false,
231            surface: OverlaySurface::new("hao-egui-overlay"),
232        })
233    }
234
235    fn material(&self) -> Material {
236        Material(self.material.target())
237    }
238
239    /// Rebuilds the material and font texture if a scene load destroyed them
240    /// despite `HideAndDontSave`. The GC handles keep the C# wrappers alive, so
241    /// their sizes survive; only the underlying Unity objects are remade.
242    fn ensure_alive(&mut self) -> Result<()> {
243        if self.material().is_alive()? {
244            return Ok(());
245        }
246        tracing::debug!("egui: resources were destroyed, recreating");
247        self.material = GcHandle::new(crate::il2cpp()?, make_material()?.object());
248        if let Some((_, size)) = self.texture.take() {
249            self.ensure_texture(size)?;
250            if !self.atlas.is_empty() {
251                Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)?;
252            }
253        }
254        Ok(())
255    }
256
257    fn frame(&mut self, ui: &(impl Fn(&egui::Context) + ?Sized)) -> Result<()> {
258        self.ensure_alive()?;
259        let (sw, sh) = screen::size()?;
260        let (iw, ih) = (sw.max(1), sh.max(1));
261        let scale = ui_scale();
262        let inv = 1.0 / scale;
263        // Point space is larger than screen when scale < 1 → smaller UI.
264        let (pw, ph) = (iw as f32 * inv, ih as f32 * inv);
265        // Render texture matches point space so 1 point = 1 pixel → crisp text.
266        // The Canvas bilinearly downscales the larger texture to screen size.
267        let tex_w = (iw as f32 * inv) as i32;
268        let tex_h = (ih as f32 * inv) as i32;
269
270        let input = self.raw_input(pw, ph, inv)?;
271        let mut output = self.ctx.run_pass(input, |ctx| ui(ctx));
272        for (id, deltas) in &output.textures_delta.set {
273            if matches!(id, egui::TextureId::Managed(_)) {
274                for delta in deltas {
275                    self.update_texture(delta)?;
276                }
277            }
278        }
279        // The `.set` deltas are uploaded above; mark the whole delta consumed so
280        // epaint's `TexturesDelta::drop` debug_assert passes (a debug build would
281        // otherwise panic here). `.free` ids aren't reclaimed in Unity yet.
282        output.textures_delta.clear();
283        let primitives = self.ctx.tessellate(output.shapes, 1.0);
284        self.render(pw, ph, (tex_w, tex_h), &primitives)
285    }
286
287    fn raw_input(&mut self, pw: f32, ph: f32, inv: f32) -> Result<egui::RawInput> {
288        use crate::KeyCode as K;
289        let held = |k| input::key(k).unwrap_or(false);
290        let ctrl = held(K::LEFT_CONTROL) || held(K::RIGHT_CONTROL);
291        let modifiers = egui::Modifiers {
292            alt: held(K::LEFT_ALT) || held(K::RIGHT_ALT),
293            ctrl,
294            shift: held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT),
295            mac_cmd: false,
296            command: ctrl,
297        };
298
299        let mouse = input::mouse_position()?;
300        // Unity mouse is in pixel coords (bottom-left origin). Scale to point
301        // space (top-left origin): x_pt = x_px * inv, y_pt = ph - y_px * inv.
302        let pos = egui::pos2(mouse.x * inv, ph - mouse.y * inv);
303        let mut events = vec![egui::Event::PointerMoved(pos)];
304        for (i, (button, egui_button)) in [
305            (0, egui::PointerButton::Primary),
306            (1, egui::PointerButton::Secondary),
307        ]
308        .into_iter()
309        .enumerate()
310        {
311            // Send an event only when the button changes state, so egui gets one
312            // press and one release per click rather than a press every frame
313            // (which left drags stuck to the cursor).
314            let down = input::mouse_button(button)?;
315            if down != self.pointer_down[i] {
316                self.pointer_down[i] = down;
317                events.push(egui::Event::PointerButton {
318                    pos,
319                    button: egui_button,
320                    pressed: down,
321                    modifiers,
322                });
323            }
324        }
325
326        let scroll = input::scroll_delta()?;
327        if scroll.x != 0.0 || scroll.y != 0.0 {
328            events.push(egui::Event::MouseWheel {
329                unit: egui::MouseWheelUnit::Line,
330                delta: egui::vec2(scroll.x, scroll.y),
331                phase: egui::TouchPhase::Move,
332                source: egui::MouseWheelSource::Unknown,
333                modifiers,
334            });
335        }
336
337        // Non-text keys, edge-detected from the held state (see KEYS).
338        for (i, &(key_code, key)) in KEYS.iter().enumerate() {
339            let down = held(key_code);
340            if down != self.keys_down[i] {
341                self.keys_down[i] = down;
342                events.push(egui::Event::Key {
343                    key,
344                    physical_key: None,
345                    pressed: down,
346                    repeat: false,
347                    modifiers,
348                });
349            }
350        }
351
352        // Typed characters. Prefer Unity's `Input.inputString` (handles
353        // layout, shift, IME), falling back to manual key-to-char conversion
354        // when it's unavailable or consistently empty.
355        if let Ok(typed) = input::input_string() {
356            if !typed.is_empty() {
357                self.input_string_works = true;
358            }
359            for c in typed.chars().filter(|c| !c.is_control()) {
360                events.push(egui::Event::Text(c.to_string()));
361            }
362        }
363
364        // Fallback: generate text events from individual key edges when
365        // inputString isn't delivering characters. Doesn't handle non-US
366        // layouts, but covers the common case.
367        if !self.input_string_works {
368            let shift = held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT);
369            for (i, &(key_code, lower, upper)) in TEXT_KEYS.iter().enumerate() {
370                let down = held(key_code);
371                if down && !self.text_keys_down[i] {
372                    let ch = if shift { upper } else { lower };
373                    events.push(egui::Event::Text(ch.to_string()));
374                }
375                self.text_keys_down[i] = down;
376            }
377        }
378
379        Ok(egui::RawInput {
380            screen_rect: Some(egui::Rect::from_min_size(
381                egui::pos2(0.0, 0.0),
382                egui::vec2(pw, ph),
383            )),
384            events,
385            ..Default::default()
386        })
387    }
388
389    /// Patches the CPU atlas with a texture delta and re-uploads it.
390    fn update_texture(&mut self, delta: &egui::epaint::ImageDelta) -> Result<()> {
391        let [dw, dh] = delta.image.size();
392        let pixels: Vec<u8> = match &delta.image {
393            egui::epaint::ImageData::Color(image) => {
394                image.pixels.iter().flat_map(|p| p.to_array()).collect()
395            }
396        };
397
398        match delta.pos {
399            None => {
400                self.atlas = pixels;
401                self.ensure_texture([dw, dh])?;
402            }
403            Some([x, y]) => {
404                let full = self.texture.as_ref().map(|(_, s)| *s).unwrap_or([dw, dh]);
405                for row in 0..dh {
406                    let dst = ((y + row) * full[0] + x) * 4;
407                    let src = row * dw * 4;
408                    if dst + dw * 4 <= self.atlas.len() {
409                        self.atlas[dst..dst + dw * 4].copy_from_slice(&pixels[src..src + dw * 4]);
410                    }
411                }
412            }
413        }
414        Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)
415    }
416
417    fn ensure_texture(&mut self, size: [usize; 2]) -> Result<()> {
418        if self.texture.as_ref().map(|(_, s)| *s) != Some(size) {
419            let texture = Texture2D::new(size[0] as i32, size[1] as i32, TextureFormat::RGBA32)?;
420            // Survive scene loads, as for the material.
421            texture.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
422            // Point sampling: egui's solid fills sample the atlas's white texel, and
423            // bilinear filtering blends it with transparent neighbours, which capped
424            // every fill's alpha below 1 and made the whole UI look see-through.
425            texture.set_filter_mode(crate::FilterMode::POINT)?;
426            let handle = GcHandle::new(crate::il2cpp()?, texture.object());
427            self.texture = Some((handle, size));
428        }
429        Ok(())
430    }
431
432    fn render(
433        &mut self,
434        w: f32,
435        h: f32,
436        size: (i32, i32),
437        primitives: &[egui::ClippedPrimitive],
438    ) -> Result<()> {
439        let Some((atlas_handle, _)) = &self.texture else {
440            return Ok(());
441        };
442        let atlas_obj = atlas_handle.target();
443        let material = self.material();
444        material.set_main_texture(Texture2D(atlas_obj))?;
445
446        let user_textures = USER_TEXTURES.lock().unwrap();
447
448        // Draw the tessellated UI into the overlay surface (cleared transparent so
449        // last frame's UI doesn't linger), which composites it on top of the game.
450        self.surface.draw(size, Color::CLEAR, || {
451            gl::push_matrix()?;
452            // Flip Y so egui's top-left origin maps to Unity's bottom-left.
453            gl::load_pixel_matrix(0.0, w, h, 0.0)?;
454            let mut active_texture = atlas_obj;
455            for primitive in primitives {
456                let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
457                    continue;
458                };
459                let wanted = match mesh.texture_id {
460                    egui::TextureId::Managed(_) => atlas_obj,
461                    egui::TextureId::User(id) => match user_textures.get(&id) {
462                        Some(handle) => handle.target(),
463                        None => atlas_obj,
464                    },
465                };
466                if wanted != active_texture {
467                    material.set_main_texture(Texture2D(wanted))?;
468                    active_texture = wanted;
469                }
470                material.set_pass(0)?;
471                gl::begin(gl::Mode::Triangles)?;
472                for &index in &mesh.indices {
473                    let v = mesh.vertices[index as usize];
474                    // egui's Color32 is gamma (sRGB); Unity's linear colour space
475                    // wants linear values from GL.Color, so convert (otherwise the
476                    // dark UI is brightened into grey). Both are premultiplied.
477                    let c = egui::Rgba::from(v.color);
478                    gl::color(Color::rgba(c.r(), c.g(), c.b(), c.a()))?;
479                    gl::tex_coord(v.uv.x, v.uv.y)?;
480                    gl::vertex(v.pos.x, v.pos.y)?;
481                }
482                gl::end()?;
483            }
484            gl::pop_matrix()
485        })
486    }
487}