engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
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
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
//! This module contains an abstraction for a mesh of triangles, represented by vertices and their
//! indices into the vertex list.  This abstraction is built around the `TriMesh` type from the
//! `parry3d` crate.
//!
//! For the connectivity-first view of the same surface, used by repair, smoothing and decimation,
//! see [`half_edge3`](crate::geom3::half_edge3). [`MeshEditor`] is the handle which converts across,
//! runs a sequence of edits, and converts back.

pub mod algorithms;
mod collisions;
mod conformal;
pub mod data;
pub(crate) mod edges;
mod editor;
pub mod filtering;
mod flat_domain;
pub(crate) mod measurement;
mod nav_structure;
mod outline;
pub mod patches;
mod queries;
pub mod sampling;
mod section;
mod transverse;
mod view;
pub mod voxelize;

use crate::common::{IndexMask, PCoords};
use crate::geom3::attributes3::{FaceAttrSet3, PointAttrSet3};
use crate::na::SVector;
use crate::{Iso3, Point2, Point3, Result, SurfacePoint3, UnitVec3, Vector3};
pub use collisions::MeshCollisionSet;
pub use data::{Attr3, MeshData3};
pub use edges::MeshEdges;
pub use editor::{EditReport, MeshEditor};
pub use flat_domain::FlatDomain;
pub use measurement::SurfaceDeviation;
pub use nav_structure::MeshNav;
use parry3d_f64::bounding_volume::Aabb;
use parry3d_f64::shape::{TriMesh, TriMeshFlags};
use parry3d_f64::transformation;
pub use patches::{PatchFilter, PatchLabels, PatchStats};
pub use section::PlanarSection;
pub use transverse::{TransverseOptions, TransversePlane};
pub use view::MeshView3;

use crate::io::write_tc_mesh_file;
#[cfg(feature = "ply")]
use crate::io::{PlyWriteOpts, write_ply_mesh};
#[cfg(feature = "stl")]
use crate::io::{StlWriteOpts, write_stl_mesh};
use std::path::Path;

/// A struct that represents a point on the surface of a mesh, including the index of the face
/// on which it lies, its barycentric coordinates, and the point/normal representation in space.
/// This representation has no link back to the original mesh, so the face index and barycentric
/// coordinates will be invalid if (1) the mesh is modified, or (2) if you attempt to use them on
/// a different mesh.
#[derive(Debug, Clone, Copy)]
pub struct MeshSurfPoint {
    /// The index of the face on which this point lies.
    pub face_index: u32,

    /// The barycentric coordinates of the point on the face.
    pub bc: [f64; 3],

    /// The surface point (point + normal) corresponding to this barycentric coordinate.
    pub sp: SurfacePoint3,
}

impl MeshSurfPoint {
    /// Create a new `MeshSurfPoint` from the given face index, barycentric coordinates, and
    /// surface point.
    pub fn new(face_index: u32, bc: [f64; 3], sp: SurfacePoint3) -> Self {
        Self { face_index, bc, sp }
    }

    /// Get the point in space corresponding to this surface point.
    pub fn point(&self) -> Point3 {
        self.sp.point
    }

    /// Get the normal at this surface point.
    pub fn normal(&self) -> UnitVec3 {
        self.sp.normal
    }

    pub fn new_transformed_by(&self, iso: &Iso3) -> Self {
        Self {
            face_index: self.face_index,
            bc: self.bc,
            sp: iso * self.sp,
        }
    }
}

impl Default for MeshSurfPoint {
    fn default() -> Self {
        Self {
            face_index: 0,
            bc: [0.0, 0.0, 0.0],
            sp: SurfacePoint3::default(),
        }
    }
}

impl PCoords<3> for MeshSurfPoint {
    fn coords(&self) -> SVector<f64, 3> {
        self.sp.point.coords
    }
}

/// This is a triangle mesh optimized for collision detection and geometric queries. It is built on
/// top of the `parry3d` library's `TriMesh` type, which provides efficient storage and querying of
/// triangle meshes. This mesh has some basic functionality for interrogating its structure, and
/// some very basic functionality for editing.  However, it is not a structure optimized for
/// editing or modification.
///
/// # Relationship with `MeshData3`
///
/// This is the accelerated half of a complementary pair. `MeshData3` holds the same point and face
/// buffers with no spatial acceleration at all, and is the type to reach for when building or
/// editing mesh data, or when working with serialization. Converting between the two is done with
/// `from_data`/`to_data`, or the equivalent `TryFrom`/`From` implementations.
///
/// Both types carry the same `PointAttrSet3` and `FaceAttrSet3` of per-element attributes. A mesh
/// loaded with measured normals, colors, or uncertainties therefore preserves them when converted
/// in either direction.
///
/// # Invariants
///
/// The attribute arrays are validated against the point and face counts, exactly as they are on
/// `MeshData3`. That makes the point and face buffers inside the underlying `TriMesh` load bearing:
/// anything which renumbers a point or drops a face has to update the attributes to match, or
/// refuse to run. This is why the `merge_duplicates` and `delete_degenerate` options on
/// `new_with_options` are only reachable from a constructor which attaches no attributes.
#[derive(Clone)]
pub struct Mesh3 {
    shape: TriMesh,
    point_attrs: PointAttrSet3,
    face_attrs: FaceAttrSet3,
    is_solid: bool,
}

// ===============================================================================================
// Core access
// ===============================================================================================

impl Mesh3 {
    /// Get a reference to the AABB of the underlying mesh in the local coordinate system.
    pub fn aabb(&self) -> Aabb {
        self.shape.local_aabb()
    }

    /// Gets a reference to the underlying `TriMesh` object to provide direct access to
    /// the `parry3d` API.
    pub fn tri_mesh(&self) -> &TriMesh {
        &self.shape
    }

    /// Return a flag indicating whether the mesh is considered "solid" or not for the purposes of
    /// distance queries. If a mesh is "solid", then distance queries for points on the inside of
    /// the mesh will return a zero distance.
    pub fn is_solid(&self) -> bool {
        self.is_solid
    }

    /// Get a reference to the points of the mesh.
    pub fn points(&self) -> &[Point3] {
        self.shape.vertices()
    }

    /// Get a reference to the face indices of the mesh.
    pub fn faces(&self) -> &[[u32; 3]] {
        self.shape.indices()
    }

    /// Get the number of points in the mesh.
    pub fn point_count(&self) -> usize {
        self.shape.vertices().len()
    }

    /// Get the number of faces in the mesh.
    pub fn face_count(&self) -> usize {
        self.shape.indices().len()
    }
}

// ===============================================================================================
// Attribute access
// ===============================================================================================

impl Mesh3 {
    /// Get a reference to the per-point attributes attached to this mesh.
    pub fn point_attrs(&self) -> &PointAttrSet3 {
        &self.point_attrs
    }

    /// Get a reference to the per-face attributes attached to this mesh.
    pub fn face_attrs(&self) -> &FaceAttrSet3 {
        &self.face_attrs
    }

    /// Returns true if the mesh carries any attributes in either domain.
    pub fn has_attrs(&self) -> bool {
        !self.point_attrs.is_empty() || !self.face_attrs.is_empty()
    }

    /// Get the per-point unit normals, if present.
    ///
    /// These are whatever was measured or stored, not a computed quantity. Use
    /// `compute_point_normals` to derive normals from the faces.
    pub fn point_normals(&self) -> Option<&[UnitVec3]> {
        self.point_attrs.normals()
    }

    /// Get the per-point RGB colors, if present.
    pub fn point_colors(&self) -> Option<&[[u8; 3]]> {
        self.point_attrs.colors()
    }

    /// Get the per-point standard deviations, if present. These are 1-sigma values in the mesh's
    /// own length units.
    pub fn point_stdev(&self) -> Option<&[f64]> {
        self.point_attrs.stdev()
    }

    /// Get the per-point flat coordinates, if present: each point's position in a flattened 2D
    /// chart of the surface, expressed in the mesh's own length units. See
    /// [`set_point_flat`](Self::set_point_flat).
    pub fn point_flat(&self) -> Option<&[Point2]> {
        self.point_attrs.flat()
    }

    /// Get the per-face RGB colors, if present.
    pub fn face_colors(&self) -> Option<&[[u8; 3]]> {
        self.face_attrs.colors()
    }

    /// Get the per-face labels, if present.
    pub fn face_labels(&self) -> Option<&[u32]> {
        self.face_attrs.labels()
    }

    /// Get the open-map per-point attribute stored under the given name, if present.
    pub fn point_attr(&self, name: &str) -> Option<&Attr3> {
        self.point_attrs.attr(name)
    }

    /// Get the open-map per-face attribute stored under the given name, if present.
    pub fn face_attr(&self, name: &str) -> Option<&Attr3> {
        self.face_attrs.attr(name)
    }
}

