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
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
//! An `Elf` posed by one `Animator` over ten states: `Idle` and `Dance`
//! loop in place, `Locomotion` blends `Walk` into `Jog` paced by the speed
//! `WASD` or the arrows are held (`Left Shift` runs, relative to the
//! camera), `Attack`, `Hit`, `Jump`, `SitDown` and `StandUp` each play
//! once, and `Sit` loops between them. A walk onto one of the red patches
//! plays `Hit`; a third one plays `Death` and holds it until
//! `Button::Restart` starts a new `Animator`. `Button::Interact` near the
//! seat sits the elf on it and stands it back up, and a move, `Button::Attack`
//! or `Button::Jump` leaves the seat at once. A second `Elf`, standing
//! in place, is posed by a machine of one state that scrubs its own
//! `SitDown` by its distance from the first. A click, `Button::Hold`,
//! takes the held pointer; `Button::Release` (escape) frees it again. The
//! pointer orbits and tilts the camera, which always frames the whole
//! figure; a prompt over the seat,
//! the patches, and the second elf names what each does; the panel names
//! the state, the hits taken, and the controls. The sun lights the ground; a
//! lamp post by the seat casts the elf's own shadow as it walks past; a cone
//! of light over the red patches lights them from above; and a `Butterfly`,
//! one `Animator` looping `Fly`, orbits the seat and the lamp, its own point
//! light colorful and shadowed too.

use core::f32::consts::TAU;
use core::ops::Range;
use core::time::Duration;

use mirage_engine::prelude::*;

/// The elf's source, next to the other example assets.
const ELF_SOURCE: &str = "examples/assets/elf.glb";
/// The root node the source names the elf under.
const ELF_ROOT: &str = "Elf";
/// The elf's own height, as `tools/elf_fixture.py` holds it: read here only
/// to lift the second elf's prompt over its head, since nothing in the
/// mesh API reports a draw's bounds back to the game.
const ELF_HEIGHT: f32 = 1.6;

/// The window this game opens at, and the surface [`CAMERA_YAW_SCALE`] and
/// [`CAMERA_PITCH_SCALE`] read a drag as a fraction of.
const WINDOW_WIDTH: u32 = 1280;
const WINDOW_HEIGHT: u32 = 720;

/// The elf's top speed, in meters per second.
const ELF_SPEED: f32 = 4.0;
/// The fraction of top speed a walk, without `Button::Run` held, is held
/// at: past it a held run is what raises `Locomotion`'s blend toward `Jog`.
const WALK_CAP: f32 = 0.5;
/// The least speed `Locomotion` reads over `Idle`.
const WALK_THRESHOLD: f32 = 0.1;
/// The turn rate facing a new heading, in radians a second.
const TURN_RATE: f32 = TAU * 2.0;

/// The elf's upward speed the instant `Jump` is entered, in meters a
/// second; with [`GRAVITY`] it is back on the ground in about `0.9`
/// seconds, near where the clip's own landing falls, inside its length.
const JUMP_LAUNCH_SPEED: f32 = 4.5;
/// Acceleration that takes the elf's height down while off the ground, in
/// meters a second squared.
const GRAVITY: f32 = 9.8;

const IDLE_LOCOMOTION_FADE: Duration = Duration::from_millis(200);
const ATTACK_ENTER_FADE: Duration = Duration::from_millis(80);
const ATTACK_CHAIN_FADE: Duration = Duration::from_millis(60);
const ATTACK_EXIT_FADE: Duration = Duration::from_millis(200);
/// Where along `Attack` a second press chains into it again, past the
/// start the first press already played.
const ATTACK_CHAIN_ENTRY: f32 = 0.15;
/// How far along `Attack` it stops reading new presses and instead runs to
/// its own end.
const ATTACK_RELEASE: f32 = 0.8;
const HIT_ENTER_FADE: Duration = Duration::from_millis(50);
const HIT_EXIT_FADE: Duration = Duration::from_millis(150);
const DEATH_FADE: Duration = Duration::from_millis(150);
const JUMP_ENTER_FADE: Duration = Duration::from_millis(100);
const JUMP_EXIT_FADE: Duration = Duration::from_millis(150);
const SIT_DOWN_FADE: Duration = Duration::from_millis(200);
const STAND_UP_FADE: Duration = Duration::from_millis(150);
const STAND_EXIT_FADE: Duration = Duration::from_millis(150);
const DANCE_FADE: Duration = Duration::from_millis(200);

const ELF_START: Vec3 = Vec3::new(-3.0, 0.0, 4.0);

/// Ground positions of the three hurt patches, and their radius.
const HURT_PATCHES: [Vec3; 3] = [
    Vec3::new(1.5, 0.0, -1.0),
    Vec3::new(-1.5, 0.0, -3.5),
    Vec3::new(3.0, 0.0, 2.0),
];
const HURT_RADIUS: f32 = 0.9;
/// Hits it takes before the elf reads `Death` instead of `Hit`.
const FATAL_HITS: u32 = 3;

