ferrocad_occt 0.1.5

OCCT geometry backend for FerroCAD: implements the ferrocad_geom GeometryBackend
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
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
//! The OCCT implementation of [`ferrocad_geom::GeometryBackend`].
//!
//! First operations: [`make_box`](OcctBackend::make_box), fuse, cut, fillet and
//! place. Fuse/cut/common build a [`History`] from the sibling bridge's
//! `Modified`/`Generated`/`IsDeleted` for **both** operands and all three element
//! kinds the kernel reports (faces, edges, vertices), using the result's map of
//! the same kind to turn output sub-shapes into positional names. Each relation
//! also carries an [`ElementId`] (operand, kind, 1-based ordinal), so two operands
//! that both report a `Face1` remain distinguishable.
//!
//! Unchanged sub-shapes are deliberately **absent** from `modified`/`generated`:
//! an input that is neither modified, generated, nor deleted simply survives as
//! itself, and the mapper treats an unmapped, non-deleted input that way. (Verified
//! in `spikes/occt-history-rs`.) They are reported separately as `identity`
//! relations, and the result's own incidence graph adds `derived` naming steps, so
//! the reverse map names every result element upstream names.
//!
//! `cut` also reproduces upstream's compound policy
//! (`FCBRepAlgoAPI_BooleanOperation::Build`): a compound tool is flattened and
//! fused before the cut, and a compound base is cut child by child.

use cxx::UniquePtr;
use ferrocad_curves::{
    Arc, ArcOfHyperbola, ArcOfParabola, BezierCurve, Circle, EdgeCurve, Ellipse, EllipticalArc,
    Hyperbola, Line, NurbsCurve, OffsetCurve, Parabola, Vector3,
};
use ferrocad_geom::{
    BsplineSurfaceData, Capabilities, Continuity, ElementId, ElementKind, ElementRef, FailureKind,
    GeomError, GeometryBackend, History, Lineage, MapVersion, MassProperties, OpResult, OperandId,
    PrincipalProperties, Shape, ShapeDistance, SurfaceData, SurfaceSpec, Tessellation,
    TessellationOptions, ToleranceKind, unsupported,
};
use ferrocad_types::{Matrix4, Placement};
use opencascade_sys as ffi;

use std::collections::BTreeSet;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use ffi::top_abs::TopAbs_Orientation;

use crate::surface_ops;
use ffi::top_abs::TopAbs_ShapeEnum;
use ffi::top_tools::TopTools_IndexedMapOfShape;
use ffi::top_tools::TopTools_ListOfShape;
use ffi::topo_ds::{TopoDS, TopoDS_Shape};

use crate::error::OcctError;
use crate::history;
use crate::policy;
use crate::shape::{downcast, erase, find_index_same, new_map, sub_shape_map};
use crate::topology;

type Map = TopTools_IndexedMapOfShape;

/// A geometry kernel backed by OCCT.
#[derive(Debug, Default, Clone, Copy)]
pub struct OcctBackend;

impl OcctBackend {
    pub fn new() -> Self {
        OcctBackend
    }

    /// Name every face, edge and vertex of `shape` positionally.
    ///
    /// This is the element-map rule a *container* applies to itself: upstream's
    /// `TopoShape::makeElementCompound` calls `mapSubElement(shapes, op)`, which
    /// gives every sub-element of the compound a name although no operation
    /// related it to an input. A compound of two boxes therefore reports 52 names
    /// (2 × 26). The relation is an identity one — the name denotes the element it
    /// is — so it adds one reverse-map entry per element and no operand
    /// provenance.
    pub fn name_every_element(&self, shape: &Shape) -> History {
        let mut history = History::default();
        let Ok(occt) = downcast(shape) else {
            return history;
        };
        let guard = occt.borrow();
        let Some(inner) = guard.as_ref() else {
            return history;
        };
        // A default-constructed handle is non-null as a `UniquePtr` but holds a null
        // `TShape`; enumerating it would dereference that.
        if inner.IsNull() {
            return history;
        }
        for (kind, occt_kind) in HISTORY_KINDS {
            let map = sub_shape_map(inner, occt_kind);
            for ordinal in 1..=map.Extent() {
                let element = element_ref(kind, ordinal, map.FindKey(ordinal));
                history.push_identity(element.clone(), element);
            }
        }
        history
    }

    /// The element map a shape carries without an operation history.
    ///
    /// A **compound that holds a body** names its own sub-elements
    /// ([`name_every_element`](OcctBackend::name_every_element)), the mapping
    /// upstream's `makeElementCompound` performs. Every other shape carries none: a
    /// primitive and a single-body result are named by the operation that produced
    /// them, and a compound of lower elements (the wires a slice returns) is an
    /// internal container rather than a result body. When an operation does have a
    /// history, the caller folds that instead of this map.
    pub fn intrinsic_history(&self, shape: &Shape) -> Option<History> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if inner.IsNull() {
            return None;
        }
        if inner.ShapeType() != TopAbs_ShapeEnum::TopAbs_COMPOUND {
            return None;
        }
        let solids = sub_shape_map(inner, TopAbs_ShapeEnum::TopAbs_SOLID);
        if solids.Extent() == 0 {
            return None;
        }
        Some(self.name_every_element(shape))
    }

    /// Drop the dangling internal wires a fused region may carry. A wire other
    /// than the outer boundary that encloses no area is the trace of a cutter
    /// that terminated inside the face, not a hole; removing it leaves the
    /// region with a single clean boundary.
    fn without_dangling_wires(&self, shape: &Shape) -> Shape {
        let Ok(occt) = downcast(shape) else {
            return shape.clone();
        };
        let guard = occt.borrow();
        let Some(inner) = guard.as_ref() else {
            return shape.clone();
        };
        if !is_face(inner) {
            return shape.clone();
        }
        let wires = sub_shape_map(inner, TopAbs_ShapeEnum::TopAbs_WIRE);
        if wires.Extent() <= 1 {
            return shape.clone();
        }
        let Some(outer) = self.outer_wire(shape) else {
            return shape.clone();
        };
        let Ok(outer_occt) = downcast(&outer) else {
            return shape.clone();
        };
        let outer_guard = outer_occt.borrow();
        let Some(outer_inner) = outer_guard.as_ref() else {
            return shape.clone();
        };
        let outer_index = find_index_same(&wires, outer_inner);

        // A wire bounds an area only when it encloses a region on its own; probe
        // each one and count the ones that do not.
        let area = |shape: &Shape| {
            self.mass_properties(shape)
                .map(|mass| mass.area)
                .unwrap_or(0.0)
        };
        let mut dangling = 0;
        for index in 1..=wires.Extent() {
            if index == outer_index {
                continue;
            }
            let wire = erase(wires.FindKey(index));
            let enclosed = {
                let Ok(wire_occt) = downcast(&wire) else {
                    return shape.clone();
                };
                let wire_guard = wire_occt.borrow();
                let Some(wire_inner) = wire_guard.as_ref() else {
                    return shape.clone();
                };
                match crate::shape_ops::split_wire_into_faces(wire_inner).as_ref() {
                    Some(enclosed) => {
                        let faces = sub_shape_map(enclosed, TopAbs_ShapeEnum::TopAbs_FACE);
                        (1..=faces.Extent())
                            .map(|face| area(&erase(faces.FindKey(face))))
                            .sum::<f64>()
                    }
                    None => 0.0,
                }
            };
            if enclosed <= 1e-9 {
                dangling += 1;
            }
        }
        // Real holes must be kept; only a face whose extra wires are all
        // dangling can be rebuilt from its outer boundary alone.
        if dangling == 0 || dangling != wires.Extent() - 1 {
            return shape.clone();
        }
        let Ok(cleaned) = self.make_face(&[outer]) else {
            return shape.clone();
        };
        let cleaned_area = area(&cleaned);
        let original_area = area(shape);
        if cleaned_area > 0.0
            && (cleaned_area - original_area).abs() <= 1e-9 * original_area.max(1.0)
        {
            cleaned
        } else {
            shape.clone()
        }
    }

    /// A B-spline edge from explicit poles, weights, unique knots and
    /// multiplicities (`Part.BSplineCurve.buildFromPolesMultsKnots`).
    ///
    /// The [`GeometryBackend`] seam's `make_bspline_poles` only knows the uniform
    /// clamped/periodic form (its arguments are poles, degree and the periodic
    /// flag), so the general knot vector has no seam entry point. This is the
    /// kernel's own constructor, used by the Part curve binding when the user
    /// supplies knots and multiplicities.
    #[allow(clippy::too_many_arguments)]
    pub fn make_bspline_poles_mults_knots(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
    ) -> Result<Shape, GeomError> {
        let mut coords = Vec::with_capacity(poles.len() * 3);
        for pole in poles {
            coords.extend_from_slice(&[pole.x, pole.y, pole.z]);
        }
        let Some(curve) = crate::curve::build(
            &coords,
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
        ) else {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles_mults_knots",
            }
            .into());
        };
        let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
        let edge = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles_mults_knots",
            }
            .into());
        }
        Ok(edge)
    }

    /// The flattened state of the B-spline with the given poles, weights, knots
    /// and multiplicities, read back from OCCT (see
    /// [`make_bspline_poles_mults_knots`](Self::make_bspline_poles_mults_knots)).
    /// `None` when the arguments do not describe a valid curve.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_state(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
    ) -> Option<crate::curve::BsplineState> {
        let coords = flatten(poles);
        crate::curve::probe(
            &coords,
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
        )
    }

    /// The flattened state of the B-spline interpolating `points`
    /// (`Part.BSplineCurve.interpolate`), read back from OCCT. `None` when the
    /// interpolation fails.
    pub fn bspline_interpolated_state(
        &self,
        points: &[Vector3],
        periodic: bool,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::interpolated(&flatten(points), periodic)
    }

    /// The state of the same curve after `SetPeriodic`/`SetNotPeriodic`. `None`
    /// when the conversion is rejected.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_periodic_state(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        target_periodic: bool,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::set_periodic(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            target_periodic,
        )
    }

    /// `Geom_BSplineCurve::Resolution`: the parameter tolerance equivalent to
    /// `tolerance`. `None` when the curve cannot be built.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_resolution(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        tolerance: f64,
    ) -> Option<f64> {
        let resolution = crate::curve::resolution(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            tolerance,
        );
        resolution
    }

    /// `BSplineCurve.segment(u1, u2)`: the state of the curve restricted to
    /// `[u1, u2]` (`Geom_BSplineCurve::Segment`).
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_segment(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        u1: f64,
        u2: f64,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::segment(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            u1,
            u2,
        )
    }

    /// The point at parameter `u` on the B-spline with the given state
    /// (`BSplineCurve.value(u)`). `None` when the curve cannot be built or the
    /// parameter is outside its domain.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_point(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        u: f64,
    ) -> Option<Vector3> {
        crate::curve::bspline_point(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            u,
        )
    }

    /// A conic converted to a B-spline over `[first, last]`, flattened like
    /// [`bspline_state`](Self::bspline_state). `kind` is 2 for a circle and 3 for
    /// an ellipse; `x_axis` is the direction of parameter 0. With `nurbs` the
    /// exact rational conversion is used (`GeomConic::toNurbs`), otherwise the
    /// approximation of `GeomCurve::toBSpline`. `None` on failure.
    #[allow(clippy::too_many_arguments)]
    pub fn conic_spline_state(
        &self,
        kind: i32,
        center: Vector3,
        normal: Vector3,
        x_axis: Vector3,
        major: f64,
        minor: f64,
        first: f64,
        last: f64,
        nurbs: bool,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::conic_to_spline(kind, center, normal, x_axis, major, minor, first, last, nurbs)
    }

    /// The curve parameter of the closest point to `point`
    /// (`GeomAPI_ProjectPointOnCurve`, `GeometryCurve.parameter`). `None` when
    /// the projection fails.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_parameter(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        point: Vector3,
    ) -> Option<f64> {
        let parameter = crate::curve::parameter(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            point.x,
            point.y,
            point.z,
        );
        parameter
    }

    /// The state of the B-spline with knot `index` reduced to multiplicity `mult`
    /// (`Geom_BSplineCurve::RemoveKnot`). `None` when the removal is rejected.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_remove_knot_state(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        index: i32,
        mult: i32,
        tolerance: f64,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::remove_knot(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            index,
            mult,
            tolerance,
        )
    }

    /// The state of the B-spline approximating `points`
    /// (`GeomAPI_PointsToBSpline`), read back from OCCT. `None` when the
    /// approximation fails.
    pub fn bspline_approximated_state(
        &self,
        points: &[Vector3],
        degree_min: i32,
        degree_max: i32,
        tolerance: f64,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::approximated(&flatten(points), degree_min, degree_max, tolerance)
    }

    /// The state of the B-spline with `u` inserted up to multiplicity `mult`
    /// (`Geom_BSplineCurve::InsertKnot`). `None` when the insertion is rejected.
    #[allow(clippy::too_many_arguments)]
    pub fn bspline_insert_knot_state(
        &self,
        poles: &[Vector3],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        check_rational: bool,
        u: f64,
        mult: i32,
        tolerance: f64,
    ) -> Option<crate::curve::BsplineState> {
        crate::curve::insert_knot(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            u,
            mult,
            tolerance,
        )
    }

    /// The surface normal of `face` at `(u, v)` (`BRepLProp_SLProps` through
    /// upstream's `Part::Tools::getNormal`), with the face orientation applied.
    /// `None` where the normal is not defined.
    pub fn face_normal_at(&self, face: &Shape, u: f64, v: f64) -> Option<Vector3> {
        let occt = downcast(face).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        crate::curve::face_normal(ffi::topo_ds::TopoDS::Face(inner), u, v)
    }

    /// The two unit surface tangents at `(u, v)` (`TangentU`, `TangentV`).
    pub fn face_tangents_at(
        &self,
        face: &Shape,
        u: f64,
        v: f64,
    ) -> Option<(Vector3, Vector3)> {
        let occt = downcast(face).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        let raw = crate::curve::face_tangents(ffi::topo_ds::TopoDS::Face(inner), u, v);
        raw
    }

    /// The two partial derivatives of order `order` (1 or 2) at `(u, v)`.
    pub fn face_derivatives_at(
        &self,
        face: &Shape,
        u: f64,
        v: f64,
        order: i32,
    ) -> Option<(Vector3, Vector3)> {
        let occt = downcast(face).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        crate::curve::face_derivatives(ffi::topo_ds::TopoDS::Face(inner), u, v, order)
    }

    /// The `(min, max)` principal curvatures of a face at `(u, v)`.
    pub fn face_curvature_at(&self, face: &Shape, u: f64, v: f64) -> Option<(f64, f64)> {
        let occt = downcast(face).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        crate::curve::face_curvature(ffi::topo_ds::TopoDS::Face(inner), u, v)
    }

    /// Sample a wire into points (`Wire.discretize`, upstream's
    /// `BRepAdaptor_CompCurve` samplers). The modes are the same as
    /// [`GeometryBackend::edge_discretize`](ferrocad_geom::GeometryBackend::edge_discretize).
    #[allow(clippy::too_many_arguments)]
    pub fn wire_discretize(
        &self,
        wire: &Shape,
        mode: i32,
        value: f64,
        curvature: f64,
        minimum: i32,
        first: f64,
        last: f64,
    ) -> Result<Vec<Vector3>, GeomError> {
        let occt = downcast(wire)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null wire" })?;
        if !is_wire(inner) {
            return Err(OcctError::InvalidInput {
                what: "not a wire",
            }
            .into());
        }
        let points = crate::part_ops::wire_discretize(inner, mode, value, curvature, minimum, first, last);
        if points.is_empty() {
            return Err(OcctError::NotDone {
                operation: "wire_discretize",
            }
            .into());
        }
        Ok(points)
    }

    /// The untrimmed parameter bounds `(u1, u2, v1, v2)` of the surface behind a
    /// face (`Geom_Surface::Bounds`).
    pub fn face_surface_bounds(&self, face: &Shape) -> Option<(f64, f64, f64, f64)> {
        let occt = downcast(face).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        crate::curve::face_surface_bounds(ffi::topo_ds::TopoDS::Face(inner))
    }

    /// The principal normal of an edge's curve at `parameter`.
    pub fn edge_normal_at(&self, edge: &Shape, parameter: f64) -> Option<Vector3> {
        let occt = downcast(edge).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_edge(inner) {
            return None;
        }
        crate::curve::edge_normal(ffi::topo_ds::TopoDS::Edge(inner), parameter)
    }

    /// The derivative of order `order` (1, 2 or 3) of an edge's curve.
    pub fn edge_derivatives_at(
        &self,
        edge: &Shape,
        parameter: f64,
        order: i32,
    ) -> Option<Vector3> {
        let occt = downcast(edge).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_edge(inner) {
            return None;
        }
        crate::curve::edge_derivatives(ffi::topo_ds::TopoDS::Edge(inner), parameter, order)
    }

    /// The curvature of an edge's curve at `parameter`.
    pub fn edge_curvature_at(&self, edge: &Shape, parameter: f64) -> Option<f64> {
        let occt = downcast(edge).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_edge(inner) {
            return None;
        }
        crate::curve::edge_curvature(ffi::topo_ds::TopoDS::Edge(inner), parameter)
    }

    /// The pcurve an edge has on a face, as a B-spline state (see
    /// [`SplineState`](ferrocad_part_py)) whose range is the edge's own.
    pub fn edge_pcurve_state(&self, edge: &Shape, face: &Shape) -> Option<crate::curve::BsplineState> {
        let edge = downcast(edge).ok()?;
        let face = downcast(face).ok()?;
        let edge = edge.borrow();
        let face = face.borrow();
        let state = crate::curve::edge_pcurve(edge.as_ref()?, face.as_ref()?);
        state
    }

    /// A 2-D B-spline lifted onto a surface as an edge: `poles` are `(u, v)`
    /// points, and the 3-D curve is the surface image of the pcurve
    /// (`BRepBuilderAPI_MakeEdge` with the pcurve/surface form).
    #[allow(clippy::too_many_arguments)]
    pub fn make_bspline2d_edge(
        &self,
        poles: &[(f64, f64)],
        weights: &[f64],
        knots: &[f64],
        multiplicities: &[i32],
        degree: i32,
        periodic: bool,
        surface: Option<&SurfaceSpec>,
        face: Option<&Shape>,
        range: Option<(f64, f64)>,
    ) -> Result<Shape, GeomError> {
        let mut coordinates = Vec::with_capacity(poles.len() * 2);
        for (u, v) in poles {
            coordinates.extend_from_slice(&[*u, *v]);
        }
        let owned_face = surface_face(face)?;
        let null_face = ffi::topo_ds::TopoDS_Face_new();
        let face_shape: &TopoDS_Shape = match &owned_face {
            Some(shape) => shape,
            None => ffi::topo_ds::cast_face_to_shape(&null_face),
        };
        let (first, last) = range.unwrap_or((0.0, 0.0));
        let edge = crate::curve::bspline2d_edge(
            &coordinates,
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            surface,
            face_shape,
            first,
            last,
            range.is_some(),
        );
        match edge.as_ref() {
            Some(edge) => Ok(erase(edge)),
            None => Err(OcctError::NotDone {
                operation: "make_bspline2d_edge",
            }
            .into()),
        }
    }

    /// An analytic 2-D curve lifted onto a surface as an edge, upstream's
    /// `Curve2dPy::toShape(surface)` for the non-B-spline forms.
    ///
    /// `planar_edge` is the exact `z = 0` edge the caller already builds for the
    /// same 2-D curve; the kernel turns its curve into the pcurve and builds the
    /// surface image. The B-spline form goes through
    /// [`Self::make_bspline2d_edge`] instead, which carries the control points
    /// across directly.
    pub fn curve2d_on_surface_edge(
        &self,
        planar_edge: &Shape,
        surface: Option<&SurfaceSpec>,
        face: Option<&Shape>,
    ) -> Result<Shape, GeomError> {
        let owned_face = surface_face(face)?;
        let null_face = ffi::topo_ds::TopoDS_Face_new();
        let face_shape: &TopoDS_Shape = match &owned_face {
            Some(shape) => shape,
            None => ffi::topo_ds::cast_face_to_shape(&null_face),
        };
        let edge = downcast(planar_edge)?;
        let guard = edge.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let lifted = crate::curve::curve2d_on_surface(inner, surface, face_shape);
        match lifted.as_ref() {
            Some(shape) => Ok(erase(shape)),
            None => Err(OcctError::NotDone {
                operation: "curve2d_on_surface_edge",
            }
            .into()),
        }
    }

    /// The face triangulations in **double** precision, as flat positions and
    /// per-face triangle indices (upstream's `Shape.tessellate`).
    ///
    /// [`GeometryBackend::tessellate`] narrows to `f32` for the viewport; the
    /// Python API promises `Base.Vector` precision, so it reads the same
    /// `Poly_Triangulation` nodes here without narrowing.
    pub fn tessellate_points(
        &self,
        shape: &Shape,
        options: &TessellationOptions,
    ) -> Result<(Vec<[f64; 3]>, Vec<u32>), GeomError> {
        crate::topology::tessellate_points(shape, options)
    }

    /// Assemble `faces` into one shell with `BRep_Builder`, without judging or
    /// repairing it.
    fn assemble_shell(&self, faces: &[Shape]) -> Result<Shape, GeomError> {
        if faces.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "a shell needs at least one face",
            }
            .into());
        }
        let mut shell = ffi::topo_ds::TopoDS_Shell_new();
        let builder = ffi::b_rep::BRep_Builder_new();
        let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
        builder.MakeShell(shell.pin_mut());
        let mut shell = ffi::topo_ds::TopoDS_Shell_as_shape(shell);
        for face in faces {
            let occt = downcast(face)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null face" })?;
            if !is_face(inner) {
                return Err(OcctError::InvalidInput {
                    what: "a shell is made of faces",
                }
                .into());
            }
            builder.Add(shell.pin_mut(), inner);
        }
        Ok(erase(&shell))
    }
}

/// The owned surface face handed to the 2-D lifting bridges: `None` when the
/// caller passes an elementary surface spec instead.
fn surface_face(face: Option<&Shape>) -> Result<Option<UniquePtr<TopoDS_Shape>>, GeomError> {
    match face {
        Some(face) => {
            let occt = downcast(face)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null face" })?;
            Ok(Some(ffi::topo_ds::TopoDS_Shape_to_owned(inner)))
        }
        None => Ok(None),
    }
}

/// The `Vector3` in three leading components, or `None` when the kernel
/// reported nothing.
fn three(values: &[f64]) -> Option<Vector3> {
    (values.len() >= 3).then(|| Vector3::new(values[0], values[1], values[2]))
}

fn is_edge(shape: &TopoDS_Shape) -> bool {
    !shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_EDGE
}

fn is_wire(shape: &TopoDS_Shape) -> bool {
    !shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_WIRE
}

fn is_vertex(shape: &TopoDS_Shape) -> bool {
    !shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_VERTEX
}

fn is_face(shape: &TopoDS_Shape) -> bool {
    !shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_FACE
}

fn is_shell(shape: &TopoDS_Shape) -> bool {
    !shape.IsNull() && shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_SHELL
}

