codecraft 0.2.0

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, a yakui-drawn UI, audio and gamepad haptics; its binary maps any folder, and the symbols of its Rust files, as a 3D wall of boxes
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
//! Procedural meshes (box, sphere, extrusion) that build the same [`MeshData`] the loader produces.
//! Each shape is a component: spawn it with [`crate::AppState::spawn_entity`] and the app
//! gives the entity a mesh, uploaded once per distinct size and shared.
use glam::{Vec2, Vec3};

use crate::ecs::Component;
use crate::mesh::{MeshData, Vertex};
use crate::render3d::Transform;
use crate::sceneobjects::{Category, SceneObject};
use crate::ui::Color;
use crate::ui::icons::path;

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

impl Box {
    pub fn new(width: f32, height: f32, depth: f32) -> Self {
        Self {
            size: Vec3::new(width, height, depth),
            transform: Transform::default(),
            color: None,
            name: 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
    }

    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
    }

    /// Sets the whole placement; [`Self::at`] is the shorthand for a position alone.
    pub fn transform(mut self, transform: Transform) -> Self {
        self.transform = transform;
        self
    }

    /// What the outliner calls the entity, instead of the shape's own name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl Box {
    pub fn object(&self) -> SceneObject {
        let label = match self.size.x == self.size.y && self.size.y == self.size.z {
            true => "Cube",
            false => "Box",
        };
        SceneObject::new(
            self.name.as_deref().unwrap_or(label),
            path::CUBE,
            Category::Mesh,
        )
    }

    /// The name the shared mesh is filed under: shapes of one size share one upload.
    pub fn key(&self) -> String {
        // Three decimals so float noise in a recomputed size does not upload a fresh mesh.
        format!(
            "primitive:box:{:.3}x{:.3}x{:.3}",
            self.size.x, self.size.y, self.size.z
        )
    }

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

        // Four vertices per face keeps the normals square; `u × v` is the outward normal so winding survives 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.key(),
            vertices,
            indices,
            base_color: self.color,
            min: -half,
            max: half,
        }
    }
}

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_entity(primitives::Sphere::new(0.2).at(0.0, 1.0, 0.0));
/// # }
/// ```
#[derive(Clone, Debug, Component)]
pub struct Sphere {
    pub radius: f32,
    pub transform: Transform,
    pub color: Option<Color>,
    pub name: Option<String>,
}

impl Sphere {
    pub fn new(radius: f32) -> Self {
        Self {
            radius,
            transform: Transform::default(),
            color: None,
            name: 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
    }

    /// Sets the whole placement; [`Self::at`] is the shorthand for a position alone.
    pub fn transform(mut self, transform: Transform) -> Self {
        self.transform = transform;
        self
    }

    /// What the outliner calls the entity, instead of the shape's own name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl Sphere {
    pub fn object(&self) -> SceneObject {
        SceneObject::new(
            self.name.as_deref().unwrap_or("Sphere"),
            path::CIRCLE,
            Category::Mesh,
        )
    }

    /// The name the shared mesh is filed under: shapes of one size share one upload.
    pub fn key(&self) -> String {
        format!("primitive:sphere:{:.3}", self.radius)
    }

    pub fn mesh(&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);

        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;

        // Round the ring then down the strip winds outward, which back-face culling needs.
        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.key(),
            vertices,
            indices,
            base_color: self.color,
            min: Vec3::splat(-radius),
            max: Vec3::splat(radius),
        }
    }
}

/// A convex `(z, y)` profile swept along X by a width and centred across it.
/// The profile must be convex (its corners' hull is the solid; see [`Extrusion::corners`]) and may be wound either way.
///
/// ```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_entity(primitives::Extrusion::new(wedge, 1.0));
/// # }
/// ```
#[derive(Clone, Debug, Component)]
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>,
    pub name: Option<String>,
}

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();
        }
        // Strictly left-turning corners: rejects concave, collinear and repeated points alike.
        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,
            name: None,
        }
    }

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

    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
    }

    /// Sets the whole placement; [`Self::at`] is the shorthand for a position alone.
    pub fn transform(mut self, transform: Transform) -> Self {
        self.transform = transform;
        self
    }

    /// What the outliner calls the entity, instead of the shape's own name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Every corner of the solid; their convex hull is exactly this solid, so a collider can share them.
    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()
    }
}

fn corner(x: f32, point: Vec2) -> Vec3 {
    Vec3::new(x, point.y, point.x)
}

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 Extrusion {
    pub fn object(&self) -> SceneObject {
        SceneObject::new(
            self.name.as_deref().unwrap_or("Extrusion"),
            path::SHAPES,
            Category::Mesh,
        )
    }

    /// The name the shared mesh is filed under: shapes of one size share one upload.
    pub fn key(&self) -> String {
        // Canonical start corner (min z, then min y) so the same outline begun elsewhere is the same mesh.
        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)
    }

    pub fn mesh(&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);

        // Outward is square to the edge on its right (the outline is counter-clockwise).
        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]);
        }

        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.key(),
            vertices,
            indices,
            base_color: self.color,
            min,
            max,
        }
    }
}

#[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).mesh();
        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));

        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() {
        let mesh = Box::new(2.0, 1.0, 3.0).mesh();
        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).mesh();
        assert_eq!(mesh.max, Vec3::new(1.0, 2.0, 3.0));
        assert_ne!(Box::cube(1.0).key(), Box::cube(2.0).key());
        assert_eq!(Box::cube(1.0).key(), Box::new(1.0, 1.0, 1.0).key());
    }

    #[test]
    fn a_sphere_is_one_vertex_per_pole_and_a_ring_between_every_band() {
        let mesh = Sphere::new(2.0).mesh();
        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",
        );
        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).mesh();
        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() {
        let mesh = Sphere::new(1.0).mesh();
        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).key(), Sphere::new(2.0).key());
        assert_eq!(Sphere::new(1.0).key(), Sphere::new(1.0001).key());
    }

    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().mesh();
        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().mesh();
        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).mesh();
        let cube = Box::new(2.0, 1.0, 3.0).mesh();
        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.key(), ramp().key(), "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.mesh();
        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).key(), ramp().key());
        assert_eq!(Extrusion::new(ramp().profile, 2.0001).key(), ramp().key());
        assert_ne!(Extrusion::new(ramp().profile, 3.0).key(), ramp().key());
        let mut taller = ramp().profile;
        taller[3].y = 1.5;
        assert_ne!(Extrusion::new(taller, 2.0).key(), ramp().key());
    }

    #[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).key(), ramp().key());
    }

    #[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);
    }
}