BREP_construction 0.29.0

Rust B-rep CAD kernel (next.BREP.io): solid construction: extrusions, revolutions, sweeps and lofts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
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
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
//! Gear sections and gear solids.
//!
//! An involute gear is built the way it is cut: its section is the envelope of a
//! rack cutter rolled round the pitch circle. A rack point `q` with outward normal
//! `n` touches the gear when its normal passes through the pitch point; with the
//! gear's tooth 0 centred on +x, the rack's rolling line on `x = r` and the rack
//! displaced by `s` along +y, that is
//!
//! ```text
//!   s = (q.x - r) n.y / n.x - q.y,      gear point = Rot(-s / r) (q.x, q.y + s).
//! ```
//!
//! The cutter's straight flank generates the involute; its tip fillet (radius
//! `rho`) generates the root fillet, the equidistant of the trochoid traced by
//! the fillet's centre, and so the real undercut when the tooth count is small.
//! Neither curve is rational: each is fitted by a cubic B-spline (C1 Hermite
//! spans, refined until every span is within the fit bound of the closed form at
//! its sample parameters), while the tip and root lands are exact circular arcs.
use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
use std::f64::consts::{PI, TAU};

/// The fit bound of every fitted gear curve, as a fraction of the module: the
/// largest distance, at the span sample parameters, between a fitted curve and
/// its closed form.
pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;

/// The bound of a generated (envelope) gear surface against the meshing equation's points, as a fraction of
/// the module (the build spec's 1e-5 x module). A skinned surface is within the sum of its section fit's error
/// and its skin's (a B-spline surface stays within its control points' largest deviation), so the bound is
/// split: a quarter to the section fit in each plane, three quarters to the skin between planes.
pub const GEAR_GENERATED_TOLERANCE: f64 = 1e-5;
const GENERATED_SECTION_SHARE: f64 = 0.25;
const CROWN_SECTION_SHARE: f64 = 0.1;

/// An external spur gear generated by a standard rack cutter. Lengths in model
/// units, angles in radians; coefficients are multiples of the module.
#[derive(Clone, Debug)]
pub struct SpurGear {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    /// Profile shift coefficient x (the cutter moved out by x · module).
    pub profile_shift: f64,
    /// Addendum coefficient ha* (tip radius = r + (ha* + x) m).
    pub addendum: f64,
    /// Dedendum coefficient hf* (root radius = r - (hf* - x) m).
    pub dedendum: f64,
    /// Cutter tip radius coefficient rho_f*.
    pub root_fillet: f64,
    /// Circumferential backlash taken off the tooth thickness on the reference circle.
    pub backlash: f64,
    pub face_width: f64,
}

impl Default for SpurGear {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 20,
            pressure_angle: 20f64.to_radians(),
            profile_shift: 0.0,
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
        }
    }
}

/// Derived data of a generated gear (diameters in model units).
#[derive(Clone, Debug, Default)]
pub struct GearData {
    pub pitch_diameter: f64,
    pub base_diameter: f64,
    pub tip_diameter: f64,
    pub root_diameter: f64,
    /// Diameter where the involute flank meets the root fillet.
    pub form_diameter: f64,
    /// Tooth thickness on the reference (pitch) circle, arc length.
    pub tooth_thickness: f64,
    /// Tooth thickness on the tip circle, arc length.
    pub tip_thickness: f64,
    /// Whether the root fillet cuts into the involute (generated undercut).
    pub undercut: bool,
    /// The smallest profile shift at which this gear has no undercut.
    pub min_shift_without_undercut: f64,
}

/// One curve of a gear section with the face role it gives the solid.
#[derive(Clone, Debug)]
pub struct SectionCurve {
    pub curve: NurbsCurve,
    /// Face role: `V`/`W` root fillets, `R`/`L` flanks, `K` tip land, `G` root land.
    pub role: &'static str,
    pub tooth: usize,
}

impl SectionCurve {
    /// The face-name suffix this curve's face carries (`R3`, `K0`, …).
    pub fn suffix(&self) -> String {
        format!("{}{}", self.role, self.tooth)
    }
}

/// A closed gear section in the z = 0 plane, counter-clockwise about +z.
#[derive(Clone, Debug)]
pub struct GearSection {
    pub curves: Vec<SectionCurve>,
    pub data: GearData,
}

fn refuse(code: &str, message: String) -> KernelRefusal {
    KernelRefusal::input(KernelStage::Collect, code, message)
}

fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
    let (s, c) = angle.sin_cos();
    [c * point[0] - s * point[1], s * point[0] + c * point[1]]
}

fn polar_angle(point: [f64; 2]) -> f64 {
    point[1].atan2(point[0])
}

fn radius_of(point: [f64; 2]) -> f64 {
    point[0].hypot(point[1])
}

/// The rack cutter of a spur gear in the generating frame, and its envelope.
struct RackCutter {
    r: f64,
    alpha: f64,
    /// Reference line of the cutter (x).
    x_ref: f64,
    /// The cutter flank's y on the reference line.
    y0: f64,
    /// Root radius = the cutter tip line (x).
    r_f: f64,
    rho: f64,
    /// Tip fillet centre.
    centre: [f64; 2],
}

impl RackCutter {
    fn new(gear: &SpurGear) -> Self {
        let m = gear.module;
        let r = m * gear.teeth as f64 / 2.0;
        let p = PI * m;
        let alpha = gear.pressure_angle;
        let x_ref = r + gear.profile_shift * m;
        let y0 = p / 4.0 - gear.backlash / 2.0;
        let r_f = x_ref - gear.dedendum * m;
        let rho = gear.root_fillet * m;
        let x_c = r_f + rho;
        let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
        Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
    }

    /// The gear point generated by the rack point `q` with outward normal `n`.
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = (q[0] - self.r) * n[1] / n[0] - q[1];
        rotate([q[0], q[1] + s], -s / self.r)
    }

    /// The involute flank (left side of tooth 0) generated by the flank point at `x`.
    fn flank(&self, x: f64) -> [f64; 2] {
        let a = self.alpha;
        let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
        self.envelope(q, [-a.sin(), -a.cos()])
    }

    /// The root fillet (left side of tooth 0) generated by the cutter tip fillet
    /// at normal angle `psi` (0 = the tip line, pi/2 - alpha = the flank).
    fn fillet(&self, psi: f64) -> [f64; 2] {
        let n = [-psi.cos(), -psi.sin()];
        if self.rho == 0.0 {
            // A sharp cutter corner: the point is fixed, its normal still sweeps.
            return self.envelope(self.centre, n);
        }
        let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
        self.envelope(q, n)
    }

    /// The flank point x whose generated point lies at radius `radius` (the involute branch).
    fn flank_x_at_radius(&self, radius: f64) -> f64 {
        let c = 1.0 / self.alpha.tan();
        let c2 = c * c;
        let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
        (self.r * c2 + disc.sqrt()) / (1.0 + c2)
    }
}

/// A cubic B-spline (C1 Hermite spans) through `f` on `[a, b]`, refined until each
/// span is within `tolerance` of `f` at its sample parameters.
fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
    let derivative = |t: f64| {
        let h = 1e-6 * (b - a).abs().max(1e-12);
        let p = f(t + h);
        let q = f(t - h);
        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
    };
    let span_points = |t0: f64, t1: f64| {
        let (p0, p1) = (f(t0), f(t1));
        let (d0, d1) = (derivative(t0), derivative(t1));
        let k = (t1 - t0) / 3.0;
        [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
    };
    let bezier = |c: &[[f64; 2]; 4], u: f64| {
        let v = 1.0 - u;
        let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
        [
            w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
            w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
        ]
    };
    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
        let t0 = a + (b - a) * i as f64 / 4.0;
        let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
        (t0, t1, 0)
    }).collect();
    let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
    while let Some((t0, t1, depth)) = pending.pop() {
        let c = span_points(t0, t1);
        let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
            .iter()
            .map(|&u| {
                let exact = f(t0 + (t1 - t0) * u);
                let fitted = bezier(&c, u);
                (exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
            })
            .fold(0.0, f64::max);
        if worst > tolerance && depth < 16 {
            let mid = 0.5 * (t0 + t1);
            pending.push((mid, t1, depth + 1));
            pending.push((t0, mid, depth + 1));
        } else if worst > tolerance {
            return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
        } else {
            spans.push((t0, t1, c));
        }
    }
    // Knots in [0, 1] (normalised). The Hermite spans join with C1 continuity,
    // so each interior knot is doubled and the shared span end, which lies on
    // the segment between its two neighbours, is implied rather than stored.
    let scale = 1.0 / (b - a);
    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
    let mut knots = vec![0.0; 4];
    let mut points = vec![to_point(spans[0].2[0])];
    for (index, (_, t1, c)) in spans.iter().enumerate() {
        points.push(to_point(c[1]));
        points.push(to_point(c[2]));
        if index + 1 < spans.len() {
            let k = (t1 - a) * scale;
            knots.extend([k, k]);
        } else {
            points.push(to_point(c[3]));
        }
    }
    knots.extend([1.0; 4]);
    NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
}

fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
    let mut copy = curve.clone();
    for point in &mut copy.control_points {
        point.y = -point.y;
    }
    NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
}

fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
    let (s, c) = angle.sin_cos();
    let points = curve
        .control_points
        .iter()
        .map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
        .collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
}

fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
    make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
        .map_err(|error| refuse("gear_arc", error))
}

fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(gear.module, "module")?;
    positive(gear.face_width, "face width")?;
    positive(gear.addendum, "addendum coefficient")?;
    positive(gear.dedendum, "dedendum coefficient")?;
    if gear.teeth < 3 {
        return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    Ok(())
}

/// The section of an external spur gear, generated by its rack cutter.
pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    check_spur(gear, 35.0)?;
    generated_section(gear)
}

/// [`spur_section`] for a helical gear's transverse section, whose pressure
/// angle (already checked in the normal section) may exceed 35°.
fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    check_spur(gear, 60.0)?;
    generated_section(gear)
}

fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    let z = gear.teeth as f64;
    let rack = RackCutter::new(gear);
    let alpha = rack.alpha;
    let r = rack.r;
    let r_b = r * alpha.cos();
    let r_a = r + (gear.addendum + gear.profile_shift) * m;
    let r_f = rack.r_f;
    let half_pitch = PI / z;
    let tolerance = GEAR_FIT_TOLERANCE * m;

    if r_f <= 1e-9 * m {
        return Err(refuse(
            "root_below_centre",
            format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
        ));
    }
    // The cutter's tip land must stay; with too large a tip radius the two fillets cross.
    let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
    if rack.rho > rho_max + 1e-9 * m {
        return Err(refuse(
            "root_fillet_too_large",
            format!(
                "The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
                gear.root_fillet,
                rho_max / m
            ),
        ));
    }
    let psi_end = PI / 2.0 - alpha;
    let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
    let x_interference = r * alpha.cos().powi(2);
    let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
    let undercut = x_flank_tangent < x_interference - 1e-12 * m;

    // The junction J of the left flank and its root fillet.
    let (x_join, psi_join) = if !undercut {
        (x_flank_tangent, psi_end)
    } else {
        // The fillet cuts the involute. Above the base circle the fillet lies
        // outside the involute at the flank tangency (psi_end) and inside it
        // just above the base circle, so the crossing is in [psi_base, psi_end],
        // where psi_base is the fillet's base-circle crossing (its radius rises
        // from the root, which is below the base circle here). Search that
        // interval at a resolution relative to its own width, so a gear just
        // past the undercut limit (a very short interval) is found too.
        let difference = |psi: f64| -> Option<f64> {
            let point = rack.fillet(psi);
            let radius = radius_of(point);
            if radius <= r_b {
                return None;
            }
            Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
        };
        let (mut below, mut above) = (0.0, psi_end);
        for _ in 0..200 {
            let mid = 0.5 * (below + above);
            if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
        }
        let psi_base = above;
        let steps = 4000;
        let mut found = None;
        let mut previous: Option<(f64, f64)> = None;
        for step in 0..=steps {
            let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
            if let Some(value) = difference(psi) {
                if let Some((last_psi, last_value)) = previous {
                    if (value <= 0.0) != (last_value <= 0.0) {
                        found = Some((psi, last_psi));
                        break;
                    }
                }
                previous = Some((psi, value));
            }
        }
        // No crossing resolvable above the base circle: the fillet meets the
        // flank at the base circle itself (the undercut limit).
        let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
        let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            match difference(mid) {
                Some(value) if (value <= 0.0) == sign_lo => lo = mid,
                Some(_) => hi = mid,
                None => lo = mid,
            }
        }
        let psi = 0.5 * (lo + hi);
        (rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
    };
    let join = rack.fillet(psi_join);
    let form_radius = radius_of(join);
    if r_a <= form_radius + 1e-9 * m {
        return Err(refuse(
            "tip_below_form",
            format!(
                "The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
                2.0 * r_a,
                2.0 * form_radius
            ),
        ));
    }
    let x_tip = rack.flank_x_at_radius(r_a);
    let tip = rack.flank(x_tip);
    // Half the tooth thickness angle at a radius (the textbook involute form,
    // unwrapped: a polar angle read off a crossed flank wraps round and would
    // pass a tooth whose flanks crossed below the tip).
    let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
    let involute = |angle: f64| angle.tan() - angle;
    let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
    let tip_angle = half_angle(r_a);
    let tip_offset = polar_angle(tip) - tip_angle;
    if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
        // Where the flanks meet: half_angle falls as the radius grows.
        let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
        }
        return Err(refuse(
            "pointed_tip",
            format!(
                "The teeth come to a point at d = {:.4}, inside the tip circle (d = {:.4}); reduce the addendum or the profile shift, or add teeth.",
                2.0 * lo,
                2.0 * r_a
            ),
        ));
    }
    if tip_angle >= half_pitch {
        return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
    }
    // Fillet samples must stay inside the half space (else neighbouring gaps cross).
    for step in 0..=64 {
        let point = rack.fillet(psi_join * step as f64 / 64.0);
        let angle = polar_angle(point);
        if angle <= 0.0 || angle > half_pitch + 1e-12 {
            return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
        }
    }

    let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; // J -> tip
    let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; // root -> J
    let root_angle = rack.centre[1] / r;
    let land = 2.0 * half_pitch - 2.0 * root_angle;

    // Tooth 0, counter-clockwise: V (root -> J_R), R (J_R -> tip), K, L (tip -> J), W (J -> root), G.
    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
        ("V", mirrored(&fillet_fit)),
        ("R", mirrored(&flank_fit)),
        ("K", arc(r_a, -tip_angle, tip_angle)?),
        ("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
        ("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
    ];
    if land > 1e-9 {
        tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
    }

    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = TAU * index as f64 / z;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    // Share every junction exactly: each curve ends on the next one's first point.
    snap_junctions(&mut curves);

    let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
    let data = GearData {
        pitch_diameter: 2.0 * r,
        base_diameter: 2.0 * r_b,
        tip_diameter: 2.0 * r_a,
        root_diameter: 2.0 * r_f,
        form_diameter: 2.0 * form_radius,
        tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
        tip_thickness: 2.0 * r_a * tip_angle,
        undercut,
        min_shift_without_undercut: min_shift,
    };
    Ok(GearSection { curves, data })
}

/// A spur gear solid: the section extruded along +z by the face width. The face
/// names (suffixes, in the solid's face order) are the section curves' roles,
/// then `F` (the z = 0 face) and `B` (the z = width face).
pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = spur_section(gear)?;
    let solid = extrude_section(&section, gear.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// An intermittent (mutilated) spur gear: only teeth 0 .. `kept` of the full gear, the rest of the rim an exact
/// arc. Without `locking` the gap is the root circle; with it, past one root land after the last tooth and before
/// the first (room for the driven gear's tooth to leave and enter), the rim rises radially to an arc on the tip
/// circle that locks the driven gear between steps. Names: the kept teeth as the spur gear's, `S` the gap's arc,
/// `E0`/`E1` the locking arc's radial ends, then `F`, `B`.
pub fn spur_sector_solid(gear: &SpurGear, kept: usize, locking: bool) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let full = spur_section(gear)?;
    let z = gear.teeth;
    if !(1..z).contains(&kept) {
        return Err(refuse("gear_input", format!("A sector keeps from 1 to {} of the {z} teeth (not {kept}).", z - 1)));
    }
    if locking && kept + 2 > z {
        return Err(refuse("gear_input", "A locking arc needs at least two teeth left out (a root land each side).".into()));
    }
    let point = |curve: &NurbsCurve, end: bool| -> Result<[f64; 2], KernelRefusal> {
        let [a, b] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let p = curve.evaluate(if end { b } else { a }).map_err(|e| refuse("gear_eval", e))?;
        Ok([p.x, p.y])
    };
    let unwrap_ccw = |from: f64, to: f64| from + (to - from).rem_euclid(TAU);
    let mut curves: Vec<SectionCurve> = full.curves.iter().filter(|c| c.tooth < kept).cloned().collect();
    let first = full.curves.iter().find(|c| c.tooth == 0).expect("tooth 0").curve.clone();
    let start = point(&first, false)?; // tooth 0's first piece: where the rim comes back
    let root_r = radius_of(start);
    if locking {
        // Keep the root land after the last tooth and the one before tooth 0; between them the locking arc.
        let after = full.curves.iter().filter(|c| c.tooth == kept).next().expect("the next tooth").curve.clone();
        let rise = point(&after, false)?; // where tooth `kept` would start
        let before_land = full.curves.iter().filter(|c| c.tooth == z - 1 && c.role == "G").last().map(|c| c.curve.clone());
        let Some(before_land) = before_land else {
            return Err(refuse("gear_input", "This gear has no root land for a locking arc.".into()));
        };
        let fall = point(&before_land, false)?; // where the land before tooth 0 starts
        let tip_r = full.data.tip_diameter / 2.0;
        let (a0, a1) = (polar_angle(rise), polar_angle(fall));
        let a1 = unwrap_ccw(a0, a1);
        let up = [tip_r * a0.cos(), tip_r * a0.sin()];
        let down = [tip_r * a1.cos(), tip_r * a1.sin()];
        curves.push(SectionCurve { curve: line(rise, up)?, role: "E", tooth: 0 });
        curves.push(SectionCurve { curve: arc(tip_r, a0, a1)?, role: "S", tooth: 0 });
        curves.push(SectionCurve { curve: line(down, fall)?, role: "E", tooth: 1 });
        curves.push(SectionCurve { curve: before_land, role: "G", tooth: z - 1 });
    } else {
        // Drop the last kept tooth's root land: the root circle runs on to tooth 0.
        if curves.last().is_some_and(|c| c.role == "G") {
            curves.pop();
        }
        let end = point(&curves.last().expect("a kept tooth").curve, true)?;
        let (a0, a1) = (polar_angle(end), polar_angle(start));
        curves.push(SectionCurve { curve: arc(root_r, a0, unwrap_ccw(a0, a1))?, role: "S", tooth: 0 });
    }
    snap_junctions(&mut curves);
    let section = GearSection { curves, data: full.data };
    let solid = extrude_section(&section, gear.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// Extrude a counter-clockwise gear section along +z.
pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
}

/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
/// Each end stops in the middle of a tooth space.
#[derive(Clone, Debug)]
pub struct Rack {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    /// Root fillet radius coefficient (× module).
    pub root_fillet: f64,
    /// Circumferential backlash taken off the tooth thickness on the pitch line.
    pub backlash: f64,
    pub face_width: f64,
    /// Distance from the pitch line down to the rack's back face.
    pub height: f64,
    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
    /// angle and coefficients are then those of the normal section. Positive
    /// leans the teeth one way (right hand), negative the other.
    pub helix_angle: f64,
}

impl Default for Rack {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 10,
            pressure_angle: 20f64.to_radians(),
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
            height: 6.0,
            helix_angle: 0.0,
        }
    }
}

fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
    crate::make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)).map_err(|error| refuse("gear_line", error))
}

fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
    make_arc(Vec3::new(centre[0], centre[1], 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
        .map_err(|error| refuse("gear_arc", error))
}

/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
/// and `E1` the ends at x = 0 and x = length.
pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
    rack_section_checked(rack, 35.0)
}

fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
    let m = rack.module;
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(m, "module")?;
    positive(rack.face_width, "face width")?;
    positive(rack.addendum, "addendum coefficient")?;
    positive(rack.dedendum, "dedendum coefficient")?;
    if rack.teeth < 1 {
        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
    }
    let degrees = rack.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    let alpha = rack.pressure_angle;
    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
    if rack.height <= hf + 1e-9 * m {
        return Err(refuse(
            "rack_too_thin",
            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
        ));
    }
    let p = PI * m;
    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
    let tip_half = w - ha * alpha.tan();
    if tip_half <= 1e-6 * m {
        return Err(refuse(
            "pointed_tip",
            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
        ));
    }
    let rho = rack.root_fillet * m;
    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
    let y_p = -hf + rho - rho * alpha.sin();
    let flank_x = |y: f64| w - y * alpha.tan();
    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
    if y_p >= ha - 1e-9 * m {
        return Err(refuse(
            "root_fillet_too_large",
            format!(
                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
                rack.root_fillet
            ),
        ));
    }
    if root_half > p / 2.0 + 1e-9 * m {
        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
        return Err(refuse(
            "root_fillet_too_large",
            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
        ));
    }
    let length = p * rack.teeth as f64;
    let mut curves: Vec<SectionCurve> = Vec::new();
    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
    let base = -rack.height;
    push(line([0.0, base], [length, base])?, "BASE", 0);
    push(line([length, base], [length, -hf])?, "E1", 0);
    // Teeth from the right end leftwards (counter-clockwise along the top).
    let mut x_prev_root = length; // where the current root land starts (right end)
    for k in (0..rack.teeth).rev() {
        let c = (k as f64 + 0.5) * p;
        let right_root = [c + root_half, -hf];
        if x_prev_root - right_root[0] > 1e-9 * m {
            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
        }
        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
        let right_centre = [c + centre[0], centre[1]];
        let right_flank_low = [c + flank_x(y_p), y_p];
        if rho > 0.0 {
            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
        }
        let right_tip = [c + tip_half, ha];
        let left_tip = [c - tip_half, ha];
        let left_flank_low = [c - flank_x(y_p), y_p];
        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
        push(line(right_tip, left_tip)?, "K", k);
        let left_root = [c - root_half, -hf];
        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
        if rho > 0.0 {
            let left_centre = [c - centre[0], centre[1]];
            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
        }
        x_prev_root = left_root[0];
    }
    if x_prev_root > 1e-9 * m {
        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
    }
    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
    // Share every junction exactly.
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: f64::INFINITY,
        tooth_thickness: 2.0 * w,
        tip_thickness: 2.0 * tip_half,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A rack solid: the section extruded along +z by the face width; names as
