cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
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
// SPDX-License-Identifier: Apache-2.0
//! Source tessellation retained alongside exact boundary representation.

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::assets::AssetId;
use crate::features::{FinitePoint3, FiniteVector3};
use crate::ids::{BodyId, FaceId};
use crate::math::{Point3, Vector3};
use crate::provenance::SourceObjectAssociation;
use crate::scalar::NonNegativeReal;

crate::ids::id_type!(
    /// Stable tessellation identity.
    TessellationId, compose, into_string
);

/// Admission error in a tessellation mesh or channel carrier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TessellationError {
    /// A mesh or channel value the carrier cannot admit. The carrier states
    /// this case; an outside caller states only [`Self::EditRefused`].
    #[non_exhaustive]
    Admission(String),
    /// An edit closure refused the value it was given, stating its own reason.
    EditRefused(String),
}

impl std::fmt::Display for TessellationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Admission(message) | Self::EditRefused(message) => formatter.write_str(message),
        }
    }
}

impl std::error::Error for TessellationError {}

fn tessellation_error(message: impl Into<String>) -> TessellationError {
    TessellationError::Admission(message.into())
}

/// One mesh vertex carrying its shading normal.
// A source states raw coordinates; a `Tessellation` holds the admitted row,
// whose position is a `FinitePoint3` and whose normal is a `FiniteVector3`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ShadedVertex<P = Point3, N = Vector3> {
    /// Vertex position in document units.
    pub position: P,
    /// Shading normal at this vertex.
    pub normal: N,
}

/// One triangle carrying a shading normal at each of its corners.
// A source states raw normals; a `Tessellation` holds the admitted row, whose
// normals are `FiniteVector3` values.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ShadedTriangle<N = Vector3> {
    /// Zero-based vertex indices, with source winding preserved.
    pub corners: [u32; 3],
    /// Shading normal at each corner, in corner order.
    pub normals: [N; 3],
}

/// One triangle strip: the vertices it spans, at least three of them.
///
/// A strip of one or two vertices spans no triangle, so it is not a strip at
/// all; the mint refuses it and [`Self::triangle_count`] subtracts without a
/// clamp on a length the type proved is at least three.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct Strip<V>(Vec<V>);

impl<V> Strip<V> {
    /// A strip over `vertices`, absent below three.
    #[must_use]
    pub fn new(vertices: Vec<V>) -> Option<Self> {
        (vertices.len() >= 3).then_some(Self(vertices))
    }

    /// The strip's vertices in strip order.
    #[must_use]
    pub fn vertices(&self) -> &[V] {
        &self.0
    }

    /// The strip's vertices in strip order, for editing in place.
    pub fn vertices_mut(&mut self) -> &mut [V] {
        &mut self.0
    }

    /// The triangles this strip expands to: two fewer than its vertices.
    #[must_use]
    pub fn triangle_count(&self) -> usize {
        self.0.len() - 2
    }
}

impl<'de, V: Deserialize<'de>> Deserialize<'de> for Strip<V> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(Vec::<V>::deserialize(deserializer)?)
            .ok_or_else(|| serde::de::Error::custom("tessellation strip spans no triangle"))
    }
}

/// One or more triangle strips.
///
/// The vector is private and never empty, so "the mesh is a flat triangle
/// list" has no second spelling inside a strip mesh. The mint also proves the
/// strips span no more vertices than a `u32` index can name, so expanding them
/// into triangles is total.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct Strips<V>(Vec<Strip<V>>);

impl<V> Strips<V> {
    /// The strips in mesh order, absent when there are none and absent when
    /// they span more vertices than a `u32` index can name.
    #[must_use]
    pub fn new(strips: Vec<Strip<V>>) -> Option<Self> {
        if strips.is_empty() {
            return None;
        }
        let span = strips.iter().try_fold(0u64, |total, strip| {
            total.checked_add(cadmpeg_core::decode::u64_from_index(strip.vertices().len()))
        })?;
        u32::try_from(span).is_ok().then_some(Self(strips))
    }

    /// The strips in mesh order.
    #[must_use]
    pub fn as_slice(&self) -> &[Strip<V>] {
        &self.0
    }

    /// Every strip vertex in mesh order, for editing in place.
    ///
    /// The narrow write route: a caller reaches the vertices and never a
    /// strip, so the vertex span the mint proved a `u32` index can name
    /// stays the span the strips hold.
    pub fn vertices_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.0.iter_mut().flat_map(Strip::vertices_mut)
    }

    /// Map every vertex in strip order, keeping each strip's vertex count.
    ///
    /// Every strip keeps the count the mint proved, so the mapped strips
    /// satisfy the same proof without a second check.
    fn try_map<W, E>(self, mut map: impl FnMut(V) -> Result<W, E>) -> Result<Strips<W>, E> {
        self.0
            .into_iter()
            .map(|strip| {
                strip
                    .0
                    .into_iter()
                    .map(&mut map)
                    .collect::<Result<Vec<_>, E>>()
                    .map(Strip)
            })
            .collect::<Result<Vec<_>, E>>()
            .map(Strips)
    }
}

impl<V> Strips<V> {
    /// Cut a flat vertex lane into the strips `spans` names.
    ///
    /// A source that states its strip spans beside one vertex array pairs the
    /// two here, once, at the decode boundary: the result is absent when a
    /// span the lane cannot fill, a span below three, or a vertex the spans do
    /// not consume.
    #[must_use]
    pub fn from_spans(vertices: Vec<V>, spans: &[u32]) -> Option<Self> {
        let mut remaining = vertices.into_iter();
        let mut strips = Vec::new();
        for span in spans {
            let span = usize::try_from(*span).ok()?;
            let run: Vec<V> = remaining.by_ref().take(span).collect();
            if run.len() != span {
                return None;
            }
            strips.push(Strip::new(run)?);
        }
        if remaining.next().is_some() {
            return None;
        }
        Self::new(strips)
    }
}