/// The seat's position, at the ground, and its footprint: measured on the
/// asset, `sit_down` lowers the pelvis from `0.77` meters to `0.47` meters
/// and moves it `0.29` meters toward the seat, the feet staying where they
/// stood, so a block this tall under that landing puts the pelvis on its
/// top face.
const SEAT_POSITION: Vec3 = Vec3::new(-3.5, 0.0, -3.0);
const SEAT_FOOTPRINT: f32 = 1.0;
const SEAT_HEIGHT: f32 = 0.45;
/// How tall the figure sits, from the seat's top to its head.
const SEATED_HEIGHT: f32 = 0.75;
/// Height from the ground to the seated elf's head.
const SEAT_HEAD_HEIGHT: f32 = SEAT_HEIGHT + SEATED_HEIGHT;
/// The gap in front of the seat's own face the elf stands at.
const SEAT_STAND_CLEARANCE: f32 = 0.05;
/// Where the elf stands to sit on the seat, at its front face plus
/// [`SEAT_STAND_CLEARANCE`], and which way it faces there: away from the
/// seat, so `sit_down` moves the pelvis back onto it.
const SEAT_SPOT: Vec3 = Vec3::new(
    SEAT_POSITION.x,
    0.0,
    SEAT_POSITION.z + SEAT_FOOTPRINT * 0.5 + SEAT_STAND_CLEARANCE,
);
const SEAT_FACING: f32 = 0.0;
/// The least distance from [`SEAT_POSITION`] `Button::Interact` sits the
/// elf down at.
const SEAT_INTERACT_RADIUS: f32 = 1.6;

/// The second elf's fixed position, under a machine scrubbed by its
/// distance from the first.
const SCRUBBED_ELF_POSITION: Vec3 = Vec3::new(3.5, 0.0, 4.0);
/// The distance at and under which the scrubbed elf reads fully seated.
const SCRUB_NEAR: f32 = 1.5;
/// The distance at and past which it reads fully standing.
const SCRUB_FAR: f32 = 5.0;

/// The lamp post's own position, near the seat and its stand.
const LAMP_POST_POSITION: Vec3 = Vec3::new(-4.9, 0.0, -2.0);
const LAMP_POST_HEIGHT: f32 = 2.2;
const LAMP_POST_THICKNESS: f32 = 0.16;
const LAMP_POST_COLOR: Color = Color::rgb(0.16, 0.14, 0.12);
/// The lamp's own head, on top of the post, emissive in [`LAMP_LIGHT_COLOR`].
const LAMP_HEAD_SIZE: f32 = 0.34;
/// The gap left between the post's own top and the head's bottom face, so
/// the light sits clear of both meshes rather than inside the head it
/// would then cast no light from.
const LAMP_HEAD_GAP: f32 = 0.06;
/// Past `1.0`, so its glow lands on the ground near it, visible against
/// the sky, and the head reads bright once bloom spreads it.
const LAMP_LIGHT_COLOR: Color = Color::rgb(5.5, 4.2, 2.2);
const LAMP_LIGHT_RANGE: f32 = 6.0;

/// Centered over the three [`HURT_PATCHES`], tall enough for one cone to
/// reach all of them.
const SPOT_POSITION: Vec3 = Vec3::new(1.0, 6.0, -0.83);
const SPOT_DIRECTION: Vec3 = Vec3::NEG_Y;
/// Past `1.0`, so the cone is visible on the ground against the sky, and
/// bright enough that a patch inside it reads well past a patch outside.
const SPOT_COLOR: Color = Color::rgb(11.0, 9.8, 8.2);
const SPOT_RANGE: f32 = 9.0;
const SPOT_ANGLE: f32 = 0.85;
/// The fixture's own edge length, drawn where the cone starts.
const SPOT_FIXTURE_SIZE: f32 = 0.22;
const SPOT_FIXTURE_COLOR: Color = Color::rgb(0.2, 0.2, 0.22);

/// The butterfly's own source, next to the other example assets.
const BUTTERFLY_SOURCE: &str = "examples/assets/butterfly.glb";
/// The root node the source names the butterfly under.
const BUTTERFLY_ROOT: &str = "Butterfly";
/// The point halfway between [`SEAT_POSITION`] and [`LAMP_POST_POSITION`],
/// the closed path's own center.
const BUTTERFLY_CENTER: Vec3 = Vec3::new(-4.2, 0.0, -2.5);
/// The closed path's radius along `x` and `z`, wide enough to loop around
/// both the seat and the lamp.
const BUTTERFLY_RADIUS: Vec2 = Vec2::new(1.8, 1.4);
/// About the lamp's own height.
const BUTTERFLY_HEIGHT: f32 = LAMP_POST_HEIGHT;
/// Radians a second around the path; a full loop takes about 14 seconds.
const BUTTERFLY_ANGULAR_SPEED: f32 = TAU / 14.0;
/// Past `1.0`, so its glow lands on the ground and the lamp post it passes.
const BUTTERFLY_LIGHT_COLOR: Color = Color::rgb(1.8, 5.5, 5.0);
const BUTTERFLY_LIGHT_RANGE: f32 = 3.0;
/// The butterfly's own small emissive, so it reads bright rather than
/// dark against the glow it casts.
const BUTTERFLY_EMISSIVE: Color = Color::rgb(0.6, 1.8, 1.6);

const GROUND_SIZE: f32 = 400.0;
const GROUND_COLOR: Color = Color::rgb(0.24, 0.30, 0.22);
const HURT_COLOR: Color = Color::rgb(0.75, 0.12, 0.10);
const SEAT_COLOR: Color = Color::rgb(0.5, 0.42, 0.3);
/// Low, near the horizon, and dim.
const SUN_DIRECTION: Vec3 = Vec3::new(-0.85, -0.18, -0.5);
const SUN_COLOR: Color = Color::rgb(0.55, 0.32, 0.22);
const SKY_ZENITH: Color = Color::rgb(0.06, 0.07, 0.2);
const SKY_HORIZON: Color = Color::rgb(0.55, 0.35, 0.28);
const SKY_NADIR: Color = Color::rgb(0.05, 0.05, 0.07);
/// The fraction of its own light the sky lands and reflects: dim, so the
/// lamp, spotlight and butterfly lights read against it.
const SKY_LIGHT: f32 = 0.15;

