mirage-engine 0.1.1

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
Documentation
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Actions: what a player can do, and the controls bound to each one.
//!
//! A game names its own actions — `Jump`, `Walk`, `Aim` — in up to three
//! vocabularies, one per kind: a button is pressed, released or down, an
//! axis reads one number, an axis2 reads two. [`InputActions`] holds the
//! three, and [`Game::InputActions`](crate::Game::InputActions) names the
//! set; [`NoInputActions`] is the set of a game that reads no input, and
//! [`Key`] is the prototype set that binds each key to itself. Every query
//! — `down`, `pressed`, `released`, `axis`, `axis2` — takes an action of
//! that set and no other.
//!
//! Each action declares its own default bindings, which may hold a key, a
//! mouse button, a pad button, a stick or a composite of them. An axis or
//! axis2 binding holds a deadzone —
//! [`AxisBinding::DEFAULT_DEADZONE`](crate::AxisBinding::DEFAULT_DEADZONE)
//! for a pad or joystick control, and zero for the rest — and a scale.
//! A [`PointerDelta`] lane, a [`WheelDelta`] lane and
//! [`Axis2Binding::pointer`](crate::Axis2Binding::pointer) read how far
//! they moved through that scale and nothing clamps what they read; every
//! other binding reads in its kind's own range.
//!
//! A game that rebinds reads [`bindings`](crate::FrameContext::bindings) for
//! what an action is bound to now, and shows each binding's text.
//! [`actuated_button`](crate::FrameContext::actuated_button),
//! [`actuated_axis`](crate::FrameContext::actuated_axis) and
//! [`actuated_axis2`](crate::FrameContext::actuated_axis2) then report
//! whatever the player just moved, which
//! [`rebind`](crate::FrameContext::rebind) takes. The engine keeps every
//! rebind in the platform's own store, under a name made from the title
//! [`Config::new`](crate::Config::new) was given.
//!
//! [`Cursor`] is what the pointer itself is drawn as, the closed set
//! [`set_cursor`](crate::FrameContext::set_cursor) takes for one frame; a
//! frame that sets none draws [`Cursor::Arrow`]. Where the UI sets a cursor
//! of its own, the UI's is drawn instead. [`Cursor::Held`] draws no pointer
//! and holds it in place, leaving a [`PointerDelta`] binding its
//! movement to read and [`pointer`](crate::FrameContext::pointer) the place
//! it was held at; the frame after it sets another cursor releases it.

pub use action::{
    InputAction, InputActions, InputAxis2Action, InputAxisAction, InputButtonAction,
    NoInputActions, NoInputAxes, NoInputAxes2, NoInputButtons,
};
pub use binding::{
    Axis2Binding, AxisBinding, ButtonAxis, ButtonAxis2, ButtonBinding, JoystickControl, Key,
    MouseButton, Pad, PadAxis, PointerDelta, Stick, WheelDelta,
};
pub use cursor::Cursor;

#[cfg(feature = "offscreen")]
pub use state::Switch;

pub(crate) use pad::Pads;
pub(crate) use state::WheelRate;

use core::num::NonZeroU32;
use core::time::Duration;

use winit::event::{DeviceEvent, WindowEvent};

use crate::math::Vec2;
use crate::platform::Store;
use state::Devices;
use table::{Rebound, Table};

/// State behind the input API: every action's bindings, what the devices
/// read, and where a rebind is kept.
pub(crate) struct Input {
    table: Table,
    devices: Devices,
    pads: Pads,
    store: Store,
    dirty: bool,
    /// How long after a press a second one still counts as a double click.
    double_click: Duration,
}

impl Input {
    /// The input a run starts with: the game's actions at their declared
    /// bindings, with whatever `store` kept of an earlier run over them.
    pub(crate) fn new<A: InputActions>(pads: Pads, store: Store, double_click: Duration) -> Self {
        Self {
            table: Table::new::<A>(store.read().as_deref()),
            devices: Devices::default(),
            pads,
            store,
            dirty: false,
            double_click,
        }
    }

    pub(crate) fn see(&mut self, event: &WindowEvent) {
        self.devices.see(event);
    }

    /// Takes what `event` reports of a device's own movement, which a held
    /// pointer moves by and a pointer the window still places ignores.
    pub(crate) fn see_device(&mut self, event: &DeviceEvent) {
        self.devices.see_device(event);
    }

    /// Holds the pointer in place or releases it, by what the platform did
    /// with it rather than by what the frame set.
    pub(crate) fn hold_pointer(&mut self, held: bool) {
        self.devices.hold_pointer(held);
    }

    /// Presses `control` or releases it in place of a window's event; only
    /// a session calls this.
    #[cfg(feature = "offscreen")]
    pub(crate) fn press(&mut self, control: Switch, down: bool) {
        self.devices.press(control, down);
    }

