1use crate::madd::Madd;
8use std::cell::RefCell;
9use std::f64::consts::{FRAC_PI_2, TAU};
10
11use crate::MathError;
12use crate::aabb::Aabb3;
13use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
14use crate::frame::Frame3;
15use crate::nurbs::curve::NurbsCurve;
16use crate::nurbs::fitting::interpolate;
17use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
18use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
19use crate::tolerance::Tolerance;
20use crate::vec::{Point3, Vec3};
21
22mod cover;
23mod section_fit;
24use section_fit::{crosses_at, fit_section, settle_on_section};
25pub use section_fit::{point_off_surface, spline_off_surface};
26
27#[derive(Debug, Clone)]
29pub enum ExactIntersectionCurve {
30 Circle(Circle3D),
32 Ellipse(Ellipse3D),
34 Points(Vec<Point3>),
36}
37
38#[derive(Debug, Clone)]
40#[non_exhaustive]
41pub enum PlaneSection {
42 Circle(Circle3D),
44 Ellipse(Ellipse3D),
46 Line {
50 line: Line3D,
52 ray: bool,
54 },
55 Point(Point3),
57 Points(Vec<Point3>),
59 Parabola(Parabola3D),
61 Hyperbola(Hyperbola3D),
64}
65
66impl From<ExactIntersectionCurve> for PlaneSection {
67 fn from(curve: ExactIntersectionCurve) -> Self {
68 match curve {
69 ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
70 ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
71 ExactIntersectionCurve::Points(points) => Self::Points(points),
72 }
73 }
74}
75
76pub fn exact_plane_section(
91 surface: AnalyticSurface<'_>,
92 normal: Vec3,
93 d: f64,
94) -> Result<Vec<PlaneSection>, MathError> {
95 match surface {
96 AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
97 return plane_cylinder_rulings(cyl, normal, d);
98 }
99 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
100 return plane_cone_apex_rulings(cone, normal);
101 }
102 AnalyticSurface::Cone(cone) => {
103 if let Some(open) = plane_cone_open_section(cone, normal, d)? {
104 return Ok(open);
105 }
106 }
107 AnalyticSurface::Sphere(sphere) => {
108 let h = dot_np(normal, sphere.center()) - d;
109 let r = sphere.radius();
110 if (r - h.abs()).abs() <= TOUCH * r {
111 return Ok(vec![PlaneSection::Point(Point3::new(
112 h.madd(-normal.x(), sphere.center().x()),
113 h.madd(-normal.y(), sphere.center().y()),
114 h.madd(-normal.z(), sphere.center().z()),
115 ))]);
116 }
117 }
118 AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
119 }
120 Ok(exact_plane_analytic(surface, normal, d)?
121 .into_iter()
122 .map(PlaneSection::from)
123 .collect())
124}
125
126const PARABOLIC: f64 = 1e-12;
129
130const HYPERBOLIC: f64 = 1e-6;
134
135#[allow(clippy::many_single_char_names)]
142fn plane_cone_open_section(
143 cone: &ConicalSurface,
144 normal: Vec3,
145 d: f64,
146) -> Result<Option<Vec<PlaneSection>>, MathError> {
147 let axis = cone.axis();
148 let c = normal.dot(axis);
149 let p2 = c.madd(-c, 1.0).max(0.0);
150 let p = p2.sqrt();
151 let rise = cone.half_angle().sin();
152 let k = rise * rise;
153 let a_coeff = p2 - k;
154 let eccentric = a_coeff / k;
155 let m = axis - normal * c;
156 let m_len = m.length();
157 if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
158 {
159 return Ok(None);
160 }
161 let e1 = m * (1.0 / m_len);
162 let e2 = normal.cross(e1);
163 let apex = cone.apex();
164 let e = d - dot_np(normal, apex);
165 let origin = apex + normal * e;
166 let real = |s: f64| e.madd(c, s * p) >= 0.0;
169 let holds = |q: Point3| {
172 let w = q - apex;
173 let reach = w.length();
174 reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
175 };
176 if eccentric <= PARABOLIC {
177 let ecp = e * c * p;
180 let vertex_s = -e * (c * c - k) / (2.0 * c * p);
181 let focal = ecp.abs() / (2.0 * k);
182 if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
183 return Ok(None);
184 }
185 if !real(vertex_s) {
186 return Ok(Some(Vec::new()));
187 }
188 let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
189 if ![0.0, focal, -focal]
190 .iter()
191 .all(|&t| holds(parabola.evaluate(t)))
192 {
193 return Ok(None);
194 }
195 return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
196 }
197 let centre_s = -e * c * p / a_coeff;
200 let rhs = e * e * k * (1.0 - k) / a_coeff;
201 let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
202 if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
203 return Ok(None);
204 }
205 let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
206 let hyperbola = Hyperbola3D::with_axes(
207 origin + e1 * centre_s,
208 real_axis,
209 imaginary_axis,
210 toward,
211 e2,
212 )?;
213 if ![0.0, 1.0, -1.0]
214 .iter()
215 .all(|&t| holds(hyperbola.evaluate(t)))
216 {
217 return Ok(None);
218 }
219 Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
220}
221
222const TOUCH: f64 = 4.0 * f64::EPSILON;
225
226fn plane_cylinder_rulings(
229 cyl: &CylindricalSurface,
230 normal: Vec3,
231 d: f64,
232) -> Result<Vec<PlaneSection>, MathError> {
233 let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
236 let amp = a.hypot(b);
237 if amp < 1e-12 {
238 return Ok(vec![]);
239 }
240 let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
241 if ratio.abs() > 1.0 + TOUCH {
242 return Ok(vec![]);
243 }
244 let phi = b.atan2(a);
245 let spread = ratio.clamp(-1.0, 1.0).acos();
246 let at = if ratio.abs() >= 1.0 - TOUCH {
247 vec![phi + spread]
248 } else {
249 vec![phi + spread, phi - spread]
250 };
251 at.into_iter()
252 .map(|u| {
253 Ok(PlaneSection::Line {
254 line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
255 ray: false,
256 })
257 })
258 .collect()
259}
260
261fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
263 let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
264 (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
265}
266
267fn plane_cone_apex_rulings(
271 cone: &ConicalSurface,
272 normal: Vec3,
273) -> Result<Vec<PlaneSection>, MathError> {
274 let (sin_a, cos_a) = cone.half_angle().sin_cos();
277 let a = cos_a * normal.dot(cone.x_axis());
278 let b = cos_a * normal.dot(cone.y_axis());
279 let c = sin_a * normal.dot(cone.axis());
280 let amp = a.hypot(b);
281 let apex = cone.apex();
282 if amp < 1e-12 * c.abs().max(1.0) {
283 return Ok(vec![PlaneSection::Point(apex)]);
284 }
285 let ratio = -c / amp;
286 if ratio.abs() > 1.0 + TOUCH {
287 return Ok(vec![PlaneSection::Point(apex)]);
288 }
289 let phi = b.atan2(a);
290 let spread = ratio.clamp(-1.0, 1.0).acos();
291 let at = if ratio.abs() >= 1.0 - TOUCH {
292 vec![phi + spread]
293 } else {
294 vec![phi + spread, phi - spread]
295 };
296 at.into_iter()
297 .map(|u| {
298 Ok(PlaneSection::Line {
299 line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
300 ray: true,
301 })
302 })
303 .collect()
304}
305
306pub fn exact_plane_analytic(
321 surface: AnalyticSurface<'_>,
322 plane_normal: Vec3,
323 plane_d: f64,
324) -> Result<Vec<ExactIntersectionCurve>, MathError> {
325 exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
326}
327
328pub fn exact_plane_analytic_reaching(
336 surface: AnalyticSurface<'_>,
337 plane_normal: Vec3,
338 plane_d: f64,
339 reach: f64,
340) -> Result<Vec<ExactIntersectionCurve>, MathError> {
341 match surface {
342 AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
343 AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
344 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
345 AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
346 AnalyticSurface::Torus(torus) => {
347 if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
348 return Ok(circles);
349 }
350 if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
351 return Ok(loops
352 .into_iter()
353 .map(ExactIntersectionCurve::Points)
354 .collect());
355 }
356 let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
358 Ok(chains
359 .into_iter()
360 .map(ExactIntersectionCurve::Points)
361 .collect())
362 }
363 }
364}
365
366fn exact_plane_torus(
380 torus: &ToroidalSurface,
381 normal: Vec3,
382 d: f64,
383) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
384 let len = normal.length();
385 let n = normal.normalize()?;
386 let d = d / len;
387 let axis = torus.z_axis();
388 let center = torus.center();
389 let (big, small) = (torus.major_radius(), torus.minor_radius());
390 let height = d - dot_np(n, center);
391 let along = n.dot(axis);
392 if along.abs() > 1.0 - 1e-10 {
393 if height.abs() >= small - 1e-10 * small {
394 if height.abs() > small + 1e-10 * small {
395 return Ok(Some(Vec::new()));
396 }
397 if big <= 1e-10 * small
404 || axis.cross(n).length() > 1e-12
405 || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
406 {
407 return Ok(None);
408 }
409 let middle = center + n * height;
410 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
411 middle, n, big,
412 )?)]));
413 }
414 let reach = small.madd(small, -(height * height)).sqrt();
415 if big - reach <= 1e-10 * big {
416 return Ok(None);
417 }
418 let middle = center + n * height;
419 return Ok(Some(vec![
420 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
421 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
422 ]));
423 }
424 if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
425 let out = axis.cross(n).normalize()?;
426 return Ok(Some(vec![
427 ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
428 ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
429 ]));
430 }
431 Ok(None)
432}
433
434fn exact_plane_cylinder(
440 cyl: &CylindricalSurface,
441 normal: Vec3,
442 d: f64,
443) -> Result<Vec<ExactIntersectionCurve>, MathError> {
444 let axis = cyl.axis();
445 let cos_theta = normal.dot(axis).abs();
446 let r = cyl.radius();
447
448 if cos_theta < 1e-10 {
449 return Ok(vec![]);
452 }
453
454 let n_dot_axis = normal.dot(axis);
457 let n_dot_origin = dot_np(normal, cyl.origin());
458 let t = (d - n_dot_origin) / n_dot_axis;
459 let center_on_axis = Point3::new(
460 cyl.origin().x() + t * axis.x(),
461 cyl.origin().y() + t * axis.y(),
462 cyl.origin().z() + t * axis.z(),
463 );
464
465 if cos_theta > 1.0 - 1e-10 {
466 let circle = Circle3D::new(center_on_axis, normal, r)?;
468 Ok(vec![ExactIntersectionCurve::Circle(circle)])
469 } else {
470 let semi_minor = r;
474 let semi_major = r / cos_theta;
475
476 let axis_proj = Vec3::new(
480 axis.x() - n_dot_axis * normal.x(),
481 axis.y() - n_dot_axis * normal.y(),
482 axis.z() - n_dot_axis * normal.z(),
483 );
484 let u_axis = axis_proj.normalize()?;
485 let v_axis = normal.cross(u_axis);
486
487 let ellipse = Ellipse3D::with_axes(
488 center_on_axis,
489 normal,
490 semi_major,
491 semi_minor,
492 u_axis,
493 v_axis,
494 )?;
495 Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
496 }
497}
498
499fn exact_plane_sphere(
503 sphere: &SphericalSurface,
504 normal: Vec3,
505 d: f64,
506) -> Result<Vec<ExactIntersectionCurve>, MathError> {
507 let h = dot_np(normal, sphere.center()) - d;
508 let r = sphere.radius();
509
510 if r - h.abs() <= TOUCH * r {
513 return Ok(vec![]);
514 }
515
516 let circle_r = (r.madd(r, -(h * h))).sqrt();
517 let circle_center = Point3::new(
518 h.madd(-normal.x(), sphere.center().x()),
519 h.madd(-normal.y(), sphere.center().y()),
520 h.madd(-normal.z(), sphere.center().z()),
521 );
522
523 let circle = Circle3D::new(circle_center, normal, circle_r)?;
524 Ok(vec![ExactIntersectionCurve::Circle(circle)])
525}
526
527pub fn exact_sphere_sphere(
539 s1: &SphericalSurface,
540 s2: &SphericalSurface,
541) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
542 let delta = s2.center() - s1.center();
543 let d = delta.length();
544 let (r1, r2) = (s1.radius(), s2.radius());
545 let scale = r1.max(r2);
546 if d <= 1e-12 * scale {
547 return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
549 }
550 let normal = delta * (1.0 / d);
551 let (centre, toward, r_small, r_big) = if r1 <= r2 {
554 (s1.center(), normal, r1, r2)
555 } else {
556 (s2.center(), -normal, r2, r1)
557 };
558 let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
559 if along.abs() > r_small - 1e-10 * scale.max(1.0) {
560 return Ok(Some(Vec::new()));
561 }
562 let radius = r_small.madd(r_small, -(along * along)).sqrt();
563 let circle = Circle3D::new(centre + toward * along, normal, radius)?;
564 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
565}
566
567fn exact_plane_cone(
576 cone: &ConicalSurface,
577 normal: Vec3,
578 d: f64,
579 reach: f64,
580) -> Result<Vec<ExactIntersectionCurve>, MathError> {
581 let axis = cone.axis();
582 let cos_theta = normal.dot(axis).abs();
583 let half_angle = cone.half_angle();
584
585 if cos_theta > 1.0 - 1e-10 {
586 let n_dot_axis = normal.dot(axis);
589 let n_dot_apex = dot_np(normal, cone.apex());
590 let t = (d - n_dot_apex) / n_dot_axis;
591
592 if t.abs() < 1e-10 {
597 return Ok(vec![]);
598 }
599
600 let center = Point3::new(
601 cone.apex().x() + t * axis.x(),
602 cone.apex().y() + t * axis.y(),
603 cone.apex().z() + t * axis.z(),
604 );
605 let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
609 if circle_r < 1e-15 {
610 return Ok(vec![]);
611 }
612
613 let circle = Circle3D::new(center, normal, circle_r)?;
614 return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
615 }
616
617 let c = normal.dot(axis);
629 let p2 = (1.0 - c * c).max(0.0);
630 let p = p2.sqrt();
631 let k = half_angle.sin().powi(2);
632 let a_coeff = p2 - k;
633
634 let m = Vec3::new(
636 axis.x() - c * normal.x(),
637 axis.y() - c * normal.y(),
638 axis.z() - c * normal.z(),
639 );
640 let m_len = m.length();
641 if m_len < 1e-12 {
642 let chains = sample_plane_cone(cone, normal, d, reach)?;
645 return Ok(chains
646 .into_iter()
647 .map(ExactIntersectionCurve::Points)
648 .collect());
649 }
650 let e1 = m * (1.0 / m_len);
651 let e2 = normal.cross(e1);
652 let apex = cone.apex();
653 let e = d - dot_np(normal, apex);
654
655 if a_coeff < -1e-9 {
658 let abs_a = -a_coeff; if e * c < 0.0 {
665 return Ok(vec![]);
666 }
667 let s_c = e * c * p / abs_a;
670 let rhs = e * e * k * (1.0 - k) / abs_a;
671 if rhs <= 0.0 {
672 return Ok(vec![]);
673 }
674 let semi_s = (rhs / abs_a).sqrt(); let semi_t = (rhs / k).sqrt(); if semi_s < 1e-12 || semi_t < 1e-12 {
677 return Ok(vec![]);
678 }
679 let center = apex + normal * e + e1 * s_c;
680 let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
681 (semi_s, semi_t, e1, e2)
682 } else {
683 (semi_t, semi_s, e2, e1)
684 };
685 let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
686 return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
687 }
688
689 let chains = sample_plane_cone(cone, normal, d, reach)?;
692 Ok(chains
693 .into_iter()
694 .map(ExactIntersectionCurve::Points)
695 .collect())
696}
697
698#[allow(clippy::many_single_char_names)]
713pub fn plane_cone_conic_arc(
714 cone: &ConicalSurface,
715 normal: Vec3,
716 d: f64,
717 from: Point3,
718 to: Point3,
719) -> Result<Option<NurbsCurve>, MathError> {
720 let len = normal.length();
721 if len < 1e-15 {
722 return Err(MathError::ZeroVector);
723 }
724 let (normal, d) = (normal * (1.0 / len), d / len);
725 let axis = cone.axis();
726 let c = normal.dot(axis);
727 let p2 = (1.0 - c * c).max(0.0);
728 let p = p2.sqrt();
729 let k = cone.half_angle().sin().powi(2);
730 let a_coeff = p2 - k;
731 let m = Vec3::new(
732 axis.x() - c * normal.x(),
733 axis.y() - c * normal.y(),
734 axis.z() - c * normal.z(),
735 );
736 let m_len = m.length();
737 if m_len < 1e-12 || a_coeff < -1e-9 {
738 return Ok(None);
739 }
740 let e1 = m * (1.0 / m_len);
741 let e2 = normal.cross(e1);
742 let apex = cone.apex();
743 let e = d - dot_np(normal, apex);
744 let origin = apex + normal * e;
745 let plane_st = |q: Point3| {
746 let w = q - origin;
747 (w.dot(e1), w.dot(e2))
748 };
749 let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
750 let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
751 if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
752 return Ok(None);
753 }
754 let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
755 let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
756 let (control, weights) = if a_coeff.abs() <= 1e-9 {
757 let lin = 2.0 * e * c * p;
759 if lin.abs() < 1e-12 * scale {
760 return Ok(None);
761 }
762 let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
763 if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
764 || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
765 {
766 return Ok(None);
767 }
768 let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
769 (vec![from, mid, to], vec![1.0; 3])
770 } else {
771 let s_c = -e * c * p / a_coeff;
773 let r = e * e * k * (1.0 - k) / a_coeff;
774 if r <= 0.0 {
775 return Ok(None);
776 }
777 let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
778 let (x0, x1) = (s0 - s_c, s1 - s_c);
779 if x0 * x1 <= 0.0 {
780 return Ok(None);
781 }
782 let side = x0.signum();
783 let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
784 let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
785 if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
786 return Ok(None);
787 }
788 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
789 let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
790 let mut control = vec![from];
791 let mut weights = vec![1.0];
792 for i in 0..pieces {
793 #[allow(clippy::cast_precision_loss)]
794 let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
795 let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
796 let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
797 let w = half.cosh();
798 control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
799 weights.push(w);
800 control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
801 weights.push(1.0);
802 }
803 (control, weights)
804 };
805 let pieces = (control.len() - 1) / 2;
806 let mut knots = vec![0.0; 3];
807 for i in 1..pieces {
808 #[allow(clippy::cast_precision_loss)]
809 knots.extend([i as f64; 2]);
810 }
811 #[allow(clippy::cast_precision_loss)]
812 knots.extend([pieces as f64; 3]);
813 let curve = NurbsCurve::new(2, knots, control, weights)?;
814 let (sin_a, cos_a) = cone.half_angle().sin_cos();
819 let off_cone = |q: Point3| {
820 let w = q - apex;
821 let h = w.dot(axis);
822 (w - axis * h)
823 .length()
824 .madd(sin_a, -(h.abs() * cos_a))
825 .abs()
826 };
827 for i in 0..pieces {
828 for f in [0.25, 0.5, 0.75] {
829 #[allow(clippy::cast_precision_loss)]
830 if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
831 return Ok(None);
832 }
833 }
834 }
835 Ok(Some(curve))
836}
837
838#[derive(Clone, Copy)]
840pub enum AnalyticSurface<'a> {
841 Cylinder(&'a CylindricalSurface),
843 Cone(&'a ConicalSurface),
845 Sphere(&'a SphericalSurface),
847 Torus(&'a ToroidalSurface),
849}
850
851fn dot_np(n: Vec3, p: Point3) -> f64 {
853 n.dot(Vec3::new(p.x(), p.y(), p.z()))
854}
855
856pub fn intersect_plane_analytic(
864 surface: AnalyticSurface<'_>,
865 normal: Vec3,
866 d: f64,
867) -> Result<Vec<IntersectionCurve>, MathError> {
868 match surface {
869 AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
870 AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
871 AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
872 AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
873 }
874}
875
876pub fn sample_plane_analytic(
887 surface: AnalyticSurface<'_>,
888 normal: Vec3,
889 d: f64,
890) -> Result<Vec<Vec<Point3>>, MathError> {
891 match surface {
892 AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
893 AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
894 AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
895 AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
896 }
897}
898
899#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
901fn sample_plane_cylinder(
902 cyl: &CylindricalSurface,
903 normal: Vec3,
904 d: f64,
905) -> Result<Vec<Vec<Point3>>, MathError> {
906 let n_samples = 64_usize;
907 let mut points = Vec::with_capacity(n_samples + 1);
908
909 for i in 0..=n_samples {
910 let u = TAU * (i as f64) / (n_samples as f64);
911 let base = cyl.evaluate(u, 0.0);
912 let n_dot_axis = normal.dot(cyl.axis());
913 let n_dot_base = dot_np(normal, base);
914
915 if n_dot_axis.abs() < 1e-12 {
916 if (n_dot_base - d).abs() < 1e-6 {
917 points.push(base);
918 }
919 } else {
920 let v = (d - n_dot_base) / n_dot_axis;
921 if v.abs() <= 100.0 {
922 points.push(cyl.evaluate(u, v));
923 }
924 }
925 }
926
927 if points.len() < 2 {
928 Ok(vec![])
929 } else {
930 Ok(vec![points])
931 }
932}
933
934#[allow(clippy::cast_precision_loss)]
936fn sample_plane_sphere(
937 sphere: &SphericalSurface,
938 normal: Vec3,
939 d: f64,
940) -> Result<Vec<Vec<Point3>>, MathError> {
941 let h = dot_np(normal, sphere.center()) - d;
942 let r = sphere.radius();
943
944 if h.abs() > r - 1e-10 {
945 return Ok(vec![]);
946 }
947
948 let circle_r = (r.madd(r, -(h * h))).sqrt();
949 let circle_center = Point3::new(
950 h.madd(-normal.x(), sphere.center().x()),
951 h.madd(-normal.y(), sphere.center().y()),
952 h.madd(-normal.z(), sphere.center().z()),
953 );
954
955 let basis = Frame3::from_normal(circle_center, normal)?;
956 let u_dir = basis.x;
957 let v_dir = basis.y;
958
959 let n_samples = 64_usize;
960 let mut points = Vec::with_capacity(n_samples + 1);
961
962 for i in 0..=n_samples {
963 let theta = TAU * (i as f64) / (n_samples as f64);
964 let (sin_t, cos_t) = theta.sin_cos();
965 points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
966 }
967
968 Ok(vec![points])
969}
970
971#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
983fn sample_plane_cone(
984 cone: &ConicalSurface,
985 normal: Vec3,
986 d: f64,
987 reach: f64,
988) -> Result<Vec<Vec<Point3>>, MathError> {
989 let apex = cone.apex();
990 let n_dot_apex = dot_np(normal, apex);
991 let e = d - n_dot_apex;
992
993 let n_samples = 512_usize;
997 let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
998 let mut v_min = f64::INFINITY;
999 for i in 0..n_samples {
1000 let u = TAU * (i as f64) / (n_samples as f64);
1001 let g = cone.evaluate(u, 1.0) - apex;
1002 let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
1003 if n_dot_g.abs() < 1e-12 {
1004 vs.push(None);
1005 continue;
1006 }
1007 let v = e / n_dot_g;
1008 if v >= -1e-12 {
1009 let v = v.max(0.0);
1010 v_min = v_min.min(v);
1011 vs.push(Some(v));
1012 } else {
1013 vs.push(None);
1014 }
1015 }
1016
1017 if !v_min.is_finite() {
1018 return Ok(Vec::new());
1019 }
1020
1021 let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1030
1031 let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1034
1035 let point_at = |u: f64, v: f64| -> Point3 {
1036 let g = cone.evaluate(u, 1.0) - apex;
1037 apex + g * v
1038 };
1039 #[allow(clippy::cast_precision_loss)]
1040 let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1041 let n_dot_g_at = |u: f64| -> f64 {
1042 let g = cone.evaluate(u, 1.0) - apex;
1043 normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1044 };
1045
1046 if kept.iter().all(Option::is_some) {
1047 let mut pts: Vec<Point3> = kept
1049 .iter()
1050 .enumerate()
1051 .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1052 .collect();
1053 if let Some(&first) = pts.first() {
1054 pts.push(first);
1055 }
1056 return Ok(vec![pts]);
1057 }
1058
1059 let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1068 let Some(v_end) = kept[i_end] else {
1069 return Vec::new();
1070 };
1071 let u_end = u_of(i_end);
1072 #[allow(clippy::cast_precision_loss)]
1073 let pitch = TAU / (n_samples as f64);
1074 let u_next = if forward {
1075 u_end + pitch
1076 } else {
1077 u_end - pitch
1078 };
1079 let target = e / v_max;
1080 let h_end = n_dot_g_at(u_end) - target;
1081 let h_next = n_dot_g_at(u_next) - target;
1082 if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1083 return Vec::new();
1084 }
1085 let (mut lo, mut hi) = (u_end, u_next);
1086 for _ in 0..60 {
1087 let mid = f64::midpoint(lo, hi);
1088 if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1089 lo = mid;
1090 } else {
1091 hi = mid;
1092 }
1093 }
1094 let u_star = f64::midpoint(lo, hi);
1095 let tail_n = 8_usize;
1096 (1..=tail_n)
1097 .filter_map(|k| {
1098 #[allow(clippy::cast_precision_loss)]
1099 let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1100 let ng = n_dot_g_at(u);
1101 if ng.abs() < 1e-12 {
1102 return None;
1103 }
1104 let v = e / ng;
1105 (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1106 })
1107 .collect()
1108 };
1109
1110 let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1113 let mut chains: Vec<Vec<Point3>> = Vec::new();
1114 let mut run: Vec<usize> = Vec::new();
1115 let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1116 if run.len() >= 2 {
1117 let first = run[0];
1118 let last = run[run.len() - 1];
1119 let mut pts: Vec<Point3> = tail(first, false, &kept);
1120 pts.reverse();
1121 pts.extend(
1122 run.iter()
1123 .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1124 );
1125 pts.extend(tail(last, true, &kept));
1126 chains.push(pts);
1127 }
1128 run.clear();
1129 };
1130 for k in 0..n_samples {
1131 let idx = (gap + k) % n_samples;
1132 if kept[idx].is_some() {
1133 run.push(idx);
1134 } else {
1135 flush(&mut run, &mut chains);
1136 }
1137 }
1138 flush(&mut run, &mut chains);
1139 Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1140}
1141
1142#[allow(clippy::unnecessary_wraps)] fn sample_plane_torus(
1148 torus: &ToroidalSurface,
1149 normal: Vec3,
1150 d: f64,
1151) -> Result<Vec<Vec<Point3>>, MathError> {
1152 Ok(plane_torus_loops(torus, normal, d, 128)
1153 .into_iter()
1154 .map(|run| run.into_iter().map(|p| p.point).collect())
1155 .collect())
1156}
1157
1158#[allow(clippy::cast_precision_loss)]
1168pub fn intersect_plane_cylinder(
1169 cyl: &CylindricalSurface,
1170 normal: Vec3,
1171 d: f64,
1172) -> Result<Vec<IntersectionCurve>, MathError> {
1173 let n_samples = 64_usize;
1174 let mut points_3d = Vec::new();
1175 let mut ipoints = Vec::new();
1176
1177 for i in 0..=n_samples {
1178 let u = TAU * (i as f64) / (n_samples as f64);
1179 let base = cyl.evaluate(u, 0.0);
1182 let n_dot_axis = normal.dot(cyl.axis());
1183 let n_dot_base = dot_np(normal, base);
1184
1185 if n_dot_axis.abs() < 1e-12 {
1186 if (n_dot_base - d).abs() < 1e-6 {
1188 let pt = base;
1189 points_3d.push(pt);
1190 ipoints.push(IntersectionPoint {
1191 point: pt,
1192 param1: (u, 0.0),
1193 param2: (0.0, 0.0),
1194 });
1195 }
1196 } else {
1197 let v = (d - n_dot_base) / n_dot_axis;
1198 if v.abs() <= 100.0 {
1200 let pt = cyl.evaluate(u, v);
1201 points_3d.push(pt);
1202 ipoints.push(IntersectionPoint {
1203 point: pt,
1204 param1: (u, v),
1205 param2: (0.0, 0.0),
1206 });
1207 }
1208 }
1209 }
1210
1211 build_curves_from_points(&points_3d, ipoints)
1212}
1213
1214#[allow(clippy::cast_precision_loss)]
1223pub fn intersect_plane_sphere(
1224 sphere: &SphericalSurface,
1225 normal: Vec3,
1226 d: f64,
1227) -> Result<Vec<IntersectionCurve>, MathError> {
1228 let h = dot_np(normal, sphere.center()) - d;
1229 let r = sphere.radius();
1230
1231 if h.abs() > r - 1e-10 {
1233 return Ok(vec![]);
1234 }
1235
1236 let circle_r = (r.madd(r, -(h * h))).sqrt();
1237 let circle_center = Point3::new(
1238 h.madd(-normal.x(), sphere.center().x()),
1239 h.madd(-normal.y(), sphere.center().y()),
1240 h.madd(-normal.z(), sphere.center().z()),
1241 );
1242
1243 let basis = Frame3::from_normal(circle_center, normal)?;
1245 let u_dir = basis.x;
1246 let v_dir = basis.y;
1247
1248 let n_samples = 64_usize;
1249 let mut points_3d = Vec::new();
1250 let mut ipoints = Vec::new();
1251
1252 for i in 0..=n_samples {
1253 let theta = TAU * (i as f64) / (n_samples as f64);
1254 let (sin_t, cos_t) = theta.sin_cos();
1255 let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1256 points_3d.push(pt);
1257 ipoints.push(IntersectionPoint {
1258 point: pt,
1259 param1: (theta, 0.0),
1260 param2: (0.0, 0.0),
1261 });
1262 }
1263
1264 build_curves_from_points(&points_3d, ipoints)
1265}
1266
1267#[allow(clippy::cast_precision_loss)]
1276pub fn intersect_plane_cone(
1277 cone: &ConicalSurface,
1278 normal: Vec3,
1279 d: f64,
1280) -> Result<Vec<IntersectionCurve>, MathError> {
1281 let n_samples = 64_usize;
1282 let mut points_3d = Vec::new();
1283 let mut ipoints = Vec::new();
1284
1285 for i in 0..n_samples {
1286 let u = TAU * (i as f64) / (n_samples as f64);
1287 let apex = cone.apex();
1290 let n_dot_apex = dot_np(normal, apex);
1291 let p1 = cone.evaluate(u, 1.0);
1293 let dir = p1 - apex;
1294 let n_dot_dir = normal.dot(dir);
1295
1296 if n_dot_dir.abs() < 1e-12 {
1297 continue;
1298 }
1299
1300 let v = (d - n_dot_apex) / n_dot_dir;
1301 if v.abs() > 1e-10 && v.abs() < 100.0 {
1303 let pt = cone.evaluate(u, v);
1304 points_3d.push(pt);
1305 ipoints.push(IntersectionPoint {
1306 point: pt,
1307 param1: (u, v),
1308 param2: (0.0, 0.0),
1309 });
1310 }
1311 }
1312
1313 build_curves_from_points(&points_3d, ipoints)
1314}
1315
1316#[allow(clippy::unnecessary_wraps)]
1328pub fn intersect_plane_torus(
1329 torus: &ToroidalSurface,
1330 normal: Vec3,
1331 d: f64,
1332) -> Result<Vec<IntersectionCurve>, MathError> {
1333 let mut curves = Vec::new();
1337 for ipts in plane_torus_loops(torus, normal, d, 128) {
1338 let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1339 if let Ok(curve) = fit_plane_torus_section(torus, normal, d, &pts) {
1340 curves.push(IntersectionCurve {
1341 curve,
1342 points: ipts,
1343 });
1344 }
1345 }
1346
1347 Ok(curves)
1348}
1349
1350#[must_use]
1362pub fn plane_torus_section_point(
1363 torus: &ToroidalSurface,
1364 normal: Vec3,
1365 d: f64,
1366 p: Point3,
1367) -> Option<Point3> {
1368 plane_torus_newton(torus, normal, d, p, 0.0)
1369}
1370
1371fn plane_torus_newton(
1376 torus: &ToroidalSurface,
1377 normal: Vec3,
1378 d: f64,
1379 p: Point3,
1380 short: f64,
1381) -> Option<Point3> {
1382 let scale = normal.length();
1383 if scale <= 0.0 || !scale.is_finite() {
1384 return None;
1385 }
1386 let n = normal * (1.0 / scale);
1387 let d = d / scale;
1388 let (axis, centre) = (torus.z_axis(), torus.center());
1389 let (big, small) = (torus.major_radius(), torus.minor_radius());
1390 let radial_of = |x: Point3| {
1391 let w = x - centre;
1392 w - axis * axis.dot(w)
1393 };
1394 let side = {
1397 let radial = radial_of(p);
1398 let rho = radial.length();
1399 let h = axis.dot(p - centre);
1400 if (rho + big).hypot(h) - small < ((rho - big).hypot(h) - small).abs() {
1401 -1.0
1402 } else {
1403 1.0
1404 }
1405 };
1406 let residuals = |x: Point3| -> Option<(f64, f64, Vec3)> {
1408 let radial = radial_of(x);
1409 let rho = radial.length();
1410 if rho <= 0.0 {
1411 return None;
1412 }
1413 let to = (x - centre) - radial * (side * big / rho);
1414 let reach = to.length();
1415 if reach <= 0.0 {
1416 return None;
1417 }
1418 Some((dot_np(n, x) - d, reach - small, to * (1.0 / reach)))
1419 };
1420 let rounding = 16.0 * f64::EPSILON * (big + small + (p - centre).length());
1421 let mut x = p;
1422 for _ in 0..16 {
1423 let (f_plane, f_torus, g) = residuals(x)?;
1424 if f_plane.abs() <= rounding && f_torus.abs() <= rounding {
1425 return Some(x);
1426 }
1427 let c = n.dot(g);
1428 let det = c.madd(-c, 1.0);
1429 if det < 1e-12 {
1430 return None;
1431 }
1432 let along_n = c.madd(-f_torus, f_plane) / det;
1433 let along_g = c.madd(-f_plane, f_torus) / det;
1434 x = x - n * along_n - g * along_g;
1435 if (x - p).length() < short {
1436 return Some(x);
1437 }
1438 }
1439 let (f_plane, f_torus, _) = residuals(x)?;
1440 (f_plane.abs() <= 1e3 * rounding && f_torus.abs() <= 1e3 * rounding).then_some(x)
1441}
1442
1443const PLANE_TORUS_FIT: f64 = 1e-9;
1446
1447const PLANE_TORUS_FIT_POINTS: usize = 4096;
1449
1450pub fn fit_plane_torus_section(
1470 torus: &ToroidalSurface,
1471 normal: Vec3,
1472 d: f64,
1473 points: &[Point3],
1474) -> Result<NurbsCurve, MathError> {
1475 let tol = PLANE_TORUS_FIT.madd(
1476 torus.major_radius() + torus.minor_radius(),
1477 64.0 * f64::EPSILON * (torus.center() - Point3::new(0.0, 0.0, 0.0)).length(),
1478 );
1479 let strays = |p: Point3| {
1482 let w = p - torus.center();
1483 let height = torus.z_axis().dot(w);
1484 let rho = (w - torus.z_axis() * height).length();
1485 let off_torus = [1.0, -1.0]
1486 .into_iter()
1487 .map(|side: f64| {
1488 (side.madd(-torus.major_radius(), rho).hypot(height) - torus.minor_radius()).abs()
1489 })
1490 .fold(f64::INFINITY, f64::min);
1491 ((dot_np(normal, p) - d) / normal.length())
1492 .abs()
1493 .max(off_torus)
1494 };
1495 let mut pts = points.to_vec();
1496 let mut passes = 0;
1497 loop {
1498 passes += 1;
1499 let curve = interpolate(&pts, 3.min(pts.len().saturating_sub(1)))?;
1500 let params = crate::nurbs::fitting::chord_length_params(&pts);
1501 let mut finer = Vec::with_capacity(2 * pts.len());
1502 let mut added = false;
1503 for (i, pair) in pts.windows(2).enumerate() {
1504 finer.push(pair[0]);
1505 let gap = (pair[1] - pair[0]).length();
1506 let middle = curve.evaluate(f64::midpoint(params[i], params[i + 1]));
1507 let on = plane_torus_newton(torus, normal, d, middle, 0.25 * tol)
1510 .filter(|on| (*on - middle).length() < 0.5 * gap);
1511 match on {
1512 Some(on) if (on - middle).length() <= tol => {}
1513 Some(on) => {
1514 finer.push(on);
1515 added = true;
1516 }
1517 None if strays(middle) <= tol => {}
1518 None => return Err(MathError::ConvergenceFailure { iterations: passes }),
1519 }
1520 }
1521 if !added {
1522 return Ok(curve);
1523 }
1524 if let Some(&last) = pts.last() {
1525 finer.push(last);
1526 }
1527 if finer.len() > PLANE_TORUS_FIT_POINTS {
1528 return Err(MathError::ConvergenceFailure { iterations: passes });
1529 }
1530 pts = finer;
1531 }
1532}
1533
1534const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1537
1538#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1561fn plane_torus_loops(
1562 torus: &ToroidalSurface,
1563 normal: Vec3,
1564 d: f64,
1565 n_v: usize,
1566) -> Vec<Vec<IntersectionPoint>> {
1567 let big_r = torus.major_radius();
1568 let small_r = torus.minor_radius();
1569 let a = normal.dot(torus.x_axis());
1570 let b = normal.dot(torus.y_axis());
1571 let c = normal.dot(torus.z_axis());
1572 let s = a.hypot(b);
1573 let phi = b.atan2(a);
1574 let d_local = d - dot_np(normal, torus.center());
1575 let point = |u: f64, v: f64| IntersectionPoint {
1576 point: torus.evaluate(u, v),
1577 param1: (u, v.rem_euclid(TAU)),
1578 param2: (0.0, 0.0),
1579 };
1580 let closed = |mut run: Vec<IntersectionPoint>| {
1581 run.push(run[0]);
1582 run
1583 };
1584
1585 if s < 1e-12 {
1587 if c.abs() < 1e-12 {
1588 return Vec::new();
1589 }
1590 let sin_v = d_local / (small_r * c);
1591 if sin_v.abs() > 1.0 + 1e-9 {
1592 return Vec::new();
1593 }
1594 let v0 = sin_v.clamp(-1.0, 1.0).asin();
1595 let v1 = std::f64::consts::PI - v0;
1596 let mut vs = vec![v0];
1597 let apart = (v1 - v0).rem_euclid(TAU);
1600 if apart.min(TAU - apart) > 1e-9 {
1601 vs.push(v1);
1602 }
1603 return vs
1604 .into_iter()
1605 .map(|v| {
1606 closed(
1607 (0..n_v)
1608 .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1609 .collect(),
1610 )
1611 })
1612 .collect();
1613 }
1614
1615 let length = normal.length();
1617 TorusSection {
1618 torus,
1619 phi,
1620 num: [d_local, 0.0, -small_r * c],
1621 den: [s * big_r, s * small_r],
1622 clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1623 slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1624 }
1625 .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1626}
1627
1628struct TorusSection<'a, F> {
1636 torus: &'a ToroidalSurface,
1637 phi: f64,
1638 num: [f64; 3],
1640 den: [f64; 2],
1642 clearance: F,
1644 slack: f64,
1646}
1647
1648impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1649 fn rhs(&self, v: f64) -> f64 {
1650 let [n0, n1, n2] = self.num;
1651 let [d0, d1] = self.den;
1652 let (sin, cos) = v.sin_cos();
1653 n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1654 }
1655
1656 fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1657 IntersectionPoint {
1658 point: self.torus.evaluate(u, v),
1659 param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1660 param2: (0.0, 0.0),
1661 }
1662 }
1663
1664 fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1665 self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1666 }
1667
1668 fn node(&self, v: f64) -> IntersectionPoint {
1670 let u = if self.rhs(v) >= 0.0 {
1671 self.phi
1672 } else {
1673 self.phi + std::f64::consts::PI
1674 };
1675 self.point(u, v)
1676 }
1677
1678 fn depth(&self, v: f64) -> f64 {
1681 (self.clearance)(self.node(v).point).abs()
1682 }
1683
1684 fn crossings(&self) -> Vec<f64> {
1688 let [n0, n1, n2] = self.num;
1689 let [d0, d1] = self.den;
1690 let mut roots = Vec::with_capacity(4);
1691 for c in [1.0_f64, -1.0] {
1692 let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1693 let m = beta.hypot(gamma);
1694 let ratio = -alpha / m;
1695 if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1696 continue;
1697 }
1698 let theta = gamma.atan2(beta);
1699 let delta = ratio.clamp(-1.0, 1.0).acos();
1700 roots.push((theta - delta).rem_euclid(TAU));
1701 roots.push((theta + delta).rem_euclid(TAU));
1702 }
1703 roots.sort_by(f64::total_cmp);
1704 roots
1705 }
1706
1707 fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1713 let roots = self.crossings();
1714 let n = roots.len();
1715 if n == 0 {
1716 let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1717 return if whole {
1718 vec![(0.0, TAU, None, true)]
1719 } else {
1720 Vec::new()
1721 };
1722 }
1723 let arcs: Vec<(f64, f64)> = (0..n)
1724 .map(|i| {
1725 (
1726 roots[i],
1727 if i + 1 < n {
1728 roots[i + 1]
1729 } else {
1730 roots[0] + TAU
1731 },
1732 )
1733 })
1734 .collect();
1735 let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1736 let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1737 let shallow: Vec<bool> = (0..n)
1738 .map(|i| self.depth(middle(i)) <= self.slack)
1739 .collect();
1740 let deep_beside = |i: usize, back: bool| {
1741 (1..n)
1742 .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1743 .find(|&j| !shallow[j])
1744 };
1745 let kept: Vec<bool> = (0..n)
1746 .map(|i| {
1747 if !shallow[i] {
1748 return inside[i];
1749 }
1750 matches!(
1751 (deep_beside(i, true), deep_beside(i, false)),
1752 (Some(a), Some(b)) if inside[a] && inside[b]
1753 )
1754 })
1755 .collect();
1756 let node_in = |from: usize, len: usize| {
1757 (0..len).find_map(|j| {
1758 let i = (from + j) % n;
1759 let wraps = if from + j >= n { TAU } else { 0.0 };
1760 shallow[i].then(|| middle(i) + wraps)
1761 })
1762 };
1763 let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1764 return if kept.iter().all(|&k| k) {
1765 let node = node_in(0, n);
1766 let lo = node.unwrap_or(roots[0]);
1767 vec![(lo, lo + TAU, node, true)]
1768 } else {
1769 Vec::new()
1770 };
1771 };
1772 let mut runs = Vec::new();
1773 let mut j = 0;
1774 while j < n {
1775 let i = (first + j) % n;
1776 if !kept[i] {
1777 j += 1;
1778 continue;
1779 }
1780 let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1781 let last = i + len - 1;
1782 let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1783 runs.push((arcs[i].0, hi, node_in(i, len), false));
1784 j += len;
1785 }
1786 runs
1787 }
1788
1789 #[allow(
1796 clippy::cast_precision_loss,
1797 clippy::cast_possible_truncation,
1798 clippy::cast_sign_loss
1799 )]
1800 fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1801 let closed = |mut run: Vec<IntersectionPoint>| {
1802 run.push(run[0]);
1803 run
1804 };
1805 let step = TAU / (n_v as f64);
1806 let mut loops = Vec::new();
1807 for (t_lo, t_hi, at_node, whole) in self.runs() {
1808 if whole {
1809 for sign in [1.0, -1.0] {
1810 loops.push(closed(match at_node {
1811 Some(v_node) => std::iter::once(self.node(v_node))
1812 .chain(
1813 (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1814 )
1815 .collect(),
1816 None => (0..n_v)
1817 .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1818 .collect(),
1819 }));
1820 }
1821 continue;
1822 }
1823 let len = ((t_hi - t_lo) / step).ceil();
1831 let probes = (len as usize).max(8);
1832 let (u_lo, u_hi) = (0..=probes)
1833 .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1834 .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1835 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1836 (lo.min(u), hi.max(u))
1837 });
1838 let m = len
1839 .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1840 .max(fewest)
1841 .min(most)
1842 .ceil();
1843 let steps = m as usize;
1844 if let Some(v_node) = at_node {
1845 for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1848 let along = |k: usize| {
1849 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1850 (to - from).madd(f, from)
1851 };
1852 let mut pts = vec![self.node(v_node)];
1853 pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1854 pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1855 loops.push(closed(pts));
1856 }
1857 } else {
1858 let at = |k: usize| {
1859 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1860 (t_hi - t_lo).madd(f, t_lo)
1861 };
1862 let mut pts: Vec<IntersectionPoint> =
1863 (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1864 pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1865 loops.push(closed(pts));
1866 }
1867 }
1868 loops
1869 }
1870
1871 fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1874 let half = |from: f64, to: f64| {
1875 let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1876 0.5_f64.madd(gap, from)
1877 };
1878 let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1879 let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1880 let miss =
1881 |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1882 let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1883 1.0
1884 } else {
1885 -1.0
1886 };
1887 self.branch(v, sign)
1888 }
1889}
1890
1891#[allow(clippy::cast_precision_loss)]
1900fn plane_torus_winding_loops(
1901 torus: &ToroidalSurface,
1902 normal: Vec3,
1903 d: f64,
1904 n_v: usize,
1905) -> Option<Vec<Vec<Point3>>> {
1906 let big_r = torus.major_radius();
1907 let small_r = torus.minor_radius();
1908 let a = normal.dot(torus.x_axis());
1909 let b = normal.dot(torus.y_axis());
1910 let c = normal.dot(torus.z_axis());
1911 let s = a.hypot(b);
1912 if s < 1e-12 * normal.length() || small_r >= big_r {
1913 return None;
1914 }
1915 let phi = b.atan2(a);
1916 let d_local = d - dot_np(normal, torus.center());
1917 let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1918 let dense = 8 * n_v;
1919 if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1920 return None;
1921 }
1922 let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1923 for i in 0..n_v {
1924 let v = TAU * i as f64 / n_v as f64;
1925 let delta = rhs(v).acos();
1926 loops[0].push(torus.evaluate(phi + delta, v));
1927 loops[1].push(torus.evaluate(phi - delta, v));
1928 }
1929 Some(
1930 loops
1931 .into_iter()
1932 .map(|mut run| {
1933 run.push(run[0]);
1934 run
1935 })
1936 .collect(),
1937 )
1938}
1939
1940#[must_use]
1954pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1955 let c = torus.center();
1956 let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1957 let big_r = torus.major_radius();
1958 let small_r = torus.minor_radius();
1959
1960 let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1962 let (a0, a1) = (xa.dot(o), xa.dot(dir));
1963 let (b0, b1) = (ya.dot(o), ya.dot(dir));
1964 let (c0, c1) = (za.dot(o), za.dot(dir));
1965
1966 let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1968 let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1969 let g0 = a0.madd(
1970 a0,
1971 b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1972 );
1973
1974 let four_rr = 4.0 * big_r * big_r;
1976 let h2 = four_rr * a1.madd(a1, b1 * b1);
1977 let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1978 let h0 = four_rr * a0.madd(a0, b0 * b0);
1979
1980 let e4 = g2 * g2;
1982 let e3 = 2.0 * g2 * g1;
1983 let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1984 let e1 = 2.0f64.madd(g1 * g0, -h1);
1985 let e0 = g0.madd(g0, -h0);
1986
1987 let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1988 let tube = |t: f64, across: bool| -> f64 {
1994 let p = origin + dir * t;
1995 let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1996 let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1997 let centre = if across { -big_r } else { big_r };
1998 (a.hypot(b) - centre).hypot(cc) - small_r
1999 };
2000 for t in &mut roots {
2001 let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
2002 for _ in 0..8 {
2003 let eps = 1e-7;
2004 let f = tube(*t, across);
2005 let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
2006 if df.abs() <= 1e-12 {
2007 break;
2008 }
2009 let step = f / df;
2010 *t -= step;
2011 if step.abs() < 1e-14 * (1.0 + t.abs()) {
2012 break;
2013 }
2014 }
2015 }
2016 roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2017 roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
2018 roots
2019}
2020
2021fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
2024 if c4.abs() < 1e-14 {
2026 return real_roots_cubic(c3, c2, c1, c0);
2027 }
2028 let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
2030 let eval = |z: Complex| -> Complex {
2031 let mut acc = Complex::new(1.0, 0.0);
2033 acc = acc * z + Complex::new(a, 0.0);
2034 acc = acc * z + Complex::new(b, 0.0);
2035 acc = acc * z + Complex::new(c, 0.0);
2036 acc * z + Complex::new(d, 0.0)
2037 };
2038 let seed = Complex::new(0.4, 0.9);
2040 let mut r = [
2041 Complex::new(1.0, 0.0),
2042 seed,
2043 seed * seed,
2044 seed * seed * seed,
2045 ];
2046 for _ in 0..100 {
2047 let mut max_step = 0.0_f64;
2048 for i in 0..4 {
2049 let mut denom = Complex::new(1.0, 0.0);
2050 for j in 0..4 {
2051 if i != j {
2052 denom = denom * (r[i] - r[j]);
2053 }
2054 }
2055 if denom.norm() < 1e-300 {
2056 continue;
2057 }
2058 let step = eval(r[i]) / denom;
2059 r[i] = r[i] - step;
2060 max_step = max_step.max(step.norm());
2061 }
2062 if max_step < 1e-14 {
2063 break;
2064 }
2065 }
2066 let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
2073 let mut out: Vec<f64> = Vec::new();
2074 for z in r {
2075 if z.im.abs() >= 1e-7 {
2076 continue;
2077 }
2078 let x = z.re;
2079 let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
2082 if p_real(x).abs() > 1e-6 * scale {
2083 continue;
2084 }
2085 if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
2086 continue;
2087 }
2088 out.push(x);
2089 }
2090 out
2091}
2092
2093fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
2095 if a.abs() < 1e-14 {
2096 return real_roots_quadratic(b, c, d);
2097 }
2098 let (b, c, d) = (b / a, c / a, d / a);
2100 let p = c - b * b / 3.0;
2101 let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
2102 let shift = -b / 3.0;
2103 let disc = q * q / 4.0 + p * p * p / 27.0;
2104 if disc > 1e-14 {
2105 let sq = disc.sqrt();
2106 let u = (-q / 2.0 + sq).cbrt();
2107 let v = (-q / 2.0 - sq).cbrt();
2108 vec![u + v + shift]
2109 } else if disc < -1e-14 {
2110 let m = 2.0 * (-p / 3.0).sqrt();
2112 let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
2113 (0..3)
2114 .map(|k| {
2115 m.madd(
2116 (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
2117 shift,
2118 )
2119 })
2120 .collect()
2121 } else {
2122 let u = (-q / 2.0).cbrt();
2124 vec![2.0 * u + shift, -u + shift]
2125 }
2126}
2127
2128fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
2130 if a.abs() < 1e-14 {
2131 if b.abs() < 1e-14 {
2132 return Vec::new();
2133 }
2134 return vec![-c / b];
2135 }
2136 let disc = b * b - 4.0 * a * c;
2137 if disc < 0.0 {
2138 Vec::new()
2139 } else {
2140 let sq = disc.sqrt();
2141 vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
2142 }
2143}
2144
2145#[derive(Clone, Copy)]
2147struct Complex {
2148 re: f64,
2149 im: f64,
2150}
2151
2152impl Complex {
2153 const fn new(re: f64, im: f64) -> Self {
2154 Self { re, im }
2155 }
2156 fn norm(self) -> f64 {
2157 self.re.hypot(self.im)
2158 }
2159}
2160
2161impl std::ops::Add for Complex {
2162 type Output = Self;
2163 fn add(self, o: Self) -> Self {
2164 Self::new(self.re + o.re, self.im + o.im)
2165 }
2166}
2167
2168impl std::ops::Sub for Complex {
2169 type Output = Self;
2170 fn sub(self, o: Self) -> Self {
2171 Self::new(self.re - o.re, self.im - o.im)
2172 }
2173}
2174
2175impl std::ops::Mul for Complex {
2176 type Output = Self;
2177 fn mul(self, o: Self) -> Self {
2178 Self::new(
2179 self.re.madd(o.re, -(self.im * o.im)),
2180 self.re.madd(o.im, self.im * o.re),
2181 )
2182 }
2183}
2184
2185impl std::ops::Div for Complex {
2186 type Output = Self;
2187 fn div(self, o: Self) -> Self {
2188 let den = o.re.madd(o.re, o.im * o.im);
2189 Self::new(
2190 self.re.madd(o.re, self.im * o.im) / den,
2191 self.im.madd(o.re, -(self.re * o.im)) / den,
2192 )
2193 }
2194}
2195
2196fn build_curves_from_points(
2200 points_3d: &[Point3],
2201 ipoints: Vec<IntersectionPoint>,
2202) -> Result<Vec<IntersectionCurve>, MathError> {
2203 if points_3d.len() < 2 {
2204 return Ok(vec![]);
2205 }
2206
2207 let degree = 3.min(points_3d.len() - 1);
2208 let curve = interpolate(points_3d, degree)?;
2209 Ok(vec![IntersectionCurve {
2210 curve,
2211 points: ipoints,
2212 }])
2213}
2214
2215#[allow(
2227 clippy::cast_precision_loss,
2228 clippy::too_many_lines,
2229 clippy::similar_names,
2230 clippy::unnecessary_wraps,
2231 clippy::type_complexity
2232)]
2233pub fn intersect_analytic_analytic(
2234 a: AnalyticSurface<'_>,
2235 b: AnalyticSurface<'_>,
2236 grid_res: usize,
2237) -> Result<Vec<IntersectionCurve>, MathError> {
2238 intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2239}
2240
2241pub fn intersect_analytic_analytic_bounded(
2252 a: AnalyticSurface<'_>,
2253 b: AnalyticSurface<'_>,
2254 grid_res: usize,
2255 v_range_hint_a: Option<(f64, f64)>,
2256 v_range_hint_b: Option<(f64, f64)>,
2257) -> Result<Vec<IntersectionCurve>, MathError> {
2258 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2259}
2260
2261pub fn intersect_analytic_analytic_in_region(
2274 a: AnalyticSurface<'_>,
2275 b: AnalyticSurface<'_>,
2276 grid_res: usize,
2277 v_range_hint_a: Option<(f64, f64)>,
2278 v_range_hint_b: Option<(f64, f64)>,
2279 region: Aabb3,
2280) -> Result<Vec<IntersectionCurve>, MathError> {
2281 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2282}
2283
2284fn intersect_analytic_analytic_impl(
2285 a: AnalyticSurface<'_>,
2286 b: AnalyticSurface<'_>,
2287 grid_res: usize,
2288 v_range_hint_a: Option<(f64, f64)>,
2289 v_range_hint_b: Option<(f64, f64)>,
2290 region: Option<Aabb3>,
2291) -> Result<Vec<IntersectionCurve>, MathError> {
2292 if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2295 return Ok(result);
2296 }
2297 marched_sections(a, b, grid_res, v_range_hint_a, v_range_hint_b, region)
2298}
2299
2300fn add_product(x: f64, y: f64, t: f64) -> f64 {
2304 let split = |v: f64| {
2305 let c = 134_217_729.0 * v;
2306 let hi = c - (c - v);
2307 (hi, v - hi)
2308 };
2309 let p = y * t;
2310 let ((yh, yl), (th, tl)) = (split(y), split(t));
2311 let p_err = yl.madd(tl, yl.madd(th, yh.madd(tl, yh.madd(th, -p))));
2312 let s = x + p;
2313 let back = s - x;
2314 let s_err = (x - (s - back)) + (p - back);
2315 s + (s_err + p_err)
2316}
2317
2318enum Moved {
2320 Cylinder(CylindricalSurface),
2321 Cone(ConicalSurface),
2322 Sphere(SphericalSurface),
2323 Torus(ToroidalSurface),
2324}
2325
2326impl Moved {
2327 fn new(surface: &AnalyticSurface<'_>, anchor: Point3) -> (Self, f64, f64) {
2341 let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2342 let shift = Point3::new(0.0, 0.0, 0.0) - anchor;
2343 match surface {
2344 AnalyticSurface::Cylinder(c) => {
2345 let (o, a) = (c.origin(), c.axis());
2346 let along = a.dot(anchor - o);
2347 let foot = Point3::new(
2348 add_product(o.x(), a.x(), along),
2349 add_product(o.y(), a.y(), along),
2350 add_product(o.z(), a.z(), along),
2351 );
2352 let near = foot + shift;
2353 let error = 4.0 * f64::EPSILON * (size(foot) + size(near));
2354 (Self::Cylinder(c.framed_at(near)), along, error)
2355 }
2356 AnalyticSurface::Cone(c) => {
2357 let near = c.translated(shift);
2358 let error = 2.0 * f64::EPSILON * size(near.apex());
2359 (Self::Cone(near), 0.0, error)
2360 }
2361 AnalyticSurface::Sphere(s) => {
2362 let near = s.translated(shift);
2363 let error = 2.0 * f64::EPSILON * size(near.center());
2364 (Self::Sphere(near), 0.0, error)
2365 }
2366 AnalyticSurface::Torus(t) => {
2367 let near = t.translated(shift);
2368 let error = 2.0 * f64::EPSILON * size(near.center());
2369 (Self::Torus(near), 0.0, error)
2370 }
2371 }
2372 }
2373
2374 const fn surface(&self) -> AnalyticSurface<'_> {
2375 match self {
2376 Self::Cylinder(c) => AnalyticSurface::Cylinder(c),
2377 Self::Cone(c) => AnalyticSurface::Cone(c),
2378 Self::Sphere(s) => AnalyticSurface::Sphere(s),
2379 Self::Torus(t) => AnalyticSurface::Torus(t),
2380 }
2381 }
2382}
2383
2384fn marched_sections(
2399 a: AnalyticSurface<'_>,
2400 b: AnalyticSurface<'_>,
2401 grid_res: usize,
2402 v_range_hint_a: Option<(f64, f64)>,
2403 v_range_hint_b: Option<(f64, f64)>,
2404 region: Option<Aabb3>,
2405) -> Result<Vec<IntersectionCurve>, MathError> {
2406 let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2407 let (anchor, reach) = if let Some(r) = region {
2408 (r.min + (r.max - r.min) * 0.5, (r.max - r.min).length())
2409 } else {
2410 let (surf_a, _, (u0, u1), default_v_a) = surface_closures(&a);
2411 let (v0, v1) = v_range_hint_a.unwrap_or(default_v_a);
2412 let (first, last) = (surf_a(u0, v0), surf_a(u1, v1));
2413 let reach = patch_diagonal(surf_a.as_ref(), (u0, u1), (v0, v1));
2414 (first + (last - first) * 0.5, reach)
2415 };
2416 let shift = anchor - Point3::new(0.0, 0.0, 0.0);
2417 let ((near_a, dv_a, moved_a), (near_b, dv_b, moved_b)) =
2418 (Moved::new(&a, anchor), Moved::new(&b, anchor));
2419 let v_range = |surface: &AnalyticSurface<'_>, hint: Option<(f64, f64)>, dv: f64| {
2420 let (lo, hi) = hint.unwrap_or_else(|| surface_closures(surface).3);
2421 Some((lo - dv, hi - dv))
2422 };
2423 let linear = Tolerance::new().linear;
2424 let fit_tol =
2425 ((-f64::EPSILON).madd(size(anchor) + reach, linear) - moved_a - moved_b).min(linear);
2426 let near_region = region.map(|r| Aabb3 {
2427 min: r.min - shift,
2428 max: r.max - shift,
2429 });
2430 let curves = marched_sections_near(
2431 near_a.surface(),
2432 near_b.surface(),
2433 grid_res,
2434 v_range(&a, v_range_hint_a, dv_a),
2435 v_range(&b, v_range_hint_b, dv_b),
2436 near_region,
2437 fit_tol,
2438 )?;
2439 curves
2440 .into_iter()
2441 .map(|c| {
2442 let ctrl = c
2443 .curve
2444 .control_points()
2445 .iter()
2446 .map(|&p| p + shift)
2447 .collect();
2448 let curve = NurbsCurve::new(
2449 c.curve.degree(),
2450 c.curve.knots().to_vec(),
2451 ctrl,
2452 c.curve.weights().to_vec(),
2453 )?;
2454 let points = c
2455 .points
2456 .into_iter()
2457 .map(|ip| IntersectionPoint {
2458 point: ip.point + shift,
2459 ..ip
2460 })
2461 .collect();
2462 Ok(IntersectionCurve { curve, points })
2463 })
2464 .collect()
2465}
2466
2467#[allow(clippy::too_many_lines, clippy::similar_names)]
2471fn marched_sections_near(
2472 a: AnalyticSurface<'_>,
2473 b: AnalyticSurface<'_>,
2474 grid_res: usize,
2475 v_range_hint_a: Option<(f64, f64)>,
2476 v_range_hint_b: Option<(f64, f64)>,
2477 region: Option<Aabb3>,
2478 fit_tol: f64,
2479) -> Result<Vec<IntersectionCurve>, MathError> {
2480 let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2481 let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2482 let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2483 let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2484
2485 let diag_a = patch_diagonal(surf_a.as_ref(), u_range_a, v_range_a);
2487 let diag_b = patch_diagonal(surf_b.as_ref(), u_range_b, v_range_b);
2488 let char_size = diag_a.min(diag_b).max(0.1);
2489
2490 let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2491 let meet = region;
2492 #[allow(clippy::cast_precision_loss)]
2493 let margin = 2.0 * char_size / grid_res as f64;
2494 let region = region.map(|r| r.expanded(margin));
2495
2496 let cells = |surface: &AnalyticSurface<'_>,
2505 surf: &dyn Fn(f64, f64) -> Point3,
2506 (u_range, v_range): ((f64, f64), (f64, f64)),
2507 other: &AnalyticSurface<'_>,
2508 near: Option<Aabb3>| {
2509 #[allow(clippy::cast_precision_loss)]
2510 let n = grid_res as f64;
2511 let (du, dv) = ((u_range.1 - u_range.0) / n, (v_range.1 - v_range.0) / n);
2512 let mut found = Vec::new();
2513 let mut kept = Vec::new();
2514 let mut held: Option<Aabb3> = None;
2515 for i in 0..grid_res {
2516 for j in 0..grid_res {
2517 #[allow(clippy::cast_precision_loss)]
2518 let (u, v) = (
2519 du.madd(i as f64 + 0.5, u_range.0),
2520 dv.madd(j as f64 + 0.5, v_range.0),
2521 );
2522 let middle = surf(u, v);
2523 let reach = cell_reach(surface, (0.5 * du, 0.5 * dv), v);
2524 let placed = reach.is_finite()
2525 && middle.x().is_finite()
2526 && middle.y().is_finite()
2527 && middle.z().is_finite();
2528 if placed && near.is_some_and(|r| !r.expanded(reach).contains_point(middle)) {
2529 continue;
2530 }
2531 let reading = section_fit::Carrier::distance(other, middle)
2532 .filter(|(d, n)| d.is_finite() && n.length().is_finite());
2533 let slack = || {
2536 let size = middle.x().abs().max(middle.y().abs()).max(middle.z().abs());
2537 128.0
2538 * f64::EPSILON
2539 * (section_fit::Carrier::scale(surface, middle)
2540 + section_fit::Carrier::scale(other, middle)
2541 + size)
2542 };
2543 let (dist, seed) = match reading {
2544 Some((d, _))
2545 if placed
2546 && d.abs() > reach
2547 && (d.abs() > 2.0 * reach || d.abs() - slack() > reach) =>
2548 {
2549 continue;
2550 }
2551 Some((d, n)) => (d.abs(), middle - n * (0.5 * d)),
2552 None => (f64::INFINITY, middle),
2553 };
2554 found.push((dist, seed));
2555 kept.push((i, j));
2556 let cell = if placed {
2557 Aabb3 {
2558 min: middle,
2559 max: middle,
2560 }
2561 .expanded(reach)
2562 } else {
2563 Aabb3 {
2564 min: Point3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2565 max: Point3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2566 }
2567 };
2568 held = Some(held.map_or(cell, |h| h.union(cell)));
2569 }
2570 }
2571 (found, held, kept)
2572 };
2573 let (mut candidates, held, kept_a) =
2574 cells(&a, surf_a.as_ref(), (u_range_a, v_range_a), &b, region);
2575
2576 let Some(held) = held else {
2581 return Ok(vec![]);
2582 };
2583 let mut cover = cover::Cover::new(
2591 &a,
2592 &b,
2593 (u_range_a, v_range_a),
2594 v_range_b,
2595 grid_res,
2596 &kept_a,
2597 meet.zip(region),
2598 Tolerance::new().linear,
2599 cover::MOST_LEAVES,
2600 );
2601 if !cover.complete() {
2605 candidates.extend(cells(&b, surf_b.as_ref(), (u_range_b, v_range_b), &a, Some(held)).0);
2606 }
2607 candidates.sort_by(|p, q| p.0.total_cmp(&q.0));
2608
2609 let settle = |mid: Point3| {
2620 let on = settle_on_section(&a, &b, mid).or_else(|| {
2621 let mut p = mid;
2622 for _ in 0..8 {
2623 let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2624 let pa = surf_a(ua, va);
2625 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2626 let pb = surf_b(ub, vb);
2627 p = Point3::new(
2628 (pa.x() + pb.x()) * 0.5,
2629 (pa.y() + pb.y()) * 0.5,
2630 (pa.z() + pb.z()) * 0.5,
2631 );
2632 if (pa - pb).length() < 1e-9 {
2633 break;
2634 }
2635 }
2636 settle_on_section(&a, &b, p)
2637 });
2638 let near_patches = |q: Point3| {
2641 let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2642 let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2643 (q - surf_a(ua, va)).length() <= march_step
2644 && (q - surf_b(ub, vb)).length() <= march_step
2645 };
2646 let Some(on) = on.filter(|&on| {
2647 crosses_at(&a, &b, on)
2648 && near_patches(on)
2649 && region.is_none_or(|r| r.contains_point(on))
2650 }) else {
2651 return Ok(None);
2652 };
2653 station(&a, &b, on, Vec3::new(0.0, 0.0, 0.0))
2656 .map(Some)
2657 .ok_or(MathError::ConvergenceFailure { iterations: 0 })
2658 };
2659 let off_patch = |q: Point3| {
2660 let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2661 let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2662 (!is_u_periodic(&a) && (ua <= u_range_a.0 || ua >= u_range_a.1))
2663 || va <= v_range_a.0
2664 || va >= v_range_a.1
2665 || (!is_u_periodic(&b) && (ub <= u_range_b.0 || ub >= u_range_b.1))
2666 || vb <= v_range_b.0
2667 || vb >= v_range_b.1
2668 };
2669
2670 let trace = |seed: Point3,
2680 marched: &mut Vec<Vec<Point3>>,
2681 curves: &mut Vec<IntersectionCurve>|
2682 -> Result<Option<Vec<Point3>>, MathError> {
2683 let march_result = march_analytic_intersection(
2684 &a,
2685 &b,
2686 surf_a.as_ref(),
2687 norm_a.as_ref(),
2688 surf_b.as_ref(),
2689 norm_b.as_ref(),
2690 seed,
2691 u_range_a,
2692 v_range_a,
2693 u_range_b,
2694 v_range_b,
2695 march_step,
2696 is_u_periodic(&a),
2697 is_u_periodic(&b),
2698 region,
2699 )
2700 .ok_or(MathError::ConvergenceFailure {
2701 iterations: MARCH_STEPS,
2702 })?;
2703 if march_result.len() < 2 {
2704 return Ok(None);
2705 }
2706 let middle = march_result[march_result.len() / 2];
2707 if marched.iter().any(|m| on_march(&a, &b, middle, m)) {
2708 return Ok(Some(march_result));
2709 }
2710
2711 let crowd = 1e-3 * march_step;
2713 let mut spaced: Vec<Point3> = Vec::with_capacity(march_result.len());
2714 for (k, &p) in march_result.iter().enumerate() {
2715 let last = k + 1 == march_result.len();
2716 match spaced.last() {
2717 Some(&q) if (p - q).length() < crowd => {
2718 if last && spaced.len() > 1 {
2719 spaced.pop();
2720 spaced.push(p);
2721 }
2722 }
2723 _ => spaced.push(p),
2724 }
2725 }
2726 if spaced.len() < 2 {
2727 match (march_result.first(), march_result.last()) {
2730 (Some(&first), Some(&last)) if (last - first).length() > 0.0 => {
2731 spaced = vec![first, last];
2732 }
2733 _ => return Ok(None),
2734 }
2735 }
2736 if fit_tol < 0.5 * Tolerance::new().linear {
2737 return Err(MathError::ConvergenceFailure { iterations: 0 });
2738 }
2739 let (curve, points) = fit_section(&a, &b, &spaced, fit_tol)?;
2740 let ipts: Vec<IntersectionPoint> = points
2741 .iter()
2742 .map(|&pt| IntersectionPoint {
2743 point: pt,
2744 param1: (0.0, 0.0),
2745 param2: (0.0, 0.0),
2746 })
2747 .collect();
2748 marched.push(march_result.clone());
2749 curves.push(IntersectionCurve {
2750 curve,
2751 points: ipts,
2752 });
2753 Ok(Some(march_result))
2754 };
2755
2756 let mut curves = Vec::new();
2757 let mut marched: Vec<Vec<Point3>> = Vec::new();
2758 let mut past_edges = Vec::new();
2759 let mut k = 0;
2760 while k < candidates.len() + past_edges.len() {
2761 let seed = if k < candidates.len() {
2762 let mid = candidates[k].1;
2763 k += 1;
2764 let Some(seed) = settle(mid)? else {
2765 continue;
2766 };
2767 if off_patch(seed.p) {
2768 past_edges.push(seed);
2769 continue;
2770 }
2771 seed
2772 } else {
2773 k += 1;
2774 past_edges[k - 1 - candidates.len()]
2775 };
2776 if marched.iter().any(|m| on_march(&a, &b, seed.p, m)) {
2777 continue;
2778 }
2779 trace(seed.p, &mut marched, &mut curves)?;
2780 }
2781
2782 for m in &marched {
2783 cover.mark_marched(m);
2784 }
2785 let (marched, curves) = (RefCell::new(marched), RefCell::new(curves));
2786 let fitted = |cover: &cover::Cover<'_, '_>, class: &[usize], z: Point3| {
2790 curves.borrow().iter().any(|c| {
2791 crate::nurbs::projection::project_point_to_curve(&c.curve, z, 1e-12)
2792 .is_ok_and(|f| cover.holds(class, f.point, fit_tol))
2793 })
2794 };
2795 let mut seed = |z: Point3| -> Result<Option<Vec<Point3>>, MathError> {
2797 let Some(seed) = settle(z)? else {
2798 return Ok(None);
2799 };
2800 if marched.borrow().iter().any(|m| on_march(&a, &b, seed.p, m)) {
2801 return Ok(Some(vec![seed.p]));
2802 }
2803 let traced = trace(seed.p, &mut marched.borrow_mut(), &mut curves.borrow_mut())?;
2804 Ok(Some(traced.unwrap_or_default()))
2805 };
2806 while cover.complete() {
2809 let classes = cover.classes();
2810 if classes.is_empty() {
2811 break;
2812 }
2813 for class in classes {
2814 cover.resolve(&class, &fitted, &mut seed)?;
2815 }
2816 }
2817
2818 Ok(curves.into_inner())
2819}
2820
2821fn cell_reach(surface: &AnalyticSurface<'_>, (du, dv): (f64, f64), v: f64) -> f64 {
2825 match surface {
2826 AnalyticSurface::Cylinder(c) => du.madd(c.radius(), dv),
2827 AnalyticSurface::Cone(c) => (du * c.half_angle().cos()).madd(v.abs() + dv, dv),
2828 AnalyticSurface::Sphere(s) => (du + dv) * s.radius(),
2829 AnalyticSurface::Torus(t) => {
2830 du.madd(t.major_radius() + t.minor_radius(), dv * t.minor_radius())
2831 }
2832 }
2833}
2834
2835fn on_march(
2846 a: &AnalyticSurface<'_>,
2847 b: &AnalyticSurface<'_>,
2848 p: Point3,
2849 points: &[Point3],
2850) -> bool {
2851 use section_fit::Carrier;
2852 let nearest = points
2853 .windows(2)
2854 .map(|w| {
2855 let chord = w[1] - w[0];
2856 let len2 = chord.dot(chord);
2857 let s = if len2 > 0.0 {
2858 ((p - w[0]).dot(chord) / len2).clamp(0.0, 1.0)
2859 } else {
2860 0.0
2861 };
2862 let foot = w[0] + chord * s;
2863 ((p - foot).length(), len2.sqrt(), foot, w)
2864 })
2865 .min_by(|x, y| x.0.total_cmp(&y.0));
2866 let Some((off, len, foot, w)) = nearest else {
2867 return false;
2868 };
2869 let sheets = |q: Point3| (a.sheet(q), b.sheet(q));
2870 if off > MARCH_TURN * len || sheets(w[0]) != sheets(p) || sheets(w[1]) != sheets(p) {
2871 return false;
2872 }
2873 let tol = Tolerance::new().linear;
2874 let mut guess = foot;
2875 for _ in 0..8 {
2876 let Some(q) = settle_on_section(a, b, guess) else {
2877 return false;
2878 };
2879 if sheets(q) != sheets(p) {
2880 return false;
2881 }
2882 let miss = p - q;
2883 if miss.length() <= tol {
2884 return true;
2885 }
2886 let (Some((_, na)), Some((_, nb))) = (a.distance(q), b.distance(q)) else {
2887 return false;
2888 };
2889 let t = na.cross(nb);
2890 let sin = t.length();
2891 if sin <= 0.0 {
2892 return false;
2893 }
2894 let t = t * (1.0 / sin);
2895 guess = q + t * miss.dot(t);
2896 }
2897 false
2898}
2899
2900fn patch_diagonal(
2905 surf: &dyn Fn(f64, f64) -> Point3,
2906 (u0, u1): (f64, f64),
2907 (v0, v1): (f64, f64),
2908) -> f64 {
2909 let corner = (surf(u0, v0) - surf(u1, v1)).length();
2910 let middle = (surf(u0, v0) - surf(f64::midpoint(u0, u1), f64::midpoint(v0, v1))).length();
2911 if corner > 1e-9 * middle {
2912 corner
2913 } else {
2914 middle
2915 }
2916}
2917
2918#[allow(clippy::too_many_lines)]
2932fn try_algebraic_intersection(
2933 a: &AnalyticSurface<'_>,
2934 b: &AnalyticSurface<'_>,
2935 v_range_a: Option<(f64, f64)>,
2936 v_range_b: Option<(f64, f64)>,
2937) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2938 match (a, b) {
2939 (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2940 algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2941 .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2942 ),
2943 (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2944 algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2945 .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2946 ),
2947 (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2948 algebraic_sphere_sphere(s1, s2).map(Some)
2949 }
2950 (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2951 let axis_dot = c1.axis().dot(c2.axis()).abs();
2952 if axis_dot > 1.0 - 1e-10 {
2953 let delta = c2.origin() - c1.origin();
2955 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2956 let along = delta_vec.dot(c1.axis());
2957 let perp = (delta_vec - c1.axis() * along).length();
2958 if perp < 1e-8 {
2959 if (c1.radius() - c2.radius()).abs() < 1e-8 {
2962 return Ok(None); }
2964 return Ok(Some(vec![])); }
2966 if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2967 return Ok(Some(rulings));
2968 }
2969 }
2970 algebraic_cylinder_cylinder(c1, c2)
2972 }
2973 (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2975 algebraic_sphere_cylinder(s, c, true)
2976 }
2977 (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2978 algebraic_sphere_cylinder(s, c, false)
2979 }
2980 (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2981 if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2982 return Ok(Some(rulings));
2983 }
2984 if let Some(curves) = algebraic_cone_cone(c1, c2)? {
2985 return Ok(Some(curves));
2986 }
2987 Ok(algebraic_parallel_cone_cone(c1, c2, v_range_a, v_range_b))
2988 }
2989 (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2990 Ok(ruling_cone_sphere(cone, sphere, true))
2991 }
2992 (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2993 Ok(ruling_cone_sphere(cone, sphere, false))
2994 }
2995 (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2996 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2997 return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2998 .map(Some);
2999 }
3000 Ok(parallel_axis_torus_cylinder(t, c, true)
3001 .or_else(|| ruling_torus_cylinder(t, c, true)))
3002 }
3003 (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
3004 if let Some(exacts) = exact_cylinder_torus(c, t)? {
3005 return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
3006 .map(Some);
3007 }
3008 Ok(parallel_axis_torus_cylinder(t, c, false)
3009 .or_else(|| ruling_torus_cylinder(t, c, false)))
3010 }
3011 (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
3012 match exact_sphere_torus(s, t)? {
3013 Some(exacts) => {
3014 exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
3015 .map(Some)
3016 }
3017 None => Ok(sphere_torus_curves(s, t, true)),
3018 }
3019 }
3020 (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
3021 match exact_sphere_torus(s, t)? {
3022 Some(exacts) => {
3023 exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
3024 .map(Some)
3025 }
3026 None => Ok(sphere_torus_curves(s, t, false)),
3027 }
3028 }
3029 (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
3030 .map(|exacts| {
3031 exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
3032 })
3033 .transpose(),
3034 (AnalyticSurface::Cone(c), AnalyticSurface::Torus(t)) => exact_cone_torus(c, t)?
3035 .map(|exacts| exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p))))
3036 .transpose(),
3037 (AnalyticSurface::Torus(t), AnalyticSurface::Cone(c)) => exact_cone_torus(c, t)?
3038 .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p))))
3039 .transpose(),
3040 }
3041}
3042
3043fn parallel_axis_torus_cylinder(
3050 torus: &ToroidalSurface,
3051 cyl: &CylindricalSurface,
3052 torus_first: bool,
3053) -> Option<Vec<IntersectionCurve>> {
3054 let axis = torus.z_axis();
3055 let along = cyl.axis().dot(axis);
3056 if along.abs() < 1.0 - 1e-10 {
3057 return None;
3058 }
3059 let offset = cyl.origin() - torus.center();
3060 if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
3061 return None;
3062 }
3063 let (major, minor) = (torus.major_radius(), torus.minor_radius());
3064 let roots = |u: f64| {
3065 let q = cyl.evaluate(u, 0.0) - torus.center();
3066 let height = q.dot(axis);
3067 let rho = (q - axis * height).length();
3068 let reach = minor * minor - (rho - major) * (rho - major);
3069 ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
3070 };
3071 let samples = ruling_samples(cyl, &roots);
3072 let loops = if samples.iter().all(Option::is_some) {
3073 closed_ruling_loops(cyl, &roots, &samples)
3074 } else {
3075 partial_ruling_loops(cyl, &roots, &samples)
3076 };
3077 if loops.is_empty() {
3078 return None;
3079 }
3080 Some(fit_ruling_loops(&loops, |p| {
3081 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3082 }))
3083}
3084
3085fn meridian_crossings(
3092 first: (f64, f64, f64),
3093 second: (f64, f64, f64),
3094 scale: f64,
3095) -> Option<Vec<(f64, f64)>> {
3096 let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
3097 let (dx, dz) = (x2 - x1, z2 - z1);
3098 let dist = dx.hypot(dz);
3099 let slack = 1e-9 * scale;
3100 if dist < slack {
3101 return None;
3102 }
3103 let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
3104 if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
3105 return Some(Vec::new());
3106 }
3107 let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
3108 let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
3109 let (ux, uz) = (dx / dist, dz / dist);
3110 let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
3111 &[0.0]
3112 } else {
3113 &[1.0, -1.0]
3114 };
3115 let mut crossings = Vec::with_capacity(sides.len());
3116 for side in sides {
3117 let rho = x1 + along * ux - side * across * uz;
3118 if rho <= slack {
3119 return None;
3120 }
3121 crossings.push((rho, z1 + along * uz + side * across * ux));
3122 }
3123 Some(crossings)
3124}
3125
3126fn exact_circle_curves(
3130 exacts: Vec<ExactIntersectionCurve>,
3131 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3132) -> Result<Vec<IntersectionCurve>, MathError> {
3133 let mut curves = Vec::with_capacity(exacts.len());
3134 for exact in exacts {
3135 match exact {
3136 ExactIntersectionCurve::Circle(circle) => {
3137 let points = (0..=32)
3138 .map(|i| {
3139 let point = circle.evaluate(TAU * f64::from(i) / 32.0);
3140 let (param1, param2) = params(point);
3141 IntersectionPoint {
3142 point,
3143 param1,
3144 param2,
3145 }
3146 })
3147 .collect();
3148 let r = circle.radius();
3149 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3150 curves.push(IntersectionCurve { curve, points });
3151 }
3152 ExactIntersectionCurve::Points(points) if points.len() == 1 => {
3154 let point = points[0];
3155 let (param1, param2) = params(point);
3156 curves.push(IntersectionCurve {
3157 curve: interpolate(&[point, point], 1)?,
3158 points: vec![IntersectionPoint {
3159 point,
3160 param1,
3161 param2,
3162 }],
3163 });
3164 }
3165 ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
3166 }
3167 }
3168 Ok(curves)
3169}
3170
3171fn circles_about_axis(
3173 base: Point3,
3174 axis: Vec3,
3175 crossings: &[(f64, f64)],
3176) -> Result<Vec<ExactIntersectionCurve>, MathError> {
3177 crossings
3178 .iter()
3179 .map(|&(rho, z)| {
3180 Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
3181 })
3182 .collect()
3183}
3184
3185pub fn exact_torus_torus(
3197 first: &ToroidalSurface,
3198 second: &ToroidalSurface,
3199) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3200 let axis = first.z_axis();
3201 let scale = first.major_radius() + second.major_radius();
3202 let offset = second.center() - first.center();
3203 if first.minor_radius() >= first.major_radius()
3205 || second.minor_radius() >= second.major_radius()
3206 || axis.cross(second.z_axis()).length() > 1e-9
3207 || offset.cross(axis).length() > 1e-9 * scale
3208 {
3209 return Ok(None);
3210 }
3211 let Some(crossings) = meridian_crossings(
3212 (first.major_radius(), 0.0, first.minor_radius()),
3213 (
3214 second.major_radius(),
3215 offset.dot(axis),
3216 second.minor_radius(),
3217 ),
3218 scale,
3219 ) else {
3220 return Ok(None);
3221 };
3222 circles_about_axis(first.center(), axis, &crossings).map(Some)
3223}
3224
3225pub fn exact_cylinder_torus(
3239 cylinder: &CylindricalSurface,
3240 torus: &ToroidalSurface,
3241) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3242 let axis = torus.z_axis();
3243 let scale = torus.major_radius() + cylinder.radius();
3244 let offset = cylinder.origin() - torus.center();
3245 let linear = crate::tolerance::Tolerance::default().linear;
3246 if axis.cross(cylinder.axis()).length() > 1e-9
3247 || offset.cross(axis).length() > 1e-9 * scale
3248 || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
3249 {
3250 return Ok(None);
3251 }
3252 let gap = cylinder.radius() - torus.major_radius();
3253 let small = torus.minor_radius();
3254 if (gap.abs() - small).abs() <= linear {
3258 return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
3259 }
3260 if gap.abs() > small {
3261 return Ok(Some(Vec::new()));
3262 }
3263 let height = small.madd(small, -(gap * gap)).sqrt();
3264 circles_about_axis(
3265 torus.center(),
3266 axis,
3267 &[(cylinder.radius(), height), (cylinder.radius(), -height)],
3268 )
3269 .map(Some)
3270}
3271
3272pub fn exact_cone_torus(
3292 cone: &ConicalSurface,
3293 torus: &ToroidalSurface,
3294) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3295 let axis = cone.axis();
3296 let (major, minor) = (torus.major_radius(), torus.minor_radius());
3297 let offset = torus.center() - cone.apex();
3298 if minor >= major
3301 || axis.cross(torus.z_axis()).length() > 1e-9
3302 || offset.cross(axis).length() > 1e-9 * (major + minor)
3303 {
3304 return Ok(None);
3305 }
3306 let linear = Tolerance::new().linear;
3307 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3308 let height = offset.dot(axis);
3309 let foot = major.madd(cos_a, height * sin_a);
3310 let reach = major.madd(sin_a, -(height * cos_a)).abs();
3311 let roots = if (reach - minor).abs() <= linear {
3312 vec![foot]
3313 } else if reach > minor {
3314 Vec::new()
3315 } else {
3316 let half = ((minor - reach) * (minor + reach)).sqrt();
3317 vec![foot - half, foot + half]
3318 };
3319 let crossings: Vec<(f64, f64)> = roots
3320 .into_iter()
3321 .filter(|&v| v * cos_a > linear)
3322 .map(|v| (v * cos_a, v * sin_a))
3323 .collect();
3324 circles_about_axis(cone.apex(), axis, &crossings).map(Some)
3325}
3326
3327pub fn exact_sphere_torus(
3342 sphere: &SphericalSurface,
3343 torus: &ToroidalSurface,
3344) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3345 let axis = torus.z_axis();
3346 let scale = torus.major_radius() + sphere.radius();
3347 let offset = sphere.center() - torus.center();
3348 if torus.minor_radius() >= torus.major_radius() {
3350 return Ok(None);
3351 }
3352 if offset.cross(axis).length() > 1e-9 * scale {
3353 let radial = offset - axis * offset.dot(axis);
3359 let slack = 64.0
3360 * f64::EPSILON
3361 * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
3362 let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
3363 + (sphere.radius() - torus.minor_radius()).abs();
3364 if stray <= slack.min(Tolerance::new().linear) {
3365 let along = axis.cross(radial).normalize()?;
3366 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
3367 sphere.center(),
3368 along,
3369 sphere.radius(),
3370 )?)]));
3371 }
3372 return Ok(
3373 off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
3374 );
3375 }
3376 let Some(crossings) = meridian_crossings(
3377 (0.0, offset.dot(axis), sphere.radius()),
3378 (torus.major_radius(), 0.0, torus.minor_radius()),
3379 scale,
3380 ) else {
3381 return Ok(None);
3382 };
3383 circles_about_axis(torus.center(), axis, &crossings).map(Some)
3384}
3385
3386const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
3390
3391fn sphere_torus_section<'a>(
3400 sphere: &SphericalSurface,
3401 torus: &'a ToroidalSurface,
3402) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
3403 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3404 let offset = sphere.center() - torus.center();
3405 let (a, b, h) = (
3406 offset.dot(torus.x_axis()),
3407 offset.dot(torus.y_axis()),
3408 offset.dot(torus.z_axis()),
3409 );
3410 let s = a.hypot(b);
3411 if small >= big || s <= 1e-9 * (big + radius) {
3412 return None;
3413 }
3414 let centre = sphere.center();
3415 Some(TorusSection {
3416 torus,
3417 phi: b.atan2(a),
3418 num: [
3419 big.madd(
3420 big,
3421 small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
3422 ),
3423 2.0 * big * small,
3424 -2.0 * h * small,
3425 ],
3426 den: [2.0 * s * big, 2.0 * s * small],
3427 clearance: move |p: Point3| (p - centre).length() - radius,
3428 slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
3429 })
3430}
3431
3432const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
3434
3435fn sphere_torus_curves(
3443 sphere: &SphericalSurface,
3444 torus: &ToroidalSurface,
3445 sphere_first: bool,
3446) -> Option<Vec<IntersectionCurve>> {
3447 let section = sphere_torus_section(sphere, torus)?;
3448 let tol = Tolerance::new().linear;
3449 let (big, small) = (torus.major_radius(), torus.minor_radius());
3450 let offset = sphere.center() - torus.center();
3455 let rise = offset.dot(torus.z_axis());
3456 let reach = (offset - torus.z_axis() * rise).length();
3457 let (nearest, farthest) = (
3458 ((reach - big).hypot(rise) - small).abs(),
3459 (reach + big).hypot(rise) + small,
3460 );
3461 let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
3462 let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
3463 let off = |p: Point3| {
3464 let local = p - torus.center();
3465 let (x, y, z) = (
3466 local.dot(torus.x_axis()),
3467 local.dot(torus.y_axis()),
3468 local.dot(torus.z_axis()),
3469 );
3470 let on_torus = (x.hypot(y) - big).hypot(z) - small;
3471 on_torus.abs().max((section.clearance)(p).abs())
3472 };
3473 let centre = sphere.center();
3477 let polish = |q: IntersectionPoint| {
3478 let (mut u, mut v) = q.param1;
3479 let mut best = q;
3480 for _ in 0..4 {
3481 let gap = (section.clearance)(best.point);
3482 let (sin_u, cos_u) = u.sin_cos();
3483 let (sin_v, cos_v) = v.sin_cos();
3484 let rho = small.madd(cos_v, big);
3485 let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
3486 let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
3487 let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
3488 let away = best.point - centre;
3489 let normal = away * (1.0 / away.length());
3490 let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
3491 let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
3492 let reach = g_u.madd(w_u, g_v * w_v);
3493 if reach <= f64::MIN_POSITIVE {
3494 break;
3495 }
3496 let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
3497 if (section.clearance)(next.point).abs() >= gap.abs() {
3498 break;
3499 }
3500 (u, v) = next.param1;
3501 best = next;
3502 }
3503 best
3504 };
3505 let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
3506 if loops.is_empty() && crosses {
3507 return None;
3508 }
3509 let mut curves = Vec::new();
3510 for points in loops {
3511 let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
3512 if points.iter().any(|q| off(q.point) > tol) {
3513 return None;
3514 }
3515 points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
3518 let mut rounds = 0;
3519 let curve = loop {
3520 let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
3521 let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
3522 let params = crate::nurbs::fitting::chord_length_params(&positions);
3523 let strays: Vec<usize> = (0..positions.len() - 1)
3524 .filter(|&k| {
3525 off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
3526 })
3527 .collect();
3528 if strays.is_empty() {
3529 break curve;
3530 }
3531 if rounds == SPHERE_TORUS_FIT_ROUNDS {
3532 return None;
3533 }
3534 rounds += 1;
3535 for &k in strays.iter().rev() {
3536 let mid = polish(section.between(points[k].param1, points[k + 1].param1));
3537 if off(mid.point) > tol {
3538 return None;
3539 }
3540 points.insert(k + 1, mid);
3541 }
3542 };
3543 for q in &mut points {
3544 let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
3545 (q.param1, q.param2) = if sphere_first {
3546 (on_sphere, on_torus)
3547 } else {
3548 (on_torus, on_sphere)
3549 };
3550 }
3551 curves.push(IntersectionCurve { curve, points });
3552 }
3553 Some(curves)
3554}
3555
3556fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
3564 let axis = torus.z_axis();
3565 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3566 let offset = sphere.center() - torus.center();
3567 let radial = offset - axis * offset.dot(axis);
3568 let out = radial * (1.0 / radial.length());
3569 let near = torus.center() + out * big;
3570 let far = torus.center() - out * big;
3571 let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
3572 let (d_near, d_far) = (to_near.length(), to_far.length());
3573 let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
3574 if d_near > slack
3577 && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
3578 {
3579 return Some(near + to_near * (small / d_near));
3580 }
3581 ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
3582}
3583
3584pub fn exact_cone_cone(
3609 c1: &ConicalSurface,
3610 c2: &ConicalSurface,
3611) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3612 let axis = c1.axis();
3613 let axis2 = c2.axis();
3614
3615 if axis.dot(axis2).abs() < 1.0 - 1e-10 {
3617 return Ok(None); }
3619 let apex1 = c1.apex();
3620 let apex2 = c2.apex();
3621 let delta = apex2 - apex1;
3622 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3623 let along = delta_v.dot(axis);
3624 if (delta_v - axis * along).length() > 1e-8 {
3625 return offset_parallel_cone_cone(c1, c2);
3626 }
3627
3628 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3629 if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
3630 return Ok(None); }
3632 let m1 = c1.half_angle().cos() / s1;
3633 let m2 = c2.half_angle().cos() / s2;
3634 let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
3635 let d2 = along; let denom = m1 - m2 * sigma;
3638 if denom.abs() < 1e-12 {
3639 if sigma > 0.0 && d2.abs() < 1e-9 {
3642 return Ok(None);
3643 }
3644 return Ok(Some(vec![]));
3645 }
3646
3647 let t_star = (-m2 * sigma * d2) / denom;
3648 let radius = m1 * t_star;
3649 if radius < 1e-12 {
3650 return Ok(Some(vec![])); }
3652
3653 let center = Point3::new(
3654 apex1.x() + axis.x() * t_star,
3655 apex1.y() + axis.y() * t_star,
3656 apex1.z() + axis.z() * t_star,
3657 );
3658 let circle = Circle3D::new(center, axis, radius)?;
3659 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3660}
3661
3662fn offset_parallel_cone_cone(
3673 c1: &ConicalSurface,
3674 c2: &ConicalSurface,
3675) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3676 if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
3677 return Ok(None); }
3679 let t1 = c1.half_angle().tan();
3680 let t2 = c2.half_angle().tan();
3681 if !t1.is_finite() || !t2.is_finite() {
3682 return Ok(None);
3683 }
3684 if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
3685 return Ok(None);
3686 }
3687
3688 let w = c1.axis();
3689 let apex1 = c1.apex();
3690 let apex2 = c2.apex();
3691 let delta = apex2 - apex1;
3692 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3693 let s = delta_v.dot(w);
3694 let tm = 0.5 * (t1 + t2);
3695 let k = 1.0 + tm * tm;
3696
3697 let n = (delta_v - w * (k * s)) * 2.0;
3701 let n_len = n.length();
3702 if n_len < 1e-12 {
3703 return Ok(None);
3704 }
3705 let n_hat = n * (1.0 / n_len);
3706 let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3707
3708 let axis2 = c2.axis();
3714 let scale = 1.0 + delta_v.length();
3715 let mut out = Vec::new();
3716 for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3717 let samples: Vec<Point3> = match &curve {
3718 ExactIntersectionCurve::Circle(c) => (0..4)
3719 .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3720 .collect(),
3721 ExactIntersectionCurve::Ellipse(e) => (0..4)
3722 .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3723 .collect(),
3724 ExactIntersectionCurve::Points(_) => return Ok(None),
3725 };
3726 let on_real_nappe = |p: &Point3| {
3727 let rel = *p - apex2;
3728 Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3729 };
3730 let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3731 match hits {
3732 0 => {}
3733 4 => out.push(curve),
3734 _ => return Ok(None),
3735 }
3736 }
3737 Ok(Some(out))
3738}
3739
3740pub fn exact_cone_cylinder(
3760 cone: &ConicalSurface,
3761 cyl: &CylindricalSurface,
3762) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3763 let axis = cone.axis();
3764 let cyl_axis = cyl.axis();
3765
3766 if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3768 return Ok(None);
3769 }
3770 let apex = cone.apex();
3771 let delta = apex - cyl.origin();
3772 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3773 let along = delta_v.dot(cyl_axis);
3774 if (delta_v - cyl_axis * along).length() > 1e-8 {
3775 return Ok(None);
3776 }
3777
3778 let s = cone.half_angle().sin();
3779 if s.abs() < 1e-12 {
3780 return Ok(None); }
3782 let m = cone.half_angle().cos() / s; if m.abs() < 1e-12 {
3784 return Ok(None); }
3786
3787 let t_star = cyl.radius() / m; if t_star.abs() < 1e-12 {
3789 return Ok(Some(vec![])); }
3791 let center = Point3::new(
3792 apex.x() + axis.x() * t_star,
3793 apex.y() + axis.y() * t_star,
3794 apex.z() + axis.z() * t_star,
3795 );
3796 let circle = Circle3D::new(center, axis, cyl.radius())?;
3797 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3798}
3799
3800fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3805 let w = std::f64::consts::FRAC_1_SQRT_2;
3806 let corners: [(f64, f64); 9] = [
3807 (1.0, 0.0),
3808 (1.0, 1.0),
3809 (0.0, 1.0),
3810 (-1.0, 1.0),
3811 (-1.0, 0.0),
3812 (-1.0, -1.0),
3813 (0.0, -1.0),
3814 (1.0, -1.0),
3815 (1.0, 0.0),
3816 ];
3817 let points = corners
3818 .iter()
3819 .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3820 .collect();
3821 let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3822 let knots = vec![
3823 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3824 ];
3825 NurbsCurve::new(2, knots, points, weights)
3826}
3827
3828fn shared_apex_cones(
3840 c1: &ConicalSurface,
3841 c2: &ConicalSurface,
3842 v1: Option<(f64, f64)>,
3843 v2: Option<(f64, f64)>,
3844) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3845 let (Some(v1), Some(v2)) = (v1, v2) else {
3846 return Ok(None);
3847 };
3848 let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3849 let across = a1.cross(a2);
3850 let sin = across.length();
3851 if sin < 1e-9 {
3852 return Ok(None);
3853 }
3854 let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3855 let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3856 if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3857 return Ok(None);
3858 }
3859 let normal = across * (1.0 / sin);
3860 let tol = Tolerance::new().linear;
3861 if f64::EPSILON * reach > 0.1 * tol * sin {
3865 return Ok(None);
3866 }
3867 let toward = normal.cross(a1);
3869 let cos = a1.dot(a2);
3870 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3871 let params = |cone: &ConicalSurface, p: Point3| {
3873 let (u, v) = cone.project_point(p);
3874 if v < 0.0 {
3875 ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3876 } else {
3877 (u, v)
3878 }
3879 };
3880 let mut curves = Vec::new();
3881 for nappe in [1.0, -1.0] {
3882 let t2 = nappe * s2;
3883 let side = cos.madd(-s1, t2) / sin;
3884 let foot = a1 * s1 + toward * side;
3885 let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3886 let rounding = 4.0 * f64::EPSILON;
3887 let lifts = if lift_sq.abs() <= rounding {
3888 if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3893 return Ok(None);
3894 }
3895 vec![0.0]
3896 } else if lift_sq < 0.0 {
3897 Vec::new()
3898 } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3899 vec![0.0]
3900 } else {
3901 vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3902 };
3903 let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3904 let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3905 if hi - lo <= tol {
3906 continue;
3907 }
3908 for lift in lifts {
3909 let d = (foot + normal * lift).normalize()?;
3910 let pieces = if lo < 0.0 && hi > 0.0 {
3911 vec![(lo, 0.0), (0.0, hi)]
3912 } else {
3913 vec![(lo, hi)]
3914 };
3915 for (from, to) in pieces {
3916 curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3917 (params(c1, p), params(c2, p))
3918 })?);
3919 }
3920 }
3921 }
3922 Ok(Some(curves))
3923}
3924
3925fn crossing_equal_cylinders(
3938 c1: &CylindricalSurface,
3939 c2: &CylindricalSurface,
3940) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3941 let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3942 if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3943 return Ok(None);
3944 }
3945 let bisectors = [d1 - d2, d1 + d2];
3950 let tol = Tolerance::new().linear;
3951 if bisectors
3952 .iter()
3953 .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3954 {
3955 return Ok(None);
3956 }
3957 let across = d1.cross(d2);
3958 let sin = across.length();
3959 let normal = across * (1.0 / sin);
3960 let w = c1.origin() - c2.origin();
3961 let cos = d1.dot(d2);
3962 let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3963 let centre = c1.origin() + d1 * along;
3964 let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3968 if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3969 return Ok(None);
3970 }
3971 let majors = bisectors.map(|bisector| {
3974 let length = bisector.length();
3975 let major = (bisector * (1.0 / length)).cross(normal);
3976 let major = if major.dot(d1) < 0.0 { -major } else { major };
3977 (major, 2.0 * r / length)
3978 });
3979 let corner = std::f64::consts::FRAC_1_SQRT_2;
3980 let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3981 let mut curves = Vec::with_capacity(2);
3982 for side in [1.0, -1.0] {
3983 let [(m1, a1), (m2, a2)] = majors;
3984 let out = half
3985 .iter()
3986 .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3987 let back = half[1..]
3988 .iter()
3989 .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3990 let curve = NurbsCurve::new(
3991 2,
3992 vec![
3993 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3994 ],
3995 out.chain(back).collect(),
3996 vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3997 )?;
3998 #[allow(clippy::cast_precision_loss)]
3999 let points = (0..=32)
4000 .map(|i| {
4001 let point = curve.evaluate(i as f64 / 32.0);
4002 IntersectionPoint {
4003 point,
4004 param1: c1.project_point(point),
4005 param2: c2.project_point(point),
4006 }
4007 })
4008 .collect();
4009 curves.push(IntersectionCurve { curve, points });
4010 }
4011 Ok(Some(curves))
4012}
4013
4014fn algebraic_cone_cone(
4023 c1: &ConicalSurface,
4024 c2: &ConicalSurface,
4025) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4026 let Some(exacts) = exact_cone_cone(c1, c2)? else {
4027 return Ok(None);
4028 };
4029 let mut curves = Vec::new();
4030 for exact in exacts {
4031 let n_samples = 33;
4032 let mut points = Vec::with_capacity(n_samples);
4033 #[allow(clippy::cast_precision_loss)]
4034 for i in 0..n_samples {
4035 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4036 let pt = match &exact {
4037 ExactIntersectionCurve::Circle(circle) => {
4038 crate::traits::ParametricCurve::evaluate(circle, theta)
4039 }
4040 ExactIntersectionCurve::Ellipse(ellipse) => {
4041 crate::traits::ParametricCurve::evaluate(ellipse, theta)
4042 }
4043 ExactIntersectionCurve::Points(_) => break,
4044 };
4045 points.push(IntersectionPoint {
4046 point: pt,
4047 param1: (0.0, 0.0),
4048 param2: (0.0, 0.0),
4049 });
4050 }
4051 let curve = match &exact {
4052 ExactIntersectionCurve::Circle(c) => {
4053 conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
4054 }
4055 ExactIntersectionCurve::Ellipse(e) => conic_loop(
4056 e.center(),
4057 e.u_axis(),
4058 e.v_axis(),
4059 e.semi_major(),
4060 e.semi_minor(),
4061 )?,
4062 ExactIntersectionCurve::Points(_) => continue,
4063 };
4064 curves.push(IntersectionCurve { curve, points });
4065 }
4066 Ok(Some(curves))
4067}
4068
4069pub fn exact_sphere_cylinder(
4089 sphere: &SphericalSurface,
4090 cyl: &CylindricalSurface,
4091) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4092 let sc = sphere.center();
4093 let r_sphere = sphere.radius();
4094 let co = cyl.origin();
4095 let axis = cyl.axis();
4096 let r_cyl = cyl.radius();
4097
4098 let delta = sc - co;
4100 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
4101 let along = delta_vec.dot(axis);
4102 let perp_vec = delta_vec - axis * along;
4103 let d_perp = perp_vec.length();
4104
4105 if d_perp > 1e-7 {
4108 return Ok(None);
4109 }
4110
4111 if r_cyl > r_sphere + 1e-10 {
4114 return Ok(Some(vec![]));
4115 }
4116 let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
4117 if z_sq < 0.0 {
4118 return Ok(Some(vec![]));
4119 }
4120 let z = z_sq.sqrt();
4121
4122 let center_axis_pt = Point3::new(
4125 co.x() + axis.x() * along,
4126 co.y() + axis.y() * along,
4127 co.z() + axis.z() * along,
4128 );
4129
4130 let mut circles = Vec::new();
4131 let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
4132 for &z_offset in offsets {
4133 let center = Point3::new(
4134 center_axis_pt.x() + axis.x() * z_offset,
4135 center_axis_pt.y() + axis.y() * z_offset,
4136 center_axis_pt.z() + axis.z() * z_offset,
4137 );
4138 let circle = Circle3D::new(center, axis, r_cyl)?;
4139 circles.push(ExactIntersectionCurve::Circle(circle));
4140 }
4141 Ok(Some(circles))
4142}
4143
4144pub fn exact_cone_sphere(
4162 cone: &ConicalSurface,
4163 sphere: &SphericalSurface,
4164) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4165 let offset = cone.apex() - sphere.center();
4166 let along = offset.dot(cone.axis());
4167 if (offset - cone.axis() * along).length() > 1e-7 {
4168 return Ok(None);
4169 }
4170 let lin_tol = Tolerance::new().linear;
4171 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4172 let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
4173 let b = 2.0 * sin_a * along;
4174 let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
4175 let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
4178 if disc < -noise {
4179 return Ok(Some(vec![]));
4180 }
4181 let roots: &[f64] = if far - near < lin_tol {
4182 &[far]
4183 } else {
4184 &[near, far]
4185 };
4186 let mut circles = Vec::new();
4187 for &v in roots {
4188 if v * cos_a > lin_tol {
4189 let centre = cone.apex() + cone.axis() * (v * sin_a);
4190 let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
4191 circles.push(ExactIntersectionCurve::Circle(circle));
4192 }
4193 }
4194 Ok(Some(circles))
4195}
4196
4197fn algebraic_sphere_cylinder(
4206 sphere: &SphericalSurface,
4207 cyl: &CylindricalSurface,
4208 sphere_first: bool,
4209) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4210 let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
4211 return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
4212 };
4213
4214 let mut curves = Vec::new();
4215 for exact in exacts {
4216 let ExactIntersectionCurve::Circle(circle) = exact else {
4217 continue;
4218 };
4219 let n_samples = 33;
4220 let mut points = Vec::with_capacity(n_samples);
4221 #[allow(clippy::cast_precision_loss)]
4222 for i in 0..n_samples {
4223 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4224 let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
4225 let (param1, param2) = in_order(
4226 sphere.project_point(pt),
4227 cyl.project_point(pt),
4228 sphere_first,
4229 );
4230 points.push(IntersectionPoint {
4231 point: pt,
4232 param1,
4233 param2,
4234 });
4235 }
4236 let r = circle.radius();
4237 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
4238 curves.push(IntersectionCurve { curve, points });
4239 }
4240
4241 Ok(Some(curves))
4242}
4243
4244fn off_axis_sphere_cylinder(
4253 sphere: &SphericalSurface,
4254 cyl: &CylindricalSurface,
4255 sphere_first: bool,
4256) -> Option<Vec<IntersectionCurve>> {
4257 let (centre, radius) = (sphere.center(), sphere.radius());
4258 let axis = cyl.axis();
4259 let offset = centre - cyl.origin();
4260 let axis_distance = (offset - axis * offset.dot(axis)).length();
4261 let lin_tol = Tolerance::new().linear;
4262 if axis_distance > radius + cyl.radius() + lin_tol
4263 || axis_distance + radius < cyl.radius() - lin_tol
4264 {
4265 return Some(Vec::new());
4266 }
4267 let roots = |u: f64| {
4268 let q = cyl.evaluate(u, 0.0) - centre;
4269 ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
4270 };
4271 let samples = ruling_samples(cyl, &roots);
4272 let loops = if samples.iter().all(Option::is_some) {
4273 closed_ruling_loops(cyl, &roots, &samples)
4274 } else {
4275 partial_ruling_loops(cyl, &roots, &samples)
4276 };
4277 if loops.is_empty() {
4278 return None;
4279 }
4280 Some(fit_ruling_loops(&loops, |p| {
4281 in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
4282 }))
4283}
4284
4285const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
4288 if a_first { (a, b) } else { (b, a) }
4289}
4290
4291fn parallel_cylinders(
4301 c1: &CylindricalSurface,
4302 c2: &CylindricalSurface,
4303 v_range_1: Option<(f64, f64)>,
4304 v_range_2: Option<(f64, f64)>,
4305) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4306 let axis = c1.axis();
4307 let delta = c2.origin() - c1.origin();
4308 let along = delta.dot(axis);
4309 let across = delta - axis * along;
4310 let d = across.length();
4311 let (r1, r2) = (c1.radius(), c2.radius());
4312 let flip = c2.axis().dot(axis);
4314 let ranges = [
4315 v_range_1,
4316 v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
4317 ];
4318 let (lo, hi) = ranges
4319 .into_iter()
4320 .flatten()
4321 .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
4322 (lo.max(a.min(b)), hi.min(a.max(b)))
4323 });
4324 if !lo.is_finite() || !hi.is_finite() {
4325 return Ok(None);
4326 }
4327 let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
4328 if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
4329 return Ok(Some(Vec::new()));
4330 }
4331 let toward = across * (1.0 / d);
4332 let side = axis.cross(toward);
4333 let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
4334 let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
4335 let linear = Tolerance::new().linear;
4336 let feet = if 2.0 * y <= linear {
4337 vec![toward * x]
4338 } else {
4339 vec![toward * x + side * y, toward * x - side * y]
4340 };
4341 let on_second = |p: Point3| {
4342 let w = p - c2.origin();
4343 ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
4344 };
4345 let mut rulings = Vec::with_capacity(feet.len());
4346 for foot in feet {
4347 let base = c1.origin() + foot;
4348 let (from, to) = (base + axis * lo, base + axis * hi);
4349 if !on_second(from) || !on_second(to) {
4350 return Ok(None);
4351 }
4352 rulings.push(ruling_segment(from, to, |p| {
4353 (c1.project_point(p), c2.project_point(p))
4354 })?);
4355 }
4356 Ok(Some(rulings))
4357}
4358
4359fn ruling_segment(
4362 from: Point3,
4363 to: Point3,
4364 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4365) -> Result<IntersectionCurve, MathError> {
4366 let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
4367 let points = [from, from + (to - from) * 0.5, to]
4368 .into_iter()
4369 .map(|point| {
4370 let (param1, param2) = params(point);
4371 IntersectionPoint {
4372 point,
4373 param1,
4374 param2,
4375 }
4376 })
4377 .collect();
4378 Ok(IntersectionCurve { curve, points })
4379}
4380
4381#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
4395fn algebraic_cylinder_cylinder(
4396 c1: &CylindricalSurface,
4397 c2: &CylindricalSurface,
4398) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4399 if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
4400 return Ok(Some(halves));
4401 }
4402 let alpha = c1.axis().dot(c2.axis());
4403 let a_coeff = 1.0 - alpha * alpha;
4404
4405 if a_coeff.abs() < 1e-12 {
4407 return Ok(None);
4408 }
4409
4410 let r1 = c1.radius();
4411 let r2 = c2.radius();
4412 let o1 = c1.origin();
4413 let o2 = c2.origin();
4414 let a1 = c1.axis();
4415 let a2 = c2.axis();
4416
4417 let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
4420 let cross = a1.cross(a2);
4421 let cross_len = cross.length();
4422 if cross_len > 1e-12 {
4423 let axis_dist = delta.dot(cross).abs() / cross_len;
4424 if axis_dist > r1 + r2 + Tolerance::new().linear {
4425 return Ok(Some(vec![])); }
4427 }
4428
4429 let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
4435 let (o, a, radius) = (other.origin(), other.axis(), other.radius());
4436 let alpha = sweep.axis().dot(a);
4437 let quad = 1.0 - alpha * alpha;
4438 let (axis, sweep) = (sweep.axis(), sweep.clone());
4439 move |u: f64| {
4440 let q = sweep.evaluate(u, 0.0) - o;
4441 let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
4442 let b = 2.0 * (q_a1 - alpha * q_a2);
4443 let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
4444 ruling_quadratic(quad, b, c)
4445 }
4446 };
4447 let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
4448 let samples1 = ruling_samples(c1, &roots1);
4449 let loops = if samples1.iter().all(Option::is_some) {
4450 closed_ruling_loops(c1, &roots1, &samples1)
4451 } else {
4452 let samples2 = ruling_samples(c2, &roots2);
4453 if samples2.iter().all(Option::is_some) {
4454 closed_ruling_loops(c2, &roots2, &samples2)
4455 } else if samples1.iter().any(Option::is_some) {
4456 partial_ruling_loops(c1, &roots1, &samples1)
4457 } else {
4458 partial_ruling_loops(c2, &roots2, &samples2)
4459 }
4460 };
4461 if loops.is_empty() {
4462 return Ok(None);
4463 }
4464 Ok(Some(fit_ruling_loops(&loops, |p| {
4465 (c1.project_point(p), c2.project_point(p))
4466 })))
4467}
4468
4469fn ruling_cone_cylinder(
4476 cone: &ConicalSurface,
4477 cyl: &CylindricalSurface,
4478 cone_first: bool,
4479) -> Option<Vec<IntersectionCurve>> {
4480 let (sin_t, cos_t) = cone.half_angle().sin_cos();
4481 if sin_t < 1e-12 || cos_t < 1e-12 {
4482 return None;
4483 }
4484 let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
4485 let s = 1.0 / (sin_t * sin_t);
4486 let alpha = w.dot(d);
4487 let quad = 1.0 - s * alpha * alpha;
4488 if quad.abs() < 1e-9 {
4489 return None;
4490 }
4491 let roots = |u: f64| {
4492 let delta = cyl.evaluate(u, 0.0) - apex;
4493 let (dd, dw) = (delta.dot(d), delta.dot(w));
4494 let b = 2.0 * (dw - s * dd * alpha);
4495 let c = delta.dot(delta) - s * dd * dd;
4496 ruling_quadratic(quad, b, c)
4497 };
4498 let lin_tol = Tolerance::new().linear;
4499 let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
4500 #[allow(clippy::cast_precision_loss)]
4501 let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
4502 let (disc, vp, vm) = roots(u);
4503 disc >= -lin_tol
4504 && [vp, vm]
4505 .iter()
4506 .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
4507 });
4508 if far_nappe {
4509 return None;
4510 }
4511 let samples = ruling_samples(cyl, &roots);
4512 let meeting: Vec<Option<(Point3, Point3)>> = samples
4516 .iter()
4517 .enumerate()
4518 .map(|(i, &pair)| pair.filter(|_| roots(ruling_u(i)).0 >= 0.0))
4519 .collect();
4520 let scan = WINDOW_SCAN * RULING_SAMPLES;
4526 #[allow(clippy::cast_precision_loss)]
4527 let scan_u = |k: usize| TAU * (k as f64 + 0.5) / scan as f64;
4528 let discs: Vec<f64> = (0..scan).map(|k| roots(scan_u(k)).0).collect();
4529 for k in 0..scan {
4533 let (before, here, after) = (
4534 discs[(k + scan - 1) % scan],
4535 discs[k],
4536 discs[(k + 1) % scan],
4537 );
4538 if here >= -lin_tol || here < before || here < after {
4539 continue;
4540 }
4541 let (mut lo, mut hi) = (scan_u(k) - TAU / scan as f64, scan_u(k) + TAU / scan as f64);
4542 for _ in 0..100 {
4543 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4544 if roots(a).0 < roots(b).0 {
4545 lo = a;
4546 } else {
4547 hi = b;
4548 }
4549 }
4550 if roots(f64::midpoint(lo, hi)).0 >= -lin_tol {
4551 return None;
4552 }
4553 }
4554 let meets = |k: usize| discs[k % scan] >= -lin_tol;
4557 if let Some(start) = (0..scan).find(|&k| !meets(k)) {
4558 let mut k = start;
4559 while k < start + scan {
4560 if !meets(k) {
4561 k += 1;
4562 continue;
4563 }
4564 let first = k;
4565 while k < start + scan && meets(k) {
4566 k += 1;
4567 }
4568 let sampled = (first..k).any(|j| {
4569 j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1
4570 && meeting[(j / WINDOW_SCAN) % RULING_SAMPLES].is_some()
4571 });
4572 if !sampled {
4573 return None;
4574 }
4575 }
4576 }
4577 let loops = if samples.iter().all(Option::is_some) {
4578 closed_ruling_loops(cyl, &roots, &samples)
4579 } else {
4580 partial_ruling_loops(cyl, &roots, &meeting)
4581 };
4582 if loops.is_empty() {
4583 return None;
4584 }
4585 Some(fit_ruling_loops(&loops, |p| {
4586 in_order(cone.project_point(p), cyl.project_point(p), cone_first)
4587 }))
4588}
4589
4590fn ruling_torus_cylinder(
4600 torus: &ToroidalSurface,
4601 cyl: &CylindricalSurface,
4602 torus_first: bool,
4603) -> Option<Vec<IntersectionCurve>> {
4604 if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
4605 || torus.minor_radius() >= torus.major_radius()
4606 {
4607 return None;
4608 }
4609 let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
4610 let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
4611 let count = rows[0].len();
4612 let scan = WINDOW_SCAN * RULING_SAMPLES;
4613 #[allow(clippy::cast_precision_loss)]
4614 if count == 0
4615 || count % 2 == 1
4616 || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
4617 {
4618 return None;
4619 }
4620 let loops: Vec<Vec<Point3>> = (0..count)
4621 .map(|j| {
4622 let mut pts: Vec<Point3> = rows
4623 .iter()
4624 .enumerate()
4625 .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
4626 .collect();
4627 pts.push(pts[0]);
4628 pts
4629 })
4630 .collect();
4631 Some(fit_ruling_loops(&loops, |p| {
4632 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
4633 }))
4634}
4635
4636fn ruling_cone_sphere(
4645 cone: &ConicalSurface,
4646 sphere: &SphericalSurface,
4647 cone_first: bool,
4648) -> Option<Vec<IntersectionCurve>> {
4649 let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
4650 let offset = apex - centre;
4651 let lin_tol = Tolerance::new().linear;
4652 let along = offset.dot(cone.axis());
4653 let across = (offset - cone.axis() * along).length();
4654 if across < lin_tol {
4655 return None;
4656 }
4657 let k = offset.dot(offset) - radius * radius;
4663 if radius - offset.length() > lin_tol {
4664 let exit = |u: f64| {
4665 let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
4666 let root = h.madd(h, -k).sqrt();
4667 cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
4668 };
4669 let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
4674 .map(|i| (ruling_u(i), exit(ruling_u(i))))
4675 .collect();
4676 for _ in 0..10 {
4677 let mut refined = Vec::with_capacity(2 * samples.len());
4678 for pair in samples.windows(2) {
4679 let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
4680 refined.push(pair[0]);
4681 let um = 0.5 * (u0 + u1);
4682 let pm = exit(um);
4683 let chord = (p1 - p0).length();
4684 if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
4685 refined.push((um, pm));
4686 }
4687 }
4688 refined.extend(samples.last().copied());
4689 if refined.len() == samples.len() {
4690 break;
4691 }
4692 samples = refined;
4693 }
4694 let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
4695 if let Some(last) = pts.last_mut() {
4696 *last = samples[0].1;
4697 }
4698 return Some(fit_ruling_loops(&[pts], |p| {
4699 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4700 }));
4701 }
4702 let crossing = |h: f64| {
4706 let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
4707 (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
4708 };
4709 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4714 if crossing(sin_a.madd(along, cos_a * across)).is_none()
4715 || crossing(sin_a.madd(along, -cos_a * across)).is_none()
4716 {
4717 return window_cone_sphere(cone, sphere, cone_first);
4718 }
4719 let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
4720 .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
4721 .collect::<Option<_>>()?;
4722 let loops: Vec<Vec<Point3>> = [0, 1]
4723 .iter()
4724 .map(|&j| {
4725 let mut pts: Vec<Point3> = rows
4726 .iter()
4727 .enumerate()
4728 .map(|(i, &(near, far))| {
4729 cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4730 })
4731 .collect();
4732 pts.push(pts[0]);
4733 pts
4734 })
4735 .collect();
4736 Some(fit_ruling_loops(&loops, |p| {
4737 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4738 }))
4739}
4740
4741fn window_cone_sphere(
4756 cone: &ConicalSurface,
4757 sphere: &SphericalSurface,
4758 cone_first: bool,
4759) -> Option<Vec<IntersectionCurve>> {
4760 let offset = cone.apex() - sphere.center();
4761 let lin_tol = Tolerance::new().linear;
4762 if offset.length() - sphere.radius() <= lin_tol {
4763 return None;
4764 }
4765 let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4766 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4767 let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4768 let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4769 if a < lin_tol {
4770 return None;
4771 }
4772 let reach = (-k.sqrt() - c) / a;
4773 if reach <= -1.0 {
4774 return Some(Vec::new());
4775 }
4776 if reach >= 1.0 {
4777 return None;
4778 }
4779 let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4780 let half = std::f64::consts::PI - half;
4781 let n = RULING_SAMPLES;
4782 let mut pts: Vec<Point3> = (0..n)
4783 .map(|i| {
4784 #[allow(clippy::cast_precision_loss)]
4785 let theta = TAU * i as f64 / n as f64;
4786 let u = half.madd(-theta.cos(), mid);
4787 let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4788 let split = h.madd(h, -k).max(0.0).sqrt();
4789 cone.evaluate(u, -h - split.copysign(theta.sin()))
4790 })
4791 .collect();
4792 pts.push(pts[0]);
4793 Some(fit_ruling_loops(&[pts], |p| {
4794 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4795 }))
4796}
4797
4798const WINDOW_SCAN: usize = 16;
4801
4802const RULING_SAMPLES: usize = 128;
4806
4807#[allow(clippy::cast_precision_loss)]
4808fn ruling_u(i: usize) -> f64 {
4809 TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4810}
4811
4812fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4814 let disc = b * b - 4.0 * quad * c;
4815 let root = disc.max(0.0).sqrt();
4816 (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4817}
4818
4819fn ruling_samples(
4823 sweep: &CylindricalSurface,
4824 roots: &impl Fn(f64) -> (f64, f64, f64),
4825) -> Vec<Option<(Point3, Point3)>> {
4826 let lin_tol = Tolerance::new().linear;
4827 (0..RULING_SAMPLES)
4828 .map(|i| {
4829 let u = ruling_u(i);
4830 let (disc, vp, vm) = roots(u);
4831 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4832 })
4833 .collect()
4834}
4835
4836fn closed_ruling_loops(
4843 sweep: &CylindricalSurface,
4844 roots: &impl Fn(f64) -> (f64, f64, f64),
4845 samples: &[Option<(Point3, Point3)>],
4846) -> Vec<Vec<Point3>> {
4847 let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4848 if let Some((neck, touching)) = narrowest_ruling(roots) {
4849 let count = 2 * RULING_SAMPLES;
4850 #[allow(clippy::cast_precision_loss)]
4851 (0..count)
4852 .map(|i| {
4853 let t = i as f64 / count as f64;
4854 let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4855 let (_, vp, vm) = roots(u);
4856 if i == 0 && touching {
4857 let at = sweep.evaluate(u, 0.5 * (vp + vm));
4858 (at, at)
4859 } else {
4860 (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4861 }
4862 })
4863 .unzip()
4864 } else {
4865 samples.iter().flatten().copied().unzip()
4866 };
4867 plus.push(plus[0]);
4868 minus.push(minus[0]);
4869 vec![plus, minus]
4870}
4871
4872fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4880 let scan = WINDOW_SCAN * RULING_SAMPLES;
4881 #[allow(clippy::cast_precision_loss)]
4882 let step = TAU / scan as f64;
4883 let gap = |u: f64| {
4884 let (_, vp, vm) = roots(u);
4885 (vp - vm).abs()
4886 };
4887 #[allow(clippy::cast_precision_loss)]
4888 let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4889 let widest = gaps.iter().copied().fold(0.0, f64::max);
4890 let tol = Tolerance::new().linear * (1.0 + widest);
4891 let mut necks = Vec::new();
4892 for k in 0..scan {
4893 let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4894 if here > before || here >= after || here >= 0.25 * widest {
4895 continue;
4896 }
4897 #[allow(clippy::cast_precision_loss)]
4898 let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4899 for _ in 0..100 {
4900 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4901 if gap(a) < gap(b) {
4902 hi = b;
4903 } else {
4904 lo = a;
4905 }
4906 }
4907 let u = 0.5 * (lo + hi);
4908 necks.push((u, gap(u) <= tol));
4909 }
4910 match necks[..] {
4911 [neck] => Some(neck),
4912 _ => None,
4913 }
4914}
4915
4916fn partial_ruling_loops(
4927 sweep: &CylindricalSurface,
4928 roots: &impl Fn(f64) -> (f64, f64, f64),
4929 samples: &[Option<(Point3, Point3)>],
4930) -> Vec<Vec<Point3>> {
4931 let lin_tol = Tolerance::new().linear;
4932 let branch_u = |inside: usize, outside: usize| -> f64 {
4935 let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4936 if (hi - lo).abs() > std::f64::consts::PI {
4937 hi += if hi < lo { TAU } else { -TAU };
4938 }
4939 for _ in 0..60 {
4940 let mid = 0.5 * (lo + hi);
4941 if roots(mid).0 >= 0.0 {
4942 lo = mid;
4943 } else {
4944 hi = mid;
4945 }
4946 }
4947 lo
4948 };
4949 let joint = |u: f64| {
4950 let (_, vp, vm) = roots(u);
4951 sweep.evaluate(u, 0.5 * (vp + vm))
4952 };
4953 let Some(first_gap) = samples.iter().position(Option::is_none) else {
4954 return Vec::new();
4955 };
4956 let mut loops = Vec::new();
4957 let mut k = 0;
4958 while k < RULING_SAMPLES {
4959 let i = (first_gap + k) % RULING_SAMPLES;
4960 if samples[i].is_none() {
4961 k += 1;
4962 continue;
4963 }
4964 let start = i;
4965 let mut run = Vec::new();
4966 while k < RULING_SAMPLES {
4967 let j = (first_gap + k) % RULING_SAMPLES;
4968 let Some(pair) = samples[j] else { break };
4969 run.push(pair);
4970 k += 1;
4971 }
4972 let end = (start + run.len() - 1) % RULING_SAMPLES;
4973 let u_head = branch_u(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4974 let u_tail = branch_u(end, (end + 1) % RULING_SAMPLES);
4975 let span = (u_tail - u_head).rem_euclid(TAU);
4976 #[allow(clippy::cast_precision_loss)]
4977 let fresh: Option<Vec<(Point3, Point3)>> = (1..RULING_SAMPLES)
4978 .map(|n| {
4979 let t = n as f64 / RULING_SAMPLES as f64;
4980 let u = span.madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), u_head);
4981 let (disc, vp, vm) = roots(u);
4982 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4983 })
4984 .collect();
4985 let run = fresh.unwrap_or(run);
4988 let (head, tail) = (joint(u_head), joint(u_head + span));
4989 let mut pts = vec![head];
4990 pts.extend(run.iter().map(|p| p.0));
4991 pts.push(tail);
4992 pts.extend(run.iter().rev().map(|p| p.1));
4993 pts.push(head);
4994 loops.push(pts);
4995 }
4996 loops
4997}
4998
4999fn fit_ruling_loops(
5002 loops: &[Vec<Point3>],
5003 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
5004) -> Vec<IntersectionCurve> {
5005 let mut curves = Vec::new();
5006 for pts in loops {
5007 if pts.len() < 4 {
5008 continue;
5009 }
5010 let ipts: Vec<IntersectionPoint> = pts
5011 .iter()
5012 .map(|&p| {
5013 let (param1, param2) = params(p);
5014 IntersectionPoint {
5015 point: p,
5016 param1,
5017 param2,
5018 }
5019 })
5020 .collect();
5021 let degree = 3.min(pts.len() - 1);
5022 if let Ok(curve) = interpolate(pts, degree) {
5023 curves.push(IntersectionCurve {
5024 curve,
5025 points: ipts,
5026 });
5027 }
5028 }
5029 curves
5030}
5031
5032#[allow(clippy::unnecessary_wraps)]
5058fn algebraic_parallel_cone_cylinder(
5059 cone: &ConicalSurface,
5060 cyl: &CylindricalSurface,
5061 v_range_cone: Option<(f64, f64)>,
5062 v_range_cyl: Option<(f64, f64)>,
5063) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
5064 let axis = cone.axis();
5065 if axis.cross(cyl.axis()).length() > Tolerance::new().angular {
5066 return Ok(None); }
5068
5069 let apex = cone.apex();
5070 let delta = cyl.origin() - apex;
5071 let along = delta.dot(axis);
5072 let perp = delta - axis * along;
5073 let d = perp.length();
5074 if d < 1e-9 {
5075 return Ok(None); }
5077
5078 let (e1, e2) = (cone.x_axis(), cone.y_axis());
5079 let phi0 = perp.dot(e2).atan2(perp.dot(e1));
5080
5081 let (sin_t, cos_t) = cone.half_angle().sin_cos();
5082 if cos_t < 1e-12 || sin_t < 1e-12 {
5083 return Ok(None);
5084 }
5085 let r = cyl.radius();
5086
5087 let mut v_min = (d - r).abs() / cos_t;
5089 let mut v_max = (d + r) / cos_t;
5090 if v_max <= v_min {
5091 return Ok(Some(vec![]));
5092 }
5093
5094 let mut lo = v_min;
5100 let mut hi = v_max;
5101 if let Some((a, b)) = v_range_cone {
5106 let (a, b) = if a <= b { (a, b) } else { (b, a) };
5107 lo = lo.max(a);
5108 hi = hi.min(b);
5109 }
5110 if let Some((a, b)) = v_range_cyl {
5111 let flip = cyl.axis().dot(axis);
5114 let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
5115 let (a, b) = (to_cone_v(a), to_cone_v(b));
5116 let (a, b) = if a <= b { (a, b) } else { (b, a) };
5117 lo = lo.max(a);
5118 hi = hi.min(b);
5119 }
5120 let (turn_lo, turn_hi) = (v_min, v_max);
5121 v_min = lo.max(v_min);
5122 v_max = hi.min(v_max);
5123 if v_max - v_min <= 1e-12 {
5124 return Ok(Some(vec![]));
5125 }
5126 let slack = Tolerance::new().linear;
5134 #[allow(clippy::cast_precision_loss)]
5135 let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
5136 if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
5137 let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
5138 .map(|i| {
5139 let (sin_u, cos_u) = ruling_u(i).sin_cos();
5140 let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
5141 let off = foot - apex;
5142 let across = off - axis * off.dot(axis);
5143 apex + across + axis * (across.length() * sin_t / cos_t)
5144 })
5145 .collect();
5146 pts.push(pts[0]);
5147 return Ok(Some(fit_ruling_loops(&[pts], |p| {
5148 (cone.project_point(p), cyl.project_point(p))
5149 })));
5150 }
5151
5152 let n_samples = 128;
5153 let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5154 let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5155 #[allow(clippy::cast_precision_loss)]
5156 for i in 0..=n_samples {
5157 let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
5158 let rho = v * cos_t;
5159 if rho < 1e-12 {
5160 if (d - r).abs() < 1e-12 {
5168 let apex = cone.evaluate(phi0, v);
5169 plus.push(apex);
5170 minus.push(apex);
5171 }
5172 continue;
5173 }
5174 let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
5175 let alpha = cos_alpha.acos();
5176 plus.push(cone.evaluate(phi0 + alpha, v));
5177 minus.push(cone.evaluate(phi0 - alpha, v));
5178 }
5179
5180 let mut curves = Vec::new();
5181 for pts in [&plus, &minus] {
5182 if pts.len() < 4 {
5185 continue;
5186 }
5187 let ipts: Vec<IntersectionPoint> = pts
5188 .iter()
5189 .map(|&p| IntersectionPoint {
5190 point: p,
5191 param1: cone.project_point(p),
5192 param2: cyl.project_point(p),
5193 })
5194 .collect();
5195 let degree = 3.min(pts.len() - 1);
5196 match interpolate(pts, degree) {
5197 Ok(curve) => curves.push(IntersectionCurve {
5198 curve,
5199 points: ipts,
5200 }),
5201 Err(_) => return Ok(None),
5206 }
5207 }
5208
5209 Ok(Some(curves))
5210}
5211
5212const PARALLEL_CONES_FIT_ROUNDS: usize = 8;
5215
5216fn cone_wall_distance(cone: &ConicalSurface, p: Point3) -> f64 {
5219 let rel = p - cone.apex();
5220 let along = rel.dot(cone.axis());
5221 let across = (rel - cone.axis() * along).length();
5222 let (sin, cos) = cone.half_angle().sin_cos();
5223 across.madd(sin, -along * cos)
5224}
5225
5226fn algebraic_parallel_cone_cone(
5250 c1: &ConicalSurface,
5251 c2: &ConicalSurface,
5252 v_range_1: Option<(f64, f64)>,
5253 v_range_2: Option<(f64, f64)>,
5254) -> Option<Vec<IntersectionCurve>> {
5255 let tol = Tolerance::new();
5256 if [v_range_1, v_range_2]
5258 .into_iter()
5259 .flatten()
5260 .any(|(p, q)| p.min(q) < -tol.linear)
5261 {
5262 return None;
5263 }
5264 let axis = c1.axis();
5265 if axis.cross(c2.axis()).length() > tol.angular {
5266 return None;
5267 }
5268 let sigma = axis.dot(c2.axis()).signum();
5269 let delta = c2.apex() - c1.apex();
5270 let along = delta.dot(axis);
5271 let perp = delta - axis * along;
5272 let d = perp.length();
5273 if d < 1e-9 {
5274 return None;
5275 }
5276 let phi0 = perp.dot(c1.y_axis()).atan2(perp.dot(c1.x_axis()));
5277 let (sin1, cos1) = c1.half_angle().sin_cos();
5278 let (sin2, cos2) = c2.half_angle().sin_cos();
5279 if [sin1, cos1, sin2, cos2].iter().any(|&x| x < 1e-12) {
5280 return None;
5281 }
5282 let slope2 = cos2 / sin2;
5285 let (a, b) = (-sigma * along * slope2, sigma * sin1 * slope2);
5286 let (mut lo, mut hi) = (0.0_f64, f64::INFINITY);
5288 let (mut lo_touch, mut hi_touch) = (false, false);
5289 for (k, c, touch) in [
5292 (b, a, false),
5293 (cos1 + b, a - d, true),
5294 (b - cos1, a + d, true),
5295 (cos1 - b, d - a, true),
5296 ] {
5297 if k > 0.0 {
5300 if -c / k > lo {
5301 (lo, lo_touch) = (-c / k, touch);
5302 }
5303 } else if k < 0.0 {
5304 if -c / k < hi {
5305 (hi, hi_touch) = (-c / k, touch);
5306 }
5307 } else if c < 0.0 {
5308 return Some(Vec::new());
5309 }
5310 }
5311 let mut clip = |p: f64, q: f64| {
5312 if p.min(q) > lo {
5313 (lo, lo_touch) = (p.min(q), false);
5314 }
5315 if p.max(q) < hi {
5316 (hi, hi_touch) = (p.max(q), false);
5317 }
5318 };
5319 if let Some((p, q)) = v_range_1 {
5320 clip(p, q);
5321 }
5322 if let Some((p, q)) = v_range_2 {
5323 let to_v1 = |v2: f64| sigma.madd(v2 * sin2, along) / sin1;
5324 clip(to_v1(p), to_v1(q));
5325 }
5326 if !hi.is_finite() {
5327 return None;
5328 }
5329 if hi - lo <= 1e-12 {
5330 return Some(Vec::new());
5331 }
5332
5333 let at = |v: f64, touch: bool| -> Option<(Point3, Point3)> {
5335 let rho1 = v * cos1;
5336 let rho2 = b.madd(v, a);
5337 if rho1 < 1e-12 {
5338 return ((rho2 - d).abs() < 1e-12).then(|| (c1.apex(), c1.apex()));
5341 }
5342 let cos_alpha = (d.madd(d, rho1 * rho1) - rho2 * rho2) / (2.0 * d * rho1);
5343 if touch {
5344 let p = c1.evaluate(
5347 if cos_alpha >= 0.0 {
5348 phi0
5349 } else {
5350 phi0 + std::f64::consts::PI
5351 },
5352 v,
5353 );
5354 return Some((p, p));
5355 }
5356 let alpha = cos_alpha.clamp(-1.0, 1.0).acos();
5357 Some((c1.evaluate(phi0 + alpha, v), c1.evaluate(phi0 - alpha, v)))
5358 };
5359 let v_at = |t: f64| (hi - lo).madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), lo);
5362 let n_samples = 128;
5363 let mut plus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5364 let mut minus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5365 #[allow(clippy::cast_precision_loss)]
5366 for i in 0..=n_samples {
5367 let t = i as f64 / n_samples as f64;
5368 let touch = (i == 0 && lo_touch) || (i == n_samples && hi_touch);
5369 if let Some((p, m)) = at(v_at(t), touch) {
5370 plus.push((t, p));
5371 minus.push((t, m));
5372 }
5373 }
5374
5375 let off = |p: Point3| {
5376 cone_wall_distance(c1, p)
5377 .abs()
5378 .max(cone_wall_distance(c2, p).abs())
5379 };
5380 let mut curves = Vec::new();
5381 for (branch, side) in [(&mut plus, 0), (&mut minus, 1)] {
5382 if branch.len() < 4 {
5383 continue;
5384 }
5385 let mut rounds = 0;
5386 let curve = loop {
5389 let positions: Vec<Point3> = branch.iter().map(|&(_, p)| p).collect();
5390 let curve = interpolate(&positions, 3).ok()?;
5391 let params = crate::nurbs::fitting::chord_length_params(&positions);
5392 let errors: Vec<f64> = (0..positions.len() - 1)
5393 .map(|k| off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))))
5394 .collect();
5395 if errors.iter().all(|&e| e <= 0.25 * tol.linear) {
5396 break curve;
5397 }
5398 if rounds == PARALLEL_CONES_FIT_ROUNDS {
5399 return None;
5400 }
5401 rounds += 1;
5402 let mut split: Vec<usize> = (0..errors.len())
5406 .filter(|&k| errors[k] > 0.0625 * tol.linear)
5407 .flat_map(|k| {
5408 let stray = errors[k] > 0.25 * tol.linear;
5409 let (first, last) = if stray {
5410 (k.saturating_sub(1), k + 1)
5411 } else {
5412 (k, k)
5413 };
5414 first..=last.min(errors.len() - 1)
5415 })
5416 .collect();
5417 split.sort_unstable();
5418 split.dedup();
5419 for &k in split.iter().rev() {
5420 let t = f64::midpoint(branch[k].0, branch[k + 1].0);
5421 let (p, m) = at(v_at(t), false)?;
5422 branch.insert(k + 1, (t, if side == 0 { p } else { m }));
5423 }
5424 };
5425 let points = branch
5426 .iter()
5427 .map(|&(_, p)| IntersectionPoint {
5428 point: p,
5429 param1: c1.project_point(p),
5430 param2: c2.project_point(p),
5431 })
5432 .collect();
5433 curves.push(IntersectionCurve { curve, points });
5434 }
5435 Some(curves)
5436}
5437
5438fn algebraic_sphere_sphere(
5446 s1: &SphericalSurface,
5447 s2: &SphericalSurface,
5448) -> Result<Vec<IntersectionCurve>, MathError> {
5449 let c1 = s1.center();
5450 let c2 = s2.center();
5451 let r1 = s1.radius();
5452 let r2 = s2.radius();
5453
5454 let delta = c2 - c1;
5455 let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
5456 let d = d_sq.sqrt();
5457
5458 if d < 1e-12 {
5459 return Ok(vec![]);
5461 }
5462
5463 if d > r1 + r2 + 1e-10 {
5465 return Ok(vec![]); }
5467 if d + r2.min(r1) + 1e-10 < r1.max(r2) {
5468 return Ok(vec![]); }
5470
5471 let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
5473
5474 let r_circle_sq = r1 * r1 - d1 * d1;
5476 if r_circle_sq < 0.0 {
5477 if r_circle_sq > -1e-10 {
5479 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5481 let tangent_pt = Point3::new(
5482 c1.x() + axis.x() * d1,
5483 c1.y() + axis.y() * d1,
5484 c1.z() + axis.z() * d1,
5485 );
5486 let ipt = IntersectionPoint {
5487 point: tangent_pt,
5488 param1: (0.0, 0.0),
5489 param2: (0.0, 0.0),
5490 };
5491 return Ok(vec![IntersectionCurve {
5493 curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
5494 points: vec![ipt],
5495 }]);
5496 }
5497 return Ok(vec![]);
5498 }
5499
5500 let r_circle = r_circle_sq.sqrt();
5501 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5502 let center = Point3::new(
5503 c1.x() + axis.x() * d1,
5504 c1.y() + axis.y() * d1,
5505 c1.z() + axis.z() * d1,
5506 );
5507
5508 let basis = Frame3::from_normal(center, axis)?;
5510 let u_dir = basis.x;
5511 let v_dir = basis.y;
5512
5513 let n_samples = 33; let mut points = Vec::with_capacity(n_samples);
5516 #[allow(clippy::cast_precision_loss)]
5517 for i in 0..n_samples {
5518 let theta = TAU * i as f64 / (n_samples - 1) as f64;
5519 let (sin_t, cos_t) = theta.sin_cos();
5520 let pt = Point3::new(
5521 center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
5522 center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
5523 center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
5524 );
5525 points.push(IntersectionPoint {
5526 point: pt,
5527 param1: (0.0, 0.0),
5528 param2: (0.0, 0.0),
5529 });
5530 }
5531
5532 let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
5533
5534 Ok(vec![IntersectionCurve { curve, points }])
5535}
5536
5537#[allow(clippy::too_many_arguments)]
5543fn correct_to_intersection(
5544 a: &AnalyticSurface<'_>,
5545 b: &AnalyticSurface<'_>,
5546 surf_a: &dyn Fn(f64, f64) -> Point3,
5547 norm_a: &dyn Fn(f64, f64) -> Vec3,
5548 surf_b: &dyn Fn(f64, f64) -> Point3,
5549 norm_b: &dyn Fn(f64, f64) -> Vec3,
5550 point: Point3,
5551 u_range_a: (f64, f64),
5552 v_range_a: (f64, f64),
5553 u_range_b: (f64, f64),
5554 v_range_b: (f64, f64),
5555 max_iters: usize,
5556) -> Point3 {
5557 let mut p = point;
5558 for _ in 0..max_iters {
5559 let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
5560 let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
5561 let pa = surf_a(ua, va);
5562 let pb = surf_b(ub, vb);
5563 let na = norm_a(ua, va);
5564 let nb = norm_b(ub, vb);
5565 let pv = Vec3::new(p.x(), p.y(), p.z());
5566
5567 let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
5568 let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
5569
5570 if da.abs() < 1e-7 && db.abs() < 1e-7 {
5571 break;
5572 }
5573
5574 let t = na.cross(nb);
5575 let t_len = t.length();
5576 if t_len < 1e-10 {
5577 return Point3::new(
5579 (pa.x() + pb.x()) * 0.5,
5580 (pa.y() + pb.y()) * 0.5,
5581 (pa.z() + pb.z()) * 0.5,
5582 );
5583 }
5584 let t_hat = t * (1.0 / t_len);
5585
5586 let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5588 - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5589 + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
5590 if det.abs() < 1e-15 {
5591 return Point3::new(
5592 (pa.x() + pb.x()) * 0.5,
5593 (pa.y() + pb.y()) * 0.5,
5594 (pa.z() + pb.z()) * 0.5,
5595 );
5596 }
5597 let inv = 1.0 / det;
5598 let dx = inv
5600 * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5601 + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
5602 let dy = inv
5603 * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5604 - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
5605 let dz = inv
5606 * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
5607 + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
5608 let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
5609
5610 let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
5613 let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
5614 let pc_a = surf_a(uc, vc);
5615 let pc_b = surf_b(ud, vd);
5616 let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
5617 let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
5618 .dot(norm_a(uc, vc))
5619 .abs();
5620 let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
5621 .dot(norm_b(ud, vd))
5622 .abs();
5623 if da_new > da.abs() && db_new > db.abs() {
5624 return p;
5625 }
5626
5627 p = candidate;
5628 }
5629 p
5630}
5631
5632const MARCH_TURN: f64 = 0.2;
5634
5635const MARCH_BASIN: f64 = 0.25;
5638
5639const MARCH_STEPS: usize = 4096;
5641
5642#[derive(Clone, Copy)]
5645struct Station {
5646 p: Point3,
5647 t: Vec3,
5649 bend: f64,
5651 gap: f64,
5655}
5656
5657fn station(
5668 a: &AnalyticSurface<'_>,
5669 b: &AnalyticSurface<'_>,
5670 p: Point3,
5671 toward: Vec3,
5672) -> Option<Station> {
5673 use section_fit::Carrier;
5674 let (_, na) = a.distance(p)?;
5675 let (_, nb) = b.distance(p)?;
5676 let cross = na.cross(nb);
5677 let sin = cross.length();
5678 if sin < 1e-6 {
5679 return None;
5680 }
5681 let mut t = cross * (1.0 / sin);
5682 if t.dot(toward) < 0.0 {
5683 t = -t;
5684 }
5685 let (ka, kb) = (a.bend(p, t)?, b.bend(p, t)?);
5686 let c = na.dot(nb);
5687 let det = sin * sin;
5688 let along_a = c.madd(kb, -ka) / det;
5689 let along_b = c.madd(ka, -kb) / det;
5690 let bend = (2.0 * along_a * along_b)
5691 .madd(c, along_a.madd(along_a, along_b * along_b))
5692 .max(0.0)
5693 .sqrt();
5694 let (qa, qb) = (a.bend(p, t.cross(na))?, b.bend(p, t.cross(nb))?);
5695 let spread = qa.abs() + qb.abs();
5696 let gap = if spread > 0.0 {
5697 2.0 * sin / spread
5698 } else {
5699 f64::INFINITY
5700 };
5701 bend.is_finite().then_some(Station { p, t, bend, gap })
5702}
5703
5704impl Station {
5705 fn reach(&self, longest: f64) -> f64 {
5709 if self.bend > 0.0 {
5710 longest
5711 .min(MARCH_TURN / self.bend)
5712 .min((2.0 * MARCH_BASIN * self.gap / self.bend).sqrt())
5713 } else {
5714 longest
5715 }
5716 }
5717}
5718
5719fn singular_point(
5742 a: &AnalyticSurface<'_>,
5743 b: &AnalyticSurface<'_>,
5744 p: Point3,
5745 reach: f64,
5746) -> Option<Point3> {
5747 use section_fit::Carrier;
5748 let axes = [
5749 Vec3::new(1.0, 0.0, 0.0),
5750 Vec3::new(0.0, 1.0, 0.0),
5751 Vec3::new(0.0, 0.0, 1.0),
5752 ];
5753 let miss = |x: Point3| {
5754 let (Some((da, na)), Some((_, nb))) = (a.distance(x), b.distance(x)) else {
5755 return f64::INFINITY;
5756 };
5757 da.hypot(reach * na.cross(nb).length())
5758 };
5759 let mut best: Option<(f64, Point3, bool)> = None;
5760 let mut q = p;
5761 for _ in 0..32 {
5762 let (da, na) = a.distance(q)?;
5763 let (db, nb) = b.distance(q)?;
5764 let cross = na.cross(nb);
5765 let mut hessians = [[Vec3::new(0.0, 0.0, 0.0); 3]; 2];
5766 for (h, s) in hessians.iter_mut().zip([a, b]) {
5767 for (j, &v) in axes.iter().enumerate() {
5768 let mut row = [0.0; 3];
5769 for (k, &e) in axes.iter().enumerate() {
5770 row[k] = 0.25 * (s.bend(q, e + v)? - s.bend(q, e - v)?);
5771 }
5772 h[j] = Vec3::new(row[0], row[1], row[2]);
5773 }
5774 }
5775 let curvature = |h: &[Vec3; 3]| h.iter().fold(0.0, |m: f64, v| m.max(v.length()));
5776 let (ka, kb) = (curvature(&hessians[0]), curvature(&hessians[1]));
5777 let near = 64.0 * f64::EPSILON * (a.scale(q) + b.scale(q));
5778 let parallel = (64.0 * f64::EPSILON * ka.madd(a.scale(q), kb.madd(b.scale(q), 2.0)))
5779 .max(f64::EPSILON.sqrt());
5780 let here = cross.length();
5781 let holds = da.abs() <= near && db.abs() <= near && here <= parallel;
5782 if best.is_none_or(|(c, _, _)| here < c) {
5783 best = Some((here, q, holds));
5784 }
5785 let mut rows = vec![(na, da)];
5788 for (k, &e) in axes.iter().enumerate() {
5789 let grad = Vec3::new(
5790 (hessians[0][0].cross(nb) + na.cross(hessians[1][0])).dot(e),
5791 (hessians[0][1].cross(nb) + na.cross(hessians[1][1])).dot(e),
5792 (hessians[0][2].cross(nb) + na.cross(hessians[1][2])).dot(e),
5793 );
5794 let value = [cross.x(), cross.y(), cross.z()][k];
5795 rows.push((grad * reach, value * reach));
5796 }
5797 let mut m = [[0.0; 3]; 3];
5798 let mut rhs = [0.0; 3];
5799 for (g, r) in &rows {
5800 let g = [g.x(), g.y(), g.z()];
5801 for i in 0..3 {
5802 rhs[i] -= g[i] * r;
5803 for j in 0..3 {
5804 m[i][j] = g[i].madd(g[j], m[i][j]);
5805 }
5806 }
5807 }
5808 let damp = 1e-12 * (m[0][0] + m[1][1] + m[2][2]);
5809 for (i, row) in m.iter_mut().enumerate() {
5810 row[i] += damp;
5811 }
5812 let Some(step) = solve3(m, rhs) else {
5813 break;
5814 };
5815 let onto_a = |x: Point3| a.distance(x).map_or(x, |(d, n)| x - n * d);
5818 let next = [1.0, 2.0, 3.0]
5819 .iter()
5820 .map(|&k| onto_a(q + step * k))
5821 .min_by(|x, y| miss(*x).total_cmp(&miss(*y)))?;
5822 if (next - p).length() > reach || miss(next) >= miss(q) {
5823 break;
5824 }
5825 q = next;
5826 }
5827 best.and_then(|(_, x, holds)| holds.then_some(x))
5828}
5829
5830fn solve3(m: [[f64; 3]; 3], rhs: [f64; 3]) -> Option<Vec3> {
5833 let det = |c: [[f64; 3]; 3]| {
5834 c[0][0] * c[1][1].madd(c[2][2], -c[1][2] * c[2][1])
5835 - c[0][1] * c[1][0].madd(c[2][2], -c[1][2] * c[2][0])
5836 + c[0][2] * c[1][0].madd(c[2][1], -c[1][1] * c[2][0])
5837 };
5838 let d = det(m);
5839 if d.abs() <= 0.0 || !d.is_finite() {
5840 return None;
5841 }
5842 let mut out = [0.0; 3];
5843 for (k, x) in out.iter_mut().enumerate() {
5844 let mut c = m;
5845 for (row, r) in c.iter_mut().zip(rhs) {
5846 row[k] = r;
5847 }
5848 *x = det(c) / d;
5849 }
5850 Some(Vec3::new(out[0], out[1], out[2]))
5851}
5852
5853#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
5871fn march_analytic_intersection(
5872 a: &AnalyticSurface<'_>,
5873 b: &AnalyticSurface<'_>,
5874 surf_a: &dyn Fn(f64, f64) -> Point3,
5875 norm_a: &dyn Fn(f64, f64) -> Vec3,
5876 surf_b: &dyn Fn(f64, f64) -> Point3,
5877 norm_b: &dyn Fn(f64, f64) -> Vec3,
5878 seed: Point3,
5879 u_range_a: (f64, f64),
5880 v_range_a: (f64, f64),
5881 u_range_b: (f64, f64),
5882 v_range_b: (f64, f64),
5883 initial_step: f64,
5884 u_periodic_a: bool,
5885 u_periodic_b: bool,
5886 region: Option<Aabb3>,
5887) -> Option<Vec<Point3>> {
5888 let h_max = initial_step * 4.0;
5889 let h_min = initial_step * 1e-6;
5890
5891 let off_patch = |q: Point3| {
5893 let (ua, va) = project_analytic(a, q, u_range_a, v_range_a);
5894 let (ub, vb) = project_analytic(b, q, u_range_b, v_range_b);
5895 (!u_periodic_a && (ua <= u_range_a.0 || ua >= u_range_a.1))
5896 || va <= v_range_a.0
5897 || va >= v_range_a.1
5898 || (!u_periodic_b && (ub <= u_range_b.0 || ub >= u_range_b.1))
5899 || vb <= v_range_b.0
5900 || vb >= v_range_b.1
5901 };
5902 let on_curve = |from: Point3, step: Vec3| {
5904 correct_to_intersection(
5905 a,
5906 b,
5907 surf_a,
5908 norm_a,
5909 surf_b,
5910 norm_b,
5911 from + step,
5912 u_range_a,
5913 v_range_a,
5914 u_range_b,
5915 v_range_b,
5916 5,
5917 )
5918 };
5919 let last_on_patch = |from: Point3, step: Vec3| {
5923 let (mut lo, mut hi) = (0.0, 1.0);
5924 for _ in 0..48 {
5925 let s = f64::midpoint(lo, hi);
5926 if off_patch(on_curve(from, step * s)) {
5927 hi = s;
5928 } else {
5929 lo = s;
5930 }
5931 }
5932 (lo > 0.0).then(|| on_curve(from, step * lo))
5933 };
5934
5935 let start = station(a, b, seed, Vec3::new(0.0, 0.0, 0.0))?;
5936 let sheets = |q: Point3| {
5938 use section_fit::Carrier;
5939 (a.sheet(q), b.sheet(q))
5940 };
5941 let home_sheets = sheets(seed);
5942
5943 let mut forward = Vec::new();
5945 let mut backward = Vec::new();
5947
5948 let mut looped = false;
5951 for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
5952 if looped {
5953 break;
5954 }
5955 let home = start.t * direction;
5956 let mut here = Station { t: home, ..start };
5957 let mut h = here.reach(h_max.min(initial_step));
5958 let mut ended = false;
5959
5960 for _ in 0..MARCH_STEPS {
5961 h = h.min(here.reach(h_max));
5962 if !points.is_empty() {
5963 let to_seed = seed - here.p;
5964 let ahead = to_seed.dot(here.t);
5965 let aside = (to_seed - here.t * ahead).length();
5966 if ahead > 0.0
5967 && ahead <= h
5968 && aside <= MARCH_TURN * ahead
5969 && aside <= MARCH_BASIN * here.gap.min(start.gap)
5970 && home.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5971 {
5972 points.push(seed);
5973 looped = true;
5974 ended = true;
5975 break;
5976 }
5977 }
5978
5979 let next = loop {
5980 if h < h_min {
5981 break None;
5982 }
5983 let guess = Point3::new(
5984 h.madd(here.t.x(), here.p.x()),
5985 h.madd(here.t.y(), here.p.y()),
5986 h.madd(here.t.z(), here.p.z()),
5987 );
5988 let taken = settle_on_section(a, b, guess)
5989 .and_then(|q| station(a, b, q, here.t))
5990 .filter(|next| {
5991 let missed = (next.p - guess).length();
5992 missed <= MARCH_BASIN * here.gap.min(next.gap)
5993 && missed <= 0.5 * h
5994 && next.t.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5995 && (next.p - here.p).dot(here.t) >= 0.5 * h
5996 && sheets(next.p) == home_sheets
5997 });
5998 match taken {
5999 Some(next) => break Some(next),
6000 None => h *= 0.5,
6001 }
6002 };
6003 let Some(next) = next else {
6009 let end = singular_point(a, b, here.p, initial_step)?;
6010 points.push(end);
6011 ended = true;
6012 break;
6013 };
6014
6015 if off_patch(next.p) {
6016 points.extend(last_on_patch(here.p, next.p - here.p));
6020 ended = true;
6021 break;
6022 }
6023 if region.is_some_and(|r| !r.contains_point(next.p)) {
6024 points.push(next.p);
6025 ended = true;
6026 break;
6027 }
6028 points.push(next.p);
6029 here = next;
6030 h *= 2.0;
6031 }
6032 if !ended {
6033 return None;
6034 }
6035 }
6036
6037 backward.reverse();
6039 let mut result = backward;
6040 result.push(seed);
6041 result.append(&mut forward);
6042
6043 if let [first, second, ..] = result[..]
6047 && off_patch(first)
6048 && !off_patch(second)
6049 && let Some(edge) = last_on_patch(second, first - second)
6050 {
6051 result[0] = edge;
6052 }
6053 if let [.., second, last] = result[..]
6054 && off_patch(last)
6055 && !off_patch(second)
6056 && let Some(edge) = last_on_patch(second, last - second)
6057 && let Some(end) = result.last_mut()
6058 {
6059 *end = edge;
6060 }
6061
6062 for pt in &mut result {
6065 let from = *pt;
6066 *pt = settle_on_section(a, b, from)
6067 .filter(|on| (*on - from).length() <= initial_step)
6068 .unwrap_or_else(|| {
6069 correct_to_intersection(
6070 a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b,
6071 v_range_b, 5,
6072 )
6073 });
6074 }
6075
6076 Some(result)
6077}
6078
6079fn project_analytic(
6083 surface: &AnalyticSurface<'_>,
6084 point: Point3,
6085 u_range: (f64, f64),
6086 v_range: (f64, f64),
6087) -> (f64, f64) {
6088 match surface {
6089 AnalyticSurface::Cylinder(cyl) => {
6090 let (u, v) = cyl.project_point(point);
6091 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6092 }
6093 AnalyticSurface::Sphere(sphere) => {
6094 let (u, v) = sphere.project_point(point);
6095 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6096 }
6097 AnalyticSurface::Cone(cone) => {
6100 let (u, v) = cone.project_point(point);
6101 let v = v.clamp(v_range.0, v_range.1);
6102 let u = if v < 0.0 {
6103 (u + std::f64::consts::PI).rem_euclid(TAU)
6104 } else {
6105 u
6106 };
6107 (u.clamp(u_range.0, u_range.1), v)
6108 }
6109 AnalyticSurface::Torus(torus) => {
6110 let (u, v) = torus.project_point(point);
6111 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6112 }
6113 }
6114}
6115
6116fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
6120 matches!(
6121 surface,
6122 AnalyticSurface::Cylinder(_)
6123 | AnalyticSurface::Cone(_)
6124 | AnalyticSurface::Sphere(_)
6125 | AnalyticSurface::Torus(_)
6126 )
6127}
6128
6129#[allow(clippy::type_complexity)]
6131fn surface_closures<'a>(
6132 surface: &'a AnalyticSurface<'a>,
6133) -> (
6134 Box<dyn Fn(f64, f64) -> Point3 + 'a>,
6135 Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
6136 (f64, f64),
6137 (f64, f64),
6138) {
6139 match surface {
6140 AnalyticSurface::Cylinder(cyl) => (
6141 Box::new(|u, v| cyl.evaluate(u, v)),
6142 Box::new(|u, v| cyl.normal(u, v)),
6143 (0.0, TAU),
6144 (-1.0, 1.0),
6145 ),
6146 AnalyticSurface::Cone(cone) => (
6147 Box::new(|u, v| cone.evaluate(u, v)),
6148 Box::new(|u, v| cone.normal(u, v)),
6149 (0.0, TAU),
6150 (0.01, 2.0),
6151 ),
6152 AnalyticSurface::Sphere(sphere) => (
6153 Box::new(|u, v| sphere.evaluate(u, v)),
6154 Box::new(|u, v| sphere.normal(u, v)),
6155 (0.0, TAU),
6156 (-FRAC_PI_2, FRAC_PI_2),
6157 ),
6158 AnalyticSurface::Torus(torus) => (
6159 Box::new(|u, v| torus.evaluate(u, v)),
6160 Box::new(|u, v| torus.normal(u, v)),
6161 (0.0, TAU),
6162 (0.0, TAU),
6163 ),
6164 }
6165}
6166
6167#[cfg(test)]
6168#[allow(clippy::unwrap_used, clippy::expect_used)]
6169mod tests {
6170 use super::*;
6171 use crate::tolerance::Tolerance;
6172
6173 #[test]
6177 fn plane_cone_conic_arcs_lie_on_both_surfaces() {
6178 let half_angle = 1.1_f64;
6179 let cone = ConicalSurface::new(
6180 Point3::new(0.0, 0.0, 0.0),
6181 Vec3::new(0.0, 0.0, 1.0),
6182 half_angle,
6183 )
6184 .unwrap();
6185 let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
6186 for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
6187 let chains =
6188 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
6189 .unwrap();
6190 let chain = chains
6191 .iter()
6192 .find_map(|c| match c {
6193 ExactIntersectionCurve::Points(chain) => Some(chain),
6194 _ => None,
6195 })
6196 .expect("a parabola or hyperbola section is sampled");
6197 let (from, to) = (chain[2], chain[chain.len() - 3]);
6198 let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
6199 .unwrap()
6200 .expect("an exact arc");
6201 let (t0, t1) = arc.domain();
6202 assert!((arc.evaluate(t0) - from).length() < 1e-12);
6203 assert!((arc.evaluate(t1) - to).length() < 1e-12);
6204 for i in 0..=200 {
6205 let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
6206 let w = q - Point3::new(0.0, 0.0, 0.0);
6207 let off_plane = (normal.dot(w) - d).abs();
6208 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6209 assert!(off_plane < 1e-9, "off the plane by {off_plane}");
6210 assert!(off_cone < 1e-9, "off the cone by {off_cone}");
6211 }
6212 }
6213 }
6214
6215 #[test]
6219 fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
6220 let half_angle = 1.1_f64;
6221 let cone = ConicalSurface::new(
6222 Point3::new(0.0, 0.0, 0.0),
6223 Vec3::new(0.0, 0.0, 1.0),
6224 half_angle,
6225 )
6226 .unwrap();
6227 for shortfall in [1e-10, 3e-10, 8e-10] {
6228 let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
6229 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
6230 let chains =
6231 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
6232 .unwrap();
6233 let Some(chain) = chains.iter().find_map(|c| match c {
6234 ExactIntersectionCurve::Points(chain) => Some(chain),
6235 _ => None,
6236 }) else {
6237 continue;
6238 };
6239 let (from, to) = (chain[2], chain[chain.len() - 3]);
6240 assert!(
6241 plane_cone_conic_arc(&cone, normal, 1.0, from, from)
6242 .unwrap()
6243 .is_none(),
6244 "coincident ends"
6245 );
6246 let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
6247 continue;
6248 };
6249 let (t0, t1) = arc.domain();
6250 for i in 0..=200 {
6251 let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
6252 - Point3::new(0.0, 0.0, 0.0);
6253 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6254 assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
6255 }
6256 }
6257 }
6258
6259 #[test]
6260 fn plane_cylinder_perpendicular() {
6261 let cyl =
6262 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
6263 .unwrap();
6264
6265 let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
6267 assert!(!curves.is_empty(), "should find intersection curve");
6268 assert!(
6269 curves[0].points.len() > 10,
6270 "should have many sample points"
6271 );
6272
6273 let tol = Tolerance::loose();
6274 for pt in &curves[0].points {
6275 assert!(
6276 tol.approx_eq(pt.point.z(), 3.0),
6277 "z should be ~3.0, got {}",
6278 pt.point.z()
6279 );
6280 let r = pt.point.x().hypot(pt.point.y());
6281 assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
6282 }
6283 }
6284
6285 #[test]
6286 fn plane_sphere_equator() {
6287 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6288
6289 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6290 assert!(!curves.is_empty());
6291
6292 let tol = Tolerance::loose();
6293 for pt in &curves[0].points {
6294 assert!(
6295 tol.approx_eq(pt.point.z(), 0.0),
6296 "z should be ~0, got {}",
6297 pt.point.z()
6298 );
6299 let r = pt.point.x().hypot(pt.point.y());
6300 assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
6301 }
6302 }
6303
6304 #[test]
6305 fn plane_sphere_no_intersection() {
6306 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6307
6308 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
6309 assert!(curves.is_empty());
6310 }
6311
6312 #[test]
6313 fn plane_cone_cross_section() {
6314 let cone = ConicalSurface::new(
6315 Point3::new(0.0, 0.0, 0.0),
6316 Vec3::new(0.0, 0.0, 1.0),
6317 std::f64::consts::FRAC_PI_4,
6318 )
6319 .unwrap();
6320
6321 let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6322 assert!(!curves.is_empty(), "should find intersection with cone");
6323 }
6324
6325 #[test]
6332 fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
6333 let c1 = ConicalSurface::new(
6334 Point3::new(
6335 -16.999_999_999_999_975,
6336 -16.999_999_999_999_975,
6337 5.849_999_999_999_951,
6338 ),
6339 Vec3::new(0.0, 0.0, -1.0),
6340 0.785_398_163_397_433_5,
6341 )
6342 .unwrap();
6343 let c2 = ConicalSurface::new(
6344 Point3::new(
6345 -16.750_000_000_000_036,
6346 -16.750_000_000_000_018,
6347 0.749_999_999_999_881,
6348 ),
6349 Vec3::new(0.0, 0.0, 1.0),
6350 0.785_398_163_397_467_6,
6351 )
6352 .unwrap();
6353
6354 let curves = exact_cone_cone(&c1, &c2)
6355 .unwrap()
6356 .expect("offset parallel equal-angle cones must take the radical-plane path");
6357 assert_eq!(curves.len(), 1, "expected exactly one section conic");
6358 assert!(
6359 matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
6360 "expected an ellipse section, got {:?}",
6361 curves[0]
6362 );
6363 let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
6364 return;
6365 };
6366
6367 for i in 0..16 {
6371 let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
6372 for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
6373 let rel = p - cone.apex();
6374 let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
6375 let axial = rel_v.dot(cone.axis());
6376 let radial = (rel_v - cone.axis() * axial).length();
6377 assert!(
6378 axial > 0.0,
6379 "{label}: sample on phantom nappe (axial {axial})"
6380 );
6381 let expect = cone.half_angle().tan() * axial;
6382 assert!(
6383 (radial - expect).abs() < 1e-9,
6384 "{label}: sample off surface by {}",
6385 (radial - expect).abs()
6386 );
6387 }
6388 }
6389 }
6390
6391 #[test]
6395 fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
6396 let c1 = ConicalSurface::new(
6397 Point3::new(0.0, 0.0, 5.0),
6398 Vec3::new(0.0, 0.0, -1.0),
6399 std::f64::consts::FRAC_PI_4,
6400 )
6401 .unwrap();
6402 let c2 = ConicalSurface::new(
6403 Point3::new(0.25, 0.25, 20.0),
6404 Vec3::new(0.0, 0.0, 1.0),
6405 std::f64::consts::FRAC_PI_4,
6406 )
6407 .unwrap();
6408 let curves = exact_cone_cone(&c1, &c2)
6409 .unwrap()
6410 .expect("radical-plane path");
6411 assert!(curves.is_empty(), "disjoint nappes must yield no curves");
6412 }
6413
6414 #[test]
6417 fn offset_parallel_cones_with_unequal_angles_defer() {
6418 let c1 = ConicalSurface::new(
6419 Point3::new(0.0, 0.0, 5.0),
6420 Vec3::new(0.0, 0.0, -1.0),
6421 std::f64::consts::FRAC_PI_4,
6422 )
6423 .unwrap();
6424 let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
6425 .unwrap();
6426 assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
6427 }
6428
6429 fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
6433 let cone = ConicalSurface::new(
6434 Point3::new(0.0, 0.0, 0.0),
6435 Vec3::new(0.0, 0.0, 1.0),
6436 std::f64::consts::FRAC_PI_4,
6437 )
6438 .unwrap();
6439 let (s, c) = 40.0_f64.to_radians().sin_cos();
6440 let tube =
6441 CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
6442 (cone, tube)
6443 }
6444
6445 #[test]
6446 fn marcher_keeps_to_its_region() {
6447 let (cone, tube) = cone_and_tilted_tube();
6448 let run = |region: Option<Aabb3>| {
6449 let (a, b) = (
6450 AnalyticSurface::Cone(&cone),
6451 AnalyticSurface::Cylinder(&tube),
6452 );
6453 let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
6454 match region {
6455 Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
6456 None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
6457 }
6458 .unwrap()
6459 };
6460 assert!(!run(None).is_empty());
6461 let near = Aabb3 {
6462 min: Point3::new(-0.5, -2.0, 0.8),
6463 max: Point3::new(0.7, -0.7, 2.0),
6464 };
6465 let curves = run(Some(near));
6466 assert!(!curves.is_empty(), "the loop through the region is kept");
6467 let reach = near.expanded(0.6);
6469 for curve in &curves {
6470 assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
6471 }
6472 let away = Aabb3 {
6473 min: Point3::new(5.0, 5.0, 5.0),
6474 max: Point3::new(6.0, 6.0, 6.0),
6475 };
6476 assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
6477 }
6478
6479 #[test]
6480 fn coaxial_cones_cross_at_single_circle() {
6481 let outer = ConicalSurface::new(
6486 Point3::new(0.0, 0.0, 50.0),
6487 Vec3::new(0.0, 0.0, -1.0),
6488 5.0_f64.atan(),
6489 )
6490 .unwrap();
6491 let inner = ConicalSurface::new(
6492 Point3::new(0.0, 0.0, 90.0),
6493 Vec3::new(0.0, 0.0, -1.0),
6494 10.0_f64.atan(),
6495 )
6496 .unwrap();
6497
6498 let curves = intersect_analytic_analytic_bounded(
6499 AnalyticSurface::Cone(&outer),
6500 AnalyticSurface::Cone(&inner),
6501 32,
6502 None,
6503 None,
6504 )
6505 .unwrap();
6506
6507 assert_eq!(
6508 curves.len(),
6509 1,
6510 "coaxial cones crossing at one circle must yield exactly one curve, got {}",
6511 curves.len()
6512 );
6513 for p in &curves[0].points {
6514 let r = p.point.x().hypot(p.point.y());
6515 assert!(
6516 (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
6517 "intersection point off the expected z=10,r=8 circle: {:?}",
6518 p.point
6519 );
6520 }
6521 }
6522
6523 #[test]
6524 fn plane_torus_cross_section() {
6525 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
6526
6527 let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6528 assert!(
6529 !curves.is_empty(),
6530 "should find intersection curves with torus"
6531 );
6532 }
6533
6534 #[test]
6537 fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
6538 for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
6539 let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
6540 for z in [3.0 - minor, 3.0 + minor] {
6541 let exact = exact_plane_analytic(
6542 AnalyticSurface::Torus(&torus),
6543 Vec3::new(0.0, 0.0, 1.0),
6544 z,
6545 )
6546 .unwrap();
6547 assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
6548 let circle = match &exact[0] {
6549 ExactIntersectionCurve::Circle(c) => Some(c),
6550 _ => None,
6551 };
6552 let c = circle.expect("a circle");
6553 assert!((c.radius() - major).abs() < 1e-12);
6554 assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
6555
6556 let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
6557 assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
6558 }
6559 let single = |normal: Vec3, d: f64| {
6561 matches!(
6562 exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
6563 .unwrap()
6564 .as_slice(),
6565 [ExactIntersectionCurve::Circle(_)]
6566 )
6567 };
6568 assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
6569 }
6570 }
6571
6572 #[test]
6576 fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
6577 let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
6578 let level = Vec3::new(0.0, 0.0, 1.0);
6579 let curves =
6580 |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
6581 assert!(matches!(
6582 curves(3.0 + 100.1).as_slice(),
6583 [ExactIntersectionCurve::Circle(_)]
6584 ));
6585 let inside = curves(3.0 + 100.1 - 4e-7);
6586 assert!(!matches!(
6587 inside.as_slice(),
6588 [ExactIntersectionCurve::Circle(_)]
6589 ));
6590 }
6591
6592 fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
6595 let rho = p.x().hypot(p.y());
6596 ((rho - major).hypot(p.z())) - minor
6597 }
6598
6599 #[test]
6605 fn oblique_cone_cylinder_traces_curves_on_both() {
6606 use crate::traits::ParametricCurve;
6607 let cone = ConicalSurface::new(
6611 Point3::new(0.0, 0.0, 3.0),
6612 Vec3::new(0.0, 0.0, -1.0),
6613 2.0_f64.atan(),
6614 )
6615 .unwrap();
6616 for (x0, loops) in [(0.5, 1), (0.0, 2)] {
6617 let cyl =
6618 CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6619 .unwrap();
6620 for cone_first in [true, false] {
6621 let (a, b) = if cone_first {
6622 (
6623 AnalyticSurface::Cone(&cone),
6624 AnalyticSurface::Cylinder(&cyl),
6625 )
6626 } else {
6627 (
6628 AnalyticSurface::Cylinder(&cyl),
6629 AnalyticSurface::Cone(&cone),
6630 )
6631 };
6632 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6633 assert_eq!(curves.len(), loops, "x0 {x0}: loops");
6634 for c in &curves {
6635 let (t0, t1) = c.curve.domain();
6636 for k in 0..=64 {
6637 let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
6638 let p = ParametricCurve::evaluate(&c.curve, t);
6639 let rod = (p.x() - x0).hypot(p.z() - 1.0);
6642 assert!(
6643 (rod - 0.6).abs() < 1e-4,
6644 "x0 {x0}: off the rod by {}",
6645 rod - 0.6
6646 );
6647 let cone_r = p.x().hypot(p.y());
6648 assert!(
6649 (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
6650 "x0 {x0}: off the cone at {p:?}"
6651 );
6652 }
6653 }
6654 }
6655 }
6656 }
6657
6658 #[test]
6659 fn a_rod_through_a_rings_tube_traces_four_loops() {
6660 use crate::traits::ParametricCurve;
6661 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6662 let rod =
6665 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
6666 .unwrap();
6667 let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
6668 assert_eq!(curves.len(), 4);
6669 for c in &curves {
6670 let (t0, t1) = c.curve.domain();
6671 for k in 0..=64 {
6672 let p =
6673 ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
6674 let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
6675 let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6676 assert!(
6677 on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
6678 "off by {on_rod}, {on_ring}"
6679 );
6680 }
6681 }
6682 let high =
6684 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6685 .unwrap();
6686 assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
6687 let grazing =
6689 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
6690 .unwrap();
6691 assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
6692 let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
6694 let thin =
6695 CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
6696 .unwrap();
6697 assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
6698 }
6699
6700 #[test]
6701 fn a_pin_through_a_ball_traces_two_loops() {
6702 use crate::traits::ParametricCurve;
6703 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6704 let half = 0.08_f64.atan();
6707 let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
6708 let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
6709 for cone_first in [true, false] {
6710 let (a, b) = if cone_first {
6711 (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
6712 } else {
6713 (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
6714 };
6715 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6716 assert_eq!(curves.len(), 2, "entry and exit loops");
6717 for c in &curves {
6718 let (t0, t1) = c.curve.domain();
6719 for k in 0..=64 {
6720 let p = ParametricCurve::evaluate(
6721 &c.curve,
6722 (t1 - t0).madd(f64::from(k) / 64.0, t0),
6723 );
6724 let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
6725 let axial = apex.z() - p.z();
6726 let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
6727 assert!(
6728 on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
6729 "off by {on_ball}, {on_pin}"
6730 );
6731 }
6732 }
6733 }
6734 let coaxial =
6739 ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
6740 .unwrap();
6741 assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
6742 let aside = ConicalSurface::new(
6743 Point3::new(2.8, 0.0, 10.0),
6744 Vec3::new(0.0, 0.0, -1.0),
6745 FRAC_PI_2 - half,
6746 )
6747 .unwrap();
6748 assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
6749 let holding = ConicalSurface::new(
6750 Point3::new(1.0, 0.5, 1.0),
6751 Vec3::new(0.0, 0.0, -1.0),
6752 FRAC_PI_2 - half,
6753 )
6754 .unwrap();
6755 assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
6756 let away = ConicalSurface::new(
6757 Point3::new(1.0, 0.5, 10.0),
6758 Vec3::new(0.0, 0.0, 1.0),
6759 FRAC_PI_2 - half,
6760 )
6761 .unwrap();
6762 assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
6763 let step = TAU / 2048.0;
6767 let grazed =
6768 SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
6769 .unwrap();
6770 let wide =
6771 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
6772 assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
6773 }
6774
6775 #[test]
6776 fn a_ball_beside_a_cone_meets_it_in_one_loop() {
6777 use crate::traits::ParametricCurve;
6778 let cone = ConicalSurface::new(
6780 Point3::new(0.0, 0.0, 3.0),
6781 Vec3::new(0.0, 0.0, -1.0),
6782 2.0_f64.atan(),
6783 )
6784 .unwrap();
6785 for (centre, radius) in [
6786 (Point3::new(1.0, 0.8, 1.2), 1.1),
6787 (Point3::new(1.5, 0.0, 0.0), 0.8),
6788 ] {
6789 let ball = SphericalSurface::new(centre, radius).unwrap();
6790 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6791 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6792 let (t0, t1) = curves[0].curve.domain();
6793 for k in 0..=64 {
6794 let p = ParametricCurve::evaluate(
6795 &curves[0].curve,
6796 (t1 - t0).madd(f64::from(k) / 64.0, t0),
6797 );
6798 let on_ball = (p - centre).length() - radius;
6799 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6800 assert!(
6801 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
6802 "ball at {centre:?}: off by {on_ball}, {on_cone}"
6803 );
6804 }
6805 }
6806 let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
6808 assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
6809 let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
6810 assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
6811 }
6812
6813 #[test]
6814 fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
6815 use crate::traits::ParametricCurve;
6816 let cone = ConicalSurface::new(
6817 Point3::new(0.0, 0.0, 3.0),
6818 Vec3::new(0.0, 0.0, -1.0),
6819 2.0_f64.atan(),
6820 )
6821 .unwrap();
6822 for (centre, radius) in [
6825 (Point3::new(0.5, 0.0, 2.5), 2.0),
6826 (Point3::new(-0.4, 0.3, 2.0), 1.5),
6827 (Point3::new(0.0, 0.8, 3.0), 0.8001),
6828 (Point3::new(0.0, 0.8, 3.0), 0.800_001),
6829 ] {
6830 let ball = SphericalSurface::new(centre, radius).unwrap();
6831 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6832 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6833 let (t0, t1) = curves[0].curve.domain();
6834 for k in 0..=4096 {
6835 let p = ParametricCurve::evaluate(
6836 &curves[0].curve,
6837 (t1 - t0).madd(f64::from(k) / 4096.0, t0),
6838 );
6839 let on_ball = (p - centre).length() - radius;
6840 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6841 assert!(
6842 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
6843 "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
6844 );
6845 }
6846 }
6847 }
6848
6849 #[test]
6856 fn a_pin_tip_between_two_samples_is_not_traced_from_a_miss() {
6857 use std::f64::consts::{FRAC_PI_2, PI};
6858 let slope = 0.04375_f64;
6859 let pin = ConicalSurface::new(
6860 Point3::new(0.0, 5.005, 10.0),
6861 Vec3::new(0.0, -1.0, 0.0),
6862 (1.0 / slope).atan(),
6863 )
6864 .unwrap();
6865 let turn = FRAC_PI_2 + 5e-5 - PI / 128.0;
6866 let rod = CylindricalSurface::with_ref_dir(
6867 Point3::new(0.0, 0.0, 0.0),
6868 Vec3::new(0.0, 0.0, 1.0),
6869 5.0,
6870 Vec3::new(turn.cos(), turn.sin(), 0.0),
6871 )
6872 .unwrap();
6873 assert!(ruling_cone_cylinder(&pin, &rod, true).is_none());
6874 }
6875
6876 #[test]
6880 fn a_taper_pin_through_a_turned_rod_traces_both_loops() {
6881 use crate::traits::ParametricCurve;
6882 let slope = 0.7_f64 / 16.0;
6883 let half = (1.0 / slope).atan();
6884 for flip in [false, true] {
6885 let (apex_y, axis_y) = if flip {
6886 (-8.0 - 0.8 / slope, 1.0)
6887 } else {
6888 (-8.0 + 1.5 / slope, -1.0)
6889 };
6890 let pin = ConicalSurface::new(
6891 Point3::new(0.0, apex_y, 10.0),
6892 Vec3::new(0.0, axis_y, 0.0),
6893 half,
6894 )
6895 .unwrap();
6896 for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
6897 let rod = CylindricalSurface::with_ref_dir(
6898 Point3::new(0.0, 0.0, 0.0),
6899 Vec3::new(0.0, 0.0, 1.0),
6900 5.0,
6901 Vec3::new(spin.cos(), spin.sin(), 0.0),
6902 )
6903 .unwrap();
6904 let curves = ruling_cone_cylinder(&pin, &rod, true);
6905 assert!(curves.is_some(), "spin {spin} flip {flip}: no trace");
6906 let curves = curves.unwrap();
6907 assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
6908 for c in &curves {
6909 let (t0, t1) = c.curve.domain();
6910 for k in 0..=1000 {
6911 let p = ParametricCurve::evaluate(
6912 &c.curve,
6913 (t1 - t0).madd(f64::from(k) / 1000.0, t0),
6914 );
6915 let on_rod = p.x().hypot(p.y()) - 5.0;
6916 let on_pin = p.x().hypot(p.z() - 10.0) - slope * (p.y() - apex_y).abs();
6917 assert!(
6918 on_rod.abs() < 1e-7 && on_pin.abs() < 1e-7,
6919 "spin {spin} flip {flip}: off by {on_rod:.2e}, {on_pin:.2e}"
6920 );
6921 }
6922 }
6923 }
6924 }
6925 }
6926
6927 #[test]
6928 fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
6929 let t = 2.0_f64.atan();
6930 let cone =
6931 ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
6932 let through_apex =
6934 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6935 .unwrap();
6936 assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
6937 let generator = Vec3::new(t.cos(), 0.0, -t.sin());
6939 let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
6940 assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
6941 let pin =
6944 ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
6945 let tube =
6946 CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
6947 .unwrap();
6948 assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
6949 }
6950
6951 #[test]
6952 fn parallel_cone_cylinder_gives_two_exact_branches() {
6953 use crate::traits::ParametricCurve;
6954 let cone = ConicalSurface::new(
6955 Point3::new(-5.45, -36.55, -4.85),
6956 Vec3::new(0.0, 0.0, 1.0),
6957 std::f64::consts::FRAC_PI_4,
6958 )
6959 .unwrap();
6960 let cyl = CylindricalSurface::new(
6961 Point3::new(-8.0, -34.0, -5.0),
6962 Vec3::new(0.0, 0.0, 1.0),
6963 4.45,
6964 )
6965 .unwrap();
6966 let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
6968 let curves = intersect_analytic_analytic_bounded(
6969 AnalyticSurface::Cone(&cone),
6970 AnalyticSurface::Cylinder(&cyl),
6971 32,
6972 Some(v_hint),
6973 Some((0.0, 2.5)),
6974 )
6975 .unwrap();
6976
6977 assert_eq!(curves.len(), 2, "expected exactly the two branches");
6978 for c in &curves {
6979 let (t0, t1) = c.curve.domain();
6980 for k in 0..=32 {
6981 let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
6982 let p = ParametricCurve::evaluate(&c.curve, t);
6983 let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
6985 assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
6986 let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
6988 assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
6989 assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
6991 }
6992 }
6993 }
6994
6995 #[test]
6996 fn parallel_rod_through_a_cones_wall_closes_one_loop() {
6997 use crate::traits::ParametricCurve;
6998 let cone = ConicalSurface::new(
7000 Point3::new(0.0, 0.0, 3.0),
7001 Vec3::new(0.0, 0.0, -1.0),
7002 2.0_f64.atan(),
7003 )
7004 .unwrap();
7005 for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
7007 let rod =
7008 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7009 .unwrap();
7010 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7011 .unwrap()
7012 .unwrap();
7013 assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
7014 let (t0, t1) = curves[0].curve.domain();
7015 let (first, last) = (
7016 ParametricCurve::evaluate(&curves[0].curve, t0),
7017 ParametricCurve::evaluate(&curves[0].curve, t1),
7018 );
7019 assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
7020 for k in 0..=64 {
7021 let p = ParametricCurve::evaluate(
7022 &curves[0].curve,
7023 (t1 - t0).madd(f64::from(k) / 64.0, t0),
7024 );
7025 let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
7026 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7027 assert!(
7028 on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
7029 "({x}, {y}): off by {on_rod}, {on_cone}"
7030 );
7031 }
7032 }
7033 for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
7036 let rod =
7037 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7038 .unwrap();
7039 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7040 .unwrap()
7041 .unwrap();
7042 assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
7043 }
7044 }
7045
7046 #[test]
7052 fn parallel_cones_give_two_exact_branches() {
7053 use crate::traits::ParametricCurve;
7054 let frustum = |x: f64, r_big: f64, r_small: f64, h: f64| {
7055 let apex = h + r_small * h / (r_big - r_small);
7056 let cone = ConicalSurface::new(
7057 Point3::new(x, 0.0, apex),
7058 Vec3::new(0.0, 0.0, -1.0),
7059 apex.atan2(r_big),
7060 )
7061 .unwrap();
7062 let v = move |z: f64| (apex - z) / apex.atan2(r_big).sin();
7064 (cone, v(h), v(0.0))
7065 };
7066 let (big, big_top, big_base) = frustum(0.0, 72.0, 50.0, 84.0);
7067 for (x, flip) in [(-70.0_f64, false), (70.0, true)] {
7068 let (small, small_top, small_base) = frustum(x, 10.0, 5.0, 44.0);
7069 let (first, second) = if flip {
7070 (AnalyticSurface::Cone(&small), AnalyticSurface::Cone(&big))
7071 } else {
7072 (AnalyticSurface::Cone(&big), AnalyticSurface::Cone(&small))
7073 };
7074 let (hint_first, hint_second) = if flip {
7075 ((small_top, small_base), (big_top, big_base))
7076 } else {
7077 ((big_top, big_base), (small_top, small_base))
7078 };
7079 let curves = intersect_analytic_analytic_bounded(
7080 first,
7081 second,
7082 32,
7083 Some(hint_first),
7084 Some(hint_second),
7085 )
7086 .unwrap();
7087 assert_eq!(curves.len(), 2, "x = {x}: the two branches");
7088 let touch = 12.0 / (22.0 / 84.0 + 5.0 / 44.0);
7090 let mut tops = Vec::new();
7091 for c in &curves {
7092 let (t0, t1) = c.curve.domain();
7093 let ends = [
7094 ParametricCurve::evaluate(&c.curve, t0),
7095 ParametricCurve::evaluate(&c.curve, t1),
7096 ];
7097 let (low, high) = if ends[0].z() < ends[1].z() {
7098 (ends[0], ends[1])
7099 } else {
7100 (ends[1], ends[0])
7101 };
7102 assert!(low.z().abs() < 1e-9, "x = {x}: starts at z = {}", low.z());
7103 assert!((high.z() - touch).abs() < 1e-9, "x = {x}: tops at {high:?}");
7104 tops.push(high);
7105 for k in 0..=256 {
7106 let p = ParametricCurve::evaluate(
7107 &c.curve,
7108 (t1 - t0).madd(f64::from(k) / 256.0, t0),
7109 );
7110 let on_big = p.x().hypot(p.y()) - (72.0 - 22.0 * p.z() / 84.0);
7111 let on_small = (p.x() - x).hypot(p.y()) - (10.0 - 5.0 * p.z() / 44.0);
7112 assert!(
7113 on_big.abs() < 1e-6 && on_small.abs() < 1e-6,
7114 "x = {x}: {p:?} off by {on_big}, {on_small}"
7115 );
7116 }
7117 }
7118 assert!((tops[0] - tops[1]).length() < 1e-9, "x = {x}: {tops:?}");
7119 }
7120 }
7121
7122 #[test]
7127 fn parallel_cones_of_nearly_equal_slope_trace_on_both() {
7128 use crate::traits::ParametricCurve;
7129 let up = Vec3::new(0.0, 0.0, 1.0);
7130 let first =
7131 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7132 .unwrap();
7133 let second =
7134 ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, (1.0 / 1.001_f64).atan()).unwrap();
7135 let curves = algebraic_parallel_cone_cone(&first, &second, None, None).unwrap();
7136 assert_eq!(curves.len(), 2, "the two branches");
7137 let mut ends = Vec::new();
7138 for c in &curves {
7139 let (t0, t1) = c.curve.domain();
7140 ends.push(ParametricCurve::evaluate(&c.curve, t0));
7141 ends.push(ParametricCurve::evaluate(&c.curve, t1));
7142 for k in 0..=4096 {
7143 let p =
7144 ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 4096.0, t0));
7145 let on_first = p.x().hypot(p.y()) - p.z();
7146 let on_second = (p.x() - 1.0).hypot(p.y()) - 1.001 * p.z();
7147 assert!(
7148 on_first.abs() < 1e-7 && on_second.abs() < 1e-7,
7149 "{p:?} off by {on_first}, {on_second}"
7150 );
7151 }
7152 }
7153 let (low, high) = (1.0 / 2.001, 1000.0);
7154 for (k, z) in [(0, low), (1, high)] {
7155 let (a, b) = (ends[k], ends[2 + k]);
7156 assert!(
7157 (a.z() - z).abs() < 1e-6 * z,
7158 "branch end at {a:?}, not z = {z}"
7159 );
7160 assert!((a - b).length() < 1e-9, "branches part at {a:?} and {b:?}");
7161 }
7162 }
7163
7164 #[test]
7169 fn nearly_equal_slopes_meet_far_out() {
7170 let up = Vec3::new(0.0, 0.0, 1.0);
7171 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7172 .unwrap();
7173 let (sin1, cos1) = std::f64::consts::FRAC_PI_4.sin_cos();
7174 let slope = (cos1 + 5e-13) / sin1;
7177 let along = 2.0 / slope;
7178 let narrow =
7179 ConicalSurface::new(Point3::new(1.0, 0.0, along), up, (1.0 / slope).atan()).unwrap();
7180 let curves = algebraic_parallel_cone_cone(&wide, &narrow, Some((0.0, 4e12)), None);
7181 assert!(
7182 !curves.as_ref().is_some_and(Vec::is_empty),
7183 "called apart: {:?}",
7184 curves.map(|c| c.len())
7185 );
7186 }
7187
7188 #[test]
7194 fn parallel_cones_bounded_on_their_negative_nappes_go_to_the_marcher() {
7195 let up = Vec3::new(0.0, 0.0, 1.0);
7196 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7197 .unwrap();
7198 let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
7199 let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
7200 for cone in [&wide, &narrow] {
7201 assert!(off_cone(cone, shared).0 < 1e-12);
7202 }
7203 let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
7204 let curves = algebraic_parallel_cone_cone(
7205 &wide,
7206 &narrow,
7207 Some((-r1, -r1 / 3.0)),
7208 Some((-r2, -r2 / 3.0)),
7209 );
7210 assert!(curves.is_none(), "{:?} curves", curves.map(|c| c.len()));
7211 }
7212
7213 #[test]
7217 fn nearly_parallel_axes_take_neither_parallel_path() {
7218 let tilt = 1e-5_f64;
7219 let down = Vec3::new(0.0, 0.0, -1.0);
7220 let tilted = Vec3::new(tilt.sin(), 0.0, -tilt.cos());
7221 let big = ConicalSurface::new(
7222 Point3::new(0.0, 0.0, 274.909_090_909),
7223 down,
7224 274.909_090_909_f64.atan2(72.0),
7225 )
7226 .unwrap();
7227 let small =
7228 ConicalSurface::new(Point3::new(-70.0, 0.0, 88.0), tilted, 88.0_f64.atan2(10.0))
7229 .unwrap();
7230 assert!(algebraic_parallel_cone_cone(&big, &small, None, None).is_none());
7231 let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), down, 2.0_f64.atan()).unwrap();
7232 let rod = CylindricalSurface::new(Point3::new(1.2, 0.5, -10.0), tilted, 0.6).unwrap();
7233 assert!(
7234 algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7235 .unwrap()
7236 .is_none()
7237 );
7238 }
7239
7240 #[test]
7243 fn coaxial_cone_cylinder_defers_to_other_paths() {
7244 let cone = ConicalSurface::new(
7245 Point3::new(0.0, 0.0, 0.0),
7246 Vec3::new(0.0, 0.0, 1.0),
7247 std::f64::consts::FRAC_PI_4,
7248 )
7249 .unwrap();
7250 let cyl =
7251 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
7252 .unwrap();
7253 assert!(
7254 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7255 .unwrap()
7256 .is_none()
7257 );
7258 }
7259
7260 #[test]
7261 fn oblique_cone_cylinder_defers_to_other_paths() {
7262 let cone = ConicalSurface::new(
7263 Point3::new(0.0, 0.0, 0.0),
7264 Vec3::new(0.0, 0.0, 1.0),
7265 std::f64::consts::FRAC_PI_4,
7266 )
7267 .unwrap();
7268 let cyl =
7269 CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7270 .unwrap();
7271 assert!(
7272 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7273 .unwrap()
7274 .is_none()
7275 );
7276 }
7277
7278 #[test]
7279 fn plane_torus_lobe_closes_and_stays_on_surface() {
7280 use crate::traits::ParametricCurve;
7281 let (major, minor) = (10.0, 3.0);
7282 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7283
7284 for (n, d) in [
7288 (Vec3::new(0.0, -1.0, 0.0), 4.0), (Vec3::new(-1.0, 0.0, 0.0), -6.0), (Vec3::new(0.0, 0.0, 1.0), 0.0), ] {
7292 let curves = intersect_plane_torus(&torus, n, d).unwrap();
7293 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7294 for c in &curves {
7295 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
7296 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
7297 assert!(
7298 (p0 - p1).length() < 1e-7,
7299 "lobe not closed: gap={} (n={n:?} d={d})",
7300 (p0 - p1).length()
7301 );
7302 for k in 0..=64 {
7304 let t = f64::from(k) / 64.0;
7305 let p = ParametricCurve::evaluate(&c.curve, t);
7306 assert!(
7307 torus_implicit(p, major, minor).abs() < 1e-2,
7308 "off-surface point {p:?} implicit={}",
7309 torus_implicit(p, major, minor)
7310 );
7311 }
7312 }
7313 }
7314 }
7315
7316 #[test]
7320 fn plane_torus_fits_stay_on_the_section_where_it_turns_tightly() {
7321 use crate::traits::ParametricCurve;
7322 let (major, minor) = (4.0, 1.5);
7323 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7324 for (n, d) in [
7325 (Vec3::new(0.0, 1.0, 0.0), 2.1),
7326 (Vec3::new(1.0, 0.0, 0.0), -1.9),
7327 (Vec3::new(0.0, 0.6, 0.8), 3.5),
7328 ] {
7329 let curves = intersect_plane_torus(&torus, n, d).unwrap();
7330 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7331 for c in &curves {
7332 for k in 0..=4000 {
7333 let p = ParametricCurve::evaluate(&c.curve, f64::from(k) / 4000.0);
7334 let off = ((p.x().hypot(p.y()) - major).hypot(p.z()) - minor).abs();
7335 assert!(off <= 1e-8, "{off} off the torus at {p:?} (n={n:?} d={d})");
7336 let off_plane = (n.dot(Vec3::new(p.x(), p.y(), p.z())) - d).abs();
7337 assert!(off_plane <= 1e-12, "{off_plane} off the plane at {p:?}");
7338 }
7339 }
7340 }
7341 }
7342
7343 #[test]
7348 fn a_plane_torus_fit_it_cannot_check_is_refused() {
7349 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7350 let across = [Point3::new(5.5, 0.0, 0.0), Point3::new(-5.5, 0.0, 0.0)];
7351 assert!(fit_plane_torus_section(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0, &across).is_err());
7352 }
7353
7354 #[test]
7359 fn a_short_newton_check_reads_each_middle_as_the_full_one_does() {
7360 let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7361 let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7362 let tol = PLANE_TORUS_FIT * 5.5;
7363 for ipts in plane_torus_loops(&torus, n, d, 128) {
7364 for (ip, power) in ipts.iter().zip((0..10).cycle()) {
7365 let off = Vec3::new(0.3, -0.7, 0.2) * (1e-13 * 10f64.powi(power));
7366 let p = ip.point + off;
7367 let full = plane_torus_section_point(&torus, n, d, p).unwrap();
7368 let short = plane_torus_newton(&torus, n, d, p, 0.25 * tol).unwrap();
7369 if (short - p).length() < 0.25 * tol {
7370 assert!((full - p).length() <= tol, "{:.2e}", (full - p).length());
7371 assert!((full - short).length() < 1e-15);
7372 } else {
7373 assert_eq!(full, short);
7374 }
7375 }
7376 }
7377 }
7378
7379 #[test]
7382 fn plane_torus_section_points_lie_on_both_surfaces() {
7383 let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7384 let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7385 for ipts in plane_torus_loops(&torus, n, d, 128) {
7386 for ip in ipts.iter().step_by(5) {
7387 let near = ip.point + Vec3::new(1e-4, -2e-4, 3e-4);
7388 let on = plane_torus_section_point(&torus, n, d, near).unwrap();
7389 let w = on - torus.center();
7390 let off = ((w.x().hypot(w.y()) - 4.0).hypot(w.z()) - 1.5).abs();
7391 assert!(off <= 1e-14, "{off} off the torus");
7392 assert!(
7393 (on.y() - 0.1).abs() <= 1e-14,
7394 "{} off the plane",
7395 on.y() - 0.1
7396 );
7397 assert!((on - near).length() < 1e-3);
7398 }
7399 }
7400 }
7401
7402 #[test]
7407 fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
7408 let (major, minor) = (10.0, 3.0);
7409 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7410 let curves =
7411 intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
7412 assert_eq!(curves.len(), 2, "one loop per lobe");
7413 let node = Point3::new(major - minor, 0.0, 0.0);
7414 let mut sides = Vec::new();
7415 for c in &curves {
7416 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7417 assert!((first - node).length() < 1e-6, "starts at {first:?}");
7418 assert_eq!(first, last, "closes on the node");
7419 for p in c.points.iter().map(|p| p.point) {
7420 assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
7421 assert!(
7422 torus_implicit(p, major, minor).abs() < 1e-6,
7423 "off the torus at {p:?}"
7424 );
7425 }
7426 let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
7427 sides.push(y > 0.0);
7428 assert!(
7429 c.points.iter().all(|p| p.point.y() * y >= -1e-9),
7430 "a lobe crosses y = 0"
7431 );
7432 }
7433 assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
7434 }
7435
7436 #[test]
7442 fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
7443 let (major, minor) = (3.0, 1.0);
7444 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7445 for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
7446 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
7447 assert_eq!(curves.len(), loops, "x = {x}");
7448 for c in &curves {
7449 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7450 assert_eq!(first, last, "x = {x}: the loop closes");
7451 for p in c.points.iter().map(|p| p.point) {
7452 assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
7453 assert!(
7454 torus_implicit(p, major, minor).abs() < 1e-6,
7455 "x = {x}: off the torus at {p:?}"
7456 );
7457 }
7458 }
7459 }
7460 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
7462 let low = curves[0]
7463 .points
7464 .iter()
7465 .map(|p| p.point)
7466 .filter(|p| p.y().abs() < 1e-6)
7467 .map(Point3::z)
7468 .collect::<Vec<_>>();
7469 let gap = (2.0001_f64 - 2.0)
7470 .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
7471 .sqrt();
7472 assert!(
7473 low.iter().any(|z| (z - gap).abs() < 1e-6)
7474 && low.iter().any(|z| (z + gap).abs() < 1e-6),
7475 "turns at {low:?}, not at z = ±{gap}"
7476 );
7477 }
7478
7479 #[test]
7483 fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
7484 let (major, minor) = (3.0, 1.0);
7485 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7486 for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
7487 let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
7488 let node = torus.evaluate(0.0, v0);
7489 let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
7490 let curves = intersect_plane_torus(&torus, normal, d).unwrap();
7491 assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
7492 for c in &curves {
7493 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7494 assert!(
7495 (first - node).length() < 1e-6,
7496 "v0 {v0}: starts at {first:?}, not {node:?}"
7497 );
7498 assert_eq!(first, last, "v0 {v0}: closes on the node");
7499 for p in c.points.iter().map(|p| p.point) {
7500 let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
7501 assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
7502 assert!(
7503 torus_implicit(p, major, minor).abs() < 1e-6,
7504 "v0 {v0}: off the torus at {p:?}"
7505 );
7506 }
7507 }
7508 }
7509 }
7510
7511 #[test]
7516 fn plane_torus_wall_sections_close_into_their_loops() {
7517 for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
7518 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7519 for k in 1..200 {
7520 let (d, want) = match k.cmp(&100) {
7521 std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
7523 std::cmp::Ordering::Greater => (
7525 2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
7526 1,
7527 ),
7528 std::cmp::Ordering::Equal => continue,
7529 };
7530 let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
7531 let closed = loops
7532 .iter()
7533 .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
7534 .count();
7535 assert_eq!(
7536 (loops.len(), closed),
7537 (want, want),
7538 "R {major} r {minor}, wall at {d}"
7539 );
7540 }
7541 }
7542 }
7543
7544 #[test]
7548 fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
7549 let (major, minor) = (4.0, 1.5);
7550 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7551 for tilt in [0.03_f64, 0.08, 0.2] {
7552 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
7553 let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
7554 assert_eq!(curves.len(), 2, "tilt {tilt}");
7555 for c in &curves {
7556 let (t0, t1) = c.curve.domain();
7557 let off = (0..=400)
7558 .map(|k| {
7559 let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
7560 (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
7561 })
7562 .fold(0.0_f64, |m, e| m.max(e.abs()));
7563 assert!(
7564 off < 1e-6,
7565 "tilt {tilt}: fitted section {off} off the torus"
7566 );
7567 }
7568 }
7569 }
7570
7571 #[test]
7572 fn line_torus_box_edge_crossing_is_exact() {
7573 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7576 let ts = intersect_line_torus(
7577 &torus,
7578 Point3::new(6.0, -4.0, -5.0),
7579 Vec3::new(0.0, 0.0, 1.0),
7580 );
7581 assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
7583 let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
7584 let rho = 6.0_f64.hypot(4.0);
7585 let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
7586 assert!(
7587 (zs[0] - (-z_exp)).abs() < 1e-9,
7588 "z0={} exp={}",
7589 zs[0],
7590 -z_exp
7591 );
7592 assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
7593 for &t in &ts {
7595 let p = Point3::new(6.0, -4.0, -5.0 + t);
7596 let rho = p.x().hypot(p.y());
7597 let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
7598 assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
7599 }
7600 }
7601
7602 #[test]
7607 fn line_spindle_torus_roots_lie_on_their_tubes() {
7608 let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
7609 let origin = Point3::new(42.36, 18.31, 3.4);
7610 let dir = Vec3::new(
7611 0.573_576_436_351_046,
7612 0.740_535_693_464_567_5,
7613 0.350_889_803_483_932_2,
7614 );
7615 let ts = intersect_line_torus(&torus, origin, dir);
7616 let tube = |t: f64, across: f64| {
7617 let q = origin + dir * t;
7618 ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
7619 };
7620 for &t in &ts {
7621 assert!(
7622 tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
7623 "root {t} off both tubes in {ts:?}"
7624 );
7625 }
7626 for want in [0.124, 0.398] {
7627 assert!(
7628 ts.iter().any(|&t| (t - want).abs() < 1e-3),
7629 "no root near {want} in {ts:?}"
7630 );
7631 }
7632 }
7633
7634 #[test]
7635 fn line_torus_miss_and_tangent() {
7636 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7637 let miss = intersect_line_torus(
7639 &torus,
7640 Point3::new(20.0, 0.0, 0.0),
7641 Vec3::new(0.0, 0.0, 1.0),
7642 );
7643 assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
7644 let axis =
7646 intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
7647 assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
7648 }
7649
7650 #[test]
7651 fn dispatch_via_analytic_surface() {
7652 let cyl =
7653 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7654 .unwrap();
7655 let curves = intersect_plane_analytic(
7656 AnalyticSurface::Cylinder(&cyl),
7657 Vec3::new(0.0, 0.0, 1.0),
7658 0.0,
7659 )
7660 .unwrap();
7661 assert!(!curves.is_empty());
7662 }
7663
7664 #[test]
7665 fn perpendicular_cylinders_intersect() {
7666 let cyl_z =
7667 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7668 .unwrap();
7669 let cyl_x =
7670 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7671 .unwrap();
7672
7673 let curves = intersect_analytic_analytic(
7674 AnalyticSurface::Cylinder(&cyl_z),
7675 AnalyticSurface::Cylinder(&cyl_x),
7676 16,
7677 )
7678 .unwrap();
7679
7680 assert!(
7681 !curves.is_empty(),
7682 "perpendicular cylinders should intersect"
7683 );
7684
7685 for c in &curves {
7686 assert!(
7687 c.points.len() >= 2,
7688 "intersection curve should have >= 2 points, got {}",
7689 c.points.len()
7690 );
7691 }
7692 }
7693
7694 #[test]
7697 fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
7698 let cyl_z =
7699 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7700 .unwrap();
7701 let cyl_x =
7702 CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7703 .unwrap();
7704 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7705 .unwrap()
7706 .unwrap();
7707 assert_eq!(curves.len(), 1);
7708 let curve = &curves[0].curve;
7709 let (t0, t1) = curve.domain();
7710 assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
7711 let off = |p: Point3| {
7712 let on_z = (p.x().hypot(p.y()) - 1.0).abs();
7713 let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
7714 on_z.max(on_x)
7715 };
7716 let worst = (0..=400)
7717 .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
7718 .fold(0.0, f64::max);
7719 assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
7720 }
7721
7722 #[test]
7726 fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
7727 let cyl_z =
7728 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7729 .unwrap();
7730 let cyl_x =
7731 CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
7732 .unwrap();
7733 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7734 .unwrap()
7735 .expect("the thin cylinder's sweep finds the loop");
7736 assert_eq!(curves.len(), 1);
7737 }
7738
7739 #[test]
7744 fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
7745 let crossing = Point3::new(1.0, 2.0, 3.0);
7746 let (s, c) = 60.0_f64.to_radians().sin_cos();
7747 let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
7748 let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
7749 let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
7750 let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
7751 assert_eq!(curves.len(), 2);
7752 let off = |p: Point3, cyl: &CylindricalSurface| {
7753 let q = p - cyl.origin();
7754 ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
7755 };
7756 let ends = [
7757 crossing + Vec3::new(0.0, 1.5, 0.0),
7758 crossing - Vec3::new(0.0, 1.5, 0.0),
7759 ];
7760 let mut vertices: Vec<Point3> = Vec::new();
7761 for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
7762 let (t0, t1) = ic.curve.domain();
7763 for k in 0..=400 {
7764 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
7765 assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
7766 assert!(side * (p - crossing).dot(d1) > -1e-13);
7767 }
7768 assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
7769 assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
7770 let other = ends[usize::from(side > 0.0)];
7771 assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
7772 for t in [0.25, 0.75] {
7773 let vertex = ic.curve.evaluate(t);
7774 assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
7775 vertices.push(vertex);
7776 }
7777 }
7778 }
7779
7780 #[test]
7785 fn nearly_crossing_equal_cylinders_are_not_ellipses() {
7786 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7787 .unwrap();
7788 let x = |(x0, y): (f64, f64), r: f64| {
7789 CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
7790 };
7791 let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
7792 assert!(taken(&x((-2.0, 0.0), 1.0)));
7793 assert!(!taken(&x((-2.0, 1e-9), 1.0)));
7794 assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
7795 assert!(!taken(&x((-1e8, 1e-6), 1.0)));
7796 }
7797
7798 #[test]
7802 fn nearly_parallel_equal_cylinders_are_not_ellipses() {
7803 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
7804 .unwrap();
7805 for slope in [1e-8, 1.5e-5] {
7806 let tilted = CylindricalSurface::new(
7807 Point3::new(0.0, 0.0, 0.0),
7808 Vec3::new(slope, 0.0, 1.0),
7809 10.0,
7810 )
7811 .unwrap();
7812 assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
7813 }
7814 }
7815
7816 #[test]
7817 fn sphere_cylinder_intersect() {
7818 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7819 let cyl =
7820 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7821 .unwrap();
7822
7823 let curves = intersect_analytic_analytic(
7824 AnalyticSurface::Sphere(&sphere),
7825 AnalyticSurface::Cylinder(&cyl),
7826 16,
7827 )
7828 .unwrap();
7829
7830 assert!(!curves.is_empty(), "sphere and cylinder should intersect");
7834 }
7835
7836 #[test]
7837 fn exact_sphere_cylinder_coaxial_two_circles() {
7838 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7841 let cyl =
7842 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7843 .unwrap();
7844 let circles = exact_sphere_cylinder(&sphere, &cyl)
7845 .unwrap()
7846 .expect("coaxial case returns Some");
7847 assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
7848 let mut zs: Vec<f64> = circles
7849 .iter()
7850 .filter_map(|c| match c {
7851 ExactIntersectionCurve::Circle(circle) => {
7852 assert!(
7853 (circle.radius() - 3.0).abs() < 1e-9,
7854 "rim radius == cyl radius"
7855 );
7856 Some(circle.center().z())
7857 }
7858 _ => None,
7859 })
7860 .collect();
7861 assert_eq!(zs.len(), 2, "both sections must be exact circles");
7862 zs.sort_by(f64::total_cmp);
7863 let z = 27.0_f64.sqrt();
7864 assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
7865 }
7866
7867 #[test]
7868 fn exact_sphere_cylinder_non_coaxial_defers() {
7869 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7871 let cyl =
7872 CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7873 .unwrap();
7874 assert!(
7875 exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
7876 "non-coaxial sphere/cylinder defers to the marcher"
7877 );
7878 }
7879
7880 #[test]
7881 fn a_ball_on_a_cones_axis_meets_it_in_circles() {
7882 let cone = ConicalSurface::new(
7884 Point3::new(0.0, 0.0, 3.0),
7885 Vec3::new(0.0, 0.0, -1.0),
7886 2.0_f64.atan(),
7887 )
7888 .unwrap();
7889 for (height, radius, count) in [
7890 (0.0, 2.0, 2), (2.5, 1.3, 1), (2.5, 0.5, 1), (0.0, 1.0, 0), (5.0, 1.0, 0), ] {
7896 let centre = Point3::new(0.0, 0.0, height);
7897 let ball = SphericalSurface::new(centre, radius).unwrap();
7898 let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
7899 let circles = circles_of(&curves);
7900 assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
7901 for circle in circles {
7902 for k in 0..16 {
7903 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7904 let on_ball = (p - centre).length() - radius;
7905 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7906 assert!(
7907 on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
7908 "ball at {height}: off by {on_ball}, {on_cone}"
7909 );
7910 }
7911 }
7912 }
7913 let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
7914 assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
7915 let wide =
7918 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
7919 let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
7920 let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
7921 let circles = circles_of(&curves);
7922 assert_eq!(circles.len(), 1, "the touch");
7923 let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
7924 assert!(
7925 (circles[0].radius() - touch).abs() < 1e-3,
7926 "{}",
7927 circles[0].radius()
7928 );
7929 }
7930
7931 fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
7933 curves
7934 .iter()
7935 .filter_map(|c| match c {
7936 ExactIntersectionCurve::Circle(circle) => Some(circle),
7937 _ => None,
7938 })
7939 .collect()
7940 }
7941
7942 fn worst_off(
7945 circles: &[&Circle3D],
7946 torus: &ToroidalSurface,
7947 other: impl Fn(Point3) -> f64,
7948 ) -> f64 {
7949 let mut worst = 0.0_f64;
7950 for circle in circles {
7951 for k in 0..16 {
7952 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7953 let q = p - torus.center();
7954 let along = q.dot(torus.z_axis());
7955 let rho = (q - torus.z_axis() * along).length();
7956 let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
7957 worst = worst.max(off).max(other(p).abs());
7958 }
7959 }
7960 worst
7961 }
7962
7963 #[test]
7964 fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
7965 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7966 for height in [0.0, 1.0] {
7967 let centre = Point3::new(0.0, 0.0, height);
7968 let sphere = SphericalSurface::new(centre, 3.0).unwrap();
7969 let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
7970 let circles = circles_of(&curves);
7971 assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
7972 let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
7973 assert!(worst < 1e-9, "height {height}: {worst}");
7974 }
7975 }
7976
7977 #[test]
7983 fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
7984 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7985 let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
7986 for (centre, radius, loops) in [
7987 (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
7988 (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
7989 (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
7990 (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
7991 ] {
7992 let ball = SphericalSurface::new(centre, radius).unwrap();
7993 let on_ball = |p: Point3| (p - centre).length() - radius;
7994 for ball_first in [true, false] {
7995 let (a, b) = if ball_first {
7996 (
7997 AnalyticSurface::Sphere(&ball),
7998 AnalyticSurface::Torus(&torus),
7999 )
8000 } else {
8001 (
8002 AnalyticSurface::Torus(&torus),
8003 AnalyticSurface::Sphere(&ball),
8004 )
8005 };
8006 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8007 let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
8008 assert_eq!(curves.len(), loops, "{case}");
8009 for ic in &curves {
8010 for q in &ic.points {
8011 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8012 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8013 let (on_ball_at, on_torus_at) = if ball_first {
8014 (q.param1, q.param2)
8015 } else {
8016 (q.param2, q.param1)
8017 };
8018 let (pb, pt) = (
8019 ball.evaluate(on_ball_at.0, on_ball_at.1),
8020 torus.evaluate(on_torus_at.0, on_torus_at.1),
8021 );
8022 assert!(
8023 (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
8024 "{case}: a point's parameters miss it"
8025 );
8026 }
8027 let (t0, t1) = ic.curve.domain();
8028 for k in 0..=400 {
8029 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8030 let off = on_ball(p).abs().max(on_torus(p).abs());
8031 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8032 }
8033 }
8034 }
8035 }
8036 }
8037
8038 #[test]
8045 fn balls_meet_tori_in_loops_a_scan_would_miss() {
8046 for (big, small, centre, radius, loops) in [
8047 (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
8048 (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
8049 (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
8050 (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
8051 ] {
8052 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
8053 let ball = SphericalSurface::new(centre, radius).unwrap();
8054 let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
8055 let on_ball = |p: Point3| (p - centre).length() - radius;
8056 for ball_first in [true, false] {
8057 let (a, b) = if ball_first {
8058 (
8059 AnalyticSurface::Sphere(&ball),
8060 AnalyticSurface::Torus(&torus),
8061 )
8062 } else {
8063 (
8064 AnalyticSurface::Torus(&torus),
8065 AnalyticSurface::Sphere(&ball),
8066 )
8067 };
8068 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8069 let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
8070 assert_eq!(curves.len(), loops, "{case}");
8071 for ic in &curves {
8072 for q in &ic.points {
8073 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8074 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8075 }
8076 let (t0, t1) = ic.curve.domain();
8077 for k in 0..=2000 {
8078 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8079 let off = on_ball(p).abs().max(on_torus(p).abs());
8080 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8081 }
8082 }
8083 }
8084 }
8085 }
8086
8087 #[test]
8093 fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
8094 let origin = Point3::new(0.0, 0.0, 0.0);
8095 let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
8096 let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
8097 let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
8098 assert_eq!((unit, scaled), (1, 1));
8099
8100 let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
8101 let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
8102 assert!(sphere_torus_curves(&speck, &large, true).is_none());
8103
8104 let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
8105 let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
8106 assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
8107 assert!(sphere_torus_curves(&ball, &ring, true).is_none());
8108 }
8109
8110 #[test]
8114 fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
8115 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8116 let centre = Point3::new(4.0, 0.0, 0.0);
8117 let ball = SphericalSurface::new(centre, 1.5).unwrap();
8118 for (a, b) in [
8119 (
8120 AnalyticSurface::Sphere(&ball),
8121 AnalyticSurface::Torus(&torus),
8122 ),
8123 (
8124 AnalyticSurface::Torus(&torus),
8125 AnalyticSurface::Sphere(&ball),
8126 ),
8127 ] {
8128 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8129 assert_eq!(curves.len(), 1);
8130 let (t0, t1) = curves[0].curve.domain();
8131 for k in 0..=100 {
8132 let p = curves[0]
8133 .curve
8134 .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
8135 let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
8136 assert!(off < 1e-9, "the circle strays {off:.2e}");
8137 }
8138 }
8139 }
8140
8141 #[test]
8142 fn exact_sphere_torus_misses_touches_and_defers() {
8143 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8144 let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
8145 assert!(
8146 exact_sphere_torus(&ball(0.0, 1.0), &torus)
8147 .unwrap()
8148 .unwrap()
8149 .is_empty(),
8150 "a small ball in the hole misses"
8151 );
8152 let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
8153 .unwrap()
8154 .unwrap();
8155 let circles = circles_of(&touching);
8156 assert_eq!(
8157 circles.len(),
8158 1,
8159 "a ball in the hole touches the inner equator"
8160 );
8161 assert!((circles[0].radius() - 2.5).abs() < 1e-12);
8162 assert!(circles[0].center().z().abs() < 1e-12);
8163 assert!(
8164 exact_sphere_torus(&ball(1.0, 3.0), &torus)
8165 .unwrap()
8166 .is_none(),
8167 "a ball off the axis defers"
8168 );
8169 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8170 Point3::new(0.0, 0.0, 0.0),
8171 1.0,
8172 2.0,
8173 Vec3::new(0.0, 0.0, 1.0),
8174 Vec3::new(1.0, 0.0, 0.0),
8175 )
8176 .unwrap();
8177 assert!(
8178 exact_sphere_torus(&ball(0.0, 2.5), &spindle)
8179 .unwrap()
8180 .is_none()
8181 );
8182 }
8183
8184 #[test]
8189 fn a_marched_loop_closes_on_both_surfaces() {
8190 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8191 let rod =
8192 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
8193 .unwrap();
8194 let region = Aabb3 {
8195 min: Point3::new(-0.1, -5.5, 0.4),
8196 max: Point3::new(1.1, 5.5, 1.5),
8197 };
8198 let curves = intersect_analytic_analytic_in_region(
8199 AnalyticSurface::Cylinder(&rod),
8200 AnalyticSurface::Torus(&torus),
8201 32,
8202 Some((-10.0, 10.0)),
8203 None,
8204 region,
8205 )
8206 .unwrap();
8207 assert_eq!(curves.len(), 2);
8208 for c in &curves {
8209 let (t0, t1) = c.curve.domain();
8210 let worst = (0..=4000)
8211 .map(|k| {
8212 let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 4000.0, t0));
8213 let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
8214 let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
8215 on_torus.max(on_rod)
8216 })
8217 .fold(0.0, f64::max);
8218 assert!(worst <= 1e-7, "off the surfaces by {worst}");
8219 }
8220 }
8221
8222 #[test]
8227 fn a_marched_loop_round_an_axis_runs_round_it_once() {
8228 let skin = 1.6 * std::f64::consts::SQRT_2;
8229 let tilt = 0.001_f64;
8230 let torus = ToroidalSurface::with_axis(
8231 Point3::new(0.0, 0.0, 70.5),
8232 80.8 + skin / 2.0,
8233 2.0,
8234 Vec3::new(0.0, -tilt.sin(), tilt.cos()),
8235 )
8236 .unwrap();
8237 let cone = ConicalSurface::new(
8238 Point3::new(0.0, 0.0, -9.5 - skin),
8239 Vec3::new(0.0, 0.0, 1.0),
8240 std::f64::consts::FRAC_PI_4,
8241 )
8242 .unwrap();
8243 let region = Aabb3 {
8244 min: Point3::new(-84.0, -84.0, 68.0),
8245 max: Point3::new(84.0, 84.0, 73.0),
8246 };
8247 let curves = intersect_analytic_analytic_in_region(
8248 AnalyticSurface::Cone(&cone),
8249 AnalyticSurface::Torus(&torus),
8250 32,
8251 Some((16.6, 116.3)),
8252 None,
8253 region,
8254 )
8255 .unwrap();
8256 assert_eq!(curves.len(), 1);
8257 let (t0, t1) = curves[0].curve.domain();
8258 let (start, end) = (curves[0].curve.evaluate(t0), curves[0].curve.evaluate(t1));
8259 assert!((start - end).length() < 1e-9, "{start:?} to {end:?}");
8260 let n = 4000;
8261 let mut turn = 0.0;
8262 let mut last = start.y().atan2(start.x());
8263 for k in 1..=n {
8264 let p = curves[0]
8265 .curve
8266 .evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0));
8267 let at = p.y().atan2(p.x());
8268 turn += (at - last + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
8269 last = at;
8270 }
8271 assert!((turn.abs() - TAU).abs() < 1e-6, "turns {}", turn / TAU);
8272 }
8273
8274 #[test]
8278 fn exact_cone_torus_meets_a_coaxial_cone_in_circles() {
8279 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8280 let z = Vec3::new(0.0, 0.0, 1.0);
8281 let quarter = std::f64::consts::FRAC_PI_4;
8282 let cone = |apex: f64, axis: Vec3| {
8283 ConicalSurface::new(Point3::new(0.0, 0.0, apex), axis, quarter).unwrap()
8284 };
8285 let on_cone = |apex: f64| move |p: Point3| p.x().hypot(p.y()) - (p.z() - apex);
8286 let curves = exact_cone_torus(&cone(-5.0, z), &torus).unwrap().unwrap();
8287 let circles = circles_of(&curves);
8288 assert_eq!(
8289 (curves.len(), circles.len()),
8290 (2, 2),
8291 "a wall through the tube"
8292 );
8293 let worst = worst_off(&circles, &torus, on_cone(-5.0));
8294 assert!(worst < 1e-12, "{worst}");
8295 assert!(
8296 exact_cone_torus(&cone(-8.0, z), &torus)
8297 .unwrap()
8298 .unwrap()
8299 .is_empty(),
8300 "a wall clear of the tube misses it"
8301 );
8302 let touch = -4.0 - 1.5 * std::f64::consts::SQRT_2;
8303 let curves = exact_cone_torus(&cone(touch, z), &torus).unwrap().unwrap();
8304 let circles = circles_of(&curves);
8305 assert_eq!(circles.len(), 1, "a wall touching the tube");
8306 let worst = worst_off(&circles, &torus, on_cone(touch));
8307 assert!(worst < 1e-12, "{worst}");
8308 assert_eq!(
8309 exact_cone_torus(&cone(touch + 1e-6, z), &torus)
8310 .unwrap()
8311 .unwrap()
8312 .len(),
8313 2,
8314 "a wall into the tube by more than the tolerance crosses it twice"
8315 );
8316 let below = ConicalSurface::new(Point3::new(0.0, 0.0, 5.0), -z, quarter).unwrap();
8318 let curves = exact_cone_torus(&below, &torus).unwrap().unwrap();
8319 let circles = circles_of(&curves);
8320 assert_eq!(circles.len(), 2);
8321 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - (5.0 - p.z()));
8322 assert!(worst < 1e-12, "{worst}");
8323 let tilted = cone(-5.0, Vec3::new(0.0, 0.1, 1.0));
8324 let offset = ConicalSurface::new(Point3::new(0.5, 0.0, -5.0), z, quarter).unwrap();
8325 assert!(exact_cone_torus(&tilted, &torus).unwrap().is_none());
8326 assert!(exact_cone_torus(&offset, &torus).unwrap().is_none());
8327 let far = ConicalSurface::new(Point3::new(0.0005, 0.0, -1e6), z, (1e6_f64 / 4.75).atan())
8330 .unwrap();
8331 assert!(
8332 exact_cone_torus(&far, &torus).unwrap().is_none(),
8333 "a cone off the torus's axis by 0.0005 is not coaxial, however far its apex"
8334 );
8335 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8336 Point3::new(0.0, 0.0, 0.0),
8337 1.0,
8338 2.0,
8339 z,
8340 Vec3::new(1.0, 0.0, 0.0),
8341 )
8342 .unwrap();
8343 assert!(
8344 exact_cone_torus(&cone(-5.0, z), &spindle)
8345 .unwrap()
8346 .is_none(),
8347 "a spindle torus's tube reaches the axis"
8348 );
8349 }
8350
8351 #[test]
8352 fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
8353 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8354 let z = Vec3::new(0.0, 0.0, 1.0);
8355 let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
8356 let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
8357 let circles = circles_of(&curves);
8358 assert_eq!((curves.len(), circles.len()), (2, 2));
8359 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
8360 assert!(worst < 1e-9, "{worst}");
8361 assert!(
8362 exact_cylinder_torus(&rod(2.0), &torus)
8363 .unwrap()
8364 .unwrap()
8365 .is_empty(),
8366 "a rod clear in the hole misses"
8367 );
8368 for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
8369 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8370 let circles = circles_of(&curves);
8371 assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
8372 assert!(circles[0].center().z().abs() < 1e-12, "{label}");
8373 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
8374 assert!(worst < 1e-9, "{label}: {worst}");
8375 }
8376 assert!(
8377 exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
8378 .unwrap()
8379 .unwrap()
8380 .is_empty(),
8381 "a wall clear of the tube by more than the tolerance misses it"
8382 );
8383 assert_eq!(
8384 exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
8385 .unwrap()
8386 .unwrap()
8387 .len(),
8388 2,
8389 "a wall into the tube by more than the tolerance crosses it twice"
8390 );
8391 for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
8395 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8396 assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
8397 }
8398 let tilted =
8399 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
8400 .unwrap();
8401 let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
8402 assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
8403 assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
8404 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8405 Point3::new(0.0, 0.0, 0.0),
8406 1.0,
8407 2.0,
8408 z,
8409 Vec3::new(1.0, 0.0, 0.0),
8410 )
8411 .unwrap();
8412 assert!(
8413 exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
8414 "a spindle torus's inner lemon also meets the rod"
8415 );
8416 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8419 Point3::new(0.0, 0.0, 4.7),
8420 0.1,
8421 2.45,
8422 z,
8423 Vec3::new(1.0, 0.0, 0.0),
8424 )
8425 .unwrap();
8426 let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
8427 let circles = circles_of(&curves);
8428 assert_eq!(circles.len(), 1);
8429 assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
8430 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
8431 assert!(worst < 1e-9, "{worst}");
8432 let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
8433 let circles = circles_of(&curves);
8434 assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
8435 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
8436 assert!(worst < 1e-9, "{worst}");
8437 }
8438
8439 fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
8442 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
8443 let cyl =
8444 CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
8445 .unwrap();
8446 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8447 .unwrap()
8448 .unwrap();
8449 let mut worst: f64 = 0.0;
8450 for c in &curves {
8451 for ip in &c.points {
8452 let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
8453 let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
8454 worst = worst
8455 .max((on_sphere - ip.point).length())
8456 .max((on_cylinder - ip.point).length());
8457 }
8458 let (t0, t1) = c.curve.domain();
8459 assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
8460 for k in 0..=400 {
8461 let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8462 let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
8463 let on_cylinder = ((p.x() - cylinder_origin.x())
8464 .hypot(p.y() - cylinder_origin.y())
8465 - cylinder_radius)
8466 .abs();
8467 worst = worst.max(on_sphere).max(on_cylinder);
8468 }
8469 }
8470 (curves.len(), worst)
8471 }
8472
8473 #[test]
8476 fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
8477 let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
8478 assert_eq!(count, 2);
8479 assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
8480 }
8481
8482 #[test]
8484 fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
8485 let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
8486 assert_eq!(count, 1);
8487 assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
8488 }
8489
8490 #[test]
8494 fn a_ball_through_a_wide_wall_meets_it_in_one_close_loop() {
8495 let centre = Point3::new(7.35, 0.0, 0.0);
8496 let sphere = SphericalSurface::new(centre, 2.4145).unwrap();
8497 let cyl =
8498 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 9.15)
8499 .unwrap();
8500 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8501 .unwrap()
8502 .unwrap();
8503 assert_eq!(curves.len(), 1);
8504 let (t0, t1) = curves[0].curve.domain();
8505 let mut worst: f64 = 0.0;
8506 for k in 0..=2000 {
8507 let p = curves[0]
8508 .curve
8509 .evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8510 let on_sphere = ((p - centre).length() - 2.4145).abs();
8511 let on_cylinder = (p.x().hypot(p.y()) - 9.15).abs();
8512 worst = worst.max(on_sphere).max(on_cylinder);
8513 }
8514 assert!(worst < 1e-6, "the loop leaves the surfaces by {worst}");
8515 }
8516
8517 #[test]
8520 fn a_whole_torus_patch_spans_its_ring() {
8521 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 50.0, 10.0).unwrap();
8522 let size = patch_diagonal(&|u, v| torus.evaluate(u, v), (0.0, TAU), (0.0, TAU));
8523 assert!((size - 100.0).abs() < 1e-9, "size {size}");
8524 }
8525
8526 #[test]
8530 fn marched_cone_cylinder_curves_end_on_the_band_edges() {
8531 let half_angle = 14.0_f64.atan2(10.0);
8532 let cone = ConicalSurface::new(
8533 Point3::new(0.0, 0.0, 273.2),
8534 Vec3::new(0.0, 0.0, -1.0),
8535 half_angle,
8536 )
8537 .unwrap();
8538 let cyl = CylindricalSurface::new(
8539 Point3::new(0.0, -50.0, 215.0),
8540 Vec3::new(0.0, 1.0, 0.0),
8541 60.0,
8542 )
8543 .unwrap();
8544 let v_cone = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8547 let region = Aabb3 {
8548 min: Point3::new(-59.98, -40.0, 178.0),
8549 max: Point3::new(-47.23, 40.0, 192.0),
8550 };
8551 let curves = intersect_analytic_analytic_in_region(
8552 AnalyticSurface::Cone(&cone),
8553 AnalyticSurface::Cylinder(&cyl),
8554 32,
8555 Some(v_cone),
8556 Some((10.0, 90.0)),
8557 region,
8558 )
8559 .unwrap();
8560 assert_eq!(curves.len(), 2);
8561 for c in &curves {
8562 let (t0, t1) = c.curve.domain();
8563 for p in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
8564 let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8565 assert!(on_edge, "a curve ends at {p:?}");
8566 }
8567 }
8568 }
8569
8570 #[test]
8574 fn long_march_steps_end_on_the_band_edges() {
8575 let half_angle = 14.0_f64.atan2(10.0);
8576 let cone = ConicalSurface::new(
8577 Point3::new(0.0, 0.0, 273.2),
8578 Vec3::new(0.0, 0.0, -1.0),
8579 half_angle,
8580 )
8581 .unwrap();
8582 let cyl = CylindricalSurface::new(
8583 Point3::new(0.0, -50.0, 215.0),
8584 Vec3::new(0.0, 1.0, 0.0),
8585 60.0,
8586 )
8587 .unwrap();
8588 let (a, b) = (
8589 AnalyticSurface::Cone(&cone),
8590 AnalyticSurface::Cylinder(&cyl),
8591 );
8592 let (surf_a, norm_a, u_a, _) = surface_closures(&a);
8593 let (surf_b, norm_b, u_b, _) = surface_closures(&b);
8594 let v_a = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8595 let v_b = (10.0, 90.0);
8596 let seed = correct_to_intersection(
8597 &a,
8598 &b,
8599 surf_a.as_ref(),
8600 norm_a.as_ref(),
8601 surf_b.as_ref(),
8602 norm_b.as_ref(),
8603 Point3::new(-53.0, -30.0, 187.0),
8604 u_a,
8605 v_a,
8606 u_b,
8607 v_b,
8608 20,
8609 );
8610 for step in [0.5, 1.0, 2.0, 3.0] {
8611 let points = march_analytic_intersection(
8612 &a,
8613 &b,
8614 surf_a.as_ref(),
8615 norm_a.as_ref(),
8616 surf_b.as_ref(),
8617 norm_b.as_ref(),
8618 seed,
8619 u_a,
8620 v_a,
8621 u_b,
8622 v_b,
8623 step,
8624 true,
8625 true,
8626 None,
8627 )
8628 .unwrap();
8629 for p in [points[0], points[points.len() - 1]] {
8630 let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8631 assert!(on_edge, "step {step}: the march ends at {p:?}");
8632 }
8633 }
8634 }
8635
8636 #[test]
8637 fn disjoint_cylinders_no_intersection() {
8638 let cyl_a =
8639 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8640 .unwrap();
8641 let cyl_b =
8642 CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8643 .unwrap();
8644
8645 let curves = intersect_analytic_analytic(
8646 AnalyticSurface::Cylinder(&cyl_a),
8647 AnalyticSurface::Cylinder(&cyl_b),
8648 16,
8649 )
8650 .unwrap();
8651
8652 assert!(curves.is_empty(), "disjoint cylinders should not intersect");
8653 }
8654
8655 fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
8659 use crate::traits::ParametricCurve;
8660 match curve {
8661 ExactIntersectionCurve::Circle(c) => (0..=64)
8662 .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
8663 .collect(),
8664 ExactIntersectionCurve::Ellipse(e) => (0..=64)
8665 .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
8666 .collect(),
8667 ExactIntersectionCurve::Points(pts) => pts.clone(),
8668 }
8669 }
8670
8671 fn assert_on_plane_and_cone(
8674 curves: &[ExactIntersectionCurve],
8675 cone: &ConicalSurface,
8676 n: Vec3,
8677 d: f64,
8678 z_bound: (f64, f64),
8679 ) {
8680 assert!(!curves.is_empty(), "expected at least one section curve");
8681 let mut total = 0;
8682 for curve in curves {
8683 for p in collect_points(curve) {
8684 total += 1;
8685 let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
8686 assert!(
8687 plane_err < 1e-9,
8688 "point off plane by {plane_err:.2e}: {p:?}"
8689 );
8690 let (u, v) = cone.project_point(p);
8691 let q = cone.evaluate(u, v);
8692 let cone_err =
8693 ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
8694 .sqrt();
8695 assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
8696 assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
8697 assert!(
8698 p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
8699 "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
8700 p.z()
8701 );
8702 }
8703 }
8704 assert!(total >= 8, "too few section points ({total})");
8705 }
8706
8707 #[test]
8708 fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
8709 let cone = ConicalSurface::new(
8713 Point3::new(0.0, 0.0, 0.0),
8714 Vec3::new(0.0, 0.0, 1.0),
8715 std::f64::consts::FRAC_PI_4,
8716 )
8717 .unwrap();
8718 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8719 let d = n.z() * 5.0;
8721 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8722 assert!(
8723 curves
8724 .iter()
8725 .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
8726 "oblique steep plane × cone must yield an exact Ellipse"
8727 );
8728 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
8730 }
8731
8732 #[test]
8733 fn oblique_plane_cone_wrong_nappe_is_empty() {
8734 let cone = ConicalSurface::new(
8738 Point3::new(0.0, 0.0, 0.0),
8739 Vec3::new(0.0, 0.0, 1.0),
8740 std::f64::consts::FRAC_PI_4,
8741 )
8742 .unwrap();
8743 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8744 let d = n.z() * -5.0;
8745 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8746 assert!(
8747 curves.is_empty(),
8748 "plane on the phantom-nappe side must yield no real curve, got {}",
8749 curves.len()
8750 );
8751 }
8752
8753 #[test]
8754 fn oblique_plane_cone_parabola_on_both_single_branch() {
8755 let cone = ConicalSurface::new(
8758 Point3::new(0.0, 0.0, 0.0),
8759 Vec3::new(0.0, 0.0, 1.0),
8760 std::f64::consts::FRAC_PI_4,
8761 )
8762 .unwrap();
8763 let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
8764 let d = n.x() * 3.0 + n.z() * 3.0; let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8766 assert_eq!(
8767 curves.len(),
8768 1,
8769 "a parabola is a single branch, got {}",
8770 curves.len()
8771 );
8772 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
8774 }
8775
8776 #[test]
8777 fn oblique_plane_cone_hyperbola_real_nappe_only() {
8778 let cone = ConicalSurface::new(
8786 Point3::new(-59.0, -59.0, 15.85),
8787 Vec3::new(0.0, 0.0, -1.0),
8788 std::f64::consts::FRAC_PI_4,
8789 )
8790 .unwrap();
8791 let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
8792 let d = -58.360_56;
8793 let cos_theta = n.dot(cone.axis()).abs();
8794 assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
8795 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8796 assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
8799 for c in &curves {
8801 assert!(
8802 matches!(c, ExactIntersectionCurve::Points(_)),
8803 "hyperbola must be sampled Points, not a closed conic"
8804 );
8805 }
8806 }
8807
8808 #[test]
8812 fn sphere_sphere_meets_in_a_circle_on_both() {
8813 let ball = |x: f64, y: f64, z: f64, r: f64| {
8814 SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
8815 };
8816 let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
8817 let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
8818 assert_eq!(curves.len(), 1);
8819 let circle = match &curves[0] {
8820 ExactIntersectionCurve::Circle(circle) => circle,
8821 other => unreachable!("expected a circle, got {other:?}"),
8822 };
8823 for k in 0..16 {
8824 let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
8825 assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
8826 assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
8827 }
8828 assert!(
8829 exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
8830 .unwrap()
8831 .unwrap()
8832 .is_empty()
8833 );
8834 assert!(
8835 exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
8836 .unwrap()
8837 .unwrap()
8838 .is_empty()
8839 );
8840 assert!(
8841 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
8842 .unwrap()
8843 .unwrap()
8844 .is_empty()
8845 );
8846 assert!(
8847 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
8848 .unwrap()
8849 .is_none()
8850 );
8851
8852 let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
8855 match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
8856 [ExactIntersectionCurve::Circle(c)] => c.radius(),
8857 other => unreachable!("expected one circle, got {other:?}"),
8858 }
8859 };
8860 let tiny = ball(2.0, 0.0, 0.0, 1e-5);
8861 assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
8862 assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
8863 let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
8864 let far = radius(
8865 &ball(1e10, 0.0, 0.0, 2.0),
8866 &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
8867 );
8868 assert!(near > 1e-3);
8869 assert!((far - near).abs() < 1e-9 * near.max(1.0));
8870 }
8871
8872 #[allow(clippy::panic)]
8875 fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
8876 sections
8877 .iter()
8878 .map(|s| match s {
8879 PlaneSection::Line { line, ray } => (line.clone(), *ray),
8880 other => panic!("expected a line, got {other:?}"),
8881 })
8882 .collect()
8883 }
8884
8885 #[test]
8890 fn a_plane_along_a_cylinder_cuts_its_rulings() {
8891 let cyl =
8892 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
8893 .unwrap();
8894 let y = Vec3::new(0.0, 1.0, 0.0);
8895 let surface = AnalyticSurface::Cylinder(&cyl);
8896 let on_both = |p: Point3, d: f64| {
8897 assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
8898 assert!(
8899 (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
8900 "{p:?} off the cylinder"
8901 );
8902 };
8903 for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
8904 assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
8905 let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
8906 assert_eq!(lines.len(), count, "plane y = {d}");
8907 let mut xs = Vec::new();
8908 for (line, ray) in lines {
8909 assert!(!ray);
8910 assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
8911 for t in [-3.0, 0.0, 3.0] {
8912 on_both(line.evaluate(t), d);
8913 }
8914 xs.push(line.evaluate(0.0).x());
8915 }
8916 if count == 2 {
8917 let apart = (xs[0] - xs[1]).abs();
8918 let want = 2.0 * (1.0 - d * d).sqrt();
8919 assert!(
8920 (apart - want).abs() < 1e-9 * want.max(1e-6),
8921 "{apart} apart"
8922 );
8923 }
8924 }
8925 }
8926
8927 #[test]
8932 #[allow(clippy::panic)]
8933 fn a_plane_through_a_cone_apex_cuts_its_rulings() {
8934 use std::f64::consts::FRAC_PI_4;
8935
8936 let cone = ConicalSurface::new(
8937 Point3::new(1.0, 2.0, 3.0),
8938 Vec3::new(0.0, 0.0, 1.0),
8939 FRAC_PI_4,
8940 )
8941 .unwrap();
8942 let surface = AnalyticSurface::Cone(&cone);
8943 let apex = cone.apex();
8944 let through = |n: Vec3| {
8945 let n = n.normalize().unwrap();
8946 let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
8947 assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
8948 (n, d, exact_plane_section(surface, n, d).unwrap())
8949 };
8950 for (n, count) in [
8951 (Vec3::new(1.0, 0.0, 0.0), 2),
8952 (Vec3::new(1.0, 0.0, -1.0), 1),
8953 ] {
8954 let (n, d, sections) = through(n);
8955 let rays = lines_of(§ions);
8956 assert_eq!(rays.len(), count, "plane normal {n:?}");
8957 for (line, ray) in rays {
8958 assert!(ray);
8959 assert!((line.evaluate(0.0) - apex).length() < 1e-12);
8960 let p = line.evaluate(2.0);
8961 assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
8962 let rel = p - apex;
8963 assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
8964 assert!(
8965 (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
8966 "{p:?} off the cone"
8967 );
8968 }
8969 }
8970 for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
8971 let (_, _, sections) = through(n);
8972 assert!(
8973 matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
8974 "{sections:?}"
8975 );
8976 }
8977
8978 let upright = ConicalSurface::new(
8979 Point3::new(0.0, 0.0, 0.0),
8980 Vec3::new(0.0, 0.0, 1.0),
8981 FRAC_PI_4,
8982 )
8983 .unwrap();
8984 let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
8985 let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
8986 let [PlaneSection::Ellipse(ellipse)] = §ions[..] else {
8987 panic!("{sections:?}");
8988 };
8989 assert!(
8990 ellipse.semi_major() > 1.0,
8991 "semi-major {}",
8992 ellipse.semi_major()
8993 );
8994 }
8995
8996 #[test]
8999 #[allow(clippy::panic)]
9000 fn a_plane_touching_a_sphere_meets_it_at_a_point() {
9001 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
9002 let surface = AnalyticSurface::Sphere(&sphere);
9003 let z = Vec3::new(0.0, 0.0, 1.0);
9004 assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
9005 let sections = exact_plane_section(surface, z, 0.0).unwrap();
9006 assert!(
9007 matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
9008 "{sections:?}"
9009 );
9010 assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
9011 for height in [5e-15, 1e-12, 1e-8] {
9012 let sections = exact_plane_section(surface, z, height).unwrap();
9013 let [PlaneSection::Circle(circle)] = §ions[..] else {
9014 panic!("{sections:?}");
9015 };
9016 let want = (height * (2.0 - height)).sqrt();
9017 assert!(
9018 (circle.radius() - want).abs() < 1e-3 * want,
9019 "circle at z = {height}: radius {}, want {want}",
9020 circle.radius()
9021 );
9022 assert!((circle.center().z() - height).abs() < 1e-15);
9023 }
9024 }
9025
9026 fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
9028 let mut far = 0.0_f64;
9029 for ic in curves {
9030 let (t0, t1) = ic.curve.domain();
9031 for i in 0..=2000 {
9032 let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
9033 far = far.max(off(ic.curve.evaluate(t)));
9034 }
9035 }
9036 far
9037 }
9038
9039 #[test]
9042 fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
9043 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9044 let bore =
9045 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9046 .unwrap();
9047 let curves = intersect_analytic_analytic_bounded(
9048 AnalyticSurface::Sphere(&ball),
9049 AnalyticSurface::Cylinder(&bore),
9050 64,
9051 None,
9052 Some((0.0, 4.0)),
9053 )
9054 .unwrap();
9055 assert_eq!(curves.len(), 1);
9056 let far = farthest(&curves, |p| {
9057 let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9058 on_ball
9059 .max((p.x().hypot(p.y()) - 1.0).abs())
9060 .max(p.z().abs())
9061 });
9062 assert!(far < 1e-14, "circle strays {far:.2e}");
9063 }
9064
9065 #[test]
9068 fn overlapping_balls_meet_on_an_exact_circle() {
9069 let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9070 let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
9071 let curves = intersect_analytic_analytic_bounded(
9072 AnalyticSurface::Sphere(&a),
9073 AnalyticSurface::Sphere(&b),
9074 64,
9075 None,
9076 None,
9077 )
9078 .unwrap();
9079 assert_eq!(curves.len(), 1);
9080 let far = farthest(&curves, |p| {
9081 let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9082 on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
9083 });
9084 assert!(far < 1e-14, "circle strays {far:.2e}");
9085 }
9086
9087 #[test]
9090 fn a_conic_loop_is_its_ellipse() {
9091 let centre = Point3::new(1.0, -2.0, 0.5);
9092 let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
9093 let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
9094 let (t0, t1) = curve.domain();
9095 assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
9096 for i in 0..=2000 {
9097 let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
9098 let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
9099 assert!(
9100 (x.hypot(y) - 1.0).abs() < 1e-14,
9101 "off its ellipse by {}",
9102 x.hypot(y) - 1.0
9103 );
9104 assert!(p.dot(frame.z).abs() < 1e-14);
9105 }
9106 }
9107
9108 #[test]
9112 fn touching_coaxial_rings_meet_along_one_circle() {
9113 let z = Vec3::new(0.0, 0.0, 1.0);
9114 let x = Vec3::new(1.0, 0.0, 0.0);
9115 let ring =
9116 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
9117 .unwrap();
9118 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
9119 let curves = intersect_analytic_analytic_bounded(
9120 AnalyticSurface::Sphere(&ball),
9121 AnalyticSurface::Torus(&ring),
9122 64,
9123 None,
9124 None,
9125 )
9126 .unwrap();
9127 assert_eq!(curves.len(), 1);
9128 let far = farthest(&curves, |p| {
9129 let q = p - Point3::new(0.0, 0.0, 0.0);
9130 let rho = q.x().hypot(q.y());
9131 let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
9132 on_ring.max((q.length() - 2.0).abs())
9133 });
9134 assert!(far < 1e-14, "circle strays {far:.2e}");
9135
9136 let wider =
9140 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
9141 .unwrap();
9142 let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
9143 let circles = circles_of(&touching);
9144 assert_eq!(circles.len(), 1);
9145 assert!(
9146 (circles[0].radius() - 3.6).abs() < 1e-12,
9147 "{}",
9148 circles[0].radius()
9149 );
9150 assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
9151 }
9152
9153 #[test]
9158 fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
9159 let z = Vec3::new(0.0, 0.0, 1.0);
9160 let x = Vec3::new(1.0, 0.0, 0.0);
9161 let ring = |big: f64| {
9162 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
9163 .unwrap()
9164 };
9165 let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
9166 .unwrap()
9167 .unwrap();
9168 let circles = circles_of(&crossing);
9169 assert_eq!(circles.len(), 2);
9170 for circle in circles {
9171 let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
9172 assert!(
9173 (circle.center().z().abs() - height).abs() < 1e-9,
9174 "{}",
9175 circle.center().z()
9176 );
9177 }
9178 let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
9179 .unwrap()
9180 .unwrap();
9181 assert!(apart.is_empty());
9182 }
9183
9184 #[test]
9188 fn a_plane_cuts_a_cones_open_conics() {
9189 let up = Vec3::new(0.0, 0.0, 1.0);
9190 let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
9191 let steep =
9192 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
9193 let slope = 60_f64.to_radians().tan();
9194 let along =
9195 exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
9196 .unwrap();
9197 let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
9198 unreachable!("{along:?}")
9199 };
9200 for i in -20..=20 {
9201 let p = h.evaluate(f64::from(i) / 5.0);
9202 assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
9203 assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
9204 }
9205 let even =
9206 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
9207 let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
9208 let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
9209 let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
9210 unreachable!("{above:?}")
9211 };
9212 for i in -20..=20 {
9213 let p = parabola.evaluate(f64::from(i) / 2.0);
9214 assert!(
9215 (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
9216 "{p:?}"
9217 );
9218 assert!(
9219 p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
9220 "{p:?}"
9221 );
9222 }
9223 let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
9224 assert!(below.is_empty(), "{below:?}");
9225 }
9226
9227 #[test]
9233 fn extreme_cones_give_sections_on_the_cone() {
9234 let up = Vec3::new(0.0, 0.0, 1.0);
9235 let apex = Point3::new(0.0, 0.0, 0.0);
9236 let holds = |cone: &ConicalSurface, q: Point3| {
9237 let w = q - apex;
9238 (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
9239 };
9240 let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
9241 let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
9242 let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
9243 for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
9244 let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
9245 assert!(!sections.is_empty());
9246 for section in §ions {
9247 let points: Vec<Point3> = match section {
9248 PlaneSection::Hyperbola(h) => {
9249 (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
9250 }
9251 PlaneSection::Parabola(q) => {
9252 (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
9253 }
9254 PlaneSection::Points(points) => points.clone(),
9255 other => unreachable!("{other:?}"),
9256 };
9257 for q in points {
9258 assert!(holds(cone, q), "{q:?} off the cone");
9259 }
9260 }
9261 }
9262 let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
9263 assert!(matches!(
9264 flat_section.as_slice(),
9265 [PlaneSection::Hyperbola(_)]
9266 ));
9267 }
9268
9269 fn parallel_rulings(
9272 (c1, r1, v1): (Point3, f64, (f64, f64)),
9273 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9274 ) -> Vec<(Point3, Point3)> {
9275 rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
9276 }
9277
9278 fn rulings_within(
9281 (c1, r1, v1): (Point3, f64, (f64, f64)),
9282 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9283 tolerance: f64,
9284 ) -> Vec<(Point3, Point3)> {
9285 let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
9286 let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
9287 let curves = intersect_analytic_analytic_bounded(
9288 AnalyticSurface::Cylinder(&a),
9289 AnalyticSurface::Cylinder(&b),
9290 32,
9291 Some(v1),
9292 Some(v2),
9293 )
9294 .unwrap();
9295 curves
9296 .iter()
9297 .map(|ic| {
9298 let (t0, t1) = ic.curve.domain();
9299 let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
9300 for i in 0..=100 {
9301 let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
9302 let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
9303 let w = x - c2;
9304 let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
9305 assert!(
9306 on_a.abs() < tolerance && on_b.abs() < tolerance,
9307 "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
9308 );
9309 }
9310 if p.z() <= q.z() { (p, q) } else { (q, p) }
9311 })
9312 .collect()
9313 }
9314
9315 #[test]
9319 fn overlapping_parallel_rods_meet_along_two_rulings() {
9320 let mut rulings = parallel_rulings(
9321 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
9322 (
9323 Point3::new(1.2, 0.0, 3.0),
9324 1.0,
9325 Vec3::new(0.0, 0.0, -1.0),
9326 (0.0, 2.0),
9327 ),
9328 );
9329 rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9330 assert_eq!(rulings.len(), 2);
9331 for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
9332 assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
9333 assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
9334 }
9335 }
9336
9337 #[test]
9340 fn touching_parallel_rods_meet_along_one_ruling() {
9341 let up = Vec3::new(0.0, 0.0, 1.0);
9342 let beside = parallel_rulings(
9343 (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
9344 (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
9345 );
9346 assert_eq!(beside.len(), 1);
9347 assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
9348 assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
9349 let inside = parallel_rulings(
9350 (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
9351 (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9352 );
9353 assert_eq!(inside.len(), 1);
9354 assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
9355 let apart = parallel_rulings(
9356 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
9357 (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9358 );
9359 assert!(apart.is_empty());
9360 }
9361
9362 #[test]
9366 fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
9367 let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9368 .unwrap();
9369 let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
9370 let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
9371 let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
9372 assert!(span(100.0).unwrap().is_none());
9373 assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
9374 }
9375
9376 #[test]
9380 fn parallel_rods_keep_short_and_close_rulings() {
9381 let up = Vec3::new(0.0, 0.0, 1.0);
9382 let huge = rulings_within(
9383 (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
9384 (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
9385 1e-9,
9386 );
9387 assert_eq!(huge.len(), 2);
9388 assert!(
9389 huge.iter()
9390 .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
9391 );
9392 let mut close = rulings_within(
9393 (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
9394 (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
9395 1e-9,
9396 );
9397 assert_eq!(close.len(), 2);
9398 close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9399 let apart = close[1].0.y() - close[0].0.y();
9400 assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
9401 }
9402
9403 fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
9405 let q = p - cone.apex();
9406 let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
9407 ((along.abs() - s * q.length()).abs(), along / s)
9408 }
9409
9410 #[test]
9414 fn cones_sharing_an_apex_touch_along_one_ruling() {
9415 let apex = Point3::new(1.0, 2.0, 3.0);
9416 let a = 20.0_f64.to_radians();
9417 let half = std::f64::consts::FRAC_PI_2 - a;
9418 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9419 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9420 let curves = intersect_analytic_analytic_bounded(
9421 AnalyticSurface::Cone(&c1),
9422 AnalyticSurface::Cone(&c2),
9423 64,
9424 Some((0.2, 3.0)),
9425 Some((0.5, 4.0)),
9426 )
9427 .unwrap();
9428 assert_eq!(curves.len(), 1);
9429 let curve = &curves[0].curve;
9430 let (t0, t1) = curve.domain();
9431 let x = Vec3::new(1.0, 0.0, 0.0);
9432 assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
9433 assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
9434 }
9435
9436 #[test]
9440 fn cones_sharing_an_apex_cross_along_two_rulings() {
9441 let apex = Point3::new(-1.0, 0.5, 2.0);
9442 let b = 20.0_f64.to_radians();
9443 let half = 60.0_f64.to_radians();
9444 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9445 let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
9446 for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
9447 let curves = intersect_analytic_analytic_bounded(
9448 AnalyticSurface::Cone(&c1),
9449 AnalyticSurface::Cone(&c2),
9450 64,
9451 Some(range),
9452 Some(range),
9453 )
9454 .unwrap();
9455 assert_eq!(curves.len(), pieces, "{range:?}");
9456 for ic in &curves {
9457 let (t0, t1) = ic.curve.domain();
9458 for k in 0..=20 {
9459 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
9460 for cone in [&c1, &c2] {
9461 let (off, v) = off_cone(cone, p);
9462 assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
9463 assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
9464 }
9465 }
9466 if pieces == 4 {
9467 let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
9468 assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
9469 }
9470 for point in &ic.points {
9471 let (on1, on2) = (point.param1, point.param2);
9472 assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
9473 assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
9474 }
9475 }
9476 }
9477 }
9478
9479 #[test]
9484 fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
9485 let apex = Point3::new(0.0, 0.0, 0.0);
9486 let half = 60.0_f64.to_radians();
9487 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9488 let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
9489 .unwrap();
9490 let near = Some((0.5, 2.0));
9491 assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
9492 let a = 20.0_f64.to_radians();
9493 let half = std::f64::consts::FRAC_PI_2 - a;
9494 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9495 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9496 let far = Some((0.5, 1e6));
9497 assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
9498 }
9499
9500 #[test]
9503 fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
9504 let apex = Point3::new(0.0, 0.0, 0.0);
9505 let half = std::f64::consts::FRAC_PI_4 - 1e-15;
9506 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9507 let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
9508 let range = Some((0.5, 1e6));
9509 let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
9510 assert_eq!(curves.len(), 2);
9511 let ends: Vec<Point3> = curves
9512 .iter()
9513 .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
9514 .collect();
9515 assert!((ends[0] - ends[1]).length() > 0.05);
9516 }
9517
9518 #[test]
9525 fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
9526 let o = Point3::new(1.0, 2.0, 3.0);
9527 let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
9528 let (s, c) = 30.0_f64.to_radians().sin_cos();
9529 let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
9530 let on_ring = |p: Point3| {
9531 let q = p - o;
9532 ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
9533 };
9534 let balls = [
9535 (o + out * 5.0, 1.0),
9536 (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
9537 (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
9538 ];
9539 let mut touches = Vec::new();
9540 for (centre, radius) in balls {
9541 let ball = SphericalSurface::new(centre, radius).unwrap();
9542 let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
9543 let p = match exacts.as_slice() {
9544 [ExactIntersectionCurve::Points(points)] => points[0],
9545 _ => unreachable!("one touching point"),
9546 };
9547 assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
9548 let curves = intersect_analytic_analytic(
9549 AnalyticSurface::Sphere(&ball),
9550 AnalyticSurface::Torus(&ring),
9551 16,
9552 )
9553 .unwrap();
9554 assert_eq!(curves.len(), 1);
9555 let (t0, t1) = curves[0].curve.domain();
9556 assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
9557 assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
9558 touches.push(p);
9559 }
9560 assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
9561 let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
9562 assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
9563 let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
9564 let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
9565 let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
9566 unreachable!("one meridian circle");
9567 };
9568 assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
9569 assert!((circle.radius() - 1.0).abs() < 1e-12);
9570 }
9571
9572 fn taper_pin_and_rod(
9576 flip: bool,
9577 spin: f64,
9578 ) -> (ConicalSurface, (f64, f64), f64, CylindricalSurface) {
9579 let slope = 0.7_f64 / 16.0;
9580 let half = (1.0 / slope).atan();
9581 let (apex_y, axis_y) = if flip {
9582 (-8.0 - 0.8 / slope, 1.0)
9583 } else {
9584 (-8.0 + 1.5 / slope, -1.0)
9585 };
9586 let pin = ConicalSurface::new(
9587 Point3::new(0.0, apex_y, 10.0),
9588 Vec3::new(0.0, axis_y, 0.0),
9589 half,
9590 )
9591 .unwrap();
9592 let (h0, h1) = ((-8.0 - apex_y).abs(), (8.0 - apex_y).abs());
9593 let v_pin = (h0.min(h1) / half.sin(), h0.max(h1) / half.sin());
9594 let rod = CylindricalSurface::with_ref_dir(
9595 Point3::new(0.0, 0.0, 0.0),
9596 Vec3::new(0.0, 0.0, 1.0),
9597 5.0,
9598 Vec3::new(spin.cos(), spin.sin(), 0.0),
9599 )
9600 .unwrap();
9601 (pin, v_pin, apex_y, rod)
9602 }
9603
9604 const TAPER_PIN_REGION: Aabb3 = Aabb3 {
9606 min: Point3::new(-1.6, -5.1, 8.4),
9607 max: Point3::new(1.6, 5.1, 11.6),
9608 };
9609
9610 fn farthest_along(curve: &NurbsCurve, n: u32, off: impl Fn(Point3) -> f64) -> f64 {
9612 let (t0, t1) = curve.domain();
9613 (0..=n)
9614 .map(|k| off(curve.evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0))))
9615 .fold(0.0, f64::max)
9616 }
9617
9618 #[test]
9625 fn marched_cone_cylinder_sections_stay_on_both_between_their_points() {
9626 let lin = Tolerance::new().linear;
9627 for flip in [false, true] {
9628 for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
9629 let (pin, v_pin, apex_y, rod) = taper_pin_and_rod(flip, spin);
9630 let half = pin.half_angle();
9631 let off_pin = |p: Point3| {
9632 let rho = p.x().hypot(p.z() - 10.0);
9633 let h = (p.y() - apex_y).abs();
9634 rho.madd(half.sin(), -h * half.cos()).abs()
9635 };
9636 let off_rod = |p: Point3| (p.x().hypot(p.y()) - 5.0).abs();
9637 for rod_first in [true, false] {
9638 let (a, b, va, vb) = if rod_first {
9639 (
9640 AnalyticSurface::Cylinder(&rod),
9641 AnalyticSurface::Cone(&pin),
9642 Some((0.0, 20.0)),
9643 Some(v_pin),
9644 )
9645 } else {
9646 (
9647 AnalyticSurface::Cone(&pin),
9648 AnalyticSurface::Cylinder(&rod),
9649 Some(v_pin),
9650 Some((0.0, 20.0)),
9651 )
9652 };
9653 let curves =
9654 marched_sections(a, b, 32, va, vb, Some(TAPER_PIN_REGION)).unwrap();
9655 assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
9656 for c in &curves {
9657 let worst = farthest_along(&c.curve, 4000, |p| off_pin(p).max(off_rod(p)));
9658 assert!(worst <= lin, "spin {spin} flip {flip}: off by {worst:.2e}");
9659 }
9660 }
9661 }
9662 }
9663
9664 let (cone, tube) = cone_and_tilted_tube();
9665 let curves = intersect_analytic_analytic_bounded(
9666 AnalyticSurface::Cone(&cone),
9667 AnalyticSurface::Cylinder(&tube),
9668 32,
9669 Some((0.5, 4.0)),
9670 Some((-5.0, 5.0)),
9671 )
9672 .unwrap();
9673 assert!(!curves.is_empty());
9674 let (sin, cos) = cone.half_angle().sin_cos();
9675 let axis = tube.axis();
9676 for c in &curves {
9677 let worst = farthest_along(&c.curve, 4000, |p| {
9678 let on_cone = p.x().hypot(p.y()).madd(sin, -p.z().abs() * cos).abs();
9679 let w = p - tube.origin();
9680 let on_tube = ((w - axis * axis.dot(w)).length() - 0.1).abs();
9681 on_cone.max(on_tube)
9682 });
9683 assert!(worst <= lin, "tilted tube: off by {worst:.2e}");
9684 }
9685
9686 let half_angle = 14.0_f64.atan2(10.0);
9687 let cone = ConicalSurface::new(
9688 Point3::new(0.0, 0.0, 273.2),
9689 Vec3::new(0.0, 0.0, -1.0),
9690 half_angle,
9691 )
9692 .unwrap();
9693 let cyl = CylindricalSurface::new(
9694 Point3::new(0.0, -50.0, 215.0),
9695 Vec3::new(0.0, 1.0, 0.0),
9696 60.0,
9697 )
9698 .unwrap();
9699 let curves = intersect_analytic_analytic_in_region(
9700 AnalyticSurface::Cone(&cone),
9701 AnalyticSurface::Cylinder(&cyl),
9702 32,
9703 Some((81.2 / half_angle.sin(), 95.2 / half_angle.sin())),
9704 Some((10.0, 90.0)),
9705 Aabb3 {
9706 min: Point3::new(-59.98, -40.0, 178.0),
9707 max: Point3::new(-47.23, 40.0, 192.0),
9708 },
9709 )
9710 .unwrap();
9711 assert_eq!(curves.len(), 2);
9712 let (sin, cos) = half_angle.sin_cos();
9713 for c in &curves {
9714 let worst = farthest_along(&c.curve, 4000, |p| {
9715 let on_cone = p.x().hypot(p.y()).madd(sin, -(273.2 - p.z()) * cos).abs();
9716 let on_cyl = (p.x().hypot(p.z() - 215.0) - 60.0).abs();
9717 on_cone.max(on_cyl)
9718 });
9719 assert!(worst <= lin, "band: off by {worst:.2e}");
9720 }
9721 }
9722
9723 #[test]
9732 fn a_seed_where_two_walls_pass_closest_starts_no_march() {
9733 let (pin, v_pin, _, rod) = taper_pin_and_rod(false, 0.9);
9734 let (a, b) = (AnalyticSurface::Cylinder(&rod), AnalyticSurface::Cone(&pin));
9735 let stalled = Point3::new(
9736 -2.503_835_657_485_280_5,
9737 -3.349_109_255_073_426,
9738 9.881_016_348_226_973,
9739 );
9740 let off_rod = |p: Point3| section_fit::Carrier::distance(&a, p).unwrap().0;
9741 let off_pin = |p: Point3| section_fit::Carrier::distance(&b, p).unwrap().0;
9742 assert!(off_rod(stalled).abs() > 0.8);
9743 let on = settle_on_section(&a, &b, stalled).unwrap();
9744 let (d_rod, d_pin) = (off_rod(on), off_pin(on));
9745 assert!(
9746 d_rod.abs() < 1e-12 && d_pin.abs() < 1e-12,
9747 "{d_rod:.1e}, {d_pin:.1e}"
9748 );
9749
9750 let curves = marched_sections(
9751 a,
9752 b,
9753 32,
9754 Some((0.0, 20.0)),
9755 Some(v_pin),
9756 Some(TAPER_PIN_REGION),
9757 )
9758 .unwrap();
9759 assert_eq!(curves.len(), 2);
9760 for c in &curves {
9761 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
9762 assert!((first - last).length() < 1e-9, "{first:?} to {last:?}");
9763 assert!(c.points.len() < 400, "{} points", c.points.len());
9764 }
9765
9766 let ball = SphericalSurface::new(Point3::new(3.0, 0.0, 0.0), 1.0).unwrap();
9768 let post =
9769 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9770 .unwrap();
9771 let gap = Point3::new(1.5, 0.0, 0.0);
9772 assert!(
9773 settle_on_section(
9774 &AnalyticSurface::Sphere(&ball),
9775 &AnalyticSurface::Cylinder(&post),
9776 gap
9777 )
9778 .is_none()
9779 );
9780 }
9781
9782 #[test]
9788 fn rods_that_only_touch_trace_no_section() {
9789 let wall =
9790 CylindricalSurface::new(Point3::new(1.1, 1.1, 1.2), Vec3::new(0.0, 0.0, 1.0), 2.55)
9791 .unwrap();
9792 let air =
9793 CylindricalSurface::new(Point3::new(-3.9, 1.1, 4.7), Vec3::new(0.0, 1.0, 0.0), 2.45)
9794 .unwrap();
9795 let (a, b) = (
9796 AnalyticSurface::Cylinder(&wall),
9797 AnalyticSurface::Cylinder(&air),
9798 );
9799 let touch = Point3::new(-1.45, 1.1, 4.7);
9800 assert!(!crosses_at(&a, &b, touch));
9801 let region = Aabb3 {
9802 min: Point3::new(-2.1625, 0.3875, 1.5375),
9803 max: Point3::new(-0.7375, 1.8125, 5.4125),
9804 };
9805 let curves = marched_sections(
9806 a,
9807 b,
9808 32,
9809 Some((1.05, 12.45)),
9810 Some((0.0, 30.9)),
9811 Some(region),
9812 )
9813 .unwrap();
9814 assert!(curves.is_empty(), "{} sections", curves.len());
9815 }
9816
9817 fn off_double_cone(cone: &ConicalSurface, p: Point3) -> f64 {
9820 let w = p - cone.apex();
9821 let h = cone.axis().dot(w);
9822 let rho = (w - cone.axis() * h).length();
9823 let (sin, cos) = cone.half_angle().sin_cos();
9824 rho.madd(sin, -h.abs() * cos).abs()
9825 }
9826
9827 #[test]
9834 fn negative_nappe_sections_are_marched_on_both_cones() {
9835 let up = Vec3::new(0.0, 0.0, 1.0);
9836 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
9837 .unwrap();
9838 let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
9839 let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
9840 for cone in [&wide, &narrow] {
9841 let (off, _) =
9842 section_fit::Carrier::distance(&AnalyticSurface::Cone(cone), shared).unwrap();
9843 assert!(off.abs() < 1e-12, "{off}");
9844 }
9845 let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
9846 let (v_wide, v_narrow) = ((-r1, -r1 / 3.0), (-r2, -r2 / 3.0));
9847 for wide_first in [true, false] {
9848 let (a, b, va, vb) = if wide_first {
9849 (
9850 AnalyticSurface::Cone(&wide),
9851 AnalyticSurface::Cone(&narrow),
9852 v_wide,
9853 v_narrow,
9854 )
9855 } else {
9856 (
9857 AnalyticSurface::Cone(&narrow),
9858 AnalyticSurface::Cone(&wide),
9859 v_narrow,
9860 v_wide,
9861 )
9862 };
9863 let curves = marched_sections(a, b, 32, Some(va), Some(vb), None).unwrap();
9864 assert!(!curves.is_empty(), "wide first {wide_first}: no section");
9865 for c in &curves {
9866 let worst = farthest_along(&c.curve, 4000, |p| {
9867 off_double_cone(&wide, p).max(off_double_cone(&narrow, p))
9868 });
9869 assert!(worst <= 1e-7, "wide first {wide_first}: off by {worst:.2e}");
9870 let below = farthest_along(&c.curve, 4000, |p| (p.z() + 1.0 / 3.0).max(0.0));
9871 assert!(
9872 below < 1e-9,
9873 "wide first {wide_first}: above z = -1/3 by {below:.2e}"
9874 );
9875 }
9876 }
9877 }
9878
9879 #[test]
9886 fn a_fit_along_a_negative_ruling_is_bounded() {
9887 let cone = ConicalSurface::new(
9888 Point3::new(0.0, 0.0, 0.0),
9889 Vec3::new(0.0, 0.0, 1.0),
9890 std::f64::consts::FRAC_PI_4,
9891 )
9892 .unwrap();
9893 let along = Vec3::new(1.0, 0.0, -1.0) * std::f64::consts::FRAC_1_SQRT_2;
9894 let rod = CylindricalSurface::new(Point3::new(0.0, 1.0, 0.0), along, 1.0).unwrap();
9895 let (a, b) = (
9896 AnalyticSurface::Cone(&cone),
9897 AnalyticSurface::Cylinder(&rod),
9898 );
9899 let ruling: Vec<Point3> = (1..=4)
9900 .map(|k| Point3::new(f64::from(k), 0.0, -f64::from(k)))
9901 .collect();
9902 let ctrl = [ruling[0], ruling[1], ruling[2], ruling[3]];
9903 let bound = section_fit::Carrier::bound(&a, &ctrl).unwrap();
9904 assert!(bound < 1e-12, "{bound:.2e}");
9905 let (curve, points) = fit_section(&a, &b, &ruling, 1e-7).unwrap();
9906 assert_eq!(points.len(), 4);
9907 let worst = farthest_along(&curve, 1000, |p| p.y().abs().max((p.x() + p.z()).abs()));
9908 assert!(worst < 1e-12, "{worst:.2e}");
9909 let through_apex = [
9910 Point3::new(-1.0, 0.0, 1.0),
9911 Point3::new(-1.0 / 3.0, 0.0, 1.0 / 3.0),
9912 Point3::new(1.0 / 3.0, 0.0, -1.0 / 3.0),
9913 Point3::new(1.0, 0.0, -1.0),
9914 ];
9915 assert!(section_fit::Carrier::bound(&a, &through_apex).is_none());
9916 }
9917
9918 #[test]
9927 fn a_touch_far_from_the_origin_settles_as_one_near_it_does() {
9928 for o in [
9929 Vec3::new(0.0, 0.0, 0.0),
9930 Vec3::new(1e6, 0.0, 0.0),
9931 Vec3::new(1e12, 0.0, 0.0),
9932 Vec3::new(0.0, 1e12, 0.0),
9933 Vec3::new(0.0, 0.0, 1e12),
9934 ] {
9935 let post = CylindricalSurface::new(
9936 Point3::new(0.0, 0.0, 0.0) + o,
9937 Vec3::new(0.0, 0.0, 1.0),
9938 1.0,
9939 )
9940 .unwrap();
9941 let beam = CylindricalSurface::new(
9942 Point3::new(3.0, 0.0, 0.0) + o,
9943 Vec3::new(0.0, 1.0, 0.0),
9944 2.0,
9945 )
9946 .unwrap();
9947 let (a, b) = (
9948 AnalyticSurface::Cylinder(&post),
9949 AnalyticSurface::Cylinder(&beam),
9950 );
9951 if o.length() == 0.0 {
9952 let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
9953 assert!(
9954 settled.is_none_or(|p| !crosses_at(&a, &b, p)),
9955 "settles on a crossing at {settled:?}"
9956 );
9957 }
9958 let region = Aabb3 {
9959 min: Point3::new(0.5, -0.5, -0.5) + o,
9960 max: Point3::new(1.5, 0.5, 0.5) + o,
9961 };
9962 let curves =
9963 marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some(region))
9964 .unwrap();
9965 assert!(curves.is_empty(), "moved {o:?}: {} sections", curves.len());
9966 }
9967 }
9968
9969 #[test]
9975 fn fits_on_slender_and_flat_cones_are_bounded() {
9976 use std::f64::consts::FRAC_PI_2;
9977 for half in [FRAC_PI_2 - 0.01, FRAC_PI_2 - 0.001, 0.01, 0.001] {
9978 let cone =
9979 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), half)
9980 .unwrap();
9981 let v = 10.0;
9982 let (rho, h) = (v * half.cos(), v * half.sin());
9983 let rod =
9984 CylindricalSurface::new(Point3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0), rho)
9985 .unwrap();
9986 let (a, b) = (
9987 AnalyticSurface::Cone(&cone),
9988 AnalyticSurface::Cylinder(&rod),
9989 );
9990 let circle: Vec<Point3> = (0..=12)
9991 .map(|k| {
9992 let t = TAU * f64::from(k) / 12.0;
9993 Point3::new(rho * t.cos(), rho * t.sin(), h)
9994 })
9995 .collect();
9996 let (curve, points) = fit_section(&a, &b, &circle, 1e-7).unwrap();
9997 let worst = farthest_along(&curve, 4000, |p| {
9998 off_double_cone(&cone, p).max((p.x().hypot(p.y()) - rho).abs())
9999 });
10000 assert!(worst <= 1e-7, "half {half}: off by {worst:.2e}");
10001 assert!(points.len() < 2000, "half {half}: {} points", points.len());
10002 }
10003 }
10004
10005 #[test]
10012 fn a_section_far_from_the_origin_is_traced_as_near_it() {
10013 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10014 let run = |o: Vec3| {
10015 let torus = ring.translated(o);
10016 let rod = CylindricalSurface::new(
10017 Point3::new(0.5, 0.0, 1.0) + o,
10018 Vec3::new(0.0, 1.0, 0.0),
10019 0.6,
10020 )
10021 .unwrap();
10022 let region = Aabb3 {
10023 min: Point3::new(-0.1, -5.5, 0.4) + o,
10024 max: Point3::new(1.1, 5.5, 1.5) + o,
10025 };
10026 intersect_analytic_analytic_in_region(
10027 AnalyticSurface::Cylinder(&rod),
10028 AnalyticSurface::Torus(&torus),
10029 32,
10030 Some((-10.0, 10.0)),
10031 None,
10032 region,
10033 )
10034 };
10035 for o in [
10036 Vec3::new(0.0, 0.0, 0.0),
10037 Vec3::new(1e6, 0.0, 0.0),
10038 Vec3::new(0.0, 1e6, 0.0),
10039 Vec3::new(0.0, 0.0, 1e6),
10040 ] {
10041 let curves = run(o).unwrap();
10042 assert_eq!(curves.len(), 2, "moved {o:?}");
10043 for c in &curves {
10044 let worst = farthest_along(&c.curve, 4000, |p| {
10045 let q = p - o;
10046 let on_torus = ((q.x().hypot(q.y()) - 4.0).hypot(q.z()) - 1.5).abs();
10047 let on_rod = ((q.x() - 0.5).hypot(q.z() - 1.0) - 0.6).abs();
10048 on_torus.max(on_rod)
10049 });
10050 assert!(worst <= 1e-7, "moved {o:?}: off by {worst:.2e}");
10051 }
10052 }
10053 for o in [
10054 Vec3::new(1e9, 0.0, 0.0),
10055 Vec3::new(0.0, 1e9, 0.0),
10056 Vec3::new(0.0, 0.0, 1e9),
10057 ] {
10058 assert!(
10059 matches!(run(o), Err(MathError::ConvergenceFailure { iterations: 0 })),
10060 "moved {o:?}: not refused before its fit"
10061 );
10062 }
10063 }
10064
10065 #[test]
10074 fn frames_far_along_a_rods_axis_read_as_near_ones() {
10075 let post =
10076 CylindricalSurface::new(Point3::new(0.0, 0.0, -1e6), Vec3::new(0.0, 0.0, 1.0), 1.0)
10077 .unwrap();
10078 let beam =
10079 CylindricalSurface::new(Point3::new(3.0, -1e6, 0.0), Vec3::new(0.0, 1.0, 0.0), 2.0)
10080 .unwrap();
10081 let (a, b) = (
10082 AnalyticSurface::Cylinder(&post),
10083 AnalyticSurface::Cylinder(&beam),
10084 );
10085 let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
10086 assert!(
10087 settled.is_none_or(|p| !crosses_at(&a, &b, p)),
10088 "settles on a crossing at {settled:?}"
10089 );
10090 let region = Aabb3 {
10091 min: Point3::new(0.5, -0.5, -0.5),
10092 max: Point3::new(1.5, 0.5, 0.5),
10093 };
10094 let far = Some((1e6 - 1.0, 1e6 + 1.0));
10095 let curves = marched_sections(a, b, 32, far, far, Some(region)).unwrap();
10096 assert!(curves.is_empty(), "{} sections", curves.len());
10097
10098 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10099 let boxes = |frame: f64| {
10100 let rod = CylindricalSurface::new(
10101 Point3::new(0.5, -frame, 1.0),
10102 Vec3::new(0.0, 1.0, 0.0),
10103 0.6,
10104 )
10105 .unwrap();
10106 let region = Aabb3 {
10107 min: Point3::new(-0.1, -5.5, 0.4),
10108 max: Point3::new(1.1, 5.5, 1.5),
10109 };
10110 let curves = intersect_analytic_analytic_in_region(
10111 AnalyticSurface::Cylinder(&rod),
10112 AnalyticSurface::Torus(&ring),
10113 32,
10114 Some((frame - 10.0, frame + 10.0)),
10115 None,
10116 region,
10117 )
10118 .unwrap();
10119 let mut boxes: Vec<Aabb3> = curves
10120 .iter()
10121 .map(|c| {
10122 let worst = farthest_along(&c.curve, 4000, |p| {
10123 let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10124 let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
10125 on_torus.max(on_rod)
10126 });
10127 assert!(worst <= 1e-7, "frame {frame}: off by {worst:.2e}");
10128 Aabb3::try_from_points(c.points.iter().map(|ip| ip.point)).unwrap()
10129 })
10130 .collect();
10131 boxes.sort_by(|p, q| p.min.y().total_cmp(&q.min.y()));
10132 boxes
10133 };
10134 let (near, far) = (boxes(0.0), boxes(1e6));
10135 assert_eq!(near.len(), 2);
10136 assert_eq!(far.len(), near.len());
10137 for (n, f) in near.iter().zip(&far) {
10138 assert!((n.min - f.min).length() < 1e-6 && (n.max - f.max).length() < 1e-6);
10139 }
10140 }
10141
10142 fn two_sum(a: f64, b: f64) -> (f64, f64) {
10144 let s = a + b;
10145 let back = s - a;
10146 (s, (a - (s - back)) + (b - back))
10147 }
10148
10149 fn two_prod(a: f64, b: f64) -> (f64, f64) {
10151 let split = |v: f64| {
10152 let c = 134_217_729.0 * v;
10153 let hi = c - (c - v);
10154 (hi, v - hi)
10155 };
10156 let p = a * b;
10157 let ((ah, al), (bh, bl)) = (split(a), split(b));
10158 (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl)
10159 }
10160
10161 fn off_line(o: Point3, a: Vec3, p: Point3) -> f64 {
10165 let w = [
10166 two_sum(p.x(), -o.x()),
10167 two_sum(p.y(), -o.y()),
10168 two_sum(p.z(), -o.z()),
10169 ];
10170 let a = [a.x(), a.y(), a.z()];
10171 let dot = |y: &[(f64, f64); 3]| {
10173 let (mut hi, mut lo) = (0.0, 0.0);
10174 for (ai, (yh, yl)) in a.iter().zip(y) {
10175 let (prod, prod_err) = two_prod(*ai, *yh);
10176 let (sum, sum_err) = two_sum(hi, prod);
10177 hi = sum;
10178 lo += sum_err + prod_err + ai * yl;
10179 }
10180 two_sum(hi, lo)
10181 };
10182 let (aw, aw_err) = dot(&w);
10183 let (aa, aa_err) = dot(&a.map(|x| (x, 0.0)));
10184 let s = aw / aa;
10187 let (sa, sa_err) = two_prod(s, aa);
10188 let rest = ((aw - sa) - sa_err) + aw_err - s * aa_err;
10189 let s_err = rest / aa;
10190 let across = a.iter().zip(w).map(|(ai, (hi, lo))| {
10191 let (prod, prod_err) = two_prod(*ai, s);
10192 let (diff, diff_err) = two_sum(hi, -prod);
10193 diff + (diff_err + lo - prod_err - ai * s_err)
10194 });
10195 across.map(|c| c * c).sum::<f64>().sqrt()
10196 }
10197
10198 #[test]
10206 fn a_tilted_rod_framed_far_along_its_axis_is_traced_on_it() {
10207 let along = Vec3::new(0.3, 0.4, 0.5);
10208 let through = Point3::new(4.0, 0.0, 0.0);
10209 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10210 let near_rod = CylindricalSurface::new(through, along, 0.6).unwrap();
10211 let axis = near_rod.axis();
10212 let far = through + axis * 1e12;
10213 let rod = CylindricalSurface::new(far, along, 0.6).unwrap();
10214 let anchor = Point3::new(4.0, 0.0, 0.0);
10215 let (moved, dv, error) = Moved::new(&AnalyticSurface::Cylinder(&rod), anchor);
10216 let AnalyticSurface::Cylinder(moved) = moved.surface() else {
10217 unreachable!("a rod moves to a rod");
10218 };
10219 let foot = moved.origin() + (anchor - Point3::new(0.0, 0.0, 0.0));
10220 let off = off_line(rod.origin(), rod.axis(), foot);
10221 assert!(
10222 off <= error && error < 1e-14,
10223 "the frame lies {off:.2e} off the axis"
10224 );
10225 assert!((dv + 1e12).abs() < 1.0, "v moved by {dv}");
10226
10227 let region = Aabb3 {
10228 min: Point3::new(2.0, -2.0, -2.0),
10229 max: Point3::new(6.0, 2.0, 2.0),
10230 };
10231 let sweep = (1e12 - 10.0, 1e12 + 10.0);
10232 let result = marched_sections(
10233 AnalyticSurface::Cylinder(&rod),
10234 AnalyticSurface::Torus(&ring),
10235 32,
10236 Some((-sweep.1, -sweep.0)),
10237 None,
10238 Some(region),
10239 );
10240 let curves = result.unwrap();
10241 assert_eq!(curves.len(), 2);
10242 {
10243 for c in &curves {
10244 let worst = farthest_along(&c.curve, 4000, |p| {
10245 let on_rod = (off_line(rod.origin(), rod.axis(), p) - 0.6).abs();
10246 let on_ring = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10247 on_rod.max(on_ring)
10248 });
10249 assert!(worst <= 1e-7, "off by {worst:.2e}");
10250 }
10251 }
10252 }
10253
10254 #[test]
10258 fn each_surface_bends_as_its_distance_does() {
10259 use section_fit::Carrier;
10260 let cyl =
10261 CylindricalSurface::new(Point3::new(0.3, -0.2, 0.5), Vec3::new(0.2, 0.3, 1.0), 0.7)
10262 .unwrap();
10263 let ball = SphericalSurface::new(Point3::new(-0.4, 0.1, 0.2), 1.3).unwrap();
10264 let cone = ConicalSurface::new(Point3::new(0.1, 0.2, -0.3), Vec3::new(-0.3, 0.1, 1.0), 0.6)
10265 .unwrap();
10266 let ring = ToroidalSurface::new(Point3::new(0.2, -0.1, 0.1), 2.0, 0.6).unwrap();
10267 let surfaces = [
10268 AnalyticSurface::Cylinder(&cyl),
10269 AnalyticSurface::Sphere(&ball),
10270 AnalyticSurface::Cone(&cone),
10271 AnalyticSurface::Torus(&ring),
10272 ];
10273 let directions = [
10274 Vec3::new(1.0, 0.0, 0.0),
10275 Vec3::new(0.0, 1.0, 0.0),
10276 Vec3::new(0.0, 0.0, 1.0),
10277 Vec3::new(0.6, -0.48, 0.64),
10278 ];
10279 let (_, _, _, cone_v) = surface_closures(&AnalyticSurface::Cone(&cone));
10280 for (k, s) in surfaces.iter().enumerate() {
10281 let (surf, norm, _, (v0, v1)) = surface_closures(s);
10282 let (v0, v1) = if matches!(s, AnalyticSurface::Cone(_)) {
10283 (cone_v.0.max(0.5), cone_v.1)
10284 } else {
10285 (v0, v1)
10286 };
10287 for (u, v) in [(0.3, 0.25), (1.9, 0.5), (4.4, 0.75)] {
10288 let v = (v1 - v0).madd(v, v0);
10289 for off in [0.0, 0.05, -0.05] {
10290 let p = surf(u, v) + norm(u, v) * off;
10291 let f = |q: Point3| s.distance(q).unwrap().0;
10292 for d in directions {
10293 let d = d * (1.0 / d.length());
10294 let h = 1e-4;
10295 let second = (f(p + d * h) - 2.0 * f(p) + f(p - d * h)) / (h * h);
10296 let exact = s.bend(p, d).unwrap();
10297 assert!(
10298 (second - exact).abs() <= 1e-5 * (1.0 + exact.abs()),
10299 "surface {k} at {p:?} along {d:?}: {exact} against {second}"
10300 );
10301 }
10302 }
10303 }
10304 }
10305 }
10306
10307 #[test]
10314 fn a_cone_reads_no_curvature_on_its_apex_plane() {
10315 use section_fit::Carrier;
10316 let axis = Vec3::new(0.0, 0.0, 1.0);
10317 let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), axis, 0.7).unwrap();
10318 let rod =
10319 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
10320 .unwrap();
10321 let (a, b) = (
10322 AnalyticSurface::Cone(&cone),
10323 AnalyticSurface::Cylinder(&rod),
10324 );
10325 let across = Vec3::new(1.0, 0.0, 0.0);
10326 for on in [
10327 Point3::new(2.0, 0.0, 0.0),
10328 Point3::new(2.0, 0.0, 1e-17),
10329 Point3::new(2.0, 0.0, -1e-17),
10330 ] {
10331 assert!(a.distance(on).is_some());
10332 assert!(a.bend(on, axis).is_none(), "{on:?} along the axis");
10333 assert!(a.bend(on, across).is_none(), "{on:?} across");
10334 assert!(station(&a, &b, on, axis).is_none(), "{on:?} station");
10335 assert!(singular_point(&a, &b, on, 1.0).is_none(), "{on:?} touch");
10336 }
10337 for off in [Point3::new(2.0, 0.0, 1e-3), Point3::new(2.0, 0.0, -1e-3)] {
10338 assert!(a.bend(off, axis).is_some(), "{off:?} along the axis");
10339 assert!(a.bend(off, across).is_some(), "{off:?} across");
10340 }
10341 }
10342
10343 fn three_poses() -> [crate::mat::Mat4; 3] {
10345 use crate::mat::Mat4;
10346 [
10347 Mat4::identity(),
10348 Mat4::translation(-3.7, 5.5, 14.0) * Mat4::rotation_z(0.7) * Mat4::rotation_x(-0.9),
10349 Mat4::scale(-1.0, 1.0, 1.0) * Mat4::rotation_y(0.4),
10350 ]
10351 }
10352
10353 fn posed_cone_and_rod(
10358 pose: &crate::mat::Mat4,
10359 half: f64,
10360 z0: f64,
10361 r: f64,
10362 n: u32,
10363 ) -> (ConicalSurface, CylindricalSurface, Vec<Point3>) {
10364 let o = Point3::new(0.0, 0.0, 0.0);
10365 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10366 let cone =
10367 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half).unwrap();
10368 let rod = CylindricalSurface::new(
10369 pose.mul_point(Point3::new(0.0, 0.0, z0)),
10370 along(Vec3::new(1.0, 0.0, 0.0)),
10371 r,
10372 )
10373 .unwrap();
10374 let mut truth = Vec::new();
10375 for k in 0..n {
10376 let phi = TAU * f64::from(k) / f64::from(n);
10377 let (y, z) = (r * phi.sin(), r.madd(-phi.cos(), z0));
10378 let rho = z.abs() / half.tan();
10379 let x2 = rho.madd(rho, -y * y);
10380 if x2 >= 0.0 {
10381 for x in [x2.sqrt(), -x2.sqrt()] {
10382 truth.push(pose.mul_point(Point3::new(x, y, z)));
10383 }
10384 }
10385 }
10386 (cone, rod, truth)
10387 }
10388
10389 #[test]
10401 fn thin_loops_on_flat_and_slender_cones_are_marched_round() {
10402 use std::f64::consts::FRAC_PI_2;
10403 let lin = Tolerance::new().linear;
10404 let cases = [
10405 (0.01, 0.1, 0.05),
10406 (FRAC_PI_2 - 0.01, 3.0, 0.05),
10407 (FRAC_PI_2 - 0.01, 10.0, 0.05),
10408 (FRAC_PI_2 - 0.01, 10.0, 0.2),
10409 ];
10410 for (half, z0, r) in cases {
10411 for (p, pose) in three_poses().iter().enumerate() {
10412 let (cone, rod, truth) = posed_cone_and_rod(pose, half, z0, r, 360);
10413 for cone_first in [true, false] {
10414 let label =
10415 format!("half {half} z0 {z0} r {r} pose {p} cone first {cone_first}");
10416 let (a, b, va, vb) = if cone_first {
10417 (
10418 AnalyticSurface::Cone(&cone),
10419 AnalyticSurface::Cylinder(&rod),
10420 (1.0, 20.0),
10421 (-20.0, 20.0),
10422 )
10423 } else {
10424 (
10425 AnalyticSurface::Cylinder(&rod),
10426 AnalyticSurface::Cone(&cone),
10427 (-20.0, 20.0),
10428 (1.0, 20.0),
10429 )
10430 };
10431 let result = marched_sections(a, b, 32, Some(va), Some(vb), None);
10432 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10433 let curves = result.unwrap();
10434 assert_eq!(curves.len(), 2, "{label}: loops");
10435 let off_rod = |p: Point3| {
10436 let (w, ax) = (p - rod.origin(), rod.axis());
10437 ((w - ax * ax.dot(w)).length() - r).abs()
10438 };
10439 for c in &curves {
10440 let worst = farthest_along(&c.curve, 4000, |p| {
10441 off_double_cone(&cone, p).max(off_rod(p))
10442 });
10443 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10444 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10445 assert!((first - last).length() < 1e-9, "{label}: open");
10446 }
10447 for &t in &truth {
10448 let near = curves
10449 .iter()
10450 .map(|c| {
10451 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10452 .unwrap()
10453 .distance
10454 })
10455 .fold(f64::INFINITY, f64::min);
10456 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10457 }
10458 }
10459 }
10460 }
10461 }
10462
10463 #[test]
10474 fn sections_on_both_nappes_of_a_flat_cone_are_each_marched() {
10475 let (half, r) = (0.001_f64, 0.05_f64);
10476 let lin = Tolerance::new().linear;
10477 let t2 = half.tan() * half.tan();
10478 for (k, pose) in three_poses().iter().enumerate() {
10479 let o = Point3::new(0.0, 0.0, 0.0);
10480 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10481 let cone =
10482 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10483 .unwrap();
10484 let rod =
10485 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10486 .unwrap();
10487 let mut truth = Vec::new();
10488 for j in 0..=90 {
10489 let x = 0.9 * (f64::from(j) / 45.0 - 1.0);
10490 let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10491 let y = z.madd(-z, r * r).sqrt();
10492 for (sy, sz) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
10493 truth.push(pose.mul_point(Point3::new(x, sy * y, sz * z)));
10494 }
10495 }
10496 let off_rod = |p: Point3| {
10497 let (w, ax) = (p - rod.origin(), rod.axis());
10498 ((w - ax * ax.dot(w)).length() - r).abs()
10499 };
10500 for cone_first in [true, false] {
10501 let label = format!("pose {k} cone first {cone_first}");
10502 let (a, b) = if cone_first {
10503 (
10504 AnalyticSurface::Cone(&cone),
10505 AnalyticSurface::Cylinder(&rod),
10506 )
10507 } else {
10508 (
10509 AnalyticSurface::Cylinder(&rod),
10510 AnalyticSurface::Cone(&cone),
10511 )
10512 };
10513 let result = marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), None);
10514 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10515 let curves = result.unwrap();
10516 assert_eq!(curves.len(), 4, "{label}: curves");
10517 for c in &curves {
10518 let worst = farthest_along(&c.curve, 4000, |p| {
10519 off_double_cone(&cone, p).max(off_rod(p))
10520 });
10521 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10522 }
10523 for &t in &truth {
10524 let near = curves
10525 .iter()
10526 .map(|c| {
10527 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10528 .unwrap()
10529 .distance
10530 })
10531 .fold(f64::INFINITY, f64::min);
10532 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10533 }
10534 }
10535 }
10536 }
10537
10538 #[test]
10547 fn a_shallow_crossing_too_tight_to_march_is_refused_not_dropped() {
10548 let (half, r) = (2e-6_f64, 0.1_f64);
10549 let t2 = half.tan() * half.tan();
10550 for (k, pose) in three_poses().iter().enumerate() {
10551 let o = Point3::new(0.0, 0.0, 0.0);
10552 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10553 let cone =
10554 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10555 .unwrap();
10556 let rod =
10557 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10558 .unwrap();
10559 let mut truth = Vec::new();
10560 for j in 0..=100 {
10561 let x = 40_000.0 + 99.9 * f64::from(j);
10562 let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10563 if z < r {
10564 let y = z.madd(-z, r * r).sqrt();
10565 for sy in [1.0, -1.0] {
10566 truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10567 }
10568 }
10569 }
10570 for cone_first in [true, false] {
10571 let label = format!("pose {k} cone first {cone_first}");
10572 let (a, b) = if cone_first {
10573 (
10574 AnalyticSurface::Cone(&cone),
10575 AnalyticSurface::Cylinder(&rod),
10576 )
10577 } else {
10578 (
10579 AnalyticSurface::Cylinder(&rod),
10580 AnalyticSurface::Cone(&cone),
10581 )
10582 };
10583 let range = Some((40_000.0, 60_000.0));
10584 let Ok(curves) = marched_sections(a, b, 32, range, range, None) else {
10585 continue;
10586 };
10587 for &t in &truth {
10588 let near = curves
10589 .iter()
10590 .map(|c| {
10591 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10592 .unwrap()
10593 .distance
10594 })
10595 .fold(f64::INFINITY, f64::min);
10596 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10597 }
10598 }
10599 }
10600 }
10601
10602 #[test]
10609 fn a_section_that_crosses_itself_is_traced_through_the_node() {
10610 let lin = Tolerance::new().linear;
10611 for (k, pose) in three_poses().iter().enumerate() {
10612 let o = Point3::new(0.0, 0.0, 0.0);
10613 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10614 let ball = SphericalSurface::new(pose.mul_point(o), 2.0).unwrap();
10615 let rod = CylindricalSurface::new(
10616 pose.mul_point(Point3::new(1.0, 0.0, 0.0)),
10617 along(Vec3::new(0.0, 0.0, 1.0)),
10618 1.0,
10619 )
10620 .unwrap();
10621 let node = pose.mul_point(Point3::new(2.0, 0.0, 0.0));
10622 let mut truth = Vec::new();
10623 for j in 1..360 {
10624 let t = TAU * f64::from(j) / 360.0;
10625 let z = 2.0 * (0.5 * t).sin().abs();
10626 for sz in [1.0, -1.0] {
10627 truth.push(pose.mul_point(Point3::new(1.0 + t.cos(), t.sin(), sz * z)));
10628 }
10629 }
10630 let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - 2.0).abs();
10631 let off_rod = |p: Point3| {
10632 let (w, ax) = (p - rod.origin(), rod.axis());
10633 ((w - ax * ax.dot(w)).length() - 1.0).abs()
10634 };
10635 for ball_first in [true, false] {
10636 let label = format!("pose {k} ball first {ball_first}");
10637 let (a, b, va, vb) = if ball_first {
10638 (
10639 AnalyticSurface::Sphere(&ball),
10640 AnalyticSurface::Cylinder(&rod),
10641 None,
10642 Some((-3.0, 3.0)),
10643 )
10644 } else {
10645 (
10646 AnalyticSurface::Cylinder(&rod),
10647 AnalyticSurface::Sphere(&ball),
10648 Some((-3.0, 3.0)),
10649 None,
10650 )
10651 };
10652 let result = marched_sections(a, b, 32, va, vb, None);
10653 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10654 let curves = result.unwrap();
10655 assert!(!curves.is_empty(), "{label}: no section");
10656 for c in &curves {
10657 let worst = farthest_along(&c.curve, 4000, |p| off_ball(p).max(off_rod(p)));
10658 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10659 let (t0, t1) = c.curve.domain();
10660 let (first, last) = (c.curve.evaluate(t0), c.curve.evaluate(t1));
10661 if (first - last).length() > lin {
10662 for end in [first, last] {
10663 let miss = (end - node).length();
10664 assert!(miss <= lin, "{label}: an end lies {miss:.1e} from the node");
10665 }
10666 }
10667 }
10668 for &t in &truth {
10669 let near = curves
10670 .iter()
10671 .map(|c| {
10672 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10673 .unwrap()
10674 .distance
10675 })
10676 .fold(f64::INFINITY, f64::min);
10677 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10678 }
10679 }
10680 }
10681 }
10682
10683 #[test]
10693 fn a_marched_branch_that_runs_into_a_touch_ends_on_it() {
10694 let lin = Tolerance::new().linear;
10695 for (k, pose) in three_poses().iter().enumerate() {
10696 let o = Point3::new(0.0, 0.0, 0.0);
10697 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10698 let leg =
10699 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 3.0)
10700 .unwrap();
10701 let bend = ToroidalSurface::with_axis(
10702 pose.mul_point(Point3::new(20.0, 0.0, 30.0)),
10703 20.0,
10704 3.0,
10705 along(Vec3::new(0.0, 1.0, 0.0)),
10706 )
10707 .unwrap();
10708 let touches = [
10709 pose.mul_point(Point3::new(0.0, 3.0, 30.0)),
10710 pose.mul_point(Point3::new(0.0, -3.0, 30.0)),
10711 ];
10712 let mut truth = Vec::new();
10713 for j in 1..=120 {
10714 let x = 3.0 * f64::from(j) / 120.0;
10715 let z = 30.0 - (80.0 * x).sqrt();
10716 let y = x.madd(-x, 9.0).max(0.0).sqrt();
10717 for sy in [1.0, -1.0] {
10718 truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10719 }
10720 }
10721 let back = pose.inverse().unwrap();
10722 let off_leg = |p: Point3| {
10723 let (w, ax) = (p - leg.origin(), leg.axis());
10724 ((w - ax * ax.dot(w)).length() - 3.0).abs()
10725 };
10726 let off_bend = |p: Point3| {
10727 let q = back.mul_point(p);
10728 (((q.x() - 20.0).hypot(q.z() - 30.0) - 20.0).hypot(q.y()) - 3.0).abs()
10729 };
10730 for leg_first in [true, false] {
10731 let label = format!("pose {k} leg first {leg_first}");
10732 let (a, b, va, vb) = if leg_first {
10733 (
10734 AnalyticSurface::Cylinder(&leg),
10735 AnalyticSurface::Torus(&bend),
10736 Some((0.0, 30.0)),
10737 None,
10738 )
10739 } else {
10740 (
10741 AnalyticSurface::Torus(&bend),
10742 AnalyticSurface::Cylinder(&leg),
10743 None,
10744 Some((0.0, 30.0)),
10745 )
10746 };
10747 let result = marched_sections(a, b, 32, va, vb, None);
10748 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10749 let curves = result.unwrap();
10750 assert_eq!(curves.len(), 1, "{label}: curves");
10751 let c = &curves[0];
10752 let worst = farthest_along(&c.curve, 4000, |p| off_leg(p).max(off_bend(p)));
10753 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10754 let (t0, t1) = c.curve.domain();
10755 for end in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
10756 let miss = touches
10757 .iter()
10758 .map(|&t| (end - t).length())
10759 .fold(f64::INFINITY, f64::min);
10760 assert!(
10761 miss <= 1e-5,
10762 "{label}: an end lies {miss:.1e} from the touch"
10763 );
10764 }
10765 for &t in &truth {
10766 let near = crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10767 .unwrap()
10768 .distance;
10769 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10770 }
10771 }
10772 }
10773 }
10774
10775 #[test]
10784 fn cells_centred_on_a_balls_centre_are_kept() {
10785 use std::f64::consts::FRAC_PI_4;
10786 let lin = Tolerance::new().linear;
10787 let (radius, h) = (0.1_f64, 0.1 * FRAC_PI_4.sin());
10788 let rho = 0.1 * FRAC_PI_4.cos();
10789 for (k, pose) in three_poses().iter().enumerate() {
10790 let o = Point3::new(0.0, 0.0, 0.0);
10791 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10792 let cone = ConicalSurface::new(
10793 pose.mul_point(o),
10794 along(Vec3::new(0.0, 0.0, 1.0)),
10795 FRAC_PI_4,
10796 )
10797 .unwrap();
10798 let ball = SphericalSurface::new(pose.mul_point(o), radius).unwrap();
10799 let mut truth = Vec::new();
10800 for j in 0..72 {
10801 let t = TAU * f64::from(j) / 72.0;
10802 for z in [h, -h] {
10803 truth.push(pose.mul_point(Point3::new(rho * t.cos(), rho * t.sin(), z)));
10804 }
10805 }
10806 let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - radius).abs();
10807 for cone_first in [true, false] {
10808 let label = format!("pose {k} cone first {cone_first}");
10809 let (a, b, va, vb) = if cone_first {
10810 (
10811 AnalyticSurface::Cone(&cone),
10812 AnalyticSurface::Sphere(&ball),
10813 Some((-0.5, 31.5)),
10814 None,
10815 )
10816 } else {
10817 (
10818 AnalyticSurface::Sphere(&ball),
10819 AnalyticSurface::Cone(&cone),
10820 None,
10821 Some((-0.5, 31.5)),
10822 )
10823 };
10824 let result = marched_sections(a, b, 32, va, vb, None);
10825 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10826 let curves = result.unwrap();
10827 assert_eq!(curves.len(), 2, "{label}: circles");
10828 for c in &curves {
10829 let worst = farthest_along(&c.curve, 4000, |p| {
10830 off_double_cone(&cone, p).max(off_ball(p))
10831 });
10832 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10833 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10834 assert!((first - last).length() < 1e-9, "{label}: open");
10835 }
10836 for &t in &truth {
10837 let near = curves
10838 .iter()
10839 .map(|c| {
10840 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10841 .unwrap()
10842 .distance
10843 })
10844 .fold(f64::INFINITY, f64::min);
10845 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10846 }
10847 }
10848 }
10849 }
10850
10851 #[test]
10860 fn a_crossing_on_a_nearly_flat_cone_is_traced_or_refused() {
10861 let lin = Tolerance::new().linear;
10862 for (k, pose) in three_poses().iter().enumerate() {
10863 let o = Point3::new(0.0, 0.0, 0.0);
10864 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10865 let cone =
10866 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 1e-14)
10867 .unwrap();
10868 let rod = CylindricalSurface::new(
10869 pose.mul_point(Point3::new(3.0, 0.0, 0.0)),
10870 along(Vec3::new(0.0, 0.0, 1.0)),
10871 1.0,
10872 )
10873 .unwrap();
10874 let truth: Vec<Point3> = (0..72)
10875 .map(|j| {
10876 let t = TAU * f64::from(j) / 72.0;
10877 let (x, y) = (3.0 + t.cos(), t.sin());
10878 pose.mul_point(Point3::new(x, y, 1e-14_f64.tan() * x.hypot(y)))
10879 })
10880 .collect();
10881 let off_rod = |p: Point3| {
10882 let (w, ax) = (p - rod.origin(), rod.axis());
10883 ((w - ax * ax.dot(w)).length() - 1.0).abs()
10884 };
10885 for cone_first in [true, false] {
10886 let label = format!("pose {k} cone first {cone_first}");
10887 let (a, b, va, vb) = if cone_first {
10888 (
10889 AnalyticSurface::Cone(&cone),
10890 AnalyticSurface::Cylinder(&rod),
10891 Some((1.0, 5.0)),
10892 Some((-1.0, 1.0)),
10893 )
10894 } else {
10895 (
10896 AnalyticSurface::Cylinder(&rod),
10897 AnalyticSurface::Cone(&cone),
10898 Some((-1.0, 1.0)),
10899 Some((1.0, 5.0)),
10900 )
10901 };
10902 let Ok(curves) = marched_sections(a, b, 32, va, vb, None) else {
10903 continue;
10904 };
10905 assert!(!curves.is_empty(), "{label}: no section and no refusal");
10906 for c in &curves {
10907 let worst = farthest_along(&c.curve, 4000, |p| {
10908 off_double_cone(&cone, p).max(off_rod(p))
10909 });
10910 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10911 }
10912 for &t in &truth {
10913 let near = curves
10914 .iter()
10915 .map(|c| {
10916 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10917 .unwrap()
10918 .distance
10919 })
10920 .fold(f64::INFINITY, f64::min);
10921 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10922 }
10923 }
10924 }
10925 }
10926
10927 #[test]
10942 fn two_loops_in_one_cell_of_each_patch_are_both_traced() {
10943 let lin = Tolerance::new().linear;
10944 let turn = crate::mat::Mat4::rotation_z(0.75 * TAU / 32.0);
10945 let (delta, depth) = (0.007_f64, 8e-6_f64);
10946 let (y0, z0) = (4.0 - delta, 2.1 - depth);
10947 for (k, pose) in three_poses().iter().enumerate() {
10948 let pose = *pose * turn;
10949 let o = Point3::new(0.0, 0.0, 0.0);
10950 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10951 let centre = pose.mul_point(o);
10952 let up = along(Vec3::new(0.0, 0.0, 1.0));
10953 let ring = ToroidalSurface::with_axis(centre, 4.0, 1.5, up).unwrap();
10954 let start = pose.mul_point(Point3::new(0.0, y0, z0));
10955 let dir = along(Vec3::new(1.0, 0.0, 0.0));
10956 let rod = CylindricalSurface::new(start, dir, 0.6).unwrap();
10957 let ring_normal = |p: Point3| {
10958 let w = p - centre;
10959 let across = w - up * up.dot(w);
10960 let tube = centre + across * (4.0 / across.length());
10961 (p - tube) * (1.0 / (p - tube).length())
10962 };
10963 let rod_normal = |p: Point3| {
10964 let w = p - start;
10965 let across = w - dir * dir.dot(w);
10966 across * (1.0 / across.length())
10967 };
10968 let off_ring = |p: Point3| {
10969 let w = p - centre;
10970 let h = up.dot(w);
10971 ((w - up * h).length() - 4.0).hypot(h) - 1.5
10972 };
10973 let off_rod = |p: Point3| {
10974 let w = p - start;
10975 ((w - dir * dir.dot(w)).length() - 0.6).abs()
10976 };
10977 let mut truth = Vec::new();
10980 for j in -300..=300 {
10981 let phi = f64::from(j) * 1e-4;
10982 let from =
10983 pose.mul_point(Point3::new(0.0, y0 + 0.6 * phi.sin(), z0 - 0.6 * phi.cos()));
10984 for t in intersect_line_torus(&ring, from, dir) {
10985 if t.abs() < 2.0 {
10986 truth.push(from + dir * t);
10987 }
10988 }
10989 }
10990 assert!(truth.len() > 100, "pose {k}: {} points", truth.len());
10991 for rod_first in [true, false] {
10992 let label = format!("pose {k} rod first {rod_first}");
10993 let along_rod = Some((-9.6875, 10.3125));
10994 let result = if rod_first {
10995 marched_sections(
10996 AnalyticSurface::Cylinder(&rod),
10997 AnalyticSurface::Torus(&ring),
10998 32,
10999 along_rod,
11000 None,
11001 None,
11002 )
11003 } else {
11004 marched_sections(
11005 AnalyticSurface::Torus(&ring),
11006 AnalyticSurface::Cylinder(&rod),
11007 32,
11008 None,
11009 along_rod,
11010 None,
11011 )
11012 };
11013 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
11014 let curves = result.unwrap();
11015 assert_eq!(curves.len(), 2, "{label}: loops");
11016 for c in &curves {
11017 let worst =
11018 farthest_along(&c.curve, 4000, |p| off_ring(p).abs().max(off_rod(p)));
11019 assert!(worst <= lin, "{label}: off by {worst:.2e}");
11020 }
11021 for &t in &truth {
11022 let sin = ring_normal(t).cross(rod_normal(t)).length();
11023 let bound = (4.0 * lin / sin).max(1e-5);
11024 let near = curves
11025 .iter()
11026 .map(|c| {
11027 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
11028 .unwrap()
11029 .distance
11030 })
11031 .fold(f64::INFINITY, f64::min);
11032 assert!(
11033 near <= bound,
11034 "{label}: {t:?} lies {near:.1e} off, past {bound:.1e}"
11035 );
11036 }
11037 }
11038 }
11039 }
11040}