/// The orbit camera's distance behind and height above its target.
const CAMERA_BACK: f32 = 3.4;
const CAMERA_UP: f32 = 1.7;
/// Height above the ground the camera looks at, framing the whole figure.
const CAMERA_LOOK_HEIGHT: f32 = 0.8;
const CAMERA_FOV: f32 = 50.0;
/// Radians the camera orbits, or tilts, per pixel the pointer moves,
/// chosen so a drag the width, or the height, of the window turns it by
/// [`CAMERA_YAW_PER_DRAG`], or [`CAMERA_PITCH_PER_DRAG`].
const CAMERA_YAW_PER_DRAG: f32 = core::f32::consts::PI;
const CAMERA_PITCH_PER_DRAG: f32 = core::f32::consts::FRAC_PI_3;
const CAMERA_YAW_SCALE: f32 = CAMERA_YAW_PER_DRAG / WINDOW_WIDTH as f32;
const CAMERA_PITCH_SCALE: f32 = CAMERA_PITCH_PER_DRAG / WINDOW_HEIGHT as f32;
/// The range the camera's tilt is held inside, in radians: short of
/// looking flat along the ground or straight down, either of which would
/// stop framing the figure.
const CAMERA_PITCH_RANGE: Range<f32> = -0.4..0.9;

/// The panel's controls, a key and what it does.
const CONTROLS: [(&str, &str); 10] = [
    ("mouse", "turns the camera"),
    ("click", "locks the pointer"),
    ("escape", "frees the pointer"),
    ("wasd or arrows", "walk"),
    ("left shift", "runs"),
    ("f", "attacks, chains on a second press"),
    ("space", "jumps"),
    ("n", "dances while idle"),
    ("e", "sits on the seat and stands back up"),
    ("r", "starts a new elf"),
];

/// The UI's own text color, read over the ground and the sky both.
const PANEL_TEXT_COLOR: egui::Color32 = egui::Color32::from_gray(230);
/// How much dark a panel or a prompt's own backdrop puts behind its text.
const PANEL_BACKDROP: u8 = 190;
/// The panel's own inner margin, around its labels.
const PANEL_PADDING: i8 = 8;
/// The size a world-space prompt reads at, in logical points.
const PROMPT_SIZE: f32 = 15.0;
/// Height a world-space prompt is lifted over the point it names.
const PROMPT_LIFT: f32 = 0.35;
/// Margin a prompt's own backdrop keeps past its galley, in logical points.
const PROMPT_PADDING: f32 = 4.0;

meshes! { enum Shape { Plane, Cube, Elf, Butterfly } }

/// The one sky this game draws, a gradient set each frame.
#[derive(Catalog, Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum Sky {
    Day,
}

impl Skyboxes for Sky {
    fn build(&self, _assets: &Assets) -> SkyboxData {
        match self {
            Self::Day => SkyboxData::gradient(SKY_ZENITH, SKY_HORIZON, SKY_NADIR).lit_by(SKY_LIGHT),
        }
    }
}

#[derive(Catalog, Clone, PartialEq, Eq, Hash)]
struct Elf;

/// The clips `ElfState` and `ScrubbedState` play, named as the source
/// names them.
#[derive(Clip, Clone, Debug, PartialEq, Eq, Hash)]
enum ElfClip {
    #[clip("idle")]
    Idle,
    #[clip("walk")]
    Walk,
    #[clip("jog")]
    Jog,
    #[clip("attack")]
    Attack,
    #[clip("hit")]
    Hit,
    #[clip("death")]
    Death,
    #[clip("sit_down")]
    SitDown,
    #[clip("sit")]
    Sit,
    #[clip("stand_up")]
    StandUp,
    #[clip("jump")]
    Jump,
    #[clip("dance")]
    Dance,
}

impl Mesh<NoParts, ElfClip> for Elf {
    fn build(&self, assets: &Assets) -> MeshData<NoParts, ElfClip> {
        assets.model(ELF_ROOT)
    }
}

/// What the game fills each tick to move `ElfState` on.
#[derive(Default)]
struct ElfInput {
    /// The elf's speed this tick, a fraction of [`ELF_SPEED`].
    speed: f32,
    attack: bool,
    /// True the tick a hurt patch is stepped onto and [`FATAL_HITS`] have
    /// not yet landed.
    hit: bool,
    /// True the tick a hurt patch is stepped onto the third time, which
    /// [`FATAL_HITS`] counts.
    dying: bool,
    jump: bool,
    /// True the tick `Jump`'s own height curve returns the elf to the
    /// ground after it launches.
    landed: bool,
    dance: bool,
    /// `Button::Interact`, read as sitting down, standing back up, or
    /// nothing, by the state it reaches.
    interact: bool,
    /// Whether the elf stands close enough to the cube to sit on it.
    near_seat: bool,
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum ElfState {
    Idle,
    Locomotion,
    Attack,
    Hit,
    Death,
    SitDown,
    Sit,
    StandUp,
    Jump,
    Dance,
}

impl ElfState {
    /// Whether the elf is on the seat, or on its way onto or off it.
    fn seated(self) -> bool {
        matches!(self, Self::SitDown | Self::Sit | Self::StandUp)
    }

