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
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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
use core::num::NonZeroU64;

use bytemuck::{Pod, Zeroable};

use crate::gpu::{
    DEPTH_FORMAT, SMALLEST_VALUES, buffer, pipeline_layout, sampled, sampler, uniform,
};
use crate::light::{GpuLight, MAX_LIGHTS};
use crate::math::{Mat4, UVec2, Vec3, Vec4};
use crate::mesh::{Frame, MeshPlane, Placement, Vertex, Weighted};
use crate::renderer::post::HDR_FORMAT;
use crate::renderer::shadows::{Cast, GpuMap, MAX_MAPS};
use crate::renderer::skybox::Lighting;
use crate::surface_style::{self, Declaration, DrawPass, SurfaceStyleId};
use crate::{Camera, Color, Error, Material, ReliefData};

/// The litness lane of a cutout instance: under `-1.0`, past anything a
/// plain instance writes, since the layout has no lane left for it alone;
/// `forward.wgsl` reads it back the same way.
const CUTOUT: f32 = -1.0;

/// Extent of the viewpoint buffer one pass reads: its own viewpoint, and
/// none of the passes around it.
const VIEWPOINT: u64 = size_of::<Cast>() as u64;

/// Matrix count the frame's palette holds until a frame's posed draws take
/// more of them; it grows to what they take and never shrinks.
const INITIAL_JOINTS: usize = 256;

/// The way an additive draw lands on the target: what it draws, scaled by
/// the alpha it draws, added to what is there — never taken away from it,
/// and never over the alpha the target already holds.
const ADDING: wgpu::BlendState = wgpu::BlendState {
    color: wgpu::BlendComponent {
        src_factor: wgpu::BlendFactor::SrcAlpha,
        dst_factor: wgpu::BlendFactor::One,
        operation: wgpu::BlendOperation::Add,
    },
    alpha: wgpu::BlendComponent {
        src_factor: wgpu::BlendFactor::Zero,
        dst_factor: wgpu::BlendFactor::One,
        operation: wgpu::BlendOperation::Add,
    },
};

const VERTEX_ATTRIBUTES: [wgpu::VertexAttribute; 3] =
    wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x2];

const INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 11] = wgpu::vertex_attr_array![
    3 => Float32x4, 4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Float32x4,
    8 => Float32x4, 11 => Float32x4, 10 => Uint32, 14 => Float32,
    15 => Float32, 9 => Uint32,
];

/// What a skinned mesh holds beside its corners: the joints each of them
/// takes and how much of each. These are the last two lanes a pipeline has
/// left: a skinned one reads all sixteen.
const SKIN_ATTRIBUTES: [wgpu::VertexAttribute; 2] =
    wgpu::vertex_attr_array![12 => Uint32x4, 13 => Float32x4];

const VERTICES: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
    array_stride: size_of::<Vertex>() as wgpu::BufferAddress,
    step_mode: wgpu::VertexStepMode::Vertex,
    attributes: &VERTEX_ATTRIBUTES,
};

const INSTANCES: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
    array_stride: size_of::<GpuInstance>() as wgpu::BufferAddress,
    step_mode: wgpu::VertexStepMode::Instance,
    attributes: &INSTANCE_ATTRIBUTES,
};

const SKIN: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
    array_stride: size_of::<Weighted>() as wgpu::BufferAddress,
    step_mode: wgpu::VertexStepMode::Vertex,
    attributes: &SKIN_ATTRIBUTES,
};

