bevy_mesh 0.19.1

Provides mesh types for Bevy Engine
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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
use core::f32::consts::FRAC_PI_2;
use core::mem;

use crate::{primitives::dim3::triangle3d, Indices, Mesh, PerimeterSegment, VertexAttributeValues};
use bevy_asset::RenderAssetUsages;

use super::{Extrudable, MeshBuilder, Meshable};
use bevy_math::prelude::Polyline2d;
use bevy_math::{
    ops,
    primitives::{
        Annulus, Capsule2d, Circle, CircularSector, CircularSegment, ConvexPolygon, Ellipse,
        Primitive2d, Rectangle, RegularPolygon, Rhombus, Ring, Segment2d, Triangle2d, Triangle3d,
        WindingOrder,
    },
    FloatExt, Vec2, Vec3,
};
use bevy_reflect::prelude::*;
use wgpu_types::PrimitiveTopology;

/// A builder used for creating a [`Mesh`] with a [`Circle`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct CircleMeshBuilder {
    /// The [`Circle`] shape.
    pub circle: Circle,
    /// The number of vertices used for the circle mesh.
    /// The default is `32`.
    #[doc(alias = "vertices")]
    pub resolution: u32,
}

impl Default for CircleMeshBuilder {
    fn default() -> Self {
        Self {
            circle: Circle::default(),
            resolution: 32,
        }
    }
}

impl CircleMeshBuilder {
    /// Creates a new [`CircleMeshBuilder`] from a given radius and vertex count.
    #[inline]
    pub const fn new(radius: f32, resolution: u32) -> Self {
        Self {
            circle: Circle { radius },
            resolution,
        }
    }

    /// Sets the number of vertices used for the circle mesh.
    #[inline]
    #[doc(alias = "vertices")]
    pub const fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }
}

impl MeshBuilder for CircleMeshBuilder {
    fn build(&self) -> Mesh {
        Ellipse::new(self.circle.radius, self.circle.radius)
            .mesh()
            .resolution(self.resolution)
            .build()
    }
}

impl Extrudable for CircleMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Smooth {
            first_normal: Vec2::Y,
            last_normal: Vec2::Y,
            indices: (0..self.resolution).chain([0]).collect(),
        }]
    }
}

impl Meshable for Circle {
    type Output = CircleMeshBuilder;

    fn mesh(&self) -> Self::Output {
        CircleMeshBuilder {
            circle: *self,
            ..Default::default()
        }
    }
}

impl From<Circle> for Mesh {
    fn from(circle: Circle) -> Self {
        circle.mesh().build()
    }
}

/// Specifies how to generate UV-mappings for the [`CircularSector`] and [`CircularSegment`] shapes.
///
/// Currently the only variant is `Mask`, which is good for showing a portion of a texture that includes
/// the entire circle, particularly the same texture will be displayed with different fractions of a
/// complete circle.
///
/// It's expected that more will be added in the future, such as a variant that causes the texture to be
/// scaled to fit the bounding box of the shape, which would be good for packed textures only including the
/// portion of the circle that is needed to display.
#[derive(Copy, Clone, Debug, PartialEq, Reflect)]
#[reflect(Default, Debug, Clone)]
#[non_exhaustive]
pub enum CircularMeshUvMode {
    /// Treats the shape as a mask over a circle of equal size and radius,
    /// with the center of the circle at the center of the texture.
    Mask {
        /// Angle by which to rotate the shape when generating the UV map.
        angle: f32,
    },
}

impl Default for CircularMeshUvMode {
    fn default() -> Self {
        CircularMeshUvMode::Mask { angle: 0.0 }
    }
}

/// A builder used for creating a [`Mesh`] with a [`CircularSector`] shape.
///
/// The resulting mesh will have a UV-map such that the center of the circle is
/// at the center of the texture.
#[derive(Clone, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct CircularSectorMeshBuilder {
    /// The sector shape.
    pub sector: CircularSector,
    /// The number of vertices used for the arc portion of the sector mesh.
    /// The default is `32`.
    #[doc(alias = "vertices")]
    pub resolution: u32,
    /// The UV mapping mode
    pub uv_mode: CircularMeshUvMode,
}

impl Default for CircularSectorMeshBuilder {
    fn default() -> Self {
        Self {
            sector: CircularSector::default(),
            resolution: 32,
            uv_mode: CircularMeshUvMode::default(),
        }
    }
}

impl CircularSectorMeshBuilder {
    /// Creates a new [`CircularSectorMeshBuilder`] from a given sector
    #[inline]
    pub fn new(sector: CircularSector) -> Self {
        Self {
            sector,
            ..Self::default()
        }
    }

    /// Sets the number of vertices used for the sector mesh.
    #[inline]
    #[doc(alias = "vertices")]
    pub const fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }

    /// Sets the uv mode used for the sector mesh
    #[inline]
    pub const fn uv_mode(mut self, uv_mode: CircularMeshUvMode) -> Self {
        self.uv_mode = uv_mode;
        self
    }
}

