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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
//! The engine's two threads, the end each of them holds of what crosses
//! between them, and the values that cross: the game thread records what a
//! frame wants, the display thread draws and plays it, and nothing on the
//! display thread names a game type.

use core::num::NonZeroU32;
use core::time::Duration;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, TryLockError};

use rayon::ThreadPoolBuilder;
use winit::event::{DeviceEvent, ElementState, WindowEvent};

use crate::assets::Assets;
use crate::context::{Engine, Recording, Run, Simulating};
use crate::gpu::Gpu;
use crate::input::{Controls, Cursor, Devices, Queries};
use crate::math::UVec2;
use crate::platform::{Init, Instant, PointerHold, Store, hardware_threads, spawn_worker};
use crate::renderer::Renderer;
use crate::renderer::draw_list::DrawList;
use crate::renderer::mesh_cache::{HandedMeshes, MeshCatalog};
use crate::renderer::skybox::{SkyCatalog, SkyId};
use crate::save::Saved;
use crate::skybox::Resident;
use crate::sound::{MixRate, Played, SoundOutput, Sounding};
use crate::time::{Clock, FrameTime};
use crate::ui::{Building, Changes, Layer, Layered, Painted, Painter};
use crate::{Camera, Config, Error, Game, InitContext};

/// What the display thread states with every hand: the drawing area, and
/// whether the platform allows sound to start.
///
/// Every tick and every frame reads it.
pub(crate) struct Stated {
    pub(crate) window_size: UVec2,
    pub(crate) sound_unlocked: bool,
}

impl Stated {
    /// What the game thread reads until the first hand: the drawing area the
    /// run starts at, and no sound.
    fn starting(window_size: UVec2) -> Self {
        Self {
            window_size,
            sound_unlocked: false,
        }
    }
}

/// What the display thread hands the game thread before a frame: what it
/// states of itself and the controls as the devices closed them, both read
/// by every tick and the frame, and the UI's input, closed at the frame and
/// read there alone.
pub(crate) struct Sample {
    pub(crate) stated: Stated,
    pub(crate) controls: Controls,
    pub(crate) ui_input: UiInput,
}

/// The UI's input for one frame, as the painter closed it.
///
/// It holds nothing without the `ui` feature, where no frame draws a UI.
#[derive(Default)]
pub(crate) struct UiInput {
    #[cfg(feature = "ui")]
    raw: egui::RawInput,
}

impl UiInput {
    /// The input a painter closed.
    #[cfg(feature = "ui")]
    pub(crate) fn of(raw: egui::RawInput) -> Self {
        Self { raw }
    }

    /// The same, as the layer takes it.
    #[cfg(feature = "ui")]
    pub(crate) fn raw(self) -> egui::RawInput {
        self.raw
    }
}

/// One frame as the game thread hands it over, which the display thread draws
/// until another reaches it: every draw keyed by mesh id, the UI drawn over
/// them, its cursor, and whether it closes the run.
pub(crate) struct HandedFrame {
    pub(crate) draws: DrawList,
    pub(crate) ui: Painted,
    pub(crate) cursor: Cursor,
    pub(crate) closing: bool,
}

/// What a frame commands beside what it draws, which the display thread takes
/// once each: the meshes and skies it built and the mesh ids it dropped, the
/// textures its UI changed, the sounds, and the text a flush of the bindings
/// or the saves changed.
pub(crate) struct Commands {
    pub(crate) meshes: HandedMeshes,
    pub(crate) skies: Vec<(SkyId, Resident)>,
    pub(crate) ui: Changes,
    pub(crate) sound: Played,
    pub(crate) bindings: Option<String>,
    pub(crate) saves: Option<String>,
}

/// One value in the queue the display thread empties whole: what a frame
/// commands, or the error a game that never started failed with.
pub(crate) enum Queued {
    /// Boxed: a frame's commands are far larger than an error, and the queue
    /// holds them by value.
    Frame(Box<Commands>),
    Failed(Error),
}

/// What a pool that already stands means for the start building one.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Standing {
    /// It is refused, naming the game that built it: a run behind a window
    /// holds its process, since the event loop is built once, so the engine
    /// has built no pool before this one.
    Refused,
    /// It is taken, as the one an earlier start of this process built: an
    /// offscreen session is one start of many, as the engine's own tests are.
    #[cfg(any(feature = "offscreen", test))]
    Taken,
}

/// How many workers the engine runs a game's parallel iterators on, and what a
/// pool that already stands means for the start that builds them.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Workers {
    count: usize,
    standing: Standing,
}

