mirage-engine 0.2.0

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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Creates the window, runs the event loop, and starts the GPU.

use core::time::Duration;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use winit::application::ApplicationHandler;
use winit::event::{DeviceEvent, DeviceId, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};

use crate::gpu::Gpu;
use crate::input::{Devices, Pads, WheelRate};
use crate::math::UVec2;
use crate::renderer::Renderer;
use crate::sound::{Output, SoundOutput};
use crate::ui::Painter;
use crate::{Config, Error, Game, InitContext};
use threads::{DisplayEnd, DisplayThread, Kept, Starting, Workers};

#[cfg(not(target_arch = "wasm32"))]
use native as sys;
#[cfg(target_arch = "wasm32")]
use web as sys;

/// A point in time the engine reads, on any target.
pub use sys::Instant;

pub(crate) use sys::{AFTER_LOSS, AFTER_OUT_OF_MEMORY, PLATFORM, hardware_threads, spawn_worker};

#[cfg(feature = "offscreen")]
pub(crate) use sys::install_diagnostics;

pub(crate) use sys::PointerHold;

/// How far this build's windows report the wheel turning for one notch.
pub(crate) const WHEEL_RATE: WheelRate = PLATFORM.wheel_rate();

/// How long after a press a second one counts as a double click where the
/// platform states none of its own, and what a windowless session counts
/// by: `400` milliseconds.
pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);

/// Which platform this build runs on, as that platform's own seam states
/// it: a number the two targets count by is a match over this.
// One build states one of the two, so the other is built by the tests
// alone; a `cfg` cannot state that here, where a `cfg` on the target may
// only select a module.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Platform {
    /// A window of the desktop's own.
    Desktop,
    /// A canvas in a browser page.
    Browser,
}

impl Platform {
    /// How far this platform's windows report the wheel turning for one
    /// notch.
    pub(crate) const fn wheel_rate(self) -> WheelRate {
        match self {
            Self::Desktop => WheelRate::DESKTOP,
            Self::Browser => WheelRate::BROWSER,
        }
    }
}

/// How long after a press a second one counts as a double click for a run
/// `config` starts behind a window: what the game set, else what the
/// desktop states, else [`DOUBLE_CLICK_INTERVAL`].
pub(crate) fn double_click_interval(config: &Config) -> Duration {
    config
        .double_click_interval()
        .or_else(sys::double_click_interval)
        .unwrap_or(DOUBLE_CLICK_INTERVAL)
}

/// Text a sweep over stored text drops in, from what a store writes to what
/// it never could.
#[cfg(test)]
const GARBAGE: [char; 8] = [' ', '\n', '\\', 's', '#', '\u{0}', '\u{7f}', 'é'];

/// Storage for one kind of a game's kept text between runs: a file of its
/// own on the desktop, an entry of its own in the page's store in the
/// browser.
pub(crate) struct Store(Option<String>);

impl Store {
    /// Storage for the bindings of a game called `title`, or nowhere at
    /// all for a run that must not read or write a player's own bindings.
    pub(crate) fn bindings(title: Option<&str>) -> Self {
        Self(title.map(|title| format!("{}-bindings", named(title))))
    }

    /// Storage for the save data of a game called `title`: next to its
    /// bindings, never in the same text.
    pub(crate) fn saves(title: Option<&str>) -> Self {
        Self(title.map(|title| format!("{}-saves", named(title))))
    }

    /// Text kept by an earlier run, or nothing if it kept nothing, or the
    /// platform could not read it back.
    pub(crate) fn read(&self) -> Option<String> {
        sys::store_read(self.0.as_deref()?)
    }

    pub(crate) fn write(&self, text: &str) {
        let Some(title) = self.0.as_deref() else {
            return;
        };
        sys::store_write(title, text);
    }
}

/// Every broken variant of `kept` this sweep produces: cut short at each
/// position, one `char` from `GARBAGE` added at each position, and each
/// line repeated.
#[cfg(test)]
pub(crate) fn manglings(kept: &str) -> Vec<String> {
    let letters: Vec<char> = kept.chars().collect();
    let lines: Vec<&str> = kept.lines().collect();
    let mut out = Vec::with_capacity((letters.len() + 1) * (GARBAGE.len() + 1) + lines.len());

    for at in 0..=letters.len() {
        out.push(letters[..at].iter().collect());
        out.extend(GARBAGE.iter().map(|&dropped| {
            let mut with = letters.clone();
            with.insert(at, dropped);
            with.iter().collect()
        }));
    }
    out.extend((0..lines.len()).map(|at| {
        let mut twice = lines.clone();
        twice.insert(at, lines[at]);
        twice.join("\n")
    }));

    out
}

