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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! The engine's UI: one full-screen transparent egui layer per frame, which
//! the game thread builds and the display thread's painter draws over the
//! scene.

#[cfg(feature = "ui")]
pub(crate) use egui_layer::{Building, Changes, Layer, Painted, Painter};
#[cfg(not(feature = "ui"))]
pub(crate) use no_layer::{Building, Changes, Layer, Painted, Painter};

use crate::input::Cursor;

/// Claims the UI made last frame; a game checks this before it uses the
/// same input.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Claims {
    pub(crate) pointer: bool,
    pub(crate) keyboard: bool,
}

/// What one frame's layer built: the shapes the painter draws until another
/// frame reaches it, the changes it takes once, and the cursor the frame
/// drew the pointer as.
pub(crate) struct Layered {
    pub(crate) painted: Painted,
    pub(crate) changes: Changes,
    pub(crate) cursor: Cursor,
}

#[cfg(feature = "ui")]
mod egui_layer {
    use core::num::NonZeroUsize;
    #[cfg(feature = "offscreen")]
    use core::time::Duration;
    use std::sync::Arc;

    use winit::event::WindowEvent;
    use winit::window::Window;

    use super::{Claims, Layered};
    use crate::input::Cursor;
    use crate::math::UVec2;
    use crate::platform::threads::UiInput;

    /// Length an egui animation takes; much less than egui's own default.
    const ANIMATION: f32 = 0.05;

    /// Points the layer keeps clear of the window's edges, egui's own.
    const MARGIN: f32 = 8.0;