impl Standing {
    /// What the build reports where a pool already stands.
    fn reported(self) -> Result<(), Error> {
        match self {
            Self::Refused => Err(Error::msg(
                "a pool for parallel work stood before the run started: the engine builds the pool, so a game builds none",
            )),
            #[cfg(any(feature = "offscreen", test))]
            Self::Taken => {
                log::debug!("mirage-engine runs parallel work on the pool an earlier start built");
                Ok(())
            }
        }
    }
}

impl Workers {
    /// The most workers a run builds, whatever the machine states.
    const MOST: usize = 16;
    /// The threads the engine runs itself, beside the workers: the display
    /// thread and the game thread.
    const OWN_THREADS: usize = 2;

    /// The workers this machine runs beside the engine's own two threads: its
    /// hardware threads less those two, at least one and at most
    /// [`Workers::MOST`].
    ///
    /// Read where the run starts, which is the display thread: the browser
    /// states the number on the page's own thread alone. The run holds its
    /// process, so a pool that already stands is one the game built and
    /// [`Workers::build_pool`] stops naming it.
    pub(crate) fn here() -> Self {
        Self {
            count: Self::beside_the_run(hardware_threads()),
            standing: Standing::Refused,
        }
    }

    /// The same workers, for a start that is one of many in its process: a
    /// pool that already stands is the one an earlier start built, and this
    /// start runs on it.
    #[cfg(any(feature = "offscreen", test))]
    pub(crate) fn here_again() -> Self {
        Self {
            count: Self::beside_the_run(hardware_threads()),
            standing: Standing::Taken,
        }
    }

    /// Builds the pool `rayon` runs every parallel iterator on over these
    /// workers, and returns once every one of them has started, so the first
    /// tick runs over the whole pool.
    ///
    /// Fails where a worker did not start, where the thread it is called on is
    /// a worker of a pool, and where a pool stands that the engine did not
    /// build.
    pub(crate) fn build_pool(self) -> Result<(), Error> {
        // A thread that is already a worker of a pool resolves every parallel
        // iterator against that pool, never against the one built here.
        if rayon::current_thread_index().is_some() {
            return Err(Error::msg(
                "mirage-engine starts no game thread on a worker of a pool: parallel work there reaches that pool and never the engine's",
            ));
        }
        let built = ThreadPoolBuilder::new()
            .num_threads(self.count())
            .spawn_handler(spawn_worker)
            .build_global();

        match built {
            Ok(()) => {
                log::info!(
                    "mirage-engine runs parallel work on {} workers",
                    self.count()
                );
                Ok(())
            }
            // `rayon` keeps the kind of its error private: past the check
            // above, an error with no source of its own states that the pool
            // this process built stands, and a worker that did not start
            // states the one it failed with.
            Err(standing) if std::error::Error::source(&standing).is_none() => {
                self.standing.reported()
            }
            Err(error) => Err(Error::msg(format!(
                "mirage-engine started no worker for parallel work: {error}"
            ))),
        }
    }

    /// How many workers these are.
    pub(crate) fn count(self) -> usize {
        self.count
    }

    /// How many workers a machine stating `hardware_threads` runs.
    fn beside_the_run(hardware_threads: usize) -> usize {
        hardware_threads
            .saturating_sub(Self::OWN_THREADS)
            .clamp(1, Self::MOST)
    }
}

/// What the display thread hands the game thread once, before the game exists:
/// what the store kept of the bindings and the saves, the drawing area, the
/// rate the output mixes at, and the workers a game's parallel iterators run
/// on.
pub(crate) struct Kept {
    pub(crate) bindings: Option<String>,
    pub(crate) saves: Option<String>,
    pub(crate) window_size: UVec2,
    /// None where the output takes clips at their own rate.
    pub(crate) mix_rate: Option<MixRate>,
    pub(crate) workers: Workers,
}

/// Everything the game thread is built from, which crosses to it once: the
/// configuration, the bytes of every asset source the game named, what the
/// display thread kept, and the closure that builds the game.
pub(crate) struct Starting<G: Game> {
    pub(crate) config: Config,
    pub(crate) files: Vec<(String, Vec<u8>)>,
    pub(crate) kept: Kept,
    pub(crate) init: Init<G>,
}

/// The state every hand is kept in until the other thread takes it.
struct Crossing {
    pending: Mutex<Pending>,
    /// What the game thread waits on between samples, which a hand and the
    /// end of the run both end.
    handed: Condvar,
    back: Mutex<Back>,
}