// ===============================================================================================
// Attribute mutation
// ===============================================================================================

impl Mesh3 {
    /// Set or clear the per-point unit normals.
    ///
    /// # Arguments
    ///
    /// * `values`: the normals to store, or `None` to clear them. Must match the point count.
    ///
    /// returns: `Result<()>`
    pub fn set_point_normals(&mut self, values: Option<Vec<UnitVec3>>) -> Result<()> {
        self.point_attrs.set_normals(values, self.point_count())
    }

    /// Set or clear the per-point RGB colors.
    ///
    /// # Arguments
    ///
    /// * `values`: the colors to store, or `None` to clear them. Must match the point count.
    ///
    /// returns: `Result<()>`
    pub fn set_point_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
        self.point_attrs.set_colors(values, self.point_count())
    }

    /// Set or clear the per-point standard deviations, which must be 1-sigma values in the mesh's
    /// own length units.
    ///
    /// # Arguments
    ///
    /// * `values`: the standard deviations to store, or `None` to clear them. Must match the point
    ///   count, and must be finite and non-negative.
    ///
    /// returns: `Result<()>`
    pub fn set_point_stdev(&mut self, values: Option<Vec<f64>>) -> Result<()> {
        self.point_attrs.set_stdev(values, self.point_count())
    }

    /// Set or clear the per-point flat coordinates: the position of each point in a flattened 2D
    /// chart of the surface, such as the output of boundary first flattening. These are not
    /// texture coordinates; they express the mesh's own length units in a plane. They scale with
    /// the geometry under a uniform scale while remaining fixed under a rigid transform.
    ///
    /// Set this after finalizing the mesh because the values are validated against the point count
    /// at the time of the call. The flat-domain queries (`compute_flat_domain`) use this attribute.
    ///
    /// # Arguments
    ///
    /// * `values`: the flat coordinates to store, or `None` to clear them. Must match the point
    ///   count.
    ///
    /// returns: `Result<()>`
    pub fn set_point_flat(&mut self, values: Option<Vec<Point2>>) -> Result<()> {
        self.point_attrs.set_flat(values, self.point_count())
    }

    /// Set or clear the per-face RGB colors.
    ///
    /// # Arguments
    ///
    /// * `values`: the colors to store, or `None` to clear them. Must match the face count.
    ///
    /// returns: `Result<()>`
    pub fn set_face_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
        self.face_attrs.set_colors(values, self.face_count())
    }

    /// Set or clear the per-face labels.
    ///
    /// # Arguments
    ///
    /// * `values`: the labels to store, or `None` to clear them. Must match the face count.
    ///
    /// returns: `Result<()>`
    pub fn set_face_labels(&mut self, values: Option<Vec<u32>>) -> Result<()> {
        self.face_attrs.set_labels(values, self.face_count())
    }

    /// Insert an open-map per-point attribute under the given name, replacing any attribute already
    /// stored there.
    ///
    /// # Arguments
    ///
    /// * `name`: the key to store under, which must not be a reserved name
    /// * `attr`: the attribute array to store, whose length must match the point count
    ///
    /// returns: `Result<()>`
    pub fn insert_point_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
        self.point_attrs.insert_attr(name, attr, self.point_count())
    }

    /// Insert an open-map per-face attribute under the given name, replacing any attribute already
    /// stored there.
    ///
    /// # Arguments
    ///
    /// * `name`: the key to store under, which must not be a reserved name
    /// * `attr`: the attribute array to store, whose length must match the face count
    ///
    /// returns: `Result<()>`
    pub fn insert_face_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
        self.face_attrs.insert_attr(name, attr, self.face_count())
    }

    /// Remove and return the open-map per-point attribute stored under the given name.
    pub fn remove_point_attr(&mut self, name: &str) -> Option<Attr3> {
        self.point_attrs.remove_attr(name)
    }

    /// Remove and return the open-map per-face attribute stored under the given name.
    pub fn remove_face_attr(&mut self, name: &str) -> Option<Attr3> {
        self.face_attrs.remove_attr(name)
    }

    /// Replace the entire set of per-point attributes without changing the face domain.
    ///
    /// # Arguments
    ///
    /// * `attrs`: the per-point attributes to attach, whose arrays must match the point count
    ///
    /// returns: `Result<()>`, leaving the existing attributes untouched on failure
    pub fn set_point_attrs(&mut self, attrs: PointAttrSet3) -> Result<()> {
        attrs.validate(self.point_count())?;
        self.point_attrs = attrs;
        Ok(())
    }

    /// Replace the entire set of per-face attributes without changing the point domain.
    ///
    /// # Arguments
    ///
    /// * `attrs`: the per-face attributes to attach, whose arrays must match the face count
    ///
    /// returns: `Result<()>`, leaving the existing attributes untouched on failure
    pub fn set_face_attrs(&mut self, attrs: FaceAttrSet3) -> Result<()> {
        attrs.validate(self.face_count())?;
        self.face_attrs = attrs;
        Ok(())
    }

    /// Remove and return all per-point attributes, leaving that domain empty on the mesh.
    pub fn take_point_attrs(&mut self) -> PointAttrSet3 {
        std::mem::take(&mut self.point_attrs)
    }

    /// Remove and return all per-face attributes, leaving that domain empty on the mesh.
    pub fn take_face_attrs(&mut self) -> FaceAttrSet3 {
        std::mem::take(&mut self.face_attrs)
    }
}

// ===============================================================================================
// General creation methods
// ===============================================================================================
impl Mesh3 {
    /// Create a new mesh from a list of vertices and a list of triangles.  Additional options can
    /// be set to merge duplicate vertices and delete degenerate triangles.
    ///
    /// The resulting mesh carries no attributes. The cleanup options renumber points and drop
    /// faces, so there is no correct way to carry an attribute array through them, which is why
    /// they live here rather than on the `MeshData3` conversion path.
    ///
    /// Set attributes, including the flat coordinates of a flattened mesh, afterward through their
    /// own setters. The setters validate them against the point and face counts that remain after
    /// cleanup.
    ///
    /// # Arguments
    ///
    /// * `vertices`: the point positions
    /// * `triangles`: the faces, as triples of indices into `vertices`
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at zero
    ///   distance
    /// * `merge_duplicates`: merge points which compare equal as `f64`, and drop the duplicate
    ///   faces that produces
    /// * `delete_degenerate`: drop faces with zero area or repeated indices
    ///
    /// returns: `Result<Mesh3>`, failing if a face refers to a point which does not exist
    pub fn new_with_options(
        vertices: Vec<Point3>,
        triangles: Vec<[u32; 3]>,
        is_solid: bool,
        merge_duplicates: bool,
        delete_degenerate: bool,
    ) -> Result<Self> {
        let mut flags = TriMeshFlags::empty();
        if merge_duplicates {
            flags |= TriMeshFlags::MERGE_DUPLICATE_VERTICES;
            flags |= TriMeshFlags::DELETE_DUPLICATE_TRIANGLES;
        }
        if delete_degenerate {
            flags |= TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES;
            flags |= TriMeshFlags::DELETE_DEGENERATE_TRIANGLES;
        }

        let shape = TriMesh::with_flags(vertices, triangles, flags)?;
        Ok(Self {
            shape,
            point_attrs: PointAttrSet3::empty(),
            face_attrs: FaceAttrSet3::empty(),
            is_solid,
        })
    }

    pub fn new(vertices: Vec<Point3>, triangles: Vec<[u32; 3]>, is_solid: bool) -> Self {
        let shape = TriMesh::new(vertices, triangles).expect("Failed to create TriMesh");
        Self {
            shape,
            point_attrs: PointAttrSet3::empty(),
            face_attrs: FaceAttrSet3::empty(),
            is_solid,
        }
    }

    pub fn from_trimesh(shape: TriMesh, is_solid: bool) -> Self {
        Self {
            shape,
            point_attrs: PointAttrSet3::empty(),
            face_attrs: FaceAttrSet3::empty(),
            is_solid,
        }
    }
}

// ===============================================================================================
// Serialization
// ===============================================================================================
//
// Loading goes through `MeshData3`, where the readers live, and builds a bounding volume hierarchy
// after the read. Saving gives the writers a borrowed `MeshView3` over this mesh's buffers, so
// nothing is copied. Work directly with `MeshData3` when you do not need the acceleration
// structure.

impl Mesh3 {
    /// Load a triangle mesh from a PLY file, preserving every property the file carries.
    ///
    /// The file must have a `vertex` element with `x`, `y`, and `z` properties, and a `face`
    /// element with at least one face. A PLY point cloud is refused, since there is nothing for an
    /// acceleration structure to be built over; load those with `PointCloud3::load_ply`.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to the PLY file
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at zero
    ///   distance
    ///
    /// returns: `Result<Mesh3>`
    #[cfg(feature = "ply")]
    pub fn load_ply(path: &Path, is_solid: bool) -> Result<Self> {
        Self::from_data(MeshData3::load_ply(path)?, is_solid)
    }

