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
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
// SPDX-License-Identifier: Apache-2.0
//! Neutral planar sketches, solved entities, and geometric constraints.

use crate::math::{Point2, Point3, Vector3};
use crate::transform::Transform;
use crate::{
    features::{FinitePoint3, FiniteVector3, ParameterId},
    scalar::{Angle, FiniteReal, Length, PositiveAngle, PositiveLength, PositiveReal},
    units::{FinitePoint2, UnitVector2, UnitVector3},
};
use cadmpeg_core::text::NonBlankString;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Collection admission or decode resource refusal.
#[derive(Debug, thiserror::Error)]
pub enum SketchCollectionError {
    /// Geometric or collection invariant failure.
    #[error("{0}")]
    Invalid(&'static str),
    /// Storage or work allowance exhausted.
    #[error("resource refusal: {0:?}")]
    Resource(cadmpeg_core::decode::ResourceLimit),
    /// A fallible admission operation could not complete.
    #[error("{0}")]
    Admission(String),
}

impl From<cadmpeg_core::CodecError> for SketchCollectionError {
    fn from(error: cadmpeg_core::CodecError) -> Self {
        match error {
            cadmpeg_core::CodecError::ResourceLimit(limit) => Self::Resource(limit),
            error => Self::Admission(error.to_string()),
        }
    }
}

fn distinct_sketch_members<'id>(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    identities: impl ExactSizeIterator<Item = &'id str>,
    operation: &'static str,
) -> Result<bool, cadmpeg_core::CodecError> {
    // Drop the temporary identities before their storage reservation.
    let (storage, mut members) = {
        let mut values = Vec::new();
        let reservation = ctx.reserve_temporary_vec(&mut values, identities.len(), operation)?;
        (reservation, values)
    };
    for identity in identities {
        ctx.charge_work(1, operation)?;
        let mut low = 0;
        let mut high = members.len();
        while low < high {
            ctx.charge_work(1, operation)?;
            let middle = low + (high - low) / 2;
            let candidate: &str = members[middle];
            ctx.charge_work(
                cadmpeg_core::decode::u64_from_index(candidate.len().min(identity.len())),
                operation,
            )?;
            match candidate.cmp(identity) {
                std::cmp::Ordering::Less => low = middle + 1,
                std::cmp::Ordering::Greater => high = middle,
                std::cmp::Ordering::Equal => return Ok(false),
            }
        }
        ctx.charge_work(
            cadmpeg_core::decode::u64_from_index(members.len() - low),
            operation,
        )?;
        ctx.charge_work(1, operation)?;
        members.insert(low, identity);
    }
    drop(members);
    drop(storage);
    Ok(true)
}

pub mod scaling;

crate::ids::id_type!(
    /// Identifies a neutral planar sketch.
    SketchId, compose, into_string
);
crate::ids::id_type!(
    /// Identifies solved geometry in a sketch.
    SketchEntityId, compose
);
crate::ids::id_type!(
    /// Identifies a neutral spatial sketch.
    SpatialSketchId, compose
);
crate::ids::id_type!(
    /// Identifies solved geometry in a spatial sketch.
    SpatialSketchEntityId, compose
);
crate::ids::id_type!(
    /// Identifies a geometric sketch constraint.
    SketchConstraintId, compose
);

/// Font weight admitted by neutral sketch text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "i32", into = "i32")]
#[repr(i32)]
pub enum SketchFontWeight {
    /// Regular text weight.
    Regular = 400,
    /// Medium text weight.
    Medium = 500,
    /// Bold text weight.
    Bold = 750,
}

impl TryFrom<i32> for SketchFontWeight {
    type Error = &'static str;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        match value {
            400 => Ok(Self::Regular),
            500 => Ok(Self::Medium),
            750 => Ok(Self::Bold),
            _ => Err("sketch text font_weight must be 400, 500, or 750"),
        }
    }
}

impl From<SketchFontWeight> for i32 {
    fn from(value: SketchFontWeight) -> Self {
        match value {
            SketchFontWeight::Regular => 400,
            SketchFontWeight::Medium => 500,
            SketchFontWeight::Bold => 750,
        }
    }
}

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

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({"type": "integer", "enum": [400, 500, 750]})
    }
}

/// Horizontal placement of sketch text about its text anchor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "native_value", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchTextHorizontalAlignment {
    /// Align the text's left edge with its anchor.
    Left,
    /// Center the text about its anchor.
    Center,
    /// Align the text's right edge with its anchor.
    Right,
    /// Source alignment ordinal without an assigned neutral meaning.
    Native(u32),
}

/// Vertical placement of sketch text about its text anchor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "native_value", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchTextVerticalAlignment {
    /// Align the text's top with its anchor.
    Top,
    /// Center the text about its anchor.
    Middle,
    /// Align the text's bottom with its anchor.
    Bottom,
    /// Source alignment ordinal without an assigned neutral meaning.
    Native(u32),
}

/// Canonical reference axis in neutral sketch coordinates.
#[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 SketchAxis {
    /// Positive sketch-u direction.
    Horizontal,
    /// Positive sketch-v direction.
    Vertical,
}

/// A planar sketch and its ordered profile loops.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Sketch {
    /// Globally unique sketch id.
    pub id: SketchId,
    /// Source display name, when recorded.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_name"
    )]
    pub name: Option<String>,
    /// Source configuration key, when scoped.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_configuration"
    )]
    pub configuration: Option<String>,
    /// Source display visibility, when recorded.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_visible"
    )]
    pub visible: Option<bool>,
    /// Placement of sketch coordinates in model space.
    pub placement: SketchPlacement,
    /// Ordered closed or open profile chains.
    #[serde(default, skip_serializing_if = "SketchProfiles::is_empty")]
    pub profiles: SketchProfiles,
    /// Identifier of the full-fidelity native input lane.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// Placement of a planar sketch's local coordinates in model space.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchPlacement {
    /// Local geometry is decoded but its model-space frame is unresolved.
    Unresolved {},
    /// Complete model-space sketch frame.
    Resolved {
        /// Checked origin and nonzero perpendicular axes.
        frame: SketchPlaneFrame,
    },
}

const EPS_SKETCH_PLANE_ORTHOGONALITY: f64 = 1.0e-9;

/// A finite origin with nonzero perpendicular sketch axes.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SketchPlaneFrameWire")]
pub struct SketchPlaneFrame {
    origin: FinitePoint3,
    normal: FiniteVector3,
    u_axis: FiniteVector3,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SketchPlaneFrameWire {
    /// Sketch-plane origin in model space.
    origin: Point3,
    /// Sketch-plane normal.
    normal: Vector3,
    /// In-plane first axis, perpendicular to `normal`.
    u_axis: Vector3,
}

impl TryFrom<SketchPlaneFrameWire> for SketchPlaneFrame {
    type Error = &'static str;

    fn try_from(wire: SketchPlaneFrameWire) -> Result<Self, Self::Error> {
        let normal =
            FiniteVector3::new(wire.normal).ok_or("sketch normal must be finite and nonzero")?;
        let unit_normal = normal
            .unit_nonzero()
            .ok_or("sketch normal must be finite and nonzero")?;
        let u_axis =
            FiniteVector3::new(wire.u_axis).ok_or("sketch u_axis must be finite and nonzero")?;
        let unit_u_axis = u_axis
            .unit_nonzero()
            .ok_or("sketch u_axis must be finite and nonzero")?;
        if unit_normal.dot(unit_u_axis).abs() > EPS_SKETCH_PLANE_ORTHOGONALITY {
            return Err("sketch normal and u_axis must be perpendicular");
        }
        let origin = FinitePoint3::new(wire.origin).ok_or("sketch origin must be finite")?;
        Ok(Self {
            origin,
            normal,
            u_axis,
        })
    }
}

impl SketchPlacement {
    /// Admit a resolved sketch frame with finite origin and nonzero perpendicular axes.
    pub fn try_resolved(
        origin: Point3,
        normal: Vector3,
        u_axis: Vector3,
    ) -> Result<Self, &'static str> {
        Ok(Self::Resolved {
            frame: SketchPlaneFrameWire {
                origin,
                normal,
                u_axis,
            }
            .try_into()?,
        })
    }

    /// Replace the origin of a resolved frame and keep its admitted axes.
    /// The axes alone satisfy the frame contract, so the result needs no new
    /// admission. An unresolved placement has no origin and stays unresolved.
    #[must_use]
    pub fn with_origin(self, origin: FinitePoint3) -> Self {
        match self {
            Self::Unresolved {} => Self::Unresolved {},
            Self::Resolved { frame } => Self::Resolved {
                frame: SketchPlaneFrame { origin, ..frame },
            },
        }
    }

    /// Return the complete frame when placement is resolved.
    pub fn resolved(self) -> Option<(FinitePoint3, FiniteVector3, FiniteVector3)> {
        match self {
            Self::Unresolved {} => None,
            Self::Resolved { frame } => Some((frame.origin, frame.normal, frame.u_axis)),
        }
    }
}

/// An ordered collection of nonempty sketch profile chains.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "Vec<Vec<SketchEntityUse>>")]
pub struct SketchProfiles(Vec<Vec<SketchEntityUse>>);

impl TryFrom<Vec<Vec<SketchEntityUse>>> for SketchProfiles {
    type Error = &'static str;

    fn try_from(profiles: Vec<Vec<SketchEntityUse>>) -> Result<Self, Self::Error> {
        if profiles.iter().any(Vec::is_empty) {
            return Err("sketch profiles must contain no empty chain");
        }
        Ok(Self(profiles))
    }
}

impl std::ops::Deref for SketchProfiles {
    type Target = [Vec<SketchEntityUse>];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> IntoIterator for &'a SketchProfiles {
    type Item = &'a Vec<SketchEntityUse>;
    type IntoIter = std::slice::Iter<'a, Vec<SketchEntityUse>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl IntoIterator for SketchProfiles {
    type Item = Vec<SketchEntityUse>;
    type IntoIter = std::vec::IntoIter<Vec<SketchEntityUse>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl SketchProfiles {
    /// Borrow the ordered nonempty profile chains.
    #[must_use]
    pub fn as_slice(&self) -> &[Vec<SketchEntityUse>] {
        &self.0
    }

    /// Whether the sketch has no profile chains.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Append a profile containing one entity use after resource admission.
    pub fn push_single(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        entity: SketchEntityUse,
    ) -> Result<(), cadmpeg_core::CodecError> {
        const OPERATION: &str = "append sketch profile use";
        ctx.charge_work(2, OPERATION)?;
        let mut profile = Vec::new();
        ctx.reserve_vec(&mut profile, 1, OPERATION)?;
        if self.0.len() == self.0.capacity() {
            ctx.charge_work(
                u64::try_from(self.0.len())
                    .map_err(|_| ctx.refuse_codec_limit(OPERATION, u64::MAX - 1, u64::MAX))?,
                OPERATION,
            )?;
        }
        ctx.reserve_vec(&mut self.0, 1, OPERATION)?;
        profile.push(entity);
        self.0.push(profile);
        Ok(())
    }

    /// Retain matching uses and remove empty chains after every predicate returns.
    pub fn retain_uses(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        mut keep: impl FnMut(&SketchEntityUse) -> bool,
    ) -> Result<(), cadmpeg_core::CodecError> {
        const OPERATION: &str = "filter sketch profile uses";
        let count = self.0.iter().try_fold(0usize, |count, profile| {
            ctx.charge_work(1, OPERATION)?;
            count
                .checked_add(profile.len())
                .ok_or_else(|| ctx.refuse_codec_limit(OPERATION, u64::MAX - 1, u64::MAX))
        })?;
        ctx.charge_work(
            u64::try_from(count)
                .ok()
                .and_then(|count| count.checked_mul(4))
                .ok_or_else(|| ctx.refuse_codec_limit(OPERATION, u64::MAX - 1, u64::MAX))?,
            OPERATION,
        )?;
        let (mut decisions, _decision_storage) = ctx.temporary_vec(count, OPERATION)?;
        for profile in &self.0 {
            for usage in profile {
                ctx.charge_work(
                    u64::try_from(usage.entity.as_str().len())
                        .ok()
                        .and_then(|len| len.checked_add(1))
                        .and_then(|work| work.checked_mul(4))
                        .ok_or_else(|| ctx.refuse_codec_limit(OPERATION, u64::MAX - 1, u64::MAX))?,
                    OPERATION,
                )?;
                decisions.push(keep(usage));
            }
        }
        let mut decision_index = 0;
        for profile in &mut self.0 {
            profile.retain(|_| {
                let decision = decisions[decision_index];
                decision_index += 1;
                decision
            });
        }
        self.0.retain(|profile| !profile.is_empty());
        Ok(())
    }

    /// Append a nonempty profile chain.
    pub fn try_push(&mut self, profile: Vec<SketchEntityUse>) -> Result<(), &'static str> {
        if profile.is_empty() {
            return Err("sketch profile chain must be nonempty");
        }
        self.0.push(profile);
        Ok(())
    }

    /// Replace profile chains only after every edited chain passes admission.
    pub fn edit(
        &mut self,
        edit: impl FnOnce(&mut Vec<Vec<SketchEntityUse>>),
    ) -> Result<(), &'static str> {
        let mut profiles = self.0.clone();
        edit(&mut profiles);
        *self = profiles.try_into()?;
        Ok(())
    }
}

impl Sketch {
    /// Return the complete model-space frame when placement is resolved.
    pub fn resolved_placement(&self) -> Option<(FinitePoint3, FiniteVector3, FiniteVector3)> {
        self.placement.resolved()
    }
}

/// Oriented use of one sketch entity in a profile chain.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchEntityUse {
    /// Referenced sketch entity.
    pub entity: SketchEntityId,
    /// Whether traversal opposes the entity's stored direction.
    #[serde(default)]
    pub reversed: bool,
}

/// Solved geometry belonging to one sketch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchEntity {
    /// Globally unique entity id.
    id: SketchEntityId,
    /// Owning sketch.
    pub sketch: SketchId,
    /// Whether the entity is construction geometry.
    #[serde(default)]
    pub construction: bool,
    /// Source-native geometry record represented by this entity.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
    /// Source-native curve carrier represented by this entity.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_geometry_ref"
    )]
    pub geometry_ref: Option<String>,
    /// Source-native endpoint records in stored entity direction.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub endpoint_refs: Vec<String>,
    /// Solved two-dimensional geometry.
    pub geometry: SketchGeometry,
}

impl SketchEntity {
    /// Construct a sketch entity from its id, owning sketch, and geometry.
    pub fn new(id: SketchEntityId, sketch: SketchId, geometry: SketchGeometry) -> Self {
        Self {
            id,
            sketch,
            construction: false,
            native_ref: None,
            geometry_ref: None,
            endpoint_refs: Vec::new(),
            geometry,
        }
    }

