meshbrep 0.4.0

Rebuild an exact B-rep (planes, cylinders, cones, spheres, tori, B-spline surfaces) from a triangle mesh tagged with the surface each triangle came from, write it as STEP AP214, and make fillet and chamfer tools
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
//! Parametrising faces: frames, seams and parameter-space curves.
//!
//! A STEP reader trims a face in its surface's (u, v) space. Without the
//! 2D curves a reader rebuilds them itself, and on spheres trimmed by
//! circles that are not parallels OCCT ends at tolerances up to 6.7e-3
//! (measured with OCCT 8.0.1). So every edge on a curved face gets a parameter-space
//! curve here, and every face that wraps around its axis gets a seam: the
//! edge along `u = 0` (= 2π) where the face meets itself, used once in each
//! direction.
//!
//! Each curved face gets its own frame, chosen so that its loops are
//! simple in (u, v): a sphere's axis is the normal of the circles that
//! bound it (so they are parallels), and the seam is placed along a
//! meridian that misses every hole, at `u = 0`.

use crate::bspline;
use crate::curve::{self, CurveEval};
use crate::math::*;
use crate::model::{BSpline, Curve};
use crate::surf::{Param, Surf};
use crate::topo::{TEdge, Topo};
use crate::{Error, Failure};

/// One sample of a loop in parameter space.
#[derive(Clone, Copy, Debug)]
struct S {
    u: f64,
    v: f64,
    /// Curve parameter of the sample.
    t: f64,
}

/// Samples of a coedge in loop order, `n + 1` of them, with the ends at
/// the exact vertex positions.
fn coedge_points(topo: &Topo, e: usize, fwd: bool, n: usize) -> Vec<(V, f64)> {
    let ed = &topo.edges[e];
    let [t0, t1] = ed.range;
    let mut out: Vec<(V, f64)> = (0..=n)
        .map(|i| {
            let t = t0 + (t1 - t0) * i as f64 / n as f64;
            (curve::eval(&ed.curve, t), t)
        })
        .collect();
    out[0].0 = topo.verts[ed.v0];
    out[n].0 = topo.verts[ed.v1];
    if !fwd {
        out.reverse();
    }
    out
}

fn wrap_near(raw: f64, prev: f64) -> f64 {
    let mut d = raw - prev;
    d -= TAU * (d / TAU).round();
    prev + d
}

/// Lifts points to (u, v) with `u` continuous, starting near `start_u`
/// (or at the first point's own angle). Points on the axis take the angle
/// of their neighbours.
fn lift(param: &Param, pts: &[(V, f64)], start_u: Option<f64>, tol: f64) -> Vec<S> {
    let raw: Vec<(Option<f64>, f64)> = pts
        .iter()
        .map(|&(p, _)| {
            let (u, w) = param.uv(p);
            ((!param.near_axis(p, tol)).then_some(u), w)
        })
        .collect();
    let mut us: Vec<Option<f64>> = raw.iter().map(|r| r.0).collect();
    // Fill axis points from the next known angle, then the previous.
    let mut next: Option<f64> = None;
    for u in us.iter_mut().rev() {
        match u {
            Some(x) => next = Some(*x),
            None => *u = next,
        }
    }
    let mut prev_known: Option<f64> = None;
    for u in us.iter_mut() {
        match u {
            Some(x) => prev_known = Some(*x),
            None => *u = prev_known,
        }
    }
    let mut out = Vec::with_capacity(pts.len());
    let mut prev = start_u;
    for (i, u) in us.iter().enumerate() {
        let raw_u = u.unwrap_or(prev.unwrap_or(0.0));
        // Only an angle wraps. On a plane `u` is a length, and wrapping it
        // by 2π folded any loop whose samples are more than π apart (a
        // 30 mm cube's 5-sample edges) into the wrong area, so a hole
        // read as a second outer loop.
        let lu = match prev {
            Some(p) if param.periodic() => wrap_near(raw_u, p),
            _ => raw_u,
        };
        out.push(S {
            u: lu,
            v: raw[i].1,
            t: pts[i].1,
        });
        prev = Some(lu);
    }
    out
}

/// A loop lifted into parameter space: per coedge, its samples in loop
/// order.
fn lift_loop(
    topo: &Topo,
    param: &Param,
    lp: &[(usize, bool)],
    start_u: Option<f64>,
    tol: f64,
) -> Vec<Vec<S>> {
    let mut out: Vec<Vec<S>> = Vec::with_capacity(lp.len());
    let mut cur = start_u;
    for &(e, fwd) in lp {
        let ed = &topo.edges[e];
        let n = curve::sample_count(&ed.curve, ed.range);
        let pts = coedge_points(topo, e, fwd, n);
        let s = lift(param, &pts, cur, tol);
        cur = s.last().map(|x| x.u);
        out.push(s);
    }
    out
}

fn winding(l: &[Vec<S>]) -> i64 {
    let (a, b) = (
        l[0][0].u,
        l.last().expect("loop").last().expect("samples").u,
    );
    ((b - a) / TAU).round() as i64
}

/// Twice the signed area of a lifted loop (positive counter-clockwise).
fn area(l: &[Vec<S>]) -> f64 {
    let mut s = 0.0;
    for c in l {
        for w in c.windows(2) {
            s += w[0].u * w[1].v - w[1].u * w[0].v;
        }
    }
    s
}

/// Twice the signed area of a loop on a planar face: `area(&lift_loop(..))`
/// to the bit (the same samples, summed in the same order), without the
/// vectors of samples. A large faceted model has a million coedges, every
/// one on a plane, and allocating their samples to find which loop is a
/// face's outer one took a tenth of its reconstruction.
fn planar_loop_area(topo: &Topo, param: &Param, lp: &[(usize, bool)]) -> f64 {
    let mut s = 0.0;
    for &(e, fwd) in lp {
        let ed = &topo.edges[e];
        let n = curve::sample_count(&ed.curve, ed.range);
        let [t0, t1] = ed.range;
        // Sample `i` of the edge, as `coedge_points` places it.
        let at = |i: usize| {
            let p = if i == 0 {
                topo.verts[ed.v0]
            } else if i == n {
                topo.verts[ed.v1]
            } else {
                curve::eval(&ed.curve, t0 + (t1 - t0) * i as f64 / n as f64)
            };
            param.uv(p)
        };
        let in_loop = |k: usize| if fwd { k } else { n - k };
        let mut prev = at(in_loop(0));
        for k in 1..=n {
            let cur = at(in_loop(k));
            s += prev.0 * cur.1 - cur.0 * prev.1;
            prev = cur;
        }
    }
    s
}