impl GeometryBackend for OcctBackend {
    fn make_box(&self, length: f64, width: f64, height: f64) -> Result<Shape, GeomError> {
        let origin = ffi::gp::new_point(0.0, 0.0, 0.0);
        let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeBox_new(&origin, length, width, height);
        let shape = erase(make.pin_mut().Shape());
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_box",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_cylinder(
        &self,
        radius: f64,
        height: f64,
        base: Vector3,
        direction: Vector3,
    ) -> Result<Shape, GeomError> {
        let axis = axis_from(base, direction)?;
        let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeCylinder_new(&axis, radius, height);
        let shape = erase(make.pin_mut().Shape());
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_cylinder",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_sphere(&self, radius: f64, center: Vector3) -> Result<Shape, GeomError> {
        let origin = point(center);
        let direction = ffi::gp::gp_Dir_new(0.0, 0.0, 1.0);
        let axis = ffi::gp::gp_Ax2_new(&origin, &direction);
        let mut make =
            ffi::b_rep_prim_api::BRepPrimAPI_MakeSphere_new(&axis, radius, std::f64::consts::TAU);
        let shape = erase(make.pin_mut().Shape());
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_sphere",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_cone(
        &self,
        radius1: f64,
        radius2: f64,
        height: f64,
        base: Vector3,
        direction: Vector3,
    ) -> Result<Shape, GeomError> {
        let axis = axis_from(base, direction)?;
        let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeCone_new(
            &axis,
            radius1,
            radius2,
            height,
            std::f64::consts::TAU,
        );
        let shape = erase(make.pin_mut().Shape());
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_cone",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_edge(&self, curve: &EdgeCurve) -> Result<Shape, GeomError> {
        match curve {
            EdgeCurve::LineSegment(segment) => {
                let start = point(segment.start());
                let end = point(segment.end());
                let mut make =
                    ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_gp_Pnt_gp_Pnt(&start, &end);
                if !make.IsDone() {
                    return Err(OcctError::NotDone {
                        operation: "make_edge",
                    }
                    .into());
                }
                Ok(erase(ffi::topo_ds::cast_edge_to_shape(
                    make.pin_mut().Edge(),
                )))
            }
            EdgeCurve::Circle(circle) => edge_from_circle(circle),
            EdgeCurve::Arc(arc) => {
                if arc.is_closed() {
                    // A full turn is a circle; `GC_MakeArcOfCircle` needs three
                    // distinct points, and the mid point would coincide.
                    return edge_from_circle(&arc.circle());
                }
                let start = point(arc.start());
                let middle = point(arc.point_at(arc.first() + arc.sweep() / 2.0));
                let end = point(arc.end());
                let arc_maker =
                    ffi::gc::GC_MakeArcOfCircle_point_point_point(&start, &middle, &end);
                let trimmed = ffi::gc::GC_MakeArcOfCircle_Value(&*arc_maker);
                if trimmed.is_null() {
                    return Err(OcctError::NotDone {
                        operation: "make_edge (arc)",
                    }
                    .into());
                }
                let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_TrimmedCurve(&*trimmed);
                let mut make =
                    ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&*curve);
                if !make.IsDone() {
                    return Err(OcctError::NotDone {
                        operation: "make_edge (arc)",
                    }
                    .into());
                }
                Ok(erase(ffi::topo_ds::cast_edge_to_shape(
                    make.pin_mut().Edge(),
                )))
            }
            EdgeCurve::Line(_) => Err(unsupported("make_edge for an infinite line")),
            EdgeCurve::Ellipse(ellipse) => edge_from_ellipse(ellipse),
            EdgeCurve::EllipticalArc(arc) => {
                let ellipse = arc.ellipse();
                edge_from_conic(
                    3,
                    &ellipse,
                    arc.first(),
                    arc.last(),
                    "make_edge (elliptical arc)",
                )
            }
            EdgeCurve::Hyperbola(_) => Err(unsupported("make_edge for an unbounded hyperbola")),
            EdgeCurve::ArcOfHyperbola(arc) => {
                let hyperbola = arc.hyperbola();
                edge_from_conic(
                    4,
                    &hyperbola,
                    arc.first(),
                    arc.last(),
                    "make_edge (arc of hyperbola)",
                )
            }
            EdgeCurve::Parabola(_) => Err(unsupported("make_edge for an unbounded parabola")),
            EdgeCurve::ArcOfParabola(arc) => {
                let parabola = arc.parabola();
                edge_from_conic(
                    5,
                    &parabola,
                    arc.first(),
                    arc.last(),
                    "make_edge (arc of parabola)",
                )
            }
            EdgeCurve::BezierCurve(curve) => edge_from_bezier(curve),
            EdgeCurve::BSplineCurve(curve) => edge_from_nurbs(curve),
            EdgeCurve::OffsetCurve(curve) => {
                let basis = self.make_edge(curve.basis())?;
                let basis_occt = downcast(&basis)?;
                let basis_guard = basis_occt.borrow();
                let basis_inner = basis_guard
                    .as_ref()
                    .ok_or(OcctError::InvalidInput { what: "null basis edge" })?;
                let direction = curve.direction();
                let edge = (|| {
                    if !is_edge(basis_inner) {
                        return None;
                    }
                    let mut bf = 0.0;
                    let mut bl = 0.0;
                    let base = ffi::b_rep::BRep_Tool_Curve(
                        ffi::topo_ds::TopoDS::Edge(basis_inner),
                        &mut bf,
                        &mut bl,
                    );
                    if base.IsNull() {
                        return None;
                    }
                    let dir = ffi::gp::gp_Dir_new(direction.x, direction.y, direction.z);
                    let offset = ffi::geom::Geom_OffsetCurve_new(&base, curve.offset(), &dir).ok()?;
                    let offset = ffi::geom::new_HandleGeomCurve_from_HandleGeom_OffsetCurve(&offset);
                    let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_CurveRange(
                        &offset,
                        curve.first(),
                        curve.last(),
                    )
                    .ok()?;
                    if !make.IsDone() {
                        return None;
                    }
                    Some(ffi::topo_ds::TopoDS_Shape_to_owned(
                        ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()),
                    ))
                })();
                let Some(edge) = edge else {
                    return Err(OcctError::NotDone {
                        operation: "make_edge (offset curve)",
                    }
                    .into());
                };
                Ok(erase(&edge))
            }
        }
    }

    fn make_wire(&self, edges: &[Shape]) -> Result<Shape, GeomError> {
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeWire_new();
        for edge in edges {
            let occt = downcast(edge)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null edge" })?;
            if !is_edge(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_wire expects edges",
                }
                .into());
            }
            make.pin_mut().add_edge(ffi::topo_ds::TopoDS::Edge(inner));
        }
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_wire",
            }
            .into());
        }
        Ok(erase(ffi::topo_ds::cast_wire_to_shape(
            make.pin_mut().Wire(),
        )))
    }

    fn make_vertex(&self, at: Vector3) -> Result<Shape, GeomError> {
        let pnt = point(at);
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeVertex_gp_Pnt(&pnt);
        Ok(erase(ffi::topo_ds::cast_vertex_to_shape(
            make.pin_mut().Vertex(),
        )))
    }

    fn vertex_point(&self, shape: &Shape) -> Option<Vector3> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_vertex(inner) {
            return None;
        }
        let pnt = ffi::b_rep::BRep_Tool_Pnt(ffi::topo_ds::TopoDS::Vertex(inner));
        Some(Vector3::new(pnt.X(), pnt.Y(), pnt.Z()))
    }

    fn make_bspline_edge(&self, points: &[Vector3], periodic: bool) -> Result<Shape, GeomError> {
        if points.len() < 2 {
            return Err(OcctError::InvalidInput {
                what: "a B-spline needs at least two points",
            }
            .into());
        }
        let mut array = ffi::t_col_gp::TColgp_HArray1OfPnt_new(1, points.len() as i32);
        for (index, value) in points.iter().enumerate() {
            let value = point(*value);
            array.pin_mut().SetValue(index as i32 + 1, &value);
        }
        let array = ffi::t_col_gp::new_HandleTColgpHArray1OfPnt_from_TColgpHArray1OfPnt(array);
        let mut interpolate = ffi::geom_api::GeomAPI_Interpolate_new(&array, periodic, 1e-7);
        interpolate.pin_mut().Perform();
        let curve = ffi::geom_api::GeomAPI_Interpolate_Curve(&interpolate);
        let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
        let shape = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_bspline_edge",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_bspline_poles(
        &self,
        poles: &[Vector3],
        degree: i32,
        periodic: bool,
    ) -> Result<Shape, GeomError> {
        if poles.len() < 2 {
            return Err(OcctError::InvalidInput {
                what: "a B-spline needs at least two poles",
            }
            .into());
        }
        let mut coords = Vec::with_capacity(poles.len() * 3);
        for pole in poles {
            coords.extend_from_slice(&[pole.x, pole.y, pole.z]);
        }
        let curve = crate::curve::bspline_from_poles(&coords, degree, periodic);
        let Some(curve) = curve else {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles",
            }
            .into());
        };
        let curve = ffi::geom::new_HandleGeomCurve_from_HandleGeom_BSplineCurve(&curve);
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_HandleGeomCurve(&curve);
        let shape = erase(ffi::topo_ds::cast_edge_to_shape(make.pin_mut().Edge()));
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles",
            }
            .into());
        }
        Ok(shape)
    }

    fn add_wire_to_face(&self, face: &Shape, wire: &Shape) -> Result<Shape, GeomError> {
        let face_occt = downcast(face)?;
        let face_guard = face_occt.borrow();
        let face_inner = face_guard.as_ref().ok_or(OcctError::InvalidInput {
            what: "null face",
        })?;
        let wire_occt = downcast(wire)?;
        let wire_guard = wire_occt.borrow();
        let wire_inner = wire_guard.as_ref().ok_or(OcctError::InvalidInput {
            what: "null wire",
        })?;
        // Upstream's `BRep_Builder::Add(face, wire)`: no reversal, no containment
        // test. A caller that adds a hole reverses its wire itself.
        let added = crate::policy::face_add_wire(face_inner, wire_inner).map_err(GeomError::from)?;
        Ok(erase(&added))
    }

    fn make_face(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
        let (first, rest) = wires.split_first().ok_or(OcctError::InvalidInput {
            what: "a face needs a wire",
        })?;
        let first_occt = downcast(first)?;
        let first_guard = first_occt.borrow();
        let first_inner = first_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null wire" })?;
        if !is_wire(first_inner) {
            return Err(OcctError::InvalidInput {
                what: "make_face expects wires",
            }
            .into());
        }
        // Upstream's `BRepBuilderAPI_MakeFace(wire)`: the surface is found from
        // the wire itself, so a wire that lies on a cylinder or a sphere still
        // bounds a face. See `fc_face_from_wire` for the tolerance retry.
        let outer = crate::policy::face_from_wire(first_inner).map_err(GeomError::from)?;
        if outer.is_null() {
            return Err(OcctError::NotDone {
                operation: "make_face",
            }
            .into());
        }
        let mut face = outer;
        for wire in rest {
            let occt = downcast(wire)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null wire" })?;
            if !is_wire(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_face expects wires",
                }
                .into());
            }
            // A hole must run opposite to the outer boundary; reverse it so the
            // boundary subtracts its area instead of adding another one.
            let reversed = ffi::topo_ds::Reversed(inner);
            let Some(reversed) = reversed.as_ref() else {
                return Err(OcctError::InvalidInput { what: "null wire" }.into());
            };
            let Some(source) = face.as_ref() else {
                return Err(OcctError::InvalidInput { what: "null face" }.into());
            };
            let next = crate::policy::face_add_wire(source, reversed).map_err(GeomError::from)?;
            if next.is_null() {
                return Err(OcctError::NotDone {
                    operation: "make_face",
                }
                .into());
            }
            face = next;
        }
        Ok(erase(&face))
    }

    fn make_faces(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
        let mut faces = Vec::with_capacity(wires.len());
        let mut splitters = Vec::new();
        let mut all_planar = true;
        for wire in wires {
            let occt = downcast(wire)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null wire" })?;
            if !is_wire(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_faces expects wires",
                }
                .into());
            }

            // A self-intersecting boundary splits into several loops (one face
            // per loop); a simple boundary stays on the ordinary path below.
            let split = crate::shape_ops::split_wire_into_faces(inner);
            if let Some(split) = split.as_ref() {
                let map = sub_shape_map(split, TopAbs_ShapeEnum::TopAbs_FACE);
                if map.Extent() > 1 {
                    for index in 1..=map.Extent() {
                        faces.push(erase(map.FindKey(index)));
                    }
                    continue;
                }
            }

            let make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeFace_wire(
                ffi::topo_ds::TopoDS::Wire(inner),
                true,
            );
            if make.IsDone() {
                faces.push(erase(ffi::topo_ds::cast_face_to_shape(make.Face())));
                continue;
            }
            // A boundary lying on an existing surface (for example a cylinder's
            // lateral wire) can still build a face when the builder is allowed
            // to find that surface.
            let make_any = ffi::b_rep_builder_api::BRepBuilderAPI_MakeFace_wire(
                ffi::topo_ds::TopoDS::Wire(inner),
                false,
            );
            if make_any.IsDone() {
                faces.push(erase(ffi::topo_ds::cast_face_to_shape(make_any.Face())));
                continue;
            }

            let mut list = ffi::top_tools::new_list_of_shape();
            let _ = list.pin_mut().Append(inner);
            let filled = crate::shape_ops::fill_wires(&list);
            let Some(filled) = filled.as_ref() else {
                // An open boundary cannot bound a face; it still subdivides the
                // faces around it (dangling ends are pruned by the boolean).
                splitters.push(wire.clone());
                continue;
            };
            let filled = erase(filled);
            // `BRepFill_Filling` can also "succeed" on an open boundary, but only
            // with a degenerate face. Such a wire is a cutter, not a boundary.
            let filled_area = self
                .mass_properties(&filled)
                .map(|mass| mass.area)
                .unwrap_or(0.0);
            if filled_area <= 1e-9 {
                splitters.push(wire.clone());
                continue;
            }
            all_planar = false;
            faces.push(filled);
        }

        if !splitters.is_empty() {
            if faces.is_empty() {
                return Err(OcctError::InvalidInput {
                    what: "an open wire cannot form a face",
                }
                .into());
            }
            let mut list = ffi::top_tools::new_list_of_shape();
            for shape in faces.iter().chain(splitters.iter()) {
                let occt = downcast(shape)?;
                let guard = occt.borrow();
                if let Some(inner) = guard.as_ref() {
                    let _ = list.pin_mut().Append(inner);
                }
            }
            let fused = crate::shape_ops::general_fuse(&list, 0.0);
            if let Some(fused) = fused.as_ref() {
                let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
                let mut regions = Vec::with_capacity(map.Extent() as usize);
                for index in 1..=map.Extent() {
                    let region = erase(map.FindKey(index));
                    // General Fuse keeps the degenerate slivers and the dangling
                    // cutters as regions of their own; neither bounds an area.
                    let area = self
                        .mass_properties(&region)
                        .map(|mass| mass.area)
                        .unwrap_or(0.0);
                    if area <= 1e-9 {
                        continue;
                    }
                    regions.push(self.without_dangling_wires(&region));
                }
                if !regions.is_empty() {
                    return if regions.len() == 1 {
                        Ok(regions.remove(0))
                    } else {
                        self.make_compound(&regions)
                    };
                }
            }
            return Err(OcctError::NotDone {
                operation: "make_faces",
            }
            .into());
        }

        // Coplanar faces that overlap or cross must be split into their regions;
        // General Fuse returns all parts, unlike a boolean union. Nested boundaries
        // are different: upstream keeps them as one face with holes.
        if all_planar && faces.len() > 1 {
            let area = |shape: &Shape| {
                self.mass_properties(shape)
                    .map(|mass| mass.area)
                    .unwrap_or(0.0)
            };
            let contains = |outer: &Shape, inner: &Shape| {
                let inner_area = area(inner);
                if inner_area <= 0.0 {
                    return false;
                }
                match self.common(outer, inner, 0.0) {
                    Ok(result) => {
                        let overlap = area(&result.shape);
                        (overlap - inner_area).abs() <= 1e-6 * inner_area.max(1.0)
                    }
                    Err(_) => false,
                }
            };
            // Nesting follows the even-odd rule: the outermost boundary is a face,
            // its direct children are holes, their children are islands, and so on.
            let count = faces.len();
            let mut parent: Vec<Option<usize>> = vec![None; count];
            for inner in 0..count {
                for outer in 0..count {
                    if inner == outer || !contains(&faces[outer], &faces[inner]) {
                        continue;
                    }
                    let smaller = parent[inner]
                        .map(|current| area(&faces[outer]) < area(&faces[current]))
                        .unwrap_or(true);
                    if smaller {
                        parent[inner] = Some(outer);
                    }
                }
            }
            if parent.iter().any(Option::is_some) {
                let depth = |mut index: usize| {
                    let mut depth = 0;
                    while let Some(up) = parent[index] {
                        depth += 1;
                        index = up;
                        if depth > count {
                            break;
                        }
                    }
                    depth
                };
                let even: Vec<usize> = (0..count).filter(|index| depth(*index) % 2 == 0).collect();
                let odd: Vec<usize> = (0..count).filter(|index| depth(*index) % 2 == 1).collect();
                let intersection_area = |a: &Shape, b: &Shape| match self.common(a, b, 0.0) {
                    Ok(result) => area(&result.shape),
                    Err(_) => 0.0,
                };

                // Positive faces that partially overlap must be unioned first; the
                // hole regions are then removed from the split result.
                let mut partial_overlap = false;
                'pairs: for (position, &a) in even.iter().enumerate() {
                    for &b in &even[position + 1..] {
                        let overlap = intersection_area(&faces[a], &faces[b]);
                        let smaller = area(&faces[a]).min(area(&faces[b]));
                        if overlap > 1e-9 && smaller - overlap > 1e-9 {
                            partial_overlap = true;
                            break 'pairs;
                        }
                    }
                }
                if !odd.is_empty() && partial_overlap {
                    // Include the hole boundaries too: General Fuse must split on
                    // them so there is a region inside each hole to discard.
                    let mut list = ffi::top_tools::new_list_of_shape();
                    for face in &faces {
                        let occt = downcast(face)?;
                        let guard = occt.borrow();
                        if let Some(inner) = guard.as_ref() {
                            let _ = list.pin_mut().Append(inner);
                        }
                    }
                    let fused = crate::shape_ops::general_fuse(&list, 0.0);
                    if let Some(fused) = fused.as_ref() {
                        let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
                        let mut kept = Vec::new();
                        for index in 1..=map.Extent() {
                            let region = erase(map.FindKey(index));
                            let inside_hole =
                                odd.iter().any(|&hole| contains(&faces[hole], &region));
                            if !inside_hole {
                                kept.push(region);
                            }
                        }
                        if !kept.is_empty() {
                            return if kept.len() == 1 {
                                Ok(kept.remove(0))
                            } else {
                                self.make_compound(&kept)
                            };
                        }
                    }
                }

                let mut built = Vec::new();
                for node in 0..count {
                    if depth(node) % 2 != 0 {
                        continue;
                    }
                    let mut boundaries = vec![wires[node].clone()];
                    let mut holes: Vec<(f64, Shape)> = (0..count)
                        .filter(|&child| parent[child] == Some(node))
                        .map(|child| (area(&faces[child]), wires[child].clone()))
                        .collect();
                    holes
                        .sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
                    boundaries.extend(holes.into_iter().map(|(_, wire)| wire));
                    if let Ok(face) = self.make_face(&boundaries) {
                        built.push(face);
                    }
                }
                if !built.is_empty() {
                    return if built.len() == 1 {
                        Ok(built.remove(0))
                    } else {
                        self.make_compound(&built)
                    };
                }
            }

            let mut list = ffi::top_tools::new_list_of_shape();
            for face in &faces {
                let occt = downcast(face)?;
                let guard = occt.borrow();
                if let Some(inner) = guard.as_ref() {
                    let _ = list.pin_mut().Append(inner);
                }
            }
            let fused = crate::shape_ops::general_fuse(&list, 0.0);
            if let Some(fused) = fused.as_ref() {
                let map = sub_shape_map(fused, TopAbs_ShapeEnum::TopAbs_FACE);
                let mut regions = Vec::with_capacity(map.Extent() as usize);
                for index in 1..=map.Extent() {
                    regions.push(erase(map.FindKey(index)));
                }
                if regions.len() > 1 {
                    return self.make_compound(&regions);
                }
            }
        }
        match faces.len() {
            0 => Err(OcctError::InvalidInput {
                what: "a face needs a wire",
            }
            .into()),
            1 => Ok(faces.remove(0)),
            _ => self.make_compound(&faces),
        }
    }

    fn make_face_on_surface(
        &self,
        surface: &SurfaceSpec,
        wires: &[Shape],
    ) -> Result<Shape, GeomError> {
        if wires.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "a face needs a wire",
            }
            .into());
        }
        let mut list = ffi::top_tools::new_list_of_shape();
        for wire in wires {
            let occt = downcast(wire)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null wire" })?;
            if !is_wire(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_face_on_surface expects wires",
                }
                .into());
            }
            let _ = list.pin_mut().Append(inner);
        }
        let face = crate::policy::make_face_on_surface(surface, &list).map_err(GeomError::from)?;
        match face.as_ref() {
            Some(face) => Ok(erase(face)),
            None => Err(OcctError::NotDone {
                operation: "make_face_on_surface",
            }
            .into()),
        }
    }

    fn make_face_on_band(
        &self,
        surface: &SurfaceSpec,
        u1: f64,
        u2: f64,
        v1: f64,
        v2: f64,
    ) -> Result<Shape, GeomError> {
        let face = crate::policy::face_on_surface_band(surface, u1, u2, v1, v2)
            .map_err(GeomError::from)?;
        Ok(erase(&face))
    }

    fn surface_type(&self, shape: &Shape) -> Option<String> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        let surface = ffi::b_rep::BRep_Tool_Surface(ffi::topo_ds::TopoDS::Face(inner));
        let name = ffi::standard::type_name(ffi::geom::DynamicType(surface.as_ref()?));
        Some(
            match name.as_str() {
                "Geom_Plane" => "Part::GeomPlane",
                "Geom_CylindricalSurface" => "Part::GeomCylinder",
                "Geom_ConicalSurface" => "Part::GeomCone",
                "Geom_SphericalSurface" => "Part::GeomSphere",
                "Geom_ToroidalSurface" => "Part::GeomToroid",
                "Geom_BSplineSurface" => "Part::GeomBSplineSurface",
                _ => "Part::GeomSurface",
            }
            .to_string(),
        )
    }

    fn surface_data(&self, shape: &Shape) -> Option<SurfaceData> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        match crate::surface_frame::of(ffi::topo_ds::TopoDS::Face(inner)) {
            Some(frame) => Some(frame.into_surface_data()),
            None => self
                .surface_type(shape)
                .map(|type_id| SurfaceData::Other { type_id }),
        }
    }

    fn sew(&self, shape: &Shape, tolerance: f64) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let sewn = crate::part_ops::sew_shape(inner, tolerance).map_err(GeomError::from)?;
        match sewn.as_ref() {
            Some(sewn) => Ok(erase(sewn)),
            None => Err(OcctError::NotDone { operation: "sew" }.into()),
        }
    }

    fn connect_edges_to_wires(
        &self,
        shape: &Shape,
        shared: bool,
        tolerance: f64,
    ) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let wires = crate::policy::connect_edges_to_wires(inner, shared, tolerance)?;
        Ok(erase(&wires))
    }

    fn to_nurbs(&self, shape: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let converted = crate::part_ops::to_nurbs(inner).map_err(GeomError::from)?;
        match converted.as_ref() {
            Some(converted) => Ok(erase(converted)),
            None => Err(OcctError::NotDone {
                operation: "to_nurbs",
            }
            .into()),
        }
    }

    fn sub_shapes_of_type(&self, shape: &Shape, kind: &str) -> Vec<Shape> {
        let Ok(occt) = downcast(shape) else {
            return Vec::new();
        };
        let guard = occt.borrow();
        let Some(inner) = guard.as_ref() else {
            return Vec::new();
        };
        let shape_type = match kind {
            "Compound" => TopAbs_ShapeEnum::TopAbs_COMPOUND,
            "CompSolid" => TopAbs_ShapeEnum::TopAbs_COMPSOLID,
            _ => return Vec::new(),
        };
        let Some(compound) = crate::part_ops::shape_sub_shapes_of_type(inner, shape_type)
            .as_ref()
            .map(erase)
        else {
            return Vec::new();
        };
        // `fc_shape_sub_shapes_of_type` wraps the map in a compound so it can
        // cross the bridge; its direct children are the sub-shapes themselves.
        let compound_occt = match downcast(&compound) {
            Ok(occt) => occt,
            Err(_) => return Vec::new(),
        };
        let compound_guard = compound_occt.borrow();
        let Some(compound_inner) = compound_guard.as_ref() else {
            return Vec::new();
        };
        history::children(compound_inner)
            .iter()
            .filter_map(|child| child.as_ref().map(erase))
            .collect()
    }

    fn children(&self, shape: &Shape) -> Vec<Shape> {
        let Ok(occt) = downcast(shape) else {
            return Vec::new();
        };
        let guard = occt.borrow();
        let Some(inner) = guard.as_ref() else {
            return Vec::new();
        };
        history::children(inner)
            .iter()
            .filter_map(|child| child.as_ref().map(erase))
            .collect()
    }

    fn outer_wire(&self, shape: &Shape) -> Option<Shape> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !is_face(inner) {
            return None;
        }
        let wire = ffi::b_rep_tools::outer_wire(ffi::topo_ds::TopoDS::Face(inner));
        Some(erase(ffi::topo_ds::cast_wire_to_shape(wire.as_ref()?)))
    }

    fn curve_of(&self, shape: &Shape) -> Result<EdgeCurve, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        crate::curve::edge_curve(inner)
    }

    fn fuse(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
        boolean(a, b, CutOperation::Fuse, tolerance)
    }

    fn cut(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
        boolean(a, b, CutOperation::Cut, tolerance)
    }

    fn fillet(
        &self,
        shape: &Shape,
        edges: &[ElementRef],
        radius: f64,
    ) -> Result<OpResult, GeomError> {
        topology::fillet(shape, edges, radius)
    }

    fn common(&self, a: &Shape, b: &Shape, tolerance: f64) -> Result<OpResult, GeomError> {
        boolean(a, b, CutOperation::Common, tolerance)
    }

    fn make_compound(&self, shapes: &[Shape]) -> Result<Shape, GeomError> {
        if shapes.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "a compound needs at least one shape",
            }
            .into());
        }
        let mut compound = ffi::topo_ds::TopoDS_Compound_new();
        let builder = ffi::b_rep::BRep_Builder_new();
        let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
        builder.MakeCompound(compound.pin_mut());

        // `TopoDS_Builder::Add(S, C)` takes the container first and the child
        // second; the cxx binding keeps that order (`shape` is the compound).
        let mut compound = ffi::topo_ds::TopoDS_Compound_as_shape(compound);
        for shape in shapes {
            let occt = downcast(shape)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            builder.Add(compound.pin_mut(), inner);
        }
        Ok(erase(&compound))
    }

    fn make_comp_solid(&self, solids: &[Shape]) -> Result<Shape, GeomError> {
        if solids.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "a comp-solid needs at least one solid",
            }
            .into());
        }
        let mut list = ffi::top_tools::new_list_of_shape();
        for solid in solids {
            let occt = downcast(solid)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null solid" })?;
            let _ = list.pin_mut().Append(inner);
        }
        let composed = crate::shape_ops::comp_solid(&list);
        let Some(composed) = composed.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_comp_solid",
            }
            .into());
        };
        Ok(erase(composed))
    }

    fn make_solid(&self, shell: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shell)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shell" })?;
        if !is_shell(inner) {
            return Err(OcctError::InvalidInput {
                what: "make_solid expects a shell",
            }
            .into());
        }
        let mut make =
            ffi::b_rep_builder_api::BRepBuilderAPI_MakeSolid_new(ffi::topo_ds::TopoDS::Shell(inner));
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_solid",
            }
            .into());
        }
        // Upstream's `makeElementSolid` orients the solid after adding its shells.
        let mut solid = ffi::topo_ds::TopoDS_Solid_to_owned(make.pin_mut().Solid());
        ffi::b_rep_lib::BRepLib::OrientClosedSolid(solid.pin_mut());
        Ok(erase(ffi::topo_ds::cast_solid_to_shape(&solid)))
    }

    fn make_shell(&self, faces: &[Shape]) -> Result<Shape, GeomError> {
        let shell = self.assemble_shell(faces)?;
        // Upstream's `makeElementBoolean(OpCodes::Shell)` re-sews the assembly
        // when the naive `BRep_Builder` shell is not a valid shell. Independently
        // built faces (a mesh's triangles, a set of planar regions) only share
        // geometry, not topology, so without this they never form a closed
        // shell.
        if self.is_valid(&shell) {
            return Ok(shell);
        }
        let occt = downcast(&shell)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shell" })?;
        match crate::part_ops::sew_shell(inner).ok().as_ref() {
            Some(sewn) => Ok(erase(sewn)),
            None => Ok(shell),
        }
    }

    fn make_shell_from_wires(&self, wires: &[Shape]) -> Result<Shape, GeomError> {
        if wires.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "a shell needs at least one wire",
            }
            .into());
        }
        let mut faces = Vec::with_capacity(wires.len());
        for wire in wires {
            // Each wire bounds one planar face; upstream's wires are the
            // boundaries of a box's faces.
            faces.push(self.make_face(std::slice::from_ref(wire))?);
        }
        // No sewing here: this entry point assembles the faces it just made, and
        // upstream's `makeElementShellFromWires` does not run the shell sewing
        // `Part.makeShell` falls back to.
        self.assemble_shell(&faces)
    }

    fn make_loft(&self, wires: &[Shape], solid: bool) -> Result<Shape, GeomError> {
        if wires.len() < 2 {
            return Err(OcctError::InvalidInput {
                what: "a loft needs at least two sections",
            }
            .into());
        }
        let mut make = ffi::b_rep_offset_api::BRepOffsetAPI_ThruSections_new(solid);
        for wire in wires {
            let occt = downcast(wire)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null wire" })?;
            if !is_wire(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_loft expects wires",
                }
                .into());
            }
            make.pin_mut().AddWire(ffi::topo_ds::TopoDS::Wire(inner));
        }
        // Upstream keeps the wires in the order given rather than letting OCCT
        // reorder them to match a common origin.
        make.pin_mut().CheckCompatibility(false);
        let progress = ffi::message::Message_ProgressRange_new();
        make.pin_mut().Build(&progress);
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_loft",
            }
            .into());
        }
        Ok(erase(make.pin_mut().Shape()))
    }

    fn make_ruled_surface(&self, first: &Shape, second: &Shape) -> Result<Shape, GeomError> {
        let first_occt = downcast(first)?;
        let second_occt = downcast(second)?;
        let first_guard = first_occt.borrow();
        let second_guard = second_occt.borrow();
        let a = first_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let b = second_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let face = crate::shape_ops::ruled_surface(a, b);
        let Some(face) = face.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_ruled_surface",
            }
            .into());
        };
        Ok(erase(face))
    }

    fn make_pipe(
        &self,
        spine: &Shape,
        profile: &Shape,
        tolerance: f64,
    ) -> Result<Shape, GeomError> {
        let spine_occt = downcast(spine)?;
        let spine_guard = spine_occt.borrow();
        let spine_inner = spine_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null spine" })?;
        let profile_occt = downcast(profile)?;
        let profile_guard = profile_occt.borrow();
        let profile_inner = profile_guard.as_ref().ok_or(OcctError::InvalidInput {
            what: "null profile",
        })?;
        let piped = crate::shape_ops::pipe(spine_inner, profile_inner, tolerance);
        let Some(piped) = piped.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_pipe",
            }
            .into());
        };
        Ok(erase(piped))
    }

    fn intrinsic_lineage(&self, shape: &Shape) -> Result<Lineage, GeomError> {
        // A container that holds a body keeps the map `intrinsic_history` already
        // describes; a shell, solid, loft or filled face names every result
        // element, which is the map the factory attaches upstream. Callers decide
        // where the count is known to match.
        let history = self
            .intrinsic_history(shape)
            .unwrap_or_else(|| self.name_every_element(shape));
        Ok(Lineage::from_history(&history, MapVersion::default()))
    }

    fn make_filled_face(&self, edges: &[Shape]) -> Result<Shape, GeomError> {
        let wire = self.make_wire(edges)?;
        let mut list = ffi::top_tools::new_list_of_shape();
        {
            let occt = downcast(&wire)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null wire" })?;
            list.pin_mut().Append(inner);
        }
        let face = crate::shape_ops::fill_wires(&list);
        let Some(face) = face.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_filled_face",
            }
            .into());
        };
        Ok(erase(face))
    }

    fn extrude(&self, shape: &Shape, vector: Vector3) -> Result<Shape, GeomError> {
        if vector.length() <= 0.0 || !vector.length().is_finite() {
            return Err(OcctError::InvalidInput {
                what: "extrusion needs a non-zero vector",
            }
            .into());
        }
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let direction = ffi::gp::new_vec(vector.x, vector.y, vector.z);
        let mut make =
            ffi::b_rep_prim_api::BRepPrimAPI_MakePrism_new(inner, &direction, true, true);
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "extrude",
            }
            .into());
        }
        Ok(erase(make.pin_mut().Shape()))
    }

    fn line_direction(&self, edge: &Shape) -> Option<Vector3> {
        surface_ops::edge_line_direction(edge).ok()
    }

    fn planar_normal(&self, shape: &Shape) -> Option<Vector3> {
        surface_ops::shape_plane_normal(shape).ok()
    }

    fn revolve(
        &self,
        shape: &Shape,
        center: Vector3,
        axis: Vector3,
        angle: f64,
    ) -> Result<Shape, GeomError> {
        if axis.length() <= 0.0 || !axis.length().is_finite() {
            return Err(OcctError::InvalidInput {
                what: "revolving needs a non-zero axis",
            }
            .into());
        }
        if !angle.is_finite() {
            return Err(OcctError::InvalidInput {
                what: "revolving needs a finite angle",
            }
            .into());
        }
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let origin = point(center);
        let direction = ffi::gp::gp_Dir_new(axis.x, axis.y, axis.z);
        let axis = ffi::gp::gp_Ax1_new(&origin, &direction);
        let mut make = ffi::b_rep_prim_api::BRepPrimAPI_MakeRevol_new(inner, &axis, angle, true);
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "revolve",
            }
            .into());
        }
        Ok(erase(make.pin_mut().Shape()))
    }

    fn bounds(&self, shape: &Shape) -> Option<(Vector3, Vector3)> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        let mut bnd = ffi::bnd::Bnd_Box_new();
        ffi::b_rep_bnd_lib::BRepBndLib::Add(inner, bnd.pin_mut(), false);
        if bnd.IsVoid() {
            return None;
        }
        // Drop the protective gap so the box is the tight one upstream reports.
        bnd.pin_mut().SetGap(0.0);
        let (mut xmin, mut ymin, mut zmin) = (0.0, 0.0, 0.0);
        let (mut xmax, mut ymax, mut zmax) = (0.0, 0.0, 0.0);
        bnd.Get(
            &mut xmin, &mut ymin, &mut zmin, &mut xmax, &mut ymax, &mut zmax,
        );
        Some((
            Vector3::new(xmin, ymin, zmin),
            Vector3::new(xmax, ymax, zmax),
        ))
    }

    fn mass_properties(&self, shape: &Shape) -> Option<MassProperties> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;

        let mut linear = ffi::g_prop::GProps_new();
        ffi::b_rep_g_prop::BRepGProp::LinearProperties(inner, linear.pin_mut(), false, false);
        let length = linear.Mass();

        let mut surface = ffi::g_prop::GProps_new();
        ffi::b_rep_g_prop::BRepGProp::SurfaceProperties(inner, surface.pin_mut(), false, false);
        let area = surface.Mass();

        let mut volume = ffi::g_prop::GProps_new();
        ffi::b_rep_g_prop::BRepGProp::VolumeProperties(
            inner,
            volume.pin_mut(),
            false,
            false,
            false,
        );
        let centre = ffi::g_prop::GProp_GProps_CentreOfMass(&volume);
        Some(MassProperties {
            length,
            area,
            volume: volume.Mass(),
            center_of_mass: Vector3::new(centre.X(), centre.Y(), centre.Z()),
        })
    }

    fn center_of_mass(&self, shape: &Shape) -> Option<Vector3> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        // Upstream's `getShapeProperties` rule: the property regime follows what
        // the shape contains, so a compound of faces measures its surface instead
        // of a zero-mass volume (whose centre is the origin).
        crate::shape_ops::center_of_mass(inner)
    }

    fn is_valid(&self, shape: &Shape) -> bool {
        let Ok(occt) = downcast(shape) else {
            return false;
        };
        let guard = occt.borrow();
        match guard.as_ref() {
            Some(inner) => crate::shape_ops::is_valid(inner),
            None => false,
        }
    }

    fn inertia_matrix(&self, shape: &Shape) -> Option<Matrix4> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        let values = crate::shape_ops::inertia_matrix(inner)?;
        let mut matrix = Matrix4::identity();
        for row in 0..3 {
            for column in 0..3 {
                matrix.m[row * 4 + column] = values[row * 3 + column];
            }
        }
        Some(matrix)
    }

    fn principal_properties(&self, shape: &Shape) -> Option<PrincipalProperties> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        let values = crate::shape_ops::principal_properties(inner)?;
        Some(PrincipalProperties {
            symmetry_axis: values.symmetry_axis,
            symmetry_point: values.symmetry_point,
            moments: (values.moments[0], values.moments[1], values.moments[2]),
            axes: (values.axes[0], values.axes[1], values.axes[2]),
            radius_of_gyration: (
                values.radius_of_gyration[0],
                values.radius_of_gyration[1],
                values.radius_of_gyration[2],
            ),
        })
    }

    fn clean(&self, shape: &Shape) -> Option<Shape> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        let mut op = ffi::shape_upgrade::UnifySameDomain_new(inner, true, true, false);
        op.pin_mut().build();
        Some(erase(op.shape()))
    }

    fn refine(&self, shape: &Shape) -> Option<OpResult> {
        let cleaned = self.clean(shape)?;
        let before = downcast(shape).ok()?.borrow();
        let after = downcast(&cleaned).ok()?.borrow();
        let history = refine_history(before.as_ref()?, after.as_ref()?);
        Some(OpResult::new(cleaned, history))
    }

    fn shape_type(&self, shape: &Shape) -> Option<&'static str> {
        crate::part_ops::shape_kind(shape)
    }

    fn project(&self, shape: &Shape, tools: &[Shape]) -> Result<Shape, GeomError> {
        // Upstream's `Shape.project` is a *normal* projection
        // (`BRepAlgo_NormalProjection`), not a parallel one: it lays each tool on
        // the target along the target's own normals, which is what wrapping a
        // sketch onto a curved face needs.
        if tools.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "project needs at least one tool shape",
            }
            .into());
        }
        let target = downcast(shape)?;
        let guard = target.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let mut list = ffi::top_tools::new_list_of_shape();
        for tool in tools {
            let occt = downcast(tool)?;
            let tool_guard = occt.borrow();
            let piece = tool_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            list.pin_mut().Append(piece);
        }
        let projected = crate::part_ops::project_normal(inner, &list).map_err(GeomError::from)?;
        match projected.as_ref() {
            Some(projected) => Ok(erase(projected)),
            None => Err(OcctError::NotDone {
                operation: "project",
            }
            .into()),
        }
    }

    fn make_offset(&self, shape: &Shape, distance: f64, join: i32) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let offset = crate::shape_ops::offset(inner, distance, join);
        let Some(offset) = offset.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_offset",
            }
            .into());
        };
        Ok(erase(offset))
    }

    fn make_thickness(
        &self,
        shape: &Shape,
        closing_faces: &[Shape],
        thickness: f64,
        tolerance: f64,
    ) -> Result<Shape, GeomError> {
        if !thickness.is_finite() || thickness == 0.0 {
            return Err(OcctError::InvalidInput {
                what: "make_thickness needs a non-zero thickness",
            }
            .into());
        }
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let mut list = ffi::top_tools::new_list_of_shape();
        for face in closing_faces {
            let face_occt = downcast(face)?;
            let face_guard = face_occt.borrow();
            let face_inner = face_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null face" })?;
            let _ = list.pin_mut().Append(face_inner);
        }
        let thickened = crate::shape_ops::thick_solid(inner, &list, thickness, tolerance);
        let Some(thickened) = thickened.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_thickness",
            }
            .into());
        };
        Ok(erase(thickened))
    }

    fn section(&self, a: &Shape, b: &Shape) -> Result<Shape, GeomError> {
        let a_occt = downcast(a)?;
        let b_occt = downcast(b)?;
        let a_guard = a_occt.borrow();
        let b_guard = b_occt.borrow();
        let sa = a_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let sb = b_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let section = crate::shape_ops::section(sa, sb);
        let Some(section) = section.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "section",
            }
            .into());
        };
        Ok(erase(section))
    }

    fn slice(
        &self,
        shape: &Shape,
        direction: Vector3,
        distance: f64,
    ) -> Result<Vec<Shape>, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let sliced = crate::shape_ops::slice(inner, direction.x, direction.y, direction.z, distance);
        let Some(sliced) = sliced.as_ref() else {
            return Err(OcctError::NotDone { operation: "slice" }.into());
        };
        let wires = sub_shape_map(sliced, TopAbs_ShapeEnum::TopAbs_WIRE);
        Ok((1..=wires.Extent())
            .map(|index| erase(wires.FindKey(index)))
            .collect())
    }

    fn general_fuse(
        &self,
        shapes: &[Shape],
        tolerance: f64,
    ) -> Result<(Shape, Vec<Vec<Shape>>), GeomError> {
        if shapes.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "general fuse needs at least one shape",
            }
            .into());
        }
        let tolerance = if tolerance.is_finite() && tolerance > 0.0 {
            tolerance
        } else {
            0.0
        };
        let mut list = ffi::top_tools::new_list_of_shape();
        for shape in shapes {
            let occt = downcast(shape)?;
            let guard = occt.borrow();
            let inner = guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            let _ = list.pin_mut().Append(inner);
        }
        let Some((fused, parts)) = crate::shape_ops::general_fuse_parts(&list, tolerance) else {
            return Err(OcctError::NotDone {
                operation: "general_fuse",
            }
            .into());
        };
        let Some(fused) = fused.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "general_fuse",
            }
            .into());
        };
        // `parts` is one entry per input, in input order: the split pieces of the
        // inputs the fuse touched, and nothing for the ones it left alone.
        let split = parts
            .iter()
            .map(|part| {
                part.as_ref()
                    .and_then(|part| part.as_ref())
                    .map(top_level_parts)
                    .unwrap_or_default()
            })
            .collect();
        Ok((erase(fused), split))
    }

    fn split_shape(
        &self,
        shape: &Shape,
        tools: &[(Shape, Shape)],
        check_interior: bool,
    ) -> Result<(Vec<Shape>, Vec<Shape>), GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;

        let mut cutters = ffi::top_tools::new_list_of_shape();
        let mut faces = ffi::top_tools::new_list_of_shape();
        for (cutter, face) in tools {
            let cutter_occt = downcast(cutter)?;
            let cutter_guard = cutter_occt.borrow();
            let cutter_inner = cutter_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null tool" })?;
            let face_occt = downcast(face)?;
            let face_guard = face_occt.borrow();
            let face_inner = face_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null face" })?;
            let _ = cutters.pin_mut().Append(cutter_inner);
            let _ = faces.pin_mut().Append(face_inner);
        }

        let mut direct = ffi::top_tools::new_list_of_shape();
        let mut left = ffi::top_tools::new_list_of_shape();
        if !crate::shape_ops::split_shape(
            inner,
            &cutters,
            &faces,
            check_interior,
            direct.pin_mut(),
            left.pin_mut(),
        ) {
            return Err(OcctError::NotDone {
                operation: "split_shape",
            }
            .into());
        }
        Ok((collect_list(&direct), collect_list(&left)))
    }

    fn optimal_bounds(
        &self,
        shape: &Shape,
        use_triangulation: bool,
        use_tolerance: bool,
    ) -> Option<(Vector3, Vector3)> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        crate::shape_ops::optimal_box(inner, use_triangulation, use_tolerance)
    }

    fn same_shape(&self, a: &Shape, b: &Shape) -> bool {
        let (Ok(a_occt), Ok(b_occt)) = (downcast(a), downcast(b)) else {
            return a.is_same(b);
        };
        let a_guard = a_occt.borrow();
        let b_guard = b_occt.borrow();
        match (a_guard.as_ref(), b_guard.as_ref()) {
            (Some(a_inner), Some(b_inner)) => a_inner.IsSame(b_inner),
            _ => a.is_same(b),
        }
    }

    fn element_kind(&self, shape: &Shape) -> Option<ElementKind> {
        match crate::part_ops::shape_kind(shape)? {
            "Solid" => Some(ElementKind::Solid),
            "Shell" => Some(ElementKind::Shell),
            "Face" => Some(ElementKind::Face),
            "Wire" => Some(ElementKind::Wire),
            "Edge" => Some(ElementKind::Edge),
            "Vertex" => Some(ElementKind::Vertex),
            _ => None,
        }
    }

    fn count_sub_shapes(&self, shape: &Shape, kind: &str) -> Result<usize, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        if inner.IsNull() {
            return Ok(0);
        }
        // Upstream's `countSubShapes("SubShape")` counts the direct children, not
        // every descendant; every other spelling counts that sub-shape kind.
        if kind == "SubShape" {
            let mut count = 0;
            let mut iterator = ffi::topo_ds::TopoDS_Iterator_new(inner);
            while iterator.More() {
                count += 1;
                iterator.pin_mut().Next();
            }
            return Ok(count.max(0) as usize);
        }
        let Some(occt_kind) = count_kind(kind) else {
            return Ok(0);
        };
        Ok(sub_shape_map(inner, occt_kind).Extent() as usize)
    }

    fn is_degenerate(&self, edge: &Shape) -> Result<bool, GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        Ok(ffi::b_rep::BRep_Tool::Degenerated(TopoDS::Edge(inner)))
    }

    fn is_seam(&self, edge: &Shape, face: &Shape) -> Result<bool, GeomError> {
        let edge_occt = downcast(edge)?;
        let face_occt = downcast(face)?;
        let edge_guard = edge_occt.borrow();
        let face_guard = face_occt.borrow();
        let edge_inner = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let face_inner = face_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null face" })?;
        if !is_edge(edge_inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        if !is_face(face_inner) {
            return Err(OcctError::InvalidInput { what: "not a face" }.into());
        }
        Ok(ffi::b_rep::BRep_Tool_IsClosed_edge_face(
            TopoDS::Edge(edge_inner),
            TopoDS::Face(face_inner),
        ))
    }

    fn edge_parameter_range(&self, edge: &Shape) -> Result<(f64, f64), GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        let (mut first, mut last) = (0.0, 0.0);
        ffi::b_rep::BRep_Tool::Range(TopoDS::Edge(inner), &mut first, &mut last);
        Ok((first, last))
    }

    fn face_parameter_range(&self, face: &Shape) -> Result<(f64, f64, f64, f64), GeomError> {
        let occt = downcast(face)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null face" })?;
        if !is_face(inner) {
            return Err(OcctError::InvalidInput { what: "not a face" }.into());
        }
        let (mut u0, mut u1, mut v0, mut v1) = (0.0, 0.0, 0.0, 0.0);
        ffi::b_rep_tools::BRepTools::UVBounds(
            TopoDS::Face(inner),
            &mut u0,
            &mut u1,
            &mut v0,
            &mut v1,
        );
        Ok((u0, u1, v0, v1))
    }

    fn dist_to_shape(&self, first: &Shape, second: &Shape) -> Result<ShapeDistance, GeomError> {
        let first_occt = downcast(first)?;
        let second_occt = downcast(second)?;
        let first_guard = first_occt.borrow();
        let second_guard = second_occt.borrow();
        let first_inner = first_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let second_inner = second_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let dist = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_new(first_inner, second_inner);
        if !dist.IsDone() || dist.NbSolution() < 1 {
            return Err(OcctError::NotDone {
                operation: "dist_to_shape",
            }
            .into());
        }
        let p1 = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_point_on_shape1(&dist, 1);
        let p2 = ffi::b_rep_extrema::BRepExtrema_DistShapeShape_point_on_shape2(&dist, 1);
        Ok(ShapeDistance {
            distance: dist.Value(),
            first: Vector3::new(p1.X(), p1.Y(), p1.Z()),
            second: Vector3::new(p2.X(), p2.Y(), p2.Z()),
        })
    }

    fn is_closed(&self, shape: &Shape) -> Result<bool, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        Ok(policy::is_closed(inner))
    }

    fn shape_tolerance(&self, shape: &Shape) -> Result<f64, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        Ok(policy::shape_tolerance(inner))
    }

    fn is_inside(
        &self,
        shape: &Shape,
        point: Vector3,
        tolerance: f64,
        check_face: bool,
    ) -> Result<bool, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        policy::is_inside(inner, point, tolerance, check_face).map_err(GeomError::from)
    }

    fn is_partner(&self, first: &Shape, second: &Shape) -> Result<bool, GeomError> {
        let first_occt = downcast(first)?;
        let second_occt = downcast(second)?;
        let first_guard = first_occt.borrow();
        let second_guard = second_occt.borrow();
        match (first_guard.as_ref(), second_guard.as_ref()) {
            (Some(a), Some(b)) => Ok(a.IsPartner(b)),
            _ => Ok(false),
        }
    }

    fn complement(&self, shape: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let complemented = policy::complement(inner)?;
        Ok(erase(&complemented))
    }

    fn transform_geometry(
        &self,
        shape: &Shape,
        matrix: &Matrix4,
        copy: bool,
    ) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let m = &matrix.m;
        if m[12].abs() > 1e-12
            || m[13].abs() > 1e-12
            || m[14].abs() > 1e-12
            || (m[15] - 1.0).abs() > 1e-12
        {
            return Err(OcctError::InvalidInput {
                what: "matrix is not affine",
            }
            .into());
        }
        let result = policy::transform_geometry(inner, m, copy)?;
        Ok(erase(&result))
    }

    fn global_tolerance(&self, shape: &Shape, mode: i32) -> Result<f64, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        policy::global_tolerance(inner, mode).map_err(GeomError::from)
    }

    fn fix_tolerance(
        &self,
        shape: &Shape,
        value: f64,
        kind: ToleranceKind,
    ) -> Result<(), GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        policy::fix_tolerance(inner, value, tolerance_shape_type(kind)).map_err(GeomError::from)
    }

    fn limit_tolerance(
        &self,
        shape: &Shape,
        minimum: f64,
        maximum: f64,
        kind: ToleranceKind,
    ) -> Result<bool, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        policy::limit_tolerance(inner, minimum, maximum, tolerance_shape_type(kind))
            .map_err(GeomError::from)
    }

    fn tolerance_in(
        &self,
        shape: &Shape,
        minimum: f64,
        maximum: f64,
        kind: ToleranceKind,
    ) -> Result<Vec<Shape>, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let list = policy::tolerance_in(inner, minimum, maximum, tolerance_shape_type(kind))?;
        Ok(list_shapes(&list))
    }

    fn tolerance_over(
        &self,
        shape: &Shape,
        value: f64,
        kind: ToleranceKind,
    ) -> Result<Vec<Shape>, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let list = policy::tolerance_over(inner, value, tolerance_shape_type(kind))?;
        Ok(list_shapes(&list))
    }

    fn make_wires(
        &self,
        shape: &Shape,
        _op: &str,
        tolerance: f64,
    ) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let wires = policy::make_wires(inner, tolerance)?;
        Ok(erase(&wires))
    }

    fn remove_internal_wires(
        &self,
        shape: &Shape,
        minimum_area: f64,
    ) -> Result<(Shape, bool), GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let (result, performed) = policy::remove_internal_wires(inner, minimum_area)?;
        Ok((erase(&result), performed))
    }

    fn stl_bytes(&self, shape: &Shape, deflection: f64) -> Result<Vec<u8>, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        if !deflection.is_finite() || deflection <= 0.0 {
            return Err(OcctError::InvalidInput {
                what: "the deflection is a positive number",
            }
            .into());
        }
        let bytes = crate::stl::mesh(inner, deflection)?.encode_binary();
        if bytes.is_empty() {
            return Err(OcctError::NotDone {
                operation: "stl_bytes",
            }
            .into());
        }
        Ok(bytes)
    }

    fn edge_value_at(&self, edge: &Shape, t: f64) -> Result<Vector3, GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        let curve = ffi::b_rep_adaptor::BRepAdaptor_Curve_new(TopoDS::Edge(inner));
        let point = ffi::b_rep_adaptor::BRepAdaptor_Curve_value(&curve, t);
        Ok(Vector3::new(point.X(), point.Y(), point.Z()))
    }

    fn face_value_at(&self, face: &Shape, u: f64, v: f64) -> Result<Vector3, GeomError> {
        let occt = downcast(face)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null face" })?;
        if !is_face(inner) {
            return Err(OcctError::InvalidInput { what: "not a face" }.into());
        }
        let surface = ffi::b_rep_adaptor::BRepAdaptor_Surface_new(TopoDS::Face(inner));
        let point = ffi::b_rep_adaptor::BRepAdaptor_Surface_value(&surface, u, v);
        Ok(Vector3::new(point.X(), point.Y(), point.Z()))
    }

    fn edge_discretize(
        &self,
        edge: &Shape,
        mode: i32,
        value: f64,
        curvature: f64,
        minimum: i32,
        first: f64,
        last: f64,
    ) -> Result<Vec<Vector3>, GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        let points = crate::part_ops::edge_discretize(inner, mode, value, curvature, minimum, first, last);
        if points.is_empty() {
            return Err(OcctError::NotDone {
                operation: "edge_discretize",
            }
            .into());
        }
        Ok(points)
    }

    fn edge_parameter_by_length(
        &self,
        edge: &Shape,
        length: f64,
        tolerance: f64,
    ) -> Result<f64, GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "not an edge",
            }
            .into());
        }
        let parameter = crate::part_ops::edge_parameter_by_length(inner, length, tolerance);
        if !parameter.is_finite() {
            return Err(OcctError::InvalidInput {
                what: "value out of range",
            }
            .into());
        }
        Ok(parameter)
    }

    fn shell_free_edges(&self, shell: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shell)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shell" })?;
        let free = crate::part_ops::shell_free_edges(inner).map_err(GeomError::from)?;
        match free.as_ref() {
            Some(free) => Ok(erase(free)),
            None => Err(OcctError::NotDone {
                operation: "shell_free_edges",
            }
            .into()),
        }
    }

    fn bspline_surface_interpolate(
        &self,
        rows: &[Vec<Vector3>],
    ) -> Result<BsplineSurfaceData, GeomError> {
        crate::part_ops::bspline_surface_interpolate(rows)
    }

    fn bspline_surface_face(&self, rows: &[Vec<Vector3>]) -> Result<Shape, GeomError> {
        let face = crate::part_ops::bspline_surface_face_from_points(rows)?;
        let Some(face) = face.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "bspline_surface_face",
            }
            .into());
        };
        Ok(erase(face))
    }

    fn is_equal(&self, a: &Shape, b: &Shape) -> Result<bool, GeomError> {
        let a_occt = downcast(a)?;
        let b_occt = downcast(b)?;
        let a_guard = a_occt.borrow();
        let b_guard = b_occt.borrow();
        match (a_guard.as_ref(), b_guard.as_ref()) {
            (Some(a_inner), Some(b_inner)) => Ok(a_inner.IsEqual(b_inner)),
            _ => Ok(false),
        }
    }

    fn copy_shape(&self, shape: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        if inner.IsNull() {
            return Err(OcctError::InvalidInput { what: "null shape" }.into());
        }
        let mut copier = ffi::b_rep_builder_api::BRepBuilderAPI_Copy_new(inner, true, false);
        if !copier.IsDone() {
            return Err(OcctError::NotDone {
                operation: "copy_shape",
            }
            .into());
        }
        Ok(erase(copier.pin_mut().Shape()))
    }

    fn shape_hash(&self, shape: &Shape) -> Result<u64, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        if inner.IsNull() {
            return Ok(0);
        }
        // Same TShape pointer and location as the old `fc_shape_hash`, but the
        // pointer is re-hashed with a deterministic hasher before the boost
        // combine. Only `IsSame => same hash` matters, so the exact value is not
        // asserted anywhere.
        let ptr = ffi::topo_ds::TopoDS_Shape_t_shape_ptr(inner);
        let mut hasher = DefaultHasher::new();
        ptr.hash(&mut hasher);
        let mut hash = hasher.finish();
        let location = inner.Location().HashCode() as u64;
        hash ^= location
            .wrapping_add(0x9e3779b97f4a7c15u64)
            .wrapping_add(hash.wrapping_shl(6))
            .wrapping_add(hash.wrapping_shr(2));
        Ok(hash)
    }

    fn orientation(&self, shape: &Shape) -> Option<&'static str> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        Some(match inner.Orientation() {
            TopAbs_Orientation::TopAbs_REVERSED => "Reversed",
            TopAbs_Orientation::TopAbs_INTERNAL => "Internal",
            TopAbs_Orientation::TopAbs_EXTERNAL => "External",
            TopAbs_Orientation::TopAbs_FORWARD => "Forward",
            _ => "Forward",
        })
    }

    fn reversed(&self, shape: &Shape) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let reversed = ffi::topo_ds::Reversed(inner);
        let Some(reversed) = reversed.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "reversed",
            }
            .into());
        };
        Ok(erase(reversed))
    }

    fn with_orientation(&self, shape: &Shape, orientation: &str) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let value = match orientation {
            "Forward" => 0,
            "Reversed" => 1,
            "Internal" => 2,
            "External" => 3,
            _ => {
                return Err(OcctError::InvalidInput {
                    what: "an orientation is Forward, Reversed, Internal or External",
                }
                .into());
            }
        };
        let oriented = crate::part_ops::with_orientation(inner, value);
        let Some(oriented) = oriented.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "with_orientation",
            }
            .into());
        };
        Ok(erase(oriented))
    }

    fn remove_shapes(&self, shape: &Shape, shapes: &[Shape]) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let mut list = ffi::top_tools::new_list_of_shape();
        for removal in shapes {
            let removal_occt = downcast(removal)?;
            let removal_guard = removal_occt.borrow();
            let removal_inner = removal_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            let _ = list.pin_mut().Append(removal_inner);
        }
        let result = crate::shape_ops::reshape_remove(inner, &list);
        let Some(result) = result.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "remove_shapes",
            }
            .into());
        };
        Ok(erase(result))
    }

    fn split_edge(&self, edge: &Shape, parameters: &[f64]) -> Result<Shape, GeomError> {
        let occt = downcast(edge)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if !is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "split_edge needs an edge",
            }
            .into());
        }
        let split = crate::shape_ops::split_edge(inner, parameters);
        let Some(split) = split.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "split_edge",
            }
            .into());
        };
        Ok(erase(split))
    }

    fn replace_shapes(
        &self,
        shape: &Shape,
        replacements: &[(Shape, Shape)],
    ) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let mut from = ffi::top_tools::new_list_of_shape();
        let mut to = ffi::top_tools::new_list_of_shape();
        for (old, new) in replacements {
            let old_occt = downcast(old)?;
            let old_guard = old_occt.borrow();
            let old_inner = old_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            let new_occt = downcast(new)?;
            let new_guard = new_occt.borrow();
            let new_inner = new_guard
                .as_ref()
                .ok_or(OcctError::InvalidInput { what: "null shape" })?;
            let _ = from.pin_mut().Append(old_inner);
            let _ = to.pin_mut().Append(new_inner);
        }
        let result = crate::shape_ops::reshape_replace(inner, &from, &to);
        let Some(result) = result.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "replace_shapes",
            }
            .into());
        };
        Ok(erase(result))
    }

    fn static_moments(&self, shape: &Shape) -> Option<[f64; 3]> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        let mut props = ffi::g_prop::GProps_new();
        ffi::b_rep_g_prop::BRepGProp::VolumeProperties(inner, props.pin_mut(), false, false, false);
        let (mut lx, mut ly, mut lz) = (0.0, 0.0, 0.0);
        props.StaticMoments(&mut lx, &mut ly, &mut lz);
        Some([lx, ly, lz])
    }

    fn place(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
        let shape_occt = downcast(shape)?;
        let shape_guard = shape_occt.borrow();
        let s = shape_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let trsf = transform_from(placement);
        let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(s, &trsf, true);
        let out = erase(op.pin_mut().Shape());
        if !op.IsDone() {
            return Err(OcctError::NotDone { operation: "place" }.into());
        }
        Ok(out)
    }

    /// A placement write: `copy = false` attaches a `TopLoc_Location` to the shape
    /// instead of rebuilding every face, edge and vertex. OCCT reads the location through
    /// every query (tessellation especially - `topology.rs` applies it per face), so the
    /// result is the same shape at a different place, and the move costs one transform
    /// rather than a copy of the whole body.
    fn moved(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
        let shape_occt = downcast(shape)?;
        let shape_guard = shape_occt.borrow();
        let s = shape_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let trsf = transform_from(placement);
        let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(s, &trsf, false);
        let out = erase(op.pin_mut().Shape());
        if !op.IsDone() {
            return Err(OcctError::NotDone { operation: "moved" }.into());
        }
        Ok(out)
    }

    fn relocate(&self, shape: &Shape, placement: &Placement) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        // A location already on the shape would be *replaced* by the write below, so
        // compose through a real transform instead of silently dropping it.
        if !inner.Location().IsIdentity() {
            return self.transform(shape, &placement.to_matrix());
        }
        let trsf = transform_from(placement);
        let location = ffi::top_loc::Location_from_transform(&trsf);
        // `TopoDS_Shape` keeps the location in the handle, not in the TShape, so a
        // copy carries the new placement while the identity of every sub-shape is the
        // one the caller already had.
        let mut moved = ffi::topo_ds::TopoDS_Shape_to_owned(inner);
        moved.pin_mut().set_location(&location, false);
        Ok(erase(&moved))
    }

    fn transform(&self, shape: &Shape, matrix: &Matrix4) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        let mut trsf = ffi::gp::new_transform();
        let m = &matrix.m;
        if m.len() < 16 {
            return Err(OcctError::InvalidInput {
                what: "matrix is not an affine transform",
            }
            .into());
        }
        ffi::gp::gp_Trsf_SetValues(
            trsf.pin_mut(),
            m[0], m[1], m[2], m[3],
            m[4], m[5], m[6], m[7],
            m[8], m[9], m[10], m[11],
        )
        .map_err(|_| GeomError::from(OcctError::InvalidInput {
            what: "matrix is not an affine transform",
        }))?;
        let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_Transform_new(inner, &trsf, true);
        let out = erase(op.pin_mut().Shape());
        if !op.IsDone() {
            return Err(OcctError::NotDone {
                operation: "transform",
            }
            .into());
        }
        Ok(out)
    }

    fn general_transform(&self, shape: &Shape, matrix: &Matrix4) -> Result<Shape, GeomError> {
        let occt = downcast(shape)?;
        let guard = occt.borrow();
        let inner = guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null shape" })?;
        // `gp_GTrsf` holds only the affine 3x4 block; reject a perspective
        // matrix instead of silently dropping its last row.
        let m = &matrix.m;
        if m[12].abs() > 1e-12
            || m[13].abs() > 1e-12
            || m[14].abs() > 1e-12
            || (m[15] - 1.0).abs() > 1e-12
        {
            return Err(OcctError::InvalidInput {
                what: "matrix is not affine",
            }
            .into());
        }
        let mut transform = ffi::gp::new_gp_GTrsf();
        for row in 1..=3 {
            for column in 1..=4 {
                let value = m[((row - 1) * 4 + (column - 1)) as usize];
                transform.pin_mut().SetValue(row, column, value);
            }
        }
        let mut op = ffi::b_rep_builder_api::BRepBuilderAPI_GTransform_new(
            inner,
            transform.as_ref().unwrap(),
            true,
        );
        if !op.IsDone() {
            return Err(OcctError::NotDone {
                operation: "general_transform",
            }
            .into());
        }
        let result = op.pin_mut().Shape();
        if result.IsNull() {
            return Err(OcctError::NotDone {
                operation: "general_transform",
            }
            .into());
        }
        Ok(erase(result))
    }

    fn resolve(&self, shape: &Shape, name: &str) -> Option<Shape> {
        // Positional fallback only: `FaceN`/`EdgeN` -> the N-th sub-shape. Stable
        // *named* resolution needs the lineage mapper (a later slice); this mirrors
        // FreeCAD's behaviour when no element map is available.
        let shape_occt = downcast(shape).ok()?;
        let shape_guard = shape_occt.borrow();
        let s = shape_guard.as_ref()?;
        let (kind, index) = parse_sub_name(name)?;
        let map = sub_shape_map(s, kind);
        if index >= 1 && index <= map.Extent() {
            Some(erase(map.FindKey(index)))
        } else {
            None
        }
    }

    fn save_shape(&self, shape: &Shape) -> Vec<u8> {
        crate::shape::write_brep(shape).unwrap_or_default()
    }

    fn load_shape(&self, bytes: &[u8]) -> Option<Shape> {
        crate::shape::read_brep(bytes)
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities::BOOLEANS
            | Capabilities::FILLET
            | Capabilities::CHAMFER
            | Capabilities::TESSELLATION
            | Capabilities::TOPOLOGY
    }

    fn tessellate(
        &self,
        shape: &Shape,
        options: &TessellationOptions,
    ) -> Result<Tessellation, GeomError> {
        topology::tessellate(shape, options)
    }

    fn elements(&self, shape: &Shape, kind: ElementKind) -> Vec<ElementRef> {
        topology::elements(shape, kind)
    }

    fn ancestors(&self, shape: &Shape, element: &ElementRef, kind: ElementKind) -> Vec<ElementRef> {
        topology::ancestors(shape, element, kind)
    }

    fn continuity(&self, shape: &Shape, a: &ElementRef, b: &ElementRef) -> Option<Continuity> {
        topology::continuity(shape, a, b)
    }

    fn chamfer(
        &self,
        shape: &Shape,
        edges: &[ElementRef],
        d1: f64,
        d2: Option<f64>,
    ) -> Result<OpResult, GeomError> {
        topology::chamfer(shape, edges, d1, d2)
    }

    fn classify(&self, error: &GeomError) -> FailureKind {
        // The whole OCCT mapping lives in `error.rs` so it can be audited and
        // unit-tested in one place; this backend's job is simply to opt in.
        crate::error::classify(error)
    }
}