/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let beta = rack.helix_angle;
    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    // A helical rack's transverse section (the plane z = const) is the rack of
    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
    let degrees = rack.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    if beta == 0.0 {
        // Straight teeth: the rack exactly as given (no transverse conversion).
        let section = rack_section(rack)?;
        let solid = extrude_section(&section, rack.face_width)?;
        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
        names.push("F".into());
        names.push("B".into());
        return Ok((solid, names, section.data));
    }
    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
    // normal section (across the teeth) is the basic rack; the transverse
    // section (z = const) is that section stretched along the rack by
    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
    // (still rational quadratic arcs).
    let c = beta.cos();
    let mut section = rack_section(rack)?;
    for piece in &mut section.curves {
        for point in &mut piece.curve.control_points {
            point.x /= c;
        }
    }
    // The recorded thicknesses are read along the rack (transverse), as the section is.
    section.data.tooth_thickness /= c;
    section.data.tip_thickness /= c;
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

fn rack_suffix(piece: &SectionCurve) -> String {
    match piece.role {
        "BASE" | "E0" | "E1" => piece.role.to_string(),
        _ => piece.suffix(),
    }
}

/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
fn snap_junctions(curves: &mut [SectionCurve]) {
    let count = curves.len();
    for index in 0..count {
        let start = curves[(index + 1) % count].curve.control_points[0];
        let curve = &mut curves[index].curve;
        let last = curve.control_points.len() - 1;
        let w = curve.control_points[last].w;
        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
    }
}

/// An internal (ring) gear: involute tooth spaces cut into the inside of a
/// ring. Lengths in model units, angles in radians, coefficients × module.
#[derive(Clone, Debug)]
pub struct RingGear {
    pub module: f64,
    pub teeth: usize,
    pub pressure_angle: f64,
    /// Profile shift: the cutter moved outward by x · module (tip and root
    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
    pub profile_shift: f64,
    pub addendum: f64,
    pub dedendum: f64,
    /// Radius of the root fillet (× module): an exact arc tangent to the
    /// flank and the root circle.
    pub root_fillet: f64,
    /// Circumferential backlash added to each tooth space on the reference circle.
    pub backlash: f64,
    pub face_width: f64,
    /// Radial wall beyond the root circle.
    pub rim: f64,
}

impl Default for RingGear {
    fn default() -> Self {
        Self {
            module: 2.0,
            teeth: 60,
            pressure_angle: 20f64.to_radians(),
            profile_shift: 0.0,
            addendum: 1.0,
            dedendum: 1.25,
            root_fillet: 0.38,
            backlash: 0.0,
            face_width: 10.0,
            rim: 6.0,
        }
    }
}

/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
/// the ring tooth after the space.
pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
    ring_section_checked(gear, 35.0)
}

fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    let positive = |value: f64, what: &str| {
        if value.is_finite() && value > 0.0 {
            Ok(())
        } else {
            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
        }
    };
    positive(m, "module")?;
    positive(gear.face_width, "face width")?;
    positive(gear.addendum, "addendum coefficient")?;
    positive(gear.dedendum, "dedendum coefficient")?;
    positive(gear.rim, "rim thickness")?;
    if gear.teeth < 6 {
        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
    }
    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    let z = gear.teeth as f64;
    let alpha = gear.pressure_angle;
    let r = m * z / 2.0;
    let r_b = r * alpha.cos();
    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
    let rho = gear.root_fillet * m;
    let half_pitch = PI / z;
    let tolerance = GEAR_FIT_TOLERANCE * m;
    if r_a <= r_b + 1e-9 * m {
        return Err(refuse(
            "tip_inside_base",
            format!(
                "An internal gear's tip circle (d = {:.4}) must lie outside its base circle (d = {:.4}); raise the tooth count, lower the pressure angle or the addendum.",
                2.0 * r_a,
                2.0 * r_b
            ),
        ));
    }
    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
    let involute = |angle: f64| angle.tan() - angle;
    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
    let flank = |radius: f64| {
        let angle = half_space(radius);
        [radius * angle.cos(), radius * angle.sin()]
    };
    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
        return Err(refuse(
            "pointed_tip",
            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
        ));
    }
    // The spaces narrow outward: one that closes before the root circle has
    // crossed flanks (read unwrapped, from the closed form).
    if half_space(r_f) <= 1e-6 * m / r_f {
        let (mut lo, mut hi) = (r_a, r_f);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
        }
        return Err(refuse(
            "teeth_overlap",
            format!(
                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
                2.0 * lo,
                2.0 * r_f
            ),
        ));
    }
    // The fillet: a circle of radius rho tangent to the flank (left side of
    // space 0, at T) and inside the root circle. Its centre is T moved by rho
    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
    let normal_into_space = |radius: f64| {
        let h = 1e-6 * m;
        let (a, b) = (flank(radius - h), flank(radius + h));
        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
        let length = tx.hypot(ty);
        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
        [ty / length, -tx / length]
    };
    let centre_at = |radius: f64| {
        let point = flank(radius);
        let n = normal_into_space(radius);
        [point[0] + rho * n[0], point[1] + rho * n[1]]
    };
    let (join_radius, centre) = if rho == 0.0 {
        (r_f, flank(r_f))
    } else {
        let target = r_f - rho;
        let (mut lo, mut hi) = (r_a, r_f);
        if radius_of(centre_at(lo)) > target {
            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
        }
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
        }
        let radius = 0.5 * (lo + hi);
        (radius, centre_at(radius))
    };
    let root_angle = polar_angle(centre);
    if rho > 0.0 && root_angle <= 1e-9 {
        return Err(refuse(
            "root_fillet_too_large",
            "The root fillet is larger than fits the tooth space; lower it.".into(),
        ));
    }
    let tip_angle = half_space(r_a);
    // Left flank of space 0 from its root end (join) in to the tip circle.
    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
    space.push(("R", mirrored(&flank_fit)));
    if rho > 0.0 {
        // The left fillet runs counter-clockwise about its centre from the root
        // tangent point (straight out from the centre) round to the flank join.
        let join = flank(join_radius);
        let from = root_angle;
        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
        while to <= from {
            to += TAU;
        }
        let left = centred_arc(centre, rho, from, to)?; // root -> join
        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
        space.push(("G", arc(r_f, -root_angle, root_angle)?));
        space.push(("W", left));
    } else {
        space.push(("G", arc(r_f, -root_angle, root_angle)?));
    }
    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = TAU * index as f64 / z;
        for (role, curve) in &space {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: 2.0 * r,
        base_diameter: 2.0 * r_b,
        tip_diameter: 2.0 * r_a,
        root_diameter: 2.0 * r_f,
        form_diameter: 2.0 * join_radius,
        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
        undercut: false,
        min_shift_without_undercut: 0.0,
    };
    Ok(GearSection { curves, data })
}

/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let section = ring_section(gear)?;
    let outer = section.data.root_diameter / 2.0 + gear.rim;
    let width = gear.face_width;
    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * width, w: p.w }];
    let ring = hollow_prism(&section, outer, width, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
    Ok((ring, section.data))
}

/// A helical (or double helical) ring gear: `gear` in the normal section,
/// its transverse section screwed through the blank. Names as [`ring_solid`].
pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let beta = helix_angle;
    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    let normal = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
    }
    let c = beta.cos();
    let transverse = RingGear {
        module: gear.module / c,
        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
        profile_shift: gear.profile_shift * c,
        addendum: gear.addendum * c,
        dedendum: gear.dedendum * c,
        root_fillet: gear.root_fillet * c,
        ..gear.clone()
    };
    let section = ring_section_checked(&transverse, 60.0)?;
    let r = transverse.module * transverse.teeth as f64 / 2.0;
    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
    let rate = sign * beta.tan() / r; // turn per unit height
    let outer = section.data.root_diameter / 2.0 + gear.rim;
    // The section carried up the face width turning at the helix's rate (out and back for double helical).
    let width = gear.face_width;
    let turn = rate * width;
    let twist = if herringbone { Twist::Herringbone { turn } } else { Twist::Helical { turn } };
    let reach = section.curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
    let (knots_v, basis) = twist_basis(twist, reach, GEAR_FIT_TOLERANCE * transverse.module)?;
    let rows = |p: Vec4| -> Vec<Vec4> { basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect() };
    let ring = hollow_prism(&section, outer, width, 3, &knots_v, &rows)?;
    Ok((ring, section.data))
}

fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
    let points = curve.control_points.iter().map(|p| Vec4 { x: p.x, y: p.y, z: p.z + p.w * dz, w: p.w }).collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
}

/// Which ISO 606 tooth form a sprocket is cut to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SprocketForm {
    /// Smallest seating radius, largest flank radius, largest seating angle.
    Minimum,
    /// Largest seating radius, smallest flank radius, smallest seating angle.
    Maximum,
    /// The mean of the two.
    Mean,
}

/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
#[derive(Clone, Debug)]
pub struct Sprocket {
    pub pitch: f64,
    pub roller_diameter: f64,
    pub teeth: usize,
    pub form: SprocketForm,
    /// Tooth width across the sprocket (the extrusion).
    pub width: f64,
}

/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
/// (absent when the flanks meet below the tip circle).
pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
    let p = sprocket.pitch;
    let d1 = sprocket.roller_diameter;
    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
        return Err(refuse(
            "gear_input",
            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
        ));
    }
    if sprocket.teeth < 6 || sprocket.teeth > 300 {
        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
    }
    let z = sprocket.teeth as f64;
    let tau = TAU / z;
    let d = p / (PI / z).sin();
    // ISO 606 tooth form limits.
    let ri_min = 0.505 * d1;
    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
    let re_min = 0.008 * d1 * (z * z + 180.0);
    let re_max = 0.12 * d1 * (z + 2.0);
    let a_min = (120.0 - 90.0 / z).to_radians();
    let a_max = (140.0 - 90.0 / z).to_radians();
    let da_min = d + p * (1.0 - 1.6 / z) - d1;
    let da_max = d + 1.25 * p - d1;
    let (ri, re, alpha, da) = match sprocket.form {
        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
        SprocketForm::Mean => (0.5 * (ri_min + ri_max), 0.5 * (re_min + re_max), 0.5 * (a_min + a_max), 0.5 * (da_min + da_max)),
    };
    let ra = da / 2.0;
    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
    let c = [d / 2.0, 0.0];
    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
    // is centred on the line at angle tau / 2 (built frame).
    let half = tau / 2.0;
    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
    // Walk the flank circle from t_up in the sense that moves away from the axis.
    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
    let step = 1e-4;
    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
    let reach = |angle: f64| {
        let q = on_flank(angle);
        (radius_of(q) >= ra, polar_angle(q) >= half)
    };
    let (mut lo, mut hi) = (0.0, PI / 2.0);
    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
    }
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        let (tip, centre) = reach(a_t + sense * mid);
        if tip || centre { hi = mid } else { lo = mid }
    }
    let a_end = a_t + sense * hi;
    let end = on_flank(a_end);
    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
    let (a_end, end) = if pointed {
        // Land exactly on the tooth centre line.
        let (mut lo, mut hi) = (0.0, hi);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
        }
        let a = a_t + sense * hi;
        (a, on_flank(a))
    } else {
        (a_end, end)
    };
    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
    };
    let upper = flank_arc(a_t, a_end)?; // t_up -> end
    let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; // t_down -> t_up
    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
    let tip_angle = polar_angle(end);
    if !pointed {
        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
    }
    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
    for index in 0..sprocket.teeth {
        let angle = tau * index as f64 + half;
        for (role, curve) in &gap {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: d,
        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
        root_diameter: d - 2.0 * ri,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A sprocket solid: the section extruded along +z by the width; names as
/// [`sprocket_section`], then `F` and `B`.
pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = sprocket_section(sprocket)?;
    let solid = extrude_section(&section, sprocket.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The turn of a twisted prism's section along its height: `theta(t)` at
/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
/// herringbone's apex).
#[derive(Clone, Copy, Debug)]
pub enum Twist {
    /// theta = turn · t (a helical gear: a screw motion).
    Helical { turn: f64 },
    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
    Herringbone { turn: f64 },
}

impl Twist {
    fn angle(&self, t: f64) -> f64 {
        match *self {
            Twist::Helical { turn } => turn * t,
            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
        }
    }

    fn rate(&self, t: f64, after_crease: bool) -> f64 {
        match *self {
            Twist::Helical { turn } => turn,
            Twist::Herringbone { turn } => {
                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
            }
        }
    }

    fn total_turn(&self) -> f64 {
        match *self {
            Twist::Helical { turn } => turn.abs(),
            Twist::Herringbone { turn } => turn.abs(),
        }
    }
}

/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
    let crease = matches!(twist, Twist::Herringbone { .. });
    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
    let needed = twist.total_turn() / per;
    if !(needed <= 4096.0) {
        return Err(refuse(
            "twist_too_long",
            format!(
                "The teeth turn {:.3} times round the axis over the face width; shorten the face width or lower the helix angle (at most {:.1} turns at this size).",
                twist.total_turn() / TAU,
                4096.0 * per / TAU
            ),
        ));
    }
    let mut spans = (needed.ceil() as usize).max(1);
    if crease && spans % 2 == 1 {
        spans += 1;
    }
    let value = |t: f64| {
        let a = twist.angle(t);
        [a.cos(), a.sin(), t]
    };
    let slope = |t: f64, after: bool| {
        let a = twist.angle(t);
        let r = twist.rate(t, after);
        [-a.sin() * r, a.cos() * r, 1.0]
    };
    let mut knots = vec![0.0; 4];
    let mut points = vec![value(0.0)];
    for index in 0..spans {
        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
        let h = (t1 - t0) / 3.0;
        let (p0, p1) = (value(t0), value(t1));
        let (d0, d1) = (slope(t0, true), slope(t1, false));
        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
        let last = index + 1 == spans;
        let at_crease = crease && 2 * (index + 1) == spans;
        if last {
            points.push(p1);
        } else if at_crease {
            points.push(p1);
            knots.extend([t1, t1, t1]);
        } else {
            knots.extend([t1, t1]);
        }
    }
    knots.extend([1.0; 4]);
    Ok((knots, points))
}

/// Carry a section curve along the twist: the curve turned by theta and lifted


/// A counter-clockwise section (z = 0) carried up to z = width while turning
/// by `twist`: side faces in section order, then the face at z = 0, then the
/// face at z = width (exactly the section turned by the end angle).
pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
    if !(width > 0.0) {
        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
    }
    let reach = section
        .curves
        .iter()
        .flat_map(|c| c.curve.control_points.iter())
        .map(|p| (p.x / p.w).hypot(p.y / p.w))
        .fold(0.0, f64::max);
    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
    let rows = |p: Vec4| -> Vec<Vec4> {
        basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect()
    };
    prism_by_rows(section, 3, &knots_v, &rows)
}

/// The section's largest distance from the z axis, read off the curves (a rational arc's middle control
/// point lies outside the arc).
fn section_reach(section: &GearSection) -> Result<f64, KernelRefusal> {
    let mut reach: f64 = 0.0;
    for piece in &section.curves {
        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        for i in 0..=32 {
            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
            reach = reach.max(p.x.hypot(p.y));
        }
    }
    Ok(reach)
}

/// A cylinder of `radius` and `height` with the counter-clockwise planar section (in z = z0, read off the
/// section) carried through it by `rows` (as [`prism_by_rows`] carries it; the last row planar at z0 + `height`)
/// taken out:
/// a ring gear or a spline hub, built directly rather than as a boolean. The section's faces are named by
/// their role (`R3`, `G0`, …), the cylinder `OD`, the face at z = 0 `F` and the face at z = `height` `B`.
pub fn hollow_prism(section: &GearSection, radius: f64, height: f64, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    if !(height > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
        return Err(refuse("gear_input", format!("The ring's outside radius ({radius}) must clear its section and its height ({height}) be positive.")));
    }
    let count = section.curves.len();
    let z0 = section.curves.first().map(|c| c.curve.control_points[0]).map(|p| p.z / p.w).unwrap_or(0.0);
    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
    // The walls: junction j starts curve j at the bottom and the top, joined by its v-curve.
    let mut bottom_v = Vec::with_capacity(count);
    let mut top_v = Vec::with_capacity(count);
    let mut axial = Vec::with_capacity(count);
    for piece in &section.curves {
        let start = piece.curve.control_points[0];
        let unit = Vec4 { x: start.x / start.w, y: start.y / start.w, z: start.z / start.w, w: 1.0 };
        let row = rows(unit);
        let (b, t) = (shell.vertex(point_of(start)), shell.vertex(point_of(*row.last().expect("a row"))));
        let curve = NurbsCurve::new(degree_v, knots_v.to_vec(), row).map_err(|e| refuse("gear_edge", e))?;
        axial.push(shell.edge(curve, b, t)?);
        bottom_v.push(b);
        top_v.push(t);
    }
    let mut bottom_e = Vec::with_capacity(count);
    let mut top_e = Vec::with_capacity(count);
    for (index, piece) in section.curves.iter().enumerate() {
        let next = (index + 1) % count;
        let top = NurbsCurve::new(piece.curve.degree, piece.curve.knots.clone(), piece.curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect()).map_err(|e| refuse("gear_curve", e))?;
        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
        top_e.push(shell.edge(top, top_v[index], top_v[next])?);
    }
    for (index, piece) in section.curves.iter().enumerate() {
        let next = (index + 1) % count;
        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let grid: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| rows(*p)).collect();
        let surface = NurbsSurface::new(piece.curve.degree, degree_v, piece.curve.knots.clone(), knots_v.to_vec(), grid).map_err(|e| refuse("gear_surface", e))?;
        let loops = vec![vec![
            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
        ]];
        // The section's outward normal points into the hole: the solid lies outside it.
        shell.face(surface, false, loops, piece.suffix())?;
    }
    // The outside cylinder, one face with a seam at angle 0.
    let circle = crate::make_arc(Vec3::new(0.0, 0.0, z0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
    let lifted = translated(&circle, height);
    let (b0, t0) = (shell.vertex(Vec3::new(radius, 0.0, z0)), shell.vertex(Vec3::new(radius, 0.0, z0 + height)));
    let bottom_circle = shell.edge(circle.clone(), b0, b0)?;
    let top_circle = shell.edge(lifted.clone(), t0, t0)?;
    let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, z0), Vec3::new(radius, 0.0, z0 + height)).map_err(|e| refuse("gear_edge", e))?, b0, t0)?;
    let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
    let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
    let loops = vec![vec![
        (bottom_circle, true, line([c0, 0.0], [c1, 0.0])?),
        (seam, true, line([c1, 0.0], [c1, 1.0])?),
        (top_circle, false, line([c0, 1.0], [c1, 1.0])?),
        (seam, false, line([c0, 0.0], [c0, 1.0])?),
    ]];
    shell.face(side, true, loops, "OD".into())?;
    // The two ends: the outer circle round the section's hole.
    let pad = radius * 1.1 + 1.0;
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    for (z, name, ring_edge, hole) in [(z0, "F", bottom_circle, &bottom_e), (z0 + height, "B", top_circle, &top_e)] {
        let origin = Vec3::new(-pad, -pad, z);
        let on_plane = |curve: &NurbsCurve| curve_to_plane_parameters(curve, origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
        let outer = vec![(ring_edge, true, on_plane(shell.curve(ring_edge))?)];
        let mut inner = Vec::with_capacity(count);
        for &edge in hole.iter() {
            inner.push((edge, true, on_plane(shell.curve(edge))?));
        }
        let plane = make_plane(origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
        shell.face(plane, name == "B", vec![outer, inner], name.into())?;
    }
    let id = shell.id();
    let shell_id = shell.id();
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id,
        vertices: shell.vertices,
        edges: shell.edges,
        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
        genus: 1,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("hollow gear prism is not valid: {issues:?}")));
    }
    Ok(solid)
}

/// A planar counter-clockwise section (in a plane z = const) carried along
/// v in [0, 1] by `rows`, which maps each homogeneous control point to the
/// control points of its v-curve (degree `degree_v` on `knots_v`); the last
/// row must again be planar at a constant z (the top cap). Side faces in
/// section order, then the face at v = 0, then the face at v = 1.
pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
    let count = curves.len();
    let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
        let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
        NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
    };
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
    let mut vertices = Vec::with_capacity(2 * count);
    for (index, start) in starts.iter().enumerate() {
        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
    }
    for (index, start) in starts.iter().enumerate() {
        vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
    }
    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
    let mut edges = Vec::with_capacity(3 * count);
    let mut tops = Vec::with_capacity(count);
    for (index, curve) in curves.iter().enumerate() {
        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let next = (index + 1) % count;
        let top = top_of(curve)?;
        let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
        edges.push(EdgeRecord { id: edge_id(0, index), curve: curve.clone(), t0: start, t1: end, start_vertex_id: index as u64 + 1, end_vertex_id: next as u64 + 1, degenerate: false, name: None });
        edges.push(EdgeRecord { id: edge_id(1, index), curve: top.clone(), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
        edges.push(EdgeRecord { id: edge_id(2, index), curve: axial, t0: 0.0, t1: 1.0, start_vertex_id: index as u64 + 1, end_vertex_id: (count + index) as u64 + 1, degenerate: false, name: None });
        tops.push(top);
    }
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let mut next_id = 10 + 3 * count as u64 + 1000;
    let mut faces = Vec::with_capacity(count + 2);
    for (index, curve) in curves.iter().enumerate() {
        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let next = (index + 1) % count;
        let coedges = vec![
            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
        ];
        next_id += 4;
        let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
        let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
        faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
        next_id += 2;
    }
    let reach = curves.iter().chain(tops.iter()).flat_map(|c| c.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
    let pad = reach * 1.1 + 1.0;
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    let z0 = vertices[0].point.z;
    let z1 = vertices[count].point.z;
    let bottom_origin = Vec3::new(-pad, -pad, z0);
    let mut bottom = Vec::with_capacity(count);
    for index in (0..count).rev() {
        bottom.push(CoedgeRecord {
            id: next_id,
            edge_id: edge_id(0, index),
            forward: false,
            pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis).and_then(|c| c.reversed()).map_err(|e| refuse("gear_pcurve", e))?,
        });
        next_id += 1;
    }
    faces.push(FaceRecord {
        id: next_id + 1,
        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
        same_sense: false,
        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
        name: None,
    });
    next_id += 2;
    let top_origin = Vec3::new(-pad, -pad, z1);
    let mut top = Vec::with_capacity(count);
    for (index, curve) in tops.iter().enumerate() {
        top.push(CoedgeRecord {
            id: next_id,
            edge_id: edge_id(1, index),
            forward: true,
            pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
        });
        next_id += 1;
    }
    faces.push(FaceRecord {
        id: next_id + 1,
        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
        same_sense: true,
        loops: vec![LoopRecord { id: next_id, coedges: top }],
        name: None,
    });
    next_id += 2;
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id: next_id + 1,
        vertices,
        edges,
        shells: vec![ShellRecord { id: next_id, faces }],
        genus: 0,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if issues.is_empty() {
        Ok(solid)
    } else {
        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
    }
}

/// Hand of a helical gear's teeth.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
    Right,
    Left,
}