impl<'de, V: Deserialize<'de>> Deserialize<'de> for Strips<V> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(Vec::<Strip<V>>::deserialize(deserializer)?)
            .ok_or_else(|| serde::de::Error::custom("tessellation strip set is empty"))
    }
}

/// The mesh's vertices, triangles and shading normals.
///
/// The shading form is the wire's tag, so a mesh states per-vertex or
/// per-corner normals and never both, and never a normal run that does not
/// cover the mesh. A strip owns the vertices it spans, so a strip mesh states
/// neither a triangle list nor a vertex total: both are derived.
// A source states raw positions and normals. A `Tessellation` holds the
// admitted mesh, whose positions are `FinitePoint3` values and whose normals
// are `FiniteVector3` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum TessellationMesh<P = Point3, N = Vector3> {
    /// Independent triangle list carrying no shading normals.
    List {
        /// Vertex positions in document units.
        vertices: Vec<P>,
        /// Zero-based vertex indices, with source winding preserved.
        triangles: Vec<[u32; 3]>,
    },
    /// Independent triangle list with one shading normal per vertex.
    ShadedList {
        /// Vertex rows, each carrying its shading normal.
        vertices: Vec<ShadedVertex<P, N>>,
        /// Zero-based vertex indices, with source winding preserved.
        triangles: Vec<[u32; 3]>,
    },
    /// Independent triangle list with one shading normal per triangle corner.
    CornerShadedList {
        /// Vertex positions in document units.
        vertices: Vec<P>,
        /// Triangle rows, each carrying its three corner normals.
        triangles: Vec<ShadedTriangle<N>>,
    },
    /// Triangle strips carrying no shading normals.
    Strips {
        /// Strips in mesh order; each spans the vertices it owns.
        strips: Strips<P>,
    },
    /// Triangle strips with one shading normal per vertex.
    ShadedStrips {
        /// Strips in mesh order; each spans the vertex rows it owns.
        strips: Strips<ShadedVertex<P, N>>,
    },
}

/// Expand strip runs into triangles in strip order.
///
/// [`Strips::new`] proves the strips span no more vertices than a `u32` index
/// can name, so every index below is in range and the expansion is total.
fn strip_triangles<V>(strips: &Strips<V>) -> Vec<[u32; 3]> {
    let mut triangles = Vec::new();
    let mut base: u32 = 0;
    for strip in strips.as_slice() {
        // The walk counts in the `u32` the proof is stated in, so no in-memory
        // count is narrowed here. A strip holds two more vertices than it has
        // triangles, so `index` ends at the strip's vertex count less two.
        let mut index: u32 = 0;
        for _ in 0..strip.triangle_count() {
            let a = base + index;
            triangles.push(if index.is_multiple_of(2) {
                [a, a + 1, a + 2]
            } else {
                [a, a + 2, a + 1]
            });
            index += 1;
        }
        base += index + 2;
    }
    triangles
}

/// A source's tessellation lanes do not pair.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TessellationLaneError {
    /// A stated per-vertex normal lane does not cover the vertex lane.
    #[error("{vertices} vertex/vertices against {normals} vertex normal(s)")]
    VertexNormalLane {
        /// Vertices the source stated.
        vertices: usize,
        /// Normals the source stated.
        normals: usize,
    },
    /// A stated per-corner normal lane does not cover the triangle corners.
    #[error("{corners} triangle corner(s) against {normals} corner normal(s)")]
    CornerNormalLane {
        /// Triangle corners the source stated: three per triangle.
        corners: usize,
        /// Normals the source stated.
        normals: usize,
    },
    /// The triangle count has no corner count: three times it overflows.
    #[error("{triangles} triangle(s) name more corners than an index can count")]
    CornerCountOverflow {
        /// Triangles the source stated.
        triangles: usize,
    },
    /// The stated strip spans do not cut the vertex lane into strips.
    ///
    /// A span below three spans no triangle, a span the lane cannot fill, a
    /// vertex the spans do not consume, an empty span list, and a strip set
    /// spanning more vertices than a `u32` index can name are all refused here.
    #[error("{spans} strip span(s) do not cut the vertex lane")]
    Strips {
        /// Spans the source stated.
        spans: usize,
    },
}

impl From<TessellationLaneError> for cadmpeg_core::CodecError {
    fn from(error: TessellationLaneError) -> Self {
        Self::Malformed(error.to_string())
    }
}

impl TessellationMesh {
    /// Pair a source's flat strip lanes into mesh rows.
    ///
    /// A display stream that states strip spans, vertex positions and vertex
    /// normals as separate lanes pairs them here. An unshaded mesh is stated by
    /// absence — `None` — not by an empty lane: a stated lane covers the
    /// vertices exactly, and `Some(vec![])` against a non-empty vertex lane is
    /// a length mismatch.
    ///
    /// # Errors
    ///
    /// Refuses a normal lane whose length differs from the vertex lane, naming
    /// both counts, and a strip set the spans cannot cut.
    pub fn from_strip_lanes(
        positions: Vec<Point3>,
        normals: Option<Vec<Vector3>>,
        spans: &[u32],
    ) -> Result<Self, TessellationLaneError> {
        let Some(normals) = normals else {
            let strips = Strips::from_spans(positions, spans)
                .ok_or(TessellationLaneError::Strips { spans: spans.len() })?;
            return Ok(Self::Strips { strips });
        };
        if normals.len() != positions.len() {
            return Err(TessellationLaneError::VertexNormalLane {
                vertices: positions.len(),
                normals: normals.len(),
            });
        }
        let rows = positions
            .into_iter()
            .zip(normals)
            .map(|(position, normal)| ShadedVertex { position, normal })
            .collect();
        let strips = Strips::from_spans(rows, spans)
            .ok_or(TessellationLaneError::Strips { spans: spans.len() })?;
        Ok(Self::ShadedStrips { strips })
    }

    /// Pair a source's flat triangle-list lanes into mesh rows.
    ///
    /// An unshaded mesh is stated by absence — `None` — not by an empty lane.
    ///
    /// # Errors
    ///
    /// Refuses a normal lane whose length differs from the vertex lane, naming
    /// both counts.
    pub fn from_list_lanes(
        positions: Vec<Point3>,
        triangles: Vec<[u32; 3]>,
        normals: Option<Vec<Vector3>>,
    ) -> Result<Self, TessellationLaneError> {
        Self::pair_list_lanes(positions, triangles, normals)
    }
}