/// The sample slot: the one the game thread has not taken yet, and whether the
/// display thread is still running.
struct Pending {
    sample: Option<Sample>,
    running: bool,
}

/// What the game thread has handed back: the newest frame, and everything the
/// display thread takes once, in the order the frames made it.
#[derive(Default)]
struct Back {
    frame: Option<HandedFrame>,
    queued: Vec<Queued>,
}

/// The display thread's end of what crosses: it hands a sample over once the
/// game thread has taken the one before, takes the newest frame and empties
/// the queue, and waits for nothing.
///
/// Every read here takes what is free and returns. The browser's display
/// thread is the page's own thread, where a wait on memory ends the run
/// with an error the game cannot catch, so this end holds no call that
/// waits.
pub(crate) struct DisplayEnd(Arc<Crossing>);

impl DisplayEnd {
    /// The two ends of one run.
    pub(crate) fn paired() -> (Self, GameEnd) {
        let crossing = Arc::new(Crossing {
            pending: Mutex::new(Pending {
                sample: None,
                running: true,
            }),
            handed: Condvar::new(),
            back: Mutex::default(),
        });

        (Self(Arc::clone(&crossing)), GameEnd(crossing))
    }

    /// Closes a sample with `close` and hands it over, where the game thread
    /// has taken the one before it.
    ///
    /// Where it has not, and where the game thread holds the slot right now,
    /// nothing is closed, so every event since folds into the sample it
    /// takes next and no edge is lost.
    pub(crate) fn hand(&self, close: impl FnOnce() -> Sample) {
        let Some(mut pending) = tried(&self.0.pending) else {
            return;
        };
        if pending.sample.is_some() {
            return;
        }
        pending.sample = Some(close());
        self.0.handed.notify_one();
    }

    /// The newest frame the game thread has handed, or nothing where it has
    /// handed none since the last call, or where it holds the slot now.
    pub(crate) fn frame(&self) -> Option<HandedFrame> {
        tried(&self.0.back)?.frame.take()
    }

    /// Everything the queue has held since the last call, in order; nothing
    /// where the game thread holds the queue now, which the next call takes.
    pub(crate) fn queued(&self) -> Vec<Queued> {
        tried(&self.0.back)
            .map(|mut back| core::mem::take(&mut back.queued))
            .unwrap_or_default()
    }
}

impl Drop for DisplayEnd {
    /// Ends the run for the game thread, which waits for no sample after it.
    fn drop(&mut self) {
        // The game thread holds the slot for a take and never across a frame,
        // so this turns a few times at most.
        let mut pending = loop {
            if let Some(pending) = tried(&self.0.pending) {
                break pending;
            }
            core::hint::spin_loop();
        };
        pending.running = false;
        self.0.handed.notify_one();
    }
}

/// `lock`'s state where nothing holds it now, and nothing where something
/// does.
fn tried<T>(lock: &Mutex<T>) -> Option<MutexGuard<'_, T>> {
    match lock.try_lock() {
        Ok(state) => Some(state),
        Err(TryLockError::Poisoned(poisoned)) => Some(poisoned.into_inner()),
        Err(TryLockError::WouldBlock) => None,
    }
}

/// The game thread's end: it reads the sample every frame runs from, and hands
/// each frame back beside everything that frame commands.
pub(crate) struct GameEnd(Arc<Crossing>);

impl GameEnd {
    /// The sample the next frame runs from, waiting for the display thread to
    /// hand one, or nothing where the run has ended.
    ///
    /// The game thread waits here, which is the one wait the engine makes
    /// for a value.
    pub(crate) fn sample(&self) -> Option<Sample> {
        let mut pending = self.pending();
        while pending.running && pending.sample.is_none() {
            pending = self
                .0
                .handed
                .wait(pending)
                .unwrap_or_else(PoisonError::into_inner);
        }
        pending.sample.take()
    }

    /// Hands `frame` over, in place of one the display thread has not taken,
    /// and enqueues `commands` behind everything it has not taken.
    pub(crate) fn hand(&self, frame: HandedFrame, commands: Commands) {
        let mut back = self.back();
        back.queued.push(Queued::Frame(Box::new(commands)));
        back.frame = Some(frame);
    }

    /// Enqueues `error`, the whole of what the display thread is handed of a
    /// game that never started.
    pub(crate) fn fail(&self, error: Error) {
        self.back().queued.push(Queued::Failed(error));
    }

