BREP_construction 0.35.0

Rust B-rep CAD kernel (next.BREP.io): solid construction: extrusions, revolutions, sweeps and lofts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
//! The tube route's self-trim (stage 1 and 2): where the motion carries the
//! ring back over K, K is cut along the curves where its points' depth under
//! the other poses falls to r, and only the uncovered part bounds the solid.
//!
//! K's domain is (σ, ψ), σ in [0, 4) round its four charts and ψ in [0, 2π),
//! periodic both ways. A lattice over it (aligned with the patches' sides) is
//! read for g = depth − r, depth the least distance to the core circle over
//! the poses away from the point's own time; the zero set is marched cell by
//! cell, each crossing solved on its lattice edge from exact K. Loops of the
//! zero set are returned with each point's mate: the pose and foot that reach
//! it, which name the point of K on the other side of the cut.
use super::Tube;
use crate::Vec3;

/// A point of a trim curve: where on K, where its mate is (the pose that
/// reaches it), and the 3D point.
#[derive(Clone, Copy, Debug)]
pub struct TrimPoint {
    pub sigma: f64,
    pub psi: f64,
    pub mate_time: f64,
    pub point: Vec3,
}

/// The lattice over K's domain: σ stations (each chart's chunks, `per_chunk`
/// cells each) and ψ stations (`per_quarter` cells each of four quarters).
pub struct Lattice {
    pub sigmas: Vec<f64>,
    pub psis: Vec<f64>,
    pub per_chunk: usize,
    pub per_quarter: usize,
}

impl Lattice {
    pub fn new(chunks: [usize; 4], per_chunk: usize, per_quarter: usize) -> Lattice {
        let mut sigmas = Vec::new();
        for (chart, &count) in chunks.iter().enumerate() {
            for c in 0..count {
                for k in 0..per_chunk {
                    sigmas.push(chart as f64 + (c as f64 + k as f64 / per_chunk as f64) / count as f64);
                }
            }
        }
        let quarters = 4 * per_quarter;
        let psis = (0..quarters).map(|k| std::f64::consts::TAU * k as f64 / quarters as f64).collect();
        Lattice { sigmas, psis, per_chunk, per_quarter }
    }
}

impl Tube {
    /// K at the domain point (σ, ψ), σ in [0, 4).
    pub fn k_at(&self, sigma: f64, psi: f64) -> Option<Vec3> {
        let chart = (sigma.floor() as i64).rem_euclid(4) as usize;
        self.k_point(chart, sigma - sigma.floor(), psi)
    }

    /// The time whose pose K's point (σ, ψ) belongs to.
    pub(super) fn own_time(&self, sigma: f64) -> f64 {
        let chart = (sigma.floor() as i64).rem_euclid(4) as usize;
        let s = sigma - sigma.floor();
        match chart {
            0 => self.from + (self.to - self.from) * s,
            1 => self.to,
            2 => self.to - (self.to - self.from) * s,
            _ => self.from,
        }
    }

    /// The least distance from `q` to the core circle over the poses outside
    /// (own − window, own + window), read to `tolerance` (pose intervals
    /// cleared by the speed bound or bisected), with the time that reaches it.
    pub fn far_depth(&self, q: Vec3, own: f64, window: f64, tolerance: f64) -> (f64, f64) {
        self.far_depth_until(q, own, window, tolerance, f64::NEG_INFINITY)
    }

    /// [`Tube::far_depth`], returning as soon as some pose is nearer than `stop`.
    pub fn far_depth_until(&self, q: Vec3, own: f64, window: f64, tolerance: f64, stop: f64) -> (f64, f64) {
        let speed = self.reach_speed(q);
        let mut spans: Vec<(f64, f64)> = Vec::new();
        let (a, b) = (own - window, own + window);
        if a > self.from {
            spans.push((self.from, a.min(self.to)));
        }
        if b < self.to {
            spans.push((b.max(self.from), self.to));
        }
        let mut best = (f64::INFINITY, own);
        let mut stack: Vec<(f64, f64)> = Vec::new();
        for (lo, hi) in spans {
            let count = 256usize;
            let h = (hi - lo) / count as f64;
            stack.extend((0..count).map(|k| (lo + h * k as f64, lo + h * (k + 1) as f64)));
        }
        while let Some((lo, hi)) = stack.pop() {
            let (fl, fh) = (self.reach(q, lo), self.reach(q, hi));
            if fl < best.0 {
                best = (fl, lo);
            }
            if fh < best.0 {
                best = (fh, hi);
            }
            if best.0 < stop {
                return best;
            }
            if fl.min(fh) - speed * (hi - lo) * 0.5 >= best.0 - tolerance || hi - lo <= 1e-13 * (self.to - self.from) {
                continue;
            }
            let m = 0.5 * (lo + hi);
            stack.push((lo, m));
            stack.push((m, hi));
        }
        best
    }

    /// The stretch about `own` the far reads leave out: within `window` of it,
    /// only as far as the distance keeps rising away from own (the own time's
    /// basin, stepped out by doublings from 1e-7 of the range). Near a fold the
    /// distance falls at once on the folded side, so the poses there, which
    /// hold the point, are read as competitors.
    pub fn own_basin(&self, q: Vec3, own: f64, window: f64) -> (f64, f64) {
        let range = self.to - self.from;
        // A fall counts only past the reads' rounding: at a sheet point the
        // distance is stationary at own (it rises as ½f''h², ~1e-15 at the
        // first step), so a rounding-level dip would end the basin at once and
        // leave the far read to find own itself (depth = r, a false tie).
        let noise = 1e-13 * (self.major + self.minor);
        // Each side's edge is the distance's local maximum, found exactly: the
        // doubling steps bracket it (it rose to the last step and fell at the
        // next), and a golden section on that bracket places it, so a far read
        // never lands on a cut that is not a stationary point.
        let side = |sign: f64| -> f64 {
            let mut before = 0.0f64;
            let mut last = (0.0f64, self.reach(q, own));
            let mut h = 1e-7 * range;
            // On past the window while the distance still rises (a slow pose
            // leaves the basin wide): a cut at the window is no stationary
            // point, and a far read would find its least on it. A side that
            // rises to the range's end is basin throughout.
            let _ = window;
            while h <= 2.0 * range {
                let mut t = own + sign * h;
                // A step past the range's end reads the end pose itself: the
                // basin runs to the end only if the distance still rises there,
                // else its edge lies before the end and the end pose (an end
                // torus that may hold the point) is a competitor.
                let past = t < self.from || t > self.to;
                if past {
                    let end = if sign > 0.0 { self.to - own } else { own - self.from };
                    if !(end > last.0) {
                        return end + 1e-12 * range;
                    }
                    h = end;
                    t = own + sign * h;
                }
                let value = self.reach(q, t);
                if past && !(value < last.1 - noise) {
                    return h + 1e-12 * range;
                }
                if value < last.1 - noise {
                    let (mut a, mut b) = (before, h);
                    let ratio = 0.5 * (5f64.sqrt() - 1.0);
                    for _ in 0..60 {
                        if b - a <= 1e-15 * range {
                            break;
                        }
                        let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
                        if self.reach(q, own + sign * c) > self.reach(q, own + sign * d) {
                            b = d;
                        } else {
                            a = c;
                        }
                    }
                    return 0.5 * (a + b);
                }
                before = last.0;
                last = (h, value);
                h *= 2.0;
            }
            2.0 * range
        };
        (own - side(-1.0), own + side(1.0))
    }

    /// The far depth by sampling (`count` poses outside the window, the five
    /// least local minima refined by golden section): fast, NOT certified
    /// (a dip narrower than a pose step can be missed). Prototype only.
    pub fn far_depth_sampled(&self, q: Vec3, own: f64, window: f64, count: usize) -> (f64, f64) {
        let mut times: Vec<f64> = Vec::with_capacity(count + 1);
        let (lo, hi) = self.own_basin(q, own, window);
        for k in 0..=count {
            let t = self.from + (self.to - self.from) * k as f64 / count as f64;
            if t <= lo || t >= hi {
                times.push(t);
            }
        }
        if lo > self.from && lo < self.to {
            times.push(lo);
        }
        if hi > self.from && hi < self.to {
            times.push(hi);
        }
        times.sort_by(f64::total_cmp);
        let values: Vec<f64> = times.iter().map(|&t| self.reach(q, t)).collect();
        let n = times.len();
        if n == 0 {
            return (f64::INFINITY, own);
        }
        let mut best = (f64::INFINITY, own);
        for k in 0..n {
            if values[k] < best.0 {
                best = (values[k], times[k]);
            }
        }
        let mut minima: Vec<usize> = (0..n).filter(|&k| (k == 0 || values[k] <= values[k - 1]) && (k + 1 == n || values[k] <= values[k + 1])).collect();
        minima.sort_by(|&x, &y| values[x].total_cmp(&values[y]));
        let ratio = 0.5 * (5f64.sqrt() - 1.0);
        for &k in minima.iter().take(5) {
            let (mut a, mut b) = (times[k.saturating_sub(1)], times[(k + 1).min(n - 1)]);
            // never refine across the own-time window
            if a < hi && b > lo && (a - own).abs() > 0.0 {
                if times[k] <= lo { b = b.min(lo); } else { a = a.max(hi); }
            }
            for _ in 0..80 {
                if b - a <= 1e-14 * (self.to - self.from) {
                    break;
                }
                let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
                if self.reach(q, c) < self.reach(q, d) {
                    b = d;
                } else {
                    a = c;
                }
            }
            let t = 0.5 * (a + b);
            let value = self.reach(q, t);
            if value < best.0 {
                best = (value, t);
            }
        }
        best
    }

    /// The far depth near a known reaching time `guess` (a trim curve's
    /// competitor moves continuously along it): the least of 33 poses over
    /// guess ± `span` (outside the own window) refined by golden section.
    pub fn far_depth_near(&self, q: Vec3, own: f64, window: f64, guess: f64, span: f64) -> (f64, f64) {
        let lo = (guess - span).max(self.from);
        let hi = (guess + span).min(self.to);
        let (left, right) = self.own_basin(q, own, window);
        let allowed = |t: f64| t <= left || t >= right;
        let mut best = (f64::INFINITY, guess);
        let mut best_k = None;
        let count = 16;
        let samples: Vec<f64> = (0..=count).map(|k| lo + (hi - lo) * k as f64 / count as f64).collect();
        let mut values = vec![f64::INFINITY; count + 1];
        for (k, &t) in samples.iter().enumerate() {
            if allowed(t) {
                values[k] = self.reach(q, t);
                if values[k] < best.0 {
                    best = (values[k], t);
                    best_k = Some(k);
                }
            }
        }
        let Some(k) = best_k else { return self.far_depth_sampled(q, own, window, 1024) };
        // A least at the span's edge (not the range's) is no local minimum:
        // the competitor moved beyond the span, so read the whole range.
        if (k == 0 && lo > self.from) || (k == count && hi < self.to) {
            return self.far_depth_sampled(q, own, window, 1024);
        }
        // A bracket about the least sample, refined by parabolic steps
        // (the distance is smooth and nearly quadratic at its least) with a
        // golden step wherever a parabola would leave the bracket or stall.
        let (mut a, mut b) = (samples[k.saturating_sub(1)], samples[(k + 1).min(count)]);
        if !allowed(a) { a = samples[k]; }
        if !allowed(b) { b = samples[k]; }
        let (mut x, mut fx) = (best.1, best.0);
        let ratio = 0.5 * (3.0 - 5f64.sqrt());
        for _ in 0..40 {
            if b - a <= 1e-13 * (self.to - self.from) {
                break;
            }
            let (fa, fb) = (self.reach(q, a), self.reach(q, b));
            let denominator = (x - a) * (fx - fb) - (x - b) * (fx - fa);
            let mut u = if denominator.abs() > 0.0 { x - 0.5 * ((x - a) * (x - a) * (fx - fb) - (x - b) * (x - b) * (fx - fa)) / denominator } else { f64::NAN };
            if !(u > a && u < b) || (u - x).abs() < 1e-15 * (self.to - self.from) {
                u = if x - a > b - x { x - ratio * (x - a) } else { x + ratio * (b - x) };
            }
            let fu = self.reach(q, u);
            if fu < fx {
                if u < x { b = x; } else { a = x; }
                x = u;
                fx = fu;
            } else if u < x {
                a = u;
            } else {
                b = u;
            }
        }
        if fx < best.0 { (fx, x) } else { best }
    }

    /// Whether every pose outside the own window keeps `q` beyond `level`
    /// (Some(true), certified by the speed bound), some pose brings it within
    /// (Some(false)), or neither is settled within `budget` intervals (None).
    pub fn beyond(&self, q: Vec3, own: f64, window: f64, level: f64, budget: usize) -> Option<bool> {
        let speed = self.reach_speed(q);
        let mut stack: Vec<(f64, f64)> = Vec::new();
        let (lo, hi) = (own - window, own + window);
        for (a, b) in [(self.from, lo.min(self.to)), (hi.max(self.from), self.to)] {
            if b > a {
                let count = 64usize;
                let h = (b - a) / count as f64;
                stack.extend((0..count).map(|k| (a + h * k as f64, a + h * (k + 1) as f64)));
            }
        }
        let mut spent = 0usize;
        while let Some((a, b)) = stack.pop() {
            let (fa, fb) = (self.reach(q, a), self.reach(q, b));
            if fa < level || fb < level {
                return Some(false);
            }
            if fa.min(fb) - speed * (b - a) * 0.5 >= level {
                continue;
            }
            spent += 1;
            if spent > budget || b - a <= 1e-12 * (self.to - self.from) {
                return None;
            }
            let m = 0.5 * (a + b);
            stack.push((a, m));
            stack.push((m, b));
        }
        Some(true)
    }

    /// g = far depth − r at K's domain point, with the reaching time.
    pub(super) fn trim_value(&self, sigma: f64, psi: f64, window: f64, tolerance: f64) -> Option<(f64, f64, Vec3)> {
        let q = self.k_at(sigma, psi)?;
        let _ = tolerance;
        let (depth, time) = self.far_depth_sampled(q, self.own_time(sigma), window, 1024);
        Some((depth - self.minor, time, q))
    }
}

impl Tube {
    /// The times at which the core circle passes at distance r from `q` (the
    /// distance's local leasts over the range that reach r to `tolerance`),
    /// distinct by a thousandth of the range: one at a point of K away from
    /// its self-meetings, two on a double curve, a single double root at a
    /// fold's cusp, and three at a triple point.
    pub(crate) fn touching_times(&self, q: Vec3, tolerance: f64) -> Vec<f64> {
        let (range, count) = (self.to - self.from, 2048usize);
        let at = |k: usize| self.from + range * k as f64 / count as f64;
        let values: Vec<f64> = (0..=count).map(|k| self.reach(q, at(k))).collect();
        let ratio = 0.5 * (5f64.sqrt() - 1.0);
        let mut times: Vec<f64> = Vec::new();
        for k in 0..=count {
            let left = k == 0 || values[k] <= values[k - 1];
            let right = k == count || values[k] <= values[k + 1];
            if !(left && right) {
                continue;
            }
            let (mut a, mut b) = (at(k.saturating_sub(1)), at((k + 1).min(count)));
            for _ in 0..100 {
                if b - a <= 1e-15 * range {
                    break;
                }
                let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
                if self.reach(q, c) < self.reach(q, d) {
                    b = d;
                } else {
                    a = c;
                }
            }
            let t = 0.5 * (a + b);
            if (self.reach(q, t) - self.minor).abs() <= tolerance && times.iter().all(|u| (u - t).abs() > 1e-3 * range) {
                times.push(t);
            }
        }
        times
    }

    /// The domain point (σ, ψ) of K that the pose at `time` puts at `q` (q at
    /// distance r from that pose's core circle): on the sheet Σ + r·N or Σ − r·N
    /// inside the range, on the end torus's leading or the start torus's
    /// trailing half at the range's ends.
    pub fn mate_of(&self, q: Vec3, time: f64) -> Option<(f64, f64)> {
        if let Some(found) = self.mate_at(q, time) {
            return Some(found);
        }
        // A sampled time (a lattice read's least sample) is off the reaching
        // pose: the distance's least near it, by golden section over two
        // samples' spacing either side (clamped to the range), read again.
        let range = self.to - self.from;
        let spread = range / 512.0;
        let (mut lo, mut hi) = ((time - spread).max(self.from), (time + spread).min(self.to));
        let ratio = 0.5 * (5f64.sqrt() - 1.0);
        let (mut a, mut b) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
        let (mut fa, mut fb) = (self.reach(q, a), self.reach(q, b));
        for _ in 0..80 {
            if !(hi - lo > 1e-15 * range) {
                break;
            }
            if fa <= fb {
                hi = b;
                (b, fb) = (a, fa);
                a = hi - ratio * (hi - lo);
                fa = self.reach(q, a);
            } else {
                lo = a;
                (a, fa) = (b, fb);
                b = lo + ratio * (hi - lo);
                fb = self.reach(q, b);
            }
        }
        let refined = 0.5 * (lo + hi);
        // At distance r from that pose's circle, or not its mate at all.
        if !((self.reach(q, refined) - self.minor).abs() <= 1e-6 * self.minor) {
            return None;
        }
        if let Some(found) = self.mate_at(q, refined) {
            return Some(found);
        }
        // A least inside the range is stationary, so its point is on a sheet
        // (± by its normal part): near a cusp the distance is too flat in time
        // for its lead part to settle within 1e-6 of r.
        if !((refined - self.from) > 1e-6 * range && (self.to - refined) > 1e-6 * range) {
            return None;
        }
        let local = self.motion.pose(refined).invert(q).sub(self.centre);
        let psi = local.dot(self.y).atan2(local.dot(self.x)).rem_euclid(std::f64::consts::TAU);
        let frame = self.frame(refined, psi)?;
        let sigma = if q.sub(frame.point).dot(frame.normal) >= 0.0 { (refined - self.from) / range } else { 2.0 + (self.to - refined) / range };
        Some((sigma, psi))
    }