    /// Return the globally unique entity id.
    pub fn id(&self) -> &SketchEntityId {
        &self.id
    }

    /// Set whether this entity is construction geometry.
    #[must_use]
    pub fn with_construction(mut self, construction: bool) -> Self {
        self.construction = construction;
        self
    }

    /// Set the source-native geometry record.
    #[must_use]
    pub fn with_native_ref(mut self, native_ref: Option<String>) -> Self {
        self.native_ref = native_ref;
        self
    }

    /// Set the source-native curve carrier.
    #[must_use]
    pub fn with_geometry_ref(mut self, geometry_ref: Option<String>) -> Self {
        self.geometry_ref = geometry_ref;
        self
    }

    /// Set the source-native endpoint records.
    #[must_use]
    pub fn with_endpoint_refs(mut self, endpoint_refs: Vec<String>) -> Self {
        self.endpoint_refs = endpoint_refs;
        self
    }
}

/// A finite reference-line direction longer than machine epsilon.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct ReferenceLineDirection(FinitePoint2);

impl ReferenceLineDirection {
    /// Admit the direction used by a reference line.
    pub fn new(direction: FinitePoint2) -> Option<Self> {
        (direction.u.hypot(direction.v) > f64::EPSILON).then_some(Self(direction))
    }

    /// Return the direction coordinates.
    pub fn get(self) -> Point2 {
        self.0.get()
    }
}

impl std::ops::Deref for ReferenceLineDirection {
    type Target = Point2;

    fn deref(&self) -> &Point2 {
        self.0.as_raw()
    }
}

/// An ellipse's radii before their numeric relationship is admitted.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct EllipseRadii<L> {
    /// Semi-major radius.
    pub major_radius: L,
    /// Semi-minor radius.
    pub minor_radius: L,
}

/// Positive ellipse radii with a major radius at least the minor radius.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OrderedMajorRadius {
    major: PositiveLength,
    minor: PositiveLength,
}

impl OrderedMajorRadius {
    /// Admit the relation between two positive radii.
    pub fn new(major: PositiveLength, minor: PositiveLength) -> Option<Self> {
        (major.get() >= minor.get()).then_some(Self { major, minor })
    }

    /// Return the major radius.
    pub const fn major(self) -> PositiveLength {
        self.major
    }

    /// Return the minor radius.
    pub const fn minor(self) -> PositiveLength {
        self.minor
    }
}

impl Serialize for OrderedMajorRadius {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut radii = serializer.serialize_struct("EllipseRadii", 2)?;
        radii.serialize_field("major_radius", &self.major)?;
        radii.serialize_field("minor_radius", &self.minor)?;
        radii.end()
    }
}

/// Solved two-dimensional sketch geometry with finite numeric coordinates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(into = "SketchGeometryDefinition"))]
#[serde(try_from = "SketchGeometryDefinition")]
pub struct SketchGeometry(
    SketchGeometryDefinition<
        FinitePoint2,
        PositiveLength,
        FiniteReal,
        PositiveReal,
        ReferenceLineDirection,
        OrderedMajorRadius,
    >,
);

impl SketchGeometry {
    /// Copy geometry after charging each retained nested allocation.
    pub fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        use SketchGeometryDefinition as Definition;
        ctx.charge_work(1, operation)?;
        let definition = match self.definition() {
            Definition::Nurbs { curve } => Definition::Nurbs {
                curve: curve.try_clone_for_decode(ctx, operation)?,
            },
            Definition::Text {
                text,
                font_family,
                font_weight,
                height,
                width_factor,
                placement,
                horizontal_alignment,
                vertical_alignment,
            } => Definition::Text {
                text: text.try_clone_for_decode(ctx, operation)?,
                font_family: font_family.try_clone_for_decode(ctx, operation)?,
                font_weight: *font_weight,
                height: *height,
                width_factor: *width_factor,
                placement: *placement,
                horizontal_alignment: *horizontal_alignment,
                vertical_alignment: *vertical_alignment,
            },
            Definition::ExternalReference {
                document,
                object,
                subelements,
            } => {
                let document = document
                    .as_deref()
                    .map(|document| ctx.copy_retained_text(document, operation))
                    .transpose()?;
                let object = object.try_clone_for_decode(ctx, operation)?;
                let mut copied_subelements = Vec::new();
                ctx.reserve_vec(&mut copied_subelements, subelements.len(), operation)?;
                ctx.charge_work(
                    cadmpeg_core::decode::u64_from_index(subelements.len()),
                    operation,
                )?;
                for subelement in subelements {
                    copied_subelements.push(ctx.copy_retained_text(subelement, operation)?);
                }
                Definition::ExternalReference {
                    document,
                    object,
                    subelements: copied_subelements,
                }
            }
            Definition::Native { native_kind } => Definition::Native {
                native_kind: native_kind.try_clone_for_decode(ctx, operation)?,
            },
            Definition::Point { .. }
            | Definition::Line { .. }
            | Definition::ReferenceLine { .. }
            | Definition::Circle { .. }
            | Definition::Arc { .. }
            | Definition::Ellipse { .. }
            | Definition::Hyperbola { .. }
            | Definition::Parabola { .. } => return Ok(self.clone()),
        };
        Ok(Self::from_admitted_definition(definition))
    }

    /// Build from a definition whose field types already carry the admitted invariants.
    #[must_use]
    pub fn from_admitted_definition(
        definition: SketchGeometryDefinition<
            FinitePoint2,
            PositiveLength,
            FiniteReal,
            PositiveReal,
            ReferenceLineDirection,
            OrderedMajorRadius,
        >,
    ) -> Self {
        Self(definition)
    }

    /// Retain source-native geometry without solved numeric fields.
    #[must_use]
    pub fn native(native_kind: NonBlankString) -> Self {
        Self(SketchGeometryDefinition::Native { native_kind })
    }

    /// Admit an already checked planar NURBS curve.
    #[must_use]
    pub fn nurbs(curve: crate::geometry::pcurve::PcurveNurbs) -> Self {
        Self(SketchGeometryDefinition::Nurbs { curve })
    }

    /// Build the geometry from an admitted definition. The field types
    /// state finiteness and positivity, so only the conditions between
    /// fields are tested: a reference-line direction longer than machine
    /// epsilon and an ellipse major radius at least its minor radius.
    pub fn from_parts(
        definition: SketchGeometryDefinition<
            FinitePoint2,
            PositiveLength,
            FiniteReal,
            PositiveReal,
        >,
    ) -> Result<Self, &'static str> {
        use SketchGeometryDefinition as Definition;
        Ok(Self(match definition {
            Definition::Point { position } => Definition::Point { position },
            Definition::Line { start, end } => Definition::Line { start, end },
            Definition::ReferenceLine { origin, direction } => Definition::ReferenceLine {
                origin,
                direction: ReferenceLineDirection::new(direction).ok_or(
                    "sketch reference line requires finite origin and nonzero finite direction",
                )?,
            },
            Definition::Circle { center, radius } => Definition::Circle { center, radius },
            Definition::Arc {
                center,
                radius,
                start_angle,
                end_angle,
            } => Definition::Arc {
                center,
                radius,
                start_angle,
                end_angle,
            },
            Definition::Ellipse {
                center,
                major_angle,
                radii,
                bounds,
            } => Definition::Ellipse {
                center,
                major_angle,
                radii: OrderedMajorRadius::new(radii.major_radius, radii.minor_radius)
                    .ok_or("sketch ellipse major_radius must be at least minor_radius")?,
                bounds,
            },
            Definition::Hyperbola {
                center,
                major_angle,
                major_radius,
                minor_radius,
                bounds,
            } => Definition::Hyperbola {
                center,
                major_angle,
                major_radius,
                minor_radius,
                bounds,
            },
            Definition::Parabola {
                vertex,
                axis_angle,
                focal_length,
                bounds,
            } => Definition::Parabola {
                vertex,
                axis_angle,
                focal_length,
                bounds,
            },
            Definition::Nurbs { curve } => Definition::Nurbs { curve },
            Definition::Text {
                text,
                font_family,
                font_weight,
                height,
                width_factor,
                placement,
                horizontal_alignment,
                vertical_alignment,
            } => Definition::Text {
                text,
                font_family,
                font_weight,
                height,
                width_factor,
                placement,
                horizontal_alignment,
                vertical_alignment,
            },
            Definition::ExternalReference {
                document,
                object,
                subelements,
            } => Definition::ExternalReference {
                document,
                object,
                subelements,
            },
            Definition::Native { native_kind } => Definition::Native { native_kind },
        }))
    }

    /// Borrow the admitted geometry definition.
    #[must_use]
    pub fn definition(
        &self,
    ) -> &SketchGeometryDefinition<
        FinitePoint2,
        PositiveLength,
        FiniteReal,
        PositiveReal,
        ReferenceLineDirection,
        OrderedMajorRadius,
    > {
        &self.0
    }

    /// Extract the admitted definition.
    #[must_use]
    pub fn into_definition(
        self,
    ) -> SketchGeometryDefinition<
        FinitePoint2,
        PositiveLength,
        FiniteReal,
        PositiveReal,
        ReferenceLineDirection,
        OrderedMajorRadius,
    > {
        self.0
    }
}

impl
    SketchGeometryDefinition<
        FinitePoint2,
        PositiveLength,
        FiniteReal,
        PositiveReal,
        ReferenceLineDirection,
        OrderedMajorRadius,
    >
{
    /// The definition with raw points, lengths, bounds and width factor.
    #[must_use]
    pub fn to_raw(&self) -> SketchGeometryDefinition {
        use SketchGeometryDefinition as Definition;
        match self {
            Self::Point { position } => Definition::Point {
                position: position.get(),
            },
            Self::Line { start, end } => Definition::Line {
                start: start.get(),
                end: end.get(),
            },
            Self::ReferenceLine { origin, direction } => Definition::ReferenceLine {
                origin: origin.get(),
                direction: direction.get(),
            },
            Self::Circle { center, radius } => Definition::Circle {
                center: center.get(),
                radius: Length::from(*radius),
            },
            Self::Arc {
                center,
                radius,
                start_angle,
                end_angle,
            } => Definition::Arc {
                center: center.get(),
                radius: Length::from(*radius),
                start_angle: *start_angle,
                end_angle: *end_angle,
            },
            Self::Ellipse {
                center,
                major_angle,
                radii,
                bounds,
            } => Definition::Ellipse {
                center: center.get(),
                major_angle: *major_angle,
                radii: EllipseRadii {
                    major_radius: Length::from(radii.major()),
                    minor_radius: Length::from(radii.minor()),
                },
                bounds: *bounds,
            },
            Self::Hyperbola {
                center,
                major_angle,
                major_radius,
                minor_radius,
                bounds,
            } => Definition::Hyperbola {
                center: center.get(),
                major_angle: *major_angle,
                major_radius: Length::from(*major_radius),
                minor_radius: Length::from(*minor_radius),
                bounds: bounds.map(FiniteReal::raw_array),
            },
            Self::Parabola {
                vertex,
                axis_angle,
                focal_length,
                bounds,
            } => Definition::Parabola {
                vertex: vertex.get(),
                axis_angle: *axis_angle,
                focal_length: Length::from(*focal_length),
                bounds: bounds.map(FiniteReal::raw_array),
            },
            Self::Nurbs { curve } => Definition::Nurbs {
                curve: curve.clone(),
            },
            Self::Text {
                text,
                font_family,
                font_weight,
                height,
                width_factor,
                placement,
                horizontal_alignment,
                vertical_alignment,
            } => Definition::Text {
                text: text.clone(),
                font_family: font_family.clone(),
                font_weight: *font_weight,
                height: Length::from(*height),
                width_factor: width_factor.map(PositiveReal::get),
                placement: placement.map(|placement| TextPlacement {
                    anchor: placement.anchor.get(),
                    rotation: placement.rotation,
                }),
                horizontal_alignment: *horizontal_alignment,
                vertical_alignment: *vertical_alignment,
            },
            Self::ExternalReference {
                document,
                object,
                subelements,
            } => Definition::ExternalReference {
                document: document.clone(),
                object: object.clone(),
                subelements: subelements.clone(),
            },
            Self::Native { native_kind } => Definition::Native {
                native_kind: native_kind.clone(),
            },
        }
    }
}

/// Admit a sketch point, or refuse it with `message`.
fn admit_sketch_point(point: Point2, message: &'static str) -> Result<FinitePoint2, &'static str> {
    FinitePoint2::new(point).ok_or(message)
}

/// Admit a positive sketch length, or refuse it with `message`.
fn admit_sketch_length(
    length: Length,
    message: &'static str,
) -> Result<PositiveLength, &'static str> {
    PositiveLength::try_from(length).map_err(|_| message)
}

/// Admit optional finite bounds, or refuse them with `message`.
fn admit_sketch_bounds(
    bounds: Option<[f64; 2]>,
    message: &'static str,
) -> Result<Option<[FiniteReal; 2]>, &'static str> {
    bounds
        .map(|bounds| FiniteReal::array(bounds).ok_or(message))
        .transpose()
}

impl TryFrom<SketchGeometryDefinition> for SketchGeometry {
    type Error = &'static str;

