brepkit-math 4.11.20

Vector math, transforms, NURBS, and geometric predicates for brepkit
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
//! SSI seed finding: subdivision-based and grid-based approaches, plus the
//! main `intersect_nurbs_nurbs` entry point.

use crate::madd::Madd;
use std::collections::VecDeque;

use crate::MathError;
use crate::aabb::Aabb3;
use crate::bvh::Bvh;
use crate::nurbs::curve::NurbsCurve;
use crate::nurbs::decompose::BezierPatch;
use crate::nurbs::projection::{
    SurfaceProjection, project_point_to_surface, project_point_to_surface_from,
};
use crate::nurbs::surface::NurbsSurface;
use crate::vec::{Point3, Vec3};

use super::chaining::{Section, build_curves_from_chains, chain_traced_segments};
use super::curve_surface::intersect_curve_surface;
use super::surface_marching::{
    constrain_param, constrain_state, march_with_branches, near_existing_segment,
    surface_newton_step,
};
use super::{IntersectionCurve, IntersectionPoint, MAX_NEWTON_ITER, MAX_QUEUE_SIZE, MAX_SEGMENTS};

/// The plane a patch lies in, when every control point lies on it to
/// rounding: as `(unit normal, offset)`, from the cross of its corners'
/// diagonals. Rounding is weighed by the plane's own terms, so that a patch
/// far along the plane keeps its curvature.
pub(super) fn plane_of(surface: &NurbsSurface) -> Option<(Vec3, f64)> {
    let cps = surface.control_points();
    let (first, last) = (cps.first()?, cps.last()?);
    let corners = [
        *first.first()?,
        *first.last()?,
        *last.first()?,
        *last.last()?,
    ];
    let across = (corners[3] - corners[0]).cross(corners[1] - corners[2]);
    let normal = across.normalize().ok()?;
    let offset = normal.dot(Vec3::new(corners[0].x(), corners[0].y(), corners[0].z()));
    let scale = cps
        .iter()
        .flatten()
        .map(|&p| super::plane::plane_terms(normal, offset, p))
        .fold(0.0, f64::max);
    cps.iter()
        .flatten()
        .all(|&p| normal.dot(p - corners[0]).abs() <= 64.0 * f64::EPSILON * scale)
        .then_some((normal, offset))
}

/// Points along a flat patch's fitted section checked to lie on the patch,
/// for each point of the section.
const CURVE_CHECKS: usize = 4;

/// When `flat` lies in a plane, the plane's section of `other`, as
/// [`intersect_plane_nurbs`](super::intersect_plane_nurbs) finds it, with
/// each point's parameters on both patches (`flat`'s first when
/// `flat_first`). `None` unless the section lies on `flat` itself, at its
/// points and along its fitted curve between them: a section reaching past
/// the patch is left to the marcher, and so is one the plane's grid may
/// have missed a branch of, where the search below can find it.
pub(super) fn planar_patch_sections(
    flat: &NurbsSurface,
    other: &NurbsSurface,
    samples: usize,
    flat_first: bool,
) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
    let Some((normal, offset)) = plane_of(flat) else {
        return Ok(None);
    };
    let mut curves = super::intersect_plane_nurbs(other, normal, offset, samples)?;
    if curves.is_empty() {
        return Ok(None);
    }
    // The plane's grid can miss a branch narrower than its step while it
    // finds others. A span of `other` whose control points reach the plane,
    // to rounding, may meet it there, crossing or only touching it; where
    // no point of the section lies in such a span, the search looks
    // instead.
    let rounding = 64.0
        * f64::EPSILON
        * other
            .control_points()
            .iter()
            .flatten()
            .map(|&p| super::plane::plane_terms(normal, offset, p))
            .fold(0.0, f64::max);
    let Ok(patches) = other.bezier_patches() else {
        return Ok(None);
    };
    for patch in patches.iter() {
        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
        for p in patch.surface.control_points().iter().flatten() {
            let side = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - offset;
            (low, high) = (low.min(side), high.max(side));
        }
        let (u0, u1) = patch.u_range;
        let (v0, v1) = patch.v_range;
        let (su, sv) = (1e-9 * (u1 - u0), 1e-9 * (v1 - v0));
        let met = curves.iter().flat_map(|c| &c.points).any(|q| {
            let (u, v) = q.param1;
            (u0 - su..=u1 + su).contains(&u) && (v0 - sv..=v1 + sv).contains(&v)
        });
        if low <= rounding && high >= -rounding && !met {
            return Ok(None);
        }
    }
    let (u_lo, u_hi) = flat.domain_u();
    let (v_lo, v_hi) = flat.domain_v();
    let slack = 1e-9 * (u_hi - u_lo).max(v_hi - v_lo);
    let on_flat = |foot: &SurfaceProjection| {
        (u_lo - slack..=u_hi + slack).contains(&foot.u)
            && (v_lo - slack..=v_hi + slack).contains(&foot.v)
            && foot.distance <= 1e-7
    };
    for curve in &mut curves {
        let mut feet = Vec::with_capacity(curve.points.len());
        for point in &mut curve.points {
            let Ok(foot) = project_point_to_surface(flat, point.point, 1e-10) else {
                return Ok(None);
            };
            if !on_flat(&foot) {
                return Ok(None);
            }
            feet.push((point.point, (foot.u, foot.v)));
            let on_other = point.param1;
            (point.param1, point.param2) = if flat_first {
                ((foot.u, foot.v), on_other)
            } else {
                (on_other, (foot.u, foot.v))
            };
        }
        // The fitted curve between the points must lie on the patch too: a
        // section passing just outside the patch's edge between points, or
        // across a gap in it, leaves its points on the patch.
        let (t0, t1) = curve.curve.domain();
        let checks = CURVE_CHECKS * feet.len();
        for k in 0..=checks {
            #[allow(clippy::cast_precision_loss)]
            let q = curve
                .curve
                .evaluate((t1 - t0).madd(k as f64 / checks as f64, t0));
            let Some(&(_, near)) = feet
                .iter()
                .min_by(|a, b| (a.0 - q).length().total_cmp(&(b.0 - q).length()))
            else {
                return Ok(None);
            };
            let Ok(foot) = project_point_to_surface_from(flat, q, near, 1e-10) else {
                return Ok(None);
            };
            let inside = (u_lo - slack..=u_hi + slack).contains(&foot.u)
                && (v_lo - slack..=v_hi + slack).contains(&foot.v);
            // The fit keeps within its tolerance of the plane, not on it.
            if !inside || foot.distance > 1e-6 {
                return Ok(None);
            }
        }
    }
    Ok(Some(curves))
}

/// What the sections kept by [`intersect_nurbs_nurbs`] may hold in all: their
/// surfaces' control points and their curves' points together.
const SECTIONS_KEPT: usize = 1 << 19;

/// A pair of surfaces intersected lately, anywhere: both surfaces' content
/// keys and data, the call's grid and step, and the sections found.
pub(super) struct KeptSections {
    keys: (u64, u64),
    surfaces: (NurbsSurface, NurbsSurface),
    samples: usize,
    step: u64,
    curves: Vec<IntersectionCurve>,
    size: usize,
}

/// The sections worked out lately, the most lately used last.
static SECTIONS: std::sync::Mutex<Vec<KeptSections>> = std::sync::Mutex::new(Vec::new());

impl KeptSections {
    pub(super) fn new(
        surfaces: (&NurbsSurface, &NurbsSurface),
        samples: usize,
        march_step: f64,
        curves: Vec<IntersectionCurve>,
    ) -> Self {
        let points = |s: &NurbsSurface| s.control_points().iter().map(Vec::len).sum::<usize>();
        let size = points(surfaces.0)
            + points(surfaces.1)
            + curves
                .iter()
                .map(|c| c.points.len() + c.curve.control_points().len())
                .sum::<usize>();
        Self {
            keys: (surfaces.0.content_key(), surfaces.1.content_key()),
            surfaces: (surfaces.0.data_only(), surfaces.1.data_only()),
            samples,
            step: march_step.to_bits(),
            curves,
            size,
        }
    }

