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
//! One scene, every knob live: `Sky` pairs a whole scene's sky with its
//! sun. `Dawn`, `Noon`, `Dusk` and `Night` each pair a gradient with a
//! sun of its own color and direction; six loaded images each pair with
//! a sun that fits it, from a bright sky's own bright sun to two space
//! images lit by none; `Default` is the engine's own grey sky and white
//! sun. The lamp and the spotlight add their own light beside it, and a
//! material and the post chain read from sliders too.
//!
//! Hold the right mouse button and drag to look around, `W`/`A`/`S`/`D`
//! to move along the view and to its side, `Space`/`Left Shift` up and
//! down, and the wheel to scale how far each move goes; the `eye` stays
//! above the ground plane wherever it moves.
//!
//! The ground draws the shading, relief and emissive map pairs, left
//! plain and right checked on or off, the front sphere whose material a
//! set of sliders resolves new each frame, a row where each sphere's own
//! roughness rises so what the sky reflects reads apart across it, a
//! cloth displaced by a wave and drawn from both its sides, and a
//! pulsing sphere beside three pillars a light can shadow. The controls
//! stay in a side area of fixed width, not the bare UI layer, so the
//! flat grey default sky does not read as a slab under a row that spans
//! the whole window.

use mirage_engine::prelude::*;

/// Ground plane's side length, in meters.
const GROUND_SIZE: f32 = 18.0;

/// A pair's two halves are drawn this far either side of its row's center,
/// in meters.
const PAIR_HALF_SPACING: f32 = 1.0;

/// Depth, along `z`, of each map pair.
const SHADING_Z: f32 = 3.4;
const RELIEF_Z: f32 = 1.8;
const EMISSIVE_Z: f32 = 0.2;

/// A sphere's radius, so its center is a radius above the ground.
const SPHERE_RADIUS: f32 = 0.5;
/// An emissive cube's edge length.
const CUBE_SIZE: f32 = 0.85;

/// The front sphere's position and scale, ahead of every pair and larger,
/// so its live material reads apart from them.
const FRONT_POSITION: Vec3 = Vec3::new(0.0, 0.7, -1.6);
const FRONT_SCALE: f32 = 1.4;

/// Sphere density every built sphere in this scene shares.
const SPHERE_SUBDIVISIONS: u32 = 3;

/// How many draws the reflection row makes, and the meters between their
/// centers.
const REFLECT_ROW_COUNT: usize = 5;
const REFLECT_ROW_SPACING: f32 = 1.5;
const REFLECT_ROW_Z: f32 = -1.6;
const REFLECT_ROW_RADIUS: f32 = 0.55;

const GROUND_COLOR: Color = Color::rgb(0.24, 0.25, 0.22);
const SHADING_TINT: Color = Color::rgb(0.55, 0.55, 0.6);
const RELIEF_TINT: Color = Color::rgb(0.5, 0.45, 0.35);
const EMISSIVE_BASE: Color = Color::rgb(0.04, 0.04, 0.05);
const EMISSIVE_GLOW: Color = Color::rgb(3.2, 2.2, 0.7);

/// Texel side length of every generated map: coarse enough that each
/// checker cell reads as a distinct part on a sphere or a cube face.
const MAP_SIZE: UVec2 = UVec2::new(64, 64);

/// Checker cell width, in texels, for the shading map.
const SHADING_CELL: u32 = 8;
/// The shading checker's two states: occlusion, roughness and metallic —
/// one square low across all three, the other full across all three.
const SHADING_LOW: [u8; 3] = [70, 40, 15];
const SHADING_HIGH: [u8; 3] = [255, 225, 235];

/// Checker cell width, in texels, for the emissive map.
const EMISSIVE_CELL: u32 = 6;

/// Wave count the relief's texture repeats across its map, and the peak
/// slope of its surface, in height over distance.
const BUMP_WAVES: f32 = 6.0;
const BUMP_SLOPE: f32 = 1.15;

/// `BannerCloth`'s width and height, in meters.
const BANNER_WIDTH: f32 = 1.1;
const BANNER_HEIGHT: f32 = 0.7;

/// Columns `BannerCloth` splits into, so its wave curves smoothly.
const BANNER_COLUMNS: u32 = 10;

/// Where the pillars, the pole, the cloth and the pulsing sphere are
/// placed, added to every one of their own positions: apart from the
/// pairs and the reflection row, so a light's shadow has clear ground to
/// land on.
const OUTPOST: Vec3 = Vec3::new(-4.6, 0.0, -0.8);

const PILLARS: [(Vec3, Vec3); 3] = [
    (Vec3::new(-1.8, 0.6, -0.6), Vec3::new(0.6, 1.2, 0.6)),
    (Vec3::new(0.4, 0.4, -1.6), Vec3::new(0.5, 0.8, 0.5)),
    (Vec3::new(1.7, 0.9, 0.4), Vec3::new(0.55, 1.8, 0.55)),
];

const POLE_POSITION: Vec3 = Vec3::new(-2.6, 1.0, 0.4);
const POLE_SCALE: Vec3 = Vec3::new(0.12, 2.0, 0.12);
const BANNER_MOUNT: Vec3 = Vec3::new(-2.54, 1.55, 0.46);

const FIELD_ORB_POSITION: Vec3 = Vec3::new(1.3, 1.1, 1.6);
const FIELD_ORB_SCALE: f32 = 0.7;

