geng_state/
lib.rs

1use geng_ui as ui;
2use geng_window::Event;
3use std::ops::DerefMut;
4
5mod combined;
6mod manager;
7
8pub use combined::*;
9pub use manager::*;
10
11/// Represents a transition between states.
12pub enum Transition {
13    /// Pops (removes) the current state from the state stack.
14    Pop,
15    /// Replaces the current state with another state.
16    Switch(Box<dyn State>),
17    /// Pushes a new state on the state stack.
18    Push(Box<dyn State>),
19}
20
21/// Represents a state in the game.
22pub trait State: 'static {
23    /// Called every frame.
24    fn update(&mut self, delta_time: f64) {
25        #![allow(unused_variables)]
26    }
27
28    /// Called periodically every `fixed_delta_time` defined in [ContextOptions].
29    /// To start the application with different `fixed_delta_time`,
30    /// initialize geng with [`Geng::new_with()`].
31    fn fixed_update(&mut self, delta_time: f64) {
32        #![allow(unused_variables)]
33    }
34
35    fn draw(&mut self, framebuffer: &mut ugli::Framebuffer);
36
37    /// Called whenever an event is registered. See [Event] for a full list of possible events.
38    fn handle_event(&mut self, event: Event) {
39        #![allow(unused_variables)]
40    }
41
42    /// Called every frame. If returns `Some`, then a transition occurs.
43    fn transition(&mut self) -> Option<Transition> {
44        None
45    }
46
47    fn ui<'a>(&'a mut self, cx: &'a ui::Controller) -> Box<dyn ui::Widget + 'a> {
48        #![allow(unused_variables)]
49        Box::new(ui::Void)
50    }
51}
52
53pub struct Empty;
54
55impl State for Empty {
56    fn draw(&mut self, _: &mut ugli::Framebuffer) {}
57}
58
59impl<T: State + ?Sized> State for Box<T> {
60    fn update(&mut self, delta_time: f64) {
61        <T as State>::update(self, delta_time);
62    }
63    fn fixed_update(&mut self, delta_time: f64) {
64        <T as State>::fixed_update(self, delta_time);
65    }
66    fn draw(&mut self, framebuffer: &mut ugli::Framebuffer) {
67        <T as State>::draw(self, framebuffer);
68    }
69    fn handle_event(&mut self, event: Event) {
70        <T as State>::handle_event(self, event);
71    }
72    fn transition(&mut self) -> Option<Transition> {
73        <T as State>::transition(self)
74    }
75    fn ui<'a>(&'a mut self, cx: &'a ui::Controller) -> Box<dyn ui::Widget + 'a> {
76        <T as State>::ui(self, cx)
77    }
78}