    fn try_from(definition: SketchGeometryDefinition) -> Result<Self, Self::Error> {
        use SketchGeometryDefinition as Definition;
        const CIRCULAR: &str =
            "sketch circular geometry requires finite center and positive finite radius";
        Self::from_parts(match definition {
            Definition::Point { position } => Definition::Point {
                position: admit_sketch_point(position, "sketch point position must be finite")?,
            },
            Definition::Line { start, end } => {
                const LINE: &str = "sketch line endpoints must be finite";
                Definition::Line {
                    start: admit_sketch_point(start, LINE)?,
                    end: admit_sketch_point(end, LINE)?,
                }
            }
            Definition::ReferenceLine { origin, direction } => {
                const REFERENCE: &str =
                    "sketch reference line requires finite origin and nonzero finite direction";
                Definition::ReferenceLine {
                    origin: admit_sketch_point(origin, REFERENCE)?,
                    direction: admit_sketch_point(direction, REFERENCE)?,
                }
            }
            Definition::Circle { center, radius } => Definition::Circle {
                center: admit_sketch_point(center, CIRCULAR)?,
                radius: admit_sketch_length(radius, CIRCULAR)?,
            },
            Definition::Arc {
                center,
                radius,
                start_angle,
                end_angle,
            } => Definition::Arc {
                center: admit_sketch_point(center, CIRCULAR)?,
                radius: admit_sketch_length(radius, CIRCULAR)?,
                start_angle,
                end_angle,
            },
            Definition::Ellipse {
                center,
                major_angle,
                radii,
                bounds,
            } => {
                const RADII: &str = "sketch ellipse radii must be positive and finite";
                Definition::Ellipse {
                    center: admit_sketch_point(
                        center,
                        "sketch ellipse center and major_angle must be finite",
                    )?,
                    major_angle,
                    radii: EllipseRadii {
                        major_radius: admit_sketch_length(radii.major_radius, RADII)?,
                        minor_radius: admit_sketch_length(radii.minor_radius, RADII)?,
                    },
                    bounds,
                }
            }
            Definition::Hyperbola {
                center,
                major_angle,
                major_radius,
                minor_radius,
                bounds,
            } => {
                const RADII: &str = "sketch hyperbola radii must be positive and finite";
                Definition::Hyperbola {
                    center: admit_sketch_point(
                        center,
                        "sketch hyperbola center and major_angle must be finite",
                    )?,
                    major_angle,
                    major_radius: admit_sketch_length(major_radius, RADII)?,
                    minor_radius: admit_sketch_length(minor_radius, RADII)?,
                    bounds: admit_sketch_bounds(bounds, "sketch hyperbola bounds must be finite")?,
                }
            }
            Definition::Parabola {
                vertex,
                axis_angle,
                focal_length,
                bounds,
            } => Definition::Parabola {
                vertex: admit_sketch_point(
                    vertex,
                    "sketch parabola vertex and axis_angle must be finite",
                )?,
                axis_angle,
                focal_length: admit_sketch_length(
                    focal_length,
                    "sketch parabola focal_length must be positive and finite",
                )?,
                bounds: admit_sketch_bounds(bounds, "sketch parabola bounds must be finite")?,
            },
            Definition::Nurbs { curve } => Definition::Nurbs { curve },
            Definition::Text {
                text,
                font_family,
                font_weight,
                height,
                width_factor,
                placement,
                horizontal_alignment,
                vertical_alignment,
            } => Definition::Text {
                text,
                font_family,
                font_weight,
                height: admit_sketch_length(
                    height,
                    "sketch text height must be positive and finite",
                )?,
                width_factor: width_factor
                    .map(|value| {
                        PositiveReal::new(value)
                            .ok_or("sketch text width_factor must be positive and finite")
                    })
                    .transpose()?,
                placement: placement
                    .map(|placement| {
                        Ok::<_, &'static str>(TextPlacement {
                            anchor: admit_sketch_point(
                                placement.anchor,
                                "sketch text anchor and rotation must be finite",
                            )?,
                            rotation: placement.rotation,
                        })
                    })
                    .transpose()?,
                horizontal_alignment,
                vertical_alignment,
            },
            Definition::ExternalReference {
                document,
                object,
                subelements,
            } => Definition::ExternalReference {
                document,
                object,
                subelements,
            },
            Definition::Native { native_kind } => Definition::Native { native_kind },
        })
    }
}

/// Definition admitted by a solved two-dimensional sketch geometry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(bound(
    deserialize = "P: Deserialize<'de>, L: Deserialize<'de>, R: Deserialize<'de>, W: Deserialize<'de>, D: Deserialize<'de>, M: Deserialize<'de>"
))]
pub enum SketchGeometryDefinition<
    P = Point2,
    L = Length,
    R = f64,
    W = f64,
    D = P,
    M = EllipseRadii<L>,
> {
    /// Isolated point.
    Point {
        /// Solved point position.
        position: P,
    },
    /// Bounded line segment.
    Line {
        /// Segment start.
        start: P,
        /// Segment end.
        end: P,
    },
    /// Unbounded construction or reference line.
    ReferenceLine {
        /// Point on the line.
        origin: P,
        /// Non-zero direction in sketch coordinates.
        direction: D,
    },
    /// Full circle.
    Circle {
        /// Circle center.
        center: P,
        /// Circle radius.
        radius: L,
    },
    /// Circular arc with angles in radians.
    Arc {
        /// Arc center.
        center: P,
        /// Arc radius.
        radius: L,
        /// Start angle.
        start_angle: Angle,
        /// End angle.
        end_angle: Angle,
    },
    /// Full or bounded ellipse.
    Ellipse {
        /// Ellipse center.
        center: P,
        /// Major-axis angle in sketch coordinates.
        major_angle: Angle,
        /// Semi-major and semi-minor radii.
        #[serde(flatten)]
        radii: M,
        /// Parameter bounds for an arc; absent for a full ellipse.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_bounds"
        )]
        bounds: Option<[Angle; 2]>,
    },
    /// Full or bounded hyperbola.
    Hyperbola {
        /// Hyperbola center.
        center: P,
        /// Major-axis angle in sketch coordinates.
        major_angle: Angle,
        /// Semi-major radius.
        major_radius: L,
        /// Semi-minor radius.
        minor_radius: L,
        /// Parameter bounds for a branch; absent for the full curve.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_sketch_geometry_definition_bounds"
        )]
        bounds: Option<[R; 2]>,
    },
    /// Full or bounded parabola.
    Parabola {
        /// Parabola vertex.
        vertex: P,
        /// Symmetry-axis angle in sketch coordinates.
        axis_angle: Angle,
        /// Distance from the vertex to the focus.
        focal_length: L,
        /// Bounds on the local transverse coordinate `y`, in sketch length units.
        /// The axial coordinate is `x = y² / (4 * focal_length)`.
        /// Absent for the full curve.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_sketch_geometry_definition_bounds"
        )]
        bounds: Option<[R; 2]>,
    },
    /// NURBS curve in sketch coordinates.
    Nurbs {
        /// Checked two-dimensional knot, pole, and weight payload.
        curve: crate::geometry::pcurve::PcurveNurbs,
    },
    /// Text placed in sketch coordinates.
    Text {
        /// Unicode text content.
        text: NonBlankString,
        /// Source font-family name.
        font_family: NonBlankString,
        /// Font weight from the source text style.
        font_weight: SketchFontWeight,
        /// Nominal character height.
        height: L,
        /// Horizontal scale relative to the nominal font width, absent when the
        /// source stores none.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_width_factor"
        )]
        width_factor: Option<W>,
        /// Text placement in sketch coordinates, absent when the source stores none.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_placement"
        )]
        placement: Option<TextPlacement<P>>,
        /// Horizontal placement about the text anchor, when the source class
        /// carries an alignment enum.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_horizontal_alignment"
        )]
        horizontal_alignment: Option<SketchTextHorizontalAlignment>,
        /// Vertical placement about the text anchor, when the source class
        /// carries an alignment enum.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_vertical_alignment"
        )]
        vertical_alignment: Option<SketchTextVerticalAlignment>,
    },
    /// Geometry referenced from another object when no solved sketch-space carrier is stored.
    ExternalReference {
        /// External document identity, absent for a reference within the current document.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_document"
        )]
        document: Option<String>,
        /// Referenced object identity.
        #[serde(deserialize_with = "deserialize_object")]
        object: NonBlankString,
        /// Ordered source subelement selectors.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        subelements: Vec<String>,
    },
    /// Source-native geometry not yet reduced to a neutral family.
    Native {
        /// Source geometry family.
        #[serde(deserialize_with = "deserialize_native_kind")]
        native_kind: NonBlankString,
    },
}

/// Placement of sketch text about one anchor point.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextPlacement<P = Point2> {
    /// Point the text is placed and rotated about, in sketch coordinates.
    pub anchor: P,
    /// Counterclockwise rotation from the sketch u axis.
    pub rotation: Angle,
}

/// A sketch whose solved geometry is expressed directly in model space.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpatialSketch {
    /// Globally unique spatial-sketch id.
    pub id: SpatialSketchId,
    /// Source display name, when recorded.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_name"
    )]
    pub name: Option<String>,
    /// Source configuration key, when scoped.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_configuration"
    )]
    pub configuration: Option<String>,
    /// Source display visibility, when recorded.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_visible"
    )]
    pub visible: Option<bool>,
    /// Ordered closed profile loops with profile-local planes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub profiles: Vec<SpatialSketchProfile>,
    /// Identifier of the full-fidelity native input lane.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

const EPS_SPATIAL_PROFILE_FRAME: f64 = 1.0e-9;
const SPATIAL_PROFILE_AXES_ERROR: &str =
    "spatial profile normal and u_axis must be unit and orthogonal";

/// One closed spatial-sketch profile and its admitted model-space plane.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SpatialSketchProfileWire")]
pub struct SpatialSketchProfile {
    origin: FinitePoint3,
    normal: UnitVector3,
    u_axis: UnitVector3,
    boundary: Vec<SpatialSketchEntityUse>,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SpatialSketchProfileWire {
    /// Profile-plane origin in model space.
    origin: Point3,
    /// Profile-plane unit normal.
    normal: Vector3,
    /// Profile-plane unit u-axis.
    u_axis: Vector3,
    /// Ordered oriented boundary uses.
    boundary: Vec<SpatialSketchEntityUse>,
}

impl TryFrom<SpatialSketchProfileWire> for SpatialSketchProfile {
    type Error = SketchCollectionError;

    fn try_from(wire: SpatialSketchProfileWire) -> Result<Self, Self::Error> {
        let origin = FinitePoint3::new(wire.origin).ok_or(SketchCollectionError::Invalid(
            "spatial profile origin must be finite",
        ))?;
        let normal = UnitVector3::new(wire.normal)
            .ok_or(SketchCollectionError::Invalid(SPATIAL_PROFILE_AXES_ERROR))?;
        let u_axis = UnitVector3::new(wire.u_axis)
            .ok_or(SketchCollectionError::Invalid(SPATIAL_PROFILE_AXES_ERROR))?;
        let [n, u] = [normal.as_raw(), u_axis.as_raw()];
        if (n.x * u.x + n.y * u.y + n.z * u.z).abs() > EPS_SPATIAL_PROFILE_FRAME {
            return Err(SketchCollectionError::Invalid(SPATIAL_PROFILE_AXES_ERROR));
        }
        let invalid = "spatial profile boundary must be nonempty and contain distinct entities";
        if wire.boundary.is_empty() {
            return Err(SketchCollectionError::Invalid(invalid));
        }
        let mut members = std::collections::HashSet::new();
        members
            .try_reserve(wire.boundary.len())
            .map_err(|error| SketchCollectionError::Admission(error.to_string()))?;
        for use_ in &wire.boundary {
            if !members.insert(&use_.entity) {
                return Err(SketchCollectionError::Invalid(invalid));
            }
        }
        Ok(Self {
            origin,
            normal,
            u_axis,
            boundary: wire.boundary,
        })
    }
}

impl SpatialSketchProfile {
    /// Build a decoded profile through the shared typed-parts admission body.
    pub fn try_new(
        origin: Point3,
        normal: Vector3,
        u_axis: Vector3,
        boundary: Vec<SpatialSketchEntityUse>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::CodecError> {
        let Some(origin) = FinitePoint3::new(origin) else {
            return Ok(Err("spatial profile origin must be finite"));
        };
        let Some(normal) = UnitVector3::new(normal) else {
            return Ok(Err(SPATIAL_PROFILE_AXES_ERROR));
        };
        let Some(u_axis) = UnitVector3::new(u_axis) else {
            return Ok(Err(SPATIAL_PROFILE_AXES_ERROR));
        };
        Self::from_parts(origin, normal, u_axis, boundary, ctx, operation)
    }

    /// Admit typed plane controls and charge temporary uniqueness storage.
    pub fn from_parts(
        origin: FinitePoint3,
        normal: UnitVector3,
        u_axis: UnitVector3,
        boundary: Vec<SpatialSketchEntityUse>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::CodecError> {
        let [n, u] = [normal.as_raw(), u_axis.as_raw()];
        ctx.charge_work(1, operation)?;
        let dot = n.x * u.x + n.y * u.y + n.z * u.z;
        if dot.abs() > EPS_SPATIAL_PROFILE_FRAME {
            return Ok(Err(SPATIAL_PROFILE_AXES_ERROR));
        }
        if boundary.is_empty() {
            return Ok(Err(
                "spatial profile boundary must be nonempty and contain distinct entities",
            ));
        }
        if !distinct_sketch_members(
            ctx,
            boundary.iter().map(|use_| use_.entity.as_str()),
            operation,
        )? {
            return Ok(Err(
                "spatial profile boundary must be nonempty and contain distinct entities",
            ));
        }
        Ok(Ok(Self {
            origin,
            normal,
            u_axis,
            boundary,
        }))
    }

    /// Profile-plane origin in model space.
    #[must_use]
    pub fn origin(&self) -> FinitePoint3 {
        self.origin
    }

    /// Profile-plane unit normal.
    #[must_use]
    pub fn normal(&self) -> UnitVector3 {
        self.normal
    }

    /// Profile-plane unit u-axis.
    #[must_use]
    pub fn u_axis(&self) -> UnitVector3 {
        self.u_axis
    }

    /// Ordered oriented boundary uses.
    #[must_use]
    pub fn boundary(&self) -> &[SpatialSketchEntityUse] {
        &self.boundary
    }

    /// Replace the origin after finite-coordinate admission.
    pub fn set_origin(&mut self, origin: Point3) -> Result<(), &'static str> {
        self.origin = FinitePoint3::new(origin).ok_or("spatial profile origin must be finite")?;
        Ok(())
    }
}

/// Oriented use of one spatial-sketch entity in a profile boundary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpatialSketchEntityUse {
    /// Referenced spatial-sketch entity.
    pub entity: SpatialSketchEntityId,
    /// Whether traversal opposes the entity's stored direction.
    #[serde(default)]
    pub reversed: bool,
}

/// Solved model-space geometry belonging to one spatial sketch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpatialSketchEntity {
    /// Globally unique spatial entity id.
    id: SpatialSketchEntityId,
    /// Owning spatial sketch.
    pub sketch: SpatialSketchId,
    /// Whether the entity is construction geometry.
    #[serde(default)]
    pub construction: bool,
    /// Source-native geometry record represented by this entity.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
    /// Source-native curve carrier represented by this entity.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_geometry_ref"
    )]
    pub geometry_ref: Option<String>,
    /// Source-native endpoint records in stored entity direction.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub endpoint_refs: Vec<String>,
    /// Solved model-space geometry.
    pub geometry: SpatialSketchGeometry,
}

impl SpatialSketchEntity {
    /// Construct a spatial sketch entity from its id, owning sketch, and geometry.
    pub fn new(
        id: SpatialSketchEntityId,
        sketch: SpatialSketchId,
        geometry: SpatialSketchGeometry,
    ) -> Self {
        Self {
            id,
            sketch,
            construction: false,
            native_ref: None,
            geometry_ref: None,
            endpoint_refs: Vec::new(),
            geometry,
        }
    }

    /// Return the globally unique spatial entity id.
    pub fn id(&self) -> &SpatialSketchEntityId {
        &self.id
    }

    /// Set whether this entity is construction geometry.
    #[must_use]
    pub fn with_construction(mut self, construction: bool) -> Self {
        self.construction = construction;
        self
    }

    /// Set the source-native geometry record.
    #[must_use]
    pub fn with_native_ref(mut self, native_ref: Option<String>) -> Self {
        self.native_ref = native_ref;
        self
    }

