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
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
// SPDX-License-Identifier: Apache-2.0
//! NURBS curves, surfaces, pole layouts, and knot invariants.

/// Homogeneous Bezier extraction and boundary certificates.
pub mod bezier;
/// Rational control-polygon speed bounds.
pub mod bounds;

pub(super) mod admitted;

use crate::features::FinitePoint3;
use crate::math::Point3;
use crate::scalar::{FiniteReal, NonZeroReal};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Knot values that are finite and non-decreasing.
///
/// A NURBS store admits its knots through [`Self::new`], so a reader holds
/// the guarantee and the raw values through [`Self::as_slice`] or deref.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(transparent)]
pub struct KnotVector(Vec<f64>);

impl KnotVector {
    /// Admit finite non-decreasing knot values.
    ///
    /// # Errors
    ///
    /// Refuses a non-finite knot, then a decreasing pair.
    pub fn new(knots: Vec<f64>) -> Result<Self, NurbsError> {
        build_raw_knots(knots, "")
    }

    /// Build a knot vector from finite values. Only their order is checked.
    pub fn from_finite_lanes(knots: Vec<FiniteReal>) -> Result<Self, NurbsError> {
        build_finite_knots(knots, "")
    }

    /// Move the admitted knot storage into its owner without copying it.
    pub fn into_values(self) -> Vec<f64> {
        self.0
    }

    /// Borrow the knot values.
    #[must_use]
    pub fn as_slice(&self) -> &[f64] {
        &self.0
    }

    /// Reverse the order and negate every value, the knots of the reversed
    /// parameterization. Negation turns a non-decreasing sequence into a
    /// non-increasing one, and the reversal restores the order, so the
    /// result stays admitted.
    pub(super) fn reverse_negated(&mut self) {
        self.0.reverse();
        for knot in &mut self.0 {
            *knot = -*knot;
        }
    }
}

impl std::ops::Deref for KnotVector {
    type Target = [f64];
    fn deref(&self) -> &[f64] {
        &self.0
    }
}

impl<'a> IntoIterator for &'a KnotVector {
    type Item = &'a f64;
    type IntoIter = std::slice::Iter<'a, f64>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

mod knot_value_sealed {
    pub trait Sealed {}

    impl Sealed for Vec<f64> {}
    impl Sealed for Vec<crate::scalar::FiniteReal> {}
    impl Sealed for super::KnotVector {}
}

/// A raw or admitted knot lane passed into a NURBS constructor.
///
/// Only a raw vector or an admitted [`KnotVector`] can supply this lane.
pub trait KnotValue: knot_value_sealed::Sealed {
    /// Number of knots before cardinality validation.
    fn knot_count(&self) -> usize;
    /// Admit raw knots or keep an admitted knot vector.
    fn admit<E>(
        self,
        raw: impl FnOnce(Vec<f64>) -> Result<KnotVector, E>,
        finite: impl FnOnce(Vec<FiniteReal>) -> Result<KnotVector, E>,
    ) -> Result<KnotVector, E>;
}

impl KnotValue for Vec<f64> {
    fn knot_count(&self) -> usize {
        Vec::len(self)
    }

    fn admit<E>(
        self,
        raw: impl FnOnce(Vec<f64>) -> Result<KnotVector, E>,
        _finite: impl FnOnce(Vec<FiniteReal>) -> Result<KnotVector, E>,
    ) -> Result<KnotVector, E> {
        raw(self)
    }
}

impl KnotValue for Vec<FiniteReal> {
    fn knot_count(&self) -> usize {
        Vec::len(self)
    }

    fn admit<E>(
        self,
        _raw: impl FnOnce(Vec<f64>) -> Result<KnotVector, E>,
        finite: impl FnOnce(Vec<FiniteReal>) -> Result<KnotVector, E>,
    ) -> Result<KnotVector, E> {
        finite(self)
    }
}

impl KnotValue for KnotVector {
    fn knot_count(&self) -> usize {
        self.0.len()
    }

    fn admit<E>(
        self,
        _raw: impl FnOnce(Vec<f64>) -> Result<KnotVector, E>,
        _finite: impl FnOnce(Vec<FiniteReal>) -> Result<KnotVector, E>,
    ) -> Result<KnotVector, E> {
        Ok(self)
    }
}

fn build_raw_knots(knots: Vec<f64>, prefix: &str) -> Result<KnotVector, NurbsError> {
    require_nondecreasing_knots(&knots, prefix)?;
    Ok(KnotVector(knots))
}

fn build_finite_knots(knots: Vec<FiniteReal>, prefix: &str) -> Result<KnotVector, NurbsError> {
    let values: Vec<f64> = knots.into_iter().map(FiniteReal::get).collect();
    require_knot_order(&values, prefix)?;
    Ok(KnotVector(values))
}

pub(super) fn admit_knots<K: KnotValue>(knots: K, prefix: &str) -> Result<KnotVector, NurbsError> {
    knots.admit(
        |values| build_raw_knots(values, prefix),
        |values| build_finite_knots(values, prefix),
    )
}

/// One rational pole in model space: its position and its weight.
// A source states a raw position; a NURBS store holds the admitted row, whose
// position is a `FinitePoint3`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct WeightedPole3<P = Point3> {
    /// Pole position in model space.
    pub point: P,
    /// Rational weight at this pole.
    pub weight: NonZeroReal,
}

/// The poles of a NURBS curve, stating the curve's rational form.
///
/// A rational pole carries its weight in its own row, so a weight list that
/// does not cover the poles has no spelling, and "the curve is polynomial" has
/// exactly one spelling.
// A source states raw positions; a `NurbsCurve` holds the admitted poles,
// whose positions are `FinitePoint3` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "form", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum NurbsPoles3<P = Point3> {
    /// A polynomial curve: its poles carry no weight.
    Polynomial {
        /// Poles in parameter order.
        points: Vec<P>,
    },
    /// A rational curve: every pole carries its weight.
    Rational {
        /// Pole rows in parameter order.
        points: Vec<WeightedPole3<P>>,
    },
}

/// A pole value a producer hands a NURBS store: a raw value, which the store
/// admits in its own refusal order, or an admitted value, which it keeps.
pub trait PoleValue<T>: Copy {
    /// Whether pole admission retains the input vector storage.
    /// The admitted value, absent when a raw value is not finite.
    fn admit(self) -> Option<T>;

    /// Admit a curve lane through its explicit conversion policy.
    /// An implementation may keep storage whose positions are already admitted.
    fn admit_curve_poles<E>(
        poles: NurbsPoles3<Self>,
        convert: impl FnOnce(NurbsPoles3<Self>) -> Result<NurbsPoles3<T>, E>,
    ) -> Result<NurbsPoles3<T>, E> {
        convert(poles)
    }