/// A helical (or, with `herringbone`, double helical) external gear given by
/// its normal-section values; `spur` carries them (module = normal module,
/// pressure angle = normal pressure angle, coefficients × normal module).
#[derive(Clone, Debug)]
pub struct HelicalGear {
    pub spur: SpurGear,
    pub helix_angle: f64,
    pub hand: Hand,
    pub herringbone: bool,
}

/// The transverse spur gear a helical gear's every section is (turned).
pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
    let beta = gear.helix_angle;
    // The pressure angle limits apply to the normal section (the cutter's).
    let normal = gear.spur.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
    }
    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
    }
    let n = &gear.spur;
    let c = beta.cos();
    Ok(SpurGear {
        module: n.module / c,
        teeth: n.teeth,
        pressure_angle: (n.pressure_angle.tan() / c).atan(),
        profile_shift: n.profile_shift * c,
        addendum: n.addendum * c,
        dedendum: n.dedendum * c,
        // The cutter's tip radius in the transverse section is taken as the
        // normal one (the true section of the round is a slightly longer ellipse).
        root_fillet: n.root_fillet * c,
        backlash: n.backlash,
        face_width: n.face_width,
    })
}

/// A helical or herringbone gear solid; names as [`spur_solid`].
pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let transverse = helical_transverse(gear)?;
    let section = transverse_section(&transverse)?;
    let r = transverse.module * transverse.teeth as f64 / 2.0;
    let width = transverse.face_width;
    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
    let twist = if gear.herringbone {
        // Each half advances by its own half width.
        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
    } else {
        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
    };
    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
/// between the minor diameter `minor` and the major diameter `major`).
#[derive(Clone, Debug)]
pub struct StraightSpline {
    pub teeth: usize,
    pub minor: f64,
    pub major: f64,
    pub key_width: f64,
    pub length: f64,
}

fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
        return Err(refuse(
            "gear_input",
            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
        ));
    }
    if teeth < 2 || teeth > 100 {
        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
    }
    // The keys must not meet on the minor circle.
    let half_root = (key_width / minor).asin();
    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
    }
    Ok(())
}

/// The section of a straight-sided spline shaft, counter-clockwise; exact
/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
    check_straight_spline(spline)?;
    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
    let n = spline.teeth as f64;
    let foot = [(rr * rr - h * h).sqrt(), h];
    let top = [(ra * ra - h * h).sqrt(), h];
    let top_angle = (h / ra).asin();
    let foot_angle = (h / rr).asin();
    let key: Vec<(&'static str, NurbsCurve)> = vec![
        ("R", line([foot[0], -h], [top[0], -h])?),
        ("K", arc(ra, -top_angle, top_angle)?),
        ("L", line(top, foot)?),
        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
    ];
    let mut curves = Vec::with_capacity(4 * spline.teeth);
    for index in 0..spline.teeth {
        let angle = TAU * index as f64 / n;
        for (role, curve) in &key {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
}

/// A spline shaft: the section extruded along +z by the length; names as the
/// section's roles, then `F` and `B`.
pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = straight_spline_section(spline)?;
    let solid = extrude_section(&section, spline.length)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// Cut a counter-clockwise section through a cylinder of `outside` diameter
/// and `length`: a hub. The section's faces keep their role names, the
/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
    // The section's true outer radius, read off the curves (a rational arc's
    // middle control point lies outside the arc).
    let mut reach: f64 = 0.0;
    for piece in &section.curves {
        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        for i in 0..=32 {
            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
            reach = reach.max(p.x.hypot(p.y));
        }
    }
    if !(outside / 2.0 > reach + 1e-9) {
        return Err(refuse(
            "hub_too_small",
            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
        ));
    }
    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * length, w: p.w }];
    hollow_prism(section, outside / 2.0, length, 1, &[0.0, 0.0, 1.0, 1.0], &rows)
}

/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
    let section = straight_spline_section(spline)?;
    let hub = hub_from_section(&section, outside, spline.length)?;
    Ok((hub, section.data))
}

/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
/// the metric trapezoidal profiles the same way): every curve a line or an arc.
#[derive(Clone, Debug)]
pub struct TimingPulley {
    /// Belt pitch.
    pub pitch: f64,
    pub teeth: usize,
    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
    pub pld: f64,
    /// Groove bottom width bw.
    pub bottom_width: f64,
    /// Groove depth hg (from the outside diameter).
    pub depth: f64,
    /// Groove side angle to the radial direction, each side (half of 2 beta).
    pub side_angle: f64,
    /// Bottom (root) corner radius rb.
    pub bottom_radius: f64,
    /// Top (tip) corner radius rt.
    pub top_radius: f64,
    pub width: f64,
}

/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
/// when `ccw`, else clockwise.
fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
    if ccw {
        let mut end = a1;
        while end <= a0 {
            end += TAU;
        }
        centred_arc(centre, radius, a0, end)
    } else {
        let mut start = a1;
        while start <= a0 - TAU {
            start += TAU;
        }
        while start >= a0 {
            start -= TAU;
        }
        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
    }
}

/// The pulley section, counter-clockwise. Groove k is centred on angle
/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
/// the land of the next tooth on the outside diameter.
pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
    if !(pitch > 0.0 && pld >= 0.0 && bottom_width > 0.0 && depth > 0.0 && width > 0.0 && bottom_radius >= 0.0 && top_radius >= 0.0) {
        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
    }
    if !(0.0..60f64.to_radians()).contains(&side_angle) {
        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
    }
    if teeth < 6 || teeth > 400 {
        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
    }
    let z = teeth as f64;
    let ro = pitch * z / PI / 2.0 - pld / 2.0;
    let x_bottom = ro - depth;
    if !(x_bottom > 0.0) {
        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
    }
    let tau = TAU / z;
    let (s, c) = side_angle.sin_cos();
    let side = [c, s]; // outward along the upper side
    let normal = [-s, c]; // from the upper side into the material
    let corner = [x_bottom, bottom_width / 2.0];
    // The upper side meets the outside circle at |corner + t side| = ro.
    let b = corner[0] * side[0] + corner[1] * side[1];
    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
    // Bottom corner fillet: between the bottom (direction +y) and the side; the
    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
    let turn = PI / 2.0 - side_angle;
    let reach_b = bottom_radius * (turn / 2.0).tan();
    let t1 = [corner[0], corner[1] - reach_b];
    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
    let centre_b = [t1[0] + bottom_radius, t1[1]];
    // Top corner fillet: tangent to the side (offset into the material) and
    // inside the outside circle (centre at ro - rt).
    let rt = top_radius;
    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
    let bb = base[0] * side[0] + base[1] * side[1];
    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
    if disc < 0.0 {
        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
    }
    let t_c = -bb + disc.sqrt();
    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
    let scale = ro / (centre_t[0].hypot(centre_t[1]));
    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
    let land_start = polar_angle(t4);
    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
        return Err(refuse(
            "groove_too_wide",
            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
        ));
    }
    let _ = top;
    // The upper half of groove 0, outward: bottom half line, D, C, P.
    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
    if bottom_radius > 0.0 {
        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
    }
    upper.push(("C", line(t2, t3)?));
    if rt > 0.0 {
        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
    }
    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
    let lower_roles = |role: &'static str| match role {
        "D" => "U",
        "C" => "A",
        _ => "Q",
    };
    for (role, curve) in upper.iter().rev() {
        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
    }
    groove.push(("S", line([t1[0], -t1[1]], t1)?));
    groove.extend(upper.into_iter());
    groove.push(("K", arc(ro, land_start, tau - land_start)?));
    let mut curves = Vec::with_capacity(groove.len() * teeth);
    for index in 0..teeth {
        let angle = tau * index as f64 + tau / 2.0;
        for (role, curve) in &groove {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
    Ok(GearSection { curves, data })
}

/// A straight beveloid (conical involute) gear: a spur gear whose profile shift grows linearly across the
/// face, `cone_angle` the angle its tip and root cones make with the axis. Every plane square to the axis is the
/// spur gear the standard rack generates at that plane's shift, so the flanks are involute helicoids (turning
/// opposite ways on the two sides) and the tip and root are cones; it meshes with spur, helical or beveloid
/// gears on parallel, crossed or skew axes and takes up backlash by sliding along its axis. `spur` is the gear
/// at z = 0 (its profile shift there) and its face width.
#[derive(Clone, Debug)]
pub struct BeveloidGear {
    pub spur: SpurGear,
    pub cone_angle: f64,
}

/// A beveloid gear solid: plane sections skinned (planes added until the skin holds 1e-5 × module halfway
/// between them). Names as the spur gear's per tooth, then `F` (z = 0) and `B`.
pub fn beveloid_solid(gear: &BeveloidGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let base = &gear.spur;
    let m = base.module;
    let width = base.face_width;
    let degrees = gear.cone_angle.to_degrees();
    if !(degrees > 0.0 && degrees <= 20.0 + 1e-9) {
        return Err(refuse("gear_input", format!("The cone angle must be over 0° and at most 20° (it is {degrees}°).")));
    }
    if !(width > 0.0) {
        return Err(refuse("gear_input", "The face width must be positive.".into()));
    }
    let slope = gear.cone_angle.tan() / m;
    let at = |z: f64| -> Result<GearSection, KernelRefusal> { spur_section(&SpurGear { profile_shift: base.profile_shift + slope * z, ..base.clone() }) };
    let first = at(0.0)?;
    let roles: Vec<&'static str> = first.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
    let count = roles.len();
    // Tooth 0's pieces in a plane, each as a function of its normalised parameter.
    let pieces = |section: &GearSection| -> Result<Vec<NurbsCurve>, KernelRefusal> {
        let tooth: Vec<NurbsCurve> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.curve.clone()).collect();
        let same: Vec<&'static str> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
        if same != roles {
            return Err(refuse(
                "section_changes",
                "The tooth's form changes across the face (undercut or a pointed tip appears partway): lower the cone angle or narrow the face.".into(),
            ));
        }
        Ok(tooth)
    };
    let evaluate = |curve: &NurbsCurve, t: f64| -> [f64; 2] {
        let [a, b] = curve.domain().unwrap_or([0.0, 1.0]);
        let p = curve.evaluate_extended(a + (b - a) * t).unwrap_or(Vec3::new(f64::NAN, f64::NAN, 0.0));
        [p.x, p.y]
    };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let skin_tolerance = 1e-5 * m;
    let probes: Vec<Vec<NurbsCurve>> = [0.0, 0.5 * width, width].iter().map(|&z| at(z).and_then(|s| pieces(&s))).collect::<Result<_, _>>()?;
    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(count);
    for role in 0..count {
        let mut all: Vec<f64> = Vec::new();
        for probe in &probes {
            all.extend(adaptive_breaks(&|t| evaluate(&probe[role], t), tolerance)?);
        }
        all.sort_by(f64::total_cmp);
        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
        breaks.push(all);
    }
    // Tooth 0's curves in the plane at height z, refitted on the shared breaks (so every plane's control points pair up).
    let refit = |z: f64| -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
        let tooth = pieces(&at(z)?)?;
        let mut curves = Vec::with_capacity(count);
        let mut worst = 0.0_f64;
        for (role, role_breaks) in breaks.iter().enumerate() {
            let (mut curve, error) = fit_on_breaks(&|t| evaluate(&tooth[role], t), role_breaks)?;
            worst = worst.max(error);
            for p in &mut curve.control_points {
                p.z = z * p.w;
            }
            curves.push(curve);
        }
        Ok((curves, worst))
    };
    let teeth = base.teeth;
    let tau = TAU / teeth as f64;
    let mut planes = 4usize;
    loop {
        let step = width / planes as f64;
        let delta = 1e-3 * step.min(m);
        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1);
        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
        for j in 0..=planes {
            let z = step * j as f64;
            let (tooth, worst) = refit(z)?;
            if worst > 2.0 * tolerance {
                return Err(refuse("gear_fit", format!("The beveloid's sections could not be fitted on shared breaks ({worst:.2e}).")));
            }
            let lo = refit(z - delta)?.0;
            let hi = refit(z + delta)?.0;
            let slope: Vec<Vec<[f64; 2]>> = lo
                .iter()
                .zip(&hi)
                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
                .collect();
            rows.push(tooth);
            slopes.push(slope);
        }
        let mut worst = 0.0_f64;
        for j in 0..planes {
            let exact = refit(step * (j as f64 + 0.5))?.0;
            for role in 0..count {
                for (k, p) in exact[role].control_points.iter().enumerate() {
                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
                    worst = worst.max((x - p.x).hypot(y - p.y));
                }
            }
        }
        if worst > skin_tolerance {
            if planes >= 256 {
                return Err(refuse("gear_fit", format!("The beveloid's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
            }
            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
            continue;
        }
        // The full section from tooth 0's curves at z = 0, junctions shared; every tooth's rows tooth 0's turned.
        let mut section_curves: Vec<SectionCurve> = Vec::with_capacity(count * teeth);
        for index in 0..teeth {
            for (role, curve) in rows[0].iter().enumerate() {
                section_curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: roles[role], tooth: index });
            }
        }
        snap_junctions(&mut section_curves);
        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
        let h = 1.0 / planes as f64;
        for (index, piece) in section_curves.iter().enumerate() {
            let (role, tooth) = (index % count, index / count);
            let (s, cs) = (tau * tooth as f64).sin_cos();
            for (k, p) in piece.curve.control_points.iter().enumerate() {
                let mut row = Vec::with_capacity(2 * planes + 2);
                for j in 0..=planes {
                    let q = if j == 0 { *p } else { let r = rows[j][role].control_points[k]; Vec4 { x: cs * r.x - s * r.y, y: s * r.x + cs * r.y, z: r.z, w: r.w } };
                    let d = slopes[j][role][k];
                    let dv = [width * (cs * d[0] - s * d[1]), width * (s * d[0] + cs * d[1]), width];
                    let point = Vec3::new(q.x, q.y, q.z);
                    if j > 0 {
                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
                    }
                    if j == 0 || j == planes {
                        row.push(Vec4::from_point(point, 1.0));
                    }
                    if j < planes {
                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
                    }
                }
                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
            }
        }
        let mut knots_v = vec![0.0; 4];
        for j in 1..planes {
            let v = j as f64 * h;
            knots_v.extend([v, v]);
        }
        knots_v.extend([1.0; 4]);
        let section = GearSection { curves: section_curves, data: GearData::default() };
        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
        })?;
        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
        names.push("F".into());
        names.push("B".into());
        return Ok((solid, names, first.data));
    }
}

/// A star (pin) wheel: the wheel that drives a lantern pinion, as in clocks and mills. Its teeth are cut
/// for the pinion's round pins: above the pitch circle each flank is the curve parallel, at the pin radius, to
/// the epicycloid the pin's centre traces relative to the wheel (the pinion's pitch circle rolling on the
/// wheel's), so the pins roll on the flanks; below it the tooth space has straight walls the pin's width apart
/// and a round root clear of the pins. Module m: wheel pitch radius m × teeth / 2, the pinion's m × pins / 2.
/// Tooth space 0 is centred on +x.
#[derive(Clone, Debug)]
pub struct StarWheel {
    pub module: f64,
    pub teeth: usize,
    /// Pins of the mating lantern pinion.
    pub pinion_pins: usize,
    pub pin_diameter: f64,
    /// Tip height above the pitch circle × module; 0 takes 92% of the height where the flanks meet.
    pub addendum: f64,
    /// Root clearance below the pins, × module.
    pub clearance: f64,
    pub backlash: f64,
    pub face_width: f64,
}