/// The lamp's fixed position and reach, in meters.
const LAMP_POSITION: Vec3 = Vec3::new(2.4, 1.4, -3.0);
const LAMP_RANGE: f32 = 5.0;

/// The spotlight's fixed placement: where it is placed, which way its
/// cone points, its reach in meters and its width in radians.
const SPOT_POSITION: Vec3 = Vec3::new(-3.4, 3.0, 1.6);
const SPOT_DIRECTION: Vec3 = Vec3::new(0.55, -1.0, -1.0);
const SPOT_RANGE: f32 = 7.0;
const SPOT_ANGLE: f32 = 0.5;

/// The camera's vertical field of view, in degrees.
const CAMERA_FOV: f32 = 46.0;
/// Where the camera starts, and the `yaw` and the pitch, in radians, it
/// starts turned to.
const START_EYE: Vec3 = Vec3::new(-0.6, 2.2, 9.0);
const START_YAW: f32 = 0.0;
const START_PITCH: f32 = -0.15;
/// How far short of straight up or down the pitch may turn, in radians,
/// where a turn alone reads as nothing.
const PITCH_LIMIT: f32 = 1.5;
/// The `eye`'s least height above the ground plane, in meters: held above
/// zero so a move can never take it below.
const MIN_EYE_HEIGHT: f32 = 0.3;
/// Radians the pointer's own motion turns the view by, per physical
/// pixel it crosses, before the axis it reads through bounds it: a drag
/// across the whole window turns about a quarter turn.
const LOOK_SENSITIVITY: f32 = core::f32::consts::FRAC_PI_2 / 1280.0;
/// Meters a move key covers per second, at [`Playground::speed_scale`]'s
/// own default.
const MOVE_SPEED: f32 = 4.0;
/// The factor one full wheel step multiplies the move speed apart from.
const SPEED_STEP: f32 = 1.5;
/// The move speed's own least and most, as a factor of [`MOVE_SPEED`].
const MIN_SPEED_SCALE: f32 = 0.2;
const MAX_SPEED_SCALE: f32 = 5.0;

/// Bloom this scene starts at, past the engine's own default: enough that
/// [`EMISSIVE_GLOW`] and the brightest lights scatter right away.
const START_BLOOM: f32 = 0.25;
const START_EXPOSURE: f32 = 1.0;

/// The sky a frame that keeps [`Sky::Default`] draws and is lit by: the
/// same flat grey the engine falls back to when a frame sets none.
const DEFAULT_SKY: Color = Color::rgb(0.1, 0.1, 0.1);

/// The fraction of its own light each loaded sky lands and reflects,
/// through [`SkyboxData::lit_by`]: the bright images fixed low, since an
/// image read too bright under the frame's own lights at its default
/// `1.0`; the dim images fixed more, since the scene read too dark under
/// them at the bright images' value.
const CLEAR_SKY_LIGHT: f32 = 0.35;
const CLASSIC_SKY_LIGHT: f32 = 0.35;
const DAWN_SKY_LIGHT: f32 = 0.3;
const SINISTER_SKY_LIGHT: f32 = 0.6;
const LIGHT_BLUE_STARS_LIGHT: f32 = 0.8;
const BLUE_STARS_LIGHT: f32 = 0.8;

/// The shading pair's plain half: a sphere given the shared shading
/// material and no map.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct ShadingPlain;

impl Mesh for ShadingPlain {
    fn build(&self, assets: &Assets) -> MeshData {
        sphere_with_material(assets, shading_material())
    }
}

/// The shading pair's mapped half: the same sphere and material, with its
/// shading map (occlusion, roughness and metallic) baked in.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct ShadingMapped;

impl Mesh for ShadingMapped {
    fn build(&self, assets: &Assets) -> MeshData {
        sphere_with_material(assets, shading_material()).with_shading(shading_checker())
    }
}

/// The relief pair's plain half.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct ReliefPlain;

impl Mesh for ReliefPlain {
    fn build(&self, assets: &Assets) -> MeshData {
        sphere_with_material(assets, relief_material())
    }
}

/// The relief pair's mapped half: the same sphere and material, with its
/// relief map baked in.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct ReliefMapped;

impl Mesh for ReliefMapped {
    fn build(&self, assets: &Assets) -> MeshData {
        sphere_with_material(assets, relief_material()).with_relief(relief_bumps())
    }
}

/// The emissive pair's plain half.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct EmissivePlain;

impl Mesh for EmissivePlain {
    fn build(&self, assets: &Assets) -> MeshData {
        cube_with_material(assets, emissive_material())
    }
}

/// The emissive pair's mapped half: the same cube and material, with its
/// emissive map baked in.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct EmissiveMapped;

impl Mesh for EmissiveMapped {
    fn build(&self, assets: &Assets) -> MeshData {
        cube_with_material(assets, emissive_material()).with_emissive_map(emissive_checker())
    }
}

/// The front sphere: a draw overrides its material new every frame, in
/// place of a baked one.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct Front;

impl Mesh for Front {
    fn build(&self, assets: &Assets) -> MeshData {
        Sphere {
            subdivisions: SPHERE_SUBDIVISIONS,
        }
        .build(assets)
    }
}

/// `BannerCloth`: a mesh split into columns along its span and placed at
/// its `x = 0` edge, so `Banner`'s wave curves it, not a single flat
/// quad. Its triangles are built twice: once as authored and once in the
/// other order, with the normal turned around, so the cloth draws from
/// both sides however its wave curves it.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
struct BannerCloth;