    fn back(&self) -> MutexGuard<'_, Back> {
        self.0.back.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn pending(&self) -> MutexGuard<'_, Pending> {
        self.0
            .pending
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }
}

/// The game thread behind a window, and the clock its ticks and its frames are
/// paced by, which is read on its own thread and nowhere else.
pub(crate) struct Paced<G: Game> {
    game: GameThread<G>,
    clock: Clock,
}

impl<G: Game> Paced<G> {
    /// The game thread `starting` builds, paced from now on.
    ///
    /// Nothing where a vocabulary named what the assets do not hold, or the
    /// init closure failed: that error is handed to the display thread, which
    /// reports it and ends the run.
    pub(crate) fn started(end: &GameEnd, starting: Starting<G>) -> Option<Self> {
        let Starting {
            config,
            files,
            kept,
            init,
        } = starting;

        match GameThread::start(config, files, kept, init) {
            Ok(game) => Some(Self {
                game,
                clock: Clock::new(Instant::now()),
            }),
            Err(error) => {
                end.fail(error);
                None
            }
        }
    }

    /// Runs every sample the display thread hands: the ticks each one needs,
    /// the frame after them, and the hand back.
    ///
    /// The game thread makes this call once and waits inside it for each
    /// sample. It returns where the game closed the run and where the
    /// display thread ended it.
    pub(crate) fn run(&mut self, end: &GameEnd) {
        while let Some(sample) = end.sample() {
            let dt = self.game.start_ticks();
            let owed = self.clock.frame_at(Instant::now(), dt);
            let Sample {
                stated,
                controls,
                ui_input,
            } = sample;
            self.game.take(stated, Some(controls));
            if let Some(ticks) = NonZeroU32::new(owed) {
                self.game.ticks(ticks, dt, self.clock.elapsed());
            }

            let time = self.clock.frame_time(self.game.tick_interval());
            let (handed, commands) = self.game.frame(time, ui_input);
            let closing = handed.closing;
            end.hand(handed, commands);
            if closing {
                return;
            }
        }
    }
}

/// The thread that owns the game: every catalog its vocabularies build into,
/// each over the assets, its queries, its saves, its UI and the run it
/// paces; every frame it records becomes one [`HandedFrame`] beside one
/// [`Commands`].
pub(crate) struct GameThread<G: Game> {
    game: G,
    config: Config,
    meshes: MeshCatalog<G::Meshes>,
    skies: SkyCatalog<G::Skyboxes>,
    sounding: Sounding<G::Sounds>,
    queries: Queries,
    saves: Saved,
    ui: Layer,
    draws: DrawList,
    run: Run,
    last_camera: Camera,
    /// What the hand last taken stated, which the ticks and the frame read.
    stated: Stated,
}

