cadmpeg-ir 0.6.1

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
// SPDX-License-Identifier: Apache-2.0
//! Analytic curves and surfaces with admitted frames and dimensions.
//!
//! Each type states what its caller supplies through three constructor forms:
//!
//! | Inputs | Constructor |
//! |---|---|
//! | Raw values requiring admission | `try_new(...) -> Result<Self, &'static str>` |
//! | Checked parts that establish every invariant | `new(...) -> Self` |
//! | Checked parts with a remaining relationship | `try_from_parts(...) -> Result<Self, &'static str>` |
//!
//! `try_new` admits each raw component and delegates, so wire deserialization
//! and model code reach the same stored state through one admission path. A
//! getter returns the checked type of the stored value, so an unchanged
//! component moves into another model object without a second admission.
//!
//! Raw construction reports component admission failures before relationships
//! between components. For example, an ellipse with radii `-1` and `2` reports
//! the invalid major radius before checking radius ordering. Sphere radii and
//! torus minor radii use a single field-specific finite/nonzero error for both
//! restrictions. This replaces the separate zero check used before checked
//! constructor composition; callers must not depend on the old error precedence.

use crate::features::FinitePoint3;
use crate::math::{Point3, Vector3};
use crate::scalar::{Angle, NonNegativeLength, NonZeroLength, PositiveLength, PositiveReal};
use crate::sketches::OrderedMajorRadius;
use crate::units::{OrthonormalFrame3, UnitVector3};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Plane with a finite origin and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "PlaneSurfaceWire", into = "PlaneSurfaceWire")]
pub struct PlaneSurface {
    origin: FinitePoint3,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PlaneSurfaceWire {
    /// Plane origin.
    origin: Point3,
    /// Plane normal.
    normal: Vector3,
    /// First in-plane axis, perpendicular to `normal`.
    u_axis: Vector3,
}

impl PlaneSurface {
    /// Build a plane from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// Checked parts taken from one plane rebuild another without readmission:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::PlaneSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let plane = PlaneSurface::try_new(
    ///     Point3::new(1.0, 2.0, 3.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    /// )
    /// .expect("orthonormal frame and finite origin");
    /// let moved = PlaneSurface::new(plane.origin(), *plane.frame());
    /// assert_eq!(moved, plane);
    /// ```
    ///
    /// Raw coordinates and directions do not reach it:
    ///
    /// ```compile_fail
    /// use cadmpeg_ir::geometry::analytic::PlaneSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let plane = PlaneSurface::new(
    ///     Point3::new(1.0, 2.0, 3.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    /// );
    /// ```
    #[must_use]
    pub const fn new(origin: FinitePoint3, frame: OrthonormalFrame3) -> Self {
        Self { origin, frame }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(origin: Point3, normal: Vector3, u_axis: Vector3) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(normal, u_axis)
            .ok_or("PlaneSurface.normal/u_axis must form an orthonormal frame")?;
        let origin = FinitePoint3::new(origin).ok_or("PlaneSurface.origin must be finite")?;
        Ok(Self::new(origin, frame))
    }

    /// Return the origin.
    #[must_use]
    pub const fn origin(&self) -> FinitePoint3 {
        self.origin
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }
}

impl From<PlaneSurface> for PlaneSurfaceWire {
    fn from(value: PlaneSurface) -> Self {
        Self {
            origin: value.origin().get(),
            normal: *value.frame().axis().as_raw(),
            u_axis: *value.frame().reference().as_raw(),
        }
    }
}

impl TryFrom<PlaneSurfaceWire> for PlaneSurface {
    type Error = &'static str;
    fn try_from(wire: PlaneSurfaceWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.origin, wire.normal, wire.u_axis)
    }
}

/// Circular cylinder with a positive radius and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "CylinderSurfaceWire", into = "CylinderSurfaceWire")]
pub struct CylinderSurface {
    origin: FinitePoint3,
    radius: PositiveLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct CylinderSurfaceWire {
    /// Cylinder frame origin.
    origin: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Frame reference direction, perpendicular to `axis`.
    ref_direction: Vector3,
    /// Cylinder radius.
    radius: f64,
}

impl CylinderSurface {
    /// Build a cylinder from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// A raw radius has no way in:
    ///
    /// ```compile_fail
    /// use cadmpeg_ir::geometry::analytic::CylinderSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let cylinder = CylinderSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite origin and positive radius");
    /// let wider = CylinderSurface::new(cylinder.origin(), *cylinder.frame(), 4.0);
    /// ```
    ///
    /// An admitted one does:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::CylinderSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    /// use cadmpeg_ir::scalar::PositiveLength;
    ///
    /// let cylinder = CylinderSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite origin and positive radius");
    /// let wider = CylinderSurface::new(
    ///     cylinder.origin(),
    ///     *cylinder.frame(),
    ///     PositiveLength::new(4.0).expect("positive finite"),
    /// );
    /// assert_eq!(wider.radius().get(), 4.0);
    /// ```
    #[must_use]
    pub const fn new(
        origin: FinitePoint3,
        frame: OrthonormalFrame3,
        radius: PositiveLength,
    ) -> Self {
        Self {
            origin,
            radius,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        origin: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        radius: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, ref_direction)
            .ok_or("CylinderSurface.axis/ref_direction must form an orthonormal frame")?;
        let origin = FinitePoint3::new(origin).ok_or("CylinderSurface.origin must be finite")?;
        let radius = PositiveLength::new(radius)
            .ok_or("CylinderSurface.radius must be positive and finite")?;
        Ok(Self::new(origin, frame, radius))
    }

