1use crate::curve::interior_knot_count;
2use crate::fit::solve_small;
3use crate::projection::project_point_to_surface_from_seed;
4use crate::{project_point_to_surface, KnotVector, NurbsSurface, Vec3, Vec4};
5use std::collections::HashMap;
6use serde::{Deserialize, Serialize};
7
8const EPSILON: f64 = crate::tolerance::FP_FLOOR;
9const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
10
11const TRANSVERSE_START_CROSS: f64 = 1e-2;
26
27pub const TRANSVERSE_SEED_CROSS: f64 = TRANSVERSE_START_CROSS;
32
33const MARCH_REACH_EXTENTS: f64 = 4.0;
61
62fn step_budget(maximum_steps: usize, maximum_step: f64, diagonal: f64) -> usize {
65 if !(maximum_step > 0.0) || !diagonal.is_finite() {
66 return maximum_steps;
67 }
68 let needed = (MARCH_REACH_EXTENTS * diagonal / maximum_step).ceil();
69 if !needed.is_finite() || needed <= maximum_steps as f64 {
70 return maximum_steps;
71 }
72 needed as usize
73}
74
75use crate::spatial::Aabb as Bounds;
76
77
78#[derive(Clone, Copy)]
79struct SurfaceInfo<'a> {
80 surface: &'a NurbsSurface,
81 u0: f64,
82 u1: f64,
83 v0: f64,
84 v1: f64,
85 closed_u: bool,
86 closed_v: bool,
87}
88
89fn surface_info(surface: &NurbsSurface) -> Result<SurfaceInfo<'_>, String> {
90 let ku = KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
91 let kv = KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
92 let [u0, u1] = ku.domain();
93 let [v0, v1] = kv.domain();
94 let mut closed_u = true;
95 let mut closed_v = true;
96 for fraction in [0.17, 0.5, 0.83] {
97 let v = v0 + (v1 - v0) * fraction;
98 if surface
99 .evaluate(u0, v)?
100 .sub(surface.evaluate(u1, v)?)
101 .length()
102 > LINEAR_TOLERANCE * 10.0
103 {
104 closed_u = false;
105 }
106 let u = u0 + (u1 - u0) * fraction;
107 if surface
108 .evaluate(u, v0)?
109 .sub(surface.evaluate(u, v1)?)
110 .length()
111 > LINEAR_TOLERANCE * 10.0
112 {
113 closed_v = false;
114 }
115 }
116 Ok(SurfaceInfo {
117 surface,
118 u0,
119 u1,
120 v0,
121 v1,
122 closed_u,
123 closed_v,
124 })
125}
126
127fn fit(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
128 crate::projection::fit_parameter(value, minimum, maximum, closed)
129}
130
131
132#[derive(Clone, Copy)]
133struct IntersectionPoint {
134 ua: f64,
135 va: f64,
136 ub: f64,
137 vb: f64,
138 point: Vec3,
139}
140
141fn refine_point(
142 first: SurfaceInfo<'_>,
143 second: SurfaceInfo<'_>,
144 mut ua: f64,
145 mut va: f64,
146 mut ub: f64,
147 mut vb: f64,
148 tolerance: f64,
149) -> Result<Option<IntersectionPoint>, String> {
150 for _ in 0..40 {
151 let da = first.surface.derivatives(ua, va, 1)?;
152 let db = second.surface.derivatives(ub, vb, 1)?;
153 let residual = da[0][0].sub(db[0][0]);
154 if residual.length() <= tolerance * 0.01 + EPSILON {
155 return Ok(Some(IntersectionPoint {
156 ua,
157 va,
158 ub,
159 vb,
160 point: da[0][0].add(db[0][0]).scale(0.5),
161 }));
162 }
163 let columns = [
164 da[1][0],
165 da[0][1],
166 db[1][0].scale(-1.0),
167 db[0][1].scale(-1.0),
168 ];
169 let mut matrix = [[0.0f64; 3]; 3];
170 for column in columns {
171 let values = [column.x, column.y, column.z];
172 for row in 0..3 {
173 for col in 0..3 {
174 matrix[row][col] += values[row] * values[col];
175 }
176 }
177 }
178 let lambda = match solve_small(matrix, [-residual.x, -residual.y, -residual.z], 3) {
179 Ok(value) => value,
180 Err(_) => return Ok(None),
181 };
182 let multiplier = Vec3::new(lambda[0], lambda[1], lambda[2]);
183 let mut changes = columns.map(|column| column.dot(multiplier));
184 let domains = [
185 first.u1 - first.u0,
186 first.v1 - first.v0,
187 second.u1 - second.u0,
188 second.v1 - second.v0,
189 ];
190 for index in 0..4 {
191 changes[index] = changes[index].clamp(-domains[index] / 4.0, domains[index] / 4.0);
192 }
193 ua = fit(ua + changes[0], first.u0, first.u1, first.closed_u);
194 va = fit(va + changes[1], first.v0, first.v1, first.closed_v);
195 ub = fit(ub + changes[2], second.u0, second.u1, second.closed_u);
196 vb = fit(vb + changes[3], second.v0, second.v1, second.closed_v);
197 }
198 let a = first.surface.evaluate(ua, va)?;
199 let b = second.surface.evaluate(ub, vb)?;
200 if a.sub(b).length() <= tolerance {
201 Ok(Some(IntersectionPoint {
202 ua,
203 va,
204 ub,
205 vb,
206 point: a.add(b).scale(0.5),
207 }))
208 } else {
209 Ok(None)
210 }
211}
212
213fn find_start_points(
214 first: SurfaceInfo<'_>,
215 second: SurfaceInfo<'_>,
216 tolerance: f64,
217 density: f64,
218) -> Result<Vec<IntersectionPoint>, String> {
219 let grid_count = |info: SurfaceInfo<'_>, direction_u: bool| {
220 let (knots, degree) = if direction_u {
221 (&info.surface.knots_u, info.surface.degree_u)
222 } else {
223 (&info.surface.knots_v, info.surface.degree_v)
224 };
225 (8.0_f64)
226 .max(((interior_knot_count(knots, degree) + 1) * (degree + 1)) as f64 * density)
227 .ceil()
228 .min(24.0) as usize
229 };
230 let nu = grid_count(first, true);
231 let nv = grid_count(first, false);
232 let first_box = Bounds::from_surface_controls(first.surface)?;
233 let second_box = Bounds::from_surface_controls(second.surface)?;
234 let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
235 let expanded_second = second_box.expanded((tolerance * 100.0).max(gate));
236 let mut starts = Vec::new();
237 for i in 0..=nu {
238 for j in 0..=nv {
239 let ua = first.u0 + (first.u1 - first.u0) * i as f64 / nu as f64;
240 let va = first.v0 + (first.v1 - first.v0) * j as f64 / nv as f64;
241 let point = first.surface.evaluate(ua, va)?;
242 if !expanded_second.contains(point) {
243 continue;
244 }
245 let projection = project_point_to_surface(second.surface, point)?;
246 if projection.distance > gate {
247 continue;
248 }
249 if let Some(refined) =
250 refine_point(first, second, ua, va, projection.u, projection.v, tolerance)?
251 {
252 starts.push(refined);
253 }
254 }
255 }
256 Ok(starts)
257}
258
259struct SpanLeaf {
262 bounds: Bounds,
263 centre: [f64; 2],
264}
265
266pub fn separation_prefilter_enabled() -> bool {
273 crate::switch!(live "BREP_SSI_SEPARATION_PREFILTER", true)
274}
275
276struct SpanHull {
280 bounds: Bounds,
281 points: Vec<Vec3>,
282 normal: Option<Vec3>,
283 range: [f64; 4],
285 net: Vec<Vec4>,
288 degrees: (usize, usize),
289}
290
291fn hull_of_net(net: Vec<Vec4>, (p, q): (usize, usize), range: [f64; 4]) -> Option<SpanHull> {
294 let mut points = Vec::with_capacity(net.len());
295 let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
296 let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
297 for control in &net {
298 if !(control.w > 0.0) || !control.w.is_finite() {
299 return None;
300 }
301 let point = control.point().ok()?;
302 if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite()) {
305 return None;
306 }
307 minimum = Vec3::new(minimum.x.min(point.x), minimum.y.min(point.y), minimum.z.min(point.z));
308 maximum = Vec3::new(maximum.x.max(point.x), maximum.y.max(point.y), maximum.z.max(point.z));
309 points.push(point);
310 }
311 let at = |r: usize, c: usize| points[r * (q + 1) + c];
312 let du = at(p, 0).add(at(p, q)).sub(at(0, 0)).sub(at(0, q));
313 let dv = at(0, q).add(at(p, q)).sub(at(0, 0)).sub(at(p, 0));
314 let normal = du.cross(dv).normalized().ok();
315 Some(SpanHull { bounds: Bounds { minimum, maximum }, points, normal, range, net, degrees: (p, q) })
316}
317
318fn quartered(hull: &SpanHull) -> Option<[SpanHull; 4]> {
323 let (p, q) = hull.degrees;
324 let split = |row: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
326 let mut work = row.to_vec();
327 let n = work.len() - 1;
328 let mut left = Vec::with_capacity(n + 1);
329 let mut right = vec![work[n]; n + 1];
330 left.push(work[0]);
331 right[n] = work[n];
332 for level in 1..=n {
333 for k in 0..=n - level {
334 work[k] = work[k].scale(0.5).add(work[k + 1].scale(0.5));
336 }
337 left.push(work[0]);
338 right[n - level] = work[n - level];
339 }
340 (left, right)
341 };
342 let mut low_u = vec![Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; (p + 1) * (q + 1)];
344 let mut high_u = low_u.clone();
345 for c in 0..=q {
346 let column: Vec<Vec4> = (0..=p).map(|r| hull.net[r * (q + 1) + c]).collect();
347 let (left, right) = split(&column);
348 for r in 0..=p {
349 low_u[r * (q + 1) + c] = left[r];
350 high_u[r * (q + 1) + c] = right[r];
351 }
352 }
353 let halves_v = |net: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
355 let (mut low, mut high) = (Vec::with_capacity(net.len()), Vec::with_capacity(net.len()));
356 for r in 0..=p {
357 let (left, right) = split(&net[r * (q + 1)..(r + 1) * (q + 1)]);
358 low.extend(left);
359 high.extend(right);
360 }
361 (low, high)
362 };
363 let [u0, u1, v0, v1] = hull.range;
364 let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
365 let (a, b) = halves_v(&low_u);
366 let (c, d) = halves_v(&high_u);
367 Some([
368 hull_of_net(a, (p, q), [u0, um, v0, vm])?,
369 hull_of_net(b, (p, q), [u0, um, vm, v1])?,
370 hull_of_net(c, (p, q), [um, u1, v0, vm])?,
371 hull_of_net(d, (p, q), [um, u1, vm, v1])?,
372 ])
373}
374
375pub fn separation_local_refine_enabled() -> bool {
382 crate::switch!(live "BREP_SSI_SEPARATION_LOCAL_REFINE", true)
383}
384
385fn span_hulls(surface: &NurbsSurface) -> Option<Vec<SpanHull>> {
388 let (p, q) = (surface.degree_u, surface.degree_v);
389 let rows = surface.control_points.len();
390 let columns = surface.control_points.first().map_or(0, Vec::len);
391 if rows == 0
393 || columns == 0
394 || surface.control_points.iter().any(|row| row.len() != columns)
395 || surface.knots_u.len() != rows + p + 1
396 || surface.knots_v.len() != columns + q + 1
397 {
398 return None;
399 }
400 if surface.control_points.iter().flatten().any(|control| !(control.w > 0.0) || !control.w.is_finite()) {
401 return None;
402 }
403 let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
404 (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
405 };
406 let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
407 let mut hulls = Vec::with_capacity(spans_u.len() * spans_v.len());
408 for &i in &spans_u {
409 for &j in &spans_v {
410 let net: Vec<Vec4> = surface.control_points[i - p..=i].iter().flat_map(|row| row[j - q..=j].iter().copied()).collect();
411 let range = [surface.knots_u[i], surface.knots_u[i + 1], surface.knots_v[j], surface.knots_v[j + 1]];
412 hulls.push(hull_of_net(net, (p, q), range)?);
413 }
414 }
415 (!hulls.is_empty()).then_some(hulls)
416}
417
418fn readable_net(surface: &NurbsSurface) -> bool {
421 let (p, q) = (surface.degree_u, surface.degree_v);
422 let rows = surface.control_points.len();
423 let columns = surface.control_points.first().map_or(0, Vec::len);
424 let knots_fit = |knots: &[f64], degree: usize, count: usize| {
425 knots.len() == count + degree + 1
426 && knots.iter().all(|knot| knot.is_finite())
427 && knots.windows(2).all(|pair| pair[0] <= pair[1])
428 && knots[0] < knots[knots.len() - 1]
429 };
430 rows > 0
431 && columns > 0
432 && surface.control_points.iter().all(|row| row.len() == columns)
433 && knots_fit(&surface.knots_u, p, rows)
434 && knots_fit(&surface.knots_v, q, columns)
435}
436
437fn bezier_form(surface: &NurbsSurface) -> Option<NurbsSurface> {
442 if !readable_net(surface) {
443 return None;
444 }
445 let raise = |knots: &[f64], degree: usize| -> Vec<f64> {
446 let (first, last) = (knots[0], knots[knots.len() - 1]);
447 let mut inserted = Vec::new();
448 let mut index = 0;
449 while index < knots.len() {
450 let knot = knots[index];
451 let count = knots[index..].iter().take_while(|&&other| other == knot).count();
452 if knot > first && knot < last && count < degree {
453 inserted.extend(std::iter::repeat(knot).take(degree - count));
454 }
455 index += count;
456 }
457 inserted
458 };
459 let in_u = raise(&surface.knots_u, surface.degree_u);
460 let refined = if in_u.is_empty() { surface.clone() } else { surface.refine_knots(crate::KnotDirection::U, &in_u).ok()? };
461 let in_v = raise(&refined.knots_v, refined.degree_v);
462 if in_v.is_empty() { Some(refined) } else { refined.refine_knots(crate::KnotDirection::V, &in_v).ok() }
463}
464
465fn halved_spans(surface: &NurbsSurface) -> Option<NurbsSurface> {
469 let middles = |knots: &[f64], degree: usize| -> Vec<f64> {
470 knots
471 .windows(2)
472 .filter(|pair| pair[0] < pair[1])
473 .flat_map(|pair| std::iter::repeat(0.5 * (pair[0] + pair[1])).take(degree))
474 .collect()
475 };
476 let refined = surface.refine_knots(crate::KnotDirection::U, &middles(&surface.knots_u, surface.degree_u)).ok()?;
477 refined.refine_knots(crate::KnotDirection::V, &middles(&refined.knots_v, refined.degree_v)).ok()
478}
479
480pub fn carriers_proved_apart(first: &NurbsSurface, second: &NurbsSurface, margin: f64) -> bool {
495 match (SpanHullSet::of(first), SpanHullSet::of(second)) {
496 (Some(a), Some(b)) => hull_sets_proved_apart(&a, &b, margin),
497 _ => false,
498 }
499}
500
501pub struct SpanHullSet {
504 surface: NurbsSurface,
505 hulls: Vec<SpanHull>,
506}
507
508impl SpanHullSet {
509 pub fn of(surface: &NurbsSurface) -> Option<Self> {
512 let surface = bezier_form(surface)?;
513 let hulls = span_hulls(&surface)?;
514 Some(Self { surface, hulls })
515 }
516}
517
518pub fn hull_sets_proved_apart(first: &SpanHullSet, second: &SpanHullSet, margin: f64) -> bool {
520 const PAIR_CAP: usize = 250_000;
521 const REFINE_CAP: usize = 64;
525 const LEVELS: usize = 3;
526 if first.hulls.len().saturating_mul(second.hulls.len()) > PAIR_CAP {
527 return false;
528 }
529 let (a, b) = (&first.hulls, &second.hulls);
530 let interval = |points: &[Vec3], normal: Vec3| {
531 points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
532 let value = point.dot(normal);
533 (low.min(value), high.max(value))
534 })
535 };
536 let centroid = |points: &[Vec3]| points.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, p| sum.add(*p)).scale(1.0 / points.len() as f64);
537 let apart = |hull_a: &SpanHull, hull_b: &SpanHull| {
538 if !hull_a.bounds.intersects(hull_b.bounds, margin) {
539 return true;
540 }
541 let between = centroid(&hull_b.points).sub(centroid(&hull_a.points)).normalized().ok();
543 [hull_a.normal, hull_b.normal, between].into_iter().flatten().any(|normal| {
544 let (low_a, high_a) = interval(&hull_a.points, normal);
545 let (low_b, high_b) = interval(&hull_b.points, normal);
546 low_a > high_b + margin || low_b > high_a + margin
547 })
548 };
549 let mut unproved: Vec<(usize, usize)> = Vec::new();
550 for (ia, hull_a) in a.iter().enumerate() {
551 for (ib, hull_b) in b.iter().enumerate() {
552 if !apart(hull_a, hull_b) {
553 unproved.push((ia, ib));
554 if unproved.len() > REFINE_CAP {
555 return false;
556 }
557 }
558 }
559 }
560 if separation_local_refine_enabled() {
561 let mut level_a: Vec<SpanHull> = Vec::new();
564 let mut level_b: Vec<SpanHull> = Vec::new();
565 let mut first_level = true;
566 for _ in 0..LEVELS {
567 if unproved.is_empty() {
568 break;
569 }
570 let (parents_a, parents_b): (&[SpanHull], &[SpanHull]) =
571 if first_level { (a, b) } else { (&level_a, &level_b) };
572 let mut quarters_a: HashMap<usize, usize> = HashMap::new();
573 let mut quarters_b: HashMap<usize, usize> = HashMap::new();
574 let (mut next_a, mut next_b): (Vec<SpanHull>, Vec<SpanHull>) = (Vec::new(), Vec::new());
575 let mut next: Vec<(usize, usize)> = Vec::new();
576 for &(ia, ib) in &unproved {
577 let start_a = match quarters_a.get(&ia) {
578 Some(&start) => start,
579 None => {
580 let Some(children) = quartered(&parents_a[ia]) else { return false };
581 let start = next_a.len();
582 next_a.extend(children);
583 quarters_a.insert(ia, start);
584 start
585 }
586 };
587 let start_b = match quarters_b.get(&ib) {
588 Some(&start) => start,
589 None => {
590 let Some(children) = quartered(&parents_b[ib]) else { return false };
591 let start = next_b.len();
592 next_b.extend(children);
593 quarters_b.insert(ib, start);
594 start
595 }
596 };
597 for ka in start_a..start_a + 4 {
598 for kb in start_b..start_b + 4 {
599 if !apart(&next_a[ka], &next_b[kb]) {
600 next.push((ka, kb));
601 if next.len() > REFINE_CAP {
602 return false;
603 }
604 }
605 }
606 }
607 }
608 next.sort_unstable();
609 next.dedup();
610 unproved = next;
611 level_a = next_a;
612 level_b = next_b;
613 first_level = false;
614 }
615 if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
616 eprintln!("separation (local): unproved after refinement {}", unproved.len());
617 }
618 return unproved.is_empty();
619 }
620 let within = |child: &[f64; 4], parent: &[f64; 4]| child[0] >= parent[0] && child[1] <= parent[1] && child[2] >= parent[2] && child[3] <= parent[3];
623 let mut levels: Vec<(NurbsSurface, NurbsSurface, Vec<SpanHull>, Vec<SpanHull>)> = Vec::new();
624 for _ in 0..LEVELS {
625 if unproved.is_empty() {
626 break;
627 }
628 let (surface_a, surface_b, parents_a, parents_b) = match levels.last() {
629 Some((sa, sb, ha, hb)) => (sa, sb, ha.as_slice(), hb.as_slice()),
630 None => (&first.surface, &second.surface, a.as_slice(), b.as_slice()),
631 };
632 let (Some(next_a), Some(next_b)) = (halved_spans(surface_a), halved_spans(surface_b)) else { return false };
633 let (Some(hulls_a), Some(hulls_b)) = (span_hulls(&next_a), span_hulls(&next_b)) else { return false };
634 let mut next: Vec<(usize, usize)> = Vec::new();
635 for &(ia, ib) in &unproved {
636 let children_a: Vec<usize> = (0..hulls_a.len()).filter(|&k| within(&hulls_a[k].range, &parents_a[ia].range)).collect();
637 let children_b: Vec<usize> = (0..hulls_b.len()).filter(|&k| within(&hulls_b[k].range, &parents_b[ib].range)).collect();
638 for &ka in &children_a {
639 for &kb in &children_b {
640 if !apart(&hulls_a[ka], &hulls_b[kb]) {
641 next.push((ka, kb));
642 if next.len() > REFINE_CAP {
643 return false;
644 }
645 }
646 }
647 }
648 }
649 next.sort_unstable();
650 next.dedup();
651 unproved = next;
652 levels.push((next_a, next_b, hulls_a, hulls_b));
653 }
654 if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
655 let (a, b) = match levels.last() {
656 Some((_, _, ha, hb)) => (ha.as_slice(), hb.as_slice()),
657 None => (a.as_slice(), b.as_slice()),
658 };
659 eprintln!("separation: spans {}x{} unproved after refinement {}", a.len(), b.len(), unproved.len());
660 }
661 unproved.is_empty()
662}
663
664fn span_leaves(info: SurfaceInfo<'_>) -> Result<Vec<SpanLeaf>, String> {
665 let surface = info.surface;
666 let (p, q) = (surface.degree_u, surface.degree_v);
667 let rows = surface.control_points.len();
668 let columns = surface.control_points.first().map_or(0, Vec::len);
669 let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
670 (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
671 };
672 let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
673 if spans_u.is_empty() || spans_v.is_empty() {
674 return Ok(vec![SpanLeaf {
675 bounds: Bounds::from_surface_controls(surface)?,
676 centre: [0.5 * (info.u0 + info.u1), 0.5 * (info.v0 + info.v1)],
677 }]);
678 }
679 let mut leaves = Vec::with_capacity(spans_u.len() * spans_v.len());
680 for &i in &spans_u {
681 for &j in &spans_v {
682 let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
683 let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
684 for row in &surface.control_points[i - p..=i] {
685 for control in &row[j - q..=j] {
686 let point = control.point()?;
687 minimum.x = minimum.x.min(point.x);
688 minimum.y = minimum.y.min(point.y);
689 minimum.z = minimum.z.min(point.z);
690 maximum.x = maximum.x.max(point.x);
691 maximum.y = maximum.y.max(point.y);
692 maximum.z = maximum.z.max(point.z);
693 }
694 }
695 leaves.push(SpanLeaf {
696 bounds: Bounds { minimum, maximum },
697 centre: [
698 0.5 * (surface.knots_u[i] + surface.knots_u[i + 1]),
699 0.5 * (surface.knots_v[j] + surface.knots_v[j + 1]),
700 ],
701 });
702 }
703 }
704 Ok(leaves)
705}
706
707const TREE_SEED_PAIR_CAP: usize = 4096;
712
713fn tree_start_points(
720 first: SurfaceInfo<'_>,
721 second: SurfaceInfo<'_>,
722 tolerance: f64,
723) -> Result<Option<(Vec<IntersectionPoint>, usize)>, String> {
724 let first_box = Bounds::from_surface_controls(first.surface)?;
725 let second_box = Bounds::from_surface_controls(second.surface)?;
726 let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
727 let grow = (tolerance * 100.0).max(gate);
728 let leaves_a = span_leaves(first)?;
729 let leaves_b = span_leaves(second)?;
730 let mut pairs = Vec::new();
731 for (ia, leaf_a) in leaves_a.iter().enumerate() {
732 for (ib, leaf_b) in leaves_b.iter().enumerate() {
733 if leaf_a.bounds.intersects(leaf_b.bounds, grow) {
734 pairs.push((ia, ib));
735 if pairs.len() > TREE_SEED_PAIR_CAP {
736 return Ok(None);
737 }
738 }
739 }
740 }
741 let mut starts = Vec::new();
742 for (ia, ib) in &pairs {
743 let (leaf_a, leaf_b) = (&leaves_a[*ia], &leaves_b[*ib]);
744 let reach = gate.max(leaf_a.bounds.diagonal().max(leaf_b.bounds.diagonal()));
750 for (from, onto, from_info, onto_info, from_first) in [
753 (leaf_a, leaf_b, first, second, true),
754 (leaf_b, leaf_a, second, first, false),
755 ] {
756 let point = from_info.surface.evaluate(from.centre[0], from.centre[1])?;
757 let projection = project_point_to_surface_from_seed(onto_info.surface, point, onto.centre)?;
758 if projection.distance > reach {
759 continue;
760 }
761 let refined = if from_first {
762 refine_point(first, second, from.centre[0], from.centre[1], projection.u, projection.v, tolerance)?
763 } else {
764 refine_point(first, second, projection.u, projection.v, from.centre[0], from.centre[1], tolerance)?
765 };
766 if let Some(refined) = refined {
767 starts.push(refined);
768 }
769 }
770 }
771 Ok(Some((starts, pairs.len())))
772}
773
774fn transverse_at(
778 first: SurfaceInfo<'_>,
779 second: SurfaceInfo<'_>,
780 point: IntersectionPoint,
781) -> bool {
782 crossing_at(first, second, point) >= TRANSVERSE_START_CROSS
783}
784
785fn crossing_at(
787 first: SurfaceInfo<'_>,
788 second: SurfaceInfo<'_>,
789 point: IntersectionPoint,
790) -> f64 {
791 match (
792 first.surface.normal(point.ua, point.va),
793 second.surface.normal(point.ub, point.vb),
794 ) {
795 (Ok(a), Ok(b)) => a.cross(b).length(),
796 _ => 0.0,
797 }
798}
799
800fn tangent_at(
801 first: SurfaceInfo<'_>,
802 second: SurfaceInfo<'_>,
803 point: IntersectionPoint,
804) -> Result<Option<Vec3>, String> {
805 let first_normal = first.surface.normal(point.ua, point.va).ok();
806 let second_normal = second.surface.normal(point.ub, point.vb).ok();
807 match (first_normal, second_normal) {
808 (Some(a), Some(b)) => {
809 let tangent = a.cross(b);
810 if tangent.length() <= 1e-9 {
811 Ok(None)
812 } else {
813 Ok(Some(tangent.normalized()?))
814 }
815 }
816 _ => Ok(None),
817 }
818}
819
820fn polish_boundary(
821 first: SurfaceInfo<'_>,
822 second: SurfaceInfo<'_>,
823 mut point: IntersectionPoint,
824 tolerance: f64,
825) -> Result<Option<IntersectionPoint>, String> {
826 let free = [
827 first.closed_u || (point.ua > first.u0 && point.ua < first.u1),
828 first.closed_v || (point.va > first.v0 && point.va < first.v1),
829 second.closed_u || (point.ub > second.u0 && point.ub < second.u1),
830 second.closed_v || (point.vb > second.v0 && point.vb < second.v1),
831 ];
832 for _ in 0..40 {
833 let da = first.surface.derivatives(point.ua, point.va, 1)?;
834 let db = second.surface.derivatives(point.ub, point.vb, 1)?;
835 let residual = da[0][0].sub(db[0][0]);
836 if residual.length() <= tolerance {
837 point.point = da[0][0].add(db[0][0]).scale(0.5);
838 return Ok(Some(point));
839 }
840 let all_columns = [
841 da[1][0],
842 da[0][1],
843 db[1][0].scale(-1.0),
844 db[0][1].scale(-1.0),
845 ];
846 let indices: Vec<usize> = (0..4).filter(|index| free[*index]).collect();
847 if indices.is_empty() {
848 return Ok(None);
849 }
850 let mut matrix = [[0.0f64; 4]; 4];
851 let mut rhs = [0.0f64; 4];
852 for (row, &r) in indices.iter().enumerate() {
853 rhs[row] = -all_columns[r].dot(residual);
854 for (column, &c) in indices.iter().enumerate() {
855 matrix[row][column] = all_columns[r].dot(all_columns[c]);
856 }
857 }
858 let changes = match solve_small(matrix, rhs, indices.len()) {
859 Ok(value) => value,
860 Err(_) => return Ok(None),
861 };
862 let mut update = [0.0; 4];
863 for (index, ¶meter_index) in indices.iter().enumerate() {
864 update[parameter_index] = changes[index];
865 }
866 point.ua = fit(point.ua + update[0], first.u0, first.u1, first.closed_u);
867 point.va = fit(point.va + update[1], first.v0, first.v1, first.closed_v);
868 point.ub = fit(point.ub + update[2], second.u0, second.u1, second.closed_u);
869 point.vb = fit(point.vb + update[3], second.v0, second.v1, second.closed_v);
870 }
871 Ok(None)
872}
873
874fn correct(
875 first: SurfaceInfo<'_>,
876 second: SurfaceInfo<'_>,
877 from: IntersectionPoint,
878 predicted: Vec3,
879 tangent: Vec3,
880 tolerance: f64,
881) -> Result<Option<(IntersectionPoint, bool)>, String> {
882 let mut point = from;
883 let mut boundary = false;
884 for _ in 0..30 {
885 let da = first.surface.derivatives(point.ua, point.va, 1)?;
886 let db = second.surface.derivatives(point.ub, point.vb, 1)?;
887 let residual = da[0][0].sub(db[0][0]);
888 let plane_residual = da[0][0].sub(predicted).dot(tangent);
889 if residual.length() <= tolerance * 0.01 + EPSILON
890 && plane_residual.abs() <= tolerance * 0.01 + EPSILON
891 {
892 point.point = da[0][0].add(db[0][0]).scale(0.5);
893 return Ok(Some((point, boundary)));
894 }
895 let matrix = [
896 [da[1][0].x, da[0][1].x, -db[1][0].x, -db[0][1].x],
897 [da[1][0].y, da[0][1].y, -db[1][0].y, -db[0][1].y],
898 [da[1][0].z, da[0][1].z, -db[1][0].z, -db[0][1].z],
899 [da[1][0].dot(tangent), da[0][1].dot(tangent), 0.0, 0.0],
900 ];
901 let changes = match solve_small(
902 matrix,
903 [-residual.x, -residual.y, -residual.z, -plane_residual],
904 4,
905 ) {
906 Ok(value) => value,
907 Err(_) => return Ok(None),
908 };
909 let scale = [
910 changes[0].abs() / ((first.u1 - first.u0) / 4.0),
911 changes[1].abs() / ((first.v1 - first.v0) / 4.0),
912 changes[2].abs() / ((second.u1 - second.u0) / 4.0),
913 changes[3].abs() / ((second.v1 - second.v0) / 4.0),
914 1.0,
915 ]
916 .into_iter()
917 .fold(1.0_f64, f64::max);
918 let raw = [
919 point.ua + changes[0] / scale,
920 point.va + changes[1] / scale,
921 point.ub + changes[2] / scale,
922 point.vb + changes[3] / scale,
923 ];
924 let domains = [
925 (first.u0, first.u1, first.closed_u),
926 (first.v0, first.v1, first.closed_v),
927 (second.u0, second.u1, second.closed_u),
928 (second.v0, second.v1, second.closed_v),
929 ];
930 boundary = false;
931 let mut next = [0.0; 4];
932 for index in 0..4 {
933 next[index] = fit(
934 raw[index],
935 domains[index].0,
936 domains[index].1,
937 domains[index].2,
938 );
939 if !domains[index].2
940 && (next[index] == domains[index].0 || next[index] == domains[index].1)
941 && raw[index] != next[index]
942 {
943 boundary = true;
944 }
945 }
946 let old = [point.ua, point.va, point.ub, point.vb];
947 let spans = [
948 first.u1 - first.u0,
949 first.v1 - first.v0,
950 second.u1 - second.u0,
951 second.v1 - second.v0,
952 ];
953 let stalled = (0..4).all(|index| (next[index] - old[index]).abs() <= 1e-14 * spans[index]);
954 point.ua = next[0];
955 point.va = next[1];
956 point.ub = next[2];
957 point.vb = next[3];
958 if stalled {
959 if boundary {
960 if let Some(polished) = polish_boundary(first, second, point, tolerance)? {
961 return Ok(Some((polished, true)));
962 }
963 }
964 return Ok(None);
965 }
966 }
967 Ok(None)
968}
969
970struct Trace {
971 points: Vec<IntersectionPoint>,
972 tangents: Vec<Vec3>,
974 closed: bool,
975 deviation: f64,
977}
978
979struct Spliced {
982 points: Vec<IntersectionPoint>,
983 tangents: Vec<Vec3>,
984 deviation: f64,
985}
986
987impl From<Trace> for Spliced {
988 fn from(trace: Trace) -> Self {
989 Self {
990 points: trace.points,
991 tangents: trace.tangents,
992 deviation: trace.deviation,
993 }
994 }
995}
996
997fn splice(backward: Trace, forward: Trace) -> Spliced {
1000 let mut points: Vec<_> = backward.points.into_iter().skip(1).rev().collect();
1001 let mut tangents: Vec<_> = backward
1002 .tangents
1003 .into_iter()
1004 .skip(1)
1005 .rev()
1006 .map(|tangent| tangent.scale(-1.0))
1007 .collect();
1008 points.extend(forward.points);
1009 tangents.extend(forward.tangents);
1010 Spliced {
1011 points,
1012 tangents,
1013 deviation: backward.deviation.max(forward.deviation),
1014 }
1015}
1016
1017fn curve_from(all: Spliced, closed: bool, measured: bool) -> SurfaceIntersectionCurve {
1020 let complete = all.tangents.len() == all.points.len();
1021 SurfaceIntersectionCurve {
1022 points: all.points.iter().map(|point| point.point).collect(),
1023 params_a: all.points.iter().map(|point| [point.ua, point.va]).collect(),
1024 params_b: all.points.iter().map(|point| [point.ub, point.vb]).collect(),
1025 closed,
1026 tangents: (complete && (measured || (crate::carried_uv::carried_uv_enabled() && all.points.len() >= crate::carried_uv::carried_uv_min_stations()))).then_some(all.tangents),
1027 span_deviation: (complete && measured).then_some(all.deviation),
1028 tangent: false,
1029 }
1030}
1031
1032fn hermite_at(p0: Vec3, d0: Vec3, p1: Vec3, d1: Vec3, s: f64) -> Vec3 {
1035 let s2 = s * s;
1036 let s3 = s2 * s;
1037 p0.scale(2.0 * s3 - 3.0 * s2 + 1.0)
1038 .add(d0.scale(s3 - 2.0 * s2 + s))
1039 .add(p1.scale(-2.0 * s3 + 3.0 * s2))
1040 .add(d1.scale(s3 - s2))
1041}
1042
1043struct ParameterHermite {
1049 p0: [f64; 2],
1050 d0: [f64; 2],
1051 p1: [f64; 2],
1052 d1: [f64; 2],
1053}
1054
1055impl ParameterHermite {
1056 fn new(
1057 info: SurfaceInfo<'_>,
1058 p0: [f64; 2],
1059 t0: Vec3,
1060 p1: [f64; 2],
1061 t1: Vec3,
1062 chord: f64,
1063 ) -> Result<Self, String> {
1064 let image = |uv: [f64; 2], tangent: Vec3| -> Result<[f64; 2], String> {
1065 let d = info.surface.derivatives(uv[0], uv[1], 1)?;
1066 let (su, sv) = (d[1][0], d[0][1]);
1067 let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
1068 let (bu, bv) = (su.dot(tangent), sv.dot(tangent));
1069 let det = e * g - f * f;
1070 if det.abs() <= EPSILON * (1.0 + e * g) {
1071 return Ok([0.0, 0.0]);
1072 }
1073 Ok([
1074 (g * bu - f * bv) / det * chord,
1075 (e * bv - f * bu) / det * chord,
1076 ])
1077 };
1078 let mut p1 = p1;
1079 let unwrap = |value: f64, near: f64, closed: bool, minimum: f64, maximum: f64| {
1080 let period = maximum - minimum;
1081 if closed && period > 0.0 && (value - near).abs() > 0.5 * period {
1082 value - period * ((value - near) / period).round()
1083 } else {
1084 value
1085 }
1086 };
1087 p1[0] = unwrap(p1[0], p0[0], info.closed_u, info.u0, info.u1);
1088 p1[1] = unwrap(p1[1], p0[1], info.closed_v, info.v0, info.v1);
1089 Ok(Self {
1090 p0,
1091 d0: image(p0, t0)?,
1092 p1,
1093 d1: image([fit(p1[0], info.u0, info.u1, info.closed_u), fit(p1[1], info.v0, info.v1, info.closed_v)], t1)?,
1094 })
1095 }
1096
1097 fn at(&self, s: f64) -> [f64; 2] {
1098 let s2 = s * s;
1099 let s3 = s2 * s;
1100 let (h00, h10, h01, h11) = (
1101 2.0 * s3 - 3.0 * s2 + 1.0,
1102 s3 - 2.0 * s2 + s,
1103 -2.0 * s3 + 3.0 * s2,
1104 s3 - s2,
1105 );
1106 [
1107 h00 * self.p0[0] + h10 * self.d0[0] + h01 * self.p1[0] + h11 * self.d1[0],
1108 h00 * self.p0[1] + h10 * self.d0[1] + h01 * self.p1[1] + h11 * self.d1[1],
1109 ]
1110 }
1111}
1112
1113fn span_deviation(
1117 first: SurfaceInfo<'_>,
1118 second: SurfaceInfo<'_>,
1119 from: IntersectionPoint,
1120 from_tangent: Vec3,
1121 to: IntersectionPoint,
1122 to_tangent: Vec3,
1123) -> Result<f64, String> {
1124 let chord = to.point.sub(from.point).length();
1125 if chord <= EPSILON {
1126 return Ok(0.0);
1127 }
1128 let on_a = ParameterHermite::new(first, [from.ua, from.va], from_tangent, [to.ua, to.va], to_tangent, chord)?;
1129 let on_b = ParameterHermite::new(second, [from.ub, from.vb], from_tangent, [to.ub, to.vb], to_tangent, chord)?;
1130 let (d0, d1) = (from_tangent.scale(chord), to_tangent.scale(chord));
1131 let mut worst: f64 = 0.0;
1132 for s in [0.17, 0.33, 0.5, 0.67, 0.83] {
1133 let c = hermite_at(from.point, d0, to.point, d1, s);
1134 let [ua, va] = on_a.at(s);
1135 let a = first.surface.evaluate(fit(ua, first.u0, first.u1, first.closed_u), fit(va, first.v0, first.v1, first.closed_v))?;
1136 let [ub, vb] = on_b.at(s);
1137 let b = second.surface.evaluate(fit(ub, second.u0, second.u1, second.closed_u), fit(vb, second.v0, second.v1, second.closed_v))?;
1138 worst = worst
1139 .max(a.sub(b).length())
1140 .max(a.sub(c).length())
1141 .max(b.sub(c).length());
1142 }
1143 Ok(worst)
1144}
1145
1146fn vector_angle(a: Vec3, b: Vec3) -> f64 {
1147 (a.dot(b) / (a.length() * b.length()))
1148 .clamp(-1.0, 1.0)
1149 .acos()
1150}
1151
1152fn normal_turn_step(
1161 first: SurfaceInfo<'_>,
1162 second: SurfaceInfo<'_>,
1163 point: IntersectionPoint,
1164 tangent: Vec3,
1165 budget: f64,
1166) -> Option<f64> {
1167 let mut best: Option<f64> = None;
1168 for (surface, u, v) in [
1169 (first.surface, point.ua, point.va),
1170 (second.surface, point.ub, point.vb),
1171 ] {
1172 let derivatives = surface.derivatives(u, v, 2).ok()?;
1173 let normal = derivatives[1][0].cross(derivatives[0][1]);
1174 let normal_length = normal.length();
1175 if normal_length <= 1e-12 {
1176 continue;
1177 }
1178 let unit_normal = normal.scale(1.0 / normal_length);
1179 for (first_derivative, second_derivative) in [
1180 (derivatives[1][0], derivatives[2][0]),
1181 (derivatives[0][1], derivatives[0][2]),
1182 ] {
1183 let metric = first_derivative.dot(first_derivative);
1184 if metric <= 1e-16 {
1185 continue;
1186 }
1187 let curvature = second_derivative.dot(unit_normal).abs();
1188 if curvature <= 1e-12 {
1189 continue; }
1191 let advance = budget * metric / curvature;
1192 let alignment = first_derivative
1193 .scale(1.0 / metric.sqrt())
1194 .dot(tangent)
1195 .abs();
1196 if alignment <= 0.1 {
1197 continue; }
1199 let along = advance * alignment;
1200 if best.map(|value| along < value).unwrap_or(true) {
1201 best = Some(along);
1202 }
1203 }
1204 }
1205 best
1206}
1207
1208fn normal_turn_rate_step(
1222 first: SurfaceInfo<'_>,
1223 second: SurfaceInfo<'_>,
1224 point: IntersectionPoint,
1225 tangent: Vec3,
1226 budget: f64,
1227) -> Option<f64> {
1228 let mut best: Option<f64> = None;
1229 for (surface, u, v) in [
1230 (first.surface, point.ua, point.va),
1231 (second.surface, point.ub, point.vb),
1232 ] {
1233 let derivatives = surface.derivatives(u, v, 2).ok()?;
1234 let su = derivatives[1][0];
1235 let sv = derivatives[0][1];
1236 let normal = su.cross(sv);
1237 let length = normal.length();
1238 if length <= 1e-12 {
1239 continue;
1240 }
1241 let unit = normal.scale(1.0 / length);
1242 let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
1243 let determinant = e * g - f * f;
1244 if !(determinant > 1e-24) {
1245 continue;
1246 }
1247 let (tu, tv) = (tangent.dot(su), tangent.dot(sv));
1248 let a = (g * tu - f * tv) / determinant;
1249 let b = (e * tv - f * tu) / determinant;
1250 let (suu, suv, svv) = (derivatives[2][0], derivatives[1][1], derivatives[0][2]);
1251 let raw = suu.cross(sv).add(su.cross(suv)).scale(a).add(suv.cross(sv).add(su.cross(svv)).scale(b));
1252 let turn = raw.sub(unit.scale(unit.dot(raw))).scale(1.0 / length);
1253 let rate = turn.length();
1254 if !rate.is_finite() || rate <= 1e-12 {
1255 continue; }
1257 let along = budget / rate;
1258 if best.map(|value| along < value).unwrap_or(true) {
1259 best = Some(along);
1260 }
1261 }
1262 best
1263}
1264
1265fn ceiling_step(
1268 first: SurfaceInfo<'_>,
1269 second: SurfaceInfo<'_>,
1270 point: IntersectionPoint,
1271 tangent: Vec3,
1272 budget: f64,
1273 switches: TraceSwitches,
1274) -> Option<f64> {
1275 if switches.turn_rate_ceiling {
1276 normal_turn_rate_step(first, second, point, tangent, budget)
1277 } else {
1278 normal_turn_step(first, second, point, tangent, budget)
1279 }
1280}
1281
1282#[derive(Clone, Copy)]
1285struct TraceSwitches {
1286 first_step_ceiling: bool,
1289 oriented_continuation: bool,
1291 debug: bool,
1293 turn_rate_retrace: bool,
1297 turn_rate_ceiling: bool,
1300}
1301
1302impl TraceSwitches {
1303 fn from_env() -> Self {
1304 Self {
1305 first_step_ceiling: std::env::var("BREP_SSI_FIRST_STEP_BUDGET").as_deref() != Ok("0"),
1306 oriented_continuation: crate::switch!(live "BREP_SSI_ORIENTED_CONTINUATION", true),
1307 debug: std::env::var_os("BREP_DEBUG_SSI_TRACE").is_some(),
1308 turn_rate_retrace: crate::switch!(live "BREP_SSI_TURN_RATE_RETRACE", true),
1309 turn_rate_ceiling: false,
1310 }
1311 }
1312}
1313
1314fn chord_in_carrier_bands(
1318 first: SurfaceInfo<'_>, second: SurfaceInfo<'_>,
1319 start: Vec3, end: Vec3, tolerance: f64,
1320) -> Result<bool, String> {
1321 for fraction in [0.25, 0.5, 0.75] {
1322 let point = start.add(end.sub(start).scale(fraction));
1323 for surface in [first.surface, second.surface] {
1324 let foot = project_point_to_surface(surface, point)?;
1325 if !foot.distance.is_finite() || foot.distance > tolerance { return Ok(false); }
1326 }
1327 }
1328 Ok(true)
1329}
1330
1331const TRACE_EXHAUSTED: &str = "surface intersection trace exhausted";
1333
1334#[allow(clippy::too_many_arguments)]
1341fn trace(
1342 first: SurfaceInfo<'_>,
1343 second: SurfaceInfo<'_>,
1344 start: IntersectionPoint,
1345 direction: f64,
1346 tolerance: f64,
1347 initial_step: f64,
1348 minimum_step: f64,
1349 maximum_step: f64,
1350 maximum_steps: usize,
1351 switches: TraceSwitches,
1352 span_budget: Option<f64>,
1353) -> Result<Trace, String> {
1354 let traced = trace_once(
1355 first, second, start, direction, tolerance, initial_step, minimum_step, maximum_step, maximum_steps,
1356 switches, span_budget,
1357 );
1358 match traced {
1359 Err(error) if switches.turn_rate_retrace && !switches.turn_rate_ceiling && error.starts_with(TRACE_EXHAUSTED) => {
1360 let retrace = TraceSwitches { turn_rate_ceiling: true, ..switches };
1361 if switches.debug {
1362 eprintln!("SSI-RETRACE turn-rate ceiling after: {error}");
1363 }
1364 trace_once(
1365 first, second, start, direction, tolerance, initial_step, minimum_step, maximum_step, maximum_steps,
1366 retrace, span_budget,
1367 )
1368 .map_err(|again| {
1369 if again.starts_with(TRACE_EXHAUSTED) {
1370 format!("{error}; retraced under the measured normal-turn ceiling: {again}")
1371 } else {
1372 again
1373 }
1374 })
1375 }
1376 traced => traced,
1377 }
1378}
1379
1380#[allow(clippy::too_many_arguments)]
1381fn trace_once(
1382 first: SurfaceInfo<'_>,
1383 second: SurfaceInfo<'_>,
1384 start: IntersectionPoint,
1385 direction: f64,
1386 tolerance: f64,
1387 initial_step: f64,
1388 minimum_step: f64,
1389 maximum_step: f64,
1390 maximum_steps: usize,
1391 switches: TraceSwitches,
1392 span_budget: Option<f64>,
1393) -> Result<Trace, String> {
1394 let mut points = vec![start];
1395 let mut current = start;
1396 let Some(mut tangent) = tangent_at(first, second, start)? else {
1397 return Ok(Trace {
1398 points,
1399 tangents: Vec::new(),
1400 closed: false,
1401 deviation: 0.0,
1402 });
1403 };
1404 tangent = tangent.scale(direction);
1405 let mut field_direction = direction;
1406 let mut tangents = vec![tangent];
1407 let mut deviation: f64 = 0.0;
1408 let mut step_size = initial_step.min(maximum_step);
1419 if switches.first_step_ceiling {
1420 if let Some(budget) = ceiling_step(first, second, start, tangent, 0.1, switches) {
1421 step_size = step_size.min(budget).clamp(minimum_step, maximum_step);
1422 }
1423 }
1424 let mut terminated = false;
1425 for _ in 0..maximum_steps {
1426 let mut accepted = None;
1427 let mut rejected_continuation = false;
1428 while step_size >= minimum_step {
1429 let predicted = current.point.add(tangent.scale(step_size));
1430 if let Some((corrected, boundary)) =
1431 correct(first, second, current, predicted, tangent, tolerance)?
1432 {
1433 let chord = corrected.point.sub(current.point);
1434 if switches.oriented_continuation && !boundary {
1439 let next = tangent_at(first, second, corrected)?.map(|t| t.scale(field_direction));
1440 let suspect = next.is_some_and(|next| next.dot(tangent) <= 0.0 || chord.dot(next) <= 0.0);
1446 if suspect && !chord_in_carrier_bands(first, second, current.point, corrected.point, tolerance)? {
1447 if switches.debug {
1448 eprintln!("SSI-REJECT boundary={boundary} step={step_size:.8e} field_dot={:?} chord_dot={:?} from={:?} to={:?}",
1449 next.map(|n| n.dot(tangent)), next.map(|n| chord.dot(n)), current.point, corrected.point);
1450 }
1451 rejected_continuation = true;
1452 step_size /= 2.0;
1453 continue;
1454 }
1455 }
1456 if chord.length() <= 2.5 * step_size {
1457 accepted = Some((corrected, boundary));
1458 break;
1459 }
1460 }
1461 step_size /= 2.0;
1462 }
1463 let Some((candidate, boundary)) = accepted else {
1464 if rejected_continuation {
1465 return Err(format!("surface intersection continuation unresolved at minimum step {minimum_step:.3e}"));
1466 }
1467 terminated = true;
1468 break;
1469 };
1470 points.push(candidate);
1471 if switches.debug {
1472 let turn = tangent_at(first, second, candidate)
1476 .ok()
1477 .flatten()
1478 .map(|next| vector_angle(tangent, if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }))
1479 .unwrap_or(f64::NAN);
1480 let budget = ceiling_step(first, second, current, tangent, 0.1, switches).unwrap_or(f64::NAN);
1481 let at = candidate.point;
1482 eprintln!(
1483 "SSI-TRACE dir {direction} step {step_size:.4e} jump {:.4e} turn {turn:.4} ceiling {budget:.4e} boundary {boundary} p ({:.6},{:.6},{:.6})",
1484 at.sub(current.point).length(),
1485 at.x,
1486 at.y,
1487 at.z
1488 );
1489 }
1490 let raw_next = tangent_at(first, second, candidate)?;
1494 let next = raw_next.map(|next| {
1495 if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }
1496 });
1497 if boundary {
1498 tangents.push(next.unwrap_or(tangent));
1499 terminated = true;
1500 break;
1501 }
1502 let Some(next_tangent) = next else {
1503 tangents.push(tangent);
1504 terminated = true;
1505 break;
1506 };
1507 let angle = vector_angle(tangent, next_tangent);
1508 if angle > 0.35 {
1509 points.pop();
1510 step_size = minimum_step.max(step_size / 2.0);
1511 if step_size <= minimum_step * 1.01 {
1512 points.push(candidate);
1513 } else {
1514 continue;
1515 }
1516 }
1517 let mut span_fine = true;
1522 if let Some(budget) = span_budget {
1523 let measured = span_deviation(first, second, current, tangent, candidate, next_tangent)?;
1524 if measured > budget && step_size > minimum_step * 1.01 {
1525 points.pop();
1526 step_size = minimum_step.max(step_size / 2.0);
1527 continue;
1528 }
1529 deviation = deviation.max(measured);
1530 span_fine = measured < budget / 8.0;
1531 }
1532 tangents.push(next_tangent);
1533 if let Some(raw) = raw_next {
1534 field_direction = if raw.dot(next_tangent) < 0.0 { -1.0 } else { 1.0 };
1535 }
1536 let reactive = if angle < 0.03 && span_fine {
1541 step_size * 1.5
1542 } else if angle > 0.15 {
1543 step_size * 0.6
1544 } else {
1545 step_size
1546 };
1547 step_size = match ceiling_step(first, second, candidate, next_tangent, 0.1, switches) {
1548 Some(budget) => reactive.min(budget),
1549 None => reactive,
1550 }
1551 .clamp(minimum_step, maximum_step);
1552 if points.len() > 4 && candidate.point.sub(start.point).length() <= step_size * 1.2 {
1553 let to_start = start.point.sub(candidate.point);
1554 let follows_start = next_tangent.dot(tangents[0]) > 0.0
1557 && (to_start.length() <= tolerance || to_start.dot(tangents[0]) > 0.0);
1558 if (to_start.length() <= EPSILON || to_start.dot(next_tangent) >= 0.0)
1559 && (!switches.oriented_continuation || follows_start
1560 || chord_in_carrier_bands(first, second, candidate.point, start.point, tolerance)?)
1561 {
1562 points.push(start);
1563 tangents.push(tangents[0]);
1564 return Ok(Trace {
1565 points,
1566 tangents,
1567 closed: true,
1568 deviation,
1569 });
1570 }
1571 }
1572 current = candidate;
1573 tangent = next_tangent;
1574 }
1575 if !terminated {
1576 return Err(format!(
1580 "surface intersection trace exhausted {maximum_steps} steps \
1581 ({} points, step {step_size:.3e}) without reaching a boundary or closure",
1582 points.len()
1583 ));
1584 }
1585 Ok(Trace {
1586 points,
1587 tangents,
1588 closed: false,
1589 deviation,
1590 })
1591}
1592
1593fn point_segment_distance(point: Vec3, start: Vec3, end: Vec3) -> f64 {
1594 point.distance_to_segment(start, end, EPSILON)
1595}
1596
1597#[derive(Clone, Debug, Serialize)]
1598pub struct SurfaceIntersectionCurve {
1599 pub points: Vec<Vec3>,
1600 pub params_a: Vec<[f64; 2]>,
1601 pub params_b: Vec<[f64; 2]>,
1602 pub closed: bool,
1603 #[serde(skip_serializing_if = "Option::is_none")]
1607 pub tangents: Option<Vec<Vec3>>,
1608 #[serde(skip_serializing_if = "Option::is_none")]
1611 pub span_deviation: Option<f64>,
1612 #[serde(skip_serializing_if = "std::ops::Not::not")]
1617 pub tangent: bool,
1618}
1619
1620#[derive(Clone, Debug, Deserialize)]
1621pub struct SurfaceIntersectionOptions {
1622 #[serde(default = "default_tolerance")]
1623 pub tolerance: f64,
1624 #[serde(default = "default_density")]
1625 pub seed_density: f64,
1626 #[serde(default = "default_maximum_steps")]
1627 pub maximum_steps: usize,
1628 pub maximum_step: Option<f64>,
1629 #[serde(default)]
1630 pub seed_points: Vec<Vec3>,
1631 #[serde(default)]
1632 pub seed_only: bool,
1633 pub seed_gate: Option<f64>,
1634 #[serde(default)]
1651 pub span_budget: Option<f64>,
1652 #[serde(default)]
1654 pub ordered_starts: bool,
1655 #[serde(default)]
1661 pub consume_starts: bool,
1662 #[serde(default)]
1664 pub tree_seeds: bool,
1665 #[serde(default)]
1681 pub seed_start_cross: Option<f64>,
1682}
1683
1684fn default_tolerance() -> f64 {
1685 LINEAR_TOLERANCE
1686}
1687fn default_density() -> f64 {
1688 1.0
1689}
1690fn default_maximum_steps() -> usize {
1691 4000
1692}
1693
1694impl Default for SurfaceIntersectionOptions {
1695 fn default() -> Self {
1696 Self {
1697 tolerance: default_tolerance(),
1698 seed_density: default_density(),
1699 maximum_steps: default_maximum_steps(),
1700 maximum_step: None,
1701 seed_points: Vec::new(),
1702 seed_only: false,
1703 seed_gate: None,
1704 span_budget: None,
1705 ordered_starts: false,
1706 consume_starts: false,
1707 tree_seeds: false,
1708 seed_start_cross: None,
1709 }
1710 }
1711}
1712
1713#[derive(Clone, Copy, Debug)]
1716pub struct EmissionSample {
1717 pub point: Vec3,
1718 pub uv_a: [f64; 2],
1719 pub uv_b: [f64; 2],
1720 pub tangent: Vec3,
1721}
1722
1723pub fn refine_emission_samples(
1727 first_surface: &NurbsSurface,
1728 second_surface: &NurbsSurface,
1729 samples: &[EmissionSample],
1730 budget: f64,
1731) -> Result<Option<Vec<EmissionSample>>, String> {
1732 if samples.len() < 2 || !(budget > 0.0 && budget.is_finite()) { return Ok(None); }
1733 let first = surface_info(first_surface)?;
1734 let second = surface_info(second_surface)?;
1735 let point = |s: EmissionSample| IntersectionPoint {
1736 point: s.point, ua: s.uv_a[0], va: s.uv_a[1], ub: s.uv_b[0], vb: s.uv_b[1],
1737 };
1738 for s in samples {
1741 if !(first_surface.evaluate(s.uv_a[0], s.uv_a[1])?.sub(s.point).length() <= budget)
1742 || !(second_surface.evaluate(s.uv_b[0], s.uv_b[1])?.sub(s.point).length() <= budget)
1743 { return Ok(None); }
1744 }
1745 let mut pending: Vec<_> = samples.windows(2).rev().map(|p| (p[0], p[1], 0usize)).collect();
1746 let mut out = vec![samples[0]];
1747 let mut inserted = 0;
1748 while let Some((a, b, depth)) = pending.pop() {
1749 let pa = point(a);
1750 let pb = point(b);
1751 if span_deviation(first, second, pa, a.tangent, pb, b.tangent)? <= budget {
1752 out.push(b);
1753 continue;
1754 }
1755 let chord_vector = b.point.sub(a.point);
1756 let chord = chord_vector.length();
1757 if depth >= 8 || inserted >= 4096 || chord <= 4.0 * crate::KNOT_IDENTITY_TOL
1758 || crossing_at(first, second, pa) < 0.05 || crossing_at(first, second, pb) < 0.05
1759 || a.tangent.dot(b.tangent) < 0.5
1760 || a.tangent.dot(chord_vector) <= 0.5 * chord || b.tangent.dot(chord_vector) <= 0.5 * chord
1761 { return Ok(None); }
1762 let ha = ParameterHermite::new(first, a.uv_a, a.tangent, b.uv_a, b.tangent, chord)?;
1763 let hb = ParameterHermite::new(second, a.uv_b, a.tangent, b.uv_b, b.tangent, chord)?;
1764 let ua = ha.at(0.5);
1765 let ub = hb.at(0.5);
1766 let predicted = hermite_at(a.point, a.tangent.scale(chord), b.point, b.tangent.scale(chord), 0.5);
1767 let direction = a.tangent.add(b.tangent).normalized()?;
1768 let seed = IntersectionPoint {
1769 point: predicted,
1770 ua: fit(ua[0], first.u0, first.u1, first.closed_u),
1771 va: fit(ua[1], first.v0, first.v1, first.closed_v),
1772 ub: fit(ub[0], second.u0, second.u1, second.closed_u),
1773 vb: fit(ub[1], second.v0, second.v1, second.closed_v),
1774 };
1775 let Some((mid, boundary)) = correct(first, second, seed, predicted, direction, budget * 0.1)? else { return Ok(None); };
1776 let along = mid.point.sub(a.point).dot(chord_vector) / (chord * chord);
1777 if boundary || mid.point.sub(predicted).length() > 0.25 * chord
1778 || !(0.2..=0.8).contains(&along) || crossing_at(first, second, mid) < 0.05
1779 { return Ok(None); }
1780 let Some(mut tangent) = tangent_at(first, second, mid)? else { return Ok(None); };
1781 if tangent.dot(direction) < 0.0 { tangent = tangent.scale(-1.0); }
1782 if tangent.dot(a.tangent) < 0.5 || tangent.dot(b.tangent) < 0.5 { return Ok(None); }
1783 let m = EmissionSample { point: mid.point, uv_a: [mid.ua, mid.va], uv_b: [mid.ub, mid.vb], tangent };
1784 inserted += 1;
1785 pending.push((m, b, depth + 1));
1786 pending.push((a, m, depth + 1));
1787 }
1788 Ok(Some(out))
1789}
1790
1791pub fn correct_in_plane(
1797 first_surface: &NurbsSurface,
1798 second_surface: &NurbsSurface,
1799 uv_a: [f64; 2],
1800 uv_b: [f64; 2],
1801 predicted: Vec3,
1802 direction: Vec3,
1803 tolerance: f64,
1804) -> Result<Option<(Vec3, [f64; 2], [f64; 2])>, String> {
1805 let first = surface_info(first_surface)?;
1806 let second = surface_info(second_surface)?;
1807 let seed = IntersectionPoint {
1808 point: predicted,
1809 ua: fit(uv_a[0], first.u0, first.u1, first.closed_u),
1810 va: fit(uv_a[1], first.v0, first.v1, first.closed_v),
1811 ub: fit(uv_b[0], second.u0, second.u1, second.closed_u),
1812 vb: fit(uv_b[1], second.v0, second.v1, second.closed_v),
1813 };
1814 Ok(correct(first, second, seed, predicted, direction, tolerance)?
1815 .map(|(point, _)| (point.point, [point.ua, point.va], [point.ub, point.vb])))
1816}
1817
1818pub fn refine_to_intersection(
1827 first_surface: &NurbsSurface,
1828 second_surface: &NurbsSurface,
1829 seed: Vec3,
1830 tolerance: f64,
1831 reach: f64,
1832) -> Result<Option<Vec3>, String> {
1833 let first = surface_info(first_surface)?;
1834 let second = surface_info(second_surface)?;
1835 let on_first = project_point_to_surface(first_surface, seed)?;
1836 let on_second = project_point_to_surface(second_surface, seed)?;
1837 let Some(refined) = refine_point(
1838 first,
1839 second,
1840 on_first.u,
1841 on_first.v,
1842 on_second.u,
1843 on_second.v,
1844 tolerance,
1845 )?
1846 else {
1847 return Ok(None);
1848 };
1849 if refined.point.sub(seed).length() > reach {
1850 return Ok(None);
1851 }
1852 Ok(Some(refined.point))
1853}
1854
1855pub fn intersect_surfaces(
1856 first_surface: &NurbsSurface,
1857 second_surface: &NurbsSurface,
1858 options: &SurfaceIntersectionOptions,
1859) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1860 let check = crate::switch!(live "BREP_SSI_ORIENTED_CONTINUATION_CHECK", false);
1861 let mut switches = TraceSwitches::from_env();
1862 if check { switches.oriented_continuation = true; }
1863 let result = intersect_surfaces_with_switches(first_surface, second_surface, options, switches);
1864 if check {
1865 switches.oriented_continuation = false;
1866 let old = intersect_surfaces_with_switches(first_surface, second_surface, options, switches);
1867 match (&old, &result) {
1868 (Ok(before), Ok(after)) => {
1869 eprintln!("ssi.continuation_check branches {} -> {}", before.len(), after.len());
1870 for i in 0..before.len().max(after.len()) {
1871 match (before.get(i), after.get(i)) {
1872 (Some(a), Some(b)) => {
1873 let changed = a.points.iter().zip(&b.points).position(|(p, q)| p.sub(*q).length() > options.tolerance);
1874 if changed.is_some() || a.points.len() != b.points.len() || a.closed != b.closed {
1875 eprintln!("ssi.continuation_check branch={i} stations={}->{} closed={}->{} first_changed={changed:?}", a.points.len(), b.points.len(), a.closed, b.closed);
1876
1877 }
1878 }
1879 _ => eprintln!("ssi.continuation_check branch={i} added_or_removed"),
1880 }
1881 }
1882 }
1883 _ => eprintln!("ssi.continuation_check old_error={:?} guarded_error={:?}", old.as_ref().err(), result.as_ref().err()),
1884 }
1885 }
1886 result
1887}
1888
1889fn intersect_surfaces_with_switches(
1890 first_surface: &NurbsSurface,
1891 second_surface: &NurbsSurface,
1892 options: &SurfaceIntersectionOptions,
1893 switches: TraceSwitches,
1894) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1895 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
1896 let _lap = crate::projection_profile::Lap::enter_pair(first_surface, second_surface);
1897 let first_box = Bounds::from_surface_controls(first_surface)?;
1898 let second_box = Bounds::from_surface_controls(second_surface)?;
1899 if !first_box.intersects(second_box, options.tolerance * 10.0) {
1900 return Ok(Vec::new());
1901 }
1902 let first = surface_info(first_surface)?;
1903 let second = surface_info(second_surface)?;
1904 let diagonal = first_box.diagonal().min(second_box.diagonal());
1905 let initial_step = diagonal / 100.0;
1906 let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
1907 let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
1908 let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
1909 let mut starts = if options.seed_only {
1910 Vec::new()
1911 } else if options.tree_seeds {
1912 match tree_start_points(first, second, options.tolerance)? {
1915 Some((starts, _pairs)) => starts,
1916 None => find_start_points(first, second, options.tolerance, options.seed_density)?,
1917 }
1918 } else {
1919 find_start_points(first, second, options.tolerance, options.seed_density)?
1920 };
1921 starts.retain(|start| transverse_at(first, second, *start));
1926 let seed_gate = options.seed_gate.unwrap_or(options.tolerance * 100.0);
1927 let grid_count = starts.len();
1929 for seed in &options.seed_points {
1930 let projection_a = project_point_to_surface(first_surface, *seed)?;
1931 if projection_a.distance > seed_gate {
1932 continue;
1933 }
1934 let projection_b = project_point_to_surface(second_surface, *seed)?;
1935 if projection_b.distance > seed_gate {
1936 continue;
1937 }
1938 let Some(refined) = refine_point(
1939 first,
1940 second,
1941 projection_a.u,
1942 projection_a.v,
1943 projection_b.u,
1944 projection_b.v,
1945 options.tolerance,
1946 )?
1947 else {
1948 continue;
1949 };
1950 let admitted = match options.seed_start_cross {
1953 Some(bound) => crossing_at(first, second, refined) >= bound.min(TRANSVERSE_START_CROSS),
1954 None => transverse_at(first, second, refined),
1955 };
1956 if !admitted {
1957 continue;
1958 }
1959 starts.push(refined);
1960 }
1961 if options.ordered_starts {
1962 let crossing = |start: &IntersectionPoint| -> f64 {
1966 match (
1967 first.surface.normal(start.ua, start.va),
1968 second.surface.normal(start.ub, start.vb),
1969 ) {
1970 (Ok(a), Ok(b)) => a.cross(b).length(),
1971 _ => 0.0,
1972 }
1973 };
1974 let mut seeds = starts.split_off(grid_count);
1975 seeds.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1976 starts.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1977 seeds.append(&mut starts);
1978 starts = seeds;
1979 }
1980
1981 let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
1982 for start in starts {
1983 let mut claimed = false;
1984 for curve in &mut curves {
1985 let Some((index, distance)) = curve
1986 .points
1987 .windows(2)
1988 .enumerate()
1989 .map(|(index, segment)| (index, point_segment_distance(start.point, segment[0], segment[1])))
1990 .filter(|(_, distance)| *distance <= initial_step * 1.5)
1991 .min_by(|a, b| a.1.total_cmp(&b.1))
1992 else {
1993 continue;
1994 };
1995 claimed = true;
1996 if options.consume_starts
2001 && distance > 0.0
2002 && start.point.sub(curve.points[index]).length() > minimum_step
2003 && start.point.sub(curve.points[index + 1]).length() > minimum_step
2004 {
2005 curve.points.insert(index + 1, start.point);
2006 if let Some(tangents) = curve.tangents.as_mut() {
2007 let along = curve.points[index + 2].sub(curve.points[index]);
2008 let tangent = match tangent_at(first, second, start)? {
2009 Some(tangent) if tangent.dot(along) < 0.0 => tangent.scale(-1.0),
2010 Some(tangent) => tangent,
2011 None => tangents[index],
2012 };
2013 tangents.insert(index + 1, tangent);
2014 }
2015 if curve.params_a.len() > index + 1 && curve.params_b.len() > index + 1 {
2016 curve.params_a.insert(index + 1, [start.ua, start.va]);
2017 curve.params_b.insert(index + 1, [start.ub, start.vb]);
2018 }
2019 }
2020 break;
2021 }
2022 if switches.debug {
2023 let at = start.point;
2024 eprintln!(
2025 "SSI-START claimed {claimed} p ({:.6},{:.6},{:.6}) initial {initial_step:.4e} minimum {minimum_step:.4e} maximum {maximum_step:.4e}",
2026 at.x, at.y, at.z
2027 );
2028 }
2029 if claimed {
2030 continue;
2031 }
2032 let forward = trace(
2033 first,
2034 second,
2035 start,
2036 1.0,
2037 options.tolerance,
2038 initial_step,
2039 minimum_step,
2040 maximum_step,
2041 maximum_steps,
2042 switches,
2043 options.span_budget,
2044 )?;
2045 let (all, closed) = if forward.closed {
2046 (Spliced::from(forward), true)
2047 } else {
2048 let backward = trace(
2049 first,
2050 second,
2051 start,
2052 -1.0,
2053 options.tolerance,
2054 initial_step,
2055 minimum_step,
2056 maximum_step,
2057 maximum_steps,
2058 switches,
2059 options.span_budget,
2060 )?;
2061 (splice(backward, forward), false)
2062 };
2063 if all.points.len() < 2 {
2064 continue;
2065 }
2066 curves.push(curve_from(all, closed, options.span_budget.is_some()));
2067 }
2068 Ok(curves)
2069}
2070
2071const SUPPLEMENTAL_TRANSVERSE_CROSS: f64 = TRANSVERSE_START_CROSS;
2075
2076pub fn intersect_surfaces_supplemental(
2103 first_surface: &NurbsSurface,
2104 second_surface: &NurbsSurface,
2105 options: &SurfaceIntersectionOptions,
2106) -> Result<Vec<SurfaceIntersectionCurve>, String> {
2107 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
2108 let first_box = Bounds::from_surface_controls(first_surface)?;
2109 let second_box = Bounds::from_surface_controls(second_surface)?;
2110 if !first_box.intersects(second_box, options.tolerance * 10.0) {
2111 return Ok(Vec::new());
2112 }
2113 let first = surface_info(first_surface)?;
2114 let second = surface_info(second_surface)?;
2115 let diagonal = first_box.diagonal().min(second_box.diagonal());
2116 let initial_step = diagonal / 100.0;
2117 let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
2118 let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
2119 let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
2120
2121 let density = options.seed_density.max(2.0);
2126 let mut starts: Vec<IntersectionPoint> = Vec::new();
2127 for gridded_second in [false, true] {
2128 let (a, b) = if gridded_second {
2129 (second, first)
2130 } else {
2131 (first, second)
2132 };
2133 for start in find_start_points(a, b, options.tolerance, density)? {
2134 let start = if gridded_second {
2137 IntersectionPoint {
2138 ua: start.ub,
2139 va: start.vb,
2140 ub: start.ua,
2141 vb: start.va,
2142 point: start.point,
2143 }
2144 } else {
2145 start
2146 };
2147 starts.push(start);
2148 }
2149 }
2150 starts.retain(|start| {
2154 match (
2155 first.surface.normal(start.ua, start.va),
2156 second.surface.normal(start.ub, start.vb),
2157 ) {
2158 (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
2159 _ => false,
2160 }
2161 });
2162
2163 let switches = TraceSwitches { turn_rate_retrace: false, ..TraceSwitches::from_env() };
2168 let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
2169 for start in starts {
2170 let claimed = curves.iter().any(|curve| {
2171 curve.points.windows(2).any(|segment| {
2172 point_segment_distance(start.point, segment[0], segment[1]) <= initial_step * 1.5
2173 })
2174 });
2175 if claimed {
2176 continue;
2177 }
2178 let Ok(forward) = trace(
2182 first,
2183 second,
2184 start,
2185 1.0,
2186 options.tolerance,
2187 initial_step,
2188 minimum_step,
2189 maximum_step,
2190 maximum_steps,
2191 switches,
2192 options.span_budget,
2193 ) else {
2194 continue;
2195 };
2196 let (all, closed) = if forward.closed {
2197 (Spliced::from(forward), true)
2198 } else {
2199 let Ok(backward) = trace(
2200 first,
2201 second,
2202 start,
2203 -1.0,
2204 options.tolerance,
2205 initial_step,
2206 minimum_step,
2207 maximum_step,
2208 maximum_steps,
2209 switches,
2210 options.span_budget,
2211 ) else {
2212 continue;
2213 };
2214 (splice(backward, forward), false)
2215 };
2216 if all.points.len() < 2 {
2217 continue;
2218 }
2219 let transverse = all.points.iter().step_by((all.points.len() / 5).max(1)).any(|point| {
2223 match (
2224 first.surface.normal(point.ua, point.va),
2225 second.surface.normal(point.ub, point.vb),
2226 ) {
2227 (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
2228 _ => false,
2229 }
2230 });
2231 if !transverse {
2232 continue;
2233 }
2234 curves.push(curve_from(all, closed, options.span_budget.is_some()));
2235 }
2236 Ok(curves)
2237}
2238