    /// Admit a parameter-space lane through its explicit conversion policy.
    /// An implementation may keep storage whose positions are already admitted.
    fn admit_pcurve_poles<E>(
        poles: super::pcurve::PcurveNurbsPoles<Self>,
        convert: impl FnOnce(
            super::pcurve::PcurveNurbsPoles<Self>,
        ) -> Result<super::pcurve::PcurveNurbsPoles<T>, E>,
    ) -> Result<super::pcurve::PcurveNurbsPoles<T>, E> {
        convert(poles)
    }

    /// Admit a surface grid through its explicit conversion policy.
    /// An implementation may keep storage whose positions are already admitted.
    fn admit_surface_poles<E>(
        grid: NurbsPoleGrid<Self>,
        convert: impl FnOnce(NurbsPoleGrid<Self>) -> Result<NurbsPoleGrid<T>, E>,
    ) -> Result<NurbsPoleGrid<T>, E> {
        convert(grid)
    }
}

impl PoleValue<FinitePoint3> for Point3 {
    fn admit(self) -> Option<FinitePoint3> {
        FinitePoint3::new(self)
    }
}

impl PoleValue<FinitePoint3> for FinitePoint3 {
    fn admit(self) -> Option<FinitePoint3> {
        Some(self)
    }

    fn admit_curve_poles<E>(
        poles: NurbsPoles3<Self>,
        _convert: impl FnOnce(NurbsPoles3<Self>) -> Result<NurbsPoles3<FinitePoint3>, E>,
    ) -> Result<NurbsPoles3<FinitePoint3>, E> {
        Ok(poles)
    }

    fn admit_surface_poles<E>(
        grid: NurbsPoleGrid<Self>,
        _convert: impl FnOnce(NurbsPoleGrid<Self>) -> Result<NurbsPoleGrid<FinitePoint3>, E>,
    ) -> Result<NurbsPoleGrid<FinitePoint3>, E> {
        Ok(grid)
    }
}

fn map_pole<P: PoleValue<T>, T>(point: P) -> Result<T, NurbsError> {
    match point.admit() {
        Some(point) => Ok(point),
        None => Err(NurbsError::Structure(
            "control_points contains a non-finite point".to_owned(),
        )),
    }
}

fn map_curve_poles<P: PoleValue<T>, T>(
    poles: NurbsPoles3<P>,
) -> Result<NurbsPoles3<T>, NurbsError> {
    Ok(match poles {
        NurbsPoles3::Polynomial { points } => NurbsPoles3::Polynomial {
            points: points
                .into_iter()
                .map(map_pole)
                .collect::<Result<Vec<_>, NurbsError>>()?,
        },
        NurbsPoles3::Rational { points } => NurbsPoles3::Rational {
            points: points
                .into_iter()
                .map(|pole| {
                    Ok(WeightedPole3 {
                        point: map_pole(pole.point)?,
                        weight: pole.weight,
                    })
                })
                .collect::<Result<Vec<_>, NurbsError>>()?,
        },
    })
}

fn map_surface_poles<P: PoleValue<T>, T>(
    grid: NurbsPoleGrid<P>,
) -> Result<NurbsPoleGrid<T>, NurbsError> {
    Ok(match grid {
        NurbsPoleGrid::Polynomial { rows } => NurbsPoleGrid::Polynomial {
            rows: rows
                .into_iter()
                .map(|row| {
                    row.into_iter()
                        .map(map_pole)
                        .collect::<Result<Vec<_>, NurbsError>>()
                })
                .collect::<Result<Vec<_>, NurbsError>>()?,
        },
        NurbsPoleGrid::Rational { rows } => NurbsPoleGrid::Rational {
            rows: rows
                .into_iter()
                .map(|row| {
                    row.into_iter()
                        .map(|pole| {
                            Ok(WeightedPole3 {
                                point: map_pole(pole.point)?,
                                weight: pole.weight,
                            })
                        })
                        .collect::<Result<Vec<_>, NurbsError>>()
                })
                .collect::<Result<Vec<_>, NurbsError>>()?,
        },
    })
}

/// Pair each pole with its weight.
fn weighted_poles<P, W, E>(
    points: Vec<P>,
    weights: Vec<W>,
    mut weight: impl FnMut(usize, W) -> Result<NonZeroReal, E>,
) -> Result<Vec<WeightedPole3<P>>, E> {
    points
        .into_iter()
        .zip(weights)
        .enumerate()
        .map(|(index, (point, value))| {
            Ok(WeightedPole3 {
                point,
                weight: weight(index, value)?,
            })
        })
        .collect()
}

impl NurbsPoles3<FinitePoint3> {
    /// The poles with raw positions, for a reader that edits or writes them.
    #[must_use]
    pub fn to_raw(&self) -> NurbsPoles3 {
        let Ok(raw) = self
            .clone()
            .try_map_points(|point| Ok::<_, std::convert::Infallible>(point.get()));
        raw
    }

    /// Raw pole positions in parameter order, for a reader that computes with
    /// or writes them.
    #[must_use]
    pub fn raw_points(&self) -> Vec<Point3> {
        self.points().into_iter().map(FinitePoint3::get).collect()
    }
}

impl<P> NurbsPoles3<P> {
    /// Pair a source's pole lane with its weight lane. A store admits the
    /// positions it is handed.
    ///
    /// A source that states poles and weights as two arrays pairs them here,
    /// once, at the decode boundary.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both counts,
    /// and a weight that is zero or non-finite, naming its index.
    pub fn from_lanes(points: Vec<P>, weights: Option<Vec<f64>>) -> Result<Self, NurbsError> {
        pair_curve_lanes(points, weights, |index, weight| {
            admit_weight("poles", index, weight)
        })
    }

    /// Pair poles with finite weights, checking only lane length and nonzero weights.
    pub fn from_finite_lanes(
        points: Vec<P>,
        weights: Option<Vec<FiniteReal>>,
    ) -> Result<Self, NurbsError> {
        pair_curve_lanes(points, weights, |index, weight| {
            admit_finite_weight("poles", index, weight)
        })
    }

    /// Pair a pole lane with an admitted weight lane. The weight type states
    /// the weight contract; a store admits the positions it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both
    /// counts.
    pub fn from_checked_lanes(
        points: Vec<P>,
        weights: Option<Vec<NonZeroReal>>,
    ) -> Result<Self, NurbsError> {
        pair_curve_lanes(points, weights, |_, weight| Ok(weight))
    }