impl Mesh for BannerCloth {
    fn build(&self, _: &Assets) -> MeshData {
        banner_mesh()
    }
}

// Everything this game draws: the ground plane, each map pair's plain and
// mapped half, the front sphere with its own live material, the built-in
// primitives the reflection row and the pillars beside it place per draw,
// and the displaced cloth.
meshes! {
    enum Shape {
        Plane,
        Sphere,
        Cube,
        ShadingPlain,
        ShadingMapped,
        ReliefPlain,
        ReliefMapped,
        EmissivePlain,
        EmissiveMapped,
        Front,
        BannerCloth,
    }
}

fn sphere_with_material(assets: &Assets, material: Material) -> MeshData {
    Sphere {
        subdivisions: SPHERE_SUBDIVISIONS,
    }
    .build(assets)
    .with_material(material)
}

fn cube_with_material(assets: &Assets, material: Material) -> MeshData {
    Cube.build(assets).with_material(material)
}

fn shading_material() -> Material {
    Material::lit(SHADING_TINT).roughness(0.5).metallic(0.5)
}

fn relief_material() -> Material {
    Material::lit(RELIEF_TINT).roughness(0.35)
}

fn emissive_material() -> Material {
    Material::color(EMISSIVE_BASE).emissive(EMISSIVE_GLOW)
}

/// A shading map whose checker goes between low occlusion, roughness and
/// metallic and full occlusion, roughness and metallic, so all three read
/// apart across [`ShadingMapped`].
fn shading_checker() -> ShadingData {
    ShadingData::rgba8(
        MAP_SIZE,
        checker_pixels(MAP_SIZE, SHADING_CELL, SHADING_LOW, SHADING_HIGH),
    )
}

/// An emissive map whose checker goes between full glow and none, so
/// [`EMISSIVE_GLOW`] shapes across [`EmissiveMapped`] instead of casting
/// whole.
fn emissive_checker() -> TextureData {
    TextureData::rgba8(
        MAP_SIZE,
        checker_pixels(MAP_SIZE, EMISSIVE_CELL, [0, 0, 0], [255, 255, 255]),
    )
}

fn checker_pixels(size: UVec2, cell: u32, low: [u8; 3], high: [u8; 3]) -> Vec<u8> {
    let mut pixels = Vec::with_capacity((size.x * size.y * 4) as usize);
    for y in 0..size.y {
        for x in 0..size.x {
            let on = ((x / cell) + (y / cell)).is_multiple_of(2);
            let [red, green, blue] = if on { high } else { low };
            pixels.extend_from_slice(&[red, green, blue, u8::MAX]);
        }
    }
    pixels
}

/// A relief whose normals turn across a wave that repeats over the map:
/// each texel's slope comes from the partial derivatives of a
/// `sin(u) * sin(v)` height field at `BUMP_SLOPE`'s peak, computed at that
/// texel and not sampled from any other.
fn relief_bumps() -> ReliefData {
    let size = MAP_SIZE;
    let turns = core::f32::consts::TAU * BUMP_WAVES;
    let mut pixels = Vec::with_capacity((size.x * size.y * 4) as usize);
    for y in 0..size.y {
        for x in 0..size.x {
            let u = (x as f32 + 0.5) / size.x as f32;
            let v = (y as f32 + 0.5) / size.y as f32;
            let slope_u = BUMP_SLOPE * (turns * u).cos() * (turns * v).sin();
            let slope_v = BUMP_SLOPE * (turns * u).sin() * (turns * v).cos();
            let normal = Vec3::new(-slope_u, -slope_v, 1.0).normalize();
            let encode = |signed: f32| ((signed * 0.5 + 0.5) * 255.0).round() as u8;
            pixels.extend_from_slice(&[encode(normal.x), encode(normal.y), encode(normal.z), 0]);
        }
    }
    ReliefData::normals(size, pixels)
}

/// `BannerCloth`'s vertices and indices, built twice over: the columns as
/// authored, facing `+Z`, and the same columns again facing `-Z`, their
/// triangles in the other order so both draw front side out.
fn banner_mesh() -> MeshData {
    let mut vertices = Vec::with_capacity(((BANNER_COLUMNS + 1) * 4) as usize);
    for normal in [Vec3::Z, Vec3::NEG_Z] {
        for column in 0..=BANNER_COLUMNS {
            let u = column as f32 / BANNER_COLUMNS as f32;
            let x = u * BANNER_WIDTH;
            for v in [0.0, 1.0] {
                vertices.push(Vertex::new(
                    Vec3::new(x, -v * BANNER_HEIGHT, 0.0),
                    normal,
                    Vec2::new(u, v),
                ));
            }
        }
    }

    let side = BANNER_COLUMNS + 1;
    let mut indices = Vec::with_capacity((BANNER_COLUMNS * 12) as usize);
    for column in 0..BANNER_COLUMNS {
        let top_left = column * 2;
        let bottom_left = top_left + 1;
        let top_right = top_left + 2;
        let bottom_right = top_left + 3;
        indices.extend([
            bottom_left,
            bottom_right,
            top_right,
            bottom_left,
            top_right,
            top_left,
        ]);

        let back = side * 2;
        indices.extend([
            back + top_right,
            back + bottom_right,
            back + bottom_left,
            back + top_left,
            back + top_right,
            back + bottom_left,
        ]);
    }

    MeshData::new(vertices, indices)
}