impl<P, N> TessellationMesh<P, N> {
    fn pair_list_lanes(
        positions: Vec<P>,
        triangles: Vec<[u32; 3]>,
        normals: Option<Vec<N>>,
    ) -> Result<Self, TessellationLaneError> {
        let Some(normals) = normals else {
            return Ok(Self::List {
                vertices: positions,
                triangles,
            });
        };
        if normals.len() != positions.len() {
            return Err(TessellationLaneError::VertexNormalLane {
                vertices: positions.len(),
                normals: normals.len(),
            });
        }
        Ok(Self::ShadedList {
            vertices: positions
                .into_iter()
                .zip(normals)
                .map(|(position, normal)| ShadedVertex { position, normal })
                .collect(),
            triangles,
        })
    }
}

impl<P: Copy, N: Copy> TessellationMesh<P, N> {
    /// Vertex positions in mesh order.
    #[must_use]
    pub fn vertices(&self) -> Vec<P> {
        match self {
            Self::List { vertices, .. } | Self::CornerShadedList { vertices, .. } => {
                vertices.clone()
            }
            Self::ShadedList { vertices, .. } => {
                vertices.iter().map(|vertex| vertex.position).collect()
            }
            Self::Strips { strips } => strips
                .as_slice()
                .iter()
                .flat_map(|strip| strip.vertices().iter().copied())
                .collect(),
            Self::ShadedStrips { strips } => strips
                .as_slice()
                .iter()
                .flat_map(|strip| strip.vertices().iter().map(|vertex| vertex.position))
                .collect(),
        }
    }

    /// Number of vertices in the mesh.
    #[must_use]
    pub fn vertex_count(&self) -> usize {
        match self {
            Self::List { vertices, .. } | Self::CornerShadedList { vertices, .. } => vertices.len(),
            Self::ShadedList { vertices, .. } => vertices.len(),
            Self::Strips { strips } => strips
                .as_slice()
                .iter()
                .map(|strip| strip.vertices().len())
                .sum(),
            Self::ShadedStrips { strips } => strips
                .as_slice()
                .iter()
                .map(|strip| strip.vertices().len())
                .sum(),
        }
    }

    /// Zero-based triangle corner indices, with source winding preserved.
    ///
    /// A strip mesh derives its triangles from the strips it owns.
    #[must_use]
    pub fn triangles(&self) -> Vec<[u32; 3]> {
        match self {
            Self::List { triangles, .. } | Self::ShadedList { triangles, .. } => triangles.clone(),
            Self::CornerShadedList { triangles, .. } => {
                triangles.iter().map(|triangle| triangle.corners).collect()
            }
            Self::Strips { strips } => strip_triangles(strips),
            Self::ShadedStrips { strips } => strip_triangles(strips),
        }
    }

    /// Number of triangles in the mesh.
    #[must_use]
    pub fn triangle_count(&self) -> usize {
        match self {
            Self::List { triangles, .. } | Self::ShadedList { triangles, .. } => triangles.len(),
            Self::CornerShadedList { triangles, .. } => triangles.len(),
            Self::Strips { strips } => strips.as_slice().iter().map(Strip::triangle_count).sum(),
            Self::ShadedStrips { strips } => {
                strips.as_slice().iter().map(Strip::triangle_count).sum()
            }
        }
    }

    /// Per-vertex shading normals; empty when the mesh carries none.
    #[must_use]
    pub fn vertex_normals(&self) -> Vec<N> {
        match self {
            Self::List { .. } | Self::CornerShadedList { .. } | Self::Strips { .. } => Vec::new(),
            Self::ShadedList { vertices, .. } => {
                vertices.iter().map(|vertex| vertex.normal).collect()
            }
            Self::ShadedStrips { strips } => strips
                .as_slice()
                .iter()
                .flat_map(|strip| strip.vertices().iter().map(|vertex| vertex.normal))
                .collect(),
        }
    }

    /// Per-corner shading normals in flattened triangle order; empty when the
    /// mesh carries none.
    #[must_use]
    pub fn corner_normals(&self) -> Vec<N> {
        match self {
            Self::List { .. }
            | Self::ShadedList { .. }
            | Self::Strips { .. }
            | Self::ShadedStrips { .. } => Vec::new(),
            Self::CornerShadedList { triangles, .. } => triangles
                .iter()
                .flat_map(|triangle| triangle.normals)
                .collect(),
        }
    }

    /// Strip spans in mesh order; empty when the mesh is a triangle list.
    #[must_use]
    pub fn strip_lengths(&self) -> Vec<u32> {
        let spans = |lengths: Vec<usize>| {
            lengths
                .into_iter()
                .filter_map(|length| u32::try_from(length).ok())
                .collect()
        };
        match self {
            Self::List { .. } | Self::ShadedList { .. } | Self::CornerShadedList { .. } => {
                Vec::new()
            }
            Self::Strips { strips } => spans(
                strips
                    .as_slice()
                    .iter()
                    .map(|strip| strip.vertices().len())
                    .collect(),
            ),
            Self::ShadedStrips { strips } => spans(
                strips
                    .as_slice()
                    .iter()
                    .map(|strip| strip.vertices().len())
                    .collect(),
            ),
        }
    }

    /// Edit every vertex position in place, keeping every accepted edit.
    ///
    /// A refusal leaves the mesh partly edited, so the caller owns the copy
    /// that states the prior positions.
    fn apply_positions(
        &mut self,
        mut edit: impl FnMut(&mut P) -> Result<(), TessellationError>,
    ) -> Result<(), TessellationError> {
        match self {
            Self::List { vertices, .. } | Self::CornerShadedList { vertices, .. } => {
                for vertex in vertices.iter_mut() {
                    edit(vertex)?;
                }
            }
            Self::ShadedList { vertices, .. } => {
                for vertex in vertices.iter_mut() {
                    edit(&mut vertex.position)?;
                }
            }
            Self::Strips { strips } => {
                for vertex in strips.vertices_mut() {
                    edit(vertex)?;
                }
            }
            Self::ShadedStrips { strips } => {
                for vertex in strips.vertices_mut() {
                    edit(&mut vertex.position)?;
                }
            }
        }
        Ok(())
    }