/// Which operation a reusable upstream-style operation object is configured for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CutOperation {
    Cut,
    Fuse,
    Common,
}

impl CutOperation {
    /// The `BOPAlgo_Operation` this operation selects on the shared object.
    fn code(self) -> ffi::bop_algo::BOPAlgo_Operation {
        match self {
            CutOperation::Cut => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_CUT,
            CutOperation::Fuse => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_FUSE,
            CutOperation::Common => ffi::bop_algo::BOPAlgo_Operation::BOPAlgo_COMMON,
        }
    }

    /// The operation's name, for diagnostics.
    fn label(self) -> &'static str {
        match self {
            CutOperation::Cut => "cut",
            CutOperation::Fuse => "fuse",
            CutOperation::Common => "common",
        }
    }
}

/// The `TopAbs_ShapeEnum` value upstream's `ShapeTypeFromPyType` picks for a
/// `Part.Shape` subclass, as the integer the sibling bridge takes.
///
/// cxx exposes a shared enum as a transparent struct, so its `repr` field is the
/// OCCT discriminant (`TopAbs_SHAPE` is 8, `TopAbs_VERTEX` 7, …).
fn tolerance_shape_type(kind: ToleranceKind) -> TopAbs_ShapeEnum {
    match kind {
        ToleranceKind::All => TopAbs_ShapeEnum::TopAbs_SHAPE,
        ToleranceKind::Solid => TopAbs_ShapeEnum::TopAbs_SOLID,
        ToleranceKind::Shell => TopAbs_ShapeEnum::TopAbs_SHELL,
        ToleranceKind::Face => TopAbs_ShapeEnum::TopAbs_FACE,
        ToleranceKind::Wire => TopAbs_ShapeEnum::TopAbs_WIRE,
        ToleranceKind::Edge => TopAbs_ShapeEnum::TopAbs_EDGE,
        ToleranceKind::Vertex => TopAbs_ShapeEnum::TopAbs_VERTEX,
    }
}

