ferrocad_occt 0.1.4

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
//! 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_geom::{
    Capabilities, Continuity, ElementId, ElementKind, ElementRef, GeomError, GeometryBackend,
    History, Lineage, MapVersion, MassProperties, OpResult, OperandId, PrincipalProperties, Shape,
    Tessellation, TessellationOptions, unsupported,
};
use ferrocad_curves::{Arc, Circle, EdgeCurve, Ellipse, Line, Vector3};
use ferrocad_types::{Matrix4, Placement};
use opencascade_sys as ffi;

use std::collections::BTreeSet;

use ffi::top_abs::TopAbs_ShapeEnum;
use ffi::top_abs::TopAbs_Orientation;
use ffi::top_tools::TopTools_IndexedMapOfShape;
use ffi::top_tools::TopTools_ListOfShape;
use ffi::topo_ds::TopoDS_Shape;

use crate::bridge;
use crate::error::OcctError;
use crate::shape::{downcast, erase, 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 !bridge::fc_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 = bridge::fc_indexed_map_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 bridge::fc_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 edge = bridge::fc_bspline_edge(
            &coords,
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
        );
        let Some(edge) = edge.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles_mults_knots",
            }
            .into());
        };
        Ok(erase(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<Vec<f64>> {
        let coords = flatten(poles);
        let state = bridge::fc_bspline_probe(
            &coords,
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
        );
        (!state.is_empty()).then_some(state)
    }

    /// 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<Vec<f64>> {
        let state = bridge::fc_bspline_probe_interpolated(&flatten(points), periodic);
        (!state.is_empty()).then_some(state)
    }

    /// 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<Vec<f64>> {
        let state = bridge::fc_bspline_set_periodic(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            target_periodic,
        );
        (!state.is_empty()).then_some(state)
    }

    /// `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 = bridge::fc_bspline_resolution(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            tolerance,
        );
        resolution.is_finite().then_some(resolution)
    }

    /// 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> {
        let point = bridge::fc_bspline_point(
            &flatten(poles),
            weights,
            knots,
            multiplicities,
            degree,
            periodic,
            check_rational,
            u,
        );
        (point.len() == 3).then(|| Vector3::new(point[0], point[1], point[2]))
    }

    /// 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<Vec<f64>> {
        let state = bridge::fc_conic_to_spline(
            kind,
            center.x,
            center.y,
            center.z,
            normal.x,
            normal.y,
            normal.z,
            x_axis.x,
            x_axis.y,
            x_axis.z,
            major,
            minor,
            first,
            last,
            nurbs,
        );
        (!state.is_empty()).then_some(state)
    }
}

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),
        }
    }

    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 !bridge::fc_is_edge(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_wire expects edges",
                }
                .into());
            }
            make.pin_mut().add_edge(bridge::fc_shape_as_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 !bridge::fc_is_vertex(inner) {
            return None;
        }
        let pnt = ffi::b_rep::BRep_Tool_Pnt(bridge::fc_shape_as_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 = bridge::fc_bspline_from_poles(&coords, degree, periodic);
        let Some(curve) = curve.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "make_bspline_poles",
            }
            .into());
        };
        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 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 !bridge::fc_is_wire(first_inner) {
            return Err(OcctError::InvalidInput {
                what: "make_face expects wires",
            }
            .into());
        }
        let mut make = ffi::b_rep_builder_api::BRepBuilderAPI_MakeFace_wire(
            bridge::fc_shape_as_wire(first_inner),
            true,
        );
        // Adding a hole to an already-failed builder can crash OCCT, so stop as
        // soon as the outer wire does not make a face.
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_face",
            }
            .into());
        }
        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 !bridge::fc_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
            // builder subtracts its area instead of adding another outer boundary.
            let reversed = bridge::fc_reversed(inner);
            let reversed = reversed.as_ref().ok_or(OcctError::InvalidInput {
                what: "null wire",
            })?;
            make.pin_mut().add_wire(bridge::fc_shape_as_wire(reversed));
            if !make.IsDone() {
                return Err(OcctError::NotDone {
                    operation: "make_face",
                }
                .into());
            }
        }
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_face",
            }
            .into());
        }
        Ok(erase(ffi::topo_ds::cast_face_to_shape(make.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 !bridge::fc_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 = bridge::fc_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(
                bridge::fc_shape_as_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(
                bridge::fc_shape_as_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 = bridge::fc_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 = bridge::fc_general_fuse(&list);
            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) {
                    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) {
                    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 = bridge::fc_general_fuse(&list);
                    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 = bridge::fc_general_fuse(&list);
            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 surface_type(&self, shape: &Shape) -> Option<String> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !bridge::fc_is_face(inner) {
            return None;
        }
        let surface = ffi::b_rep::BRep_Tool_Surface(bridge::fc_shape_as_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 outer_wire(&self, shape: &Shape) -> Option<Shape> {
        let occt = downcast(shape).ok()?;
        let guard = occt.borrow();
        let inner = guard.as_ref()?;
        if !bridge::fc_is_face(inner) {
            return None;
        }
        let wire = ffi::b_rep_tools::outer_wire(bridge::fc_shape_as_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" })?;
        let data = bridge::fc_edge_curve(inner);
        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]);
        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 => Ok(EdgeCurve::Ellipse(Ellipse::with_axis(
                origin,
                direction,
                x_axis,
                major,
                minor,
            )?)),
            _ => Err(unsupported("curve_of: unsupported curve type")),
        }
    }

    fn fuse(&self, a: &Shape, b: &Shape) -> 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_Fuse_new(sa, sb);
        if !op.IsDone() {
            return Err(OcctError::NotDone { operation: "fuse" }.into());
        }
        let out_maps = sub_shape_maps(op.pin_mut().Shape());
        let history = build_history(
            [(OperandId::A, sa), (OperandId::B, sb)],
            &out_maps,
            |sub, mods, gens| {
                bridge::fc_brep_fuse_modified(op.pin_mut(), sub, mods.pin_mut());
                bridge::fc_brep_fuse_generated(op.pin_mut(), sub, gens.pin_mut());
                bridge::fc_brep_fuse_is_deleted(op.pin_mut(), sub)
            },
        );
        Ok(OpResult::new(erase(op.pin_mut().Shape()), history))
    }

    fn cut(&self, a: &Shape, b: &Shape) -> 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" })?;

        // Upstream's `FCBRepAlgoAPI_BooleanOperation::Build` rewrites a compound
        // cut before OCCT sees it. One operation object is reused for every
        // internal build, so its history describes the last of them — which is
        // exactly what the element map is built from.
        let mut op = bridge::fc_cut_new_op();
        // The constructor-time settings, taken from the *original* operands: the
        // fuzzy value is not recomputed for the internal fuse/cut builds.
        let initial_arguments = shape_list(&[sa]);
        let initial_tools = shape_list(&[sb]);
        bridge::fc_cut_configure(op.pin_mut(), &initial_arguments, &initial_tools);
        bridge::fc_cut_prepare(op.pin_mut());
        bridge::fc_cut_set_auto_fuzzy(op.pin_mut());

        let Some(result) = build_cut_policy(&mut op, &[sa], &[sb], CutOperation::Cut) else {
            return Err(OcctError::NotDone { operation: "cut" }.into());
        };

        let result = result.as_ref().expect("the cut result");
        let out_maps = sub_shape_maps(result);
        let history = build_history(
            [(OperandId::A, sa), (OperandId::B, sb)],
            &out_maps,
            |sub, mods, gens| {
                bridge::fc_brep_cut_modified(op.pin_mut(), sub, mods.pin_mut());
                bridge::fc_brep_cut_generated(op.pin_mut(), sub, gens.pin_mut());
                bridge::fc_brep_cut_is_deleted(op.pin_mut(), sub)
            },
        );
        Ok(OpResult::new(erase(result), history))
    }

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

    fn common(&self, a: &Shape, b: &Shape) -> 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_Common_new(sa, sb);
        if !op.IsDone() {
            return Err(OcctError::NotDone { operation: "common" }.into());
        }
        let out_maps = sub_shape_maps(op.pin_mut().Shape());
        let history = build_history(
            [(OperandId::A, sa), (OperandId::B, sb)],
            &out_maps,
            |sub, mods, gens| {
                bridge::fc_brep_common_modified(op.pin_mut(), sub, mods.pin_mut());
                bridge::fc_brep_common_generated(op.pin_mut(), sub, gens.pin_mut());
                bridge::fc_brep_common_is_deleted(op.pin_mut(), sub)
            },
        );
        Ok(OpResult::new(erase(op.pin_mut().Shape()), history))
    }

    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 = bridge::fc_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 !bridge::fc_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(
            bridge::fc_shape_as_shell(inner),
        );
        let shape = erase(make.pin_mut().Shape());
        if !make.IsDone() {
            return Err(OcctError::NotDone {
                operation: "make_solid",
            }
            .into());
        }
        Ok(shape)
    }

    fn make_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 !bridge::fc_is_face(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_shell expects faces",
                }
                .into());
            }
            builder.Add(shell.pin_mut(), inner);
        }
        Ok(erase(&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))?);
        }
        self.make_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 !bridge::fc_is_wire(inner) {
                return Err(OcctError::InvalidInput {
                    what: "make_loft expects wires",
                }
                .into());
            }
            make.pin_mut().AddWire(bridge::fc_shape_as_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 = bridge::fc_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 = bridge::fc_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 = bridge::fc_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 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 is_valid(&self, shape: &Shape) -> bool {
        let Ok(occt) = downcast(shape) else {
            return false;
        };
        let guard = occt.borrow();
        match guard.as_ref() {
            Some(inner) => bridge::fc_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 mut values = Vec::with_capacity(9);
        bridge::fc_inertia_matrix(inner, &mut values);
        if values.len() < 9 {
            return None;
        }
        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 mut values = Vec::with_capacity(17);
        bridge::fc_principal_properties(inner, &mut values);
        if values.len() < 17 {
            return None;
        }
        let axis = |offset: usize| {
            Vector3::new(values[offset], values[offset + 1], values[offset + 2])
        };
        Some(PrincipalProperties {
            symmetry_axis: values[0] != 0.0,
            symmetry_point: values[1] != 0.0,
            moments: (values[2], values[3], values[4]),
            axes: (axis(5), axis(8), axis(11)),
            radius_of_gyration: (values[14], values[15], values[16]),
        })
    }

    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 project(&self, shape: &Shape, tools: &[Shape]) -> Result<Shape, GeomError> {
        // This slice supports a planar target only, where a tool that already
        // lies in the target's plane projects onto itself. Other surfaces need
        // `BRepAlgo_NormalProjection`, which the seam does not expose yet.
        if self.surface_type(shape).as_deref() != Some("Part::GeomPlane") {
            return Err(unsupported(
                "project: only a planar target is supported (projection is the identity on it)",
            ));
        }
        if tools.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "project needs at least one tool shape",
            }
            .into());
        }
        self.make_compound(tools)
    }

    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 = bridge::fc_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 = bridge::fc_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 = bridge::fc_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 = bridge::fc_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]) -> Result<(Shape, Vec<Vec<Shape>>), GeomError> {
        if shapes.is_empty() {
            return Err(OcctError::InvalidInput {
                what: "general fuse needs at least one shape",
            }
            .into());
        }
        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 fused = bridge::fc_general_fuse(&list);
        let Some(fused) = fused.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "general_fuse",
            }
            .into());
        };
        let mut split = Vec::with_capacity(shapes.len());
        for index in 1..=shapes.len() as i32 {
            let modified = bridge::fc_general_fuse_modified(&list, index, 0.0);
            split.push(
                modified
                    .as_ref()
                    .map(|shape| top_level_parts(shape))
                    .unwrap_or_default(),
            );
        }
        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 !bridge::fc_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()?;
        let mut values = Vec::with_capacity(6);
        if !bridge::fc_optimal_box(inner, use_triangulation, use_tolerance, &mut values) {
            return None;
        }
        if values.len() < 6 {
            return None;
        }
        Some((
            Vector3::new(values[0], values[1], values[2]),
            Vector3::new(values[3], values[4], values[5]),
        ))
    }

    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)) => bridge::fc_is_same(a_inner, b_inner),
            _ => a.is_same(b),
        }
    }

    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 = bridge::fc_reversed(inner);
        let Some(reversed) = reversed.as_ref() else {
            return Err(OcctError::NotDone {
                operation: "reversed",
            }
            .into());
        };
        Ok(erase(reversed))
    }

    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 = bridge::fc_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 !bridge::fc_is_edge(inner) {
            return Err(OcctError::InvalidInput {
                what: "split_edge needs an edge",
            }
            .into());
        }
        let split = bridge::fc_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 = bridge::fc_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)
    }

    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();
        if !bridge::fc_trsf_from_matrix(&matrix.m, trsf.pin_mut()) {
            return Err(OcctError::InvalidInput {
                what: "matrix is not an affine transform",
            }
            .into());
        }
        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 result = bridge::fc_gtransform(inner, m);
        let Some(result) = result.as_ref() else {
            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)
    }
}

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