    /// Edit every shading normal in place, keeping every accepted edit.
    ///
    /// A refusal leaves the mesh partly edited, so the caller owns the copy
    /// that states the prior normals.
    fn apply_normals(
        &mut self,
        mut edit: impl FnMut(&mut N) -> Result<(), TessellationError>,
    ) -> Result<bool, TessellationError> {
        match self {
            Self::List { .. } | Self::Strips { .. } => return Ok(false),
            Self::ShadedList { vertices, .. } => {
                for vertex in vertices.iter_mut() {
                    edit(&mut vertex.normal)?;
                }
            }
            Self::CornerShadedList { triangles, .. } => {
                for triangle in triangles.iter_mut() {
                    for normal in &mut triangle.normals {
                        edit(normal)?;
                    }
                }
            }
            Self::ShadedStrips { strips } => {
                for vertex in strips.vertices_mut() {
                    edit(&mut vertex.normal)?;
                }
            }
        }
        Ok(true)
    }
}

impl<P, N> TessellationMesh<P, N> {
    /// Pair flat triangle corners and their optional normal lane into rows.
    ///
    /// The lane's values keep their admitted type. Absence means unshaded;
    /// a present lane has exactly three normals per triangle.
    pub fn from_corner_lanes(
        positions: Vec<P>,
        triangles: Vec<[u32; 3]>,
        corner_normals: Option<Vec<N>>,
    ) -> Result<Self, TessellationLaneError> {
        let Some(corner_normals) = corner_normals else {
            return Ok(Self::List {
                vertices: positions,
                triangles,
            });
        };
        let Some(corner_count) = triangles.len().checked_mul(3) else {
            return Err(TessellationLaneError::CornerCountOverflow {
                triangles: triangles.len(),
            });
        };
        if corner_normals.len() != corner_count {
            return Err(TessellationLaneError::CornerNormalLane {
                corners: corner_count,
                normals: corner_normals.len(),
            });
        }
        let mut normals = corner_normals.into_iter();
        let rows = triangles
            .into_iter()
            .map(|corners| {
                let triple: Vec<N> = normals.by_ref().take(3).collect();
                let normals = <[N; 3]>::try_from(triple).map_err(|short: Vec<_>| {
                    TessellationLaneError::CornerNormalLane {
                        corners: corner_count,
                        normals: short.len(),
                    }
                })?;
                Ok(ShadedTriangle { corners, normals })
            })
            .collect::<Result<Vec<_>, TessellationLaneError>>()?;
        Ok(Self::CornerShadedList {
            vertices: positions,
            triangles: rows,
        })
    }

    /// Map every vertex position in mesh order, keeping the triangles, the
    /// strip spans and the normals.
    fn try_map_points<Q, E>(
        self,
        mut point: impl FnMut(P) -> Result<Q, E>,
    ) -> Result<TessellationMesh<Q, N>, E> {
        Ok(match self {
            Self::List {
                vertices,
                triangles,
            } => TessellationMesh::List {
                vertices: vertices.into_iter().map(point).collect::<Result<_, E>>()?,
                triangles,
            },
            Self::ShadedList {
                vertices,
                triangles,
            } => TessellationMesh::ShadedList {
                vertices: vertices
                    .into_iter()
                    .map(|vertex| {
                        Ok(ShadedVertex {
                            position: point(vertex.position)?,
                            normal: vertex.normal,
                        })
                    })
                    .collect::<Result<_, E>>()?,
                triangles,
            },
            Self::CornerShadedList {
                vertices,
                triangles,
            } => TessellationMesh::CornerShadedList {
                vertices: vertices.into_iter().map(point).collect::<Result<_, E>>()?,
                triangles,
            },
            Self::Strips { strips } => TessellationMesh::Strips {
                strips: strips.try_map(point)?,
            },
            Self::ShadedStrips { strips } => TessellationMesh::ShadedStrips {
                strips: strips.try_map(|vertex| {
                    Ok(ShadedVertex {
                        position: point(vertex.position)?,
                        normal: vertex.normal,
                    })
                })?,
            },
        })
    }

    /// Map every shading normal in mesh order, keeping the positions, the
    /// triangles and the strip spans.
    fn try_map_normals<M, E>(
        self,
        mut normal: impl FnMut(N) -> Result<M, E>,
    ) -> Result<TessellationMesh<P, M>, E> {
        Ok(match self {
            Self::List {
                vertices,
                triangles,
            } => TessellationMesh::List {
                vertices,
                triangles,
            },
            Self::ShadedList {
                vertices,
                triangles,
            } => TessellationMesh::ShadedList {
                vertices: vertices
                    .into_iter()
                    .map(|vertex| {
                        Ok(ShadedVertex {
                            position: vertex.position,
                            normal: normal(vertex.normal)?,
                        })
                    })
                    .collect::<Result<_, E>>()?,
                triangles,
            },
            Self::CornerShadedList {
                vertices,
                triangles,
            } => TessellationMesh::CornerShadedList {
                vertices,
                triangles: triangles
                    .into_iter()
                    .map(|triangle| {
                        let [first, second, third] = triangle.normals;
                        Ok(ShadedTriangle {
                            corners: triangle.corners,
                            normals: [normal(first)?, normal(second)?, normal(third)?],
                        })
                    })
                    .collect::<Result<_, E>>()?,
            },
            Self::Strips { strips } => TessellationMesh::Strips { strips },
            Self::ShadedStrips { strips } => TessellationMesh::ShadedStrips {
                strips: strips.try_map(|vertex| {
                    Ok(ShadedVertex {
                        position: vertex.position,
                        normal: normal(vertex.normal)?,
                    })
                })?,
            },
        })
    }
}