    /// Count poles.
    #[must_use]
    pub fn count(&self) -> usize {
        match self {
            Self::Polynomial { points } => points.len(),
            Self::Rational { points } => points.len(),
        }
    }

    /// Rational weights in pole order, absent on a polynomial curve.
    #[must_use]
    pub fn weights(&self) -> Option<Vec<f64>> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { points } => {
                Some(points.iter().map(|pole| pole.weight.get()).collect())
            }
        }
    }

    /// Reverse the pole order.
    pub fn reverse(&mut self) {
        match self {
            Self::Polynomial { points } => points.reverse(),
            Self::Rational { points } => points.reverse(),
        }
    }

    /// Map every pole position in parameter order, keeping the weights.
    fn try_map_points<Q, E>(
        self,
        mut point: impl FnMut(P) -> Result<Q, E>,
    ) -> Result<NurbsPoles3<Q>, E> {
        Ok(match self {
            Self::Polynomial { points } => NurbsPoles3::Polynomial {
                points: points.into_iter().map(point).collect::<Result<_, E>>()?,
            },
            Self::Rational { points } => NurbsPoles3::Rational {
                points: points
                    .into_iter()
                    .map(|pole| {
                        Ok(WeightedPole3 {
                            point: point(pole.point)?,
                            weight: pole.weight,
                        })
                    })
                    .collect::<Result<_, E>>()?,
            },
        })
    }
}

impl<P: Copy> NurbsPoles3<P> {
    /// One borrowed pole position in parameter order.
    #[must_use]
    pub fn point_at(&self, index: usize) -> Option<P> {
        match self {
            Self::Polynomial { points } => points.get(index).copied(),
            Self::Rational { points } => points.get(index).map(|pole| pole.point),
        }
    }

    /// One rational weight, absent for a polynomial curve or invalid index.
    #[must_use]
    pub fn weight_at(&self, index: usize) -> Option<f64> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { points } => points.get(index).map(|pole| pole.weight.get()),
        }
    }

    /// Pole positions in parameter order.
    #[must_use]
    pub fn points(&self) -> Vec<P> {
        match self {
            Self::Polynomial { points } => points.clone(),
            Self::Rational { points } => points.iter().map(|pole| pole.point).collect(),
        }
    }
}

/// The control grid of a NURBS surface, stating the surface's rational form.
///
/// A rational pole carries its weight in its own row, so a weight grid that
/// does not cover the pole grid has no spelling.
///
/// Transposition requires admission as a [`NurbsSurface`].
///
/// ```compile_fail
/// use cadmpeg_ir::geometry::nurbs::NurbsPoleGrid;
/// let mut grid = NurbsPoleGrid::Polynomial { rows: Vec::new() };
/// grid.transpose();
/// ```
// A source states raw positions; a `NurbsSurface` holds the admitted grid,
// whose positions are `FinitePoint3` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "form", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum NurbsPoleGrid<P = Point3> {
    /// A polynomial surface: its poles carry no weight.
    Polynomial {
        /// Control grid rows: `rows[i][j]` is pole `(i, j)`.
        rows: Vec<Vec<P>>,
    },
    /// A rational surface: every pole carries its weight.
    Rational {
        /// Control grid rows: `rows[i][j]` is pole `(i, j)`.
        rows: Vec<Vec<WeightedPole3<P>>>,
    },
}

pub(crate) fn pair_curve_lanes<P, W>(
    points: Vec<P>,
    weights: Option<Vec<W>>,
    mut weight: impl FnMut(usize, W) -> Result<NonZeroReal, NurbsError>,
) -> Result<NurbsPoles3<P>, NurbsError> {
    let Some(weights) = weights else {
        return Ok(NurbsPoles3::Polynomial { points });
    };
    require_weight_lane("poles", points.len(), weights.len())?;
    Ok(NurbsPoles3::Rational {
        points: weighted_poles(points, weights, &mut weight)?,
    })
}

fn pair_grid_lanes<P, W>(
    rows: Vec<Vec<P>>,
    weights: Option<Vec<Vec<W>>>,
    mut weight: impl FnMut(usize, W) -> Result<NonZeroReal, NurbsError>,
) -> Result<NurbsPoleGrid<P>, NurbsError> {
    let Some(weights) = weights else {
        return Ok(NurbsPoleGrid::Polynomial { rows });
    };
    require_weight_lane("pole grid", rows.len(), weights.len())?;
    let mut output = Vec::new();
    for (row, weights) in rows.into_iter().zip(weights) {
        require_weight_lane("pole grid row", row.len(), weights.len())?;
        output.push(weighted_poles(row, weights, &mut weight)?);
    }
    Ok(NurbsPoleGrid::Rational { rows: output })
}

impl NurbsPoleGrid<FinitePoint3> {
    /// The grid with raw positions, for a reader that edits or writes them.
    #[must_use]
    pub fn to_raw(&self) -> NurbsPoleGrid {
        let Ok(raw) = self
            .clone()
            .try_map_points(|point| Ok::<_, std::convert::Infallible>(point.get()));
        raw
    }

    /// Raw pole positions as grid rows, for a reader that computes with or
    /// writes them.
    #[must_use]
    pub fn raw_points(&self) -> Vec<Vec<Point3>> {
        self.points()
            .into_iter()
            .map(|row| row.into_iter().map(FinitePoint3::get).collect())
            .collect()
    }
}

impl<P> NurbsPoleGrid<P> {
    /// Pair a source's pole grid with its weight grid. A store admits the
    /// positions it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight grid that does not cover the pole grid, row count or
    /// row width, naming both counts, and a weight that is zero or non-finite,
    /// naming its index within its row.
    pub fn from_lanes(
        rows: Vec<Vec<P>>,
        weights: Option<Vec<Vec<f64>>>,
    ) -> Result<Self, NurbsError> {
        pair_grid_lanes(rows, weights, |index, weight| {
            admit_weight("pole grid row", index, weight)
        })
    }

    /// Pair a pole grid with finite weights, checking grid shape and nonzero weights.
    pub fn from_finite_lanes(
        rows: Vec<Vec<P>>,
        weights: Option<Vec<Vec<FiniteReal>>>,
    ) -> Result<Self, NurbsError> {
        pair_grid_lanes(rows, weights, |index, weight| {
            admit_finite_weight("pole grid row", index, weight)
        })
    }

    /// Pair a pole grid with an admitted weight grid. The weight type states
    /// the weight contract; a store admits the positions it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight grid that does not cover the pole grid, row count or
    /// row width, naming both counts.
    pub fn from_checked_lanes(
        rows: Vec<Vec<P>>,
        weights: Option<Vec<Vec<NonZeroReal>>>,
    ) -> Result<Self, NurbsError> {
        pair_grid_lanes(rows, weights, |_, weight| Ok(weight))
    }