/// The star wheel's section (counter-clockwise; per tooth `V` the +θ space wall, `R` its flank, `K` the tip,
/// `L`/`W` the next space's flank and wall, `G` that space's root).
pub fn star_wheel_section(wheel: &StarWheel) -> Result<GearSection, KernelRefusal> {
    let m = wheel.module;
    if !(m > 0.0 && wheel.pin_diameter > 0.0 && wheel.face_width > 0.0 && wheel.addendum >= 0.0 && wheel.clearance >= 0.0 && wheel.backlash >= 0.0) {
        return Err(refuse("gear_input", "The module, pin diameter and face width must be positive; the addendum, clearance and backlash not negative.".into()));
    }
    if !(6..=1000).contains(&wheel.teeth) || !(3..=200).contains(&wheel.pinion_pins) {
        return Err(refuse("gear_input", format!("A star wheel needs 6 to 1000 teeth and a pinion of 3 to 200 pins (it has {} and {}).", wheel.teeth, wheel.pinion_pins)));
    }
    let r2 = m * wheel.teeth as f64 / 2.0;
    let r1 = m * wheel.pinion_pins as f64 / 2.0;
    let rho = wheel.pin_diameter / 2.0;
    let half = rho + wheel.backlash / 2.0; // the space's half width
    let tau = TAU / wheel.teeth as f64;
    if !(2.0 * half < PI * m * 0.9) {
        return Err(refuse("pins_too_thick", format!("The pins ({}) fill the pitch ({:.4}): a star wheel needs pins under 0.9 of the pitch.", wheel.pin_diameter, PI * m)));
    }
    // The pin centre's path in the wheel's frame: the epicycloid with its cusp at (r2, 0), and its normal.
    let k = (r1 + r2) / r1;
    let path = |a: f64| {
        let t = PI + a * k;
        [(r2 + r1) * a.cos() + r1 * t.cos(), (r2 + r1) * a.sin() + r1 * t.sin()]
    };
    let path_tangent = |a: f64| {
        let t = PI + a * k;
        let d = [-(r2 + r1) * a.sin() - r1 * k * t.sin(), (r2 + r1) * a.cos() + r1 * k * t.cos()];
        let l = d[0].hypot(d[1]);
        [d[0] / l, d[1] / l]
    };
    // The flank: the path offset by the space's half width to the tooth's side (left of the outgoing branch).
    let flank = |a: f64| {
        let (p, t) = (path(a), path_tangent(a));
        [p[0] - half * t[1], p[1] + half * t[0]]
    };
    // Near the cusp the offset curve first runs back below the pitch circle (a swallowtail: the pin's centre
    // leaves the cusp sideways before it rises), so the space's boundary there is the offset curve only from its
    // own cusp (where its x stops falling) out; below that point the wall is straight at that point's height.
    let slope_x = |a: f64| {
        let h = 1e-7 * a.max(1e-9);
        flank(a + h)[0] - flank(a - h)[0]
    };
    let mut hi = 1e-6;
    while slope_x(hi) < 0.0 {
        hi *= 1.5;
        if hi > 1.0 {
            return Err(refuse("gear_fit", "The star wheel's flank never turns outward.".into()));
        }
    }
    let (mut lo, mut top) = (hi / 1.5, hi);
    for _ in 0..200 {
        let mid = 0.5 * (lo + top);
        if !(mid > lo && mid < top) {
            break;
        }
        if slope_x(mid) < 0.0 { lo = mid } else { top = mid }
    }
    let cusp = 0.5 * (lo + top);
    // Below that the swept pins (the cusp's disc and the swallowtail inside it) stay under the line at the half
    // width, so the space's wall is straight at the half width up to where the outer branch rises to it.
    let outside = |a: f64| flank(a)[1] - half;
    let mut hi = cusp * 1.5;
    while outside(hi) < 0.0 {
        hi *= 1.5;
        if hi > PI {
            return Err(refuse("gear_fit", "The star wheel's flank never rises past the pin's width.".into()));
        }
    }
    let (mut lo, mut top) = (cusp, hi);
    for _ in 0..200 {
        let mid = 0.5 * (lo + top);
        if !(mid > lo && mid < top) {
            break;
        }
        if outside(mid) < 0.0 { lo = mid } else { top = mid }
    }
    let start = 0.5 * (lo + top);
    // Where the flank reaches the tooth's middle (the flanks of neighbouring spaces meet): the pointed tip.
    let reach = |a: f64| polar_angle(flank(a)) - tau / 2.0;
    let mut hi = 1e-3;
    while reach(hi) < 0.0 {
        hi *= 1.5;
        if hi > PI {
            return Err(refuse("gear_fit", "The star wheel's flanks never meet.".into()));
        }
    }
    let (mut lo, mut top) = (start, hi);
    for _ in 0..200 {
        let mid = 0.5 * (lo + top);
        if !(mid > lo && mid < top) {
            break;
        }
        if reach(mid) < 0.0 { lo = mid } else { top = mid }
    }
    let pointed = radius_of(flank(0.5 * (lo + top)));
    let base = radius_of(flank(start));
    let tip_r = if wheel.addendum > 0.0 { r2 + wheel.addendum * m } else { base + 0.92 * (pointed - base) };
    if !(tip_r < pointed - 1e-6 * m) {
        return Err(refuse("pointed_tip", format!("The teeth come to a point at radius {pointed:.4}, below the tip ({tip_r:.4}): lower the addendum.")));
    }
    if !(tip_r > base) {
        return Err(refuse("gear_input", "The tip must lie above the pitch circle.".into()));
    }
    // The flank's parameter at the tip circle.
    let (mut lo, mut top) = (start, 0.5 * (lo + top));
    for _ in 0..200 {
        let mid = 0.5 * (lo + top);
        if !(mid > lo && mid < top) {
            break;
        }
        if radius_of(flank(mid)) < tip_r { lo = mid } else { top = mid }
    }
    let end = 0.5 * (lo + top);
    let root_r = r2 - half - wheel.clearance * m;
    if !(root_r > half * 1.01) {
        return Err(refuse("root_below_centre", "The root circle falls inside the space's width: more teeth or thinner pins.".into()));
    }
    let wall_foot = [(root_r * root_r - half * half).sqrt(), half];
    let wall_top = flank(start);
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let right_flank = fit_planar(&flank, start, end, tolerance)?;
    let tip_from = polar_angle(flank(end));
    let mirror_into_next = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
        // Space 1's -θ side: space 0's +θ side mirrored about the x axis, turned by tau, run backwards.
        rotated(&mirrored(curve), tau).reversed().map_err(|e| refuse("gear_fit", e))
    };
    let wall = line(wall_foot, wall_top)?;
    let beta = (half / root_r).asin();
    let tooth: Vec<(&'static str, NurbsCurve)> = vec![
        ("V", wall.clone()),
        ("R", right_flank.clone()),
        ("K", arc(tip_r, tip_from, tau - tip_from)?),
        ("L", mirror_into_next(&right_flank)?),
        ("W", mirror_into_next(&wall)?),
        ("G", arc(root_r, tau - beta, tau + beta)?),
    ];
    let mut curves = Vec::with_capacity(6 * wheel.teeth);
    for index in 0..wheel.teeth {
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: 2.0 * r2,
        tip_diameter: 2.0 * tip_r,
        root_diameter: 2.0 * root_r,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A star wheel solid (the section extruded by the face width) with its face names and data.
pub fn star_wheel_solid(wheel: &StarWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = star_wheel_section(wheel)?;
    let solid = extrude_section(&section, wheel.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A lantern pinion: two discs joined by `pins` round pins on a circle, as a clock's or a mill's pinion,
/// driven by a star wheel's cycloidal teeth. Exact: pins and disc rims are cylinders, the disc faces planes.
/// The first disc spans z = -thickness..0, the pins z = 0..length, the second disc length..length + thickness;
/// pin 0 is centred on +x.
#[derive(Clone, Debug)]
pub struct LanternPinion {
    pub pins: usize,
    pub pin_circle_diameter: f64,
    pub pin_diameter: f64,
    pub disc_diameter: f64,
    pub disc_thickness: f64,
    /// The pins' length between the discs.
    pub length: f64,
}

/// A lantern pinion solid and its data. Faces are named `P<k>` (pin walls), `FL1_OD`, `FL1_F` (the first
/// disc's outer face), `FL1_B` (its inner face round the pins), `FL2_F` (the second disc's inner face),
/// `FL2_OD` and `FL2_B`.
pub fn lantern_solid(lantern: &LanternPinion) -> Result<(BrepSolid, GearData), KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
    let n = lantern.pins;
    let (r, d, t, length) = (lantern.pin_circle_diameter / 2.0, lantern.pin_diameter, lantern.disc_thickness, lantern.length);
    let radius = lantern.disc_diameter / 2.0;
    if !(3..=200).contains(&n) {
        return Err(refuse("gear_input", format!("A lantern pinion needs from 3 to 200 pins (it has {n}).")));
    }
    if !(r > 0.0 && d > 0.0 && t > 0.0 && length > 0.0 && [r, d, t, length, radius].iter().all(|v| v.is_finite())) {
        return Err(refuse("gear_input", "The pin circle, pin diameter, disc thickness and length must be positive.".into()));
    }
    if !(2.0 * r * (PI / n as f64).sin() > d * (1.0 + 1e-9)) {
        return Err(refuse("pins_overlap", format!("The {n} pins of diameter {d} overlap on a pin circle of diameter {}: enlarge the circle or thin the pins.", 2.0 * r)));
    }
    if !(radius > r + d / 2.0) {
        return Err(refuse("disc_too_small", format!("The discs (diameter {}) must reach past the pins (to {:.4}).", 2.0 * radius, 2.0 * r + d)));
    }
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    let circle = |cx: f64, cy: f64, z: f64, rad: f64| crate::make_arc(Vec3::new(cx, cy, z), x_axis, y_axis, rad, 0.0, TAU).map_err(|e| refuse("gear_arc", e));
    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
    // A cylinder from z = `low` up by `height` round (cx, cy): its circles, its seam and its face; returns the circles.
    let cylinder = |shell: &mut ShellBuilder, cx: f64, cy: f64, rad: f64, low: f64, height: f64, name: String| -> Result<(u64, u64), KernelRefusal> {
        let base = circle(cx, cy, low, rad)?;
        let (a, b) = (shell.vertex(Vec3::new(cx + rad, cy, low)), shell.vertex(Vec3::new(cx + rad, cy, low + height)));
        let lower = shell.edge(base.clone(), a, a)?;
        let upper = shell.edge(translated(&base, height), b, b)?;
        let seam = shell.edge(crate::make_line(Vec3::new(cx + rad, cy, low), Vec3::new(cx + rad, cy, low + height)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
        let side = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
        let [c0, c1] = base.domain().map_err(|e| refuse("gear_domain", e))?;
        let loops = vec![vec![
            (lower, true, line([c0, 0.0], [c1, 0.0])?),
            (seam, true, line([c1, 0.0], [c1, 1.0])?),
            (upper, false, line([c0, 1.0], [c1, 1.0])?),
            (seam, false, line([c0, 0.0], [c0, 1.0])?),
        ]];
        shell.face(side, true, loops, name)?;
        Ok((lower, upper))
    };
    let mut pin_bottoms = Vec::with_capacity(n);
    let mut pin_tops = Vec::with_capacity(n);
    for k in 0..n {
        let (s, c) = (TAU * k as f64 / n as f64).sin_cos();
        let (lower, upper) = cylinder(&mut shell, r * c, r * s, d / 2.0, 0.0, length, format!("P{k}"))?;
        pin_bottoms.push(lower);
        pin_tops.push(upper);
    }
    let (outer1, inner1) = cylinder(&mut shell, 0.0, 0.0, radius, -t, t, "FL1_OD".into())?;
    let (inner2, outer2) = cylinder(&mut shell, 0.0, 0.0, radius, length, t, "FL2_OD".into())?;
    let pad = radius * 1.1 + 1.0;
    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
    // The discs' outer faces, then their inner faces round the pins.
    let face = vec![vec![(outer1, true, on_plane(shell.curve(outer1), -t)?)]];
    shell.face(plane_at(-t)?, false, face, "FL1_F".into())?;
    let face = vec![vec![(outer2, true, on_plane(shell.curve(outer2), length + t)?)]];
    shell.face(plane_at(length + t)?, true, face, "FL2_B".into())?;
    for (z, rim, pins, same_sense, name) in [(0.0, inner1, &pin_bottoms, true, "FL1_B"), (length, inner2, &pin_tops, false, "FL2_F")] {
        let mut loops = vec![vec![(rim, true, on_plane(shell.curve(rim), z)?)]];
        for &pin in pins.iter() {
            loops.push(vec![(pin, true, on_plane(shell.curve(pin), z)?)]);
        }
        shell.face(plane_at(z)?, same_sense, loops, name.into())?;
    }
    let id = shell.id();
    let shell_id = shell.id();
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id,
        vertices: shell.vertices,
        edges: shell.edges,
        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
        genus: (n - 1) as _,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("lantern pinion is not valid: {issues:?}")));
    }
    let data = GearData { pitch_diameter: 2.0 * r, tip_diameter: 2.0 * r + d, root_diameter: 2.0 * r - d, ..GearData::default() };
    Ok((solid, data))
}

/// A pulley solid: the section extruded along +z by the width; names as the
/// section's roles, then `F` and `B`.
/// The counter-clockwise section (z = 0) extruded to z = `width` with a flange disc of `radius` and
/// `thickness` under it (and, with `both`, another over it), built directly rather than as a union. Faces
/// are named: the section's walls by role, the flanges `FL1_OD`/`FL1_F` (its outer face)/`FL1_B` (the
/// annulus round the section) and `FL2_F` (the annulus)/`FL2_OD`/`FL2_B`, and without a second flange the
/// section's own end `B`.
pub fn flanged_prism(section: &GearSection, width: f64, radius: f64, thickness: f64, both: bool) -> Result<BrepSolid, KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    if !(width > 0.0 && thickness > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
        return Err(refuse(
            "gear_input",
            format!("The flange radius ({radius}) must clear the section, and the width ({width}) and flange thickness ({thickness}) be positive."),
        ));
    }
    let up = Vec3::new(0.0, 0.0, width);
    let count = section.curves.len();
    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
    let mut bottom_v = Vec::with_capacity(count);
    let mut top_v = Vec::with_capacity(count);
    let mut axial = Vec::with_capacity(count);
    for piece in &section.curves {
        let p = point_of(piece.curve.control_points[0]);
        let (b, t) = (shell.vertex(p), shell.vertex(p.add(up)));
        axial.push(shell.edge(crate::make_line(p, p.add(up)).map_err(|e| refuse("gear_edge", e))?, b, t)?);
        bottom_v.push(b);
        top_v.push(t);
    }
    let mut bottom_e = Vec::with_capacity(count);
    let mut top_e = Vec::with_capacity(count);
    for (index, piece) in section.curves.iter().enumerate() {
        let next = (index + 1) % count;
        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
        top_e.push(shell.edge(translated(&piece.curve, width), top_v[index], top_v[next])?);
    }
    for (index, piece) in section.curves.iter().enumerate() {
        let next = (index + 1) % count;
        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let surface = crate::make_extrusion(&piece.curve, up).map_err(|e| refuse("gear_surface", e))?;
        let loops = vec![vec![
            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
        ]];
        shell.face(surface, true, loops, piece.suffix())?;
    }
    let pad = radius * 1.1 + 1.0;
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
    // A flange from z = `low` to `low` + thickness: its circles, seam and outside cylinder; returns the circles.
    let flange = |shell: &mut ShellBuilder, low: f64, name: &str| -> Result<(u64, u64), KernelRefusal> {
        let circle = crate::make_arc(Vec3::new(0.0, 0.0, low), x_axis, y_axis, radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
        let lifted = translated(&circle, thickness);
        let (a, b) = (shell.vertex(Vec3::new(radius, 0.0, low)), shell.vertex(Vec3::new(radius, 0.0, low + thickness)));
        let lower = shell.edge(circle.clone(), a, a)?;
        let upper = shell.edge(lifted, b, b)?;
        let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, low), Vec3::new(radius, 0.0, low + thickness)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
        let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, thickness)).map_err(|e| refuse("gear_surface", e))?;
        let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
        let loops = vec![vec![
            (lower, true, line([c0, 0.0], [c1, 0.0])?),
            (seam, true, line([c1, 0.0], [c1, 1.0])?),
            (upper, false, line([c0, 1.0], [c1, 1.0])?),
            (seam, false, line([c0, 0.0], [c0, 1.0])?),
        ]];
        shell.face(side, true, loops, format!("{name}OD"))?;
        Ok((lower, upper))
    };
    // Flange 1 under the section: its outer face at z = -thickness, the annulus at z = 0 round the section.
    let (outer1, inner1) = flange(&mut shell, -thickness, "FL1_")?;
    let face = vec![(outer1, true, on_plane(shell.curve(outer1), -thickness)?)];
    shell.face(plane_at(-thickness)?, false, vec![face], "FL1_F".into())?;
    let mut annulus = vec![vec![(inner1, true, on_plane(shell.curve(inner1), 0.0)?)], Vec::with_capacity(count)];
    for &edge in &bottom_e {
        annulus[1].push((edge, true, on_plane(shell.curve(edge), 0.0)?));
    }
    shell.face(plane_at(0.0)?, true, annulus, "FL1_B".into())?;
    if both {
        let (inner2, outer2) = flange(&mut shell, width, "FL2_")?;
        let mut annulus = vec![vec![(inner2, true, on_plane(shell.curve(inner2), width)?)], Vec::with_capacity(count)];
        for &edge in &top_e {
            annulus[1].push((edge, true, on_plane(shell.curve(edge), width)?));
        }
        shell.face(plane_at(width)?, false, annulus, "FL2_F".into())?;
        let face = vec![(outer2, true, on_plane(shell.curve(outer2), width + thickness)?)];
        shell.face(plane_at(width + thickness)?, true, vec![face], "FL2_B".into())?;
    } else {
        let mut end = Vec::with_capacity(count);
        for &edge in &top_e {
            end.push((edge, true, on_plane(shell.curve(edge), width)?));
        }
        shell.face(plane_at(width)?, true, vec![end], "B".into())?;
    }
    let id = shell.id();
    let shell_id = shell.id();
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id,
        vertices: shell.vertices,
        edges: shell.edges,
        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
        genus: 0,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("flanged prism is not valid: {issues:?}")));
    }
    Ok(solid)
}

pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = timing_pulley_section(pulley)?;
    let solid = extrude_section(&section, pulley.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
/// in under load) and a straight back; a symmetric tooth leans both faces
/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
/// when `clockwise_locks` is false.
#[derive(Clone, Debug)]
pub struct Ratchet {
    pub teeth: usize,
    pub outside: f64,
    pub depth: f64,
    pub lean: f64,
    pub symmetric: bool,
    pub clockwise_locks: bool,
    pub width: f64,
}

/// The ratchet section, counter-clockwise; straight lines only. Roles per
/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
/// tip, `BK<k>` the back running up to it.
pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
    }
    if teeth < 3 || teeth > 360 {
        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
    }
    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
    }
    let z = teeth as f64;
    let tau = TAU / z;
    let ra = outside / 2.0;
    let rf = ra - depth;
    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
    // A radial face has foot = 0; leaning back by `lean` moves the root point
    // forward along the face's direction: solve |tip + t d| = rf.
    let tip = [ra, 0.0];
    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
    let d = [face_angle.cos(), face_angle.sin()];
    let b = tip[0] * d[0] + tip[1] * d[1];
    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
    let foot = polar_angle(root);
    let (lock, back) = if symmetric {
        // Both faces meet at the root halfway between tips, each leaning equally.
        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
        let lock = line(tip, mid)?;
        let next = [ra * tau.cos(), ra * tau.sin()];
        (lock, line(mid, next)?)
    } else {
        if foot >= tau - 1e-9 {
            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
        }
        let next = [ra * tau.cos(), ra * tau.sin()];
        (line(tip, root)?, line(root, next)?)
    };
    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
    let mut curves = Vec::with_capacity(2 * teeth);
    for index in 0..teeth {
        let angle = tau * index as f64;
        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
    }
    if clockwise_locks {
        // The mirror image locks the other way; mirror, then restore the
        // counter-clockwise order.
        let mut mirrored_curves: Vec<SectionCurve> = curves
            .iter()
            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
            .collect();
        mirrored_curves.reverse();
        curves = mirrored_curves;
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
}

/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = ratchet_section(ratchet)?;
    let solid = extrude_section(&section, ratchet.width)?;
    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
/// rim between slots is cut by the concave locking arc of radius
/// `lock_radius + clearance / 2` about the driver's centre.
#[derive(Clone, Debug)]
pub struct GenevaWheel {
    pub slots: usize,
    pub centre_distance: f64,
    pub pin_diameter: f64,
    pub clearance: f64,
    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
    pub lock_radius: f64,
    pub width: f64,
}

/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
    let n = wheel.slots as f64;
    let a = wheel.centre_distance;
    let crank = a * (PI / n).sin();
    let radius = a * (PI / n).cos();
    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
    (crank, radius, a - crank, lock)
}

/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
/// follows slot k.
pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
    if !(3..=12).contains(&slots) {
        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
    }
    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
    }
    let n = slots as f64;
    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
    let half = (dp + c) / 2.0; // half the slot width
    let rl = lock + c / 2.0;
    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
    }
    // Adjacent slots must not meet: their ends (and sides) stay apart only
    // while the end centres are more than a slot width apart.
    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
        return Err(refuse(
            "gear_input",
            format!("Adjacent slots meet near the hub: {slots} slots {:.4} wide need a larger centre distance than {a}, or a smaller pin.", 2.0 * half),
        ));
    }
    let x_top = (rw * rw - half * half).sqrt();
    let p1 = [x_top, half];
    let beta = PI / n;
    let centre = [a * beta.cos(), a * beta.sin()];
    // Rim circle (O, rw) meets the locking circle (centre, rl).
    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
    let h2 = rw * rw - along * along;
    if h2 <= 0.0 {
        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
    }
    let h = h2.sqrt();
    let e = [beta.cos(), beta.sin()];
    let perp = [-beta.sin(), beta.cos()];
    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
    let a1 = polar_angle(p1);
    if polar_angle(q1) <= a1 + 1e-9 {
        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
    }
    let tau = TAU / n;
    let slot: Vec<(&'static str, NurbsCurve)> = vec![
        ("SL", line([x_top, -half], [end_centre, -half])?),
        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
        ("SU", line([end_centre, half], p1)?),
        ("RA", arc(rw, a1, polar_angle(q1))?),
        ("LA", arc_through(centre, q1, q2, false)?),
        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
    ];
    let mut curves = Vec::with_capacity(6 * slots);
    for index in 0..slots {
        let angle = tau * index as f64;
        for (role, curve) in &slot {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let _ = crank;
    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
}

/// A Geneva wheel solid: the section extruded along +z; names as the
/// section's roles, then `F` and `B`.
pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = geneva_section(wheel)?;
    let solid = extrude_section(&section, wheel.width)?;
    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
/// axial section at the axial pressure angle. Lengths in model units.
#[derive(Clone, Debug)]
pub struct Worm {
    pub axial_module: f64,
    pub starts: usize,
    /// Reference (pitch) diameter d1 = q × axial module.
    pub reference_diameter: f64,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    pub length: f64,
    pub hand: Hand,
}

impl Worm {
    /// The lead: starts × axial pitch.
    pub fn lead(&self) -> f64 {
        self.starts as f64 * PI * self.axial_module
    }

    /// The axial thread thickness at a radius (ZA: straight axial flanks).
    pub fn axial_thickness(&self, radius: f64) -> f64 {
        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
    }
}

/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
    let m = worm.axial_module;
    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
    }
    if worm.starts < 1 || worm.starts > 8 {
        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
    }
    let degrees = worm.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let r1 = worm.reference_diameter / 2.0;
    let ra = r1 + worm.addendum * m;
    let rf = r1 - worm.dedendum * m;
    if !(rf > 0.0) {
        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
    }
    let lead = worm.lead();
    let gamma = (lead / (PI * worm.reference_diameter)).atan();
    if gamma.to_degrees() > 45.0 {
        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
    }
    if worm.axial_thickness(ra) <= 1e-6 * m {
        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
    }
    let n = worm.starts as f64;
    let pitch = PI * m;
    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
    }
    // Half the angular width of a thread at radius r in the transverse plane.
    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
    let flank = |r: f64| {
        let t = half(r);
        [r * t.cos(), r * t.sin()]
    };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
    let tau = TAU / n;
    let thread: Vec<(&'static str, NurbsCurve)> = vec![
        ("R", mirrored(&upper)),
        ("K", arc(ra, -half(ra), half(ra))?),
        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
        ("G", arc(rf, half(rf), tau - half(rf))?),
    ];
    let mut curves = Vec::with_capacity(4 * worm.starts);
    for index in 0..worm.starts {
        let angle = tau * index as f64;
        for (role, curve) in &thread {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
    Ok(GearSection { curves, data })
}

/// A worm solid: the transverse section screwed along +z by the length (one
/// lead per turn); names as the section's roles, then `F` and `B`.
pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = worm_section(worm)?;
    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
    let turn = sign * TAU * worm.length / worm.lead();
    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
/// half the clearance) of the epitrochoid the pin centres trace relative to it.
#[derive(Clone, Debug)]
pub struct CycloidalDisc {
    pub pins: usize,
    pub pin_circle_diameter: f64,
    pub pin_diameter: f64,
    pub eccentricity: f64,
    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
    pub clearance: f64,
    pub width: f64,
}

impl CycloidalDisc {
    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
        let r = self.pin_circle_diameter / 2.0;
        let e = self.eccentricity;
        let n = self.pins as f64;
        (
            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
        )
    }

    /// The disc profile point at parameter t: the trochoid moved by the offset
    /// along its normal towards the disc's centre.
    pub fn profile(&self, t: f64) -> [f64; 2] {
        let (q, d) = self.trochoid(t);
        let length = d[0].hypot(d[1]);
        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
        let n = [d[1] / length, -d[0] / length];
        [q[0] + offset * n[0], q[1] + offset * n[1]]
    }
}

/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
    if !(4..=200).contains(&pins) {
        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
    }
    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
    }
    let n = pins as f64;
    let r = dc / 2.0;
    // The trochoid loops back on itself once e >= r / n.
    if e >= r / n * (1.0 - 1e-9) {
        return Err(refuse(
            "gear_input",
            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
        ));
    }
    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
    let offset = dp / 2.0 + clearance / 2.0;
    // An inward offset can cusp only where the (clockwise) curve turns
    // clockwise, its centre of curvature inside. Radius of curvature there,
    // from the closed-form first and second derivatives.
    let (rr, ee) = (dc / 2.0, e);
    let radius = |t: f64| -> f64 {
        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
        let cross = d[0] * dd[1] - d[1] * dd[0];
        let speed = d[0].hypot(d[1]);
        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
    };
    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
    // refine every local minimum by golden-section search.
    let period = TAU / (n - 1.0);
    let samples = 2000;
    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
    let mut least = f64::INFINITY;
    for i in 0..=samples {
        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
        let next = values[if i == samples { 1 } else { i + 1 }];
        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
            for _ in 0..100 {
                let a = lo + (hi - lo) * 0.381966;
                let b = hi - (hi - lo) * 0.381966;
                if radius(a) < radius(b) { hi = b } else { lo = a }
            }
            least = least.min(radius(0.5 * (lo + hi)));
        }
    }
    if offset >= least * (1.0 - 1e-6) {
        return Err(refuse(
            "undercut",
            format!("The pins ({dp}) are too large for this eccentricity and pin circle: the lobes would cusp (the pin radius plus half the clearance must be under {least:.4})."),
        ));
    }
    let lobes = pins - 1;
    let step = TAU / lobes as f64;
    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
    let mut curves = Vec::with_capacity(lobes);
    for k in 0..lobes {
        let (a, b) = (step * k as f64, step * (k + 1) as f64);
        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
    }
    snap_junctions(&mut curves);
    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
}

