summaryrefslogtreecommitdiff
path: root/engine/src/input.rs
blob: e8477028729608e7ce4fc03f5e3a2a4920e57945 (plain)
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::collections::HashMap;

use ecs::extension::Collector as ExtensionCollector;
use ecs::sole::Single;
use ecs::Sole;

use crate::event::{
    PostPresent as PostPresentEvent,
    PreUpdate as PreUpdateEvent,
    Start as StartEvent,
};
use crate::vector::Vec2;
use crate::window::Window;

mod reexports
{
    pub use crate::window::{Key, KeyState};
}

pub use reexports::*;

#[derive(Debug, Sole)]
pub struct Keys
{
    map: HashMap<Key, KeyData>,
}

impl Keys
{
    #[must_use]
    pub fn new() -> Self
    {
        Self {
            map: Key::KEYS
                .iter()
                .map(|key| {
                    (
                        *key,
                        KeyData {
                            state: KeyState::Released,
                            prev_tick_state: KeyState::Released,
                        },
                    )
                })
                .collect(),
        }
    }

    #[must_use]
    pub fn get_key_state(&self, key: Key) -> KeyState
    {
        let Some(key_data) = self.map.get(&key) else {
            unreachable!();
        };

        key_data.state
    }

    #[must_use]
    pub fn get_prev_key_state(&self, key: Key) -> KeyState
    {
        let Some(key_data) = self.map.get(&key) else {
            unreachable!();
        };

        key_data.prev_tick_state
    }

    pub fn set_key_state(&mut self, key: Key, new_key_state: KeyState)
    {
        let Some(key_data) = self.map.get_mut(&key) else {
            unreachable!();
        };

        key_data.state = new_key_state;
    }

    #[must_use]
    pub fn is_anything_pressed(&self) -> bool
    {
        self.map
            .values()
            .any(|key_data| matches!(key_data.state, KeyState::Pressed))
    }
}

impl Default for Keys
{
    fn default() -> Self
    {
        Self::new()
    }
}

#[derive(Debug, Default, Clone, Sole)]
pub struct Cursor
{
    pub position: Vec2<f64>,
    pub has_moved: bool,
}

#[derive(Debug, Clone, Sole)]
pub struct CursorFlags
{
    /// This flag is set in two situations:
    /// A: The window has just started
    /// B: The window has gained focus again after losing focus.
    ///
    /// This flag only lasts a single tick then it is cleared (at the beginning of the
    /// next tick).
    pub is_first_move: CursorFlag,
}

impl Default for CursorFlags
{
    fn default() -> Self
    {
        Self {
            is_first_move: CursorFlag { flag: true, ..Default::default() },
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct CursorFlag
{
    pub flag: bool,
    pub pending_clear: bool,
}

impl CursorFlag
{
    pub fn clear(&mut self)
    {
        self.flag = false;
        self.pending_clear = false;
    }
}

/// Input extension.
#[derive(Debug, Default)]
pub struct Extension {}

impl ecs::extension::Extension for Extension
{
    fn collect(self, mut collector: ExtensionCollector<'_>)
    {
        collector.add_system(StartEvent, initialize);
        collector.add_system(PreUpdateEvent, maybe_clear_cursor_is_first_move);
        collector.add_system(PostPresentEvent, set_keys_prev_tick_state);

        collector.add_sole(Keys::default()).ok();
        collector.add_sole(Cursor::default()).ok();
        collector.add_sole(CursorFlags::default()).ok();
    }
}

fn initialize(
    keys: Single<Keys>,
    cursor: Single<Cursor>,
    cursor_flags: Single<CursorFlags>,
    window: Single<Window>,
)
{
    let keys_weak_ref = keys.to_weak_ref();

    window.set_key_callback(move |key, _scancode, key_state, _modifiers| {
        let keys_ref = keys_weak_ref.access().expect("No world");

        let mut keys = keys_ref.to_single();

        keys.set_key_state(key, key_state);
    });

    let cursor_weak_ref = cursor.to_weak_ref();

    window.set_cursor_pos_callback(move |cursor_position| {
        let cursor_ref = cursor_weak_ref.access().expect("No world");

        let mut cursor = cursor_ref.to_single();

        cursor.position = Vec2 {
            x: cursor_position.x,
            y: cursor_position.y,
        };

        cursor.has_moved = true;
    });

    let cursor_flags_weak_ref = cursor_flags.to_weak_ref();

    window.set_focus_callback(move |is_focused| {
        tracing::trace!("Window is focused: {is_focused}");

        let cursor_flags_ref = cursor_flags_weak_ref.access().expect("No world");

        cursor_flags_ref.to_single().is_first_move.flag = is_focused;
    });
}

fn maybe_clear_cursor_is_first_move(
    cursor: Single<Cursor>,
    mut cursor_flags: Single<CursorFlags>,
)
{
    if cursor_flags.is_first_move.pending_clear {
        tracing::trace!("Clearing is_first_move");

        // This flag was set for the whole previous tick so it can be cleared now
        cursor_flags.is_first_move.clear();

        return;
    }

    if cursor.has_moved && cursor_flags.is_first_move.flag {
        tracing::trace!("Setting flag to clear is_first_move next tick");

        // Make this system clear is_first_move the next time it runs
        cursor_flags.is_first_move.pending_clear = true;
    }
}

fn set_keys_prev_tick_state(mut keys: Single<Keys>)
{
    for key_data in keys.map.values_mut() {
        key_data.prev_tick_state = key_data.state;
    }
}

#[derive(Debug)]
struct KeyData
{
    state: KeyState,
    prev_tick_state: KeyState,
}