    /// The layer as one frame builds it: where game code builds it, what
    /// the frame before claimed, and what the frame draws the pointer as.
    pub(crate) struct Building<'a> {
        pub(crate) ui: &'a mut egui::Ui,
        pub(crate) claims: Claims,
        pub(crate) pixels_per_point: f32,
        pub(crate) cursor: &'a mut Cursor,
    }

    /// The game thread's UI: the egui context, set to one pass, and what the
    /// last frame's layer claimed.
    pub(crate) struct Layer {
        context: egui::Context,
        claims: Claims,
    }

    impl Layer {
        pub(crate) fn new() -> Self {
            let context = egui::Context::default();
            context.options_mut(|options| {
                options.max_passes = NonZeroUsize::MIN;
                // The two threads lay the UI out at the window's own scale,
                // which a zoom of egui's own would move on one of them alone.
                options.zoom_with_keyboard = false;
            });
            context.all_styles_mut(|style| style.animation_time = ANIMATION);
            Self {
                context,
                claims: Claims::default(),
            }
        }

        /// Claims the last frame's UI made.
        pub(crate) fn claims(&self) -> Claims {
            self.claims
        }

        /// Draws the text of every frame from the next one on in `fonts`.
        pub(crate) fn set_fonts(&self, fonts: egui::FontDefinitions) {
            self.context.set_fonts(fonts);
        }

        /// Opens this frame's layer over `input`'s screen, less `MARGIN` on
        /// every side, and runs `build` within it.
        ///
        /// The cursor it returns is what `build` set, or the UI's own where
        /// it sets one over a cursor that holds nothing; the UI's output
        /// names that one too, so the painter sets it.
        pub(crate) fn frame(
            &mut self,
            input: UiInput,
            mut build: impl FnMut(Building<'_>),
        ) -> Layered {
            let claims = self.claims;
            let mut cursor = Cursor::default();
            let mut output = self.context.run_ui(input.raw(), |ui| {
                let pixels_per_point = ui.ctx().pixels_per_point();
                layer(ui, |ui| {
                    build(Building {
                        ui,
                        claims,
                        pixels_per_point,
                        cursor: &mut cursor,
                    })
                })
            });

            self.claims = Claims {
                pointer: self.context.egui_wants_pointer_input(),
                keyboard: self.context.egui_wants_keyboard_input(),
            };
            let icon = &mut output.platform_output.cursor_icon;
            let shown = match Cursor::of_ui(*icon) {
                Some(over_ui) if !cursor.holds_pointer() => over_ui,
                _ => {
                    *icon = cursor.ui_icon();
                    cursor
                }
            };
            Layered {
                painted: Painted {
                    primitives: self
                        .context
                        .tessellate(output.shapes, output.pixels_per_point),
                    pixels_per_point: output.pixels_per_point,
                },
                changes: Changes {
                    textures: output.textures_delta,
                    platform: output.platform_output,
                },
                cursor: shown,
            }
        }
    }

    /// What one frame's layer built, as the painter draws it: the shapes as
    /// triangles, and the scale they were laid out at.
    pub(crate) struct Painted {
        primitives: Vec<egui::ClippedPrimitive>,
        pixels_per_point: f32,
    }

    /// What the painter takes of one frame's layer once: the textures the
    /// layer changed, and what its UI set for the platform.
    pub(crate) struct Changes {
        textures: egui::TexturesDelta,
        platform: egui::PlatformOutput,
    }

    /// The display thread's UI: the pass that draws what a frame built, and
    /// the window or session it takes the frame's input from.
    pub(crate) struct Painter {
        renderer: egui_wgpu::Renderer,
        source: Source,
        primitives: Vec<egui::ClippedPrimitive>,
        pixels_per_point: f32,
        /// Textures the last frame may still draw from, freed once its work
        /// is submitted.
        stale: Vec<egui::TextureId>,
    }

    impl Painter {
        /// The painter `window`'s events drive, which names no value of the
        /// game thread's: the context it reads those events against is its
        /// own.
        ///
        /// `format` is the target read as encoded values, never its sRGB
        /// view: egui's colors are authored in that space and blend in it.
        pub(crate) fn windowed(
            device: &wgpu::Device,
            format: wgpu::TextureFormat,
            window: Arc<Window>,
        ) -> Self {
            let source = Source::window(device, window);
            Self::assembled(device, format, source)
        }

        /// The painter a windowless session `size` physical pixels across
        /// feeds events to; `format` is as on [`Painter::windowed`].
        #[cfg(feature = "offscreen")]
        pub(crate) fn offscreen(
            device: &wgpu::Device,
            format: wgpu::TextureFormat,
            size: UVec2,
        ) -> Self {
            let fed = Source::Fed {
                events: Vec::new(),
                screen: size,
                pixels_per_point: 1.0,
                elapsed: Duration::ZERO,
            };
            Self::assembled(device, format, fed)
        }

        /// A painter reading `source`, drawing to `format`.
        fn assembled(device: &wgpu::Device, format: wgpu::TextureFormat, source: Source) -> Self {
            Self {
                renderer: egui_wgpu::Renderer::new(
                    device,
                    format,
                    egui_wgpu::RendererOptions::default(),
                ),
                source,
                primitives: Vec::new(),
                pixels_per_point: 1.0,
                stale: Vec::new(),
            }
        }

        /// Offers `event` to the UI, which never keeps it from the game's own
        /// input sample.
        pub(crate) fn fold(&mut self, event: &WindowEvent) {
            self.source.fold(event);
        }

        /// Adds `event` to the input the next [`Painter::take_input`] returns,
        /// for a session that drives the UI with no window of its own.
        #[cfg(feature = "offscreen")]
        pub(crate) fn feed(&mut self, event: egui::Event) {
            self.source.feed(event);
        }

        /// Physical pixels the layer lays out per point, which a session's
        /// own events are measured in.
        #[cfg(feature = "offscreen")]
        pub(crate) fn pixels_per_point(&self) -> f32 {
            self.pixels_per_point
        }

        /// Sets the clock the UI paces its own animations by, for a session
        /// whose clock is its caller's.
        #[cfg(feature = "offscreen")]
        pub(crate) fn set_clock(&mut self, at: Duration) {
            self.source.set_clock(at);
        }

        /// The input the next frame's layer is built from: a window's
        /// events since the last frame, or what a session fed.
        ///
        /// A zoom of egui's own is left out: the layer is laid out at the
        /// window's own scale, which the painter reads for itself.
        pub(crate) fn take_input(&mut self) -> UiInput {
            #[cfg(feature = "offscreen")]
            self.source.lay_out_at(self.pixels_per_point);
            let mut input = self.source.take();
            input
                .events
                .retain(|event| !matches!(event, egui::Event::Zoom(_)));

            UiInput::of(input)
        }

        /// Takes what a frame's layer changed: uploads its textures, frees
        /// what the frame before it drew from, and sets on the window what
        /// its UI set for the platform, the cursor among it.
        pub(crate) fn take(
            &mut self,
            device: &wgpu::Device,
            queue: &wgpu::Queue,
            changes: Changes,
        ) {
            for id in self.stale.drain(..) {
                self.renderer.free_texture(&id);
            }
            for (id, image) in changes.textures.set {
                self.renderer.update_texture(device, queue, id, &image);
            }
            self.stale = changes.textures.free;
            self.source.apply(changes.platform);
        }

        /// Keeps what a frame's layer built, which every [`Painter::encode`]
        /// until the next frame draws.
        pub(crate) fn keep(&mut self, painted: Painted, _cursor: Cursor) {
            self.primitives = painted.primitives;
            self.pixels_per_point = painted.pixels_per_point;
        }

        /// Records the layer over `target`; the work it returns must be
        /// submitted before the encoder that holds it.
        pub(crate) fn encode(
            &mut self,
            device: &wgpu::Device,
            queue: &wgpu::Queue,
            encoder: &mut wgpu::CommandEncoder,
            into: &wgpu::TextureView,
            size: UVec2,
        ) -> Vec<wgpu::CommandBuffer> {
            if self.primitives.is_empty() {
                return Vec::new();
            }

            let screen = egui_wgpu::ScreenDescriptor {
                size_in_pixels: [size.x, size.y],
                pixels_per_point: self.pixels_per_point,
            };
            let prerequisites =
                self.renderer
                    .update_buffers(device, queue, encoder, &self.primitives, &screen);

            let mut pass = encoder
                .begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("mirage-engine ui"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: into,
                        depth_slice: None,
                        resolve_target: None,
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Load,
                            store: wgpu::StoreOp::Store,
                        },
                    })],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                })
                .forget_lifetime();
            self.renderer.render(&mut pass, &self.primitives, &screen);

            prerequisites
        }
    }

    /// Where a painter takes a frame's input from.
    enum Source {
        /// The events a window has taken since the last frame.
        Window(Box<egui_winit::State>, Arc<Window>),
        /// What a windowless session has fed it since the last frame: the
        /// events, the screen it lays them out over in physical pixels, the
        /// points that screen is laid out in, and the session's own clock.
        ///
        /// The scale is the one the frame before measured, so a zoom a game
        /// sets lands a frame later here than it does behind a window,
        /// which reads its own before the frame runs.
        #[cfg(feature = "offscreen")]
        Fed {
            events: Vec<egui::Event>,
            screen: UVec2,
            pixels_per_point: f32,
            elapsed: Duration,
        },
    }

    impl Source {
        /// The source that reads `window`'s events, against a context of
        /// its own: the game thread's is the game thread's alone, and reading
        /// it here would stop the display thread for as long as a frame runs
        /// in it.
        fn window(device: &wgpu::Device, window: Arc<Window>) -> Self {
            let state = egui_winit::State::new(
                egui::Context::default(),
                egui::ViewportId::ROOT,
                &*window,
                Some(window.scale_factor() as f32),
                None,
                Some(device.limits().max_texture_dimension_2d as usize),
            );
            Self::Window(Box::new(state), window)
        }

        /// Takes `event` in, for the window it came from; only the platform
        /// layer, which builds a window source, has one.
        fn fold(&mut self, event: &WindowEvent) {
            match self {
                Self::Window(state, window) => drop(state.on_window_event(window, event)),
                #[cfg(feature = "offscreen")]
                Self::Fed { .. } => {}
            }
        }

        /// Adds `event` to what the next [`Source::take`] returns; only a
        /// session feeds one, and a session builds a fed source.
        #[cfg(feature = "offscreen")]
        fn feed(&mut self, event: egui::Event) {
            if let Self::Fed { events, .. } = self {
                events.push(event);
            }
        }

        /// Lays the fed screen out in `scale` physical pixels per point,
        /// which the frame before it measured.
        #[cfg(feature = "offscreen")]
        fn lay_out_at(&mut self, scale: f32) {
            if let Self::Fed {
                pixels_per_point, ..
            } = self
            {
                *pixels_per_point = scale;
            }
        }

        /// Sets the clock the UI paces its own animations by, which is the
        /// session's.
        #[cfg(feature = "offscreen")]
        fn set_clock(&mut self, at: Duration) {
            if let Self::Fed { elapsed, .. } = self {
                *elapsed = at;
            }
        }

        /// The frame's raw input: a window's events since the last frame,
        /// or what a session fed it, over the screen the source reads in
        /// the points it is laid out in.
        fn take(&mut self) -> egui::RawInput {
            match self {
                Self::Window(state, window) => state.take_egui_input(window),
                #[cfg(feature = "offscreen")]
                Self::Fed {
                    events,
                    screen,
                    pixels_per_point,
                    elapsed,
                } => egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(
                            screen.x as f32 / *pixels_per_point,
                            screen.y as f32 / *pixels_per_point,
                        ),
                    )),
                    time: Some(elapsed.as_secs_f64()),
                    events: core::mem::take(events),
                    ..Default::default()
                },
            }
        }

        /// Applies what the frame's UI set for the platform; only a window
        /// takes it.
        fn apply(&mut self, output: egui::PlatformOutput) {
            match self {
                Self::Window(state, window) => state.handle_platform_output(window, output),
                #[cfg(feature = "offscreen")]
                Self::Fed { .. } => {}
            }
        }
    }

    /// Runs `build` in the area a layer covers: the window less [`MARGIN`]
    /// on every side, so nothing a game draws lands against an edge.
    fn layer(ui: &mut egui::Ui, build: impl FnOnce(&mut egui::Ui)) {
        let inset = egui::UiBuilder::new().max_rect(ui.max_rect().shrink(MARGIN));
        ui.scope_builder(inset, build);
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        const SCREEN: egui::Vec2 = egui::vec2(800.0, 600.0);

        /// Claims `build` makes with the pointer at `pointer`; egui checks
        /// the previous pass, so this runs twice.
        fn claims_at(pointer: egui::Pos2, mut build: impl FnMut(&mut egui::Ui)) -> Claims {
            let context = Layer::new().context;
            for _ in 0..2 {
                drop(context.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, SCREEN)),
                        events: vec![egui::Event::PointerMoved(pointer)],
                        ..Default::default()
                    },
                    &mut build,
                ));
            }
            Claims {
                pointer: context.egui_wants_pointer_input(),
                keyboard: context.egui_wants_keyboard_input(),
            }
        }

        #[test]
        fn a_window_narrower_than_the_margin_still_takes_a_layer() {
            for side in [1.0, 8.0, 16.0, 17.0] {
                drop(Layer::new().context.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::Pos2::ZERO,
                            egui::Vec2::splat(side),
                        )),
                        ..Default::default()
                    },
                    |ui| {
                        layer(ui, |ui| {
                            ui.label("wasd / arrows / stick to walk");
                        })
                    },
                ));
            }
        }

        #[test]
        fn a_layer_covers_the_screen_but_its_margin() {
            let mut covered = egui::Rect::NOTHING;
            drop(Layer::new().context.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, SCREEN)),
                    ..Default::default()
                },
                |ui| layer(ui, |ui| covered = ui.max_rect()),
            ));
            assert_eq!(
                covered,
                egui::Rect::from_min_size(egui::Pos2::ZERO, SCREEN).shrink(MARGIN)
            );
        }

        #[test]
        fn a_layer_nothing_was_drawn_into_claims_nothing() {
            let claims = claims_at(egui::pos2(400.0, 300.0), |_| {});
            assert!(!claims.pointer);
            assert!(!claims.keyboard);
        }

        #[test]
        fn a_layer_claims_the_pointer_only_over_what_it_drew() {
            let hud = |ui: &mut egui::Ui| {
                ui.label("score: 3");
            };
            assert!(claims_at(egui::pos2(8.0, 8.0), hud).pointer, "over the hud");
            assert!(
                !claims_at(egui::pos2(400.0, 300.0), hud).pointer,
                "clear of it"
            );
        }

        #[test]
        fn a_window_claims_the_pointer_only_where_it_stands() {
            let menu = |ui: &mut egui::Ui| {
                egui::Window::new("paused")
                    .fixed_pos(egui::pos2(300.0, 250.0))
                    .show(ui.ctx(), |ui| {
                        let _ = ui.button("resume");
                    });
            };
            assert!(claims_at(egui::pos2(340.0, 285.0), menu).pointer, "on it");
            assert!(
                !claims_at(egui::pos2(700.0, 560.0), menu).pointer,
                "clear of it"
            );
        }
    }
}