impl MeshBuilder for CircularSectorMeshBuilder {
    fn build(&self) -> Mesh {
        let resolution = self.resolution as usize;
        let mut indices = Vec::with_capacity((resolution - 1) * 3);
        let mut positions = Vec::with_capacity(resolution + 1);
        let normals = vec![[0.0, 0.0, 1.0]; resolution + 1];
        let mut uvs = Vec::with_capacity(resolution + 1);

        let CircularMeshUvMode::Mask { angle: uv_angle } = self.uv_mode;

        // Push the center of the circle.
        positions.push([0.0; 3]);
        uvs.push([0.5; 2]);

        let first_angle = FRAC_PI_2 - self.sector.half_angle();
        let last_angle = FRAC_PI_2 + self.sector.half_angle();
        let last_i = (self.resolution - 1) as f32;
        for i in 0..self.resolution {
            let angle = f32::lerp(first_angle, last_angle, i as f32 / last_i);

            // Compute the vertex
            let vertex = self.sector.radius() * Vec2::from_angle(angle);
            // Compute the UV coordinate by taking the modified angle's unit vector, negating the Y axis, and rescaling and centering it at (0.5, 0.5).
            // We accomplish the Y axis flip by negating the angle.
            let uv =
                Vec2::from_angle(-(angle + uv_angle)).mul_add(Vec2::splat(0.5), Vec2::splat(0.5));

            positions.push([vertex.x, vertex.y, 0.0]);
            uvs.push([uv.x, uv.y]);
        }

        for i in 1..self.resolution {
            // Index 0 is the center.
            indices.extend_from_slice(&[0, i, i + 1]);
        }

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for CircularSectorMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let (sin, cos) = ops::sin_cos(self.sector.arc.half_angle);
        let first_normal = Vec2::new(sin, cos);
        let last_normal = Vec2::new(-sin, cos);
        vec![
            PerimeterSegment::Flat {
                indices: vec![self.resolution, 0, 1],
            },
            PerimeterSegment::Smooth {
                first_normal,
                last_normal,
                indices: (1..=self.resolution).collect(),
            },
        ]
    }
}

impl Meshable for CircularSector {
    type Output = CircularSectorMeshBuilder;

    fn mesh(&self) -> Self::Output {
        CircularSectorMeshBuilder {
            sector: *self,
            ..Default::default()
        }
    }
}

impl From<CircularSector> for Mesh {
    /// Converts this sector into a [`Mesh`] using a default [`CircularSectorMeshBuilder`].
    ///
    /// See the documentation of [`CircularSectorMeshBuilder`] for more details.
    fn from(sector: CircularSector) -> Self {
        sector.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`CircularSegment`] shape.
///
/// The resulting mesh will have a UV-map such that the center of the circle is
/// at the center of the texture.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct CircularSegmentMeshBuilder {
    /// The segment shape.
    pub segment: CircularSegment,
    /// The number of vertices used for the arc portion of the segment mesh.
    /// The default is `32`.
    #[doc(alias = "vertices")]
    pub resolution: u32,
    /// The UV mapping mode
    pub uv_mode: CircularMeshUvMode,
}

impl Default for CircularSegmentMeshBuilder {
    fn default() -> Self {
        Self {
            segment: CircularSegment::default(),
            resolution: 32,
            uv_mode: CircularMeshUvMode::default(),
        }
    }
}

impl CircularSegmentMeshBuilder {
    /// Creates a new [`CircularSegmentMeshBuilder`] from a given segment
    #[inline]
    pub fn new(segment: CircularSegment) -> Self {
        Self {
            segment,
            ..Self::default()
        }
    }

    /// Sets the number of vertices used for the segment mesh.
    #[inline]
    #[doc(alias = "vertices")]
    pub const fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }

    /// Sets the uv mode used for the segment mesh
    #[inline]
    pub const fn uv_mode(mut self, uv_mode: CircularMeshUvMode) -> Self {
        self.uv_mode = uv_mode;
        self
    }
}

impl MeshBuilder for CircularSegmentMeshBuilder {
    fn build(&self) -> Mesh {
        let resolution = self.resolution as usize;
        let mut indices = Vec::with_capacity((resolution - 1) * 3);
        let mut positions = Vec::with_capacity(resolution + 1);
        let normals = vec![[0.0, 0.0, 1.0]; resolution + 1];
        let mut uvs = Vec::with_capacity(resolution + 1);

        let CircularMeshUvMode::Mask { angle: uv_angle } = self.uv_mode;

        // Push the center of the chord.
        let midpoint_vertex = self.segment.chord_midpoint();
        positions.push([midpoint_vertex.x, midpoint_vertex.y, 0.0]);
        // Compute the UV coordinate of the midpoint vertex.
        // This is similar to the computation inside the loop for the arc vertices,
        // but the vertex angle is PI/2, and we must scale by the ratio of the apothem to the radius
        // to correctly position the vertex.
        let midpoint_uv = Vec2::from_angle(-uv_angle - FRAC_PI_2).mul_add(
            Vec2::splat(0.5 * (self.segment.apothem() / self.segment.radius())),
            Vec2::splat(0.5),
        );
        uvs.push([midpoint_uv.x, midpoint_uv.y]);

        let first_angle = FRAC_PI_2 - self.segment.half_angle();
        let last_angle = FRAC_PI_2 + self.segment.half_angle();
        let last_i = (self.resolution - 1) as f32;
        for i in 0..self.resolution {
            let angle = f32::lerp(first_angle, last_angle, i as f32 / last_i);

            // Compute the vertex
            let vertex = self.segment.radius() * Vec2::from_angle(angle);
            // Compute the UV coordinate by taking the modified angle's unit vector, negating the Y axis, and rescaling and centering it at (0.5, 0.5).
            // We accomplish the Y axis flip by negating the angle.
            let uv =
                Vec2::from_angle(-(angle + uv_angle)).mul_add(Vec2::splat(0.5), Vec2::splat(0.5));

            positions.push([vertex.x, vertex.y, 0.0]);
            uvs.push([uv.x, uv.y]);
        }

        for i in 1..self.resolution {
            // Index 0 is the midpoint of the chord.
            indices.extend_from_slice(&[0, i, i + 1]);
        }

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for CircularSegmentMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let (sin, cos) = ops::sin_cos(self.segment.arc.half_angle);
        let first_normal = Vec2::new(sin, cos);
        let last_normal = Vec2::new(-sin, cos);
        vec![
            PerimeterSegment::Flat {
                indices: vec![self.resolution, 0, 1],
            },
            PerimeterSegment::Smooth {
                first_normal,
                last_normal,
                indices: (1..=self.resolution).collect(),
            },
        ]
    }
}

impl Meshable for CircularSegment {
    type Output = CircularSegmentMeshBuilder;

    fn mesh(&self) -> Self::Output {
        CircularSegmentMeshBuilder {
            segment: *self,
            ..Default::default()
        }
    }
}