impl<G: Game> GameThread<G> {
    /// Builds the pool a game's parallel iterators run on, decodes `files`,
    /// builds every catalog over them, runs the catalog run, and starts the
    /// game with `init`.
    ///
    /// Fails where a worker of the pool did not start, where a source does
    /// not decode, where a vocabulary names what the assets do not hold, or
    /// where `init` does.
    pub(crate) fn start(
        config: Config,
        files: Vec<(String, Vec<u8>)>,
        kept: Kept,
        init: impl FnOnce(&mut InitContext<'_, G>) -> Result<G, Error>,
    ) -> Result<Self, Error> {
        kept.workers.build_pool()?;
        let assets = Arc::new(Assets::load(files)?);
        let mut meshes = MeshCatalog::new(Arc::clone(&assets), config.mesh_memory());
        let mut skies = SkyCatalog::new(Arc::clone(&assets));
        let mut sounding = Sounding::new(Arc::clone(&assets), kept.mix_rate);
        let queries = Queries::new::<G::InputActions>(kept.bindings.as_deref());
        let saves = Saved::new(kept.saves.as_deref());
        let ui = Layer::new();

        let mut unresolved = sounding.build_catalog();
        unresolved.record(meshes.build_catalog());
        unresolved.record(skies.build_catalog());
        if let Some(error) = unresolved.error() {
            return Err(error);
        }

        let game = init(&mut InitContext::new(
            Engine::new(kept.window_size, &config, Camera::default(), false),
            &mut meshes,
            &mut sounding,
            &saves,
            &assets,
            &ui,
        ))?;

        Ok(Self {
            game,
            run: Run::new(config.tick_interval()),
            stated: Stated::starting(kept.window_size),
            config,
            meshes,
            skies,
            sounding,
            queries,
            saves,
            ui,
            draws: DrawList::new(),
            last_camera: Camera::default(),
        })
    }

    /// Takes what the display thread stated, and `controls` where a snapshot
    /// closed: every tick and the frame after them read them.
    ///
    /// `None` states that no snapshot closed, which leaves the queries
    /// reading what they read.
    pub(crate) fn take(&mut self, stated: Stated, controls: Option<Controls>) {
        self.stated = stated;
        if let Some(controls) = controls {
            self.queries.take(controls);
        }
    }

    /// Starts a batch of ticks, and returns the step each one takes.
    pub(crate) fn start_ticks(&mut self) -> Duration {
        self.run.start_ticks()
    }

    /// The step the ticks running now take.
    pub(crate) fn tick_interval(&self) -> Duration {
        self.run.tick_interval()
    }

    /// Runs `count` ticks of `dt` at `elapsed` on the run clock, each
    /// reading the sample last taken.
    pub(crate) fn ticks(&mut self, count: NonZeroU32, dt: Duration, elapsed: Duration) {
        let Self {
            game,
            config,
            meshes,
            sounding,
            queries,
            saves,
            ui,
            run,
            last_camera,
            stated,
            ..
        } = self;
        queries.ticks(count, |ticking| {
            let simulating = Simulating {
                audio: sounding,
                saves,
                run,
            };
            game.tick(&mut simulating.tick_context(
                Engine::new(
                    stated.window_size,
                    config,
                    *last_camera,
                    stated.sound_unlocked,
                ),
                meshes,
                ticking,
                dt,
                elapsed,
                ui.claims(),
            ));
        });
    }

    /// Runs the game's frame at `time`, over `ui_input` as the frame closed
    /// it, and hands over what it recorded, beside what it commands.
    pub(crate) fn frame(&mut self, time: FrameTime, ui_input: UiInput) -> (HandedFrame, Commands) {
        let Self {
            game,
            config,
            meshes,
            skies,
            sounding,
            queries,
            saves,
            ui,
            draws,
            run,
            last_camera,
            stated,
        } = self;
        let window_size = stated.window_size;
        let sound_unlocked = stated.sound_unlocked;

        let build = |layer: Building<'_>| {
            let recording = Recording {
                draws,
                meshes,
                skies,
                input: queries,
                simulating: Simulating {
                    audio: sounding,
                    saves,
                    run,
                },
            };
            let engine = Engine::new(window_size, config, *last_camera, sound_unlocked);
            game.frame(&mut recording.frame_context(engine, time, layer));
        };
        let layered = ui.frame(ui_input, build);
        let Layered {
            painted,
            changes,
            cursor,
        } = layered;

        let draws = draws.take();
        *last_camera = draws.camera();
        let handed = HandedFrame {
            draws,
            ui: painted,
            cursor,
            closing: run.closing(),
        };
        let commands = Commands {
            meshes: meshes.end_frame(),
            skies: skies.end_frame(),
            ui: changes,
            sound: sounding.flush(last_camera.view()),
            bindings: queries.flush(),
            saves: saves.flush(),
        };

        (handed, commands)
    }

    /// Whether the game has requested that the run end, which a session
    /// with no loop to end reads back.
    #[cfg(feature = "offscreen")]
    pub(crate) fn closing(&self) -> bool {
        self.run.closing()
    }

    /// The game itself, for a session that reads it between frames.
    #[cfg(feature = "offscreen")]
    pub(crate) fn game(&self) -> &G {
        &self.game
    }

    /// The game itself, for a session that changes it between frames.
    #[cfg(feature = "offscreen")]
    pub(crate) fn game_mut(&mut self) -> &mut G {
        &mut self.game
    }
}

/// The thread that owns the device: the GPU, the devices the window's events
/// fold into, the passes a handed frame is drawn through, the painter the
/// UI is drawn by, the output the commands play through, the hold the
/// window keeps the pointer in, and the stores the kept text is written
/// to. One value, which names no game type.
pub(crate) struct DisplayThread {
    pub(crate) gpu: Gpu,
    devices: Devices,
    renderer: Renderer,
    painter: Painter,
    output: SoundOutput,
    hold: PointerHold,
    bindings: Store,
    saves: Store,
    /// The draws of the frame handed last, which every draw until the next
    /// one draws again.
    drawn: DrawList,
    /// When this thread started, which is what a double click is counted
    /// against: the game thread keeps its own clock, never this one.
    started: Instant,
}