/// A copy of every shape in a bridged `TopTools_ListOfShape`.
fn list_shapes(list: &TopTools_ListOfShape) -> Vec<Shape> {
    ffi::topo_ds::shape_list_to_vector(list)
        .iter()
        .map(erase)
        .collect()
}

/// A copy of an OCCT shape handle (reference-counted).
fn owned(shape: &TopoDS_Shape) -> UniquePtr<TopoDS_Shape> {
    ffi::topo_ds::TopoDS_Shape_to_owned(shape)
}

/// Borrow every non-null handle in `shapes`.
fn refs(shapes: &[UniquePtr<TopoDS_Shape>]) -> Vec<&TopoDS_Shape> {
    shapes.iter().filter_map(|shape| shape.as_ref()).collect()
}

/// The *direct* children of a shape, in `TopoDS_Iterator` order.
///
/// Unlike `TopExp::MapShapes`, this does not recurse: it is the iteration
/// upstream's `RecursiveAddTools`/`RecursiveCutCompound` perform.
fn direct_children(shape: &TopoDS_Shape) -> Vec<UniquePtr<TopoDS_Shape>> {
    history::children(shape)
}

/// Flatten a shape's compound children recursively, as `RecursiveAddTools` does.
fn flatten_compound(shape: &TopoDS_Shape) -> Vec<UniquePtr<TopoDS_Shape>> {
    let mut out = Vec::new();
    flatten_compound_into(shape, &mut out);
    out
}