    /// `Locomotion` where `input` reads a walk or a run, `Idle` at rest:
    /// where a grounded state returns once whatever interrupted it ends.
    fn grounded(input: &ElfInput) -> Self {
        match input.speed > WALK_THRESHOLD {
            true => Self::Locomotion,
            false => Self::Idle,
        }
    }
}

impl AnimationStates for ElfState {
    type Clip = ElfClip;
    type Input = ElfInput;

    fn entry() -> Self {
        Self::Idle
    }

    fn motion(&self, input: &ElfInput) -> Motion<ElfClip> {
        match self {
            Self::Idle => Motion::looping(ElfClip::Idle),
            Self::Locomotion => {
                Motion::blend(ElfClip::Walk, ElfClip::Jog, input.speed).paced(input.speed)
            }
            Self::Attack => Motion::once(ElfClip::Attack),
            Self::Hit => Motion::once(ElfClip::Hit),
            Self::Death => Motion::once(ElfClip::Death),
            Self::SitDown => Motion::once(ElfClip::SitDown),
            Self::Sit => Motion::looping(ElfClip::Sit),
            Self::StandUp => Motion::once(ElfClip::StandUp),
            Self::Jump => Motion::once(ElfClip::Jump),
            Self::Dance => Motion::looping(ElfClip::Dance),
        }
    }

    fn next(&self, input: &ElfInput, at: Progress) -> Option<Transition<Self>> {
        match (self, input) {
            (Self::Death, _) => None,
            (_, ElfInput { dying: true, .. }) => Some(Self::Death.fade(DEATH_FADE)),
            (_, ElfInput { hit: true, .. }) if *self != Self::Hit => {
                Some(Self::Hit.fade(HIT_ENTER_FADE))
            }
            (Self::Hit, _) if at.ended() => Some(ElfState::grounded(input).fade(HIT_EXIT_FADE)),
            (Self::Attack, ElfInput { attack: true, .. }) if at.past(ATTACK_RELEASE) => Some(
                Self::Attack
                    .restarted()
                    .entering_at(ATTACK_CHAIN_ENTRY)
                    .fade(ATTACK_CHAIN_FADE),
            ),
            (Self::Attack, _) if at.past(ATTACK_RELEASE) => {
                Some(ElfState::grounded(input).fade(ATTACK_EXIT_FADE))
            }
            (Self::SitDown | Self::Sit | Self::StandUp, i) if i.speed > WALK_THRESHOLD => {
                Some(Self::Locomotion.fade(STAND_EXIT_FADE))
            }
            (Self::SitDown | Self::Sit | Self::StandUp, ElfInput { attack: true, .. }) => {
                Some(Self::Attack.fade(ATTACK_ENTER_FADE))
            }
            (Self::SitDown | Self::Sit | Self::StandUp, ElfInput { jump: true, .. }) => {
                Some(Self::Jump.fade(JUMP_ENTER_FADE))
            }
            (Self::SitDown, _) if at.ended() => Some(Self::Sit.at_once()),
            (Self::Sit, ElfInput { interact: true, .. }) => Some(Self::StandUp.fade(STAND_UP_FADE)),
            (Self::StandUp, _) if at.ended() => Some(Self::Idle.fade(STAND_EXIT_FADE)),
            (Self::Jump, ElfInput { landed: true, .. }) => {
                Some(ElfState::grounded(input).fade(JUMP_EXIT_FADE))
            }
            (Self::Jump, _) if at.ended() => Some(ElfState::grounded(input).fade(JUMP_EXIT_FADE)),
            (
                Self::Idle | Self::Locomotion,
                ElfInput {
                    interact: true,
                    near_seat: true,
                    ..
                },
            ) => Some(Self::SitDown.fade(SIT_DOWN_FADE)),
            (Self::Idle | Self::Locomotion, ElfInput { attack: true, .. }) => {
                Some(Self::Attack.fade(ATTACK_ENTER_FADE))
            }
            (Self::Idle | Self::Locomotion, ElfInput { jump: true, .. }) => {
                Some(Self::Jump.fade(JUMP_ENTER_FADE))
            }
            (Self::Idle, ElfInput { dance: true, .. }) => Some(Self::Dance.fade(DANCE_FADE)),
            (Self::Dance, i) if i.speed > WALK_THRESHOLD => {
                Some(Self::Locomotion.fade(IDLE_LOCOMOTION_FADE))
            }
            (Self::Idle, i) if i.speed > WALK_THRESHOLD => {
                Some(Self::Locomotion.fade(IDLE_LOCOMOTION_FADE))
            }
            (Self::Locomotion, i) if i.speed <= WALK_THRESHOLD => {
                Some(Self::Idle.fade(IDLE_LOCOMOTION_FADE))
            }
            _ => None,
        }
    }
}

/// A machine of one state, posed by nothing but the value it scrubs.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum ScrubbedState {
    SitDown,
}

/// What the game fills each tick to move `ScrubbedState` on.
#[derive(Default)]
struct ScrubbedInput {
    /// How far into sitting down the second elf reads, a fraction in
    /// `0.0..=1.0`.
    settled: f32,
}

impl AnimationStates for ScrubbedState {
    type Clip = ElfClip;
    type Input = ScrubbedInput;

    fn entry() -> Self {
        Self::SitDown
    }

    fn motion(&self, input: &ScrubbedInput) -> Motion<ElfClip> {
        Motion::scrubbed(ElfClip::SitDown, input.settled)
    }