    /// Number of grid rows, the pole count along u.
    #[must_use]
    pub fn u_count(&self) -> usize {
        match self {
            Self::Polynomial { rows } => rows.len(),
            Self::Rational { rows } => rows.len(),
        }
    }

    /// Length of the first grid row, the pole count along v.
    #[must_use]
    pub fn v_count(&self) -> usize {
        match self {
            Self::Polynomial { rows } => rows.first().map_or(0, Vec::len),
            Self::Rational { rows } => rows.first().map_or(0, Vec::len),
        }
    }

    /// Rational weight rows, absent on a polynomial surface.
    #[must_use]
    pub fn weights(&self) -> Option<Vec<Vec<f64>>> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { rows } => Some(
                rows.iter()
                    .map(|row| row.iter().map(|pole| pole.weight.get()).collect())
                    .collect(),
            ),
        }
    }

    /// Map every pole position in grid order, keeping the weights.
    fn try_map_points<Q, E>(
        self,
        mut point: impl FnMut(P) -> Result<Q, E>,
    ) -> Result<NurbsPoleGrid<Q>, E> {
        Ok(match self {
            Self::Polynomial { rows } => NurbsPoleGrid::Polynomial {
                rows: rows
                    .into_iter()
                    .map(|row| row.into_iter().map(&mut point).collect())
                    .collect::<Result<_, E>>()?,
            },
            Self::Rational { rows } => NurbsPoleGrid::Rational {
                rows: rows
                    .into_iter()
                    .map(|row| {
                        row.into_iter()
                            .map(|pole| {
                                Ok(WeightedPole3 {
                                    point: point(pole.point)?,
                                    weight: pole.weight,
                                })
                            })
                            .collect()
                    })
                    .collect::<Result<_, E>>()?,
            },
        })
    }
}

impl<P: Copy> NurbsPoleGrid<P> {
    /// Pole positions as grid rows.
    #[must_use]
    pub fn points(&self) -> Vec<Vec<P>> {
        match self {
            Self::Polynomial { rows } => rows.clone(),
            Self::Rational { rows } => rows
                .iter()
                .map(|row| row.iter().map(|pole| pole.point).collect())
                .collect(),
        }
    }
}

/// A tensor-product NURBS surface.
///
/// The control grid is stored as rows: the outer index is u, the inner index
/// is v, so the grid states both pole counts. `weights == None` denotes a
/// non-rational surface.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct NurbsSurface {
    /// Degree in the u parametric direction.
    u_degree: u32,
    /// Degree in the v parametric direction.
    v_degree: u32,
    /// Full knot vector in u.
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    u_knots: KnotVector,
    /// Full knot vector in v.
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    v_knots: KnotVector,
    /// Control grid rows, with the surface's rational form.
    #[cfg_attr(feature = "schema", schemars(with = "NurbsPoleGrid"))]
    poles: NurbsPoleGrid<FinitePoint3>,
    /// Whether the carrier's oriented normal is opposite `Pu × Pv`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    normal_reversed: bool,
    /// Whether the surface is periodic in u.
    u_periodic: bool,
    /// Whether the surface is periodic in v.
    v_periodic: bool,
}

/// Polynomial tensor-product B-spline surface with a rectangular control grid.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct BsplineSurface {
    u_degree: u32,
    v_degree: u32,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    u_knots: KnotVector,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    v_knots: KnotVector,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<Vec<Point3>>"))]
    control_points: Vec<Vec<FinitePoint3>>,
}

impl BsplineSurface {
    /// Build a rectangular grid with full knot vectors for both parameters.
    pub fn new(
        u_degree: u32,
        v_degree: u32,
        u_knots: Vec<f64>,
        v_knots: Vec<f64>,
        control_points: Vec<Vec<Point3>>,
    ) -> Result<Self, NurbsError> {
        let u_count = control_points.len();
        let v_count = control_points.first().map_or(0, Vec::len);
        let u_knots = bspline_axis_knots("u", "u_knots", u_degree, u_count, u_knots)?;
        let v_knots = bspline_axis_knots("v", "v_knots", v_degree, v_count, v_knots)?;
        require_rectangular_grid("control_points", &control_points)?;
        let control_points = control_points
            .into_iter()
            .map(|row| {
                row.into_iter()
                    .map(map_pole)
                    .collect::<Result<Vec<_>, NurbsError>>()
            })
            .collect::<Result<Vec<_>, NurbsError>>()?;
        Ok(BsplineSurface {
            u_degree,
            v_degree,
            u_knots,
            v_knots,
            control_points,
        })
    }

    /// Degree in the first parameter.
    pub const fn u_degree(&self) -> u32 {
        self.u_degree
    }

    /// Degree in the second parameter.
    pub const fn v_degree(&self) -> u32 {
        self.v_degree
    }

    /// Map every pole position in row-major order, or change nothing.
    ///
    /// `map` receives each pole's row-major index and position. The first
    /// refusal returns before any pole changes; otherwise `map` runs again for
    /// every pole and the results are written in place. Nothing is allocated.
    pub fn try_map_control_points<E>(
        &mut self,
        map: impl Fn(usize, FinitePoint3) -> Result<FinitePoint3, E>,
    ) -> Result<(), E> {
        for (index, point) in self.control_points.iter().flatten().copied().enumerate() {
            map(index, point)?;
        }
        for (index, point) in self.control_points.iter_mut().flatten().enumerate() {
            *point = map(index, *point)?;
        }
        Ok(())
    }
}
/// Admit one B-spline axis: more poles than its degree, the full knot count
/// for them, and finite non-decreasing knots, refused in that order.
fn bspline_axis_knots(
    axis: &str,
    knot_field: &str,
    degree: u32,
    count: usize,
    knots: Vec<f64>,
) -> Result<KnotVector, NurbsError> {
    if count <= cadmpeg_core::decode::index_from_u32(degree) {
        return Err(NurbsError::Structure(format!(
            "control_points {axis} count must exceed degree {degree}, found {count}"
        )));
    }
    require_length(
        knot_field,
        knots.len(),
        checked_knot_count(axis, count, degree)?,
    )?;
    build_raw_knots(knots, "")
}

