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    /// The top-most render target egui draws into and is composited from.
67    surface: OverlaySurface,
68}
69
70/// Non-text keys forwarded to egui for editing and navigation. Typed characters
71/// go through `Input.inputString` instead (see [`EguiState::raw_input`]).
72const KEYS: &[(crate::KeyCode, egui::Key)] = {
73    use crate::KeyCode as K;
74    use egui::Key;
75    &[
76        (K::BACKSPACE, Key::Backspace),
77        (K::DELETE, Key::Delete),
78        (K::RETURN, Key::Enter),
79        (K::TAB, Key::Tab),
80        (K::ESCAPE, Key::Escape),
81        (K::LEFT, Key::ArrowLeft),
82        (K::RIGHT, Key::ArrowRight),
83        (K::UP, Key::ArrowUp),
84        (K::DOWN, Key::ArrowDown),
85        (K::HOME, Key::Home),
86        (K::END, Key::End),
87        (K::PAGE_UP, Key::PageUp),
88        (K::PAGE_DOWN, Key::PageDown),
89        (K::SPACE, Key::Space),
90        // With a held ctrl/cmd these drive select-all/copy/paste/cut/undo.
91        (K::A, Key::A),
92        (K::C, Key::C),
93        (K::V, Key::V),
94        (K::X, Key::X),
95        (K::Z, Key::Z),
96    ]
97};
98
99/// Builds the egui material: a textured, vertex-coloured, alpha-blended shader.
100/// `HideAndDontSave` keeps Unity from destroying it (and throwing NRE on later
101/// use) when a scene loads, which `DontDestroyOnLoad` does not do for assets.
102fn make_material() -> Result<Material> {
103    let (name, shader) = match Shader::find("Sprites/Default")? {
104        Some(shader) => ("Sprites/Default", shader),
105        None => (
106            "UI/Default",
107            Shader::find("UI/Default")?.ok_or_else(|| {
108                hao_il2cpp_runtime::Error::NotFound("a sprite/UI shader for egui".into())
109            })?,
110        ),
111    };
112    tracing::debug!(shader = name, "egui material shader");
113    let material = Material::new(shader)?;
114    material.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
115    Ok(material)
116}
117
118impl EguiState {
119    fn new() -> Result<Self> {
120        let ctx = egui::Context::default();
121        ctx.set_pixels_per_point(1.0);
122        let material = make_material()?;
123        Ok(Self {
124            ctx,
125            material: GcHandle::new(crate::il2cpp()?, material.object()),
126            texture: None,
127            atlas: Vec::new(),
128            pointer_down: [false; 2],
129            keys_down: [false; KEYS.len()],
130            surface: OverlaySurface::new("hao-egui-overlay"),
131        })
132    }
133
134    fn material(&self) -> Material {
135        Material(self.material.target())
136    }
137
138    /// Rebuilds the material and font texture if a scene load destroyed them
139    /// despite `HideAndDontSave`. The GC handles keep the C# wrappers alive, so
140    /// their sizes survive; only the underlying Unity objects are remade.
141    fn ensure_alive(&mut self) -> Result<()> {
142        if self.material().is_alive()? {
143            return Ok(());
144        }
145        tracing::debug!("egui: resources were destroyed, recreating");
146        self.material = GcHandle::new(crate::il2cpp()?, make_material()?.object());
147        if let Some((_, size)) = self.texture.take() {
148            self.ensure_texture(size)?;
149            if !self.atlas.is_empty() {
150                Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)?;
151            }
152        }
153        Ok(())
154    }
155
156    fn frame(&mut self, ui: &(impl Fn(&egui::Context) + ?Sized)) -> Result<()> {
157        self.ensure_alive()?;
158        let (sw, sh) = screen::size()?;
159        let (iw, ih) = (sw.max(1), sh.max(1));
160        let (w, h) = (iw as f32, ih as f32);
161
162        let input = self.raw_input(w, h)?;
163        let output = self.ctx.run(input, |ctx| ui(ctx));
164        for (id, delta) in output.textures_delta.set {
165            // Only the egui font atlas (managed texture 0) is handled here.
166            if matches!(id, egui::TextureId::Managed(_)) {
167                self.update_texture(&delta)?;
168            }
169        }
170        let primitives = self.ctx.tessellate(output.shapes, 1.0);
171        self.render(w, h, (iw, ih), &primitives)
172    }
173
174    fn raw_input(&mut self, w: f32, h: f32) -> Result<egui::RawInput> {
175        use crate::KeyCode as K;
176        let held = |k| input::key(k).unwrap_or(false);
177        let ctrl = held(K::LEFT_CONTROL) || held(K::RIGHT_CONTROL);
178        let modifiers = egui::Modifiers {
179            alt: held(K::LEFT_ALT) || held(K::RIGHT_ALT),
180            ctrl,
181            shift: held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT),
182            mac_cmd: false,
183            // On non-mac this is ctrl; egui's shortcuts check `command`.
184            command: ctrl,
185        };
186
187        let mouse = input::mouse_position()?;
188        // Unity's origin is bottom-left; egui's is top-left.
189        let pos = egui::pos2(mouse.x, h - mouse.y);
190        let mut events = vec![egui::Event::PointerMoved(pos)];
191        for (i, (button, egui_button)) in [
192            (0, egui::PointerButton::Primary),
193            (1, egui::PointerButton::Secondary),
194        ]
195        .into_iter()
196        .enumerate()
197        {
198            // Send an event only when the button changes state, so egui gets one
199            // press and one release per click rather than a press every frame
200            // (which left drags stuck to the cursor).
201            let down = input::mouse_button(button)?;
202            if down != self.pointer_down[i] {
203                self.pointer_down[i] = down;
204                events.push(egui::Event::PointerButton {
205                    pos,
206                    button: egui_button,
207                    pressed: down,
208                    modifiers,
209                });
210            }
211        }
212
213        let scroll = input::scroll_delta()?;
214        if scroll.x != 0.0 || scroll.y != 0.0 {
215            events.push(egui::Event::MouseWheel {
216                unit: egui::MouseWheelUnit::Line,
217                delta: egui::vec2(scroll.x, scroll.y),
218                modifiers,
219            });
220        }
221
222        // Non-text keys, edge-detected from the held state (see KEYS).
223        for (i, &(key_code, key)) in KEYS.iter().enumerate() {
224            let down = held(key_code);
225            if down != self.keys_down[i] {
226                self.keys_down[i] = down;
227                events.push(egui::Event::Key {
228                    key,
229                    physical_key: None,
230                    pressed: down,
231                    repeat: false,
232                    modifiers,
233                });
234            }
235        }
236
237        // Typed characters (Unity resolves layout/shift/IME for us). Control
238        // characters are left to the key events above. `Input.inputString` only
239        // exists under the legacy input manager; a game on the new Input System
240        // lacks it, so a failure here is not fatal — just skip text input.
241        if let Ok(typed) = input::input_string() {
242            for c in typed.chars().filter(|c| !c.is_control()) {
243                events.push(egui::Event::Text(c.to_string()));
244            }
245        }
246
247        Ok(egui::RawInput {
248            screen_rect: Some(egui::Rect::from_min_size(
249                egui::pos2(0.0, 0.0),
250                egui::vec2(w, h),
251            )),
252            modifiers,
253            events,
254            ..Default::default()
255        })
256    }
257
258    /// Patches the CPU atlas with a texture delta and re-uploads it.
259    fn update_texture(&mut self, delta: &egui::epaint::ImageDelta) -> Result<()> {
260        let [dw, dh] = delta.image.size();
261        let pixels: Vec<u8> = match &delta.image {
262            egui::epaint::ImageData::Font(font) => {
263                font.srgba_pixels(None).flat_map(|p| p.to_array()).collect()
264            }
265            egui::epaint::ImageData::Color(image) => {
266                image.pixels.iter().flat_map(|p| p.to_array()).collect()
267            }
268        };
269
270        match delta.pos {
271            None => {
272                self.atlas = pixels;
273                self.ensure_texture([dw, dh])?;
274            }
275            Some([x, y]) => {
276                let full = self.texture.as_ref().map(|(_, s)| *s).unwrap_or([dw, dh]);
277                for row in 0..dh {
278                    let dst = ((y + row) * full[0] + x) * 4;
279                    let src = row * dw * 4;
280                    if dst + dw * 4 <= self.atlas.len() {
281                        self.atlas[dst..dst + dw * 4].copy_from_slice(&pixels[src..src + dw * 4]);
282                    }
283                }
284            }
285        }
286        Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)
287    }
288
289    fn ensure_texture(&mut self, size: [usize; 2]) -> Result<()> {
290        if self.texture.as_ref().map(|(_, s)| *s) != Some(size) {
291            let texture = Texture2D::new(size[0] as i32, size[1] as i32, TextureFormat::RGBA32)?;
292            // Survive scene loads, as for the material.
293            texture.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
294            // Point sampling: egui's solid fills sample the atlas's white texel, and
295            // bilinear filtering blends it with transparent neighbours, which capped
296            // every fill's alpha below 1 and made the whole UI look see-through.
297            texture.set_filter_mode(crate::FilterMode::POINT)?;
298            let handle = GcHandle::new(crate::il2cpp()?, texture.object());
299            self.texture = Some((handle, size));
300        }
301        Ok(())
302    }
303
304    fn render(
305        &mut self,
306        w: f32,
307        h: f32,
308        size: (i32, i32),
309        primitives: &[egui::ClippedPrimitive],
310    ) -> Result<()> {
311        let Some((texture, _)) = &self.texture else {
312            return Ok(());
313        };
314        let material = self.material();
315        material.set_main_texture(Texture2D(texture.target()))?;
316
317        // Draw the tessellated UI into the overlay surface (cleared transparent so
318        // last frame's UI doesn't linger), which composites it on top of the game.
319        self.surface.draw(size, Color::CLEAR, || {
320            gl::push_matrix()?;
321            // Flip Y so egui's top-left origin maps to Unity's bottom-left.
322            gl::load_pixel_matrix(0.0, w, h, 0.0)?;
323            for primitive in primitives {
324                let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
325                    continue;
326                };
327                material.set_pass(0)?;
328                gl::begin(gl::Mode::Triangles)?;
329                for &index in &mesh.indices {
330                    let v = mesh.vertices[index as usize];
331                    // egui's Color32 is gamma (sRGB); Unity's linear colour space
332                    // wants linear values from GL.Color, so convert (otherwise the
333                    // dark UI is brightened into grey). Both are premultiplied.
334                    let c = egui::Rgba::from(v.color);
335                    gl::color(Color::rgba(c.r(), c.g(), c.b(), c.a()))?;
336                    gl::tex_coord(v.uv.x, v.uv.y)?;
337                    gl::vertex(v.pos.x, v.pos.y)?;
338                }
339                gl::end()?;
340            }
341            gl::pop_matrix()
342        })
343    }
344}