/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = cycloidal_disc_section(disc)?;
    let solid = extrude_section(&section, disc.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
/// `G<k>` the bore between pins, `OD`, `F`, `B`.
pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
        return Err(refuse("gear_input", "The pin ring needs 4 to 200 pins, a pin circle larger than the pins and a positive width.".into()));
    }
    let r = pin_circle_diameter / 2.0;
    let rp = pin_diameter / 2.0;
    let n = pins as f64;
    let tau = TAU / n;
    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
    let delta = 2.0 * (rp / (2.0 * r)).asin();
    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
    }
    let centre = [r, 0.0];
    let a = [r * (-delta).cos(), r * (-delta).sin()];
    let b = [r * delta.cos(), r * delta.sin()];
    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
    let cw = arc_through(centre, a, b, false)?;
    let pin_arc = {
        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
    };
    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
    let mut curves = Vec::with_capacity(2 * pins);
    for k in 0..pins {
        for (role, curve) in &space {
            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
        }
    }
    snap_junctions(&mut curves);
    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
    let ring = hub_from_section(&section, outside, width)?;
    Ok((ring, section.data))
}

/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
#[derive(Clone, Debug)]
pub struct CycloidalGear {
    pub module: f64,
    pub teeth: usize,
    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
    pub generating_radius: f64,
    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
    pub tooth_fraction: f64,
    /// Addendum limit × module (the tip is pointed if the flanks meet first).
    pub addendum: f64,
    /// Dedendum × module.
    pub dedendum: f64,
    pub width: f64,
}

/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
/// the tip land (absent when pointed), `G<k>` the root land.
pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
    }
    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
    }
    if gear.teeth < 6 || gear.teeth > 1000 {
        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
    }
    let z = gear.teeth as f64;
    let r = m * z / 2.0;
    let rho = gear.generating_radius;
    let rf = r - gear.dedendum * m;
    if !(rf > 0.0) {
        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
    }
    let tau = TAU / z;
    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
    // The right flank's epicycloid, from the pitch circle at angle -psi.
    let k = (r + rho) / rho;
    let epi = |phi: f64| {
        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
        rotate(p, -psi)
    };
    let ra = r + gear.addendum * m;
    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
    let mut hi = 1e-3;
    while !reach(hi) {
        hi *= 1.5;
        if hi > PI {
            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
        }
    }
    let mut lo = 0.0;
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        if reach(mid) { hi = mid } else { lo = mid }
    }
    let end = epi(hi);
    // Pointed when the flank reaches the tooth centre line no later than the
    // tip circle (a tip land narrower than 1e-9 counts as pointed).
    let pointed = polar_angle(end) >= -1e-9;
    let phi_end = if pointed {
        let (mut lo, mut hi) = (0.0, hi);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
        }
        hi
    } else {
        hi
    };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
    let tip_angle = -polar_angle(epi(phi_end));
    if !pointed {
        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
    }
    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
    tooth.push(("G", arc(rf, psi, tau - psi)?));
    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = tau * index as f64;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let data = GearData {
        pitch_diameter: 2.0 * r,
        tip_diameter: 2.0 * radius_of(epi(phi_end)),
        root_diameter: 2.0 * rf,
        tooth_thickness: 2.0 * psi * r,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = cycloidal_gear_section(gear)?;
    let solid = extrude_section(&section, gear.width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// A straight bevel gear with spherical-involute teeth (the true conjugate
/// form; not Tredgold's back-cone approximation). Module at the heel, shaft
/// angle 90°, pitch cone angle atan(z / z_mate). Apex at the origin, axis +z,
/// the teeth between cone distances R − face width and R; back and front
/// faces are the back and front cones (perpendicular to the pitch cone).
#[derive(Clone, Debug)]
pub struct BevelGear {
    pub module: f64,
    pub teeth: usize,
    pub mate_teeth: usize,
    pub pressure_angle: f64,
    pub addendum: f64,
    pub dedendum: f64,
    pub face_width: f64,
    pub backlash: f64,
}

/// Derived bevel sizes: (pitch cone angle, cone distance, base cone angle).
pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
    let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
    let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
    let base = (delta.sin() * gear.pressure_angle.cos()).asin();
    (delta, cone, base)
}

/// A point of the spherical involute of the base cone (half angle `base`) on
/// the sphere of radius `r`, unwrapped by `phi` from the base circle at azimuth 0.
fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
    let (s, c) = base.sin_cos();
    let t = phi * s;
    [
        r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
        r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
        r * t.cos() * c,
    ]
}

/// The polar angle from the axis (the cone angle) of a point.
fn cone_angle(p: [f64; 3]) -> f64 {
    p[0].hypot(p[1]).atan2(p[2])
}

/// Central projection from the apex onto the plane z = h.
fn project(p: [f64; 3], h: f64) -> [f64; 2] {
    [p[0] * h / p[2], p[1] * h / p[2]]
}

/// The bevel gear section: the spherical tooth outline on the sphere through
/// the heel, centrally projected onto the plane z = h (so every surface the
/// apex sees edge-on — tooth flanks, root and tip cones — becomes a planar
/// curve; the cones' circles project to exact arcs). Counter-clockwise; roles
/// as the spur gear's: `V/R/K/L/W/G` with `V/W` the radial (meridian) root
/// extension below the base cone when the root lies under it.
pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
    }
    if gear.teeth < 6 || gear.mate_teeth < 6 {
        return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let (delta, r, base) = bevel_cones(gear);
    if gear.face_width > r / 3.0 + 1e-9 {
        return Err(refuse(
            "face_too_wide",
            format!("The face width ({}) is over a third of the cone distance ({:.4}): the teeth would be too small at the toe.", gear.face_width, r),
        ));
    }
    let z = gear.teeth as f64;
    let tip = delta + gear.addendum * m / r;
    let root = delta - gear.dedendum * m / r;
    if !(root > 0.0) {
        return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
    }
    // The unwrap angle where the involute reaches a cone angle theta: cos(phi sin b) cos b = cos theta.
    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
    // Position the left flank: half the tooth thickness (arc on the pitch circle of radius r sin delta) at the pitch cone.
    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
    let p_pitch = spherical_involute(r, base, phi_at(delta));
    // The involute (unwrapping counter-clockwise) leans to positive azimuth as it rises: the left flank
    // is it mirrored, turned so its pitch point sits at +half.
    let shift = half + azimuth(p_pitch);
    let left = |phi: f64| {
        let p = spherical_involute(r, base, phi);
        let q = [p[0], -p[1], p[2]];
        let (s, c) = shift.sin_cos();
        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
    };
    let tip_phi = phi_at(tip);
    if azimuth(left(tip_phi)) <= 1e-6 * m / r {
        return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
    }
    // At the base cone the involute leaves with zero speed (a cusp in phi):
    // when the root lies under it, the flank starts a little above (2% of the
    // unwrap) and the radial root extension runs up to that point.
    let extend = !(root > base); // the root lies on or under the base cone: a radial extension
    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
    let tolerance = GEAR_FIT_TOLERANCE * m;
    let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; // root side -> tip
    let tau = TAU / z;
    let base_point = project(left(start_phi), h);
    let root_r = h * root.tan();
    let tip_r = h * tip.tan();
    let foot_angle = base_point[1].atan2(base_point[0]);
    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
    let tip_angle = {
        let p = project(left(tip_phi), h);
        p[1].atan2(p[0])
    };
    // Right side (mirror), going up: [V radial] + R; tip K; then L down + [W radial]; G root land.
    let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
    if extend {
        tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
    }
    tooth.push(("R", mirrored(&flank)));
    tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
    tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
    if extend {
        tooth.push(("W", line(base_point, radial_foot)?));
    }
    if foot_angle >= tau / 2.0 - 1e-9 {
        return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
    }
    tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
    for index in 0..gear.teeth {
        let angle = tau * index as f64;
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
        }
    }
    // Lift the section into the plane z = h.
    for piece in &mut curves {
        for p in &mut piece.curve.control_points {
            p.z = p.w * h;
        }
    }
    snap_junctions(&mut curves);
    // Diameters at the heel: where each cone meets the back cone (perpendicular
    // to the pitch cone at cone distance r).
    let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
    let data = GearData {
        pitch_diameter: 2.0 * r * delta.sin(),
        tip_diameter: heel(tip),
        root_diameter: heel(root),
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// A straight bevel gear solid: the section's cone (every flank exactly the cone from the apex over the
/// spherical involute) between the front and back cones. Built directly, without booleans: the back cone
/// cuts every generator at the cone distance r, so each face of the tooth outline is its back curve (the
/// outline's trace on the back cone) scaled towards the apex down to the front cone, a ruled face whose
/// edges are all iso-lines. Faces carry their roles in `face.name` (`R3`, `K0`, …, `BACK`, `FRONT`).
pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
    use crate::sweep_topology::parameter_line;
    let (delta, r, base) = bevel_cones(gear);
    // The section's own checks and data (diameters at the heel).
    let data = bevel_section(gear, r * delta.cos())?.data;
    let m = gear.module;
    let teeth = gear.teeth;
    let tau = TAU / teeth as f64;
    let tip = delta + gear.addendum * m / r;
    let root = delta - gear.dedendum * m / r;
    // The left flank on the sphere of radius r, as `bevel_section` positions it.
    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
    let shift = half + azimuth(spherical_involute(r, base, phi_at(delta)));
    let left = |phi: f64| {
        let p = spherical_involute(r, base, phi);
        let q = [p[0], -p[1], p[2]];
        let (s, c) = shift.sin_cos();
        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
    };
    let tip_phi = phi_at(tip);
    let extend = !(root > base);
    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
    let foot_angle = azimuth(left(start_phi));
    let tip_angle = azimuth(left(tip_phi));
    // Along the ray through p, the point on the back cone (rho sin delta + z cos delta = r).
    let (sd, cd) = delta.sin_cos();
    let back = |p: [f64; 3]| {
        let s = r / (p[0].hypot(p[1]) * sd + p[2] * cd);
        [p[0] * s, p[1] * s, p[2] * s]
    };
    // The back cone's circle at cone angle theta: (radius, height).
    let circle_at = |theta: f64| {
        let k = r / (theta - delta).cos();
        (k * theta.sin(), k * theta.cos())
    };
    let at = |theta: f64, angle: f64| {
        let (rho, z) = circle_at(theta);
        Vec3::new(rho * angle.cos(), rho * angle.sin(), z)
    };
    let v3 = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
    let mirror = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x, y: -p.y, z: p.z, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
    };
    let arc_on = |theta: f64, from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
        let (rho, z) = circle_at(theta);
        crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), rho, from, to).map_err(|e| refuse("gear_arc", e))
    };
    let segment = |a: Vec3, b: Vec3| crate::make_line(a, b).map_err(|e| refuse("gear_edge", e));
    // The left flank's back curve, fitted from the exact involute (tip -> foot); the right flank mirrors it.
    let tolerance = 0.2 * GEAR_FIT_TOLERANCE * m;
    let flank = |t: f64| back(left(tip_phi - t * (tip_phi - start_phi)));
    let (left_back, _) = fit_on_breaks3(&flank, &adaptive_breaks3(&flank, tolerance)?)?;
    let right_back = mirror(&left_back)?.reversed().map_err(|e| refuse("gear_fit", e))?;
    let foot = v3(back(left(start_phi)));
    let mirrored = |p: Vec3| Vec3::new(p.x, -p.y, p.z);
    // Tooth 0's back curves in section order (counter-clockwise about +z).
    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
    if extend {
        tooth.push(("V", segment(at(root, -foot_angle), mirrored(foot))?));
    }
    tooth.push(("R", right_back));
    tooth.push(("K", arc_on(tip, -tip_angle, tip_angle)?));
    tooth.push(("L", left_back));
    if extend {
        tooth.push(("W", segment(foot, at(root, foot_angle))?));
    }
    tooth.push(("G", arc_on(root, foot_angle, tau - foot_angle)?));
    let mut curves: Vec<SectionCurve> = Vec::with_capacity(tooth.len() * teeth);
    for index in 0..teeth {
        for (role, curve) in &tooth {
            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
        }
    }
    snap_junctions(&mut curves);
    let count = curves.len();
    let lambda = (r - gear.face_width) / r;
    let scaled = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
    };
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
    // Junction j starts curve j: its back and front vertices and the generator between them.
    let mut back_v = Vec::with_capacity(count);
    let mut front_v = Vec::with_capacity(count);
    let mut generators = Vec::with_capacity(count);
    for piece in &curves {
        let b = point_of(piece.curve.control_points[0]);
        let f = b.scale(lambda);
        let (vb, vf) = (shell.vertex(b), shell.vertex(f));
        generators.push(shell.edge(segment(f, b)?, vf, vb)?);
        back_v.push(vb);
        front_v.push(vf);
    }
    let mut back_e = Vec::with_capacity(count);
    let mut front_e = Vec::with_capacity(count);
    for (index, piece) in curves.iter().enumerate() {
        let next = (index + 1) % count;
        back_e.push(shell.edge(piece.curve.clone(), back_v[index], back_v[next])?);
        front_e.push(shell.edge(scaled(&piece.curve)?, front_v[index], front_v[next])?);
    }
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    for (index, piece) in curves.iter().enumerate() {
        let next = (index + 1) % count;
        let rows: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| vec![Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }, *p]).collect();
        let surface = NurbsSurface::new(piece.curve.degree, 1, piece.curve.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))?;
        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let loops = vec![vec![
            (front_e[index], true, line([u0, 0.0], [u1, 0.0])?),
            (generators[next], true, line([u1, 0.0], [u1, 1.0])?),
            (back_e[index], false, line([u0, 1.0], [u1, 1.0])?),
            (generators[index], false, line([u0, 0.0], [u0, 1.0])?),
        ]];
        shell.face(surface, true, loops, piece.suffix())?;
    }
    // The back and front cones, each one face round its apex (a pole edge there) with a seam through
    // junction 0. u follows the rational circle from junction 0's azimuth, v runs out from the apex.
    let seam = {
        let p = point_of(curves[0].curve.control_points[0]);
        p.y.atan2(p.x)
    };
    let reach = curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max) * 1.1 + m;
    let circle = crate::make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 1.0, seam, seam + TAU).map_err(|e| refuse("gear_arc", e))?;
    let segments = (circle.knots.len() - 6) / 2 + 1;
    let quarter = TAU / segments as f64;
    let cone = |scale: f64| -> Result<NurbsSurface, KernelRefusal> {
        let (apex, rim) = (scale * r / cd, scale * (r - reach * sd) / cd);
        let rows = circle.control_points.iter().map(|c| vec![Vec4 { x: 0.0, y: 0.0, z: apex * c.w, w: c.w }, Vec4 { x: scale * reach * c.x, y: scale * reach * c.y, z: rim * c.w, w: c.w }]).collect();
        NurbsSurface::new(circle.degree, 1, circle.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))
    };
    // The circle's parameter at an angle from the seam: each span a rational quadratic arc of `quarter`, on
    // which tan(beta / 2) = (2 s - 1) tan(quarter / 4) about the span's middle.
    let parameter = |angle: f64| {
        let k = ((angle / quarter).floor().max(0.0) as usize).min(segments - 1);
        let beta = angle - (k as f64 + 0.5) * quarter;
        let s = ((beta / 2.0).tan() / (quarter / 4.0).tan() + 1.0) / 2.0;
        (k as f64 + s) / segments as f64
    };
    // Back-cone pcurves of the back curves (the front cone is the back scaled to the apex: the same pcurves).
    let mut cone_pcurves = Vec::with_capacity(count);
    for piece in &curves {
        let curve = &piece.curve;
        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let mid = curve.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_curve", e))?;
        let middle = (mid.y.atan2(mid.x) - seam).rem_euclid(TAU);
        // (Extended past the ends: the fit's end slopes look a step outside the edge.)
        let uv = |t: f64| {
            let p = curve.evaluate_extended(t0 + (t1 - t0) * t).unwrap_or(mid);
            let angle = middle + ((p.y.atan2(p.x) - seam - middle + PI).rem_euclid(TAU) - PI);
            [parameter(angle), p.x.hypot(p.y) / reach]
        };
        let breaks = adaptive_breaks(&uv, 1e-11)?;
        let (mut pcurve, _) = fit_on_breaks(&uv, &breaks)?;
        // On the edge's own parameter range.
        pcurve.knots.iter_mut().for_each(|k| *k = t0 + (t1 - t0) * *k);
        cone_pcurves.push(NurbsCurve::new(pcurve.degree, pcurve.knots.clone(), pcurve.control_points.clone()).map_err(|e| refuse("gear_pcurve", e))?);
    }
    let seam_v = point_of(curves[0].curve.control_points[0]).x.hypot(point_of(curves[0].curve.control_points[0]).y) / reach;
    for (scale, name, outline, junction) in [(1.0, "BACK", &back_e, &back_v), (lambda, "FRONT", &front_e, &front_v)] {
        let surface = cone(scale)?;
        let apex_point = Vec3::new(0.0, 0.0, scale * r / cd);
        let apex = shell.vertex(apex_point);
        let pole_curve = NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[0]).collect()).map_err(|e| refuse("gear_edge", e))?;
        let pole = shell.degenerate_edge(pole_curve, apex)?;
        let seam_point = shell.vertices.iter().find(|v| v.id == junction[0]).expect("junction 0").point;
        let seam_edge = shell.edge(segment(apex_point, seam_point)?, apex, junction[0])?;
        let mut coedges = vec![(pole, true, line([0.0, 0.0], [1.0, 0.0])?), (seam_edge, true, line([1.0, 0.0], [1.0, seam_v])?)];
        for index in (0..count).rev() {
            coedges.push((outline[index], false, cone_pcurves[index].clone()));
        }
        coedges.push((seam_edge, false, line([0.0, 0.0], [0.0, seam_v])?));
        // The surface's normal points to the apex side: outward for the front, inward for the back.
        shell.face(surface, name == "FRONT", vec![coedges], name.into())?;
    }
    let id = shell.id();
    let shell_id = shell.id();
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id,
        vertices: shell.vertices,
        edges: shell.edges,
        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
        genus: 0,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("bevel gear is not valid: {issues:?}")));
    }
    Ok((solid, data))
}

/// The cubic Hermite span of a space curve (numeric end derivatives) as Bézier points.
fn hermite_span3(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> [[f64; 3]; 4] {
    let derivative = |t: f64| {
        let h = 1e-6;
        let (p, q) = (f(t + h), f(t - h));
        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h), (p[2] - q[2]) / (2.0 * h)]
    };
    let (p0, p1) = (f(t0), f(t1));
    let (d0, d1) = (derivative(t0), derivative(t1));
    let k = (t1 - t0) / 3.0;
    let ahead = |p: [f64; 3], d: [f64; 3], s: f64| [p[0] + s * d[0], p[1] + s * d[1], p[2] + s * d[2]];
    [p0, ahead(p0, d0, k), ahead(p1, d1, -k), p1]
}

fn hermite_span3_error(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> f64 {
    let c = hermite_span3(f, t0, t1);
    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
        .iter()
        .map(|&u| {
            let exact = f(t0 + (t1 - t0) * u);
            let v = 1.0 - u;
            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
            let mut d = 0.0;
            for axis in 0..3 {
                let x = w[0] * c[0][axis] + w[1] * c[1][axis] + w[2] * c[2][axis] + w[3] * c[3][axis];
                d += (exact[axis] - x).powi(2);
            }
            d.sqrt()
        })
        .fold(0.0, f64::max)
}

fn adaptive_breaks3(f: &dyn Fn(f64) -> [f64; 3], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
    let mut breaks = vec![0.0];
    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
    while let Some((t0, t1, depth)) = pending.pop() {
        if hermite_span3_error(f, t0, t1) > tolerance {
            if depth >= 16 {
                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
            }
            let mid = 0.5 * (t0 + t1);
            pending.push((mid, t1, depth + 1));
            pending.push((t0, mid, depth + 1));
        } else {
            breaks.push(t1);
        }
    }
    Ok(breaks)
}

/// A space curve on [0, 1] as C1 cubic Hermite spans at the given breaks, and its worst error.
fn fit_on_breaks3(f: &dyn Fn(f64) -> [f64; 3], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
    let to_point = |p: [f64; 3]| Vec4::from_point(Vec3::new(p[0], p[1], p[2]), 1.0);
    let mut knots = vec![0.0; 4];
    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
    let mut worst = 0.0_f64;
    let spans = breaks.len() - 1;
    for index in 0..spans {
        let (t0, t1) = (breaks[index], breaks[index + 1]);
        let c = hermite_span3(f, t0, t1);
        worst = worst.max(hermite_span3_error(f, t0, t1));
        if index == 0 {
            points.push(to_point(c[0]));
        }
        points.push(to_point(c[1]));
        points.push(to_point(c[2]));
        if index + 1 < spans {
            knots.extend([t1, t1]);
        } else {
            points.push(to_point(c[3]));
        }
    }
    knots.extend([1.0; 4]);
    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
}

/// Builds a closed shell from faces whose loops are given in any direction: each loop is turned to run
/// counter-clockwise about the outward normal (its pcurves' area sign against `same_sense`). A face's first
/// loop is its outer loop.
pub(crate) struct ShellBuilder {
    pub(crate) vertices: Vec<crate::sweep_topology::VertexRecord>,
    pub(crate) edges: Vec<crate::sweep_topology::EdgeRecord>,
    pub(crate) faces: Vec<crate::sweep_topology::FaceRecord>,
    pub(crate) next: u64,
}

impl ShellBuilder {
    pub(crate) fn id(&mut self) -> u64 {
        self.next += 1;
        self.next
    }

    pub(crate) fn vertex(&mut self, p: Vec3) -> u64 {
        let id = self.id();
        self.vertices.push(crate::sweep_topology::VertexRecord { id, point: p });
        id
    }

    pub(crate) fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64) -> Result<u64, KernelRefusal> {
        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let id = self.id();
        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
        Ok(id)
    }

    /// A pole: an edge collapsed to the vertex `at` (its curve the surface's iso-curve there).
    pub(crate) fn degenerate_edge(&mut self, curve: NurbsCurve, at: u64) -> Result<u64, KernelRefusal> {
        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
        let id = self.id();
        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: at, end_vertex_id: at, degenerate: true, name: None });
        Ok(id)
    }

    #[allow(dead_code)]
    pub(crate) fn curve(&self, edge: u64) -> &NurbsCurve {
        &self.edges.iter().find(|e| e.id == edge).expect("a known edge").curve
    }

    /// `loops`: (edge, forward, pcurve along the edge's own direction).
    pub(crate) fn face(&mut self, surface: NurbsSurface, same_sense: bool, loops: Vec<Vec<(u64, bool, NurbsCurve)>>, name: String) -> Result<(), KernelRefusal> {
        use crate::sweep_topology::{CoedgeRecord, FaceRecord, LoopRecord};
        let area = |coedges: &[(u64, bool, NurbsCurve)]| -> Result<f64, KernelRefusal> {
            let mut points = Vec::new();
            for (_, forward, pcurve) in coedges {
                let [a, b] = pcurve.domain().map_err(|e| refuse("gear_pcurve", e))?;
                for i in 0..16 {
                    let f = i as f64 / 16.0;
                    let t = if *forward { a + (b - a) * f } else { b - (b - a) * f };
                    points.push(pcurve.evaluate(t).map_err(|e| refuse("gear_pcurve", e))?);
                }
            }
            Ok((0..points.len()).map(|i| {
                let (p, q) = (points[i], points[(i + 1) % points.len()]);
                p.x * q.y - q.x * p.y
            }).sum::<f64>() / 2.0)
        };
        // The first loop is the outer one (a sampled area cannot tell: a hole of many short edges can out-measure
        // an outer circle of one).
        let areas: Vec<f64> = loops.iter().map(|l| area(l)).collect::<Result<_, _>>()?;
        let outer = 0;
        let mut records = Vec::with_capacity(loops.len());
        for (index, coedges) in loops.into_iter().enumerate() {
            let want = (index == outer) == same_sense;
            let mut coedges = coedges;
            if (areas[index] > 0.0) != want {
                coedges.reverse();
                for coedge in &mut coedges {
                    coedge.1 = !coedge.1;
                }
            }
            let mut out = Vec::with_capacity(coedges.len());
            for (edge, forward, pcurve) in coedges {
                let pcurve = if forward { pcurve } else { pcurve.reversed().map_err(|e| refuse("gear_pcurve", e))? };
                out.push(CoedgeRecord { id: self.id(), edge_id: edge, forward, pcurve });
            }
            records.push(LoopRecord { id: self.id(), coedges: out });
        }
        let id = self.id();
        self.faces.push(FaceRecord { id, surface, same_sense, loops: records, name: Some(name) });
        Ok(())
    }
}