impl<'de> Deserialize<'de> for BsplineSurface {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            u_degree: u32,
            v_degree: u32,
            u_knots: Vec<f64>,
            v_knots: Vec<f64>,
            control_points: Vec<Vec<Point3>>,
        }
        let wire = Wire::deserialize(deserializer)?;
        BsplineSurface::new(
            wire.u_degree,
            wire.v_degree,
            wire.u_knots,
            wire.v_knots,
            wire.control_points,
        )
        .map_err(serde::de::Error::custom)
    }
}

/// Structural error in a NURBS knot or pole carrier.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum NurbsError {
    /// A source stated a weight lane that does not cover its pole lane.
    #[error("{field}: {poles} pole(s) against {weights} weight(s)")]
    WeightLaneLength {
        /// The carrier field the lanes belong to.
        field: String,
        /// Poles the source stated.
        poles: usize,
        /// Weights the source stated.
        weights: usize,
    },
    /// A source stated a weight no pole can carry.
    #[error("{field}: weight {weight} at index {index} is not a usable weight")]
    UnusableWeight {
        /// The carrier field the weight belongs to.
        field: String,
        /// Position of the weight in the lane the source stated.
        index: usize,
        /// The refused weight.
        weight: f64,
    },
    /// A knot vector, degree, grid or coordinate the carrier cannot state.
    #[error("{0}")]
    Structure(String),
    /// An edit closure refused the value it was given, stating its own reason.
    #[error("{0}")]
    EditRefused(String),
}

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

fn checked_knot_count(field: &str, pole_count: usize, degree: u32) -> Result<usize, NurbsError> {
    let Ok(degree) = usize::try_from(degree) else {
        return Err(NurbsError::Structure(format!(
            "{field} knot count overflows usize"
        )));
    };
    match pole_count
        .checked_add(degree)
        .and_then(|count| count.checked_add(1))
    {
        Some(count) => Ok(count),
        None => Err(NurbsError::Structure(format!(
            "{field} knot count overflows usize"
        ))),
    }
}

/// Check every row width in source order through the caller's work policy.
fn require_rectangular_grid<T>(field: &str, rows: &[Vec<T>]) -> Result<(), NurbsError> {
    let width = rows.first().map_or(0, Vec::len);
    for row in rows {
        if row.len() != width {
            return Err(NurbsError::Structure(format!(
                "{field} row must contain {width} values, found {}",
                row.len(),
            )));
        }
    }
    Ok(())
}

fn require_length(field: &str, actual: usize, expected: usize) -> Result<(), NurbsError> {
    if actual == expected {
        Ok(())
    } else {
        Err(NurbsError::Structure(format!(
            "{field} must contain {expected} values, found {actual}"
        )))
    }
}

/// A weight lane covers the pole lane it belongs to.
pub(super) fn require_weight_lane(
    field: &str,
    poles: usize,
    weights: usize,
) -> Result<(), NurbsError> {
    if poles == weights {
        Ok(())
    } else {
        Err(NurbsError::WeightLaneLength {
            field: field.to_owned(),
            poles,
            weights,
        })
    }
}

/// Admit one weight a source states, naming its index within its lane.
pub(crate) fn admit_weight(
    field: &str,
    index: usize,
    weight: f64,
) -> Result<NonZeroReal, NurbsError> {
    if let Some(admitted) = NonZeroReal::new(weight) {
        return Ok(admitted);
    }
    Err(NurbsError::UnusableWeight {
        field: field.to_owned(),
        index,
        weight,
    })
}

/// Check the nonzero condition of a weight whose finiteness is already admitted.
pub(super) fn admit_finite_weight(
    field: &str,
    index: usize,
    weight: FiniteReal,
) -> Result<NonZeroReal, NurbsError> {
    if let Some(admitted) = NonZeroReal::from_finite(weight) {
        return Ok(admitted);
    }
    Err(NurbsError::UnusableWeight {
        field: field.to_owned(),
        index,
        weight: weight.get(),
    })
}

fn require_finite_scalars(prefix: &str, values: &[f64]) -> Result<(), NurbsError> {
    for value in values {
        if !value.is_finite() {
            return Err(NurbsError::Structure(format!(
                "{prefix}knots contains a non-finite value"
            )));
        }
    }
    Ok(())
}

fn require_knot_order(knots: &[f64], prefix: &str) -> Result<(), NurbsError> {
    if knots_ordered(knots, true) {
        Ok(())
    } else {
        Err(NurbsError::Structure(format!(
            "{prefix}knots must be non-decreasing"
        )))
    }
}

fn require_nondecreasing_knots(knots: &[f64], prefix: &str) -> Result<(), NurbsError> {
    require_finite_scalars(prefix, knots)?;
    require_knot_order(knots, prefix)
}

pub(super) fn require_curve_cardinality(
    degree: u32,
    knot_count: usize,
    pole_count: usize,
    point_field: &str,
) -> Result<(), NurbsError> {
    if u64::try_from(pole_count).is_ok_and(|count| count <= u64::from(degree)) {
        return Err(NurbsError::Structure(format!(
            "{point_field} must contain more than degree {degree} poles, found {pole_count}"
        )));
    }
    require_length(
        "knots",
        knot_count,
        checked_knot_count("curve", pole_count, degree)?,
    )
}

/// One parameter axis of a tensor-product NURBS surface.
///
/// A degree, its knot vector and its periodicity are one statement about one
/// axis: the knot count a source may state depends on the degree, and the
/// periodicity describes that same knot vector. They travel together.
#[derive(Debug, Clone, PartialEq)]
pub struct NurbsSurfaceAxis<K = Vec<f64>> {
    degree: u32,
    knots: K,
    periodic: bool,
}

impl<K> NurbsSurfaceAxis<K> {
    /// One axis of a surface: its degree, its knot vector and its periodicity.
    #[must_use]
    pub const fn new(degree: u32, knots: K, periodic: bool) -> Self {
        Self {
            degree,
            knots,
            periodic,
        }
    }
}

/// The pole grid and weight grid a source states for one NURBS surface.
///
/// A weight grid covers the pole grid it belongs to, so the two are one
/// statement and are paired once, at the decode boundary. A source states raw
/// lanes; a producer that holds admitted positions and weights states the
/// `FinitePoint3` and `NonZeroReal` lanes.
#[derive(Debug, Clone, PartialEq)]
pub struct NurbsSurfaceLanes<P = Point3, W = f64> {
    control_points: Vec<Vec<P>>,
    weights: Option<Vec<Vec<W>>>,
}