    /// Moves the pointer in place of a window's event; only a session calls
    /// this.
    #[cfg(feature = "offscreen")]
    pub(crate) fn point_at(&mut self, at: Vec2) {
        self.devices.point_at(at);
    }

    /// Moves one lane of the pointer in place of a window's event; only a
    /// session calls this.
    #[cfg(feature = "offscreen")]
    pub(crate) fn move_pointer(&mut self, lane: PointerDelta, pixels: f32) {
        self.devices.move_pointer(lane.moving(pixels));
    }

    /// Turns one lane of the wheel in place of a window's event; only a
    /// session calls this.
    #[cfg(feature = "offscreen")]
    pub(crate) fn turn_wheel(&mut self, lane: WheelDelta, notches: f32) {
        self.devices.turn_wheel(lane.turning(notches));
    }

    /// The `Shift`, `Control` and `Alt` keys held down as of now, as the
    /// UI reads them, with `Control` as its command key.
    ///
    /// Only a session reads this: the keys a window holds down reach the
    /// UI through `egui-winit`. A window on `macOS` takes its command key
    /// from `Super`, which [`Key`] has no position for, so a session's
    /// `Control` is what a command reads there.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn ui_modifiers(&self) -> egui::Modifiers {
        let either = |left, right| {
            self.devices.holds(Switch::Key(left)) || self.devices.holds(Switch::Key(right))
        };
        let ctrl = either(Key::LeftControl, Key::RightControl);

        egui::Modifiers {
            alt: either(Key::LeftAlt, Key::RightAlt),
            ctrl,
            shift: either(Key::LeftShift, Key::RightShift),
            mac_cmd: false,
            command: ctrl,
        }
    }

    /// Where the pointer has been placed, ahead of the snapshot the game
    /// reads, or `None` where nothing has placed it yet; only a session
    /// reads this, for the press it passes to the UI.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn pointing_at(&self) -> Option<Vec2> {
        self.devices.pointing_at()
    }

    /// Closes the snapshot that every tick, and the frame that follows
    /// them, read from — at `at` on the run's own clock.
    pub(crate) fn sample(&mut self, at: Duration) {
        self.devices.sample(&mut self.pads, at, self.double_click);
    }

    /// Runs `tick` `count` times, on the edges since the last frame whose
    /// ticks ran.
    ///
    /// Each call reads the same edges; no later tick reads them again.
    pub(crate) fn ticks(&mut self, count: NonZeroU32, mut tick: impl FnMut(&Ticking<'_>)) {
        let ticking = Ticking { input: self };
        for _ in 0..count.get() {
            tick(&ticking);
        }
    }

    pub(crate) fn down<A: InputButtonAction>(&self, action: A) -> bool {
        self.devices.snapshot().down(self.table.resolve(action))
    }

    pub(crate) fn pressed<A: InputButtonAction>(&self, action: A) -> bool {
        self.devices.snapshot().pressed(self.table.resolve(action))
    }

    pub(crate) fn released<A: InputButtonAction>(&self, action: A) -> bool {
        self.devices.snapshot().released(self.table.resolve(action))
    }

    pub(crate) fn clicks<A: InputButtonAction>(&self, action: A) -> u32 {
        match self.pressed(action) {
            true => self.devices.clicks(self.table.resolve(action)),
            false => 0,
        }
    }

    pub(crate) fn axis<A: InputAxisAction>(&self, action: A) -> f32 {
        self.devices.snapshot().axis(self.table.resolve(action))
    }

    pub(crate) fn axis2<A: InputAxis2Action>(&self, action: A) -> Vec2 {
        self.devices.snapshot().axis2(self.table.resolve(action))
    }

    pub(crate) fn pointer(&self) -> Vec2 {
        self.devices.snapshot().pointer()
    }

    pub(crate) fn bindings<A: InputAction>(&self, action: A) -> Vec<A::Binding> {
        self.table.resolve(action).to_vec()
    }

    /// Binds `action` to `bindings` and marks the store to be written where
    /// that is not what the action already read through.
    pub(crate) fn rebind<A: InputAction>(&mut self, action: A, bindings: Vec<A::Binding>) {
        match self.table.rebind(action, bindings) {
            Rebound::Changed => self.dirty = true,
            Rebound::Unchanged => {}
        }
    }

    /// Writes the bindings where a rebind changed one since the last call,
    /// and nothing at all where none did.
    pub(crate) fn flush(&mut self) {
        if core::mem::take(&mut self.dirty) {
            self.store.write(&self.table.written());
        }
    }

    pub(crate) fn actuated_button(&self) -> Option<ButtonBinding> {
        self.devices.snapshot().actuated_button()
    }

    pub(crate) fn actuated_axis(&self) -> Option<AxisBinding> {
        self.devices.snapshot().actuated_axis()
    }

    pub(crate) fn actuated_axis2(&self) -> Option<Axis2Binding> {
        self.devices.snapshot().actuated_axis2()
    }

    /// Whether `action` went down since the last frame whose ticks ran.
    /// Only [`Ticking`] calls this.
    fn pressed_over_ticks<A: InputButtonAction>(&self, action: A) -> bool {
        self.devices.ticks().pressed(self.table.resolve(action))
    }

    /// Whether `action` came up since the last frame whose ticks ran. Only
    /// [`Ticking`] calls this.
    fn released_over_ticks<A: InputButtonAction>(&self, action: A) -> bool {
        self.devices.ticks().released(self.table.resolve(action))
    }

    /// Presses in a row the press these ticks read is the last of. Only
    /// [`Ticking`] calls this.
    fn clicks_over_ticks<A: InputButtonAction>(&self, action: A) -> u32 {
        match self.pressed_over_ticks(action) {
            true => self.devices.clicks(self.table.resolve(action)),
            false => 0,
        }
    }

    /// Ends the ticks of one frame. Only dropping a [`Ticking`] calls this.
    fn ticked(&mut self) {
        self.devices.ticked();
    }
}