/// Displaced by a wave that grows away from its `x = 0` edge; casts the
/// shadow of where it was placed, unmoved by its own wave. Its one value
/// is the clock its wave slides on.
#[derive(Default, ShaderValues)]
struct Banner {
    time: f32,
}

impl SurfaceStyle for Banner {
    const PASS: DrawPass = DrawPass::Opaque;
    const DISPLACE: Option<&'static str> = Some(include_str!("material_playground_banner.wgsl"));
}

/// A surface that reads no light of the scene's own: it draws its own
/// pulsing tint, added over what is behind it, through the color it pulses
/// through and the clock the pulse is timed by.
#[derive(Default, ShaderValues)]
struct Field {
    tint: Color,
    time: f32,
}

impl SurfaceStyle for Field {
    const PASS: DrawPass = DrawPass::Additive;
    const SURFACE: Option<&'static str> = Some(include_str!("material_playground_field.wgsl"));
}

surface_styles! { enum Looks { Banner, Field } }

/// A whole scene lighting choice: it names a sky and, kept with it, the
/// sun that lights the scene, so a choice cannot leave the two apart.
/// `Dawn`, `Noon`, `Dusk` and `Night` each pair a gradient with a sun of
/// its own color and direction; `Clear`, `Classic`, `ImageDawn` and
/// `Sinister` each pair a loaded image with a sun that fits it, and
/// `LightBlueStars` and `BlueStars` pair a loaded space image with none;
/// `Default` is the engine's own grey sky and white sun.
///
/// [`Skyboxes`] proves every value at startup, so it must be [`Eq`] and
/// [`Hash`] over a fixed [`Skyboxes::catalog`] — a sky and sun a player
/// set to any color and direction live could never meet, since `f32` is
/// neither. This fixed, named set is the shape this file chose in its
/// place: the side area offers it as one row, and shows the chosen sky's
/// own light and its sun's own strength as text, read only, rather than
/// controls a game could not build from. See this example's report for
/// what that choice costs.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum Sky {
    Dawn,
    Noon,
    Dusk,
    Night,
    Clear,
    Classic,
    ImageDawn,
    Sinister,
    LightBlueStars,
    BlueStars,
    Default,
}

impl Sky {
    const ALL: [Sky; 11] = [
        Self::Dawn,
        Self::Noon,
        Self::Dusk,
        Self::Night,
        Self::Clear,
        Self::Classic,
        Self::ImageDawn,
        Self::Sinister,
        Self::LightBlueStars,
        Self::BlueStars,
        Self::Default,
    ];

    fn name(self) -> &'static str {
        match self {
            Self::Dawn => "dawn",
            Self::Noon => "noon",
            Self::Dusk => "dusk",
            Self::Night => "night",
            Self::Clear => "clear day",
            Self::Classic => "classic",
            Self::ImageDawn => "dawn image",
            Self::Sinister => "sinister night",
            Self::LightBlueStars => "light blue stars",
            Self::BlueStars => "blue stars",
            Self::Default => "default",
        }
    }

    /// The fraction of its own light this sky lands and reflects, through
    /// [`SkyboxData::lit_by`]: fixed per choice, so a bright one does not
    /// read too bright, and a dark one does not read too dark, under the
    /// frame's own lights.
    fn light(self) -> f32 {
        match self {
            Self::Dawn => 0.4,
            Self::Noon => 0.5,
            Self::Dusk => 0.35,
            Self::Night => 0.3,
            Self::Clear => CLEAR_SKY_LIGHT,
            Self::Classic => CLASSIC_SKY_LIGHT,
            Self::ImageDawn => DAWN_SKY_LIGHT,
            Self::Sinister => SINISTER_SKY_LIGHT,
            Self::LightBlueStars => LIGHT_BLUE_STARS_LIGHT,
            Self::BlueStars => BLUE_STARS_LIGHT,
            Self::Default => 1.0,
        }
    }

    /// The sun this choice pairs with its sky: direction, color and
    /// strength resolved together, so a choice cannot leave them apart.
    /// `None` for the two space images, which pair with no sun at all.
    fn sun(self) -> Option<(Vec3, Color, f32)> {
        match self {
            Self::Dawn => Some((
                Vec3::new(-1.0, -0.15, 0.05),
                Color::rgb(1.0, 0.7, 0.45),
                1.4,
            )),
            Self::Noon => Some((
                Vec3::new(-0.15, -1.0, -0.1),
                Color::rgb(1.0, 1.0, 0.98),
                1.6,
            )),
            Self::Dusk => Some((
                Vec3::new(1.0, -0.15, 0.05),
                Color::rgb(1.0, 0.55, 0.25),
                1.2,
            )),
            Self::Night => Some((
                Vec3::new(-0.3, -0.7, -0.6),
                Color::rgb(0.55, 0.65, 0.85),
                0.15,
            )),
            Self::Clear => Some((
                Vec3::new(-0.2, -1.0, -0.15),
                Color::rgb(1.0, 0.98, 0.9),
                1.5,
            )),
            Self::Classic => Some((
                Vec3::new(-0.4, -0.9, -0.2),
                Color::rgb(1.0, 0.95, 0.85),
                1.3,
            )),
            Self::ImageDawn => Some((Vec3::new(-1.0, -0.2, 0.1), Color::rgb(1.0, 0.75, 0.5), 1.1)),
            Self::Sinister => Some((Vec3::new(0.4, -0.5, -0.7), Color::rgb(0.4, 0.5, 0.75), 0.1)),
            Self::LightBlueStars | Self::BlueStars => None,
            Self::Default => Some((Vec3::new(-0.4, -1.0, -0.6), Color::WHITE, 1.0)),
        }
    }

    /// The color the sky reads under the horizon, through
    /// [`SkyboxData::with_ground`]: the floor as lit under this choice's own
    /// sun and [`Self::light`], so it moves with them, not only with the
    /// image. `None` for the gradient skies and `Default`, which need no
    /// ground, and for the two space images, which hold space below the
    /// horizon as well.
    fn ground(self) -> Option<Color> {
        match self {
            Self::Clear => Some(Color::rgb(0.501, 0.517, 0.449)),
            Self::Classic => Some(Color::rgb(0.420, 0.405, 0.379)),
            Self::ImageDawn => Some(Color::rgb(0.073, 0.053, 0.032)),
            Self::Sinister => Some(Color::rgb(0.012, 0.014, 0.020)),
            Self::Dawn
            | Self::Noon
            | Self::Dusk
            | Self::Night
            | Self::LightBlueStars
            | Self::BlueStars
            | Self::Default => None,
        }
    }
}