/// The title as a name both a file system and a browser take.
fn named(title: &str) -> String {
    let plain: String = title
        .chars()
        .map(|letter| match letter.is_ascii_alphanumeric() {
            true => letter.to_ascii_lowercase(),
            false => '-',
        })
        .collect();
    match plain.trim_matches('-') {
        "" => "game".to_owned(),
        trimmed => trimmed.to_owned(),
    }
}

/// The game's constructor, kept until the GPU exists, then handed to the
/// game thread and used once.
pub(crate) type Init<G> = Box<dyn FnOnce(&mut InitContext<'_, G>) -> Result<G, Error> + Send>;

pub(crate) fn run<G: Game>(
    config: Config,
    init: impl FnOnce(&mut InitContext<'_, G>) -> Result<G, Error> + Send + 'static,
) {
    sys::run_app(App::<G>::new(config, Box::new(init)));
}

/// The loop a run behind a window is driven by, with the engine's log
/// channel open and the loop waiting between frames. `None` where the
/// platform's own loop failed to open; that error is reported before this
/// returns.
fn event_loop() -> Option<EventLoop<()>> {
    sys::install_diagnostics();
    match EventLoop::new() {
        Ok(event_loop) => {
            event_loop.set_control_flow(ControlFlow::Wait);
            Some(event_loop)
        }
        Err(error) => {
            sys::report_fatal(&Error::msg(format!("no event loop: {error}")));
            None
        }
    }
}

/// Everything the startup task gets before a game can exist: the GPU, the
/// bytes of every configured source, and what the game draws through — the
/// styles it declared compiled and checked.
struct Booted {
    gpu: Gpu,
    files: Vec<(String, Vec<u8>)>,
    renderer: Renderer,
}

/// Result the startup task passes on, once it has anything to pass on.
type Handed = Rc<RefCell<Option<Result<Booted, Error>>>>;

/// Passes the startup result to the event loop that gets it.
#[derive(Clone, Default)]
struct BootHandoff(Handed);

impl BootHandoff {
    fn publish(&self, booted: Result<Booted, Error>) {
        *self.0.borrow_mut() = Some(booted);
    }

    fn collect(&self) -> Option<Result<Booted, Error>> {
        self.0.borrow_mut().take()
    }
}

/// Reads every configured source, in load order; the game thread decodes what
/// this returns, so no decode runs where the window's events do.
pub(crate) async fn read_sources(sources: &[String]) -> Result<Vec<(String, Vec<u8>)>, Error> {
    let mut files = Vec::with_capacity(sources.len());
    for source in sources {
        files.push((source.clone(), sys::read(source).await?));
    }

    Ok(files)
}

async fn boot<G: Game>(
    instance: wgpu::Instance,
    window: Arc<Window>,
    config: Config,
) -> Result<Booted, Error> {
    let gpu = Gpu::new(instance, window, sys::adapter_facts().await).await?;
    let files = read_sources(config.asset_sources()).await?;
    let renderer = Renderer::new(
        gpu.device(),
        gpu.queue(),
        gpu.target_format(),
        &config,
        crate::surface_style::Declarations::of::<G::SurfaceStyles>(),
        crate::post_effect::Declarations::of::<G::PostEffects>(),
    )
    .await?;

    Ok(Booted {
        gpu,
        files,
        renderer,
    })
}

enum Stage {
    Unstarted,
    Booting,
    Running(Box<Running>),
    Ended,
}

/// The run once the GPU exists: the display thread, which draws and plays
/// what it is handed, the game thread as this target holds it, and the end
/// the display thread hands and takes through.
struct Running {
    game: sys::GameThreadHandle,
    display: DisplayThread,
    end: DisplayEnd,
}

struct App<G: Game> {
    config: Config,
    handoff: BootHandoff,
    stage: Stage,
    init: Option<Init<G>>,
}

impl<G: Game> App<G> {
    fn new(config: Config, init: Init<G>) -> Self {
        Self {
            config,
            handoff: BootHandoff::default(),
            stage: Stage::Unstarted,
            init: Some(init),
        }
    }

    fn boot(&mut self, event_loop: &ActiveEventLoop) {
        let attributes = match sys::window_attributes(&self.config) {
            Ok(attributes) => attributes,
            Err(error) => return end_run(event_loop, &error),
        };
        let window = match event_loop.create_window(attributes) {
            Ok(window) => Arc::new(window),
            Err(error) => {
                return end_run(event_loop, &Error::msg(format!("no window: {error}")));
            }
        };

        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle(
            Box::new(event_loop.owned_display_handle()),
        ));

        self.stage = Stage::Booting;
        let handoff = self.handoff.clone();
        let config = self.config.clone();
        sys::spawn(async move {
            handoff.publish(boot::<G>(instance, Arc::clone(&window), config).await);
            wake_event_loop(&window);
        });
    }

    fn start_game_if_booted(&mut self, event_loop: &ActiveEventLoop) {
        let Some(booted) = self.handoff.collect() else {
            return;
        };
        let Some(init) = self.init.take() else {
            return;
        };

        let Booted {
            gpu,
            files,
            renderer,
        } = match booted {
            Ok(booted) => booted,
            Err(error) => return end_run(event_loop, &error),
        };
        let output = SoundOutput::new(Output::open());
        let bindings = Store::bindings(Some(self.config.title()));
        let saves = Store::saves(Some(self.config.title()));
        let starting = Starting {
            config: self.config.clone(),
            files,
            kept: Kept {
                bindings: bindings.read(),
                saves: saves.read(),
                window_size: gpu.physical_size(),
                mix_rate: output.rate(),
                workers: Workers::here(),
            },
            init,
        };
        let painter = Painter::windowed(gpu.device(), gpu.overlay_format(), gpu.window());
        let (end, game_end) = DisplayEnd::paired();
        let game = match sys::start_game::<G>(game_end, starting) {
            Ok(game) => game,
            Err(error) => return end_run(event_loop, &error),
        };

        self.stage = Stage::Running(Box::new(Running {
            game,
            display: DisplayThread::new(
                gpu,
                Devices::new(Pads::open(), double_click_interval(&self.config)),
                renderer,
                painter,
                output,
                bindings,
                saves,
            ),
            end,
        }));
    }
}

impl<G: Game> ApplicationHandler for App<G> {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if matches!(self.stage, Stage::Unstarted) {
            self.boot(event_loop);
            self.start_game_if_booted(event_loop);
        }
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window: WindowId,
        event: WindowEvent,
    ) {
        self.start_game_if_booted(event_loop);

        let Stage::Running(running) = &mut self.stage else {
            return;
        };
        let Running { game, display, end } = running.as_mut();
        display.see(&event);

        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => {
                display.gpu.resize(UVec2::new(size.width, size.height));
                display.gpu.request_frame();
            }
            WindowEvent::RedrawRequested => {
                if let Some(fault) = display.gpu.fault() {
                    log::error!("{fault}");
                    return end_run(event_loop, &Error::msg(fault.told(display.gpu.adapter())));
                }
                if let Some(error) = game.failed().or_else(|| display.take(end.queued())) {
                    return end_run(event_loop, &error);
                }

                let closing = end.frame().is_some_and(|frame| display.keep(frame));
                display.render();
                if closing {
                    sys::close(&display.gpu.window(), &self.config);
                    event_loop.exit();
                    return;
                }

                display.gpu.request_frame();
                end.hand(|| display.sample());
            }
            _ => {}
        }
    }

    /// Ends the game thread with the loop, each target as its own seam does.
    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
        if let Stage::Running(running) = core::mem::replace(&mut self.stage, Stage::Ended) {
            let Running { game, end, .. } = *running;
            game.ended(end);
        }
    }

    /// Takes what a device reports of its own movement, which is how a
    /// held pointer moves: a window reports no place for one.
    fn device_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _device: DeviceId,
        event: DeviceEvent,
    ) {
        let Stage::Running(running) = &mut self.stage else {
            return;
        };
        running.display.see_device(&event);
    }
}