    /// Write this mesh to a PLY file, preserving every attribute it carries.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to write to, which is overwritten if it already exists
    /// * `opts`: encoding and header options
    ///
    /// returns: `Result<()>`
    #[cfg(feature = "ply")]
    pub fn save_ply(&self, path: &Path, opts: &PlyWriteOpts) -> Result<()> {
        write_ply_mesh(path, self, opts)
    }

    /// Load a triangle mesh from an STL file, in either the ascii or binary encoding.
    ///
    /// STL is a triangle soup with no point identity, so the points are recovered by welding on
    /// exact coordinate equality. See `load_stl_mesh_data` for what that does and does not recover,
    /// and for the precision the format costs you.
    ///
    /// The cleanup options renumber points and drop faces, which is why they are available here and
    /// not on the PLY path: an STL carries no attributes for the renumbering to invalidate.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to the STL file
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at zero
    ///   distance
    /// * `merge_duplicates`: additionally merge points which compare equal as `f64`, which after
    ///   the exact weld the reader already performs means only merging `0.0` with `-0.0`
    /// * `delete_degenerate`: drop triangles with zero area or bad topology
    ///
    /// returns: `Result<Mesh3>`
    #[cfg(feature = "stl")]
    pub fn load_stl(
        path: &Path,
        is_solid: bool,
        merge_duplicates: bool,
        delete_degenerate: bool,
    ) -> Result<Self> {
        let (points, faces, _, _) = MeshData3::load_stl(path)?.into_parts();
        Self::new_with_options(points, faces, is_solid, merge_duplicates, delete_degenerate)
    }

    /// Write this mesh to an STL file, which carries geometry and nothing else.
    ///
    /// The default options write binary with no attribute loss permitted, so a mesh carrying any
    /// attributes at all is refused rather than silently stripped. Set `allow_attribute_loss` to
    /// accept the loss.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to write to, which is overwritten if it already exists
    /// * `opts`: encoding, header, and attribute loss options
    ///
    /// returns: `Result<()>`
    #[cfg(feature = "stl")]
    pub fn save_stl(&self, path: &Path, opts: &StlWriteOpts) -> Result<()> {
        write_stl_mesh(path, self, opts)
    }

    /// Load a triangle mesh from a GOM `.g3d` file, the format written by GOM's Atos scanner and
    /// GOM/Zeiss Inspect. See [`MeshData3::load_g3d`] for what this does and does not support.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to the `.g3d` file
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at
    ///   zero distance
    ///
    /// returns: `Result<Mesh3>`
    pub fn load_g3d(path: &Path, is_solid: bool) -> Result<Self> {
        Self::from_data(MeshData3::load_g3d(path)?, is_solid)
    }

    /// Load a triangle mesh from a tolerance-compressed `.tcmesh` file. See
    /// [`MeshData3::load_tcmesh`] for the guarantees the format makes.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to the `.tcmesh` file
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at
    ///   zero distance
    ///
    /// returns: `Result<Mesh3>`
    pub fn load_tcmesh(path: &Path, is_solid: bool) -> Result<Self> {
        Self::from_data(MeshData3::load_tcmesh(path)?, is_solid)
    }

    /// Write this mesh to a tolerance-compressed `.tcmesh` file, which carries geometry and
    /// nothing else. See [`MeshData3::save_tcmesh`] for what the tolerance buys and for the vertex
    /// renumbering the format performs.
    ///
    /// # Arguments
    ///
    /// * `path`: the path to write to, which is overwritten if it already exists
    /// * `tol`: the largest acceptable round-trip position error for any vertex, in the same units
    ///   as the coordinates
    ///
    /// returns: `Result<()>`, failing if the mesh carries any attributes
    pub fn save_tcmesh(&self, path: &Path, tol: f64) -> Result<()> {
        write_tc_mesh_file(path, self, tol)
    }
}

// ===============================================================================================
// Conversion to and from MeshData3
// ===============================================================================================

impl Mesh3 {
    /// Build an accelerated mesh from plain mesh data, taking ownership of its buffers and its
    /// attributes.
    ///
    /// The point and face buffers are moved into the underlying `TriMesh` unchanged, so every
    /// index keeps the meaning it had and the attribute arrays stay valid. The cost paid here is
    /// the bounding volume hierarchy build.
    ///
    /// # Arguments
    ///
    /// * `data`: the mesh data to consume
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at zero
    ///   distance
    ///
    /// returns: `Result<Mesh3>`, failing if the mesh has no faces, since there is nothing to build
    /// an acceleration structure over
    pub fn from_data(data: MeshData3, is_solid: bool) -> Result<Self> {
        let (points, faces, point_attrs, face_attrs) = data.into_parts();

        if faces.is_empty() {
            return Err(
                "Cannot build a Mesh3 from mesh data with no faces. A MeshData3 is allowed \
                        to hold points without faces, but there is nothing for an acceleration \
                        structure to be built over."
                    .into(),
            );
        }

        let shape = TriMesh::new(points, faces)?;
        Ok(Self {
            shape,
            point_attrs,
            face_attrs,
            is_solid,
        })
    }

    /// Copy this mesh's buffers and attributes out into plain mesh data.
    ///
    /// Unlike `from_data`, this **clones** the point and face buffers. `parry3d` gives no way to
    /// move them back out of a `TriMesh`, so the copy is unavoidable. Use `into_data` if you are
    /// done with the accelerated mesh, which at least drops the acceleration structure.
    ///
    /// returns: `MeshData3`
    pub fn to_data(&self) -> MeshData3 {
        MeshData3::new_with_attrs(
            self.points().to_vec(),
            self.faces().to_vec(),
            self.point_attrs.clone(),
            self.face_attrs.clone(),
        )
        .expect(
            "A Mesh3's attributes are validated against its point and face counts on every \
             operation which can change them, so rebuilding a MeshData3 from them cannot fail",
        )
    }

    /// Consume this mesh and return its buffers and attributes as plain mesh data.
    ///
    /// This still copies the point and face buffers, for the reason given on `to_data`, but it
    /// discards the acceleration structure rather than leaving it alive alongside the copy.
    ///
    /// returns: `MeshData3`
    pub fn into_data(self) -> MeshData3 {
        self.to_data()
    }
}

impl TryFrom<MeshData3> for Mesh3 {
    type Error = Box<dyn std::error::Error>;

    /// Build an accelerated mesh which is **not** solid. Use `Mesh3::from_data` or
    /// `MeshData3::into_mesh` to specify whether the mesh is solid.
    fn try_from(value: MeshData3) -> Result<Self> {
        Mesh3::from_data(value, false)
    }
}

impl From<Mesh3> for MeshData3 {
    fn from(value: Mesh3) -> Self {
        value.into_data()
    }
}

// ===============================================================================================
// Mutation/Transformation
// ===============================================================================================
impl Mesh3 {
    /// Transform the mesh in place by applying the given transformation to all vertices.
    ///
    /// Any stored point normals and `Vector` attributes are rotated with the geometry. Because
    /// those hold directions rather than positions, only the rotation component has any effect.
    pub fn transform_in_place(&mut self, transform: &Iso3) {
        self.shape.transform_vertices(transform);
        self.point_attrs.transform_in_place(transform);
        self.face_attrs.transform_in_place(transform);
    }

    /// Returns a new mesh with all vertices transformed by the given isometry, leaving the
    /// original unchanged.
    pub fn transform_copy(&self, transform: &Iso3) -> Self {
        let mut result = self.clone();
        result.transform_in_place(transform);
        result
    }

    /// Create a new mesh by scaling all points uniformly about the origin.
    ///
    /// Any stored point standard deviations are scaled with the geometry, since they are lengths in
    /// the mesh's own units. Normals are directions and a uniform scale does not move them.
    ///
    /// A **negative** factor is a mirror, which is orientation-reversing: the face normals implied
    /// by the winding keep pointing the same way in space while the solid turns inside out around
    /// them. The winding is therefore reversed and any stored point normals negated, matching what
    /// `MeshData3::scale_copy` does.
    ///
    /// # Arguments
    ///
    /// * `scale`: the factor to scale by, which must be finite and non-zero
    ///
    /// returns: `Result<Mesh3>`
    pub fn scale_copy(&self, scale: f64) -> Result<Self> {
        if !scale.is_finite() || scale == 0.0 {
            return Err(format!(
                "A scale factor must be finite and non-zero, but {scale} was given. Scaling by zero \
                 would collapse the mesh to a point irrecoverably."
            )
            .into());
        }

        let new_shape = self
            .shape
            .clone()
            .scaled(&Vector3::new(scale, scale, scale));

        let mut result = Mesh3::from_trimesh(new_shape, self.is_solid);
        result.point_attrs = self.point_attrs.clone();
        result.face_attrs = self.face_attrs.clone();

        // Only the point domain has anything with length units.
        result.point_attrs.scale_in_place(scale);

        if scale < 0.0 {
            result.flip_normals_in_place();
        }

        Ok(result)
    }