    fn next(&self, _input: &ScrubbedInput, _at: Progress) -> Option<Transition<Self>> {
        None
    }
}

#[derive(Catalog, Clone, PartialEq, Eq, Hash)]
struct Butterfly;

/// The one clip `FlyingState` plays, named as the source names it.
#[derive(Clip, Clone, Debug, PartialEq, Eq, Hash)]
enum ButterflyClip {
    #[clip("fly")]
    Fly,
}

impl Mesh<NoParts, ButterflyClip> for Butterfly {
    fn build(&self, assets: &Assets) -> MeshData<NoParts, ButterflyClip> {
        assets.model(BUTTERFLY_ROOT)
    }
}

/// A machine of one state, looping the butterfly's only clip.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum FlyingState {
    Flying,
}

impl AnimationStates for FlyingState {
    type Clip = ButterflyClip;
    type Input = ();

    fn entry() -> Self {
        Self::Flying
    }

    fn motion(&self, _input: &()) -> Motion<ButterflyClip> {
        Motion::looping(ButterflyClip::Fly)
    }

    fn next(&self, _input: &(), _at: Progress) -> Option<Transition<Self>> {
        None
    }
}

/// The butterfly's position and the `yaw` it faces, `t` seconds into its
/// closed loop around [`BUTTERFLY_CENTER`].
fn butterfly_pose(t: f32) -> (Vec3, f32) {
    let angle = t * BUTTERFLY_ANGULAR_SPEED;
    let position = BUTTERFLY_CENTER
        + Vec3::new(
            BUTTERFLY_RADIUS.x * angle.cos(),
            BUTTERFLY_HEIGHT,
            BUTTERFLY_RADIUS.y * angle.sin(),
        );
    let direction = Vec3::new(
        -BUTTERFLY_RADIUS.x * angle.sin(),
        0.0,
        BUTTERFLY_RADIUS.y * angle.cos(),
    );
    (position, direction.x.atan2(direction.z))
}

/// How far into sitting down the second elf reads at `distance` from the
/// first.
fn settled_at(distance: f32) -> f32 {
    1.0 - (distance - SCRUB_NEAR) / (SCRUB_FAR - SCRUB_NEAR)
}

/// A camera [`CAMERA_BACK`] behind and [`CAMERA_UP`] above `target`, tilted
/// `pitch` radians and turned `yaw` radians around it, looking at a point
/// [`CAMERA_LOOK_HEIGHT`] above `target`.
fn orbit_camera(target: Vec3, yaw: f32, pitch: f32) -> Camera {
    let look_at = target + Vec3::Y * CAMERA_LOOK_HEIGHT;
    let base = Vec3::new(0.0, CAMERA_UP, CAMERA_BACK);
    let offset = Quat::from_rotation_y(yaw) * (Quat::from_rotation_x(pitch) * base);
    Camera::new(
        View::look_at(look_at + offset, look_at),
        Projection::perspective(CAMERA_FOV),
    )
}

/// The logical point egui paints the physical pixel `pixel` at.
fn logical(pixel: Vec2, pixels_per_point: f32) -> egui::Pos2 {
    let point = pixel / pixels_per_point;
    egui::pos2(point.x, point.y)
}

#[derive(InputButtonAction, Clone, Copy)]
enum Button {
    Run,
    Attack,
    Jump,
    Dance,
    Interact,
    Restart,
    Hold,
    Release,
}

impl InputButtonAction for Button {
    fn bindings(&self) -> Vec<ButtonBinding> {
        match self {
            Button::Run => vec![Key::LeftShift.into()],
            Button::Attack => vec![Key::F.into()],
            Button::Jump => vec![Key::Space.into()],
            Button::Dance => vec![Key::N.into()],
            Button::Interact => vec![Key::E.into()],
            Button::Restart => vec![Key::R.into()],
            Button::Hold => vec![MouseButton::Left.into()],
            Button::Release => vec![Key::Escape.into()],
        }
    }
}

/// The camera's own controls: turned and tilted by how far the pointer
/// moves sideways and upward each tick.
#[derive(InputAxisAction, Clone, Copy)]
enum Axis {
    CameraYaw,
    CameraPitch,
}

impl InputAxisAction for Axis {
    fn bindings(&self) -> Vec<AxisBinding> {
        match self {
            Axis::CameraYaw => {
                vec![AxisBinding::pointer_delta(PointerDelta::Sideways).scale(CAMERA_YAW_SCALE)]
            }
            Axis::CameraPitch => {
                vec![AxisBinding::pointer_delta(PointerDelta::Up).scale(CAMERA_PITCH_SCALE)]
            }
        }
    }
}

#[derive(InputAxis2Action, Clone, Copy)]
enum Move {
    Walk,
}

impl InputAxis2Action for Move {
    fn bindings(&self) -> Vec<Axis2Binding> {
        match self {
            Move::Walk => vec![
                Axis2Binding::from(ButtonAxis2 {
                    left: Key::A,
                    right: Key::D,
                    down: Key::S,
                    up: Key::W,
                }),
                Axis2Binding::from(ButtonAxis2 {
                    left: Key::Left,
                    right: Key::Right,
                    down: Key::Down,
                    up: Key::Up,
                }),
            ],
        }
    }
}

struct Controls;

impl InputActions for Controls {
    type Button = Button;
    type Axis = Axis;
    type Axis2 = Move;
}

/// `text` in [`PANEL_TEXT_COLOR`].
fn panel_text(text: impl Into<String>) -> egui::RichText {
    egui::RichText::new(text.into()).color(PANEL_TEXT_COLOR)
}