const BUFFER_LAYOUTS: [wgpu::VertexBufferLayout<'static>; 2] = [VERTICES, INSTANCES];

/// The same, with the stream a skinned mesh holds at the slot `passes.rs`
/// binds it to.
const SKINNED_LAYOUTS: [wgpu::VertexBufferLayout<'static>; 3] = [VERTICES, INSTANCES, SKIN];

/// Data a draw writes into the instance buffer: the mesh's position, its
/// tint, its shading, the part of its texture it samples, what relief the
/// part it draws holds, the plane it takes its depth from, and where the
/// matrices it is skinned by start.
///
/// The transform is the three transposed rows of its affine part; the
/// shader adds the last row. The parameters are litness, then the
/// surface's own emissive light, with the roughness and the metallic in
/// lanes of their own. The window is the sampled part's start and extent
/// within the texture.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub(crate) struct GpuInstance {
    model: [Vec4; 3],
    tint: Color,
    params: Vec4,
    window: Vec4,
    plane: WorldPlane,
    relief: Relief,
    roughness: f32,
    metallic: f32,
    /// Where this draw's run of the frame's palette starts; the skinned
    /// stages alone read it, and a draw of a mesh with no joints leaves it
    /// at zero.
    palette: u32,
}

impl GpuInstance {
    /// Lays `placement`, `material` and `frame` out as the shader reads
    /// them: the affine rows of the transform the viewpoint placed the
    /// draw by, the tint whole, the shading parameters with litness first,
    /// and the sampled part of the texture. `pass` is the draw's resolved
    /// pass, which decides whether its texels are dropped, `relief` what
    /// the part it covers holds, and `plane` the plane it takes its depth
    /// from. Whether the viewpoint turned the draw is a pipeline of its
    /// own, never a lane here.
    pub(crate) fn new(
        placement: Placement,
        material: Material,
        pass: DrawPass,
        frame: Frame,
        relief: Relief,
        plane: WorldPlane,
    ) -> Self {
        let rows = placement.transform().matrix().transpose();
        let emissive = material.emission();
        Self {
            model: [rows.x_axis, rows.y_axis, rows.z_axis],
            tint: material.tint(),
            params: Vec4::new(
                shading(&material, pass),
                emissive.red,
                emissive.green,
                emissive.blue,
            ),
            window: frame.lane(),
            plane,
            relief,
            roughness: material.rough(),
            metallic: material.metal(),
            palette: 0,
        }
    }

    /// The same instance skinned by the run of the frame's palette that
    /// starts at `at`.
    pub(crate) fn posed(mut self, at: u32) -> Self {
        self.palette = at;
        self
    }
}

/// What relief the part a draw covers has, and whether the draw moves
/// its texels off the plane by the depth that relief holds.
///
/// The mesh, the part and the turn decide it, and the sort key holds all
/// three, so it splits no batch. It is written to an instance lane because
/// a part with no relief is bound to the flat texel used in place of one,
/// and the shader reads that texel like any relief.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub(crate) struct Relief(u32);

impl Relief {
    /// The lane a draw writes where its part has no relief: it takes every
    /// light by the normal its mesh holds, and a faced one takes them
    /// whole and meets them half a sprite width off the plane.
    /// `forward.wgsl` reads it as `NO_RELIEF`.
    const NONE: Self = Self(0);

    /// The lane it writes where the relief holds a normal alone;
    /// `forward.wgsl` reads it as `NORMALS`.
    const NORMALS: Self = Self(1);

    /// The lane it writes where the relief also moves its texels off the
    /// plane; `forward.wgsl` reads it as `SOLID`.
    const SOLID: Self = Self(2);

    /// Which of the three `relief` is for this draw: only a `faced` draw
    /// reads the depth a relief holds, a placed one taking the normals
    /// alone.
    pub(crate) fn of(relief: Option<&ReliefData>, faced: bool) -> Self {
        match relief {
            Some(relief) if faced && relief.deep() => Self::SOLID,
            Some(_) => Self::NORMALS,
            None => Self::NONE,
        }
    }

    /// Whether the draw casts the solid its relief holds. A depth map casts
    /// a draw that does through a stage that samples the slot, the way it
    /// casts a cutout draw.
    pub(crate) fn solid(self) -> bool {
        self == Self::SOLID
    }
}

/// The plane a draw takes its depth from, as the four numbers of its
/// equation: the world plane its own transform lays a flat mesh in, or the
/// upright plane the viewpoint placed a faced draw in.
///
/// Every stage that draws one of these computes its depth from this plane
/// and the pixel alone, so two draws of one plane are at one depth and the
/// later of them draws over the earlier, whole. A draw that takes the depth
/// of its own corners holds [`WorldPlane::NONE`].
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub(crate) struct WorldPlane(Vec4);

impl WorldPlane {
    /// The lane written for a draw of a mesh that is flat in no plane, for
    /// a draw whose style moves its corners off that plane, and for a faced
    /// draw under a view with no level direction to look along, which
    /// places it in no plane at all.
    pub(crate) const NONE: Self = Self(Vec4::ZERO);

    /// The world plane `plane` holds, which a flat mesh's own transform
    /// already laid it in.
    pub(crate) fn of(plane: MeshPlane) -> Self {
        Self(plane.equation())
    }

    /// The upright plane through `anchor`, facing the `level`
    /// direction the view looks along. Two draws the view placed in one plane
    /// are given the same numbers for it, which is what puts them at one
    /// depth.
    pub(crate) fn upright(level: Vec3, anchor: Vec3) -> Self {
        Self(level.extend(-level.dot(anchor)))
    }

    /// Whether the draw takes its depth from a plane at all, which chooses
    /// the stages it is drawn through.
    pub(crate) fn lies(self) -> bool {
        self != Self::NONE
    }
}

/// The litness lane of `material`, which also encodes whether the draw
/// drops the texels its alpha leaves out. Dropping is required in the cutout pass
/// whatever the material declares, and by a cutout material in any pass.
fn shading(material: &Material, pass: DrawPass) -> f32 {
    if pass == DrawPass::Cutout || material.cuts() {
        CUTOUT - material.litness()
    } else {
        material.litness()
    }
}

/// Values every draw of one pass shares beyond its viewpoint: the light the
/// frame's sky lands on a surface and the rays it is drawn along, the
/// camera a faced draw resolves its depth against, the light buffer's used
/// extent, and the mip a fully rough surface reflects that sky from.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
struct FrameUniform {
    irradiance: [Vec4; 9],
    /// What a clip position is taken through to give the direction the sky
    /// is read along.
    sky_from_clip: Mat4,
    eye: Vec3,
    /// Whether rays leave `eye`, rather than running level along `looking`
    /// from wherever they start.
    foreshortened: u32,
    looking: Vec3,
    lights: u32,
    /// The mip level a fully rough surface reflects the sky from: the
    /// smallest mip's, counting `0.0` at the largest.
    top_mip: f32,
    /// What a surface's reflection of the sky is scaled by; the coefficients
    /// already hold it.
    sky_share: f32,
    /// Keeps this struct's size at WGSL's alignment; `bytemuck` needs
    /// padding written out.
    _padding: [u32; 2],
}

/// Everything the whole frame is drawn against: the viewpoint of each
/// pass, the lights it submitted, the depth maps that darken them, and the
/// sky it is lit by.
///
/// The light and map buffers are sized for their caps once, and written
/// again from their starts every frame, so only the sky ever changes what a
/// pass is bound to; each sky holds a bind group of its own.
pub(crate) struct FrameBindings {
    viewpoints: wgpu::Buffer,
    frame: wgpu::Buffer,
    lights: wgpu::Buffer,
    maps: wgpu::Buffer,
    palette: wgpu::Buffer,
    /// Matrix count the palette buffer holds, which only ever grows.
    joints: usize,
    stride: wgpu::BufferAddress,
    layout: wgpu::BindGroupLayout,
}

impl FrameBindings {
    pub(crate) fn new(device: &wgpu::Device) -> Self {
        let stride = wgpu::BufferAddress::from(device.limits().min_uniform_buffer_offset_alignment);
        let viewpoints = buffer(
            device,
            "mirage-engine viewpoints",
            stride * (1 + MAX_MAPS as wgpu::BufferAddress),
            wgpu::BufferUsages::UNIFORM,
        );
        let frame = buffer(
            device,
            "mirage-engine frame",
            size_of::<FrameUniform>() as wgpu::BufferAddress,
            wgpu::BufferUsages::UNIFORM,
        );
        let lights = buffer(
            device,
            "mirage-engine lights",
            (MAX_LIGHTS * size_of::<GpuLight>()) as wgpu::BufferAddress,
            wgpu::BufferUsages::STORAGE,
        );
        let maps = buffer(
            device,
            "mirage-engine shadow maps",
            (MAX_MAPS * size_of::<GpuMap>()) as wgpu::BufferAddress,
            wgpu::BufferUsages::STORAGE,
        );
        let palette = palette(device, INITIAL_JOINTS);

        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("mirage-engine frame"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: NonZeroU64::new(VIEWPOINT),
                    },
                    count: None,
                },
                uniform(1, wgpu::ShaderStages::VERTEX_FRAGMENT),
                storage(2),
                storage(3),
                sampled(4, true),
                sampler(5),
                skinning(6),
            ],
        });

        Self {
            viewpoints,
            frame,
            lights,
            maps,
            palette,
            joints: INITIAL_JOINTS,
            stride,
            layout,
        }
    }

    /// Writes the matrices the frame's posed draws are skinned by, and grows
    /// the buffer that holds them where the frame took more than it does.
    ///
    /// Returns whether it grew, which is what leaves every bind group over
    /// these values to be built again.
    pub(crate) fn set_palette(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        matrices: &[Mat4],
    ) -> bool {
        let grew = matrices.len() > self.joints;
        if grew {
            self.joints = matrices.len().next_power_of_two();
            self.palette = palette(device, self.joints);
        }
        if !matrices.is_empty() {
            queue.write_buffer(&self.palette, 0, bytemuck::cast_slice(matrices));
        }

        grew
    }

    /// Writes what the frame is drawn against, over a target `size` pixels
    /// across and under the sky it is lit by; the plan already keeps
    /// `lights` to [`MAX_LIGHTS`].
    pub(crate) fn set_frame(
        &self,
        queue: &wgpu::Queue,
        camera: Camera,
        size: UVec2,
        lights: &[GpuLight],
        sky: Lighting,
    ) {
        let view = camera.view();
        let looking = view.direction();
        let aspect = size.x as f32 / size.y as f32;
        queue.write_buffer(
            &self.viewpoints,
            0,
            bytemuck::bytes_of(&Cast::camera(camera.view_projection(aspect), size)),
        );
        queue.write_buffer(
            &self.frame,
            0,
            bytemuck::bytes_of(&FrameUniform {
                irradiance: sky.irradiance,
                sky_from_clip: camera.rays_from_clip(aspect),
                eye: view.eye(),
                foreshortened: u32::from(camera.foreshortened()),
                looking,
                lights: lights.len() as u32,
                top_mip: sky.top_mip,
                sky_share: sky.share,
                _padding: [0; 2],
            }),
        );
        queue.write_buffer(&self.lights, 0, bytemuck::cast_slice(lights));
    }

    /// Writes what each depth map is drawn from, in the order they are drawn.
    pub(crate) fn set_casters(&self, queue: &wgpu::Queue, casters: impl Iterator<Item = Cast>) {
        for (slot, cast) in casters.enumerate() {
            let at = wgpu::BufferAddress::from(self.caster_offset(slot));
            queue.write_buffer(&self.viewpoints, at, bytemuck::bytes_of(&cast));
        }
    }

    /// Writes what the forward pass samples those maps by.
    pub(crate) fn set_maps(&self, queue: &wgpu::Queue, maps: &[GpuMap]) {
        if maps.is_empty() {
            return;
        }
        queue.write_buffer(&self.maps, 0, bytemuck::cast_slice(maps));
    }

    /// The offset the caster pass drawing map `slot` reads its viewpoint
    /// from.
    pub(crate) fn caster_offset(&self, slot: usize) -> wgpu::DynamicOffset {
        ((1 + slot as wgpu::BufferAddress) * self.stride) as wgpu::DynamicOffset
    }

    pub(crate) fn layout(&self) -> &wgpu::BindGroupLayout {
        &self.layout
    }

    /// What every pass of the frame reads these values and the sky `view`
    /// holds through.
    pub(crate) fn bind(
        &self,
        device: &wgpu::Device,
        view: &wgpu::TextureView,
        sampler: &wgpu::Sampler,
    ) -> wgpu::BindGroup {
        fn held(binding: u32, resource: wgpu::BindingResource<'_>) -> wgpu::BindGroupEntry<'_> {
            wgpu::BindGroupEntry { binding, resource }
        }

        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mirage-engine frame"),
            layout: &self.layout,
            entries: &[
                held(
                    0,
                    wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.viewpoints,
                        offset: 0,
                        size: NonZeroU64::new(VIEWPOINT),
                    }),
                ),
                held(1, self.frame.as_entire_binding()),
                held(2, self.lights.as_entire_binding()),
                held(3, self.maps.as_entire_binding()),
                held(4, wgpu::BindingResource::TextureView(view)),
                held(5, wgpu::BindingResource::Sampler(sampler)),
                held(6, self.palette.as_entire_binding()),
            ],
        })
    }
}