impl<P, W> NurbsSurfaceLanes<P, W> {
    /// The pole grid a source states, with its weight grid when it is
    /// rational.
    #[must_use]
    pub const fn new(control_points: Vec<Vec<P>>, weights: Option<Vec<Vec<W>>>) -> Self {
        Self {
            control_points,
            weights,
        }
    }
}
fn require_surface_shape<P>(
    u_degree: u32,
    u_knots: usize,
    v_degree: u32,
    v_knots: usize,
    poles: &NurbsPoleGrid<P>,
) -> Result<(), NurbsError> {
    let u_count = poles.u_count();
    let v_count = poles.v_count();
    if u64::try_from(u_count).is_ok_and(|count| count <= u64::from(u_degree)) {
        return Err(NurbsError::Structure(format!(
            "u_count must exceed u_degree {u_degree}, found {u_count}"
        )));
    }
    if u64::try_from(v_count).is_ok_and(|count| count <= u64::from(v_degree)) {
        return Err(NurbsError::Structure(format!(
            "v_count must exceed v_degree {v_degree}, found {v_count}"
        )));
    }
    require_length(
        "u_knots",
        u_knots,
        checked_knot_count("u", u_count, u_degree)?,
    )?;
    require_length(
        "v_knots",
        v_knots,
        checked_knot_count("v", v_count, v_degree)?,
    )?;
    match poles {
        NurbsPoleGrid::Polynomial { rows } => {
            require_rectangular_grid("control_points", rows)?;
        }
        NurbsPoleGrid::Rational { rows } => {
            require_rectangular_grid("control_points", rows)?;
        }
    }
    Ok(())
}

impl NurbsSurface {
    /// Build a tensor-product NURBS surface with consistent cardinalities.
    ///
    /// Raw pole positions are admitted; admitted positions are kept, so a
    /// producer that holds them tests only the grid's cross-field conditions.
    ///
    /// # Errors
    ///
    /// Refuses a pole count that does not exceed its degree, a knot count that
    /// does not follow from the degree and the pole count, a ragged grid, a
    /// non-finite raw pole coordinate and then a non-finite or decreasing
    /// knot.
    pub fn new<P: PoleValue<FinitePoint3>, U: KnotValue, V: KnotValue>(
        u: NurbsSurfaceAxis<U>,
        v: NurbsSurfaceAxis<V>,
        poles: NurbsPoleGrid<P>,
        normal_reversed: bool,
    ) -> Result<Self, NurbsError> {
        let NurbsSurfaceAxis {
            degree: u_degree,
            knots: u_knots,
            periodic: u_periodic,
        } = u;
        let NurbsSurfaceAxis {
            degree: v_degree,
            knots: v_knots,
            periodic: v_periodic,
        } = v;
        require_surface_shape(
            u_degree,
            u_knots.knot_count(),
            v_degree,
            v_knots.knot_count(),
            &poles,
        )?;
        let poles = P::admit_surface_poles(poles, |poles| map_surface_poles(poles))?;
        let u_knots = admit_knots(u_knots, "u_")?;
        let v_knots = admit_knots(v_knots, "v_")?;
        Ok(NurbsSurface {
            u_degree,
            v_degree,
            u_knots,
            v_knots,
            poles,
            normal_reversed,
            u_periodic,
            v_periodic,
        })
    }

    /// Degree in the u parametric direction.
    pub const fn u_degree(&self) -> u32 {
        self.u_degree
    }

    /// Degree in the v parametric direction.
    pub const fn v_degree(&self) -> u32 {
        self.v_degree
    }

    /// Full knot vector in u.
    pub fn u_knots(&self) -> &KnotVector {
        &self.u_knots
    }

    /// Full knot vector in v.
    pub fn v_knots(&self) -> &KnotVector {
        &self.v_knots
    }

    /// Number of control points along u, the number of grid rows.
    pub fn u_count(&self) -> usize {
        self.poles.u_count()
    }

    /// Number of control points along v, the length of every grid row.
    pub fn v_count(&self) -> usize {
        self.poles.v_count()
    }

    /// Build from finite knots, poles, and weights. Only relationships and
    /// the nonzero weight condition are checked.
    pub fn from_finite_lanes(
        u: NurbsSurfaceAxis<Vec<FiniteReal>>,
        v: NurbsSurfaceAxis<Vec<FiniteReal>>,
        lanes: NurbsSurfaceLanes<FinitePoint3, FiniteReal>,
        normal_reversed: bool,
    ) -> Result<Self, NurbsError> {
        let NurbsSurfaceLanes {
            control_points,
            weights,
        } = lanes;
        let poles = pair_grid_lanes(control_points, weights, |index, weight| {
            admit_finite_weight("pole grid row", index, weight)
        })?;
        NurbsSurface::new(u, v, poles, normal_reversed)
    }

    /// Build a NURBS surface from knot axes, a pole grid and an admitted weight grid.
    /// Admitted knot vectors are kept; raw knots are admitted by [`Self::new`].
    ///
    /// # Errors
    ///
    /// Refuses a weight grid that does not cover its pole grid, invalid
    /// cardinalities, a non-finite raw pole coordinate, or a non-finite or
    /// decreasing raw knot.
    pub fn from_checked_lanes<P: PoleValue<FinitePoint3>, U: KnotValue, V: KnotValue>(
        u: NurbsSurfaceAxis<U>,
        v: NurbsSurfaceAxis<V>,
        lanes: NurbsSurfaceLanes<P, NonZeroReal>,
        normal_reversed: bool,
    ) -> Result<Self, NurbsError> {
        let NurbsSurfaceLanes {
            control_points,
            weights,
        } = lanes;
        let poles = pair_grid_lanes(control_points, weights, |_, weight| Ok(weight))?;
        NurbsSurface::new(u, v, poles, normal_reversed)
    }

    /// Control grid rows, with the surface's rational form and admitted
    /// positions.
    pub const fn pole_grid(&self) -> &NurbsPoleGrid<FinitePoint3> {
        &self.poles
    }

    /// Control-point rows, outer index u and inner index v.
    #[must_use]
    pub fn control_grid(&self) -> Vec<Vec<FinitePoint3>> {
        self.poles.points()
    }

    /// Control points in u-major order.
    #[must_use]
    pub fn poles(&self) -> Vec<FinitePoint3> {
        self.control_grid().into_iter().flatten().collect()
    }

    /// Pole at grid position `(u, v)`.
    #[must_use]
    pub fn pole(&self, u: usize, v: usize) -> Option<FinitePoint3> {
        match &self.poles {
            NurbsPoleGrid::Polynomial { rows } => rows.get(u)?.get(v).copied(),
            NurbsPoleGrid::Rational { rows } => rows.get(u)?.get(v).map(|pole| pole.point),
        }
    }