impl DisplayThread {
    /// The display thread once the GPU exists, with `devices` reading nothing,
    /// the pointer held nowhere and nothing drawn yet.
    pub(crate) fn new(
        gpu: Gpu,
        devices: Devices,
        renderer: Renderer,
        painter: Painter,
        output: SoundOutput,
        bindings: Store,
        saves: Store,
    ) -> Self {
        Self {
            gpu,
            devices,
            renderer,
            painter,
            output,
            hold: PointerHold::released(),
            bindings,
            saves,
            drawn: DrawList::new(),
            started: Instant::now(),
        }
    }

    /// Folds `event` into the next sample: the UI and the devices each
    /// take it, a gesture allows sound to start and takes the pointer hold
    /// a browser waits for, and a focus change drops the hold.
    pub(crate) fn see(&mut self, event: &WindowEvent) {
        self.painter.fold(event);
        self.devices.see(event);
        if is_gesture(event) {
            self.output.unlock();
            self.hold.see_gesture(&self.gpu.window());
        }
        if matches!(event, WindowEvent::Focused(_)) {
            self.hold.see_focus_change();
        }
    }

    /// Takes what a device reports of its own movement, which is how a
    /// held pointer moves: a window reports no place for one.
    pub(crate) fn see_device(&mut self, event: &DeviceEvent) {
        self.devices.see_device(event);
    }

    /// Closes the sample the next frame reads: every event folded since the
    /// last one is in it, and none is lost.
    pub(crate) fn sample(&mut self) -> Sample {
        Sample {
            stated: Stated {
                window_size: self.gpu.physical_size(),
                sound_unlocked: self.output.unlocked(),
            },
            controls: self.devices.sample(self.started.elapsed()),
            ui_input: self.painter.take_input(),
        }
    }

    /// Takes everything `queued` holds, in order, and returns the error a
    /// game that never started failed with.
    pub(crate) fn take(&mut self, queued: Vec<Queued>) -> Option<Error> {
        queued.into_iter().find_map(|one| match one {
            Queued::Frame(commands) => {
                self.commanded(*commands);
                None
            }
            Queued::Failed(error) => Some(error),
        })
    }

    /// Keeps `frame` as what every draw until the next frame draws — its
    /// draws, its UI's shapes, and the hold its cursor puts on the pointer —
    /// and reports whether it ends the run.
    pub(crate) fn keep(&mut self, frame: HandedFrame) -> bool {
        let HandedFrame {
            draws,
            ui,
            cursor,
            closing,
        } = frame;
        let held = self.hold.set(&self.gpu.window(), cursor.holds_pointer());
        self.devices.hold_pointer(held);
        self.painter.keep(ui, cursor);
        self.drawn = draws;

        closing
    }

    /// Draws what it last kept into the window: the frame the game thread
    /// handed, or nothing at all before it has handed one.
    pub(crate) fn render(&mut self) {
        self.renderer
            .render(&mut self.gpu, &self.drawn, &mut self.painter);
    }

    /// Takes and plays everything one frame commands: what it built for the
    /// GPU, its sounds through the output, and each kept text where a flush
    /// changed it.
    fn commanded(&mut self, commands: Commands) {
        let Commands {
            meshes,
            skies,
            ui,
            sound,
            bindings,
            saves,
        } = commands;
        self.renderer.take(
            self.gpu.device(),
            self.gpu.queue(),
            meshes,
            skies,
            ui,
            &mut self.painter,
        );
        self.output.play(sound);
        if let Some(text) = bindings {
            self.bindings.write(&text);
        }
        if let Some(text) = saves {
            self.saves.write(&text);
        }
    }
}