/// Where a loop crosses the meridian `u ≡ u0`.
#[derive(Clone, Copy, Debug)]
struct Crossing {
    /// Index of the coedge in the loop.
    ci: usize,
    /// Curve parameter of the crossing.
    t: f64,
    /// At the coedge's start vertex.
    at_start: bool,
}

/// Where a loop crosses the meridian `u ≡ u0`, before the crossing's
/// curve parameter is solved for: the coedge, the sample the crossing
/// follows, and whether that sample is on the meridian itself.
#[derive(Clone, Copy, Debug)]
struct Site {
    ci: usize,
    i: usize,
    on: bool,
}

/// How close to the meridian a sample is on it.
const MERIDIAN_EPS: f64 = 1e-11;

/// A sample's signed offset from the meridian `u0`, in (-π, π].
fn sheet(u: f64, u0: f64) -> f64 {
    let d = u - u0;
    d - TAU * (d / TAU).round()
}

/// Where the lifted loop `l` crosses the meridian `u0`. Finding them
/// costs a pass over the samples; solving each for its curve parameter
/// ([`crossing_at`]) costs a bisection on the curve, which the search for
/// a seam needs only for the meridians it can use.
fn crossing_sites(l: &[Vec<S>], u0: f64) -> Vec<Site> {
    let mut out = Vec::new();
    for (ci, c) in l.iter().enumerate() {
        for i in 0..c.len() - 1 {
            let (a, b) = (c[i], c[i + 1]);
            // Signed offsets in one sheet: continue a's sheet to b.
            let ga = sheet(a.u, u0);
            let gb = ga + (b.u - a.u);
            if ga.abs() < MERIDIAN_EPS {
                out.push(Site { ci, i, on: true });
                continue;
            }
            // Between samples u moves by less than π, so b lies in the
            // same sheet as a, and a crossing is a change of sign. A
            // crossing at b itself is counted as the next segment's start.
            if gb.abs() < MERIDIAN_EPS || (ga < 0.0) == (gb < 0.0) {
                continue;
            }
            out.push(Site { ci, i, on: false });
        }
    }
    out
}