    /// Set the source-native curve carrier.
    #[must_use]
    pub fn with_geometry_ref(mut self, geometry_ref: Option<String>) -> Self {
        self.geometry_ref = geometry_ref;
        self
    }

    /// Set the source-native endpoint records.
    #[must_use]
    pub fn with_endpoint_refs(mut self, endpoint_refs: Vec<String>) -> Self {
        self.endpoint_refs = endpoint_refs;
        self
    }
}

/// One geometric relation owned by a spatial sketch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpatialSketchConstraint {
    /// Globally unique constraint id.
    pub id: SketchConstraintId,
    /// Owning spatial sketch.
    pub sketch: SpatialSketchId,
    /// Neutral relation semantics.
    pub definition: SpatialSketchConstraintDefinition,
    /// Source-native relation represented by this constraint.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// One unordered entity pair in a repeated model-space sketch relation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SpatialSketchEntityPair {
    /// First member in source discovery order.
    pub first: SpatialSketchEntityId,
    /// Second member in source discovery order.
    pub second: SpatialSketchEntityId,
}

/// A spatial sketch constraint with admitted local members and scalar values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(into = "SpatialSketchConstraintDefinitionInput")
)]
#[serde(try_from = "SpatialSketchConstraintDefinitionInput")]
pub struct SpatialSketchConstraintDefinition(
    SpatialSketchConstraintDefinitionInput<UnitVector3, PositiveLength>,
);

impl SpatialSketchConstraintDefinition {
    /// Borrow the admitted spatial constraint kind.
    #[must_use]
    pub fn kind(&self) -> &SpatialSketchConstraintDefinitionInput<UnitVector3, PositiveLength> {
        &self.0
    }

    /// Edit the raw kind and replace it only after all edited local
    /// invariants pass.
    pub fn edit<R>(
        &mut self,
        edit: impl FnOnce(&mut SpatialSketchConstraintDefinitionInput) -> R,
    ) -> Result<R, &'static str> {
        let mut kind = self.0.to_raw();
        let result = edit(&mut kind);
        *self = kind.try_into()?;
        Ok(result)
    }
}

impl TryFrom<SpatialSketchConstraintDefinitionInput> for SpatialSketchConstraintDefinition {
    type Error = &'static str;

    fn try_from(kind: SpatialSketchConstraintDefinitionInput) -> Result<Self, Self::Error> {
        use SpatialSketchConstraintDefinitionInput as Kind;
        const INVALID: &str = "invalid spatial sketch constraint local arity or scalar value";
        let kind = kind.map_values(
            |direction| UnitVector3::new(direction).ok_or(INVALID),
            |distance| PositiveLength::try_from(distance).map_err(|_| INVALID),
        )?;
        let valid = match &kind {
            Kind::Native { operands, .. } => !operands.is_empty(),
            Kind::LineLength { .. } => true,
            Kind::Coincident { first, second }
            | Kind::Tangent { first, second }
            | Kind::PointDistance { first, second, .. }
            | Kind::ParallelLineDistance { first, second, .. } => first != second,
            Kind::Symmetric {
                first,
                second,
                axis,
            } => first != second && first != axis && second != axis,
            Kind::PointOnSurface { point, surface } => point != surface,
            Kind::Midpoint { point, entity } => point != entity,
            Kind::PointLineDistance { point, line, .. } => point != line,
            Kind::RepeatedLineLength { entities, .. } | Kind::SplineGroup { entities } => {
                entities.len() >= 2
                    && entities
                        .iter()
                        .collect::<std::collections::HashSet<_>>()
                        .len()
                        == entities.len()
            }
            Kind::RepeatedParallelLineDistance { pairs, .. } => {
                let mut entities = std::collections::HashSet::new();
                pairs.len() >= 2
                    && pairs
                        .iter()
                        .all(|pair| entities.insert(&pair.first) && entities.insert(&pair.second))
            }
            Kind::ParallelLineSetDistance { first, second, .. } => {
                !first.is_empty()
                    && !second.is_empty()
                    && (first.len() > 1 || second.len() > 1)
                    && first
                        .iter()
                        .chain(second)
                        .collect::<std::collections::HashSet<_>>()
                        .len()
                        == first.len() + second.len()
            }
            Kind::Offset {
                sources, results, ..
            } => {
                !sources.is_empty()
                    && !results.is_empty()
                    && sources
                        .iter()
                        .chain(results)
                        .collect::<std::collections::HashSet<_>>()
                        .len()
                        == sources.len() + results.len()
            }
            Kind::ParallelToDirection { .. } => true,
        };
        if !valid {
            return Err(INVALID);
        }
        Ok(Self(kind))
    }
}

/// Neutral geometric relations between model-space sketch entities.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SpatialSketchConstraintDefinitionInput<U = Vector3, L = crate::scalar::Length> {
    /// Source-native spatial relation without complete neutral semantics.
    Native {
        /// Source relation family.
        #[serde(deserialize_with = "deserialize_native_kind")]
        native_kind: NonBlankString,
        /// Source relation state or subtype discriminator, when present.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_native_state"
        )]
        native_state: Option<u64>,
        /// Neutral parameter driving the relation, when resolved.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_parameter"
        )]
        parameter: Option<crate::features::ParameterId>,
        /// Full-fidelity source operands in field order.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        operands: Vec<SketchNativeOperand>,
    },
    /// Two model-space sketch points occupy the same solved position.
    Coincident {
        /// First coincident point.
        first: SpatialSketchEntityId,
        /// Second coincident point.
        second: SpatialSketchEntityId,
    },
    /// Two model-space sketch points are mirror images across a model-space line.
    Symmetric {
        /// First symmetric point.
        first: SpatialSketchEntityId,
        /// Second symmetric point.
        second: SpatialSketchEntityId,
        /// Bounded line whose infinite carrier is the reflection axis.
        axis: SpatialSketchEntityId,
    },
    /// A model-space point lies on a model-space surface.
    PointOnSurface {
        /// Point constrained to the surface.
        point: SpatialSketchEntityId,
        /// Surface containing the point.
        surface: SpatialSketchEntityId,
    },
    /// A model-space point lies at the midpoint of a bounded line.
    Midpoint {
        /// Point constrained to the midpoint.
        point: SpatialSketchEntityId,
        /// Bounded line whose midpoint is used.
        entity: SpatialSketchEntityId,
    },
    /// Two model-space curves are tangent.
    Tangent {
        /// First tangent curve.
        first: SpatialSketchEntityId,
        /// Second tangent curve.
        second: SpatialSketchEntityId,
    },
    /// Euclidean distance between two model-space sketch points.
    PointDistance {
        /// First measured point.
        first: SpatialSketchEntityId,
        /// Second measured point.
        second: SpatialSketchEntityId,
        /// Driving distance parameter.
        parameter: crate::features::ParameterId,
    },
    /// Distance from a model-space point to an infinite model-space line.
    PointLineDistance {
        /// Measured point.
        point: SpatialSketchEntityId,
        /// Bounded entity supplying the infinite line carrier.
        line: SpatialSketchEntityId,
        /// Driving distance parameter.
        parameter: crate::features::ParameterId,
    },
    /// Endpoint-to-endpoint length of one bounded model-space sketch line.
    LineLength {
        /// Measured line.
        entity: SpatialSketchEntityId,
        /// Driving length parameter.
        parameter: crate::features::ParameterId,
    },
    /// Endpoint-to-endpoint lengths of multiple bounded model-space sketch lines.
    RepeatedLineLength {
        /// Distinct measured lines in spatial-sketch entity order.
        entities: Vec<SpatialSketchEntityId>,
        /// Shared driving length parameter.
        parameter: crate::features::ParameterId,
    },
    /// Minimum separation between two parallel model-space sketch lines.
    ParallelLineDistance {
        /// First measured line.
        first: SpatialSketchEntityId,
        /// Second measured line.
        second: SpatialSketchEntityId,
        /// Driving distance parameter.
        parameter: crate::features::ParameterId,
    },
    /// Repeated separation between disjoint pairs of parallel lines.
    RepeatedParallelLineDistance {
        /// Distinct line pairs in profile traversal order.
        pairs: Vec<SpatialSketchEntityPair>,
        /// Shared driving distance parameter.
        parameter: crate::features::ParameterId,
    },
    /// Minimum separation between two parallel collinear model-space line sets.
    ParallelLineSetDistance {
        /// Collinear entities forming the first line carrier.
        first: Vec<SpatialSketchEntityId>,
        /// Collinear entities forming the second line carrier.
        second: Vec<SpatialSketchEntityId>,
        /// Driving distance parameter.
        parameter: crate::features::ParameterId,
    },
    /// A model-space curve set generated at one offset distance from a source set.
    Offset {
        /// Source curves in native relation order.
        sources: Vec<SpatialSketchEntityId>,
        /// Generated curves in native relation order.
        ///
        /// Position does not imply pairwise geometric correspondence with
        /// `sources`; an offset operation can change curve carriers or topology.
        results: Vec<SpatialSketchEntityId>,
        /// Unit normal of the result curve set's common plane.
        normal: U,
        /// Strictly positive operation-level offset magnitude.
        distance: L,
        /// Signed driving offset-distance parameter, when dimensional.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_spatial_sketch_constraint_definition_input_parameter"
        )]
        parameter: Option<OffsetParameter>,
    },
    /// A model-space line is parallel to one fixed model-space direction.
    ParallelToDirection {
        /// Line constrained to the direction.
        entity: SpatialSketchEntityId,
        /// Unit model-space direction; either sign denotes the same axis.
        direction: U,
    },
    /// A spline's defining model-space entities grouped by one native relation.
    SplineGroup {
        /// Ordered spline-group members.
        entities: Vec<SpatialSketchEntityId>,
    },
}

impl<U, L> SpatialSketchConstraintDefinitionInput<U, L> {
    /// The kind with its unit directions and its offset distance mapped, or
    /// the first refusal of either map.
    fn map_values<V, M, E>(
        self,
        mut direction: impl FnMut(U) -> Result<V, E>,
        length: impl FnOnce(L) -> Result<M, E>,
    ) -> Result<SpatialSketchConstraintDefinitionInput<V, M>, E> {
        use SpatialSketchConstraintDefinitionInput as Kind;
        Ok(match self {
            Self::Native {
                native_kind,
                native_state,
                parameter,
                operands,
            } => Kind::Native {
                native_kind,
                native_state,
                parameter,
                operands,
            },
            Self::Coincident { first, second } => Kind::Coincident { first, second },
            Self::Symmetric {
                first,
                second,
                axis,
            } => Kind::Symmetric {
                first,
                second,
                axis,
            },
            Self::PointOnSurface { point, surface } => Kind::PointOnSurface { point, surface },
            Self::Midpoint { point, entity } => Kind::Midpoint { point, entity },
            Self::Tangent { first, second } => Kind::Tangent { first, second },
            Self::PointDistance {
                first,
                second,
                parameter,
            } => Kind::PointDistance {
                first,
                second,
                parameter,
            },
            Self::PointLineDistance {
                point,
                line,
                parameter,
            } => Kind::PointLineDistance {
                point,
                line,
                parameter,
            },
            Self::LineLength { entity, parameter } => Kind::LineLength { entity, parameter },
            Self::RepeatedLineLength {
                entities,
                parameter,
            } => Kind::RepeatedLineLength {
                entities,
                parameter,
            },
            Self::ParallelLineDistance {
                first,
                second,
                parameter,
            } => Kind::ParallelLineDistance {
                first,
                second,
                parameter,
            },
            Self::RepeatedParallelLineDistance { pairs, parameter } => {
                Kind::RepeatedParallelLineDistance { pairs, parameter }
            }
            Self::ParallelLineSetDistance {
                first,
                second,
                parameter,
            } => Kind::ParallelLineSetDistance {
                first,
                second,
                parameter,
            },
            Self::Offset {
                sources,
                results,
                normal,
                distance,
                parameter,
            } => Kind::Offset {
                sources,
                results,
                normal: direction(normal)?,
                distance: length(distance)?,
                parameter,
            },
            Self::ParallelToDirection {
                entity,
                direction: value,
            } => Kind::ParallelToDirection {
                entity,
                direction: direction(value)?,
            },
            Self::SplineGroup { entities } => Kind::SplineGroup { entities },
        })
    }
}

impl SpatialSketchConstraintDefinitionInput<UnitVector3, PositiveLength> {
    /// The kind with raw directions and a raw offset distance.
    #[must_use]
    pub fn to_raw(&self) -> SpatialSketchConstraintDefinitionInput {
        let Ok(raw) = self.clone().map_values(
            |direction| Ok::<_, std::convert::Infallible>(Vector3::from(direction)),
            |distance| Ok(crate::scalar::Length::from(distance)),
        );
        raw
    }
}

/// NURBS curve with positive degree and positive rational weights.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct SpatialSketchNurbsCurve(crate::geometry::nurbs::NurbsCurve);

impl TryFrom<crate::geometry::nurbs::NurbsCurve> for SpatialSketchNurbsCurve {
    type Error = &'static str;

    fn try_from(curve: crate::geometry::nurbs::NurbsCurve) -> Result<Self, Self::Error> {
        if curve.degree() == 0 {
            return Err("spatial sketch NURBS degree must be at least one");
        }
        if curve
            .weights()
            .is_some_and(|weights| weights.iter().any(|weight| weight.get() <= 0.0))
        {
            return Err("spatial sketch NURBS weights must be positive");
        }
        Ok(Self(curve))
    }
}

impl<'de> Deserialize<'de> for SpatialSketchNurbsCurve {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Self::try_from(crate::geometry::nurbs::NurbsCurve::deserialize(
            deserializer,
        )?)
        .map_err(serde::de::Error::custom)
    }
}