#[cfg(not(feature = "ui"))]
mod no_layer {
    use std::sync::Arc;

    use winit::event::WindowEvent;
    use winit::window::Window;

    use super::{Claims, Layered};
    use crate::input::Cursor;
    use crate::math::UVec2;
    use crate::platform::threads::UiInput;

    /// The layer as one frame builds it without the `ui` feature: claims
    /// that are always empty, and what the frame draws the pointer as.
    pub(crate) struct Building<'a> {
        pub(crate) claims: Claims,
        pub(crate) cursor: &'a mut Cursor,
    }

    /// The game thread's UI the `ui` feature would build: without it nothing
    /// is drawn over the scene and nothing claims the frame's input.
    pub(crate) struct Layer;

    /// What one frame's layer built without the `ui` feature: nothing.
    pub(crate) struct Painted;

    /// What the painter takes of it once without the `ui` feature: nothing.
    pub(crate) struct Changes;

    impl Layer {
        pub(crate) fn new() -> Self {
            Self
        }

        pub(crate) fn claims(&self) -> Claims {
            Claims::default()
        }

        /// Runs `build`, and returns the cursor it set; `input` holds
        /// nothing without the `ui` feature.
        pub(crate) fn frame(
            &mut self,
            _input: UiInput,
            mut build: impl FnMut(Building<'_>),
        ) -> Layered {
            let mut cursor = Cursor::default();
            build(Building {
                claims: Claims::default(),
                cursor: &mut cursor,
            });
            Layered {
                painted: Painted,
                changes: Changes,
                cursor,
            }
        }
    }

    /// The display thread's UI without the `ui` feature: the window takes
    /// each frame's cursor from here, and nothing is drawn.
    pub(crate) struct Painter {
        window: Option<Arc<Window>>,
        shown: Cursor,
    }

    impl Painter {
        pub(crate) fn windowed(
            _device: &wgpu::Device,
            _format: wgpu::TextureFormat,
            window: Arc<Window>,
        ) -> Self {
            Self {
                window: Some(window),
                shown: Cursor::default(),
            }
        }

        #[cfg(feature = "offscreen")]
        pub(crate) fn offscreen(
            _device: &wgpu::Device,
            _format: wgpu::TextureFormat,
            _size: UVec2,
        ) -> Self {
            Self {
                window: None,
                shown: Cursor::default(),
            }
        }

        pub(crate) fn fold(&mut self, _event: &WindowEvent) {}

        /// Nothing to read: no frame draws a UI without the `ui` feature.
        pub(crate) fn take_input(&mut self) -> UiInput {
            UiInput::default()
        }

        /// Nothing to take: a frame's layer changes no texture without the
        /// `ui` feature, and sets nothing for the platform.
        pub(crate) fn take(
            &mut self,
            _device: &wgpu::Device,
            _queue: &wgpu::Queue,
            _changes: Changes,
        ) {
        }

        /// Sets `cursor` on the window where it changed; a frame built
        /// nothing else to draw.
        pub(crate) fn keep(&mut self, _painted: Painted, cursor: Cursor) {
            if core::mem::replace(&mut self.shown, cursor) != cursor
                && let Some(window) = &self.window
            {
                match cursor.window_icon() {
                    Some(icon) => {
                        window.set_cursor_visible(true);
                        window.set_cursor(icon);
                    }
                    None => window.set_cursor_visible(false),
                }
            }
        }

        pub(crate) fn encode(
            &mut self,
            _device: &wgpu::Device,
            _queue: &wgpu::Queue,
            _encoder: &mut wgpu::CommandEncoder,
            _into: &wgpu::TextureView,
            _size: UVec2,
        ) -> Vec<wgpu::CommandBuffer> {
            Vec::new()
        }
    }
}