    fn is_for(&self, other: &Self) -> bool {
        self.keys == other.keys
            && self.samples == other.samples
            && self.step == other.step
            && self.surfaces.0.same_bits(&other.surfaces.0)
            && self.surfaces.1.same_bits(&other.surfaces.1)
    }

    #[cfg(test)]
    pub(super) const fn size(&self) -> usize {
        self.size
    }
}

/// The sections `kept` holds for the call `wanted` names, their entry moved
/// to the end as the most lately used.
pub(super) fn sections_kept(
    kept: &mut Vec<KeptSections>,
    wanted: &KeptSections,
) -> Option<Vec<IntersectionCurve>> {
    let at = kept.iter().position(|e| e.is_for(wanted))?;
    let entry = kept.remove(at);
    let curves = entry.curves.clone();
    kept.push(entry);
    Some(curves)
}

/// Keeps `entry` in `kept` as the most lately used, within `limit` points in
/// all. The least lately used entries go first to make room, in one pass. An
/// entry over the limit by itself is not kept, nor is one whose call `kept`
/// already holds, where another caller worked it out meanwhile.
pub(super) fn keep_sections(kept: &mut Vec<KeptSections>, entry: KeptSections, limit: usize) {
    if entry.size > limit || kept.iter().any(|e| e.is_for(&entry)) {
        return;
    }
    let mut total: usize = kept.iter().map(|e| e.size).sum();
    let mut gone = 0;
    while total + entry.size > limit {
        total -= kept[gone].size;
        gone += 1;
    }
    kept.drain(..gone);
    kept.push(entry);
}

/// Intersect two NURBS surfaces.
///
/// A pair already intersected lately with the same grid and step (the same
/// surfaces bit for bit: faces of one fitted body often share a surface, and
/// a boolean meets each pair of them) takes the sections found then, which
/// are what intersecting it again would find.
///
/// Uses a subdivision + marching approach:
/// 1. Sample both surfaces on grids to find seed points where they are close
/// 2. Refine seeds with Newton iteration in (u1,v1,u2,v2) space
/// 3. March along the intersection curve from each seed
/// 4. Fit NURBS curves through the traced points
///
/// # Parameters
///
/// - `surface1`, `surface2`: The two NURBS surfaces
/// - `samples`: Grid resolution for seed finding (e.g., 20)
/// - `march_step`: Step size for marching. If `0.0`, an adaptive initial
///   step is computed from the parameter domain extents and control polygon
///   diagonals.
///
/// # Errors
///
/// Returns an error if NURBS evaluation or curve fitting fails.
pub fn intersect_nurbs_nurbs(
    surface1: &NurbsSurface,
    surface2: &NurbsSurface,
    samples: usize,
    march_step: f64,
) -> Result<Vec<IntersectionCurve>, MathError> {
    let mut entry = KeptSections::new((surface1, surface2), samples, march_step, Vec::new());
    let found = SECTIONS
        .lock()
        .ok()
        .and_then(|mut kept| sections_kept(&mut kept, &entry));
    if let Some(curves) = found {
        return Ok(curves);
    }
    let curves = sections_of(surface1, surface2, samples, march_step)?;
    entry.size += curves
        .iter()
        .map(|c| c.points.len() + c.curve.control_points().len())
        .sum::<usize>();
    if entry.size <= SECTIONS_KEPT
        && let Ok(mut kept) = SECTIONS.lock()
    {
        entry.curves.clone_from(&curves);
        keep_sections(&mut kept, entry, SECTIONS_KEPT);
    }
    Ok(curves)
}

/// [`intersect_nurbs_nurbs`] worked out.
#[allow(clippy::too_many_lines)]
fn sections_of(
    surface1: &NurbsSurface,
    surface2: &NurbsSurface,
    samples: usize,
    march_step: f64,
) -> Result<Vec<IntersectionCurve>, MathError> {
    if let Some(curves) = planar_patch_sections(surface1, surface2, samples, true)? {
        return Ok(curves);
    }
    if let Some(curves) = planar_patch_sections(surface2, surface1, samples, false)? {
        return Ok(curves);
    }
    let n = samples.max(5);
    let tolerance = 1e-6;

    // Surfaces whose control hulls part under subdivision meet nowhere: no
    // seed search, by grid or along a boundary, has anything to find.
    if surfaces_apart(surface1, surface2, 10.0 * tolerance) {
        return Ok(Vec::new());
    }

    // Compute adaptive initial step if not explicitly provided.
    let march_step = if march_step <= 0.0 || march_step > 1.0 {
        // Use parameter domain extent -- step is a fraction of the smallest
        // domain dimension. This ensures roughly consistent point density
        // regardless of surface parameterization scale.
        let (u1_min, u1_max) = surface1.domain_u();
        let (v1_min, v1_max) = surface1.domain_v();
        let (u2_min, u2_max) = surface2.domain_u();
        let (v2_min, v2_max) = surface2.domain_v();
        let extent1 = (u1_max - u1_min).min(v1_max - v1_min);
        let extent2 = (u2_max - u2_min).min(v2_max - v2_min);
        let min_extent = extent1.min(extent2);
        // Start with 1/50th of the smallest domain dimension -- the RKF45
        // and curvature adaptation will refine from there.
        (min_extent / 50.0).max(1e-4)
    } else {
        march_step
    };

    // Phase 1: Find seed points using Bezier subdivision.
    // Falls back to grid sampling if decomposition fails.
    let seeds = {
        let sub_seeds = find_ssi_seeds_subdivision(surface1, surface2, tolerance);
        if sub_seeds.is_empty() {
            find_ssi_seeds_grid(surface1, surface2, n, tolerance)
        } else {
            sub_seeds
        }
    };

    // An open branch ends where a boundary curve of one patch meets the
    // other, so those points seed every open branch; the subdivision alone
    // can miss a short one in a patch corner (a fillet run's end against a
    // leaning corner, x 1.7 long on a run of 82).
    let mut seeds = seeds;
    let boundary = boundary_seeds(surface1, surface2, tolerance);
    for &b in &boundary {
        if !seeds
            .iter()
            .any(|s| (s.point - b.point).length() < tolerance * 100.0)
        {
            seeds.push(b);
        }
    }
    if seeds.is_empty() {
        return Ok(Vec::new());
    }

    // Phase 2: March from each seed along the intersection curve.
    // Uses a work-queue to discover branch points during marching and
    // spawn additional traces from those branches. Segment-distance
    // dedup avoids redundant marching on already-traced curves.
    let dedup_dist = march_step * 0.5;
    let mut traced_segments: Vec<Vec<IntersectionPoint>> = Vec::new();
    let mut work_queue: VecDeque<IntersectionPoint> = seeds.into();

    while let Some(seed) = work_queue.pop_front() {
        if traced_segments.len() >= MAX_SEGMENTS {
            break;
        }

        // Segment-distance dedup: check if this seed is near any already-
        // traced polyline *segment*, not just individual points. This
        // prevents false positives when a seed is near the middle of a
        // traced curve but could reach a different branch.
        if near_existing_segment(&traced_segments, &seed, dedup_dist) {
            continue;
        }

        let (traced, branch_seeds) =
            march_with_branches(surface1, surface2, &seed, march_step, tolerance);

        if !traced.is_empty() {
            traced_segments.push(traced);
        }

        // Add branch seeds to the work queue (capped).
        for bs in branch_seeds {
            if work_queue.len() < MAX_QUEUE_SIZE {
                work_queue.push_back(bs);
            }
        }
    }

    // A bridge joins two seeds no march reached and stays a chain of its
    // own: within the chainer's marcher-scale trim and join radii of another
    // branch it would be trimmed away or spliced onto that branch.
    let bridges = bridge_orphan_seeds(
        surface1,
        surface2,
        &boundary,
        &traced_segments,
        dedup_dist,
        tolerance,
    );

    // Phase 3: Assemble the traced segments into ordered chains and fit a
    // curve through each. A segment re-tracing another from a later seed is
    // trimmed where it overlaps (within the seed dedup distance), and the
    // pieces left meet the chains they continue within one marched step.
    let longest_step = traced_segments
        .iter()
        .flat_map(|seg| seg.windows(2))
        .map(|w| (w[1].point - w[0].point).length())
        .fold(0.0_f64, f64::max);
    let mut chains = chain_traced_segments(traced_segments, dedup_dist, dedup_dist + longest_step);
    chains.extend(bridges);
    if chains.is_empty() {
        return Ok(Vec::new());
    }
    let foot = |s: &NurbsSurface, p: Point3, uv: (f64, f64)| {
        project_point_to_surface_from(s, p, uv, tolerance)
            .or_else(|_| project_point_to_surface(s, p, tolerance))
            .ok()
    };
    let off = |p: Point3, near: &IntersectionPoint| {
        let a = foot(surface1, p, near.param1)?;
        let b = foot(surface2, p, near.param2)?;
        Some(a.distance.max(b.distance))
    };
    // Newton aims a tenth inside the tolerance and its fallback accepts ten
    // times its aim, so no point the fit adds strays past the tolerance.
    let settle = |p: Point3, near: &IntersectionPoint| {
        let a = foot(surface1, p, near.param1)?;
        let b = foot(surface2, p, near.param2)?;
        refine_ssi_point(surface1, surface2, a.u, a.v, b.u, b.v, tolerance * 0.1)
    };
    build_curves_from_chains(
        &chains,
        tolerance,
        &Section {
            off: &off,
            settle: &settle,
        },
    )
}