/// An elliptical gear: the pitch curve is an ellipse turning about one of its
/// foci, and the teeth are generated by rolling the standard basic rack round
/// it without slip (the rack's pitch line tangent to the ellipse, the contact
/// normal through the touching point), as a spur gear is generated round its
/// pitch circle. Two identical elliptical gears with an odd tooth count mesh
/// at a centre distance of the major axis (see [`elliptical_sizes`]).
///
/// The ellipse is sized so its perimeter is exactly `teeth` circular pitches
/// (π · module), so the teeth close. Tooth 0 is centred on the near vertex
/// (on +x, closest to the pivot).
#[derive(Clone, Debug)]
pub struct EllipticalGear {
    pub module: f64,
    pub teeth: usize,
    /// Eccentricity of the pitch ellipse (0 is a spur gear turning about its centre).
    pub eccentricity: f64,
    pub pressure_angle: f64,
    /// Addendum coefficient × module, measured normal to the pitch curve.
    pub addendum: f64,
    /// Dedendum coefficient × module, normal to the pitch curve.
    pub dedendum: f64,
    /// Tip radius of the generating rack × module.
    pub root_fillet: f64,
    /// Arc length added to each tooth space along the pitch curve.
    pub backlash: f64,
    pub face_width: f64,
}

/// The pitch ellipse about its focus, by arc length.
struct PitchEllipse {
    /// Semi-latus rectum: r(θ) = p / (1 + e cos nθ) about the focus (n = 1, an ellipse) or the centre (n lobes).
    latus: f64,
    e: f64,
    lobes: f64,
    segments: usize,
    /// Cumulative arc length at θ = 2π i / SEGMENTS.
    table: Vec<f64>,
}

impl PitchEllipse {
    const SEGMENTS: usize = 1024;

    fn new(latus: f64, e: f64) -> Self {
        Self::lobed(latus, e, 1)
    }

    fn lobed(latus: f64, e: f64, lobes: usize) -> Self {
        let segments = Self::SEGMENTS * lobes.max(1);
        let mut curve = Self { latus, e, lobes: lobes.max(1) as f64, segments, table: Vec::with_capacity(segments + 1) };
        // Five-point Gauss-Legendre per segment.
        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
        let step = TAU / segments as f64;
        let mut total = 0.0;
        curve.table.push(0.0);
        for i in 0..segments {
            let mid = (i as f64 + 0.5) * step;
            let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
            total += 0.5 * step * sum;
            curve.table.push(total);
        }
        curve
    }

    fn length(&self) -> f64 {
        self.table[self.segments]
    }

    /// Point, first and second derivatives in θ.
    fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
        let n = self.lobes;
        let (s, c) = theta.sin_cos();
        let (sn, cn) = (n * theta).sin_cos();
        let d = 1.0 + self.e * cn;
        let d1 = -self.e * n * sn;
        let d2 = -self.e * n * n * cn;
        let r = self.latus / d;
        let r1 = -self.latus * d1 / (d * d);
        let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
        (
            [r * c, r * s],
            [r1 * c - r * s, r1 * s + r * c],
            [r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
        )
    }

    fn speed(&self, theta: f64) -> f64 {
        let (_, d1, _) = self.derivatives(theta);
        d1[0].hypot(d1[1])
    }

    /// The polar angle at arc length `s` (any real; the curve is periodic).
    fn theta_at(&self, s: f64) -> f64 {
        let length = self.length();
        let turns = (s / length).floor();
        let local = s - turns * length;
        let index = self.table.partition_point(|&value| value <= local).clamp(1, self.segments) - 1;
        let step = TAU / self.segments as f64;
        let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
        let span = self.table[index + 1] - self.table[index];
        let mut theta = lo + step * (local - self.table[index]) / span;
        // Newton on the segment's arc length, measured from its start by Gauss-Legendre.
        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
        for _ in 0..8 {
            let half = 0.5 * (theta - lo);
            let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
            let error = self.table[index] + arc - local;
            theta = (theta - error / self.speed(theta)).clamp(lo, hi);
            if error.abs() < 1e-15 * length {
                break;
            }
        }
        theta + turns * TAU
    }

    /// Point, unit tangent (counter-clockwise), outward unit normal and signed curvature at arc length `s`.
    fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
        let (p, d1, d2) = self.derivatives(self.theta_at(s));
        let speed = d1[0].hypot(d1[1]);
        let t = [d1[0] / speed, d1[1] / speed];
        let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
        (p, t, [t[1], -t[0]], curvature)
    }
}

/// The derived sizes of an elliptical gear: (semi-major axis, eccentricity,
/// perimeter, centre distance to an identical mate = 2 × semi-major axis).
pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
    lobed_sizes(gear, 1)
}

/// [`elliptical_sizes`] for a pitch curve of `lobes` lobes, r(θ) = a (1 − e²) / (1 + e cos(lobes · θ)) about its
/// centre (one lobe: the ellipse about its focus). Two equal gears roll on it at the same centre distance 2a.
pub fn lobed_sizes(gear: &EllipticalGear, lobes: usize) -> (f64, f64, f64, f64) {
    let e = gear.eccentricity;
    let unit = PitchEllipse::lobed(1.0 - e * e, e, lobes); // a = 1
    let a = PI * gear.module * gear.teeth as f64 / unit.length();
    (a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
}

/// The rack, pitch line on y = 0 with +y away from the gear, rolled to arc
/// length `s`: rack point (x, y) lies at P(s) + (x − s) T(s) + y N(s).
struct RollingRack<'a> {
    pitch: &'a PitchEllipse,
}

impl RollingRack<'_> {
    /// The gear point generated by the rack point `q` with normal direction `n`
    /// (either sense): the normal through q meets the pitch line at the rolling position.
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = q[0] - q[1] * n[0] / n[1];
        self.place(q, s)
    }

    fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
        let (p, t, n, _) = self.pitch.frame(s);
        let u = q[0] - s;
        [p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
    }

    /// The arc length of the foot of the normal from `g` to the pitch curve
    /// (starting near `guess`) and the signed distance along the outward normal.
    fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
        let mut sigma = guess;
        for _ in 0..40 {
            let (p, t, n, curvature) = self.pitch.frame(sigma);
            let v = [g[0] - p[0], g[1] - p[1]];
            let along = v[0] * t[0] + v[1] * t[1];
            let distance = v[0] * n[0] + v[1] * n[1];
            let step = along / (1.0 + curvature * distance);
            sigma += step;
            if step.abs() < 1e-15 * self.pitch.length() {
                break;
            }
        }
        let (p, _, n, _) = self.pitch.frame(sigma);
        (sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
    }
}

/// The elliptical gear section, counter-clockwise about the pivot (the focus,
/// at the origin). Roles per tooth k, as the spur gear's: `V<k>` root fillet,
/// `R<k>` flank rising to `K<k>` the tip land (normal offset of the pitch
/// curve), `L<k>` the falling flank, `W<k>` root fillet, `G<k>` the root land
/// (inward offset) of the space after tooth k.
pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
    lobed_section(gear, 1)
}

/// [`elliptical_section`] on a pitch curve of `lobes` lobes about its centre ([`lobed_sizes`]); tooth 0 is
/// centred on +x, where the curve is nearest its axis.
pub fn lobed_section(gear: &EllipticalGear, lobes: usize) -> Result<GearSection, KernelRefusal> {
    if !(1..=8).contains(&lobes) {
        return Err(refuse("gear_input", format!("A lobed pitch curve has 1 to 8 lobes (not {lobes}).")));
    }
    let m = gear.module;
    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
    }
    if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
    }
    if !(0.0..=0.8).contains(&gear.eccentricity) {
        return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
    }
    if gear.teeth < 8 || gear.teeth > 1000 {
        return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
    }
    let (a, e, perimeter, _) = lobed_sizes(gear, lobes);
    let pitch_curve = PitchEllipse::lobed(a * (1.0 - e * e), e, lobes);
    let rack = RollingRack { pitch: &pitch_curve };
    let z = gear.teeth as f64;
    let p = perimeter / z;
    let alpha = gear.pressure_angle;
    let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
    let h_a = gear.addendum * m;
    let h_f = gear.dedendum * m;
    let rho = gear.root_fillet * m;
    let tolerance = GEAR_FIT_TOLERANCE * m;
    // The sharpest point of the ellipse is its major vertex: radius b²/a.
    // The sharpest point's radius of curvature: the ellipse's major vertex b²/a; with lobes, read off the curve
    // (which must be convex for a rack to roll round it).
    let min_radius = if lobes == 1 {
        a * (1.0 - e * e)
    } else {
        let mut least = f64::INFINITY;
        for i in 0..4096 {
            let (_, d1, d2) = pitch_curve.derivatives(TAU * i as f64 / 4096.0);
            let cross = d1[0] * d2[1] - d1[1] * d2[0];
            if !(cross > 0.0) {
                return Err(refuse("not_convex", format!("The {lobes}-lobe pitch curve is not convex at this eccentricity ({e}): a rack cannot roll round it; lower the eccentricity.")));
            }
            least = least.min(d1[0].hypot(d1[1]).powi(3) / cross);
        }
        least
    };
    if h_f >= min_radius {
        return Err(refuse(
            "undercut",
            format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
        ));
    }
    // Cutter tooth centred on x = 0 (it cuts the space there): half width at height y is w0 + y tan α.
    let w0 = p / 4.0 + gear.backlash / 2.0;
    let centre_y = -h_f + rho;
    let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; // low-side fillet centre
    if centre_x >= 0.0 {
        return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
    }
    let y_join = centre_y - rho * sin_a;
    let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
    let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
    // ψ ∈ [0, 1]: from the flank tangency (0) to the tip line (1).
    let fillet_normal = |t: f64| {
        let psi = -PI + alpha + t * (PI / 2.0 - alpha);
        [psi.cos(), psi.sin()]
    };
    let low_fillet = |c: f64, t: f64| {
        let n = fillet_normal(t);
        if rho == 0.0 {
            return rack.envelope([c + centre_x, centre_y], n);
        }
        rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
    };
    let high_fillet = |c: f64, t: f64| {
        let n = fillet_normal(t);
        if rho == 0.0 {
            return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
        }
        rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
    };
    let root = |x: f64| rack.place([x, -h_f], x);
    let tip = |sigma: f64| {
        let (q, _, n, _) = pitch_curve.frame(sigma);
        [q[0] + h_a * n[0], q[1] + h_a * n[1]]
    };
    // The generated flank is regular while sin²α + y κ > 0 down to its foot (it cusps
    // where the rack flank passes the point of interference); κ is largest, 1 / min_radius,
    // at the major vertices.
    if sin_a * sin_a + y_join / min_radius <= 1e-9 {
        return Err(refuse(
            "undercut",
            format!(
                "The teeth would be undercut where the ellipse is sharpest (radius of curvature {min_radius:.4}): add teeth, lower the eccentricity or raise the pressure angle."
            ),
        ));
    }
    // The flank height where a generated flank reaches the tip offset (offset distance h_a).
    let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
        let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
        let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
        if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
            return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
        }
        // Until the interval stops shrinking (about 55 halvings), not a fixed 200 evaluations.
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if !(mid > lo && mid < hi) {
                break;
            }
            if offset(mid) < 0.0 { lo = mid } else { hi = mid }
        }
        let y = 0.5 * (lo + hi);
        Ok((y, rack.foot(flank(y), guess).0))
    };
    let mut curves = Vec::with_capacity(6 * gear.teeth);
    let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
    for k in 0..gear.teeth {
        let before = (k as f64 - 0.5) * p; // the space before tooth k
        let after = (k as f64 + 0.5) * p;
        let rising = |y: f64| high_flank(before, y);
        let falling = |y: f64| low_flank(after, y);
        let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
        let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
        if sigma_fall - sigma_rise <= 1e-6 * m {
            return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
        }
        curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
        curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
        curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
        if centre_x < -1e-9 * m {
            curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
        }
    }
    snap_junctions(&mut curves);
    let samples = 4096;
    let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
    for i in 0..samples {
        let s = perimeter * i as f64 / samples as f64;
        tip_max = tip_max.max(radius_of(tip(s)));
        root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
    }
    let data = GearData {
        pitch_diameter: perimeter / PI,
        tip_diameter: 2.0 * tip_max,
        root_diameter: 2.0 * root_min,
        tooth_thickness: p / 2.0 - gear.backlash,
        ..GearData::default()
    };
    Ok(GearSection { curves, data })
}

/// An elliptical gear solid: the section extruded along +z by the face width;
/// names as the section's roles, then `F` and `B`.
pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    lobed_solid(gear, 1)
}

/// A lobed non-circular gear solid ([`lobed_section`] extruded by the face width), names as the elliptical gear's.
pub fn lobed_solid(gear: &EllipticalGear, lobes: usize) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let section = lobed_section(gear, lobes)?;
    let solid = extrude_section(&section, gear.face_width)?;
    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
    names.push("F".into());
    names.push("B".into());
    Ok((solid, names, section.data))
}

/// The parameter breaks (normalised to [0, 1]) at which [`fit_planar`] would
/// split `f` on `[a, b]` to fit it within `tolerance`.
fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
    let mut breaks = vec![0.0];
    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
    while let Some((t0, t1, depth)) = pending.pop() {
        if hermite_span_error(f, t0, t1) > tolerance {
            if depth >= 16 {
                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
            }
            let mid = 0.5 * (t0 + t1);
            pending.push((mid, t1, depth + 1));
            pending.push((t0, mid, depth + 1));
        } else {
            breaks.push(t1);
        }
    }
    Ok(breaks)
}

/// Merge `fresh` breaks into `breaks` role by role (both are dyadic, so the union refines each
/// shared set only where the fresh one is finer). Returns whether any break was added.
fn merge_breaks(breaks: &mut [Vec<f64>], fresh: Vec<Vec<f64>>) -> bool {
    let mut added = false;
    for (role_breaks, more) in breaks.iter_mut().zip(fresh) {
        let before = role_breaks.len();
        role_breaks.extend(more);
        role_breaks.sort_by(f64::total_cmp);
        role_breaks.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
        added |= role_breaks.len() > before;
    }
    added
}

/// Halve every span of every role (the fallback when a plane's own breaks add nothing).
fn halve_breaks(breaks: &mut [Vec<f64>]) {
    for role_breaks in breaks.iter_mut() {
        let mut finer = Vec::with_capacity(2 * role_breaks.len());
        for pair in role_breaks.windows(2) {
            finer.push(pair[0]);
            finer.push(0.5 * (pair[0] + pair[1]));
        }
        finer.push(1.0);
        *role_breaks = finer;
    }
}

/// The cubic Hermite span of `f` on `[t0, t1]` (numeric end derivatives) as Bézier points.
fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
    let derivative = |t: f64| {
        let h = 1e-6;
        let (p, q) = (f(t + h), f(t - h));
        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
    };
    let (p0, p1) = (f(t0), f(t1));
    let (d0, d1) = (derivative(t0), derivative(t1));
    let k = (t1 - t0) / 3.0;
    [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
}

fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
    let c = hermite_span(f, t0, t1);
    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
        .iter()
        .map(|&u| {
            let exact = f(t0 + (t1 - t0) * u);
            let v = 1.0 - u;
            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
            let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
            let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
            (exact[0] - x).hypot(exact[1] - y)
        })
        .fold(0.0, f64::max)
}

/// `f` on [0, 1] as C1 cubic Hermite spans at the given breaks (as
/// [`fit_planar`] lays them out), and its worst error over the spans.
fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
    let mut knots = vec![0.0; 4];
    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
    let mut worst = 0.0_f64;
    let spans = breaks.len() - 1;
    for index in 0..spans {
        let (t0, t1) = (breaks[index], breaks[index + 1]);
        let c = hermite_span(f, t0, t1);
        worst = worst.max(hermite_span_error(f, t0, t1));
        if index == 0 {
            points.push(to_point(c[0]));
        }
        points.push(to_point(c[1]));
        points.push(to_point(c[2]));
        if index + 1 < spans {
            knots.extend([t1, t1]);
        } else {
            points.push(to_point(c[3]));
        }
    }
    knots.extend([1.0; 4]);
    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
}

/// A throated (single-enveloping) worm wheel: the teeth are cut as a hob of
/// the mating ZA worm cuts them, the worm's thread swept by the generating
/// motion (the worm turning, the wheel turning with it at the gear ratio).
/// In every plane across the face width the worm's thread section moves as a
/// rack and the wheel section is its envelope; the flanks, tips (the throat,
/// a torus about the worm's axis) and roots are skinned through those
/// sections. Front face on z = 0, back face on z = face width; the worm's
/// axis runs along +y at x = centre distance, z = face width / 2.
#[derive(Clone, Debug)]
pub struct WormWheel {
    /// The mating worm (its length is not used).
    pub worm: Worm,
    pub teeth: usize,
    /// Wheel addendum × module, in the mid-plane (the throat).
    pub addendum: f64,
    /// Wheel dedendum × module, in the mid-plane: the hob's tip (the worm's tip plus the clearance).
    pub dedendum: f64,
    pub face_width: f64,
    /// Axial backlash: the hob's thread is that much thicker than the worm's.
    pub backlash: f64,
}

/// The worm wheel's sizes: (pitch radius, centre distance, throat radius in the mid-plane, outside radius at the faces).
pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
    let m = wheel.worm.axial_module;
    let r2 = m * wheel.teeth as f64 / 2.0;
    let a = r2 + wheel.worm.reference_diameter / 2.0;
    let throat = r2 + wheel.addendum * m;
    let tube = a - throat;
    let half = wheel.face_width / 2.0;
    (r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
}

/// One plane z = c (from the mid-plane) of the wheel: the hob section as a rack.
struct WheelPlane<'a> {
    wheel: &'a WormWheel,
    c: f64,
    r2: f64,
    a: f64,
    /// The hob's tip radius about the worm axis.
    rho_tip: f64,
    /// The wheel's tip (throat) radius in this plane.
    r_tip: f64,
    /// Flank parameters (radius about the worm axis) where each flank reaches the tip: [- side, + side].
    rho_clip: [f64; 2],
}