impl From<CircularSegment> for Mesh {
    /// Converts this sector into a [`Mesh`] using a default [`CircularSegmentMeshBuilder`].
    ///
    /// See the documentation of [`CircularSegmentMeshBuilder`] for more details.
    fn from(segment: CircularSegment) -> Self {
        segment.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`ConvexPolygon`] shape.
///
/// You must verify that the `vertices` are not concave when constructing this type. You can
/// guarantee this by creating a [`ConvexPolygon`] first, then calling [`ConvexPolygon::mesh()`].
#[derive(Clone, Debug, Reflect)]
#[reflect(Debug, Clone)]
pub struct ConvexPolygonMeshBuilder {
    pub vertices: Vec<Vec2>,
}

impl Meshable for ConvexPolygon {
    type Output = ConvexPolygonMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Self::Output {
            vertices: self.vertices().to_vec(),
        }
    }
}

impl MeshBuilder for ConvexPolygonMeshBuilder {
    fn build(&self) -> Mesh {
        let len = self.vertices.len();
        let mut indices = Vec::with_capacity((len - 2) * 3);
        let mut positions = Vec::with_capacity(len);
        let normals = vec![[0.0, 0.0, 1.0]; len];
        let mut uvs = Vec::with_capacity(len);

        let mut min = Vec2::splat(f32::INFINITY);
        let mut max = Vec2::splat(f32::NEG_INFINITY);

        for vertex in &self.vertices {
            min = min.min(*vertex);
            max = max.max(*vertex);
        }

        let size = (max - min).max(Vec2::splat(f32::EPSILON));

        for vertex in &self.vertices {
            positions.push([vertex.x, vertex.y, 0.0]);
            let uv = (*vertex - min) / size;
            // Map each axis independently into [0, 1] over the polygon's AABB.
            uvs.push([uv.x, uv.y]);
        }
        for i in 2..len as u32 {
            indices.extend_from_slice(&[0, i - 1, i]);
        }
        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for ConvexPolygonMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Flat {
            indices: (0..self.vertices.len() as u32).chain([0]).collect(),
        }]
    }
}

impl From<ConvexPolygon> for Mesh {
    fn from(polygon: ConvexPolygon) -> Self {
        polygon.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`RegularPolygon`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct RegularPolygonMeshBuilder {
    circumradius: f32,
    sides: u32,
}

impl Default for RegularPolygonMeshBuilder {
    /// Returns the default [`RegularPolygonMeshBuilder`] with six sides (a hexagon) and a circumradius of `0.5`.
    fn default() -> Self {
        Self {
            circumradius: 0.5,
            sides: 6,
        }
    }
}

impl RegularPolygonMeshBuilder {
    /// Creates a new [`RegularPolygonMeshBuilder`] from the radius of a circumcircle and a number
    /// of sides.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if `circumradius` is negative, or if `sides` is less than 3.
    pub const fn new(circumradius: f32, sides: u32) -> Self {
        debug_assert!(
            circumradius.is_sign_positive(),
            "polygon has a negative radius"
        );
        debug_assert!(sides > 2, "polygon has less than 3 sides");

        Self {
            circumradius,
            sides,
        }
    }
}

impl Meshable for RegularPolygon {
    type Output = RegularPolygonMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Self::Output {
            circumradius: self.circumcircle.radius,
            sides: self.sides,
        }
    }
}

impl MeshBuilder for RegularPolygonMeshBuilder {
    fn build(&self) -> Mesh {
        // The ellipse mesh is just a regular polygon with two radii
        Ellipse::new(self.circumradius, self.circumradius)
            .mesh()
            .resolution(self.sides)
            .build()
    }
}

impl Extrudable for RegularPolygonMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Flat {
            indices: (0..self.sides).chain([0]).collect(),
        }]
    }
}

impl From<RegularPolygon> for Mesh {
    fn from(polygon: RegularPolygon) -> Self {
        polygon.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with an [`Ellipse`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct EllipseMeshBuilder {
    /// The [`Ellipse`] shape.
    pub ellipse: Ellipse,
    /// The number of vertices used for the ellipse mesh.
    /// The default is `32`.
    #[doc(alias = "vertices")]
    pub resolution: u32,
}

impl Default for EllipseMeshBuilder {
    fn default() -> Self {
        Self {
            ellipse: Ellipse::default(),
            resolution: 32,
        }
    }
}

impl EllipseMeshBuilder {
    /// Creates a new [`EllipseMeshBuilder`] from a given half width and half height and a vertex count.
    #[inline]
    pub const fn new(half_width: f32, half_height: f32, resolution: u32) -> Self {
        Self {
            ellipse: Ellipse::new(half_width, half_height),
            resolution,
        }
    }

    /// Sets the number of vertices used for the ellipse mesh.
    #[inline]
    #[doc(alias = "vertices")]
    pub const fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }
}

impl MeshBuilder for EllipseMeshBuilder {
    fn build(&self) -> Mesh {
        let resolution = self.resolution as usize;
        let mut indices = Vec::with_capacity((resolution - 2) * 3);
        let mut positions = Vec::with_capacity(resolution);
        let normals = vec![[0.0, 0.0, 1.0]; resolution];
        let mut uvs = Vec::with_capacity(resolution);

        // Add pi/2 so that there is a vertex at the top (sin is 1.0 and cos is 0.0)
        let start_angle = FRAC_PI_2;
        let step = core::f32::consts::TAU / self.resolution as f32;

        for i in 0..self.resolution {
            // Compute vertex position at angle theta
            let theta = start_angle + i as f32 * step;
            let (sin, cos) = ops::sin_cos(theta);
            let x = cos * self.ellipse.half_size.x;
            let y = sin * self.ellipse.half_size.y;

            positions.push([x, y, 0.0]);
            uvs.push([0.5 * (cos + 1.0), 1.0 - 0.5 * (sin + 1.0)]);
        }

        for i in 1..(self.resolution - 1) {
            indices.extend_from_slice(&[0, i, i + 1]);
        }

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for EllipseMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Smooth {
            first_normal: Vec2::Y,
            last_normal: Vec2::Y,
            indices: (0..self.resolution).chain([0]).collect(),
        }]
    }
}

impl Meshable for Ellipse {
    type Output = EllipseMeshBuilder;