/// Curves between boundary seeds no traced segment reached. A march keeps
/// every state a margin inside each patch's domain, so a curve crossing a
/// patch's corner closer to it than that margin takes no step from either of
/// its ends (a strut facet's corner poking 0.001 through a corner cylinder,
/// its section 0.003 long). Two such seeds within a twentieth of the smaller
/// patch's size are joined where every midpoint refined onto both patches
/// lies inside both domains and between its neighbours. A seed within `near`
/// of a traced segment counts as reached, the distance at which the march
/// skips a seed as traced, so a bridge never retraces a branch.
fn bridge_orphan_seeds(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    boundary: &[IntersectionPoint],
    traced: &[Vec<IntersectionPoint>],
    near: f64,
    tolerance: f64,
) -> Vec<Vec<IntersectionPoint>> {
    let reached = |b: &IntersectionPoint| {
        traced
            .iter()
            .any(|seg| seg.len() >= 2 && near_existing_segment(std::slice::from_ref(seg), b, near))
    };
    let orphans: Vec<IntersectionPoint> =
        boundary.iter().filter(|b| !reached(b)).copied().collect();
    if orphans.len() < 2 {
        return Vec::new();
    }
    let size = |s: &NurbsSurface| {
        let b = s.aabb();
        (b.max - b.min).length()
    };
    let reach = 0.05 * size(s1).min(size(s2));
    // The edges of either patch a seed lies on. Two seeds on one edge bound
    // a section along that edge, which the march leaves to the edge itself.
    let edges = |p: &IntersectionPoint| {
        let mut on = Vec::new();
        for (k, (s, (u, v))) in [(s1, p.param1), (s2, p.param2)].into_iter().enumerate() {
            for (axis, x, (lo, hi)) in [(0, u, s.domain_u()), (1, v, s.domain_v())] {
                let near = 1e-5 * (hi - lo);
                if (x - lo).abs() <= near {
                    on.push((k, axis, false));
                } else if (hi - x).abs() <= near {
                    on.push((k, axis, true));
                }
            }
        }
        on
    };
    let mut used = vec![false; orphans.len()];
    let mut out = Vec::new();
    for i in 0..orphans.len() {
        if used[i] {
            continue;
        }
        let nearest = (i + 1..orphans.len())
            .filter(|&j| !used[j])
            .map(|j| (j, (orphans[j].point - orphans[i].point).length()))
            .filter(|&(j, d)| {
                d > tolerance * 100.0
                    && d < reach
                    && !edges(&orphans[i])
                        .iter()
                        .any(|e| edges(&orphans[j]).contains(e))
            })
            .min_by(|a, b| a.1.total_cmp(&b.1));
        let Some((j, _)) = nearest else {
            continue;
        };
        if let Some(bridge) = bridge_seeds(s1, s2, &orphans[i], &orphans[j], tolerance) {
            used[i] = true;
            used[j] = true;
            out.push(bridge);
        }
    }
    out
}

/// The curve from `a` to `b`, both on both patches, by four rounds of
/// midpoints refined onto both, or `None` where a midpoint leaves either
/// domain or strays from between its neighbours.
fn bridge_seeds(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    a: &IntersectionPoint,
    b: &IntersectionPoint,
    tolerance: f64,
) -> Option<Vec<IntersectionPoint>> {
    let within = |s: &NurbsSurface, (u, v): (f64, f64)| {
        let ((u0, u1), (v0, v1)) = (s.domain_u(), s.domain_v());
        let slack = 1e-9 * (u1 - u0).max(v1 - v0);
        (u0 - slack..=u1 + slack).contains(&u) && (v0 - slack..=v1 + slack).contains(&v)
    };
    let mut pts = vec![*a, *b];
    for _ in 0..4 {
        let mut next = Vec::with_capacity(pts.len() * 2);
        next.push(pts[0]);
        for w in pts.windows(2) {
            let (p, q) = (w[0], w[1]);
            let m = refine_in_domain(
                s1,
                s2,
                [
                    f64::midpoint(p.param1.0, q.param1.0),
                    f64::midpoint(p.param1.1, q.param1.1),
                    f64::midpoint(p.param2.0, q.param2.0),
                    f64::midpoint(p.param2.1, q.param2.1),
                ],
                tolerance,
            );
            let m = m?;
            let chord = (q.point - p.point).length();
            if !within(s1, m.param1)
                || !within(s2, m.param2)
                || (m.point - p.point).length() >= chord
                || (m.point - q.point).length() >= chord
            {
                return None;
            }
            next.push(m);
            next.push(q);
        }
        pts = next;
    }
    Some(pts)
}

/// Newton onto both patches from `guess`, clamped to each patch's own domain
/// rather than the march's margin inside it: a bridge's points lie within
/// that margin of a corner.
fn refine_in_domain(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    guess: [f64; 4],
    tolerance: f64,
) -> Option<IntersectionPoint> {
    let clamp = |state: [f64; 4]| {
        let ((a0, a1), (b0, b1)) = (s1.domain_u(), s1.domain_v());
        let ((c0, c1), (d0, d1)) = (s2.domain_u(), s2.domain_v());
        [
            state[0].clamp(a0, a1),
            state[1].clamp(b0, b1),
            state[2].clamp(c0, c1),
            state[3].clamp(d0, d1),
        ]
    };
    let mut state = clamp(guess);
    for _ in 0..MAX_NEWTON_ITER {
        let (p1, p2) = (
            s1.evaluate(state[0], state[1]),
            s2.evaluate(state[2], state[3]),
        );
        let r = p1 - p2;
        if r.length() < tolerance {
            return Some(IntersectionPoint {
                point: p1,
                param1: (state[0], state[1]),
                param2: (state[2], state[3]),
            });
        }
        let d1 = s1.first_derivatives(state[0], state[1]);
        let d2 = s2.first_derivatives(state[2], state[3]);
        let j = [d1.1, d1.2, -d2.1, -d2.2];
        let r_vec = Vec3::new(r.x(), r.y(), r.z());
        let jtr: [f64; 4] = std::array::from_fn(|i| -j[i].dot(r_vec));
        let mut jtj: [[f64; 4]; 4] =
            std::array::from_fn(|i| std::array::from_fn(|k| j[i].dot(j[k])));
        // The curve is a one-parameter family of solutions, so the normal
        // equations are singular along it: damping takes the least step.
        let lambda = (jtj[0][0] + jtj[1][1] + jtj[2][2] + jtj[3][3]).max(1e-10) * 1e-9;
        for (i, row) in jtj.iter_mut().enumerate() {
            row[i] += lambda;
        }
        let delta = solve_4x4(jtj, jtr)?;
        state = clamp(std::array::from_fn(|i| state[i] + delta[i]));
    }
    None
}