/// Whether the player did something, which a browser requires before it
/// plays anything.
fn is_gesture(event: &WindowEvent) -> bool {
    matches!(
        event,
        WindowEvent::KeyboardInput { .. }
            | WindowEvent::Touch(_)
            | WindowEvent::MouseInput {
                state: ElementState::Pressed,
                ..
            }
    )
}

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

    use super::*;
    use crate::{
        FrameContext, NoInputActions, NoMeshes, NoPostEffects, NoSkyboxes, NoSounds,
        NoSurfaceStyles, TickContext,
    };

    /// The drawing area every test hands over.
    const SIZE: UVec2 = UVec2::new(320, 200);

    /// The values one chunk of the fold below adds up.
    const CHUNK: usize = 1024;

    /// The thread each frame of a [`Probe`] ran on, which the test that
    /// started it reads once that run is over.
    type Ran = Arc<Mutex<Vec<std::thread::ThreadId>>>;

    /// A game that counts its frames, records where each one ran and closes
    /// the run at one of them, drawing nothing and reading nothing.
    struct Probe {
        frames: u32,
        closes_at: u32,
        ran: Ran,
    }

    impl Game for Probe {
        type Meshes = NoMeshes;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = NoSurfaceStyles;
        type PostEffects = NoPostEffects;

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            self.frames += 1;
            self.ran
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(std::thread::current().id());
            if self.frames == self.closes_at {
                ctx.close();
            }
        }
    }

    /// A run of [`Probe`], which closes the run at frame `closes_at`, beside
    /// the thread each of its frames runs on.
    fn starting(closes_at: u32) -> (Starting<Probe>, Ran) {
        let ran = Ran::default();
        let probe = Arc::clone(&ran);
        let starting = Starting {
            config: Config::new("threads"),
            files: Vec::new(),
            kept: Kept {
                bindings: None,
                saves: None,
                window_size: SIZE,
                mix_rate: None,
                workers: Workers::here_again(),
            },
            init: Box::new(move |_ctx| {
                Ok(Probe {
                    frames: 0,
                    closes_at,
                    ran: probe,
                })
            }),
        };

        (starting, ran)
    }

    /// One sample, as a window with nothing on it closes one.
    fn sample() -> Sample {
        Sample {
            stated: Stated::starting(SIZE),
            controls: Controls::default(),
            ui_input: UiInput::default(),
        }
    }

    /// The game thread of a run of [`Probe`], on this thread.
    fn game_thread(closes_at: u32) -> GameThread<Probe> {
        let (
            Starting {
                config,
                files,
                kept,
                init,
            },
            _,
        ) = starting(closes_at);

        GameThread::start(config, files, kept, init).expect("a game that names no asset starts")
    }

    #[test]
    fn a_sample_the_game_thread_has_not_taken_is_never_closed_over() {
        let (end, game) = DisplayEnd::paired();
        let closed = core::cell::Cell::new(0);
        let close = || {
            closed.set(closed.get() + 1);
            sample()
        };

        end.hand(close);
        end.hand(close);
        assert_eq!(
            closed.get(),
            1,
            "the events since fold into the one waiting"
        );

        game.sample().expect("the sample the display thread handed");
        end.hand(close);
        assert_eq!(closed.get(), 2, "and the next is closed once it is taken");
    }

    #[test]
    fn the_display_thread_returns_while_the_game_thread_holds_the_crossing() {
        let (end, game) = DisplayEnd::paired();
        let (took, taken) = std::sync::mpsc::channel();
        let (release, released) = std::sync::mpsc::channel();
        let (report, reported) = std::sync::mpsc::channel();

        let holder = std::thread::spawn(move || {
            let pending = game.pending();
            let back = game.back();
            took.send(()).expect("the test reads that both are held");
            released.recv().expect("the test lets both go");
            drop((pending, back));
            game
        });
        taken.recv().expect("the game thread holds the crossing");

        let display = std::thread::spawn(move || {
            let mut closed = 0;
            end.hand(|| {
                closed += 1;
                sample()
            });
            report
                .send((closed, end.frame().is_some(), end.queued().len()))
                .expect("the test reads what the display thread took");
            end
        });
        let took = reported.recv_timeout(Duration::from_secs(5));
        let (closed, framed, queued) =
            took.expect("the display thread returns while the game thread holds the crossing");

        assert_eq!(closed, 0, "no sample is closed over a slot it cannot hand");
        assert!(!framed, "no frame is taken out of a hand being made");
        assert_eq!(queued, 0, "and nothing is taken out of the queue");

        release.send(()).expect("the game thread lets go");
        let game = holder.join().expect("the thread holding the crossing");
        let end = display.join().expect("the thread reading it");
        end.hand(sample);
        assert!(
            game.sample().is_some(),
            "and the hand after it lands, so no sample is lost"
        );
    }

    #[test]
    fn a_frame_the_slot_replaces_loses_nothing_the_display_thread_acts_on() {
        let (end, game) = DisplayEnd::paired();
        let mut thread = game_thread(2);

        for _ in 0..2 {
            let Sample {
                stated,
                controls,
                ui_input,
            } = sample();
            thread.take(stated, Some(controls));
            let (frame, commands) = thread.frame(FrameTime::default(), ui_input);
            game.hand(frame, commands);
        }

        assert!(
            end.frame().expect("a frame to draw").closing,
            "the newest frame is the one the display thread draws"
        );
        assert_eq!(
            end.queued().len(),
            2,
            "and what both frames command is queued, neither of them dropped"
        );
    }

    #[test]
    fn the_frame_of_the_sample_handed_runs_on_the_game_thread() {
        let (end, game) = DisplayEnd::paired();
        let (starting, ran) = starting(1);
        let thread = std::thread::spawn(move || {
            let Some(mut paced) = Paced::started(&game, starting) else {
                return;
            };
            paced.run(&game);
        });

        end.hand(sample);
        thread.join().expect("the game thread ends with the run");

        assert!(
            end.frame().expect("the frame it ran").closing,
            "the frame that closed the run is drawn"
        );
        assert_eq!(end.queued().len(), 1, "beside what it commands");
        match ran
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_slice()
        {
            [frame] => assert_ne!(
                *frame,
                std::thread::current().id(),
                "and no frame ran where the display thread's own events run"
            ),
            frames => panic!("one sample runs one frame, not {}", frames.len()),
        }
    }

    #[test]
    fn the_error_the_init_closure_failed_with_reaches_the_display_thread() {
        let (end, game) = DisplayEnd::paired();
        let failing = Starting::<Probe> {
            init: Box::new(|_ctx| Err(Error::msg("no game today"))),
            ..starting(1).0
        };

        let thread = std::thread::spawn(move || {
            assert!(
                Paced::started(&game, failing).is_none(),
                "no game thread runs where the init closure failed"
            );
        });
        thread.join().expect("the game thread ends with the error");

        match end.queued().as_slice() {
            [Queued::Failed(error)] => assert_eq!(error.to_string(), "no game today"),
            _ => panic!("the error is the whole of what the display thread is handed"),
        }
        assert!(end.frame().is_none(), "and no frame was ever handed");
    }

    #[test]
    fn the_worker_count_leaves_the_engine_its_two_threads_and_stops_at_the_cap() {
        assert_eq!(Workers::beside_the_run(8), 6);
        assert_eq!(
            Workers::beside_the_run(64),
            Workers::MOST,
            "however many a machine states"
        );
        assert_eq!(
            Workers::beside_the_run(2),
            1,
            "and a machine with nothing to spare still runs one"
        );
        assert_eq!(Workers::beside_the_run(0), 1);
    }

    #[test]
    fn a_game_thread_that_is_already_a_worker_of_a_pool_is_refused_at_startup() {
        let pool = ThreadPoolBuilder::new()
            .num_threads(2)
            .build()
            .expect("a pool of this test's own");

        let refused = pool
            .install(|| Workers::here_again().build_pool())
            .expect_err("a game thread on a worker of a pool");

        assert!(
            refused.to_string().contains("worker of a pool"),
            "{refused}"
        );
    }

    #[test]
    fn a_pool_the_game_built_before_the_run_stops_a_start_behind_a_window() {
        Workers::here_again()
            .build_pool()
            .expect("the pool a game builds for itself, which a start of many builds here");

        let refused = Workers::here()
            .build_pool()
            .expect_err("a pool that stood before the run started");

        assert!(
            refused.to_string().contains("stood before the run"),
            "{refused}"
        );
    }

    #[test]
    fn a_chunked_fold_reads_the_same_bits_at_any_worker_count() {
        let values: Vec<f32> = (0..100_000).map(|at| (at as f32).sin() * 1e3).collect();
        let folded = |workers| {
            let pool = ThreadPoolBuilder::new()
                .num_threads(workers)
                .build()
                .expect("a pool of this test's own");

            pool.install(|| {
                values
                    .par_chunks(CHUNK)
                    .map(|chunk| chunk.iter().sum::<f32>())
                    .collect::<Vec<f32>>()
                    .iter()
                    .sum::<f32>()
            })
        };

        assert_eq!(
            folded(1).to_bits(),
            folded(Workers::MOST).to_bits(),
            "the chunks hold the same values at either count, and the fold adds them up in order"
        );
    }

    #[test]
    fn everything_that_crosses_between_the_two_threads_is_plain_data() {
        fn crosses<T: Send>() {}

        crosses::<Sample>();
        crosses::<HandedFrame>();
        crosses::<Queued>();
        crosses::<Starting<Probe>>();
        crosses::<GameEnd>();
    }
}