/// The shader every draw with no style of its own is drawn with, opaque,
/// cutout, blended and added, plus the two passes a light draws its depth
/// maps with.
pub(crate) struct Pipelines {
    opaque: Placing,
    cutout: Placing,
    transparent: Placing,
    additive: Placing,
    sky: wgpu::RenderPipeline,
    caster: Skinning,
    sampled_caster: Skinning,
}

impl Pipelines {
    pub(crate) fn new(
        device: &wgpu::Device,
        samples: u32,
        uniforms: &wgpu::BindGroupLayout,
        textures: &wgpu::BindGroupLayout,
        shadows: &wgpu::BindGroupLayout,
    ) -> Self {
        let shaders = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("mirage-engine forward"),
            source: wgpu::ShaderSource::Wgsl(surface_style::built_in().into()),
        });
        let layout = pipeline_layout(
            device,
            "mirage-engine forward",
            &[Some(uniforms), Some(textures), Some(shadows)],
        );

        let (caster, sampled_caster) = casters(device, &shaders, uniforms, textures);
        let covering = pipeline_layout(device, "mirage-engine skybox", &[Some(uniforms)]);

        Self {
            sky: sky(device, &shaders, &covering, samples),
            opaque: forward(device, &shaders, &layout, samples, Variant::Opaque),
            cutout: forward(device, &shaders, &layout, samples, Variant::Cutout),
            transparent: forward(device, &shaders, &layout, samples, Variant::Transparent),
            additive: forward(device, &shaders, &layout, samples, Variant::Additive),
            caster,
            sampled_caster,
        }
    }

    /// The pipelines the opaque batches draw with.
    pub(crate) fn opaque(&self) -> &Placing {
        &self.opaque
    }

    /// The ones the cutout batches draw with, over the depth the opaque
    /// ones left and into it.
    pub(crate) fn cutout(&self) -> &Placing {
        &self.cutout
    }

    /// The ones the translucent batches draw with, over the depth the
    /// opaque ones left.
    pub(crate) fn transparent(&self) -> &Placing {
        &self.transparent
    }

    /// The ones the additive batches draw with, over the depth the opaque
    /// ones left and after the translucent ones.
    pub(crate) fn additive(&self) -> &Placing {
        &self.additive
    }

    /// The pipeline the frame's sky is drawn with: one triangle at the far
    /// depth, drawn where the depth buffer holds nothing nearer and writing
    /// no depth of its own.
    pub(crate) fn sky(&self) -> &wgpu::RenderPipeline {
        &self.sky
    }

    /// The pipelines a light's depth maps draw a batch that lies in no plane
    /// with: the forward vertex stage alone, from the light's own viewpoint.
    pub(crate) fn caster(&self) -> &Skinning {
        &self.caster
    }

    /// The pipelines a map draws a batch through a fragment stage of its own:
    /// a cutout draw, whose alpha drops texels out of the shadow, a faced
    /// draw casting the solid its relief holds, whose depth is offset from
    /// the plane, and a draw lying in a plane, which records that plane's
    /// own depth.
    pub(crate) fn sampled_caster(&self) -> &Skinning {
        &self.sampled_caster
    }
}