impl TessellationMesh<FinitePoint3, FiniteVector3> {
    /// Pair admitted triangle-list positions and normals without checking
    /// their scalar values again.
    pub fn from_checked_list_lanes(
        positions: Vec<FinitePoint3>,
        triangles: Vec<[u32; 3]>,
        normals: Option<Vec<FiniteVector3>>,
    ) -> Result<Self, TessellationLaneError> {
        Self::pair_list_lanes(positions, triangles, normals)
    }
    /// The mesh with raw positions and normals, for a reader that edits or
    /// writes them.
    #[must_use]
    pub fn into_raw(self) -> TessellationMesh {
        let Ok(positions) =
            self.try_map_points(|point| Ok::<_, std::convert::Infallible>(point.get()));
        let Ok(raw) =
            positions.try_map_normals(|normal| Ok::<_, std::convert::Infallible>(normal.get()));
        raw
    }
}

/// Admit one mesh position whose every coordinate is finite.
fn admit_vertex(point: Point3) -> Result<FinitePoint3, TessellationError> {
    FinitePoint3::new(point)
        .ok_or_else(|| tessellation_error("vertices contain a non-finite coordinate"))
}

/// Admit one shading normal whose every component is finite.
fn admit_normal(normal: Vector3) -> Result<FiniteVector3, TessellationError> {
    FiniteVector3::new(normal)
        .ok_or_else(|| tessellation_error("normals contain a non-finite coordinate"))
}

/// Index table that addresses a tessellation channel payload.
///
/// The domain is the wire's tag, so the selector table exists only on the two
/// domains that address one: vertex-order addressing has no `indices` key to
/// leave empty and none to refuse.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "domain", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ChannelAddressing {
    /// Vertex-order addressing with no explicit index table.
    Vertex {},
    /// One selector per triangle corner.
    Corner {
        /// One selector per triangle corner.
        indices: Vec<u32>,
    },
    /// One selector per triangle.
    Triangle {
        /// One selector per triangle.
        indices: Vec<u32>,
    },
}

impl ChannelAddressing {
    /// Explicit selectors, empty for vertex-order addressing.
    #[must_use]
    pub fn indices(&self) -> &[u32] {
        match self {
            Self::Vertex {} => &[],
            Self::Corner { indices } | Self::Triangle { indices } => indices,
        }
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TessellationWire {
    /// Stable source-derived identifier.
    id: TessellationId,
    /// Body represented by this mesh, when known.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_body"
    )]
    body: Option<BodyId>,
    /// Faces represented by this mesh, empty when face-level ownership is unknown.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    faces: Vec<FaceId>,
    /// Source chordal deflection tolerance, when carried.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_chordal_deflection"
    )]
    chordal_deflection: Option<f64>,
    /// Native source-object identity and effective display metadata.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_object"
    )]
    source_object: Option<SourceObjectAssociation>,
    /// The mesh's vertices, triangles and shading normals.
    mesh: TessellationMesh,
    /// Undirected geometric feature edges.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    feature_edges: Vec<[u32; 2]>,
    /// Source face or region groups as an ordered partition of the triangle ordinals.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    triangle_groups: Vec<TessellationTriangleGroup>,
    /// Source texture resources assigned to disjoint sets of triangle ordinals.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    texture_assignments: Vec<TessellationTextureAssignment>,
    /// Additional per-vertex or per-facet data channels.
    #[serde(default)]
    channels: Vec<TessellationChannel>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TessellationChannelWire {
    /// Mesh element addressed by this channel.
    addressing: ChannelAddressing,
    /// Byte size of one element of `data`.
    item_size: u32,
    /// Source channel-kind tag.
    kind: u32,
    /// Source per-channel flag word.
    flags: u32,
    /// Raw channel payload.
    #[serde(with = "crate::bytes")]
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    data: Vec<u8>,
}

/// One indexed triangle mesh decoded from a source display or facet stream.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(try_from = "TessellationWire", into = "TessellationWire")]
pub struct Tessellation {
    /// Stable source-derived identifier.
    pub id: TessellationId,
    /// Body represented by this mesh, when known.
    pub body: Option<BodyId>,
    /// Faces represented by this mesh, empty when face-level ownership is unknown.
    pub faces: Vec<FaceId>,
    /// Source chordal deflection tolerance, when carried.
    chordal_deflection: Option<NonNegativeReal>,
    /// Native source-object identity and effective display metadata.
    pub source_object: Option<SourceObjectAssociation>,
    mesh: TessellationMesh<FinitePoint3, FiniteVector3>,
    /// Undirected geometric feature edges.
    feature_edges: Vec<[u32; 2]>,
    /// Source face or region groups as an ordered partition of the triangle ordinals.
    triangle_groups: Vec<TessellationTriangleGroup>,
    /// Source texture resources assigned to disjoint sets of triangle ordinals.
    texture_assignments: Vec<TessellationTextureAssignment>,
    channels: Vec<TessellationChannel>,
}

/// One source-defined group in a tessellation triangle partition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TessellationTriangleGroup {
    /// Source group identity, when the source stores one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_id"
    )]
    pub source_id: Option<String>,
    /// Strictly increasing triangle ordinals belonging to this group.
    pub triangles: Vec<u32>,
}

/// One source texture resource assigned directly to tessellation triangles.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TessellationTextureAssignment {
    /// Source texture-resource identity, when the source stores one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_id"
    )]
    pub source_id: Option<String>,
    /// Assigned texture asset.
    pub texture: AssetId,
    /// Strictly increasing triangle ordinals receiving the texture.
    pub triangles: Vec<u32>,
}

/// One descriptor from the source tessellation table.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(try_from = "TessellationChannelWire", into = "TessellationChannelWire")]
pub struct TessellationChannel {
    addressing: ChannelAddressing,
    item_size: u32,
    kind: u32,
    flags: u32,
    data: Vec<u8>,
    /// Element count, computed and bounded at construction. The channel is
    /// immutable once built, so this is the count [`Self::data`] holds.
    count: u32,
}