/// Points where a boundary curve of either patch crosses the other patch.
fn boundary_seeds(s1: &NurbsSurface, s2: &NurbsSurface, tolerance: f64) -> Vec<IntersectionPoint> {
    const MAX_BOUNDARY_SEEDS: usize = 16;
    let mut out = Vec::new();
    for (own_is_s1, own, other) in [(true, s1, s2), (false, s2, s1)] {
        for (curve, fixed_is_u, fixed) in boundary_curves(own) {
            let Ok(hits) = intersect_curve_surface(&curve, other, tolerance) else {
                continue;
            };
            for hit in hits {
                let on_edge = if fixed_is_u {
                    (fixed, hit.t)
                } else {
                    (hit.t, fixed)
                };
                let (param1, param2) = if own_is_s1 {
                    (on_edge, hit.uv)
                } else {
                    (hit.uv, on_edge)
                };
                out.push(IntersectionPoint {
                    point: hit.point,
                    param1,
                    param2,
                });
                if out.len() >= MAX_BOUNDARY_SEEDS {
                    return out;
                }
            }
        }
    }
    out
}

/// A patch's boundary curves, each with whether `u` is the parameter held
/// fixed along it and its value. A clamped knot vector puts only the end
/// row (or column) of control points on that end.
fn boundary_curves(s: &NurbsSurface) -> Vec<(NurbsCurve, bool, f64)> {
    let clamped = |k: &[f64], p: usize| {
        k.len() > 2 * p + 1
            && k[..=p].iter().all(|&x| (x - k[0]).abs() <= 1e-15)
            && k[k.len() - p - 1..]
                .iter()
                .all(|&x| (x - k[k.len() - 1]).abs() <= 1e-15)
    };
    let (ku, kv) = (s.knots_u(), s.knots_v());
    let (pu, pv) = (s.degree_u(), s.degree_v());
    let (cps, w) = (s.control_points(), s.weights());
    let mut out = Vec::new();
    if clamped(ku, pu) && !cps.is_empty() {
        for (row, u) in [(0, ku[0]), (cps.len() - 1, ku[ku.len() - 1])] {
            if let Ok(c) = NurbsCurve::new(pv, kv.to_vec(), cps[row].clone(), w[row].clone()) {
                out.push((c, true, u));
            }
        }
    }
    if clamped(kv, pv) && cps.first().is_some_and(|r| !r.is_empty()) {
        let last = cps[0].len() - 1;
        for (col, v) in [(0, kv[0]), (last, kv[kv.len() - 1])] {
            let points: Vec<Point3> = cps.iter().map(|r| r[col]).collect();
            let weights: Vec<f64> = w.iter().map(|r| r[col]).collect();
            if let Ok(c) = NurbsCurve::new(pu, ku.to_vec(), points, weights) {
                out.push((c, false, v));
            }
        }
    }
    out
}

/// Find SSI seed points using recursive Bezier patch subdivision + BVH overlap.
///
/// This approach **cannot miss intersection branches** because it converges
/// on all regions where the two surfaces are close. Steps:
/// 1. Decompose both surfaces into Bezier patches
/// 2. Build a BVH over B's patch AABBs
/// 3. For each A-patch, find overlapping B-patches
/// 4. Small overlapping pairs -> seed from centroid + `refine_ssi_point`
/// 5. Large pairs -> subdivide and recurse (max depth limit)
#[allow(clippy::cast_precision_loss)]
pub(super) fn find_ssi_seeds_subdivision(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    tolerance: f64,
) -> Vec<IntersectionPoint> {
    let patches_a = match s1.bezier_patches() {
        Ok(p) => p,
        Err(_) => return Vec::new(),
    };
    let patches_b = match s2.bezier_patches() {
        Ok(p) => p,
        Err(_) => return Vec::new(),
    };

    // Build BVH over B's patches.
    let b_entries: Vec<(usize, Aabb3)> = patches_b
        .iter()
        .enumerate()
        .map(|(i, p)| (i, p.aabb()))
        .collect();
    let bvh = Bvh::build(&b_entries);

    // Collect candidate pairs by AABB overlap.
    let mut candidate_pairs: Vec<(BezierPatch, BezierPatch)> = Vec::new();
    for pa in patches_a.iter() {
        let aabb_a = pa.aabb();
        let candidates = bvh.query_overlap(&aabb_a);
        for &b_idx in &candidates {
            candidate_pairs.push((pa.clone(), patches_b[b_idx].clone()));
        }
    }

    // Recursively subdivide overlapping pairs to find seeds.
    // 100x: patch diagonal threshold for Newton seeding -- patches this small
    // are close enough to attempt direct refinement
    let diag_threshold = tolerance * 100.0;
    let max_depth = 6;
    let mut seeds: Vec<IntersectionPoint> = Vec::new();

    subdivide_for_seeds(
        s1,
        s2,
        &candidate_pairs,
        diag_threshold,
        max_depth,
        0,
        tolerance,
        &mut seeds,
    );

    seeds
}

/// How many halvings [`surfaces_apart`] tries on one pair of patches, and
/// how many pairs it halves in all, before it gives up on a proof.
const APART_DEPTH: usize = 10;
const APART_BUDGET: usize = 512;

/// Whether no point of `s1` is proved to lie within `margin` of `s2`.
///
/// The proof is by their Bezier patches' control points: a patch lies in the
/// box of its control points, and between their extremes along any axis, and
/// halves of it lie in smaller ones. `false` says only that the patches did
/// not part within the budget.
#[must_use]
pub fn surfaces_apart(s1: &NurbsSurface, s2: &NurbsSurface, margin: f64) -> bool {
    if !holds_its_hull(s1) || !holds_its_hull(s2) {
        return false;
    }
    let (Ok(patches_a), Ok(patches_b)) = (s1.bezier_patches(), s2.bezier_patches()) else {
        return false;
    };
    let mut budget = APART_BUDGET;
    patches_a.iter().all(|pa| {
        patches_b
            .iter()
            .all(|pb| patches_apart(pa, pb, margin, 0, &mut budget))
    })
}

/// Whether a surface's Bezier patches are sure to hold it inside their
/// control points: every weight positive and finite, which keeps a rational
/// patch in its hull, and both knot vectors clamped with no interior knot
/// repeated past the degree, which is all the decomposition reads.
fn holds_its_hull(surface: &NurbsSurface) -> bool {
    let weights_hold = surface
        .weights()
        .iter()
        .flatten()
        .all(|&w| w.is_finite() && w > 0.0);
    let points_hold = surface
        .control_points()
        .iter()
        .flatten()
        .all(|p| p.x().is_finite() && p.y().is_finite() && p.z().is_finite());
    let knots_hold = |knots: &[f64], degree: usize| {
        let n = knots.len();
        if n < 2 * (degree + 1) || knots.iter().any(|k| !k.is_finite()) {
            return false;
        }
        let clamped = knots[..=degree]
            .iter()
            .all(|&k| k.to_bits() == knots[0].to_bits())
            && knots[n - degree - 1..]
                .iter()
                .all(|&k| k.to_bits() == knots[n - 1].to_bits());
        let interior = &knots[degree + 1..n - degree - 1];
        let mut run = 0;
        let mut repeats_hold = true;
        for (i, k) in interior.iter().enumerate() {
            run = if i > 0 && k.to_bits() == interior[i - 1].to_bits() {
                run + 1
            } else {
                1
            };
            repeats_hold &= run <= degree;
        }
        clamped && repeats_hold
    };
    weights_hold
        && points_hold
        && knots_hold(surface.knots_u(), surface.degree_u())
        && knots_hold(surface.knots_v(), surface.degree_v())
}