/// 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>> {
    let count = bridge::fc_shape_child_count(shape);
    (1..=count)
        .map(|index| bridge::fc_shape_child(shape, index))
        .filter(|child| !child.is_null())
        .collect()
}

/// 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);
            bridge::fc_cut_set_operation(op.pin_mut(), true);
            bridge::fc_cut_configure(op.pin_mut(), &argument_list, &tool_list);
            bridge::fc_cut_build(op.pin_mut());
            bridge::fc_cut_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);
        bridge::fc_cut_set_operation(op.pin_mut(), false);
        bridge::fc_cut_configure(op.pin_mut(), &argument_list, &tool_list);
        bridge::fc_cut_build(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);
    bridge::fc_cut_set_operation(op.pin_mut(), operation == CutOperation::Fuse);
    bridge::fc_cut_configure(op.pin_mut(), &argument_list, &tool_list);
    bridge::fc_cut_build(op.pin_mut());
    op.IsDone().then(|| owned(op.pin_mut().Shape()))
}

/// 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 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 = bridge::fc_indexed_map_find_index(out_map, 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 = bridge::fc_indexed_map_find_index(out_map, 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
}

/// 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 = bridge::fc_indexed_map_find_index(out_map, 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 = bridge::fc_indexed_map_find_index(lower_map, 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(bridge::fc_shape_as_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 = bridge::fc_indexed_map_find_index(map, 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,
    ] {
        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();
    };
    let count = bridge::fc_list_size(list);
    (1..=count)
        .map(|index| erase(bridge::fc_list_value(list, index)))
        .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 `fc_curve.hxx` 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
}