impl std::ops::Deref for SpatialSketchNurbsCurve {
    type Target = crate::geometry::nurbs::NurbsCurve;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl SpatialSketchNurbsCurve {
    /// Map pole positions after every result passes admission.
    pub fn try_map_control_points<E>(
        &mut self,
        map: impl Fn(usize, FinitePoint3) -> Result<FinitePoint3, E>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Result<Result<(), E>, cadmpeg_core::CodecError> {
        self.0.try_map_control_points(map, ctx)
    }
}

const EPS_SPATIAL_LINE_LENGTH: f64 = 1.0e-12;
const EPS_SPATIAL_CIRCLE_FRAME: f64 = 1.0e-9;

/// Spatial-sketch geometry with checked analytic numeric fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(into = "SpatialSketchGeometryDefinition"))]
#[serde(try_from = "SpatialSketchGeometryDefinition")]
pub struct SpatialSketchGeometry(
    SpatialSketchGeometryDefinition<FinitePoint3, UnitVector3, PositiveLength>,
);

impl SpatialSketchGeometry {
    /// Copy the retained geometry payload through the decode budget.
    pub fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        use SpatialSketchGeometryDefinition as Definition;
        ctx.charge_work(1, operation)?;
        let definition = match &self.0 {
            Definition::Nurbs { curve } => Definition::Nurbs {
                curve: SpatialSketchNurbsCurve(curve.0.try_clone_for_decode(ctx, operation)?),
            },
            Definition::NurbsSurface { surface } => Definition::NurbsSurface {
                surface: surface.try_clone_for_decode(ctx, operation)?,
            },
            Definition::Native { native_kind } => Definition::Native {
                native_kind: native_kind.try_clone_for_decode(ctx, operation)?,
            },
            Definition::Point { .. }
            | Definition::Line { .. }
            | Definition::Circle { .. }
            | Definition::Arc { .. } => return Ok(self.clone()),
        };
        Ok(Self(definition))
    }

    /// Borrow the admitted spatial geometry definition.
    #[must_use]
    pub fn definition(
        &self,
    ) -> &SpatialSketchGeometryDefinition<FinitePoint3, UnitVector3, PositiveLength> {
        &self.0
    }

    /// Build a line from admitted endpoints. Only their separation is checked.
    pub fn try_line_from_parts(
        start: FinitePoint3,
        end: FinitePoint3,
    ) -> Result<Self, &'static str> {
        let start_point = start.get();
        let end_point = end.get();
        let distance = (end_point.x - start_point.x)
            .hypot(end_point.y - start_point.y)
            .hypot(end_point.z - start_point.z);
        if distance <= EPS_SPATIAL_LINE_LENGTH {
            return Err("spatial sketch line endpoints must be finite and separated");
        }
        Ok(Self(SpatialSketchGeometryDefinition::Line { start, end }))
    }
}

/// An admitted circular frame: center, radius, unit normal and unit
/// reference direction.
type CircularFrame = (FinitePoint3, PositiveLength, UnitVector3, UnitVector3);

/// Admit a circular center and radius, then a unit orthogonal frame.
fn admit_spatial_circle(
    center: Point3,
    radius: Length,
    normal: Vector3,
    reference_direction: Vector3,
) -> Result<CircularFrame, &'static str> {
    let (Some(center), Ok(radius)) = (FinitePoint3::new(center), PositiveLength::try_from(radius))
    else {
        return Err("spatial circular geometry requires finite center and positive finite radius");
    };
    let (Some(normal), Some(reference_direction)) = (
        UnitVector3::new(normal),
        UnitVector3::new(reference_direction),
    ) else {
        return Err("spatial circular normal and reference_direction must be unit and orthogonal");
    };
    if normal.as_raw().dot(*reference_direction.as_raw()).abs() > EPS_SPATIAL_CIRCLE_FRAME {
        return Err("spatial circular normal and reference_direction must be unit and orthogonal");
    }
    Ok((center, radius, normal, reference_direction))
}

impl TryFrom<SpatialSketchGeometryDefinition> for SpatialSketchGeometry {
    type Error = &'static str;

    fn try_from(definition: SpatialSketchGeometryDefinition) -> Result<Self, Self::Error> {
        use SpatialSketchGeometryDefinition as Definition;
        Ok(Self(match definition {
            Definition::Point { position } => Definition::Point {
                position: FinitePoint3::new(position)
                    .ok_or("spatial sketch point position must be finite")?,
            },
            Definition::Line { start, end } => {
                let distance = (end.x - start.x)
                    .hypot(end.y - start.y)
                    .hypot(end.z - start.z);
                let (Some(start), Some(end)) = (FinitePoint3::new(start), FinitePoint3::new(end))
                else {
                    return Err("spatial sketch line endpoints must be finite and separated");
                };
                if distance <= EPS_SPATIAL_LINE_LENGTH {
                    return Err("spatial sketch line endpoints must be finite and separated");
                }
                Definition::Line { start, end }
            }
            Definition::Circle {
                center,
                normal,
                reference_direction,
                radius,
            } => {
                let (center, radius, normal, reference_direction) =
                    admit_spatial_circle(center, radius, normal, reference_direction)?;
                Definition::Circle {
                    center,
                    normal,
                    reference_direction,
                    radius,
                }
            }
            Definition::Arc {
                center,
                normal,
                reference_direction,
                radius,
                start_angle,
                end_angle,
            } => {
                let (center, radius, normal, reference_direction) =
                    admit_spatial_circle(center, radius, normal, reference_direction)?;
                if start_angle == end_angle {
                    return Err("spatial sketch arc angles must be finite and distinct");
                }
                Definition::Arc {
                    center,
                    normal,
                    reference_direction,
                    radius,
                    start_angle,
                    end_angle,
                }
            }
            Definition::Nurbs { curve } => Definition::Nurbs { curve },
            Definition::NurbsSurface { surface } => Definition::NurbsSurface { surface },
            Definition::Native { native_kind } => Definition::Native { native_kind },
        }))
    }
}

impl SpatialSketchGeometryDefinition<FinitePoint3, UnitVector3, PositiveLength> {
    /// The definition with raw points, directions and radii.
    #[must_use]
    pub fn to_raw(&self) -> SpatialSketchGeometryDefinition {
        use SpatialSketchGeometryDefinition as Definition;
        match self {
            Self::Point { position } => Definition::Point {
                position: position.get(),
            },
            Self::Line { start, end } => Definition::Line {
                start: start.get(),
                end: end.get(),
            },
            Self::Circle {
                center,
                normal,
                reference_direction,
                radius,
            } => Definition::Circle {
                center: center.get(),
                normal: Vector3::from(*normal),
                reference_direction: Vector3::from(*reference_direction),
                radius: Length::from(*radius),
            },
            Self::Arc {
                center,
                normal,
                reference_direction,
                radius,
                start_angle,
                end_angle,
            } => Definition::Arc {
                center: center.get(),
                normal: Vector3::from(*normal),
                reference_direction: Vector3::from(*reference_direction),
                radius: Length::from(*radius),
                start_angle: *start_angle,
                end_angle: *end_angle,
            },
            Self::Nurbs { curve } => Definition::Nurbs {
                curve: curve.clone(),
            },
            Self::NurbsSurface { surface } => Definition::NurbsSurface {
                surface: surface.clone(),
            },
            Self::Native { native_kind } => Definition::Native {
                native_kind: native_kind.clone(),
            },
        }
    }
}

/// Definition admitted by model-space spatial-sketch geometry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SpatialSketchGeometryDefinition<P = Point3, V = Vector3, L = Length> {
    /// Model-space point.
    Point {
        /// Point position in model coordinates.
        position: P,
    },
    /// Bounded model-space line segment.
    Line {
        /// Segment start in model coordinates.
        start: P,
        /// Segment end in model coordinates.
        end: P,
    },
    /// Oriented full model-space circle.
    Circle {
        /// Circle center in model coordinates.
        center: P,
        /// Unit normal defining positive angular travel.
        normal: V,
        /// Unit radial direction at parameter zero.
        reference_direction: V,
        /// Circle radius.
        radius: L,
    },
    /// Oriented bounded model-space circular arc.
    Arc {
        /// Arc center in model coordinates.
        center: P,
        /// Unit normal defining positive angular travel.
        normal: V,
        /// Unit radial direction at parameter zero.
        reference_direction: V,
        /// Arc radius.
        radius: L,
        /// Inclusive start parameter in radians.
        start_angle: Angle,
        /// Inclusive end parameter in radians.
        end_angle: Angle,
    },
    /// Model-space NURBS curve.
    Nurbs {
        /// Checked model-space knot, pole, and weight payload.
        curve: SpatialSketchNurbsCurve,
    },
    /// Polynomial tensor-product B-spline surface embedded in model space.
    NurbsSurface {
        /// Checked rectangular control grid and full knot vectors.
        surface: crate::geometry::nurbs::BsplineSurface,
    },
    /// Source-native spatial geometry not yet reduced to a neutral family.
    Native {
        /// Source geometry family.
        #[serde(deserialize_with = "deserialize_native_kind")]
        native_kind: NonBlankString,
    },
}

/// One relation constraining solved sketch geometry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchConstraint {
    /// Globally unique constraint id.
    pub id: SketchConstraintId,
    /// Owning sketch.
    pub sketch: SketchId,
    /// Constraint semantics.
    pub definition: SketchConstraintDefinition,
    /// User-visible constraint name, when assigned.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_name"
    )]
    pub name: Option<String>,
    /// Whether this dimensional relation drives geometry.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_driving"
    )]
    pub driving: Option<bool>,
    /// Whether the solver currently applies this relation.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_active"
    )]
    pub active: Option<bool>,
    /// Whether the relation belongs to virtual sketch space.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_virtual_space"
    )]
    pub virtual_space: Option<bool>,
    /// Whether the relation is displayed in the sketch UI.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_visible"
    )]
    pub visible: Option<bool>,
    /// Source orientation bit field, when the relation carries one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_orientation"
    )]
    pub orientation: Option<u32>,
    /// Persisted label offset from the constrained geometry.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_label_distance"
    )]
    pub label_distance: Option<SketchLabelValue>,
    /// Persisted position along the dimension label path.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_label_position"
    )]
    pub label_position: Option<SketchLabelValue>,
    /// Application metadata text attached to this relation.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_metadata"
    )]
    pub metadata: Option<String>,
    /// Source-native relation record when decoded from one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// A geometric locus on a sketch entity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "entity", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchLocus {
    /// The complete entity.
    Entity(SketchEntityId),
    /// Stored start point of a bounded entity.
    Start(SketchEntityId),
    /// Stored end point of a bounded entity.
    End(SketchEntityId),
    /// Center of a circle, arc, or ellipse.
    Center(SketchEntityId),
}

/// Coordinate axis selected by a sketch relation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchCoordinateAxis {
    /// First coordinate in sketch space.
    U,
    /// Second coordinate in sketch space.
    V,
}

/// Source-native field and optional role carrying one sketch operand.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct NativeOperandField {
    /// Non-empty source-native field name.
    pub name: NonBlankString,
    /// Source-native role code, when the field carries one.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_role"
    )]
    pub role: Option<u32>,
}

/// One ordered operand retained from a native sketch relation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchNativeOperand {
    /// Non-empty source-native operand family.
    pub native_kind: NonBlankString,
    /// Source-native field and optional role containing this operand.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_field"
    )]
    pub field: Option<NativeOperandField>,
    /// Source-native object index; absent when the native operand names no
    /// object (an axis, root point, or external reference slot).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_object_index"
    )]
    pub object_index: Option<u32>,
    /// Resolved source-native operand record.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_native_ref"
    )]
    pub native_ref: Option<String>,
}

/// One progenitor/result pair in a sketch offset relation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchOffsetPair {
    /// Source entity whose stored direction defines the signed offset normal.
    pub source: SketchEntityId,
    /// Entity produced at the shared signed offset distance.
    pub result: SketchEntityId,
    /// Reverse the source's stored traversal before selecting its left normal.
    #[serde(default)]
    pub source_reversed: bool,
}

/// Signed use of a driving offset-distance parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct OffsetParameter {
    /// Driving parameter identity.
    pub id: ParameterId,
    /// Whether the stored positive distance is the negation of the parameter.
    pub negated: bool,
}

/// One axis of a rectangular sketch pattern.
#[derive(Debug, Clone, PartialEq)]
pub struct SketchPatternDirection {
    /// Unit direction in sketch coordinates.
    direction: UnitVector2,
    /// Adjacent-instance spacing along `direction`.
    spacing: Length,
    /// Driving distance parameter and the distance form it controls.
    pub distance: Option<SketchPatternDistance>,
    /// Driving instance-count parameter, when the source exposes it as a neutral parameter.
    pub count_parameter: Option<ParameterId>,
}

const EPS_PATTERN_DIRECTION_ORTHOGONALITY: f64 = 1.0e-9;

impl SketchPatternDirection {
    /// Admit a finite unit direction and finite signed spacing.
    pub fn new(
        direction: [f64; 2],
        spacing: Length,
        distance: Option<SketchPatternDistance>,
        count_parameter: Option<ParameterId>,
    ) -> Option<Self> {
        let direction = UnitVector2::new(direction)?;
        Some(Self {
            direction,
            spacing,
            distance,
            count_parameter,
        })
    }

    /// Unit direction in sketch coordinates.
    #[must_use]
    pub fn direction(&self) -> UnitVector2 {
        self.direction
    }

    /// Adjacent-instance signed spacing.
    #[must_use]
    pub fn spacing(&self) -> Length {
        self.spacing
    }
}

/// Distance form controlled by a rectangular-pattern parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchPatternDistance {
    /// The parameter controls adjacent-instance spacing.
    Spacing {
        /// Driving parameter identity.
        parameter: ParameterId,
    },
    /// The parameter controls the seed-to-final-instance span.
    Span {
        /// Driving parameter identity.
        parameter: ParameterId,
    },
}

impl SketchPatternDistance {
    /// Parameter that controls this distance form.
    #[must_use]
    pub fn parameter(&self) -> &ParameterId {
        match self {
            Self::Spacing { parameter } | Self::Span { parameter } => parameter,
        }
    }
}

/// One resolved rectangular-pattern instance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchPatternInstance {
    /// Entities in fixed seed-entity order.
    pub entities: Vec<SketchEntityId>,
}

/// One resolved circular-pattern instance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchCircularPatternInstance {
    /// Signed rotation from the seed instance in radians.
    pub angle: crate::scalar::NonZeroAngle,
    /// Entities in fixed seed-entity order.
    pub entities: Vec<SketchEntityId>,
}

/// Checked two-axis rectangular sketch pattern.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    try_from = "SketchRectangularPatternWire",
    into = "SketchRectangularPatternWire"
)]
pub struct SketchRectangularPattern {
    directions: [SketchPatternDirection; 2],
    rows: Vec<Vec<SketchPatternInstance>>,
}

impl SketchRectangularPattern {
    /// Construct a non-empty rectangular grid whose instances have one fixed
    /// positive entity arity.
    pub fn new(
        directions: [SketchPatternDirection; 2],
        rows: Vec<Vec<SketchPatternInstance>>,
    ) -> Option<Self> {
        let row_count = u32::try_from(rows.len()).ok()?;
        let column_count = u32::try_from(rows.first()?.len()).ok()?;
        if row_count == 0
            || column_count == 0
            || rows
                .iter()
                .any(|row| row.len() != cadmpeg_core::decode::index_from_u32(column_count))
        {
            return None;
        }
        let entity_arity = rows.first()?.first()?.entities.len();
        if entity_arity == 0
            || rows
                .iter()
                .flatten()
                .any(|instance| instance.entities.len() != entity_arity)
        {
            return None;
        }
        let [first, second] = [directions[0].direction.get(), directions[1].direction.get()];
        let dot = first[0] * second[0] + first[1] * second[1];
        let mut entities = std::collections::HashSet::new();
        if dot.abs() > EPS_PATTERN_DIRECTION_ORTHOGONALITY
            || rows.iter().flatten().any(|instance| {
                instance
                    .entities
                    .iter()
                    .any(|entity| !entities.insert(entity))
            })
        {
            return None;
        }
        Some(Self { directions, rows })
    }

