codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
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
//! Meshes the code makes for itself, for when there is no asset yet.
//!
//! A scene testing a control scheme or a camera wants something in front of
//! it, and a `.glb` is a lot of ceremony for a cube. These build the same
//! [`MeshData`] the loader produces, so everything downstream — instancing,
//! shadows, the shadow-map fit — treats them like any other mesh.
//!
//! The size is baked into the vertices rather than carried as a scale, since
//! [`Transform`] scales uniformly; a primitive is uploaded once per distinct
//! size and shared from then on (see [`crate::AppState::spawn_primitive`]).
use glam::{Vec2, Vec3};

use crate::mesh::{MeshData, Vertex};
use crate::render3d::Transform;
use crate::ui::Color;

/// A shape that can build its own mesh.
///
/// [`name`](Primitive::name) is the key it is cached under, so two boxes of
/// the same size share one upload and two of different sizes do not collide.
pub trait Primitive {
    fn name(&self) -> String;
    fn build(&self) -> MeshData;
    /// Where it goes, and what colour to draw it — the parts that belong to
    /// the instance rather than the mesh.
    fn placement(&self) -> (Transform, Option<Color>);
}

/// A rectangular box, centred on its own origin.
///
/// ```no_run
/// # use codecraft::{AppState, primitives};
/// # fn demo(app: &mut AppState) {
/// app.spawn_primitive(primitives::Box::cube(1.0));
/// # }
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Box {
    pub size: Vec3,
    pub transform: Transform,
    pub color: Option<Color>,
}

impl Box {
    pub fn new(width: f32, height: f32, depth: f32) -> Self {
        Self {
            size: Vec3::new(width, height, depth),
            transform: Transform::default(),
            color: None,
        }
    }

    pub fn cube(size: f32) -> Self {
        Self::new(size, size, size)
    }

    pub fn at(mut self, x: f32, y: f32, z: f32) -> Self {
        self.transform.translation = Vec3::new(x, y, z);
        self
    }