    /// Create a new mesh by offsetting each point along its smoothed point normal.
    ///
    /// The offset is applied as `point + offset * normal`, where the normal is the per-point normal
    /// computed by `compute_point_normals`.
    ///
    /// Positive offsets expand the mesh outward; negative offsets shrink it inward.
    /// The original mesh is not modified.
    ///
    /// # Arguments
    ///
    /// * `offset`: The distance to offset each point along its normal.
    ///
    /// returns: `Result<Mesh3>`, failing if any point has no well-defined normal
    pub fn offset_points_copy(&self, offset: f64) -> Result<Self> {
        let normals = self.compute_point_normals()?;

        let updated = self
            .points()
            .iter()
            .zip(normals.iter())
            .map(|(v, n)| v + offset * n.into_inner())
            .collect();

        Ok(Self::new(updated, self.faces().to_vec(), self.is_solid))
    }

    /// Reverse the winding order of every face, turning the surface inside out.
    ///
    /// Any stored point normals are negated to match, since the direction the surface faces has
    /// changed.
    pub fn flip_normals_in_place(&mut self) {
        self.shape.reverse();
        self.point_attrs.flip_in_place();
    }
}

// ===============================================================================================
// Unsorted
// ===============================================================================================

impl Mesh3 {
    pub fn compute_edges(&self) -> Result<MeshEdges<'_>> {
        MeshEdges::new(self)
    }

    /// Return a convex hull of the points in the mesh.
    ///
    /// The hull is new topology: its points are a subset of this mesh's but its faces are not, and
    /// `parry3d` gives no mapping back from one to the other. There is therefore no correct value
    /// to carry any attribute forward with, so a mesh which has any is refused unless the caller
    /// says the loss is acceptable.
    ///
    /// # Arguments
    ///
    /// * `allow_attribute_loss`: accept the loss of every attribute this mesh carries
    ///
    /// returns: `Result<Mesh3>`
    pub fn convex_hull(&self, allow_attribute_loss: bool) -> Result<Self> {
        self.check_attribute_loss("a convex hull", allow_attribute_loss)?;

        let (vertices, faces) = transformation::convex_hull(self.shape.vertices());
        Ok(Self::new(vertices, faces, true))
    }

    /// Append another mesh onto the end of this one.
    ///
    /// The other mesh's points are added after this one's and its faces are re-indexed to match. No
    /// points are welded and no faces are merged, so a shared boundary between the two meshes stays
    /// as two coincident sets of points.
    ///
    /// Attributes are all-or-nothing: a typed field or an open-map key present on one side and
    /// absent on the other is an error, because there is no correct value to pad the missing side
    /// with. The whole append is validated before anything is modified, so a failure leaves this
    /// mesh untouched.
    ///
    /// # Arguments
    ///
    /// * `other`: the mesh to append
    ///
    /// returns: `Result<()>`
    pub fn append_in_place(&mut self, other: &Mesh3) -> Result<()> {
        // Both attribute domains are checked before anything is modified because these checks are
        // the only steps that can fail. Extending the point domain before checking the face domain
        // would leave the mesh only partially appended if a face attribute were mismatched.
        self.point_attrs.check_extend_from(&other.point_attrs)?;
        self.face_attrs.check_extend_from(&other.face_attrs)?;

        self.point_attrs.apply_extend_from(&other.point_attrs)?;
        self.face_attrs.apply_extend_from(&other.face_attrs)?;

        self.shape.append(&other.shape);

        Ok(())
    }

    /// Verify that the caller has accepted the loss of this mesh's attributes, for an operation
    /// which cannot carry them.
    ///
    /// See `MeshData3::check_attribute_loss` for why this is an error rather than a warning.
    ///
    /// # Arguments
    ///
    /// * `operation`: what is about to discard them, used in the error message
    /// * `allow_loss`: whether the caller has accepted the loss
    ///
    /// returns: `Result<()>`
    pub fn check_attribute_loss(&self, operation: &str, allow_loss: bool) -> Result<()> {
        if allow_loss || !self.has_attrs() {
            return Ok(());
        }

        Err(format!(
            "Taking {} would discard the attributes on this mesh ({}), because it produces \
             topology with no index mapping back to the original. Pass `allow_attribute_loss` to \
             accept this.",
            operation,
            self.view().attr_labels().join(", ")
        )
        .into())
    }

    /// Borrow this mesh as the read-only view accepted by the file writers.
    pub fn view(&self) -> MeshView3<'_> {
        MeshView3::from(self)
    }

    /// Create a new `MeshNav` structure for this mesh. This structure is used to efficiently
    /// navigate the mesh through edges and faces.  It is recommended to use this if you will be
    /// performing multiple structural queries on the mesh, so that the structure does not need to
    /// be recomputed each time.
    pub fn compute_nav(&self) -> MeshNav<'_> {
        MeshNav::new(self)
    }

    /// Label every face with the connected patch it belongs to.
    ///
    /// The labeling costs one `u32` per face regardless of how many patches the mesh splits into.
    /// Use `PatchLabels::mask_where` or `mask_of` to turn the result into face masks, one at a
    /// time, rather than materializing all of them at once. See `MeshNav::patch_labels` for the
    /// connectivity rule.
    ///
    /// This builds a `MeshNav` on every call. Build one yourself with `compute_nav()` if you are
    /// going to query the structure of the mesh more than once.
    ///
    /// # Arguments
    ///
    /// * `mask`: an optional mask restricting which faces take part, as if the mesh had been
    ///   pruned to it.
    ///
    /// returns: `Result<PatchLabels>`
    pub fn compute_patch_labels(&self, mask: Option<&IndexMask>) -> Result<PatchLabels> {
        let nav = self.compute_nav();
        nav.patch_labels(mask)
    }

    /// Build a face mask selecting the connected patches which pass a filter.
    ///
    /// Use this rather than `remove_small_patches` when you want to see what would be discarded,
    /// or to combine the selection with other criteria before extracting.
    ///
    /// # Arguments
    ///
    /// * `filter`: which patches are worth keeping
    ///
    /// returns: `Result<IndexMask>` over the mesh's faces
    pub fn patch_mask(&self, filter: &PatchFilter) -> Result<IndexMask> {
        let nav = self.compute_nav();
        nav.patch_mask(filter, None)
    }

    /// Discard the connected patches which fail a filter, returning what is left.
    ///
    /// This is the tool for cleaning flying patches and speckle out of scan data. Every attribute
    /// survives, because dropping whole faces keeps an index mapping back to the original.
    ///
    /// If no patch fails the filter the mesh is returned unchanged, rather than rebuilt, so a
    /// filter which finds nothing to do is cheap and preserves the UV mapping.
    ///
    /// # Arguments
    ///
    /// * `filter`: which patches are worth keeping
    ///
    /// returns: `Result<Mesh3>`, failing if the filter would discard every face, since a mesh
    /// needs at least one face
    pub fn remove_small_patches(&self, filter: &PatchFilter) -> Result<Self> {
        let mask = self.patch_mask(filter)?;
        let kept = mask.count_true();

        if kept == 0 {
            return Err(
                "Every patch was discarded by the filter, which would leave an empty mesh".into(),
            );
        }

        if kept == self.faces().len() {
            return Ok(self.clone());
        }

        self.extract_subset_faces(&mask)
    }

    /// Gets the boundary points of each patch in the mesh.  This function will return a list of
    /// lists of points, where each list of points is the boundary of a patch.  Note that this
    /// function will not work on non-manifold meshes.
    ///
    /// returns: Result<Vec<Vec<usize, Global>, Global>>
    pub fn compute_patch_boundary_points(&self) -> Result<Vec<Vec<Point3>>> {
        let edges = MeshEdges::new(self)?;

        let mut b_loops = Vec::new();
        for b_loop in edges.boundary_loops.iter() {
            b_loops.push(
                b_loop
                    .iter()
                    .map(|vi| self.points()[*vi as usize])
                    .collect(),
            );
        }

        Ok(b_loops)
    }

    /// Compute the unit normal of every face, from the winding of its three points.
    ///
    /// returns: `Result<Vec<UnitVec3>>`, one normal per face, failing on a face which has no
    /// well-defined normal because its points are coincident or collinear
    pub fn compute_face_normals(&self) -> Result<Vec<UnitVec3>> {
        algorithms::compute_face_normals(self.points(), self.faces())
    }

    /// Compute the area of every face.
    ///
    /// returns: `Result<Vec<f64>>`, one area per face. A degenerate face has an area of zero rather
    /// than being an error.
    pub fn compute_face_areas(&self) -> Result<Vec<f64>> {
        algorithms::compute_face_areas(self.points(), self.faces())
    }

    /// Compute the centroid of every face, which is the mean of its three points.
    ///
    /// returns: `Result<Vec<Point3>>`, one centroid per face
    pub fn compute_face_centers(&self) -> Result<Vec<Point3>> {
        algorithms::compute_face_centers(self.points(), self.faces())
    }

    /// Compute a smoothed normal for every point by averaging the normals of the faces which touch
    /// it, weighting each by the interior angle of that face at that point.
    ///
    /// See `algorithms::compute_point_normals` for why the weighting is by angle and not by area,
    /// and for what this quantity is and is not good for.
    ///
    /// returns: `Result<Vec<UnitVec3>>`, one normal per point, failing if any point has no
    /// well-defined normal, which happens when it belongs to no face, belongs only to degenerate
    /// faces, or sits where the weighted contributions cancel exactly
    pub fn compute_point_normals(&self) -> Result<Vec<UnitVec3>> {
        algorithms::compute_point_normals(self.points(), self.faces())
    }
}

