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