fn flatten_compound_into(shape: &TopoDS_Shape, out: &mut Vec<UniquePtr<TopoDS_Shape>>) {
    if shape.ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND {
        for child in direct_children(shape) {
            if let Some(child) = child.as_ref() {
                flatten_compound_into(child, out);
            }
        }
    } else {
        out.push(owned(shape));
    }
}

/// An OCCT shape list holding the given handles, in order.
fn shape_list(shapes: &[&TopoDS_Shape]) -> UniquePtr<TopTools_ListOfShape> {
    let mut list = ffi::top_tools::new_list_of_shape();
    for shape in shapes {
        let _ = list.pin_mut().Append(shape);
    }
    list
}

/// A compound of the given shapes, in order.
fn compound_of(shapes: &[&TopoDS_Shape]) -> UniquePtr<TopoDS_Shape> {
    let mut compound = ffi::topo_ds::TopoDS_Compound_new();
    let builder = ffi::b_rep::BRep_Builder_new();
    let builder = ffi::b_rep::BRep_Builder_upcast_to_topods_builder(&builder);
    builder.MakeCompound(compound.pin_mut());
    let mut compound = ffi::topo_ds::TopoDS_Compound_as_shape(compound);
    for shape in shapes {
        builder.Add(compound.pin_mut(), shape);
    }
    compound
}

/// Upstream's `FCBRepAlgoAPI_BooleanOperation::Build`, for a cut.
///
/// - **Compound tool**, one argument (`RecursiveCutFusedTools`): flatten the
///   tool's compound children. With two or more pieces, fuse them on this same
///   operation object and use the fused result (flattened again when it is a
///   compound) as the tool list. A single-child compound is cut as-is.
/// - **Compound base**, one argument (`RecursiveCutCompound`): cut each direct
///   child with the unchanged tool and assemble the per-child results into a new
///   compound. The operation object keeps the history of the last child build,
///   exactly as upstream's does.
/// - Otherwise the plain two-list boolean is built.
///
/// Returns `None` when OCCT reports the build not done.
fn build_cut_policy(
    op: &mut UniquePtr<ffi::b_rep_algo_api::BRepAlgoAPI_Cut>,
    arguments: &[&TopoDS_Shape],
    tools: &[&TopoDS_Shape],
    operation: CutOperation,
) -> Option<UniquePtr<TopoDS_Shape>> {
    if operation == CutOperation::Cut
        && arguments.len() == 1
        && tools.len() == 1
        && tools[0].ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND
    {
        let mut pieces = flatten_compound(tools[0]);
        if pieces.len() >= 2 {
            // Fuse the tool pieces before cutting. Upstream flips
            // `myOperation` on the cut object and calls `Build()` again.
            let first = pieces.remove(0);
            let rest = refs(&pieces);
            let fuse_arguments = [first.as_ref().expect("a tool piece")];
            let argument_list = shape_list(&fuse_arguments);
            let tool_list = shape_list(&rest);
            history::set_operation(op.pin_mut(), true);
            history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
            history::build_cut(op.pin_mut());
            history::set_operation(op.pin_mut(), false);
            if !op.IsDone() {
                return None;
            }
            let fused = owned(op.pin_mut().Shape());
            // `RecursiveAddTools(myShape)`: a fused result that is still a
            // compound did not all touch, so cut with its pieces individually.
            pieces = flatten_compound(fused.as_ref().expect("the fused tool"));
        }

        let tool_refs = refs(&pieces);
        let argument_list = shape_list(arguments);
        let tool_list = shape_list(&tool_refs);
        history::set_operation(op.pin_mut(), false);
        history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
        history::build_cut(op.pin_mut());
        return op.IsDone().then(|| owned(op.pin_mut().Shape()));
    }

    if operation == CutOperation::Cut
        && arguments.len() == 1
        && arguments[0].ShapeType() == TopAbs_ShapeEnum::TopAbs_COMPOUND
    {
        let mut results = Vec::new();
        for child in direct_children(arguments[0]) {
            let child = child.as_ref().expect("a compound child");
            let child_arguments = [child];
            let out = build_cut_policy(op, &child_arguments, tools, CutOperation::Cut)?;
            results.push(out);
        }
        let result_refs = refs(&results);
        return Some(compound_of(&result_refs));
    }

    let argument_list = shape_list(arguments);
    let tool_list = shape_list(tools);
    history::set_boolean_operation(op.pin_mut(), operation.code());
    history::configure_cut(op.pin_mut(), &argument_list, &tool_list);
    history::build_cut(op.pin_mut());
    op.IsDone().then(|| owned(op.pin_mut().Shape()))
}

/// One boolean over two shapes, with upstream's fuzzy contract.
///
/// Every boolean is built on `BRepAlgoAPI_Cut`, which is the class the bridge exposes
/// the operation code and the fuzzy value on — the same thing upstream does through
/// `BRepAlgoAPI_BooleanOperation` and its `myOperation` field. `Cut` goes through
/// [`build_cut_policy`] because upstream's `Build` rewrites a compound tool before
/// OCCT sees it; `Fuse` and `Common` are one plain build.
///
/// The fuzzy value follows `TopoShape::makeElementBoolean`: a positive `tolerance` is
/// used as given, a negative one asks for the automatic value, and `0` leaves the
/// kernel's own confusion tolerance alone. Upstream's *document* features auto-fuzz
/// because they are built through the two-shape `FCBRepAlgoAPI_*` constructors, which
/// is why `containers.rs` passes [`ferrocad_geom::AUTO_FUZZY`] and `Shape.fuse` and
/// friends pass the caller's tolerance through.
fn boolean(
    a: &Shape,
    b: &Shape,
    operation: CutOperation,
    tolerance: f64,
) -> Result<OpResult, GeomError> {
    let a_occt = downcast(a)?;
    let b_occt = downcast(b)?;
    let a_guard = a_occt.borrow();
    let b_guard = b_occt.borrow();
    let sa = a_guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;
    let sb = b_guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;

    let mut op = ffi::b_rep_algo_api::BRepAlgoAPI_Cut_new_default();
    // The settings are taken from the *original* operands: the fuzzy value is not
    // recomputed for the internal fuse/cut builds a compound cut performs.
    let initial_arguments = shape_list(&[sa]);
    let initial_tools = shape_list(&[sb]);
    history::configure_cut(op.pin_mut(), &initial_arguments, &initial_tools);
    policy::cut_prepare(op.pin_mut());
    policy::apply_boolean_fuzzy(op.pin_mut(), tolerance);

    let result = match operation {
        CutOperation::Cut => build_cut_policy(&mut op, &[sa], &[sb], CutOperation::Cut),
        _ => {
            history::set_boolean_operation(op.pin_mut(), operation.code());
            history::build_cut(op.pin_mut());
            op.IsDone().then(|| owned(op.pin_mut().Shape()))
        }
    };
    let Some(result) = result else {
        return Err(OcctError::NotDone {
            operation: operation.label(),
        }
        .into());
    };

    let result = result.as_ref().expect("the boolean result");
    let out_maps = sub_shape_maps(result);
    let history = build_history(
        [(OperandId::A, sa), (OperandId::B, sb)],
        &out_maps,
        |sub, mods, gens| {
            history::collect(op.pin_mut().Modified(sub), mods);
            history::collect(op.pin_mut().Generated(sub), gens);
            op.pin_mut().IsDeleted(sub)
        },
    );
    Ok(OpResult::new(erase(result), history))
}

/// The sub-shape kinds a boolean reports lineage for, coarsest first.
///
/// The order is fixed so a history is deterministic; it is not the order of the
/// relation lists (those stay grouped by input), only of enumeration.
const HISTORY_KINDS: [(ElementKind, TopAbs_ShapeEnum); 3] = [
    (ElementKind::Face, TopAbs_ShapeEnum::TopAbs_FACE),
    (ElementKind::Edge, TopAbs_ShapeEnum::TopAbs_EDGE),
    (ElementKind::Vertex, TopAbs_ShapeEnum::TopAbs_VERTEX),
];

/// The OCCT shape type behind a `Shape.countElement` spelling.
///
/// Upstream matches a *prefix* of the name (`boost::starts_with`), so `Faces`
/// and `Face6` both count faces. An unknown spelling counts zero.
fn count_kind(kind: &str) -> Option<TopAbs_ShapeEnum> {
    const KINDS: [(&str, TopAbs_ShapeEnum); 8] = [
        ("Vertex", TopAbs_ShapeEnum::TopAbs_VERTEX),
        ("Edge", TopAbs_ShapeEnum::TopAbs_EDGE),
        ("Face", TopAbs_ShapeEnum::TopAbs_FACE),
        ("Wire", TopAbs_ShapeEnum::TopAbs_WIRE),
        ("Shell", TopAbs_ShapeEnum::TopAbs_SHELL),
        ("Solid", TopAbs_ShapeEnum::TopAbs_SOLID),
        ("Compound", TopAbs_ShapeEnum::TopAbs_COMPOUND),
        ("CompSolid", TopAbs_ShapeEnum::TopAbs_COMPSOLID),
    ];
    KINDS
        .iter()
        .find(|(name, _)| kind.starts_with(name))
        .map(|(_, occt)| *occt)
}

/// The result's sub-shape maps, one per kind in [`HISTORY_KINDS`] order.
///
/// Built before the operation object is probed: the result shape borrows the
/// operation immutably, and `Modified`/`Generated` need it mutably, so the two
/// borrows cannot overlap.
fn sub_shape_maps(shape: &TopoDS_Shape) -> [(ElementKind, UniquePtr<Map>); 3] {
    HISTORY_KINDS.map(|(kind, occt)| (kind, sub_shape_map(shape, occt)))
}

/// Build the [`History`] of a boolean from **both** of its operands.
///
/// Every sub-shape of both operands is enumerated, for each of the three kinds the
/// kernel reports (`Face`, `Edge`, `Vertex`); `probe` fills `mods`/`gens` for one of
/// them and reports whether OCCT considers it deleted. An output is kept only if it
/// appears in the result's map of the same kind, so an element that does not survive
/// there is dropped, as before.
///
/// Each kept relation also records the input's [`ElementId`]: which operand it came
/// from, its kind, and its 1-based ordinal in that operand's map. Names stay
/// positional (`Face1`, `Edge3`, `Vertex8`), so one operand's `Face1` and another's
/// are told apart by identity rather than by spelling. An input with no surviving
/// output is reported deleted only when the kernel says so: unchanged elements
/// remain absent from all three lists.
fn build_history<F>(
    operands: [(OperandId, &TopoDS_Shape); 2],
    out_maps: &[(ElementKind, UniquePtr<Map>); 3],
    mut probe: F,
) -> History
where
    F: FnMut(&TopoDS_Shape, &mut UniquePtr<Map>, &mut UniquePtr<Map>) -> bool,
{
    let mut history = History::default();

    for (operand, in_shape) in operands {
        for (kind_index, (kind, occt_kind)) in HISTORY_KINDS.into_iter().enumerate() {
            let in_map = sub_shape_map(in_shape, occt_kind);
            let out_map = &out_maps[kind_index].1;

            for ordinal in 1..=in_map.Extent() {
                let element = in_map.FindKey(ordinal);
                let mut mods = new_map();
                let mut gens = new_map();
                let deleted = probe(element, &mut mods, &mut gens);
                let input_id = ElementId::new(operand, kind.prefix(), ordinal as usize);

                let mut mapped = false;
                for entry in 1..=mods.Extent() {
                    let out = mods.FindKey(entry);
                    let index = out_map.FindIndex(out);
                    if index > 0 {
                        history.push_modified(
                            element_ref(kind, ordinal, element),
                            input_id.clone(),
                            element_ref(kind, index, out),
                        );
                        mapped = true;
                    }
                }
                for entry in 1..=gens.Extent() {
                    let out = gens.FindKey(entry);
                    let index = out_map.FindIndex(out);
                    if index > 0 {
                        history.push_generated(
                            element_ref(kind, ordinal, element),
                            input_id.clone(),
                            element_ref(kind, index, out),
                        );
                        mapped = true;
                    }
                }
                if !mapped && deleted {
                    history.push_deleted(element_ref(kind, ordinal, element), input_id);
                }
            }
        }
    }

    // The identity (`IsSame`) pass: an unchanged input keeps its name in the
    // result. Upstream's `mapSubElement` runs this before the modified/generated
    // names, so `ElementMap::apply` folds it first too.
    add_identity_relations(&mut history, operands, out_maps);

    // The reverse/forward derivation passes. They name result elements from the
    // result's own incidence graph; see `add_derived_names`.
    add_derived_names(&mut history, out_maps);

    // The identity side table is canonical: sorted by operand, kind, ordinal,
    // relation and output, so the order OCCT reported relations in cannot change
    // how a history compares. The relation lists above keep reporting order.
    history.provenance.sort();
    history
}

/// The `(kind, 1-based ordinal)` behind a positional element name.
fn element_key(name: &str) -> Option<(ElementKind, i32)> {
    for kind in [ElementKind::Face, ElementKind::Edge, ElementKind::Vertex] {
        if let Some(rest) = name.strip_prefix(kind.prefix()) {
            if let Ok(ordinal) = rest.parse::<i32>() {
                return Some((kind, ordinal));
            }
        }
    }
    None
}

/// The relations a refine leaves behind (upstream's `makeElementRefine` history).
///
/// The unifier reports no `Modified` map through the bridge, and it *rebuilds* every
/// sub-shape it keeps, so `IsSame` is false even for an element it did not touch.
/// Matching is therefore geometric: an input element whose measure and centre of mass
/// (a vertex: its point) are found once in the result keeps its name through an
/// identity relation, and one the unifier merged into a larger element — or removed —
/// is retired. Naming a merged face after either of its parents would be an invention,
/// which the lineage layer refuses to make.
fn refine_history(before: &TopoDS_Shape, after: &TopoDS_Shape) -> History {
    let mut history = History::default();
    for (kind, occt_kind) in HISTORY_KINDS {
        let in_map = sub_shape_map(before, occt_kind);
        let out_map = sub_shape_map(after, occt_kind);
        let out_keys: Vec<Option<(f64, Vector3)>> = (1..=out_map.Extent())
            .map(|index| sub_shape_key(kind, &out_map.FindKey(index)))
            .collect();
        for ordinal in 1..=in_map.Extent() {
            let element = in_map.FindKey(ordinal);
            let matched = sub_shape_key(kind, &element).and_then(|key| {
                let mut hits = out_keys
                    .iter()
                    .enumerate()
                    .filter(|(_, other)| other.as_ref().is_some_and(|other| same_key(&key, other)))
                    .map(|(index, _)| index as i32 + 1);
                let first = hits.next()?;
                // Two geometrically identical outputs make the match ambiguous, so
                // the name is retired rather than bound to either.
                if hits.next().is_some() {
                    return None;
                }
                Some(first)
            });
            match matched {
                Some(index) => history.push_identity(
                    element_ref(kind, ordinal, &element),
                    element_ref(kind, index, &out_map.FindKey(index)),
                ),
                None => history.push_deleted(
                    element_ref(kind, ordinal, &element),
                    ElementId::new(OperandId::A, kind.prefix(), ordinal as usize),
                ),
            }
        }
    }
    history.provenance.sort();
    history
}

/// A sub-element's geometric identity: its measure (length, area) and its centre of
/// mass. A vertex measures zero and identifies by its point.
fn sub_shape_key(kind: ElementKind, shape: &TopoDS_Shape) -> Option<(f64, Vector3)> {
    if kind == ElementKind::Vertex {
        let point = ffi::b_rep::BRep_Tool_Pnt(ffi::topo_ds::TopoDS::Vertex(shape));
        return Some((0.0, Vector3::new(point.X(), point.Y(), point.Z())));
    }
    crate::shape_ops::measure_key(shape)
}

/// Whether two sub-shape keys name the same geometry.
///
/// The unifier rebuilds without moving anything, so the two sides agree to rounding;
/// the tolerance is OCCT's confusion distance for the centre and a relative one for
/// the measure, which keeps two differently sized faces apart.
fn same_key(a: &(f64, Vector3), b: &(f64, Vector3)) -> bool {
    let scale = a.0.abs().max(b.0.abs()).max(1.0);
    (a.0 - b.0).abs() <= 1e-7 * scale && a.1.sub(&b.1).length() <= 1e-7
}

/// Record every input sub-element that survives unchanged as the same result
/// sub-element (`IsSame`), under the same kind.
///
/// This is upstream's `mapSubElement(shapes)` identity mapping: it names a result
/// element after the input element it literally still is, without claiming the
/// operation modified or generated it.
fn add_identity_relations(
    history: &mut History,
    operands: [(OperandId, &TopoDS_Shape); 2],
    out_maps: &[(ElementKind, UniquePtr<Map>); 3],
) {
    for (_operand, in_shape) in operands {
        for (kind_index, (kind, occt_kind)) in HISTORY_KINDS.into_iter().enumerate() {
            let in_map = sub_shape_map(in_shape, occt_kind);
            let out_map = &out_maps[kind_index].1;
            for ordinal in 1..=in_map.Extent() {
                let element = in_map.FindKey(ordinal);
                let index = out_map.FindIndex(element);
                if index > 0 {
                    history.push_identity(
                        element_ref(kind, ordinal, element),
                        element_ref(kind, index, out_map.FindKey(index)),
                    );
                }
            }
        }
    }
}

/// Name result elements from the result's incidence graph, mirroring upstream's
/// derivation passes.
///
/// 1. **Reverse** (faces, then edges): a *named* upper element names the lower
///    elements it contains that are still unnamed (`Face1` names its edges, an
///    edge names its vertices).
/// 2. **Forward** (edges, then faces): a still-unnamed higher element is named
///    from its lower elements, but only when **all** of them are named. An edge
///    uses its vertices; a face uses the edges of its outer wire, as upstream
///    does.
///
/// A derivation is recorded as a naming relation, not as operand provenance.
fn add_derived_names(history: &mut History, out_maps: &[(ElementKind, UniquePtr<Map>); 3]) {
    let face_map = &out_maps[0].1;
    let edge_map = &out_maps[1].1;
    let vertex_map = &out_maps[2].1;

    let mut named: BTreeSet<(ElementKind, i32)> = BTreeSet::new();
    for (_, output) in history.modified.iter().chain(&history.generated) {
        if let Some(key) = element_key(&output.name) {
            named.insert(key);
        }
    }
    for (_, output) in &history.identity {
        if let Some(key) = element_key(&output.name) {
            named.insert(key);
        }
    }

    // Reverse pass: face -> edge, then edge -> vertex.
    for (upper_kind, upper_map, lower_kind, lower_occt) in [
        (
            ElementKind::Face,
            face_map,
            ElementKind::Edge,
            TopAbs_ShapeEnum::TopAbs_EDGE,
        ),
        (
            ElementKind::Edge,
            edge_map,
            ElementKind::Vertex,
            TopAbs_ShapeEnum::TopAbs_VERTEX,
        ),
    ] {
        let lower_map = if lower_kind == ElementKind::Edge {
            edge_map
        } else {
            vertex_map
        };
        for index in 1..=upper_map.Extent() {
            if !named.contains(&(upper_kind, index)) {
                continue;
            }
            let upper = upper_map.FindKey(index);
            let sub = sub_shape_map(upper, lower_occt);
            for sub_index in 1..=sub.Extent() {
                let lower_shape = sub.FindKey(sub_index);
                let lower_index = lower_map.FindIndex(lower_shape);
                if lower_index <= 0 || named.contains(&(lower_kind, lower_index)) {
                    continue;
                }
                history.push_derived(
                    element_ref(upper_kind, index, upper),
                    element_ref(lower_kind, lower_index, lower_map.FindKey(lower_index)),
                );
                named.insert((lower_kind, lower_index));
            }
        }
    }

    // Forward pass: edges from their vertices.
    for index in 1..=edge_map.Extent() {
        if named.contains(&(ElementKind::Edge, index)) {
            continue;
        }
        let edge = edge_map.FindKey(index);
        let Some(lower) =
            complete_lower(&edge, TopAbs_ShapeEnum::TopAbs_VERTEX, vertex_map, &named)
        else {
            continue;
        };
        for ordinal in lower {
            history.push_derived(
                element_ref(ElementKind::Vertex, ordinal, vertex_map.FindKey(ordinal)),
                element_ref(ElementKind::Edge, index, edge),
            );
        }
        named.insert((ElementKind::Edge, index));
    }

    // Forward pass: faces from the edges of their outer wire.
    for index in 1..=face_map.Extent() {
        if named.contains(&(ElementKind::Face, index)) {
            continue;
        }
        let face = face_map.FindKey(index);
        let wire = ffi::b_rep_tools::outer_wire(ffi::topo_ds::TopoDS::Face(face));
        let Some(wire) = wire.as_ref() else {
            continue;
        };
        let wire = ffi::topo_ds::cast_wire_to_shape(wire);
        let Some(lower) = complete_lower(wire, TopAbs_ShapeEnum::TopAbs_EDGE, edge_map, &named)
        else {
            continue;
        };
        for ordinal in lower {
            history.push_derived(
                element_ref(ElementKind::Edge, ordinal, edge_map.FindKey(ordinal)),
                element_ref(ElementKind::Face, index, face),
            );
        }
        named.insert((ElementKind::Face, index));
    }
}

/// The distinct lower-element ordinals of `shape`, or `None` unless there is at
/// least one and every one is already `named`.
fn complete_lower(
    shape: &TopoDS_Shape,
    kind: TopAbs_ShapeEnum,
    map: &UniquePtr<Map>,
    named: &BTreeSet<(ElementKind, i32)>,
) -> Option<Vec<i32>> {
    let element_kind = if kind == TopAbs_ShapeEnum::TopAbs_EDGE {
        ElementKind::Edge
    } else {
        ElementKind::Vertex
    };
    let sub = sub_shape_map(shape, kind);
    let mut ordinals: Vec<i32> = Vec::new();
    for index in 1..=sub.Extent() {
        let index = map.FindIndex(sub.FindKey(index));
        if index <= 0 || !named.contains(&(element_kind, index)) {
            return None;
        }
        if !ordinals.contains(&index) {
            ordinals.push(index);
        }
    }
    (!ordinals.is_empty()).then_some(ordinals)
}