// ===============================================================================================
// Shape creation methods
// ===============================================================================================
//
// Every one of these is a pass-through to the `MeshData3` constructor of the same name, adding the
// `is_solid` flag. The tessellations live there because they produce points and faces and nothing
// else; `is_solid` is a query behavior and belongs only to the accelerated type.

impl Mesh3 {
    /// Create a box mesh with the given dimensions, centered at the origin.
    ///
    /// See `MeshData3::create_box`.
    ///
    /// # Arguments
    ///
    /// * `length`: the dimension of the box in the x direction
    /// * `width`: the dimension of the box in the y direction
    /// * `height`: the dimension of the box in the z direction
    /// * `is_solid`: whether distance queries should treat points inside the mesh as being at zero
    ///   distance
    ///
    /// returns: `Mesh3`
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::Mesh3;
    /// use approx::assert_relative_eq;
    /// let mesh = Mesh3::create_box(2.0, 4.0, 6.0, false);
    /// assert_relative_eq!(mesh.aabb().maxs.x, 1.0);
    /// assert_relative_eq!(mesh.aabb().maxs.y, 2.0);
    /// assert_relative_eq!(mesh.aabb().maxs.z, 3.0);
    /// assert_relative_eq!(mesh.aabb().mins.x, -1.0);
    /// assert_relative_eq!(mesh.aabb().mins.y, -2.0);
    /// assert_relative_eq!(mesh.aabb().mins.z, -3.0);
    /// ```
    pub fn create_box(length: f64, width: f64, height: f64, is_solid: bool) -> Self {
        Self::from_primitive(MeshData3::create_box(length, width, height), is_solid)
    }