    fn mesh(&self) -> Self::Output {
        EllipseMeshBuilder {
            ellipse: *self,
            ..Default::default()
        }
    }
}

impl From<Ellipse> for Mesh {
    fn from(ellipse: Ellipse) -> Self {
        ellipse.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Segment2d`].
pub struct Segment2dMeshBuilder {
    /// The [`Segment2d`] shape.
    pub segment: Segment2d,
}

impl Segment2dMeshBuilder {
    /// Creates a new [`Segment2dMeshBuilder`] from a given segment.
    #[inline]
    pub const fn new(line: Segment2d) -> Self {
        Self { segment: line }
    }
}

impl MeshBuilder for Segment2dMeshBuilder {
    fn build(&self) -> Mesh {
        let positions = self.segment.vertices.map(|v| v.extend(0.0)).to_vec();
        let indices = Indices::U32(vec![0, 1]);

        Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
            .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
            .with_inserted_indices(indices)
    }
}

impl Meshable for Segment2d {
    type Output = Segment2dMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Segment2dMeshBuilder::new(*self)
    }
}

impl From<Segment2d> for Mesh {
    /// Converts this segment into a [`Mesh`] using a default [`Segment2dMeshBuilder`].
    fn from(segment: Segment2d) -> Self {
        segment.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Polyline2d`] shape.
#[derive(Clone, Debug, Default, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct Polyline2dMeshBuilder {
    polyline: Polyline2d,
}

impl MeshBuilder for Polyline2dMeshBuilder {
    fn build(&self) -> Mesh {
        let positions: Vec<_> = self
            .polyline
            .vertices
            .iter()
            .map(|v| v.extend(0.0))
            .collect();

        let indices = Indices::U32(
            (0..self.polyline.vertices.len() as u32 - 1)
                .flat_map(|i| [i, i + 1])
                .collect(),
        );

        Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
            .with_inserted_indices(indices)
            .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
    }
}

impl Meshable for Polyline2d {
    type Output = Polyline2dMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Polyline2dMeshBuilder {
            polyline: self.clone(),
        }
    }
}

impl From<Polyline2d> for Mesh {
    fn from(polyline: Polyline2d) -> Self {
        polyline.mesh().build()
    }
}

/// A builder for creating a [`Mesh`] with an [`Annulus`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct AnnulusMeshBuilder {
    /// The [`Annulus`] shape.
    pub annulus: Annulus,

    /// The number of vertices used in constructing each concentric circle of the annulus mesh.
    /// The default is `32`.
    pub resolution: u32,
}

impl Default for AnnulusMeshBuilder {
    fn default() -> Self {
        Self {
            annulus: Annulus::default(),
            resolution: 32,
        }
    }
}

impl AnnulusMeshBuilder {
    /// Create an [`AnnulusMeshBuilder`] with the given inner radius, outer radius, and angular vertex count.
    #[inline]
    pub fn new(inner_radius: f32, outer_radius: f32, resolution: u32) -> Self {
        Self {
            annulus: Annulus::new(inner_radius, outer_radius),
            resolution,
        }
    }

    /// Sets the number of vertices used in constructing the concentric circles of the annulus mesh.
    #[inline]
    pub fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }
}

impl MeshBuilder for AnnulusMeshBuilder {
    fn build(&self) -> Mesh {
        let inner_radius = self.annulus.inner_circle.radius;
        let outer_radius = self.annulus.outer_circle.radius;

        let num_vertices = (self.resolution as usize + 1) * 2;
        let mut indices = Vec::with_capacity(self.resolution as usize * 6);
        let mut positions = Vec::with_capacity(num_vertices);
        let mut uvs = Vec::with_capacity(num_vertices);
        let normals = vec![[0.0, 0.0, 1.0]; num_vertices];

        // We have one more set of vertices than might be naïvely expected;
        // the vertices at `start_angle` are duplicated for the purposes of UV
        // mapping. Here, each iteration places a pair of vertices at a fixed
        // angle from the center of the annulus.
        let start_angle = FRAC_PI_2;
        let step = core::f32::consts::TAU / self.resolution as f32;
        for i in 0..=self.resolution {
            let theta = start_angle + (i % self.resolution) as f32 * step;
            let (sin, cos) = ops::sin_cos(theta);
            let inner_pos = [cos * inner_radius, sin * inner_radius, 0.];
            let outer_pos = [cos * outer_radius, sin * outer_radius, 0.];
            positions.push(inner_pos);
            positions.push(outer_pos);

            // The first UV direction is radial and the second is angular;
            // i.e., a single UV rectangle is stretched around the annulus, with
            // its top and bottom meeting as the circle closes. Lines of constant
            // U map to circles, and lines of constant V map to radial line segments.
            let inner_uv = [0., i as f32 / self.resolution as f32];
            let outer_uv = [1., i as f32 / self.resolution as f32];
            uvs.push(inner_uv);
            uvs.push(outer_uv);
        }

        // Adjacent pairs of vertices form two triangles with each other; here,
        // we are just making sure that they both have the right orientation,
        // which is the CCW order of
        // `inner_vertex` -> `outer_vertex` -> `next_outer` -> `next_inner`
        for i in 0..self.resolution {
            let inner_vertex = 2 * i;
            let outer_vertex = 2 * i + 1;
            let next_inner = inner_vertex + 2;
            let next_outer = outer_vertex + 2;
            indices.extend_from_slice(&[inner_vertex, outer_vertex, next_outer]);
            indices.extend_from_slice(&[next_outer, next_inner, inner_vertex]);
        }

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for AnnulusMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let vert_count = 2 * self.resolution;
        vec![
            PerimeterSegment::Smooth {
                first_normal: Vec2::NEG_Y,
                last_normal: Vec2::NEG_Y,
                indices: (0..vert_count).step_by(2).chain([0]).rev().collect(), // Inner hole
            },
            PerimeterSegment::Smooth {
                first_normal: Vec2::Y,
                last_normal: Vec2::Y,
                indices: (1..vert_count).step_by(2).chain([1]).collect(), // Outer perimeter
            },
        ]
    }
}