    /// Ordered pattern directions.
    #[must_use]
    pub fn directions(&self) -> &[SketchPatternDirection; 2] {
        &self.directions
    }

    /// Rectangular instance rows. Outer and inner positions are the two
    /// zero-based pattern indices.
    #[must_use]
    pub fn rows(&self) -> &[Vec<SketchPatternInstance>] {
        &self.rows
    }
}

/// Checked circular sketch pattern.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    try_from = "SketchCircularPatternWire",
    into = "SketchCircularPatternWire"
)]
pub struct SketchCircularPattern {
    center: SketchEntityId,
    angle: Angle,
    angle_parameter: Option<ParameterId>,
    count_parameter: Option<ParameterId>,
    seed: Vec<SketchEntityId>,
    /// Instances after the seed, at a population whose count the IR width can
    /// state. The type carries the bound and the figure, so the pattern
    /// stores no count of its own.
    instances: SeededMembers<SketchCircularPatternInstance>,
}

/// A nonempty population whose count, with the seed counted, fits the IR
/// width.
///
/// The pattern states its instance count as the population plus the seed, in
/// a `u32`. The bound therefore belongs on the population, not on the count:
/// this type proves the bound at construction and refuses a population the
/// width cannot count. `TryFrom<Vec<T>>` is the only constructor, and the type
/// hands out a slice, so no value can grow past the count it proved.
#[derive(Debug, Clone, PartialEq)]
struct SeededMembers<T> {
    members: Vec<T>,
}

impl<T> TryFrom<Vec<T>> for SeededMembers<T> {
    type Error = &'static str;

    fn try_from(members: Vec<T>) -> Result<Self, Self::Error> {
        if members.is_empty() {
            return Err("population states no member");
        }
        let Some(_) = u32::try_from(members.len())
            .ok()
            .and_then(|population| population.checked_add(1))
        else {
            return Err("population holds more members than the seeded count can state");
        };
        Ok(Self { members })
    }
}

impl<T> std::ops::Deref for SeededMembers<T> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        &self.members
    }
}

impl<T> IntoIterator for SeededMembers<T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.members.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a SeededMembers<T> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.members.iter()
    }
}

/// The refusal every arity and ownership check of a circular pattern states.
const CIRCULAR_PATTERN_ARITY: &str =
    "circular pattern seed and instances must share one fixed positive entity arity over distinct entities";

impl SketchCircularPattern {
    /// Construct a non-empty pattern whose instances have one fixed positive
    /// entity arity.
    ///
    /// This is the recognizer shape, for a caller that holds no channel to
    /// state a cause in. The route that has one is
    /// `TryFrom<SketchCircularPatternWire>`, which states the cause
    /// `Self::admit` gives.
    pub fn new(
        center: SketchEntityId,
        angle: Angle,
        angle_parameter: Option<ParameterId>,
        count_parameter: Option<ParameterId>,
        seed: Vec<SketchEntityId>,
        instances: Vec<SketchCircularPatternInstance>,
    ) -> Option<Self> {
        Self::admit(
            center,
            angle,
            angle_parameter,
            count_parameter,
            seed,
            instances,
        )
        .ok()
    }

    /// Admit the pattern, naming the cause of every refusal.
    ///
    /// The population bound is the one `SeededMembers` proves, and its two
    /// texts are the ones this route states: an empty `instances` array is
    /// refused as a population that states no member, not as an arity
    /// disagreement.
    fn admit(
        center: SketchEntityId,
        angle: Angle,
        angle_parameter: Option<ParameterId>,
        count_parameter: Option<ParameterId>,
        seed: Vec<SketchEntityId>,
        instances: Vec<SketchCircularPatternInstance>,
    ) -> Result<Self, &'static str> {
        let entity_arity = seed.len();
        if entity_arity == 0
            || instances
                .iter()
                .any(|instance| instance.entities.len() != entity_arity)
        {
            return Err(CIRCULAR_PATTERN_ARITY);
        }
        let mut entities = std::collections::HashSet::new();
        if seed
            .iter()
            .chain(
                instances
                    .iter()
                    .flat_map(|instance| instance.entities.iter()),
            )
            .any(|entity| entity == &center || !entities.insert(entity))
        {
            return Err(CIRCULAR_PATTERN_ARITY);
        }
        Ok(Self {
            center,
            angle,
            angle_parameter,
            count_parameter,
            seed,
            instances: SeededMembers::try_from(instances)?,
        })
    }

    /// Point entity defining the center of rotation.
    #[must_use]
    pub fn center(&self) -> &SketchEntityId {
        &self.center
    }

    /// Driving angular-span parameter.
    #[must_use]
    pub fn angle_parameter(&self) -> Option<&ParameterId> {
        self.angle_parameter.as_ref()
    }

    /// Driving instance-count parameter.
    #[must_use]
    pub fn count_parameter(&self) -> Option<&ParameterId> {
        self.count_parameter.as_ref()
    }

    /// Instances in pattern order, after the seed. Slice position plus one is
    /// the zero-based pattern index.
    #[must_use]
    pub fn instances(&self) -> &[SketchCircularPatternInstance] {
        &self.instances
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SketchPatternDirectionWire {
    direction: [f64; 2],
    spacing: Length,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_distance"
    )]
    distance: Option<SketchPatternDistance>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_count_parameter"
    )]
    count_parameter: Option<ParameterId>,
}

impl SketchPatternDirectionWire {
    fn from_direction(value: &SketchPatternDirection) -> Self {
        Self {
            direction: value.direction.get(),
            spacing: value.spacing,
            distance: value.distance.clone(),
            count_parameter: value.count_parameter.clone(),
        }
    }

    fn into_direction(self) -> Result<SketchPatternDirection, &'static str> {
        SketchPatternDirection::new(
            self.direction,
            self.spacing,
            self.distance,
            self.count_parameter,
        )
        .ok_or("pattern direction must be finite and unit, with finite spacing")
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "SketchRectangularPattern"))]
#[serde(deny_unknown_fields)]
struct SketchRectangularPatternWire {
    /// Ordered pattern directions.
    directions: [SketchPatternDirectionWire; 2],
    /// Rectangular instance rows.
    rows: Vec<Vec<SketchPatternInstance>>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "SketchCircularPattern"))]
#[serde(deny_unknown_fields)]
struct SketchCircularPatternWire {
    /// Point entity defining the center of rotation.
    center: SketchEntityId,
    /// Evaluated angular span stored by the native pattern.
    angle: Angle,
    /// Driving angular-span parameter.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_angle_parameter"
    )]
    angle_parameter: Option<ParameterId>,
    /// Driving instance-count parameter.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_count_parameter"
    )]
    count_parameter: Option<ParameterId>,
    /// Seed entities in fixed order.
    seed: Vec<SketchEntityId>,
    /// Instances after the seed, in pattern order.
    instances: Vec<SketchCircularPatternInstance>,
}

impl From<SketchRectangularPattern> for SketchRectangularPatternWire {
    fn from(pattern: SketchRectangularPattern) -> Self {
        Self {
            directions: [
                SketchPatternDirectionWire::from_direction(&pattern.directions[0]),
                SketchPatternDirectionWire::from_direction(&pattern.directions[1]),
            ],
            rows: pattern.rows,
        }
    }
}

impl TryFrom<SketchRectangularPatternWire> for SketchRectangularPattern {
    type Error = &'static str;

    fn try_from(wire: SketchRectangularPatternWire) -> Result<Self, Self::Error> {
        let [first, second] = wire.directions;
        let directions = [first.into_direction()?, second.into_direction()?];
        Self::new(directions, wire.rows).ok_or(
            "rectangular pattern rows must form one non-empty grid whose instances have one fixed positive entity arity",
        )
    }
}

impl From<SketchCircularPattern> for SketchCircularPatternWire {
    fn from(pattern: SketchCircularPattern) -> Self {
        Self {
            center: pattern.center,
            angle: pattern.angle,
            angle_parameter: pattern.angle_parameter,
            count_parameter: pattern.count_parameter,
            seed: pattern.seed,
            instances: pattern.instances.into_iter().collect(),
        }
    }
}

impl TryFrom<SketchCircularPatternWire> for SketchCircularPattern {
    type Error = &'static str;

    fn try_from(wire: SketchCircularPatternWire) -> Result<Self, Self::Error> {
        Self::admit(
            wire.center,
            wire.angle,
            wire.angle_parameter,
            wire.count_parameter,
            wire.seed,
            wire.instances,
        )
    }
}

/// One independently measured pair within a repeated linear dimension.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchDistanceMeasurement {
    /// Euclidean separation between two loci.
    Distance {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
    },
    /// Horizontal separation between two loci.
    Horizontal {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
    },
    /// Vertical separation between two loci.
    Vertical {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
    },
}

/// One ordered pair of loci whose Euclidean separation participates in an
/// equality relation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SketchDistancePair {
    /// First locus in the measured pair.
    pub first: SketchLocus,
    /// Second locus in the measured pair.
    pub second: SketchLocus,
}

/// Meaning of an internal sketch alignment helper relation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    from = "SketchInternalAlignmentWire",
    into = "SketchInternalAlignmentWire"
)]
pub enum SketchInternalAlignment {
    /// Major diameter helper for an ellipse.
    EllipseMajorDiameter,
    /// Minor diameter helper for an ellipse.
    EllipseMinorDiameter,
    /// First ellipse focus helper.
    EllipseFocus1,
    /// Second ellipse focus helper.
    EllipseFocus2,
    /// Hyperbola major-axis helper.
    HyperbolaMajor,
    /// Hyperbola minor-axis helper.
    HyperbolaMinor,
    /// Hyperbola focus helper.
    HyperbolaFocus,
    /// Parabola focus helper.
    ParabolaFocus,
    /// B-spline control-point helper.
    BsplineControlPoint(u32),
    /// B-spline knot-point helper.
    BsplineKnotPoint(u32),
    /// Parabola focal-axis helper.
    ParabolaFocalAxis,
}

#[derive(Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "alignment", rename_all = "snake_case", deny_unknown_fields)]
enum SketchInternalAlignmentWire {
    /// Major diameter helper for an ellipse.
    EllipseMajorDiameter {},
    /// Minor diameter helper for an ellipse.
    EllipseMinorDiameter {},
    /// First ellipse focus helper.
    EllipseFocus1 {},
    /// Second ellipse focus helper.
    EllipseFocus2 {},
    /// Hyperbola major-axis helper.
    HyperbolaMajor {},
    /// Hyperbola minor-axis helper.
    HyperbolaMinor {},
    /// Hyperbola focus helper.
    HyperbolaFocus {},
    /// Parabola focus helper.
    ParabolaFocus {},
    /// B-spline control-point helper.
    BsplineControlPoint {
        /// Zero-based control-point index.
        index: u32,
    },
    /// B-spline knot-point helper.
    BsplineKnotPoint {
        /// Zero-based knot-point index.
        index: u32,
    },
    /// Parabola focal-axis helper.
    ParabolaFocalAxis {},
}

impl From<SketchInternalAlignmentWire> for SketchInternalAlignment {
    fn from(wire: SketchInternalAlignmentWire) -> Self {
        match wire {
            SketchInternalAlignmentWire::EllipseMajorDiameter {} => Self::EllipseMajorDiameter,
            SketchInternalAlignmentWire::EllipseMinorDiameter {} => Self::EllipseMinorDiameter,
            SketchInternalAlignmentWire::EllipseFocus1 {} => Self::EllipseFocus1,
            SketchInternalAlignmentWire::EllipseFocus2 {} => Self::EllipseFocus2,
            SketchInternalAlignmentWire::HyperbolaMajor {} => Self::HyperbolaMajor,
            SketchInternalAlignmentWire::HyperbolaMinor {} => Self::HyperbolaMinor,
            SketchInternalAlignmentWire::HyperbolaFocus {} => Self::HyperbolaFocus,
            SketchInternalAlignmentWire::ParabolaFocus {} => Self::ParabolaFocus,
            SketchInternalAlignmentWire::BsplineControlPoint { index } => {
                Self::BsplineControlPoint(index)
            }
            SketchInternalAlignmentWire::BsplineKnotPoint { index } => {
                Self::BsplineKnotPoint(index)
            }
            SketchInternalAlignmentWire::ParabolaFocalAxis {} => Self::ParabolaFocalAxis,
        }
    }
}

impl From<SketchInternalAlignment> for SketchInternalAlignmentWire {
    fn from(value: SketchInternalAlignment) -> Self {
        match value {
            SketchInternalAlignment::EllipseMajorDiameter => Self::EllipseMajorDiameter {},
            SketchInternalAlignment::EllipseMinorDiameter => Self::EllipseMinorDiameter {},
            SketchInternalAlignment::EllipseFocus1 => Self::EllipseFocus1 {},
            SketchInternalAlignment::EllipseFocus2 => Self::EllipseFocus2 {},
            SketchInternalAlignment::HyperbolaMajor => Self::HyperbolaMajor {},
            SketchInternalAlignment::HyperbolaMinor => Self::HyperbolaMinor {},
            SketchInternalAlignment::HyperbolaFocus => Self::HyperbolaFocus {},
            SketchInternalAlignment::ParabolaFocus => Self::ParabolaFocus {},
            SketchInternalAlignment::BsplineControlPoint(index) => {
                Self::BsplineControlPoint { index }
            }
            SketchInternalAlignment::BsplineKnotPoint(index) => Self::BsplineKnotPoint { index },
            SketchInternalAlignment::ParabolaFocalAxis => Self::ParabolaFocalAxis {},
        }
    }
}

/// Ordered polygon members with at least three distinct identities.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SketchPolygonWire")]
pub struct SketchPolygon {
    entities: Vec<SketchEntityId>,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SketchPolygonWire {
    /// Ordered polygon members.
    entities: Vec<SketchEntityId>,
}

impl TryFrom<SketchPolygonWire> for SketchPolygon {
    type Error = SketchCollectionError;