/// One stage compiled twice: the pipeline a mesh with no joints
/// draws through, and the one a skinned mesh does, which blends the palette
/// its draw reads and takes the stream of what each vertex holds of it.
pub(crate) struct Skinning {
    plain: wgpu::RenderPipeline,
    skinned: wgpu::RenderPipeline,
}

impl Skinning {
    /// The pipeline a batch draws with, by whether its mesh has joints.
    pub(crate) fn of(&self, skinned: bool) -> &wgpu::RenderPipeline {
        match skinned {
            true => &self.skinned,
            false => &self.plain,
        }
    }
}

/// One forward pass compiled three times over: the pipelines for a draw
/// placed by its own transform, the one for a draw lying in a plane, which
/// takes that plane's depth, and the ones for a draw the viewpoint turned,
/// which lies in the upright plane it was placed in and takes light from
/// the relief its slot holds.
///
/// A depth map needs no such set: a caster is already drawn from the
/// viewpoint that turned it, and the pass that samples a slot takes the
/// plane's depth for every draw that lies in one, so the caster passes need
/// a [`Drawn`] alone.
pub(crate) struct Placing {
    placed: Skinning,
    flat: Skinning,
    faced: Skinning,
}

impl Placing {
    /// The pipeline a batch draws with, by the turn it was placed by and by
    /// whether its mesh has joints.
    pub(crate) fn of(&self, turn: Turn, skinned: bool) -> &wgpu::RenderPipeline {
        let turned = match turn {
            Turn::Placed => &self.placed,
            Turn::Flat => &self.flat,
            Turn::Faced => &self.faced,
        };

        turned.of(skinned)
    }
}