/// A positional element reference into an operand (`FaceN`, `EdgeN`, `VertexN`).
fn element_ref(kind: ElementKind, index: i32, shape: &TopoDS_Shape) -> ElementRef {
    ElementRef {
        shape: erase(shape),
        name: format!("{}{index}", kind.prefix()),
    }
}

/// The top-level parts of a compound: its solids when it has any, else its
/// faces, then edges, then wires (the split pieces General Fuse returns).
fn top_level_parts(shape: &TopoDS_Shape) -> Vec<Shape> {
    for kind in [
        TopAbs_ShapeEnum::TopAbs_SOLID,
        TopAbs_ShapeEnum::TopAbs_SHELL,
        TopAbs_ShapeEnum::TopAbs_FACE,
        TopAbs_ShapeEnum::TopAbs_EDGE,
        TopAbs_ShapeEnum::TopAbs_WIRE,
        TopAbs_ShapeEnum::TopAbs_VERTEX,
    ] {
        let map = sub_shape_map(shape, kind);
        if map.Extent() > 0 {
            return (1..=map.Extent())
                .map(|index| erase(map.FindKey(index)))
                .collect();
        }
    }
    Vec::new()
}

/// The shapes in an OCCT shape list, in the list's order.
fn collect_list(list: &UniquePtr<TopTools_ListOfShape>) -> Vec<Shape> {
    let Some(list) = list.as_ref() else {
        return Vec::new();
    };
    ffi::topo_ds::shape_list_to_vector(list)
        .iter()
        .map(erase)
        .collect()
}

/// A `gp_Trsf` equivalent to a FerroCAD [`Placement`] (rotation about the origin,
/// then translation).
fn transform_from(placement: &Placement) -> UniquePtr<ffi::gp::gp_Trsf> {
    let mut trsf = ffi::gp::new_transform();
    let angle = placement.rotation.angle();
    if angle.abs() > 1e-12 {
        let axis = placement.rotation.axis();
        let dir = ffi::gp::gp_Dir_new(axis.x, axis.y, axis.z);
        let origin = ffi::gp::new_point(0.0, 0.0, 0.0);
        let ax1 = ffi::gp::gp_Ax1_new(&origin, &dir);
        trsf.pin_mut().SetRotation(&ax1, angle);
    }
    let translation = ffi::gp::new_vec(placement.base.x, placement.base.y, placement.base.z);
    trsf.pin_mut().set_translation_vec(&translation);
    trsf
}

/// Parse a positional sub-element name (`Face6`, `Edge12`).
fn parse_sub_name(name: &str) -> Option<(TopAbs_ShapeEnum, i32)> {
    for (prefix, kind) in [
        ("Solid", TopAbs_ShapeEnum::TopAbs_SOLID),
        ("Shell", TopAbs_ShapeEnum::TopAbs_SHELL),
        ("Face", TopAbs_ShapeEnum::TopAbs_FACE),
        ("Wire", TopAbs_ShapeEnum::TopAbs_WIRE),
        ("Edge", TopAbs_ShapeEnum::TopAbs_EDGE),
        ("Vertex", TopAbs_ShapeEnum::TopAbs_VERTEX),
    ] {
        if let Some(rest) = name.strip_prefix(prefix) {
            if let Ok(index) = rest.parse::<i32>() {
                return Some((kind, index));
            }
        }
    }
    None
}

/// A `gp_Pnt` from a [`Vector3`].
fn axis_from(base: Vector3, direction: Vector3) -> Result<UniquePtr<ffi::gp::gp_Ax2>, GeomError> {
    if direction.x == 0.0 && direction.y == 0.0 && direction.z == 0.0 {
        return Err(OcctError::InvalidInput {
            what: "a primitive needs a non-zero direction",
        }
        .into());
    }
    let origin = point(base);
    let direction = ffi::gp::gp_Dir_new(direction.x, direction.y, direction.z);
    Ok(ffi::gp::gp_Ax2_new(&origin, &direction))
}

fn point(vector: Vector3) -> UniquePtr<ffi::gp::gp_Pnt> {
    ffi::gp::new_point(vector.x, vector.y, vector.z)
}

/// A flat xyz list, the form the `ferrocad_part_cxx` B-spline helpers take.
fn flatten(points: &[Vector3]) -> Vec<f64> {
    let mut coords = Vec::with_capacity(points.len() * 3);
    for point in points {
        coords.extend_from_slice(&[point.x, point.y, point.z]);
    }
    coords
}

/// The frame of an elliptical conic, in the form `fc_conic_edge` takes.
trait ConicFrame {
    fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64);
}

impl ConicFrame for Ellipse {
    fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
        (
            self.center(),
            self.normal(),
            self.x_axis(),
            self.major_radius(),
            self.minor_radius(),
        )
    }
}

impl ConicFrame for Hyperbola {
    fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
        (
            self.center(),
            self.normal(),
            self.x_axis(),
            self.major_radius(),
            self.minor_radius(),
        )
    }
}

impl ConicFrame for Parabola {
    fn conic_frame(&self) -> (Vector3, Vector3, Vector3, f64, f64) {
        (
            self.vertex(),
            self.normal(),
            self.x_axis(),
            self.focal(),
            0.0,
        )
    }
}

/// Read the flat payload `fc_edge_curve` writes.
///
/// See that function for the layout: a 14-value header plus a kind-specific tail.
fn parse_edge_curve(data: &[f64]) -> Result<EdgeCurve, GeomError> {
    if data.len() < 14 {
        return Err(unsupported("curve_of: the bridge returned no curve data"));
    }
    let origin = Vector3::new(data[1], data[2], data[3]);
    let direction = Vector3::new(data[4], data[5], data[6]);
    let x_axis = Vector3::new(data[7], data[8], data[9]);
    let (first, last) = (data[10], data[11]);
    let (major, minor) = (data[12], data[13]);
    let tail = &data[14..];
    match data[0] as i32 {
        1 => Ok(EdgeCurve::Line(Line::new(origin, direction)?)),
        2 => {
            let circle = Circle::with_axis(origin, direction, x_axis, major)?;
            if (last - first).abs() >= std::f64::consts::TAU - 1e-9 {
                Ok(EdgeCurve::Circle(circle))
            } else {
                Ok(EdgeCurve::Arc(Arc::new(circle, first, last)?))
            }
        }
        3 => {
            let ellipse = Ellipse::with_axis(origin, direction, x_axis, major, minor)?;
            if (last - first).abs() >= std::f64::consts::TAU - 1e-9 {
                Ok(EdgeCurve::Ellipse(ellipse))
            } else {
                Ok(EdgeCurve::EllipticalArc(EllipticalArc::new(
                    ellipse, first, last,
                )?))
            }
        }
        4 => {
            let hyperbola = Hyperbola::with_axis(origin, direction, x_axis, major, minor)?;
            Ok(EdgeCurve::ArcOfHyperbola(ArcOfHyperbola::new(
                hyperbola, first, last,
            )?))
        }
        5 => {
            let parabola = Parabola::with_axis(origin, direction, x_axis, major)?;
            Ok(EdgeCurve::ArcOfParabola(ArcOfParabola::new(
                parabola, first, last,
            )?))
        }
        6 => parse_bezier(tail, first, last),
        7 => parse_bspline(tail),
        8 => parse_offset(tail, direction, major, first, last),
        _ => Err(unsupported("curve_of: unsupported curve type")),
    }
}

/// `count` consecutive xyz triples from `values`.
fn parse_points(values: &[f64], count: usize) -> Result<Vec<Vector3>, GeomError> {
    let count3 = count.checked_mul(3).ok_or_else(|| unsupported("curve_of: truncated poles"))?;
    let coordinates = values
        .get(..count3)
        .ok_or_else(|| unsupported("curve_of: truncated poles"))?;
    Ok(coordinates
        .chunks_exact(3)
        .map(|triple| Vector3::new(triple[0], triple[1], triple[2]))
        .collect())
}

/// A Bezier payload: `[pole_count] poles weights`.
fn parse_bezier(tail: &[f64], first: f64, last: f64) -> Result<EdgeCurve, GeomError> {
    let count = tail
        .first()
        .map(|value| *value as usize)
        .ok_or_else(|| unsupported("curve_of: truncated Bezier"))?;
    let poles = parse_points(&tail[1..], count)?;
    let weight_start = 1 + count * 3;
    let weights = tail
        .get(weight_start..weight_start + count)
        .ok_or_else(|| unsupported("curve_of: truncated Bezier weights"))?
        .to_vec();
    let base = BezierCurve::new(poles, weights)?;
    // `Geom_BezierCurve` is always parameterised on `[0, 1]`; a narrower edge
    // range selects the segment while keeping the edge's parameters.
    let curve = if (first - 0.0).abs() <= 1e-12 && (last - 1.0).abs() <= 1e-12 {
        base
    } else {
        base.trim(first, last).unwrap_or(base)
    };
    Ok(EdgeCurve::BezierCurve(curve))
}

/// A B-spline payload: `[degree, pole_count, knot_count, mult_count, periodic]`
/// poles weights knots mults.
fn parse_bspline(tail: &[f64]) -> Result<EdgeCurve, GeomError> {
    let header = tail
        .get(..5)
        .ok_or_else(|| unsupported("curve_of: truncated B-spline"))?;
    let degree = header[0] as i32;
    let pole_count = header[1] as usize;
    let knot_count = header[2] as usize;
    let mult_count = header[3] as usize;
    let periodic = header[4] != 0.0;
    let mut at = 5;
    let poles = parse_points(
        tail.get(at..).ok_or_else(|| unsupported("curve_of: truncated B-spline"))?,
        pole_count,
    )?;
    at += pole_count * 3;
    let weights = tail
        .get(at..at + pole_count)
        .ok_or_else(|| unsupported("curve_of: truncated B-spline weights"))?
        .to_vec();
    at += pole_count;
    let knots = tail
        .get(at..at + knot_count)
        .ok_or_else(|| unsupported("curve_of: truncated B-spline knots"))?
        .to_vec();
    at += knot_count;
    let mults = tail
        .get(at..at + mult_count)
        .ok_or_else(|| unsupported("curve_of: truncated B-spline multiplicities"))?
        .iter()
        .map(|value| *value as i32)
        .collect();
    let curve = if periodic {
        NurbsCurve::new_periodic(degree, knots, mults, poles, weights)?
    } else {
        NurbsCurve::new(degree, knots, mults, poles, weights)?
    };
    Ok(EdgeCurve::BSplineCurve(curve))
}

/// An offset payload: `[basis_length]` then a nested payload.
fn parse_offset(
    tail: &[f64],
    direction: Vector3,
    offset: f64,
    first: f64,
    last: f64,
) -> Result<EdgeCurve, GeomError> {
    let length = tail
        .first()
        .map(|value| *value as usize)
        .ok_or_else(|| unsupported("curve_of: truncated offset curve"))?;
    let basis_data = tail
        .get(1..1 + length)
        .ok_or_else(|| unsupported("curve_of: truncated offset basis"))?;
    let basis = parse_edge_curve(basis_data)?;
    Ok(EdgeCurve::OffsetCurve(OffsetCurve::new(
        basis, offset, direction, first, last,
    )?))
}

/// A trimmed conic edge (ellipse, hyperbola or parabola) from its frame.
fn edge_from_conic<T: ConicFrame>(
    kind: i32,
    curve: &T,
    first: f64,
    last: f64,
    what: &'static str,
) -> Result<Shape, GeomError> {
    let (center, normal, x_axis, major, minor) = curve.conic_frame();
    let edge = crate::curve::conic_edge(
        kind,
        center,
        normal,
        x_axis,
        major,
        minor,
        first,
        last,
    );
    let Some(edge) = edge else {
        return Err(OcctError::NotDone { operation: what }.into());
    };
    Ok(erase(&edge))
}

/// A Bezier edge (`Geom_BezierCurve`).
///
/// OCCT parameterises a Bezier on `[0, 1]`; a curve stored over another range is
/// re-expressed there (the geometry is unchanged, but the edge's parameters are
/// `[0, 1]`). The Python `toShape` path keeps arbitrary ranges by converting to a
/// B-spline instead.
fn edge_from_bezier(curve: &BezierCurve) -> Result<Shape, GeomError> {
    let edge = crate::curve::bezier_edge(&flatten(curve.poles()), curve.weights());
    let Some(edge) = edge else {
        return Err(OcctError::NotDone {
            operation: "make_edge (Bezier)",
        }
        .into());
    };
    Ok(erase(&edge))
}

/// A B-spline edge, re-segmenting when the stored range is narrower than the knot
/// domain.
fn edge_from_nurbs(curve: &NurbsCurve) -> Result<Shape, GeomError> {
    let edge = crate::curve::bspline_edge_range(
        &flatten(curve.poles()),
        curve.weights(),
        curve.knots(),
        curve.mults(),
        curve.degree(),
        curve.is_periodic(),
        curve.first(),
        curve.last(),
    );
    let Some(edge) = edge else {
        return Err(OcctError::NotDone {
            operation: "make_edge (B-spline)",
        }
        .into());
    };
    Ok(erase(&edge))
}

/// A circular edge from the analytic circle.
///
/// The edge's parameterisation origin is OCCT's choice: `gp_Ax2` is built from a
/// point and a normal only, so the curve comes back with its own `x_axis` after
/// [`curve_of`](GeometryBackend::curve_of). The geometry (centre, normal, radius)
/// is what round-trips; an arc's angles are carried by its three points instead.
/// A full circular edge from the analytic circle.
///
/// The **analytic X axis** goes through to `gp_Ax2`: it is the direction the
/// circle reports as `XAxis`/`AngleXU`, and it is where the edge's parameter 0
/// (and its seam vertex) must sit. Letting `gp_Ax2` choose the X direction from
/// the normal alone made a `-Z` circle build its edge with the seam half a turn
/// from the frame the same circle reported, which split a sew seam into two arcs
/// (`SimpleCAD`'s boss rebuild counted three circles instead of two).
fn edge_from_circle(circle: &Circle) -> Result<Shape, GeomError> {
    let center = point(circle.center());
    let normal = ffi::gp::gp_Dir_new(circle.normal().x, circle.normal().y, circle.normal().z);
    let x_axis = circle.x_axis();
    let x_dir = ffi::gp::gp_Dir_new(x_axis.x, x_axis.y, x_axis.z);
    let axis = match ffi::gp::gp_Ax2_new3(&center, &normal, &x_dir) {
        Ok(axis) => axis,
        Err(_) => {
            return Err(OcctError::NotDone {
                operation: "make_edge (circle)",
            }
            .into())
        }
    };
    let circ = ffi::gp::gp_Circ_new(&axis, circle.radius());
    let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeEdge_circle(&circ);
    if !make.IsDone() {
        return Err(OcctError::NotDone {
            operation: "make_edge (circle)",
        }
        .into());
    }
    Ok(erase(ffi::topo_ds::cast_edge_to_shape(
        make.pin_mut().Edge(),
    )))
}

/// A full elliptical edge from the analytic ellipse.
///
/// The frame goes through explicitly (centre, plane normal, major-axis direction,
/// the two radii) because `gp_Elips`' axis placement carries all of them; the
/// edge parameterisation starts on the major axis.
fn edge_from_ellipse(ellipse: &Ellipse) -> Result<Shape, GeomError> {
    let edge = crate::curve::ellipse_edge(
        ellipse.center(),
        ellipse.normal(),
        ellipse.x_axis(),
        ellipse.major_radius(),
        ellipse.minor_radius(),
    );
    let Some(edge) = edge else {
        return Err(OcctError::NotDone {
            operation: "make_edge (ellipse)",
        }
        .into());
    };
    Ok(erase(&edge))
}

#[cfg(test)]
mod provenance_tests {
    //! Golden histories for the two-input booleans: both operands, all three
    //! element kinds, and the identity behind every reported relation.
    //!
    //! The counts are the OCCT 7.8 answer for two coincident-sized boxes, one offset
    //! by `(5, 5, 5)`. They are exact on purpose: this is the baseline S4 hands to
    //! the lineage layer, so a kernel or adapter change should be visible here first.

    use std::collections::{BTreeMap, BTreeSet};

    use ferrocad_geom::{ElementKind, GeometryBackend, History, OperandId, Relation};
    use ferrocad_types::Rotation;

    use super::*;

    /// Overlapping 10³ boxes: `a` at the origin, `b` shifted by `(5, 5, 5)`.
    fn overlapping_boxes(backend: &OcctBackend) -> (Shape, Shape) {
        let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let b = backend
            .place(
                &backend.make_box(10.0, 10.0, 10.0).unwrap(),
                &Placement {
                    base: Vector3::new(5.0, 5.0, 5.0),
                    rotation: Rotation::identity(),
                },
            )
            .unwrap();
        (a, b)
    }

    /// `(operand, kind, relation) -> count` over the provenance side table.
    fn counts(history: &History) -> BTreeMap<(OperandId, String, Relation), usize> {
        let mut counts = BTreeMap::new();
        for entry in &history.provenance {
            *counts
                .entry((
                    entry.input.operand(),
                    entry.input.kind().to_string(),
                    entry.relation,
                ))
                .or_insert(0) += 1;
        }
        counts
    }

    fn expected(
        entries: &[(OperandId, &str, Relation, usize)],
    ) -> BTreeMap<(OperandId, String, Relation), usize> {
        entries
            .iter()
            .map(|(operand, kind, relation, count)| {
                ((*operand, kind.to_string(), *relation), *count)
            })
            .collect()
    }

    /// Split a positional name into its kind prefix and 1-based ordinal.
    fn split_name(name: &str) -> (String, usize) {
        for prefix in ["Face", "Edge", "Vertex"] {
            if let Some(rest) = name.strip_prefix(prefix) {
                let ordinal = rest.parse().expect("a positional ordinal");
                return (prefix.to_string(), ordinal);
            }
        }
        panic!("not a positional sub-element name: {name}");
    }

    /// The relation lists projected onto `(kind, ordinal, relation, output)`.
    ///
    /// The relation lists have no operand field, so this is compared with the
    /// provenance projection to check that every reported relation has exactly one
    /// identity entry; the per-operand counts above then check the operand split.
    fn relation_projection(history: &History) -> Vec<(String, usize, Relation, Option<String>)> {
        let mut entries = Vec::new();
        for (input, output) in &history.modified {
            let (kind, ordinal) = split_name(&input.name);
            entries.push((kind, ordinal, Relation::Modified, Some(output.name.clone())));
        }
        for (input, output) in &history.generated {
            let (kind, ordinal) = split_name(&input.name);
            entries.push((
                kind,
                ordinal,
                Relation::Generated,
                Some(output.name.clone()),
            ));
        }
        for input in &history.deleted {
            let (kind, ordinal) = split_name(&input.name);
            entries.push((kind, ordinal, Relation::Deleted, None));
        }
        entries.sort();
        entries
    }

    fn provenance_projection(history: &History) -> Vec<(String, usize, Relation, Option<String>)> {
        let mut entries: Vec<_> = history
            .provenance
            .iter()
            .map(|entry| {
                (
                    entry.input.kind().to_string(),
                    entry.input.ordinal(),
                    entry.relation,
                    entry.output.clone(),
                )
            })
            .collect();
        entries.sort();
        entries
    }

    /// The ordered names in each relation list, for run-to-run comparison.
    fn relation_names(
        history: &History,
    ) -> (Vec<(String, String)>, Vec<(String, String)>, Vec<String>) {
        (
            history
                .modified
                .iter()
                .map(|(input, output)| (input.name.clone(), output.name.clone()))
                .collect(),
            history
                .generated
                .iter()
                .map(|(input, output)| (input.name.clone(), output.name.clone()))
                .collect(),
            history
                .deleted
                .iter()
                .map(|input| input.name.clone())
                .collect(),
        )
    }

    /// Every identity is in range for its operand and every output resolves in the
    /// result, under the same kind. Names stay positional, so the two must agree.
    fn assert_histories_are_coherent(
        backend: &OcctBackend,
        operands: [(&Shape, OperandId); 2],
        result: &Shape,
        history: &History,
    ) {
        let kinds = [ElementKind::Face, ElementKind::Edge, ElementKind::Vertex];
        let total = |shape: &Shape, kind: ElementKind| backend.elements(shape, kind).len();

        let mut outputs = BTreeMap::new();
        for kind in kinds {
            outputs.insert(kind.prefix(), total(result, kind));
        }

        for entry in &history.provenance {
            let operand = operands
                .iter()
                .find(|(_, id)| *id == entry.input.operand())
                .map(|(shape, _)| *shape)
                .expect("a known operand");
            let kind = kinds
                .iter()
                .find(|kind| kind.prefix() == entry.input.kind())
                .copied()
                .expect("Face, Edge or Vertex");

            let input_total = total(operand, kind);
            assert!(
                (1..=input_total).contains(&entry.input.ordinal()),
                "{} {}#{} is outside the operand's {input_total} elements",
                entry.input.kind(),
                entry.input.operand().position(),
                entry.input.ordinal(),
            );

            if let Some(output) = &entry.output {
                let (output_kind, ordinal) = split_name(output);
                assert_eq!(
                    output_kind,
                    entry.input.kind(),
                    "an input keeps its kind in the result"
                );
                let output_total = outputs[output_kind.as_str()];
                assert!(
                    ordinal >= 1 && ordinal <= output_total,
                    "output {output} is outside the result's {output_total} {output_kind}s",
                );
            }
        }

        assert_eq!(
            provenance_projection(history),
            relation_projection(history),
            "every relation has exactly one identity entry",
        );

        let operand_ids: BTreeSet<_> = history
            .provenance
            .iter()
            .map(|entry| entry.input.operand())
            .collect();
        assert_eq!(
            operand_ids,
            BTreeSet::from([OperandId::A, OperandId::B]),
            "both operands are reported",
        );
    }

    /// A general fuse answers every input from **one** build, so the images it reports
    /// belong to the result it returns.
    ///
    /// Rebuilding the fuse per input (what this replaced) gave each input its own
    /// independent copy: mixing those copies into one face left coincident, unshared
    /// vertices, and SimpleCAD's local face split could not rebuild the faces around a
    /// split line.
    /// A boolean honours upstream's `tol`: `0` is the kernel's own tolerance, a
    /// positive value is the fuzzy value, and `AUTO_FUZZY` is the bounding-box
    /// diagonal times the confusion tolerance.
    ///
    /// A gap wider than the fuzzy value keeps two bodies; a fuzzy value wider than the
    /// gap bridges it into one. This is the contract `Shape.fuse`/`cut`/`common` pass
    /// their `tolerance` argument to, and it is why the document booleans — which
    /// upstream builds through the auto-fuzzing `FCBRepAlgoAPI_*` constructors — ask
    /// for `AUTO_FUZZY` explicitly.
    #[test]
    fn a_boolean_honours_the_fuzzy_tolerance() {
        let backend = OcctBackend::new();
        let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let b = backend
            .place(
                &backend.make_box(10.0, 10.0, 10.0).unwrap(),
                &Placement {
                    base: Vector3::new(10.0 + 1e-4, 0.0, 0.0),
                    rotation: Rotation::identity(),
                },
            )
            .unwrap();

        let exact = backend.fuse(&a, &b, 0.0).unwrap();
        assert_eq!(
            backend.elements(&exact.shape, ElementKind::Solid).len(),
            2,
            "a 1e-4 gap is wider than the confusion tolerance"
        );

        let fuzzy = backend.fuse(&a, &b, 1e-2).unwrap();
        assert_eq!(
            backend.elements(&fuzzy.shape, ElementKind::Solid).len(),
            1,
            "a fuzzy value wider than the gap bridges it"
        );

        // The automatic value for these bounds is ~2.5e-6, so it does not bridge it.
        let auto = backend.fuse(&a, &b, ferrocad_geom::AUTO_FUZZY).unwrap();
        assert_eq!(
            backend.elements(&auto.shape, ElementKind::Solid).len(),
            2,
            "the automatic value is measured from the bounds"
        );
    }