    fn try_from(wire: SketchPolygonWire) -> Result<Self, Self::Error> {
        let invalid = "entities requires at least three distinct polygon members";
        if wire.entities.len() < 3 {
            return Err(SketchCollectionError::Invalid(invalid));
        }
        let mut members = std::collections::HashSet::new();
        members
            .try_reserve(wire.entities.len())
            .map_err(|error| SketchCollectionError::Admission(error.to_string()))?;
        for entity in &wire.entities {
            if !members.insert(entity) {
                return Err(SketchCollectionError::Invalid(invalid));
            }
        }
        Ok(Self {
            entities: wire.entities,
        })
    }
}

impl SketchPolygon {
    /// Admit decoded members and charge temporary uniqueness storage.
    pub fn try_new(
        entities: Vec<SketchEntityId>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::CodecError> {
        if entities.len() < 3 {
            return Ok(Err(
                "entities requires at least three distinct polygon members",
            ));
        }
        if !distinct_sketch_members(ctx, entities.iter().map(SketchEntityId::as_str), operation)? {
            return Ok(Err(
                "entities requires at least three distinct polygon members",
            ));
        }
        Ok(Ok(Self { entities }))
    }

    /// Returns the ordered polygon members.
    pub fn entities(&self) -> &[SketchEntityId] {
        &self.entities
    }
}

/// Two distinct loci aligned on one sketch coordinate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SketchSameCoordinateWire")]
pub struct SketchSameCoordinate {
    first: SketchLocus,
    second: SketchLocus,
    axis: SketchCoordinateAxis,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SketchSameCoordinateWire {
    /// First locus.
    first: SketchLocus,
    /// Second locus.
    second: SketchLocus,
    /// Shared coordinate axis.
    axis: SketchCoordinateAxis,
}

impl TryFrom<SketchSameCoordinateWire> for SketchSameCoordinate {
    type Error = &'static str;

    fn try_from(wire: SketchSameCoordinateWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.first, wire.second, wire.axis)
    }
}

impl SketchSameCoordinate {
    /// Admits two distinct loci and their shared coordinate axis.
    pub fn try_new(
        first: SketchLocus,
        second: SketchLocus,
        axis: SketchCoordinateAxis,
    ) -> Result<Self, &'static str> {
        if first == second {
            return Err("first and second require distinct loci");
        }
        Ok(Self {
            first,
            second,
            axis,
        })
    }

    /// Returns the first locus.
    pub fn first(&self) -> &SketchLocus {
        &self.first
    }

    /// Returns the second locus.
    pub fn second(&self) -> &SketchLocus {
        &self.second
    }

    /// Returns the shared coordinate axis.
    pub fn axis(&self) -> SketchCoordinateAxis {
        self.axis
    }
}

/// A finite sketch constraint label coordinate.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "f64")]
pub struct SketchLabelValue(f64);

impl TryFrom<f64> for SketchLabelValue {
    type Error = &'static str;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        if !value.is_finite() {
            return Err("sketch constraint label coordinate must be finite");
        }
        Ok(Self(value))
    }
}

const EPS_POLAR_DISTANCE_ZERO: f64 = 1.0e-12;

/// A sketch constraint definition with admitted local arity and scalar values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SketchConstraintDefinitionInput")]
pub struct SketchConstraintDefinition(SketchConstraintDefinitionInput);

impl SketchConstraintDefinition {
    /// Construct a native relation with one source operand and its resolved entities.
    ///
    /// The operand supplies the required nonempty binding. State, flags, and
    /// parameter are absent; callers with those fields use input admission.
    #[must_use]
    pub fn native_with_operand(
        native_kind: NonBlankString,
        native_properties: BTreeMap<String, String>,
        entities: Vec<SketchEntityId>,
        operand: SketchNativeOperand,
    ) -> Self {
        Self(SketchConstraintDefinitionInput::Native {
            native_kind,
            native_state: None,
            native_flags: None,
            native_properties,
            entities,
            parameter: None,
            operands: vec![operand],
        })
    }

    /// Borrow the admitted constraint kind.
    #[must_use]
    pub fn kind(&self) -> &SketchConstraintDefinitionInput {
        &self.0
    }

    /// Set the driving parameter of an admitted planar offset relation.
    /// The parameter does not change offset-pair admission.
    pub fn set_offset_parameter(&mut self, driving: OffsetParameter) -> bool {
        let SketchConstraintDefinitionInput::Offset { parameter, .. } = &mut self.0 else {
            return false;
        };
        *parameter = Some(driving);
        true
    }

    /// Consume the admitted definition and return its kind.
    #[must_use]
    pub fn into_kind(self) -> SketchConstraintDefinitionInput {
        self.0
    }

    /// Replace the kind only after all edited local invariants pass.
    pub fn edit<R>(
        &mut self,
        edit: impl FnOnce(&mut SketchConstraintDefinitionInput) -> R,
    ) -> Result<R, &'static str> {
        let mut kind = self.0.clone();
        let result = edit(&mut kind);
        *self = kind.try_into()?;
        Ok(result)
    }
}

impl TryFrom<SketchConstraintDefinitionInput> for SketchConstraintDefinition {
    type Error = &'static str;

    fn try_from(kind: SketchConstraintDefinitionInput) -> Result<Self, Self::Error> {
        use SketchConstraintDefinitionInput as Kind;
        let valid = match &kind {
            Kind::Coincident { entities } | Kind::SplineGroup { entities } => entities.len() >= 2,
            Kind::CoincidentLoci { loci } => loci.len() >= 2,
            Kind::Distance { entities, .. } => !entities.is_empty(),
            Kind::TextFrame { text, frame } => {
                !frame.is_empty() && frame.iter().all(|entity| entity != text)
            }
            Kind::TextPath {
                text,
                path,
                glyph_transforms,
            } => text != path && !glyph_transforms.is_empty(),
            Kind::DistanceLociValue { distance, .. } => distance.get() >= 0.0,
            Kind::PolarDistance {
                distance, angle, ..
            } => {
                distance.get() >= 0.0
                    && if distance.get() <= EPS_POLAR_DISTANCE_ZERO {
                        angle.is_none()
                    } else {
                        angle.is_some()
                    }
            }
            Kind::AngleDifference { value, .. } => {
                (0.0..=std::f64::consts::PI).contains(&value.get())
            }
            Kind::ScalarEquality { first, second } => first != second,
            Kind::RepeatedDistance { measurements, .. } => {
                let mut entities = std::collections::HashSet::new();
                !measurements.is_empty()
                    && measurements.iter().all(|measurement| {
                        let (first, second) = match measurement {
                            SketchDistanceMeasurement::Distance { first, second }
                            | SketchDistanceMeasurement::Horizontal { first, second }
                            | SketchDistanceMeasurement::Vertical { first, second } => {
                                (first, second)
                            }
                        };
                        let entity = |locus: &SketchLocus| match locus {
                            SketchLocus::Entity(id)
                            | SketchLocus::Start(id)
                            | SketchLocus::End(id)
                            | SketchLocus::Center(id) => id.clone(),
                        };
                        entities.insert(entity(first)) && entities.insert(entity(second))
                    })
            }
            Kind::RepeatedLength { entities, .. }
            | Kind::RepeatedRadius { entities, .. }
            | Kind::RepeatedDiameter { entities, .. } => {
                entities.len() >= 2
                    && entities
                        .iter()
                        .collect::<std::collections::HashSet<_>>()
                        .len()
                        == entities.len()
            }
            Kind::ParallelLineSetDistance { first, second, .. } => {
                !first.is_empty()
                    && !second.is_empty()
                    && (first.len() > 1 || second.len() > 1)
                    && first
                        .iter()
                        .chain(second)
                        .collect::<std::collections::HashSet<_>>()
                        .len()
                        == first.len() + second.len()
            }
            Kind::Offset {
                pairs, distance, ..
            } => {
                let mut sources = std::collections::HashSet::new();
                let mut results = std::collections::HashSet::new();
                !pairs.is_empty()
                    && distance.get() > 0.0
                    && pairs.iter().all(|pair| {
                        pair.source != pair.result
                            && sources.insert(&pair.source)
                            && results.insert(&pair.result)
                    })
            }
            Kind::ProjectedCopy { source, result } => source != result,
            Kind::Group { elements } | Kind::Text { elements, .. } => !elements.is_empty(),
            Kind::Native {
                entities, operands, ..
            } => !entities.is_empty() || !operands.is_empty(),
            Kind::Disabled {} => true,
            Kind::Polygon { .. } => true,
            Kind::RectangularPattern { .. } => true,
            Kind::CircularPattern { .. } => true,
            Kind::SameCoordinate { .. } => true,
            Kind::PointOnObject { .. } => true,
            Kind::Midpoint { .. } => true,
            Kind::PointCoordinateValues { .. } => true,
            Kind::MidpointCoordinate { .. } => true,
            Kind::AtIntersection { .. } => true,
            Kind::Concentric { .. } => true,
            Kind::Coradial { .. } => true,
            Kind::Collinear { .. } => true,
            Kind::Symmetric { .. } => true,
            Kind::PointSymmetric { .. } => true,
            Kind::Horizontal { .. } => true,
            Kind::Vertical { .. } => true,
            Kind::Parallel { .. } => true,
            Kind::Perpendicular { .. } => true,
            Kind::Tangent { .. } => true,
            Kind::TangentLoci { .. } => true,
            Kind::Curvature { .. } => true,
            Kind::Equal { .. } => true,
            Kind::Fixed { .. } => true,
            Kind::ArcAngle { .. } => true,
            Kind::EllipseAngle { .. } => true,
            Kind::DistanceLoci { .. } => true,
            Kind::EqualDistance { .. } => true,
            Kind::HorizontalDistance { .. } => true,
            Kind::VerticalDistance { .. } => true,
            Kind::Angle { .. } => true,
            Kind::AngleToAxis { .. } => true,
            Kind::Radius { .. } => true,
            Kind::Diameter { .. } => true,
            Kind::SnellsLaw { .. } => true,
            Kind::Weight { .. } => true,
            Kind::InternalAlignment { .. } => true,
        };
        if !valid {
            return Err("invalid sketch constraint local arity or scalar value");
        }
        Ok(Self(kind))
    }
}