impl Catalog for Sky {
    fn catalog() -> Vec<Self> {
        Self::ALL.to_vec()
    }
}

impl Skyboxes for Sky {
    fn build(&self, assets: &Assets) -> SkyboxData {
        let sky = match self {
            Self::Dawn => SkyboxData::gradient(
                Color::rgb(0.55, 0.55, 0.75),
                Color::rgb(0.95, 0.6, 0.35),
                Color::rgb(0.12, 0.08, 0.06),
            ),
            Self::Noon => SkyboxData::gradient(
                Color::rgb(0.2, 0.45, 0.85),
                Color::rgb(0.75, 0.82, 0.9),
                Color::rgb(0.3, 0.3, 0.28),
            ),
            Self::Dusk => SkyboxData::gradient(
                Color::rgb(0.18, 0.1, 0.3),
                Color::rgb(0.85, 0.35, 0.2),
                Color::rgb(0.03, 0.02, 0.03),
            ),
            Self::Night => SkyboxData::gradient(
                Color::rgb(0.02, 0.02, 0.06),
                Color::rgb(0.05, 0.05, 0.1),
                Color::rgb(0.0, 0.0, 0.0),
            ),
            Self::Clear => assets.skybox("sky-clear"),
            Self::Classic => assets.skybox("sky-classic"),
            Self::ImageDawn => assets.skybox("sky-dawn"),
            Self::Sinister => assets.skybox("sky-sinister"),
            Self::LightBlueStars => assets.skybox("sky-stars-lightblue"),
            Self::BlueStars => assets.skybox("sky-stars-blue"),
            Self::Default => SkyboxData::gradient(DEFAULT_SKY, DEFAULT_SKY, DEFAULT_SKY),
        };
        let sky = match self.ground() {
            Some(ground) => sky.with_ground(ground),
            None => sky,
        };

        sky.lit_by(self.light())
    }
}

/// `color` scaled by `strength`, the value a [`Light`] reads.
fn scaled(color: Color, strength: f32) -> Color {
    Color::rgb(
        color.red * strength,
        color.green * strength,
        color.blue * strength,
    )
}

/// One light's color and strength, held apart from the position that
/// names it, plus whether it casts.
#[derive(Clone, Copy)]
struct Glow {
    color: Color,
    strength: f32,
    shadow: bool,
}

impl Glow {
    /// `color` scaled by `strength`, the value a [`Light`] reads.
    fn scaled(self) -> Color {
        scaled(self.color, self.strength)
    }
}

/// Every key and button this game reads apart from the UI: held, `Look`
/// turns the camera by the pointer's own motion, `Forward`/`Back`/
/// `Left`/`Right` move it along the view and to its side, and `Up`/
/// `Down` move it along the world's own up.
#[derive(InputButtonAction, Clone, Copy, PartialEq)]
enum Move {
    Forward,
    Back,
    Left,
    Right,
    Up,
    Down,
    Look,
}

impl InputButtonAction for Move {
    fn bindings(&self) -> Vec<ButtonBinding> {
        match self {
            Self::Forward => vec![Key::W.into()],
            Self::Back => vec![Key::S.into()],
            Self::Left => vec![Key::A.into()],
            Self::Right => vec![Key::D.into()],
            Self::Up => vec![Key::Space.into()],
            Self::Down => vec![Key::LeftShift.into()],
            Self::Look => vec![MouseButton::Right.into()],
        }
    }
}

/// The pointer's own motion, read only while [`Move::Look`] is held.
#[derive(InputAxis2Action, Clone, Copy, PartialEq)]
enum Turn {
    Look,
}

impl InputAxis2Action for Turn {
    fn bindings(&self) -> Vec<Axis2Binding> {
        match self {
            Self::Look => vec![Axis2Binding::pointer().scale(LOOK_SENSITIVITY)],
        }
    }
}

/// How far the wheel moved this frame, read to scale the move speed.
#[derive(InputAxisAction, Clone, Copy, PartialEq)]
enum Speed {
    Wheel,
}