    /// Rotation about the up axis, in radians.
    pub fn yaw(mut self, radians: f32) -> Self {
        self.transform.set_yaw(radians);
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

impl Primitive for Box {
    fn name(&self) -> String {
        // Three decimals: enough that two sizes anyone would tell apart get
        // their own mesh, coarse enough that float noise does not upload a
        // fresh one every time a size is recomputed.
        format!(
            "primitive:box:{:.3}x{:.3}x{:.3}",
            self.size.x, self.size.y, self.size.z
        )
    }

    fn build(&self) -> MeshData {
        let half = self.size.abs() * 0.5;
        let mut vertices = Vec::with_capacity(24);
        let mut indices = Vec::with_capacity(36);

        // Each face gets its own four vertices so the normals stay square —
        // eight shared corners would round the box off in the shading.
        //
        // `u` and `v` are the face's own axes, ordered so that `u × v` is the
        // outward normal, which is what makes the two triangles wind
        // counter-clockwise seen from outside and survive back-face culling.
        let faces = [
            (Vec3::X, Vec3::NEG_Z, Vec3::Y),
            (Vec3::NEG_X, Vec3::Z, Vec3::Y),
            (Vec3::Y, Vec3::X, Vec3::NEG_Z),
            (Vec3::NEG_Y, Vec3::X, Vec3::Z),
            (Vec3::Z, Vec3::X, Vec3::Y),
            (Vec3::NEG_Z, Vec3::NEG_X, Vec3::Y),
        ];

        for (normal, u, v) in faces {
            let base = vertices.len() as u32;
            let (center, du, dv) = (normal * half, u * half, v * half);
            for corner in [
                center - du - dv,
                center + du - dv,
                center + du + dv,
                center - du + dv,
            ] {
                vertices.push(Vertex {
                    position: corner.to_array(),
                    normal: normal.to_array(),
                });
            }
            indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
        }

        MeshData {
            name: self.name(),
            vertices,
            indices,
            base_color: self.color,
            min: -half,
            max: half,
        }
    }

    fn placement(&self) -> (Transform, Option<Color>) {
        (self.transform, self.color)
    }
}

/// How many strips a sphere is cut into around its equator, and how many
/// bands from pole to pole.
///
/// Sixteen by ten is faceted up close and round from a tank's length away,
/// which is where a shell or a marker gets looked at; fine enough for that,
/// and coarse enough that a sky full of them is nothing to draw.
const SPHERE_SEGMENTS: u32 = 16;
const SPHERE_RINGS: u32 = 10;

/// A ball, centred on its own origin.
///
/// ```no_run
/// # use codecraft::{AppState, primitives};
/// # fn demo(app: &mut AppState) {
/// app.spawn_primitive(primitives::Sphere::new(0.2).at(0.0, 1.0, 0.0));
/// # }
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Sphere {
    pub radius: f32,
    pub transform: Transform,
    pub color: Option<Color>,
}

impl Sphere {
    pub fn new(radius: f32) -> Self {
        Self {
            radius,
            transform: Transform::default(),
            color: None,
        }
    }

    pub fn at(mut self, x: f32, y: f32, z: f32) -> Self {
        self.transform.translation = Vec3::new(x, y, z);
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

impl Primitive for Sphere {
    fn name(&self) -> String {
        // Three decimals, for the same reason as the box.
        format!("primitive:sphere:{:.3}", self.radius)
    }

    fn build(&self) -> MeshData {
        use std::f32::consts::{PI, TAU};
        let radius = self.radius.abs();
        let (segments, rings) = (SPHERE_SEGMENTS, SPHERE_RINGS);
        let mut vertices = Vec::with_capacity((2 + (rings - 1) * segments) as usize);
        let mut indices = Vec::with_capacity(((rings - 1) * segments * 6) as usize);

        // On a sphere a vertex's direction from the centre is its normal, so
        // one direction serves for both and the shading comes out round,
        // with no seam: there is one column of vertices at every longitude
        // and one vertex at each pole, and the strips wrap round to meet.
        let mut push = |direction: Vec3| {
            vertices.push(Vertex {
                position: (direction * radius).to_array(),
                normal: direction.to_array(),
            });
        };
        push(Vec3::Y);
        for ring in 1..rings {
            let (sin_theta, cos_theta) = (PI * ring as f32 / rings as f32).sin_cos();
            for segment in 0..segments {
                let (sin_phi, cos_phi) = (TAU * segment as f32 / segments as f32).sin_cos();
                push(Vec3::new(
                    sin_theta * cos_phi,
                    cos_theta,
                    sin_theta * sin_phi,
                ));
            }
        }
        push(Vec3::NEG_Y);

        let north = 0;
        let south = 1 + (rings - 1) * segments;
        let at = |ring: u32, segment: u32| 1 + (ring - 1) * segments + segment % segments;

        // Going round a ring runs +z from +x, and down a strip runs towards
        // -y; round then down is what crosses to the outside, which is the
        // order every triangle here keeps so back-face culling keeps them.
        for segment in 0..segments {
            indices.extend([at(1, segment), north, at(1, segment + 1)]);
        }
        for ring in 1..rings - 1 {
            for segment in 0..segments {
                let (a, b) = (at(ring, segment), at(ring + 1, segment));
                let (c, d) = (at(ring + 1, segment + 1), at(ring, segment + 1));
                indices.extend([a, d, b, b, d, c]);
            }
        }
        for segment in 0..segments {
            indices.extend([at(rings - 1, segment), at(rings - 1, segment + 1), south]);
        }

        MeshData {
            name: self.name(),
            vertices,
            indices,
            base_color: self.color,
            min: Vec3::splat(-radius),
            max: Vec3::splat(radius),
        }
    }

    fn placement(&self) -> (Transform, Option<Color>) {
        (self.transform, self.color)
    }
}

/// A convex outline drawn out sideways: a profile in the Y–Z plane, swept
/// along X by a width and centred on its own origin across that width, the
/// way a box is.
///
/// For every shape that is a box with its corners cut — a track with its
/// noses raised, a hull with a glacis, a ramp. The profile is a side
/// elevation, given as `(z, y)` points: z across the page and y up it, the
/// way a vehicle is drawn on one. It has to be convex, because the ends are
/// filled as fans from their first corner and because the point of the
/// thing is that the convex hull of its corners *is* this solid, so a
/// collider can be built from the same points the mesh is: see
/// [`Extrusion::corners`].
///
/// Wound either way. Counter-clockwise as plotted is the outline going
/// round with the inside on its left, and one given the other way is
/// turned round rather than drawn inside out — which, with back-face
/// culling on, would be a shape that could only be seen from within.
///
/// ```no_run
/// # use codecraft::{AppState, primitives};
/// # use codecraft::glam::Vec2;
/// # fn demo(app: &mut AppState) {
/// // A wedge: a metre long, half a metre high at its back, a metre wide.
/// let wedge = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 0.5)];
/// app.spawn_primitive(primitives::Extrusion::new(wedge, 1.0));
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Extrusion {
    /// The outline, as `(z, y)` points going round counter-clockwise.
    pub profile: Vec<Vec2>,
    pub width: f32,
    pub transform: Transform,
    pub color: Option<Color>,
}

impl Extrusion {
    pub fn new(profile: impl Into<Vec<Vec2>>, width: f32) -> Self {
        let mut profile = profile.into();
        assert!(
            profile.len() >= 3,
            "an outline needs three corners at the least, and this has {}",
            profile.len(),
        );
        if signed_area(&profile) < 0.0 {
            profile.reverse();
        }
        // Going round counter-clockwise, every corner turns left: that is
        // what convex is. It refuses a corner that turns right, which
        // would give a cap that crosses itself and a hull that is not the
        // solid drawn; one that does not turn at all, a point on the
        // straight between its neighbours, which the hull would drop and
        // the mesh would keep; and one that is the same point again,
        // whose edge has no length and so no normal.
        let sides = profile.len();
        for (i, &from) in profile.iter().enumerate() {
            let (to, next) = (profile[(i + 1) % sides], profile[(i + 2) % sides]);
            assert!(
                (to - from).perp_dot(next - to) > 0.0,
                "an outline has to be convex, and this one does not turn left at {to}: {profile:?}",
            );
        }
        Self {
            profile,
            width,
            transform: Transform::default(),
            color: None,
        }
    }

    pub fn at(mut self, x: f32, y: f32, z: f32) -> Self {
        self.transform.translation = Vec3::new(x, y, z);
        self
    }

    /// Rotation about the up axis, in radians.
    pub fn yaw(mut self, radians: f32) -> Self {
        self.transform.set_yaw(radians);
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Every corner of the solid: the outline at either end of the width.
    ///
    /// The convex hull of these is exactly this solid, which is what lets a
    /// collider be the same shape as the mesh rather than a box that
    /// stands in for it.
    pub fn corners(&self) -> Vec<Vec3> {
        let half = self.width.abs() * 0.5;
        self.profile
            .iter()
            .flat_map(|&point| [corner(-half, point), corner(half, point)])
            .collect()
    }
}

/// Where a point of the outline lands in space, at one end of the width.
fn corner(x: f32, point: Vec2) -> Vec3 {
    Vec3::new(x, point.y, point.x)
}

/// Twice the area inside an outline, signed: positive going round
/// counter-clockwise as plotted, negative the other way.
fn signed_area(profile: &[Vec2]) -> f32 {
    profile
        .iter()
        .zip(profile.iter().cycle().skip(1))
        .map(|(from, to)| from.x * to.y - to.x * from.y)
        .sum()
}

impl Primitive for Extrusion {
    fn name(&self) -> String {
        // Three decimals, for the same reason as the box: the outline is
        // the key, and float noise in a recomputed one should not upload
        // a fresh mesh. Begun from the same corner whichever it was given
        // from — the one furthest along -z, and the lowest of those — so
        // the same outline begun elsewhere is the same mesh rather than
        // a second copy of it.
        let sides = self.profile.len();
        let start = (0..sides)
            .min_by(|&a, &b| {
                let (a, b) = (self.profile[a], self.profile[b]);
                a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))
            })
            .unwrap_or(0);
        let outline: String = (0..sides)
            .map(|i| self.profile[(start + i) % sides])
            .map(|point| format!(":{:.3},{:.3}", point.x, point.y))
            .collect();
        format!("primitive:extrusion:{:.3}{outline}", self.width)
    }

    fn build(&self) -> MeshData {
        let half = self.width.abs() * 0.5;
        let sides = self.profile.len();
        let mut vertices = Vec::with_capacity(sides * 6);
        let mut indices = Vec::with_capacity(sides * 6 + (sides - 2) * 6);

        // A face per edge of the outline: the strip between the edge at one
        // end of the width and the same edge at the other. Each has its own
        // four vertices so the shading stays flat across it, for the reason
        // the box does not share corners.
        //
        // Outward is square to the edge, on its right going round: with the
        // outline counter-clockwise the inside is on the left. The strip's
        // two triangles are wound so that `u × v` is that normal, `u` being
        // across the width and `v` along the edge.
        for (i, &from) in self.profile.iter().enumerate() {
            let to = self.profile[(i + 1) % sides];
            let edge = to - from;
            let normal = Vec3::new(0.0, -edge.x, edge.y).normalize_or_zero();
            let base = vertices.len() as u32;
            for position in [
                corner(-half, from),
                corner(half, from),
                corner(half, to),
                corner(-half, to),
            ] {
                vertices.push(Vertex {
                    position: position.to_array(),
                    normal: normal.to_array(),
                });
            }
            indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
        }

        // The two ends, each a fan from its first corner — which is what
        // needs the outline convex. Seen from the far end the outline goes
        // round clockwise, so that fan is taken round the other way.
        for (x, normal) in [(-half, Vec3::NEG_X), (half, Vec3::X)] {
            let base = vertices.len() as u32;
            for &point in &self.profile {
                vertices.push(Vertex {
                    position: corner(x, point).to_array(),
                    normal: normal.to_array(),
                });
            }
            for i in 1..sides as u32 - 1 {
                let (a, b) = (base + i, base + i + 1);
                match x < 0.0 {
                    true => indices.extend([base, a, b]),
                    false => indices.extend([base, b, a]),
                }
            }
        }

        let (mut min, mut max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
        for position in self.corners() {
            min = min.min(position);
            max = max.max(position);
        }
        MeshData {
            name: self.name(),
            vertices,
            indices,
            base_color: self.color,
            min,
            max,
        }
    }

    fn placement(&self) -> (Transform, Option<Color>) {
        (self.transform, self.color)
    }
}

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

    #[test]
    fn a_cube_is_six_square_faces_that_do_not_share_corners() {
        let mesh = Box::cube(1.0).build();
        assert_eq!(mesh.vertices.len(), 24, "four vertices per face");
        assert_eq!(mesh.indices.len(), 36, "two triangles per face");
        assert_eq!(mesh.min, Vec3::splat(-0.5));
        assert_eq!(mesh.max, Vec3::splat(0.5));

        // Every vertex is a corner of the box, and its normal is the face's.
        for vertex in &mesh.vertices {
            let position = Vec3::from(vertex.position);
            assert_eq!(position.abs(), Vec3::splat(0.5), "{position}");
            assert_eq!(Vec3::from(vertex.normal).length(), 1.0);
        }
    }

    #[test]
    fn every_face_winds_outward() {
        // Back-face culling is on, so a face wound the wrong way is invisible
        // from outside and solid from within.
        let mesh = Box::new(2.0, 1.0, 3.0).build();
        for triangle in mesh.indices.chunks(3) {
            let corner = |i: usize| Vec3::from(mesh.vertices[triangle[i] as usize].position);
            let (a, b, c) = (corner(0), corner(1), corner(2));
            let facing = (b - a).cross(c - a).normalize();
            let outward = Vec3::from(mesh.vertices[triangle[0] as usize].normal);
            assert!((facing - outward).length() < 1e-5, "{facing} vs {outward}");
        }
    }

    #[test]
    fn size_is_baked_in_and_named_so_two_sizes_do_not_share_a_mesh() {
        let mesh = Box::new(2.0, 4.0, 6.0).build();
        assert_eq!(mesh.max, Vec3::new(1.0, 2.0, 3.0));
        assert_ne!(Box::cube(1.0).name(), Box::cube(2.0).name());
        assert_eq!(Box::cube(1.0).name(), Box::new(1.0, 1.0, 1.0).name());
    }

    #[test]
    fn a_sphere_is_one_vertex_per_pole_and_a_ring_between_every_band() {
        let mesh = Sphere::new(2.0).build();
        assert_eq!(
            mesh.vertices.len() as u32,
            2 + (SPHERE_RINGS - 1) * SPHERE_SEGMENTS,
            "the poles, and a row of vertices at every latitude between them",
        );
        // Two triangles per quad, but the strips against each pole are
        // triangles already: one each rather than two.
        assert_eq!(
            mesh.indices.len() as u32,
            (SPHERE_RINGS * 2 - 2) * SPHERE_SEGMENTS * 3
        );
        assert_eq!(mesh.indices.len() % 3, 0);
        assert_eq!(mesh.min, Vec3::splat(-2.0));
        assert_eq!(mesh.max, Vec3::splat(2.0));
    }

    #[test]
    fn every_sphere_vertex_is_on_the_surface_with_its_normal_pointing_away() {
        let mesh = Sphere::new(2.0).build();
        for vertex in &mesh.vertices {
            let position = Vec3::from(vertex.position);
            let normal = Vec3::from(vertex.normal);
            assert!((position.length() - 2.0).abs() < 1e-5, "{position}");
            assert!((normal.length() - 1.0).abs() < 1e-5, "{normal}");
            assert!(
                normal.dot(position.normalize()) > 0.999,
                "{normal} is not the direction of {position}",
            );
        }
    }

    #[test]
    fn every_sphere_triangle_winds_outward() {
        // The same rule as the box, and for the same reason: a face wound
        // the wrong way is culled from outside and shows from within.
        let mesh = Sphere::new(1.0).build();
        for triangle in mesh.indices.chunks(3) {
            let corner = |i: usize| Vec3::from(mesh.vertices[triangle[i] as usize].position);
            let (a, b, c) = (corner(0), corner(1), corner(2));
            let facing = (b - a).cross(c - a);
            assert!(
                facing.length() > 1e-6,
                "a triangle with no area: {a} {b} {c}"
            );
            let outward = (a + b + c) / 3.0;
            assert!(facing.dot(outward) > 0.0, "{facing} faces in at {outward}");
        }
    }

    #[test]
    fn a_sphere_is_named_by_its_radius() {
        assert_ne!(Sphere::new(1.0).name(), Sphere::new(2.0).name());
        assert_eq!(Sphere::new(1.0).name(), Sphere::new(1.0001).name());
    }

    /// A ramp: three metres along, a metre high at the back with a flat
    /// metre on top, two wide. The slope is the face that matters — a
    /// box's faces all lie along an axis, and a normal got wrong by a
    /// sign would still be unit; the slope leans, so its normal has to be
    /// worked out.
    fn ramp() -> Extrusion {
        Extrusion::new(
            [
                Vec2::new(0.0, 0.0),
                Vec2::new(3.0, 0.0),
                Vec2::new(3.0, 1.0),
                Vec2::new(2.0, 1.0),
            ],
            2.0,
        )
    }

    #[test]
    fn an_extrusion_is_a_face_per_edge_and_a_cap_at_each_end() {
        let mesh = ramp().build();
        assert_eq!(
            mesh.vertices.len(),
            4 * 4 + 2 * 4,
            "four vertices a side, and the outline again at each end",
        );
        assert_eq!(
            mesh.indices.len(),
            4 * 6 + 2 * 6,
            "two triangles a side, and a fan of two at each end",
        );
        assert_eq!(mesh.min, Vec3::new(-1.0, 0.0, 0.0));
        assert_eq!(mesh.max, Vec3::new(1.0, 1.0, 3.0));
    }

    #[test]
    fn every_extrusion_face_winds_outward_along_its_own_normal() {
        let mesh = ramp().build();
        for triangle in mesh.indices.chunks(3) {
            let corner = |i: usize| Vec3::from(mesh.vertices[triangle[i] as usize].position);
            let (a, b, c) = (corner(0), corner(1), corner(2));
            let facing = (b - a).cross(c - a);
            assert!(
                facing.length() > 1e-6,
                "a triangle with no area: {a} {b} {c}"
            );
            let facing = facing.normalize();
            for i in 0..3 {
                let normal = Vec3::from(mesh.vertices[triangle[i] as usize].normal);
                assert!((normal.length() - 1.0).abs() < 1e-5, "{normal}");
                assert!((facing - normal).length() < 1e-5, "{facing} vs {normal}");
            }
        }
        let slope = Vec3::new(0.0, 2.0, -1.0).normalize();
        assert!(
            mesh.vertices
                .iter()
                .any(|vertex| (Vec3::from(vertex.normal) - slope).length() < 1e-5),
            "and one of the faces is the slope, facing up and forward",
        );
    }

    #[test]
    fn an_outline_of_a_rectangle_is_a_box() {
        let rectangle = [
            Vec2::new(-1.5, -0.5),
            Vec2::new(1.5, -0.5),
            Vec2::new(1.5, 0.5),
            Vec2::new(-1.5, 0.5),
        ];
        let mesh = Extrusion::new(rectangle, 2.0).build();
        let cube = Box::new(2.0, 1.0, 3.0).build();
        assert_eq!(mesh.vertices.len(), cube.vertices.len());
        assert_eq!(mesh.indices.len(), cube.indices.len());
        assert_eq!(mesh.min, cube.min);
        assert_eq!(mesh.max, cube.max);
        for vertex in &mesh.vertices {
            let position = Vec3::from(vertex.position);
            assert_eq!(position.abs(), Vec3::new(1.0, 0.5, 1.5), "{position}");
        }
    }

    #[test]
    fn an_outline_given_clockwise_is_turned_round_rather_than_drawn_inside_out() {
        let mut backwards = ramp().profile.clone();
        backwards.reverse();
        let turned = Extrusion::new(backwards, 2.0);
        assert_eq!(turned.profile, ramp().profile);
        assert_eq!(turned.name(), ramp().name(), "and it is the same mesh");
    }

    #[test]
    fn the_corners_are_what_is_drawn_and_nothing_else_is() {
        let shape = ramp();
        let corners = shape.corners();
        let mesh = shape.build();
        assert_eq!(corners.len(), 8, "the outline at either end of the width");
        for vertex in &mesh.vertices {
            let position = Vec3::from(vertex.position);
            assert!(
                corners
                    .iter()
                    .any(|corner| (*corner - position).length() < 1e-6),
                "{position} is drawn and is not a corner",
            );
        }
        for corner in &corners {
            assert!(
                mesh.vertices
                    .iter()
                    .any(|vertex| (Vec3::from(vertex.position) - *corner).length() < 1e-6),
                "{corner} is a corner and is not drawn",
            );
        }
    }

    #[test]
    fn an_extrusion_is_named_by_its_width_and_its_outline() {
        assert_eq!(Extrusion::new(ramp().profile, 2.0).name(), ramp().name());
        assert_eq!(Extrusion::new(ramp().profile, 2.0001).name(), ramp().name());
        assert_ne!(Extrusion::new(ramp().profile, 3.0).name(), ramp().name());
        let mut taller = ramp().profile;
        taller[3].y = 1.5;
        assert_ne!(Extrusion::new(taller, 2.0).name(), ramp().name());
    }

    #[test]
    fn the_same_outline_begun_at_another_corner_is_the_same_mesh() {
        let mut elsewhere = ramp().profile;
        elsewhere.rotate_left(2);
        assert_ne!(elsewhere, ramp().profile, "begun two corners on");
        assert_eq!(Extrusion::new(elsewhere, 2.0).name(), ramp().name());
    }

    #[test]
    #[should_panic(expected = "convex")]
    fn an_outline_with_a_corner_turning_in_is_refused() {
        let notch = [
            Vec2::new(0.0, 0.0),
            Vec2::new(2.0, 0.0),
            Vec2::new(2.0, 2.0),
            Vec2::new(1.0, 0.5),
            Vec2::new(0.0, 2.0),
        ];
        Extrusion::new(notch, 1.0);
    }

    #[test]
    #[should_panic(expected = "convex")]
    fn an_outline_with_a_corner_given_twice_is_refused() {
        let mut stutter = ramp().profile;
        stutter.insert(1, stutter[1]);
        Extrusion::new(stutter, 1.0);
    }

    #[test]
    #[should_panic(expected = "convex")]
    fn an_outline_with_a_corner_on_a_straight_is_refused() {
        let mut flat = ramp().profile;
        flat.insert(1, Vec2::new(1.5, 0.0));
        Extrusion::new(flat, 1.0);
    }
}