    /// Rational weight at grid position `(u, v)`, absent when non-rational.
    pub fn weight(&self, u: usize, v: usize) -> Option<NonZeroReal> {
        match &self.poles {
            NurbsPoleGrid::Polynomial { .. } => None,
            NurbsPoleGrid::Rational { rows } => rows.get(u)?.get(v).map(|pole| pole.weight),
        }
    }

    /// Map pole positions in row-major order after every result passes admission.
    /// The map must return the same result for the same index and position.
    /// Pole weights and knots stay in place.
    pub fn try_map_control_points<E>(
        &mut self,
        map: impl Fn(usize, FinitePoint3) -> Result<FinitePoint3, E>,
    ) -> Result<(), E> {
        match &self.poles {
            NurbsPoleGrid::Polynomial { rows } => {
                for (index, point) in rows.iter().flatten().copied().enumerate() {
                    map(index, point)?;
                }
            }
            NurbsPoleGrid::Rational { rows } => {
                for (index, pole) in rows.iter().flatten().enumerate() {
                    map(index, pole.point)?;
                }
            }
        }
        match &mut self.poles {
            NurbsPoleGrid::Polynomial { rows } => {
                for (index, point) in rows.iter_mut().flatten().enumerate() {
                    *point = map(index, *point)?;
                }
            }
            NurbsPoleGrid::Rational { rows } => {
                for (index, pole) in rows.iter_mut().flatten().enumerate() {
                    pole.point = map(index, pole.point)?;
                }
            }
        }
        Ok(())
    }

    /// Rational weight rows in control-grid order.
    pub fn weights(&self) -> Option<Vec<Vec<NonZeroReal>>> {
        match &self.poles {
            NurbsPoleGrid::Polynomial { .. } => None,
            NurbsPoleGrid::Rational { rows } => Some(
                rows.iter()
                    .map(|row| row.iter().map(|pole| pole.weight).collect())
                    .collect(),
            ),
        }
    }

    /// Rational weights in control-point order.
    pub fn pole_weights(&self) -> Option<Vec<NonZeroReal>> {
        Some(self.weights()?.into_iter().flatten().collect())
    }

    /// Whether the carrier's oriented normal is reversed.
    pub const fn normal_reversed(&self) -> bool {
        self.normal_reversed
    }

    /// Whether the surface is periodic in u.
    pub const fn u_periodic(&self) -> bool {
        self.u_periodic
    }

    /// Whether the surface is periodic in v.
    pub const fn v_periodic(&self) -> bool {
        self.v_periodic
    }

    /// Exchange the u and v parameter axes and transpose pole storage.
    /// The natural normal changes sign; `normal_reversed` remains unchanged.
    pub fn transpose_parameter_axes(&mut self) {
        // Surface admission and every grid mutation preserve nonempty,
        // rectangular rows. Raw pole grids do not expose this operation.
        fn transpose<T: Copy>(rows: &[Vec<T>], width: usize) -> Vec<Vec<T>> {
            (0..width)
                .map(|column| rows.iter().map(|row| row[column]).collect())
                .collect()
        }

        let width = self.v_count();
        match &mut self.poles {
            NurbsPoleGrid::Polynomial { rows } => *rows = transpose(rows, width),
            NurbsPoleGrid::Rational { rows } => *rows = transpose(rows, width),
        }
        std::mem::swap(&mut self.u_degree, &mut self.v_degree);
        std::mem::swap(&mut self.u_knots, &mut self.v_knots);
        std::mem::swap(&mut self.u_periodic, &mut self.v_periodic);
    }
}

impl<'de> Deserialize<'de> for NurbsSurface {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            u_degree: u32,
            v_degree: u32,
            u_knots: Vec<f64>,
            v_knots: Vec<f64>,
            poles: NurbsPoleGrid,
            #[serde(default)]
            normal_reversed: bool,
            u_periodic: bool,
            v_periodic: bool,
        }

        let wire = Wire::deserialize(deserializer)?;
        NurbsSurface::new(
            NurbsSurfaceAxis::new(wire.u_degree, wire.u_knots, wire.u_periodic),
            NurbsSurfaceAxis::new(wire.v_degree, wire.v_knots, wire.v_periodic),
            wire.poles,
            wire.normal_reversed,
        )
        .map_err(serde::de::Error::custom)
    }
}

/// Fixed parameter axis used to extract an isoparametric surface curve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SurfaceParameterAxis {
    /// Hold the surface U parameter constant and vary V.
    U,
    /// Hold the surface V parameter constant and vary U.
    V,
}

/// A NURBS curve knot/pole payload.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct NurbsCurve {
    /// Curve degree.
    degree: u32,
    /// Full knot vector.
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    knots: KnotVector,
    /// Poles in parameter order, with the curve's rational form.
    #[cfg_attr(feature = "schema", schemars(with = "NurbsPoles3"))]
    poles: NurbsPoles3<FinitePoint3>,
    /// Whether the curve is periodic.
    periodic: bool,
}

impl NurbsCurve {
    /// Copy the curve and map the copied pole positions. A non-finite result
    /// leaves the source untouched and returns no curve.
    pub fn map_control_points(&self, mut map: impl FnMut(Point3) -> Point3) -> Option<Self> {
        let mut mapped = self.clone();
        match &mut mapped.poles {
            NurbsPoles3::Polynomial { points } => {
                for point in points {
                    let next = FinitePoint3::new(map(point.get()))?;
                    *point = next;
                }
            }
            NurbsPoles3::Rational { points } => {
                for pole in points {
                    let next = FinitePoint3::new(map(pole.point.get()))?;
                    pole.point = next;
                }
            }
        }
        Some(mapped)
    }

    /// Build a NURBS curve with consistent knot, pole, and weight cardinalities.
    ///
    /// Raw pole positions are admitted; admitted positions are kept, so a
    /// producer that holds them tests only the cardinalities and the knots.
    ///
    /// # Errors
    ///
    /// Refuses a pole or knot count that does not follow from the degree, a
    /// non-finite raw pole coordinate and then a non-finite or decreasing
    /// knot.
    pub fn new<P: PoleValue<FinitePoint3>, K: KnotValue>(
        degree: u32,
        knots: K,
        poles: NurbsPoles3<P>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        require_curve_cardinality(degree, knots.knot_count(), poles.count(), "control_points")?;
        let poles = P::admit_curve_poles(poles, |poles| map_curve_poles(poles))?;
        let knots = admit_knots(knots, "")?;
        Ok(NurbsCurve {
            degree,
            knots,
            poles,
            periodic,
        })
    }

    /// Curve degree.
    pub const fn degree(&self) -> u32 {
        self.degree
    }

    /// Full knot vector.
    pub fn knots(&self) -> &KnotVector {
        &self.knots
    }