fn patches_apart(
    pa: &BezierPatch,
    pb: &BezierPatch,
    margin: f64,
    depth: usize,
    budget: &mut usize,
) -> bool {
    if !pa.aabb().expanded(margin).intersects(pb.aabb()) {
        return true;
    }
    // Two sheets running side by side part along the way either one faces
    // long before their boxes do.
    if [pa, pb]
        .into_iter()
        .filter_map(facing)
        .any(|axis| parted_along(pa, pb, axis, margin))
    {
        return true;
    }
    if depth >= APART_DEPTH || *budget == 0 {
        return false;
    }
    *budget -= 1;
    if pa.diagonal() >= pb.diagonal() {
        let halves = halve_bezier_patch(pa, longer_along_u(pa));
        halves.len() == 2
            && halves
                .iter()
                .all(|half| patches_apart(half, pb, margin, depth + 1, budget))
    } else {
        let halves = halve_bezier_patch(pb, longer_along_u(pb));
        halves.len() == 2
            && halves
                .iter()
                .all(|half| patches_apart(pa, half, margin, depth + 1, budget))
    }
}

/// The way a patch faces, read off its corner control points: the cross of
/// its two diagonals. `None` for a patch whose corners lie on a line.
fn facing(patch: &BezierPatch) -> Option<Vec3> {
    let net = patch.surface.control_points();
    let (first, last) = (net.first()?, net.last()?);
    let across = *last.last()? - *first.first()?;
    let back = *first.last()? - *last.first()?;
    across.cross(back).normalize().ok()
}

/// Whether the two patches' control points, and so the patches, lie more
/// than `margin` apart along `axis`.
fn parted_along(pa: &BezierPatch, pb: &BezierPatch, axis: Vec3, margin: f64) -> bool {
    let reach = |patch: &BezierPatch| {
        patch
            .surface
            .control_points()
            .iter()
            .flatten()
            .map(|p| axis.dot(Vec3::new(p.x(), p.y(), p.z())))
            .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| {
                (lo.min(d), hi.max(d))
            })
    };
    let (a_lo, a_hi) = reach(pa);
    let (b_lo, b_hi) = reach(pb);
    a_lo > b_hi + margin || b_lo > a_hi + margin
}

/// Recursive helper: subdivide overlapping Bezier patch pairs to find SSI seeds.
#[allow(clippy::too_many_arguments)]
fn subdivide_for_seeds(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    pairs: &[(BezierPatch, BezierPatch)],
    diag_threshold: f64,
    max_depth: usize,
    depth: usize,
    tolerance: f64,
    seeds: &mut Vec<IntersectionPoint>,
) {
    // Cap seed count: marching only needs a few seeds per intersection branch.
    // Near-tangential cases can generate thousands of subdivision candidates,
    // most of which converge to the same curve. 50 seeds is plenty.
    const MAX_SEEDS: usize = 50;

    for (pa, pb) in pairs {
        if seeds.len() >= MAX_SEEDS {
            return;
        }

        let diag_a = pa.diagonal();
        let diag_b = pb.diagonal();

        if diag_a < diag_threshold && diag_b < diag_threshold {
            // Both patches are small: try to find a seed from centroid parameters.
            // Skip Newton if patch centroids are far apart -- the AABB overlap
            // doesn't guarantee the surfaces actually intersect at this location.
            let p1 = s1.evaluate(pa.u_mid(), pa.v_mid());
            let p2 = s2.evaluate(pb.u_mid(), pb.v_mid());
            let centroid_dist = (p1 - p2).length();
            let max_diag = diag_a.max(diag_b);
            if centroid_dist > max_diag * 2.0 {
                continue;
            }

            let u1 = pa.u_mid();
            let v1 = pa.v_mid();
            let u2 = pb.u_mid();
            let v2 = pb.v_mid();

            if let Some(refined) = refine_ssi_point(s1, s2, u1, v1, u2, v2, tolerance) {
                // 100x dedup: multiple patches may converge to the same intersection
                let is_dup = seeds
                    .iter()
                    .any(|s| (s.point - refined.point).length() < tolerance * 100.0);
                if !is_dup {
                    seeds.push(refined);
                }
            }
            continue;
        }

        if depth >= max_depth {
            // Max depth: try seed anyway.
            let p1 = s1.evaluate(pa.u_mid(), pa.v_mid());
            let p2 = s2.evaluate(pb.u_mid(), pb.v_mid());
            let centroid_dist = (p1 - p2).length();
            let max_diag = diag_a.max(diag_b);
            if centroid_dist > max_diag * 2.0 {
                continue;
            }

            let u1 = pa.u_mid();
            let v1 = pa.v_mid();
            let u2 = pb.u_mid();
            let v2 = pb.v_mid();

            if let Some(refined) = refine_ssi_point(s1, s2, u1, v1, u2, v2, tolerance) {
                // 100x dedup: multiple patches may converge to the same intersection
                let is_dup = seeds
                    .iter()
                    .any(|s| (s.point - refined.point).length() < tolerance * 100.0);
                if !is_dup {
                    seeds.push(refined);
                }
            }
            continue;
        }

        // Subdivide the larger patch and check overlaps with the smaller one.
        if diag_a >= diag_b {
            // Subdivide patch A at its u or v midpoint (whichever span is larger).
            let sub_pairs = subdivide_patch_a_check_overlap(pa, pb);
            subdivide_for_seeds(
                s1,
                s2,
                &sub_pairs,
                diag_threshold,
                max_depth,
                depth + 1,
                tolerance,
                seeds,
            );
        } else {
            // Subdivide patch B.
            let sub_pairs = subdivide_patch_b_check_overlap(pa, pb);
            subdivide_for_seeds(
                s1,
                s2,
                &sub_pairs,
                diag_threshold,
                max_depth,
                depth + 1,
                tolerance,
                seeds,
            );
        }
    }
}

/// Subdivide patch A at its midpoint and return sub-pairs that overlap with B.
fn subdivide_patch_a_check_overlap(
    pa: &BezierPatch,
    pb: &BezierPatch,
) -> Vec<(BezierPatch, BezierPatch)> {
    let subs = subdivide_bezier_patch(pa);
    let aabb_b = pb.aabb();
    subs.into_iter()
        .filter(|sub| sub.aabb().intersects(aabb_b))
        .map(|sub| (sub, pb.clone()))
        .collect()
}

/// Subdivide patch B at its midpoint and return sub-pairs that overlap with A.
fn subdivide_patch_b_check_overlap(
    pa: &BezierPatch,
    pb: &BezierPatch,
) -> Vec<(BezierPatch, BezierPatch)> {
    let subs = subdivide_bezier_patch(pb);
    let aabb_a = pa.aabb();
    subs.into_iter()
        .filter(|sub| sub.aabb().intersects(aabb_a))
        .map(|sub| (pa.clone(), sub))
        .collect()
}

/// Subdivide a Bezier patch into 2 patches by splitting at the midpoint
/// of the larger parameter span (u or v).
fn subdivide_bezier_patch(patch: &BezierPatch) -> Vec<BezierPatch> {
    let u_span = patch.u_range.1 - patch.u_range.0;
    let v_span = patch.v_range.1 - patch.v_range.0;
    halve_bezier_patch(patch, u_span >= v_span)
}