    /// Return the origin.
    #[must_use]
    pub const fn origin(&self) -> FinitePoint3 {
        self.origin
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the radius.
    #[must_use]
    pub const fn radius(&self) -> PositiveLength {
        self.radius
    }
}

impl From<CylinderSurface> for CylinderSurfaceWire {
    fn from(value: CylinderSurface) -> Self {
        Self {
            origin: value.origin().get(),
            axis: *value.frame().axis().as_raw(),
            ref_direction: *value.frame().reference().as_raw(),
            radius: value.radius().get(),
        }
    }
}

impl TryFrom<CylinderSurfaceWire> for CylinderSurface {
    type Error = &'static str;
    fn try_from(wire: CylinderSurfaceWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.origin, wire.axis, wire.ref_direction, wire.radius)
    }
}

/// Elliptical cone with finite parameters and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "ConeSurfaceWire", into = "ConeSurfaceWire")]
pub struct ConeSurface {
    origin: FinitePoint3,
    radius: NonNegativeLength,
    ratio: PositiveReal,
    half_angle: Angle,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct ConeSurfaceWire {
    /// Cone frame origin.
    origin: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Frame reference direction, perpendicular to `axis`.
    ref_direction: Vector3,
    /// Cross-section radius at the origin.
    radius: f64,
    /// Ratio of the minor to the major cross-section radius.
    ratio: f64,
    /// Half angle of the cone, in radians.
    half_angle: f64,
}

impl ConeSurface {
    /// Build a cone from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// One component is replaced and the rest move across unchanged:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::ConeSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    /// use cadmpeg_ir::scalar::NonNegativeLength;
    ///
    /// let cone = ConeSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     3.0,
    ///     1.0,
    ///     0.5,
    /// )
    /// .expect("orthonormal frame, finite origin and admitted dimensions");
    /// let sharpened = ConeSurface::new(
    ///     cone.origin(),
    ///     *cone.frame(),
    ///     NonNegativeLength::new(0.0).expect("zero is a valid cone radius"),
    ///     cone.ratio(),
    ///     cone.half_angle(),
    /// );
    /// assert_eq!(sharpened.radius().get(), 0.0);
    /// assert_eq!(sharpened.half_angle(), cone.half_angle());
    /// ```
    #[must_use]
    pub const fn new(
        origin: FinitePoint3,
        frame: OrthonormalFrame3,
        radius: NonNegativeLength,
        ratio: PositiveReal,
        half_angle: Angle,
    ) -> Self {
        Self {
            origin,
            radius,
            ratio,
            half_angle,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        origin: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        radius: f64,
        ratio: f64,
        half_angle: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, ref_direction)
            .ok_or("ConeSurface.axis/ref_direction must form an orthonormal frame")?;
        let origin = FinitePoint3::new(origin).ok_or("ConeSurface.origin must be finite")?;
        let radius = NonNegativeLength::new(radius)
            .ok_or("ConeSurface.radius must be nonnegative and finite")?;
        let ratio =
            PositiveReal::new(ratio).ok_or("ConeSurface.ratio must be positive and finite")?;
        let half_angle = Angle::new(half_angle).ok_or("ConeSurface.half_angle must be finite")?;
        Ok(Self::new(origin, frame, radius, ratio, half_angle))
    }