/// The crossing at `site` of [`crossing_sites`]`(l, u0)`.
fn crossing_at(
    topo: &Topo,
    param: &Param,
    lp: &[(usize, bool)],
    l: &[Vec<S>],
    u0: f64,
    site: Site,
) -> Crossing {
    let Site { ci, i, on } = site;
    let (a, b) = (l[ci][i], l[ci][i + 1]);
    if on {
        return Crossing {
            ci,
            t: a.t,
            at_start: i == 0,
        };
    }
    let ga = sheet(a.u, u0);
    // Bisection on the curve parameter.
    let ed = &topo.edges[lp[ci].0];
    let ev = CurveEval::new(&ed.curve);
    let (mut lo, mut hi) = (a.t, b.t);
    let f = |t: f64| ga + (wrap_near(param.angle(ev.at(t)), a.u) - a.u);
    for _ in 0..80 {
        let mid = 0.5 * (lo + hi);
        // Converged: `lo` and `hi` are adjacent numbers, and whichever
        // way this step went, the midpoint taken at the end would be this
        // one (the bits are the 80 steps').
        if mid == lo || mid == hi {
            break;
        }
        if (f(mid) < 0.0) == (ga < 0.0) {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    let t = 0.5 * (lo + hi);
    Crossing {
        ci,
        t,
        at_start: false,
    }
}

/// A loop that is one closed circle or ellipse whose vertex nothing else
/// uses: its vertex can move anywhere along it.
fn movable(topo: &Topo, deg: &Degrees, lp: &[(usize, bool)]) -> bool {
    if lp.len() != 1 {
        return false;
    }
    let e = &topo.edges[lp[0].0];
    e.closed()
        && !topo.pinned[e.v0]
        && matches!(e.curve, Curve::Circle { .. } | Curve::Ellipse { .. })
        && deg.of(e.v0) == 1
}

/// How many edges touch each vertex (a closed edge once), kept in step
/// with the topology while seams are added. [`movable`] asks for every
/// candidate meridian of every wrapping face; counting with a scan of all
/// edges each time made seam placement quadratic in the model's size (the
/// BOSL2 fractal tree, 4,000 cylinder faces and 200,000 edges, spent
/// seconds there).
struct Degrees {
    deg: Vec<u32>,
    /// Edges counted so far: the ones after are new since.
    seen: usize,
}

impl Degrees {
    fn new(topo: &Topo) -> Degrees {
        let mut d = Degrees {
            deg: Vec::new(),
            seen: 0,
        };
        d.sync(topo);
        d
    }

    /// Counts the edges appended since the last call, as they are now.
    fn sync(&mut self, topo: &Topo) {
        self.deg.resize(topo.verts.len(), 0);
        for e in &topo.edges[self.seen..] {
            self.deg[e.v0] += 1;
            if e.v1 != e.v0 {
                self.deg[e.v1] += 1;
            }
        }
        self.seen = topo.edges.len();
    }

    fn of(&self, v: usize) -> u32 {
        self.deg[v]
    }

    /// [`Topo::split_edge`] with the counts kept: edge `e` now ends at the
    /// new vertex, and the edge appended runs from it to where `e` ended.
    fn split_edge(&mut self, topo: &mut Topo, e: usize, t: f64, p: V) -> usize {
        self.sync(topo);
        let (v0, v1) = (topo.edges[e].v0, topo.edges[e].v1);
        let nv = topo.split_edge(e, t, p);
        self.deg.resize(topo.verts.len(), 0);
        if v1 != v0 {
            self.deg[v1] -= 1;
        }
        self.deg[nv] += 1;
        self.sync(topo);
        nv
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum End {
    Loop(usize),
    Pole(f64),
}

/// A provisional frame for a curved face (x is fixed later).
fn base_param(topo: &Topo, f: usize) -> Param {
    let face = &topo.faces[f];
    let verts: Vec<V> = face
        .loops
        .iter()
        .flatten()
        .map(|&c| topo.verts[topo.start(c)])
        .collect();
    match face.surf {
        Surf::Plane { o, n } => {
            let p0 = verts.first().copied().unwrap_or(o);
            let origin = p0 - n * (p0 - o).dot(n);
            Param::new(face.surf.clone(), origin, n, n.perp(), 0.0)
        }
        Surf::Cyl { o, a, .. } => {
            let p0 = verts.first().copied().unwrap_or(o);
            Param::new(face.surf.clone(), o + a * (p0 - o).dot(a), a, a.perp(), 0.0)
        }
        Surf::Cone { apex, a, k } => {
            let t = verts
                .iter()
                .map(|&p| (p - apex).dot(a))
                .fold(0.0f64, f64::max);
            let t = if t > 0.0 { t } else { 1.0 };
            Param::new(face.surf.clone(), apex + a * t, a, a.perp(), k * t)
        }
        Surf::Sphere { c, r } => {
            // The normal shared by most of the bounding circles, so that
            // they are parallels (lines of constant v).
            let mut counts: Vec<(V, usize)> = Vec::new();
            for &(e, _) in face.loops.iter().flatten() {
                if let Curve::Circle { normal, .. } = topo.edges[e].curve {
                    let mut n = V::from(normal);
                    let arr = n.arr();
                    let big = (0..3)
                        .max_by(|&i, &j| arr[i].abs().total_cmp(&arr[j].abs()))
                        .expect("axis");
                    if arr[big] < 0.0 {
                        n = -n;
                    }
                    match counts.iter_mut().find(|(m, _)| m.dot(n) > 1.0 - 1e-9) {
                        Some(x) => x.1 += 1,
                        None => counts.push((n, 1)),
                    }
                }
            }
            // Most shared first; equal counts keep their order of first
            // use, so the choice is deterministic.
            let mut cands: Vec<V> = Vec::new();
            for k in (1..=counts.iter().map(|x| x.1).max().unwrap_or(0)).rev() {
                cands.extend(counts.iter().filter(|x| x.1 == k).map(|x| x.0));
            }
            cands.push(v(0.0, 0.0, 1.0));
            // Then axes square to the face's mean direction, so that both
            // poles are as far from it as they can be, each also square to
            // one bounding circle's normal: a great circle square to the
            // axis is a meridian (constant u), whose parameter-space curve
            // is a segment. A box corner's patch, bounded by three quarter
            // circles through each other's poles, had its pole near or
            // inside it under the fixed axes below, and its circles needed
            // a hundred points or more each to follow longitude and
            // latitude there (most of a rounded box's STEP file).
            let mut mean = V::default();
            for &(e, _) in face.loops.iter().flatten() {
                let ed = &topo.edges[e];
                for p in curve::sample(&ed.curve, ed.range, 8) {
                    mean = mean + (p - c).norm();
                }
            }
            if mean.len() > 1e-6 {
                let m = mean.norm();
                for &(n, _) in &counts {
                    let z = m.cross(n);
                    if z.len() > 0.1 {
                        cands.push(z.norm());
                    }
                }
                cands.push(m.perp());
            }
            // Then axes no model aligns with by accident.
            for d in [
                [1.0, 2.0, 3.0],
                [3.0, -1.0, 2.0],
                [-2.0, 3.0, 1.0],
                [1.0, -3.0, -2.0],
            ] {
                cands.push(V::from(d).norm());
            }
            // Past the bounding circles' own normals (a cap's circle as a
            // parallel round its pole), an axis is taken only with both
            // poles outside the face as well: a box corner's patch turned
            // by arbitrary angles kept the fixed z axis, whose pole lay
            // inside the patch 0.03 radians from its boundary, and the
            // seam to that pole crossed the boundary in parameter space
            // (fillet corpus seed 2 model 900).
            let own = counts.len();
            let reach = face_reach(topo, face, c, mean);
            let z = cands
                .iter()
                .enumerate()
                .find(|&(i, &z)| {
                    clear_of_poles(topo, face, c, r, z)
                        && (i < own || reach.is_none_or(|(m, cos)| m.dot(z).abs() < cos))
                })
                .or_else(|| {
                    cands
                        .iter()
                        .enumerate()
                        .find(|&(_, &z)| clear_of_poles(topo, face, c, r, z))
                })
                .map_or(cands[0], |(_, &z)| z);
            Param::new(face.surf.clone(), c, z, z.perp(), 0.0)
        }
        Surf::Torus { .. } => torus_param(topo, f).0,
        Surf::Spline(ref s) => spline_param(face.surf.clone(), s),
    }
}

/// A B-spline face's frame: its surface's own parameters, placed (for
/// reports only) at the middle of the domain with the normal and `∂u`
/// there.
pub(crate) fn spline_param(surf: Surf, s: &crate::nurbs::Spline) -> Param {
    let (du, dv) = s.domain();
    let (u, v) = (0.5 * (du[0] + du[1]), 0.5 * (dv[0] + dv[1]));
    let d = s.ders(u, v, 1);
    let z = d[1][0].cross(d[0][1]).norm();
    Param::new(surf, d[0][0], z, d[1][0], 0.0)
}

/// The direction of a sphere face's boundary from the centre `c` (its
/// samples' mean `mean`, unit), and the cosine of the angle beyond which
/// an axis's pole is clear of the face: past every boundary sample's
/// angle from that direction by 0.05 radians. `None` when the boundary has
/// no mean direction (a great circle).
fn face_reach(topo: &Topo, face: &crate::topo::TFace, c: V, mean: V) -> Option<(V, f64)> {
    if mean.len() <= 1e-6 {
        return None;
    }
    let m = mean.norm();
    let mut least: f64 = 1.0;
    for &(e, _) in face.loops.iter().flatten() {
        let ed = &topo.edges[e];
        for p in curve::sample(&ed.curve, ed.range, 16) {
            least = least.min((p - c).norm().dot(m));
        }
    }
    let angle = libm::acos(least.clamp(-1.0, 1.0)) + 0.05;
    Some((m, if angle >= PI { -1.0 } else { cos(angle) }))
}

/// Whether no boundary of `face` (on the sphere `c`, `r`) comes near the
/// poles of axis `z`, except along parallels. At a pole `u` is undefined:
/// an edge through it jumps by π in parameter space, and a seam from that
/// pole runs along the boundary. Three quarter circles bounding a sphere
/// cut by an octant corner (`rotate-parameters.scad`) pass through the
/// poles of every one of their own normals.
fn clear_of_poles(topo: &Topo, face: &crate::topo::TFace, c: V, r: f64, z: V) -> bool {
    // About 0.6 degrees.
    let min_sin = 0.01;
    face.loops.iter().flatten().all(|&(e, _)| {
        let ed = &topo.edges[e];
        if let Curve::Circle { normal, .. } = ed.curve
            && V::from(normal).cross(z).len() < 1e-9
        {
            // A parallel: constant v, whatever its latitude.
            return true;
        }
        // Samples 0.005 r apart, so that a curve through a pole has one
        // within the limit.
        let len: f64 = curve::sample(&ed.curve, ed.range, 16)
            .windows(2)
            .map(|w| (w[1] - w[0]).len())
            .sum();
        let n = ((1.1 * len / (0.005 * r)).ceil() as usize).clamp(8, 4096);
        curve::sample(&ed.curve, ed.range, n)
            .iter()
            .all(|&p| ((p - c) * (1.0 / r)).cross(z).len() > min_sin)
    })
}

/// Rotates the frame's x axis by `u0` about z (a swapped torus's tube
/// angle instead; see [`Param::rotated`]).
fn rotated(p: &Param, u0: f64) -> Param {
    p.rotated(u0)
}

/// The middle of the widest gap that angle intervals leave on the circle,
/// or `None` when they cover all of it. Each interval is shorter than π.
fn widest_gap(intervals: &[(f64, f64)]) -> Option<f64> {
    let mut iv: Vec<(f64, f64)> = Vec::with_capacity(intervals.len() + 4);
    for &(lo, hi) in intervals {
        let l = lo - TAU * (lo / TAU).floor();
        let h = l + (hi - lo);
        iv.push((l, h));
        if h > TAU {
            iv.push((l - TAU, h - TAU));
        }
    }
    if iv.is_empty() {
        return None;
    }
    iv.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
    let first = iv[0].0;
    let mut end = iv[0].1;
    let mut best = (0.0f64, 0.0f64);
    for &(l, h) in &iv[1..] {
        if l > end && l - end > best.0 {
            best = (l - end, 0.5 * (l + end));
        }
        end = end.max(h);
    }
    let wrap = first + TAU - end;
    if wrap > best.0 {
        best = (wrap, end + 0.5 * wrap);
    }
    (best.0 > 1e-9).then_some(best.1)
}

/// A torus face's frame. Both of a torus's coordinates are angles, so
/// each needs its cut (where the angle jumps by 2π) outside the face, or
/// a seam where it cannot be: which one is decided from the angles the
/// face's mesh triangles cover. Returns the frame and whether the face
/// wraps both ways (a whole torus, perhaps with holes), which needs two
/// seams.
fn torus_param(topo: &Topo, f: usize) -> (Param, bool) {
    let face = &topo.faces[f];
    let Surf::Torus { c, a, big, .. } = face.surf else {
        unreachable!("a torus face")
    };
    let xr = a.perp();
    let reference = Param::new(face.surf.clone(), c, a, xr, 0.0);
    let angles = |p: V| {
        let d = p - c;
        let h = d.dot(reference.z);
        let w = d.reject(reference.z);
        (
            atan2(w.dot(reference.y), w.dot(reference.x)),
            atan2(h, w.len() - big),
        )
    };
    let mut phi = Vec::with_capacity(face.tris.len());
    let mut theta = Vec::with_capacity(face.tris.len());
    for t in &face.tris {
        let q = t.map(angles);
        let span = |k: usize| {
            let pick = |p: (f64, f64)| if k == 0 { p.0 } else { p.1 };
            let a0 = pick(q[0]);
            let (mut lo, mut hi) = (a0, a0);
            for &p in &q[1..] {
                let x = wrap_near(pick(p), a0);
                lo = lo.min(x);
                hi = hi.max(x);
            }
            (lo, hi)
        };
        phi.push(span(0));
        theta.push(span(1));
    }
    let gp = widest_gap(&phi);
    let gt = widest_gap(&theta);
    let x = match gp {
        // The axis-angle cut (±π) in the middle of the gap.
        Some(g) => reference.x * cos(g + PI) + reference.y * sin(g + PI),
        None => xr,
    };
    let mut p = Param::new(face.surf.clone(), c, a, x, 0.0);
    p.t0 = gt.map_or(0.0, |g| g + PI);
    p.swap = gp.is_some() && gt.is_none();
    (p, gp.is_none() && gt.is_none())
}

/// Seams a torus face that wraps both ways: a meridian and a parallel
/// through one new vertex, both clear of the face's loops (which must
/// then be holes), joined into one loop around the parameter square.
fn double_seam(topo: &mut Topo, f: usize, param: Param) -> Result<(), Error> {
    let Surf::Torus { c, big, r, .. } = param.s else {
        unreachable!("a torus face")
    };
    let loops = topo.faces[f].loops.clone();
    // Each loop's continuous (axis, tube) angle ranges.
    let mut ranges: Vec<((f64, f64), (f64, f64))> = Vec::with_capacity(loops.len());
    for lp in &loops {
        let mut prev: Option<(f64, f64)> = None;
        let (mut first, mut last) = ((0.0, 0.0), (0.0, 0.0));
        let mut lo = (f64::INFINITY, f64::INFINITY);
        let mut hi = (f64::NEG_INFINITY, f64::NEG_INFINITY);
        for &(e, fwd) in lp {
            let ed = &topo.edges[e];
            let n = curve::sample_count(&ed.curve, ed.range);
            for (p, _) in coedge_points(topo, e, fwd, n) {
                let (u, w) = param.uv(p);
                let q = match prev {
                    None => {
                        first = (u, w);
                        (u, w)
                    }
                    Some((pu, pw)) => (wrap_near(u, pu), wrap_near(w, pw)),
                };
                lo = (lo.0.min(q.0), lo.1.min(q.1));
                hi = (hi.0.max(q.0), hi.1.max(q.1));
                last = q;
                prev = Some(q);
            }
        }
        if ((last.0 - first.0) / TAU).round() != 0.0 || ((last.1 - first.1) / TAU).round() != 0.0 {
            return Err(Error::Reconstruction(format!(
                "face {f} on a torus: a loop winds about the axis or the tube of a face that wraps both ways"
            )));
        }
        ranges.push((lo, hi));
    }
    let clear = |x: f64, k: usize| {
        ranges.iter().all(|r| {
            let (lo, hi) = if k == 0 {
                (r.0.0, r.1.0)
            } else {
                (r.0.1, r.1.1)
            };
            let m = 1e-6;
            // The first copy of x at or above lo must lie beyond hi.
            let j = ((lo - m - x) / TAU).ceil();
            x + j * TAU > hi + m
        })
    };
    let pick = |k: usize| {
        (0..256)
            .map(|i| TAU * (i as f64 + 0.5) / 256.0 - PI)
            .find(|&x| clear(x, k))
    };
    let (Some(u0), Some(v0)) = (pick(0), pick(1)) else {
        return Err(Error::Reconstruction(format!(
            "face {f} on a torus: no meridian or parallel for a seam misses the face's holes"
        )));
    };
    let mut fr = rotated(&param, u0);
    // Tube angles of the face then lie in (v0, v0 + 2π].
    fr.t0 = v0 + PI;
    let x = fr.x;
    let p0 = fr.eval(0.0, v0);
    let vx = topo.add_vertex(p0);
    topo.pinned[vx] = true;
    let meridian = topo.edges.len();
    topo.edges.push(TEdge {
        v0: vx,
        v1: vx,
        curve: Curve::Circle {
            center: (c + x * big).arr(),
            normal: x.cross(fr.z).arr(),
            x_axis: x.arr(),
            radius: r,
        },
        range: [v0, v0 + TAU],
        faces: [f, f],
        chain: Vec::new(),
        seam: true,
        dev: 0.0,
        chain_dev: 0.0,
    });
    let parallel = topo.edges.len();
    topo.edges.push(TEdge {
        v0: vx,
        v1: vx,
        curve: Curve::Circle {
            center: (c + fr.z * (r * sin(v0))).arr(),
            normal: fr.z.arr(),
            x_axis: x.arr(),
            radius: big + r * cos(v0),
        },
        range: [0.0, TAU],
        faces: [f, f],
        chain: Vec::new(),
        seam: true,
        dev: 0.0,
        chain_dev: 0.0,
    });
    // Counter-clockwise around [0, 2π] x [v0, v0 + 2π] for a face whose
    // normal is the torus's own, clockwise otherwise.
    let outer = if topo.faces[f].same_sense {
        vec![
            (parallel, true),
            (meridian, true),
            (parallel, false),
            (meridian, false),
        ]
    } else {
        vec![
            (meridian, true),
            (parallel, true),
            (meridian, false),
            (parallel, false),
        ]
    };
    let mut new_loops = vec![outer];
    new_loops.extend(loops);
    topo.faces[f].loops = new_loops;
    topo.faces[f].param = Some(fr);
    Ok(())
}

/// The parameter-space curves of the loop [`double_seam`] made, in edge
/// direction: the parallel along `v0` or `v0 + 2π`, the meridian along
/// `u = 0` or `2π`.
fn double_seam_pcurves(
    topo: &Topo,
    param: &Param,
    lp: &[(usize, bool)],
    same: bool,
) -> Vec<BSpline<2>> {
    let v0 = param.t0 - PI;
    lp.iter()
        .map(|&(e, fwd)| {
            let ed = &topo.edges[e];
            let is_parallel = matches!(ed.curve, Curve::Circle { normal, .. }
                if V::from(normal).cross(param.z).len() < 1e-9);
            if is_parallel {
                // A same-sense loop runs the parallel forward along the
                // bottom (v0) and back along the top; the other sense the
                // opposite way round.
                let w = if fwd == same { v0 } else { v0 + TAU };
                bspline::interpolate_at(&[[0.0, w], [TAU, w]], &ed.range)
            } else {
                let u = if fwd == same { TAU } else { 0.0 };
                bspline::interpolate_at(&[[u, v0], [u, v0 + TAU]], &ed.range)
            }
        })
        .collect()
}

/// Whether a loop is the one [`double_seam`] made.
fn is_double_seam_loop(topo: &Topo, param: &Param, lp: &[(usize, bool)]) -> bool {
    matches!(param.s, Surf::Torus { .. })
        && !param.swap
        && lp.len() == 4
        && lp.iter().all(|&(e, _)| topo.edges[e].seam)
}

/// Chooses each face's frame and inserts seams (pass 1).
/// Frames and seams for every face; a failure names the face's triangles.
///
/// It goes on past a face that fails, so that the failure names every
/// such face's triangles at once: a caller that writes them as facets
/// and tries again (BOSL2 `vnf_wireframe()` has a sliver of cylinder at
/// every joint) needs one more try, not one per face.
fn frames_and_seams(topo: &mut Topo, scale: f64) -> Result<(), Failure> {
    let mut start = 0usize;
    let mut failure: Option<Failure> = None;
    let mut deg = Degrees::new(topo);
    while start < topo.faces.len() {
        let mut at = start;
        match frames_and_seams_from(topo, scale, &mut at, &mut deg) {
            Ok(()) => break,
            Err(error) => {
                let tris = &topo.faces[at].source;
                match &mut failure {
                    None => {
                        failure = Some(Failure {
                            error,
                            triangles: tris.clone(),
                        })
                    }
                    Some(f) => f.triangles.extend_from_slice(tris),
                }
                start = at + 1;
            }
        }
    }
    match failure {
        Some(mut f) => {
            f.triangles.sort_unstable();
            Err(f)
        }
        None => Ok(()),
    }
}

/// [`frames_and_seams`] from face `at` on, keeping in `at` the face it is
/// working on.
fn frames_and_seams_from(
    topo: &mut Topo,
    scale: f64,
    at: &mut usize,
    deg: &mut Degrees,
) -> Result<(), Error> {
    let tol = 1e-9 * scale;
    for f in *at..topo.faces.len() {
        *at = f;
        // The seams and poles of the faces before.
        deg.sync(topo);
        let (param, double) = match topo.faces[f].surf {
            Surf::Torus { .. } => torus_param(topo, f),
            _ => (base_param(topo, f), false),
        };
        if !param.periodic() {
            topo.faces[f].param = Some(param);
            continue;
        }
        if double {
            double_seam(topo, f, param)?;
            continue;
        }
        let s = if param.sense(topo.faces[f].same_sense) {
            1
        } else {
            -1
        };
        let loops = topo.faces[f].loops.clone();
        let lifts: Vec<Vec<Vec<S>>> = loops
            .iter()
            .map(|lp| lift_loop(topo, &param, lp, None, tol))
            .collect();
        let mut bottoms = Vec::new();
        let mut tops = Vec::new();
        for (i, l) in lifts.iter().enumerate() {
            match s * winding(l) {
                0 => {}
                1 => bottoms.push(i),
                -1 => tops.push(i),
                w => {
                    return Err(Error::Reconstruction(format!(
                        "face {f}: a loop winds {w} times about the axis"
                    )));
                }
            }
        }
        let (south, north) = param.poles();
        let any_outer = lifts.iter().any(|l| s as f64 * area(l) > 0.0);
        let is_sphere = matches!(param.s, Surf::Sphere { .. });
        let ends: Option<(End, End)> = match (bottoms.len(), tops.len()) {
            (1, 1) => Some((End::Loop(bottoms[0]), End::Loop(tops[0]))),
            (1, 0) if is_sphere => Some((End::Loop(bottoms[0]), End::Pole(north.expect("pole")))),
            (0, 1) if south.is_some() => {
                Some((End::Pole(south.expect("pole")), End::Loop(tops[0])))
            }
            (0, 0) if !any_outer && is_sphere => Some((
                End::Pole(south.expect("pole")),
                End::Pole(north.expect("pole")),
            )),
            (0, 0) if any_outer => None,
            (b, t) => {
                return Err(Error::Reconstruction(format!(
                    "face {f} on a {}: unsupported topology ({b} loops wind up, {t} down)",
                    param.s.to_public().kind()
                )));
            }
        };
        let Some((bot, top)) = ends else {
            // No seam: start u at the outer loop's smallest angle.
            let outer = lifts
                .iter()
                .find(|l| s as f64 * area(l) > 0.0)
                .expect("outer loop");
            let umin = outer
                .iter()
                .flatten()
                .map(|x| x.u)
                .fold(f64::INFINITY, f64::min);
            topo.faces[f].param = Some(rotated(&param, umin));
            continue;
        };
        // Candidate seam angles: the vertices of the wrapping loops, then
        // a fixed sweep.
        let mut cands: Vec<f64> = Vec::new();
        for end in [bot, top] {
            if let End::Loop(i) = end {
                for c in &lifts[i] {
                    cands.push(c[0].u);
                }
            }
        }
        for k in 0..64 {
            cands.push(TAU * (k as f64 + 0.5) / 64.0);
        }
        let mut best: Option<(usize, f64, Vec<Option<Crossing>>)> = None;
        'cand: for &u0 in &cands {
            // Where each loop crosses the meridian: a wrapping loop once,
            // any other loop not at all, or the meridian is no seam. Only
            // then are the wrapping loops' crossings solved for.
            let mut sites: Vec<Option<Site>> = vec![None; loops.len()];
            for (i, l) in lifts.iter().enumerate() {
                let xs = crossing_sites(l, u0);
                let wraps = End::Loop(i) == bot || End::Loop(i) == top;
                if wraps {
                    if xs.len() != 1 {
                        continue 'cand;
                    }
                    sites[i] = Some(xs[0]);
                } else if !xs.is_empty() {
                    continue 'cand;
                }
            }
            let mut chosen: Vec<Option<Crossing>> = vec![None; loops.len()];
            let mut cost = 0;
            for (i, lp) in loops.iter().enumerate() {
                if let Some(site) = sites[i] {
                    let x = crossing_at(topo, &param, lp, &lifts[i], u0, site);
                    if !x.at_start && !movable(topo, deg, lp) {
                        cost += 1;
                        // A crossing a hair from a vertex of the loop
                        // would split off an edge too short to be one
                        // (a ring blend's two patches meet a hole's wall
                        // at vertices nearly opposite those of the other
                        // rim, and a seam through one passed 2e-9 from the
                        // other, an edge the validator calls degenerate):
                        // any other meridian is better.
                        let (e, fwd) = lp[x.ci];
                        let p = curve::eval(&topo.edges[e].curve, x.t);
                        let ends = [topo.start((e, fwd)), topo.start((e, !fwd))];
                        if ends
                            .iter()
                            .any(|&v| (topo.verts[v] - p).len() < 1e-6 * scale)
                        {
                            cost += 1000;
                        }
                    }
                    chosen[i] = Some(x);
                }
            }
            if best.as_ref().is_none_or(|b| cost < b.0) {
                best = Some((cost, u0, chosen));
                if cost == 0 {
                    break;
                }
            }
        }
        let Some((_, u0, chosen)) = best else {
            return Err(Error::Reconstruction(format!(
                "face {f}: no meridian for a seam misses the face's holes"
            )));
        };
        // Put a vertex where each wrapping loop crosses the seam.
        let end_vertex = |end: End, topo: &mut Topo, deg: &mut Degrees| -> usize {
            match end {
                End::Pole(w) => {
                    let p = param.eval(0.0, w);
                    let i = topo.add_vertex(p);
                    topo.pinned[i] = true;
                    deg.sync(topo);
                    i
                }
                End::Loop(i) => {
                    let x = chosen[i].expect("crossing");
                    let (e, fwd) = loops[i][x.ci];
                    let vi = if x.at_start {
                        topo.start((e, fwd))
                    } else if movable(topo, deg, &loops[i]) {
                        topo.reseat_closed(e, x.t);
                        topo.edges[e].v0
                    } else {
                        let p = curve::eval(&topo.edges[e].curve, x.t);
                        deg.split_edge(topo, e, x.t, p)
                    };
                    topo.pinned[vi] = true;
                    vi
                }
            }
        };
        let vb = end_vertex(bot, topo, deg);
        let vt = end_vertex(top, topo, deg);
        let fr = rotated(&param, u0);
        let (pb, pt) = (topo.verts[vb], topo.verts[vt]);
        let (curve, range) = match fr.s {
            Surf::Sphere { c, r } => {
                let d = fr.x;
                let n = d.cross(fr.z);
                let (wb, wt) = (fr.uv(pb).1, fr.uv(pt).1);
                (
                    Curve::Circle {
                        center: c.arr(),
                        normal: n.arr(),
                        x_axis: d.arr(),
                        radius: r,
                    },
                    [wb, wt],
                )
            }
            // A torus: the meridian at u = 0 (the circle's parameter is
            // the tube angle), or for a swapped one the parallel at the
            // internal u = 0 (its parameter the axis angle).
            Surf::Torus { c, big, r, .. } if !fr.swap => {
                let d = fr.x;
                let (wb, wt) = (fr.uv(pb).1, fr.uv(pt).1);
                (
                    Curve::Circle {
                        center: (c + d * big).arr(),
                        normal: d.cross(fr.z).arr(),
                        x_axis: d.arr(),
                        radius: r,
                    },
                    [wb, wt],
                )
            }
            Surf::Torus { c, big, r, .. } => {
                let (wb, wt) = (fr.uv(pb).1, fr.uv(pt).1);
                (
                    Curve::Circle {
                        center: (c + fr.z * (r * sin(fr.t0))).arr(),
                        normal: fr.z.arr(),
                        x_axis: fr.x.arr(),
                        radius: big + r * cos(fr.t0),
                    },
                    [wb, wt],
                )
            }
            _ => {
                let l = (pt - pb).len();
                (
                    Curve::Line {
                        origin: pb.arr(),
                        direction: (pt - pb).norm().arr(),
                    },
                    [0.0, l],
                )
            }
        };
        let seam = topo.edges.len();
        topo.edges.push(TEdge {
            v0: vb,
            v1: vt,
            curve,
            range,
            faces: [f, f],
            chain: Vec::new(),
            seam: true,
            dev: 0.0,
            chain_dev: 0.0,
        });
        // The loops after splitting; rotate each end loop to start at its
        // seam vertex, then join them with the seam into one loop.
        let cur = topo.faces[f].loops.clone();
        let rotate_to = |lp: &[(usize, bool)], vx: usize, topo: &Topo| -> Vec<(usize, bool)> {
            let k = lp
                .iter()
                .position(|&c| topo.start(c) == vx)
                .expect("seam vertex on its loop");
            lp[k..].iter().chain(&lp[..k]).copied().collect()
        };
        let mut merged = Vec::new();
        if let End::Loop(i) = bot {
            merged.extend(rotate_to(&cur[i], vb, topo));
        }
        merged.push((seam, true));
        if let End::Loop(i) = top {
            merged.extend(rotate_to(&cur[i], vt, topo));
        }
        merged.push((seam, false));
        let mut new_loops = vec![merged];
        for (i, lp) in cur.into_iter().enumerate() {
            if End::Loop(i) != bot && End::Loop(i) != top {
                new_loops.push(lp);
            }
        }
        topo.faces[f].loops = new_loops;
        topo.faces[f].param = Some(fr);
    }
    Ok(())
}

/// Builds the parameter-space curve of one coedge (pass 2): a segment
/// when the edge is an iso-line of the frame, else a cubic refined until
/// its image lies within `fit_tol` of the edge's other surface.
#[allow(clippy::too_many_arguments)]
fn pcurve(
    topo: &Topo,
    param: &Param,
    other: Option<Surf>,
    e: usize,
    fwd: bool,
    start_u: f64,
    tol: f64,
    fit_tol: f64,
) -> (BSpline<2>, f64, f64) {
    let ed = &topo.edges[e];
    // Start coarse and double: the samples become the fit's control
    // points, so starting from the edge's own (dense) sampling would write
    // far more of them than the tolerance needs.
    let mut n = match ed.curve {
        Curve::Line { .. } => 4,
        _ => 16,
    };
    loop {
        let pts = coedge_points(topo, e, fwd, n);
        let mut s = lift(param, &pts, Some(start_u), tol);
        let end_u = s.last().expect("samples").u;
        if !fwd {
            s.reverse();
        }
        let uv: Vec<[f64; 2]> = s.iter().map(|x| [x.u, x.v]).collect();
        // Parametrised like the edge's 3D curve (see
        // `bspline::interpolate_at`).
        let ts: Vec<f64> = s.iter().map(|x| x.t).collect();
        let (a, b) = (uv[0], uv[uv.len() - 1]);
        let iso_u = uv.iter().all(|q| (q[0] - a[0]).abs() < 1e-12);
        let iso_v = uv
            .iter()
            .all(|q| (q[1] - a[1]).abs() < 1e-12 * (1.0 + a[1].abs()));
        let bs = if (iso_u || iso_v) && linear_in(&uv, &ts) {
            bspline::interpolate_at(&[a, b], &[ts[0], ts[ts.len() - 1]])
        } else {
            bspline::interpolate_at(&uv, &ts)
        };
        // How far the curve's image strays from the other face. Across a
        // tangent contact that distance changes only to second order with
        // a stray off the edge: a coarse curve on a cylinder beside a
        // blend passed while lying 1e-4 off the contact, and the face's
        // area came out 5e-4 wrong. There the stray across the edge's own
        // curve at the same parameter (the parameter-space curve shares
        // it) counts too, away from the ends (which are the vertices).
        // Only at tangent contacts: across a transversal edge the other
        // face sees any stray, while the edge's 3D curve (an intersection
        // fitted to its own tolerance) is no better a guide, and holding
        // the image to it there refined every such pcurve to thousands of
        // points, doubling STEP files.
        let ce = CurveEval::new(&ed.curve);
        let [t0, t1] = [bs.knots[0], *bs.knots.last().expect("knots")];
        let tangent = other.as_ref().is_some_and(|o| {
            let pm = ce.at(0.5 * (t0 + t1));
            let (nf, no) = (param.s.grad(pm).norm(), o.grad(pm).norm());
            nf.cross(no).len() < 0.05
        });
        let dev = {
            let m = (4 * uv.len()).min(16384);
            (0..=m)
                .map(|i| {
                    let t = t0 + (t1 - t0) * i as f64 / m as f64;
                    let q = bspline::eval(&bs, t);
                    let p = param.eval(q[0], q[1]);
                    let off = other.as_ref().map_or(0.0, |o| o.f(p).abs());
                    let across = if !tangent || i == 0 || i == m {
                        0.0
                    } else {
                        let d = p - ce.at(t);
                        d.reject(ce.deriv(t).norm()).len()
                    };
                    off.max(across)
                })
                .fold(0.0, f64::max)
        };
        if dev < fit_tol || n >= 4096 {
            return (bs, end_u, dev);
        }
        n *= 2;
    }
}

/// Whether the points are the segment from the first to the last,
/// traversed linearly in the curve parameter `ts` (to rounding), so that a
/// degree-1 curve on `ts`' range is exact and shares the edge's parameter.
fn linear_in(uv: &[[f64; 2]], ts: &[f64]) -> bool {
    let (a, b) = (uv[0], uv[uv.len() - 1]);
    let (t0, t1) = (ts[0], ts[ts.len() - 1]);
    let l = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
    if t1 <= t0 {
        return false;
    }
    uv.iter().zip(ts).all(|(q, &t)| {
        let f = (t - t0) / (t1 - t0);
        let e = [
            a[0] + (b[0] - a[0]) * f - q[0],
            a[1] + (b[1] - a[1]) * f - q[1],
        ];
        (e[0] * e[0] + e[1] * e[1]).sqrt() < 1e-12 * (1.0 + l)
    })
}

/// Pass 2: parameter-space curves on curved faces, and which loop is
/// outer. Returns the largest pcurve deviation.
fn pcurves(topo: &mut Topo, scale: f64, fit_tol: f64) -> f64 {
    let tol = 1e-9 * scale;
    let mut max_dev = 0.0f64;
    for f in 0..topo.faces.len() {
        let param = topo.faces[f].param.clone().expect("param");
        let s = if param.sense(topo.faces[f].same_sense) {
            1.0
        } else {
            -1.0
        };
        let loops = topo.faces[f].loops.clone();
        let mut all_pc = Vec::with_capacity(loops.len());
        let mut outer = Vec::with_capacity(loops.len());
        for lp in &loops {
            if !param.has_pcurves() {
                outer.push(s * planar_loop_area(topo, &param, lp) > 0.0);
                all_pc.push(vec![None; lp.len()]);
                continue;
            }
            if is_double_seam_loop(topo, &param, lp) {
                let pcs = double_seam_pcurves(topo, &param, lp, topo.faces[f].same_sense);
                all_pc.push(pcs.into_iter().map(Some).collect());
                outer.push(true);
                continue;
            }
            let seamed = lp.iter().any(|&(e, _)| topo.edges[e].seam);
            // Where the loop starts in u, so that the whole face lies in
            // [0, 2π].
            let start_u = if seamed {
                let fwd_u = if s > 0.0 { TAU } else { 0.0 };
                match lp[0] {
                    (e, true) if topo.edges[e].seam => fwd_u,
                    _ => TAU - fwd_u,
                }
            } else {
                let l = lift_loop(topo, &param, lp, None, tol);
                let pts: Vec<f64> = l.iter().flatten().map(|x| x.u).collect();
                let mean = pts.iter().sum::<f64>() / pts.len() as f64;
                let lo = pts.iter().copied().fold(f64::INFINITY, f64::min);
                let hi = pts.iter().copied().fold(f64::NEG_INFINITY, f64::max);
                // Shift by whole turns so the loop sits inside [0, 2π]
                // (when it spans a full turn, from 0). A B-spline's `u` is
                // its own and is never shifted.
                let k = if !param.periodic() {
                    0.0
                } else if hi - lo >= TAU - 1e-9 {
                    (lo / TAU).round()
                } else {
                    ((mean - PI) / TAU).round()
                };
                l[0][0].u - k * TAU
            };
            let mut cur_u = start_u;
            let mut pcs = Vec::with_capacity(lp.len());
            for &(e, fwd) in lp {
                let ed = &topo.edges[e];
                if ed.seam {
                    let u = if fwd == (s > 0.0) { TAU } else { 0.0 };
                    let (vb, vt) = (param.uv(topo.verts[ed.v0]).1, param.uv(topo.verts[ed.v1]).1);
                    let (vb, vt) = match param.s {
                        Surf::Sphere { .. } | Surf::Torus { .. } => (ed.range[0], ed.range[1]),
                        _ => (vb, vt),
                    };
                    // v is linear in the seam's own parameter (length
                    // along a line, latitude along a meridian).
                    pcs.push(Some(bspline::interpolate_at(
                        &[[u, vb], [u, vt]],
                        &ed.range,
                    )));
                    cur_u = u;
                    continue;
                }
                let other = {
                    let [a, b] = ed.faces;
                    let o = if a == f { b } else { a };
                    (o != f).then(|| topo.faces[o].surf.clone())
                };
                let (bs, end_u, dev) = pcurve(topo, &param, other, e, fwd, cur_u, tol, fit_tol);
                max_dev = max_dev.max(dev);
                pcs.push(Some(bs));
                cur_u = end_u;
            }
            if seamed {
                outer.push(true);
            } else {
                let l = lift_loop(topo, &param, lp, Some(start_u), tol);
                outer.push(s * area(&l) > 0.0);
            }
            if param.swap {
                // Back to STEP's (axis angle, tube angle).
                for bs in pcs.iter_mut().flatten() {
                    for q in &mut bs.control {
                        *q = param.step_coords(*q);
                    }
                }
            }
            all_pc.push(pcs);
        }
        // The frame as written: STEP's coordinates, whatever the internal
        // ones were.
        let mut written = param;
        written.swap = false;
        topo.faces[f].param = Some(written);
        topo.faces[f].pcurves = all_pc;
        topo.faces[f].outer = outer;
    }
    max_dev
}

/// Frames, seams and parameter-space curves for every face. Returns the
/// largest pcurve deviation.
pub(crate) fn parametrise(topo: &mut Topo, scale: f64, fit_tol: f64) -> Result<f64, Failure> {
    frames_and_seams(topo, scale)?;
    Ok(pcurves(topo, scale, fit_tol))
}