/// Candidate geometric and dimensional sketch relations for checked admission.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SketchConstraintDefinitionInput {
    /// Persisted no-op relation slot.
    Disabled {},
    /// Two entity loci coincide.
    Coincident {
        /// Coincident entity loci.
        entities: Vec<SketchEntityId>,
    },
    /// Entities participate in one native polygon relation.
    Polygon {
        /// Checked polygon members.
        polygon: SketchPolygon,
    },
    /// A spline's defining entities grouped by one native spline relation.
    SplineGroup {
        /// Ordered spline-group members: the spline's defining entities and
        /// its curve entity.
        entities: Vec<SketchEntityId>,
    },
    /// A complete two-axis rectangular pattern with resolved instances.
    RectangularPattern {
        /// Checked directions and rectangular instance grid.
        pattern: SketchRectangularPattern,
    },
    /// A parameter-driven circular pattern with geometrically resolved instances.
    CircularPattern {
        /// Checked center, parameters, and positional instances.
        pattern: SketchCircularPattern,
    },
    /// Text entity bounded by ordered frame curves.
    TextFrame {
        /// Text entity owning the frame.
        text: SketchEntityId,
        /// Ordered frame curves.
        frame: Vec<SketchEntityId>,
    },
    /// Text entity laid out along a path curve.
    TextPath {
        /// Text entity placed along the path.
        text: SketchEntityId,
        /// Path curve.
        path: SketchEntityId,
        /// Character placements in text order, expressed in sketch coordinates.
        glyph_transforms: Vec<Transform>,
    },
    /// Two or more explicit entity loci coincide.
    CoincidentLoci {
        /// Coincident endpoints, centers, or complete entities.
        loci: Vec<SketchLocus>,
    },
    /// Two loci share one sketch-space coordinate.
    SameCoordinate {
        /// Checked coordinate relation.
        relation: SketchSameCoordinate,
    },
    /// A point locus lies on another sketch entity.
    PointOnObject {
        /// Point constrained to the supporting entity.
        point: SketchLocus,
        /// Entity on which the point lies.
        entity: SketchEntityId,
    },
    /// A point locus lies at the midpoint of a bounded entity.
    Midpoint {
        /// Point constrained to the midpoint.
        point: SketchLocus,
        /// Bounded entity whose midpoint is used.
        entity: SketchEntityId,
    },
    /// A point locus has fixed values on both sketch coordinate axes.
    PointCoordinateValues {
        /// Point whose two coordinates are constrained.
        point: SketchLocus,
        /// Coordinate values in sketch `u`, then `v`, order.
        values: [Length; 2],
    },
    /// One sketch coordinate is the arithmetic mean of two point loci.
    MidpointCoordinate {
        /// First point contributing to the mean.
        first: SketchLocus,
        /// Second point contributing to the mean.
        second: SketchLocus,
        /// Coordinate axis carrying the mean relation.
        axis: SketchCoordinateAxis,
        /// Source-evaluated coordinate mean.
        value: Length,
    },
    /// One or more entities offset from their progenitors by one signed distance.
    Offset {
        /// Ordered progenitor/result pairs.
        pairs: Vec<SketchOffsetPair>,
        /// Strictly positive common offset magnitude, measured along each
        /// oriented source entity's left normal.
        distance: Length,
        /// Signed driving offset-distance parameter, when dimensional.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_spatial_sketch_constraint_definition_input_parameter"
        )]
        parameter: Option<OffsetParameter>,
    },
    /// A regular profile entity copied from a projected reference entity.
    ProjectedCopy {
        /// Projected reference entity that supplies the geometry.
        source: SketchEntityId,
        /// Regular entity used by the profile.
        result: SketchEntityId,
    },
    /// A point locus lies at the intersection of two entities.
    AtIntersection {
        /// Point constrained to the intersection.
        point: SketchLocus,
        /// First intersecting entity.
        first: SketchEntityId,
        /// Second intersecting entity.
        second: SketchEntityId,
    },
    /// Circular or elliptical entities share a center.
    Concentric {
        /// First centered entity.
        first: SketchEntityId,
        /// Second centered entity.
        second: SketchEntityId,
    },
    /// Two circular entities share a center and radius.
    Coradial {
        /// First circular entity.
        first: SketchEntityId,
        /// Second circular entity.
        second: SketchEntityId,
    },
    /// Two line entities lie on one infinite line.
    Collinear {
        /// First line.
        first: SketchEntityId,
        /// Second line.
        second: SketchEntityId,
    },
    /// Two loci are symmetric about a line entity.
    Symmetric {
        /// First symmetric locus.
        first: SketchLocus,
        /// Second symmetric locus.
        second: SketchLocus,
        /// Symmetry axis.
        axis: SketchEntityId,
    },
    /// Two loci are centrally symmetric about a point.
    PointSymmetric {
        /// First symmetric locus.
        first: SketchLocus,
        /// Second symmetric locus.
        second: SketchLocus,
        /// Center of symmetry.
        center: SketchLocus,
    },
    /// Line is horizontal in sketch coordinates.
    Horizontal {
        /// Constrained entity.
        entity: SketchEntityId,
    },
    /// Line is vertical in sketch coordinates.
    Vertical {
        /// Constrained entity.
        entity: SketchEntityId,
    },
    /// Two entities are parallel.
    Parallel {
        /// First entity.
        first: SketchEntityId,
        /// Second entity.
        second: SketchEntityId,
    },
    /// Two entities are perpendicular.
    Perpendicular {
        /// First entity.
        first: SketchEntityId,
        /// Second entity.
        second: SketchEntityId,
    },
    /// Two entities are tangent.
    Tangent {
        /// First entity.
        first: SketchEntityId,
        /// Second entity.
        second: SketchEntityId,
    },
    /// Two bounded entities are tangent at explicit loci.
    TangentLoci {
        /// Tangency locus on the first entity.
        first: SketchLocus,
        /// Tangency locus on the second entity.
        second: SketchLocus,
    },
    /// Two entities have equal tangent direction and curvature at contact.
    Curvature {
        /// First entity.
        first: SketchEntityId,
        /// Second entity.
        second: SketchEntityId,
    },
    /// Two entities have equal size.
    Equal {
        /// First entity.
        first: SketchEntityId,
        /// Second entity.
        second: SketchEntityId,
    },
    /// Entity is fixed in sketch coordinates.
    Fixed {
        /// Fixed entity.
        entity: SketchEntityId,
    },
    /// Circular arc angle fixed by the relation kind.
    ArcAngle {
        /// Constrained circular arc.
        entity: SketchEntityId,
        /// Fixed positive arc angle in radians.
        angle: PositiveAngle,
    },
    /// Bounded ellipse parameter sweep fixed by the relation kind.
    EllipseAngle {
        /// Constrained bounded ellipse.
        entity: SketchEntityId,
        /// Fixed positive parameter sweep in radians.
        angle: PositiveAngle,
    },
    /// Distance controlled by a design parameter.
    Distance {
        /// Measured entities.
        entities: Vec<SketchEntityId>,
        /// Driving distance parameter.
        parameter: ParameterId,
    },
    /// Euclidean distance between two explicit loci.
    DistanceLoci {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
        /// Driving distance parameter.
        parameter: ParameterId,
    },
    /// Euclidean distance between two loci with a source-evaluated value.
    DistanceLociValue {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
        /// Non-negative measured distance in model units.
        distance: Length,
        /// Driving distance parameter, when the source supplies one.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_sketch_constraint_definition_input_parameter"
        )]
        parameter: Option<ParameterId>,
    },
    /// A second locus is displaced from the first by a polar sketch-space
    /// distance and direction.
    PolarDistance {
        /// Origin locus of the displacement.
        first: SketchLocus,
        /// Displaced locus.
        second: SketchLocus,
        /// Non-negative displacement length in model units.
        distance: Length,
        /// Direction from the sketch-u axis; absent when the displacement is
        /// zero and therefore has no defined direction.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_angle"
        )]
        angle: Option<Angle>,
        /// Driving distance parameter, when the source supplies one.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_distance_parameter"
        )]
        distance_parameter: Option<ParameterId>,
    },
    /// Direct difference between two angle-valued solver scalars.
    AngleDifference {
        /// Solver-local key of the first angle scalar.
        first: u32,
        /// Solver-local key of the second angle scalar.
        second: u32,
        /// Solver-local key of the difference scalar receiving `first - second`.
        difference: u32,
        /// Source-evaluated non-negative angle difference in radians.
        value: Angle,
    },
    /// Equality between two equality-class solver scalars.
    ScalarEquality {
        /// Solver-local key of the first equality-class scalar.
        first: u32,
        /// Solver-local key of the second equality-class scalar.
        second: u32,
    },
    /// Two explicit Euclidean locus pairs have equal separation.
    EqualDistance {
        /// First measured locus pair.
        first: SketchDistancePair,
        /// Second measured locus pair.
        second: SketchDistancePair,
    },
    /// Horizontal separation between two explicit loci.
    HorizontalDistance {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
        /// Driving horizontal-distance parameter.
        parameter: ParameterId,
    },
    /// Vertical separation between two explicit loci.
    VerticalDistance {
        /// First measured locus.
        first: SketchLocus,
        /// Second measured locus.
        second: SketchLocus,
        /// Driving vertical-distance parameter.
        parameter: ParameterId,
    },
    /// Multiple disjoint locus pairs controlled by one linear parameter.
    RepeatedDistance {
        /// Ordered independent measurements.
        measurements: Vec<SketchDistanceMeasurement>,
        /// Shared driving distance parameter.
        parameter: ParameterId,
    },
    /// Equal-length line entities controlled by one linear parameter.
    RepeatedLength {
        /// Distinct line entities sharing the driven length.
        entities: Vec<SketchEntityId>,
        /// Shared driving length parameter.
        parameter: ParameterId,
    },
    /// Distance between two parallel collinear line-entity sets.
    ParallelLineSetDistance {
        /// Collinear entities forming the first line carrier.
        first: Vec<SketchEntityId>,
        /// Collinear entities forming the second line carrier.
        second: Vec<SketchEntityId>,
        /// Driving distance parameter.
        parameter: ParameterId,
    },
    /// Angle controlled by a design parameter.
    Angle {
        /// First angular entity.
        first: SketchEntityId,
        /// Second angular entity.
        second: SketchEntityId,
        /// Driving angle parameter.
        parameter: ParameterId,
    },
    /// Angle from a canonical sketch axis to one line entity.
    AngleToAxis {
        /// Measured line entity.
        entity: SketchEntityId,
        /// Canonical sketch reference axis.
        axis: SketchAxis,
        /// Driving angle parameter.
        parameter: ParameterId,
    },
    /// Radius controlled by a design parameter.
    Radius {
        /// Circular or elliptical entity.
        entity: SketchEntityId,
        /// Driving radius parameter.
        parameter: ParameterId,
    },
    /// Equal-radius circular entities controlled by one design parameter.
    RepeatedRadius {
        /// Distinct circular entities sharing the driven radius.
        entities: Vec<SketchEntityId>,
        /// Shared driving radius parameter.
        parameter: ParameterId,
    },
    /// Diameter controlled by a design parameter.
    Diameter {
        /// Circular entity.
        entity: SketchEntityId,
        /// Driving diameter parameter.
        parameter: ParameterId,
    },
    /// Equal-diameter circular entities controlled by one design parameter.
    RepeatedDiameter {
        /// Distinct circular entities sharing the driven diameter.
        entities: Vec<SketchEntityId>,
        /// Shared driving diameter parameter.
        parameter: ParameterId,
    },
    /// Refraction relation between two curve loci and their interface.
    SnellsLaw {
        /// Incident curve locus.
        incident: SketchLocus,
        /// Refracted curve locus.
        refracted: SketchLocus,
        /// Interface entity carrying the surface normal in sketch space.
        interface: SketchEntityId,
        /// Dimensionless refractive-index ratio.
        parameter: ParameterId,
    },
    /// Rational spline weight controlled by a dimensionless parameter.
    Weight {
        /// Weighted spline entity.
        entity: SketchEntityId,
        /// Dimensionless weight parameter.
        parameter: ParameterId,
    },
    /// Relation between generated helper geometry and its parent conic or spline.
    InternalAlignment {
        /// Generated helper geometry.
        helper: SketchEntityId,
        /// Parent geometry receiving the alignment.
        parent: SketchEntityId,
        /// Exact helper relation family, including its B-spline index when required.
        alignment: SketchInternalAlignment,
    },
    /// Ordered geometry grouped under a sketch construction handle.
    Group {
        /// Group handle followed by its ordered member loci.
        elements: Vec<SketchLocus>,
    },
    /// Text constructed from an ordered set of sketch geometry.
    Text {
        /// Text handle followed by its ordered construction loci.
        elements: Vec<SketchLocus>,
        /// Displayed text.
        text: String,
        /// Font family or source font token, when carried.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_font"
        )]
        font: Option<String>,
        /// Whether the construction dimension controls text height rather than width.
        is_text_height: bool,
    },
    /// Source-native relation not yet reduced to a neutral family.
    Native {
        /// Source constraint family.
        #[serde(deserialize_with = "deserialize_native_kind")]
        native_kind: NonBlankString,
        /// Source-native constraint-state mask, when the format carries one.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_native_state"
        )]
        native_state: Option<u64>,
        /// Source-native constraint flags, when distinct from constraint state.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_native_flags"
        )]
        native_flags: Option<u64>,
        /// Exact source-native scalar properties not represented by common state or flags.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        #[serde(deserialize_with = "cadmpeg_core::distinct_keys::btree_map")]
        native_properties: BTreeMap<String, String>,
        /// Referenced entities.
        entities: Vec<SketchEntityId>,
        /// Driving or driven parameter attached to the relation.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_sketch_constraint_definition_input_parameter"
        )]
        parameter: Option<ParameterId>,
        /// Native operands whose neutral loci are unresolved.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        operands: Vec<SketchNativeOperand>,
    },
}

impl SketchConstraintDefinitionInput {
    /// The entity whose neutral geometry kind this relation restricts, with
    /// the kind it admits. Midpoint, arc-angle and ellipse-angle relations
    /// restrict their entity; other relations restrict no entity kind.
    #[must_use]
    pub fn entity_kind_restriction(
        &self,
    ) -> Option<(&SketchEntityId, SketchEntityKindRestriction)> {
        match self {
            Self::Midpoint { entity, .. } => {
                Some((entity, SketchEntityKindRestriction::BoundedCurve))
            }
            Self::ArcAngle { entity, .. } => {
                Some((entity, SketchEntityKindRestriction::CircularArc))
            }
            Self::EllipseAngle { entity, .. } => {
                Some((entity, SketchEntityKindRestriction::BoundedEllipse))
            }
            _ => None,
        }
    }
}

/// The neutral geometry kinds that a relation admits for its restricted entity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SketchEntityKindRestriction {
    /// A line, circular arc, bounded ellipse, hyperbola or parabola, or NURBS curve.
    BoundedCurve,
    /// A circular arc.
    CircularArc,
    /// A bounded ellipse.
    BoundedEllipse,
}

impl SketchEntityKindRestriction {
    /// Whether `geometry` has an admitted kind. External and native geometry
    /// has no neutral kind, so it is admitted.
    #[must_use]
    pub fn admits<P, L, R, W, D, M>(
        self,
        geometry: &SketchGeometryDefinition<P, L, R, W, D, M>,
    ) -> bool {
        if matches!(
            geometry,
            SketchGeometryDefinition::ExternalReference { .. }
                | SketchGeometryDefinition::Native { .. }
        ) {
            return true;
        }
        match self {
            Self::BoundedCurve => matches!(
                geometry,
                SketchGeometryDefinition::Line { .. }
                    | SketchGeometryDefinition::Arc { .. }
                    | SketchGeometryDefinition::Ellipse {
                        bounds: Some(_),
                        ..
                    }
                    | SketchGeometryDefinition::Hyperbola {
                        bounds: Some(_),
                        ..
                    }
                    | SketchGeometryDefinition::Parabola {
                        bounds: Some(_),
                        ..
                    }
                    | SketchGeometryDefinition::Nurbs { .. }
            ),
            Self::CircularArc => matches!(geometry, SketchGeometryDefinition::Arc { .. }),
            Self::BoundedEllipse => matches!(
                geometry,
                SketchGeometryDefinition::Ellipse {
                    bounds: Some(_),
                    ..
                }
            ),
        }
    }
}

crate::units::named_field!(
    deserialize_object,
    cadmpeg_core::text::NonBlankString,
    "object"
);
crate::units::named_field!(
    deserialize_native_kind,
    cadmpeg_core::text::NonBlankString,
    "native_kind"
);

#[cfg(test)]
mod tests;

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_name, String, "name");
cadmpeg_core::named_optional_field!(deserialize_configuration, String, "configuration");
cadmpeg_core::named_optional_field!(deserialize_visible, bool, "visible");
cadmpeg_core::named_optional_field!(deserialize_native_ref, String, "native_ref");
cadmpeg_core::named_optional_field!(deserialize_geometry_ref, String, "geometry_ref");
cadmpeg_core::named_optional_field!(deserialize_bounds, [Angle; 2], "bounds");
cadmpeg_core::named_optional_field!(
    deserialize_sketch_geometry_definition_bounds<R>,
    [R; 2],
    "bounds"
);
cadmpeg_core::named_optional_field!(deserialize_width_factor<W>, W, "width_factor");
cadmpeg_core::named_optional_field!(deserialize_placement<P>, TextPlacement<P>, "placement");
cadmpeg_core::named_optional_field!(
    deserialize_horizontal_alignment,
    SketchTextHorizontalAlignment,
    "horizontal_alignment"
);
cadmpeg_core::named_optional_field!(
    deserialize_vertical_alignment,
    SketchTextVerticalAlignment,
    "vertical_alignment"
);
cadmpeg_core::named_optional_field!(deserialize_document, String, "document");
cadmpeg_core::named_optional_field!(deserialize_native_state, u64, "native_state");
cadmpeg_core::named_optional_field!(
    deserialize_parameter,
    crate::features::ParameterId,
    "parameter"
);
cadmpeg_core::named_optional_field!(
    deserialize_spatial_sketch_constraint_definition_input_parameter,
    OffsetParameter,
    "parameter"
);
cadmpeg_core::named_optional_field!(deserialize_driving, bool, "driving");
cadmpeg_core::named_optional_field!(deserialize_active, bool, "active");
cadmpeg_core::named_optional_field!(deserialize_virtual_space, bool, "virtual_space");
cadmpeg_core::named_optional_field!(deserialize_orientation, u32, "orientation");
cadmpeg_core::named_optional_field!(
    deserialize_label_distance,
    SketchLabelValue,
    "label_distance"
);
cadmpeg_core::named_optional_field!(
    deserialize_label_position,
    SketchLabelValue,
    "label_position"
);
cadmpeg_core::named_optional_field!(deserialize_metadata, String, "metadata");
cadmpeg_core::named_optional_field!(deserialize_role, u32, "role");
cadmpeg_core::named_optional_field!(deserialize_field, NativeOperandField, "field");
cadmpeg_core::named_optional_field!(deserialize_object_index, u32, "object_index");
cadmpeg_core::named_optional_field!(deserialize_distance, SketchPatternDistance, "distance");
cadmpeg_core::named_optional_field!(deserialize_count_parameter, ParameterId, "count_parameter");
cadmpeg_core::named_optional_field!(deserialize_angle_parameter, ParameterId, "angle_parameter");
cadmpeg_core::named_optional_field!(
    deserialize_sketch_constraint_definition_input_parameter,
    ParameterId,
    "parameter"
);
cadmpeg_core::named_optional_field!(deserialize_angle, Angle, "angle");
cadmpeg_core::named_optional_field!(
    deserialize_distance_parameter,
    ParameterId,
    "distance_parameter"
);
cadmpeg_core::named_optional_field!(deserialize_font, String, "font");
cadmpeg_core::named_optional_field!(deserialize_native_flags, u64, "native_flags");

mod identity_rewrite;