    #[test]
    fn a_general_fuse_reports_images_of_its_own_result() {
        let backend = OcctBackend::new();
        let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let b = backend
            .place(
                &backend.make_box(10.0, 10.0, 10.0).unwrap(),
                &Placement {
                    base: Vector3::new(5.0, 0.0, 0.0),
                    rotation: Rotation::identity(),
                },
            )
            .unwrap();
        // An edge as an argument of its own: the fuse cuts it where the other box
        // crosses it, and reports the pieces.
        let edge = backend.elements(&a, ElementKind::Edge)[0].shape.clone();

        let (result, split) = backend
            .general_fuse(&[a.clone(), b, edge], 0.0)
            .unwrap();
        assert_eq!(split.len(), 3, "one group per input");

        // Every reported piece must be a sub-shape of the returned result, and at
        // least one input must report something: the overlap splits a face of the
        // first box.
        let mut reported = 0;
        for pieces in &split {
            for piece in pieces {
                reported += 1;
                let kind = backend.shape_type(piece).expect("a kind");
                let element_kind = ElementKind::ALL
                    .into_iter()
                    .find(|candidate| candidate.prefix() == kind)
                    .expect("a known element kind");
                let same_kind = backend.elements(&result, element_kind);
                assert!(
                    same_kind
                        .iter()
                        .any(|element| backend.same_shape(&element.shape, piece)),
                    "a reported {kind} belongs to the returned result"
                );
            }
        }
        assert!(reported > 0, "the overlap splits an input");
    }

    /// The intrinsic map of a container: every element named once, nothing else.
    ///
    /// These are upstream's `ElementMapSize` counts for the same shapes: two boxes
    /// combine to 52 names, a general-fused pair to 60, and a circle swept along a
    /// line to 6. A primitive and a compound of lower elements keep no intrinsic
    /// map; an operation result uses its own history.
    #[test]
    fn a_container_names_its_own_elements() {
        use ferrocad_geom::{Lineage, MapVersion};
        let backend = OcctBackend::new();
        let a = backend.make_box(1.0, 2.0, 2.0).unwrap();
        let b = backend.make_box(2.0, 1.0, 2.0).unwrap();

        // A primitive has no intrinsic map; an operation result gets its names from
        // the operation (even when OCCT hands it back as a compound).
        assert!(backend.intrinsic_history(&a).is_none());
        let fused = backend.fuse(&a, &b, 0.0).unwrap();
        let lineage = Lineage::from_history(&fused.history, MapVersion::default());
        assert_eq!(lineage.reverse().len(), 58, "the boolean's own history");

        // A compound of two boxes: 2 × (6 faces + 12 edges + 8 vertices).
        let compound = backend.make_compound(&[a.clone(), b.clone()]).unwrap();
        let history = backend
            .intrinsic_history(&compound)
            .expect("a compound of bodies names itself");
        assert_eq!(history.identity.len(), 52);
        assert!(history.modified.is_empty());
        assert!(history.generated.is_empty());
        assert!(history.deleted.is_empty());
        let lineage = Lineage::from_history(&history, MapVersion::default());
        assert_eq!(lineage.reverse().len(), 52);

        // A compound of lower elements is an internal container, not a body.
        let faces: Vec<Shape> = backend
            .elements(&a, ElementKind::Face)
            .into_iter()
            .map(|element| element.shape)
            .collect();
        let lower = backend.make_compound(&faces).unwrap();
        assert!(backend.intrinsic_history(&lower).is_none());

        // General fuse: the result compound names all 60 elements.
        let (result, _split) = backend
            .general_fuse(&[a.clone(), b.clone()], 0.0)
            .unwrap();
        let history = backend
            .intrinsic_history(&result)
            .expect("the result names itself");
        assert_eq!(history.identity.len(), 60);

        // A sweep names its six elements (one face, three edges, two vertices).
        use ferrocad_curves::{Circle, LineSegment};
        let profile = backend
            .make_edge(&ferrocad_curves::EdgeCurve::Circle(
                Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 5.0).unwrap(),
            ))
            .unwrap();
        let spine = backend
            .make_edge(&ferrocad_curves::EdgeCurve::LineSegment(
                LineSegment::new(Vector3::zero(), Vector3::new(0.0, 0.0, 10.0)).unwrap(),
            ))
            .unwrap();
        let sweep = backend.make_pipe(&spine, &profile, 0.001).unwrap();
        assert_eq!(backend.name_every_element(&sweep).identity.len(), 6);
    }

    #[test]
    fn a_refine_keeps_every_name_it_does_not_merge() {
        let backend = OcctBackend::new();
        let (a, b) = overlapping_boxes(&backend);
        let fused = backend.fuse(&a, &b, 0.0).unwrap();

        let refined = backend.refine(&fused.shape).expect("the backend refines");
        assert!(
            !refined.shape.is_same(&fused.shape),
            "the unifier rebuilds the shape even when it merges nothing"
        );
        assert!(
            refined.history.modified.is_empty() && refined.history.generated.is_empty(),
            "a refine is nothing but identity and deletion"
        );
        assert!(
            refined.history.deleted.is_empty(),
            "no two faces of this fuse are coplanar, so nothing is merged"
        );
        assert_eq!(
            refined.history.identity.len(),
            ["Face", "Edge", "Vertex"]
                .into_iter()
                .map(|kind| backend.count_sub_shapes(&fused.shape, kind).unwrap())
                .sum::<usize>(),
            "every face, edge and vertex keeps its name"
        );
        assert!(
            !refined.history.identity.is_empty(),
            "matching is geometric, so a rebuilt face still keeps its name"
        );
    }

    #[test]
    fn fuse_reports_both_operands_and_all_three_kinds() {
        let backend = OcctBackend::new();
        let (a, b) = overlapping_boxes(&backend);
        let out = backend.fuse(&a, &b, 0.0).unwrap();

        assert_eq!(
            counts(&out.history),
            expected(&[
                (OperandId::A, "Face", Relation::Modified, 3),
                (OperandId::A, "Edge", Relation::Modified, 3),
                (OperandId::A, "Vertex", Relation::Deleted, 1),
                (OperandId::B, "Face", Relation::Modified, 3),
                (OperandId::B, "Edge", Relation::Modified, 3),
                (OperandId::B, "Vertex", Relation::Deleted, 1),
            ]),
        );
        assert!(
            out.history.generated.is_empty(),
            "fuse generates no new elements"
        );

        assert_histories_are_coherent(
            &backend,
            [(&a, OperandId::A), (&b, OperandId::B)],
            &out.shape,
            &out.history,
        );

        // Identity is canonical: the side table is sorted even though the relation
        // lists stay in reporting order.
        let mut sorted = out.history.provenance.clone();
        sorted.sort();
        assert_eq!(sorted, out.history.provenance);
    }

    #[test]
    fn cut_reports_both_operands_and_all_three_kinds() {
        let backend = OcctBackend::new();
        let (a, b) = overlapping_boxes(&backend);
        let out = backend.cut(&a, &b, 0.0).unwrap();

        assert_eq!(
            counts(&out.history),
            expected(&[
                (OperandId::A, "Face", Relation::Modified, 3),
                (OperandId::A, "Edge", Relation::Modified, 3),
                (OperandId::A, "Vertex", Relation::Deleted, 1),
                // The tool contributes the new walls; the rest of it is consumed.
                (OperandId::B, "Face", Relation::Modified, 3),
                (OperandId::B, "Face", Relation::Deleted, 3),
                (OperandId::B, "Edge", Relation::Modified, 3),
                (OperandId::B, "Edge", Relation::Deleted, 9),
                (OperandId::B, "Vertex", Relation::Deleted, 7),
            ]),
        );
        assert!(
            out.history.generated.is_empty(),
            "cut generates no new elements"
        );

        assert_histories_are_coherent(
            &backend,
            [(&a, OperandId::A), (&b, OperandId::B)],
            &out.shape,
            &out.history,
        );
    }

    #[test]
    fn the_same_boolean_twice_yields_the_same_history() {
        let backend = OcctBackend::new();
        let (a, b) = overlapping_boxes(&backend);

        for (first, second) in [
            (backend.fuse(&a, &b, 0.0).unwrap(), backend.fuse(&a, &b, 0.0).unwrap()),
            (backend.cut(&a, &b, 0.0).unwrap(), backend.cut(&a, &b, 0.0).unwrap()),
        ] {
            assert_eq!(
                first.history.provenance, second.history.provenance,
                "identity is deterministic",
            );
            assert_eq!(
                relation_names(&first.history),
                relation_names(&second.history),
                "the relation lists are deterministic",
            );
        }
    }
}

#[cfg(test)]
mod curve_bridge_tests {
    //! The analytic curve helpers behind `Part.Circle`/`Part.Ellipse` and the
    //! explicit-knot `Part.BSplineCurve`: round-trip the OCCT side without
    //! involving the Python binding.

    use ferrocad_curves::{EdgeCurve, Ellipse, Vector3};
    use ferrocad_geom::GeometryBackend;

    use super::*;

    /// The layout `fc_bspline_push_state` writes.
    const DEGREE: usize = 0;
    const NB_POLES: usize = 2;
    const NB_KNOTS: usize = 3;
    const PERIODIC: usize = 4;
    const FIRST_PARAMETER: usize = 12;
    const LAST_PARAMETER: usize = 13;
    const CONTINUITY: usize = 16;

    #[test]
    fn an_ellipse_round_trips_through_an_edge() {
        let backend = OcctBackend::new();
        let ellipse = Ellipse::with_axis(
            Vector3::new(1.0, 2.0, 3.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(1.0, 0.0, 0.0),
            5.0,
            3.0,
        )
        .unwrap();
        let edge = backend
            .make_edge(&EdgeCurve::Ellipse(ellipse))
            .expect("an ellipse has an OCCT edge");

        let EdgeCurve::Ellipse(back) = backend.curve_of(&edge).unwrap() else {
            panic!("the ellipse edge's basis curve is an ellipse");
        };
        assert!((back.center().sub(&ellipse.center())).length() < 1e-9);
        assert!((back.major_radius() - 5.0).abs() < 1e-9);
        assert!((back.minor_radius() - 3.0).abs() < 1e-9);
        assert!((back.normal().sub(&ellipse.normal())).length() < 1e-9);
        assert!((back.x_axis().sub(&ellipse.x_axis())).length() < 1e-9);
    }

    /// The upstream `PartTestBSplineCurve` NURBS: four poles and the knots
    /// `(0, 0.5, 1)` with multiplicities `(3, 1, 3)` at degree 2.
    fn upstream_nurbs_poles() -> [Vector3; 4] {
        [
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(2.0, 0.0, 0.0),
            Vector3::new(1.0, -1.0, 0.0),
        ]
    }

    #[test]
    fn an_explicit_knot_vector_reads_back_from_occt() {
        let backend = OcctBackend::new();
        let poles = upstream_nurbs_poles();
        let state = backend
            .bspline_state(
                &poles,
                &[1.0; 4],
                &[0.0, 0.5, 1.0],
                &[3, 1, 3],
                2,
                false,
                true,
            )
            .expect("the upstream NURBS builds");

        assert_eq!(state.degree, 2);
        assert_eq!(state.poles.len(), 4);
        assert_eq!(state.knots.len(), 3);
        assert!(!state.periodic);
        assert_eq!(state.first_parameter, 0.0);
        assert_eq!(state.last_parameter, 1.0);
        assert_eq!(state.continuity, 2, "C1 at the inner knot (mult 1, degree 2)");

        // The same arrays also build the edge, exactly.
        let edge = backend
            .make_bspline_poles_mults_knots(
                &poles,
                &[1.0; 4],
                &[0.0, 0.5, 1.0],
                &[3, 1, 3],
                2,
                false,
                true,
            )
            .expect("the explicit B-spline has an edge");
        assert!(
            matches!(backend.curve_of(&edge), Ok(EdgeCurve::BSplineCurve(_))),
            "a B-spline now reports its poles, weights and knots"
        );
        assert_eq!(backend.elements(&edge, ElementKind::Edge).len(), 1);
    }

    #[test]
    fn the_periodic_conversion_restructures_the_curve() {
        let backend = OcctBackend::new();
        let poles = [
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(2.0, 0.0, 0.0),
        ];
        let state = backend
            .bspline_state(&poles, &[1.0; 3], &[0.0, 1.0], &[3, 3], 2, false, true)
            .expect("the clamped quadratic builds");
        assert!(!state.periodic);
        assert_eq!(state.poles.len(), 3);

        // `SetPeriodic` is a structural change (the curve is not closed, so OCCT
        // drops the redundant pole); the state must come from OCCT, not from a
        // flag flip.
        let periodic = backend
            .bspline_periodic_state(
                &poles,
                &[1.0; 3],
                &[0.0, 1.0],
                &[3, 3],
                2,
                false,
                true,
                true,
            )
            .expect("SetPeriodic succeeds");
        assert!(periodic.periodic);
        assert_eq!(periodic.poles.len(), 2);
    }

    #[test]
    fn a_periodic_bspline_round_trips_through_an_edge() {
        use std::f64::consts::TAU;

        let backend = OcctBackend::new();
        // OCCT's own form for a full circle after `BRepBuilderAPI_NurbsConvert`:
        // three rational quadratic arcs, each knot doubled, period `2Ï€`.
        let step = TAU / 3.0;
        let poles = [
            Vector3::new(5.0, 0.0, 10.0),
            Vector3::new(5.0, 8.660_254_037_844_387, 10.0),
            Vector3::new(-2.5, 4.330_127_018_922_193, 10.0),
            Vector3::new(-10.0, 0.0, 10.0),
            Vector3::new(-2.5, -4.330_127_018_922_193, 10.0),
            Vector3::new(5.0, -8.660_254_037_844_387, 10.0),
        ];
        let weights = [1.0, 0.5, 1.0, 0.5, 1.0, 0.5];
        let knots = [0.0, step, 2.0 * step, TAU];
        let mults = [2, 2, 2, 2];

        let edge = backend
            .make_bspline_poles_mults_knots(&poles, &weights, &knots, &mults, 2, true, true)
            .expect("a periodic spline has an edge");
        let EdgeCurve::BSplineCurve(curve) = backend.curve_of(&edge).unwrap() else {
            panic!("a periodic spline reports its B-spline form");
        };
        assert!(curve.is_periodic());
        assert_eq!(curve.degree(), 2);
        assert_eq!(curve.poles().len(), 6);
        assert_eq!(curve.weights(), &weights[..]);
        assert_eq!(curve.knots(), &knots[..]);
        assert_eq!(curve.mults(), &mults[..]);
        assert!((curve.first() - 0.0).abs() < 1e-12);
        assert!((curve.last() - TAU).abs() < 1e-12);

        // Parameter 0 is the joint at `+X`; the period end returns to it.
        let start = curve.point_at(0.0).unwrap();
        assert!((start.sub(&Vector3::new(5.0, 0.0, 10.0))).length() < 1e-9);
        assert!((curve.point_at(TAU).unwrap().sub(&start)).length() < 1e-9);

        // `make_edge` rebuilds the same periodic curve, not a clamped copy.
        let rebuilt = backend
            .make_edge(&EdgeCurve::BSplineCurve(curve.clone()))
            .expect("the periodic curve has an edge");
        let EdgeCurve::BSplineCurve(back) = backend.curve_of(&rebuilt).unwrap() else {
            panic!("the rebuilt edge still reports a B-spline");
        };
        assert!(back.is_periodic());
        assert_eq!(back.poles().len(), 6);
        for parameter in [0.0, 0.4, 1.7, 4.2, TAU - 0.1] {
            let point = back.point_at(parameter).unwrap();
            assert!(
                point.sub(&curve.point_at(parameter).unwrap()).length() < 1e-9,
                "the rebuilt curve moved at {parameter}"
            );
            let radius = (point.x * point.x + point.y * point.y).sqrt();
            assert!((radius - 5.0).abs() < 1e-9);
        }
    }

    #[test]
    fn the_resolution_is_reported_by_occt() {
        let backend = OcctBackend::new();
        let poles = upstream_nurbs_poles();
        let resolution = backend
            .bspline_resolution(
                &poles,
                &[1.0; 4],
                &[0.0, 0.5, 1.0],
                &[3, 1, 3],
                2,
                false,
                true,
                0.5,
            )
            .expect("the resolution is finite");
        assert!(resolution > 0.0);
    }
}

#[cfg(test)]
mod shape_query_tests {
    //! The `Shape.countElement`/`Edge.Degenerated`/`Edge.isSeam`/
    //! `ParameterRange`/`Shape.isEqual` backend queries, against real OCCT
    //! primitives.

    use std::f64::consts::TAU;

    use ferrocad_geom::{ElementKind, GeometryBackend};

    use super::*;

    fn box_shape() -> Shape {
        OcctBackend::new().make_box(2.0, 3.0, 4.0).expect("a box")
    }

    #[test]
    fn count_element_counts_a_boxes_topology() {
        let backend = OcctBackend::new();
        let shape = box_shape();

        assert_eq!(backend.count_sub_shapes(&shape, "Face").unwrap(), 6);
        assert_eq!(backend.count_sub_shapes(&shape, "Edge").unwrap(), 12);
        assert_eq!(backend.count_sub_shapes(&shape, "Vertex").unwrap(), 8);
        assert_eq!(backend.count_sub_shapes(&shape, "Solid").unwrap(), 1);
        assert_eq!(backend.count_sub_shapes(&shape, "Shell").unwrap(), 1);
        assert_eq!(backend.count_sub_shapes(&shape, "Compound").unwrap(), 0);
        assert_eq!(backend.count_sub_shapes(&shape, "CompSolid").unwrap(), 0);

        // Upstream matches a prefix of the spelling.
        assert_eq!(backend.count_sub_shapes(&shape, "Faces").unwrap(), 6);
        // `SubShape` is the direct children, here the one solid.
        assert_eq!(backend.count_sub_shapes(&shape, "SubShape").unwrap(), 1);
        // An unknown spelling counts zero, as upstream's silent type lookup.
        assert_eq!(backend.count_sub_shapes(&shape, "Bogus").unwrap(), 0);
    }

    #[test]
    fn a_cone_apex_has_a_degenerate_edge() {
        let backend = OcctBackend::new();
        let cone = backend
            .make_cone(5.0, 0.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
            .expect("a cone with an apex");

        let edges = backend.elements(&cone, ElementKind::Edge);
        assert!(
            edges
                .iter()
                .any(|edge| backend.is_degenerate(&edge.shape).unwrap()),
            "the apex edge collapses to a point"
        );

        let box_shape = box_shape();
        assert!(
            backend
                .elements(&box_shape, ElementKind::Edge)
                .iter()
                .all(|edge| !backend.is_degenerate(&edge.shape).unwrap()),
            "a box has no degenerate edge"
        );
    }

    #[test]
    fn a_cylinder_seam_is_closed_on_its_face() {
        let backend = OcctBackend::new();
        let cylinder = backend
            .make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
            .expect("a cylinder");
        let edges = backend.elements(&cylinder, ElementKind::Edge);
        let faces = backend.elements(&cylinder, ElementKind::Face);

        assert!(
            edges.iter().any(|edge| faces
                .iter()
                .any(|face| backend.is_seam(&edge.shape, &face.shape).unwrap())),
            "a full cylinder has a seam edge"
        );

        let box_shape = box_shape();
        let box_edges = backend.elements(&box_shape, ElementKind::Edge);
        let box_faces = backend.elements(&box_shape, ElementKind::Face);
        assert!(
            box_edges.iter().all(|edge| box_faces
                .iter()
                .all(|face| !backend.is_seam(&edge.shape, &face.shape).unwrap())),
            "a box has no seam edge"
        );
    }

    #[test]
    fn parameter_ranges_match_the_face_and_edge_geometry() {
        let backend = OcctBackend::new();
        let cylinder = backend
            .make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
            .expect("a cylinder");
        let face = backend.elements(&cylinder, ElementKind::Face)[0]
            .shape
            .clone();
        let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();
        assert!((u1 - u0 - TAU).abs() < 1e-6, "a full turn in U");
        assert!((v1 - v0 - 10.0).abs() < 1e-6, "the cylinder's height in V");

        let box_shape = box_shape();
        let edge = backend.elements(&box_shape, ElementKind::Edge)[0]
            .shape
            .clone();
        let (first, last) = backend.edge_parameter_range(&edge).unwrap();
        assert!(first.is_finite() && last.is_finite());
        assert!(
            [2.0, 3.0, 4.0]
                .iter()
                .any(|length| ((last - first) - length).abs() < 1e-9),
            "a box edge spans one of the box's dimensions: {first}..{last}"
        );
    }

    #[test]
    fn is_equal_requires_the_same_orientation() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();

        // A separate handle around the same TShape, location and orientation.
        let same = {
            let occt = downcast(&box_shape).unwrap();
            let guard = occt.borrow();
            erase(guard.as_ref().unwrap())
        };
        assert!(backend.is_equal(&box_shape, &same).unwrap());

        let reversed = backend.reversed(&box_shape).unwrap();
        assert!(
            backend.same_shape(&box_shape, &reversed),
            "reversing changes orientation only"
        );
        assert!(
            !backend.is_equal(&box_shape, &reversed).unwrap(),
            "isEqual sees the orientation difference"
        );
    }

    #[test]
    fn a_copy_has_a_new_tshape_and_the_same_geometry() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();
        let copy = backend.copy_shape(&box_shape).expect("a deep copy");

        assert!(!backend.same_shape(&box_shape, &copy), "a new TShape");
        assert!(!backend.is_equal(&box_shape, &copy).unwrap());
        let original = backend.mass_properties(&box_shape).expect("box mass");
        let copied = backend.mass_properties(&copy).expect("copy mass");
        assert!(
            (original.volume - copied.volume).abs() < 1e-9,
            "the copy has the same volume"
        );
        assert!(
            (original.area - copied.area).abs() < 1e-9,
            "the copy has the same area"
        );
    }

    #[test]
    fn the_shape_hash_follows_is_same_not_orientation() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();
        let hash = backend.shape_hash(&box_shape).unwrap();