/// Whether a patch's control net runs farther along `u` than along `v`: the
/// longest row of control points against the longest column. Parameter spans
/// do not say, with one parameter an angle and the other a length.
fn longer_along_u(patch: &BezierPatch) -> bool {
    let net = patch.surface.control_points();
    let run = |points: &mut dyn Iterator<Item = Point3>| {
        let mut length = 0.0;
        let mut last: Option<Point3> = None;
        for p in points {
            if let Some(q) = last {
                length += (p - q).length();
            }
            last = Some(p);
        }
        length
    };
    let columns = net.first().map_or(0, Vec::len);
    let along_u = (0..columns)
        .map(|j| run(&mut net.iter().filter_map(|row| row.get(j).copied())))
        .fold(0.0, f64::max);
    let along_v = net
        .iter()
        .map(|row| run(&mut row.iter().copied()))
        .fold(0.0, f64::max);
    along_u >= along_v
}

/// A Bezier patch's two halves about the middle of its `u` range, or of its
/// `v` range.
fn halve_bezier_patch(patch: &BezierPatch, split_u: bool) -> Vec<BezierPatch> {
    let split_param = if split_u {
        patch.u_mid()
    } else {
        patch.v_mid()
    };

    // Insert the midpoint knot to full multiplicity and split.
    let surf = &patch.surface;
    let degree = if split_u {
        surf.degree_u()
    } else {
        surf.degree_v()
    };

    let refined = if split_u {
        crate::nurbs::knot_ops::surface_knot_insert_u(surf, split_param, degree)
    } else {
        crate::nurbs::knot_ops::surface_knot_insert_v(surf, split_param, degree)
    };

    let Ok(refined) = refined else {
        return vec![patch.clone()]; // Fallback: don't subdivide
    };

    // Extract two sub-patches from the refined surface.
    if split_u {
        extract_u_subpatches(&refined, patch, split_param)
    } else {
        extract_v_subpatches(&refined, patch, split_param)
    }
}

/// Extract two sub-patches from a surface that has been refined in u.
fn extract_u_subpatches(
    refined: &NurbsSurface,
    parent: &BezierPatch,
    u_split: f64,
) -> Vec<BezierPatch> {
    let pu = refined.degree_u();
    let pv = refined.degree_v();
    let cps = refined.control_points();
    let ws = refined.weights();
    let n_rows = cps.len();
    if n_rows == 0 || cps[0].is_empty() {
        return vec![parent.clone()];
    }

    // Find the split index: the row where the u-knot multiplicity reaches pu.
    let knots_u = refined.knots_u();
    let split_row = find_split_row(knots_u, u_split, pu, n_rows);

    if split_row == 0 || split_row >= n_rows {
        return vec![parent.clone()];
    }

    let mut result = Vec::with_capacity(2);

    // Left patch: rows 0..=split_row
    if split_row >= pu {
        let left_rows = split_row + 1;
        let left_cps: Vec<Vec<Point3>> = cps[..left_rows].to_vec();
        let left_ws: Vec<Vec<f64>> = ws[..left_rows].to_vec();
        let mut left_ku = vec![parent.u_range.0; pu + 1];
        left_ku.extend(std::iter::repeat_n(u_split, pu + 1));
        let left_kv = refined.knots_v().to_vec();

        if let Ok(s) = NurbsSurface::new(pu, pv, left_ku, left_kv, left_cps, left_ws) {
            result.push(BezierPatch {
                surface: s,
                u_range: (parent.u_range.0, u_split),
                v_range: parent.v_range,
            });
        }
    }

    // Right patch: rows split_row..n_rows
    let right_rows = n_rows - split_row;
    if right_rows > pu {
        let right_cps: Vec<Vec<Point3>> = cps[split_row..].to_vec();
        let right_ws: Vec<Vec<f64>> = ws[split_row..].to_vec();
        let mut right_ku = vec![u_split; pu + 1];
        right_ku.extend(std::iter::repeat_n(parent.u_range.1, pu + 1));
        let right_kv = refined.knots_v().to_vec();

        if let Ok(s) = NurbsSurface::new(pu, pv, right_ku, right_kv, right_cps, right_ws) {
            result.push(BezierPatch {
                surface: s,
                u_range: (u_split, parent.u_range.1),
                v_range: parent.v_range,
            });
        }
    }

    if result.is_empty() {
        vec![parent.clone()]
    } else {
        result
    }
}

/// Extract two sub-patches from a surface that has been refined in v.
fn extract_v_subpatches(
    refined: &NurbsSurface,
    parent: &BezierPatch,
    v_split: f64,
) -> Vec<BezierPatch> {
    let pu = refined.degree_u();
    let pv = refined.degree_v();
    let cps = refined.control_points();
    let ws = refined.weights();
    let n_rows = cps.len();
    let n_cols = if n_rows > 0 {
        cps[0].len()
    } else {
        return vec![parent.clone()];
    };

    // Find the split column index.
    let knots_v = refined.knots_v();
    let split_col = find_split_row(knots_v, v_split, pv, n_cols);

    if split_col == 0 || split_col >= n_cols {
        return vec![parent.clone()];
    }

    let mut result = Vec::with_capacity(2);

    // Bottom patch: cols 0..=split_col
    let left_cols = split_col + 1;
    if left_cols > pv {
        let left_cps: Vec<Vec<Point3>> = cps.iter().map(|row| row[..left_cols].to_vec()).collect();
        let left_ws: Vec<Vec<f64>> = ws.iter().map(|row| row[..left_cols].to_vec()).collect();
        let left_ku = refined.knots_u().to_vec();
        let mut left_kv = vec![parent.v_range.0; pv + 1];
        left_kv.extend(std::iter::repeat_n(v_split, pv + 1));

        if let Ok(s) = NurbsSurface::new(pu, pv, left_ku, left_kv, left_cps, left_ws) {
            result.push(BezierPatch {
                surface: s,
                u_range: parent.u_range,
                v_range: (parent.v_range.0, v_split),
            });
        }
    }

    // Top patch: cols split_col..n_cols
    let right_cols = n_cols - split_col;
    if right_cols > pv {
        let right_cps: Vec<Vec<Point3>> = cps.iter().map(|row| row[split_col..].to_vec()).collect();
        let right_ws: Vec<Vec<f64>> = ws.iter().map(|row| row[split_col..].to_vec()).collect();
        let right_ku = refined.knots_u().to_vec();
        let mut right_kv = vec![v_split; pv + 1];
        right_kv.extend(std::iter::repeat_n(parent.v_range.1, pv + 1));

        if let Ok(s) = NurbsSurface::new(pu, pv, right_ku, right_kv, right_cps, right_ws) {
            result.push(BezierPatch {
                surface: s,
                u_range: parent.u_range,
                v_range: (v_split, parent.v_range.1),
            });
        }
    }

    if result.is_empty() {
        vec![parent.clone()]
    } else {
        result
    }
}

/// Find the row/column index where a knot reaches full multiplicity.
fn find_split_row(knots: &[f64], split_val: f64, degree: usize, n_cps: usize) -> usize {
    // After inserting to multiplicity `degree`, the split point is where
    // knots[i] == split_val for `degree` consecutive entries.
    // The corresponding CP index is the last of those minus degree.
    let mut count = 0_usize;
    let mut last_idx = 0_usize;
    for (i, &k) in knots.iter().enumerate() {
        if (k - split_val).abs() < 1e-15 {
            count += 1;
            last_idx = i;
        }
    }

    if count >= degree {
        let split_cp = last_idx.saturating_sub(degree);
        split_cp.min(n_cps.saturating_sub(1))
    } else {
        0
    }
}