/// The input the ticks of one frame read. [`Input::ticks`] is the only
/// source of one.
///
/// Dropping it ends those ticks, so no later tick reads an edge these ticks
/// already read.
pub(crate) struct Ticking<'a> {
    input: &'a mut Input,
}

impl Ticking<'_> {
    pub(crate) fn down<A: InputButtonAction>(&self, action: A) -> bool {
        self.input.down(action)
    }

    pub(crate) fn pressed<A: InputButtonAction>(&self, action: A) -> bool {
        self.input.pressed_over_ticks(action)
    }

    pub(crate) fn released<A: InputButtonAction>(&self, action: A) -> bool {
        self.input.released_over_ticks(action)
    }

    pub(crate) fn clicks<A: InputButtonAction>(&self, action: A) -> u32 {
        self.input.clicks_over_ticks(action)
    }

    pub(crate) fn axis<A: InputAxisAction>(&self, action: A) -> f32 {
        self.input.axis(action)
    }

    pub(crate) fn axis2<A: InputAxis2Action>(&self, action: A) -> Vec2 {
        self.input.axis2(action)
    }

    pub(crate) fn pointer(&self) -> Vec2 {
        self.input.pointer()
    }
}

impl Drop for Ticking<'_> {
    fn drop(&mut self) {
        self.input.ticked();
    }
}

mod action;
mod binding;
mod cursor;
mod pad;
mod state;
mod table;

#[cfg(test)]
mod tests {
    use super::*;
    use winit::event::{DeviceId, ElementState};

    /// The interval these tests count a double click by.
    const DOUBLE_CLICK: Duration = Duration::from_millis(400);

    /// More than one tick in a frame, so a test can check what each tick
    /// reads.
    const TICKS: NonZeroU32 = match NonZeroU32::new(3) {
        Some(ticks) => ticks,
        None => NonZeroU32::MIN,
    };

    /// A run reading through the keyboard as its own vocabulary, keeping
    /// nothing between runs.
    fn input() -> Input {
        Input::new::<Key>(Pads::silent(), Store::bindings(None), DOUBLE_CLICK)
    }

    /// The primary mouse button pressed, which is the one control a test can
    /// press: `winit` keeps a keyboard event's platform field private, so no
    /// other crate builds one.
    fn click() -> WindowEvent {
        WindowEvent::MouseInput {
            device_id: DeviceId::dummy(),
            state: ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        }
    }

    /// What each of the `count` ticks of one frame reads for `action`.
    fn pressed_per_tick(input: &mut Input, count: NonZeroU32, action: Key) -> Vec<bool> {
        let mut read = Vec::new();
        input.ticks(count, |ticking| read.push(ticking.pressed(action)));
        read
    }

    #[test]
    fn only_a_rebind_that_changed_something_leaves_the_store_to_write() {
        let mut input = input();

        input.rebind(Key::Space, vec![Key::Space.into()]);
        assert!(!input.dirty, "what it read through already is no change");

        input.rebind(Key::Space, vec![Key::Enter.into()]);
        assert!(input.dirty);
        input.flush();

        assert!(!input.dirty, "so the store is written once, not per call");
        assert_eq!(input.bindings(Key::Space), vec![Key::Enter.into()]);
    }

    #[test]
    fn the_ticks_of_one_frame_read_an_edge_and_the_ticks_after_them_read_none() {
        let mut input = input();
        input.rebind(Key::Space, vec![MouseButton::Left.into()]);

        input.see(&click());
        input.sample(Duration::ZERO);
        input.sample(Duration::ZERO);

        assert_eq!(
            pressed_per_tick(&mut input, TICKS, Key::Space),
            [true; 3],
            "every tick of the frame that reads the press reads it"
        );

        input.sample(Duration::ZERO);
        assert_eq!(
            pressed_per_tick(&mut input, TICKS, Key::Space),
            [false; 3],
            "and the ticks that follow read it no more"
        );
    }
}