impl InputAxisAction for Speed {
    fn bindings(&self) -> Vec<AxisBinding> {
        match self {
            Self::Wheel => vec![AxisBinding::from(WheelDelta::Up).scale(4.0)],
        }
    }
}

struct Controls;

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

struct Playground {
    eye: Vec3,
    yaw: f32,
    pitch: f32,
    speed_scale: f32,

    sky: Sky,
    sun_shadow: bool,

    lamp: Glow,
    spotlight: Glow,

    front_tint: Color,
    front_roughness: f32,
    front_metallic: f32,
    shading_map_on: bool,
    relief_map_on: bool,
    emissive_map_on: bool,

    exposure: f32,
    bloom: f32,
}

impl Playground {
    fn init(ctx: &mut InitContext<'_, Self>) -> Result<Self, Error> {
        let _ = ctx;
        Ok(Self {
            eye: START_EYE,
            yaw: START_YAW,
            pitch: START_PITCH,
            speed_scale: 1.0,

            sky: Sky::Default,
            sun_shadow: true,

            lamp: Glow {
                color: Color::rgb(0.9, 0.55, 0.3),
                strength: 3.0,
                shadow: false,
            },
            spotlight: Glow {
                color: Color::rgb(0.4, 0.6, 1.0),
                strength: 6.0,
                shadow: true,
            },

            front_tint: Color::rgb(0.7, 0.25, 0.2),
            front_roughness: 0.4,
            front_metallic: 0.0,
            shading_map_on: true,
            relief_map_on: true,
            emissive_map_on: true,

            exposure: START_EXPOSURE,
            bloom: START_BLOOM,
        })
    }

    /// This frame's forward direction, from `yaw` (turning around the
    /// world's own up) and `pitch` (turning up or down).
    fn forward(&self) -> Vec3 {
        Vec3::new(
            -self.pitch.cos() * self.yaw.sin(),
            self.pitch.sin(),
            -self.pitch.cos() * self.yaw.cos(),
        )
    }

    /// The camera this frame draws from: `eye` looking along `forward`.
    fn camera(&self) -> Camera {
        Camera::new(
            View::look_at(self.eye, self.eye + self.forward()),
            Projection::perspective(CAMERA_FOV),
        )
    }

    /// A held `Move::Look` (the right mouse button) turns the camera by
    /// the pointer's own motion, the same way it moves: dragging right
    /// turns the view right and left turns it left, dragging down turns
    /// it to look further down at the scene, dragging up back toward the
    /// horizon. `W`/`A`/`S`/`D` move along the view and to its side,
    /// `Space`/`Left Shift` up and down, and the wheel scales how far
    /// each move goes. The `eye` is held above the ground plane wherever
    /// it moves.
    fn fly_camera(&mut self, ctx: &mut FrameContext<'_, Self>) {
        if !ctx.ui_wants_pointer() && ctx.down(Move::Look) {
            let look = ctx.axis2(Turn::Look);
            self.yaw -= look.x;
            self.pitch = (self.pitch + look.y).clamp(-PITCH_LIMIT, PITCH_LIMIT);
        }

        let wheel = ctx.axis(Speed::Wheel);
        if !ctx.ui_wants_pointer() && wheel != 0.0 {
            self.speed_scale =
                (self.speed_scale * SPEED_STEP.powf(wheel)).clamp(MIN_SPEED_SCALE, MAX_SPEED_SCALE);
        }

        let forward = self.forward();
        let right = Vec3::new(self.yaw.cos(), 0.0, -self.yaw.sin());
        let mut move_by = Vec3::ZERO;
        if ctx.down(Move::Forward) {
            move_by += forward;
        }
        if ctx.down(Move::Back) {
            move_by -= forward;
        }
        if ctx.down(Move::Right) {
            move_by += right;
        }
        if ctx.down(Move::Left) {
            move_by -= right;
        }
        if ctx.down(Move::Up) {
            move_by += Vec3::Y;
        }
        if ctx.down(Move::Down) {
            move_by -= Vec3::Y;
        }
        if move_by.length_squared() > 1.0 {
            move_by = move_by.normalize();
        }

        self.eye += move_by * MOVE_SPEED * self.speed_scale * ctx.dt().as_secs_f32();
        self.eye.y = self.eye.y.max(MIN_EYE_HEIGHT);
    }

    /// The material [`Front`] draws with, resolved new from its sliders
    /// every frame — the override [`Instance::material`] takes, in place
    /// of a baked one.
    fn front_material(&self) -> Material {
        Material::lit(self.front_tint)
            .roughness(self.front_roughness)
            .metallic(self.front_metallic)
    }

    /// Every draw this game makes: the ground, each map pair, the front
    /// sphere, the reflection row and the pillars beside it.
    fn draw_scene(&self, ctx: &mut FrameContext<'_, Self>) {
        ctx.draw(
            Plane
                .at(Transform::from_scale(Vec3::new(
                    GROUND_SIZE,
                    1.0,
                    GROUND_SIZE,
                )))
                .material(Material::lit(GROUND_COLOR).roughness(0.9)),
        );

        Self::draw_pair(
            ctx,
            SHADING_Z,
            SPHERE_RADIUS,
            ShadingPlain.at(Vec3::ZERO).into_set(),
            ShadingMapped.at(Vec3::ZERO).into_set(),
            self.shading_map_on,
        );
        Self::draw_pair(
            ctx,
            RELIEF_Z,
            SPHERE_RADIUS,
            ReliefPlain.at(Vec3::ZERO).into_set(),
            ReliefMapped.at(Vec3::ZERO).into_set(),
            self.relief_map_on,
        );
        Self::draw_pair(
            ctx,
            EMISSIVE_Z,
            CUBE_SIZE / 2.0,
            EmissivePlain.at(Vec3::ZERO).into_set(),
            EmissiveMapped.at(Vec3::ZERO).into_set(),
            self.emissive_map_on,
        );

        ctx.draw(
            Front
                .at(Transform::from_scale_rotation_translation(
                    Vec3::splat(FRONT_SCALE),
                    Quat::IDENTITY,
                    FRONT_POSITION,
                ))
                .material(self.front_material()),
        );

        self.draw_reflect_row(ctx);
        self.draw_outpost(ctx);
    }