    /// Create a closed spherical mesh centered at the origin, with its poles on the local `z`
    /// axis.
    ///
    /// See `MeshData3::create_sphere`.
    ///
    /// # Arguments
    ///
    /// * `radius`: radius of the sphere, which must be positive and finite
    /// * `tol`: the maximum allowed deviation of a facet from the true sphere, which must be
    ///   positive and finite. No matter how loose this is, a full turn around the equator never
    ///   gets fewer than 8 segments and a pole-to-pole sweep never gets fewer than 4.
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid
    pub fn create_sphere(radius: f64, tol: f64) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_sphere(radius, tol)?,
            true,
        ))
    }

    /// Create a closed cylindrical mesh centered at the origin and aligned with the local `z`
    /// axis.
    ///
    /// See `MeshData3::create_cylinder`.
    ///
    /// # Arguments
    ///
    /// * `radius`: radius of the cylinder, which must be positive and finite
    /// * `height`: full height of the cylinder, along the z-axis
    /// * `tol`: the maximum allowed chordal deviation of the wall, which must be positive and
    ///   finite. The circumference never gets fewer than 8 segments, no matter how loose this is.
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid
    pub fn create_cylinder(radius: f64, height: f64, tol: f64) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_cylinder(radius, height, tol)?,
            true,
        ))
    }

    /// Create a closed conical mesh centered at the origin and aligned with the local `z` axis,
    /// with its apex at `+height/2` and its base at `-height/2`.
    ///
    /// See `MeshData3::create_cone`.
    ///
    /// # Arguments
    ///
    /// * `radius`: radius of the base of the cone, which must be positive and finite
    /// * `height`: full height of the cone, along the z-axis
    /// * `tol`: the maximum allowed chordal deviation of the base circle, which must be positive
    ///   and finite. The base never gets fewer than 8 segments, no matter how loose this is.
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid
    pub fn create_cone(radius: f64, height: f64, tol: f64) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_cone(radius, height, tol)?,
            true,
        ))
    }

    /// Create a flat, filled circle mesh lying in the XY plane, centered at the origin, with the
    /// normal pointing along +Z.
    ///
    /// See `MeshData3::create_circle`.
    ///
    /// # Arguments
    ///
    /// * `radius`: radius of the circle, which must be positive and finite
    /// * `tol`: the maximum allowed chordal deviation of the perimeter, which must be positive
    ///   and finite
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid
    pub fn create_circle(radius: f64, tol: f64) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_circle(radius, tol)?,
            false,
        ))
    }

    /// Create a capsule mesh spanning the segment between two points.
    ///
    /// See `MeshData3::create_capsule`.
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid, or if the two points are
    /// coincident
    pub fn create_capsule(p0: &Point3, p1: &Point3, radius: f64, tol: f64) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_capsule(p0, p1, radius, tol)?,
            true,
        ))
    }

    /// Create a cylindrical mesh spanning the segment between two points.
    ///
    /// See `MeshData3::create_cylinder_between`.
    ///
    /// returns: `Result<Mesh3>`, failing if `radius` or `tol` is invalid, or if the two points are
    /// coincident
    pub fn create_cylinder_between(
        p0: &Point3,
        p1: &Point3,
        radius: f64,
        tol: f64,
    ) -> Result<Self> {
        Ok(Self::from_primitive(
            MeshData3::create_cylinder_between(p0, p1, radius, tol)?,
            true,
        ))
    }

    /// Create a rectangular beam spanning the segment between two points.
    ///
    /// See `MeshData3::create_rect_beam_between`.
    ///
    /// returns: `Result<Mesh3>`, failing if `up` is parallel to the segment
    pub fn create_rect_beam_between(
        p0: &Point3,
        p1: &Point3,
        width: f64,
        height: f64,
        up: &Vector3,
    ) -> Result<Self> {
        let data = MeshData3::create_rect_beam_between(p0, p1, width, height, up)?;
        Ok(Self::from_primitive(data, true))
    }

    /// Load a Stanford bunny mesh embedded in the binary with 453 points and 948 faces.
    ///
    /// See `MeshData3::stanford_bunny_res4`.
    pub fn stanford_bunny_res4() -> Self {
        Self::from_primitive(MeshData3::stanford_bunny_res4(), false)
    }

    /// Load a Stanford bunny mesh embedded in the binary with 1889 points and 3851 faces.
    ///
    /// See `MeshData3::stanford_bunny_res3`.
    pub fn stanford_bunny_res3() -> Self {
        Self::from_primitive(MeshData3::stanford_bunny_res3(), false)
    }

    /// Load a Stanford bunny mesh embedded in the binary with 8171 points and 16301 faces.
    ///
    /// See `MeshData3::stanford_bunny_res2`.
    pub fn stanford_bunny_res2() -> Self {
        Self::from_primitive(MeshData3::stanford_bunny_res2(), false)
    }

    /// Accelerate a mesh which came from one of the primitive constructors.
    ///
    /// Those always produce at least one face, which is the only way `from_data` can fail, so the
    /// failure is a bug in the tessellation rather than anything a caller can cause.
    fn from_primitive(data: MeshData3, is_solid: bool) -> Self {
        Self::from_data(data, is_solid)
            .expect("A primitive tessellation always has at least one face")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Plane3;
    use crate::tests::stanford_bun_4;
    use approx::assert_relative_eq;
    use parry3d_f64::query::SplitResult;
    use std::f64::consts::FRAC_PI_2;

    /// `Mesh3` reaches the format through `MeshData3`, and the only thing it adds is the `is_solid`
    /// flag, which the file does not carry and the caller therefore has to supply on load.
    #[test]
    fn a_tcmesh_round_trips_and_is_solid_comes_from_the_caller() -> Result<()> {
        let mesh = Mesh3::create_sphere(1.0, 0.025)?;
        let tol = 1e-5;
        let file = TempFile::new("tcmesh-round-trip", "tcmesh");

        mesh.save_tcmesh(file.path(), tol)?;

        let recovered = Mesh3::load_tcmesh(file.path(), true)?;
        assert_eq!(recovered.point_count(), mesh.point_count());
        assert_eq!(recovered.face_count(), mesh.face_count());
        assert!(recovered.is_solid());

        assert!(!Mesh3::load_tcmesh(file.path(), false)?.is_solid());

        Ok(())
    }

    #[test]
    fn saving_a_tcmesh_refuses_a_mesh_carrying_attributes() -> Result<()> {
        let mesh = Mesh3::from_data(attributed_data(), false)?;
        let file = TempFile::new("tcmesh-refused", "tcmesh");

        assert!(mesh.save_tcmesh(file.path(), 1e-5).is_err());

        Ok(())
    }

    #[test]
    fn point_normals_match_point_count() -> Result<()> {
        let mesh = Mesh3::create_sphere(1.0, 6.0e-3)?;
        let normals = mesh.compute_point_normals()?;

        assert_eq!(normals.len(), mesh.points().len());

        Ok(())
    }

    /// The stanford bunny asset carries a defect: faces 207 and 209 are the same triangle wound in
    /// opposite directions, and point 128 belongs to nothing else. Its two incident normals cancel,
    /// so it genuinely has no normal, and the computation is expected to say so rather than
    /// normalizing the floating point residue into a direction, which is what it used to do.
    ///
    /// The indices moved when the fixture was re-encoded from micro-mesh to tcmesh, which renumbers
    /// vertices. The defect itself is unchanged: the same pair of opposed triangles, the same lone
    /// point, verified rather than assumed when the numbers were updated.
    #[test]
    fn point_normals_report_the_bunny_asset_defect() {
        let mesh = stanford_bun_4();

        let err = mesh.compute_point_normals().unwrap_err();

        assert!(
            err.to_string().starts_with("Point 128 has no well-defined"),
            "unexpected error: {err}"
        );
    }

    /// The outline uses point normals only to nudge itself off the surface, so it tolerates the
    /// defect above rather than failing on a mesh it can perfectly well draw.
    #[test]
    fn visual_outline_survives_a_point_with_no_normal() -> Result<()> {
        let mesh = stanford_bun_4();

        let outline =
            mesh.compute_visual_outline(UnitVec3::new_normalize(Vector3::z()), 1.0, None)?;

        assert!(!outline.is_empty());
        Ok(())
    }

    /// The accelerated type and the plain container are two representations of the same buffers, so
    /// the normals they compute have to agree exactly rather than merely being close.
    #[test]
    fn point_normals_agree_with_mesh_data() -> Result<()> {
        let mesh = Mesh3::create_sphere(1.0, 6.0e-3)?;
        let from_mesh = mesh.compute_point_normals()?;
        let from_data = mesh.to_data().compute_point_normals()?;

        assert_eq!(from_mesh.len(), from_data.len());
        for (a, b) in from_mesh.iter().zip(from_data.iter()) {
            assert_relative_eq!(a.into_inner(), b.into_inner(), epsilon = 1.0e-15);
        }

        Ok(())
    }

    /// Angle weighting is invariant to how a flat face is triangulated, so every corner normal of a
    /// box lands exactly on the diagonal. Area weighting, which this method used to do, does not:
    /// a corner touching one triangle on one face and two on another gets pulled off the diagonal.
    #[test]
    fn point_normals_of_a_box_point_along_the_diagonals() -> Result<()> {
        let mesh = Mesh3::create_box(2.0, 2.0, 2.0, true);
        let normals = mesh.compute_point_normals()?;
        let diagonal = 1.0 / 3.0_f64.sqrt();

        for (point, normal) in mesh.points().iter().zip(normals.iter()) {
            let expected = Vector3::new(
                point.x.signum() * diagonal,
                point.y.signum() * diagonal,
                point.z.signum() * diagonal,
            );
            assert_relative_eq!(normal.into_inner(), &expected, epsilon = 1.0e-12);
        }

        Ok(())
    }

    #[test]
    fn scale_copy_scales_spherical_radius() -> Result<()> {
        let radius = 1.0;
        let scale = 2.5;
        let mesh = Mesh3::create_sphere(radius, radius * 1.0e-3)?;
        let scaled = mesh.scale_copy(scale)?;

        assert_eq!(mesh.points().len(), scaled.points().len());

        for vertex in scaled.points() {
            assert_relative_eq!(vertex.coords.norm(), radius * scale, epsilon = 1.0e-12);
        }

        Ok(())
    }

    #[test]
    fn offset_points_copy_preserves_spherical_radius() -> Result<()> {
        let radius = 1.0;
        let offset = 0.1;
        let mesh = Mesh3::create_sphere(radius, radius * 1.0e-3)?;
        let offset_mesh = mesh.offset_points_copy(offset)?;

        assert_eq!(mesh.points().len(), offset_mesh.points().len());

        for vertex in offset_mesh.points() {
            assert_relative_eq!(vertex.coords.norm(), radius + offset, epsilon = 1.0e-5);
        }

        Ok(())
    }

    // ===========================================================================================
    // Conversion to and from MeshData3
    // ===========================================================================================

    /// A single triangle in the xy plane, wound so that its normal is +z, carrying one attribute of
    /// every kind an operation might have to touch.
    fn attributed_data() -> MeshData3 {
        let mut data = MeshData3::new(
            vec![
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 0.0, 0.0),
                Point3::new(0.0, 1.0, 0.0),
            ],
            vec![[0, 1, 2]],
        )
        .unwrap();

        data.set_point_normals(Some(vec![UnitVec3::new_normalize(Vector3::z()); 3]))
            .unwrap();
        data.set_point_stdev(Some(vec![0.1, 0.2, 0.3])).unwrap();
        data.set_point_flat(Some(vec![
            Point2::new(0.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 2.0),
        ]))
        .unwrap();
        data.set_face_labels(Some(vec![7])).unwrap();
        data.insert_point_attr("confidence", Attr3::Scalar(vec![0.5, 0.6, 0.7]))
            .unwrap();
        data.insert_point_attr("principal_dir", Attr3::Vector(vec![Vector3::x(); 3]))
            .unwrap();

        data
    }

    #[test]
    fn round_trip_through_mesh_data_preserves_everything() -> Result<()> {
        let before = attributed_data();
        let mesh = Mesh3::from_data(before.clone(), true)?;

        assert!(mesh.is_solid());
        assert_eq!(mesh.point_count(), 3);
        assert_eq!(mesh.face_count(), 1);

        let after = mesh.to_data();

        assert_eq!(after.points(), before.points());
        assert_eq!(after.faces(), before.faces());
        assert_eq!(after.point_attrs(), before.point_attrs());
        assert_eq!(after.face_attrs(), before.face_attrs());

        Ok(())
    }

    /// The buffers have to come across index-identical, or every attribute array would be pointing
    /// at the wrong elements.
    #[test]
    fn from_data_does_not_renumber_the_buffers() -> Result<()> {
        let data = stanford_bun_4().to_data();
        let mesh = Mesh3::from_data(data.clone(), false)?;

        assert_eq!(mesh.points(), data.points());
        assert_eq!(mesh.faces(), data.faces());

        Ok(())
    }

    /// `MeshData3` allows points without faces, but there is nothing to accelerate.
    #[test]
    fn from_data_rejects_a_mesh_with_no_faces() -> Result<()> {
        let data = MeshData3::new(
            vec![Point3::origin(), Point3::new(1.0, 0.0, 0.0)],
            Vec::new(),
        )?;
        assert!(Mesh3::from_data(data, false).is_err());

        Ok(())
    }

    #[test]
    fn conversion_traits_agree_with_the_named_methods() -> Result<()> {
        let mesh = Mesh3::try_from(attributed_data())?;

        // The trait impl has no way to be told, so it picks the non-solid reading.
        assert!(!mesh.is_solid());

        let data: MeshData3 = mesh.into();
        assert_eq!(data.point_attrs(), attributed_data().point_attrs());
        assert_eq!(data.face_attrs(), attributed_data().face_attrs());

        Ok(())
    }

    // ===========================================================================================
    // Attributes under in-place mutation
    // ===========================================================================================

    #[test]
    fn transform_rotates_the_direction_attributes() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;
        mesh.insert_face_attr("face_dir", Attr3::Vector(vec![Vector3::x()]))?;

        // A quarter turn about +z, which maps +x onto +y, plus a translation.
        let iso = Iso3::new(Vector3::new(10.0, 0.0, 0.0), Vector3::z() * FRAC_PI_2);
        mesh.transform_in_place(&iso);

        assert_relative_eq!(
            mesh.points()[1],
            Point3::new(10.0, 1.0, 0.0),
            epsilon = 1.0e-12
        );

        // +z lies on the axis of rotation and does not move.
        assert_relative_eq!(
            mesh.point_normals().unwrap()[0].into_inner(),
            Vector3::z(),
            epsilon = 1.0e-12
        );
        assert_relative_eq!(
            mesh.point_attr("principal_dir")
                .unwrap()
                .as_vector()
                .unwrap()[0],
            Vector3::y(),
            epsilon = 1.0e-12
        );

        // The face domain is a separate set and must be rotated as well.
        assert_relative_eq!(
            mesh.face_attr("face_dir").unwrap().as_vector().unwrap()[0],
            Vector3::y(),
            epsilon = 1.0e-12
        );

        // Scalars are untouched.
        assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);

        Ok(())
    }

    /// A mesh carrying only a face attribute is not bare, which ensures that checking only the
    /// point domain cannot incorrectly classify it as bare.
    #[test]
    fn a_face_only_attribute_counts_as_having_attrs() -> Result<()> {
        let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        assert!(!mesh.has_attrs());

        mesh.set_face_labels(Some(vec![0; mesh.face_count()]))?;
        assert!(mesh.has_attrs());
        assert!(mesh.point_attrs().is_empty());
        assert!(mesh.check_attribute_loss("a test", false).is_err());

        Ok(())
    }

    #[test]
    fn scaling_scales_the_standard_deviations_and_flat_coordinates() -> Result<()> {
        let mesh = Mesh3::from_data(attributed_data(), false)?;
        let scaled = mesh.scale_copy(25.4)?;

        assert_relative_eq!(
            scaled.point_flat().unwrap()[1].coords,
            Point2::new(2.0 * 25.4, 0.0).coords,
            epsilon = 1.0e-12
        );

        for (actual, expected) in scaled
            .point_stdev()
            .unwrap()
            .iter()
            .zip([0.1, 0.2, 0.3].iter())
        {
            assert_relative_eq!(*actual, expected * 25.4, epsilon = 1.0e-12);
        }

        // Normals are directions and a uniform scale does not move them.
        assert_relative_eq!(
            scaled.point_normals().unwrap()[0].into_inner(),
            Vector3::z(),
            epsilon = 1.0e-12
        );

        Ok(())
    }

    #[test]
    fn flipping_negates_the_stored_normals() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;
        mesh.flip_normals_in_place();

        assert_relative_eq!(
            mesh.point_normals().unwrap()[0].into_inner(),
            -Vector3::z(),
            epsilon = 1.0e-12
        );

        Ok(())
    }

    #[test]
    fn append_unions_the_attributes() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;
        let other = Mesh3::from_data(attributed_data(), false)?;

        mesh.append_in_place(&other)?;

        assert_eq!(mesh.point_count(), 6);
        assert_eq!(mesh.face_count(), 2);
        assert_eq!(mesh.faces()[1], [3, 4, 5]);
        assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.1, 0.2, 0.3]);
        assert_eq!(mesh.face_labels().unwrap(), &[7, 7]);
        assert_eq!(mesh.point_attr("confidence").unwrap().len(), 6);

        // Flat coordinates concatenate like any other attribute. The two charts overlap in the
        // plane, and the caller is responsible for resolving that overlap if necessary.
        let flat = mesh.point_flat().unwrap();
        assert_eq!(flat.len(), 6);
        assert_eq!(flat[4], Point2::new(2.0, 0.0));

        mesh.point_attrs().validate(mesh.point_count())?;
        mesh.face_attrs().validate(mesh.face_count())?;

        Ok(())
    }

    /// An attribute on one side and not the other has no correct padding value, and a failure has
    /// to leave the target completely untouched rather than half appended.
    #[test]
    fn append_rejects_a_mismatch_without_modifying_the_target() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;

        let mut bare_data = attributed_data();
        bare_data.set_point_stdev(None)?;
        let other = Mesh3::from_data(bare_data, false)?;

        assert!(mesh.append_in_place(&other).is_err());

        assert_eq!(mesh.point_count(), 3);
        assert_eq!(mesh.face_count(), 1);
        assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);

        Ok(())
    }

    /// The two domains are separate sets, so a face-domain mismatch must be caught before the point
    /// domain is modified. Otherwise, the mesh would be left with extended point attributes but
    /// unchanged geometry and face attributes.
    #[test]
    fn a_face_domain_rejection_leaves_the_point_domain_untouched() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;

        let mut unlabeled = attributed_data();
        unlabeled.set_face_labels(None)?;
        let other = Mesh3::from_data(unlabeled, false)?;

        assert!(mesh.append_in_place(&other).is_err());

        assert_eq!(mesh.point_count(), 3);
        assert_eq!(mesh.face_count(), 1);
        assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);
        assert_eq!(mesh.point_attr("confidence").unwrap().len(), 3);
        assert_eq!(mesh.face_labels().unwrap(), &[7]);

        Ok(())
    }

    #[test]
    fn appending_two_bare_meshes_works() -> Result<()> {
        let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let other = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let n = mesh.point_count();

        mesh.append_in_place(&other)?;
        assert_eq!(mesh.point_count(), n * 2);

        Ok(())
    }

    // ===========================================================================================
    // Attributes on derived meshes
    // ===========================================================================================

    /// A box with a distinct label on every face and a distinct standard deviation on every point,
    /// so a subset can be checked against exactly which elements survived.
    fn labeled_box() -> Result<Mesh3> {
        let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let stdev = (0..mesh.point_count()).map(|i| i as f64).collect();
        let flat = mesh
            .points()
            .iter()
            .map(|p| Point2::new(p.x, p.y))
            .collect();
        let labels = (0..mesh.face_count() as u32).collect();
        mesh.set_point_stdev(Some(stdev))?;
        mesh.set_point_flat(Some(flat))?;
        mesh.set_face_labels(Some(labels))?;
        Ok(mesh)
    }

    #[test]
    fn extract_subset_faces_carries_the_attributes() -> Result<()> {
        let mesh = labeled_box()?;
        let mask = IndexMask::try_from_indices(&[0, 1], mesh.face_count())?;

        let sub = mesh.extract_subset_faces(&mask)?;

        assert_eq!(sub.face_count(), 2);
        assert_eq!(sub.face_labels().unwrap(), &[0, 1]);

        // The attribute arrays have to match the counts of the mesh they ended up on.
        assert_eq!(sub.point_stdev().unwrap().len(), sub.point_count());
        sub.point_attrs().validate(sub.point_count())?;
        sub.face_attrs().validate(sub.face_count())?;

        // The surviving standard deviations are exactly those of the points the faces reference.
        let kept: Vec<f64> = mesh
            .compute_unique_point_mask(&mask)?
            .iter_true()
            .map(|i| mesh.point_stdev().unwrap()[i])
            .collect();
        assert_eq!(sub.point_stdev().unwrap(), kept.as_slice());

        // Flat coordinates travel with their points in the same way.
        let kept_flat: Vec<Point2> = mesh
            .compute_unique_point_mask(&mask)?
            .iter_true()
            .map(|i| mesh.point_flat().unwrap()[i])
            .collect();
        assert_eq!(sub.point_flat().unwrap(), kept_flat.as_slice());

        Ok(())
    }

    #[test]
    fn extract_subset_faces_from_indices_carries_the_attributes() -> Result<()> {
        let mesh = labeled_box()?;
        let sub = mesh.extract_subset_faces_from_indices(&[2, 3])?;

        assert_eq!(sub.face_count(), 2);
        assert_eq!(sub.face_labels().unwrap(), &[2, 3]);
        sub.point_attrs().validate(sub.point_count())?;
        sub.face_attrs().validate(sub.face_count())?;

        Ok(())
    }

    /// Routing through a mask makes the selection a set, so order does not matter and a repeat
    /// selects its face once rather than duplicating it.
    #[test]
    fn extract_subset_faces_from_indices_normalizes_the_selection() -> Result<()> {
        let mesh = labeled_box()?;

        let ordered = mesh.extract_subset_faces_from_indices(&[1, 3])?;
        let reversed = mesh.extract_subset_faces_from_indices(&[3, 1])?;
        let repeated = mesh.extract_subset_faces_from_indices(&[3, 1, 3])?;

        assert_eq!(ordered.faces(), reversed.faces());
        assert_eq!(ordered.faces(), repeated.faces());
        assert_eq!(ordered.face_labels().unwrap(), &[1, 3]);
        assert_eq!(repeated.face_count(), 2);

        Ok(())
    }

    #[test]
    fn extract_subset_faces_from_indices_rejects_an_out_of_range_index() -> Result<()> {
        let mesh = labeled_box()?;
        assert!(
            mesh.extract_subset_faces_from_indices(&[0, mesh.face_count()])
                .is_err()
        );
        Ok(())
    }

    /// The split re-triangulates and introduces new points, with no mapping back, so it has to
    /// refuse rather than silently drop what it cannot carry.
    #[test]
    fn split_refuses_an_attributed_mesh_unless_the_loss_is_accepted() -> Result<()> {
        let mesh = labeled_box()?;
        let plane = Plane3::yz();

        assert!(mesh.split(&plane, false).is_err());

        // The message has to name what would be lost.
        let message = match mesh.split(&plane, false) {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected the split to be refused"),
        };
        assert!(message.contains("point_stdev"), "{message}");
        assert!(message.contains("face_labels"), "{message}");

        // Accepting the loss lets it through, and the halves come back bare.
        match mesh.split(&plane, true)? {
            SplitResult::Pair(a, b) => {
                assert!(!a.has_attrs());
                assert!(!b.has_attrs());
            }
            _ => panic!("expected the plane to cut the box in two"),
        }

        // A bare mesh needs no flag at all.
        let bare = Mesh3::create_box(1.0, 1.0, 1.0, false);
        assert!(bare.split(&plane, false).is_ok());

        Ok(())
    }

    #[test]
    fn convex_hull_refuses_an_attributed_mesh_unless_the_loss_is_accepted() -> Result<()> {
        let mesh = labeled_box()?;

        assert!(mesh.convex_hull(false).is_err());
        assert!(!mesh.convex_hull(true)?.has_attrs());

        let bare = Mesh3::create_box(1.0, 1.0, 1.0, false);
        assert!(bare.convex_hull(false).is_ok());

        Ok(())
    }

    // ===========================================================================================
    // Scaling
    // ===========================================================================================

    /// The two containers have to agree on what a negative factor means, or the same mesh scaled
    /// through each would come back with opposite orientations.
    #[test]
    fn a_negative_scale_reverses_the_winding_like_mesh_data_does() -> Result<()> {
        let mesh = Mesh3::from_data(attributed_data(), false)?;

        let through_mesh = mesh.scale_copy(-1.0)?;
        let through_data = mesh.to_data().scale_copy(-1.0)?;

        assert_eq!(through_mesh.faces(), through_data.faces());
        assert_eq!(
            through_mesh.point_normals().unwrap(),
            through_data.point_normals().unwrap()
        );

        // Preserve both domains; the face domain has nothing to scale but must not be dropped.
        assert_eq!(through_mesh.face_attrs(), through_data.face_attrs());
        assert_eq!(through_mesh.face_labels().unwrap(), &[7]);
        assert_eq!(
            through_mesh.point_attr("confidence"),
            through_data.point_attr("confidence")
        );

        // The single triangle was wound +z, so mirroring must leave it wound -z.
        let p = through_mesh.points();
        let f = through_mesh.faces()[0];
        let normal = (p[f[1] as usize] - p[f[0] as usize])
            .cross(&(p[f[2] as usize] - p[f[0] as usize]))
            .normalize();
        assert_relative_eq!(normal, -Vector3::z(), epsilon = 1.0e-12);

        Ok(())
    }

    #[test]
    fn scale_copy_rejects_zero_and_non_finite_factors() -> Result<()> {
        let mesh = Mesh3::from_data(attributed_data(), false)?;

        assert!(mesh.scale_copy(0.0).is_err());
        assert!(mesh.scale_copy(f64::NAN).is_err());
        assert!(mesh.scale_copy(f64::INFINITY).is_err());

        Ok(())
    }

    // ===========================================================================================
    // Serialization
    // ===========================================================================================

    /// A file on disk, removed when the test finishes with it.
    struct TempFile {
        path: std::path::PathBuf,
    }

    impl TempFile {
        fn new(name: &str, ext: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "engeom-mesh3-{}-{}.{}",
                name,
                std::process::id(),
                ext
            ));
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TempFile {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.path);
        }
    }

    /// The whole point of routing through `MeshData3` is that the attributes survive, which the
    /// deleted shims did not do.
    #[cfg(feature = "ply")]
    #[test]
    fn a_ply_round_trip_keeps_the_attributes_and_the_solid_flag() -> Result<()> {
        let before = Mesh3::from_data(attributed_data(), false)?;
        let file = TempFile::new("round-trip", "ply");

        before.save_ply(file.path(), &PlyWriteOpts::default())?;
        let after = Mesh3::load_ply(file.path(), true)?;

        assert!(after.is_solid());
        assert_eq!(after.points(), before.points());
        assert_eq!(after.faces(), before.faces());
        assert_eq!(after.point_stdev(), before.point_stdev());
        assert_eq!(after.face_labels(), before.face_labels());
        assert_eq!(
            after.point_attr("confidence"),
            before.point_attr("confidence")
        );

        Ok(())
    }

    /// A PLY point cloud has no faces, so there is nothing to accelerate.
    #[cfg(feature = "ply")]
    #[test]
    fn loading_a_point_cloud_ply_as_a_mesh_is_refused() -> Result<()> {
        use crate::geom3::PointCloud3;

        let cloud = PointCloud3::new(vec![Point3::origin(), Point3::new(1.0, 0.0, 0.0)]);
        let file = TempFile::new("is-a-cloud", "ply");
        cloud.save_ply(file.path(), &PlyWriteOpts::default())?;

        assert!(Mesh3::load_ply(file.path(), false).is_err());

        Ok(())
    }

    #[cfg(feature = "stl")]
    #[test]
    fn an_stl_round_trip_carries_the_geometry() -> Result<()> {
        let before = Mesh3::create_box(1.0, 2.0, 3.0, false);
        let file = TempFile::new("round-trip", "stl");

        before.save_stl(file.path(), &StlWriteOpts::default())?;
        let after = Mesh3::load_stl(file.path(), false, true, false)?;

        assert_eq!(after.face_count(), before.face_count());
        assert_relative_eq!(after.aabb().maxs, before.aabb().maxs, epsilon = 1.0e-6);

        Ok(())
    }

    /// STL carries no attributes, so writing an attributed mesh has to be refused rather than
    /// silently stripping them.
    #[cfg(feature = "stl")]
    #[test]
    fn saving_stl_refuses_to_drop_attributes_silently() -> Result<()> {
        let mesh = Mesh3::from_data(attributed_data(), false)?;
        let file = TempFile::new("lossy", "stl");

        assert!(
            mesh.save_stl(file.path(), &StlWriteOpts::default())
                .is_err()
        );

        let opts = StlWriteOpts {
            allow_attribute_loss: true,
            ..Default::default()
        };
        mesh.save_stl(file.path(), &opts)?;

        Ok(())
    }

    // ===========================================================================================
    // Attribute setters
    // ===========================================================================================

    #[test]
    fn attribute_setters_supply_the_counts() -> Result<()> {
        let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let n_points = mesh.point_count();
        let n_faces = mesh.face_count();

        mesh.set_point_stdev(Some(vec![0.5; n_points]))?;
        mesh.set_face_labels(Some(vec![3; n_faces]))?;

        assert_eq!(mesh.point_stdev().unwrap().len(), n_points);
        assert_eq!(mesh.face_labels().unwrap().len(), n_faces);

        // The wrong length is rejected without the caller having to know the count.
        assert!(mesh.set_point_stdev(Some(vec![0.5; n_points + 1])).is_err());
        assert!(mesh.set_face_labels(Some(vec![3; n_faces - 1])).is_err());

        // The rejected calls must have left the existing attributes in place.
        assert_eq!(mesh.point_stdev().unwrap().len(), n_points);

        Ok(())
    }

    #[test]
    fn set_attrs_validates_against_the_current_counts() -> Result<()> {
        let mut mesh = Mesh3::from_data(attributed_data(), false)?;

        let mut bad = FaceAttrSet3::empty();
        bad.set_labels(Some(vec![1, 2, 3]), 3)?;
        assert!(mesh.set_face_attrs(bad).is_err());

        let mut bad = PointAttrSet3::empty();
        bad.set_stdev(Some(vec![0.1]), 1)?;
        assert!(mesh.set_point_attrs(bad).is_err());

        // The rejected sets must have left the existing attributes in place.
        assert_eq!(mesh.face_labels().unwrap(), &[7]);
        assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);

        let taken = mesh.take_face_attrs();
        assert_eq!(taken.labels().unwrap(), &[7]);
        assert!(mesh.face_labels().is_none());
        assert!(mesh.point_stdev().is_some());

        let taken = mesh.take_point_attrs();
        assert_eq!(taken.stdev().unwrap(), &[0.1, 0.2, 0.3]);
        assert!(!mesh.has_attrs());

        Ok(())
    }
}