    /// Move the curve lanes to a caller that will rebuild a checked curve.
    pub fn into_parts(self) -> (u32, KnotVector, NurbsPoles3<FinitePoint3>, bool) {
        (self.degree, self.knots, self.poles, self.periodic)
    }

    /// Atomically edit knot values and preserve their invariants.
    pub fn edit_knots(&mut self, edit: impl FnOnce(&mut [f64])) -> Result<(), NurbsError> {
        let mut values = self.knots.as_slice().to_vec();
        edit(&mut values);
        let knots = build_raw_knots(values, "")?;
        self.knots = knots;
        Ok(())
    }

    /// Replace the knot vector of an owned curve without copying its poles.
    ///
    /// # Errors
    ///
    /// Refuses a knot count inconsistent with the degree and pole count, a
    /// non-finite knot, or a decreasing pair.
    pub fn with_knots(mut self, knots: Vec<f64>) -> Result<Self, NurbsError> {
        require_curve_cardinality(
            self.degree,
            knots.len(),
            self.poles.count(),
            "control_points",
        )?;
        self.knots = build_raw_knots(knots, "")?;
        Ok(self)
    }

    /// Build from finite knots, poles, and weights. Only relationships and
    /// the nonzero weight condition are checked.
    pub fn from_finite_lanes(
        degree: u32,
        knots: Vec<FiniteReal>,
        control_points: Vec<FinitePoint3>,
        weights: Option<Vec<FiniteReal>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = pair_curve_lanes(control_points, weights, |index, weight| {
            admit_finite_weight("poles", index, weight)
        })?;
        NurbsCurve::new(degree, knots, poles, periodic)
    }

    /// Build a NURBS curve from knots, a pole lane and an admitted weight lane.
    /// An admitted knot vector is kept; raw knots are admitted by [`Self::new`].
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, a pole count
    /// inconsistent with the degree, or a non-finite or decreasing raw knot.
    pub fn from_checked_lanes<P: PoleValue<FinitePoint3>, K: KnotValue>(
        degree: u32,
        knots: K,
        control_points: Vec<P>,
        weights: Option<Vec<NonZeroReal>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = pair_curve_lanes(control_points, weights, |_, weight| Ok(weight))?;
        NurbsCurve::new(degree, knots, poles, periodic)
    }

    /// Poles in parameter order, with the curve's rational form and admitted
    /// positions.
    pub const fn pole_rows(&self) -> &NurbsPoles3<FinitePoint3> {
        &self.poles
    }

    /// Control points in parameter order.
    #[must_use]
    pub fn control_points(&self) -> Vec<FinitePoint3> {
        self.poles.points()
    }

    /// Number of poles.
    pub fn pole_count(&self) -> usize {
        self.poles.count()
    }

    /// Map pole positions in order after every result passes admission.
    /// The map must return the same result for the same index and position.
    /// Pole weights and knots stay in place.
    pub fn try_map_control_points<E>(
        &mut self,
        map: impl Fn(usize, FinitePoint3) -> Result<FinitePoint3, E>,
    ) -> Result<(), E> {
        match &self.poles {
            NurbsPoles3::Polynomial { points } => {
                for (index, point) in points.iter().copied().enumerate() {
                    map(index, point)?;
                }
            }
            NurbsPoles3::Rational { points } => {
                for (index, pole) in points.iter().enumerate() {
                    map(index, pole.point)?;
                }
            }
        }
        match &mut self.poles {
            NurbsPoles3::Polynomial { points } => {
                for (index, point) in points.iter_mut().enumerate() {
                    *point = map(index, *point)?;
                }
            }
            NurbsPoles3::Rational { points } => {
                for (index, pole) in points.iter_mut().enumerate() {
                    pole.point = map(index, pole.point)?;
                }
            }
        }
        Ok(())
    }

    /// Rational weights in pole order.
    pub fn weights(&self) -> Option<Vec<NonZeroReal>> {
        match &self.poles {
            NurbsPoles3::Polynomial { .. } => None,
            NurbsPoles3::Rational { points } => {
                Some(points.iter().map(|pole| pole.weight).collect())
            }
        }
    }

    /// Whether the curve is periodic.
    pub const fn periodic(&self) -> bool {
        self.periodic
    }

    /// Reverse poles, weights, and the signed knot parameterization together.
    pub fn reverse_parameterization(&mut self) {
        self.knots.reverse_negated();
        self.poles.reverse();
    }

    /// Reverse poles and reflect knots within an admitted parameter range.
    /// The curve stays unchanged when a reflected knot is not finite or the
    /// resulting knot lane is decreasing.
    pub fn reverse_parameterization_in_range(
        &mut self,
        start: FiniteReal,
        end: FiniteReal,
    ) -> Option<()> {
        let mut previous = None;
        for knot in self.knots.0.iter().rev() {
            let reflected = FiniteReal::new(*knot)
                .and_then(|knot| crate::math::reflect_parameter(knot, start, end))?;
            if previous.is_some_and(|previous| previous > reflected) {
                return None;
            }
            previous = Some(reflected);
        }
        self.poles.reverse();
        self.knots.0.reverse();
        for knot in &mut self.knots.0 {
            // The validation pass reached the same original knot before mutation.
            let reflected = FiniteReal::new(*knot)
                .and_then(|knot| crate::math::reflect_parameter(knot, start, end))?;
            *knot = reflected.get();
        }
        Some(())
    }
}

impl<'de> Deserialize<'de> for NurbsCurve {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            degree: u32,
            knots: Vec<f64>,
            poles: NurbsPoles3,
            periodic: bool,
        }

        let wire = Wire::deserialize(deserializer)?;
        NurbsCurve::new(wire.degree, wire.knots, wire.poles, wire.periodic)
            .map_err(serde::de::Error::custom)
    }
}

/// Tests adjacent knot pairs.
/// A NaN pair fails this predicate.
pub fn knots_nondecreasing(knots: &[f64]) -> bool {
    knots_ordered(knots, true)
}

/// Tests strict adjacent knot order.
/// A repeated knot or NaN pair fails this predicate.
pub fn knots_strictly_increasing(knots: &[f64]) -> bool {
    knots_ordered(knots, false)
}

fn knots_ordered(knots: &[f64], repeats: bool) -> bool {
    for pair in knots.windows(2) {
        match pair[0].partial_cmp(&pair[1]) {
            Some(std::cmp::Ordering::Less) => {}
            Some(std::cmp::Ordering::Equal) if repeats => {}
            _ => return false,
        }
    }
    true
}

#[cfg(test)]
mod tests;

mod identity_rewrite;