/// Closest grid sample pairs the grid seeder refines before declaring a pair
/// non-intersecting when none of them (and no mutual nearest pair) converges.
const MAX_FAILED_SEED_ATTEMPTS: usize = 256;

/// Close grid sample pairs the grid seeder refines at once in its last pass,
/// which bounds what it holds of them however many there are.
const CLOSE_PAIRS_AT_ONCE: usize = 8192;

/// A close sample pair kept in the bounded max-heap of closest candidates.
#[derive(Clone, Copy, PartialEq)]
struct ClosePair {
    dist: f64,
    i: usize,
    k: usize,
}

impl Eq for ClosePair {}

impl PartialOrd for ClosePair {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ClosePair {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.dist
            .total_cmp(&other.dist)
            .then_with(|| self.i.cmp(&other.i))
            .then_with(|| self.k.cmp(&other.k))
    }
}

/// The seeds kept so far, bucketed by cells twice the merge distance wide,
/// so a new seed is checked against those in its own and the neighbouring
/// cells only: any seed nearer than the merge distance lies in one of them.
pub(super) struct SeedCells {
    distance: f64,
    cells: std::collections::HashMap<[i64; 3], Vec<usize>>,
}

impl SeedCells {
    pub(super) fn new(distance: f64) -> Self {
        Self {
            distance,
            cells: std::collections::HashMap::new(),
        }
    }

    #[allow(clippy::cast_possible_truncation)]
    fn cell(&self, p: Point3) -> [i64; 3] {
        let size = 2.0 * self.distance;
        [
            (p.x() / size).floor() as i64,
            (p.y() / size).floor() as i64,
            (p.z() / size).floor() as i64,
        ]
    }

    /// Whether `seed` is new among `seeds` (none nearer than the merge
    /// distance); a new one is recorded as `seeds`' next index.
    pub(super) fn insert(&mut self, seeds: &[IntersectionPoint], seed: IntersectionPoint) -> bool {
        let c = self.cell(seed.point);
        for dx in -1..=1 {
            for dy in -1..=1 {
                for dz in -1..=1 {
                    // A cell index far out is an end of `i64`'s range.
                    let near = self.cells.get(&[
                        c[0].saturating_add(dx),
                        c[1].saturating_add(dy),
                        c[2].saturating_add(dz),
                    ]);
                    if near.is_some_and(|near| {
                        near.iter()
                            .any(|&at| (seeds[at].point - seed.point).length() < self.distance)
                    }) {
                        return false;
                    }
                }
            }
        }
        self.cells.entry(c).or_default().push(seeds.len());
        true
    }
}

/// Find seed points for NURBS-NURBS intersection by grid sampling (fallback).
///
/// Strategy: sample both surfaces on an n x n grid and try Newton
/// refinement for all cell-center pairs whose 3D positions are within
/// a generous distance threshold.
pub(super) fn find_ssi_seeds_grid(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    n: usize,
    tolerance: f64,
) -> Vec<IntersectionPoint> {
    grid_seeds(s1, s2, n, tolerance, CLOSE_PAIRS_AT_ONCE)
}

/// [`find_ssi_seeds_grid`], its last pass refining `at_once` close pairs at
/// a time. The seeds do not depend on `at_once`.
#[allow(clippy::cast_precision_loss)]
pub(super) fn grid_seeds(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    n: usize,
    tolerance: f64,
    at_once: usize,
) -> Vec<IntersectionPoint> {
    let (u1_min, u1_max) = s1.domain_u();
    let (v1_min, v1_max) = s1.domain_v();
    let (u2_min, u2_max) = s2.domain_u();
    let (v2_min, v2_max) = s2.domain_v();

    #[allow(clippy::cast_precision_loss)]
    let u1_step = (u1_max - u1_min) / (n - 1) as f64;
    #[allow(clippy::cast_precision_loss)]
    let v1_step = (v1_max - v1_min) / (n - 1) as f64;
    #[allow(clippy::cast_precision_loss)]
    let u2_step = (u2_max - u2_min) / (n - 1) as f64;
    #[allow(clippy::cast_precision_loss)]
    let v2_step = (v2_max - v2_min) / (n - 1) as f64;

    let mut seeds = Vec::new();

    // Sample both surfaces.
    let mut pts1: Vec<(f64, f64, Point3)> = Vec::with_capacity(n * n);
    let mut pts2: Vec<(f64, f64, Point3)> = Vec::with_capacity(n * n);

    for i in 0..n {
        let u1 = u1_min + i as f64 * u1_step;
        for j in 0..n {
            let v1 = v1_min + j as f64 * v1_step;
            pts1.push((u1, v1, s1.evaluate(u1, v1)));
        }
    }

    for i in 0..n {
        let u2 = u2_min + i as f64 * u2_step;
        for j in 0..n {
            let v2 = v2_min + j as f64 * v2_step;
            pts2.push((u2, v2, s2.evaluate(u2, v2)));
        }
    }

    // For each pair of sample points, if close enough, try Newton.
    // Use a generous threshold based on the diagonal of a grid cell (in 3D space).
    let diag1 = (s1.evaluate(u1_min, v1_min) - s1.evaluate(u1_max, v1_max)).length();
    let diag2 = (s2.evaluate(u2_min, v2_min) - s2.evaluate(u2_max, v2_max)).length();
    #[allow(clippy::cast_precision_loss)]
    let threshold = ((diag1.max(diag2) / n as f64) * 3.0).max(0.1);

    // Newton from every close grid pair is the whole cost of this fallback:
    // neighbouring pairs converge to the same seed and are deduplicated away,
    // while a surface grazing the other within the threshold launches
    // thousands of refinements that all fail. One scan records each sample's
    // nearest partner and the MAX_FAILED_SEED_ATTEMPTS closest pairs overall
    // (bounded storage; a disjoint pair of dense patches has a million close
    // pairs). The mutual nearest pairs and the closest pairs are refined
    // first; Newton is local and a transversal crossing converges from its
    // closest samples, so when none of them converges the pair is grazing
    // without meeting (or touching tangentially, which the marcher cannot
    // trace either) and the search stops. Once any seed exists the full
    // close-pair pass runs, CLOSE_PAIRS_AT_ONCE pairs at a time, so a second
    // branch that has no mutual nearest pair is still found.
    let mut nearest_in_2: Vec<(usize, f64)> = vec![(usize::MAX, f64::MAX); pts1.len()];
    let mut nearest_in_1: Vec<(usize, f64)> = vec![(usize::MAX, f64::MAX); pts2.len()];
    let mut closest: std::collections::BinaryHeap<ClosePair> = std::collections::BinaryHeap::new();
    for (i, &(_, _, p1)) in pts1.iter().enumerate() {
        for (k, &(_, _, p2)) in pts2.iter().enumerate() {
            let dist = (p1 - p2).length();
            if dist < nearest_in_2[i].1 {
                nearest_in_2[i] = (k, dist);
            }
            if dist < nearest_in_1[k].1 {
                nearest_in_1[k] = (i, dist);
            }
            if dist < threshold {
                closest.push(ClosePair { dist, i, k });
                if closest.len() > MAX_FAILED_SEED_ATTEMPTS {
                    closest.pop();
                }
            }
        }
    }
    // Refine the grid pairs given, each from its two samples. Refinements
    // are independent, so they run in parallel; their seeds are taken in the
    // pairs' order, as one after another would take them.
    let refine_pairs = |pairs: &[(usize, usize)]| -> Vec<Option<IntersectionPoint>> {
        let refine = |&(i, k): &(usize, usize)| {
            refine_ssi_point(
                s1, s2, pts1[i].0, pts1[i].1, pts2[k].0, pts2[k].1, tolerance,
            )
        };
        // Tests count refinements on their own thread.
        #[cfg(not(any(target_arch = "wasm32", test)))]
        {
            use rayon::prelude::*;
            pairs.par_iter().map(refine).collect()
        }
        #[cfg(any(target_arch = "wasm32", test))]
        {
            pairs.iter().map(refine).collect()
        }
    };
    // 100x dedup: multiple grid samples may converge to the same intersection
    let mut kept = SeedCells::new(tolerance * 100.0);
    let mut take = |seeds: &mut Vec<IntersectionPoint>, refined: Vec<Option<IntersectionPoint>>| {
        for refined in refined.into_iter().flatten() {
            if kept.insert(seeds, refined) {
                seeds.push(refined);
            }
        }
    };
    let mutual: Vec<(usize, usize)> = nearest_in_2
        .iter()
        .enumerate()
        .filter(|&(i, &(k, dist))| dist < threshold && nearest_in_1[k].0 == i)
        .map(|(i, &(k, _))| (i, k))
        .collect();
    take(&mut seeds, refine_pairs(&mutual));
    let closest: Vec<(usize, usize)> = closest
        .into_sorted_vec()
        .iter()
        .map(|pair| (pair.i, pair.k))
        .collect();
    take(&mut seeds, refine_pairs(&closest));
    if seeds.is_empty() {
        return seeds;
    }
    let mut close = Vec::new();
    for (i, &(_, _, p1)) in pts1.iter().enumerate() {
        for (k, &(_, _, p2)) in pts2.iter().enumerate() {
            if (p1 - p2).length() < threshold {
                close.push((i, k));
                if close.len() == at_once {
                    take(&mut seeds, refine_pairs(&close));
                    close.clear();
                }
            }
        }
    }
    take(&mut seeds, refine_pairs(&close));

    seeds
}