fn require_triangle_indices(
    vertex_count: usize,
    triangles: &[[u32; 3]],
) -> Result<(), TessellationError> {
    if triangles
        .iter()
        .flatten()
        .any(|index| cadmpeg_core::decode::index_from_u32(*index) >= vertex_count)
    {
        return Err(tessellation_error(
            "contains an out-of-range tessellation index",
        ));
    }
    Ok(())
}

fn require_channel_indices(
    triangle_count: usize,
    channels: &[TessellationChannel],
) -> Result<(), TessellationError> {
    let corner_count = triangle_count
        .checked_mul(3)
        .ok_or_else(|| tessellation_error("tessellation corner count overflows usize"))?;
    for channel in channels {
        let expected = match channel.addressing() {
            ChannelAddressing::Vertex {} => 0,
            ChannelAddressing::Corner { .. } => corner_count,
            ChannelAddressing::Triangle { .. } => triangle_count,
        };
        if channel.indices().len() != expected
            || channel
                .indices()
                .iter()
                .any(|index| *index >= channel.count())
        {
            return Err(tessellation_error(
                "contains invalid tessellation channel indices",
            ));
        }
    }
    Ok(())
}

fn require_feature_edges(
    vertex_count: usize,
    feature_edges: &[[u32; 2]],
) -> Result<(), TessellationError> {
    if feature_edges.iter().any(|edge| {
        edge[0] >= edge[1] || usize::try_from(edge[1]).map_or(true, |index| index >= vertex_count)
    }) || feature_edges.windows(2).any(|edges| edges[0] >= edges[1])
    {
        return Err(tessellation_error(
            "contains an invalid tessellation feature edge",
        ));
    }
    Ok(())
}

fn require_triangle_groups(
    triangle_count: usize,
    triangle_groups: &[TessellationTriangleGroup],
) -> Result<(), TessellationError> {
    if triangle_groups.is_empty() {
        return Ok(());
    }
    let mut memberships = std::iter::repeat_with(|| false)
        .take(triangle_count)
        .collect::<Vec<_>>();
    let mut source_ids = std::collections::BTreeSet::new();
    let valid = triangle_groups.iter().all(|group| {
        !group.triangles.is_empty()
            && group
                .triangles
                .windows(2)
                .all(|ordinals| ordinals[0] < ordinals[1])
            && group.triangles.iter().all(|ordinal| {
                usize::try_from(*ordinal)
                    .ok()
                    .and_then(|ordinal| memberships.get_mut(ordinal))
                    .is_some_and(|visited| {
                        if *visited {
                            return false;
                        }
                        *visited = true;
                        true
                    })
            })
            && group.source_id.as_ref().is_none_or(|source_id| {
                !source_id.is_empty() && source_ids.insert(source_id.as_str())
            })
    }) && memberships.iter().all(|visited| *visited);
    if !valid {
        return Err(tessellation_error(
            "contains an invalid tessellation triangle-group partition",
        ));
    }
    Ok(())
}

fn require_texture_assignments(
    triangle_count: usize,
    texture_assignments: &[TessellationTextureAssignment],
) -> Result<(), TessellationError> {
    if texture_assignments.is_empty() {
        return Ok(());
    }
    let mut memberships = std::iter::repeat_with(|| false)
        .take(triangle_count)
        .collect::<Vec<_>>();
    let mut source_ids = std::collections::BTreeSet::new();
    let mut anonymous_textures = std::collections::BTreeSet::new();
    let valid = texture_assignments.iter().all(|assignment| {
        !assignment.triangles.is_empty()
            && match assignment.source_id.as_deref() {
                Some(source_id) => !source_id.is_empty() && source_ids.insert(source_id),
                None => anonymous_textures.insert(&assignment.texture),
            }
            && assignment
                .triangles
                .windows(2)
                .all(|ordinals| ordinals[0] < ordinals[1])
            && assignment.triangles.iter().all(|ordinal| {
                usize::try_from(*ordinal)
                    .ok()
                    .and_then(|ordinal| memberships.get_mut(ordinal))
                    .is_some_and(|visited| {
                        if *visited {
                            return false;
                        }
                        *visited = true;
                        true
                    })
            })
    });
    if !valid {
        return Err(tessellation_error(
            "contains invalid tessellation texture assignments",
        ));
    }
    Ok(())
}

impl Tessellation {
    /// Build a tessellation from its mesh rows and channels.
    pub fn new(
        id: TessellationId,
        mesh: TessellationMesh,
        channels: Vec<TessellationChannel>,
    ) -> Result<Self, TessellationError> {
        let mesh = mesh
            .try_map_points(admit_vertex)?
            .try_map_normals(admit_normal)?;
        Self::from_parts(id, mesh, channels)
    }

    /// Build from admitted positions and normals; check only relationships.
    pub fn from_parts(
        id: TessellationId,
        mesh: TessellationMesh<FinitePoint3, FiniteVector3>,
        channels: Vec<TessellationChannel>,
    ) -> Result<Self, TessellationError> {
        let triangle_count = match &mesh {
            TessellationMesh::Strips { .. } | TessellationMesh::ShadedStrips { .. } => {
                // Strips::new proved the total vertex span fits a u32 index,
                // and Strip::new proved each row has at least three vertices.
                mesh.triangle_count()
            }
            _ => {
                let triangles = mesh.triangles();
                require_triangle_indices(mesh.vertex_count(), &triangles)?;
                triangles.len()
            }
        };
        require_channel_indices(triangle_count, &channels)?;
        Ok(Self {
            id,
            body: None,
            faces: Vec::new(),
            chordal_deflection: None,
            source_object: None,
            mesh,
            feature_edges: Vec::new(),
            triangle_groups: Vec::new(),
            texture_assignments: Vec::new(),
            channels,
        })
    }