struct Scene {
    elf_pos: Vec3,
    elf_prev: Vec3,
    elf_yaw: f32,
    /// Height the elf is lifted over the ground while off the ground,
    /// integrated in [`Game::tick`] from [`Self::jump_speed`].
    elf_height: f32,
    elf_height_prev: f32,
    /// The elf's own vertical speed while off the ground, in meters a
    /// second, positive upward.
    jump_speed: f32,
    elf_input: ElfInput,
    elf_animator: Animator<Elf, ElfState>,
    scrubbed_animator: Animator<Elf, ScrubbedState>,
    butterfly_animator: Animator<Butterfly, FlyingState>,
    hits: u32,
    /// True while a hurt patch already held the elf, so leaving and
    /// returning to the same patch counts as a new hit.
    in_patch: bool,
    /// Whether the pointer is held; a click takes it, escape frees it.
    holding: bool,
    /// The camera's turn around the elf, and its tilt, both in radians.
    camera_yaw: f32,
    camera_pitch: f32,
    /// The last state change the panel names.
    last_event: &'static str,
}

impl Scene {
    fn init(_ctx: &mut InitContext<'_, Scene>) -> Result<Self, Error> {
        Ok(Self {
            elf_pos: ELF_START,
            elf_prev: ELF_START,
            elf_yaw: 0.0,
            elf_height: 0.0,
            elf_height_prev: 0.0,
            jump_speed: 0.0,
            elf_input: ElfInput::default(),
            elf_animator: Animator::new(),
            scrubbed_animator: Animator::new(),
            butterfly_animator: Animator::new(),
            hits: 0,
            in_patch: false,
            holding: false,
            camera_yaw: 0.0,
            camera_pitch: 0.0,
            last_event: "none yet",
        })
    }

    /// Turns the camera by how far the pointer moves sideways and upward,
    /// [`CAMERA_PITCH_RANGE`] holding how far it tilts.
    fn steer_camera(&mut self, ctx: &mut FrameContext<'_, Scene>) {
        self.camera_yaw -= ctx.axis(Axis::CameraYaw);
        self.camera_pitch = (self.camera_pitch + ctx.axis(Axis::CameraPitch))
            .clamp(CAMERA_PITCH_RANGE.start, CAMERA_PITCH_RANGE.end);
    }

    /// Turns `elf_yaw` toward the heading `ctx` reads, relative to the
    /// camera's own turn, and moves `elf_pos` along it; the speed it moves
    /// at, a fraction of [`ELF_SPEED`], held at [`WALK_CAP`] until
    /// `Button::Run` is held.
    fn advance(&mut self, ctx: &mut TickContext<'_, Scene>) -> f32 {
        let control = ctx.axis2(Move::Walk).clamp_length_max(1.0);
        let turn = Quat::from_rotation_y(self.camera_yaw);
        let heading = turn * Vec3::X * control.x + turn * Vec3::NEG_Z * control.y;
        let dt = ctx.dt().as_secs_f32();
        if let Some(direction) = heading.try_normalize() {
            let wanted = direction.x.atan2(direction.z);
            let turn = (wanted - self.elf_yaw + core::f32::consts::PI).rem_euclid(TAU)
                - core::f32::consts::PI;
            self.elf_yaw += turn.clamp(-TURN_RATE * dt, TURN_RATE * dt);
        }
        let cap = if ctx.down(Button::Run) { 1.0 } else { WALK_CAP };
        self.elf_pos += heading * cap * ELF_SPEED * dt;
        heading.length() * cap
    }

    /// Integrates [`Self::elf_height`] under [`GRAVITY`] from
    /// [`Self::jump_speed`], held at the ground; `true` the tick it
    /// returns there from above it.
    fn fall(&mut self, dt: f32) -> bool {
        let off_ground = self.elf_height > 0.0;
        self.jump_speed -= GRAVITY * dt;
        self.elf_height = (self.elf_height + self.jump_speed * dt).max(0.0);
        if self.elf_height == 0.0 {
            self.jump_speed = 0.0;
        }
        off_ground && self.elf_height == 0.0
    }

    /// The hurt patch `elf_pos` stands inside, if any.
    fn patch_underfoot(&self) -> Option<Vec3> {
        HURT_PATCHES
            .into_iter()
            .find(|&patch| self.elf_pos.distance(patch) < HURT_RADIUS)
    }

    /// Reads the controls and moves the elf, filling [`Self::elf_input`]
    /// for [`ElfState`] to read.
    fn tick_elf(&mut self, ctx: &mut TickContext<'_, Scene>) {
        let grounded = matches!(
            self.elf_animator.state(),
            ElfState::Idle | ElfState::Locomotion
        );

        self.elf_input.speed = self.advance(ctx);
        self.elf_input.attack = ctx.pressed(Button::Attack);
        self.elf_input.jump = ctx.pressed(Button::Jump);
        self.elf_input.dance = ctx.pressed(Button::Dance);

        self.elf_input.near_seat = self.elf_pos.distance(SEAT_POSITION) < SEAT_INTERACT_RADIUS;
        self.elf_input.interact = ctx.pressed(Button::Interact);
        if self.elf_input.interact && grounded && self.elf_input.near_seat {
            self.elf_pos = SEAT_SPOT;
            self.elf_yaw = SEAT_FACING;
        }

        let underfoot = self.patch_underfoot();
        let entered_patch = underfoot.is_some() && !self.in_patch;
        self.in_patch = underfoot.is_some();
        self.hits += u32::from(entered_patch);
        self.elf_input.hit = entered_patch && self.hits < FATAL_HITS;
        self.elf_input.dying = entered_patch && self.hits >= FATAL_HITS;
        if entered_patch {
            self.last_event = match self.elf_input.dying {
                true => "elf died",
                false => "elf hit",
            };
        }
    }

