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
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
//! The engine's UI layer: one full-screen transparent egui overlay per
//! frame, drawn over the scene.

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

/// 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,
}

#[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;
    use crate::input::Cursor;
    use crate::math::UVec2;

    /// 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;

    /// One frame's UI: the layer game code builds it in, what the frame
    /// before it claimed, and what the frame draws the pointer as.
    pub(crate) struct Layer<'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 engine's egui context, set up for the platform, and the pass that
    /// draws what a frame built.
    pub(crate) struct Overlay {
        context: egui::Context,
        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>,
        claims: Claims,
    }

    impl Overlay {
        /// The overlay `window`'s events drive.
        ///
        /// `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 context = context();
            let source = Source::window(&context, device, window);
            Self::assembled(device, format, context, source)
        }

        /// The overlay a windowless session `size` physical pixels across
        /// feeds events to; `format` is as on [`Overlay::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, context(), fed)
        }

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

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

        /// Adds `event` to the input the next [`Overlay::frame`] reads, 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);
        }

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

        /// Draws the text of every pass 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 the source's screen, less `MARGIN` on
        /// every side, and runs `build` within it. Keeps what it drew for the
        /// next [`Overlay::encode`].
        ///
        /// Returns the cursor the pointer is drawn as: what `build` set,
        /// or the UI's own where it sets one over a cursor that holds
        /// nothing. The platform takes that one.
        pub(crate) fn frame(
            &mut self,
            device: &wgpu::Device,
            queue: &wgpu::Queue,
            mut build: impl FnMut(Layer<'_>),
        ) -> Cursor {
            for id in self.stale.drain(..) {
                self.renderer.free_texture(&id);
            }

            let claims = self.claims;
            #[cfg(feature = "offscreen")]
            self.source.lay_out_at(self.pixels_per_point);
            let input = self.source.take();
            let mut cursor = Cursor::default();
            let mut output = self.context.run_ui(input, |ui| {
                let pixels_per_point = ui.ctx().pixels_per_point();
                layer(ui, |ui| {
                    build(Layer {
                        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(),
            };
            self.primitives = self
                .context
                .tessellate(core::mem::take(&mut output.shapes), output.pixels_per_point);
            self.pixels_per_point = output.pixels_per_point;
            for (id, image) in output.textures_delta.set.drain(..) {
                self.renderer.update_texture(device, queue, id, &image);
            }
            self.stale.append(&mut output.textures_delta.free);

            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
                }
            };
            self.source
                .apply(core::mem::take(&mut output.platform_output));

            shown
        }

        /// 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 an overlay 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.
        fn window(context: &egui::Context, device: &wgpu::Device, window: Arc<Window>) -> Self {
            let state = egui_winit::State::new(
                context.clone(),
                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);
    }

    /// An egui context set to one layout pass, so a game's frame does not
    /// run again.
    fn context() -> egui::Context {
        let context = egui::Context::default();
        context.options_mut(|options| options.max_passes = NonZeroUsize::MIN);
        context.all_styles_mut(|style| style.animation_time = ANIMATION);
        context
    }

    #[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 = 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(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(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;
    use crate::input::Cursor;
    use crate::math::UVec2;

    /// One frame's UI without the `ui` feature: claims that are always
    /// empty, and what the frame draws the pointer as.
    pub(crate) struct Layer<'a> {
        pub(crate) claims: Claims,
        pub(crate) cursor: &'a mut Cursor,
    }

    /// The UI layer the `ui` feature would build: without it nothing is drawn
    /// over the scene and nothing claims the frame's input, and the window
    /// takes each frame's cursor from here.
    pub(crate) struct Overlay {
        window: Option<Arc<Window>>,
        shown: Cursor,
    }

    impl Overlay {
        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) {}

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

        /// Runs `build`, and returns the cursor it set; the window takes it
        /// where it changed.
        pub(crate) fn frame(
            &mut self,
            _device: &wgpu::Device,
            _queue: &wgpu::Queue,
            mut build: impl FnMut(Layer<'_>),
        ) -> Cursor {
            let mut cursor = Cursor::default();
            build(Layer {
                claims: Claims::default(),
                cursor: &mut 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),
                }
            }

            cursor
        }

        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()
        }
    }
}