    /// One pair at depth `z`, its centers `height` above the ground: `plain`
    /// on the left always, and on the right `mapped` where `mapped_on` is
    /// set, `plain` again where it is not — the same position drawing the
    /// same base material with and without the map.
    fn draw_pair(
        ctx: &mut FrameContext<'_, Self>,
        z: f32,
        height: f32,
        plain: Instance<Shape, Looks>,
        mapped: Instance<Shape, Looks>,
        mapped_on: bool,
    ) {
        ctx.draw(plain.clone().at(Vec3::new(-PAIR_HALF_SPACING, height, z)));
        let right = if mapped_on { mapped } else { plain };
        ctx.draw(right.at(Vec3::new(PAIR_HALF_SPACING, height, z)));
    }

    /// A row of built-in `Sphere` draws at rising roughness, each
    /// `metallic(1.0)` with its tint white, so what draws is the sky's own
    /// reflection alone.
    fn draw_reflect_row(&self, ctx: &mut FrameContext<'_, Self>) {
        let start = -REFLECT_ROW_SPACING * (REFLECT_ROW_COUNT as f32 - 1.0) / 2.0;
        for index in 0..REFLECT_ROW_COUNT {
            let x = start + index as f32 * REFLECT_ROW_SPACING;
            let roughness = index as f32 / (REFLECT_ROW_COUNT as f32 - 1.0);
            ctx.draw(
                Sphere {
                    subdivisions: SPHERE_SUBDIVISIONS,
                }
                .at(Transform::from_scale_rotation_translation(
                    Vec3::splat(REFLECT_ROW_RADIUS * 2.0),
                    Quat::IDENTITY,
                    Vec3::new(x, REFLECT_ROW_RADIUS, REFLECT_ROW_Z),
                ))
                .material(
                    Material::lit(Color::WHITE)
                        .roughness(roughness)
                        .metallic(1.0),
                ),
            );
        }
    }