    /// Starts a new [`Animator`] over the elf's own state, its position and
    /// hit count reset with it.
    fn restart_elf(&mut self) {
        self.elf_animator = Animator::new();
        self.elf_pos = ELF_START;
        self.elf_prev = ELF_START;
        self.elf_yaw = 0.0;
        self.elf_height = 0.0;
        self.elf_height_prev = 0.0;
        self.jump_speed = 0.0;
        self.elf_input = ElfInput::default();
        self.hits = 0;
        self.in_patch = false;
        self.last_event = "new elf started";
    }

    fn panel(&self, ctx: &mut FrameContext<'_, Scene>) {
        let state = match self.elf_animator.state() {
            ElfState::Idle => "idle",
            ElfState::Locomotion if self.elf_input.speed > WALK_CAP => "running",
            ElfState::Locomotion => "walking",
            ElfState::Attack => "attacking",
            ElfState::Hit => "hit",
            ElfState::Death => "dead",
            ElfState::SitDown => "sitting down",
            ElfState::Sit => "sitting",
            ElfState::StandUp => "standing up",
            ElfState::Jump => "jumping",
            ElfState::Dance => "dancing",
        };
        ctx.ui(|ui| {
            egui::Frame::new()
                .fill(egui::Color32::from_black_alpha(PANEL_BACKDROP))
                .inner_margin(PANEL_PADDING)
                .corner_radius(f32::from(PANEL_PADDING))
                .show(ui, |ui| {
                    ui.heading(panel_text(format!("elf is {state}")));
                    ui.label(panel_text(format!(
                        "hits taken {} of the {} red patches hurt for, {}",
                        self.hits, FATAL_HITS, self.last_event
                    )));
                    ui.label(panel_text(match self.elf_animator.transitioning() {
                        true => "fading between clips",
                        false => "one clip playing",
                    }));
                    ui.add_space(f32::from(PANEL_PADDING));
                    egui::Grid::new("controls").show(ui, |ui| {
                        for (key, does) in CONTROLS {
                            ui.label(panel_text(key));
                            ui.label(panel_text(does));
                            ui.end_row();
                        }
                    });
                });
        });
    }

    /// A prompt over the seat, each hurt patch, and the scrubbed elf,
    /// naming what a player finds there; the seat's own prompt names the
    /// live binding of `Button::Interact` by its own name, not one fixed
    /// in the code, and is absent while the elf sits on it.
    fn draw_prompts(&self, ctx: &mut FrameContext<'_, Scene>, camera: Camera) {
        let sit_key = ctx
            .bindings(Button::Interact)
            .into_iter()
            .next()
            .map_or_else(|| "interact".to_owned(), |binding| binding.to_string());
        let sit = ctx.text_layout(
            &format!("{sit_key} sits"),
            egui::FontId::proportional(PROMPT_SIZE),
        );
        let hurts = ctx.text_layout("hurts", egui::FontId::proportional(PROMPT_SIZE));
        let walk_closer = ctx.text_layout("walk closer", egui::FontId::proportional(PROMPT_SIZE));

        let mut prompts = vec![(
            SCRUBBED_ELF_POSITION + Vec3::Y * (ELF_HEIGHT + PROMPT_LIFT),
            walk_closer,
        )];
        if !self.elf_animator.state().seated() {
            prompts.push((
                SEAT_POSITION + Vec3::Y * (SEAT_HEAD_HEIGHT + PROMPT_LIFT),
                sit,
            ));
        }
        prompts.extend(HURT_PATCHES.map(|patch| (patch + Vec3::Y * PROMPT_LIFT, hurts.clone())));

        let window_size = ctx.window_size();
        let pixels_per_point = ctx.pixels_per_point();
        ctx.ui(|ui| {
            let painter = ui.painter();
            for (point, galley) in prompts {
                let Some(pixel) = camera.pixel_of(point, window_size) else {
                    continue;
                };
                let at = logical(pixel, pixels_per_point);
                let ink = galley.mesh_bounds;
                let pos = egui::pos2(at.x - ink.center().x, at.y - ink.center().y);
                let backdrop = egui::Rect::from_center_size(
                    at,
                    ink.size() + egui::Vec2::splat(PROMPT_PADDING * 2.0),
                );
                painter.rect_filled(
                    backdrop,
                    PROMPT_PADDING,
                    egui::Color32::from_black_alpha(PANEL_BACKDROP),
                );
                painter.galley(pos, galley, PANEL_TEXT_COLOR);
            }
        });
    }
}