    /// `mate_of` at an exact time.
    fn mate_at(&self, q: Vec3, time: f64) -> Option<(f64, f64)> {
        let local = self.motion.pose(time).invert(q).sub(self.centre);
        let psi = local.dot(self.y).atan2(local.dot(self.x)).rem_euclid(std::f64::consts::TAU);
        let frame = self.frame(time, psi)?;
        let offset = q.sub(frame.point);
        let (along_n, along_lead) = (offset.dot(frame.normal), offset.dot(frame.lead));
        let range = self.to - self.from;
        // Sheet or cap by where the point sits about its circle, not by an
        // exact time: a point off ±N (its lead part past 1e-6 of r) is on a
        // cap, whose pose must then be the range's end (the competitor read
        // lands a hair inside it).
        let on_sheet = along_lead.abs() <= 1e-6 * self.minor;
        let near_end = (self.to - time) <= 1e-6 * range;
        let near_start = (time - self.from) <= 1e-6 * range;
        let sigma = if !on_sheet && near_end && along_lead > 0.0 {
            1.0 + along_lead.atan2(along_n).clamp(0.0, std::f64::consts::PI) / std::f64::consts::PI
        } else if !on_sheet && near_start && along_lead < 0.0 {
            3.0 + (-along_lead).atan2(-along_n).clamp(0.0, std::f64::consts::PI) / std::f64::consts::PI
        } else if !on_sheet {
            return None; // off the sheets, yet not at an end of the range
        } else if along_n >= 0.0 {
            (time - self.from) / range
        } else {
            2.0 + (self.to - time) / range
        };
        Some((sigma, psi))
    }
}

/// The zero set of g over the lattice as closed loops of trim points (each
/// crossing solved on its lattice edge by bisection on exact K), or why not:
/// a cell with two crossings on each diagonal pair (a saddle) declines.
pub fn trim_loops(tube: &Tube, lattice: &Lattice, window: f64, tolerance: f64) -> Result<Vec<Vec<TrimPoint>>, String> {
    trim_loops_charted(tube, lattice, window, tolerance, &[], &[]).map(|(loops, _)| loops)
}

/// A stretch of a trim loop that runs through a chart, from the loop's point k
/// to k + 1: chart `chart`'s inside run `run`, with it (`forward`) or against it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Jump {
    pub chart: usize,
    pub run: usize,
    pub forward: bool,
}

