1use ogeom_core::{OgeomResult, Tolerances, ogeom_bail};
28use ogeom_geom::{
29 Circle2d, Curve, Curve2d as _, Curve3d, Ellipse2d, Line2d, PlanarCurve, Surface,
30 SurfaceGeometry,
31};
32use ogeom_math::{Circle2, Ellipse2, Frame2, Point, Point2};
33
34use crate::approx::approximate_branch;
35use crate::march::{Marching, branches, trace_tangential};
36use crate::surface::{Meeting, surface_surface};
37
38#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct IntersectOptions {
41 pub tolerance: f64,
43 pub marching: Marching,
45}
46
47impl Default for IntersectOptions {
48 fn default() -> Self {
49 Self {
50 tolerance: 1e-6,
51 marching: Marching::default(),
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq)]
58pub struct SectionCurve {
59 pub curve: Curve,
61 pub on_a: Option<PlanarCurve>,
68 pub on_b: Option<PlanarCurve>,
70 pub tolerance: f64,
75 pub exact: bool,
77 pub closed: bool,
79 pub tangential: bool,
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub enum SurfaceIntersection {
94 Apart,
101 Touching(Vec<Point>),
103 Along(Vec<SectionCurve>),
105 Same,
107}
108
109pub fn intersect_surfaces(
123 a: &SurfaceGeometry,
124 b: &SurfaceGeometry,
125 options: IntersectOptions,
126 tol: Tolerances,
127) -> OgeomResult<SurfaceIntersection> {
128 if !options.tolerance.is_finite() || options.tolerance <= 0.0 {
129 ogeom_bail!(
130 Construction,
131 "a tolerance of {} is not a distance",
132 options.tolerance
133 );
134 }
135
136 if let Some(sections) = near_parallel_plane_drum(a, b, tol) {
141 return Ok(if sections.is_empty() {
142 SurfaceIntersection::Apart
143 } else {
144 SurfaceIntersection::Along(sections)
145 });
146 }
147 match surface_surface(a, b, tol) {
148 Ok(Meeting::Apart) => Ok(SurfaceIntersection::Apart),
149 Ok(Meeting::Same) => Ok(SurfaceIntersection::Same),
150 Ok(Meeting::Touching(points)) => Ok(SurfaceIntersection::Touching(points)),
151 Ok(Meeting::Along(curves)) => {
152 let sections: Vec<SectionCurve> = curves
153 .into_iter()
154 .filter_map(|curve| exact_section(curve, a, b, tol))
155 .collect();
156 Ok(if sections.is_empty() {
157 SurfaceIntersection::Apart
160 } else {
161 SurfaceIntersection::Along(sections)
162 })
163 }
164 Err(_) => match near_parallel_drums(a, b, tol)
167 .or_else(|| ball_through_drum(a, b, tol))
168 .or_else(|| axial_plane_revolution(a, b, tol))
169 .or_else(|| plane_along_spline_lines(a, b, tol))
170 {
171 Some(sections) if sections.is_empty() => Ok(SurfaceIntersection::Apart),
172 Some(sections) => Ok(SurfaceIntersection::Along(sections)),
173 None => marched(a, b, options, tol),
174 },
175 }
176}
177
178fn axial_plane_revolution(
191 a: &SurfaceGeometry,
192 b: &SurfaceGeometry,
193 tol: Tolerances,
194) -> Option<Vec<SectionCurve>> {
195 const SAMPLES: u32 = 64;
196 let (plane, revolution, plane_first) = match (a, b) {
197 (SurfaceGeometry::Plane(p), SurfaceGeometry::Revolution(r)) => (p, r, true),
198 (SurfaceGeometry::Revolution(r), SurfaceGeometry::Plane(p)) => (p, r, false),
199 _ => return None,
200 };
201 let cut = plane.plane();
202 let axis = revolution.axis();
203 let normal = cut.normal();
204 if normal.dot(axis.direction).abs() > tol.angular()
205 || cut.signed_distance_to(axis.location).abs() > tol.confusion()
206 {
207 return None;
208 }
209 let profile = revolution.curve();
210 let (v0, v1) = profile.domain();
211 let at = |k: u32| v0 + (v1 - v0) * f64::from(k) / f64::from(SAMPLES);
212 let radial = |v: f64| {
213 let p = profile.point_at(v, tol).ok()?;
214 Some(p - axis.project(p))
215 };
216 let mut widest = ogeom_math::Vector::ZERO;
218 for k in 0..=SAMPLES {
219 let r = radial(at(k))?;
220 if r.magnitude() > widest.magnitude() {
221 widest = r;
222 }
223 }
224 let side = ogeom_math::Direction::new(widest, tol).ok()?;
225 let across = axis.direction.cross_with(side.vector());
226 let offset = |v: f64| radial(v).map(|r| (r.dot(side.vector()), r.dot(across)));
228 for k in 0..=SAMPLES {
229 let (_, off) = offset(at(k))?;
230 if off.abs() > tol.confusion() {
231 return None;
232 }
233 }
234 let mut cuts = vec![v0];
237 for k in 0..SAMPLES {
238 let (mut lo, mut hi) = (at(k), at(k + 1));
239 let (s_lo, s_hi) = (offset(lo)?.0, offset(hi)?.0);
240 if s_lo.abs() <= tol.confusion() || s_lo * s_hi >= 0.0 {
241 continue;
242 }
243 for _ in 0..80 {
244 let mid = f64::midpoint(lo, hi);
245 if offset(mid)?.0 * s_lo > 0.0 {
246 lo = mid;
247 } else {
248 hi = mid;
249 }
250 }
251 cuts.push(f64::midpoint(lo, hi));
252 }
253 cuts.push(v1);
254 let out = axis.direction.cross_with(normal.vector());
256 let first = across.dot(out).atan2(side.vector().dot(out));
257 let (u0, u1) = revolution.domain().0;
258 let turns: Vec<f64> = [first, first + core::f64::consts::PI]
259 .into_iter()
260 .filter_map(|u| {
261 let u = u0 + (u - u0).rem_euclid(core::f64::consts::TAU);
262 let u = if (u - u0 - core::f64::consts::TAU).abs() <= tol.angular() {
263 u0
264 } else {
265 u
266 };
267 (u <= u1 + tol.angular()).then_some(u.min(u1))
268 })
269 .collect();
270 let mut sections = Vec::new();
271 for &u in &turns {
272 let turned = ogeom_geom::Transformable::transformed(
273 profile,
274 &ogeom_math::Transform::rotation(axis, u),
275 tol,
276 )
277 .ok()?;
278 for piece in cuts.windows(2) {
279 let (va, vb) = (piece[0], piece[1]);
280 if vb - va <= tol.parametric() {
281 continue;
282 }
283 let curve: Curve = ogeom_geom::TrimmedCurve::new(turned.clone(), va, vb, tol)
284 .ok()?
285 .into();
286 let column: PlanarCurve = Line2d::over(
287 ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
288 va,
289 vb,
290 )
291 .ok()?
292 .into();
293 let flat = exact_pcurve(&curve, (va, vb), a_or_b(plane_first, a, b), tol);
294 let (on_a, on_b) = if plane_first {
295 (flat, Some(column))
296 } else {
297 (Some(column), flat)
298 };
299 sections.push(SectionCurve {
300 on_a,
301 on_b,
302 tolerance: 0.0,
303 exact: true,
304 closed: false,
305 tangential: false,
306 curve,
307 });
308 }
309 }
310 Some(sections)
311}
312
313fn plane_along_spline_lines(
326 a: &SurfaceGeometry,
327 b: &SurfaceGeometry,
328 tol: Tolerances,
329) -> Option<Vec<SectionCurve>> {
330 const SAMPLES: u32 = 96;
331 let (plane, spline, plane_first) = match (a, b) {
332 (SurfaceGeometry::Plane(p), SurfaceGeometry::BSpline(s)) => (p.plane(), s, true),
333 (SurfaceGeometry::BSpline(s), SurfaceGeometry::Plane(p)) => (p.plane(), s, false),
334 _ => return None,
335 };
336 let distance = |p: Point| plane.signed_distance_to(p);
337 let ((u0, u1), (v0, v1)) = spline.domain();
338 let line_at = |along_u: bool, t: f64| -> Option<ogeom_geom::BSplineCurve> {
341 if along_u {
342 spline.iso_u_curve(t, tol).ok()
343 } else {
344 spline.iso_v_curve(t, tol).ok()
345 }
346 };
347 let weighted = |curve: &ogeom_geom::BSplineCurve| -> Vec<f64> {
348 curve
349 .control_points()
350 .iter()
351 .map(|w| w.weight * distance(w.point()))
352 .collect()
353 };
354 let lies_in = |curve: &ogeom_geom::BSplineCurve| {
355 curve
356 .control_points()
357 .iter()
358 .all(|w| distance(w.point()).abs() <= tol.confusion())
359 };
360 let has_length = |curve: &ogeom_geom::BSplineCurve| {
361 let first = curve.control_points()[0].point();
362 curve
363 .control_points()
364 .iter()
365 .any(|w| w.point().distance(first) > tol.confusion())
366 };
367 let found = |along_u: bool| -> Option<Vec<f64>> {
370 let (lo, hi) = if along_u { (u0, u1) } else { (v0, v1) };
371 let at = |k: u32| lo + (hi - lo) * f64::from(k) / f64::from(SAMPLES);
372 let rows: Vec<Vec<f64>> = (0..=SAMPLES)
373 .map(|k| line_at(along_u, at(k)).map(|c| weighted(&c)))
374 .collect::<Option<_>>()?;
375 let count = rows[0].len();
376 if rows.iter().any(|r| r.len() != count) {
377 return None;
378 }
379 let widest = (0..count).max_by(|&i, &j| {
380 let spread = |i: usize| rows.iter().fold(0.0_f64, |m, r| m.max(r[i].abs()));
381 spread(i).total_cmp(&spread(j))
382 })?;
383 let mut roots = vec![lo, hi];
384 for k in 0..SAMPLES {
385 let (mut a, mut b) = (at(k), at(k + 1));
386 let (da, db) = (rows[k as usize][widest], rows[k as usize + 1][widest]);
387 if da == 0.0 {
388 roots.push(a);
389 continue;
390 }
391 if da * db > 0.0 {
392 continue;
393 }
394 let sign = da.signum();
395 for _ in 0..80 {
396 let mid = f64::midpoint(a, b);
397 let d = weighted(&line_at(along_u, mid)?)[widest];
398 if d * sign > 0.0 {
399 a = mid;
400 } else {
401 b = mid;
402 }
403 }
404 roots.push(f64::midpoint(a, b));
405 }
406 roots.sort_by(f64::total_cmp);
407 roots.dedup_by(|x, y| (*x - *y).abs() <= tol.parametric());
408 Some(
409 roots
410 .into_iter()
411 .filter(|&t| line_at(along_u, t).is_some_and(|c| lies_in(&c) && has_length(&c)))
412 .collect(),
413 )
414 };
415 let columns = found(true)?;
416 let rows = found(false)?;
417 if columns.is_empty() && rows.is_empty() {
418 return None;
419 }
420 let strip = |lines: &[f64], t: f64| lines.iter().filter(|&&x| x < t).count();
423 let near_line = |lines: &[f64], t: f64, span: f64| {
424 lines
425 .iter()
426 .any(|&x| (x - t).abs() <= span / f64::from(SAMPLES) * 0.25)
427 };
428 let mut sides: std::collections::HashMap<(usize, usize), f64> =
429 std::collections::HashMap::new();
430 let band = tol.confusion() * 10.0;
431 for i in 0..=SAMPLES {
432 let u = u0 + (u1 - u0) * (f64::from(i) + 0.5) / f64::from(SAMPLES + 1);
433 if near_line(&columns, u, u1 - u0) {
434 continue;
435 }
436 for j in 0..=SAMPLES {
437 let v = v0 + (v1 - v0) * (f64::from(j) + 0.5) / f64::from(SAMPLES + 1);
438 if near_line(&rows, v, v1 - v0) {
439 continue;
440 }
441 let d = distance(spline.point_at(u, v, tol).ok()?);
442 if d.abs() <= band {
443 continue;
444 }
445 let cell = (strip(&columns, u), strip(&rows, v));
446 match sides.get(&cell) {
447 Some(side) if side * d < 0.0 => return None,
448 Some(_) => {}
449 None => {
450 sides.insert(cell, d.signum());
451 }
452 }
453 }
454 }
455 let closed_u = spline.is_closed_u(tol);
461 let closed_v = spline.is_closed_v(tol);
462 let side_of = |cu: Option<usize>, cv: Option<usize>| -> Option<f64> {
463 let mut found = sides
464 .iter()
465 .filter(|((u, v), _)| cu.is_none_or(|c| c == *u) && cv.is_none_or(|c| c == *v))
466 .map(|(_, s)| *s);
467 let first = found.next()?;
468 found.all(|s| s == first).then_some(first)
469 };
470 let crosses = |k: usize, count: usize, closed: bool, cell: &dyn Fn(usize) -> Option<f64>| {
471 let below = cell(k).or_else(|| closed.then(|| (0..=count).rev().find_map(cell)).flatten());
472 let above = cell(k + 1).or_else(|| closed.then(|| (0..=count).find_map(cell)).flatten());
473 matches!((below, above), (Some(x), Some(y)) if x * y < 0.0)
474 };
475 for k in 0..columns.len() {
476 if !crosses(k, columns.len(), closed_u, &|c| side_of(Some(c), None)) {
477 return None;
478 }
479 }
480 for k in 0..rows.len() {
481 if !crosses(k, rows.len(), closed_v, &|c| side_of(None, Some(c))) {
482 return None;
483 }
484 }
485 let mut sections = Vec::new();
486 let mut emit = |along_u: bool, t: f64| -> Option<()> {
487 let iso = line_at(along_u, t)?;
488 let curve: Curve = iso.into();
489 let range = curve.domain();
490 let chart: PlanarCurve = if along_u {
491 Line2d::over(
492 ogeom_math::Axis2::new(Point2::new(t, 0.0), ogeom_math::Direction2::Y),
493 range.0,
494 range.1,
495 )
496 } else {
497 Line2d::over(
498 ogeom_math::Axis2::new(Point2::new(0.0, t), ogeom_math::Direction2::X),
499 range.0,
500 range.1,
501 )
502 }
503 .ok()?
504 .into();
505 let flat = exact_pcurve(&curve, range, a_or_b(plane_first, a, b), tol)?;
506 let (on_a, on_b) = if plane_first {
507 (Some(flat), Some(chart))
508 } else {
509 (Some(chart), Some(flat))
510 };
511 sections.push(SectionCurve {
512 on_a,
513 on_b,
514 tolerance: 0.0,
515 exact: true,
516 closed: curve.is_closed(tol),
517 tangential: false,
518 curve,
519 });
520 Some(())
521 };
522 for (k, &u) in columns.iter().enumerate() {
525 if closed_u
526 && k + 1 == columns.len()
527 && k > 0
528 && columns[0] == u0
529 && (u - u1).abs() <= tol.parametric()
530 {
531 continue;
532 }
533 emit(true, u)?;
534 }
535 for (k, &v) in rows.iter().enumerate() {
536 if closed_v
537 && k + 1 == rows.len()
538 && k > 0
539 && rows[0] == v0
540 && (v - v1).abs() <= tol.parametric()
541 {
542 continue;
543 }
544 emit(false, v)?;
545 }
546 Some(sections)
547}
548
549fn a_or_b<'s>(first: bool, a: &'s SurfaceGeometry, b: &'s SurfaceGeometry) -> &'s SurfaceGeometry {
551 if first { a } else { b }
552}
553
554fn near_parallel_drums(
571 a: &SurfaceGeometry,
572 b: &SurfaceGeometry,
573 tol: Tolerances,
574) -> Option<Vec<SectionCurve>> {
575 const LEAN: f64 = 1e-3;
576 let (SurfaceGeometry::Cylinder(sa), SurfaceGeometry::Cylinder(sb)) = (a, b) else {
577 return None;
578 };
579 let (ca, cb) = (sa.cylinder(), sb.cylinder());
580 let (axis_a, axis_b) = (ca.axis(), cb.axis());
581 let (da, db) = (axis_a.direction.vector(), axis_b.direction.vector());
582 let (ra, rb) = (ca.radius(), cb.radius());
583 let cos = da.dot(db);
584 if da.cross(db).magnitude() > LEAN || cos.abs() < 0.5 {
585 return None;
586 }
587 let (pa, pb) = (axis_a.location, axis_b.location);
588 let (_, (a0, a1)) = a.domain();
590 let (_, (b0, b1)) = b.domain();
591 let along = |v: f64| (pb - pa).dot(da) + v * cos;
592 let (lo, hi) = (
593 a0.min(a1).max(along(b0).min(along(b1))),
594 a0.max(a1).min(along(b0).max(along(b1))),
595 );
596 if !(lo.is_finite() && hi.is_finite()) {
597 return None;
598 }
599 if hi - lo <= tol.confusion() {
600 return Some(Vec::new());
601 }
602 let meet = |z: f64| -> Option<[Point; 2]> {
606 let centre_a = pa + da * z;
607 let s = (centre_a - pb).dot(da) / cos;
608 let centre_b = pb + db * s;
609 let mut between = centre_b - centre_a;
610 between = between - da * between.dot(da);
611 let d = between.magnitude();
612 let margin = tol.confusion() * 1e3;
613 if d <= margin || d >= ra + rb - margin || d <= (ra - rb).abs() + margin {
614 return None;
615 }
616 let x = (d * d + ra * ra - rb * rb) / (2.0 * d);
617 let h = (ra * ra - x * x).max(0.0).sqrt();
618 let ex = between / d;
619 let ey = da.cross(ex);
620 Some([centre_a + ex * x + ey * h, centre_a + ex * x - ey * h])
621 };
622 lines_through_stations(lo, hi, meet, rb * (1.0 / cos.abs() - 1.0), tol)
623}
624
625const NEAR_PARALLEL_STRAY: f64 = 1e-5;
628
629fn lines_through_stations(
637 lo: f64,
638 hi: f64,
639 meet: impl Fn(f64) -> Option<[Point; 2]>,
640 stated: f64,
641 tol: Tolerances,
642) -> Option<Vec<SectionCurve>> {
643 const STATIONS: u32 = 32;
644 const STRAIGHT: f64 = 1e-6;
645 let at = |k: f64| (hi - lo).mul_add(k / f64::from(STATIONS), lo);
646 let heights: Vec<f64> = (0..=STATIONS).map(|k| at(f64::from(k))).collect();
647 let met: Vec<[Point; 2]> = heights.iter().map(|&z| meet(z)).collect::<Option<_>>()?;
648 let between: Vec<[Point; 2]> = (0..STATIONS)
649 .map(|k| meet(at(f64::from(k) + 0.5)))
650 .collect::<Option<_>>()?;
651 let mut out = Vec::with_capacity(2);
652 for side in 0..2 {
653 let (from, to) = (met[0][side], met[met.len() - 1][side]);
654 let span = to - from;
655 let length = span.magnitude();
656 if length <= tol.confusion() {
657 return None;
658 }
659 let off_line = |p: Point| {
660 let t = (p - from).dot(span) / (length * length);
661 p.distance(from + span * t)
662 };
663 let stray = met
664 .iter()
665 .chain(&between)
666 .map(|pair| off_line(pair[side]))
667 .fold(0.0_f64, f64::max);
668 let (curve, stray): (Curve, f64) = if stray <= STRAIGHT {
669 (
670 ogeom_geom::LineCurve::segment(from, to, tol).ok()?.into(),
671 stray,
672 )
673 } else {
674 let points: Vec<Point> = met.iter().map(|pair| pair[side]).collect();
675 let fitted =
676 ogeom_geom::fit::fit_points_at(&heights, &points, 3, tol.confusion(), tol).ok()?;
677 let curve: Curve = fitted.curve.into();
678 let mut worst = fitted.error;
679 for (k, pair) in (0..STATIONS).zip(&between) {
680 let p = curve.point_at(at(f64::from(k) + 0.5), tol).ok()?;
681 worst = worst.max(p.distance(pair[side]));
682 }
683 (curve, worst)
684 };
685 let tolerance = stray + stated + tol.confusion();
686 if tolerance > NEAR_PARALLEL_STRAY {
687 return None;
688 }
689 out.push(SectionCurve {
690 curve,
691 on_a: None,
692 on_b: None,
693 tolerance,
694 exact: false,
695 closed: false,
696 tangential: false,
697 });
698 }
699 Some(out)
700}
701
702fn ball_through_drum(
714 a: &SurfaceGeometry,
715 b: &SurfaceGeometry,
716 tol: Tolerances,
717) -> Option<Vec<SectionCurve>> {
718 const SAMPLES: u32 = 256;
719 const STRAY: f64 = 1e-5;
720 let (ball, drum, ball_first) = match (a, b) {
721 (SurfaceGeometry::Sphere(s), SurfaceGeometry::Cylinder(c)) => (s, c, true),
722 (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Sphere(s)) => (s, c, false),
723 _ => return None,
724 };
725 let (sphere, cylinder) = (ball.sphere(), drum.cylinder());
726 let frame = cylinder.frame();
727 let (x, y, d) = (frame.x().vector(), frame.y().vector(), frame.z().vector());
728 let (origin, r) = (frame.origin(), cylinder.radius());
729 let (centre, big) = (sphere.centre(), sphere.radius());
730 let ball_frame = sphere.frame();
731 let (_, (h0, h1)) = drum.domain();
732 let margin = r * 0.1;
736 let heights = |angle: f64| -> Option<[f64; 2]> {
738 let foot = origin + (x * angle.cos() + y * angle.sin()) * r;
739 let w = foot - centre;
740 let half = d.dot(w);
741 let disc = half.mul_add(half, -(w.dot(w) - big * big));
742 if disc <= margin * margin {
743 return None;
744 }
745 let root = disc.sqrt();
746 let pair = [-half - root, -half + root];
747 pair.iter().all(|v| *v >= h0 && *v <= h1).then_some(pair)
748 };
749 let at = |angle: f64, v: f64| origin + (x * angle.cos() + y * angle.sin()) * r + d * v;
750 let on_ball = |p: Point, before: Option<Point2>| -> Point2 {
752 let local = ball_frame.to_local(p);
753 let lat = local.z.atan2(local.x.hypot(local.y));
754 let mut lon = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
755 if let Some(prev) = before {
756 while lon - prev.x > core::f64::consts::PI {
757 lon -= core::f64::consts::TAU;
758 }
759 while prev.x - lon > core::f64::consts::PI {
760 lon += core::f64::consts::TAU;
761 }
762 }
763 Point2::new(lon, lat)
764 };
765 let angle_of = |k: f64| core::f64::consts::TAU * k / f64::from(SAMPLES);
766 let params: Vec<f64> = (0..=SAMPLES).map(|k| angle_of(f64::from(k))).collect();
767 let mut sampled: Vec<[f64; 2]> = Vec::with_capacity(params.len());
768 for &angle in ¶ms {
769 sampled.push(heights(angle)?);
770 }
771 let mut out = Vec::with_capacity(2);
772 for side in 0..2 {
773 let points: Vec<Point> = params
774 .iter()
775 .zip(&sampled)
776 .map(|(&angle, pair)| at(angle, pair[side]))
777 .collect();
778 let on_drum: Vec<Point2> = params
779 .iter()
780 .zip(&sampled)
781 .map(|(&angle, pair)| Point2::new(angle, pair[side]))
782 .collect();
783 let mut on_sphere: Vec<Point2> = Vec::with_capacity(points.len());
784 for p in &points {
785 let q = on_ball(*p, on_sphere.last().copied());
786 on_sphere.push(q);
787 }
788 let target = tol.confusion() * 10.0;
789 let curve: Curve = ogeom_geom::fit::fit_points_at(¶ms, &points, 3, target, tol)
790 .ok()?
791 .curve
792 .into();
793 let drum_image: PlanarCurve =
794 ogeom_geom::fit::fit_points_2d_at(¶ms, &on_drum, 3, target, tol)
795 .ok()?
796 .curve
797 .into();
798 let ball_image: PlanarCurve =
799 ogeom_geom::fit::fit_points_2d_at(¶ms, &on_sphere, 3, target, tol)
800 .ok()?
801 .curve
802 .into();
803 let mut stray = 0.0_f64;
806 for k in 0..(2 * SAMPLES) {
807 let angle = angle_of(f64::from(k) / 2.0);
808 let truth = at(angle, heights(angle)?[side]);
809 let on_curve = curve.point_at(angle, tol).ok()?;
810 let uv = drum_image.point_at(angle, tol).ok()?;
811 let through_drum = drum.point_at(uv.x, uv.y, tol).ok()?;
812 let uv = ball_image.point_at(angle, tol).ok()?;
813 let through_ball = ball.point_at(uv.x, uv.y, tol).ok()?;
814 stray = stray
815 .max(truth.distance(on_curve))
816 .max(truth.distance(through_drum))
817 .max(truth.distance(through_ball));
818 }
819 let tolerance = stray.max(tol.confusion());
820 if tolerance > STRAY {
821 return None;
822 }
823 let (on_a, on_b) = if ball_first {
824 (ball_image, drum_image)
825 } else {
826 (drum_image, ball_image)
827 };
828 out.push(SectionCurve {
829 curve,
830 on_a: Some(on_a),
831 on_b: Some(on_b),
832 tolerance,
833 exact: false,
834 closed: true,
835 tangential: false,
836 });
837 }
838 Some(out)
839}
840
841fn near_parallel_plane_drum(
853 a: &SurfaceGeometry,
854 b: &SurfaceGeometry,
855 tol: Tolerances,
856) -> Option<Vec<SectionCurve>> {
857 const LEAN: f64 = 1e-3;
858 const SPAN: f64 = 3e4;
859 let (plane, drum, surface) = match (a, b) {
860 (SurfaceGeometry::Plane(p), SurfaceGeometry::Cylinder(c)) => (p.plane(), c.cylinder(), b),
861 (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Plane(p)) => (p.plane(), c.cylinder(), a),
862 _ => return None,
863 };
864 let axis = drum.axis();
865 let (d, r) = (axis.direction.vector(), drum.radius());
866 let n = plane.normal().vector();
867 let lean = n.dot(d).abs();
868 if lean <= tol.angular() || lean > LEAN || r / lean < SPAN {
873 return None;
874 }
875 let across = n - d * n.dot(d);
876 let k = across.magnitude();
877 let e1 = across / k;
878 let e2 = d.cross(e1);
879 let (_, (lo, hi)) = surface.domain();
880 if !(lo.is_finite() && hi.is_finite()) || hi - lo <= tol.confusion() {
881 return None;
882 }
883 let meet = |z: f64| -> Option<[Point; 2]> {
884 let centre = axis.location + d * z;
885 let u = -plane.signed_distance_to(centre) / k;
886 let margin = tol.confusion() * 1e3;
887 if u.abs() >= r - margin {
888 return None;
889 }
890 let w = r.mul_add(r, -(u * u)).sqrt();
891 Some([centre + e1 * u + e2 * w, centre + e1 * u - e2 * w])
892 };
893 lines_through_stations(lo, hi, meet, 0.0, tol)
894}
895
896fn exact_section(
911 curve: Curve,
912 a: &SurfaceGeometry,
913 b: &SurfaceGeometry,
914 tol: Tolerances,
915) -> Option<SectionCurve> {
916 let closed = match &curve {
917 Curve::Circle(_) | Curve::Ellipse(_) => true,
918 _ => curve.is_closed(tol),
919 };
920 let range = curve.domain();
921 let on_a = exact_pcurve(&curve, range, a, tol);
922 let on_b = exact_pcurve(&curve, range, b, tol);
923
924 if let Curve::Line(_) = &curve {
925 let mut interval = curve.domain();
928 if let Some(p) = &on_a {
929 interval = intersect_intervals(interval, inside_box(p, a))?;
930 }
931 if let Some(p) = &on_b {
932 interval = intersect_intervals(interval, inside_box(p, b))?;
933 }
934 let (lo, hi) = interval;
935 let Curve::Line(line) = &curve else {
936 unreachable!()
937 };
938 let clipped: Curve = ogeom_geom::LineCurve::over(line.axis(), lo, hi)
939 .ok()?
940 .into();
941 let clip2 = |p: &PlanarCurve| -> Option<PlanarCurve> {
942 let PlanarCurve::Line(l) = p else {
943 return Some(p.clone());
944 };
945 Some(Line2d::over(l.axis(), lo, hi).ok()?.into())
946 };
947 let (ca, cb) = (on_a.as_ref().and_then(clip2), on_b.as_ref().and_then(clip2));
948 let tangential = touching_along(&clipped, ca.as_ref(), cb.as_ref(), a, b, tol);
949 return Some(SectionCurve {
950 on_a: ca,
951 on_b: cb,
952 tolerance: 0.0,
953 exact: true,
954 closed: false,
955 tangential,
956 curve: clipped,
957 });
958 }
959
960 for (pcurve, surface) in [(&on_a, a), (&on_b, b)] {
963 if let Some(p) = pcurve
964 && !touches_box(p, surface, tol)
965 {
966 return None;
967 }
968 }
969 let tangential = touching_along(&curve, on_a.as_ref(), on_b.as_ref(), a, b, tol);
970 Some(SectionCurve {
971 on_a,
972 on_b,
973 tolerance: 0.0,
974 exact: true,
975 closed,
976 tangential,
977 curve,
978 })
979}
980
981fn touching_along(
990 curve: &Curve,
991 on_a: Option<&PlanarCurve>,
992 on_b: Option<&PlanarCurve>,
993 a: &SurfaceGeometry,
994 b: &SurfaceGeometry,
995 tol: Tolerances,
996) -> bool {
997 let sample_uv = |pc: Option<&PlanarCurve>,
1005 surface: &SurfaceGeometry,
1006 t: f64|
1007 -> Option<ogeom_math::Point2> {
1008 if let Some(pc) = pc {
1009 return pc.point_at(t, tol).ok();
1010 }
1011 let p = curve.point_at(t, tol).ok()?;
1012 chart_inversion(surface, p, tol)
1013 };
1014 let (lo, hi) = curve.domain();
1015 let mut judged = 0_usize;
1021 for f in [0.07, 0.19, 0.37, 0.53, 0.71, 0.89] {
1022 let t = (hi - lo).mul_add(f, lo);
1023 let (Some(ua), Some(ub)) = (sample_uv(on_a, a, t), sample_uv(on_b, b, t)) else {
1024 continue;
1025 };
1026 let (Ok(na), Ok(nb)) = (a.normal_at(ua.x, ua.y, tol), b.normal_at(ub.x, ub.y, tol)) else {
1027 continue;
1028 };
1029 if na.vector().cross(nb.vector()).magnitude() > 1e-6 {
1030 return false;
1031 }
1032 judged += 1;
1033 }
1034 judged >= 3
1035}
1036
1037fn chart_inversion(
1039 surface: &SurfaceGeometry,
1040 p: ogeom_math::Point,
1041 tol: Tolerances,
1042) -> Option<ogeom_math::Point2> {
1043 use ogeom_math::elementary;
1044 let (u, v) = match surface {
1045 SurfaceGeometry::Plane(s) => elementary::plane_parameters(&s.plane(), p),
1046 SurfaceGeometry::Cylinder(s) => {
1047 elementary::cylinder_parameters(&s.cylinder(), p, tol).ok()?
1048 }
1049 SurfaceGeometry::Cone(s) => elementary::cone_parameters(&s.cone(), p, tol).ok()?,
1050 SurfaceGeometry::Sphere(s) => elementary::sphere_parameters(&s.sphere(), p, tol).ok()?,
1051 SurfaceGeometry::Torus(s) => elementary::torus_parameters(&s.torus(), p, tol).ok()?,
1052 _ => return None,
1053 };
1054 Some(ogeom_math::Point2::new(u, v))
1055}
1056
1057fn inside_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry) -> Option<(f64, f64)> {
1060 let PlanarCurve::Line(line) = pcurve else {
1061 return None;
1062 };
1063 let ((ua, ub), (va, vb)) = surface.domain();
1064 let axis = line.axis();
1065 let (o, d) = (axis.location, axis.direction.vector());
1066
1067 let mut lo = f64::NEG_INFINITY;
1069 let mut hi = f64::INFINITY;
1070 for (origin, direction, low, high) in [(o.x, d.x, ua, ub), (o.y, d.y, va, vb)] {
1071 if direction.abs() <= f64::MIN_POSITIVE {
1072 if origin < low || origin > high {
1073 return None;
1074 }
1075 continue;
1076 }
1077 let (a, b) = ((low - origin) / direction, (high - origin) / direction);
1078 let (near, far) = if a < b { (a, b) } else { (b, a) };
1079 lo = lo.max(near);
1080 hi = hi.min(far);
1081 }
1082 if lo >= hi {
1083 return None;
1084 }
1085 Some((lo, hi))
1086}
1087
1088fn touches_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry, tol: Tolerances) -> bool {
1090 use ogeom_geom::Curve2d;
1091 let ((ua, ub), (va, vb)) = surface.domain();
1092 let (lo, hi) = pcurve.domain();
1093 const SPANS: u32 = 64;
1102 let points: Vec<Option<ogeom_math::Point2>> = (0..=SPANS)
1103 .map(|i| {
1104 pcurve
1105 .point_at(lo + (hi - lo) * f64::from(i) / f64::from(SPANS), tol)
1106 .ok()
1107 })
1108 .collect();
1109 points.windows(2).any(|pair| {
1110 let (Some(p), Some(q)) = (pair[0], pair[1]) else {
1111 return false;
1112 };
1113 let pad = p.distance(q);
1114 let u_ok =
1116 surface.is_periodic_u() || (p.x.max(q.x) + pad >= ua && p.x.min(q.x) - pad <= ub);
1117 let v_ok =
1118 surface.is_periodic_v() || (p.y.max(q.y) + pad >= va && p.y.min(q.y) - pad <= vb);
1119 u_ok && v_ok
1120 })
1121}
1122
1123fn intersect_intervals(a: (f64, f64), b: Option<(f64, f64)>) -> Option<(f64, f64)> {
1125 let b = b?;
1126 let (lo, hi) = (a.0.max(b.0), a.1.min(b.1));
1127 if lo >= hi {
1128 return None;
1129 }
1130 Some((lo, hi))
1131}
1132
1133fn marched(
1135 a: &SurfaceGeometry,
1136 b: &SurfaceGeometry,
1137 options: IntersectOptions,
1138 tol: Tolerances,
1139) -> OgeomResult<SurfaceIntersection> {
1140 let traced = branches(a, b, options.marching, tol)?;
1141 if traced.is_empty() {
1142 return Ok(SurfaceIntersection::Apart);
1143 }
1144 let mut out = Vec::with_capacity(traced.len());
1145 let mut contacts: Vec<crate::march::Traced> = Vec::new();
1146 for branch in &traced {
1147 if branch_is_tangential(a, b, branch, tol)? {
1156 if let Some(contact) = walk_contact(a, b, branch, &contacts, options.marching, tol)? {
1157 contacts.push(contact);
1158 }
1159 continue;
1160 }
1161 if branch.stopped == crate::march::Stopped::RanOut {
1162 ogeom_bail!(
1163 NotDone,
1164 "a marched section ran out of its point budget before \
1165 finishing; the seam is longer than the chord affords and \
1166 fitting the truncation would state a curve that is not there"
1167 );
1168 }
1169 for fitted in fitted_in_pieces(a, b, branch, options.tolerance, tol)? {
1178 out.push(SectionCurve {
1179 curve: fitted.curve.into(),
1180 on_a: Some(fitted.on_a.into()),
1181 on_b: Some(fitted.on_b.into()),
1182 tolerance: options.marching.chord + fitted.fit_error,
1185 exact: false,
1186 closed: fitted.closed,
1187 tangential: false,
1188 });
1189 }
1190 }
1191 for contact in &contacts {
1192 let fitted = approximate_branch(a, b, contact, options.tolerance, tol)?;
1193 out.push(SectionCurve {
1194 curve: fitted.curve.into(),
1195 on_a: Some(fitted.on_a.into()),
1196 on_b: Some(fitted.on_b.into()),
1197 tolerance: options.marching.chord + fitted.fit_error,
1198 exact: false,
1199 closed: fitted.closed,
1200 tangential: true,
1201 });
1202 }
1203 if out.is_empty() {
1204 return Ok(SurfaceIntersection::Apart);
1205 }
1206 Ok(SurfaceIntersection::Along(out))
1207}
1208
1209fn fitted_in_pieces(
1222 a: &SurfaceGeometry,
1223 b: &SurfaceGeometry,
1224 branch: &crate::march::Traced,
1225 tolerance: f64,
1226 tol: Tolerances,
1227) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1228 const DEPTH: u32 = 6;
1229 const FLOOR: usize = 16;
1230 fn go(
1231 a: &SurfaceGeometry,
1232 b: &SurfaceGeometry,
1233 branch: &crate::march::Traced,
1234 tolerance: f64,
1235 depth: u32,
1236 tol: Tolerances,
1237 ) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1238 let whole = approximate_branch(a, b, branch, tolerance, tol)?;
1239 let step = branch
1240 .points
1241 .windows(2)
1242 .map(|w| w[0].distance(w[1]))
1243 .fold(0.0_f64, f64::max);
1244 if whole.met
1245 || whole.fit_error <= step
1246 || branch.closed()
1247 || depth == 0
1248 || branch.points.len() < 2 * FLOOR
1249 {
1250 return Ok(vec![whole]);
1251 }
1252 let middle = branch.points.len() / 2;
1253 let half = |range: core::ops::RangeInclusive<usize>| crate::march::Traced {
1254 points: branch.points[range.clone()].to_vec(),
1255 on_a: branch.on_a[range.clone()].to_vec(),
1256 on_b: branch.on_b[range].to_vec(),
1257 stopped: branch.stopped,
1258 };
1259 let mut pieces = go(a, b, &half(0..=middle), tolerance, depth - 1, tol)?;
1260 pieces.extend(go(
1261 a,
1262 b,
1263 &half(middle..=branch.points.len() - 1),
1264 tolerance,
1265 depth - 1,
1266 tol,
1267 )?);
1268 let worst = pieces.iter().map(|p| p.fit_error).fold(0.0_f64, f64::max);
1271 Ok(if worst < whole.fit_error {
1272 pieces
1273 } else {
1274 vec![whole]
1275 })
1276 }
1277 go(a, b, branch, tolerance, DEPTH, tol)
1278}
1279
1280fn walk_contact(
1289 a: &SurfaceGeometry,
1290 b: &SurfaceGeometry,
1291 fragment: &crate::march::Traced,
1292 already: &[crate::march::Traced],
1293 marching: Marching,
1294 tol: Tolerances,
1295) -> OgeomResult<Option<crate::march::Traced>> {
1296 let middle = fragment.points.len() / 2;
1297 let Some(point) = fragment.points.get(middle).copied() else {
1298 return Ok(None);
1299 };
1300 for traced in already {
1301 let spacing = traced
1304 .points
1305 .windows(2)
1306 .map(|w| w[0].distance(w[1]))
1307 .fold(0.0f64, f64::max);
1308 let near = traced
1309 .points
1310 .iter()
1311 .map(|p| p.distance(point))
1312 .fold(f64::INFINITY, f64::min);
1313 if near <= spacing.mul_add(0.5, marching.chord.max(tol.confusion())) {
1314 return Ok(None);
1315 }
1316 }
1317 let seed = crate::march::Contact {
1318 point,
1319 on_a: fragment.on_a[middle],
1320 on_b: fragment.on_b[middle],
1321 };
1322 Ok(trace_tangential(a, b, seed, marching, tol)
1327 .ok()
1328 .filter(|traced| traced.points.len() >= 4))
1329}
1330
1331fn branch_is_tangential(
1334 a: &SurfaceGeometry,
1335 b: &SurfaceGeometry,
1336 branch: &crate::march::Traced,
1337 tol: Tolerances,
1338) -> OgeomResult<bool> {
1339 use ogeom_geom::Surface as _;
1340 let count = branch.points.len();
1341 if count == 0 {
1342 return Ok(true);
1343 }
1344 for k in 0..5 {
1345 let i = (k * (count - 1)) / 4;
1346 let (ua, va) = branch.on_a[i.min(count - 1)];
1347 let (ub, vb) = branch.on_b[i.min(count - 1)];
1348 let (dau, dav) = a.d1_at(ua, va, tol)?;
1349 let (dbu, dbv) = b.d1_at(ub, vb, tol)?;
1350 let na = dau.cross(dav);
1351 let nb = dbu.cross(dbv);
1352 let (ma, mb) = (na.magnitude(), nb.magnitude());
1353 if ma <= tol.confusion() || mb <= tol.confusion() {
1354 continue;
1355 }
1356 if na.cross(nb).magnitude() / (ma * mb) > 3e-2 {
1363 return Ok(false);
1364 }
1365 }
1366 Ok(true)
1367}
1368
1369#[must_use]
1377pub fn exact_pcurve_of(
1378 curve: &Curve,
1379 surface: &SurfaceGeometry,
1380 tol: Tolerances,
1381) -> Option<PlanarCurve> {
1382 exact_pcurve(curve, curve.domain(), surface, tol)
1383}
1384
1385#[must_use]
1394pub fn exact_pcurve_over(
1395 curve: &Curve,
1396 range: (f64, f64),
1397 surface: &SurfaceGeometry,
1398 tol: Tolerances,
1399) -> Option<PlanarCurve> {
1400 exact_pcurve(curve, range, surface, tol)
1401}
1402
1403fn exact_pcurve(
1413 curve: &Curve,
1414 range: (f64, f64),
1415 surface: &SurfaceGeometry,
1416 tol: Tolerances,
1417) -> Option<PlanarCurve> {
1418 if let Curve::Trimmed(trimmed) = curve
1425 && !trimmed.is_reversed()
1426 {
1427 let window = ogeom_geom::Curve3d::domain(&**trimmed);
1428 let basis = exact_pcurve(trimmed.basis(), range, surface, tol)?;
1429 return ogeom_geom::Trimmed2d::new(basis, window.0, window.1, tol)
1430 .ok()
1431 .map(Into::into);
1432 }
1433 match surface {
1434 SurfaceGeometry::Plane(p) => on_plane(curve, p.plane(), tol),
1435 SurfaceGeometry::Cylinder(c) => on_cylinder(curve, range, c.cylinder(), tol),
1436 SurfaceGeometry::Sphere(s) => on_sphere(curve, range, s.sphere(), tol),
1437 SurfaceGeometry::Torus(t) => on_torus(curve, t.torus(), tol),
1438 SurfaceGeometry::Cone(c) => on_cone(curve, range, c.cone(), tol),
1439 _ => None,
1440 }
1441}
1442
1443fn on_cone(
1452 curve: &Curve,
1453 range: (f64, f64),
1454 cone: ogeom_math::Cone,
1455 tol: Tolerances,
1456) -> Option<PlanarCurve> {
1457 let frame = cone.frame();
1458 let axis_z = frame.z().vector();
1459 let tau = core::f64::consts::TAU;
1460 match curve {
1461 Curve::Circle(c) => {
1462 let circle = c.circle();
1463 if circle.frame().z().vector().cross(axis_z).magnitude() > tol.angular() {
1464 return None;
1465 }
1466 let local = frame.to_local(circle.centre());
1467 if local.x.hypot(local.y) > tol.confusion() {
1468 return None;
1469 }
1470 let expected = cone
1472 .half_angle()
1473 .tan()
1474 .mul_add(local.z, cone.reference_radius());
1475 if (expected - circle.radius()).abs() > tol.confusion() * 10.0 {
1476 return None;
1477 }
1478 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1479 let at = frame.to_local(start);
1480 let phase = at.y.atan2(at.x);
1481 let winding = circle.frame().z().vector().dot(axis_z).signum();
1482 let towards =
1483 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1484 Some(
1485 Line2d::over(
1486 ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1487 0.0,
1488 tau,
1489 )
1490 .ok()?
1491 .into(),
1492 )
1493 }
1494 Curve::Line(line) => {
1495 let axis = line.axis();
1498 let on = |t: f64| {
1499 let p = axis.location + axis.direction.vector() * t;
1500 cone.distance_to(p) <= tol.confusion() * 10.0
1501 };
1502 if !on(0.0) || !on(1.0) || !on(-1.0) {
1503 return None;
1504 }
1505 let (lo, hi) = if range.0.is_finite() && range.1.is_finite() && range.0 != range.1 {
1512 range
1513 } else {
1514 line.domain()
1515 };
1516 let mut local: Option<ogeom_math::Point> = None;
1522 for t in [lo, hi] {
1523 if !t.is_finite() {
1524 continue;
1525 }
1526 let candidate = frame.to_local(axis.location + axis.direction.vector() * t);
1527 if local.is_none_or(|held| candidate.x.hypot(candidate.y) > held.x.hypot(held.y)) {
1528 local = Some(candidate);
1529 }
1530 }
1531 let local = local?;
1532 if local.x.hypot(local.y) <= tol.confusion() {
1533 return None;
1534 }
1535 let u = local.y.atan2(local.x).rem_euclid(tau);
1536 let v_at = |t: f64| {
1540 frame
1541 .to_local(axis.location + axis.direction.vector() * t)
1542 .z
1543 };
1544 let knots = ogeom_math::KnotVector::new(vec![lo, lo, hi, hi], 1).ok()?;
1545 Some(
1546 ogeom_geom::BSpline2d::new(
1547 knots,
1548 vec![Point2::new(u, v_at(lo)), Point2::new(u, v_at(hi))],
1549 tol,
1550 )
1551 .ok()?
1552 .into(),
1553 )
1554 }
1555 _ => None,
1556 }
1557}
1558
1559fn on_torus(curve: &Curve, torus: ogeom_math::Torus, tol: Tolerances) -> Option<PlanarCurve> {
1569 let Curve::Circle(c) = curve else {
1570 return None;
1571 };
1572 let circle = c.circle();
1573 let frame = torus.frame();
1574 let axis_z = frame.z().vector();
1575 let normal = circle.frame().z().vector();
1576 let local = frame.to_local(circle.centre());
1577 let tau = core::f64::consts::TAU;
1578
1579 if normal.cross(axis_z).magnitude() <= tol.angular()
1581 && local.x.hypot(local.y) <= tol.confusion()
1582 {
1583 let sin_v = local.z / torus.minor_radius();
1584 let cos_v = (circle.radius() - torus.major_radius()) / torus.minor_radius();
1585 if (sin_v.hypot(cos_v) - 1.0).abs() > tol.confusion() {
1586 return None;
1587 }
1588 let v = sin_v.atan2(cos_v);
1589 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1590 let at = frame.to_local(start);
1591 let phase = at.y.atan2(at.x);
1592 let winding = normal.dot(axis_z).signum();
1593 let towards =
1594 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1595 return Some(
1596 Line2d::over(
1597 ogeom_math::Axis2::new(Point2::new(phase, v), towards),
1598 0.0,
1599 tau,
1600 )
1601 .ok()?
1602 .into(),
1603 );
1604 }
1605
1606 if (circle.radius() - torus.minor_radius()).abs() <= tol.confusion()
1608 && normal.dot(axis_z).abs() <= tol.angular()
1609 && (local.x.hypot(local.y) - torus.major_radius()).abs() <= tol.confusion()
1610 && local.z.abs() <= tol.confusion()
1611 {
1612 let u = local.y.atan2(local.x);
1613 let radial = frame.x().vector() * u.cos() + frame.y().vector() * u.sin();
1614 let xc = circle.frame().x().vector();
1615 let phase = xc.dot(axis_z).atan2(xc.dot(radial));
1616 let winding = normal.dot(radial.cross(axis_z)).signum();
1617 let towards =
1618 ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, winding), tol).ok()?;
1619 return Some(
1620 Line2d::over(
1621 ogeom_math::Axis2::new(Point2::new(u, phase), towards),
1622 0.0,
1623 tau,
1624 )
1625 .ok()?
1626 .into(),
1627 );
1628 }
1629 None
1630}
1631
1632fn on_plane(curve: &Curve, plane: ogeom_math::Plane, tol: Tolerances) -> Option<PlanarCurve> {
1638 let frame = plane.frame();
1639 let flat = |p: Point| {
1640 let local = frame.to_local(p);
1641 Point2::new(local.x, local.y)
1642 };
1643 let flat_direction = |d: ogeom_math::Direction| {
1644 let tip = flat(frame.origin() + d.vector());
1645 ogeom_math::Direction2::new(tip - flat(frame.origin()), tol).ok()
1646 };
1647 match curve {
1648 Curve::Line(line) => {
1649 let axis = line.axis();
1650 let through = flat(axis.location);
1651 let direction = flat_direction(axis.direction)?;
1652 let (lo, hi) = line.domain();
1653 Some(
1654 Line2d::over(ogeom_math::Axis2::new(through, direction), lo, hi)
1655 .ok()?
1656 .into(),
1657 )
1658 }
1659 Curve::Circle(c) => {
1660 let circle = c.circle();
1661 let frame2 = Frame2::from_axes(
1662 flat(circle.centre()),
1663 flat_direction(circle.frame().x())?,
1664 flat_direction(circle.frame().y())?,
1665 tol,
1666 )
1667 .ok()?;
1668 Some(Circle2d::new(Circle2::new(frame2, circle.radius(), tol).ok()?).into())
1669 }
1670 Curve::Ellipse(e) => {
1671 let ellipse = e.ellipse();
1672 let frame2 = Frame2::from_axes(
1673 flat(ellipse.centre()),
1674 flat_direction(ellipse.frame().x())?,
1675 flat_direction(ellipse.frame().y())?,
1676 tol,
1677 )
1678 .ok()?;
1679 Some(
1680 Ellipse2d::new(
1681 Ellipse2::new(frame2, ellipse.major_radius(), ellipse.minor_radius(), tol)
1682 .ok()?,
1683 )
1684 .into(),
1685 )
1686 }
1687 Curve::BSpline(b) => {
1688 let control = b
1693 .control_points()
1694 .iter()
1695 .map(|w| ogeom_math::Weighted::new(flat((*w).point()), w.weight, tol))
1696 .collect::<Result<Vec<_>, _>>()
1697 .ok()?;
1698 Some(
1699 ogeom_geom::BSpline2d::rational(b.knots().clone(), control)
1700 .ok()?
1701 .into(),
1702 )
1703 }
1704 _ => None,
1705 }
1706}
1707
1708fn on_cylinder(
1715 curve: &Curve,
1716 range: (f64, f64),
1717 cylinder: ogeom_math::Cylinder,
1718 tol: Tolerances,
1719) -> Option<PlanarCurve> {
1720 let axis = cylinder.axis();
1721 let frame = cylinder.frame();
1722 match curve {
1723 Curve::Line(line) => {
1724 let direction = line.axis().direction;
1726 let along = direction.dot(axis.direction);
1727 if !direction.is_parallel(axis.direction, tol) {
1728 return None;
1729 }
1730 let through = line.axis().location;
1731 if (axis.distance_to(through) - cylinder.radius()).abs() > tol.confusion() {
1732 return None;
1733 }
1734 let local = frame.to_local(through);
1735 let u = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
1736 let (lo, hi) = line.domain();
1740 let start = Point2::new(u, local.z);
1741 let towards =
1742 ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, along.signum()), tol)
1743 .ok()?;
1744 Some(
1745 Line2d::over(ogeom_math::Axis2::new(start, towards), lo, hi)
1746 .ok()?
1747 .into(),
1748 )
1749 }
1750 Curve::Circle(c) => {
1751 let circle = c.circle();
1752 if circle
1754 .frame()
1755 .z()
1756 .cross_with(axis.direction.vector())
1757 .magnitude()
1758 > tol.angular()
1759 {
1760 return None;
1761 }
1762 if axis.distance_to(circle.centre()) > tol.confusion() {
1763 return None;
1764 }
1765 if (circle.radius() - cylinder.radius()).abs() > tol.confusion() {
1766 return None;
1767 }
1768 let local = frame.to_local(circle.centre());
1769 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1778 let at = frame.to_local(start);
1779 let phase = at.y.atan2(at.x);
1780 let winding = circle.frame().z().dot(axis.direction).signum();
1781 let towards =
1782 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1783 Some(
1784 Line2d::over(
1785 ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1786 0.0,
1787 core::f64::consts::TAU,
1788 )
1789 .ok()?
1790 .into(),
1791 )
1792 }
1793 Curve::Ellipse(_) => {
1794 use ogeom_geom::Curve3d as _;
1800 let tau = core::f64::consts::TAU;
1801 let local = |t: f64| -> Option<ogeom_math::Point> {
1802 Some(frame.to_local(curve.point_at(t, tol).ok()?))
1803 };
1804 let l0 = local(0.0)?;
1805 let lq = local(tau / 4.0)?;
1806 let lh = local(tau / 2.0)?;
1807 let r = cylinder.radius();
1809 for l in [&l0, &lq, &lh] {
1810 if (l.x.hypot(l.y) - r).abs() > tol.confusion() * 10.0 {
1811 return None;
1812 }
1813 }
1814 let phase = l0.y.atan2(l0.x);
1815 let uq = lq.y.atan2(lq.x);
1818 let step = (uq - phase).rem_euclid(tau);
1819 let winding = if (step - tau / 4.0).abs() < 1e-6 {
1820 1.0
1821 } else if (step - 3.0 * tau / 4.0).abs() < 1e-6 {
1822 -1.0
1823 } else {
1824 return None;
1825 };
1826 let c0 = f64::midpoint(l0.z, lh.z);
1828 let a = (l0.z - lh.z) / 2.0;
1829 let b = lq.z - c0;
1830 let candidate = ogeom_geom::Trig2d::new(
1834 Point2::new(phase, c0),
1835 ogeom_math::Vector2::new(winding, 0.0),
1836 ogeom_math::Vector2::new(0.0, a),
1837 ogeom_math::Vector2::new(0.0, b),
1838 range,
1839 )
1840 .ok()?;
1841 use ogeom_geom::Curve2d as _;
1844 for i in 0..7 {
1845 let t = range.0 + (range.1 - range.0) * (0.09 + 0.13 * f64::from(i)) / 0.91;
1846 let l = local(t)?;
1847 let chart = candidate.point_at(t, tol).ok()?;
1848 let du = (chart.x - l.y.atan2(l.x)).rem_euclid(tau);
1849 if du.min(tau - du) > 1e-9 {
1850 return None;
1851 }
1852 if (chart.y - l.z).abs() > tol.confusion() * 10.0 {
1853 return None;
1854 }
1855 }
1856 Some(PlanarCurve::Trig(candidate))
1857 }
1858 _ => None,
1859 }
1860}
1861
1862fn on_meridian(
1880 curve: &ogeom_geom::CircleCurve,
1881 range: (f64, f64),
1882 sphere: ogeom_math::Sphere,
1883 tol: Tolerances,
1884) -> Option<PlanarCurve> {
1885 let circle = curve.circle();
1886 let sweep = if curve.is_reversed() { -1.0 } else { 1.0 };
1891 let frame = sphere.frame();
1892 let z = frame.z().vector();
1893 if circle.centre().distance(sphere.centre()) > tol.confusion() {
1896 return None;
1897 }
1898 if (circle.radius() - sphere.radius()).abs() > tol.confusion() {
1899 return None;
1900 }
1901 let (cx, cy) = (circle.frame().x().vector(), circle.frame().y().vector());
1902 let (xz, yz) = (cx.dot(z), cy.dot(z));
1903 if xz.hypot(yz) < 1.0 - tol.angular() {
1906 return None;
1907 }
1908 let raw_alpha = yz.atan2(xz);
1909 let w = cx * -raw_alpha.sin() + cy * raw_alpha.cos();
1912 let local = frame.to_local(sphere.centre() + w);
1913 let longitude = local.y.atan2(local.x);
1914
1915 let half = core::f64::consts::PI;
1916 let mid = f64::midpoint(range.0, range.1);
1917 let x_mid = (sweep * mid - raw_alpha).rem_euclid(core::f64::consts::TAU);
1920 let x_mid = if x_mid > half {
1921 x_mid - core::f64::consts::TAU
1922 } else {
1923 x_mid
1924 };
1925 let span = sweep * (range.1 - range.0);
1926 let (mut x0, mut x1) = (x_mid - span / 2.0, x_mid + span / 2.0);
1927 if x0 > x1 {
1928 core::mem::swap(&mut x0, &mut x1);
1929 }
1930 let alpha = sweep.mul_add(mid, -x_mid);
1935 let slack = tol.parametric().max(1e-9);
1936 let (axis_point, towards) = if x0 >= -slack && x1 <= half + slack {
1937 (
1940 Point2::new(longitude, half.mul_add(0.5, alpha)),
1941 ogeom_math::Vector2::new(0.0, -sweep),
1942 )
1943 } else if x0 >= -half - slack && x1 <= slack {
1944 (
1946 Point2::new(longitude + half, half.mul_add(0.5, -alpha)),
1947 ogeom_math::Vector2::new(0.0, sweep),
1948 )
1949 } else {
1950 return None;
1952 };
1953 let towards = ogeom_math::Direction2::new(towards, tol).ok()?;
1954 let margin = (range.1 - range.0) * 0.25;
1955 let line: PlanarCurve = Line2d::over(
1956 ogeom_math::Axis2::new(axis_point, towards),
1957 range.0 - margin,
1958 range.1 + margin,
1959 )
1960 .ok()?
1961 .into();
1962
1963 for k in 0..=4 {
1966 let t = (range.1 - range.0).mul_add(f64::from(k) / 4.0, range.0);
1967 let uv = line.point_at(t, tol).ok()?;
1968 let lifted = ogeom_math::elementary::sphere_at(&sphere, uv.x, uv.y).point;
1969 let want = curve.point_at(t, tol).ok()?;
1970 if lifted.distance(want) > tol.confusion() {
1971 return None;
1972 }
1973 }
1974 Some(line)
1975}
1976
1977fn on_sphere(
1980 curve: &Curve,
1981 range: (f64, f64),
1982 sphere: ogeom_math::Sphere,
1983 tol: Tolerances,
1984) -> Option<PlanarCurve> {
1985 let Curve::Circle(c) = curve else {
1986 return None;
1987 };
1988 let circle = c.circle();
1989 let frame = sphere.frame();
1990 if circle
1993 .frame()
1994 .z()
1995 .cross_with(frame.z().vector())
1996 .magnitude()
1997 > tol.angular()
1998 {
1999 return on_meridian(c, range, sphere, tol);
2000 }
2001 let local = frame.to_local(circle.centre());
2002 if local.x.abs() > tol.confusion() || local.y.abs() > tol.confusion() {
2003 return None;
2004 }
2005 let latitude = (local.z / sphere.radius()).clamp(-1.0, 1.0).asin();
2006 if (circle.radius() - sphere.radius() * latitude.cos()).abs() > tol.confusion() {
2008 return None;
2009 }
2010 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
2011 let at = frame.to_local(start);
2012 let phase = at.y.atan2(at.x);
2013 let winding = circle.frame().z().vector().dot(frame.z().vector()).signum();
2016 let towards = ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
2017 Some(
2018 Line2d::over(
2019 ogeom_math::Axis2::new(Point2::new(phase, latitude), towards),
2020 0.0,
2021 core::f64::consts::TAU,
2022 )
2023 .ok()?
2024 .into(),
2025 )
2026}
2027
2028#[cfg(test)]
2029#[allow(clippy::unwrap_used, clippy::expect_used)]
2030mod tests {
2031 use super::*;
2032 use ogeom_geom::{Curve2d, Curve3d, CylinderSurface, PlaneSurface, SphereSurface};
2033 use ogeom_math::{Cylinder, Direction, Frame, Plane, Sphere, Vector};
2034
2035 const T: Tolerances = Tolerances::millimetres();
2036
2037 fn sphere(centre: Point, radius: f64) -> SurfaceGeometry {
2038 SphereSurface::new(Sphere::centred(centre, radius, T).unwrap()).into()
2039 }
2040
2041 fn cylinder(axis: Vector, radius: f64) -> SurfaceGeometry {
2042 let frame = Frame::new(
2043 Point::ORIGIN,
2044 Direction::new(axis, T).unwrap(),
2045 Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2046 T,
2047 )
2048 .unwrap();
2049 CylinderSurface::new(Cylinder::new(frame, radius, T).unwrap(), (-4.0, 4.0))
2050 .unwrap()
2051 .into()
2052 }
2053
2054 fn plane(origin: Point, normal: Vector) -> SurfaceGeometry {
2055 PlaneSurface::over(
2056 Plane::through(origin, Direction::new(normal, T).unwrap()),
2057 (-6.0, 6.0),
2058 (-6.0, 6.0),
2059 )
2060 .unwrap()
2061 .into()
2062 }
2063
2064 fn assert_same_parameter(
2067 section: &SectionCurve,
2068 surface: &SurfaceGeometry,
2069 pcurve: &PlanarCurve,
2070 samples: usize,
2071 ) {
2072 let (lo, hi) = section.curve.domain();
2073 let (plo, phi) = pcurve.domain();
2074 assert!(
2075 (lo - plo).abs() < 1e-9 && (hi - phi).abs() < 1e-9,
2076 "domains disagree: [{lo}, {hi}] against [{plo}, {phi}]"
2077 );
2078 for i in 0..=samples {
2079 #[allow(clippy::cast_precision_loss)]
2080 let t = lo + (hi - lo) * i as f64 / samples as f64;
2081 let on_curve = section.curve.point_at(t, T).unwrap();
2082 let at = pcurve.point_at(t, T).unwrap();
2083 let lifted = surface.point_at(at.x, at.y, T).unwrap();
2084 assert!(
2085 on_curve.is_equal(lifted, T),
2086 "at t = {t}: curve {on_curve:?}, lifted {lifted:?}"
2087 );
2088 }
2089 }
2090
2091 #[test]
2092 fn an_analytic_pair_comes_back_exact_with_matching_pcurves() {
2093 let drum = cylinder(Vector::Z, 2.0);
2097 let cut = plane(Point::ORIGIN, Vector::X);
2098 let SurfaceIntersection::Along(curves) =
2099 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2100 else {
2101 panic!("a plane through a cylinder meets it along curves");
2102 };
2103 assert_eq!(curves.len(), 2);
2104 for section in &curves {
2105 assert!(section.exact);
2106 assert!((section.tolerance - 0.0).abs() < f64::EPSILON);
2107 let on_a = section.on_a.as_ref().expect("a line has a cylinder pcurve");
2108 let on_b = section.on_b.as_ref().expect("and a plane pcurve");
2109 assert_same_parameter(section, &drum, on_a, 50);
2110 assert_same_parameter(section, &cut, on_b, 50);
2111 }
2112 }
2113
2114 #[test]
2115 fn an_oblique_cut_gives_the_ellipse_a_trig_pcurve_on_the_drum() {
2116 let drum = cylinder(Vector::Z, 2.0);
2120 let angle: f64 = 0.5;
2121 let cut = plane(Point::ORIGIN, Vector::new(0.0, angle.sin(), angle.cos()));
2122 let SurfaceIntersection::Along(curves) =
2123 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2124 else {
2125 panic!("an oblique plane meets the cylinder along its ellipse");
2126 };
2127 assert_eq!(curves.len(), 1);
2128 let section = &curves[0];
2129 assert!(section.exact);
2130 assert!(matches!(section.curve, Curve::Ellipse(_)));
2131 let on_drum = section
2132 .on_a
2133 .as_ref()
2134 .expect("the oblique ellipse now carries its cylinder pcurve");
2135 assert!(
2136 matches!(on_drum, PlanarCurve::Trig(_)),
2137 "the chart trace is trig-affine: {on_drum:?}"
2138 );
2139 assert_same_parameter(section, &drum, on_drum, 60);
2140 let on_plane = section.on_b.as_ref().expect("and its plane pcurve");
2141 assert_same_parameter(section, &cut, on_plane, 60);
2142 }
2143
2144 #[test]
2145 fn a_perpendicular_cut_gives_a_circle_with_a_straight_pcurve() {
2146 let drum = cylinder(Vector::Z, 2.0);
2147 let cut = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2148 let SurfaceIntersection::Along(curves) =
2149 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2150 else {
2151 panic!("expected curves");
2152 };
2153 assert_eq!(curves.len(), 1);
2154 let section = &curves[0];
2155 assert!(section.closed);
2156 assert!(matches!(section.curve, Curve::Circle(_)));
2157 assert!(matches!(
2159 section.on_a.as_ref().unwrap(),
2160 PlanarCurve::Line(_)
2161 ));
2162 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 60);
2163 assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 60);
2164 }
2165
2166 #[test]
2167 fn coaxial_cylinder_and_sphere_give_circles_with_pcurves_on_both() {
2168 let drum = cylinder(Vector::Z, 1.5);
2169 let ball = sphere(Point::ORIGIN, 3.0);
2170 let SurfaceIntersection::Along(curves) =
2171 intersect_surfaces(&drum, &ball, IntersectOptions::default(), T).unwrap()
2172 else {
2173 panic!("expected curves");
2174 };
2175 assert_eq!(curves.len(), 2);
2176 for section in &curves {
2177 assert!(section.exact);
2178 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 40);
2179 assert_same_parameter(section, &ball, section.on_b.as_ref().unwrap(), 40);
2180 }
2181 }
2182
2183 fn torus(origin: Point, axis: Vector, major: f64, minor: f64) -> SurfaceGeometry {
2184 let frame = Frame::new(
2185 origin,
2186 Direction::new(axis, T).unwrap(),
2187 Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2188 T,
2189 )
2190 .unwrap();
2191 ogeom_geom::TorusSurface::new(ogeom_math::Torus::new(frame, major, minor, T).unwrap())
2192 .into()
2193 }
2194
2195 #[test]
2196 fn an_axis_normal_plane_meets_a_torus_in_two_parallels_with_pcurves() {
2197 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2198 let cut = plane(Point::new(0.0, 0.0, 0.3), Vector::Z);
2199 let SurfaceIntersection::Along(curves) =
2200 intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2201 else {
2202 panic!("an axis-normal plane through the tube meets it along curves");
2203 };
2204 assert_eq!(curves.len(), 2);
2205 let spread = 0.5_f64.mul_add(0.5, -(0.3 * 0.3)).sqrt();
2206 let mut radii: Vec<f64> = curves
2207 .iter()
2208 .map(|s| {
2209 let Curve::Circle(c) = &s.curve else {
2210 panic!("a parallel is a circle");
2211 };
2212 c.circle().radius()
2213 })
2214 .collect();
2215 radii.sort_by(|a, b| a.partial_cmp(b).unwrap());
2216 assert!((radii[0] - (2.0 - spread)).abs() < 1e-12);
2217 assert!((radii[1] - (2.0 + spread)).abs() < 1e-12);
2218 for section in &curves {
2219 assert!(section.exact);
2220 assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2221 assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 48);
2222 }
2223 }
2224
2225 #[test]
2226 fn the_plane_a_ball_rolls_on_touches_its_torus_along_the_circle_it_rolled() {
2227 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2232 let cut = plane(Point::new(0.0, 0.0, 0.5), Vector::Z);
2233 let SurfaceIntersection::Along(curves) =
2234 intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2235 else {
2236 panic!("the rolling plane touches along a circle, not at points");
2237 };
2238 assert_eq!(curves.len(), 1);
2239 let Curve::Circle(c) = &curves[0].curve else {
2240 panic!("the tangency is a circle");
2241 };
2242 assert!((c.circle().radius() - 2.0).abs() < 1e-12);
2243 assert_same_parameter(&curves[0], &ring, curves[0].on_a.as_ref().unwrap(), 48);
2244 assert_same_parameter(&curves[0], &cut, curves[0].on_b.as_ref().unwrap(), 48);
2245 }
2246
2247 #[test]
2248 fn a_coaxial_cylinder_meets_a_torus_in_two_parallels_and_touches_in_one() {
2249 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2250 let drum = cylinder(Vector::Z, 2.2);
2251 let SurfaceIntersection::Along(curves) =
2252 intersect_surfaces(&drum, &ring, IntersectOptions::default(), T).unwrap()
2253 else {
2254 panic!("a coaxial cylinder through the tube meets it along curves");
2255 };
2256 assert_eq!(curves.len(), 2);
2257 for section in &curves {
2258 assert!(section.exact);
2259 let Curve::Circle(c) = §ion.curve else {
2260 panic!("a parallel is a circle");
2261 };
2262 assert!((c.circle().radius() - 2.2).abs() < 1e-12);
2263 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 48);
2264 assert_same_parameter(section, &ring, section.on_b.as_ref().unwrap(), 48);
2265 }
2266
2267 let grazing = cylinder(Vector::Z, 2.5);
2269 let SurfaceIntersection::Along(touch) =
2270 intersect_surfaces(&grazing, &ring, IntersectOptions::default(), T).unwrap()
2271 else {
2272 panic!("the grazing cylinder touches along the equator");
2273 };
2274 assert_eq!(touch.len(), 1);
2275 assert_same_parameter(&touch[0], &grazing, touch[0].on_a.as_ref().unwrap(), 48);
2276 assert_same_parameter(&touch[0], &ring, touch[0].on_b.as_ref().unwrap(), 48);
2277 }
2278
2279 #[test]
2280 fn coaxial_tori_are_the_same_or_meet_in_parallels() {
2281 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2282 assert!(matches!(
2283 intersect_surfaces(&ring, &ring.clone(), IntersectOptions::default(), T).unwrap(),
2284 SurfaceIntersection::Same
2285 ));
2286
2287 let lifted = torus(Point::new(0.0, 0.0, 0.5), Vector::Z, 2.0, 0.5);
2290 let SurfaceIntersection::Along(curves) =
2291 intersect_surfaces(&ring, &lifted, IntersectOptions::default(), T).unwrap()
2292 else {
2293 panic!("lifted coaxial tori meet along curves");
2294 };
2295 assert_eq!(curves.len(), 2);
2296 for section in &curves {
2297 assert!(section.exact);
2298 assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2299 assert_same_parameter(section, &lifted, section.on_b.as_ref().unwrap(), 48);
2300 }
2301 }
2302
2303 #[test]
2304 fn a_pair_with_no_closed_form_comes_back_fitted_with_pcurves() {
2305 let a = cylinder(Vector::Z, 1.0);
2307 let b = cylinder(Vector::X, 1.6);
2308 let options = IntersectOptions {
2309 tolerance: 1e-5,
2310 marching: Marching {
2311 chord: 1e-5,
2312 ..Marching::default()
2313 },
2314 };
2315 let SurfaceIntersection::Along(curves) = intersect_surfaces(&a, &b, options, T).unwrap()
2316 else {
2317 panic!("crossed cylinders meet along curves");
2318 };
2319 assert_eq!(curves.len(), 2);
2320 for section in &curves {
2321 assert!(!section.exact);
2322 assert!(section.closed);
2323 assert!(
2324 section.tolerance <= 1e-5 + 1e-4,
2325 "got {}",
2326 section.tolerance
2327 );
2328 assert!(section.on_a.is_some() && section.on_b.is_some());
2329
2330 let (lo, hi) = section.curve.domain();
2332 for i in 0..=200 {
2333 #[allow(clippy::cast_precision_loss)]
2334 let t = lo + (hi - lo) * f64::from(i) / 200.0;
2335 let p = section.curve.point_at(t, T).unwrap();
2336 let (SurfaceGeometry::Cylinder(x), SurfaceGeometry::Cylinder(y)) = (&a, &b) else {
2337 unreachable!()
2338 };
2339 let off = x
2340 .cylinder()
2341 .distance_to(p)
2342 .abs()
2343 .max(y.cylinder().distance_to(p).abs());
2344 assert!(
2345 off <= section.tolerance * 2.0,
2346 "at t = {t} the fitted curve is {off:e} off, tolerance {}",
2347 section.tolerance
2348 );
2349 }
2350 }
2351 }
2352
2353 #[test]
2357 fn a_plane_all_but_along_the_axis_still_meets_a_short_drum() {
2358 let drum = cylinder(Vector::Z, 1.0);
2359 let wall: SurfaceGeometry = PlaneSurface::over(
2360 Plane::through(
2361 Point::new(0.0, 0.6, 0.0),
2362 Direction::new(Vector::new(0.0, 1.0, 1e-4), T).unwrap(),
2363 ),
2364 (-1e9, 1e9),
2365 (-1e9, 1e9),
2366 )
2367 .unwrap()
2368 .into();
2369 let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2370 let SurfaceIntersection::Along(sections) = met else {
2371 panic!("the wall crosses the drum: {met:?}");
2372 };
2373 assert_eq!(sections.len(), 1);
2374 let curve = §ions[0].curve;
2375 let (lo, hi) = curve.domain();
2376 let inside = (0..=100_000).any(|k| {
2377 let p = curve
2378 .point_at(lo + (hi - lo) * f64::from(k) / 100_000.0, T)
2379 .unwrap();
2380 p.z.abs() <= 4.0
2381 });
2382 assert!(inside, "and the section runs through the drum's height");
2383 }
2384
2385 fn on_both(section: &SectionCurve, a: &SurfaceGeometry, b: &SurfaceGeometry) {
2388 let (lo, hi) = section.curve.domain();
2389 for k in 0..=64 {
2390 let p = section
2391 .curve
2392 .point_at(lo + (hi - lo) * f64::from(k) / 64.0, T)
2393 .unwrap();
2394 for surface in [a, b] {
2395 let off = match surface {
2396 SurfaceGeometry::Plane(plane) => plane.plane().signed_distance_to(p).abs(),
2397 SurfaceGeometry::Cylinder(drum) => {
2398 let axis = drum.cylinder().axis();
2399 let rel = p - axis.location;
2400 let d = axis.direction.vector();
2401 ((rel - d * rel.dot(d)).magnitude() - drum.cylinder().radius()).abs()
2402 }
2403 _ => unreachable!("planes and drums only"),
2404 };
2405 assert!(
2406 off <= section.tolerance + 1e-9,
2407 "{p:?} is {off:e} off, stated {:e}",
2408 section.tolerance
2409 );
2410 }
2411 }
2412 }
2413
2414 #[test]
2420 fn a_plane_all_but_along_a_drums_axis_meets_it_in_two_near_lines() {
2421 let drum = cylinder(Vector::Z, 1.0);
2422 let wall: SurfaceGeometry = PlaneSurface::over(
2423 Plane::through(
2424 Point::new(0.0, 0.99, 0.0),
2425 Direction::new(Vector::new(0.0, 1.0, 2e-5), T).unwrap(),
2426 ),
2427 (-1e9, 1e9),
2428 (-1e9, 1e9),
2429 )
2430 .unwrap()
2431 .into();
2432 let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2433 let SurfaceIntersection::Along(sections) = met else {
2434 panic!("the wall crosses the drum: {met:?}");
2435 };
2436 assert_eq!(sections.len(), 2);
2437 for section in §ions {
2438 assert!(section.tolerance > 0.0 && section.tolerance <= 1e-5);
2439 on_both(section, &wall, &drum);
2440 }
2441 }
2442
2443 #[test]
2447 fn drums_all_but_parallel_meet_in_two_near_lines() {
2448 let drill = cylinder(Vector::Z, 1.0);
2449 let frame = Frame::new(
2450 Point::new(1.5, 0.0, 0.0),
2451 Direction::new(Vector::new(5e-5, 0.0, 1.0), T).unwrap(),
2452 Direction::X,
2453 T,
2454 )
2455 .unwrap();
2456 let bore: SurfaceGeometry =
2457 CylinderSurface::new(Cylinder::new(frame, 1.0, T).unwrap(), (-3.0, 3.0))
2458 .unwrap()
2459 .into();
2460 let met = intersect_surfaces(&drill, &bore, IntersectOptions::default(), T).unwrap();
2461 let SurfaceIntersection::Along(sections) = met else {
2462 panic!("the drums cross: {met:?}");
2463 };
2464 assert_eq!(sections.len(), 2);
2465 for section in §ions {
2466 assert!(!section.exact && section.tolerance <= 1e-5);
2467 let (lo, hi) = section.curve.domain();
2468 let (p, q) = (
2469 section.curve.point_at(lo, T).unwrap(),
2470 section.curve.point_at(hi, T).unwrap(),
2471 );
2472 assert!(
2473 (p.z - q.z).abs() > 5.9,
2474 "over the shared height: {p:?} {q:?}"
2475 );
2476 on_both(section, &drill, &bore);
2477 }
2478 }
2479
2480 #[test]
2481 fn exact_lines_are_clipped_to_the_surfaces_extents() {
2482 let drum = cylinder(Vector::Z, 2.0);
2487 let cut = plane(Point::ORIGIN, Vector::X);
2488 let SurfaceIntersection::Along(curves) =
2489 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2490 else {
2491 panic!("expected curves");
2492 };
2493 for section in &curves {
2494 let (lo, hi) = section.curve.domain();
2495 assert!(
2497 hi - lo <= 8.0 + 1e-9,
2498 "the line was not clipped: [{lo}, {hi}]"
2499 );
2500 let start = section.curve.point_at(lo, T).unwrap();
2501 let end = section.curve.point_at(hi, T).unwrap();
2502 assert!(start.z >= -4.0 - 1e-9 && end.z <= 4.0 + 1e-9);
2503 }
2504
2505 let high = plane(Point::new(0.0, 0.0, 10.0), Vector::Z);
2509 assert_eq!(
2510 intersect_surfaces(&drum, &high, IntersectOptions::default(), T).unwrap(),
2511 SurfaceIntersection::Apart
2512 );
2513 }
2514
2515 #[test]
2516 fn the_degenerate_answers_pass_through() {
2517 assert_eq!(
2518 intersect_surfaces(
2519 &sphere(Point::ORIGIN, 1.0),
2520 &sphere(Point::new(5.0, 0.0, 0.0), 1.0),
2521 IntersectOptions::default(),
2522 T
2523 )
2524 .unwrap(),
2525 SurfaceIntersection::Apart
2526 );
2527 assert_eq!(
2528 intersect_surfaces(
2529 &sphere(Point::ORIGIN, 1.0),
2530 &sphere(Point::ORIGIN, 1.0),
2531 IntersectOptions::default(),
2532 T
2533 )
2534 .unwrap(),
2535 SurfaceIntersection::Same
2536 );
2537 assert!(matches!(
2538 intersect_surfaces(
2539 &plane(Point::ORIGIN, Vector::Z),
2540 &sphere(Point::new(0.0, 0.0, 2.0), 2.0),
2541 IntersectOptions::default(),
2542 T
2543 )
2544 .unwrap(),
2545 SurfaceIntersection::Touching(ref p) if p.len() == 1
2546 ));
2547 }
2548
2549 #[test]
2550 fn unusable_options_are_refused() {
2551 let a = sphere(Point::ORIGIN, 1.0);
2552 let b = plane(Point::ORIGIN, Vector::Z);
2553 for tolerance in [0.0, -1.0, f64::NAN] {
2554 let options = IntersectOptions {
2555 tolerance,
2556 ..IntersectOptions::default()
2557 };
2558 assert!(intersect_surfaces(&a, &b, options, T).is_err());
2559 }
2560 }
2561
2562 #[test]
2563 fn a_circle_wound_against_the_axis_keeps_its_pcurve_same_parameter() {
2564 let drum: SurfaceGeometry = CylinderSurface::new(
2572 Cylinder::new(
2573 Frame::new(Point::new(2.0, 2.0, -1.0), Direction::Z, Direction::X, T).unwrap(),
2574 0.5,
2575 T,
2576 )
2577 .unwrap(),
2578 (0.0, 3.0),
2579 )
2580 .unwrap()
2581 .into();
2582 for normal in [Direction::Z, -Direction::Z] {
2583 let frame = Frame::new(Point::ORIGIN, normal, Direction::X, T).unwrap();
2584 let ground: SurfaceGeometry =
2585 PlaneSurface::over(Plane::new(frame), (-4.0, 4.0), (-4.0, 4.0))
2586 .unwrap()
2587 .into();
2588 let met = intersect_surfaces(&ground, &drum, IntersectOptions::default(), T).unwrap();
2589 let SurfaceIntersection::Along(curves) = met else {
2590 panic!("a plane through a cylinder sections it");
2591 };
2592 for sc in &curves {
2593 let pcurve = sc
2594 .on_b
2595 .as_ref()
2596 .expect("a circle on its cylinder has a pcurve");
2597 let (lo, hi) = sc.curve.domain();
2598 for i in 0..8 {
2599 let t = lo + (hi - lo) * f64::from(i) / 8.0;
2600 let p3 = sc.curve.point_at(t, T).unwrap();
2601 let uv = pcurve.point_at(t, T).unwrap();
2602 let lifted = drum
2603 .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2604 .unwrap();
2605 assert!(
2606 p3.distance(lifted) < 1e-9,
2607 "normal {normal:?}, t {t}: pcurve lifts {lifted:?} against {p3:?}"
2608 );
2609 }
2610 }
2611 }
2612 }
2613
2614 #[test]
2620 fn a_meridian_half_has_an_exact_line_for_a_pcurve() {
2621 use ogeom_geom::Surface as _;
2622 let half = core::f64::consts::PI;
2623 for (centre, radius) in [(Point::ORIGIN, 4.0), (Point::new(1.0, -2.0, 0.5), 1.25)] {
2624 let ball = sphere(centre, radius);
2625 let SurfaceGeometry::Sphere(s) = &ball else {
2626 panic!("a sphere surface");
2627 };
2628 for azimuth in [0.0_f64, 0.7, 2.4] {
2631 let normal = Vector::new(-azimuth.sin(), azimuth.cos(), 0.0);
2632 let cut = plane(centre, normal);
2633 let SurfaceIntersection::Along(curves) =
2634 intersect_surfaces(&ball, &cut, IntersectOptions::default(), T).unwrap()
2635 else {
2636 panic!("a plane through the centre meets the ball along a circle");
2637 };
2638 assert_eq!(curves.len(), 1, "one great circle");
2639 let circle = &curves[0].curve;
2640 assert!(curves[0].exact);
2641 assert!(
2643 exact_pcurve_over(circle, circle.domain(), &ball, T).is_none(),
2644 "the whole meridian has no single chart image"
2645 );
2646 for (lo, hi) in [(0.0, half), (half, 2.0 * half), (0.3, half - 0.1)] {
2647 let pcurve = exact_pcurve_over(circle, (lo, hi), &ball, T)
2648 .expect("half a meridian has an exact pcurve");
2649 assert!(
2650 matches!(pcurve, PlanarCurve::Line(_)),
2651 "and it is a straight line in the chart"
2652 );
2653 for i in 0..=16 {
2654 let t = (hi - lo).mul_add(f64::from(i) / 16.0, lo);
2655 let want = circle.point_at(t, T).unwrap();
2656 let uv = pcurve.point_at(t, T).unwrap();
2657 assert!(
2658 uv.y >= -half.mul_add(0.5, 1e-12) && uv.y <= half.mul_add(0.5, 1e-12),
2659 "the latitude stays inside the chart: {}",
2660 uv.y
2661 );
2662 let lifted = ball
2663 .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2664 .unwrap();
2665 assert!(
2666 want.distance(lifted) < 1e-9,
2667 "azimuth {azimuth}, t {t}: {lifted:?} against {want:?}"
2668 );
2669 }
2670 }
2671 assert!(
2674 exact_pcurve_over(circle, (half - 0.2, half + 0.2), &ball, T).is_none(),
2675 "a range across a pole has no one line"
2676 );
2677 let _ = s;
2678 }
2679 }
2680 }
2681
2682 #[test]
2691 fn a_trimmed_curve_carries_its_basis_pcurve_trimmed_the_same_way() {
2692 use ogeom_geom::TrimmedCurve;
2693 let drum = cylinder(Vector::Z, 2.0);
2694 let ground = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2695 let SurfaceIntersection::Along(curves) =
2697 intersect_surfaces(&drum, &ground, IntersectOptions::default(), T).unwrap()
2698 else {
2699 panic!("a plane across a cylinder meets it in a circle");
2700 };
2701 let whole = curves[0].curve.clone();
2702 let (lo, hi) = whole.domain();
2703 let quarter: Curve = TrimmedCurve::new(whole.clone(), lo + 0.3, lo + (hi - lo) / 4.0, T)
2704 .unwrap()
2705 .into();
2706
2707 for surface in [&drum, &ground] {
2708 let full = exact_pcurve_of(&whole, surface, T).expect("the whole circle has one");
2709 let part = exact_pcurve_of(&quarter, surface, T).expect("and so does a quarter of it");
2710 let (a, b) = quarter.domain();
2713 for i in 0..=8 {
2714 let t = (b - a).mul_add(f64::from(i) / 8.0, a);
2715 let (whole_at, part_at) =
2716 (full.point_at(t, T).unwrap(), part.point_at(t, T).unwrap());
2717 assert!(
2718 whole_at.distance(part_at) < 1e-12,
2719 "the trim carries the basis: {whole_at:?} against {part_at:?}"
2720 );
2721 let lifted = surface
2723 .point_at(part_at.x.rem_euclid(core::f64::consts::TAU), part_at.y, T)
2724 .or_else(|_| surface.point_at(part_at.x, part_at.y, T))
2725 .unwrap();
2726 assert!(
2727 lifted.distance(quarter.point_at(t, T).unwrap()) < 1e-9,
2728 "same-parameter, still"
2729 );
2730 }
2731 }
2732 }
2733 #[test]
2734 fn a_far_stated_ruling_reads_its_angle_on_the_used_nappe() {
2735 use ogeom_geom::ConeSurface;
2736 let cone =
2744 ogeom_math::Cone::new(Frame::WORLD, 24.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2745 let surface: SurfaceGeometry = ConeSurface::new(cone, (-1e5, 1e5)).unwrap().into();
2746 let u_true = 0.01_f64;
2747 let radial = Vector::new(u_true.cos(), u_true.sin(), 0.0);
2748 let direction =
2751 Direction::new((radial + Vector::new(0.0, 0.0, 1.0)) / 2f64.sqrt(), T).unwrap();
2752 let far = -7.0e5;
2753 let origin = Point::ORIGIN + radial * 24.0 + direction.vector() * far;
2754 let line = ogeom_geom::LineCurve::over(
2755 ogeom_math::Axis::new(origin, direction),
2756 far.abs() - 1.0,
2757 far.abs() + 1.0,
2758 )
2759 .unwrap();
2760 let curve: Curve = line.into();
2761 let range = ogeom_geom::Curve3d::domain(&curve);
2762 let pcurve = exact_pcurve_over(&curve, range, &surface, T).expect("a ruling inverts");
2763 let at = pcurve.point_at(range.0, T).unwrap();
2764 let tau = core::f64::consts::TAU;
2765 let gap = (at.x - u_true)
2766 .rem_euclid(tau)
2767 .min(tau - (at.x - u_true).rem_euclid(tau));
2768 assert!(
2769 gap < 1e-6,
2770 "the ruling's chart angle must be the used side's: got u {} against {u_true}",
2771 at.x
2772 );
2773 }
2774}