    /// Three pillars and a pole a light can shadow, beside `Banner`'s
    /// displaced cloth and `Field`'s pulsing sphere — [`OUTPOST`] moves the
    /// whole group clear of the rest of the scene.
    fn draw_outpost(&self, ctx: &mut FrameContext<'_, Self>) {
        let clock = ctx.elapsed().as_secs_f32();

        for &(position, scale) in &PILLARS {
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    scale,
                    Quat::IDENTITY,
                    OUTPOST + position,
                ))
                .material(Material::lit(Color::rgb(0.55, 0.5, 0.45))),
            );
        }

        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                POLE_SCALE,
                Quat::IDENTITY,
                OUTPOST + POLE_POSITION,
            ))
            .material(Material::lit(Color::rgb(0.3, 0.24, 0.18))),
        );

        ctx.set_surface_style(Banner { time: clock });
        ctx.draw(
            BannerCloth
                .at(Transform::from_translation(OUTPOST + BANNER_MOUNT))
                .material(Material::lit(Color::rgb(0.75, 0.12, 0.12)))
                .surface_style::<Banner>(),
        );

        ctx.set_surface_style(Field {
            tint: Color::rgb(0.25, 0.75, 1.0),
            time: clock,
        });
        ctx.draw(
            Sphere { subdivisions: 2 }
                .at(Transform::from_scale_rotation_translation(
                    Vec3::splat(FIELD_ORB_SCALE),
                    Quat::IDENTITY,
                    OUTPOST + FIELD_ORB_POSITION,
                ))
                .material(Material::color(Color::BLACK))
                .surface_style::<Field>(),
        );
    }

    /// This frame's sun, lamp and spotlight, each `.shadow()` where its own
    /// flag is set. The sun's direction, color and strength come from the
    /// chosen [`Sky`], and is absent where the choice pairs with none; only
    /// its shadow flag is the player's own.
    fn lights(&self) -> Vec<Light> {
        let lamp = Light::point(LAMP_POSITION, self.lamp.scaled(), LAMP_RANGE);
        let spotlight = Light::spot(Spot {
            position: SPOT_POSITION,
            direction: SPOT_DIRECTION,
            color: self.spotlight.scaled(),
            range: SPOT_RANGE,
            angle: SPOT_ANGLE,
        });

        let mut lights = vec![
            if self.lamp.shadow {
                lamp.shadow()
            } else {
                lamp
            },
            if self.spotlight.shadow {
                spotlight.shadow()
            } else {
                spotlight
            },
        ];

        if let Some((direction, color, strength)) = self.sky.sun() {
            let sun = Light::directional(direction, scaled(color, strength));
            lights.push(if self.sun_shadow { sun.shadow() } else { sun });
        }

        lights
    }

    /// Every live knob, in a side area of fixed width so the scene stays
    /// visible beside it — the default sky reads as flat grey, so a
    /// control added straight to the bare UI layer would read as a slab
    /// across the window.
    fn controls(&mut self, ctx: &mut FrameContext<'_, Self>) {
        let tonemap = ctx.config().tonemap();
        let antialiasing = ctx.config().antialiasing();
        let shadow_resolution = ctx.config().shadow_resolution();

        ctx.ui(|ui| {
            egui::Panel::right("controls")
                .resizable(false)
                .default_size(300.0)
                .show(ui, |ui| {
                    egui::ScrollArea::vertical().show(ui, |ui| {
                        ui.label(
                            "right mouse button to look, W/A/S/D to move, \
                             space/shift up and down, wheel to scale speed",
                        );
                        ui.separator();
                        self.lighting_controls(ui);
                        ui.separator();
                        self.light_controls(ui);
                        ui.separator();
                        self.material_controls(ui);
                        ui.separator();
                        ui.label(format!(
                            "tone map {tonemap:?} \u{b7} antialiasing {antialiasing} \u{b7} \
                             shadow {shadow_resolution}px: set at startup, not live"
                        ));
                        ui.add(egui::Slider::new(&mut self.exposure, 0.1..=3.0).text("exposure"));
                        ui.add(egui::Slider::new(&mut self.bloom, 0.0..=1.0).text("bloom"));
                    });
                });
        });
    }

    fn lighting_controls(&mut self, ui: &mut egui::Ui) {
        ui.heading("lighting");
        for choice in Sky::ALL {
            ui.radio_value(&mut self.sky, choice, choice.name());
        }
        ui.label(format!("sky light {:.2}: set at startup", self.sky.light()));

        match self.sky.sun() {
            Some((_, color, strength)) => {
                color_swatch(ui, "sun", color);
                ui.label(format!("sun strength {strength:.2}: set by the choice"));
                ui.checkbox(&mut self.sun_shadow, "sun shadow");
            }
            None => {
                ui.label("no sun: set by the choice");
            }
        }
    }

    fn light_controls(&mut self, ui: &mut egui::Ui) {
        ui.heading("lights");
        glow_controls(ui, "lamp", &mut self.lamp);
        glow_controls(ui, "spotlight", &mut self.spotlight);
    }

    fn material_controls(&mut self, ui: &mut egui::Ui) {
        ui.heading("material");
        color_row(ui, "tint", &mut self.front_tint);
        ui.add(egui::Slider::new(&mut self.front_roughness, 0.0..=1.0).text("roughness"));
        ui.add(egui::Slider::new(&mut self.front_metallic, 0.0..=1.0).text("metallic"));
        ui.checkbox(
            &mut self.shading_map_on,
            "shading map: occlusion \u{b7} roughness \u{b7} metallic",
        );
        ui.checkbox(&mut self.relief_map_on, "relief map: bump normals");
        ui.checkbox(&mut self.emissive_map_on, "emissive map: per-texel glow");
    }
}

/// One light's own controls: a color, its strength and a shadow flag.
fn glow_controls(ui: &mut egui::Ui, label: &str, glow: &mut Glow) {
    ui.label(label);
    color_row(ui, "color", &mut glow.color);
    ui.add(egui::Slider::new(&mut glow.strength, 0.0..=8.0).text("strength"));
    ui.checkbox(&mut glow.shadow, "shadow");
}

/// One named control over `color`'s red, green and blue channels; alpha
/// stays `1.0`.
fn color_row(ui: &mut egui::Ui, label: &str, color: &mut Color) {
    let mut rgb = [color.red, color.green, color.blue];
    ui.horizontal(|ui| {
        ui.label(label);
        if ui.color_edit_button_rgb(&mut rgb).changed() {
            *color = Color::rgb(rgb[0], rgb[1], rgb[2]);
        }
    });
}

/// `color` shown, not changed: the sun's own color, resolved from the
/// chosen [`Sky`] and not a control the player sets on its own.
fn color_swatch(ui: &mut egui::Ui, label: &str, color: Color) {
    let mut rgb = [color.red, color.green, color.blue];
    ui.horizontal(|ui| {
        ui.label(label);
        ui.add_enabled_ui(false, |ui| {
            ui.color_edit_button_rgb(&mut rgb);
        });
    });
}

impl Game for Playground {
    type Meshes = Shape;
    type Sounds = NoSounds;
    type InputActions = Controls;
    type Skyboxes = Sky;
    type SurfaceStyles = Looks;
    type PostEffects = NoPostEffects;

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.fly_camera(ctx);
        ctx.set_camera(self.camera());
        ctx.set_skybox(self.sky);
        for light in self.lights() {
            ctx.light(light);
        }
        ctx.set_exposure(self.exposure);
        ctx.set_bloom(self.bloom);

        self.draw_scene(ctx);
        self.controls(ctx);
    }
}

fn main() {
    let config = Config::new("Mirage: material playground")
        .with_size(1280, 720)
        .with_assets([
            "examples/assets/sky-clear.png",
            "examples/assets/sky-classic.png",
            "examples/assets/sky-dawn.png",
            "examples/assets/sky-sinister.png",
            "examples/assets/sky-stars-lightblue.png",
            "examples/assets/sky-stars-blue.png",
        ]);

    run(config, Playground::init);
}