1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
pub use winit::event::VirtualKeyCode as Key;

use {
    crate::{context::Context, frame::Frame},
    std::{fmt, iter, slice},
};

/// The main application loop.
pub trait Loop {
    type Error: From<Error> + fmt::Debug;

    /// Calls before render a frame to update the state.
    ///
    /// It accepts the [`Context`] and an [`Input`].
    /// The context uses to update the application state, create or delete any resources.
    /// The input contains an inputed data like a mouse position and etc.
    ///
    /// # Errors
    /// Return [`Error`](crate::Loop::Error) if this fails.
    fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error>;

    /// Calls on render a frame.
    ///
    /// It accepts a [`Frame`] to draw something on the canvas.
    ///
    /// # Errors
    /// Return [`Error`](crate::Loop::Error) if this fails.
    fn render(&self, frame: &mut Frame) -> Result<(), Self::Error>;

    /// Calls when an error has occurred.
    fn error_occurred(&mut self, err: Self::Error) {
        log::error!("{err:?}");
    }

    /// Calls when a close is requested.
    ///
    /// Returns a flag whether to terminate the main loop or not.
    fn close_requested(&mut self) -> bool {
        true
    }
}

impl<L> Loop for &mut L
where
    L: Loop,
{
    type Error = L::Error;

    fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error> {
        (**self).update(context, input)
    }

    fn render(&self, frame: &mut Frame) -> Result<(), Self::Error> {
        (**self).render(frame)
    }
}

impl<L> Loop for Box<L>
where
    L: Loop,
{
    type Error = L::Error;

    fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error> {
        self.as_mut().update(context, input)
    }

    fn render(&self, frame: &mut Frame) -> Result<(), Self::Error> {
        self.as_ref().render(frame)
    }
}

/// The main loop error.
#[derive(Debug)]
pub enum Error {
    /// Returns when a rendered resourse not found.
    ResourceNotFound,

    /// Returns when an instance of rendered resourse is not set.
    InstanceNotSet,
}

/// The user input data.
pub struct Input<'a> {
    /// Seconds since previous [update](crate::Loop::update) was called.
    pub delta_time: f32,

    /// The cursor XY position on the screen.
    /// `None` if the cursor out of screen.
    pub cursor_position: Option<(f32, f32)>,

    /// The mouse input data.
    pub mouse: Mouse,

    /// The pressed keys.
    pub pressed_keys: Keys<'a>,

    /// The released keys.
    pub released_keys: Keys<'a>,
}

/// The mouse input data.
#[derive(Clone, Copy, Default)]
pub struct Mouse {
    pub motion_delta: (f32, f32),
    pub wheel_delta: (f32, f32),
    pub pressed_left: bool,
    pub pressed_middle: bool,
    pub pressed_right: bool,
}

/// Keys input data.
#[derive(Clone, Copy)]
pub struct Keys<'a> {
    pub(crate) keys: &'a [Key],
}

impl<'a> IntoIterator for Keys<'a> {
    type Item = Key;
    type IntoIter = KeysIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        KeysIterator {
            iter: self.keys.iter().copied(),
        }
    }
}

/// Keys iterator.
pub struct KeysIterator<'a> {
    iter: iter::Copied<slice::Iter<'a, Key>>,
}

impl Iterator for KeysIterator<'_> {
    type Item = Key;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl ExactSizeIterator for KeysIterator<'_> {}