    /// Return the origin.
    #[must_use]
    pub const fn origin(&self) -> FinitePoint3 {
        self.origin
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the cross-section radius at the origin. Zero is a valid cone
    /// radius, so the type admits it.
    #[must_use]
    pub const fn radius(&self) -> NonNegativeLength {
        self.radius
    }

    /// Return the ratio of the minor to the major cross-section radius.
    #[must_use]
    pub const fn ratio(&self) -> PositiveReal {
        self.ratio
    }

    /// Return the half angle. The type admits every finite signed angle.
    ///
    /// The angle is the signed radial slope of the parameterization: the
    /// cross-section radius at signed axial distance `v` is
    /// `radius + v * tan(half_angle)`, so a negative half angle shrinks the
    /// cross-section along `+axis`. `(half_angle, axis)` and
    /// `(-half_angle, -axis)` carry the same locus under the parameter change
    /// `(u, v) -> (-u, -v)`, so the sign belongs to the chart the surface's
    /// pcurves use, not to the locus. A reader that prefers a nonnegative
    /// angle therefore flips the axis and the parameters together; the ASM and
    /// Creo readers do this, and the F3D writers read the sign back out to
    /// recover the native axis and the native axial parameter scale.
    ///
    /// Each reader narrows the angle to what its own carrier holds, and the
    /// intervals differ:
    ///
    /// - `[0, pi/2]`: the ASM b-rep and procedural-curve surface readers,
    ///   which build the angle as `atan2(|sine|, |cosine|)`, and the SLDPRT
    ///   b-rep reader, which builds it as `asin(|sine|)`.
    /// - `[0, pi/2)`: the Creo swept-surface reader, whose axial rate is
    ///   nonzero.
    /// - `(0, pi/2)`: the IGES entity 194 reader, the NX reader, the CATIA b2,
    ///   b5, e5 and zero-entity readers, and the Creo positional and legacy
    ///   cone frames.
    /// - Every finite angle: the STEP `CONICAL_SURFACE` reader and the `FCStd`
    ///   b-rep reader, which pass the file's number through unchecked. The STEP
    ///   writer reverses the frame axis and both chart parameters when the
    ///   angle is negative and its magnitude is below `pi/2`.
    ///
    /// Consumers that need a narrower angle state it where they need it: the
    /// F3D patch validator admits `[0, pi/2]` because the ASM cone record
    /// stores the sine and the cosine and folds anything else to a different
    /// angle, and the Creo `ConeEquation` and mirrored-apex witness admit
    /// `[0, pi/2)`.
    #[must_use]
    pub const fn half_angle(&self) -> Angle {
        self.half_angle
    }
}

impl From<ConeSurface> for ConeSurfaceWire {
    fn from(value: ConeSurface) -> Self {
        Self {
            origin: value.origin().get(),
            axis: *value.frame().axis().as_raw(),
            ref_direction: *value.frame().reference().as_raw(),
            radius: value.radius().get(),
            ratio: value.ratio().get(),
            half_angle: value.half_angle().get(),
        }
    }
}

impl TryFrom<ConeSurfaceWire> for ConeSurface {
    type Error = &'static str;
    fn try_from(wire: ConeSurfaceWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.origin,
            wire.axis,
            wire.ref_direction,
            wire.radius,
            wire.ratio,
            wire.half_angle,
        )
    }
}

/// Sphere with a signed nonzero radius and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SphereSurfaceWire", into = "SphereSurfaceWire")]
pub struct SphereSurface {
    center: FinitePoint3,
    radius: NonZeroLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SphereSurfaceWire {
    /// Sphere center.
    center: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Frame reference direction, perpendicular to `axis`.
    ref_direction: Vector3,
    /// Signed sphere radius.
    radius: f64,
}

impl SphereSurface {
    /// Build a sphere from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// A sphere rebuilds from its own parts, and a negative radius stays
    /// negative:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::SphereSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let sphere = SphereSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     -2.0,
    /// )
    /// .expect("orthonormal frame, finite center and nonzero radius");
    /// let moved = SphereSurface::new(sphere.center(), *sphere.frame(), sphere.radius());
    /// assert_eq!(moved, sphere);
    /// assert_eq!(moved.radius().get(), -2.0);
    /// ```
    #[must_use]
    pub const fn new(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        radius: NonZeroLength,
    ) -> Self {
        Self {
            center,
            radius,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        radius: f64,
    ) -> Result<Self, &'static str> {
        let (center, frame) = Self::admit_placement(center, axis, ref_direction)?;
        let radius =
            NonZeroLength::new(radius).ok_or("SphereSurface.radius must be finite and nonzero")?;
        Ok(Self::new(center, frame, radius))
    }

    /// Admit the center and frame around an admitted radius. The frame and
    /// center refusals are those of [`SphereSurface::try_new`].
    pub fn try_with_radius(
        center: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        radius: NonZeroLength,
    ) -> Result<Self, &'static str> {
        let (center, frame) = Self::admit_placement(center, axis, ref_direction)?;
        Ok(Self::new(center, frame, radius))
    }