/// The game's own styles as startup compiles them: one pipeline and one
/// buffer of values each, in the order the set lists them.
pub(crate) struct Styles {
    compiled: Vec<Compiled>,
}

impl Styles {
    /// Stitches every declared style into the engine's shader, builds the
    /// pipeline each of them draws with, and returns an error naming
    /// every style whose own WGSL did not compile.
    ///
    /// A game that declares no style compiles nothing and costs nothing.
    pub(crate) async fn compile(
        device: &wgpu::Device,
        declared: Vec<Declaration>,
        samples: u32,
        uniforms: &wgpu::BindGroupLayout,
        textures: &wgpu::BindGroupLayout,
        shadows: &wgpu::BindGroupLayout,
    ) -> Result<Self, Error> {
        if declared.is_empty() {
            return Ok(Self {
                compiled: Vec::new(),
            });
        }

        let mut compiled = Vec::with_capacity(declared.len());
        let mut broken = Vec::new();
        for declaration in declared {
            let name = declaration.name;
            // A shader error resolves on the GPU's own timeline, so the
            // scope over the creation is read here at startup.
            let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
            let style = compiled_style(device, declaration, samples, uniforms, textures, shadows);
            match scope.pop().await {
                Some(error) => broken.push(format!("{name}: {error}")),
                None => compiled.push(style),
            }
        }

        match broken.is_empty() {
            true => Ok(Self { compiled }),
            false => Err(Error::msg(format!(
                "a style did not compile: {}",
                broken.join("; ")
            ))),
        }
    }

    /// Every style the game declares, in the order its set lists them.
    pub(crate) fn ids(&self) -> impl Iterator<Item = SurfaceStyleId> {
        (0..self.compiled.len() as u32).map(SurfaceStyleId)
    }

    /// The pipeline and bindings a batch of `id` is drawn with, chosen by
    /// the turn its draws were placed by and by whether its mesh has joints.
    pub(crate) fn drawn_with(
        &self,
        id: SurfaceStyleId,
        turn: Turn,
        skinned: bool,
    ) -> Option<(&wgpu::RenderPipeline, &wgpu::BindGroup)> {
        let compiled = self.compiled.get(id.0 as usize)?;
        Some((compiled.pipeline.of(turn, skinned), &compiled.bindings))
    }

    /// Writes the values one style reads this frame, or its defaults where
    /// the frame passed it nothing.
    pub(crate) fn set_values(
        &self,
        queue: &wgpu::Queue,
        id: SurfaceStyleId,
        values: Option<&[u8]>,
    ) {
        let Some(compiled) = self.compiled.get(id.0 as usize) else {
            return;
        };
        let values = values.unwrap_or(&compiled.defaults);
        if values.is_empty() {
            return;
        }
        queue.write_buffer(&compiled.uniforms, 0, values);
    }
}

/// One style on the GPU: the pipelines its draws are drawn with, the buffer
/// its values are read from, and the defaults it reads where a frame
/// writes none.
struct Compiled {
    pipeline: Placing,
    uniforms: wgpu::Buffer,
    bindings: wgpu::BindGroup,
    defaults: Vec<u8>,
}