impl Meshable for Annulus {
    type Output = AnnulusMeshBuilder;

    fn mesh(&self) -> Self::Output {
        AnnulusMeshBuilder {
            annulus: *self,
            ..Default::default()
        }
    }
}

impl From<Annulus> for Mesh {
    fn from(annulus: Annulus) -> Self {
        annulus.mesh().build()
    }
}

/// A builder for creating a [`Mesh`] with an [`Rhombus`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct RhombusMeshBuilder {
    half_diagonals: Vec2,
}

impl Default for RhombusMeshBuilder {
    /// Returns the default [`RhombusMeshBuilder`] with a half-horizontal and half-vertical diagonal of `0.5`.
    fn default() -> Self {
        Self {
            half_diagonals: Vec2::splat(0.5),
        }
    }
}

impl RhombusMeshBuilder {
    /// Creates a new [`RhombusMeshBuilder`] from a horizontal and vertical diagonal size.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if `horizontal_diagonal` or `vertical_diagonal` is negative.
    pub const fn new(horizontal_diagonal: f32, vertical_diagonal: f32) -> Self {
        debug_assert!(
            horizontal_diagonal >= 0.0,
            "rhombus has a negative horizontal size",
        );
        debug_assert!(
            vertical_diagonal >= 0.0,
            "rhombus has a negative vertical size"
        );

        Self {
            half_diagonals: Vec2::new(horizontal_diagonal / 2.0, vertical_diagonal / 2.0),
        }
    }
}

impl MeshBuilder for RhombusMeshBuilder {
    fn build(&self) -> Mesh {
        let [hhd, vhd] = [self.half_diagonals.x, self.half_diagonals.y];
        let positions = vec![
            [hhd, 0.0, 0.0],
            [0.0, vhd, 0.0],
            [-hhd, 0.0, 0.0],
            [0.0, -vhd, 0.0],
        ];
        let normals = vec![[0.0, 0.0, 1.0]; 4];
        let uvs = vec![[1.0, 0.5], [0.5, 0.0], [0.0, 0.5], [0.5, 1.0]];
        let indices = Indices::U32(vec![2, 0, 1, 2, 3, 0]);

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(indices)
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    }
}

impl Extrudable for RhombusMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Flat {
            indices: vec![0, 1, 2, 3, 0],
        }]
    }
}

impl Meshable for Rhombus {
    type Output = RhombusMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Self::Output {
            half_diagonals: self.half_diagonals,
        }
    }
}