    fn admit_placement(
        center: Point3,
        axis: Vector3,
        ref_direction: Vector3,
    ) -> Result<(FinitePoint3, OrthonormalFrame3), &'static str> {
        let frame = OrthonormalFrame3::new(axis, ref_direction)
            .ok_or("SphereSurface.axis/ref_direction must form an orthonormal frame")?;
        let center = FinitePoint3::new(center).ok_or("SphereSurface.center must be finite")?;
        Ok((center, frame))
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> FinitePoint3 {
        self.center
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the radius. A sphere radius is signed and nonzero, so the type
    /// admits both signs.
    #[must_use]
    pub const fn radius(&self) -> NonZeroLength {
        self.radius
    }
}

impl From<SphereSurface> for SphereSurfaceWire {
    fn from(value: SphereSurface) -> Self {
        Self {
            center: value.center().get(),
            axis: *value.frame().axis().as_raw(),
            ref_direction: *value.frame().reference().as_raw(),
            radius: value.radius().get(),
        }
    }
}

impl TryFrom<SphereSurfaceWire> for SphereSurface {
    type Error = &'static str;
    fn try_from(wire: SphereSurfaceWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.center, wire.axis, wire.ref_direction, wire.radius)
    }
}

/// Torus with a positive major radius, signed tube radius, and orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "TorusSurfaceWire", into = "TorusSurfaceWire")]
pub struct TorusSurface {
    center: FinitePoint3,
    major_radius: PositiveLength,
    minor_radius: NonZeroLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TorusSurfaceWire {
    /// Torus center.
    center: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Frame reference direction, perpendicular to `axis`.
    ref_direction: Vector3,
    /// Distance from the center to the tube center.
    major_radius: f64,
    /// Signed tube radius.
    minor_radius: f64,
}

impl TorusSurface {
    /// Build a torus from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// The two radii carry different restrictions, so exchanging them does not
    /// compile:
    ///
    /// ```compile_fail
    /// use cadmpeg_ir::geometry::analytic::TorusSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let torus = TorusSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     5.0,
    ///     1.0,
    /// )
    /// .expect("orthonormal frame, finite center and admitted radii");
    /// let swapped = TorusSurface::new(
    ///     torus.center(),
    ///     *torus.frame(),
    ///     torus.minor_radius(),
    ///     torus.major_radius(),
    /// );
    /// ```
    ///
    /// Each radius in its own place does:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::TorusSurface;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let torus = TorusSurface::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     5.0,
    ///     1.0,
    /// )
    /// .expect("orthonormal frame, finite center and admitted radii");
    /// let moved = TorusSurface::new(
    ///     torus.center(),
    ///     *torus.frame(),
    ///     torus.major_radius(),
    ///     torus.minor_radius(),
    /// );
    /// assert_eq!(moved, torus);
    /// ```
    #[must_use]
    pub const fn new(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        major_radius: PositiveLength,
        minor_radius: NonZeroLength,
    ) -> Self {
        Self {
            center,
            major_radius,
            minor_radius,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        major_radius: f64,
        minor_radius: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, ref_direction)
            .ok_or("TorusSurface.axis/ref_direction must form an orthonormal frame")?;
        let center = FinitePoint3::new(center).ok_or("TorusSurface.center must be finite")?;
        let major_radius = PositiveLength::new(major_radius)
            .ok_or("TorusSurface.major_radius must be positive and finite")?;
        let minor_radius = NonZeroLength::new(minor_radius)
            .ok_or("TorusSurface.minor_radius must be finite and nonzero")?;
        Ok(Self::new(center, frame, major_radius, minor_radius))
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> FinitePoint3 {
        self.center
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the major radius.
    #[must_use]
    pub const fn major_radius(&self) -> PositiveLength {
        self.major_radius
    }

    /// Return the minor radius. A torus tube radius is signed and nonzero, so
    /// the type admits both signs.
    #[must_use]
    pub const fn minor_radius(&self) -> NonZeroLength {
        self.minor_radius
    }
}

impl From<TorusSurface> for TorusSurfaceWire {
    fn from(value: TorusSurface) -> Self {
        Self {
            center: value.center().get(),
            axis: *value.frame().axis().as_raw(),
            ref_direction: *value.frame().reference().as_raw(),
            major_radius: value.major_radius().get(),
            minor_radius: value.minor_radius().get(),
        }
    }
}

impl TryFrom<TorusSurfaceWire> for TorusSurface {
    type Error = &'static str;
    fn try_from(wire: TorusSurfaceWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.center,
            wire.axis,
            wire.ref_direction,
            wire.major_radius,
            wire.minor_radius,
        )
    }
}

/// Line with a finite origin and a unit direction.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "LineCurveWire")]
pub struct LineCurve {
    origin: FinitePoint3,
    direction: UnitVector3,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct LineCurveWire {
    /// Line origin.
    origin: Point3,
    /// Line direction.
    direction: Vector3,
}

impl LineCurve {
    /// Reverse the curve parameter direction.
    pub fn reverse_parameterization(&mut self) {
        self.direction = self.direction.reversed();
    }