/// Builds one style's shader, the buffer its values are read from, and the
/// pipeline its declared pass draws it with.
fn compiled_style(
    device: &wgpu::Device,
    declaration: Declaration,
    samples: u32,
    frame: &wgpu::BindGroupLayout,
    textures: &wgpu::BindGroupLayout,
    shadows: &wgpu::BindGroupLayout,
) -> Compiled {
    let label = Some(declaration.name);
    let shaders = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label,
        source: wgpu::ShaderSource::Wgsl(declaration.source.into()),
    });
    let size = (declaration.defaults.len() as wgpu::BufferAddress).max(SMALLEST_VALUES);
    let uniforms = buffer(
        device,
        "mirage-engine style",
        size,
        wgpu::BufferUsages::UNIFORM,
    );
    let values = values_layout(device, size);
    let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label,
        layout: &values,
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: uniforms.as_entire_binding(),
        }],
    });
    let layout = pipeline_layout(
        device,
        declaration.name,
        &[Some(frame), Some(textures), Some(shadows), Some(&values)],
    );

    Compiled {
        pipeline: forward(device, &shaders, &layout, samples, declaration.pass.into()),
        uniforms,
        bindings,
        defaults: declaration.defaults,
    }
}

/// The binding a style reads its values from: one buffer of `size` bytes,
/// read by both stages, since either may hold the style's own code.
///
/// The size is the smallest binding the layout takes, so a style whose
/// shader reads past what its values write is caught where its pipeline is
/// built, not where it draws.
fn values_layout(device: &wgpu::Device, size: wgpu::BufferAddress) -> wgpu::BindGroupLayout {
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("mirage-engine style"),
        entries: &[wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: NonZeroU64::new(size),
            },
            count: None,
        }],
    })
}

/// The way a forward pipeline draws over what is already there.
#[derive(Clone, Copy)]
enum Variant {
    /// Replaces the color and writes the depth.
    Opaque,
    /// The same, dropping the texels a cutting draw leaves out.
    Cutout,
    /// Blends by the alpha it draws, leaves the depth alone, and drops
    /// those texels for the instances that requested it.
    Transparent,
    /// Adds what it draws, scaled by that alpha, to what is already there,
    /// and leaves the depth alone; no texel of it is dropped.
    Additive,
}

impl Variant {
    /// The fragment stage this way of drawing goes through, named after its
    /// turn's prefix; how an added draw lands is blend state, so it shares
    /// the plain stage.
    fn entry(self) -> &'static str {
        match self {
            Self::Opaque | Self::Additive => "fragment",
            Self::Cutout | Self::Transparent => "fragment_tested",
        }
    }
}

impl From<DrawPass> for Variant {
    fn from(pass: DrawPass) -> Self {
        match pass {
            DrawPass::Opaque => Self::Opaque,
            DrawPass::Cutout => Self::Cutout,
            DrawPass::Translucent => Self::Transparent,
            DrawPass::Additive => Self::Additive,
        }
    }
}

/// The three pipelines one forward pass draws with: one for a draw placed
/// by its own transform, one for a draw lying in a plane, and one for a
/// draw the viewpoint turned.
fn forward(
    device: &wgpu::Device,
    shaders: &wgpu::ShaderModule,
    layout: &wgpu::PipelineLayout,
    samples: u32,
    variant: Variant,
) -> Placing {
    let one = |turn| Skinning {
        plain: drawn(device, shaders, layout, samples, variant, turn, false),
        skinned: drawn(device, shaders, layout, samples, variant, turn, true),
    };

    Placing {
        placed: one(Turn::Placed),
        flat: one(Turn::Flat),
        faced: one(Turn::Faced),
    }
}

/// Which stages a forward pipeline draws through: the ones that take a draw
/// where its transform placed it, the ones that take a draw lying in a plane
/// at that plane's own depth, or the ones that slide a turned draw onto the
/// plane it lies in and light it there.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) enum Turn {
    Placed,
    Flat,
    Faced,
}

impl Turn {
    /// The turn a draw takes: the one the viewpoint turned, the one lying in
    /// `plane`, or the one its own transform placed.
    pub(crate) fn of(faced: bool, plane: WorldPlane) -> Self {
        match (faced, plane.lies()) {
            (true, _) => Self::Faced,
            (false, true) => Self::Flat,
            (false, false) => Self::Placed,
        }
    }

    /// Whether the draw takes the depth of a plane, which every stage it is
    /// drawn through computes for itself.
    pub(crate) fn lies(self) -> bool {
        self != Self::Placed
    }

    /// This turn's pipeline name, the stage that places its corners, and the
    /// stage that draws them.
    fn stage(self) -> (&'static str, &'static str, &'static str) {
        match self {
            Self::Placed => ("", "", ""),
            Self::Flat => (" flat", "", "flat_"),
            Self::Faced => (" faced", "faced_", "faced_"),
        }
    }
}

/// What a skinned pipeline's name ends with, what the stage that places its
/// corners starts with, and the buffers it is drawn from: a mesh with no
/// joints takes neither of those names and no stream of its own.
fn skinned_stage(
    skinned: bool,
) -> (
    &'static str,
    &'static str,
    &'static [wgpu::VertexBufferLayout<'static>],
) {
    match skinned {
        true => (" skinned", "skinned_", &SKINNED_LAYOUTS),
        false => ("", "", &BUFFER_LAYOUTS),
    }
}