impl Game for Scene {
    type Meshes = Shape;
    type Sounds = NoSounds;
    type InputActions = Controls;
    type Skyboxes = Sky;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Scene>) {
        self.elf_prev = self.elf_pos;
        self.elf_height_prev = self.elf_height;

        if ctx.pressed(Button::Restart) {
            self.restart_elf();
        }
        if ctx.pressed(Button::Hold) {
            self.holding = true;
        }
        if ctx.pressed(Button::Release) {
            self.holding = false;
        }

        self.elf_input.landed = self.fall(ctx.dt().as_secs_f32());
        self.tick_elf(ctx);
        ctx.animate(Elf, &mut self.elf_animator, &self.elf_input);

        if self.elf_animator.entered(ElfState::Jump) {
            self.jump_speed = JUMP_LAUNCH_SPEED;
        }
        if self.elf_animator.left(ElfState::StandUp) {
            self.last_event = "elf stood up";
        }
        if self.elf_animator.entered(ElfState::Sit) {
            self.last_event = "elf sat down";
        }
        if self.elf_animator.entered(ElfState::Death) {
            self.last_event = "elf died";
        }

        let scrubbed_input = ScrubbedInput {
            settled: settled_at(self.elf_pos.distance(SCRUBBED_ELF_POSITION)),
        };
        ctx.animate(Elf, &mut self.scrubbed_animator, &scrubbed_input);
        ctx.animate(Butterfly, &mut self.butterfly_animator, &());
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, Scene>) {
        self.steer_camera(ctx);

        let alpha = ctx.alpha();
        let elf_pos = self.elf_prev.lerp(self.elf_pos, alpha);
        let elf_height = self.elf_height_prev + (self.elf_height - self.elf_height_prev) * alpha;
        let (butterfly_pos, butterfly_yaw) = butterfly_pose(ctx.elapsed().as_secs_f32());

        let camera = orbit_camera(elf_pos, self.camera_yaw, self.camera_pitch);
        ctx.set_camera(camera);
        ctx.set_cursor(if self.holding {
            Cursor::Held
        } else {
            Cursor::Arrow
        });
        ctx.set_skybox(Sky::Day);
        ctx.set_exposure(3.0);
        ctx.set_bloom(0.2);
        ctx.light(Light::directional(SUN_DIRECTION, SUN_COLOR).shadow());
        ctx.light(
            Light::point(
                LAMP_POST_POSITION + Vec3::Y * (LAMP_POST_HEIGHT + LAMP_HEAD_GAP * 0.5),
                LAMP_LIGHT_COLOR,
                LAMP_LIGHT_RANGE,
            )
            .shadow(),
        );
        ctx.light(
            Light::spot(Spot {
                position: SPOT_POSITION,
                direction: SPOT_DIRECTION,
                color: SPOT_COLOR,
                range: SPOT_RANGE,
                angle: SPOT_ANGLE,
            })
            .shadow(),
        );
        ctx.light(
            Light::point(butterfly_pos, BUTTERFLY_LIGHT_COLOR, BUTTERFLY_LIGHT_RANGE).shadow(),
        );

        ctx.draw(
            Plane
                .at(Transform::from_scale(Vec3::new(
                    GROUND_SIZE,
                    1.0,
                    GROUND_SIZE,
                )))
                .material(Material::lit(GROUND_COLOR)),
        );
        for patch in HURT_PATCHES {
            ctx.draw(
                Plane
                    .at(Transform::from_scale_rotation_translation(
                        Vec3::splat(HURT_RADIUS * 2.0),
                        Quat::IDENTITY,
                        patch,
                    ))
                    .material(Material::lit(HURT_COLOR)),
            );
        }
        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::new(SEAT_FOOTPRINT, SEAT_HEIGHT, SEAT_FOOTPRINT),
                Quat::IDENTITY,
                SEAT_POSITION + Vec3::Y * SEAT_HEIGHT * 0.5,
            ))
            .material(Material::lit(SEAT_COLOR)),
        );
        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::new(LAMP_POST_THICKNESS, LAMP_POST_HEIGHT, LAMP_POST_THICKNESS),
                Quat::IDENTITY,
                LAMP_POST_POSITION + Vec3::Y * LAMP_POST_HEIGHT * 0.5,
            ))
            .material(Material::lit(LAMP_POST_COLOR)),
        );
        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::splat(LAMP_HEAD_SIZE),
                Quat::IDENTITY,
                LAMP_POST_POSITION
                    + Vec3::Y * (LAMP_POST_HEIGHT + LAMP_HEAD_GAP + LAMP_HEAD_SIZE * 0.5),
            ))
            .material(Material::color(Color::BLACK).emissive(LAMP_LIGHT_COLOR)),
        );
        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::splat(SPOT_FIXTURE_SIZE),
                Quat::IDENTITY,
                SPOT_POSITION + Vec3::Y * SPOT_FIXTURE_SIZE * 0.5,
            ))
            .material(Material::lit(SPOT_FIXTURE_COLOR)),
        );

        ctx.draw(
            Elf.at(Transform::from_rotation_translation(
                Quat::from_rotation_y(self.elf_yaw),
                elf_pos + Vec3::Y * elf_height,
            ))
            .posed(&self.elf_animator),
        );
        ctx.draw(
            Elf.at(Transform::from_rotation_translation(
                Quat::from_rotation_y(core::f32::consts::PI),
                SCRUBBED_ELF_POSITION,
            ))
            .posed(&self.scrubbed_animator),
        );
        ctx.draw(
            Butterfly
                .at(Transform::from_rotation_translation(
                    Quat::from_rotation_y(butterfly_yaw),
                    butterfly_pos,
                ))
                .posed(&self.butterfly_animator)
                .material(Material::lit(Color::WHITE).emissive(BUTTERFLY_EMISSIVE)),
        );

        self.draw_prompts(ctx, camera);
        self.panel(ctx);
    }
}

fn main() {
    run(
        Config::new("Mirage: animation")
            .with_size(WINDOW_WIDTH, WINDOW_HEIGHT)
            .with_assets([ELF_SOURCE, BUTTERFLY_SOURCE]),
        Scene::init,
    );
}