impl<'a> WheelPlane<'a> {
    fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
        let m = wheel.worm.axial_module;
        let (r2, a, throat, _) = worm_wheel_sizes(wheel);
        let rho_tip = a - (r2 - wheel.dedendum * m);
        let tube = a - throat;
        let r_tip = a - (tube * tube - c * c).sqrt();
        let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
        for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
            // The generated flank falls from above the tip to the root. A hob point with rho under the throat's
            // tube radius sits beyond the throat (x = a - sqrt(rho^2 - c^2) > r_tip), and so does its envelope.
            let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
            if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
                return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
            }
            for _ in 0..200 {
                let mid = 0.5 * (lo + hi);
                if !(mid > lo && mid < hi) {
                    break;
                }
                if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
            }
            plane.rho_clip[index] = 0.5 * (lo + hi);
        }
        Ok(plane)
    }

    /// The hob flank point (radial x from the wheel axis, y along the worm axis) at radius `rho`
    /// about the worm axis, on the `side` (±1) of the thread centred on y = 0.
    fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
        let worm = &self.wheel.worm;
        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
        let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
        let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
        [self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
    }

    fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
        // d/drho of hob(): x = a - sqrt(rho^2 - c^2), y = side t(rho) / 2 + hand L asin(c / rho) / 2 pi (exact:
        // a difference quotient's rounding noise is magnified by the fits' own derivative steps).
        let worm = &self.wheel.worm;
        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
        let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
        let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
        let length = t[0].hypot(t[1]);
        // Outward of the thread: +y on the + side.
        let n = [-t[1] / length, t[0] / length];
        if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
    }

    /// The wheel point generated by the hob point `q` with normal `n` (rolling at the pitch radius).
    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
        let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
        rotate([q[0], q[1] + s], -s / self.r2)
    }

    fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
        self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
    }

    /// The root fillet the hob's sharp tip corner traces, `t` from the flank (0) to the tip land (1).
    fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
        let n = self.hob_normal(side, self.rho_tip);
        let from = n[1].atan2(n[0]);
        let psi = from + t * (side * PI - from);
        self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
    }

    /// The six pieces of tooth 0 on normalised parameters, in section order V, R, K, L, W, G.
    fn piece(&self, role: usize, t: f64) -> [f64; 2] {
        let tau = TAU / self.wheel.teeth as f64;
        let half = tau / 2.0;
        let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
        let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
        match role {
            0 => turn(self.fillet(1.0, 1.0 - t), -half),
            1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
            2 => {
                let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
                let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
                let angle = from + t * (to - from) - half;
                [self.r_tip * angle.cos(), self.r_tip * angle.sin()]
            }
            3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
            4 => turn(self.fillet(-1.0, t), half),
            _ => {
                // The root land of the space after the tooth (the base space turned by tau, then by -half).
                let from = polar_angle(self.fillet(-1.0, 1.0));
                let to = polar_angle(self.fillet(1.0, 1.0));
                let angle = from + t * (to - from) + half;
                [root_r * angle.cos(), root_r * angle.sin()]
            }
        }
    }

    /// Refuse a plane whose teeth are pointed, whose roots meet, or whose flanks are undercut.
    fn check(&self) -> Result<(), KernelRefusal> {
        let m = self.wheel.worm.axial_module;
        let tau = TAU / self.wheel.teeth as f64;
        let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
        if tip_span * self.r_tip <= 1e-6 * m {
            return Err(refuse("pointed_tip", format!("The wheel teeth come to a point below the throat {:.4} from the mid-plane: lower the addendum or the face width.", self.c)));
        }
        let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
        if root_span <= 1e-9 {
            return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
        }
        // Each flank must fall steadily from its tip to its root, and the corner's trace must not cross it.
        for side in [-1.0, 1.0] {
            let index = if side < 0.0 { 0 } else { 1 };
            let flank: Vec<[f64; 2]> = (0..=96).map(|i| self.flank(side, self.rho_clip[index] + (self.rho_tip - self.rho_clip[index]) * i as f64 / 96.0)).collect();
            let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
            let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
            let crosses = flank[..flank.len() - 2].windows(2).any(|f| fillet[1..].windows(2).any(|g| segments_cross(f[0], f[1], g[0], g[1])));
            if !falling || crosses {
                return Err(refuse(
                    "undercut",
                    format!("The worm undercuts the wheel teeth {:.4} from the mid-plane: add wheel teeth, narrow the face width or raise the pressure angle.", self.c),
                ));
            }
        }
        Ok(())
    }
}

fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
    let cross = |o: [f64; 2], p: [f64; 2], q: [f64; 2]| (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]);
    let (d1, d2) = (cross(c, d, a), cross(c, d, b));
    let (d3, d4) = (cross(a, b, c), cross(a, b, d));
    d1 * d2 < 0.0 && d3 * d4 < 0.0
}

const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];

/// Tooth 0's six curves in the plane `c`, fitted on the shared breaks, at height z.
fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
    let mut curves = Vec::with_capacity(6);
    let mut worst = 0.0_f64;
    for (role, role_breaks) in breaks.iter().enumerate() {
        let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
        worst = worst.max(error);
        for p in &mut curve.control_points {
            p.z = z * p.w;
        }
        curves.push(curve);
    }
    Ok((curves, worst))
}

/// The full section (every tooth) from tooth 0's curves, junctions shared.
fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
    let tau = TAU / teeth as f64;
    let mut curves = Vec::with_capacity(6 * teeth);
    for index in 0..teeth {
        for (role, curve) in tooth.iter().enumerate() {
            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
        }
    }
    snap_junctions(&mut curves);
    curves
}

/// A throated worm wheel solid and its data; face names as the spur gear's
/// per tooth (`V/R/K/L/W/G<n>`, the `K` faces making the throat), then `F` (z = 0) and `B`.
pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
    let worm = &wheel.worm;
    let m = worm.axial_module;
    worm_section(worm)?; // the worm's own checks
    if wheel.teeth < 12 || wheel.teeth > 400 {
        return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
    }
    if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
        return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
    }
    let (r2, a, throat, _) = worm_wheel_sizes(wheel);
    let tube = a - throat;
    let limit = 0.9 * tube;
    if wheel.face_width / 2.0 > limit {
        return Err(refuse(
            "face_too_wide",
            format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
        ));
    }
    // The hob's thread at the wheel's tip (in the mid-plane) must leave a tooth in the axial pitch. Checked
    // here, before any polar angle: a thread a whole pitch wider wraps round to the same teeth.
    if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
        return Err(refuse("pointed_tip", format!("The backlash ({}) leaves no wheel tooth: the hob's thread fills the whole axial pitch at the throat.", wheel.backlash)));
    }
    if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
        return Err(refuse("pointed_tip", "The hob's thread (the worm's, grown to the wheel's root) comes to a point: lower the wheel dedendum.".into()));
    }
    let half = wheel.face_width / 2.0;
    let tolerance = GEAR_GENERATED_TOLERANCE * GENERATED_SECTION_SHARE * m;
    let skin_tolerance = GEAR_GENERATED_TOLERANCE * (1.0 - GENERATED_SECTION_SHARE) * m;
    // Shared breaks per role from the mid-plane and both faces.
    let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
    for plane in &probe {
        plane.check()?;
    }
    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
    for role in 0..6 {
        let mut all: Vec<f64> = Vec::new();
        for plane in &probe {
            all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
        }
        all.sort_by(f64::total_cmp);
        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
        breaks.push(all);
    }
    // Planes across the face; each plane's control points carried along v by
    // cubic Hermite spans (derivatives from planes a step either side).
    let mut planes = 8usize;
    loop {
        let step = wheel.face_width / planes as f64;
        let delta = 1e-3 * step;
        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); // tooth 0 per plane
        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
        let mut refit: Option<WheelPlane> = None;
        for j in 0..=planes {
            let c = -half + step * j as f64;
            let plane = WheelPlane::new(wheel, c)?;
            plane.check()?;
            let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
            if worst > tolerance {
                refit = Some(plane);
                break;
            }
            let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
            let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
            let slope: Vec<Vec<[f64; 2]>> = lo
                .iter()
                .zip(&hi)
                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
                .collect();
            rows.push(tooth);
            slopes.push(slope);
        }
        if let Some(plane) = refit {
            // A plane the shared breaks fit too loosely: add that plane's own breaks (refining only the spans
            // it needs), else halve every span, and start over.
            let fresh = (0..6).map(|role| adaptive_breaks(&|t| plane.piece(role, t), tolerance)).collect::<Result<Vec<_>, _>>()?;
            if !merge_breaks(&mut breaks, fresh) {
                halve_breaks(&mut breaks);
            }
            continue;
        }
        // Check the skin halfway between planes against the exact plane there.
        let mut worst = 0.0_f64;
        for j in 0..planes {
            let c = -half + step * (j as f64 + 0.5);
            let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
            for role in 0..6 {
                for (k, p) in exact[role].control_points.iter().enumerate() {
                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
                    worst = worst.max((x - p.x).hypot(y - p.y));
                }
            }
        }
        if worst > skin_tolerance {
            if planes >= 256 {
                return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
            }
            // The skin's error falls as the fourth power of the plane spacing: go straight to the count that
            // reading predicts (with a margin), not plane-count doubling by doubling.
            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
            continue;
        }
        // Rows along v for every control point of the full bottom section, keyed by its bits.
        // Tooth 0's section with its junctions shared; every tooth's rows are tooth 0's turned.
        let first = wheel_section(&rows[0], wheel.teeth);
        let tau = TAU / wheel.teeth as f64;
        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
        let h = 1.0 / planes as f64;
        for (index, piece) in first.iter().enumerate() {
            let (role, tooth) = (index % 6, index / 6);
            let (s, cs) = (tau * tooth as f64).sin_cos();
            for (k, p) in piece.curve.control_points.iter().enumerate() {
                let mut row = Vec::with_capacity(3 * planes + 1);
                for j in 0..=planes {
                    let q = if j == 0 { piece.curve.control_points[k] } else { let p = rows[j][role].control_points[k]; Vec4 { x: cs * p.x - s * p.y, y: s * p.x + cs * p.y, z: p.z, w: p.w } };
                    let d = slopes[j][role][k];
                    // The slope in v (per unit v: face width per unit c), turned with the tooth.
                    let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
                    let point = Vec3::new(q.x, q.y, q.z);
                    if j > 0 {
                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
                    }
                    if j == 0 || j == planes {
                        row.push(Vec4::from_point(point, 1.0));
                    }
                    if j < planes {
                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
                    }
                }
                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
            }
        }
        let mut knots_v = vec![0.0; 4];
        for j in 1..planes {
            let v = j as f64 * h;
            knots_v.extend([v, v]);
        }
        knots_v.extend([1.0; 4]);
        let section = GearSection { curves: first.clone(), data: GearData::default() };
        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
        })?;
        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
        names.push("F".into());
        names.push("B".into());
        let data = GearData {
            pitch_diameter: 2.0 * r2,
            tip_diameter: 2.0 * throat,
            root_diameter: 2.0 * (r2 - wheel.dedendum * m),
            tip_thickness: 0.0,
            ..GearData::default()
        };
        return Ok((solid, names, data));
    }
}

/// A crown (face) gear: teeth on the flat face of a disc, for a spur pinion
/// whose axis lies parallel to that face and meets the crown's axis (90°
/// shaft angle). The teeth are cut as a shaper cuts them: a spur shaper with
/// `shaper_extra` more teeth than the pinion turns about the pinion's axis
/// while the crown turns with it at the tooth ratio, and the tooth spaces are
/// the volume its teeth sweep. The shaper's flanks are involutes and its tips
/// are rounded (0.2 × module, less on a thin tooth) and flat between the rounds, so every
/// face of a tooth space (root land, fillets, flanks) is the envelope of one
/// smooth piece of the shaper's outline. A shaper with more teeth than the
/// pinion touches it at a point rather than along a line, which keeps the
/// pair's contact clear of the tooth ends.
///
/// The crown's axis is +z; its back face is z = 0, the root plane z = `rim`,
/// the pitch plane z = `rim` + dedendum × module and the tips the plane
/// above by the addendum. The pinion's axis runs along +x (through the crown
/// axis, so radially) at the pitch plane + the pinion's pitch radius; tooth
/// space 0 is centred on +x.
#[derive(Clone, Debug)]
pub struct CrownGear {
    pub module: f64,
    pub teeth: usize,
    /// Teeth of the mating spur pinion.
    pub pinion_teeth: usize,
    /// The shaper's teeth over the pinion's (1 to 3).
    pub shaper_extra: usize,
    pub pressure_angle: f64,
    /// Crown addendum × module above the pitch plane (the pinion's dedendum less the clearance).
    pub addendum: f64,
    /// Crown dedendum × module below the pitch plane: the shaper's addendum (the pinion's plus the clearance).
    pub dedendum: f64,
    /// Inner radius of the toothed ring; 0 takes the undercut limit ([`crown_limits`]).
    pub inner_radius: f64,
    /// Outer radius of the toothed ring; 0 takes the pointed-tooth limit.
    pub outer_radius: f64,
    /// Blank thickness under the root plane.
    pub rim: f64,
}

/// The shaper's tip round, × module.
const CROWN_TIP_ROUND: f64 = 0.2;
/// The narrowest tip land the outer radius may leave, × module.
const CROWN_TIP_LAND: f64 = 0.05;

/// The generating shaper in its transverse plane: (Y, H), H up from the
/// shaper's axis, tooth 0 pointing down (to the crown), polar angle from −H
/// towards +Y. Its +Y side generates the +Y wall of tooth space 0.
struct CrownShaper {
    /// Pitch, base and tip radii.
    rs: f64,
    rb: f64,
    ra: f64,
    /// Crown turn per shaper turn (shaper teeth / crown teeth).
    k: f64,
    /// Half the tooth's angle at the pitch circle plus inv(α): the flank at roll u sits at c0 − inv(α(u)).
    c0: f64,
    /// Tip round radius, its centre and the roll where it meets the involute.
    rr: f64,
    centre: [f64; 2],
    uj: f64,
    /// Polar angle of the round's centre (half the tip land's angle).
    bc: f64,
    /// Normal angles (CCW from +Y) of the round where it meets the land and the involute.
    psi_land: f64,
    psi_flank: f64,
}

/// A point of the shaper's outline with its outward unit normal and its
/// moment about the shaper's axis (point × normal), which the generating
/// motion leaves unchanged.
#[derive(Clone, Copy)]
struct OutlinePoint {
    q: [f64; 2],
    n: [f64; 2],
    moment: f64,
}

impl CrownShaper {
    fn new(gear: &CrownGear) -> Result<Self, KernelRefusal> {
        let m = gear.module;
        let ns = (gear.pinion_teeth + gear.shaper_extra) as f64;
        let alpha = gear.pressure_angle;
        let rs = m * ns / 2.0;
        let rb = rs * alpha.cos();
        let ra = rs + gear.dedendum * m;
        let c0 = PI / (2.0 * ns) + alpha.tan() - alpha;
        // The tip round: 0.2 × module, smaller on a thin tooth so a tip land of at least 0.02 × module stays.
        let mut rr = CROWN_TIP_ROUND * m;
        for _ in 0..12 {
            let shaper = Self::rounded(rs, rb, ra, ns / gear.teeth as f64, c0, rr)?;
            if shaper.bc * ra >= 0.01 * m {
                return Ok(shaper);
            }
            rr *= 0.7;
        }
        Err(refuse("shaper_tip", "The shaper's teeth come to a point before its tip: lower the dedendum or raise the shaper's teeth.".into()))
    }

    fn rounded(rs: f64, rb: f64, ra: f64, k: f64, c0: f64, rr: f64) -> Result<Self, KernelRefusal> {
        let mut shaper = Self { rs, rb, ra, k, c0, rr, centre: [0.0; 2], uj: 0.0, bc: 0.0, psi_land: 0.0, psi_flank: 0.0 };
        // The round touches the tip circle (its centre on ra − rr) and the involute.
        let reach = |u: f64| {
            let p = shaper.involute(u);
            radius_of([p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]])
        };
        let u_tip = ((ra / rb).powi(2) - 1.0).sqrt();
        let (mut lo, mut hi) = (0.0, u_tip);
        if !(reach(lo) < ra - rr && reach(hi) > ra - rr) {
            return Err(refuse("shaper_tip", "The shaper's tip round does not fit its tooth: lower the dedendum or the pressure angle.".into()));
        }
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            if reach(mid) < ra - rr { lo = mid } else { hi = mid }
        }
        shaper.uj = 0.5 * (lo + hi);
        let p = shaper.involute(shaper.uj);
        shaper.centre = [p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]];
        shaper.bc = shaper.centre[0].atan2(-shaper.centre[1]);
        shaper.psi_land = shaper.centre[1].atan2(shaper.centre[0]);
        shaper.psi_flank = p.n[1].atan2(p.n[0]);
        Ok(shaper)
    }

    /// The +Y flank (an involute of the base circle) at roll `u`.
    fn involute(&self, u: f64) -> OutlinePoint {
        let s = (1.0 + u * u).sqrt();
        let rho = self.rb * s;
        let beta = self.c0 - u + u.atan();
        let (sb, cb) = beta.sin_cos();
        let (e, de) = ([sb, -cb], [cb, sb]);
        OutlinePoint { q: [rho * e[0], rho * e[1]], n: [(u * e[0] + de[0]) / s, (u * e[1] + de[1]) / s], moment: self.rb }
    }

    /// The +Y tip round at normal angle `psi`.
    fn round(&self, psi: f64) -> OutlinePoint {
        let n = [psi.cos(), psi.sin()];
        let c = self.centre;
        OutlinePoint { q: [c[0] + self.rr * n[0], c[1] + self.rr * n[1]], n, moment: c[0] * n[1] - c[1] * n[0] }
    }

    /// The crown point (crown frame: X along tooth space 0, Y, height h above the pitch plane) that
    /// the outline point generates where the shaper's line of it crosses x (from the crown axis).
    fn generate(&self, p: OutlinePoint, x: f64) -> Option<[f64; 3]> {
        // Contact where the normal is square to the relative velocity: n·v = 0 with
        // v = (k y, rs − h − k x, y) gives (n rotated by φ)_Y · k x = moment.
        let c = p.moment / (self.k * x);
        if !(c.abs() <= 1.0) {
            return None;
        }
        let mut phi = -c.acos() - p.n[1].atan2(p.n[0]);
        phi = (phi + PI).rem_euclid(TAU) - PI;
        let q = rotate(p.q, phi);
        let (s, co) = (self.k * phi).sin_cos();
        Some([x * co + q[0] * s, -x * s + q[0] * co, self.rs + q[1]])
    }

    /// The point `p` generates on the cylinder of `radius` about the crown axis: (polar angle, h).
    fn on_cylinder(&self, p: OutlinePoint, radius: f64) -> Option<[f64; 2]> {
        // The crown's turn keeps the radius: it is hypot(x, y) of the shaper's contact point.
        let radius_at = |x: f64| self.generate(p, x).map(|g| (g[0].hypot(g[1]), g));
        let mut x = radius;
        for _ in 0..60 {
            let (r, g) = radius_at(x)?;
            let error = r - radius;
            if error.abs() <= 1e-13 * radius {
                return Some([g[1].atan2(g[0]), g[2]]);
            }
            let dx = 1e-7 * radius;
            let slope = (radius_at(x + dx)?.0 - r) / dx;
            // Damped: a full step may leave the range where the contact exists (x < moment / k).
            let mut step = error / slope;
            let mut halvings = 0;
            while !(step.is_finite() && radius_at(x - step).is_some()) {
                step *= 0.5;
                halvings += 1;
                if !step.is_finite() || halvings > 60 {
                    return None;
                }
            }
            x -= step;
        }
        None
    }
}

fn check_crown_input(gear: &CrownGear) -> Result<(), KernelRefusal> {
    let m = gear.module;
    if !(m > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.rim > 0.0) {
        return Err(refuse("gear_input", "The module, addendum, dedendum and rim must be positive.".into()));
    }
    // The limits search out to 4 × the pitch radius: keep every size well inside the floating-point range.
    let sizes = [m, gear.addendum * m, gear.dedendum * m, gear.rim, gear.inner_radius, gear.outer_radius, 4.0 * m * gear.teeth as f64];
    if sizes.iter().any(|v| !(v.is_finite() && v.abs() < 1e12)) {
        return Err(refuse("gear_input", "The crown gear's sizes must be finite and under 1e12.".into()));
    }
    if !(gear.inner_radius >= 0.0 && gear.outer_radius >= 0.0) {
        return Err(refuse("gear_input", "The inner and outer radii must not be negative (0 takes the limits).".into()));
    }
    if gear.pinion_teeth < 10 || gear.pinion_teeth > 100 {
        return Err(refuse("gear_input", format!("The pinion needs from 10 to 100 teeth (it has {}).", gear.pinion_teeth)));
    }
    if !(1..=3).contains(&gear.shaper_extra) {
        return Err(refuse("gear_input", format!("The shaper has 1 to 3 teeth more than the pinion (not {}).", gear.shaper_extra)));
    }
    let shaper = gear.pinion_teeth + gear.shaper_extra;
    if gear.teeth < 2 * shaper || gear.teeth > 600 {
        return Err(refuse("gear_input", format!("A crown gear needs from twice the shaper's teeth ({}) to 600 teeth (it has {}).", 2 * shaper, gear.teeth)));
    }
    let degrees = gear.pressure_angle.to_degrees();
    if !(14.5 - 1e-9..=30.0 + 1e-9).contains(&degrees) {
        return Err(refuse("gear_input", format!("The pressure angle must be from 14.5° to 30° (it is {degrees}°).")));
    }
    Ok(())
}

/// One cylinder about the crown axis: tooth space 0's walls where they cross it.
struct CrownRing<'a> {
    shaper: &'a CrownShaper,
    radius: f64,
    /// The roll where the flank reaches the tips.
    u_tip: f64,
    /// Heights above the pitch plane of the tips and the root, and of the pitch plane above z = 0.
    tip: f64,
    root: f64,
    lift: f64,
}

impl<'a> CrownRing<'a> {
    fn new(gear: &CrownGear, shaper: &'a CrownShaper, radius: f64, lift: f64) -> Result<Self, KernelRefusal> {
        let tip = gear.addendum * gear.module;
        let undercut = || refuse("undercut", format!("The crown's teeth are undercut at radius {radius:.4}: raise the inner radius."));
        let height = |u: f64| shaper.on_cylinder(shaper.involute(u), radius).map(|p| p[1]);
        let (Some(h0), Some(h1)) = (height(0.0), height(shaper.uj)) else {
            return Err(undercut());
        };
        // The flank falls from the base circle (u = 0) to the round (u = uj); the tips need it from above them.
        if !(h0 >= tip && h1 < tip) {
            return Err(undercut());
        }
        let (mut lo, mut hi) = (0.0, shaper.uj);
        for _ in 0..200 {
            let mid = 0.5 * (lo + hi);
            match height(mid) {
                Some(h) if h >= tip => lo = mid,
                Some(_) => hi = mid,
                None => return Err(undercut()),
            }
        }
        Ok(Self { shaper, radius, u_tip: 0.5 * (lo + hi), tip, root: shaper.rs - shaper.ra, lift })
    }

    /// The five walls of tooth space 0 as (polar angle, h), in order across the space from the −θ tip to the +θ
    /// tip: L the −θ flank (down), W its fillet, G the root land, V the +θ fillet, R the +θ flank (up).
    fn polar(&self, role: usize, t: f64) -> [f64; 2] {
        let s = self.shaper;
        let at = |p: OutlinePoint| s.on_cylinder(p, self.radius).unwrap_or([f64::NAN, f64::NAN]);
        let fillet = |t: f64| at(s.round(s.psi_land + t * (s.psi_flank - s.psi_land)));
        let flank = |t: f64| at(s.involute(s.uj + t * (self.u_tip - s.uj)));
        let mirror = |p: [f64; 2]| [-p[0], p[1]];
        match role {
            0 => mirror(flank(1.0 - t)),
            1 => mirror(fillet(1.0 - t)),
            // The land, turned about the crown axis by k × its angle: the root land between two radial lines.
            2 => [s.k * s.bc * (2.0 * t - 1.0), self.root],
            3 => fillet(t),
            _ => flank(t),
        }
    }

    fn piece(&self, role: usize, t: f64) -> [f64; 3] {
        let [angle, h] = self.polar(role, t);
        [self.radius * angle.cos(), self.radius * angle.sin(), h + self.lift]
    }