fn wake_event_loop(window: &Window) {
    window.request_redraw();
}

/// Reports `error` to the player through the platform's own path, and ends
/// the run.
fn end_run(event_loop: &ActiveEventLoop, error: &Error) {
    sys::report_fatal(error);
    event_loop.exit();
}

#[cfg(not(target_arch = "wasm32"))]
mod native;
pub(crate) mod threads;
#[cfg(target_arch = "wasm32")]
mod web;

#[cfg(test)]
mod tests {
    use super::{Store, named};

    #[test]
    fn a_title_becomes_a_name_a_file_system_and_a_page_both_take() {
        assert_eq!(named("Mirage Breakout"), "mirage-breakout");
        assert_eq!(named("../../etc/passwd"), "etc-passwd");
        assert_eq!(named("  "), "game", "and there is always a name");
    }

    #[test]
    fn the_two_kinds_of_kept_text_never_name_one_place() {
        assert_eq!(
            Store::bindings(Some("Mirage Breakout")).0.as_deref(),
            Some("mirage-breakout-bindings")
        );
        assert_eq!(
            Store::saves(Some("Mirage Breakout")).0.as_deref(),
            Some("mirage-breakout-saves")
        );
        assert_ne!(
            Store::bindings(Some("Escape Saves")).0,
            Store::saves(Some("Escape")).0,
            "whatever a title ends in"
        );
        assert_eq!(Store::saves(None).0, None, "and a titleless run keeps none");
    }
}