    /// Build a line from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// A frame hands back an admitted direction, which builds a line along the
    /// axis without a second admission:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::{LineCurve, PlaneSurface};
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let plane = PlaneSurface::try_new(
    ///     Point3::new(1.0, 2.0, 3.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    /// )
    /// .expect("orthonormal frame and finite origin");
    /// let axis_line = LineCurve::new(plane.origin(), *plane.frame().axis());
    /// assert_eq!(axis_line.direction().as_raw(), plane.frame().axis().as_raw());
    /// ```
    ///
    /// A raw direction has no way in:
    ///
    /// ```compile_fail
    /// use cadmpeg_ir::geometry::analytic::LineCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let line = LineCurve::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    /// )
    /// .expect("finite origin and unit direction");
    /// let tilted = LineCurve::new(line.origin(), Vector3::new(1.0, 0.0, 0.0));
    /// ```
    #[must_use]
    pub const fn new(origin: FinitePoint3, direction: UnitVector3) -> Self {
        Self { origin, direction }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(origin: Point3, direction: Vector3) -> Result<Self, &'static str> {
        let origin = FinitePoint3::new(origin).ok_or("LineCurve.origin must be finite")?;
        let direction =
            UnitVector3::new(direction).ok_or("LineCurve.direction must have unit length")?;
        Ok(Self::new(origin, direction))
    }

    /// Return the origin.
    #[must_use]
    pub const fn origin(&self) -> FinitePoint3 {
        self.origin
    }

    /// Return the direction.
    #[must_use]
    pub const fn direction(&self) -> UnitVector3 {
        self.direction
    }
}

impl TryFrom<LineCurveWire> for LineCurve {
    type Error = &'static str;
    fn try_from(wire: LineCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.origin, wire.direction)
    }
}

/// Circle with a positive radius and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "CircleCurveWire", into = "CircleCurveWire")]
pub struct CircleCurve {
    center: FinitePoint3,
    radius: PositiveLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct CircleCurveWire {
    /// Circle center.
    center: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Frame reference direction, perpendicular to `axis`.
    ref_direction: Vector3,
    /// Circle radius.
    radius: f64,
}

impl CircleCurve {
    /// Reverse the curve parameter direction.
    pub fn reverse_parameterization(&mut self) {
        self.frame.reverse_axis();
    }

    /// Build a circle from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// A circle widens on an admitted radius and keeps the rest of its parts:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::CircleCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    /// use cadmpeg_ir::scalar::PositiveLength;
    ///
    /// let circle = CircleCurve::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite center and positive radius");
    /// let wider = CircleCurve::new(
    ///     circle.center(),
    ///     *circle.frame(),
    ///     PositiveLength::new(4.0).expect("positive finite"),
    /// );
    /// assert_eq!(wider.radius().get(), 4.0);
    /// assert_eq!(wider.center(), circle.center());
    /// ```
    #[must_use]
    pub const fn new(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        radius: PositiveLength,
    ) -> Self {
        Self {
            center,
            radius,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point3,
        axis: Vector3,
        ref_direction: Vector3,
        radius: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, ref_direction)
            .ok_or("CircleCurve.axis/ref_direction must form an orthonormal frame")?;
        let center = FinitePoint3::new(center).ok_or("CircleCurve.center must be finite")?;
        let radius =
            PositiveLength::new(radius).ok_or("CircleCurve.radius must be positive and finite")?;
        Ok(Self::new(center, frame, radius))
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> FinitePoint3 {
        self.center
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the radius.
    #[must_use]
    pub const fn radius(&self) -> PositiveLength {
        self.radius
    }
}

impl From<CircleCurve> for CircleCurveWire {
    fn from(value: CircleCurve) -> Self {
        Self {
            center: value.center().get(),
            axis: *value.frame().axis().as_raw(),
            ref_direction: *value.frame().reference().as_raw(),
            radius: value.radius().get(),
        }
    }
}

impl TryFrom<CircleCurveWire> for CircleCurve {
    type Error = &'static str;
    fn try_from(wire: CircleCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.center, wire.axis, wire.ref_direction, wire.radius)
    }
}

/// Ellipse with ordered positive radii and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "EllipseCurveWire", into = "EllipseCurveWire")]
pub struct EllipseCurve {
    center: FinitePoint3,
    radii: OrderedMajorRadius,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct EllipseCurveWire {
    /// Ellipse center.
    center: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Major-axis direction, perpendicular to `axis`.
    major_direction: Vector3,
    /// Major semiaxis radius.
    major_radius: f64,
    /// Minor semiaxis radius.
    minor_radius: f64,
}

impl EllipseCurve {
    /// Reverse the curve parameter direction.
    pub fn reverse_parameterization(&mut self) {
        self.frame.reverse_axis();
    }

    /// Build an ellipse from an admitted center, frame, and ordered radii.
    #[must_use]
    pub const fn new(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        radii: OrderedMajorRadius,
    ) -> Self {
        Self {
            center,
            radii,
            frame,
        }
    }