    /// Replace the mesh and its channels, keeping the identity, the owners,
    /// the chordal deflection and the source association. The mesh holds
    /// admitted positions and normals, so only the indices, the channels, the
    /// feature edges, the triangle groups and the texture assignments are
    /// checked against it.
    pub fn with_mesh(
        self,
        mesh: TessellationMesh<FinitePoint3, FiniteVector3>,
        channels: Vec<TessellationChannel>,
    ) -> Result<Self, TessellationError> {
        let triangles = mesh.triangles();
        require_triangle_indices(mesh.vertex_count(), &triangles)?;
        require_channel_indices(triangles.len(), &channels)?;
        require_feature_edges(mesh.vertex_count(), &self.feature_edges)?;
        require_triangle_groups(triangles.len(), &self.triangle_groups)?;
        require_texture_assignments(triangles.len(), &self.texture_assignments)?;
        Ok(Self {
            mesh,
            channels,
            ..self
        })
    }

    /// The mesh's vertices, triangles and shading normals.
    #[must_use]
    pub const fn mesh(&self) -> &TessellationMesh<FinitePoint3, FiniteVector3> {
        &self.mesh
    }

    /// Vertex positions in document units.
    #[must_use]
    pub fn vertices(&self) -> Vec<FinitePoint3> {
        self.mesh.vertices()
    }

    /// Number of vertices in the mesh.
    #[must_use]
    pub fn vertex_count(&self) -> usize {
        self.mesh.vertex_count()
    }

    /// Atomically edit vertex positions while preserving finite coordinates.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    pub fn edit_vertices(
        &mut self,
        edit: impl FnMut(&mut Point3) -> Result<(), TessellationError>,
    ) -> Result<(), TessellationError> {
        let Ok(mut mesh) = self
            .mesh
            .clone()
            .try_map_points(|point| Ok::<_, std::convert::Infallible>(point.get()));
        mesh.apply_positions(edit)?;
        self.mesh = mesh.try_map_points(admit_vertex)?;
        Ok(())
    }

    /// Zero-based vertex indices, with source winding preserved.
    ///
    /// A strip mesh derives its triangles from the strips it owns.
    #[must_use]
    pub fn triangles(&self) -> Vec<[u32; 3]> {
        self.mesh.triangles()
    }

    /// Number of triangles in the mesh.
    #[must_use]
    pub fn triangle_count(&self) -> usize {
        self.mesh.triangle_count()
    }

    /// Strip spans in mesh order; empty when the mesh is a flat triangle list.
    #[must_use]
    pub fn strip_lengths(&self) -> Vec<u32> {
        self.mesh.strip_lengths()
    }

    /// Per-vertex normals; empty when the source carried none or corner normals.
    #[must_use]
    pub fn vertex_normals(&self) -> Vec<FiniteVector3> {
        self.mesh.vertex_normals()
    }

    /// Atomically edit the stored shading normals while preserving finite coordinates.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    pub fn edit_normals(
        &mut self,
        edit: impl FnMut(&mut Vector3) -> Result<(), TessellationError>,
    ) -> Result<(), TessellationError> {
        let Ok(mut mesh) = self
            .mesh
            .clone()
            .try_map_normals(|normal| Ok::<_, std::convert::Infallible>(normal.get()));
        if !mesh.apply_normals(edit)? {
            return Err(tessellation_error("mesh has no shading normals to edit"));
        }
        self.mesh = mesh.try_map_normals(admit_normal)?;
        Ok(())
    }

    /// Per-triangle-corner normals; empty when the source carried none or vertex normals.
    #[must_use]
    pub fn per_corner_normals(&self) -> Vec<FiniteVector3> {
        self.mesh.corner_normals()
    }

    /// Additional per-vertex or per-facet data channels.
    #[must_use]
    pub fn channels(&self) -> &[TessellationChannel] {
        &self.channels
    }

    /// Undirected geometric feature edges in source order.
    #[must_use]
    pub fn feature_edges(&self) -> &[[u32; 2]] {
        &self.feature_edges
    }

    /// Source face or region groups in triangle-order partition order.
    #[must_use]
    pub fn triangle_groups(&self) -> &[TessellationTriangleGroup] {
        &self.triangle_groups
    }

    /// Source texture resources assigned to triangle ordinals.
    #[must_use]
    pub fn texture_assignments(&self) -> &[TessellationTextureAssignment] {
        &self.texture_assignments
    }

    /// Set the owning body.
    #[must_use]
    pub fn with_body(mut self, body: Option<BodyId>) -> Self {
        self.body = body;
        self
    }

    /// Set the represented faces.
    #[must_use]
    pub fn with_faces(mut self, faces: Vec<FaceId>) -> Self {
        self.faces = faces;
        self
    }

    /// Source chordal deflection tolerance.
    #[must_use]
    pub const fn chordal_deflection(&self) -> Option<NonNegativeReal> {
        self.chordal_deflection
    }

    /// Set a finite, non-negative source chordal deflection.
    pub fn set_chordal_deflection(
        &mut self,
        chordal_deflection: Option<f64>,
    ) -> Result<(), TessellationError> {
        self.chordal_deflection = chordal_deflection
            .map(|value| {
                NonNegativeReal::new(value).ok_or_else(|| {
                    tessellation_error("chordal_deflection must be finite and non-negative")
                })
            })
            .transpose()?;
        Ok(())
    }

    /// Scale the source chordal deflection in place.
    ///
    /// A positive scale keeps the deflection non-negative, so the scaled
    /// deflection is refused only when it overflows, with the admission's own
    /// error.
    pub fn scale_chordal_deflection(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), TessellationError> {
        if let Some(value) = self.chordal_deflection {
            self.chordal_deflection = Some(value.scaled(scale).ok_or_else(|| {
                tessellation_error("chordal_deflection must be finite and non-negative")
            })?);
        }
        Ok(())
    }

    /// Set a finite, non-negative source chordal deflection.
    pub fn with_chordal_deflection(
        mut self,
        chordal_deflection: Option<f64>,
    ) -> Result<Self, TessellationError> {
        self.set_chordal_deflection(chordal_deflection)?;
        Ok(self)
    }

    /// Set a source chordal deflection that was admitted before this call.
    #[must_use]
    pub fn with_admitted_chordal_deflection(
        mut self,
        chordal_deflection: Option<NonNegativeReal>,
    ) -> Self {
        self.chordal_deflection = chordal_deflection;
        self
    }

    /// Set the native source-object identity.
    #[must_use]
    pub fn with_source_object(mut self, source_object: Option<SourceObjectAssociation>) -> Self {
        self.source_object = source_object;
        self
    }

    /// Set the geometric feature edges.
    pub fn with_feature_edges(
        mut self,
        feature_edges: Vec<[u32; 2]>,
    ) -> Result<Self, TessellationError> {
        require_feature_edges(self.mesh.vertex_count(), &feature_edges)?;
        self.feature_edges = feature_edges;
        Ok(self)
    }

    /// Set the triangle-group partition.
    pub fn with_triangle_groups(
        mut self,
        triangle_groups: Vec<TessellationTriangleGroup>,
    ) -> Result<Self, TessellationError> {
        require_triangle_groups(self.mesh.triangle_count(), &triangle_groups)?;
        self.triangle_groups = triangle_groups;
        Ok(self)
    }

    /// Set the texture assignments.
    pub fn with_texture_assignments(
        mut self,
        texture_assignments: Vec<TessellationTextureAssignment>,
    ) -> Result<Self, TessellationError> {
        require_texture_assignments(self.mesh.triangle_count(), &texture_assignments)?;
        self.texture_assignments = texture_assignments;
        Ok(self)
    }
}