/// 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.
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 axis = ffi::gp::gp_Ax2_new(&center, &normal);
    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 = bridge::fc_ellipse_edge(
        ellipse.center().x,
        ellipse.center().y,
        ellipse.center().z,
        ellipse.normal().x,
        ellipse.normal().y,
        ellipse.normal().z,
        ellipse.x_axis().x,
        ellipse.x_axis().y,
        ellipse.x_axis().z,
        ellipse.major_radius(),
        ellipse.minor_radius(),
    );
    let Some(edge) = edge.as_ref() 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",
        );
    }

    /// 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).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()]).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 fuse_reports_both_operands_and_all_three_kinds() {
        let backend = OcctBackend::new();
        let (a, b) = overlapping_boxes(&backend);
        let out = backend.fuse(&a, &b).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).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).unwrap(), backend.fuse(&a, &b).unwrap()),
            (backend.cut(&a, &b).unwrap(), backend.cut(&a, &b).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.0);
        assert_eq!(state[NB_POLES], 4.0);
        assert_eq!(state[NB_KNOTS], 3.0);
        assert_eq!(state[PERIODIC], 0.0);
        assert_eq!(state[FIRST_PARAMETER], 0.0);
        assert_eq!(state[LAST_PARAMETER], 1.0);
        assert_eq!(state[CONTINUITY], 2.0, "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!(backend.curve_of(&edge).is_err(), "a B-spline is not analytic");
        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_eq!(state[PERIODIC], 0.0);
        assert_eq!(state[NB_POLES], 3.0);

        // `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_eq!(periodic[PERIODIC], 1.0);
        assert_eq!(periodic[NB_POLES], 2.0);
    }

    #[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);
    }
}