    /// Build an ellipse from checked parts. Two positive radii do not state
    /// their order, so the remaining relationship is checked here.
    ///
    /// An ellipse rebuilds from its own parts:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::EllipseCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let ellipse = EllipseCurve::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     4.0,
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite center and ordered radii");
    /// let moved = EllipseCurve::try_from_parts(
    ///     ellipse.center(),
    ///     *ellipse.frame(),
    ///     ellipse.major_radius(),
    ///     ellipse.minor_radius(),
    /// )
    /// .expect("the stored radii keep their order");
    /// assert_eq!(moved, ellipse);
    /// ```
    ///
    /// Exchanging them is refused, because the argument types state positivity
    /// and not the order:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::EllipseCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let ellipse = EllipseCurve::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     4.0,
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite center and ordered radii");
    /// assert!(EllipseCurve::try_from_parts(
    ///     ellipse.center(),
    ///     *ellipse.frame(),
    ///     ellipse.minor_radius(),
    ///     ellipse.major_radius(),
    /// )
    /// .is_err());
    /// ```
    pub fn try_from_parts(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        major_radius: PositiveLength,
        minor_radius: PositiveLength,
    ) -> Result<Self, &'static str> {
        let radii = OrderedMajorRadius::new(major_radius, minor_radius)
            .ok_or("EllipseCurve.major_radius must be at least minor_radius")?;
        Ok(Self::new(center, frame, radii))
    }

    /// Build an ellipse from radii stated in a source unit, major then
    /// minor, and the positive scale that converts them.
    ///
    /// The order is read from the source radii, so a source minor radius
    /// above the major one is refused even where the scaled radii round to
    /// one value. Rounding is monotone, so the scaled radii keep the order.
    /// The scaled major radius is admitted positive and finite; the scaled
    /// minor radius is not above it, so only its sign is tested.
    ///
    /// ```
    /// use cadmpeg_ir::features::FinitePoint3;
    /// use cadmpeg_ir::geometry::analytic::EllipseCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    /// use cadmpeg_ir::scalar::PositiveReal;
    /// use cadmpeg_ir::units::OrthonormalFrame3;
    ///
    /// let center = FinitePoint3::new(Point3::new(0.0, 0.0, 0.0)).unwrap();
    /// let frame =
    ///     OrthonormalFrame3::new(Vector3::new(0.0, 0.0, 1.0), Vector3::new(1.0, 0.0, 0.0))
    ///         .unwrap();
    /// let scale = PositiveReal::new(1000.0).unwrap();
    /// let ellipse = EllipseCurve::from_source_radii(center, frame, [0.004, 0.002], scale).unwrap();
    /// assert_eq!(ellipse.major_radius().get(), 4.0);
    /// assert!(EllipseCurve::from_source_radii(center, frame, [0.002, 0.004], scale).is_none());
    /// ```
    #[must_use]
    pub fn from_source_radii(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        radii: [f64; 2],
        scale: PositiveReal,
    ) -> Option<Self> {
        let [major, minor] = radii;
        (minor <= major).then_some(())?;
        let [major_radius, minor_radius] = PositiveLength::scale_ordered_pair(radii, scale).ok()?;
        Some(Self::new(
            center,
            frame,
            OrderedMajorRadius::new(major_radius, minor_radius)?,
        ))
    }