#[cfg(test)]
thread_local! {
    /// Refinements attempted on this thread; tests run in parallel, so a
    /// process-wide counter would mix their calls.
    pub(super) static REFINE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[allow(clippy::similar_names)]
/// Refine an SSI point using coupled 4D Newton iteration.
///
/// Solves `S1(u1,v1) - S2(u2,v2) = 0` directly as a 3x4 system via
/// normal equations `JtJ*d = Jtr`, giving **quadratic convergence**.
/// This replaces the previous alternating-projection approach which had
/// only linear convergence and could fail near tangent intersections.
pub(super) fn refine_ssi_point(
    s1: &NurbsSurface,
    s2: &NurbsSurface,
    u1_guess: f64,
    v1_guess: f64,
    u2_guess: f64,
    v2_guess: f64,
    tolerance: f64,
) -> Option<IntersectionPoint> {
    #[cfg(test)]
    REFINE_CALLS.with(|calls| calls.set(calls.get() + 1));
    let mut state = [u1_guess, v1_guess, u2_guess, v2_guess];
    let mut prev_residual = f64::MAX;

    for iteration in 0..MAX_NEWTON_ITER {
        let cstate = constrain_state(&state, s1, s2);
        // Each point and its partials in one pass (the same numbers as
        // `evaluate` and `derivatives(.., 1)`).
        let (p1, d1u, d1v) = s1.point_and_first_derivatives(cstate[0], cstate[1]);
        let (p2, d2u, d2v) = s2.point_and_first_derivatives(cstate[2], cstate[3]);
        let r = p1 - p2;
        let residual = r.length();

        if residual < tolerance {
            return Some(IntersectionPoint {
                point: p1,
                param1: (cstate[0], cstate[1]),
                param2: (cstate[2], cstate[3]),
            });
        }

        // Early bail-out: if residual isn't decreasing after initial iterations,
        // the surfaces likely don't intersect near this guess. Saves ~25 wasted
        // iterations per non-intersecting patch pair in near-tangential cases.
        if iteration >= 5 && residual > prev_residual * 0.5 {
            return None;
        }
        prev_residual = residual;

        // Build 3x4 Jacobian: J = [dS1/du1, dS1/dv1, -dS2/du2, -dS2/dv2]
        let j = [d1u, d1v, -d2u, -d2v]; // 4 column vectors (Vec3)

        // Normal equations: JtJ (4x4) * d = -Jtr (4x1)
        // Use only the well-conditioned 4x4 system.
        let r_vec = Vec3::new(r.x(), r.y(), r.z());
        let jtr: [f64; 4] = std::array::from_fn(|i| -j[i].dot(r_vec));
        let jtj: [[f64; 4]; 4] = std::array::from_fn(|i| std::array::from_fn(|k| j[i].dot(j[k])));

        // Solve 4x4 system via Gaussian elimination with partial pivoting.
        // If singular (near a surface pole/apex), try Tikhonov regularization
        // before falling back to alternating projection.
        let delta = solve_4x4(jtj, jtr).or_else(|| {
            // Regularize: add lI to JtJ (Tikhonov / Levenberg-Marquardt).
            let trace = jtj[0][0] + jtj[1][1] + jtj[2][2] + jtj[3][3];
            let lambda = trace.max(1e-10) * 1e-4;
            let mut jtj_r = jtj;
            for i in 0..4 {
                jtj_r[i][i] += lambda;
            }
            solve_4x4(jtj_r, jtr)
        });

        if let Some(delta) = delta {
            state[0] += delta[0];
            state[1] += delta[1];
            state[2] += delta[2];
            state[3] += delta[3];
        } else {
            // Still singular after regularization -- fall back to alternating projection.
            let (du2, dv2) = surface_newton_step(s2, cstate[2], cstate[3], p1);
            state[2] += du2;
            state[3] += dv2;
            let p2_new = s2.evaluate(
                constrain_param(
                    state[2],
                    s2.domain_u().0,
                    s2.domain_u().1,
                    s2.is_periodic_u(),
                ),
                constrain_param(
                    state[3],
                    s2.domain_v().0,
                    s2.domain_v().1,
                    s2.is_periodic_v(),
                ),
            );
            let (du1, dv1) = surface_newton_step(s1, cstate[0], cstate[1], p2_new);
            state[0] += du1;
            state[1] += dv1;
        }
    }

    // Final check with relaxed tolerance.
    // 10x relaxation: seed points may be imprecise
    let cstate = constrain_state(&state, s1, s2);
    let p1 = s1.evaluate(cstate[0], cstate[1]);
    let p2 = s2.evaluate(cstate[2], cstate[3]);
    if (p1 - p2).length() < tolerance * 10.0 {
        Some(IntersectionPoint {
            point: p1,
            param1: (cstate[0], cstate[1]),
            param2: (cstate[2], cstate[3]),
        })
    } else {
        None
    }
}

/// Solve a 4x4 linear system via Gaussian elimination with partial pivoting.
///
/// Returns `None` if the matrix is singular.
pub(super) fn solve_4x4(a: [[f64; 4]; 4], b: [f64; 4]) -> Option<[f64; 4]> {
    let mut m = [[0.0_f64; 5]; 4];
    for i in 0..4 {
        for j in 0..4 {
            m[i][j] = a[i][j];
        }
        m[i][4] = b[i];
    }

    // Forward elimination with partial pivoting.
    for col in 0..4 {
        // Find pivot.
        let mut max_val = m[col][col].abs();
        let mut max_row = col;
        for row in (col + 1)..4 {
            if m[row][col].abs() > max_val {
                max_val = m[row][col].abs();
                max_row = row;
            }
        }
        if max_val < 1e-14 {
            return None;
        }
        if max_row != col {
            m.swap(col, max_row);
        }
        let pivot = m[col][col];
        for row in (col + 1)..4 {
            let factor = m[row][col] / pivot;
            for j in col..5 {
                m[row][j] -= factor * m[col][j];
            }
        }
    }

    // Back substitution.
    let mut x = [0.0; 4];
    for i in (0..4).rev() {
        let mut sum = m[i][4];
        for j in (i + 1)..4 {
            sum -= m[i][j] * x[j];
        }
        x[i] = sum / m[i][i];
    }

    Some(x)
}