    /// Refuse a ring whose walls do not rise steadily from the root to the tips.
    fn check(&self) -> Result<(), KernelRefusal> {
        for role in [3, 4] {
            let points: Vec<[f64; 2]> = (0..=64).map(|i| self.polar(role, i as f64 / 64.0)).collect();
            if points.iter().any(|p| !p[0].is_finite()) || !points.windows(2).all(|w| w[1][1] > w[0][1]) {
                return Err(refuse("undercut", format!("The crown's tooth space does not rise steadily at radius {:.4}: raise the inner radius.", self.radius)));
            }
        }
        Ok(())
    }
}

/// The crown gear's limits: (undercut limit, pointed-tooth limit). The first is the smallest inner radius at
/// which the shaper's flank reaches the tips from above its base circle and every wall of the tooth space
/// reaches the cylinder (the flank's foot, by the round, the last); the second is the largest outer radius
/// that leaves a tip land of 0.05 × module.
pub fn crown_limits(gear: &CrownGear) -> Result<(f64, f64), KernelRefusal> {
    check_crown_input(gear)?;
    let shaper = CrownShaper::new(gear)?;
    let m = gear.module;
    let tip = gear.addendum * m;
    let r2 = m * gear.teeth as f64 / 2.0;
    let base_free = |r: f64| shaper.on_cylinder(shaper.involute(0.0), r).is_some_and(|p| p[1] >= tip);
    let (mut lo, mut hi) = (shaper.rb / shaper.k * (1.0 + 1e-9), 4.0 * r2);
    if !base_free(hi) {
        return Err(refuse("undercut", "The crown's tips would need the shaper's flank below its base circle at every radius: lower the addendum.".into()));
    }
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        if base_free(mid) { hi = mid } else { lo = mid }
    }
    // Then every wall must reach the cylinder: the flank's foot, by the round, is the last to.
    let walls_reach = |r: f64| base_free(r) && CrownRing::new(gear, &shaper, r, 0.0).and_then(|ring| ring.check()).is_ok();
    if !walls_reach(hi) {
        let step = 0.02 * m;
        let mut found = None;
        let mut r = hi;
        while r < 2.0 * r2 {
            r += step;
            if walls_reach(r) {
                found = Some(r);
                break;
            }
        }
        let Some(good) = found else {
            return Err(refuse("undercut", "The crown's tooth spaces do not reach from the root to the tips at any radius: lower the addendum or raise the pressure angle.".into()));
        };
        let (mut lo, mut top) = (good - step, good);
        for _ in 0..100 {
            let mid = 0.5 * (lo + top);
            if walls_reach(mid) { top = mid } else { lo = mid }
        }
        hi = top;
    }
    // A little inside, so the skin's slopes may look a step past the ring's ends.
    let inner = hi + 2e-3 * m;
    let tau = TAU / gear.teeth as f64;
    let land = |r: f64| -> Result<bool, KernelRefusal> {
        let ring = CrownRing::new(gear, &shaper, r, 0.0)?;
        Ok((tau - 2.0 * ring.polar(4, 1.0)[0]) * r >= CROWN_TIP_LAND * m)
    };
    let (mut lo, mut hi) = (inner, 4.0 * r2);
    if !land(lo)? {
        return Err(refuse("pointed_tip", "The crown's teeth come to a point at the undercut limit: add crown teeth or lower the addendum.".into()));
    }
    if land(hi).unwrap_or(false) {
        return Err(refuse("gear_input", "The crown's teeth never come to a point: check the module and tooth counts.".into()));
    }
    for _ in 0..100 {
        let mid = 0.5 * (lo + hi);
        if land(mid).unwrap_or(false) { lo = mid } else { hi = mid }
    }
    Ok((inner, lo - 2e-3 * m))
}

/// The crown gear's sizes: [pitch radius, inner radius, outer radius, z of the pitch plane, z of the tips,
/// z of the pinion's axis], the radii resolved from the limits where 0.
pub fn crown_sizes(gear: &CrownGear) -> Result<[f64; 6], KernelRefusal> {
    let m = gear.module;
    let (limit_in, limit_out) = crown_limits(gear)?;
    let inner = if gear.inner_radius > 0.0 { gear.inner_radius } else { limit_in };
    let outer = if gear.outer_radius > 0.0 { gear.outer_radius } else { limit_out };
    if inner < limit_in - 1e-9 * m {
        return Err(refuse("undercut", format!("The inner radius ({inner}) is inside the undercut limit {limit_in:.4}: raise it.")));
    }
    if outer > limit_out + 1e-9 * m {
        return Err(refuse("pointed_tip", format!("The outer radius ({outer}) is past the pointed-tooth limit {limit_out:.4}: lower it.")));
    }
    if !(outer > inner + 0.1 * m) {
        return Err(refuse("gear_input", format!("The outer radius ({outer:.4}) must be beyond the inner radius ({inner:.4}).")));
    }
    let pitch = gear.rim + gear.dedendum * m;
    Ok([m * gear.teeth as f64 / 2.0, inner, outer, pitch, pitch + gear.addendum * m, pitch + m * gear.pinion_teeth as f64 / 2.0])
}

const CROWN_ROLES: [&str; 5] = ["L", "W", "G", "V", "R"];

/// Tooth space 0's five walls on one ring, fitted on the shared breaks, junctions shared.
fn crown_walls(ring: &CrownRing, breaks: &[Vec<f64>]) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
    let mut curves: Vec<NurbsCurve> = Vec::with_capacity(5);
    let mut worst = 0.0_f64;
    for (role, role_breaks) in breaks.iter().enumerate() {
        let (curve, error) = fit_on_breaks3(&|t| ring.piece(role, t), role_breaks)?;
        worst = worst.max(error);
        curves.push(curve);
    }
    for index in 0..4 {
        let start = curves[index + 1].control_points[0];
        let last = curves[index].control_points.len() - 1;
        curves[index].control_points[last] = start;
    }
    Ok((curves, worst))
}

/// Tooth space 0's five wall surfaces (u across the wall in role order, v from the inner radius out), skinned
/// through rings until the skin holds its share of [`GEAR_GENERATED_TOLERANCE`] halfway between them.
fn crown_wall_surfaces(gear: &CrownGear, shaper: &CrownShaper, inner: f64, outer: f64, lift: f64) -> Result<Vec<NurbsSurface>, KernelRefusal> {
    let m = gear.module;
    // A tenth of the bound to the section fit, not a quarter: the crown's root and land walls run nearly flat,
    // and a fit error normal to them is what a pinion tooth sweeping by (or a check along the circle) meets
    // magnified many times.
    let tolerance = GEAR_GENERATED_TOLERANCE * CROWN_SECTION_SHARE * m;
    let skin_tolerance = GEAR_GENERATED_TOLERANCE * (1.0 - CROWN_SECTION_SHARE) * m;
    let probe: Vec<CrownRing> = [inner, 0.5 * (inner + outer), outer].iter().map(|&r| CrownRing::new(gear, shaper, r, lift)).collect::<Result<_, _>>()?;
    for ring in &probe {
        ring.check()?;
    }
    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(5);
    for role in 0..5 {
        let mut all: Vec<f64> = Vec::new();
        for ring in &probe {
            all.extend(adaptive_breaks3(&|t| ring.piece(role, t), tolerance)?);
        }
        all.sort_by(f64::total_cmp);
        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
        breaks.push(all);
    }
    let length = outer - inner;
    let mut rings = 4usize;
    loop {
        let step = length / rings as f64;
        let delta = 1e-3 * step.min(m);
        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(rings + 1);
        let mut slopes: Vec<Vec<Vec<[f64; 3]>>> = Vec::with_capacity(rings + 1);
        let mut refit: Option<CrownRing> = None;
        for j in 0..=rings {
            let r = inner + step * j as f64;
            let ring = CrownRing::new(gear, shaper, r, lift)?;
            ring.check()?;
            let (walls, worst) = crown_walls(&ring, &breaks)?;
            if worst > tolerance {
                refit = Some(ring);
                break;
            }
            let lo = crown_walls(&CrownRing::new(gear, shaper, r - delta, lift)?, &breaks)?.0;
            let hi = crown_walls(&CrownRing::new(gear, shaper, r + delta, lift)?, &breaks)?.0;
            let slope: Vec<Vec<[f64; 3]>> = lo
                .iter()
                .zip(&hi)
                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta), (q.z - p.z) / (2.0 * delta)]).collect())
                .collect();
            rows.push(walls);
            slopes.push(slope);
        }
        if let Some(ring) = refit {
            // As the worm wheel: that ring's own breaks where it needs them, else every span halved.
            let fresh = (0..5).map(|role| adaptive_breaks3(&|t| ring.piece(role, t), tolerance)).collect::<Result<Vec<_>, _>>()?;
            if !merge_breaks(&mut breaks, fresh) {
                halve_breaks(&mut breaks);
            }
            continue;
        }
        let mut worst = 0.0_f64;
        for j in 0..rings {
            let r = inner + step * (j as f64 + 0.5);
            let exact = crown_walls(&CrownRing::new(gear, shaper, r, lift)?, &breaks)?.0;
            for role in 0..5 {
                for (k, p) in exact[role].control_points.iter().enumerate() {
                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
                    let z = 0.5 * (p0.z + p1.z) + step * (d0[2] - d1[2]) / 8.0;
                    worst = worst.max(((x - p.x).powi(2) + (y - p.y).powi(2) + (z - p.z).powi(2)).sqrt());
                }
            }
        }
        if worst > skin_tolerance {
            if rings >= 256 {
                return Err(refuse("gear_fit", format!("The crown gear's tooth spaces could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
            }
            rings *= 2;
            continue;
        }
        let h = 1.0 / rings as f64;
        let mut knots_v = vec![0.0; 4];
        for j in 1..rings {
            let v = j as f64 * h;
            knots_v.extend([v, v]);
        }
        knots_v.extend([1.0; 4]);
        let mut surfaces = Vec::with_capacity(5);
        for role in 0..5 {
            let grid: Vec<Vec<Vec4>> = (0..rows[0][role].control_points.len())
                .map(|k| {
                    let mut row = Vec::with_capacity(2 * rings + 2);
                    for j in 0..=rings {
                        let q = rows[j][role].control_points[k];
                        let d = slopes[j][role][k];
                        let along = |s: f64| Vec4::from_point(Vec3::new(q.x + s * length * d[0], q.y + s * length * d[1], q.z + s * length * d[2]), 1.0);
                        if j > 0 {
                            row.push(along(-h / 3.0));
                        }
                        if j == 0 || j == rings {
                            row.push(along(0.0));
                        }
                        if j < rings {
                            row.push(along(h / 3.0));
                        }
                    }
                    row
                })
                .collect();
            surfaces.push(NurbsSurface::new(3, 3, rows[0][role].knots.clone(), knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))?);
        }
        return Ok(surfaces);
    }
}

fn iso_u(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
    let row = if last { surface.control_points.len() - 1 } else { 0 };
    NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), surface.control_points[row].clone()).map_err(|e| refuse("gear_edge", e))
}

fn iso_v(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
    let column = if last { surface.control_points[0].len() - 1 } else { 0 };
    NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[column]).collect()).map_err(|e| refuse("gear_edge", e))
}

fn turned_surface(surface: &NurbsSurface, angle: f64) -> Result<NurbsSurface, KernelRefusal> {
    let (s, c) = angle.sin_cos();
    let grid = surface.control_points.iter().map(|row| row.iter().map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w }).collect()).collect();
    NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))
}

/// Arcs of `radius` about the z axis at height `z` through the given angles, as one curve whose span i (on
/// [i, i + 1]) is the arc from angle i to angle i + 1, and each span alone.
fn joined_arcs(radius: f64, z: f64, angles: &[f64]) -> Result<(NurbsCurve, Vec<NurbsCurve>), KernelRefusal> {
    let mut pieces = Vec::with_capacity(angles.len() - 1);
    for pair in angles.windows(2) {
        pieces.push(crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, pair[0], pair[1]).map_err(|e| refuse("gear_arc", e))?);
    }
    let degree = pieces[0].degree;
    let mut knots: Vec<f64> = Vec::new();
    let mut points: Vec<Vec4> = Vec::new();
    for (index, piece) in pieces.iter().enumerate() {
        let shift = index as f64;
        if index == 0 {
            knots.extend(piece.knots[..piece.knots.len() - 1].iter().map(|k| k + shift));
            points.extend(piece.control_points.iter().copied());
        } else {
            knots.extend(piece.knots[degree + 1..piece.knots.len() - 1].iter().map(|k| k + shift));
            points.extend(piece.control_points[1..].iter().copied());
        }
    }
    knots.push(pieces.len() as f64);
    Ok((NurbsCurve::new(degree, knots, points).map_err(|e| refuse("gear_arc", e))?, pieces))
}

/// A crown gear solid and its data. Faces carry their names: per tooth space n `G<n>` (root land), `V<n>` /
/// `W<n>` (the +θ and −θ fillets), `R<n>` / `L<n>` (the +θ and −θ flanks), `I<n>` and `O<n>` (the inner and
/// outer cylinder from the middle of tooth n − 1 to the middle of tooth n); per tooth n (between spaces n and
/// n + 1) `K<n>` (tip land); and `B` (the back).
pub fn crown_solid(gear: &CrownGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
    let [r2, inner, outer, pitch, tip, _] = crown_sizes(gear)?;
    let shaper = CrownShaper::new(gear)?;
    let walls = crown_wall_surfaces(gear, &shaper, inner, outer, pitch)?;
    let teeth = gear.teeth;
    let tau = TAU / teeth as f64;
    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
    // Per space j: its walls turned by j tau, their corner vertices and edges.
    struct Space {
        walls: Vec<NurbsSurface>,
        inner: [u64; 6],
        outer: [u64; 6],
        /// Edges between walls (and the two tip edges), at u = 0 of wall 0 then u = 1 of each wall.
        across: [u64; 6],
        inner_edges: [u64; 5],
        outer_edges: [u64; 5],
    }
    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
    let mut spaces: Vec<Space> = Vec::with_capacity(teeth);
    for j in 0..teeth {
        let turned: Vec<NurbsSurface> = walls.iter().map(|w| turned_surface(w, tau * j as f64)).collect::<Result<_, _>>()?;
        let mut inner_v = [0u64; 6];
        let mut outer_v = [0u64; 6];
        for k in 0..6 {
            let (wall, row) = if k < 5 { (&turned[k], 0) } else { (&turned[4], turned[4].control_points.len() - 1) };
            let column = &wall.control_points[row];
            inner_v[k] = shell.vertex(point_of(column[0]));
            outer_v[k] = shell.vertex(point_of(*column.last().expect("a row")));
        }
        let mut across = [0u64; 6];
        across[0] = shell.edge(iso_u(&turned[0], false)?, inner_v[0], outer_v[0])?;
        for k in 0..5 {
            across[k + 1] = shell.edge(iso_u(&turned[k], true)?, inner_v[k + 1], outer_v[k + 1])?;
        }
        let mut inner_edges = [0u64; 5];
        let mut outer_edges = [0u64; 5];
        for k in 0..5 {
            inner_edges[k] = shell.edge(iso_v(&turned[k], false)?, inner_v[k], inner_v[k + 1])?;
            outer_edges[k] = shell.edge(iso_v(&turned[k], true)?, outer_v[k], outer_v[k + 1])?;
        }
        spaces.push(Space { walls: turned, inner: inner_v, outer: outer_v, across, inner_edges, outer_edges });
    }
    // The walls' faces: u along the wall, v outwards; the outward side faces into the space (or up from the land).
    for (j, space) in spaces.iter().enumerate() {
        for k in 0..5 {
            let surface = space.walls[k].clone();
            let at = |u: f64, v: f64| surface.evaluate(u, v).map_err(|e| refuse("gear_surface", e));
            let p = at(0.5, 0.5)?;
            let du = at(0.5 + 1e-6, 0.5)?.sub(at(0.5 - 1e-6, 0.5)?);
            let dv = at(0.5, 0.5 + 1e-6)?.sub(at(0.5, 0.5 - 1e-6)?);
            let normal = du.cross(dv);
            let centre = tau * j as f64;
            let off = (p.y.atan2(p.x) - centre + PI).rem_euclid(TAU) - PI;
            let tangential = Vec3::new(-p.y, p.x, 0.0).scale(1.0 / p.x.hypot(p.y));
            let outward = Vec3::new(0.0, 0.0, 1.0).sub(tangential.scale(off.signum()));
            let same_sense = normal.dot(outward) > 0.0;
            let loops = vec![vec![
                (space.inner_edges[k], true, line([0.0, 0.0], [1.0, 0.0])?),
                (space.across[k + 1], true, line([1.0, 0.0], [1.0, 1.0])?),
                (space.outer_edges[k], false, line([0.0, 1.0], [1.0, 1.0])?),
                (space.across[k], false, line([0.0, 0.0], [0.0, 1.0])?),
            ]];
            shell.face(surface, same_sense, loops, format!("{}{j}", CROWN_ROLES[k]))?;
        }
    }
    // Side lines at the middle of every tooth, inner and outer, and the cylinders between them.
    let mut sides = Vec::with_capacity(teeth); // per tooth j: [(bottom, top) inner, (bottom, top) outer] vertices and edges
    for j in 0..teeth {
        let angle = tau * j as f64 + tau / 2.0;
        let mut side = Vec::with_capacity(2);
        for radius in [inner, outer] {
            let (s, c) = angle.sin_cos();
            let bottom = shell.vertex(Vec3::new(radius * c, radius * s, 0.0));
            let top = shell.vertex(Vec3::new(radius * c, radius * s, tip));
            let edge = shell.edge(crate::make_line(Vec3::new(radius * c, radius * s, 0.0), Vec3::new(radius * c, radius * s, tip)).map_err(|e| refuse("gear_edge", e))?, bottom, top)?;
            side.push((bottom, top, edge));
        }
        sides.push(side);
    }
    // Per space j and per radius: the bottom arc edge and the two tip arcs (the tooth before, the tooth after).
    let mut bottoms: [Vec<u64>; 2] = [Vec::new(), Vec::new()];
    let mut tip_arcs: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()];
    for j in 0..teeth {
        let space = &spaces[j];
        let before = &sides[(j + teeth - 1) % teeth];
        let after = &sides[j];
        let base_angle = tau * j as f64 - tau / 2.0;
        for (side, radius) in [inner, outer].into_iter().enumerate() {
            let corners = if side == 0 { space.inner } else { space.outer };
            let point = |id: u64| shell.vertices.iter().find(|v| v.id == id).expect("a vertex").point;
            let unwrap = |p: Vec3| base_angle + (p.y.atan2(p.x) - base_angle).rem_euclid(TAU);
            let angles = [base_angle, unwrap(point(corners[0])), unwrap(point(corners[5])), base_angle + tau];
            let (base, _) = joined_arcs(radius, 0.0, &angles)?;
            let (_, lifted) = joined_arcs(radius, tip, &angles)?;
            let bottom = shell.edge(base.clone(), before[side].0, after[side].0)?;
            let first = shell.edge(lifted[0].clone(), before[side].1, corners[0])?;
            let last = shell.edge(lifted[2].clone(), corners[5], after[side].1)?;
            bottoms[side].push(bottom);
            tip_arcs[side].push((first, last));
            let surface = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, tip)).map_err(|e| refuse("gear_surface", e))?;
            let wall_edges = if side == 0 { space.inner_edges } else { space.outer_edges };
            let mut coedges = vec![
                (bottom, true, line([0.0, 0.0], [3.0, 0.0])?),
                (after[side].2, true, line([3.0, 0.0], [3.0, 1.0])?),
                (last, false, line([2.0, 1.0], [3.0, 1.0])?),
            ];
            for k in (0..5).rev() {
                let curve = shell.curve(wall_edges[k]).clone();
                let pcurve = crate::build_pcurve_on_surface(&surface, &curve).map_err(|e| refuse("gear_pcurve", e))?;
                coedges.push((wall_edges[k], false, pcurve));
            }
            coedges.push((first, false, line([0.0, 1.0], [1.0, 1.0])?));
            coedges.push((before[side].2, false, line([0.0, 0.0], [0.0, 1.0])?));
            // The extrusion's normal points out from the axis: outward for the outer cylinder, inward for the inner.
            shell.face(surface, side == 1, vec![coedges], format!("{}{j}", if side == 0 { "I" } else { "O" }))?;
        }
    }
    // Tip lands: tooth j between space j (its R tip edge) and space j + 1 (its L tip edge).
    let pad = outer * 1.1 + 1.0;
    let x_axis = Vec3::new(1.0, 0.0, 0.0);
    let y_axis = Vec3::new(0.0, 1.0, 0.0);
    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
    for j in 0..teeth {
        let next = (j + 1) % teeth;
        let mut coedges = Vec::with_capacity(6);
        for (edge, forward) in [
            (spaces[j].across[5], true),
            (tip_arcs[1][j].1, true),
            (tip_arcs[1][next].0, true),
            (spaces[next].across[0], false),
            (tip_arcs[0][next].0, false),
            (tip_arcs[0][j].1, false),
        ] {
            let pcurve = on_plane(shell.curve(edge), tip)?;
            coedges.push((edge, forward, pcurve));
        }
        let plane = make_plane(Vec3::new(-pad, -pad, tip), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
        shell.face(plane, true, vec![coedges], format!("K{j}"))?;
    }
    // The back: the outer and inner bottom arcs.
    let mut loops = Vec::with_capacity(2);
    for side in [1, 0] {
        let mut coedges = Vec::with_capacity(teeth);
        for &edge in &bottoms[side] {
            coedges.push((edge, true, on_plane(shell.curve(edge), 0.0)?));
        }
        loops.push(coedges);
    }
    let plane = make_plane(Vec3::new(-pad, -pad, 0.0), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
    shell.face(plane, false, loops, "B".into())?;
    let id = shell.id();
    let shell_id = shell.id();
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id,
        vertices: shell.vertices,
        edges: shell.edges,
        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
        genus: 1,
        kind: crate::BodyKind::Solid,
    };
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("crown gear is not valid: {issues:?}")));
    }
    let data = GearData {
        pitch_diameter: 2.0 * r2,
        base_diameter: 2.0 * r2 * gear.pressure_angle.cos(),
        tip_diameter: 2.0 * outer,
        root_diameter: 2.0 * inner,
        ..GearData::default()
    };
    Ok((solid, data))
}