        // Another handle around the same TShape hashes the same.
        let same = {
            let occt = downcast(&box_shape).unwrap();
            let guard = occt.borrow();
            erase(guard.as_ref().unwrap())
        };
        assert_eq!(backend.shape_hash(&same).unwrap(), hash);

        // Orientation is not part of `IsSame`, so it is not part of the hash.
        let reversed = backend.reversed(&box_shape).unwrap();
        assert_eq!(backend.shape_hash(&reversed).unwrap(), hash);

        // A deep copy is a different TShape and hashes differently.
        let copy = backend.copy_shape(&box_shape).unwrap();
        assert_ne!(backend.shape_hash(&copy).unwrap(), hash);
    }
}

#[cfg(test)]
mod geometry_query_tests {
    //! The closest-point, closedness, tolerance and parameter-evaluation
    //! queries (`Shape.distToShape`/`isClosed`/`getTolerance`, `Edge.valueAt`
    //! and `Face.valueAt`) against real OCCT primitives.

    use std::f64::consts::{FRAC_PI_2, PI};

    use ferrocad_curves::LineSegment;
    use ferrocad_geom::{ElementKind, GeometryBackend};
    use ferrocad_types::{Placement, Rotation};

    use super::*;

    fn placed_box(offset: Vector3) -> Shape {
        let backend = OcctBackend::new();
        backend
            .place(
                &backend.make_box(2.0, 2.0, 2.0).expect("a box"),
                &Placement {
                    base: offset,
                    rotation: Rotation::identity(),
                },
            )
            .expect("a placed box")
    }

    fn box_shape() -> Shape {
        OcctBackend::new().make_box(2.0, 3.0, 4.0).expect("a box")
    }

    /// A planar rectangular face on `z = 0`, from `(0, 0)` to `(width, height)`.
    fn rectangle_face(width: f64, height: f64) -> Shape {
        let backend = OcctBackend::new();
        let corners = [
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(width, 0.0, 0.0),
            Vector3::new(width, height, 0.0),
            Vector3::new(0.0, height, 0.0),
        ];
        let mut edges = Vec::with_capacity(4);
        for i in 0..4 {
            let segment =
                LineSegment::new(corners[i], corners[(i + 1) % 4]).expect("a rectangle side");
            edges.push(
                backend
                    .make_edge(&EdgeCurve::LineSegment(segment))
                    .expect("an edge"),
            );
        }
        let wire = backend.make_wire(&edges).expect("a wire");
        backend.make_face(&[wire]).expect("a face")
    }

    fn close(a: Vector3, b: Vector3) -> bool {
        a.distance(&b) < 1e-7
    }

    // --- dist_to_shape ---------------------------------------------------

    #[test]
    fn two_boxes_five_apart_report_the_gap_and_its_endpoints() {
        let backend = OcctBackend::new();
        let first = placed_box(Vector3::zero());
        let second = placed_box(Vector3::new(7.0, 0.0, 0.0));
        let result = backend.dist_to_shape(&first, &second).unwrap();

        assert!((result.distance - 5.0).abs() < 1e-9, "{}", result.distance);
        assert!(close(
            result.first,
            Vector3::new(2.0, result.first.y, result.first.z)
        ));
        assert!(close(
            result.second,
            Vector3::new(7.0, result.first.y, result.first.z)
        ));
        assert!((result.first.distance(&result.second) - 5.0).abs() < 1e-9);
    }

    #[test]
    fn intersecting_boxes_are_zero_apart() {
        let backend = OcctBackend::new();
        let first = placed_box(Vector3::zero());
        let second = placed_box(Vector3::new(1.0, 1.0, 1.0));
        let result = backend.dist_to_shape(&first, &second).unwrap();

        assert!(result.distance.abs() < 1e-9, "{}", result.distance);
        assert!(close(result.first, result.second));
    }

    #[test]
    fn a_vertex_and_a_face_report_both_closest_points() {
        let backend = OcctBackend::new();
        let face = rectangle_face(2.0, 3.0);
        let vertex = backend
            .make_vertex(Vector3::new(1.0, 1.5, 5.0))
            .expect("a vertex");

        let result = backend.dist_to_shape(&vertex, &face).unwrap();
        assert!((result.distance - 5.0).abs() < 1e-9, "{}", result.distance);
        assert!(
            close(result.first, Vector3::new(1.0, 1.5, 5.0)),
            "{:?}",
            result.first
        );
        assert!(
            close(result.second, Vector3::new(1.0, 1.5, 0.0)),
            "{:?}",
            result.second
        );

        // The pair follows the operand order, so swapping swaps the points.
        let swapped = backend.dist_to_shape(&face, &vertex).unwrap();
        assert!(close(swapped.first, result.second));
        assert!(close(swapped.second, result.first));
        assert!((swapped.distance - result.distance).abs() < 1e-9);
    }

    // --- is_closed -------------------------------------------------------

    #[test]
    fn a_box_solid_is_closed() {
        let backend = OcctBackend::new();
        assert!(backend.is_closed(&box_shape()).unwrap());
    }

    #[test]
    fn an_open_shell_and_a_bare_face_are_not_closed() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();
        let face = backend.elements(&box_shape, ElementKind::Face)[0]
            .shape
            .clone();
        assert!(!backend.is_closed(&face).unwrap(), "a bare face is open");

        let open_shell = backend
            .make_shell(std::slice::from_ref(&face))
            .expect("a one-face shell");
        assert!(
            !backend.is_closed(&open_shell).unwrap(),
            "one face leaves free boundaries"
        );
    }

    #[test]
    fn a_wire_and_an_edge_are_closed_when_they_have_no_free_ends() {
        let backend = OcctBackend::new();

        let circle =
            Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 2.0).expect("a circle");
        let circle_edge = backend
            .make_edge(&EdgeCurve::Circle(circle))
            .expect("a circle edge");
        assert!(
            backend.is_closed(&circle_edge).unwrap(),
            "a circle edge closes on itself"
        );
        let closed_wire = backend
            .make_wire(std::slice::from_ref(&circle_edge))
            .expect("a circle wire");
        assert!(backend.is_closed(&closed_wire).unwrap());

        let segment =
            LineSegment::new(Vector3::zero(), Vector3::new(1.0, 0.0, 0.0)).expect("a segment");
        let segment_edge = backend
            .make_edge(&EdgeCurve::LineSegment(segment))
            .expect("a segment edge");
        assert!(!backend.is_closed(&segment_edge).unwrap());
        let open_wire = backend
            .make_wire(std::slice::from_ref(&segment_edge))
            .expect("a segment wire");
        assert!(!backend.is_closed(&open_wire).unwrap());
    }

    #[test]
    fn a_cylinders_shell_is_closed() {
        let backend = OcctBackend::new();
        let cylinder = backend
            .make_cylinder(5.0, 10.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
            .expect("a cylinder");
        let shells = backend.elements(&cylinder, ElementKind::Shell);
        assert_eq!(shells.len(), 1);
        assert!(backend.is_closed(&shells[0].shape).unwrap());
    }

    // --- shape_tolerance -------------------------------------------------

    #[test]
    fn a_fresh_box_reports_a_positive_kernel_tolerance() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();
        let tolerance = backend.shape_tolerance(&box_shape).unwrap();
        assert!(tolerance.is_finite() && tolerance > 0.0, "{tolerance}");

        for kind in [ElementKind::Vertex, ElementKind::Edge, ElementKind::Face] {
            let element = &backend.elements(&box_shape, kind)[0].shape;
            let tolerance = backend.shape_tolerance(element).unwrap();
            assert!(
                tolerance.is_finite() && tolerance > 0.0,
                "{kind:?}: {tolerance}"
            );
        }
    }

    // --- value_at --------------------------------------------------------

    #[test]
    fn a_box_edge_maps_its_parameter_endpoints_to_vertices() {
        let backend = OcctBackend::new();
        let unit = backend.make_box(1.0, 1.0, 1.0).expect("a unit box");
        let edge = backend.elements(&unit, ElementKind::Edge)[0].shape.clone();
        let (first, last) = backend.edge_parameter_range(&edge).unwrap();
        let start = backend.edge_value_at(&edge, first).unwrap();
        let end = backend.edge_value_at(&edge, last).unwrap();

        let vertices: Vec<Vector3> = backend
            .elements(&unit, ElementKind::Vertex)
            .iter()
            .map(|vertex| backend.vertex_point(&vertex.shape).expect("a vertex point"))
            .collect();
        assert!(
            vertices.iter().any(|vertex| close(*vertex, start)),
            "{start:?}"
        );
        assert!(vertices.iter().any(|vertex| close(*vertex, end)), "{end:?}");
        assert!((start.distance(&end) - 1.0).abs() < 1e-9);

        // A line's parameter is arc length, so the midpoint is the midpoint.
        let middle = backend.edge_value_at(&edge, 0.5 * (first + last)).unwrap();
        let expected = start.add(&end).scale(0.5);
        assert!(close(middle, expected), "{middle:?} != {expected:?}");
    }

    #[test]
    fn a_plane_face_evaluates_the_expected_point() {
        let backend = OcctBackend::new();
        let face = rectangle_face(2.0, 3.0);
        let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();

        // A plane is affine in (u, v), so the middle of the parameter bounds is
        // the middle of the rectangle.
        let center = backend
            .face_value_at(&face, 0.5 * (u0 + u1), 0.5 * (v0 + v1))
            .unwrap();
        assert!(close(center, Vector3::new(1.0, 1.5, 0.0)), "{center:?}");

        let corners = [
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(2.0, 0.0, 0.0),
            Vector3::new(2.0, 3.0, 0.0),
            Vector3::new(0.0, 3.0, 0.0),
        ];
        for (u, v) in [(u0, v0), (u1, v0), (u1, v1), (u0, v1)] {
            let point = backend.face_value_at(&face, u, v).unwrap();
            assert!(
                corners.iter().any(|corner| close(*corner, point)),
                "{point:?} is not a rectangle corner"
            );
        }
    }

    #[test]
    fn a_sphere_face_evaluates_its_parameters_and_poles() {
        let backend = OcctBackend::new();
        let radius = 2.0;
        let sphere = backend
            .make_sphere(radius, Vector3::zero())
            .expect("a sphere");
        let face = backend.elements(&sphere, ElementKind::Face)[0]
            .shape
            .clone();
        let (u0, u1, v0, v1) = backend.face_parameter_range(&face).unwrap();

        // `Geom_SphericalSurface`: P(u, v) = R * (cos v cos u, cos v sin u, sin v)
        // with u in [0, 2*pi] and v in [-pi/2, pi/2].
        assert!((u0 - 0.0).abs() < 1e-9, "u0 = {u0}");
        assert!((u1 - 2.0 * PI).abs() < 1e-9, "u1 = {u1}");
        assert!((v0 + FRAC_PI_2).abs() < 1e-9, "v0 = {v0}");
        assert!((v1 - FRAC_PI_2).abs() < 1e-9, "v1 = {v1}");

        // (0, 0) is on the equator, on the surface's X axis.
        let equator = backend.face_value_at(&face, 0.0, 0.0).unwrap();
        assert!(
            close(equator, Vector3::new(radius, 0.0, 0.0)),
            "{equator:?}"
        );

        // Every u at v = +pi/2 is the north pole, every u at v = -pi/2 the south.
        let north = backend.face_value_at(&face, 0.0, v1).unwrap();
        assert!(close(north, Vector3::new(0.0, 0.0, radius)), "{north:?}");
        let south = backend.face_value_at(&face, PI, v0).unwrap();
        assert!(close(south, Vector3::new(0.0, 0.0, -radius)), "{south:?}");
    }

    #[test]
    fn value_at_rejects_the_wrong_shape_type() {
        let backend = OcctBackend::new();
        let box_shape = box_shape();
        let face = backend.elements(&box_shape, ElementKind::Face)[0]
            .shape
            .clone();
        let edge = backend.elements(&box_shape, ElementKind::Edge)[0]
            .shape
            .clone();

        let error = backend.edge_value_at(&face, 0.0).unwrap_err();
        assert!(matches!(
            error.downcast_ref::<OcctError>(),
            Some(OcctError::InvalidInput { .. })
        ));

        let error = backend.face_value_at(&edge, 0.0, 0.0).unwrap_err();
        assert!(matches!(
            error.downcast_ref::<OcctError>(),
            Some(OcctError::InvalidInput { .. })
        ));
    }

    // --- surface_data ----------------------------------------------------

    /// The `(u, v)` a surface's own frame assigns to `point`, matching the
    /// formulas `Part.Plane`/`Cylinder`/`Sphere.parameter` use.
    fn parameters(surface: &SurfaceData, point: Vector3) -> (f64, f64) {
        match surface {
            SurfaceData::Plane {
                origin,
                x_dir,
                y_dir,
                ..
            } => {
                let offset = point.sub(origin);
                (offset.dot(x_dir), offset.dot(y_dir))
            }
            SurfaceData::Cylinder {
                origin,
                axis,
                x_dir,
                direct,
                ..
            } => {
                let offset = point.sub(origin);
                let mut y_dir = axis.cross(x_dir);
                if !direct {
                    y_dir = y_dir.neg();
                }
                let mut u = offset.dot(&y_dir).atan2(offset.dot(x_dir));
                if u < 0.0 {
                    u += std::f64::consts::TAU;
                }
                (u, offset.dot(axis))
            }
            SurfaceData::Sphere {
                center,
                axis,
                x_dir,
                radius,
                direct,
            } => {
                let offset = point.sub(center);
                let mut y_dir = axis.cross(x_dir);
                if !direct {
                    y_dir = y_dir.neg();
                }
                let mut u = offset.dot(&y_dir).atan2(offset.dot(x_dir));
                if u < 0.0 {
                    u += std::f64::consts::TAU;
                }
                let v = (offset.dot(axis) / radius).clamp(-1.0, 1.0).asin();
                (u, v)
            }
            SurfaceData::Cone {
                origin,
                axis,
                x_dir,
                semi_angle,
                direct,
                ..
            } => {
                let offset = point.sub(origin);
                let mut y_dir = axis.cross(x_dir);
                if !direct {
                    y_dir = y_dir.neg();
                }
                let axial = offset.dot(axis);
                let radial = offset.sub(&axis.scale(axial));
                let mut u = radial.dot(&y_dir).atan2(radial.dot(x_dir));
                if u < 0.0 {
                    u += std::f64::consts::TAU;
                }
                (u, axial / semi_angle.cos())
            }
            SurfaceData::Torus {
                center,
                axis,
                x_dir,
                major_radius,
                direct,
                minor_radius: _,
            } => {
                let offset = point.sub(center);
                let mut y_dir = axis.cross(x_dir);
                if !direct {
                    y_dir = y_dir.neg();
                }
                let height = offset.dot(axis);
                let radial = offset.sub(&axis.scale(height));
                let mut u = radial.dot(&y_dir).atan2(radial.dot(x_dir));
                if u < 0.0 {
                    u += std::f64::consts::TAU;
                }
                let v = height.atan2(radial.length() - major_radius);
                (u, v)
            }
            SurfaceData::Other { .. } => panic!("a classified surface was expected"),
        }
    }

    #[test]
    fn a_box_face_is_a_plane_and_parameter_round_trips_exactly() {
        let backend = OcctBackend::new();
        let shape = box_shape();
        let face = backend.elements(&shape, ElementKind::Face)[0]
            .shape
            .clone();
        let surface = backend.surface_data(&face).expect("a box face has a surface");
        let SurfaceData::Plane {
            origin,
            x_dir,
            y_dir,
            normal,
        } = &surface
        else {
            panic!("a box face is planar, got {surface:?}");
        };

        // The frame is orthonormal and right-handed.
        assert!((x_dir.length() - 1.0).abs() < 1e-12);
        assert!((y_dir.length() - 1.0).abs() < 1e-12);
        assert!((normal.length() - 1.0).abs() < 1e-12);
        assert!(x_dir.dot(y_dir).abs() < 1e-12);
        assert!(normal.sub(&x_dir.cross(y_dir)).length() < 1e-12);

        // A point on the face's own parameter grid comes back exactly.
        let (u, v) = (0.3, 0.7);
        let point = backend.face_value_at(&face, u, v).unwrap();
        let expected = origin.add(&x_dir.scale(u)).add(&y_dir.scale(v));
        assert!(close(point, expected), "{point:?} != {expected:?}");
        let (u2, v2) = parameters(&surface, point);
        assert!((u2 - u).abs() < 1e-12, "u = {u2}");
        assert!((v2 - v).abs() < 1e-12, "v = {v2}");
        assert!(close(backend.face_value_at(&face, u2, v2).unwrap(), point));
    }

    #[test]
    fn a_cylinder_face_is_classified_and_parameter_round_trips() {
        let backend = OcctBackend::new();
        let shape = backend
            .make_cylinder(2.0, 5.0, Vector3::zero(), Vector3::new(0.0, 0.0, 1.0))
            .expect("a cylinder");
        let faces = backend.elements(&shape, ElementKind::Face);
        let (face, surface) = faces
            .iter()
            .find_map(|face| match backend.surface_data(&face.shape) {
                Some(surface @ SurfaceData::Cylinder { .. }) => {
                    Some((face.shape.clone(), surface))
                }
                _ => None,
            })
            .expect("a cylindrical lateral face");
        let SurfaceData::Cylinder {
            origin,
            axis,
            x_dir,
            radius,
            ..
        } = &surface
        else {
            unreachable!();
        };
        assert!((radius - 2.0).abs() < 1e-12);
        assert!(axis.sub(&Vector3::new(0.0, 0.0, 1.0)).length() < 1e-12);
        assert!((origin.length()).abs() < 1e-12);
        assert!(x_dir.dot(axis).abs() < 1e-12);

        for (u, v) in [(0.0, 0.5), (0.7, 2.0), (5.5, 4.0)] {
            let point = backend.face_value_at(&face, u, v).unwrap();
            let (u2, v2) = parameters(&surface, point);
            assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
            assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
            let back = backend.face_value_at(&face, u2, v2).unwrap();
            assert!(close(back, point), "{back:?} != {point:?}");
        }
    }

    #[test]
    fn a_sphere_face_is_classified_and_parameter_round_trips() {
        let backend = OcctBackend::new();
        let shape = backend
            .make_sphere(2.0, Vector3::new(1.0, 2.0, 3.0))
            .expect("a sphere");
        let face = backend.elements(&shape, ElementKind::Face)[0]
            .shape
            .clone();
        let surface = backend.surface_data(&face).expect("a sphere face has a surface");
        let SurfaceData::Sphere {
            center,
            axis,
            x_dir,
            radius,
            ..
        } = &surface
        else {
            panic!("a sphere face is spherical, got {surface:?}");
        };
        assert!((radius - 2.0).abs() < 1e-12);
        assert!(center.sub(&Vector3::new(1.0, 2.0, 3.0)).length() < 1e-12);
        assert!(axis.sub(&Vector3::new(0.0, 0.0, 1.0)).length() < 1e-12);
        assert!(x_dir.dot(axis).abs() < 1e-12);

        for (u, v) in [(0.0, 0.0), (0.8, 0.4), (4.0, -1.2)] {
            let point = backend.face_value_at(&face, u, v).unwrap();
            let (u2, v2) = parameters(&surface, point);
            assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
            assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
            let back = backend.face_value_at(&face, u2, v2).unwrap();
            assert!(close(back, point), "{back:?} != {point:?}");
        }
    }

    #[test]
    fn cone_and_torus_faces_are_classified_and_parameter_round_trips() {
        let backend = OcctBackend::new();
        let cone = backend
            .make_cone(
                2.0,
                1.0,
                4.0,
                Vector3::zero(),
                Vector3::new(0.0, 0.0, 1.0),
            )
            .expect("a cone");
        let faces = backend.elements(&cone, ElementKind::Face);
        let (face, surface) = faces
            .iter()
            .find_map(|face| match backend.surface_data(&face.shape) {
                Some(surface @ SurfaceData::Cone { .. }) => Some((face.shape.clone(), surface)),
                _ => None,
            })
            .expect("a conical face");
        let SurfaceData::Cone {
            origin,
            axis,
            x_dir,
            radius,
            semi_angle,
            ..
        } = &surface
        else {
            unreachable!();
        };
        assert!((radius - 2.0).abs() < 1e-9);
        assert!(semi_angle.is_finite() && semi_angle.abs() > 0.0);
        assert!(x_dir.dot(axis).abs() < 1e-12);
        let _ = origin;

        for (u, v) in [(0.0, 0.0), (0.8, 1.5), (4.0, 3.0)] {
            let point = backend.face_value_at(&face, u, v).unwrap();
            let (u2, v2) = parameters(&surface, point);
            assert!((u2 - u).abs() < 1e-9, "u {u} -> {u2}");
            assert!((v2 - v).abs() < 1e-9, "v {v} -> {v2}");
            let back = backend.face_value_at(&face, u2, v2).unwrap();
            assert!(close(back, point), "{back:?} != {point:?}");
        }

        // A non-face reports no surface at all.
        let edge = backend.elements(&cone, ElementKind::Edge)[0].shape.clone();
        assert!(backend.surface_data(&edge).is_none());
    }
}

#[cfg(test)]
mod tessellation_tests {
    //! Both deflections decide the mesh. OCCT only ever received the linear value,
    //! so `Shape.tessellate(deflection, angular)` ignored `angular` and every coarse
    //! deflection of a sphere produced the same 304-triangle mesh.

    use ferrocad_geom::TessellationOptions;

    use super::*;

    fn sphere() -> Shape {
        OcctBackend::new()
            .make_sphere(10.0, Vector3::new(0.0, 0.0, 0.0))
            .expect("a sphere")
    }

    fn triangle_count(linear: f64, angular: f64) -> usize {
        OcctBackend::new()
            .tessellate(
                &sphere(),
                &TessellationOptions {
                    linear_deflection: Some(linear),
                    angular_deflection: angular,
                    relative: false,
                },
            )
            .expect("a tessellation")
            .triangles
            .len()
            / 3
    }

    #[test]
    fn angular_deflection_changes_the_triangle_count() {
        // A fresh shape each time: OCCT stores the triangulation on the shape and
        // keeps it when the next request is not finer, so reusing one shape would
        // measure the cache, not the deflection.
        let coarse = triangle_count(2.0, 2.0);
        // The display mesh keeps the two degenerate pole triangles the Python
        // `tessellate` weld drops, so this is 48, not the 46 facets a script sees.
        assert!(coarse < 100, "a coarse sphere must be small, got {coarse}");
        assert!(
            triangle_count(2.0, 1.0) > coarse,
            "a smaller angular deflection must refine the mesh"
        );
        assert!(
            triangle_count(0.5, 0.2) > triangle_count(2.0, 1.0),
            "a tighter linear deflection must refine the mesh"
        );
    }

    #[test]
    fn a_non_positive_angular_deflection_is_rejected() {
        let shape = sphere();
        for angular in [0.0, -0.5, f64::NAN, std::f64::consts::PI] {
            let result = OcctBackend::new().tessellate(
                &shape,
                &TessellationOptions {
                    linear_deflection: Some(1.0),
                    angular_deflection: angular,
                    relative: false,
                },
            );
            assert!(result.is_err(), "angular {angular} must be rejected");
        }
    }
}