fn drawn(
    device: &wgpu::Device,
    shaders: &wgpu::ShaderModule,
    layout: &wgpu::PipelineLayout,
    samples: u32,
    variant: Variant,
    turn: Turn,
    skinned: bool,
) -> wgpu::RenderPipeline {
    let (turned, places, draws) = turn.stage();
    let (skinning, blends, buffers) = skinned_stage(skinned);
    let (label, blend, writes_depth) = match variant {
        Variant::Opaque => ("mirage-engine forward", None, true),
        Variant::Cutout => ("mirage-engine forward cutout", None, true),
        Variant::Transparent => (
            "mirage-engine forward blended",
            Some(wgpu::BlendState::ALPHA_BLENDING),
            false,
        ),
        Variant::Additive => ("mirage-engine forward additive", Some(ADDING), false),
    };

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(&format!("{label}{turned}{skinning}")),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shaders,
            entry_point: Some(&format!("{places}{blends}vertex")),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            buffers,
        },
        primitive: wgpu::PrimitiveState {
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: Some(wgpu::Face::Back),
            ..Default::default()
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: Some(writes_depth),
            // Draws of one plane are at one depth, and the later of them
            // draws over the earlier; every other draw takes the nearer
            // surface alone.
            depth_compare: Some(match turn.lies() {
                true => wgpu::CompareFunction::LessEqual,
                false => wgpu::CompareFunction::Less,
            }),
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: samples,
            ..Default::default()
        },
        fragment: Some(wgpu::FragmentState {
            module: shaders,
            entry_point: Some(&format!("{draws}{}", variant.entry())),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format: HDR_FORMAT,
                blend,
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        multiview_mask: None,
        cache: None,
    })
}

/// The sky's own pipeline: the two stages that cover the frame with one
/// triangle, over the frame's own values alone.
fn sky(
    device: &wgpu::Device,
    shaders: &wgpu::ShaderModule,
    layout: &wgpu::PipelineLayout,
    samples: u32,
) -> wgpu::RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("mirage-engine skybox"),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shaders,
            entry_point: Some("sky_cover"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            buffers: &[],
        },
        primitive: wgpu::PrimitiveState {
            cull_mode: None,
            ..Default::default()
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: Some(false),
            // The far depth is what the frame was cleared to, so the sky
            // lands wherever nothing nearer was drawn.
            depth_compare: Some(wgpu::CompareFunction::LessEqual),
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: samples,
            ..Default::default()
        },
        fragment: Some(wgpu::FragmentState {
            module: shaders,
            entry_point: Some("sky_draw"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format: HDR_FORMAT,
                blend: None,
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        multiview_mask: None,
        cache: None,
    })
}

/// The two passes a light draws its depth maps with: one takes depth
/// alone, and one draws a fragment stage of its own — to drop the texels a
/// cutout draw's alpha leaves out, to offset a relief's texels from the
/// plane, and to record the depth of the plane a draw lies in.
fn casters(
    device: &wgpu::Device,
    shaders: &wgpu::ShaderModule,
    uniforms: &wgpu::BindGroupLayout,
    textures: &wgpu::BindGroupLayout,
) -> (Skinning, Skinning) {
    let depth_only = pipeline_layout(device, "mirage-engine shadow caster", &[Some(uniforms)]);
    let cutout = pipeline_layout(
        device,
        "mirage-engine shadow caster cutout",
        &[Some(uniforms), Some(textures)],
    );

    let both = |layout, stage, tested| Skinning {
        plain: casting(device, shaders, layout, stage, tested, false),
        skinned: casting(device, shaders, layout, stage, tested, true),
    };

    (
        both(&depth_only, "caster", None),
        both(&cutout, "sampling_caster", Some("caster_sampled")),
    )
}

/// Both sides of a mesh cast, so that a `Plane` or a `Quad`, which has only
/// one, leaves depth in a map wherever it is drawn.
fn casting(
    device: &wgpu::Device,
    shaders: &wgpu::ShaderModule,
    layout: &wgpu::PipelineLayout,
    stage: &str,
    tested: Option<&str>,
    skinned: bool,
) -> wgpu::RenderPipeline {
    let (skinning, blends, buffers) = skinned_stage(skinned);

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(&format!("mirage-engine shadow {stage}{skinning}")),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shaders,
            entry_point: Some(&format!("{blends}{stage}")),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            buffers,
        },
        primitive: wgpu::PrimitiveState {
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: None,
            ..Default::default()
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: Some(true),
            depth_compare: Some(wgpu::CompareFunction::Less),
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState::default(),
        fragment: tested.map(|entry| wgpu::FragmentState {
            module: shaders,
            entry_point: Some(entry),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            targets: &[],
        }),
        multiview_mask: None,
        cache: None,
    })
}