    /// The ellipse with its center and radii times `scale`.
    ///
    /// Rounding is monotone, so a positive scale keeps the radius order; the
    /// radii can round to one value, which the order admits. The scaled
    /// center is refused when a coordinate overflows, then the scaled major
    /// radius when it overflows or rounds to zero, then the scaled minor
    /// radius, which is not above it, when it rounds to zero, each with the
    /// field's own text.
    pub(crate) fn scaled(&self, scale: PositiveReal) -> Result<Self, &'static str> {
        let center = self
            .center
            .scaled(scale)
            .ok_or("EllipseCurve.center must be finite")?;
        let [major_radius, minor_radius] = PositiveLength::scale_ordered_pair(
            [self.radii.major().get(), self.radii.minor().get()],
            scale,
        )
        .map_err(|index| {
            if index == 0 {
                "EllipseCurve.major_radius must be positive and finite"
            } else {
                "EllipseCurve.minor_radius must be positive and finite"
            }
        })?;
        let radii = OrderedMajorRadius::new(major_radius, minor_radius)
            .ok_or("EllipseCurve.major_radius must be at least minor_radius")?;
        Ok(Self::new(center, self.frame, radii))
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point3,
        axis: Vector3,
        major_direction: Vector3,
        major_radius: f64,
        minor_radius: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, major_direction)
            .ok_or("EllipseCurve.axis/major_direction must form an orthonormal frame")?;
        let center = FinitePoint3::new(center).ok_or("EllipseCurve.center must be finite")?;
        let major_radius = PositiveLength::new(major_radius)
            .ok_or("EllipseCurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveLength::new(minor_radius)
            .ok_or("EllipseCurve.minor_radius must be positive and finite")?;
        Self::try_from_parts(center, frame, major_radius, minor_radius)
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> FinitePoint3 {
        self.center
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the ordered radii.
    #[must_use]
    pub const fn radii(&self) -> OrderedMajorRadius {
        self.radii
    }

    /// Return the major radius.
    #[must_use]
    pub const fn major_radius(&self) -> PositiveLength {
        self.radii.major()
    }

    /// Return the minor radius.
    #[must_use]
    pub const fn minor_radius(&self) -> PositiveLength {
        self.radii.minor()
    }
}

impl From<EllipseCurve> for EllipseCurveWire {
    fn from(value: EllipseCurve) -> Self {
        Self {
            center: value.center().get(),
            axis: *value.frame().axis().as_raw(),
            major_direction: *value.frame().reference().as_raw(),
            major_radius: value.major_radius().get(),
            minor_radius: value.minor_radius().get(),
        }
    }
}

impl TryFrom<EllipseCurveWire> for EllipseCurve {
    type Error = &'static str;
    fn try_from(wire: EllipseCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.center,
            wire.axis,
            wire.major_direction,
            wire.major_radius,
            wire.minor_radius,
        )
    }
}

/// Parabola with a positive focal distance and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "ParabolaCurveWire", into = "ParabolaCurveWire")]
pub struct ParabolaCurve {
    vertex: FinitePoint3,
    focal_distance: PositiveLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct ParabolaCurveWire {
    /// Parabola vertex.
    vertex: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Major-axis direction, perpendicular to `axis`.
    major_direction: Vector3,
    /// Distance from the vertex to the focus.
    focal_distance: f64,
}

impl ParabolaCurve {
    /// Build a parabola from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    ///
    /// A parabola rebuilds from its own parts:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::ParabolaCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let parabola = ParabolaCurve::try_new(
    ///     Point3::new(1.0, 2.0, 3.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     2.0,
    /// )
    /// .expect("orthonormal frame, finite vertex and positive focal distance");
    /// let moved = ParabolaCurve::new(
    ///     parabola.vertex(),
    ///     *parabola.frame(),
    ///     parabola.focal_distance(),
    /// );
    /// assert_eq!(moved, parabola);
    /// ```
    #[must_use]
    pub const fn new(
        vertex: FinitePoint3,
        frame: OrthonormalFrame3,
        focal_distance: PositiveLength,
    ) -> Self {
        Self {
            vertex,
            focal_distance,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        vertex: Point3,
        axis: Vector3,
        major_direction: Vector3,
        focal_distance: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, major_direction)
            .ok_or("ParabolaCurve.axis/major_direction must form an orthonormal frame")?;
        let vertex = FinitePoint3::new(vertex).ok_or("ParabolaCurve.vertex must be finite")?;
        let focal_distance = PositiveLength::new(focal_distance)
            .ok_or("ParabolaCurve.focal_distance must be positive and finite")?;
        Ok(Self::new(vertex, frame, focal_distance))
    }

    /// Return the vertex.
    #[must_use]
    pub const fn vertex(&self) -> FinitePoint3 {
        self.vertex
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the focal distance.
    #[must_use]
    pub const fn focal_distance(&self) -> PositiveLength {
        self.focal_distance
    }
}

impl From<ParabolaCurve> for ParabolaCurveWire {
    fn from(value: ParabolaCurve) -> Self {
        Self {
            vertex: value.vertex().get(),
            axis: *value.frame().axis().as_raw(),
            major_direction: *value.frame().reference().as_raw(),
            focal_distance: value.focal_distance().get(),
        }
    }
}

impl TryFrom<ParabolaCurveWire> for ParabolaCurve {
    type Error = &'static str;
    fn try_from(wire: ParabolaCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.vertex,
            wire.axis,
            wire.major_direction,
            wire.focal_distance,
        )
    }
}

/// Hyperbola with positive radii and an orthonormal frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HyperbolaCurveWire", into = "HyperbolaCurveWire")]
pub struct HyperbolaCurve {
    center: FinitePoint3,
    major_radius: PositiveLength,
    minor_radius: PositiveLength,
    frame: OrthonormalFrame3,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HyperbolaCurveWire {
    /// Hyperbola center.
    center: Point3,
    /// Frame axis direction.
    axis: Vector3,
    /// Major-axis direction, perpendicular to `axis`.
    major_direction: Vector3,
    /// Transverse semiaxis radius.
    major_radius: f64,
    /// Conjugate semiaxis radius.
    minor_radius: f64,
}

impl HyperbolaCurve {
    /// Return the opposite branch with unchanged radii.
    #[must_use]
    pub fn opposite_branch(mut self) -> Self {
        self.frame.reverse_reference();
        self
    }