impl TessellationChannel {
    /// Build a channel whose payload length is an exact multiple of `item_size`.
    pub fn new(
        addressing: ChannelAddressing,
        item_size: u32,
        kind: u32,
        flags: u32,
        data: Vec<u8>,
    ) -> Result<Self, TessellationError> {
        let item_size_usize = usize::try_from(item_size)
            .map_err(|_| tessellation_error("tessellation channel item size overflows usize"))?;
        if item_size_usize == 0 {
            if !data.is_empty() {
                return Err(tessellation_error(
                    "contains a malformed tessellation channel",
                ));
            }
        } else if !data.len().is_multiple_of(item_size_usize) {
            return Err(tessellation_error(
                "contains a malformed tessellation channel",
            ));
        }
        let element_count = match std::num::NonZeroUsize::new(item_size_usize) {
            // A zero item size is admitted only with empty data, checked
            // above, so the channel holds no element.
            None => 0,
            Some(item_size) => data.len() / item_size,
        };
        let count = u32::try_from(element_count)
            .map_err(|_| tessellation_error("tessellation channel count overflows u32"))?;
        if addressing.indices().iter().any(|index| *index >= count) {
            return Err(tessellation_error(
                "contains invalid tessellation channel indices",
            ));
        }
        Ok(Self {
            addressing,
            item_size,
            kind,
            flags,
            data,
            count,
        })
    }

    /// Mesh element addressed by this channel.
    #[must_use]
    pub fn addressing(&self) -> &ChannelAddressing {
        &self.addressing
    }

    /// Byte size of one element of [`Self::data`].
    #[must_use]
    pub const fn item_size(&self) -> u32 {
        self.item_size
    }

    /// Source channel-kind tag.
    #[must_use]
    pub const fn kind(&self) -> u32 {
        self.kind
    }

    /// Source per-channel flag word.
    #[must_use]
    pub const fn flags(&self) -> u32 {
        self.flags
    }

    /// Number of elements in [`Self::data`].
    ///
    /// The constructor computes this count and refuses a channel whose data
    /// holds more elements than the stated width, so the stored value is the
    /// only one this channel ever has.
    #[must_use]
    pub const fn count(&self) -> u32 {
        self.count
    }

    /// Raw channel payload.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Explicit selectors, empty for vertex-order addressing.
    #[must_use]
    pub fn indices(&self) -> &[u32] {
        self.addressing.indices()
    }
}

#[cfg(test)]
impl From<Tessellation> for TessellationWire {
    fn from(tessellation: Tessellation) -> Self {
        Self {
            id: tessellation.id,
            body: tessellation.body,
            faces: tessellation.faces,
            chordal_deflection: tessellation.chordal_deflection.map(NonNegativeReal::get),
            source_object: tessellation.source_object,
            mesh: tessellation.mesh.into_raw(),
            feature_edges: tessellation.feature_edges,
            triangle_groups: tessellation.triangle_groups,
            texture_assignments: tessellation.texture_assignments,
            channels: tessellation.channels,
        }
    }
}

impl TryFrom<TessellationWire> for Tessellation {
    type Error = TessellationError;

    fn try_from(wire: TessellationWire) -> Result<Self, Self::Error> {
        let mut mesh = Self {
            body: wire.body,
            faces: wire.faces,
            source_object: wire.source_object,
            ..Self::new(wire.id, wire.mesh, wire.channels)?
        };
        mesh.set_chordal_deflection(wire.chordal_deflection)?;
        mesh = mesh.with_feature_edges(wire.feature_edges)?;
        mesh = mesh.with_triangle_groups(wire.triangle_groups)?;
        mesh.with_texture_assignments(wire.texture_assignments)
    }
}

impl TryFrom<TessellationChannelWire> for TessellationChannel {
    type Error = TessellationError;

    fn try_from(wire: TessellationChannelWire) -> Result<Self, Self::Error> {
        Self::new(
            wire.addressing,
            wire.item_size,
            wire.kind,
            wire.flags,
            wire.data,
        )
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for Tessellation {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Tessellation".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::Tessellation").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        TessellationWire::json_schema(generator)
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for TessellationChannel {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TessellationChannel".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::TessellationChannel").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        TessellationChannelWire::json_schema(generator)
    }
}

#[cfg(test)]
mod tests;

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_body, BodyId, "body");
cadmpeg_core::named_optional_field!(deserialize_chordal_deflection, f64, "chordal_deflection");
cadmpeg_core::named_optional_field!(
    deserialize_source_object,
    SourceObjectAssociation,
    "source_object"
);
cadmpeg_core::named_optional_field!(deserialize_source_id, String, "source_id");

mod identity_rewrite;

mod serialization;