impl From<Rhombus> for Mesh {
    fn from(rhombus: Rhombus) -> Self {
        rhombus.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Triangle2d`] shape.
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct Triangle2dMeshBuilder {
    triangle: Triangle2d,
}

impl Triangle2dMeshBuilder {
    /// Creates a new [`Triangle2dMeshBuilder`] from the points `a`, `b`, and `c`.
    pub const fn new(a: Vec2, b: Vec2, c: Vec2) -> Self {
        Self {
            triangle: Triangle2d::new(a, b, c),
        }
    }
}

impl Meshable for Triangle2d {
    type Output = Triangle2dMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Self::Output { triangle: *self }
    }
}

impl MeshBuilder for Triangle2dMeshBuilder {
    fn build(&self) -> Mesh {
        let vertices_3d = self.triangle.vertices.map(|v| v.extend(0.));

        let positions: Vec<_> = vertices_3d.into();
        let normals = vec![[0.0, 0.0, 1.0]; 3];

        let uvs: Vec<_> = triangle3d::uv_coords(&Triangle3d::new(
            vertices_3d[0],
            vertices_3d[1],
            vertices_3d[2],
        ))
        .into();

        let is_ccw = self.triangle.winding_order() == WindingOrder::CounterClockwise;
        let indices = if is_ccw {
            Indices::U32(vec![0, 1, 2])
        } else {
            Indices::U32(vec![2, 1, 0])
        };

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(indices)
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    }
}

impl Extrudable for Triangle2dMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let is_ccw = self.triangle.winding_order() == WindingOrder::CounterClockwise;
        if is_ccw {
            vec![PerimeterSegment::Flat {
                indices: vec![0, 1, 2, 0],
            }]
        } else {
            vec![PerimeterSegment::Flat {
                indices: vec![2, 1, 0, 2],
            }]
        }
    }
}

impl From<Triangle2d> for Mesh {
    fn from(triangle: Triangle2d) -> Self {
        triangle.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Rectangle`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct RectangleMeshBuilder {
    half_size: Vec2,
}

impl Default for RectangleMeshBuilder {
    /// Returns the default [`RectangleMeshBuilder`] with a half-width and half-height of `0.5`.
    fn default() -> Self {
        Self {
            half_size: Vec2::splat(0.5),
        }
    }
}

impl RectangleMeshBuilder {
    /// Creates a new [`RectangleMeshBuilder`] from a full width and height.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if `width` or `height` is negative.
    pub const fn new(width: f32, height: f32) -> Self {
        debug_assert!(width >= 0.0, "rectangle has a negative width");
        debug_assert!(height >= 0.0, "rectangle has a negative height");

        Self {
            half_size: Vec2::new(width / 2.0, height / 2.0),
        }
    }
}

impl MeshBuilder for RectangleMeshBuilder {
    fn build(&self) -> Mesh {
        let [hw, hh] = [self.half_size.x, self.half_size.y];
        let positions = vec![
            [hw, hh, 0.0],
            [-hw, hh, 0.0],
            [-hw, -hh, 0.0],
            [hw, -hh, 0.0],
        ];
        let normals = vec![[0.0, 0.0, 1.0]; 4];
        let uvs = vec![[1.0, 0.0], [0.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let indices = Indices::U32(vec![0, 1, 2, 0, 2, 3]);

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(indices)
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    }
}

impl Extrudable for RectangleMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        vec![PerimeterSegment::Flat {
            indices: vec![0, 1, 2, 3, 0],
        }]
    }
}

impl Meshable for Rectangle {
    type Output = RectangleMeshBuilder;

    fn mesh(&self) -> Self::Output {
        RectangleMeshBuilder {
            half_size: self.half_size,
        }
    }
}

impl From<Rectangle> for Mesh {
    fn from(rectangle: Rectangle) -> Self {
        rectangle.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Capsule2d`] shape.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Default, Debug, Clone)]
pub struct Capsule2dMeshBuilder {
    /// The [`Capsule2d`] shape.
    pub capsule: Capsule2d,
    /// The number of vertices used for one hemicircle.
    /// The total number of vertices for the capsule mesh will be two times the resolution.
    ///
    /// The default is `16`.
    pub resolution: u32,
}

impl Default for Capsule2dMeshBuilder {
    fn default() -> Self {
        Self {
            capsule: Capsule2d::default(),
            resolution: 16,
        }
    }
}

impl Capsule2dMeshBuilder {
    /// Creates a new [`Capsule2dMeshBuilder`] from a given radius, length, and the number of vertices
    /// used for one hemicircle. The total number of vertices for the capsule mesh will be two times the resolution.
    #[inline]
    pub fn new(radius: f32, length: f32, resolution: u32) -> Self {
        Self {
            capsule: Capsule2d::new(radius, length),
            resolution,
        }
    }

    /// Sets the number of vertices used for one hemicircle.
    /// The total number of vertices for the capsule mesh will be two times the resolution.
    #[inline]
    pub const fn resolution(mut self, resolution: u32) -> Self {
        self.resolution = resolution;
        self
    }
}

impl MeshBuilder for Capsule2dMeshBuilder {
    fn build(&self) -> Mesh {
        // The resolution is the number of vertices for one semicircle
        let resolution = self.resolution;
        let vertex_count = 2 * resolution;

        // Six extra indices for the two triangles between the semicircles
        let mut indices = Vec::with_capacity((resolution as usize - 2) * 2 * 3 + 6);
        let mut positions = Vec::with_capacity(vertex_count as usize);
        let normals = vec![[0.0, 0.0, 1.0]; vertex_count as usize];
        let mut uvs = Vec::with_capacity(vertex_count as usize);

        let radius = self.capsule.radius;
        let step = core::f32::consts::TAU / vertex_count as f32;

        // If the vertex count is even, offset starting angle of top semicircle by half a step
        // to position the vertices evenly.
        let start_angle = if vertex_count.is_multiple_of(2) {
            step / 2.0
        } else {
            0.0
        };

        // How much the hemicircle radius is of the total half-height of the capsule.
        // This is used to prevent the UVs from stretching between the semicircles.
        let radius_frac = self.capsule.radius / (self.capsule.half_length + self.capsule.radius);

        // Create top semicircle
        for i in 0..resolution {
            // Compute vertex position at angle theta
            let theta = start_angle + i as f32 * step;
            let (sin, cos) = ops::sin_cos(theta);
            let (x, y) = (cos * radius, sin * radius + self.capsule.half_length);

            positions.push([x, y, 0.0]);
            uvs.push([0.5 * (cos + 1.0), radius_frac * (1.0 - 0.5 * (sin + 1.0))]);
        }

        // Add top semicircle indices
        for i in 1..resolution - 1 {
            indices.extend_from_slice(&[0, i, i + 1]);
        }

        // Add indices for top left triangle of the part between the semicircles
        indices.extend_from_slice(&[0, resolution - 1, resolution]);

        // Create bottom semicircle
        for i in resolution..vertex_count {
            // Compute vertex position at angle theta
            let theta = start_angle + i as f32 * step;
            let (sin, cos) = ops::sin_cos(theta);
            let (x, y) = (cos * radius, sin * radius - self.capsule.half_length);

            positions.push([x, y, 0.0]);
            uvs.push([0.5 * (cos + 1.0), 1.0 - radius_frac * 0.5 * (sin + 1.0)]);
        }

        // Add bottom semicircle indices
        for i in 1..resolution - 1 {
            indices.extend_from_slice(&[resolution, resolution + i, resolution + i + 1]);
        }

        // Add indices for bottom right triangle of the part between the semicircles
        indices.extend_from_slice(&[resolution, vertex_count - 1, 0]);

        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices))
    }
}

impl Extrudable for Capsule2dMeshBuilder {
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let resolution = self.resolution;
        let top_semi_indices = (0..resolution).collect();
        let bottom_semi_indices = (resolution..(2 * resolution)).collect();
        vec![
            PerimeterSegment::Smooth {
                first_normal: Vec2::X,
                last_normal: Vec2::NEG_X,
                indices: top_semi_indices,
            }, // Top semi-circle
            PerimeterSegment::Flat {
                indices: vec![resolution - 1, resolution],
            }, // Left edge
            PerimeterSegment::Smooth {
                first_normal: Vec2::NEG_X,
                last_normal: Vec2::X,
                indices: bottom_semi_indices,
            }, // Bottom semi-circle
            PerimeterSegment::Flat {
                indices: vec![2 * resolution - 1, 0],
            }, // Right edge
        ]
    }
}

impl Meshable for Capsule2d {
    type Output = Capsule2dMeshBuilder;

    fn mesh(&self) -> Self::Output {
        Capsule2dMeshBuilder {
            capsule: *self,
            ..Default::default()
        }
    }
}

impl From<Capsule2d> for Mesh {
    fn from(capsule: Capsule2d) -> Self {
        capsule.mesh().build()
    }
}

/// A builder used for creating a [`Mesh`] with a [`Ring`] shape.
pub struct RingMeshBuilder<P>
where
    P: Primitive2d + Meshable,
{
    pub outer_shape_builder: P::Output,
    pub inner_shape_builder: P::Output,
}

impl<P> RingMeshBuilder<P>
where
    P: Primitive2d + Meshable,
{
    /// Create a new `RingMeshBuilder<P>` from a given `Ring<P>` shape.
    pub fn new(ring: &Ring<P>) -> Self {
        Self {
            outer_shape_builder: ring.outer_shape.mesh(),
            inner_shape_builder: ring.inner_shape.mesh(),
        }
    }

    /// Apply a function to the inner builders
    pub fn with_inner(mut self, func: impl Fn(P::Output) -> P::Output) -> Self {
        self.outer_shape_builder = func(self.outer_shape_builder);
        self.inner_shape_builder = func(self.inner_shape_builder);
        self
    }

    fn get_vertex_attributes(&self) -> Option<RingMeshBuilderVertexAttributes> {
        fn get_positions(mesh: &mut Mesh) -> Option<&mut Vec<[f32; 3]>> {
            if let VertexAttributeValues::Float32x3(data) =
                mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)?
            {
                Some(data)
            } else {
                None
            }
        }

        fn get_uvs(mesh: &mut Mesh) -> Option<&mut Vec<[f32; 2]>> {
            if let VertexAttributeValues::Float32x2(data) =
                mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0)?
            {
                Some(data)
            } else {
                None
            }
        }

        fn get_normals(mesh: &mut Mesh) -> Option<&mut Vec<[f32; 3]>> {
            if let VertexAttributeValues::Float32x3(data) =
                mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL)?
            {
                Some(data)
            } else {
                None
            }
        }

        let mut outer = self.outer_shape_builder.build();
        let mut inner = self.inner_shape_builder.build();

        assert_eq!(
            outer.primitive_topology(),
            PrimitiveTopology::TriangleList,
            "PrimitiveTopology must be a TriangleList, mesh builder not compatible"
        );
        assert_eq!(
            inner.primitive_topology(),
            PrimitiveTopology::TriangleList,
            "PrimitiveTopology must be a TriangleList, mesh builder not compatible"
        );

        Some(RingMeshBuilderVertexAttributes {
            outer_positions: mem::take(get_positions(&mut outer)?),
            inner_positions: mem::take(get_positions(&mut inner)?),
            outer_normals: mem::take(get_normals(&mut outer)?),
            inner_normals: mem::take(get_normals(&mut inner)?),
            outer_uvs: mem::take(get_uvs(&mut outer)?),
            inner_uvs: mem::take(get_uvs(&mut inner)?),
        })
    }
}

struct RingMeshBuilderVertexAttributes {
    outer_positions: Vec<[f32; 3]>,
    inner_positions: Vec<[f32; 3]>,
    outer_normals: Vec<[f32; 3]>,
    inner_normals: Vec<[f32; 3]>,
    outer_uvs: Vec<[f32; 2]>,
    inner_uvs: Vec<[f32; 2]>,
}

impl<P> MeshBuilder for RingMeshBuilder<P>
where
    P: Primitive2d + Meshable,
{
    /// Builds a [`Mesh`] based on the configuration in `self`.
    ///
    /// # Panics
    ///
    /// Panics if the following assumptions are not met.
    ///
    /// It is assumed that the inner and outer meshes have the same number of vertices.
    /// If not, then the [`MeshBuilder`] of the underlying 2d primitive has generated
    /// a different number of vertices for the inner and outer instances of the primitive.
    ///
    /// It is assumed that the `primitive_topology` of the mesh returned by
    /// the underlying builder is [`PrimitiveTopology::TriangleList`]
    /// and that the mesh has [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes.
    fn build(&self) -> Mesh {
        if let Some(RingMeshBuilderVertexAttributes {
            outer_uvs,
            inner_uvs,
            outer_positions,
            inner_positions,
            outer_normals,
            inner_normals,
        }) = self.get_vertex_attributes()
            && outer_uvs.len() == inner_uvs.len()
            && outer_positions.len() == inner_positions.len()
            && outer_normals.len() == inner_normals.len()
        {
            let mut uvs = outer_uvs;
            let inner_uvs = inner_positions
                .iter()
                .zip(&outer_positions)
                .zip(&inner_uvs)
                .map(|((inner_position, outer_position), inner_uv)| -> [f32; 2] {
                    const UV_CENTER: Vec2 = Vec2::splat(0.5);
                    let ip = Vec3::from(*inner_position).truncate();
                    let op = Vec3::from(*outer_position).truncate();
                    let uv = Vec2::from(*inner_uv) - UV_CENTER;
                    (uv * ip.length() / op.length() + UV_CENTER).into()
                });
            uvs.extend(inner_uvs);

            let mut normals = outer_normals;
            normals.extend(inner_normals);

            let points = outer_positions.len() as u32;
            let mut indices = Vec::with_capacity(outer_positions.len() * 6);
            for i in 0..points {
                //                               for five points:
                indices.push(i); //              0  1  2  3  4
                indices.push(i + 1); //          1  2  3  4  0  <-
                indices.push(points + i); //     0' 1' 2' 3' 4'
                indices.push(points + i); //     0' 1' 2' 3' 4'
                indices.push(i + 1); //          1  2  3  4  0  <-
                indices.push(points + i + 1); // 1' 2' 3' 4' 0' <-
            }
            let indices_length = indices.len();
            // Fix up the last pair of triangles (return to start)
            if let (_, [_, b, _, _, e, f]) = indices.split_at_mut(indices_length.saturating_sub(6))
            {
                *b = 0;
                *e = 0;
                *f = points;
            }

            let mut positions = outer_positions;
            positions.extend_from_slice(&inner_positions);

            Mesh::new(
                PrimitiveTopology::TriangleList,
                RenderAssetUsages::default(),
            )
            .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
            .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
            .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
            .with_inserted_indices(Indices::U32(indices))
        } else {
            panic!("The inner and outer meshes should have the same number of vertices, and have required attributes");
        }
    }
}

impl<P> Extrudable for RingMeshBuilder<P>
where
    P: Primitive2d + Meshable,
    P::Output: Extrudable,
{
    /// A list of the indices each representing a part of the perimeter of the mesh.
    ///
    /// # Panics
    ///
    /// Panics if the following assumptions are not met.
    ///
    /// It is assumed that the inner and outer meshes have the same number of vertices.
    /// If not, then the [`MeshBuilder`] of the underlying 2d primitive has generated
    /// a different number of vertices for the inner and outer instances of the primitive.
    ///
    /// It is assumed that the `primitive_topology` of the mesh returned by
    /// the underlying builder is [`PrimitiveTopology::TriangleList`]
    /// and that the mesh has [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes.
    fn perimeter(&self) -> Vec<PerimeterSegment> {
        let outer_vertex_count = self
            .get_vertex_attributes()
            .filter(|r| r.outer_positions.len() == r.inner_positions.len())
            .expect("The inner and outer meshes should have the same number of vertices, and have required attributes")
            .outer_positions
            .len();

        let mut outer_perimeter = self.outer_shape_builder.perimeter();
        let inner_perimeter =
            self.inner_shape_builder
                .perimeter()
                .into_iter()
                .rev()
                .map(|segment| match segment {
                    PerimeterSegment::Smooth {
                        first_normal,
                        last_normal,
                        mut indices,
                    } => PerimeterSegment::Smooth {
                        first_normal: -last_normal,
                        last_normal: -first_normal,
                        indices: {
                            let outer_perimeter_vertex_count = outer_vertex_count as u32;
                            indices.reverse();
                            for i in &mut indices {
                                *i += outer_perimeter_vertex_count;
                            }
                            indices
                        },
                    },
                    PerimeterSegment::Flat { mut indices } => PerimeterSegment::Flat {
                        indices: {
                            let outer_perimeter_vertex_count = outer_vertex_count as u32;
                            indices.reverse();
                            for i in &mut indices {
                                *i += outer_perimeter_vertex_count;
                            }
                            indices
                        },
                    },
                });

        outer_perimeter.extend(inner_perimeter);
        outer_perimeter
    }
}

impl<P> Meshable for Ring<P>
where
    P: Primitive2d + Meshable,
{
    type Output = RingMeshBuilder<P>;

    fn mesh(&self) -> Self::Output {
        RingMeshBuilder::new(self)
    }
}

impl<P> From<Ring<P>> for Mesh
where
    P: Primitive2d + Meshable,
{
    fn from(ring: Ring<P>) -> Self {
        ring.mesh().build()
    }
}

#[cfg(test)]
mod tests {
    use bevy_math::{
        prelude::Annulus,
        primitives::{ConvexPolygon, RegularPolygon},
        FloatOrd, Vec2,
    };
    use bevy_platform::collections::HashSet;

    use crate::{Mesh, MeshBuilder, Meshable, VertexAttributeValues};

    fn count_distinct_positions(points: &[[f32; 3]]) -> usize {
        let mut map = <HashSet<_>>::default();
        for point in points {
            map.insert(point.map(FloatOrd));
        }
        map.len()
    }

    #[test]
    fn test_annulus() {
        let mesh = Annulus::new(1.0, 1.2).mesh().resolution(16).build();

        assert_eq!(
            32,
            count_distinct_positions(
                mesh.attribute(Mesh::ATTRIBUTE_POSITION)
                    .unwrap()
                    .as_float3()
                    .unwrap()
            )
        );
    }

    /// Sin/cos and multiplication computations result in numbers like 0.4999999.
    /// Round these to numbers we expect like 0.5.
    fn fix_floats<const N: usize>(points: &mut [[f32; N]]) {
        for point in points.iter_mut() {
            for coord in point.iter_mut() {
                let round = (*coord * 2.).round() / 2.;
                if (*coord - round).abs() < 0.00001 {
                    *coord = round;
                }
            }
        }
    }

    #[test]
    fn test_regular_polygon() {
        let mut mesh = Mesh::from(RegularPolygon::new(7.0, 4));

        let Some(VertexAttributeValues::Float32x3(mut positions)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_POSITION)
        else {
            panic!("Expected positions f32x3");
        };
        let Some(VertexAttributeValues::Float32x2(mut uvs)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_UV_0)
        else {
            panic!("Expected uvs f32x2");
        };
        let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("Expected normals f32x3");
        };

        fix_floats(&mut positions);
        fix_floats(&mut uvs);

        assert_eq!(
            [
                [0.0, 7.0, 0.0],
                [-7.0, 0.0, 0.0],
                [0.0, -7.0, 0.0],
                [7.0, 0.0, 0.0],
            ],
            &positions[..]
        );

        // Note V coordinate increases in the opposite direction to the Y coordinate.
        assert_eq!([[0.5, 0.0], [0.0, 0.5], [0.5, 1.0], [1.0, 0.5],], &uvs[..]);

        assert_eq!(&[[0.0, 0.0, 1.0]; 4], &normals[..]);
    }

    #[test]
    fn test_convex_polygon() {
        let polygon = ConvexPolygon::new(vec![
            Vec2::new(-2.0, -1.0),
            Vec2::new(2.0, -1.0),
            Vec2::new(1.0, 3.0),
            Vec2::new(-1.0, 2.0),
        ])
        .unwrap();

        let mut mesh = Mesh::from(polygon);

        let Some(VertexAttributeValues::Float32x3(mut positions)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_POSITION)
        else {
            panic!("Expected positions f32x3");
        };
        let Some(VertexAttributeValues::Float32x2(mut uvs)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_UV_0)
        else {
            panic!("Expected uvs f32x2");
        };
        let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.remove_attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("Expected normals f32x3");
        };

        fix_floats(&mut positions);
        fix_floats(&mut uvs);

        assert_eq!(
            [
                [-2.0, -1.0, 0.0],
                [2.0, -1.0, 0.0],
                [1.0, 3.0, 0.0],
                [-1.0, 2.0, 0.0],
            ],
            &positions[..]
        );

        assert_eq!(
            [[0.0, 0.0], [1.0, 0.0], [0.75, 1.0], [0.25, 0.75]],
            &uvs[..]
        );

        assert_eq!(&[[0.0, 0.0, 1.0]; 4], &normals[..]);
    }
}