fn storage(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Storage { read_only: true },
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

/// The frame's palette, which the skinned vertex stages alone read.
fn skinning(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::VERTEX,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Storage { read_only: true },
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

/// A buffer holding `joints` matrices, which every pass of the frame reads
/// the poses of its draws from.
fn palette(device: &wgpu::Device, joints: usize) -> wgpu::Buffer {
    buffer(
        device,
        "mirage-engine palette",
        (joints * size_of::<Mat4>()) as wgpu::BufferAddress,
        wgpu::BufferUsages::STORAGE,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::math::Vec3;
    use crate::mesh::{Cube, Mesh};
    use crate::{Transform, View};

    /// A view only ever used to place draws it never turns: they stay where
    /// their own transform left them, however this view looks.
    const ANYWHERE: View = View::look_at(Vec3::Z, Vec3::ZERO);

    /// A draw of `transform` as that view places it.
    fn placed(transform: impl Into<Transform>) -> Placement {
        Cube.at::<()>(transform).record().placement(ANYWHERE)
    }

    #[test]
    fn a_material_fills_the_lanes_the_shader_reads_it_from() {
        let instance = GpuInstance::new(
            placed(Vec3::new(1.0, 2.0, 3.0)),
            Material::shaded(Color::rgb(0.25, 0.5, 0.75), 0.5).emissive(Color::rgb(2.0, 0.0, 4.0)),
            DrawPass::Opaque,
            Frame::default(),
            Relief::of(None, false),
            WorldPlane::NONE,
        );

        assert_eq!(instance.tint, Color::rgb(0.25, 0.5, 0.75));
        assert_eq!(
            instance.params,
            Vec4::new(0.5, 2.0, 0.0, 4.0),
            "litness first, then the surface's own emissive light"
        );
        assert_eq!(
            (instance.roughness, instance.metallic),
            (1.0, 0.0),
            "and a surface that reflects only its base share of the sky, \
             blurred to one color, at every angle"
        );
        assert_eq!(
            instance.model.map(|row| row.w),
            [1.0, 2.0, 3.0],
            "the transposed rows carry the translation in their last lane"
        );
        assert_eq!(
            instance.window,
            Vec4::new(0.0, 0.0, 1.0, 1.0),
            "and the whole texture is sampled where no part was asked for"
        );
    }

    #[test]
    fn a_cutting_draw_carries_its_litness_where_no_plain_one_reaches() {
        let lane = |material: Material, pass| {
            GpuInstance::new(
                placed(Transform::IDENTITY),
                material,
                pass,
                Frame::default(),
                Relief::of(None, false),
                WorldPlane::NONE,
            )
            .params
            .x
        };
        let read_back = |shading: f32| {
            // `forward.wgsl`'s reading of the lane, in the same shape.
            if shading < 0.0 {
                CUTOUT - shading
            } else {
                shading
            }
        };

        for litness in [0.0, 0.5, 1.0] {
            let painted = Material::shaded(Color::WHITE, litness);
            let plain = lane(painted, DrawPass::Opaque);
            let cutting = lane(painted.cutout(), DrawPass::Opaque);
            let cut_by_pass = lane(painted, DrawPass::Cutout);
            let cut_while_blended = lane(painted.cutout(), DrawPass::Translucent);

            assert!(plain >= 0.0 && cutting < 0.0, "{plain} {cutting}");
            assert_eq!(read_back(plain), litness);
            assert_eq!(read_back(cutting), litness);
            assert!(
                cut_by_pass < 0.0 && read_back(cut_by_pass) == litness,
                "a style's cutout pass cuts what its material never asked to"
            );
            assert!(
                cut_while_blended < 0.0,
                "and a blended draw keeps the cut its material asked for"
            );
        }
    }

    #[test]
    fn an_instance_stays_the_size_the_buffer_layout_steps_by() {
        assert_eq!(size_of::<GpuInstance>(), 128);
        assert_eq!(
            BUFFER_LAYOUTS[1].array_stride,
            size_of::<GpuInstance>() as wgpu::BufferAddress
        );
    }

    #[test]
    fn the_shader_declares_every_stage_the_forward_pipelines_are_built_from() {
        let shader = surface_style::built_in();
        let declared = |entry: String| {
            assert!(
                shader.contains(&format!("fn {entry}(")),
                "no stage of the shader is named {entry}"
            );
        };

        for turn in [Turn::Placed, Turn::Flat, Turn::Faced] {
            let (_, places, draws) = turn.stage();
            for skinned in [false, true] {
                let (_, blends, _) = skinned_stage(skinned);
                declared(format!("{places}{blends}vertex"));
            }
            for variant in [
                Variant::Opaque,
                Variant::Cutout,
                Variant::Transparent,
                Variant::Additive,
            ] {
                declared(format!("{draws}{}", variant.entry()));
            }
        }
        for skinned in [false, true] {
            let (_, blends, _) = skinned_stage(skinned);
            declared(format!("{blends}caster"));
            declared(format!("{blends}sampling_caster"));
        }
        declared("caster_sampled".to_owned());
    }
}