tiny_game_framework/gui/
ui.rs

1use imgui::*;
2use glfw::Window;
3
4use crate::{EventLoop, ImguiRenderer};
5
6pub struct Imgui {
7    last_frame: f64,
8
9    /* 
10     * INPUT IS YET TO BE IMPLEMENTED
11     */
12
13    renderer: ImguiRenderer,
14    pub ctx: Context,
15}
16
17impl Imgui {
18    pub fn new(window: &mut Window) -> Self {
19        let mut ctx = imgui::Context::create();
20
21        let renderer = ImguiRenderer::new(
22            &mut ctx, |s| window.get_proc_address(s) as _);
23
24        Self {
25            last_frame: window.glfw.get_time(),
26
27            renderer, 
28            ctx,
29        }
30    }
31
32    pub fn frame(&mut self, window: &mut Window) -> &mut Ui {
33        let io = self.ctx.io_mut();
34
35        let now = window.glfw.get_time();
36        let delta = now - self.last_frame;
37        self.last_frame = now;
38        io.delta_time = delta as f32;
39
40        let (w, h) = window.get_size();
41        io.display_size = [w as f32, h as f32];
42
43        self.ctx.frame()
44    }
45
46    pub fn on_mouse_move(
47        &mut self, xpos: f32, ypos: f32, 
48    ) {
49        self.ctx.io_mut().mouse_pos = [0., 0.];
50        self.ctx.io_mut().mouse_pos = [xpos, ypos];
51    }
52    pub fn on_mouse_click(
53        &mut self, button: glfw::MouseButton, action: glfw::Action,
54    ) {
55        let is_pressed = if action == glfw::Action::Press {true} else {false};
56
57        match button {
58            glfw::MouseButton::Button1 => { 
59                self.ctx.io_mut().mouse_down[0] = is_pressed;
60            },
61            glfw::MouseButton::Button2 => {
62                self.ctx.io_mut().mouse_down[1] = is_pressed;
63            },
64            glfw::MouseButton::Button3 => {
65                self.ctx.io_mut().mouse_down[2] = is_pressed;
66            },
67            glfw::MouseButton::Button4 => {
68                self.ctx.io_mut().mouse_down[3] = is_pressed;
69            },
70            glfw::MouseButton::Button5 => {
71                self.ctx.io_mut().mouse_down[4] = is_pressed;
72            },
73            _ => {},
74        }
75    }
76
77    pub fn on_mouse_scroll(&mut self, x: f32, y: f32) {
78        self.ctx.io_mut().mouse_wheel = y;
79        self.ctx.io_mut().mouse_wheel_h = x;
80    }
81
82    pub fn draw(&mut self) {
83        self.renderer.render(&mut self.ctx);
84    }
85}