    /// Build a hyperbola from checked parts. The argument types state the whole
    /// invariant, so nothing is checked again. A hyperbola carries no radius
    /// ordering, so two positive radii state everything its fields require.
    ///
    /// A hyperbola rebuilds from its own parts, in either order:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::HyperbolaCurve;
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let hyperbola = HyperbolaCurve::try_new(
    ///     Point3::new(0.0, 0.0, 0.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    ///     Vector3::new(1.0, 0.0, 0.0),
    ///     2.0,
    ///     5.0,
    /// )
    /// .expect("orthonormal frame, finite center and positive radii");
    /// let moved = HyperbolaCurve::new(
    ///     hyperbola.center(),
    ///     *hyperbola.frame(),
    ///     hyperbola.major_radius(),
    ///     hyperbola.minor_radius(),
    /// );
    /// assert_eq!(moved, hyperbola);
    /// assert_eq!(moved.major_radius().get(), 2.0);
    /// ```
    #[must_use]
    pub const fn new(
        center: FinitePoint3,
        frame: OrthonormalFrame3,
        major_radius: PositiveLength,
        minor_radius: PositiveLength,
    ) -> Self {
        Self {
            center,
            major_radius,
            minor_radius,
            frame,
        }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point3,
        axis: Vector3,
        major_direction: Vector3,
        major_radius: f64,
        minor_radius: f64,
    ) -> Result<Self, &'static str> {
        let frame = OrthonormalFrame3::new(axis, major_direction)
            .ok_or("HyperbolaCurve.axis/major_direction must form an orthonormal frame")?;
        let center = FinitePoint3::new(center).ok_or("HyperbolaCurve.center must be finite")?;
        let major_radius = PositiveLength::new(major_radius)
            .ok_or("HyperbolaCurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveLength::new(minor_radius)
            .ok_or("HyperbolaCurve.minor_radius must be positive and finite")?;
        Ok(Self::new(center, frame, major_radius, minor_radius))
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> FinitePoint3 {
        self.center
    }

    /// Return the frame.
    #[must_use]
    pub const fn frame(&self) -> &OrthonormalFrame3 {
        &self.frame
    }

    /// Return the major radius.
    #[must_use]
    pub const fn major_radius(&self) -> PositiveLength {
        self.major_radius
    }

    /// Return the minor radius.
    #[must_use]
    pub const fn minor_radius(&self) -> PositiveLength {
        self.minor_radius
    }
}

impl From<HyperbolaCurve> for HyperbolaCurveWire {
    fn from(value: HyperbolaCurve) -> Self {
        Self {
            center: value.center().get(),
            axis: *value.frame().axis().as_raw(),
            major_direction: *value.frame().reference().as_raw(),
            major_radius: value.major_radius().get(),
            minor_radius: value.minor_radius().get(),
        }
    }
}

impl TryFrom<HyperbolaCurveWire> for HyperbolaCurve {
    type Error = &'static str;
    fn try_from(wire: HyperbolaCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.center,
            wire.axis,
            wire.major_direction,
            wire.major_radius,
            wire.minor_radius,
        )
    }
}

/// Degenerate curve at a finite point.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "DegenerateCurveWire")]
pub struct DegenerateCurve {
    point: FinitePoint3,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct DegenerateCurveWire {
    /// Point the curve degenerates to.
    point: Point3,
}

impl DegenerateCurve {
    /// Build a degenerate curve from a checked point. The argument type states
    /// the whole invariant, so nothing is checked again.
    ///
    /// A line's admitted origin degenerates without readmission:
    ///
    /// ```
    /// use cadmpeg_ir::geometry::analytic::{DegenerateCurve, LineCurve};
    /// use cadmpeg_ir::math::{Point3, Vector3};
    ///
    /// let line = LineCurve::try_new(
    ///     Point3::new(1.0, 2.0, 3.0),
    ///     Vector3::new(0.0, 0.0, 1.0),
    /// )
    /// .expect("finite origin and unit direction");
    /// let degenerate = DegenerateCurve::new(line.origin());
    /// assert_eq!(degenerate.point(), line.origin());
    /// ```
    ///
    /// A raw point has no way in:
    ///
    /// ```compile_fail
    /// use cadmpeg_ir::geometry::analytic::DegenerateCurve;
    /// use cadmpeg_ir::math::Point3;
    ///
    /// let degenerate = DegenerateCurve::new(Point3::new(1.0, 2.0, 3.0));
    /// ```
    #[must_use]
    pub const fn new(point: FinitePoint3) -> Self {
        Self { point }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(point: Point3) -> Result<Self, &'static str> {
        let point = FinitePoint3::new(point).ok_or("DegenerateCurve.point must be finite")?;
        Ok(Self::new(point))
    }

    /// Return the point.
    #[must_use]
    pub const fn point(&self) -> FinitePoint3 {
        self.point
    }
}

impl TryFrom<DegenerateCurveWire> for DegenerateCurve {
    type Error = &'static str;
    fn try_from(wire: DegenerateCurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.point)
    }
}

#[cfg(test)]
mod tests;

mod identity_rewrite;