/// [`trim_loops`] with charts (`charts[k]`, its rim `rims[k]`): the stations
/// and cells inside a chart's boxes are neither read nor marched, each rim
/// crossing is the crossing on its box-side lattice edge, and the loop goes on
/// through the chart to the crossing joined to it (a jump, listed per loop
/// point: `jumps[loop][k]` for the stretch from point k to k + 1).
#[allow(clippy::type_complexity)]
pub fn trim_loops_charted(
    tube: &Tube,
    lattice: &Lattice,
    window: f64,
    tolerance: f64,
    charts: &[super::chart::TubeChart],
    rims: &[super::chart::Rim],
) -> Result<(Vec<Vec<TrimPoint>>, Vec<Vec<Option<Jump>>>), String> {
    let (rows, columns) = (lattice.sigmas.len(), lattice.psis.len());
    let held = |sigma: f64, psi: f64| charts.iter().any(|c| c.holds(sigma, psi));
    let sigma_at = |i: usize| -> f64 { if i == rows { 4.0 } else { lattice.sigmas[i] } };
    let psi_at = |j: usize| -> f64 { if j == columns { std::f64::consts::TAU } else { lattice.psis[j] } };
    let mut values = vec![vec![f64::NAN; columns]; rows];
    // Each station's sign: certified against r by the speed bound, sampled
    // only where that stays unsettled (near a true tangency).
    for i in 0..rows {
        for j in 0..columns {
            // inside a chart's box: neither read nor marched (K is singular there)
            if held(lattice.sigmas[i], lattice.psis[j]) {
                continue;
            }
            let q = tube.k_at(lattice.sigmas[i], lattice.psis[j]).ok_or("K is singular at a lattice station")?;
            let own = tube.own_time(lattice.sigmas[i]);
            // Inside the own window the certified own-time read (covered by a
            // witness, clear by a second-order bound, or a tie that declines);
            // outside it the speed bound, sampled only where unsettled.
            let tie = 1e-9 * (tube.major + tube.minor);
            let near = tube.own_read(q, own, window, tie);
            if matches!(near, super::fold::OwnRead::Tie) {
                return Err(format!("a station's own-time read ties at (σ {:.6}, ψ {:.6})", lattice.sigmas[i], lattice.psis[j]));
            }
            let depth = if let super::fold::OwnRead::Covered(_) = near {
                tube.minor * (1.0 - 1e-3)
            } else {
                match tube.beyond(q, own, window, tube.minor, 4096) {
                    Some(true) => tube.minor * (1.0 + 1e-3),
                    Some(false) => tube.minor * (1.0 - 1e-3),
                    None => tube.far_depth_sampled(q, own, window, 1024).0,
                }
            };
            let g = depth - tube.minor;
            if g.abs() <= tolerance {
                return Err(format!("a lattice station ties at (σ {:.6}, ψ {:.6})", lattice.sigmas[i], lattice.psis[j]));
            }
            values[i][j] = g;
        }
    }
    let covered = |i: usize, j: usize| values[i % rows][j % columns] < 0.0;
    // A crossing on the edge from node (i, j) along σ (along = 0) or ψ (1).
    let mut crossings: std::collections::HashMap<(usize, usize, u8), TrimPoint> = std::collections::HashMap::new();
    let mut solve = |i: usize, j: usize, along: u8| -> Result<TrimPoint, String> {
        if let Some(found) = crossings.get(&(i, j, along)) {
            return Ok(*found);
        }
        let (s0, p0) = (sigma_at(i), psi_at(j));
        let (s1, p1) = if along == 0 { (sigma_at(i + 1), p0) } else { (s0, psi_at(j + 1)) };
        let at = |f: f64| (s0 + (s1 - s0) * f, p0 + (p1 - p0) * f);
        let sign0 = values[i % rows][j % columns] < 0.0;
        // The competing pose, read once at the edge's covered end, then
        // followed locally along the edge (it moves continuously).
        let covered_end = if sign0 { 0.0 } else { 1.0 };
        let (cs, cp) = at(covered_end);
        let range = tube.to - tube.from;
        // (with charts, the charts' far read, which does not land on own: the
        // own basin's fall test can near a root or valley)
        let guess = if charts.is_empty() {
            tube.trim_value(cs, cp, window, tolerance).ok_or("K is singular on a lattice edge")?.1
        } else {
            let q = tube.k_at(cs.rem_euclid(4.0), cp.rem_euclid(std::f64::consts::TAU)).ok_or("K is singular on a lattice edge")?;
            super::chart::chart_far(tube, q, tube.own_time(cs.rem_euclid(4.0)), window, None, range).1
        };
        let near = |s: f64, p: f64| -> Option<(f64, f64, Vec3)> {
            let (s, p) = (s.rem_euclid(4.0), p.rem_euclid(std::f64::consts::TAU));
            let q = tube.k_at(s, p)?;
            let (depth, time) = if charts.is_empty() {
                tube.far_depth_near(q, tube.own_time(s), window, guess, 0.01 * range)
            } else {
                super::chart::chart_far(tube, q, tube.own_time(s), window, Some(guess), range)
            };
            Some((depth - tube.minor, time, q))
        };
        let (mut lo, mut hi) = (0.0f64, 1.0f64);
        for _ in 0..48 {
            let mid = 0.5 * (lo + hi);
            let (s, p) = at(mid);
            let (g, _, _) = near(s, p).ok_or("K is singular on a lattice edge")?;
            if (g < 0.0) == sign0 {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        let (s, p) = at(0.5 * (lo + hi));
        let (_, time, point) = near(s, p).ok_or("K is singular on a lattice edge")?;
        let found = TrimPoint { sigma: s, psi: p, mate_time: time, point };
        crossings.insert((i, j, along), found);
        Ok(found)
    };
    // Segments per cell: the cell (i, j) has corners (i, j), (i+1, j), (i+1, j+1), (i, j+1);
    // its edges: bottom (i, j, ψ), right (i+1, j, ψ... along σ at j+1), etc. Keys name edges.
    type Key = (usize, usize, u8);
    let mut links: std::collections::HashMap<Key, Vec<Key>> = std::collections::HashMap::new();
    for i in 0..rows {
        for j in 0..columns {
            if held(0.5 * (sigma_at(i) + sigma_at(i + 1)), 0.5 * (psi_at(j) + psi_at(j + 1))) {
                continue;
            }
            let corners = [covered(i, j), covered(i + 1, j), covered(i + 1, j + 1), covered(i, j + 1)];
            // edges: 0 = (i,j)->(i+1,j) along σ at ψ j; 1 = (i+1,j)->(i+1,j+1) along ψ; 2 = (i,j+1)->(i+1,j+1) along σ at ψ j+1; 3 = (i,j)->(i,j+1) along ψ
            let keys: [Key; 4] = [(i, j, 0), ((i + 1) % rows, j, 1), (i, (j + 1) % columns, 0), (i, j, 1)];
            let cut = [corners[0] != corners[1], corners[1] != corners[2], corners[3] != corners[2], corners[0] != corners[3]];
            let cuts: Vec<usize> = (0..4).filter(|&e| cut[e]).collect();
            match cuts.as_slice() {
                [] => {}
                [a, b] => {
                    links.entry(keys[*a]).or_default().push(keys[*b]);
                    links.entry(keys[*b]).or_default().push(keys[*a]);
                }
                _ => return Err(format!("a saddle cell at (σ {:.6}, ψ {:.6})", sigma_at(i), psi_at(j))),
            }
        }
    }
    // Each rim crossing on the box-side lattice edge that ends a run outside
    // (the edge's one link): the rim's own crossing stands for it, and a link
    // through the chart joins it to the crossing joined to it.
    let mut jumps: std::collections::HashMap<(Key, Key), Jump> = std::collections::HashMap::new();
    let mut rim_at: std::collections::HashMap<Key, TrimPoint> = std::collections::HashMap::new();
    for (c, rim) in rims.iter().enumerate() {
        // a closed curve paired inside the chart (every piece's twin there)
        // is the chart faces' alone: nothing of it reaches the lattice
        for k in 0..rim.closed.len() {
            let pieces = rim.pieces.get(rim.runs.len() + k).ok_or("a chart's closed curve has no pieces")?;
            if pieces.is_empty() || pieces.iter().any(|q| rim.edges.get(q.edge).is_none_or(|e| e.outside.is_some())) {
                return Err("a chart holds a closed trim curve whose mate side is outside it (not yet taken)".into());
            }
        }
        let mut keys_of: Vec<Key> = Vec::with_capacity(rim.crossings.len());
        for crossing in &rim.crossings {
            let mut best: Option<(f64, Key)> = None;
            let dangling: Vec<Key> = links.iter().filter(|(_, v)| v.len() == 1).map(|(k, _)| *k).collect();
            for key in dangling {
                let found = solve(key.0, key.1, key.2)?;
                let d = found.point.sub(crossing.at.point).length();
                if best.is_none_or(|b| d < b.0) {
                    best = Some((d, key));
                }
            }
            let (d, key) = best.ok_or("a rim crossing has no trim run outside its box")?;
            if !(d <= 0.05 * (tube.major + tube.minor)) {
                return Err(format!("a rim crossing lies {d:.2e} from the nearest trim run outside its box"));
            }
            rim_at.insert(key, crossing.at);
            keys_of.push(key);
        }
        for (r, run) in rim.runs.iter().enumerate() {
            let [a, b] = run.ends;
            let (ka, kb) = (keys_of[a], keys_of[b]);
            links.entry(ka).or_default().push(kb);
            links.entry(kb).or_default().push(ka);
            jumps.insert((ka, kb), Jump { chart: c, run: r, forward: true });
            jumps.insert((kb, ka), Jump { chart: c, run: r, forward: false });
        }
    }
    // Walk the links into loops.
    let mut seen: std::collections::HashSet<Key> = std::collections::HashSet::new();
    let mut loop_jumps: Vec<Vec<Option<Jump>>> = Vec::new();
    let mut loops = Vec::new();
    let mut keys: Vec<Key> = links.keys().copied().collect();
    keys.sort();
    for start in keys {
        if seen.contains(&start) {
            continue;
        }
        let mut chain = vec![start];
        seen.insert(start);
        let mut previous = start;
        let mut current = links[&start][0];
        while current != start {
            if !seen.insert(current) {
                return Err("a trim curve branches".into());
            }
            chain.push(current);
            let next = links[&current].iter().copied().find(|k| *k != previous).ok_or("a trim curve ends")?;
            previous = current;
            current = next;
        }
        let mut points = Vec::with_capacity(chain.len());
        for &(i, j, along) in &chain {
            points.push(match rim_at.get(&(i, j, along)) {
                Some(at) => *at,
                None => solve(i, j, along)?,
            });
        }
        loop_jumps.push((0..chain.len()).map(|k| jumps.get(&(chain[k], chain[(k + 1) % chain.len()])).copied()).collect());
        loops.push(points);
    }
    Ok((loops, loop_jumps))
}

/// Whether `point` lies within one and a half lattice cells of the domain path
/// `path` (its stations and the chords between them).
fn path_near(path: &[(f64, f64)], point: (f64, f64), cell_gap: &dyn Fn((f64, f64), (f64, f64)) -> f64) -> bool {
    if path.iter().any(|q| cell_gap(*q, point) <= 1.5) {
        return true;
    }
    path.windows(2).any(|w| {
        // the chord's middle and quarter points (chords are about a cell long)
        let unwrap = |value: f64, near: f64, period: f64| value + ((near - value) / period).round() * period;
        let b = (unwrap(w[1].0, w[0].0, 4.0), unwrap(w[1].1, w[0].1, std::f64::consts::TAU));
        [0.25, 0.5, 0.75].iter().any(|f| cell_gap((w[0].0 + (b.0 - w[0].0) * f, w[0].1 + (b.1 - w[0].1) * f), point) <= 1.5)
    })
}

/// A point of K's domain with where it is in 3D (shared by every face that uses it).
#[derive(Clone, Copy, Debug)]
struct Node {
    sigma: f64,
    psi: f64,
    point: Vec3,
}

/// A perimeter point of a patch: a patch corner (row a, column b of the patch
/// grid, both periodic) or a split point of a trim curve (loop, index).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Mark {
    Corner(usize, usize),
    Split(usize, usize),
    /// A chart's cusp vertex (chart, `Rim::vertices` index).
    Chart(usize, usize),
}

/// A trim curve piece as one patch sees it: its points in the patch's (σ, ψ)
/// (unwrapped into the patch's own ranges), oriented with the kept side on
/// the left, the edge it is (loop, piece) and whether it runs with that edge.
#[derive(Clone, Debug)]
struct Piece {
    marks: [Mark; 2],
    domain: Vec<(f64, f64)>,
    edge: (usize, usize),
    forward: bool,
}

/// The trimmed body: the primary loop of each mated pair is densified (three
/// exact contour points a lattice cell), split where it crosses a patch side
/// on its own side or its mate's, and each piece becomes one edge of the face
/// it cuts on each side; every patch is clipped by the pieces it holds and the
/// kept parts of its sides, a face per closed loop.
#[allow(clippy::too_many_arguments)]
pub fn trimmed_tube(
    tube: &Tube,
    chunks: [usize; 4],
    lattice: &Lattice,
    per_chunk: usize,
    per_quarter: usize,
    loops: &[Vec<TrimPoint>],
    window: f64,
    fit: f64,
    cuts: (&[f64], &[f64]),
    charts: &[super::chart::TubeChart],
    rims: &[super::chart::Rim],
    loop_jumps: &[Vec<Option<Jump>>],
) -> Result<crate::BrepSolid, String> {
    let in_chart = |sigma: f64, psi: f64| charts.iter().any(|c| c.holds(sigma, psi));
    use std::f64::consts::{FRAC_PI_2, TAU};
    let tolerance = 1e-12 * tube.minor;
    // A trim edge is an intersection curve: held to the kernel's own fit for
    // those (`intersection_fit`), not the patches' tighter one (an edge's
    // deviation moves neither the volume nor the area).
    let edge_fit = crate::KernelTolerances::for_scale(tube.major + tube.minor, 1e-7).intersection_fit.max(fit);
    // Patch rows: (chart, s0, s1, σ0, σ1) round K.
    let mut rows: Vec<(usize, f64, f64)> = Vec::new();
    for (chart, &count) in chunks.iter().enumerate() {
        for c in 0..count {
            rows.push((chart, c as f64 / count as f64, (c + 1) as f64 / count as f64));
        }
    }
    // The lattice's chunks (cell sizes come from them), then the patch rows cut
    // further at any extra σ lines (a chart's box sides become patch sides).
    let chunk_bounds: Vec<f64> = rows.iter().map(|(chart, s0, _)| *chart as f64 + s0).chain(std::iter::once(4.0)).collect();
    let chunk_of = |sigma: f64| -> usize {
        let s = sigma.rem_euclid(4.0);
        (chunk_bounds.partition_point(|b| *b <= s).max(1) - 1).min(chunk_bounds.len() - 2)
    };
    let mut cut_rows: Vec<(usize, f64, f64)> = Vec::with_capacity(rows.len());
    for &(chart, s0, s1) in &rows {
        let mut inner: Vec<f64> = cuts.0.iter().map(|c| c.rem_euclid(4.0) - chart as f64).filter(|c| *c > s0 + 1e-12 && *c < s1 - 1e-12).collect();
        inner.sort_by(f64::total_cmp);
        inner.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
        let mut from = s0;
        for c in inner {
            cut_rows.push((chart, from, c));
            from = c;
        }
        cut_rows.push((chart, from, s1));
    }
    let rows = cut_rows;
    let sigma_bounds: Vec<f64> = rows.iter().map(|(chart, s0, _)| *chart as f64 + s0).chain(std::iter::once(4.0)).collect();
    let row_of = |sigma: f64| -> usize {
        let s = sigma.rem_euclid(4.0);
        (sigma_bounds.partition_point(|b| *b <= s).max(1) - 1).min(rows.len() - 1)
    };
    // The patch columns: the four quarters of ψ, cut further at any extra ψ lines.
    let mut psi_bounds: Vec<f64> = (0..4).map(|q| q as f64 * FRAC_PI_2).chain(cuts.1.iter().map(|c| c.rem_euclid(TAU))).collect();
    psi_bounds.sort_by(f64::total_cmp);
    psi_bounds.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
    let columns = psi_bounds.len();
    let psi_end = |b: usize| if b + 1 < columns { psi_bounds[b + 1] } else { TAU };
    let column_of = |psi: f64| -> usize { (psi_bounds.partition_point(|b| *b <= psi.rem_euclid(TAU)).max(1) - 1).min(columns - 1) };
    let unwrap = |value: f64, near: f64, period: f64| value + ((near - value) / period).round() * period;
    let cell_sigma = |sigma: f64| {
        let a = chunk_of(sigma);
        (chunk_bounds[a + 1] - chunk_bounds[a]) / per_chunk as f64
    };
    let cell_psi = TAU / (4 * per_quarter) as f64;
    let g_at = |sigma: f64, psi: f64| -> Option<(f64, f64, Vec3)> {
        if charts.is_empty() {
            return tube.trim_value(sigma.rem_euclid(4.0), psi.rem_euclid(TAU), window, tolerance);
        }
        let (sigma, psi) = (sigma.rem_euclid(4.0), psi.rem_euclid(TAU));
        let q = tube.k_at(sigma, psi)?;
        let (depth, time) = super::chart::chart_far(tube, q, tube.own_time(sigma), window, None, tube.to - tube.from);
        Some((depth - tube.minor, time, q))
    };
    // A point of the contour near the chord from a to b at fraction f: g = 0
    // sought across the chord within a cell either side.
    let range = tube.to - tube.from;
    // (with charts, the charts' far read: its own basin is cut at the first
    // local least of a uniform scan, so near a root it neither ends on a
    // rounding dip nor swallows the competitor)
    let g_near = |sigma: f64, psi: f64, guess: f64| -> Option<(f64, f64, Vec3)> {
        let (sigma, psi) = (sigma.rem_euclid(4.0), psi.rem_euclid(TAU));
        let q = tube.k_at(sigma, psi)?;
        let (depth, time) = if charts.is_empty() {
            tube.far_depth_near(q, tube.own_time(sigma), window, guess, 0.01 * range)
        } else {
            super::chart::chart_far(tube, q, tube.own_time(sigma), window, Some(guess), range)
        };
        Some((depth - tube.minor, time, q))
    };
    let contour_within = |a: (f64, f64), b: (f64, f64), f: f64, guess: f64, cells: f64| -> Result<(f64, f64, f64, Vec3), String> {
        let c = (a.0 + (b.0 - a.0) * f, a.1 + (b.1 - a.1) * f);
        let (ds, dp) = (cell_sigma(c.0), cell_psi);
        // the chord's normal in cell units
        let (cs, cp) = ((b.0 - a.0) / ds, (b.1 - a.1) / dp);
        let length = cs.hypot(cp);
        let (ns, np) = if length > 0.0 { (-cp / length, cs / length) } else { (1.0, 0.0) };
        let at = |lambda: f64| (c.0 + lambda * ns * ds, c.1 + lambda * np * dp);
        // The local read first (the competitor near its guess); where it finds
        // no crossing (its competitor left the span, or the own basin's edge
        // moved), the whole-range read.
        let search = |global: bool| -> Result<(f64, f64, f64, Vec3), String> {
        let read = |s: f64, p: f64| if global { g_at(s, p) } else { g_near(s, p, guess) };
        let sign = |lambda: f64| -> Result<bool, String> {
            let (s, p) = at(lambda);
            Ok(read(s, p).ok_or("K is singular near a trim curve")?.0 < 0.0)
        };
        let (mut lo, mut hi) = (-cells, cells);
        let (mut slo, shi) = (sign(lo)?, sign(hi)?);
        if slo == shi {
            // Near a lens tip (a cusp) the other branch lies within the
            // reach: the nearest change of sign from the chord's point, out
            // in doublings from 2^-20 of the reach, is the chord's own branch
            // (both its ends lie on it).
            let here = sign(0.0)?;
            let mut lambda = cells * 2f64.powi(-20);
            let mut found = None;
            while lambda <= cells {
                if sign(lambda)? != here {
                    found = Some((0.0, lambda));
                    break;
                }
                if sign(-lambda)? != here {
                    found = Some((-lambda, 0.0));
                    break;
                }
                lambda *= 2.0;
            }
            if let Some((a0, a1)) = found {
                (lo, hi, slo) = (a0, a1, sign(a0)?);
            }
        }
        if slo == sign(hi)? {
            return Err(format!("a trim curve leaves its cell (across {cells} cells) at (σ {:.6}, ψ {:.6}) on the chord from (σ {:.6}, ψ {:.6}) to (σ {:.6}, ψ {:.6}) at {f}", c.0, c.1, a.0, a.1, b.0, b.1));
        }
        for _ in 0..30 {
            let mid = 0.5 * (lo + hi);
            if sign(mid)? == slo {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        let (s, p) = at(0.5 * (lo + hi));
        let (_, time, point) = read(s, p).ok_or("K is singular near a trim curve")?;
        Ok((s, p, time, point))
        };
        search(false).or_else(|_| search(true))
    };
    let contour = |a: (f64, f64), b: (f64, f64), f: f64, guess: f64| -> Result<(f64, f64, f64, Vec3), String> { contour_within(a, b, f, guess, 1.0) };

    // A point's mate, with the time it was read at: a stored time (a
    // lattice's least sample, a local read's guess) that is not the reaching
    // pose's is replaced by the exact far read from the point's own time.
    let mate_read = |point: Vec3, time: f64, sigma: f64| -> Option<((f64, f64), f64)> {
        if let Some(m) = tube.mate_of(point, time) {
            return Some((m, time));
        }
        // a mate inside a chart's box (near a root the frame test fails): the chart's
        if let Some(m) = charts.iter().find_map(|c| c.mate_of(tube, point, time)) {
            return Some((m, time));
        }
        let _ = tolerance;
        let (depth, exact) = tube.far_depth_sampled(point, tube.own_time(sigma.rem_euclid(4.0)), window, 1024);
        let found = tube.mate_of(point, exact).map(|m| (m, exact));
        found
    };
    // A mate followed from the last one: the other preimage of `point` on K
    // solved by Gauss-Newton on |K(σ, ψ) - point| from the last mate, so mates
    // along a curve stay on one branch where independent far reads can flip
    // between two near-equal competitors (a fold's double curve). None where it
    // does not converge onto the point; the caller then reads it afresh.
    let size = tube.major + tube.minor;
    let follow = |point: Vec3, from: (f64, f64)| -> Option<(f64, f64)> {
        let (mut s, mut p) = from;
        let h = 1e-7;
        for _ in 0..30 {
            let at = tube.k_at(s.rem_euclid(4.0), p.rem_euclid(TAU))?;
            let r = at.sub(point);
            if r.length() <= 1e-10 * size {
                return Some((s, p));
            }
            let ks = tube.k_at((s + h).rem_euclid(4.0), p.rem_euclid(TAU))?.sub(tube.k_at((s - h).rem_euclid(4.0), p.rem_euclid(TAU))?).scale(0.5 / h);
            let kp = tube.k_at(s.rem_euclid(4.0), (p + h).rem_euclid(TAU))?.sub(tube.k_at(s.rem_euclid(4.0), (p - h).rem_euclid(TAU))?).scale(0.5 / h);
            // normal equations of the 3 x 2 least squares
            let (a, b, c) = (ks.dot(ks), ks.dot(kp), kp.dot(kp));
            let (u, v) = (-ks.dot(r), -kp.dot(r));
            let det = a * c - b * b;
            if !(det.abs() > 1e-30) {
                return None;
            }
            let (ds, dp) = ((c * u - b * v) / det, (a * v - b * u) / det);
            if !(ds.is_finite() && dp.is_finite()) {
                return None;
            }
            s += ds;
            p += dp;
        }
        let at = tube.k_at(s.rem_euclid(4.0), p.rem_euclid(TAU))?;
        (at.sub(point).length() <= 1e-9 * size).then_some((s, p))
    };
    let wrap = |a: f64, b: f64, period: f64| {
        let d = (a - b).rem_euclid(period);
        d.min(period - d)
    };
    let domain_gap = |a: (f64, f64), b: (f64, f64)| wrap(a.0, b.0, 4.0).hypot(wrap(a.1, b.1, TAU));
    // A gap in lattice cells (σ and ψ cells differ in size).
    let cell_gap = |a: (f64, f64), b: (f64, f64)| (wrap(a.0, b.0, 4.0) / cell_sigma(a.0)).hypot(wrap(a.1, b.1, TAU) / cell_psi);
    // The curves to build, as arcs of the loops along which the mate moves
    // continuously. A loop is cut at a cusp (a fixed point of the mate map,
    // where a fold's covered lens ends in a tip) and at a junction (the
    // covering pose changes family: two competitors reach the point at r
    // together, a vertex where three faces meet). An arc whose points lie on
    // the mate path of an arc already kept is that arc's other side and is
    // not built again. A loop with neither is one closed curve.
    // (points, open, [first end a cusp, last end a cusp])
    let mut curves: Vec<(Vec<TrimPoint>, bool, [bool; 2])> = Vec::new();
    let mut kept_mates: Vec<Vec<(f64, f64)>> = Vec::new();
    // Each kept curve's twin: the points of the arcs dropped as its other side
    // (the same curve in space on the other preimage), where mates are found.
    let mut twins: Vec<Vec<TrimPoint>> = Vec::new();
    // Each rim crossing's far preimage: where a loop on the far sheet meets the
    // crossing's point (its mate side enters the chart there), that loop is cut,
    // and its stretch whose mate lies inside the chart is the chart run's mate
    // side, built from the run.
    let rim_far: Vec<TrimPoint> = rims
        .iter()
        .flat_map(|rim| rim.crossings.iter())
        .filter_map(|c| {
            let (m, _) = mate_read(c.at.point, c.at.mate_time, c.at.sigma)?;
            Some(TrimPoint { sigma: m.0.rem_euclid(4.0), psi: m.1.rem_euclid(TAU), mate_time: tube.own_time(c.at.sigma), point: c.at.point })
        })
        .collect();
    for (li, l) in loops.iter().enumerate() {
        let n = l.len();
        if n < 2 {
            return Err("a trim loop of fewer than two points".into());
        }
        let trace76 = std::env::var("BREP_TUBE_TRACE_LOOPS").is_ok();
        if trace76 && li == 0 {
            for (c, chart) in charts.iter().enumerate() {
                let (cs, cp) = chart.cuts();
                eprintln!("T76 chart {c}: sigma cuts {cs:?} psi cuts {cp:?}");
                for x in &rims[c].crossings {
                    let far = mate_read(x.at.point, x.at.mate_time, x.at.sigma).map(|(m, _)| m);
                    eprintln!("T76   crossing ({:.6}, {:.6}) far {far:?}", x.at.sigma, x.at.psi);
                }
            }
        }
        if trace76 {
            eprintln!("T76 loop {li}: {n} points, from ({:.6}, {:.6})", l[0].sigma, l[0].psi);
            for p in l.iter().filter(|p| p.sigma > 0.45 && p.sigma < 0.65 && p.psi > 5.9 && p.psi < 6.3) { eprintln!("T76   pt ({:.6}, {:.6}) t {:.5}", p.sigma, p.psi, p.mate_time); }
        }
        let no_jumps = vec![None; n];
        let jump_after: &[Option<Jump>] = loop_jumps.get(li).map(|v| v.as_slice()).unwrap_or(&no_jumps);
        // A domain point against the chord a → b, in cells: (the parameter of
        // its foot along the chord, its distance from the chord's line).
        let along_chord = |a: TrimPoint, b: TrimPoint, q: (f64, f64)| -> (f64, f64) {
            let (ds, dp) = (cell_sigma(a.sigma), cell_psi);
            let v = ((unwrap(b.sigma, a.sigma, 4.0) - a.sigma) / ds, (unwrap(b.psi, a.psi, TAU) - a.psi) / dp);
            let w = ((unwrap(q.0, a.sigma, 4.0) - a.sigma) / ds, (unwrap(q.1, a.psi, TAU) - a.psi) / dp);
            let vv = v.0 * v.0 + v.1 * v.1;
            if !(vv > 0.0) {
                return (0.0, w.0.hypot(w.1));
            }
            let t = (w.0 * v.0 + w.1 * v.1) / vv;
            (t, (w.0 - t * v.0).hypot(w.1 - t * v.1))
        };
        // the far crossings this loop passes through: (after station i, the point)
        let mut forced: Vec<Option<TrimPoint>> = vec![None; n];
        // (read in the domain: a loop through a crossing's own point can pass
        // its far preimage too, the pinch's run going out and coming back on
        // one loop; a jump's chord crosses the chart and passes nothing)
        for far in &rim_far {
            // the chord the point lies along (its foot within the chord, the
            // nearest such within half a cell)
            let mut best: Option<(f64, usize)> = None;
            for i in 0..n {
                if jump_after[i].is_some() {
                    continue;
                }
                let (t, d) = along_chord(l[i], l[(i + 1) % n], (far.sigma, far.psi));
                if (0.0..=1.0).contains(&t) && d <= 0.5 && best.is_none_or(|x| d < x.0) {
                    best = Some((d, i));
                }
            }
            if let Some((_, i)) = best {
                if trace76 { eprintln!("T76   far ({:.6}, {:.6}) forced after {i}", far.sigma, far.psi); }
                forced[i] = Some(*far);
            }
        }
        let mates: Vec<Option<(f64, f64)>> = l.iter().map(|p| mate_read(p.point, p.mate_time, p.sigma).map(|(m, _)| m)).collect();
        let gaps: Vec<f64> = (0..n).map(|i| mates[i].map(|m| cell_gap((l[i].sigma, l[i].psi), m)).unwrap_or(f64::INFINITY)).collect();
        // Each fixed point (a cusp) found by walking the contour from its
        // nearest station: the tangent (the gradient of g turned a quarter, in
        // cell units) predicts a step, a search along the normal brings it back
        // onto g = 0, and the walk follows whichever way the mate gap falls,
        // halving its step when the gap stops falling, until the step is 1e-9
        // of a cell.
        let walk = |i: usize| -> Result<TrimPoint, String> {
            let p0 = l[i];
            let guess = p0.mate_time;
            let g = |s: f64, p: f64| -> Result<f64, String> {
                g_near(s, p, guess).map(|x| x.0).ok_or_else(|| format!("K is singular near a cusp at (σ {s:.9}, ψ {p:.9}); start (σ {:.9}, ψ {:.9})", p0.sigma, p0.psi))
            };
            let (ds, dp) = (cell_sigma(p0.sigma), cell_psi);
            let gap_of = |s: f64, p: f64| -> Result<(f64, TrimPoint), String> {
                let (_, time, point) = g_near(s, p, guess).ok_or("K is singular near a cusp")?;
                // no mate (a corrected point whose least is off the guess): a gap that does not fall
                let gap = mate_read(point, time, s).map(|(m, _)| domain_gap(m, (s, p))).unwrap_or(f64::INFINITY);
                Ok((gap, TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }))
            };
            // back onto g = 0 along the gradient's direction, within `reach` cells
            let correct = |s: f64, p: f64, gs: f64, gp: f64, reach: f64| -> Result<Option<(f64, f64)>, String> {
                let length = gs.hypot(gp);
                if !(length.is_finite() && length > 0.0) || !(s.is_finite() && p.is_finite()) {
                    return Ok(None);
                }
                let (us, up) = (gs / length, gp / length);
                let at = |lambda: f64| (s + lambda * us * ds, p + lambda * up * dp);
                let (a0, a1) = (at(-reach), at(reach));
                let (f0, f1) = (g(a0.0, a0.1)?, g(a1.0, a1.1)?);
                if (f0 < 0.0) == (f1 < 0.0) {
                    return Ok(None);
                }
                let (mut lo, mut hi) = (-reach, reach);
                for _ in 0..40 {
                    let mid = 0.5 * (lo + hi);
                    let (x, y) = at(mid);
                    if (g(x, y)? < 0.0) == (f0 < 0.0) {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                Ok(Some(at(0.5 * (lo + hi))))
            };
            let gradient = |s: f64, p: f64, h: f64| -> Result<(f64, f64), String> {
                let gs = (g(s + h * ds, p)? - g(s - h * ds, p)?) / (2.0 * h);
                let gp = (g(s, p + h * dp)? - g(s, p - h * dp)?) / (2.0 * h);
                Ok((gs, gp))
            };
            let (mut s0, mut q0) = (p0.sigma, p0.psi);
            let (mut best, mut best_point) = gap_of(s0, q0)?;
            let mut step: f64 = 0.25;
            let mut direction = 0.0f64;
            // Bounded: a walk that keeps gaining by slivers stops after 2000 steps.
            let mut steps = 0usize;
            while step > 1e-9 && steps < 2000 {
                steps += 1;
                let (gs, gp) = gradient(s0, q0, (0.1 * step).max(1e-7))?;
                let (ts, tp) = (-gp, gs);
                let length = ts.hypot(tp);
                // a flat or undefined gradient (a sliver at the station): no direction to walk
                if !(length.is_finite() && length > 0.0) {
                    break;
                }
                let mut moved = false;
                let order: [f64; 2] = if direction < 0.0 { [-1.0, 1.0] } else { [1.0, -1.0] };
                for sign in order {
                    let (ps, pp) = (s0 + sign * step * ts / length * ds, q0 + sign * step * tp / length * dp);
                    let Some((cs, cp)) = correct(ps, pp, gs, gp, (2.0 * step).max(1e-6))? else { continue };
                    let (gap, point) = gap_of(cs, cp)?;
                    if gap < best {
                        best = gap;
                        best_point = point;
                        s0 = cs;
                        q0 = cp;
                        direction = sign;
                        moved = true;
                        break;
                    }
                }
                if !moved {
                    step *= 0.5;
                }
            }
            Ok(best_point)
        };
        // Cusp candidates: a least of the gap along the loop within four cells
        // (the fixed point can lie between stations a few cells from either);
        // the walk below decides.
        let cusp: Vec<bool> = (0..n).map(|i| gaps[i] < 4.0 && gaps[i] <= gaps[(i + n - 1) % n] && gaps[i] <= gaps[(i + 1) % n]).collect();
        // Junctions: consecutive stations whose mates jump by more than the
        // stations move (four cells beyond four times their own step).
        let jump = |i: usize| -> bool {
            let j = (i + 1) % n;
            match (mates[i], mates[j]) {
                (Some(a), Some(b)) => !cusp[i] && !cusp[j] && cell_gap(a, b) > 4.0 + 4.0 * cell_gap((l[i].sigma, l[i].psi), (l[j].sigma, l[j].psi)),
                _ => false,
            }
        };
        // The junction between stations i and i + 1, by bisection on the
        // contour between them: the last point whose mate follows i's and the
        // first whose mate follows i + 1's (the same point to 1e-12 of the chord).
        let junction = |i: usize| -> Result<Option<(TrimPoint, TrimPoint)>, String> {
            let j = (i + 1) % n;
            let (a, b) = (l[i], l[j]);
            let pa = (a.sigma, a.psi);
            let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
            let (ma, mb) = (mates[i].ok_or("a mate is singular [j]")?, mates[j].ok_or("a mate is singular [j]")?);
            let read = |f: f64, guess: f64| -> Result<(TrimPoint, Option<(f64, f64)>), String> {
                let (s, p, time, point) = contour(pa, pb, f, guess).map_err(|e| format!("{e} [junction]"))?;
                let m = mate_read(point, time, s).map(|(m, _)| m);
                Ok((TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }, m))
            };
            let (mut lo, mut hi) = (0.0f64, 1.0f64);
            let (mut left, mut right) = (a, b);
            let (mut left_mate, mut right_mate) = (Some(ma), Some(mb));
            for _ in 0..40 {
                let mid = 0.5 * (lo + hi);
                let (point, m) = read(mid, left.mate_time)?;
                let follows_a = m.is_some_and(|m| cell_gap(m, ma) <= cell_gap(m, mb));
                if follows_a {
                    lo = mid;
                    left = point;
                    left_mate = m;
                } else {
                    hi = mid;
                    right = point;
                    right_mate = m;
                }
            }
            // A mate that only moves fast (the stations far apart in its
            // chart) closes up under bisection: no junction.
            match (left_mate, right_mate) {
                (Some(x), Some(y)) if cell_gap(x, y) <= 0.05 => Ok(None),
                _ => Ok(Some((left, right))),
            }
        };
        // (a junction whose contour will not resolve stays unsplit: the arcs on
        // either side are then one, and the mates decide downstream)
        let junctions: Vec<Option<(TrimPoint, TrimPoint)>> = (0..n).map(|i| if jump(i) { junction(i).unwrap_or(None) } else { None }).collect();
        // A station only near its mate is a cusp if the walk reaches the
        // fixed point (the gap closes); else the contour merely passes close
        // to its mate path there.
        let walked: Vec<Option<TrimPoint>> = (0..n)
            .map(|i| -> Result<Option<TrimPoint>, String> {
                if !cusp[i] {
                    return Ok(None);
                }
                let w = walk(i)?;
                let closed = mate_read(w.point, w.mate_time, w.sigma).is_some_and(|(m, _)| cell_gap(m, (w.sigma, w.psi)) <= 0.05);
                if trace76 {
                    eprintln!("T76   walk from {i} ({:.6}, {:.6}) reached ({:.6}, {:.6}) mate {:?} closed {closed}", l[i].sigma, l[i].psi, w.sigma, w.psi, mate_read(w.point, w.mate_time, w.sigma).map(|x| x.0));
                }
                Ok(closed.then_some(w))
            })
            .collect::<Result<_, _>>()?;
        // A fixed point between stations that no walk reaches: where the loop
        // is its own mate there, the mate map reverses the loop's direction, so
        // its fixed points are where a station's mate passes from ahead of it
        // (along the loop) to behind it. Each such crossing is bisected on its
        // chord by the sign of the mate's offset along the chord, and kept where
        // the gap closes (off chart seams, where a curve can run with its mate).
        let mut walked = walked;
        {
            let on_seam = |sigma: f64| {
                let f = sigma.rem_euclid(1.0);
                f.min(1.0 - f) <= 1e-6
            };
            // each station's mate as an index along the loop (a cell or so off it at most)
            let along: Vec<Option<f64>> = (0..n)
                .map(|i| {
                    let m = mates[i]?;
                    let (k, d) = (0..n).map(|k| (k, cell_gap(m, (l[k].sigma, l[k].psi)))).min_by(|x, y| x.1.total_cmp(&y.1))?;
                    if d > 1.5 {
                        return None;
                    }
                    // signed steps from i to k round the loop, in (-n/2, n/2]
                    let mut steps = (k as i64 - i as i64).rem_euclid(n as i64);
                    if steps > n as i64 / 2 {
                        steps -= n as i64;
                    }
                    Some(steps as f64)
                })
                .collect();
            for i in 0..n {
                let j = (i + 1) % n;
                if trace76 && n < 60 {
                    eprintln!("T76   fold scan {i}: along {:?} {:?} gaps {:.3} mate {:?} walked {} cand {}", along[i], along[j], gaps[i], mates[i], walked[i].is_some(), cusp[i]);
                }
                let (Some(x), Some(y)) = (along[i], along[j]) else { continue };
                // ahead then behind (or the reverse), both within a few stations;
                // a station whose mate's nearest station is itself (at the fold,
                // within a station of its tip) is a step of the change too: the
                // bisection on the offset's sign below decides
                if !(x.abs() <= 3.0 && y.abs() <= 3.0 && x * y <= 0.0 && x != y) || walked[i].is_some() || walked[j].is_some() {
                    continue;
                }
                // (a fold with a walked fixed point within three stations has its
                // cusp: the 70..100 lens, whose station beside the fold reads itself)
                if (1..=3).any(|d| walked[(i + n - d % n) % n].is_some() || walked[(j + d) % n].is_some()) {
                    continue;
                }
                // (the station that reads itself has, past it, a mate on the other side)
                if x == 0.0 && !along[(i + n - 1) % n].is_some_and(|p| p * y < 0.0) || y == 0.0 && !along[(j + 1) % n].is_some_and(|q| q * x < 0.0) {
                    continue;
                }
                let (a, b) = (l[i], l[j]);
                let pa = (a.sigma, a.psi);
                let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
                let (cs, cp) = ((pb.0 - pa.0) / cell_sigma(pa.0), (pb.1 - pa.1) / cell_psi);
                let offset = |f: f64, guess: f64| -> Option<(f64, f64, TrimPoint, (f64, f64))> {
                    let (s, p, time, point) = contour(pa, pb, f, guess).ok()?;
                    let (m, _) = mate_read(point, time, s)?;
                    let m = (unwrap(m.0, s, 4.0), unwrap(m.1, p, TAU));
                    let ahead = ((m.0 - s) / cell_sigma(s)) * cs + ((m.1 - p) / cell_psi) * cp;
                    Some((ahead, cell_gap(m, (s, p)), TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point }, m))
                };
                let (o0, o1) = (offset(0.0, a.mate_time), offset(1.0, b.mate_time));
                if trace76 {
                    eprintln!("T76   fold try {i}: h0 {:?} h1 {:?}", o0.as_ref().map(|o| (o.0, o.1)), o1.as_ref().map(|o| (o.0, o.1)));
                }
                let (Some((h0, ..)), Some((h1, ..))) = (o0, o1) else { continue };
                if (h0 < 0.0) == (h1 < 0.0) {
                    continue;
                }
                let (mut lo, mut hi, mut guess) = (0.0f64, 1.0f64, a.mate_time);
                let mut last = None;
                // the last reading on each side of the sign change: (gap, point, mate)
                let mut sides: [Option<(f64, TrimPoint, (f64, f64))>; 2] = [None, None];
                for _ in 0..50 {
                    let mid = 0.5 * (lo + hi);
                    let Some((h, gap, point, m)) = offset(mid, guess) else { break };
                    guess = point.mate_time;
                    last = Some((gap, point));
                    if (h < 0.0) == (h0 < 0.0) {
                        lo = mid;
                        sides[0] = Some((gap, point, m));
                    } else {
                        hi = mid;
                        sides[1] = Some((gap, point, m));
                    }
                }
                // Within a fraction of a cell of the fixed point the mate read
                // can fall onto the point itself, and the sign then changes at
                // the edge of that reach, not at the fixed point: the last
                // reading with a true mate (under a cell off, the other side's
                // fallen onto itself) and its mate lie either side of the fixed point, which is the contour's point
                // midway between them.
                let apart = sides.iter().flatten().filter(|x| x.0 > 0.05).max_by(|x, y| x.0.total_cmp(&y.0)).copied();
                let fallen = sides.iter().flatten().any(|x| x.0 <= 0.05);
                // (and only where the loop is its own mate reversed on both sides of
                // the chord too: the station before reads its mate ahead of it and
                // the one after behind it, or the reverse; a station that reads
                // itself there is a fixed point already, with this chord beside it)
                let (before, after) = (along[(i + n - 1) % n], along[(j + 1) % n]);
                let fallen = fallen && matches!((before, after), (Some(p), Some(q)) if p * q < 0.0 && (p > 0.0) == (x > y));
                if let Some((gap, point, m)) = apart {
                    if gap <= 1.0 && fallen {
                        let own = (unwrap(point.sigma, pa.0, 4.0), unwrap(point.psi, pa.1, TAU));
                        let m = (unwrap(m.0, own.0, 4.0), unwrap(m.1, own.1, TAU));
                        if let Ok((s, p, time, at)) = contour(own, m, 0.5, point.mate_time) {
                            last = Some((0.0, TrimPoint { sigma: s.rem_euclid(4.0), psi: p.rem_euclid(TAU), mate_time: time, point: at }));
                        }
                    }
                }
                if trace76 {
                    eprintln!("T76   fold bisect {i}: lo {lo} hi {hi} last {:?}", last.as_ref().map(|(g, p)| (*g, p.sigma, p.psi)));
                }
                if let Some((gap, point)) = last {
                    // (a fixed point a walk already reached from another station is that one)
                    let reached = walked.iter().flatten().any(|w| cell_gap((w.sigma, w.psi), (point.sigma, point.psi)) <= 1.0);
                    if gap <= 0.05 && !on_seam(point.sigma) && !reached {
                        walked[i] = Some(point);
                    }
                }
            }
        }
        // A cusp the walk leaves within 1e-5 of a chart seam (a lens whose tip
        // is on the seam: the walk stops a step short of it) is read on the
        // seam itself: g = 0 along ψ at the seam's σ.
        for w in walked.iter_mut() {
            let Some(p) = *w else { continue };
            let seam = p.sigma.round();
            if (p.sigma - seam).abs() > 1e-5 || p.sigma == seam {
                continue;
            }
            let read = |psi: f64| g_near(seam, psi, p.mate_time);
            let reach = 0.02 * cell_psi;
            let (Some(f0), Some(f1)) = (read(p.psi - reach).map(|x| x.0), read(p.psi + reach).map(|x| x.0)) else { continue };
            if (f0 < 0.0) == (f1 < 0.0) {
                continue;
            }
            let (mut lo, mut hi) = (p.psi - reach, p.psi + reach);
            for _ in 0..60 {
                let mid = 0.5 * (lo + hi);
                match read(mid) {
                    Some(x) if (x.0 < 0.0) == (f0 < 0.0) => lo = mid,
                    Some(_) => hi = mid,
                    None => break,
                }
            }
            let psi = 0.5 * (lo + hi);
            if let Some((_, time, point)) = read(psi) {
                *w = Some(TrimPoint { sigma: seam.rem_euclid(4.0), psi: psi.rem_euclid(TAU), mate_time: time, point });
            }
        }
        // Two candidates whose walks reach one fixed point: one cusp.
        let mut seen: Vec<(f64, f64)> = Vec::new();
        for w in walked.iter_mut() {
            if let Some(p) = *w {
                if seen.iter().any(|q| cell_gap(*q, (p.sigma, p.psi)) <= 1e-3) {
                    *w = None;
                } else {
                    seen.push((p.sigma, p.psi));
                }
            }
        }
        let cusp: Vec<bool> = walked.iter().map(|w| w.is_some()).collect();
        let events = (0..n).any(|i| cusp[i] || junctions[i].is_some() || jump_after[i].is_some() || forced[i].is_some());
        if trace76 {
            for i in 0..n { if cusp[i] || junctions[i].is_some() || jump_after[i].is_some() || forced[i].is_some() { eprintln!("T76   event at {i} ({:.6}, {:.6}): cusp {} junction {} jump {} forced {}", l[i].sigma, l[i].psi, cusp[i], junctions[i].is_some(), jump_after[i].is_some(), forced[i].is_some()); } }
        }
        if !events {
            let middle = (l[n / 2].sigma, l[n / 2].psi);
            if trace76 {
                let mm: Vec<String> = (0..n).step_by((n / 8).max(1)).map(|i| match mates[i] { Some(m) => format!("({:.4}, {:.4}){}", m.0, m.1, if in_chart(m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)) { "C" } else { "" }), None => "-".into() }).collect();
                eprintln!("T76   no events: own ({:.6}, {:.6})..({:.6}, {:.6}) mates {mm:?} twin_of {:?}", l[0].sigma, l[0].psi, l[n / 2].sigma, l[n / 2].psi, kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)));
            }
            if let Some(k) = kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)) {
                twins[k].extend(l.iter().copied());
                continue;
            }
            kept_mates.push(mates.iter().flatten().copied().collect());
            twins.push(Vec::new());
            curves.push((l.clone(), false, [false, false]));
            continue;
        }
        // The loop as one sequence with its cuts: (point, cut) where cut is 0
        // none, 1 a cusp (ends one arc and starts the next), 2 a junction's
        // last point of an arc, 3 its first point of the next.
        let mut sequence: Vec<(TrimPoint, u8)> = Vec::with_capacity(n + 8);
        for i in 0..n {
            // a jump through a chart ends an arc at its crossing and starts the
            // next at the joined one (the stretch between is the chart's run)
            let into = jump_after[(i + n - 1) % n].is_some();
            let out = jump_after[i].is_some();
            if into && out {
                // between two jumps: an arc of no length (dropped below)
                sequence.push((l[i], 3));
                sequence.push((l[i], 2));
            } else if out {
                sequence.push((l[i], 2));
            } else if into {
                sequence.push((l[i], 3));
            } else if cusp[i] {
                sequence.push((walked[i].expect("walked"), 1));
            } else {
                sequence.push((l[i], 0));
            }
            // (the stretch after a jump's start is the chart's: nothing cut into it)
            if out {
                continue;
            }
            // a junction and a far crossing on one chord: in their order along it
            let far_first = match (junctions[i], forced[i]) {
                (Some((left, _)), Some(far)) => along_chord(l[i], l[(i + 1) % n], (far.sigma, far.psi)).0 < along_chord(l[i], l[(i + 1) % n], (left.sigma, left.psi)).0,
                _ => false,
            };
            if let (true, Some(far)) = (far_first, forced[i]) {
                sequence.push((far, 2));
                sequence.push((far, 3));
            }
            if let Some((left, right)) = junctions[i] {
                sequence.push((left, 2));
                sequence.push((right, 3));
            }
            if let (false, Some(far)) = (far_first, forced[i]) {
                sequence.push((far, 2));
                sequence.push((far, 3));
            }
        }
        // Start at the first cut that begins an arc.
        let first = sequence.iter().position(|(_, c)| *c == 1 || *c == 3).ok_or("a trim loop's cuts start no arc")?;
        sequence.rotate_left(first);
        let total = sequence.len();
        let mut k = 0;
        while k < total {
            let (start, start_cut) = sequence[k];
            let mut arc = vec![start];
            let mut j = k + 1;
            let end_cut = loop {
                let (point, cut) = sequence[j % total];
                if cut == 1 || cut == 2 {
                    arc.push(point);
                    break cut;
                }
                if cut == 3 {
                    return Err("a junction's next arc starts before the last ends".into());
                }
                arc.push(point);
                j += 1;
                if j > k + total {
                    return Err("a trim loop's arc never ends".into());
                }
            };
            // the next arc starts where this one ended (a cusp) or just after (a junction)
            k = if end_cut == 1 { j } else { j + 1 };
            if arc.len() < 2 || arc.iter().all(|p| p.point.sub(arc[0].point).length() <= 1e-12 * size) {
                continue;
            }
            let arc_mates: Vec<(f64, f64)> = arc.iter().filter_map(|p| mate_read(p.point, p.mate_time, p.sigma).map(|(m, _)| m)).collect();
            if trace76 {
                let (a0, a1) = (arc[0], arc[arc.len() - 1]);
                let mm = arc_mates.get(arc_mates.len() / 2).copied().unwrap_or((f64::NAN, f64::NAN));
                eprintln!("T76   arc {} pts ({:.6}, {:.6}) -> ({:.6}, {:.6}) cuts {start_cut}/{end_cut}, middle mate ({:.6}, {:.6}) in_chart {}", arc.len(), a0.sigma, a0.psi, a1.sigma, a1.psi, mm.0, mm.1, in_chart(mm.0.rem_euclid(4.0), mm.1.rem_euclid(TAU)));
                for (p, m) in arc.iter().zip(arc_mates.iter()) { eprintln!("T76     ({:.6}, {:.6}) mate ({:.6}, {:.6})", p.sigma, p.psi, m.0, m.1); }
            }
            // a stretch whose mate lies inside a chart is that chart's run, on its mate side
            // (a stretch of two points: midway between their mates, where those lie within four cells)
            let mate_middle = match arc_mates.len() {
                0 | 1 => None,
                2 => {
                    let (x, y) = (arc_mates[0], arc_mates[1]);
                    let y = (unwrap(y.0, x.0, 4.0), unwrap(y.1, x.1, TAU));
                    (cell_gap((x.0.rem_euclid(4.0), x.1.rem_euclid(TAU)), (y.0.rem_euclid(4.0), y.1.rem_euclid(TAU))) <= 4.0).then_some((0.5 * (x.0 + y.0), 0.5 * (x.1 + y.1)))
                }
                n => Some(arc_mates[n / 2]),
            };
            if mate_middle.is_some_and(|m| in_chart(m.0.rem_euclid(4.0), m.1.rem_euclid(TAU))) {
                if trace76 { eprintln!("T76   -> chart run's mate side (dropped)"); }
                continue;
            }
            let middle = (arc[arc.len() / 2].sigma, arc[arc.len() / 2].psi);
            if let Some(k) = kept_mates.iter().position(|path| path_near(path, middle, &cell_gap)) {
                if trace76 { eprintln!("T76   -> twin of curve {k}"); }
                twins[k].extend(arc.iter().copied());
                continue;
            }
            if trace76 { eprintln!("T76   -> kept as curve {}", curves.len()); }
            kept_mates.push(arc_mates);
            twins.push(Vec::new());
            curves.push((arc, true, [start_cut == 1, end_cut == 1]));
            if k >= total {
                break;
            }
        }
    }

    // Each primary loop: dense exact points with mates, split marks, pieces.
    struct Dense {
        own: Vec<(f64, f64)>,
        mate: Vec<(f64, f64)>,
        point: Vec<Vec3>,
        split: Vec<bool>,
        time: Vec<f64>,
    }
    let mut dense_loops: Vec<(usize, Dense, bool)> = Vec::new();
    let trace_stages = std::env::var("BREP_TUBE_TRACE_STAGES").is_ok();
    for (k, (l, open, cusps)) in curves.iter().enumerate() {
        let (open, cusps) = (*open, *cusps);
        if trace_stages {
            eprintln!("TS dense curve {k}: {} points, open {open}", l.len());
        }
        let mut dense = Dense { own: Vec::new(), mate: Vec::new(), point: Vec::new(), split: Vec::new(), time: Vec::new() };
        let n = l.len();
        let mut previous: Option<(f64, f64)> = None;
        // The last (own, mate) pair: a mate is followed from it where the two
        // stood apart (from a cusp, where they coincide, Newton would settle on
        // the point itself), and kept where it lands apart from its own point.
        let mut last: Option<((f64, f64), (f64, f64))> = None;
        // The mate on the curve's twin: from the twin's point nearest in space,
        // solved onto this point (always the other preimage's branch).
        let twin = &twins[k];
        let on_twin = |point: Vec3, own: (f64, f64)| -> Option<(f64, f64)> {
            // (the twin's ends can be the point's own preimage, shared at a cusp or seam: not a start)
            let near = twin.iter().filter(|t| cell_gap((t.sigma, t.psi), own) > 0.05).min_by(|a, b| a.point.sub(point).length().total_cmp(&b.point.sub(point).length()))?;
            let m = follow(point, (near.sigma, near.psi))?;
            Some((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)))
        };
        // `b` the arc's next point in: the end is a junction for this arc where
        // b's mate stands apart from b (this arc is not the cusp's lens) and a
        // pose other than the end's own reaches it (to 1e-3 of the ring: the
        // end is a lattice reading, not the exact triple point) whose preimage
        // continues b's mate.
        let junction_mate = |a: TrimPoint, b: TrimPoint| -> Option<((f64, f64), f64)> {
            let own_time = tube.own_time(a.sigma);
            let range = tube.to - tube.from;
            let nb = on_twin(b.point, (b.sigma, b.psi))?;
            if cell_gap(nb, (b.sigma, b.psi)) <= 1.0 {
                return None;
            }
            tube.touching_times(a.point, 1e-3 * size)
                .into_iter()
                .filter(|t| (t - own_time).abs() > 1e-3 * range)
                .filter_map(|t| tube.mate_of(a.point, t).map(|m| (m, t)))
                .filter(|(m, _)| cell_gap(*m, nb) <= 2.0 && cell_gap(*m, (a.sigma, a.psi)) > 1.0)
                .min_by(|x, y| cell_gap(x.0, nb).total_cmp(&cell_gap(y.0, nb)))
        };
        let mate_next_read = |point: Vec3, time: f64, own: (f64, f64), last: Option<((f64, f64), (f64, f64))>| -> Option<((f64, f64), f64)> {
            // (never the point itself: Newton can settle on the trivial preimage)
            if let Some(m) = on_twin(point, own).filter(|m| cell_gap(*m, own) > 1e-4) {
                return Some((m, tube.own_time(m.0)));
            }
            if let Some((lo, lm)) = last {
                let apart = cell_gap(lo, lm);
                if apart > 0.05 {
                    if let Some(m) = follow(point, lm) {
                        let m = (m.0.rem_euclid(4.0), m.1.rem_euclid(TAU));
                        if cell_gap(m, own) > 0.25 * apart.min(2.0) {
                            return Some((m, tube.own_time(m.0)));
                        }
                    }
                }
            }
            mate_read(point, time, own.0)
        };
        // A mate that jumps from the last one by far more than the point moved
        // is another preimage read by mistake: followed from the last mate
        // instead where that converges close by.
        let mate_next = |point: Vec3, time: f64, own: (f64, f64), last: Option<((f64, f64), (f64, f64))>| -> Option<((f64, f64), f64)> {
            let read = mate_next_read(point, time, own, last)?;
            if let Some((lo, lm)) = last {
                let step = cell_gap(lo, own);
                if cell_gap(read.0, lm) > 3.0 + 3.0 * step {
                    if let Some(m) = follow(point, lm) {
                        let m = (m.0.rem_euclid(4.0), m.1.rem_euclid(TAU));
                        if cell_gap(m, lm) <= 3.0 + 3.0 * step && cell_gap(m, own) > 1e-4 {
                            return Some((m, tube.own_time(m.0)));
                        }
                    }
                }
            }
            Some(read)
        };
        for i in 0..n {
            if open && i + 1 == n {
                // the open arc's last point (a cusp, its own mate, or a
                // junction, mated across): a split
                let a = l[i];
                let pa = match previous {
                    Some(p) => (unwrap(a.sigma, p.0, 4.0), unwrap(a.psi, p.1, TAU)),
                    None => (a.sigma, a.psi),
                };
                // A cusp of the arc it closes is a junction for this one where a
                // third sheet passes through it: the core circle reaches it at
                // another time too, whose preimage is this arc's mate there.
                let across = if cusps[1] && n >= 2 { junction_mate(a, l[n - 2]) } else { None };
                let (mate, time) = if let Some(m) = across { m } else if cusps[1] { (pa, a.mate_time) } else { mate_read(a.point, a.mate_time, a.sigma).ok_or("a mate is singular [5]")? };
                dense.own.push(pa);
                dense.point.push(a.point);
                dense.mate.push(mate);
                dense.split.push(true);
                dense.time.push(time);
                break;
            }
            let (a, b) = (l[i], l[(i + 1) % n]);
            // a crossing found twice (on a lattice node, by both its edges): one point
            if domain_gap((a.sigma, a.psi), (b.sigma, b.psi)) <= 1e-12 && !(open && i + 2 == n) && !(open && i == 0) {
                continue;
            }
            let pa = match previous {
                Some(p) => (unwrap(a.sigma, p.0, 4.0), unwrap(a.psi, p.1, TAU)),
                None => (a.sigma, a.psi),
            };
            let pb = (unwrap(b.sigma, pa.0, 4.0), unwrap(b.psi, pa.1, TAU));
            // the lattice crossing itself: split where it sits on a patch side
            let on_sigma_side = sigma_bounds.iter().any(|s| wrap(*s, a.sigma, 4.0) <= 1e-12);
            let on_psi_side = psi_bounds.iter().any(|q| wrap(*q, a.psi, TAU) <= 1e-12);
            dense.own.push(pa);
            dense.point.push(a.point);
            // an open arc's first point that is a cusp: its own mate
            let across = if open && i == 0 && cusps[0] && n >= 2 { junction_mate(a, l[1]) } else { None };
            let (mate, time) = if let Some(m) = across { m } else if open && i == 0 && cusps[0] { (pa, a.mate_time) } else { mate_next(a.point, a.mate_time, (a.sigma, a.psi), last).ok_or("a mate is singular [1]")? };
            last = Some(((a.sigma, a.psi), mate));
            dense.mate.push(mate);
            dense.split.push(on_sigma_side || on_psi_side || (open && i == 0));
            dense.time.push(time);
            // (a chord of no length, a crossing found on a lattice node by both its
            // edges at an open arc's end, has nothing between)
            let fractions: &[f64] = if domain_gap(pa, pb) <= 1e-12 { &[] } else { &[0.25, 0.5, 0.75] };
            for &f in fractions {
                let (s, p, time, point) = contour(pa, pb, f, time).map_err(|e| format!("{e} [densify]"))?;
                dense.own.push((unwrap(s, pa.0, 4.0), unwrap(p, pa.1, TAU)));
                dense.point.push(point);
                let (mate, time) = mate_next(point, time, (s.rem_euclid(4.0), p.rem_euclid(TAU)), last).ok_or("a mate is singular [2]")?;
                last = Some(((s.rem_euclid(4.0), p.rem_euclid(TAU)), mate));
                dense.mate.push(mate);
                dense.split.push(false);
                dense.time.push(time);
            }
            previous = Some(pa);
        }
        // A mate that leaves both its neighbours' (which agree) is a read of
        // another preimage or of the point itself: solved again from a
        // neighbour's mate.
        {
            let len = dense.mate.len();
            let wrapped = |x: (f64, f64)| (x.0.rem_euclid(4.0), x.1.rem_euclid(TAU));
            for q in 1..len.saturating_sub(1) {
                let (a, m, b) = (wrapped(dense.mate[q - 1]), wrapped(dense.mate[q]), wrapped(dense.mate[q + 1]));
                let step = cell_gap(wrapped(dense.own[q - 1]), wrapped(dense.own[q + 1]));
                let tol = 3.0 + 3.0 * step;
                if cell_gap(a, b) <= tol && cell_gap(m, a) > tol && cell_gap(m, b) > tol && !dense.split[q] {
                    if let Some(fixed) = follow(dense.point[q], a) {
                        let fixed = wrapped(fixed);
                        if cell_gap(fixed, a) <= tol {
                            dense.mate[q] = fixed;
                            dense.time[q] = tube.own_time(fixed.0);
                        }
                    }
                }
            }
        }
        // Unwrap the mates along the loop, then split where a mate crosses a patch side.
        for i in 1..dense.mate.len() {
            let before = dense.mate[i - 1];
            dense.mate[i] = (unwrap(dense.mate[i].0, before.0, 4.0), unwrap(dense.mate[i].1, before.1, TAU));
        }
        let mut i = 0;
        // A patch side crossed by the mates more often than the contour has
        // points is no crossing but a mate that will not settle: declined
        // before the splits grow without end.
        let split_cap = 2 * dense.own.len() + 64;
        let mut splits = 0usize;
        while i < dense.own.len() {
            if splits > split_cap {
                return Err(format!("a trim curve's mates cross patch sides more than {split_cap} times"));
            }
            if open && i + 1 >= dense.own.len() {
                break;
            }
            let j = (i + 1) % dense.own.len();
            let (ma, mb) = (dense.mate[i], dense.mate[j]);
            let mb = (unwrap(mb.0, ma.0, 4.0), unwrap(mb.1, ma.1, TAU));
            let crossing = |x: f64, y: f64, bounds: &[f64], period: f64| -> Option<f64> {
                bounds.iter().flat_map(|b| (-2..=2).map(move |w| b + w as f64 * period)).find(|b| (x - b) * (y - b) < 0.0 && (x - b).abs() > 1e-12 && (y - b).abs() > 1e-12)
            };
            let found = crossing(ma.0, mb.0, &sigma_bounds, 4.0).map(|b| (0, b)).or_else(|| crossing(ma.1, mb.1, &psi_bounds, TAU).map(|b| (1, b)));
            // (a chord whose mates are not continuous has no crossing to split at)
            let found = found.filter(|_| cell_gap((ma.0.rem_euclid(4.0), ma.1.rem_euclid(TAU)), (mb.0.rem_euclid(4.0), mb.1.rem_euclid(TAU))) <= 3.0 + 3.0 * cell_gap(dense.own[i], dense.own[j]));
            if let Some((axis, bound)) = found {
                let (oa, ob) = (dense.own[i], dense.own[j]);
                let ob = (unwrap(ob.0, oa.0, 4.0), unwrap(ob.1, oa.1, TAU));
                let guess = dense.time[i];
                let mate_coord = |f: f64| -> Result<(f64, (f64, f64), (f64, f64), Vec3), String> {
                    let (s, p, time, point) = contour(oa, ob, f, guess).map_err(|e| format!("{e} [mate-split]"))?;
                    // followed from the chord's first mate (it stays on that branch),
                    // read afresh only where that does not converge
                    let here = (s.rem_euclid(4.0), p.rem_euclid(TAU));
                    // followed from the chord's first mate (the branch the chord's
                    // mates are on), else the trim set's other preimage near it,
                    // else read afresh; never a mate far off that branch
                    let near_ma = |m: &(f64, f64)| cell_gap((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)), (ma.0.rem_euclid(4.0), ma.1.rem_euclid(TAU))) <= 3.0 + cell_gap(oa, ob);
                    let apart = |m: &(f64, f64)| cell_gap((m.0.rem_euclid(4.0), m.1.rem_euclid(TAU)), here) > 1e-4;
                    let followed = follow(point, ma).filter(|m| apart(m) && near_ma(m)).or_else(|| on_twin(point, here).filter(|m| apart(m) && near_ma(m)));
                    let m = match followed {
                        Some(m) => m,
                        None => mate_read(point, time, s).ok_or("a mate is singular [3]")?.0,
                    };
                    let m = (unwrap(m.0, ma.0, 4.0), unwrap(m.1, ma.1, TAU));
                    Ok((if axis == 0 { m.0 } else { m.1 } - bound, (unwrap(s, oa.0, 4.0), unwrap(p, oa.1, TAU)), m, point))
                };
                let (mut lo, mut hi) = (0.0f64, 1.0f64);
                let start = if axis == 0 { ma.0 } else { ma.1 } - bound;
                for _ in 0..50 {
                    let mid = 0.5 * (lo + hi);
                    if (mate_coord(mid)?.0 < 0.0) == (start < 0.0) {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                let (_, own, mut mate, point) = mate_coord(0.5 * (lo + hi))?;
                if axis == 0 {
                    mate.0 = bound;
                } else {
                    mate.1 = bound;
                }
                // Within a tenth of a cell of an open arc's cusp end, a mate
                // crossing is the cusp's own sliver poking across a seam (the two
                // preimages meet there): a piece that short has no patch.
                let near_cusp = |q: usize| cell_gap((dense.own[q].0.rem_euclid(4.0), dense.own[q].1.rem_euclid(TAU)), (own.0.rem_euclid(4.0), own.1.rem_euclid(TAU))) <= 0.1;
                let last = dense.own.len() - 1;
                if open && ((cusps[0] && near_cusp(0)) || (cusps[1] && near_cusp(last))) {
                    i += 1;
                    continue;
                }
                dense.own.insert(i + 1, own);
                dense.mate.insert(i + 1, mate);
                dense.point.insert(i + 1, point);
                dense.split.insert(i + 1, true);
                dense.time.insert(i + 1, guess);
                splits += 1;
            }
            i += 1;
        }
        if !dense.split.iter().any(|s| *s) {
            return Err("a trim loop never crosses a patch side".into());
        }
        dense_loops.push((k, dense, open));
    }
    // Each chart run used by a loop as a curve of its own, built on its mate
    // side only (its own side is the chart's): its points and mates from the
    // chart, split where the mate crosses a patch side (the split's point on
    // exact K at the side).
    let regular_loops = dense_loops.len();
    if trace_stages {
        eprintln!("TS chart runs");
    }
    let mut chart_runs: Vec<(usize, usize)> = Vec::new();
    for (c, rim) in rims.iter().enumerate() {
        for (r, edge) in rim.edges.iter().enumerate() {
            // an internal edge (both sides the chart's) is the chart faces' alone
            let Some(outside) = edge.outside.as_ref() else { continue };
            let n = edge.points.len();
            if n < 2 || outside.len() != n {
                return Err("a chart edge has too few points".into());
            }
            let side_of = |pm: (f64, f64), m: (f64, f64)| -> Option<(u8, f64)> {
                let across = |x: f64, y: f64, bounds: &[f64], period: f64| -> Option<f64> {
                    bounds.iter().flat_map(|b| (-2..=2).map(move |w| b + w as f64 * period)).find(|b| (x - b) * (y - b) < 0.0 && (x - b).abs() > 1e-12 && (y - b).abs() > 1e-12)
                };
                across(pm.0, m.0, &sigma_bounds, 4.0).map(|b| (0, b)).or_else(|| across(pm.1, m.1, &psi_bounds, TAU).map(|b| (1, b)))
            };
            let mut dense = Dense { own: Vec::new(), mate: Vec::new(), point: Vec::new(), split: Vec::new(), time: Vec::new() };
            for k in 0..n {
                let m = (outside[k].sigma, outside[k].psi);
                let m = match dense.mate.last() {
                    Some(pm) => (unwrap(m.0, pm.0, 4.0), unwrap(m.1, pm.1, TAU)),
                    None => m,
                };
                // own: the chart's; the mate stands in (never built)
                if let Some(&pm) = dense.mate.last() {
                    if let Some((axis, bound)) = side_of(pm, m) {
                        let (ca, cb) = if axis == 0 { (pm.0, m.0) } else { (pm.1, m.1) };
                        let f = (bound - ca) / (cb - ca);
                        let mut at = (pm.0 + (m.0 - pm.0) * f, pm.1 + (m.1 - pm.1) * f);
                        if axis == 0 {
                            at.0 = bound;
                        } else {
                            at.1 = bound;
                        }
                        let point = tube.k_at(at.0.rem_euclid(4.0), at.1.rem_euclid(TAU)).ok_or("K is singular on a chart edge's mate side")?;
                        dense.own.push(at);
                        dense.mate.push(at);
                        dense.point.push(point);
                        dense.split.push(true);
                        dense.time.push(outside[k].mate_time);
                    }
                }
                dense.own.push(m);
                dense.mate.push(m);
                dense.point.push(edge.points[k]);
                dense.split.push(k == 0 || k + 1 == n);
                dense.time.push(outside[k].mate_time);
            }
            dense_loops.push((usize::MAX, dense, true));
            chart_runs.push((c, r));
        }
    }
    let _ = (fit, lattice);
    // Pieces between split points; each lies in one own patch and one mate patch.
    struct Raw {
        own_patch: (usize, usize),
        mate_patch: (usize, usize),
        own: Vec<(f64, f64)>,
        mate: Vec<(f64, f64)>,
        points: Vec<Vec3>,
        times: Vec<f64>,
        marks: [Mark; 2],
        /// A chart run's piece: built on its mate side only.
        chart: bool,
        /// The dense curve it is a piece of.
        source: usize,
    }
    let mut raws: Vec<Raw> = Vec::new();
    #[allow(unused_mut)]
    for (index, (_, dense, open)) in dense_loops.iter().enumerate() {
        let n = dense.own.len();
        let first = dense.split.iter().position(|s| *s).unwrap();
        let mut start = first;
        loop {
            if *open && start + 1 >= n {
                break; // an open branch ends at its last cusp
            }
            let mut end = (start + 1) % n;
            let mut own = vec![dense.own[start]];
            let mut mate = vec![dense.mate[start]];
            let mut points = vec![dense.point[start]];
            let mut times = vec![dense.time[start]];
            loop {
                let last = *own.last().unwrap();
                let o = dense.own[end];
                own.push((unwrap(o.0, last.0, 4.0), unwrap(o.1, last.1, TAU)));
                let lm = *mate.last().unwrap();
                let m = dense.mate[end];
                mate.push((unwrap(m.0, lm.0, 4.0), unwrap(m.1, lm.1, TAU)));
                points.push(dense.point[end]);
                times.push(dense.time[end]);
                if dense.split[end] {
                    break;
                }
                end = (end + 1) % n;
            }
            let middle = own.len() / 2;
            let (om, mm) = (own[middle], mate[middle]);
            let (om, mm) = if own.len() == 2 { ((0.5 * (own[0].0 + own[1].0), 0.5 * (own[0].1 + own[1].1)), (0.5 * (mate[0].0 + mate[1].0), 0.5 * (mate[0].1 + mate[1].1))) } else { (om, mm) };
            raws.push(Raw {
                own_patch: (row_of(om.0), column_of(om.1)),
                mate_patch: (row_of(mm.0), column_of(mm.1)),
                own,
                mate,
                points,
                times,
                marks: [Mark::Split(index, start), Mark::Split(index, end)],
                chart: index >= regular_loops,
                source: index,
            });
            start = end;
            if start == first || (*open && start + 1 >= n) {
                break;
            }
        }
    }
    // A point reached as the end of arcs of different loops (a junction, or a
    // cusp met from both sides) is named by each arc's own split: one name
    // per point, so the faces chain through it.
    {
        let weld = 1e-7 * (tube.major + tube.minor);
        let mut names: Vec<(Mark, Vec3)> = Vec::new();
        for raw in raws.iter_mut() {
            for end in 0..2 {
                let Mark::Split(l, i) = raw.marks[end] else { continue };
                let point = dense_loops[l].1.point[i];
                match names.iter().find(|(_, q)| q.sub(point).length() <= weld) {
                    Some((name, _)) => raw.marks[end] = *name,
                    None => names.push((raw.marks[end], point)),
                }
            }
        }
    }
    // Each piece refined until its curve passes within `fit` of the exact
    // contour: a gap that misses gets its exact midpoint (with its mate).
    if trace_stages {
        eprintln!("TS refine {} raws", raws.len());
    }
    for (raw_index, raw) in raws.iter_mut().enumerate() {
        if trace_stages {
            eprintln!("TS   raw {raw_index}: {} points, source {}, own ({:.6}, {:.6})", raw.points.len(), raw.source, raw.own[0].0, raw.own[0].1);
        }
        // a chart run's points are the chart's exact ones
        if raw.chart {
            continue;
        }
        // good[k]: gap k already within the fit (its stations unchanged since).
        let mut good = vec![false; raw.points.len() - 1];
        let mut settled = false;
        for _round in 0..32 {
            if raw.points.len() > 4096 {
                return Err(format!("a trim edge does not settle within the fit {edge_fit:.1e} (over 4096 stations)"));
            }
            if trace_stages && _round < 6 {
                for k in 0..raw.own.len() {
                    eprintln!("TS     round {_round} k {k} own ({:.6}, {:.6}) mate ({:.6}, {:.6}) t {:.5} good {}", raw.own[k].0, raw.own[k].1, raw.mate[k].0, raw.mate[k].1, raw.times[k], k < good.len() && good[k]);
                }
            }
            let mut params = vec![0.0];
            for pair in raw.points.windows(2) {
                params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
            }
            let total = *params.last().unwrap();
            let params: Vec<f64> = params.iter().map(|t| t / total).collect();
            let curve = crate::interpolate_curve(&raw.points, 3.min(raw.points.len() - 1), &params)?;
            // The piece's two domain paths at the curve's own parameters (its
            // coedges' pcurves are fitted so): between stations each must lie on
            // the curve's point at the same parameter too.
            let path = |line: &[(f64, f64)]| crate::interpolate_curve(&line.iter().map(|(x, y)| Vec3::new(*x, *y, 0.0)).collect::<Vec<_>>(), 3.min(line.len() - 1), &params);
            let (own_path, mate_path) = (path(&raw.own)?, path(&raw.mate)?);
            let last = raw.own.len() - 1;
            let folds = [0, last].iter().any(|&k| cell_gap((raw.own[k].0.rem_euclid(4.0), raw.own[k].1.rem_euclid(TAU)), (raw.mate[k].0.rem_euclid(4.0), raw.mate[k].1.rem_euclid(TAU))) <= 1e-6);
            let apart = |path: &crate::NurbsCurve, t: f64| -> f64 {
                match (path.evaluate(t), curve.evaluate(t)) {
                    (Ok(q), Ok(c)) => tube.k_at(q.x.rem_euclid(4.0), q.y.rem_euclid(TAU)).map(|p| p.sub(c).length()).unwrap_or(0.0),
                    _ => 0.0,
                }
            };
            let mut inserts: Vec<(usize, (f64, f64), (f64, f64), f64, Vec3)> = Vec::new();
            for (k, fraction) in (0..raw.points.len() - 1).filter(|k| !good[*k]).flat_map(|k| [0.25, 0.5, 0.75].map(|f| (k, f))) {
                // a quarter point past a lens tip's reach (the contour turns
                // within the gap): the middle is read instead
                // the competitor's time is the mate's own time (exact, where a
                // stored read time can be a self-read's)
                let guess = tube.own_time(raw.mate[k].0.rem_euclid(4.0));
                let (s_mid, p_mid, time, target) = match contour(raw.own[k], raw.own[k + 1], fraction, guess) {
                    Ok(found) => found,
                    Err(_) if fraction != 0.5 => continue,
                    Err(e) => return Err(format!("{e} [refine]")),
                };
                let (lo, hi) = (params[k], params[k + 1]);
                let distance = |t: f64| curve.evaluate(t).map(|p| p.sub(target).length()).unwrap_or(f64::INFINITY);
                let mut best = (f64::INFINITY, lo);
                for j in 0..=32 {
                    let t = lo + (hi - lo) * j as f64 / 32.0;
                    let d = distance(t);
                    if d < best.0 {
                        best = (d, t);
                    }
                }
                let step = (hi - lo) / 32.0;
                let (mut a, mut b) = ((best.1 - step).max(lo), (best.1 + step).min(hi));
                let ratio = 0.5 * (5f64.sqrt() - 1.0);
                for _ in 0..60 {
                    let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
                    if distance(c) < distance(d) {
                        b = d;
                    } else {
                        a = c;
                    }
                }
                let miss_here = distance(0.5 * (a + b)).min(best.0);
                // (a piece that ends at a fold's fixed point is read on its own side
                // only: next to the fixed point a mate read falls onto the point
                // itself, so its mate path does not close up under more stations)
                let miss_here = if fraction == 0.5 {
                    let own_miss = 2.0 * apart(&own_path, 0.5 * (lo + hi));
                    let mate_miss = if folds { 0.0 } else { 2.0 * apart(&mate_path, 0.5 * (lo + hi)) };
                    miss_here.max(own_miss).max(mate_miss)
                } else {
                    miss_here
                };
                // A miss at the gap's quarter or middle point: the gap gets its
                // exact middle (once), which halves it.
                if miss_here > edge_fit && fraction == 0.5 || miss_here > edge_fit && !inserts.iter().any(|i| i.0 == k + 1) {
                    if trace_stages && _round < 6 {
                        eprintln!("TS     miss {miss_here:.3e} at gap {k} fraction {fraction} mid ({s_mid:.6}, {p_mid:.6})");
                    }
                    let (s_mid, p_mid, time, target) = if fraction == 0.5 { (s_mid, p_mid, time, target) } else { contour(raw.own[k], raw.own[k + 1], 0.5, guess)? };
                    let own = (unwrap(s_mid, raw.own[k].0, 4.0), unwrap(p_mid, raw.own[k].1, TAU));
                    let (m, _) = mate_read(target, time, s_mid).ok_or("a mate is singular [4]")?;
                    let mate = (unwrap(m.0, raw.mate[k].0, 4.0), unwrap(m.1, raw.mate[k].1, TAU));
                    if !inserts.iter().any(|i| i.0 == k + 1) {
                        inserts.push((k + 1, own, mate, time, target));
                    }
                }
            }
            if inserts.is_empty() {
                // Settled only by a round that read every gap: the interpolant
                // is global, so a point added elsewhere moves the whole curve.
                if good.iter().all(|g| !g) {
                    settled = true;
                    break;
                }
                good.iter_mut().for_each(|g| *g = false);
                continue;
            }
            // Every gap not split this round passed; a split gap's two halves are read next round.
            let split: std::collections::HashSet<usize> = inserts.iter().map(|i| i.0 - 1).collect();
            let mut next_good = Vec::with_capacity(good.len() + inserts.len());
            for k in 0..good.len() {
                if split.contains(&k) {
                    next_good.push(false);
                    next_good.push(false);
                } else {
                    next_good.push(true);
                }
            }
            good = next_good;
            for (at, own, mate, time, point) in inserts.into_iter().rev() {
                raw.own.insert(at, own);
                raw.mate.insert(at, mate);
                raw.times.insert(at, time);
                raw.points.insert(at, point);
            }
        }
        if !settled {
            return Err(format!("a trim edge does not settle within the fit {edge_fit:.1e} in 32 rounds"));
        }
    }
    let patch_box = |a: usize, b: usize| -> ([f64; 2], [f64; 2]) { ([sigma_bounds[a], sigma_bounds[a + 1]], [psi_bounds[b], psi_end(b)]) };
    // A domain polyline moved into patch (a, b)'s own ranges.
    let localise = |line: &[(f64, f64)], a: usize, b: usize| -> Vec<(f64, f64)> {
        let (su, pv) = patch_box(a, b);
        let m = line[line.len() / 2];
        let (ds, dp) = (((0.5 * (su[0] + su[1]) - m.0) / 4.0).round() * 4.0, ((0.5 * (pv[0] + pv[1]) - m.1) / TAU).round() * TAU);
        line.iter().map(|(x, y)| (x + ds, y + dp)).collect()
    };
    // Orient a polyline so the kept side (g ≥ 0) is on its left.
    let kept_left = |line: &[(f64, f64)]| -> Result<bool, String> {
        let k = (line.len() / 2).max(1).min(line.len() - 1);
        let (a, b) = (line[k - 1], line[k]);
        let (ds, dp) = (cell_sigma(a.0), cell_psi);
        let (cs, cp) = ((b.0 - a.0) / ds, (b.1 - a.1) / dp);
        let length = cs.hypot(cp);
        if !(length > 0.0) {
            return Err("a trim piece has no length".into());
        }
        let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
        let left = (m.0 - 0.05 * cp / length * ds, m.1 + 0.05 * cs / length * dp);
        Ok(g_at(left.0, left.1).ok_or("K is singular near a trim curve")?.0 >= 0.0)
    };
    let mut held: std::collections::HashMap<(usize, usize), Vec<Piece>> = std::collections::HashMap::new();
    for (e, raw) in raws.iter().enumerate() {
        // The piece's two uses (its own side and its mate's) are the two
        // coedges of one edge of an oriented shell, so they run opposite ways:
        // the own side is read for its kept side, the mate side follows (a
        // reading there can land past a thin lens near a cusp).
        // (a chart run's piece: its own side is the chart face's, so its kept
        // side is read on its mate side, and only that side is built here)
        let own_forward = if raw.chart { !kept_left(&localise(&raw.mate, raw.mate_patch.0, raw.mate_patch.1))? } else { kept_left(&localise(&raw.own, raw.own_patch.0, raw.own_patch.1))? };
        for (side, (patch, line)) in [(raw.own_patch, &raw.own), (raw.mate_patch, &raw.mate)].into_iter().enumerate() {
            if raw.chart && side == 0 {
                continue;
            }
            let mut domain = localise(line, patch.0, patch.1);
            let mut marks = raw.marks;
            let forward = if side == 0 { own_forward } else { !own_forward };
            if !forward {
                domain.reverse();
                marks.swap(0, 1);
            }
            held.entry(patch).or_default().push(Piece { marks, domain, edge: (0, e), forward });
        }
    }
    // Topology.
    use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
    let mut next = 1u64;
    let mut id = || {
        next += 1;
        next - 1
    };
    let mut vertices: Vec<VertexRecord> = Vec::new();
    let mut vertex_ids: std::collections::HashMap<Mark, u64> = std::collections::HashMap::new();
    let mut vertex = |mark: Mark, point: Vec3, id: &mut dyn FnMut() -> u64| -> u64 {
        *vertex_ids.entry(mark).or_insert_with(|| {
            let vid = id();
            vertices.push(VertexRecord { id: vid, point });
            vid
        })
    };
    let mark_point = |mark: Mark| -> Result<Vec3, String> {
        match mark {
            Mark::Corner(a, b) => tube.k_at(sigma_bounds[a % rows.len()], psi_bounds[b % columns]).ok_or_else(|| "K is singular at a corner".to_string()),
            Mark::Split(l, i) => Ok(dense_loops[l].1.point[i]),
            Mark::Chart(c, k) => Ok(rims[c].vertices[k]),
        }
    };
    let curve_through = |points: &[Vec3]| -> Result<crate::NurbsCurve, String> {
        let mut params = vec![0.0];
        for pair in points.windows(2) {
            params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
        }
        let total = *params.last().unwrap();
        let params: Vec<f64> = params.iter().map(|t| t / total).collect();
        crate::interpolate_curve(points, 3.min(points.len() - 1), &params)
    };
    // The parameters a polyline's curve takes its points at: its 3D chord
    // lengths, as `curve_through` does. An edge and the pcurves whose stations
    // are its points' own domain points are fitted at these same parameters, so
    // they agree station for station.
    let chord_parameters = |points: &[Vec3]| -> Vec<f64> {
        let mut params = vec![0.0];
        for pair in points.windows(2) {
            params.push(params.last().unwrap() + pair[1].sub(pair[0]).length().max(1e-300));
        }
        let total = *params.last().unwrap();
        params.iter().map(|t| t / total).collect()
    };
    // (a coedge that runs against its edge takes the stations the other way round)
    let station_pcurve = |uv: &[Vec3], edge_points: &[Vec3], forward: bool| -> Result<crate::NurbsCurve, String> {
        let mut params = chord_parameters(edge_points);
        if !forward {
            params = params.iter().rev().map(|t| 1.0 - t).collect();
        }
        crate::interpolate_curve(uv, 3.min(uv.len() - 1), &params)
    };
    // A coedge's pcurve at its edge's own parameters: the polyline's curve gives
    // the path on the face, and each station is the path's point whose 3D point
    // is the edge curve's at an even parameter (the foot along the edge's
    // tangent, by secant from the even guess), so a parameter of the edge and
    // the same fraction of the pcurve are one point. The path itself stands
    // where the stations read no closer to the edge than it does.
    let same_parameter = |surface: &crate::NurbsSurface, curve: &crate::NurbsCurve, t0: f64, t1: f64, forward: bool, uv: &[Vec3]| -> Result<crate::NurbsCurve, String> {
        let path = curve_through(uv)?;
        let [q0, q1] = path.domain()?;
        let lift = |c: &crate::NurbsCurve, q: f64| -> Option<Vec3> {
            let p = c.evaluate(q).ok()?;
            surface.evaluate_extended(p.x, p.y).ok()
        };
        let edge_at = |fraction: f64| if forward { t0 + (t1 - t0) * fraction } else { t1 - (t1 - t0) * fraction };
        let off = |c: &crate::NurbsCurve| -> f64 {
            let Ok([c0, c1]) = c.domain() else { return f64::INFINITY };
            (0..67)
                .map(|k| {
                    let f = (k as f64 + 0.5) / 67.0;
                    match (lift(c, c0 + (c1 - c0) * f), curve.evaluate(edge_at(f))) {
                        (Some(a), Ok(b)) => a.sub(b).length(),
                        _ => f64::INFINITY,
                    }
                })
                .fold(0.0, f64::max)
        };
        // (stations doubled until the two agree to 5e-7 between them, 1600 at most)
        let mut best: Option<(f64, crate::NurbsCurve)> = None;
        let mut count = (2 * (uv.len() - 1)).clamp(8, 400);
        loop {
        let mut stations = Vec::with_capacity(count + 1);
        let mut last = q0;
        for j in 0..=count {
            let fraction = j as f64 / count as f64;
            if j == 0 || j == count {
                stations.push(path.evaluate(if j == 0 { q0 } else { q1 })?);
                continue;
            }
            let t = edge_at(fraction);
            let target = curve.evaluate(t)?;
            let h = 1e-4 * (t1 - t0);
            let tangent = curve.evaluate((t + h).min(t0.max(t1)))?.sub(curve.evaluate((t - h).max(t0.min(t1)))?);
            let tangent = if forward { tangent } else { tangent.scale(-1.0) };
            let ahead = |q: f64| lift(&path, q).map(|p| p.sub(target).dot(tangent));
            let guess = (q0 + (q1 - q0) * fraction).max(last);
            let step = (q1 - q0) / count as f64;
            let (mut a, mut b) = (guess, (guess + 0.25 * step).min(q1));
            if b <= a {
                a = (b - 0.25 * step).max(q0);
            }
            let (mut fa, mut fb) = (ahead(a).ok_or("a pcurve station is off its face")?, ahead(b).ok_or("a pcurve station is off its face")?);
            for _ in 0..24 {
                if !(fb - fa).is_finite() || (fb - fa).abs() <= 1e-300 || (b - a).abs() <= 1e-14 * (q1 - q0) {
                    break;
                }
                let next = (b - fb * (b - a) / (fb - fa)).clamp(last, q1);
                a = b;
                fa = fb;
                b = next;
                fb = ahead(b).ok_or("a pcurve station is off its face")?;
            }
            last = b.clamp(last, q1);
            stations.push(path.evaluate(last)?);
        }
        let params: Vec<f64> = (0..=count).map(|j| j as f64 / count as f64).collect();
        if let Ok(matched) = crate::interpolate_curve(&stations, 3, &params) {
            let miss = off(&matched);
            if best.as_ref().is_none_or(|b| miss < b.0) {
                best = Some((miss, matched));
            }
        }
        if best.as_ref().is_some_and(|b| b.0 <= 5e-7) || count >= 1600 {
            break;
        }
        count *= 2;
        }
        match best {
            Some((miss, matched)) if miss <= off(&path) => Ok(matched),
            _ => Ok(path),
        }
    };
    let mut edges: Vec<EdgeRecord> = Vec::new();
    let mut piece_edges: std::collections::HashMap<usize, u64> = std::collections::HashMap::new();
    let mut side_edges: std::collections::HashMap<(u8, usize, usize, Mark, Mark), (u64, Mark)> = std::collections::HashMap::new();
    let mut faces: Vec<FaceRecord> = Vec::new();
    let mut face_charts: Vec<usize> = Vec::new();
    let mut fits: std::collections::HashMap<(usize, usize), crate::NurbsSurface> = std::collections::HashMap::new();
    let mut orient_by: Option<(usize, [f64; 2], [f64; 2])> = None;
    for a in 0..rows.len() {
        for b in 0..columns {
            let (su, pv) = patch_box(a, b);
            if trace_stages {
                eprintln!("TS patch ({a}, {b})");
            }
            // inside a chart's box: the chart's faces stand there
            if in_chart(0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1])) {
                continue;
            }
            let pieces = held.remove(&(a, b)).unwrap_or_default();
            if std::env::var("BREP_TUBE_TRACE_PATCH").ok().is_some_and(|v| v == format!("{a},{b}")) {
                eprintln!("TP patch ({a}, {b}): sigma {:?} psi {:?}", su, pv);
                for (k, p) in pieces.iter().enumerate() {
                    eprintln!("TP   piece {k}: {:?} -> {:?} from ({:.6}, {:.6}) to ({:.6}, {:.6}) n {} edge {:?} forward {}", p.marks[0], p.marks[1], p.domain[0].0, p.domain[0].1, p.domain.last().unwrap().0, p.domain.last().unwrap().1, p.domain.len(), p.edge, p.forward);
                }
            }
            let whole = pieces.is_empty();
            if pieces.is_empty() {
                let (g, _, _) = g_at(0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1])).ok_or("K is singular")?;
                if g < 0.0 {
                    continue; // covered whole
                }
            }
            let chart = rows[a].0;
            let surface = match fits.get(&(a, b)) {
                Some(found) => found.clone(),
                None => {
                    let (surface, ..) = super::fit_patch(tube, chart, [rows[a].1, rows[a].2], pv, fit).map_err(|e| e.message)?;
                    fits.insert((a, b), surface.clone());
                    surface
                }
            };
            // Perimeter positions in [0, 4): bottom (ψ = p0) 0..1, right (σ = s1) 1..2, top 2..3, left 3..4.
            let position = |(x, y): (f64, f64)| -> Result<f64, String> {
                let (fx, fy) = ((x - su[0]) / (su[1] - su[0]), (y - pv[0]) / (pv[1] - pv[0]));
                let near = |v: f64, t: f64| (v - t).abs() <= 1e-7;
                Ok(if near(fy, 0.0) {
                    fx.clamp(0.0, 1.0)
                } else if near(fx, 1.0) {
                    1.0 + fy.clamp(0.0, 1.0)
                } else if near(fy, 1.0) {
                    2.0 + (1.0 - fx).clamp(0.0, 1.0)
                } else if near(fx, 0.0) {
                    3.0 + (1.0 - fy).clamp(0.0, 1.0)
                } else {
                    return Err(format!("a trim piece ends inside patch ({a}, {b}) at ({fx:.6}, {fy:.6})"));
                })
            };
            let at_position = |t: f64| -> (f64, f64) {
                let f = t - t.floor();
                match t.floor() as i64 {
                    0 => (su[0] + (su[1] - su[0]) * f, pv[0]),
                    1 => (su[1], pv[0] + (pv[1] - pv[0]) * f),
                    2 => (su[1] - (su[1] - su[0]) * f, pv[1]),
                    _ => (su[0], pv[1] - (pv[1] - pv[0]) * f),
                }
            };
            // Chain the pieces end to end where they meet inside the patch
            // (a split made on the mate's side): only a chain's ends lie on
            // the perimeter.
            let mut chains: Vec<Vec<usize>> = Vec::new();
            {
                // One point of K can have two preimages in a patch (a fold's
                // double curve): its mark then starts two pieces, and the run
                // goes on with the one that starts where the last ended.
                let near = |x: (f64, f64), y: (f64, f64)| (x.0 - y.0).hypot(x.1 - y.1);
                let next_after = |tail: Mark, at: (f64, f64), taken: &[bool]| -> Option<usize> {
                    (0..pieces.len()).filter(|&k| !taken[k] && pieces[k].marks[0] == tail).min_by(|&x, &y| near(pieces[x].domain[0], at).total_cmp(&near(pieces[y].domain[0], at)))
                };
                let ends: std::collections::HashSet<Mark> = pieces.iter().map(|p| p.marks[1]).collect();
                let mut taken = vec![false; pieces.len()];
                for k in 0..pieces.len() {
                    if taken[k] || (ends.contains(&pieces[k].marks[0]) && position(pieces[k].domain[0]).is_err()) {
                        continue;
                    }
                    let mut chain = vec![k];
                    taken[k] = true;
                    let mut tail = pieces[k].marks[1];
                    while position(*pieces[*chain.last().unwrap()].domain.last().unwrap()).is_err() {
                        let at = *pieces[*chain.last().unwrap()].domain.last().unwrap();
                        let next = match next_after(tail, at, &taken) {
                            Some(next) => next,
                            None if pieces.iter().any(|p| p.marks[0] == tail) => return Err(format!("a trim run closes inside patch ({a}, {b})")),
                            None => return Err(format!("a trim run stops inside patch ({a}, {b})")),
                        };
                        taken[next] = true;
                        chain.push(next);
                        tail = pieces[next].marks[1];
                    }
                    chains.push(chain);
                }
                if taken.iter().any(|t| !t) {
                    return Err(format!("a trim run of patch ({a}, {b}) never reaches its sides"));
                }
            }
            let corners = [Mark::Corner(a, b), Mark::Corner((a + 1) % rows.len(), b), Mark::Corner((a + 1) % rows.len(), (b + 1) % columns), Mark::Corner(a, (b + 1) % columns)];
            let mut stops: Vec<(f64, Mark)> = (0..4).map(|k| (k as f64, corners[k])).collect();
            for chain in &chains {
                let (first, last) = (&pieces[chain[0]], &pieces[*chain.last().unwrap()]);
                stops.push((position(first.domain[0])?, first.marks[0]));
                stops.push((position(*last.domain.last().unwrap())?, last.marks[1]));
            }
            stops.sort_by(|x, y| x.0.total_cmp(&y.0));
            stops.dedup_by(|x, y| (x.0 - y.0).abs() <= 1e-9 && x.1 == y.1);
            // Oriented segments: (from, to, kind). kind 0: a piece (index), 1: a side run (t0, t1).
            #[derive(Clone, Copy)]
            enum Run {
                Piece(usize),
                Side(f64, f64),
            }
            let mut segments: Vec<(Mark, Mark, Run)> = pieces.iter().enumerate().map(|(k, p)| (p.marks[0], p.marks[1], Run::Piece(k))).collect();
            let _ = &chains;
            for k in 0..stops.len() {
                let (t0, m0) = stops[k];
                let (mut t1, m1) = stops[(k + 1) % stops.len()];
                if t1 <= t0 {
                    t1 += 4.0;
                }
                if t1 - t0 <= 1e-12 {
                    continue;
                }
                let middle = at_position((0.5 * (t0 + t1)).rem_euclid(4.0));
                if g_at(middle.0, middle.1).ok_or("K is singular")?.0 >= 0.0 {
                    segments.push((m0, m1, Run::Side(t0, t1)));
                }
            }
            let trace_patch = std::env::var("BREP_TUBE_TRACE_PATCH").ok().is_some_and(|v| v == format!("{a},{b}"));
            if trace_patch {
                for (t, m) in &stops {
                    eprintln!("TP   stop {t:.6} {m:?}");
                }
                for (m0, m1, run) in &segments {
                    if let Run::Side(t0, t1) = run {
                        eprintln!("TP   side {t0:.6}..{t1:.6} {m0:?} -> {m1:?}");
                    }
                }
            }
            // Chain into loops.
            let mut used = vec![false; segments.len()];
            for start in 0..segments.len() {
                if used[start] {
                    continue;
                }
                let mut chain = vec![start];
                used[start] = true;
                // Each segment's ends in the patch's domain: a mark can name
                // two points of one patch (a fold's double curve), so a loop
                // goes on from where its last segment ended.
                let ends_of = |k: usize| -> ((f64, f64), (f64, f64)) {
                    match segments[k].2 {
                        Run::Piece(i) => (pieces[i].domain[0], *pieces[i].domain.last().unwrap()),
                        Run::Side(t0, t1) => (at_position(t0.rem_euclid(4.0)), at_position(t1.rem_euclid(4.0))),
                    }
                };
                let gap = |x: (f64, f64), y: (f64, f64)| (x.0 - y.0).hypot(x.1 - y.1);
                let first = segments[start].0;
                let first_at = ends_of(start).0;
                let mut tail = segments[start].1;
                let mut tail_at = ends_of(start).1;
                while !(tail == first && gap(tail_at, first_at) <= 1e-6) {
                    let next = (0..segments.len())
                        .filter(|&k| !used[k] && segments[k].0 == tail)
                        .min_by(|&x, &y| gap(ends_of(x).0, tail_at).total_cmp(&gap(ends_of(y).0, tail_at)));
                    let next = match next {
                        Some(next) => next,
                        // the loop's start is the only way on: closed (its ends one mark)
                        None if tail == first => break,
                        None => {
                            if trace_patch {
                                eprintln!("TP   stuck at {tail:?} ({:.6}, {:.6}), loop from {first:?} ({:.6}, {:.6}), chain {}", tail_at.0, tail_at.1, first_at.0, first_at.1, chain.len());
                            }
                            return Err(format!("a face loop of patch ({a}, {b}) does not close"));
                        }
                    };
                    tail_at = ends_of(next).1;
                    used[next] = true;
                    chain.push(next);
                    tail = segments[next].1;
                }
                // Coedges.
                let mut coedges = Vec::new();
                for &k in &chain {
                    let (m0, m1, run) = segments[k];
                    let v0 = vertex(m0, mark_point(m0)?, &mut id);
                    let v1 = vertex(m1, mark_point(m1)?, &mut id);
                    match run {
                        Run::Piece(index) => {
                            let piece = &pieces[index];
                            let e = piece.edge.1;
                            let edge_id = match piece_edges.get(&e) {
                                Some(found) => *found,
                                None => {
                                    let raw = &raws[e];
                                    let curve = curve_through(&raw.points)?;
                                    // Within the fit of the contour: its refinement above ended on a round
                                    // with every gap's quarter points and middle inside it.
                                    let [t0, t1] = curve.domain()?;
                                    let eid = id();
                                    let (s0, s1) = (vertex(raw.marks[0], mark_point(raw.marks[0])?, &mut id), vertex(raw.marks[1], mark_point(raw.marks[1])?, &mut id));
                                    edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
                                    if trace_stages {
                                        eprintln!("TS edge {eid} raw {e} source {} chart {} n {} own ({:.6}, {:.6}) -> ({:.6}, {:.6}) mate ({:.6}, {:.6}) -> ({:.6}, {:.6})", raw.source, raw.chart, raw.points.len(), raw.own[0].0, raw.own[0].1, raw.own[raw.own.len() - 1].0, raw.own[raw.own.len() - 1].1, raw.mate[0].0, raw.mate[0].1, raw.mate[raw.mate.len() - 1].0, raw.mate[raw.mate.len() - 1].1);
                                    }
                                    piece_edges.insert(e, eid);
                                    eid
                                }
                            };
                            let chart = rows[a].0 as f64;
                            let uv: Vec<Vec3> = piece.domain.iter().map(|(x, y)| Vec3::new(x - chart, *y, 0.0)).collect();
                            let record = edges.iter().find(|r| r.id == edge_id).ok_or("a trim piece has no edge")?;
                            let pcurve = if uv.len() == raws[e].points.len() && uv.len() >= 2 {
                                station_pcurve(&uv, &raws[e].points, piece.forward)?
                            } else {
                                same_parameter(&surface, &record.curve, record.t0, record.t1, piece.forward, &uv)?
                            };
                            coedges.push(CoedgeRecord { id: id(), edge_id, forward: piece.forward, pcurve });
                        }
                        Run::Side(t0, t1) => {
                            let side = t0.floor() as i64;
                            let (pa, pb) = (at_position(t0.rem_euclid(4.0)), at_position(if t1 - t1.floor() == 0.0 && t1.floor() as i64 == side + 1 { t1 - 1e-15 } else { t1.rem_euclid(4.0) }));
                            let pb = if t1 >= (side + 1) as f64 - 1e-15 { at_position(((side + 1) as f64 - 1e-15).rem_euclid(4.0)) } else { pb };
                            let pb = if t1 >= (side + 1) as f64 - 1e-15 { match side { 0 => (su[1], pv[0]), 1 => (su[1], pv[1]), 2 => (su[0], pv[1]), _ => (su[0], pv[0]) } } else { pb };
                            // the side line, named by the patch pair it parts
                            let key_line: (u8, usize, usize) = match side {
                                0 => (1, a, b),
                                1 => (0, (a + 1) % rows.len(), b),
                                2 => (1, a, (b + 1) % columns),
                                _ => (0, a, b),
                            };
                            let (lo, hi) = if m0 <= m1 { (m0, m1) } else { (m1, m0) };
                            let key = (key_line.0, key_line.1, key_line.2, lo, hi);
                            let (edge_id, edge_start) = match side_edges.get(&key) {
                                Some(found) => *found,
                                None => {
                                    // The face's own iso-curve along the side, cut to the run
                                    // (the neighbour across the side has the same one: both
                                    // patches interpolate the same boundary stations).
                                    let local = rows[a].0 as f64;
                                    let (iso, from_t, to_t) = match side {
                                        0 | 2 => (surface.iso_curve_v(pa.1)?, pa.0 - local, pb.0 - local),
                                        _ => (surface.iso_curve_u(pa.0 - local)?, pa.1, pb.1),
                                    };
                                    let (lo_t, hi_t) = (from_t.min(to_t), from_t.max(to_t));
                                    let [d0, d1] = iso.domain()?;
                                    let mut piece_curve = iso;
                                    // `split` refuses a cut within 1e-9 of an end: there the
                                    // whole curve stands (its end within 1e-9 of the run's).
                                    if lo_t > d0 + 1e-9 {
                                        piece_curve = piece_curve.split(lo_t)?.1;
                                    }
                                    let [_, e1] = piece_curve.domain()?;
                                    if hi_t < e1 - 1e-9 {
                                        piece_curve = piece_curve.split(hi_t)?.0;
                                    }
                                    let curve = if from_t > to_t { piece_curve.reversed()? } else { piece_curve };
                                    let [c0, c1] = curve.domain()?;
                                    let eid = id();
                                    edges.push(EdgeRecord { id: eid, curve, t0: c0, t1: c1, start_vertex_id: v0, end_vertex_id: v1, degenerate: false, name: None });
                                    side_edges.insert(key, (eid, m0));
                                    (eid, m0)
                                }
                            };
                            let chart = rows[a].0 as f64;
                            let pcurve = crate::make_line(Vec3::new(pa.0 - chart, pa.1, 0.0), Vec3::new(pb.0 - chart, pb.1, 0.0))?;
                            coedges.push(CoedgeRecord { id: id(), edge_id, forward: edge_start == m0, pcurve });
                        }
                    }
                }
                let surface = surface.clone();
                if whole && chart == 0 && orient_by.is_none() {
                    orient_by = Some((faces.len(), [rows[a].1, rows[a].2], pv));
                }
                faces.push(FaceRecord { id: id(), surface, same_sense: true, loops: vec![LoopRecord { id: id(), coedges }], name: None });
                if trace_stages {
                    let f = faces.last().unwrap();
                    eprintln!("TS face {} patch ({a}, {b}) coedges {:?}", f.id, f.loops[0].coedges.iter().map(|c| (c.id, c.edge_id, c.forward)).collect::<Vec<_>>());
                }
                face_charts.push(chart);
            }
        }
    }
    // The charts' faces: each side is a run's edges (its pieces in order along
    // it, made here if no patch face made them) or a kept piece of a box side
    // (the patch-side edge the outside patch made there), with the chart's
    // pcurves cut to each edge.
    {
        use super::chart::ChartEnd;
        let weld = 1e-7 * (tube.major + tube.minor);
        let mark_at = |point: Vec3| -> Option<Mark> { raws.iter().flat_map(|r| r.marks).find(|m| mark_point(*m).is_ok_and(|q| q.sub(point).length() <= weld)) };
        let near_index = |bounds: &[f64], v: f64, period: f64| bounds.iter().position(|b| { let d = (b - v).rem_euclid(period); d.min(period - d) <= 1e-9 });
        // a polyline's cumulative 3D length, and the parameter of the point nearest p
        let along = |points: &[Vec3], p: Vec3| -> f64 {
            let mut best = (f64::INFINITY, 0.0);
            let mut total = 0.0;
            for w in points.windows(2) {
                let d = w[1].sub(w[0]);
                let l2 = d.dot(d);
                let f = if l2 > 0.0 { (p.sub(w[0]).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
                let dist = w[0].add(d.scale(f)).sub(p).length();
                if dist < best.0 {
                    best = (dist, total + f * l2.sqrt());
                }
                total += l2.sqrt();
            }
            best.1
        };
        let pcurve_between = |side: &super::chart::ChartSide, from: f64, to: f64| -> Vec<Vec3> {
            // the pcurve's points between two lengths along the side's points
            let mut lengths = vec![0.0];
            for w in side.points.windows(2) {
                lengths.push(lengths.last().unwrap() + w[1].sub(w[0]).length());
            }
            let at = |s: f64| -> (f64, f64) {
                let k = lengths.partition_point(|x| *x <= s).clamp(1, lengths.len() - 1);
                let (l0, l1) = (lengths[k - 1], lengths[k]);
                let f = if l1 > l0 { ((s - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 };
                let (a, b) = (side.pcurve[k - 1], side.pcurve[k]);
                (a.0 + (b.0 - a.0) * f, a.1 + (b.1 - a.1) * f)
            };
            let (lo, hi) = (from.min(to), from.max(to));
            let mut out = vec![at(lo)];
            for (k, l) in lengths.iter().enumerate() {
                if *l > lo && *l < hi {
                    out.push(side.pcurve[k]);
                }
            }
            out.push(at(hi));
            if from > to {
                out.reverse();
            }
            out.into_iter().map(|(u, v)| Vec3::new(u, v, 0.0)).collect()
        };
        let mut internal_edges: std::collections::HashMap<(usize, usize), u64> = std::collections::HashMap::new();
        for (c, chart) in charts.iter().enumerate() {
            let rim = &rims[c];
            if trace_stages {
                eprintln!("TS chart {c} faces");
            }
            for cf in chart.faces(tube, rim, window, fit)? {
                // the outer loop, then each hole (an inner loop, kept side on the left)
                let mut loops = Vec::new();
                for sides in std::iter::once(&cf.sides).chain(cf.holes.iter()) {
                    let mut coedges = Vec::new();
                    for side in sides {
                        let side_length = side.points.windows(2).map(|w| w[1].sub(w[0]).length()).sum::<f64>();
                        match side.edge {
                            Some((r, with)) if rim.edges[r].outside.is_some() => {
                                let li = regular_loops + chart_runs.iter().position(|x| *x == (c, r)).ok_or("a chart face uses an edge not built")?;
                                let mut run_raws: Vec<usize> = (0..raws.len()).filter(|&e| raws[e].source == li).collect();
                                if !with {
                                    run_raws.reverse();
                                }
                                for e in run_raws {
                                    let edge_id = match piece_edges.get(&e) {
                                        Some(found) => *found,
                                        None => {
                                            let raw = &raws[e];
                                            let curve = curve_through(&raw.points)?;
                                            let [t0, t1] = curve.domain()?;
                                            let eid = id();
                                            let (s0, s1) = (vertex(raw.marks[0], mark_point(raw.marks[0])?, &mut id), vertex(raw.marks[1], mark_point(raw.marks[1])?, &mut id));
                                            edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
                                            piece_edges.insert(e, eid);
                                            eid
                                        }
                                    };
                                    let raw = &raws[e];
                                    let (p0, p1) = if with { (raw.points[0], *raw.points.last().unwrap()) } else { (*raw.points.last().unwrap(), raw.points[0]) };
                                    let (s0, s1) = (along(&side.points, p0), along(&side.points, p1));
                                    let _ = side_length;
                                    let record = edges.iter().find(|r| r.id == edge_id).ok_or("a chart run has no edge")?;
                                    let pcurve = same_parameter(&cf.surface, &record.curve, record.t0, record.t1, with, &pcurve_between(side, s0, s1))?;
                                    coedges.push(CoedgeRecord { id: id(), edge_id, forward: with, pcurve });
                                }
                            }
                            Some((r, with)) => {
                                // an internal edge: made once from the chart's points
                                let edge_id = match internal_edges.get(&(c, r)) {
                                    Some(found) => *found,
                                    None => {
                                        let edge = &rim.edges[r];
                                        let curve = curve_through(&edge.points)?;
                                        let [t0, t1] = curve.domain()?;
                                        let mark_of = |e: ChartEnd| -> Result<Mark, String> {
                                            match e {
                                                ChartEnd::Vertex(k) => Ok(Mark::Chart(c, k)),
                                                ChartEnd::Crossing(i) => mark_at(rim.crossings[i].at.point).ok_or_else(|| "a rim crossing has no vertex".to_string()),
                                                _ => Err("an internal chart edge ends on a box side".into()),
                                            }
                                        };
                                        let (m0, m1) = (mark_of(edge.ends[0])?, mark_of(edge.ends[1])?);
                                        let eid = id();
                                        let (s0, s1) = (vertex(m0, mark_point(m0)?, &mut id), vertex(m1, mark_point(m1)?, &mut id));
                                        edges.push(EdgeRecord { id: eid, curve, t0, t1, start_vertex_id: s0, end_vertex_id: s1, degenerate: false, name: None });
                                        internal_edges.insert((c, r), eid);
                                        eid
                                    }
                                };
                                let record = edges.iter().find(|r| r.id == edge_id).ok_or("an internal chart edge has no record")?;
                                let uv: Vec<Vec3> = side.pcurve.iter().map(|(u, v)| Vec3::new(*u, *v, 0.0)).collect();
                                // the side's stations are the edge's own points (the other way round against it)
                                let edge_points = &rim.edges[r].points;
                                let n = edge_points.len();
                                let same = n == side.points.len() && n == uv.len() && n >= 2 && (0..n).all(|k| side.points[k].sub(edge_points[if with { k } else { n - 1 - k }]).length() <= 1e-12);
                                let pcurve = if same {
                                    let mut ordered = edge_points.clone();
                                    if !with {
                                        ordered.reverse();
                                    }
                                    crate::interpolate_curve(&uv, 3.min(n - 1), &chord_parameters(&ordered))?
                                } else {
                                    same_parameter(&cf.surface, &record.curve, record.t0, record.t1, with, &uv)?
                                };
                                coedges.push(CoedgeRecord { id: id(), edge_id, forward: with, pcurve });
                            }
                            None => {
                                let end_of = |e: ChartEnd| -> Result<(Mark, (f64, f64)), String> {
                                    match e {
                                        ChartEnd::Crossing(i) => {
                                            let at = rim.crossings[i].at;
                                            Ok((mark_at(at.point).ok_or("a rim crossing has no vertex")?, (at.sigma.rem_euclid(4.0), at.psi.rem_euclid(TAU))))
                                        }
                                        ChartEnd::Corner { plus, corner } => {
                                            let d = chart.corner(plus, corner);
                                            let d = (d.0.rem_euclid(4.0), d.1.rem_euclid(TAU));
                                            let a = near_index(&sigma_bounds, d.0, 4.0).ok_or("a box corner off the patch grid")?;
                                            let b = near_index(&psi_bounds, d.1, TAU).ok_or("a box corner off the patch grid")?;
                                            Ok((Mark::Corner(a % rows.len(), b % columns), d))
                                        }
                                        ChartEnd::Vertex(k) => Ok((Mark::Chart(c, k), (0.0, 0.0))),
                                        ChartEnd::Closed(_) => Err("a closed chart side (not yet taken)".into()),
                                    }
                                };
                                let ((m0, d0), (m1, d1)) = (end_of(side.ends[0])?, end_of(side.ends[1])?);
                                // The side runs along one patch grid line and can pass
                                // several patches: it is cut at each grid line it crosses,
                                // and each part is the coedge of that patch's own side edge.
                                let e1 = (unwrap(d1.0, d0.0, 4.0), unwrap(d1.1, d0.1, TAU));
                                let along_psi = (d0.0 - e1.0).abs() <= 1e-9;
                                let (from, to, bounds, period): (f64, f64, &[f64], f64) = if along_psi { (d0.1, e1.1, &psi_bounds[..], TAU) } else { (d0.0, e1.0, &sigma_bounds[..rows.len()], 4.0) };
                                let fixed = if along_psi {
                                    near_index(&sigma_bounds, d0.0, 4.0).ok_or("a box side off the patch grid")? % rows.len()
                                } else {
                                    near_index(&psi_bounds, d0.1, TAU).ok_or("a box side off the patch grid")? % columns
                                };
                                let mut stops: Vec<(f64, Mark)> = vec![(0.0, m0)];
                                if (to - from).abs() > 1e-12 {
                                    let mut inner: Vec<(f64, Mark)> = Vec::new();
                                    for (k, bound) in bounds.iter().enumerate() {
                                        for turn in -1..=1 {
                                            let f = (bound + turn as f64 * period - from) / (to - from);
                                            if f > 1e-9 && f < 1.0 - 1e-9 {
                                                inner.push((f, if along_psi { Mark::Corner(fixed, k) } else { Mark::Corner(k, fixed) }));
                                            }
                                        }
                                    }
                                    inner.sort_by(|x, y| x.0.total_cmp(&y.0));
                                    stops.extend(inner);
                                }
                                stops.push((1.0, m1));
                                let uv: Vec<Vec3> = side.pcurve.iter().map(|(u, v)| Vec3::new(*u, *v, 0.0)).collect();
                                let full = curve_through(&uv)?;
                                let [q0, q1] = full.domain()?;
                                // the side's parameter whose point on the chart face is nearest a 3D point, within [a, b]
                                let nearest = |target: Vec3, a: f64, b: f64| -> f64 {
                                    let distance = |q: f64| full.evaluate(q).ok().and_then(|p| cf.surface.evaluate_extended(p.x, p.y).ok()).map(|p| p.sub(target).length()).unwrap_or(f64::INFINITY);
                                    let mut best = (f64::INFINITY, a);
                                    for j in 0..=64 {
                                        let q = a + (b - a) * j as f64 / 64.0;
                                        let d = distance(q);
                                        if d < best.0 {
                                            best = (d, q);
                                        }
                                    }
                                    let step = (b - a).abs() / 64.0;
                                    let (lo_q, hi_q) = (a.min(b), a.max(b));
                                    let (mut x0, mut x1) = ((best.1 - step).max(lo_q), (best.1 + step).min(hi_q));
                                    let ratio = 0.5 * (5f64.sqrt() - 1.0);
                                    for _ in 0..60 {
                                        let (x, y) = (x1 - ratio * (x1 - x0), x0 + ratio * (x1 - x0));
                                        if distance(x) < distance(y) {
                                            x1 = y;
                                        } else {
                                            x0 = x;
                                        }
                                    }
                                    0.5 * (x0 + x1)
                                };
                                let mut cuts_q = vec![q0];
                                for (_, mark) in &stops[1..stops.len() - 1] {
                                    let last = *cuts_q.last().unwrap();
                                    cuts_q.push(nearest(mark_point(*mark)?, last, q1));
                                }
                                cuts_q.push(q1);
                                for (w, q) in stops.windows(2).zip(cuts_q.windows(2)) {
                                    let ((f0, k0), (f1, k1)) = (w[0], w[1]);
                                    let f = 0.5 * (f0 + f1);
                                    let mid = (d0.0 + (e1.0 - d0.0) * f, d0.1 + (e1.1 - d0.1) * f);
                                    let key_line: (u8, usize, usize) = if along_psi { (0, fixed, column_of(mid.1)) } else { (1, row_of(mid.0), fixed) };
                                    let (lo, hi) = if k0 <= k1 { (k0, k1) } else { (k1, k0) };
                                    let (edge_id, edge_start) = *side_edges.get(&(key_line.0, key_line.1, key_line.2, lo, hi)).ok_or_else(|| {
                                        let on_line: Vec<_> = side_edges.keys().filter(|k| k.0 == key_line.0 && k.1 == key_line.1 && k.2 == key_line.2).map(|k| (k.3, k.4)).collect();
                                        format!("a chart face's box side has no patch edge (chart {c}, line {key_line:?}, ends {:?} at {d0:?} -> {d1:?}, marks {lo:?}..{hi:?}; the line's edges {on_line:?})", side.ends)
                                    })?;
                                    // The patch edge runs at the patch's own speed (an
                                    // isoparametric line of K), the chart's side at the
                                    // chart's: the pcurve takes its stations at even
                                    // parameters of the edge, so the two agree parameter
                                    // for parameter.
                                    let forward = edge_start == k0;
                                    let record = edges.iter().find(|e| e.id == edge_id).ok_or("a chart face's box side has no patch edge")?;
                                    // (stations doubled until the two agree to 5e-7 between them, 768 at most)
                                    let edge_at = |fraction: f64| if forward { record.t0 + (record.t1 - record.t0) * fraction } else { record.t1 - (record.t1 - record.t0) * fraction };
                                    let mut count = 24;
                                    let pcurve = loop {
                                        let mut stations = Vec::with_capacity(count + 1);
                                        let mut at = q[0];
                                        for j in 0..=count {
                                            let t = edge_at(j as f64 / count as f64);
                                            at = if j == 0 { q[0] } else if j == count { q[1] } else { nearest(record.curve.evaluate(t)?, at, q[1]) };
                                            stations.push(full.evaluate(at)?);
                                        }
                                        let params: Vec<f64> = (0..=count).map(|j| j as f64 / count as f64).collect();
                                        let fitted = crate::interpolate_curve(&stations, 3, &params)?;
                                        let miss = (0..67)
                                            .map(|k| {
                                                let f = (k as f64 + 0.5) / 67.0;
                                                match (fitted.evaluate(f).ok().and_then(|p| cf.surface.evaluate_extended(p.x, p.y).ok()), record.curve.evaluate(edge_at(f))) {
                                                    (Some(a), Ok(b)) => a.sub(b).length(),
                                                    _ => f64::INFINITY,
                                                }
                                            })
                                            .fold(0.0, f64::max);
                                        if miss <= 5e-7 || count >= 768 {
                                            break fitted;
                                        }
                                        count *= 2;
                                    };
                                    coedges.push(CoedgeRecord { id: id(), edge_id, forward, pcurve });
                                }
                            }
                        }
                    }
                    loops.push(LoopRecord { id: id(), coedges });
                }
                faces.push(FaceRecord { id: id(), surface: cf.surface.clone(), same_sense: true, loops, name: None });
                if trace_stages {
                    let f = faces.last().unwrap();
                    eprintln!("TS face {} chart face loops {:?}", f.id, f.loops.iter().map(|l| l.coedges.iter().map(|c| (c.id, c.edge_id, c.forward)).collect::<Vec<_>>()).collect::<Vec<_>>());
                }
                face_charts.push(usize::MAX);
            }
        }
    }
    // Shells by connectivity through edges.
    let mut owner: std::collections::BTreeMap<u64, Vec<usize>> = std::collections::BTreeMap::new();
    for (f, face) in faces.iter().enumerate() {
        for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
            owner.entry(coedge.edge_id).or_default().push(f);
        }
    }
    let mut group: Vec<usize> = (0..faces.len()).collect();
    fn find(group: &mut [usize], x: usize) -> usize {
        let mut r = x;
        while group[r] != r {
            r = group[r];
        }
        group[x] = r;
        r
    }
    for users in owner.values() {
        for pair in users.windows(2) {
            let (x, y) = (find(&mut group, pair[0]), find(&mut group, pair[1]));
            group[x] = y;
        }
    }
    let mut shells: std::collections::BTreeMap<usize, Vec<FaceRecord>> = std::collections::BTreeMap::new();
    for (f, face) in faces.into_iter().enumerate() {
        let root = find(&mut group, f);
        shells.entry(root).or_default().push(face);
    }
    let shells: Vec<ShellRecord> = shells.into_values().map(|faces| ShellRecord { id: id(), faces }).collect();
    let genus = shells.len() as i64;
    let _ = face_charts;
    // Vertices that are one point (a junction reached from arcs of different
    // loops, each naming it by its own split) welded into one.
    let weld = 1e-7 * (tube.major + tube.minor);
    let mut alias: std::collections::HashMap<u64, u64> = std::collections::HashMap::new();
    let mut kept_vertices: Vec<VertexRecord> = Vec::with_capacity(vertices.len());
    for v in vertices.into_iter() {
        match kept_vertices.iter().find(|k| k.point.sub(v.point).length() <= weld) {
            Some(k) => {
                alias.insert(v.id, k.id);
            }
            None => kept_vertices.push(v),
        }
    }
    let vertices = kept_vertices;
    let mut edges = edges;
    for e in edges.iter_mut() {
        if let Some(&to) = alias.get(&e.start_vertex_id) {
            e.start_vertex_id = to;
        }
        if let Some(&to) = alias.get(&e.end_vertex_id) {
            e.end_vertex_id = to;
        }
    }
    let mut solid = crate::BrepSolid { mass_properties_cache: Default::default(), id: id(), vertices, edges, shells, genus, kind: Default::default(), cells: Vec::new() };
    // Outward on the sheet Σ + r·N is +N: a whole chart-0 face's normal at its
    // middle says whether the faces turn out.
    let (_, su, pv) = orient_by.ok_or("no whole face of the sheet Σ + r·N to orient by")?;
    let (um, vm) = (0.5 * (su[0] + su[1]), 0.5 * (pv[0] + pv[1]));
    let surface = &fits[&(row_of(su[0] + 1e-12), column_of(vm))];
    let normal = surface.normal(um, vm)?;
    let outward = tube.frame(tube.from + (tube.to - tube.from) * um, vm).ok_or("the core circle's sweep is singular")?.normal;
    let along = normal.dot(outward);
    if along < 0.0 {
        crate::orientation::flip_all_faces(&mut solid).map_err(|e| e.message)?;
    } else if !(along > 0.0) {
        return Err("the tube's normal is undecided".into());
    }
    Ok(solid)
}