1use std::f64::consts::{FRAC_PI_2, TAU};
8
9use crate::MathError;
10use crate::aabb::Aabb3;
11use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
12use crate::frame::Frame3;
13use crate::nurbs::curve::NurbsCurve;
14use crate::nurbs::fitting::interpolate;
15use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
16use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
17use crate::tolerance::Tolerance;
18use crate::vec::{Point3, Vec3};
19
20#[derive(Debug, Clone)]
22pub enum ExactIntersectionCurve {
23 Circle(Circle3D),
25 Ellipse(Ellipse3D),
27 Points(Vec<Point3>),
29}
30
31#[derive(Debug, Clone)]
33#[non_exhaustive]
34pub enum PlaneSection {
35 Circle(Circle3D),
37 Ellipse(Ellipse3D),
39 Line {
43 line: Line3D,
45 ray: bool,
47 },
48 Point(Point3),
50 Points(Vec<Point3>),
52 Parabola(Parabola3D),
54 Hyperbola(Hyperbola3D),
57}
58
59impl From<ExactIntersectionCurve> for PlaneSection {
60 fn from(curve: ExactIntersectionCurve) -> Self {
61 match curve {
62 ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
63 ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
64 ExactIntersectionCurve::Points(points) => Self::Points(points),
65 }
66 }
67}
68
69pub fn exact_plane_section(
84 surface: AnalyticSurface<'_>,
85 normal: Vec3,
86 d: f64,
87) -> Result<Vec<PlaneSection>, MathError> {
88 match surface {
89 AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
90 return plane_cylinder_rulings(cyl, normal, d);
91 }
92 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
93 return plane_cone_apex_rulings(cone, normal);
94 }
95 AnalyticSurface::Cone(cone) => {
96 if let Some(open) = plane_cone_open_section(cone, normal, d)? {
97 return Ok(open);
98 }
99 }
100 AnalyticSurface::Sphere(sphere) => {
101 let h = dot_np(normal, sphere.center()) - d;
102 let r = sphere.radius();
103 if (r - h.abs()).abs() <= TOUCH * r {
104 return Ok(vec![PlaneSection::Point(Point3::new(
105 h.mul_add(-normal.x(), sphere.center().x()),
106 h.mul_add(-normal.y(), sphere.center().y()),
107 h.mul_add(-normal.z(), sphere.center().z()),
108 ))]);
109 }
110 }
111 AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
112 }
113 Ok(exact_plane_analytic(surface, normal, d)?
114 .into_iter()
115 .map(PlaneSection::from)
116 .collect())
117}
118
119const PARABOLIC: f64 = 1e-12;
122
123const HYPERBOLIC: f64 = 1e-6;
127
128#[allow(clippy::many_single_char_names)]
135fn plane_cone_open_section(
136 cone: &ConicalSurface,
137 normal: Vec3,
138 d: f64,
139) -> Result<Option<Vec<PlaneSection>>, MathError> {
140 let axis = cone.axis();
141 let c = normal.dot(axis);
142 let p2 = c.mul_add(-c, 1.0).max(0.0);
143 let p = p2.sqrt();
144 let rise = cone.half_angle().sin();
145 let k = rise * rise;
146 let a_coeff = p2 - k;
147 let eccentric = a_coeff / k;
148 let m = axis - normal * c;
149 let m_len = m.length();
150 if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
151 {
152 return Ok(None);
153 }
154 let e1 = m * (1.0 / m_len);
155 let e2 = normal.cross(e1);
156 let apex = cone.apex();
157 let e = d - dot_np(normal, apex);
158 let origin = apex + normal * e;
159 let real = |s: f64| e.mul_add(c, s * p) >= 0.0;
162 let holds = |q: Point3| {
165 let w = q - apex;
166 let reach = w.length();
167 reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
168 };
169 if eccentric <= PARABOLIC {
170 let ecp = e * c * p;
173 let vertex_s = -e * (c * c - k) / (2.0 * c * p);
174 let focal = ecp.abs() / (2.0 * k);
175 if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
176 return Ok(None);
177 }
178 if !real(vertex_s) {
179 return Ok(Some(Vec::new()));
180 }
181 let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
182 if ![0.0, focal, -focal]
183 .iter()
184 .all(|&t| holds(parabola.evaluate(t)))
185 {
186 return Ok(None);
187 }
188 return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
189 }
190 let centre_s = -e * c * p / a_coeff;
193 let rhs = e * e * k * (1.0 - k) / a_coeff;
194 let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
195 if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
196 return Ok(None);
197 }
198 let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
199 let hyperbola = Hyperbola3D::with_axes(
200 origin + e1 * centre_s,
201 real_axis,
202 imaginary_axis,
203 toward,
204 e2,
205 )?;
206 if ![0.0, 1.0, -1.0]
207 .iter()
208 .all(|&t| holds(hyperbola.evaluate(t)))
209 {
210 return Ok(None);
211 }
212 Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
213}
214
215const TOUCH: f64 = 4.0 * f64::EPSILON;
218
219fn plane_cylinder_rulings(
222 cyl: &CylindricalSurface,
223 normal: Vec3,
224 d: f64,
225) -> Result<Vec<PlaneSection>, MathError> {
226 let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
229 let amp = a.hypot(b);
230 if amp < 1e-12 {
231 return Ok(vec![]);
232 }
233 let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
234 if ratio.abs() > 1.0 + TOUCH {
235 return Ok(vec![]);
236 }
237 let phi = b.atan2(a);
238 let spread = ratio.clamp(-1.0, 1.0).acos();
239 let at = if ratio.abs() >= 1.0 - TOUCH {
240 vec![phi + spread]
241 } else {
242 vec![phi + spread, phi - spread]
243 };
244 at.into_iter()
245 .map(|u| {
246 Ok(PlaneSection::Line {
247 line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
248 ray: false,
249 })
250 })
251 .collect()
252}
253
254fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
256 let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
257 (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
258}
259
260fn plane_cone_apex_rulings(
264 cone: &ConicalSurface,
265 normal: Vec3,
266) -> Result<Vec<PlaneSection>, MathError> {
267 let (sin_a, cos_a) = cone.half_angle().sin_cos();
270 let a = cos_a * normal.dot(cone.x_axis());
271 let b = cos_a * normal.dot(cone.y_axis());
272 let c = sin_a * normal.dot(cone.axis());
273 let amp = a.hypot(b);
274 let apex = cone.apex();
275 if amp < 1e-12 * c.abs().max(1.0) {
276 return Ok(vec![PlaneSection::Point(apex)]);
277 }
278 let ratio = -c / amp;
279 if ratio.abs() > 1.0 + TOUCH {
280 return Ok(vec![PlaneSection::Point(apex)]);
281 }
282 let phi = b.atan2(a);
283 let spread = ratio.clamp(-1.0, 1.0).acos();
284 let at = if ratio.abs() >= 1.0 - TOUCH {
285 vec![phi + spread]
286 } else {
287 vec![phi + spread, phi - spread]
288 };
289 at.into_iter()
290 .map(|u| {
291 Ok(PlaneSection::Line {
292 line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
293 ray: true,
294 })
295 })
296 .collect()
297}
298
299pub fn exact_plane_analytic(
314 surface: AnalyticSurface<'_>,
315 plane_normal: Vec3,
316 plane_d: f64,
317) -> Result<Vec<ExactIntersectionCurve>, MathError> {
318 exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
319}
320
321pub fn exact_plane_analytic_reaching(
329 surface: AnalyticSurface<'_>,
330 plane_normal: Vec3,
331 plane_d: f64,
332 reach: f64,
333) -> Result<Vec<ExactIntersectionCurve>, MathError> {
334 match surface {
335 AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
336 AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
337 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
338 AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
339 AnalyticSurface::Torus(torus) => {
340 if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
341 return Ok(circles);
342 }
343 if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
344 return Ok(loops
345 .into_iter()
346 .map(ExactIntersectionCurve::Points)
347 .collect());
348 }
349 let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
351 Ok(chains
352 .into_iter()
353 .map(ExactIntersectionCurve::Points)
354 .collect())
355 }
356 }
357}
358
359fn exact_plane_torus(
373 torus: &ToroidalSurface,
374 normal: Vec3,
375 d: f64,
376) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
377 let len = normal.length();
378 let n = normal.normalize()?;
379 let d = d / len;
380 let axis = torus.z_axis();
381 let center = torus.center();
382 let (big, small) = (torus.major_radius(), torus.minor_radius());
383 let height = d - dot_np(n, center);
384 let along = n.dot(axis);
385 if along.abs() > 1.0 - 1e-10 {
386 if height.abs() >= small - 1e-10 * small {
387 if height.abs() > small + 1e-10 * small {
388 return Ok(Some(Vec::new()));
389 }
390 if big <= 1e-10 * small
397 || axis.cross(n).length() > 1e-12
398 || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
399 {
400 return Ok(None);
401 }
402 let middle = center + n * height;
403 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
404 middle, n, big,
405 )?)]));
406 }
407 let reach = small.mul_add(small, -(height * height)).sqrt();
408 if big - reach <= 1e-10 * big {
409 return Ok(None);
410 }
411 let middle = center + n * height;
412 return Ok(Some(vec![
413 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
414 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
415 ]));
416 }
417 if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
418 let out = axis.cross(n).normalize()?;
419 return Ok(Some(vec![
420 ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
421 ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
422 ]));
423 }
424 Ok(None)
425}
426
427fn exact_plane_cylinder(
433 cyl: &CylindricalSurface,
434 normal: Vec3,
435 d: f64,
436) -> Result<Vec<ExactIntersectionCurve>, MathError> {
437 let axis = cyl.axis();
438 let cos_theta = normal.dot(axis).abs();
439 let r = cyl.radius();
440
441 if cos_theta < 1e-10 {
442 return Ok(vec![]);
445 }
446
447 let n_dot_axis = normal.dot(axis);
450 let n_dot_origin = dot_np(normal, cyl.origin());
451 let t = (d - n_dot_origin) / n_dot_axis;
452 let center_on_axis = Point3::new(
453 cyl.origin().x() + t * axis.x(),
454 cyl.origin().y() + t * axis.y(),
455 cyl.origin().z() + t * axis.z(),
456 );
457
458 if cos_theta > 1.0 - 1e-10 {
459 let circle = Circle3D::new(center_on_axis, normal, r)?;
461 Ok(vec![ExactIntersectionCurve::Circle(circle)])
462 } else {
463 let semi_minor = r;
467 let semi_major = r / cos_theta;
468
469 let axis_proj = Vec3::new(
473 axis.x() - n_dot_axis * normal.x(),
474 axis.y() - n_dot_axis * normal.y(),
475 axis.z() - n_dot_axis * normal.z(),
476 );
477 let u_axis = axis_proj.normalize()?;
478 let v_axis = normal.cross(u_axis);
479
480 let ellipse = Ellipse3D::with_axes(
481 center_on_axis,
482 normal,
483 semi_major,
484 semi_minor,
485 u_axis,
486 v_axis,
487 )?;
488 Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
489 }
490}
491
492fn exact_plane_sphere(
496 sphere: &SphericalSurface,
497 normal: Vec3,
498 d: f64,
499) -> Result<Vec<ExactIntersectionCurve>, MathError> {
500 let h = dot_np(normal, sphere.center()) - d;
501 let r = sphere.radius();
502
503 if r - h.abs() <= TOUCH * r {
506 return Ok(vec![]);
507 }
508
509 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
510 let circle_center = Point3::new(
511 h.mul_add(-normal.x(), sphere.center().x()),
512 h.mul_add(-normal.y(), sphere.center().y()),
513 h.mul_add(-normal.z(), sphere.center().z()),
514 );
515
516 let circle = Circle3D::new(circle_center, normal, circle_r)?;
517 Ok(vec![ExactIntersectionCurve::Circle(circle)])
518}
519
520pub fn exact_sphere_sphere(
532 s1: &SphericalSurface,
533 s2: &SphericalSurface,
534) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
535 let delta = s2.center() - s1.center();
536 let d = delta.length();
537 let (r1, r2) = (s1.radius(), s2.radius());
538 let scale = r1.max(r2);
539 if d <= 1e-12 * scale {
540 return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
542 }
543 let normal = delta * (1.0 / d);
544 let (centre, toward, r_small, r_big) = if r1 <= r2 {
547 (s1.center(), normal, r1, r2)
548 } else {
549 (s2.center(), -normal, r2, r1)
550 };
551 let along = d.mul_add(d, r_small.mul_add(r_small, -(r_big * r_big))) / (2.0 * d);
552 if along.abs() > r_small - 1e-10 * scale.max(1.0) {
553 return Ok(Some(Vec::new()));
554 }
555 let radius = r_small.mul_add(r_small, -(along * along)).sqrt();
556 let circle = Circle3D::new(centre + toward * along, normal, radius)?;
557 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
558}
559
560fn exact_plane_cone(
569 cone: &ConicalSurface,
570 normal: Vec3,
571 d: f64,
572 reach: f64,
573) -> Result<Vec<ExactIntersectionCurve>, MathError> {
574 let axis = cone.axis();
575 let cos_theta = normal.dot(axis).abs();
576 let half_angle = cone.half_angle();
577
578 if cos_theta > 1.0 - 1e-10 {
579 let n_dot_axis = normal.dot(axis);
582 let n_dot_apex = dot_np(normal, cone.apex());
583 let t = (d - n_dot_apex) / n_dot_axis;
584
585 if t.abs() < 1e-10 {
590 return Ok(vec![]);
591 }
592
593 let center = Point3::new(
594 cone.apex().x() + t * axis.x(),
595 cone.apex().y() + t * axis.y(),
596 cone.apex().z() + t * axis.z(),
597 );
598 let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
602 if circle_r < 1e-15 {
603 return Ok(vec![]);
604 }
605
606 let circle = Circle3D::new(center, normal, circle_r)?;
607 return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
608 }
609
610 let c = normal.dot(axis);
622 let p2 = (1.0 - c * c).max(0.0);
623 let p = p2.sqrt();
624 let k = half_angle.sin().powi(2);
625 let a_coeff = p2 - k;
626
627 let m = Vec3::new(
629 axis.x() - c * normal.x(),
630 axis.y() - c * normal.y(),
631 axis.z() - c * normal.z(),
632 );
633 let m_len = m.length();
634 if m_len < 1e-12 {
635 let chains = sample_plane_cone(cone, normal, d, reach)?;
638 return Ok(chains
639 .into_iter()
640 .map(ExactIntersectionCurve::Points)
641 .collect());
642 }
643 let e1 = m * (1.0 / m_len);
644 let e2 = normal.cross(e1);
645 let apex = cone.apex();
646 let e = d - dot_np(normal, apex);
647
648 if a_coeff < -1e-9 {
651 let abs_a = -a_coeff; if e * c < 0.0 {
658 return Ok(vec![]);
659 }
660 let s_c = e * c * p / abs_a;
663 let rhs = e * e * k * (1.0 - k) / abs_a;
664 if rhs <= 0.0 {
665 return Ok(vec![]);
666 }
667 let semi_s = (rhs / abs_a).sqrt(); let semi_t = (rhs / k).sqrt(); if semi_s < 1e-12 || semi_t < 1e-12 {
670 return Ok(vec![]);
671 }
672 let center = apex + normal * e + e1 * s_c;
673 let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
674 (semi_s, semi_t, e1, e2)
675 } else {
676 (semi_t, semi_s, e2, e1)
677 };
678 let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
679 return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
680 }
681
682 let chains = sample_plane_cone(cone, normal, d, reach)?;
685 Ok(chains
686 .into_iter()
687 .map(ExactIntersectionCurve::Points)
688 .collect())
689}
690
691#[allow(clippy::many_single_char_names)]
706pub fn plane_cone_conic_arc(
707 cone: &ConicalSurface,
708 normal: Vec3,
709 d: f64,
710 from: Point3,
711 to: Point3,
712) -> Result<Option<NurbsCurve>, MathError> {
713 let len = normal.length();
714 if len < 1e-15 {
715 return Err(MathError::ZeroVector);
716 }
717 let (normal, d) = (normal * (1.0 / len), d / len);
718 let axis = cone.axis();
719 let c = normal.dot(axis);
720 let p2 = (1.0 - c * c).max(0.0);
721 let p = p2.sqrt();
722 let k = cone.half_angle().sin().powi(2);
723 let a_coeff = p2 - k;
724 let m = Vec3::new(
725 axis.x() - c * normal.x(),
726 axis.y() - c * normal.y(),
727 axis.z() - c * normal.z(),
728 );
729 let m_len = m.length();
730 if m_len < 1e-12 || a_coeff < -1e-9 {
731 return Ok(None);
732 }
733 let e1 = m * (1.0 / m_len);
734 let e2 = normal.cross(e1);
735 let apex = cone.apex();
736 let e = d - dot_np(normal, apex);
737 let origin = apex + normal * e;
738 let plane_st = |q: Point3| {
739 let w = q - origin;
740 (w.dot(e1), w.dot(e2))
741 };
742 let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
743 let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
744 if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
745 return Ok(None);
746 }
747 let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
748 let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
749 let (control, weights) = if a_coeff.abs() <= 1e-9 {
750 let lin = 2.0 * e * c * p;
752 if lin.abs() < 1e-12 * scale {
753 return Ok(None);
754 }
755 let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
756 if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
757 || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
758 {
759 return Ok(None);
760 }
761 let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
762 (vec![from, mid, to], vec![1.0; 3])
763 } else {
764 let s_c = -e * c * p / a_coeff;
766 let r = e * e * k * (1.0 - k) / a_coeff;
767 if r <= 0.0 {
768 return Ok(None);
769 }
770 let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
771 let (x0, x1) = (s0 - s_c, s1 - s_c);
772 if x0 * x1 <= 0.0 {
773 return Ok(None);
774 }
775 let side = x0.signum();
776 let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
777 let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
778 if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
779 return Ok(None);
780 }
781 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
782 let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
783 let mut control = vec![from];
784 let mut weights = vec![1.0];
785 for i in 0..pieces {
786 #[allow(clippy::cast_precision_loss)]
787 let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
788 let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
789 let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
790 let w = half.cosh();
791 control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
792 weights.push(w);
793 control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
794 weights.push(1.0);
795 }
796 (control, weights)
797 };
798 let pieces = (control.len() - 1) / 2;
799 let mut knots = vec![0.0; 3];
800 for i in 1..pieces {
801 #[allow(clippy::cast_precision_loss)]
802 knots.extend([i as f64; 2]);
803 }
804 #[allow(clippy::cast_precision_loss)]
805 knots.extend([pieces as f64; 3]);
806 let curve = NurbsCurve::new(2, knots, control, weights)?;
807 let (sin_a, cos_a) = cone.half_angle().sin_cos();
812 let off_cone = |q: Point3| {
813 let w = q - apex;
814 let h = w.dot(axis);
815 (w - axis * h)
816 .length()
817 .mul_add(sin_a, -(h.abs() * cos_a))
818 .abs()
819 };
820 for i in 0..pieces {
821 for f in [0.25, 0.5, 0.75] {
822 #[allow(clippy::cast_precision_loss)]
823 if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
824 return Ok(None);
825 }
826 }
827 }
828 Ok(Some(curve))
829}
830
831#[derive(Clone, Copy)]
833pub enum AnalyticSurface<'a> {
834 Cylinder(&'a CylindricalSurface),
836 Cone(&'a ConicalSurface),
838 Sphere(&'a SphericalSurface),
840 Torus(&'a ToroidalSurface),
842}
843
844fn dot_np(n: Vec3, p: Point3) -> f64 {
846 n.dot(Vec3::new(p.x(), p.y(), p.z()))
847}
848
849pub fn intersect_plane_analytic(
857 surface: AnalyticSurface<'_>,
858 normal: Vec3,
859 d: f64,
860) -> Result<Vec<IntersectionCurve>, MathError> {
861 match surface {
862 AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
863 AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
864 AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
865 AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
866 }
867}
868
869pub fn sample_plane_analytic(
880 surface: AnalyticSurface<'_>,
881 normal: Vec3,
882 d: f64,
883) -> Result<Vec<Vec<Point3>>, MathError> {
884 match surface {
885 AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
886 AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
887 AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
888 AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
889 }
890}
891
892#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
894fn sample_plane_cylinder(
895 cyl: &CylindricalSurface,
896 normal: Vec3,
897 d: f64,
898) -> Result<Vec<Vec<Point3>>, MathError> {
899 let n_samples = 64_usize;
900 let mut points = Vec::with_capacity(n_samples + 1);
901
902 for i in 0..=n_samples {
903 let u = TAU * (i as f64) / (n_samples as f64);
904 let base = cyl.evaluate(u, 0.0);
905 let n_dot_axis = normal.dot(cyl.axis());
906 let n_dot_base = dot_np(normal, base);
907
908 if n_dot_axis.abs() < 1e-12 {
909 if (n_dot_base - d).abs() < 1e-6 {
910 points.push(base);
911 }
912 } else {
913 let v = (d - n_dot_base) / n_dot_axis;
914 if v.abs() <= 100.0 {
915 points.push(cyl.evaluate(u, v));
916 }
917 }
918 }
919
920 if points.len() < 2 {
921 Ok(vec![])
922 } else {
923 Ok(vec![points])
924 }
925}
926
927#[allow(clippy::cast_precision_loss)]
929fn sample_plane_sphere(
930 sphere: &SphericalSurface,
931 normal: Vec3,
932 d: f64,
933) -> Result<Vec<Vec<Point3>>, MathError> {
934 let h = dot_np(normal, sphere.center()) - d;
935 let r = sphere.radius();
936
937 if h.abs() > r - 1e-10 {
938 return Ok(vec![]);
939 }
940
941 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
942 let circle_center = Point3::new(
943 h.mul_add(-normal.x(), sphere.center().x()),
944 h.mul_add(-normal.y(), sphere.center().y()),
945 h.mul_add(-normal.z(), sphere.center().z()),
946 );
947
948 let basis = Frame3::from_normal(circle_center, normal)?;
949 let u_dir = basis.x;
950 let v_dir = basis.y;
951
952 let n_samples = 64_usize;
953 let mut points = Vec::with_capacity(n_samples + 1);
954
955 for i in 0..=n_samples {
956 let theta = TAU * (i as f64) / (n_samples as f64);
957 let (sin_t, cos_t) = theta.sin_cos();
958 points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
959 }
960
961 Ok(vec![points])
962}
963
964#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
976fn sample_plane_cone(
977 cone: &ConicalSurface,
978 normal: Vec3,
979 d: f64,
980 reach: f64,
981) -> Result<Vec<Vec<Point3>>, MathError> {
982 let apex = cone.apex();
983 let n_dot_apex = dot_np(normal, apex);
984 let e = d - n_dot_apex;
985
986 let n_samples = 512_usize;
990 let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
991 let mut v_min = f64::INFINITY;
992 for i in 0..n_samples {
993 let u = TAU * (i as f64) / (n_samples as f64);
994 let g = cone.evaluate(u, 1.0) - apex;
995 let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
996 if n_dot_g.abs() < 1e-12 {
997 vs.push(None);
998 continue;
999 }
1000 let v = e / n_dot_g;
1001 if v >= -1e-12 {
1002 let v = v.max(0.0);
1003 v_min = v_min.min(v);
1004 vs.push(Some(v));
1005 } else {
1006 vs.push(None);
1007 }
1008 }
1009
1010 if !v_min.is_finite() {
1011 return Ok(Vec::new());
1012 }
1013
1014 let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1023
1024 let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1027
1028 let point_at = |u: f64, v: f64| -> Point3 {
1029 let g = cone.evaluate(u, 1.0) - apex;
1030 apex + g * v
1031 };
1032 #[allow(clippy::cast_precision_loss)]
1033 let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1034 let n_dot_g_at = |u: f64| -> f64 {
1035 let g = cone.evaluate(u, 1.0) - apex;
1036 normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1037 };
1038
1039 if kept.iter().all(Option::is_some) {
1040 let mut pts: Vec<Point3> = kept
1042 .iter()
1043 .enumerate()
1044 .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1045 .collect();
1046 if let Some(&first) = pts.first() {
1047 pts.push(first);
1048 }
1049 return Ok(vec![pts]);
1050 }
1051
1052 let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1061 let Some(v_end) = kept[i_end] else {
1062 return Vec::new();
1063 };
1064 let u_end = u_of(i_end);
1065 #[allow(clippy::cast_precision_loss)]
1066 let pitch = TAU / (n_samples as f64);
1067 let u_next = if forward {
1068 u_end + pitch
1069 } else {
1070 u_end - pitch
1071 };
1072 let target = e / v_max;
1073 let h_end = n_dot_g_at(u_end) - target;
1074 let h_next = n_dot_g_at(u_next) - target;
1075 if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1076 return Vec::new();
1077 }
1078 let (mut lo, mut hi) = (u_end, u_next);
1079 for _ in 0..60 {
1080 let mid = f64::midpoint(lo, hi);
1081 if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1082 lo = mid;
1083 } else {
1084 hi = mid;
1085 }
1086 }
1087 let u_star = f64::midpoint(lo, hi);
1088 let tail_n = 8_usize;
1089 (1..=tail_n)
1090 .filter_map(|k| {
1091 #[allow(clippy::cast_precision_loss)]
1092 let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1093 let ng = n_dot_g_at(u);
1094 if ng.abs() < 1e-12 {
1095 return None;
1096 }
1097 let v = e / ng;
1098 (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1099 })
1100 .collect()
1101 };
1102
1103 let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1106 let mut chains: Vec<Vec<Point3>> = Vec::new();
1107 let mut run: Vec<usize> = Vec::new();
1108 let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1109 if run.len() >= 2 {
1110 let first = run[0];
1111 let last = run[run.len() - 1];
1112 let mut pts: Vec<Point3> = tail(first, false, &kept);
1113 pts.reverse();
1114 pts.extend(
1115 run.iter()
1116 .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1117 );
1118 pts.extend(tail(last, true, &kept));
1119 chains.push(pts);
1120 }
1121 run.clear();
1122 };
1123 for k in 0..n_samples {
1124 let idx = (gap + k) % n_samples;
1125 if kept[idx].is_some() {
1126 run.push(idx);
1127 } else {
1128 flush(&mut run, &mut chains);
1129 }
1130 }
1131 flush(&mut run, &mut chains);
1132 Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1133}
1134
1135#[allow(clippy::unnecessary_wraps)] fn sample_plane_torus(
1141 torus: &ToroidalSurface,
1142 normal: Vec3,
1143 d: f64,
1144) -> Result<Vec<Vec<Point3>>, MathError> {
1145 Ok(plane_torus_loops(torus, normal, d, 128)
1146 .into_iter()
1147 .map(|run| run.into_iter().map(|p| p.point).collect())
1148 .collect())
1149}
1150
1151#[allow(clippy::cast_precision_loss)]
1161pub fn intersect_plane_cylinder(
1162 cyl: &CylindricalSurface,
1163 normal: Vec3,
1164 d: f64,
1165) -> Result<Vec<IntersectionCurve>, MathError> {
1166 let n_samples = 64_usize;
1167 let mut points_3d = Vec::new();
1168 let mut ipoints = Vec::new();
1169
1170 for i in 0..=n_samples {
1171 let u = TAU * (i as f64) / (n_samples as f64);
1172 let base = cyl.evaluate(u, 0.0);
1175 let n_dot_axis = normal.dot(cyl.axis());
1176 let n_dot_base = dot_np(normal, base);
1177
1178 if n_dot_axis.abs() < 1e-12 {
1179 if (n_dot_base - d).abs() < 1e-6 {
1181 let pt = base;
1182 points_3d.push(pt);
1183 ipoints.push(IntersectionPoint {
1184 point: pt,
1185 param1: (u, 0.0),
1186 param2: (0.0, 0.0),
1187 });
1188 }
1189 } else {
1190 let v = (d - n_dot_base) / n_dot_axis;
1191 if v.abs() <= 100.0 {
1193 let pt = cyl.evaluate(u, v);
1194 points_3d.push(pt);
1195 ipoints.push(IntersectionPoint {
1196 point: pt,
1197 param1: (u, v),
1198 param2: (0.0, 0.0),
1199 });
1200 }
1201 }
1202 }
1203
1204 build_curves_from_points(&points_3d, ipoints)
1205}
1206
1207#[allow(clippy::cast_precision_loss)]
1216pub fn intersect_plane_sphere(
1217 sphere: &SphericalSurface,
1218 normal: Vec3,
1219 d: f64,
1220) -> Result<Vec<IntersectionCurve>, MathError> {
1221 let h = dot_np(normal, sphere.center()) - d;
1222 let r = sphere.radius();
1223
1224 if h.abs() > r - 1e-10 {
1226 return Ok(vec![]);
1227 }
1228
1229 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
1230 let circle_center = Point3::new(
1231 h.mul_add(-normal.x(), sphere.center().x()),
1232 h.mul_add(-normal.y(), sphere.center().y()),
1233 h.mul_add(-normal.z(), sphere.center().z()),
1234 );
1235
1236 let basis = Frame3::from_normal(circle_center, normal)?;
1238 let u_dir = basis.x;
1239 let v_dir = basis.y;
1240
1241 let n_samples = 64_usize;
1242 let mut points_3d = Vec::new();
1243 let mut ipoints = Vec::new();
1244
1245 for i in 0..=n_samples {
1246 let theta = TAU * (i as f64) / (n_samples as f64);
1247 let (sin_t, cos_t) = theta.sin_cos();
1248 let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1249 points_3d.push(pt);
1250 ipoints.push(IntersectionPoint {
1251 point: pt,
1252 param1: (theta, 0.0),
1253 param2: (0.0, 0.0),
1254 });
1255 }
1256
1257 build_curves_from_points(&points_3d, ipoints)
1258}
1259
1260#[allow(clippy::cast_precision_loss)]
1269pub fn intersect_plane_cone(
1270 cone: &ConicalSurface,
1271 normal: Vec3,
1272 d: f64,
1273) -> Result<Vec<IntersectionCurve>, MathError> {
1274 let n_samples = 64_usize;
1275 let mut points_3d = Vec::new();
1276 let mut ipoints = Vec::new();
1277
1278 for i in 0..n_samples {
1279 let u = TAU * (i as f64) / (n_samples as f64);
1280 let apex = cone.apex();
1283 let n_dot_apex = dot_np(normal, apex);
1284 let p1 = cone.evaluate(u, 1.0);
1286 let dir = p1 - apex;
1287 let n_dot_dir = normal.dot(dir);
1288
1289 if n_dot_dir.abs() < 1e-12 {
1290 continue;
1291 }
1292
1293 let v = (d - n_dot_apex) / n_dot_dir;
1294 if v.abs() > 1e-10 && v.abs() < 100.0 {
1296 let pt = cone.evaluate(u, v);
1297 points_3d.push(pt);
1298 ipoints.push(IntersectionPoint {
1299 point: pt,
1300 param1: (u, v),
1301 param2: (0.0, 0.0),
1302 });
1303 }
1304 }
1305
1306 build_curves_from_points(&points_3d, ipoints)
1307}
1308
1309#[allow(clippy::unnecessary_wraps)]
1321pub fn intersect_plane_torus(
1322 torus: &ToroidalSurface,
1323 normal: Vec3,
1324 d: f64,
1325) -> Result<Vec<IntersectionCurve>, MathError> {
1326 let mut curves = Vec::new();
1330 for ipts in plane_torus_loops(torus, normal, d, 128) {
1331 let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1332 if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
1333 curves.push(IntersectionCurve {
1334 curve,
1335 points: ipts,
1336 });
1337 }
1338 }
1339
1340 Ok(curves)
1341}
1342
1343const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1346
1347#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1370fn plane_torus_loops(
1371 torus: &ToroidalSurface,
1372 normal: Vec3,
1373 d: f64,
1374 n_v: usize,
1375) -> Vec<Vec<IntersectionPoint>> {
1376 let big_r = torus.major_radius();
1377 let small_r = torus.minor_radius();
1378 let a = normal.dot(torus.x_axis());
1379 let b = normal.dot(torus.y_axis());
1380 let c = normal.dot(torus.z_axis());
1381 let s = a.hypot(b);
1382 let phi = b.atan2(a);
1383 let d_local = d - dot_np(normal, torus.center());
1384 let point = |u: f64, v: f64| IntersectionPoint {
1385 point: torus.evaluate(u, v),
1386 param1: (u, v.rem_euclid(TAU)),
1387 param2: (0.0, 0.0),
1388 };
1389 let closed = |mut run: Vec<IntersectionPoint>| {
1390 run.push(run[0]);
1391 run
1392 };
1393
1394 if s < 1e-12 {
1396 if c.abs() < 1e-12 {
1397 return Vec::new();
1398 }
1399 let sin_v = d_local / (small_r * c);
1400 if sin_v.abs() > 1.0 + 1e-9 {
1401 return Vec::new();
1402 }
1403 let v0 = sin_v.clamp(-1.0, 1.0).asin();
1404 let v1 = std::f64::consts::PI - v0;
1405 let mut vs = vec![v0];
1406 let apart = (v1 - v0).rem_euclid(TAU);
1409 if apart.min(TAU - apart) > 1e-9 {
1410 vs.push(v1);
1411 }
1412 return vs
1413 .into_iter()
1414 .map(|v| {
1415 closed(
1416 (0..n_v)
1417 .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1418 .collect(),
1419 )
1420 })
1421 .collect();
1422 }
1423
1424 let step = TAU / (n_v as f64);
1427 let v_off = step * 0.5;
1428 let rhs_at = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.mul_add(v.cos(), big_r));
1430 let branch = |v: f64, sign: f64| point(sign.mul_add(rhs_at(v).clamp(-1.0, 1.0).acos(), phi), v);
1431 let inside = |v: f64| rhs_at(v).abs() <= 1.0;
1432 let peak = |lo: f64, hi: f64| {
1434 let golden = 0.5 * (5.0_f64.sqrt() - 1.0);
1435 let (mut lo, mut hi) = (lo, hi);
1436 for _ in 0..80 {
1437 let (m1, m2) = (hi - golden * (hi - lo), lo + golden * (hi - lo));
1438 if rhs_at(m1).abs() > rhs_at(m2).abs() {
1439 hi = m2;
1440 } else {
1441 lo = m1;
1442 }
1443 }
1444 let v = f64::midpoint(lo, hi);
1445 (v, rhs_at(v).abs())
1446 };
1447 let mut scan: Vec<f64> = Vec::with_capacity(n_v + 2);
1451 for i in 0..n_v {
1452 let v = (i as f64).mul_add(step, v_off);
1453 scan.push(v);
1454 if inside(v) && inside(v + step) {
1455 let (at, top) = peak(v, v + step);
1456 if top > 1.0 + 1e-12 {
1457 scan.push(at);
1458 }
1459 }
1460 }
1461 let n = scan.len();
1462 #[allow(clippy::cast_possible_wrap)]
1464 let scan_v = |i: isize| {
1465 let len = n as isize;
1466 scan[i.rem_euclid(len) as usize] + TAU * (i.div_euclid(len) as f64)
1467 };
1468 let touch_at = |lo: f64, hi: f64| {
1471 let (v, top) = peak(lo, hi);
1472 ((top - 1.0).abs() < 1e-12).then_some(v)
1473 };
1474 let node = |v: f64| {
1476 let u = if rhs_at(v) > 0.0 {
1477 phi
1478 } else {
1479 phi + std::f64::consts::PI
1480 };
1481 point(u, v)
1482 };
1483 let turn = |v_in: f64, v_out: f64| {
1485 let (mut lo, mut hi) = (v_in, v_out);
1486 for _ in 0..60 {
1487 let mid = f64::midpoint(lo, hi);
1488 if inside(mid) {
1489 lo = mid;
1490 } else {
1491 hi = mid;
1492 }
1493 }
1494 lo
1495 };
1496 let in_scan: Vec<bool> = scan.iter().map(|&v| inside(v)).collect();
1497 #[allow(clippy::cast_possible_wrap)]
1498 if in_scan.iter().all(|&x| x) {
1499 let at_node = (0..n as isize).find_map(|i| touch_at(scan_v(i), scan_v(i + 1)));
1500 return [1.0, -1.0]
1501 .into_iter()
1502 .map(|sign| match at_node {
1503 Some(v_node) => {
1504 let mut run = vec![node(v_node)];
1505 run.extend((1..n_v).map(|i| branch((i as f64).mul_add(step, v_node), sign)));
1506 closed(run)
1507 }
1508 None => closed(scan.iter().map(|&v| branch(v, sign)).collect()),
1509 })
1510 .collect();
1511 }
1512 let Some(first) = (0..n).find(|&i| in_scan[i] && !in_scan[(i + n - 1) % n]) else {
1513 return Vec::new();
1514 };
1515 let mut loops = Vec::new();
1516 let mut k = 0;
1517 while k < n {
1518 let i = (first + k) % n;
1519 if !in_scan[i] {
1520 k += 1;
1521 continue;
1522 }
1523 let len = (0..n - k).take_while(|&j| in_scan[(i + j) % n]).count();
1525 #[allow(clippy::cast_possible_wrap)]
1526 let run_v = |j: isize| scan_v(i as isize + j);
1527 #[allow(clippy::cast_possible_wrap)]
1528 let last = len as isize - 1;
1529 let (t_lo, t_hi) = (
1530 turn(run_v(0), run_v(-1)),
1531 turn(run_v(last), run_v(last + 1)),
1532 );
1533 let at_node = (0..last).find_map(|j| touch_at(run_v(j), run_v(j + 1)));
1534 let (u_lo, u_hi) = (0..=last)
1542 .map(run_v)
1543 .chain([t_lo, t_hi])
1544 .map(|v| rhs_at(v).clamp(-1.0, 1.0).acos())
1545 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1546 (lo.min(u), hi.max(u))
1547 });
1548 let m = (len as f64)
1549 .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1550 .max(PLANE_TORUS_LOOP_SAMPLES.0)
1551 .min(PLANE_TORUS_LOOP_SAMPLES.1)
1552 .ceil();
1553 let at = |k: f64| {
1554 let f = 0.5 * (1.0 - (std::f64::consts::PI * k / m).cos());
1555 (t_hi - t_lo).mul_add(f, t_lo)
1556 };
1557 let steps = m as usize;
1558 if let Some(v_node) = at_node {
1559 for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1562 let along = |k: usize| {
1563 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1564 (to - from).mul_add(f, from)
1565 };
1566 let mut pts = vec![node(v_node)];
1567 pts.extend((1..=steps).map(|k| branch(along(k), 1.0)));
1568 pts.extend((1..steps).rev().map(|k| branch(along(k), -1.0)));
1569 loops.push(closed(pts));
1570 }
1571 } else {
1572 let mut pts: Vec<IntersectionPoint> =
1573 (0..=steps).map(|k| branch(at(k as f64), 1.0)).collect();
1574 pts.extend((1..steps).rev().map(|k| branch(at(k as f64), -1.0)));
1575 loops.push(closed(pts));
1576 }
1577 k += len;
1578 }
1579 loops
1580}
1581
1582#[allow(clippy::cast_precision_loss)]
1591fn plane_torus_winding_loops(
1592 torus: &ToroidalSurface,
1593 normal: Vec3,
1594 d: f64,
1595 n_v: usize,
1596) -> Option<Vec<Vec<Point3>>> {
1597 let big_r = torus.major_radius();
1598 let small_r = torus.minor_radius();
1599 let a = normal.dot(torus.x_axis());
1600 let b = normal.dot(torus.y_axis());
1601 let c = normal.dot(torus.z_axis());
1602 let s = a.hypot(b);
1603 if s < 1e-12 * normal.length() || small_r >= big_r {
1604 return None;
1605 }
1606 let phi = b.atan2(a);
1607 let d_local = d - dot_np(normal, torus.center());
1608 let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.mul_add(v.cos(), big_r));
1609 let dense = 8 * n_v;
1610 if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1611 return None;
1612 }
1613 let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1614 for i in 0..n_v {
1615 let v = TAU * i as f64 / n_v as f64;
1616 let delta = rhs(v).acos();
1617 loops[0].push(torus.evaluate(phi + delta, v));
1618 loops[1].push(torus.evaluate(phi - delta, v));
1619 }
1620 Some(
1621 loops
1622 .into_iter()
1623 .map(|mut run| {
1624 run.push(run[0]);
1625 run
1626 })
1627 .collect(),
1628 )
1629}
1630
1631#[must_use]
1645pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1646 let c = torus.center();
1647 let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1648 let big_r = torus.major_radius();
1649 let small_r = torus.minor_radius();
1650
1651 let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1653 let (a0, a1) = (xa.dot(o), xa.dot(dir));
1654 let (b0, b1) = (ya.dot(o), ya.dot(dir));
1655 let (c0, c1) = (za.dot(o), za.dot(dir));
1656
1657 let g2 = a1.mul_add(a1, b1.mul_add(b1, c1 * c1));
1659 let g1 = 2.0 * a1.mul_add(a0, b1.mul_add(b0, c1 * c0));
1660 let g0 = a0.mul_add(
1661 a0,
1662 b0.mul_add(b0, c0.mul_add(c0, big_r.mul_add(big_r, -small_r * small_r))),
1663 );
1664
1665 let four_rr = 4.0 * big_r * big_r;
1667 let h2 = four_rr * a1.mul_add(a1, b1 * b1);
1668 let h1 = four_rr * (2.0 * a1.mul_add(a0, b1 * b0));
1669 let h0 = four_rr * a0.mul_add(a0, b0 * b0);
1670
1671 let e4 = g2 * g2;
1673 let e3 = 2.0 * g2 * g1;
1674 let e2 = g1.mul_add(g1, 2.0 * g2 * g0) - h2;
1675 let e1 = 2.0f64.mul_add(g1 * g0, -h1);
1676 let e0 = g0.mul_add(g0, -h0);
1677
1678 let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1679 let tube = |t: f64, across: bool| -> f64 {
1685 let p = origin + dir * t;
1686 let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1687 let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1688 let centre = if across { -big_r } else { big_r };
1689 (a.hypot(b) - centre).hypot(cc) - small_r
1690 };
1691 for t in &mut roots {
1692 let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
1693 for _ in 0..8 {
1694 let eps = 1e-7;
1695 let f = tube(*t, across);
1696 let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
1697 if df.abs() <= 1e-12 {
1698 break;
1699 }
1700 let step = f / df;
1701 *t -= step;
1702 if step.abs() < 1e-14 * (1.0 + t.abs()) {
1703 break;
1704 }
1705 }
1706 }
1707 roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1708 roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
1709 roots
1710}
1711
1712fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1715 if c4.abs() < 1e-14 {
1717 return real_roots_cubic(c3, c2, c1, c0);
1718 }
1719 let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1721 let eval = |z: Complex| -> Complex {
1722 let mut acc = Complex::new(1.0, 0.0);
1724 acc = acc * z + Complex::new(a, 0.0);
1725 acc = acc * z + Complex::new(b, 0.0);
1726 acc = acc * z + Complex::new(c, 0.0);
1727 acc * z + Complex::new(d, 0.0)
1728 };
1729 let seed = Complex::new(0.4, 0.9);
1731 let mut r = [
1732 Complex::new(1.0, 0.0),
1733 seed,
1734 seed * seed,
1735 seed * seed * seed,
1736 ];
1737 for _ in 0..100 {
1738 let mut max_step = 0.0_f64;
1739 for i in 0..4 {
1740 let mut denom = Complex::new(1.0, 0.0);
1741 for j in 0..4 {
1742 if i != j {
1743 denom = denom * (r[i] - r[j]);
1744 }
1745 }
1746 if denom.norm() < 1e-300 {
1747 continue;
1748 }
1749 let step = eval(r[i]) / denom;
1750 r[i] = r[i] - step;
1751 max_step = max_step.max(step.norm());
1752 }
1753 if max_step < 1e-14 {
1754 break;
1755 }
1756 }
1757 let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1764 let mut out: Vec<f64> = Vec::new();
1765 for z in r {
1766 if z.im.abs() >= 1e-7 {
1767 continue;
1768 }
1769 let x = z.re;
1770 let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1773 if p_real(x).abs() > 1e-6 * scale {
1774 continue;
1775 }
1776 if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1777 continue;
1778 }
1779 out.push(x);
1780 }
1781 out
1782}
1783
1784fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1786 if a.abs() < 1e-14 {
1787 return real_roots_quadratic(b, c, d);
1788 }
1789 let (b, c, d) = (b / a, c / a, d / a);
1791 let p = c - b * b / 3.0;
1792 let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1793 let shift = -b / 3.0;
1794 let disc = q * q / 4.0 + p * p * p / 27.0;
1795 if disc > 1e-14 {
1796 let sq = disc.sqrt();
1797 let u = (-q / 2.0 + sq).cbrt();
1798 let v = (-q / 2.0 - sq).cbrt();
1799 vec![u + v + shift]
1800 } else if disc < -1e-14 {
1801 let m = 2.0 * (-p / 3.0).sqrt();
1803 let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1804 (0..3)
1805 .map(|k| {
1806 m.mul_add(
1807 (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1808 shift,
1809 )
1810 })
1811 .collect()
1812 } else {
1813 let u = (-q / 2.0).cbrt();
1815 vec![2.0 * u + shift, -u + shift]
1816 }
1817}
1818
1819fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1821 if a.abs() < 1e-14 {
1822 if b.abs() < 1e-14 {
1823 return Vec::new();
1824 }
1825 return vec![-c / b];
1826 }
1827 let disc = b * b - 4.0 * a * c;
1828 if disc < 0.0 {
1829 Vec::new()
1830 } else {
1831 let sq = disc.sqrt();
1832 vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1833 }
1834}
1835
1836#[derive(Clone, Copy)]
1838struct Complex {
1839 re: f64,
1840 im: f64,
1841}
1842
1843impl Complex {
1844 const fn new(re: f64, im: f64) -> Self {
1845 Self { re, im }
1846 }
1847 fn norm(self) -> f64 {
1848 self.re.hypot(self.im)
1849 }
1850}
1851
1852impl std::ops::Add for Complex {
1853 type Output = Self;
1854 fn add(self, o: Self) -> Self {
1855 Self::new(self.re + o.re, self.im + o.im)
1856 }
1857}
1858
1859impl std::ops::Sub for Complex {
1860 type Output = Self;
1861 fn sub(self, o: Self) -> Self {
1862 Self::new(self.re - o.re, self.im - o.im)
1863 }
1864}
1865
1866impl std::ops::Mul for Complex {
1867 type Output = Self;
1868 fn mul(self, o: Self) -> Self {
1869 Self::new(
1870 self.re.mul_add(o.re, -(self.im * o.im)),
1871 self.re.mul_add(o.im, self.im * o.re),
1872 )
1873 }
1874}
1875
1876impl std::ops::Div for Complex {
1877 type Output = Self;
1878 fn div(self, o: Self) -> Self {
1879 let den = o.re.mul_add(o.re, o.im * o.im);
1880 Self::new(
1881 self.re.mul_add(o.re, self.im * o.im) / den,
1882 self.im.mul_add(o.re, -(self.re * o.im)) / den,
1883 )
1884 }
1885}
1886
1887fn build_curves_from_points(
1891 points_3d: &[Point3],
1892 ipoints: Vec<IntersectionPoint>,
1893) -> Result<Vec<IntersectionCurve>, MathError> {
1894 if points_3d.len() < 2 {
1895 return Ok(vec![]);
1896 }
1897
1898 let degree = 3.min(points_3d.len() - 1);
1899 let curve = interpolate(points_3d, degree)?;
1900 Ok(vec![IntersectionCurve {
1901 curve,
1902 points: ipoints,
1903 }])
1904}
1905
1906#[allow(
1918 clippy::cast_precision_loss,
1919 clippy::too_many_lines,
1920 clippy::similar_names,
1921 clippy::unnecessary_wraps,
1922 clippy::type_complexity
1923)]
1924pub fn intersect_analytic_analytic(
1925 a: AnalyticSurface<'_>,
1926 b: AnalyticSurface<'_>,
1927 grid_res: usize,
1928) -> Result<Vec<IntersectionCurve>, MathError> {
1929 intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
1930}
1931
1932pub fn intersect_analytic_analytic_bounded(
1943 a: AnalyticSurface<'_>,
1944 b: AnalyticSurface<'_>,
1945 grid_res: usize,
1946 v_range_hint_a: Option<(f64, f64)>,
1947 v_range_hint_b: Option<(f64, f64)>,
1948) -> Result<Vec<IntersectionCurve>, MathError> {
1949 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
1950}
1951
1952pub fn intersect_analytic_analytic_in_region(
1965 a: AnalyticSurface<'_>,
1966 b: AnalyticSurface<'_>,
1967 grid_res: usize,
1968 v_range_hint_a: Option<(f64, f64)>,
1969 v_range_hint_b: Option<(f64, f64)>,
1970 region: Aabb3,
1971) -> Result<Vec<IntersectionCurve>, MathError> {
1972 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
1973}
1974
1975fn intersect_analytic_analytic_impl(
1976 a: AnalyticSurface<'_>,
1977 b: AnalyticSurface<'_>,
1978 grid_res: usize,
1979 v_range_hint_a: Option<(f64, f64)>,
1980 v_range_hint_b: Option<(f64, f64)>,
1981 region: Option<Aabb3>,
1982) -> Result<Vec<IntersectionCurve>, MathError> {
1983 if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
1986 return Ok(result);
1987 }
1988
1989 let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
1990 let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
1991 let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
1992 let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
1993
1994 let diag_a = {
1996 let p00 = surf_a(u_range_a.0, v_range_a.0);
1997 let p11 = surf_a(u_range_a.1, v_range_a.1);
1998 (p00 - p11).length()
1999 };
2000 let diag_b = {
2001 let p00 = surf_b(u_range_b.0, v_range_b.0);
2002 let p11 = surf_b(u_range_b.1, v_range_b.1);
2003 (p00 - p11).length()
2004 };
2005 let char_size = diag_a.min(diag_b).max(0.1);
2006
2007 #[allow(clippy::type_complexity)]
2011 let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
2012 let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
2016 let mut min_dist = f64::INFINITY;
2017
2018 #[allow(clippy::cast_precision_loss)]
2019 for ia in 0..grid_res {
2020 for ja in 0..grid_res {
2021 let ua =
2022 u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
2023 let va =
2024 v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
2025
2026 let pa = surf_a(ua, va);
2027
2028 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2030 let pb = surf_b(ub, vb);
2031 let dist = (pa - pb).length();
2032 min_dist = min_dist.min(dist);
2033
2034 if dist < seed_threshold {
2035 let mid = Point3::new(
2040 (pa.x() + pb.x()) * 0.5,
2041 (pa.y() + pb.y()) * 0.5,
2042 (pa.z() + pb.z()) * 0.5,
2043 );
2044 seeds.push((mid, (ua, va), (ub, vb)));
2045 }
2046 }
2047 }
2048
2049 let reject_dist = (char_size / grid_res as f64) * 3.0;
2058 if min_dist > reject_dist {
2059 return Ok(vec![]);
2060 }
2061
2062 if seeds.is_empty() {
2063 return Ok(vec![]);
2064 }
2065
2066 let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2070 let dedup_radius = march_step * 10.0;
2071 let mut unique_seeds = Vec::new();
2072 for seed in &seeds {
2073 let dominated = unique_seeds
2074 .iter()
2075 .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
2076 if !dominated {
2077 unique_seeds.push(*seed);
2078 }
2079 }
2080
2081 let region = region.map(|r| r.expanded(2.0 * char_size / grid_res as f64));
2086 if let Some(r) = region {
2087 for seed in &mut unique_seeds {
2088 let mut p = seed.0;
2089 for _ in 0..8 {
2090 let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2091 let pa = surf_a(ua, va);
2092 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2093 let pb = surf_b(ub, vb);
2094 p = Point3::new(
2095 (pa.x() + pb.x()) * 0.5,
2096 (pa.y() + pb.y()) * 0.5,
2097 (pa.z() + pb.z()) * 0.5,
2098 );
2099 if (pa - pb).length() < 1e-9 {
2100 break;
2101 }
2102 }
2103 seed.0 = p;
2104 }
2105 unique_seeds.retain(|seed| r.contains_point(seed.0));
2106 }
2107
2108 let mut curves = Vec::new();
2110 let mut used_seeds = vec![false; unique_seeds.len()];
2111
2112 for si in 0..unique_seeds.len() {
2113 if used_seeds[si] {
2114 continue;
2115 }
2116 used_seeds[si] = true;
2117
2118 let march_result = march_analytic_intersection(
2119 &a,
2120 &b,
2121 surf_a.as_ref(),
2122 norm_a.as_ref(),
2123 surf_b.as_ref(),
2124 norm_b.as_ref(),
2125 unique_seeds[si].0,
2126 u_range_a,
2127 v_range_a,
2128 u_range_b,
2129 v_range_b,
2130 march_step,
2131 is_u_periodic(&a),
2132 is_u_periodic(&b),
2133 region,
2134 );
2135
2136 if march_result.len() >= 2 {
2137 for (sj, other) in unique_seeds.iter().enumerate() {
2138 if !used_seeds[sj]
2139 && march_result
2140 .iter()
2141 .any(|p| (*p - other.0).length() < dedup_radius)
2142 {
2143 used_seeds[sj] = true;
2144 }
2145 }
2146
2147 let ipts: Vec<IntersectionPoint> = march_result
2148 .iter()
2149 .map(|&pt| IntersectionPoint {
2150 point: pt,
2151 param1: (0.0, 0.0),
2152 param2: (0.0, 0.0),
2153 })
2154 .collect();
2155
2156 let degree = 3.min(march_result.len() - 1);
2157 if let Ok(curve) = interpolate(&march_result, degree) {
2158 curves.push(IntersectionCurve {
2159 curve,
2160 points: ipts,
2161 });
2162 }
2163 }
2164 }
2165
2166 Ok(curves)
2167}
2168
2169#[allow(clippy::too_many_lines)]
2183fn try_algebraic_intersection(
2184 a: &AnalyticSurface<'_>,
2185 b: &AnalyticSurface<'_>,
2186 v_range_a: Option<(f64, f64)>,
2187 v_range_b: Option<(f64, f64)>,
2188) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2189 match (a, b) {
2190 (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2191 algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2192 .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2193 ),
2194 (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2195 algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2196 .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2197 ),
2198 (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2199 algebraic_sphere_sphere(s1, s2).map(Some)
2200 }
2201 (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2202 let axis_dot = c1.axis().dot(c2.axis()).abs();
2203 if axis_dot > 1.0 - 1e-10 {
2204 let delta = c2.origin() - c1.origin();
2206 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2207 let along = delta_vec.dot(c1.axis());
2208 let perp = (delta_vec - c1.axis() * along).length();
2209 if perp < 1e-8 {
2210 if (c1.radius() - c2.radius()).abs() < 1e-8 {
2213 return Ok(None); }
2215 return Ok(Some(vec![])); }
2217 if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2218 return Ok(Some(rulings));
2219 }
2220 }
2221 algebraic_cylinder_cylinder(c1, c2)
2223 }
2224 (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2226 algebraic_sphere_cylinder(s, c, true)
2227 }
2228 (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2229 algebraic_sphere_cylinder(s, c, false)
2230 }
2231 (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => algebraic_cone_cone(c1, c2),
2232 (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2233 Ok(ruling_cone_sphere(cone, sphere, true))
2234 }
2235 (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2236 Ok(ruling_cone_sphere(cone, sphere, false))
2237 }
2238 (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2239 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2240 return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2241 .map(Some);
2242 }
2243 Ok(parallel_axis_torus_cylinder(t, c, true)
2244 .or_else(|| ruling_torus_cylinder(t, c, true)))
2245 }
2246 (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
2247 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2248 return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
2249 .map(Some);
2250 }
2251 Ok(parallel_axis_torus_cylinder(t, c, false)
2252 .or_else(|| ruling_torus_cylinder(t, c, false)))
2253 }
2254 (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => exact_sphere_torus(s, t)?
2255 .map(|exacts| exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p))))
2256 .transpose(),
2257 (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => exact_sphere_torus(s, t)?
2258 .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p))))
2259 .transpose(),
2260 (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
2261 .map(|exacts| {
2262 exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
2263 })
2264 .transpose(),
2265 _ => Ok(None),
2266 }
2267}
2268
2269fn parallel_axis_torus_cylinder(
2276 torus: &ToroidalSurface,
2277 cyl: &CylindricalSurface,
2278 torus_first: bool,
2279) -> Option<Vec<IntersectionCurve>> {
2280 let axis = torus.z_axis();
2281 let along = cyl.axis().dot(axis);
2282 if along.abs() < 1.0 - 1e-10 {
2283 return None;
2284 }
2285 let offset = cyl.origin() - torus.center();
2286 if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
2287 return None;
2288 }
2289 let (major, minor) = (torus.major_radius(), torus.minor_radius());
2290 let roots = |u: f64| {
2291 let q = cyl.evaluate(u, 0.0) - torus.center();
2292 let height = q.dot(axis);
2293 let rho = (q - axis * height).length();
2294 let reach = minor * minor - (rho - major) * (rho - major);
2295 ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
2296 };
2297 let samples = ruling_samples(cyl, &roots);
2298 let loops = if samples.iter().all(Option::is_some) {
2299 closed_ruling_loops(cyl, &roots, &samples)
2300 } else {
2301 partial_ruling_loops(cyl, &roots, &samples)
2302 };
2303 if loops.is_empty() {
2304 return None;
2305 }
2306 Some(fit_ruling_loops(&loops, |p| {
2307 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
2308 }))
2309}
2310
2311fn meridian_crossings(
2318 first: (f64, f64, f64),
2319 second: (f64, f64, f64),
2320 scale: f64,
2321) -> Option<Vec<(f64, f64)>> {
2322 let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
2323 let (dx, dz) = (x2 - x1, z2 - z1);
2324 let dist = dx.hypot(dz);
2325 let slack = 1e-9 * scale;
2326 if dist < slack {
2327 return None;
2328 }
2329 let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
2330 if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
2331 return Some(Vec::new());
2332 }
2333 let along = r2.mul_add(-r2, r1.mul_add(r1, dist * dist)) / (2.0 * dist);
2334 let across = r1.mul_add(r1, -(along * along)).max(0.0).sqrt();
2335 let (ux, uz) = (dx / dist, dz / dist);
2336 let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
2337 &[0.0]
2338 } else {
2339 &[1.0, -1.0]
2340 };
2341 let mut crossings = Vec::with_capacity(sides.len());
2342 for side in sides {
2343 let rho = x1 + along * ux - side * across * uz;
2344 if rho <= slack {
2345 return None;
2346 }
2347 crossings.push((rho, z1 + along * uz + side * across * ux));
2348 }
2349 Some(crossings)
2350}
2351
2352fn exact_circle_curves(
2355 exacts: Vec<ExactIntersectionCurve>,
2356 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
2357) -> Result<Vec<IntersectionCurve>, MathError> {
2358 exacts
2359 .into_iter()
2360 .filter_map(|exact| match exact {
2361 ExactIntersectionCurve::Circle(circle) => Some(circle),
2362 ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => None,
2363 })
2364 .map(|circle| {
2365 let points = (0..=32)
2366 .map(|i| {
2367 let point = circle.evaluate(TAU * f64::from(i) / 32.0);
2368 let (param1, param2) = params(point);
2369 IntersectionPoint {
2370 point,
2371 param1,
2372 param2,
2373 }
2374 })
2375 .collect();
2376 let r = circle.radius();
2377 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
2378 Ok(IntersectionCurve { curve, points })
2379 })
2380 .collect()
2381}
2382
2383fn circles_about_axis(
2385 base: Point3,
2386 axis: Vec3,
2387 crossings: &[(f64, f64)],
2388) -> Result<Vec<ExactIntersectionCurve>, MathError> {
2389 crossings
2390 .iter()
2391 .map(|&(rho, z)| {
2392 Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
2393 })
2394 .collect()
2395}
2396
2397pub fn exact_torus_torus(
2409 first: &ToroidalSurface,
2410 second: &ToroidalSurface,
2411) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2412 let axis = first.z_axis();
2413 let scale = first.major_radius() + second.major_radius();
2414 let offset = second.center() - first.center();
2415 if first.minor_radius() >= first.major_radius()
2417 || second.minor_radius() >= second.major_radius()
2418 || axis.cross(second.z_axis()).length() > 1e-9
2419 || offset.cross(axis).length() > 1e-9 * scale
2420 {
2421 return Ok(None);
2422 }
2423 let Some(crossings) = meridian_crossings(
2424 (first.major_radius(), 0.0, first.minor_radius()),
2425 (
2426 second.major_radius(),
2427 offset.dot(axis),
2428 second.minor_radius(),
2429 ),
2430 scale,
2431 ) else {
2432 return Ok(None);
2433 };
2434 circles_about_axis(first.center(), axis, &crossings).map(Some)
2435}
2436
2437pub fn exact_cylinder_torus(
2451 cylinder: &CylindricalSurface,
2452 torus: &ToroidalSurface,
2453) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2454 let axis = torus.z_axis();
2455 let scale = torus.major_radius() + cylinder.radius();
2456 let offset = cylinder.origin() - torus.center();
2457 let linear = crate::tolerance::Tolerance::default().linear;
2458 if axis.cross(cylinder.axis()).length() > 1e-9
2459 || offset.cross(axis).length() > 1e-9 * scale
2460 || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
2461 {
2462 return Ok(None);
2463 }
2464 let gap = cylinder.radius() - torus.major_radius();
2465 let small = torus.minor_radius();
2466 if (gap.abs() - small).abs() <= linear {
2470 return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
2471 }
2472 if gap.abs() > small {
2473 return Ok(Some(Vec::new()));
2474 }
2475 let height = small.mul_add(small, -(gap * gap)).sqrt();
2476 circles_about_axis(
2477 torus.center(),
2478 axis,
2479 &[(cylinder.radius(), height), (cylinder.radius(), -height)],
2480 )
2481 .map(Some)
2482}
2483
2484pub fn exact_sphere_torus(
2497 sphere: &SphericalSurface,
2498 torus: &ToroidalSurface,
2499) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2500 let axis = torus.z_axis();
2501 let scale = torus.major_radius() + sphere.radius();
2502 let offset = sphere.center() - torus.center();
2503 if torus.minor_radius() >= torus.major_radius() || offset.cross(axis).length() > 1e-9 * scale {
2505 return Ok(None);
2506 }
2507 let Some(crossings) = meridian_crossings(
2508 (0.0, offset.dot(axis), sphere.radius()),
2509 (torus.major_radius(), 0.0, torus.minor_radius()),
2510 scale,
2511 ) else {
2512 return Ok(None);
2513 };
2514 circles_about_axis(torus.center(), axis, &crossings).map(Some)
2515}
2516
2517pub fn exact_cone_cone(
2542 c1: &ConicalSurface,
2543 c2: &ConicalSurface,
2544) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2545 let axis = c1.axis();
2546 let axis2 = c2.axis();
2547
2548 if axis.dot(axis2).abs() < 1.0 - 1e-10 {
2550 return Ok(None); }
2552 let apex1 = c1.apex();
2553 let apex2 = c2.apex();
2554 let delta = apex2 - apex1;
2555 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2556 let along = delta_v.dot(axis);
2557 if (delta_v - axis * along).length() > 1e-8 {
2558 return offset_parallel_cone_cone(c1, c2);
2559 }
2560
2561 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
2562 if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
2563 return Ok(None); }
2565 let m1 = c1.half_angle().cos() / s1;
2566 let m2 = c2.half_angle().cos() / s2;
2567 let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
2568 let d2 = along; let denom = m1 - m2 * sigma;
2571 if denom.abs() < 1e-12 {
2572 if sigma > 0.0 && d2.abs() < 1e-9 {
2575 return Ok(None);
2576 }
2577 return Ok(Some(vec![]));
2578 }
2579
2580 let t_star = (-m2 * sigma * d2) / denom;
2581 let radius = m1 * t_star;
2582 if radius < 1e-12 {
2583 return Ok(Some(vec![])); }
2585
2586 let center = Point3::new(
2587 apex1.x() + axis.x() * t_star,
2588 apex1.y() + axis.y() * t_star,
2589 apex1.z() + axis.z() * t_star,
2590 );
2591 let circle = Circle3D::new(center, axis, radius)?;
2592 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2593}
2594
2595fn offset_parallel_cone_cone(
2606 c1: &ConicalSurface,
2607 c2: &ConicalSurface,
2608) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2609 if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
2610 return Ok(None); }
2612 let t1 = c1.half_angle().tan();
2613 let t2 = c2.half_angle().tan();
2614 if !t1.is_finite() || !t2.is_finite() {
2615 return Ok(None);
2616 }
2617 if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
2618 return Ok(None);
2619 }
2620
2621 let w = c1.axis();
2622 let apex1 = c1.apex();
2623 let apex2 = c2.apex();
2624 let delta = apex2 - apex1;
2625 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2626 let s = delta_v.dot(w);
2627 let tm = 0.5 * (t1 + t2);
2628 let k = 1.0 + tm * tm;
2629
2630 let n = (delta_v - w * (k * s)) * 2.0;
2634 let n_len = n.length();
2635 if n_len < 1e-12 {
2636 return Ok(None);
2637 }
2638 let n_hat = n * (1.0 / n_len);
2639 let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
2640
2641 let axis2 = c2.axis();
2647 let scale = 1.0 + delta_v.length();
2648 let mut out = Vec::new();
2649 for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
2650 let samples: Vec<Point3> = match &curve {
2651 ExactIntersectionCurve::Circle(c) => (0..4)
2652 .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
2653 .collect(),
2654 ExactIntersectionCurve::Ellipse(e) => (0..4)
2655 .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
2656 .collect(),
2657 ExactIntersectionCurve::Points(_) => return Ok(None),
2658 };
2659 let on_real_nappe = |p: &Point3| {
2660 let rel = *p - apex2;
2661 Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
2662 };
2663 let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
2664 match hits {
2665 0 => {}
2666 4 => out.push(curve),
2667 _ => return Ok(None),
2668 }
2669 }
2670 Ok(Some(out))
2671}
2672
2673pub fn exact_cone_cylinder(
2693 cone: &ConicalSurface,
2694 cyl: &CylindricalSurface,
2695) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2696 let axis = cone.axis();
2697 let cyl_axis = cyl.axis();
2698
2699 if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
2701 return Ok(None);
2702 }
2703 let apex = cone.apex();
2704 let delta = apex - cyl.origin();
2705 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2706 let along = delta_v.dot(cyl_axis);
2707 if (delta_v - cyl_axis * along).length() > 1e-8 {
2708 return Ok(None);
2709 }
2710
2711 let s = cone.half_angle().sin();
2712 if s.abs() < 1e-12 {
2713 return Ok(None); }
2715 let m = cone.half_angle().cos() / s; if m.abs() < 1e-12 {
2717 return Ok(None); }
2719
2720 let t_star = cyl.radius() / m; if t_star.abs() < 1e-12 {
2722 return Ok(Some(vec![])); }
2724 let center = Point3::new(
2725 apex.x() + axis.x() * t_star,
2726 apex.y() + axis.y() * t_star,
2727 apex.z() + axis.z() * t_star,
2728 );
2729 let circle = Circle3D::new(center, axis, cyl.radius())?;
2730 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2731}
2732
2733fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
2738 let w = std::f64::consts::FRAC_1_SQRT_2;
2739 let corners: [(f64, f64); 9] = [
2740 (1.0, 0.0),
2741 (1.0, 1.0),
2742 (0.0, 1.0),
2743 (-1.0, 1.0),
2744 (-1.0, 0.0),
2745 (-1.0, -1.0),
2746 (0.0, -1.0),
2747 (1.0, -1.0),
2748 (1.0, 0.0),
2749 ];
2750 let points = corners
2751 .iter()
2752 .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
2753 .collect();
2754 let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
2755 let knots = vec![
2756 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
2757 ];
2758 NurbsCurve::new(2, knots, points, weights)
2759}
2760
2761fn crossing_equal_cylinders(
2774 c1: &CylindricalSurface,
2775 c2: &CylindricalSurface,
2776) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2777 let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
2778 if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
2779 return Ok(None);
2780 }
2781 let bisectors = [d1 - d2, d1 + d2];
2786 let tol = Tolerance::new().linear;
2787 if bisectors
2788 .iter()
2789 .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
2790 {
2791 return Ok(None);
2792 }
2793 let across = d1.cross(d2);
2794 let sin = across.length();
2795 let normal = across * (1.0 / sin);
2796 let w = c1.origin() - c2.origin();
2797 let cos = d1.dot(d2);
2798 let along = cos.mul_add(d2.dot(w), -d1.dot(w)) / (sin * sin);
2799 let centre = c1.origin() + d1 * along;
2800 let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
2804 if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
2805 return Ok(None);
2806 }
2807 let majors = bisectors.map(|bisector| {
2810 let length = bisector.length();
2811 let major = (bisector * (1.0 / length)).cross(normal);
2812 let major = if major.dot(d1) < 0.0 { -major } else { major };
2813 (major, 2.0 * r / length)
2814 });
2815 let corner = std::f64::consts::FRAC_1_SQRT_2;
2816 let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
2817 let mut curves = Vec::with_capacity(2);
2818 for side in [1.0, -1.0] {
2819 let [(m1, a1), (m2, a2)] = majors;
2820 let out = half
2821 .iter()
2822 .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
2823 let back = half[1..]
2824 .iter()
2825 .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
2826 let curve = NurbsCurve::new(
2827 2,
2828 vec![
2829 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
2830 ],
2831 out.chain(back).collect(),
2832 vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
2833 )?;
2834 #[allow(clippy::cast_precision_loss)]
2835 let points = (0..=32)
2836 .map(|i| {
2837 let point = curve.evaluate(i as f64 / 32.0);
2838 IntersectionPoint {
2839 point,
2840 param1: c1.project_point(point),
2841 param2: c2.project_point(point),
2842 }
2843 })
2844 .collect();
2845 curves.push(IntersectionCurve { curve, points });
2846 }
2847 Ok(Some(curves))
2848}
2849
2850fn algebraic_cone_cone(
2859 c1: &ConicalSurface,
2860 c2: &ConicalSurface,
2861) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2862 let Some(exacts) = exact_cone_cone(c1, c2)? else {
2863 return Ok(None);
2864 };
2865 let mut curves = Vec::new();
2866 for exact in exacts {
2867 let n_samples = 33;
2868 let mut points = Vec::with_capacity(n_samples);
2869 #[allow(clippy::cast_precision_loss)]
2870 for i in 0..n_samples {
2871 let theta = TAU * i as f64 / (n_samples - 1) as f64;
2872 let pt = match &exact {
2873 ExactIntersectionCurve::Circle(circle) => {
2874 crate::traits::ParametricCurve::evaluate(circle, theta)
2875 }
2876 ExactIntersectionCurve::Ellipse(ellipse) => {
2877 crate::traits::ParametricCurve::evaluate(ellipse, theta)
2878 }
2879 ExactIntersectionCurve::Points(_) => break,
2880 };
2881 points.push(IntersectionPoint {
2882 point: pt,
2883 param1: (0.0, 0.0),
2884 param2: (0.0, 0.0),
2885 });
2886 }
2887 let curve = match &exact {
2888 ExactIntersectionCurve::Circle(c) => {
2889 conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
2890 }
2891 ExactIntersectionCurve::Ellipse(e) => conic_loop(
2892 e.center(),
2893 e.u_axis(),
2894 e.v_axis(),
2895 e.semi_major(),
2896 e.semi_minor(),
2897 )?,
2898 ExactIntersectionCurve::Points(_) => continue,
2899 };
2900 curves.push(IntersectionCurve { curve, points });
2901 }
2902 Ok(Some(curves))
2903}
2904
2905pub fn exact_sphere_cylinder(
2925 sphere: &SphericalSurface,
2926 cyl: &CylindricalSurface,
2927) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2928 let sc = sphere.center();
2929 let r_sphere = sphere.radius();
2930 let co = cyl.origin();
2931 let axis = cyl.axis();
2932 let r_cyl = cyl.radius();
2933
2934 let delta = sc - co;
2936 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2937 let along = delta_vec.dot(axis);
2938 let perp_vec = delta_vec - axis * along;
2939 let d_perp = perp_vec.length();
2940
2941 if d_perp > 1e-7 {
2944 return Ok(None);
2945 }
2946
2947 if r_cyl > r_sphere + 1e-10 {
2950 return Ok(Some(vec![]));
2951 }
2952 let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
2953 if z_sq < 0.0 {
2954 return Ok(Some(vec![]));
2955 }
2956 let z = z_sq.sqrt();
2957
2958 let center_axis_pt = Point3::new(
2961 co.x() + axis.x() * along,
2962 co.y() + axis.y() * along,
2963 co.z() + axis.z() * along,
2964 );
2965
2966 let mut circles = Vec::new();
2967 let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
2968 for &z_offset in offsets {
2969 let center = Point3::new(
2970 center_axis_pt.x() + axis.x() * z_offset,
2971 center_axis_pt.y() + axis.y() * z_offset,
2972 center_axis_pt.z() + axis.z() * z_offset,
2973 );
2974 let circle = Circle3D::new(center, axis, r_cyl)?;
2975 circles.push(ExactIntersectionCurve::Circle(circle));
2976 }
2977 Ok(Some(circles))
2978}
2979
2980pub fn exact_cone_sphere(
2998 cone: &ConicalSurface,
2999 sphere: &SphericalSurface,
3000) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3001 let offset = cone.apex() - sphere.center();
3002 let along = offset.dot(cone.axis());
3003 if (offset - cone.axis() * along).length() > 1e-7 {
3004 return Ok(None);
3005 }
3006 let lin_tol = Tolerance::new().linear;
3007 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3008 let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
3009 let b = 2.0 * sin_a * along;
3010 let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
3011 let noise = 16.0 * f64::EPSILON * 4.0f64.mul_add(far_sq + radius_sq, b * b);
3014 if disc < -noise {
3015 return Ok(Some(vec![]));
3016 }
3017 let roots: &[f64] = if far - near < lin_tol {
3018 &[far]
3019 } else {
3020 &[near, far]
3021 };
3022 let mut circles = Vec::new();
3023 for &v in roots {
3024 if v * cos_a > lin_tol {
3025 let centre = cone.apex() + cone.axis() * (v * sin_a);
3026 let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
3027 circles.push(ExactIntersectionCurve::Circle(circle));
3028 }
3029 }
3030 Ok(Some(circles))
3031}
3032
3033fn algebraic_sphere_cylinder(
3042 sphere: &SphericalSurface,
3043 cyl: &CylindricalSurface,
3044 sphere_first: bool,
3045) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3046 let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
3047 return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
3048 };
3049
3050 let mut curves = Vec::new();
3051 for exact in exacts {
3052 let ExactIntersectionCurve::Circle(circle) = exact else {
3053 continue;
3054 };
3055 let n_samples = 33;
3056 let mut points = Vec::with_capacity(n_samples);
3057 #[allow(clippy::cast_precision_loss)]
3058 for i in 0..n_samples {
3059 let theta = TAU * i as f64 / (n_samples - 1) as f64;
3060 let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
3061 let (param1, param2) = in_order(
3062 sphere.project_point(pt),
3063 cyl.project_point(pt),
3064 sphere_first,
3065 );
3066 points.push(IntersectionPoint {
3067 point: pt,
3068 param1,
3069 param2,
3070 });
3071 }
3072 let r = circle.radius();
3073 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3074 curves.push(IntersectionCurve { curve, points });
3075 }
3076
3077 Ok(Some(curves))
3078}
3079
3080fn off_axis_sphere_cylinder(
3089 sphere: &SphericalSurface,
3090 cyl: &CylindricalSurface,
3091 sphere_first: bool,
3092) -> Option<Vec<IntersectionCurve>> {
3093 let (centre, radius) = (sphere.center(), sphere.radius());
3094 let axis = cyl.axis();
3095 let offset = centre - cyl.origin();
3096 let axis_distance = (offset - axis * offset.dot(axis)).length();
3097 let lin_tol = Tolerance::new().linear;
3098 if axis_distance > radius + cyl.radius() + lin_tol
3099 || axis_distance + radius < cyl.radius() - lin_tol
3100 {
3101 return Some(Vec::new());
3102 }
3103 let roots = |u: f64| {
3104 let q = cyl.evaluate(u, 0.0) - centre;
3105 ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
3106 };
3107 let samples = ruling_samples(cyl, &roots);
3108 let loops = if samples.iter().all(Option::is_some) {
3109 closed_ruling_loops(cyl, &roots, &samples)
3110 } else {
3111 partial_ruling_loops(cyl, &roots, &samples)
3112 };
3113 if loops.is_empty() {
3114 return None;
3115 }
3116 Some(fit_ruling_loops(&loops, |p| {
3117 in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
3118 }))
3119}
3120
3121const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
3124 if a_first { (a, b) } else { (b, a) }
3125}
3126
3127fn parallel_cylinders(
3137 c1: &CylindricalSurface,
3138 c2: &CylindricalSurface,
3139 v_range_1: Option<(f64, f64)>,
3140 v_range_2: Option<(f64, f64)>,
3141) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3142 let axis = c1.axis();
3143 let delta = c2.origin() - c1.origin();
3144 let along = delta.dot(axis);
3145 let across = delta - axis * along;
3146 let d = across.length();
3147 let (r1, r2) = (c1.radius(), c2.radius());
3148 let flip = c2.axis().dot(axis);
3150 let ranges = [
3151 v_range_1,
3152 v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
3153 ];
3154 let (lo, hi) = ranges
3155 .into_iter()
3156 .flatten()
3157 .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
3158 (lo.max(a.min(b)), hi.min(a.max(b)))
3159 });
3160 if !lo.is_finite() || !hi.is_finite() {
3161 return Ok(None);
3162 }
3163 let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
3164 if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
3165 return Ok(Some(Vec::new()));
3166 }
3167 let toward = across * (1.0 / d);
3168 let side = axis.cross(toward);
3169 let x = r2.mul_add(-r2, d.mul_add(d, r1 * r1)) / (2.0 * d);
3170 let y = r1.mul_add(r1, -(x * x)).max(0.0).sqrt();
3171 let linear = Tolerance::new().linear;
3172 let feet = if 2.0 * y <= linear {
3173 vec![toward * x]
3174 } else {
3175 vec![toward * x + side * y, toward * x - side * y]
3176 };
3177 let on_second = |p: Point3| {
3178 let w = p - c2.origin();
3179 ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
3180 };
3181 let mut rulings = Vec::with_capacity(feet.len());
3182 for foot in feet {
3183 let base = c1.origin() + foot;
3184 let (from, to) = (base + axis * lo, base + axis * hi);
3185 if !on_second(from) || !on_second(to) {
3186 return Ok(None);
3187 }
3188 rulings.push(ruling_segment(from, to, |p| {
3189 (c1.project_point(p), c2.project_point(p))
3190 })?);
3191 }
3192 Ok(Some(rulings))
3193}
3194
3195fn ruling_segment(
3198 from: Point3,
3199 to: Point3,
3200 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3201) -> Result<IntersectionCurve, MathError> {
3202 let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
3203 let points = [from, from + (to - from) * 0.5, to]
3204 .into_iter()
3205 .map(|point| {
3206 let (param1, param2) = params(point);
3207 IntersectionPoint {
3208 point,
3209 param1,
3210 param2,
3211 }
3212 })
3213 .collect();
3214 Ok(IntersectionCurve { curve, points })
3215}
3216
3217#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
3231fn algebraic_cylinder_cylinder(
3232 c1: &CylindricalSurface,
3233 c2: &CylindricalSurface,
3234) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3235 if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
3236 return Ok(Some(halves));
3237 }
3238 let alpha = c1.axis().dot(c2.axis());
3239 let a_coeff = 1.0 - alpha * alpha;
3240
3241 if a_coeff.abs() < 1e-12 {
3243 return Ok(None);
3244 }
3245
3246 let r1 = c1.radius();
3247 let r2 = c2.radius();
3248 let o1 = c1.origin();
3249 let o2 = c2.origin();
3250 let a1 = c1.axis();
3251 let a2 = c2.axis();
3252
3253 let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
3256 let cross = a1.cross(a2);
3257 let cross_len = cross.length();
3258 if cross_len > 1e-12 {
3259 let axis_dist = delta.dot(cross).abs() / cross_len;
3260 if axis_dist > r1 + r2 + Tolerance::new().linear {
3261 return Ok(Some(vec![])); }
3263 }
3264
3265 let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
3271 let (o, a, radius) = (other.origin(), other.axis(), other.radius());
3272 let alpha = sweep.axis().dot(a);
3273 let quad = 1.0 - alpha * alpha;
3274 let (axis, sweep) = (sweep.axis(), sweep.clone());
3275 move |u: f64| {
3276 let q = sweep.evaluate(u, 0.0) - o;
3277 let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
3278 let b = 2.0 * (q_a1 - alpha * q_a2);
3279 let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
3280 ruling_quadratic(quad, b, c)
3281 }
3282 };
3283 let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
3284 let samples1 = ruling_samples(c1, &roots1);
3285 let loops = if samples1.iter().all(Option::is_some) {
3286 closed_ruling_loops(c1, &roots1, &samples1)
3287 } else {
3288 let samples2 = ruling_samples(c2, &roots2);
3289 if samples2.iter().all(Option::is_some) {
3290 closed_ruling_loops(c2, &roots2, &samples2)
3291 } else if samples1.iter().any(Option::is_some) {
3292 partial_ruling_loops(c1, &roots1, &samples1)
3293 } else {
3294 partial_ruling_loops(c2, &roots2, &samples2)
3295 }
3296 };
3297 if loops.is_empty() {
3298 return Ok(None);
3299 }
3300 Ok(Some(fit_ruling_loops(&loops, |p| {
3301 (c1.project_point(p), c2.project_point(p))
3302 })))
3303}
3304
3305fn ruling_cone_cylinder(
3312 cone: &ConicalSurface,
3313 cyl: &CylindricalSurface,
3314 cone_first: bool,
3315) -> Option<Vec<IntersectionCurve>> {
3316 let (sin_t, cos_t) = cone.half_angle().sin_cos();
3317 if sin_t < 1e-12 || cos_t < 1e-12 {
3318 return None;
3319 }
3320 let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
3321 let s = 1.0 / (sin_t * sin_t);
3322 let alpha = w.dot(d);
3323 let quad = 1.0 - s * alpha * alpha;
3324 if quad.abs() < 1e-9 {
3325 return None;
3326 }
3327 let roots = |u: f64| {
3328 let delta = cyl.evaluate(u, 0.0) - apex;
3329 let (dd, dw) = (delta.dot(d), delta.dot(w));
3330 let b = 2.0 * (dw - s * dd * alpha);
3331 let c = delta.dot(delta) - s * dd * dd;
3332 ruling_quadratic(quad, b, c)
3333 };
3334 let lin_tol = Tolerance::new().linear;
3335 let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
3336 #[allow(clippy::cast_precision_loss)]
3337 let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
3338 let (disc, vp, vm) = roots(u);
3339 disc >= -lin_tol
3340 && [vp, vm]
3341 .iter()
3342 .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
3343 });
3344 if far_nappe {
3345 return None;
3346 }
3347 let samples = ruling_samples(cyl, &roots);
3348 let scan = WINDOW_SCAN * RULING_SAMPLES;
3353 #[allow(clippy::cast_precision_loss)]
3356 let meets = |k: usize| roots(TAU * ((k % scan) as f64 + 0.5) / scan as f64).0 >= -lin_tol;
3357 if let Some(start) = (0..scan).find(|&k| !meets(k)) {
3358 let mut k = start;
3359 while k < start + scan {
3360 if !meets(k) {
3361 k += 1;
3362 continue;
3363 }
3364 let first = k;
3365 while k < start + scan && meets(k) {
3366 k += 1;
3367 }
3368 let covered = (first..k)
3369 .filter(|&j| j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1 && meets(j + 1))
3370 .count();
3371 if covered < WINDOW_MIN_SAMPLES {
3372 return None;
3373 }
3374 }
3375 }
3376 let loops = if samples.iter().all(Option::is_some) {
3377 closed_ruling_loops(cyl, &roots, &samples)
3378 } else {
3379 partial_ruling_loops(cyl, &roots, &samples)
3380 };
3381 if loops.is_empty() {
3382 return None;
3383 }
3384 Some(fit_ruling_loops(&loops, |p| {
3385 in_order(cone.project_point(p), cyl.project_point(p), cone_first)
3386 }))
3387}
3388
3389fn ruling_torus_cylinder(
3399 torus: &ToroidalSurface,
3400 cyl: &CylindricalSurface,
3401 torus_first: bool,
3402) -> Option<Vec<IntersectionCurve>> {
3403 if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
3404 || torus.minor_radius() >= torus.major_radius()
3405 {
3406 return None;
3407 }
3408 let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
3409 let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
3410 let count = rows[0].len();
3411 let scan = WINDOW_SCAN * RULING_SAMPLES;
3412 #[allow(clippy::cast_precision_loss)]
3413 if count == 0
3414 || count % 2 == 1
3415 || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
3416 {
3417 return None;
3418 }
3419 let loops: Vec<Vec<Point3>> = (0..count)
3420 .map(|j| {
3421 let mut pts: Vec<Point3> = rows
3422 .iter()
3423 .enumerate()
3424 .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
3425 .collect();
3426 pts.push(pts[0]);
3427 pts
3428 })
3429 .collect();
3430 Some(fit_ruling_loops(&loops, |p| {
3431 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3432 }))
3433}
3434
3435fn ruling_cone_sphere(
3444 cone: &ConicalSurface,
3445 sphere: &SphericalSurface,
3446 cone_first: bool,
3447) -> Option<Vec<IntersectionCurve>> {
3448 let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
3449 let offset = apex - centre;
3450 let lin_tol = Tolerance::new().linear;
3451 let along = offset.dot(cone.axis());
3452 let across = (offset - cone.axis() * along).length();
3453 if across < lin_tol {
3454 return None;
3455 }
3456 let k = offset.dot(offset) - radius * radius;
3462 if radius - offset.length() > lin_tol {
3463 let exit = |u: f64| {
3464 let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
3465 let root = h.mul_add(h, -k).sqrt();
3466 cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
3467 };
3468 let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
3473 .map(|i| (ruling_u(i), exit(ruling_u(i))))
3474 .collect();
3475 for _ in 0..10 {
3476 let mut refined = Vec::with_capacity(2 * samples.len());
3477 for pair in samples.windows(2) {
3478 let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
3479 refined.push(pair[0]);
3480 let um = 0.5 * (u0 + u1);
3481 let pm = exit(um);
3482 let chord = (p1 - p0).length();
3483 if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
3484 refined.push((um, pm));
3485 }
3486 }
3487 refined.extend(samples.last().copied());
3488 if refined.len() == samples.len() {
3489 break;
3490 }
3491 samples = refined;
3492 }
3493 let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
3494 if let Some(last) = pts.last_mut() {
3495 *last = samples[0].1;
3496 }
3497 return Some(fit_ruling_loops(&[pts], |p| {
3498 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3499 }));
3500 }
3501 let crossing = |h: f64| {
3505 let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
3506 (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
3507 };
3508 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3513 if crossing(sin_a.mul_add(along, cos_a * across)).is_none()
3514 || crossing(sin_a.mul_add(along, -cos_a * across)).is_none()
3515 {
3516 return window_cone_sphere(cone, sphere, cone_first);
3517 }
3518 let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
3519 .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
3520 .collect::<Option<_>>()?;
3521 let loops: Vec<Vec<Point3>> = [0, 1]
3522 .iter()
3523 .map(|&j| {
3524 let mut pts: Vec<Point3> = rows
3525 .iter()
3526 .enumerate()
3527 .map(|(i, &(near, far))| {
3528 cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
3529 })
3530 .collect();
3531 pts.push(pts[0]);
3532 pts
3533 })
3534 .collect();
3535 Some(fit_ruling_loops(&loops, |p| {
3536 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3537 }))
3538}
3539
3540fn window_cone_sphere(
3555 cone: &ConicalSurface,
3556 sphere: &SphericalSurface,
3557 cone_first: bool,
3558) -> Option<Vec<IntersectionCurve>> {
3559 let offset = cone.apex() - sphere.center();
3560 let lin_tol = Tolerance::new().linear;
3561 if offset.length() - sphere.radius() <= lin_tol {
3562 return None;
3563 }
3564 let k = offset.dot(offset) - sphere.radius() * sphere.radius();
3565 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3566 let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
3567 let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
3568 if a < lin_tol {
3569 return None;
3570 }
3571 let reach = (-k.sqrt() - c) / a;
3572 if reach <= -1.0 {
3573 return Some(Vec::new());
3574 }
3575 if reach >= 1.0 {
3576 return None;
3577 }
3578 let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
3579 let half = std::f64::consts::PI - half;
3580 let n = RULING_SAMPLES;
3581 let mut pts: Vec<Point3> = (0..n)
3582 .map(|i| {
3583 #[allow(clippy::cast_precision_loss)]
3584 let theta = TAU * i as f64 / n as f64;
3585 let u = half.mul_add(-theta.cos(), mid);
3586 let h = a.mul_add((u - mid + std::f64::consts::PI).cos(), c);
3587 let split = h.mul_add(h, -k).max(0.0).sqrt();
3588 cone.evaluate(u, -h - split.copysign(theta.sin()))
3589 })
3590 .collect();
3591 pts.push(pts[0]);
3592 Some(fit_ruling_loops(&[pts], |p| {
3593 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3594 }))
3595}
3596
3597const WINDOW_SCAN: usize = 16;
3600const WINDOW_MIN_SAMPLES: usize = 8;
3601
3602const RULING_SAMPLES: usize = 128;
3606
3607#[allow(clippy::cast_precision_loss)]
3608fn ruling_u(i: usize) -> f64 {
3609 TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
3610}
3611
3612fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
3614 let disc = b * b - 4.0 * quad * c;
3615 let root = disc.max(0.0).sqrt();
3616 (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
3617}
3618
3619fn ruling_samples(
3623 sweep: &CylindricalSurface,
3624 roots: &impl Fn(f64) -> (f64, f64, f64),
3625) -> Vec<Option<(Point3, Point3)>> {
3626 let lin_tol = Tolerance::new().linear;
3627 (0..RULING_SAMPLES)
3628 .map(|i| {
3629 let u = ruling_u(i);
3630 let (disc, vp, vm) = roots(u);
3631 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
3632 })
3633 .collect()
3634}
3635
3636fn closed_ruling_loops(
3643 sweep: &CylindricalSurface,
3644 roots: &impl Fn(f64) -> (f64, f64, f64),
3645 samples: &[Option<(Point3, Point3)>],
3646) -> Vec<Vec<Point3>> {
3647 let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
3648 if let Some((neck, touching)) = narrowest_ruling(roots) {
3649 let count = 2 * RULING_SAMPLES;
3650 #[allow(clippy::cast_precision_loss)]
3651 (0..count)
3652 .map(|i| {
3653 let t = i as f64 / count as f64;
3654 let u = TAU.mul_add(t - 0.9 * (TAU * t).sin() / TAU, neck);
3655 let (_, vp, vm) = roots(u);
3656 if i == 0 && touching {
3657 let at = sweep.evaluate(u, 0.5 * (vp + vm));
3658 (at, at)
3659 } else {
3660 (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
3661 }
3662 })
3663 .unzip()
3664 } else {
3665 samples.iter().flatten().copied().unzip()
3666 };
3667 plus.push(plus[0]);
3668 minus.push(minus[0]);
3669 vec![plus, minus]
3670}
3671
3672fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
3680 let scan = WINDOW_SCAN * RULING_SAMPLES;
3681 #[allow(clippy::cast_precision_loss)]
3682 let step = TAU / scan as f64;
3683 let gap = |u: f64| {
3684 let (_, vp, vm) = roots(u);
3685 (vp - vm).abs()
3686 };
3687 #[allow(clippy::cast_precision_loss)]
3688 let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
3689 let widest = gaps.iter().copied().fold(0.0, f64::max);
3690 let tol = Tolerance::new().linear * (1.0 + widest);
3691 let mut necks = Vec::new();
3692 for k in 0..scan {
3693 let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
3694 if here > before || here >= after || here >= 0.25 * widest {
3695 continue;
3696 }
3697 #[allow(clippy::cast_precision_loss)]
3698 let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
3699 for _ in 0..100 {
3700 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
3701 if gap(a) < gap(b) {
3702 hi = b;
3703 } else {
3704 lo = a;
3705 }
3706 }
3707 let u = 0.5 * (lo + hi);
3708 necks.push((u, gap(u) <= tol));
3709 }
3710 match necks[..] {
3711 [neck] => Some(neck),
3712 _ => None,
3713 }
3714}
3715
3716fn partial_ruling_loops(
3721 sweep: &CylindricalSurface,
3722 roots: &impl Fn(f64) -> (f64, f64, f64),
3723 samples: &[Option<(Point3, Point3)>],
3724) -> Vec<Vec<Point3>> {
3725 let branch_point = |inside: usize, outside: usize| -> Point3 {
3726 let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
3727 if (hi - lo).abs() > std::f64::consts::PI {
3728 hi += if hi < lo { TAU } else { -TAU };
3729 }
3730 for _ in 0..60 {
3731 let mid = 0.5 * (lo + hi);
3732 if roots(mid).0 >= 0.0 {
3733 lo = mid;
3734 } else {
3735 hi = mid;
3736 }
3737 }
3738 let (_, vp, vm) = roots(lo);
3739 sweep.evaluate(lo, 0.5 * (vp + vm))
3740 };
3741 let Some(first_gap) = samples.iter().position(Option::is_none) else {
3742 return Vec::new();
3743 };
3744 let mut loops = Vec::new();
3745 let mut k = 0;
3746 while k < RULING_SAMPLES {
3747 let i = (first_gap + k) % RULING_SAMPLES;
3748 if samples[i].is_none() {
3749 k += 1;
3750 continue;
3751 }
3752 let start = i;
3753 let mut run = Vec::new();
3754 while k < RULING_SAMPLES {
3755 let j = (first_gap + k) % RULING_SAMPLES;
3756 let Some(pair) = samples[j] else { break };
3757 run.push(pair);
3758 k += 1;
3759 }
3760 let end = (start + run.len() - 1) % RULING_SAMPLES;
3761 let head = branch_point(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
3762 let tail = branch_point(end, (end + 1) % RULING_SAMPLES);
3763 let mut pts = vec![head];
3764 pts.extend(run.iter().map(|p| p.0));
3765 pts.push(tail);
3766 pts.extend(run.iter().rev().map(|p| p.1));
3767 pts.push(head);
3768 loops.push(pts);
3769 }
3770 loops
3771}
3772
3773fn fit_ruling_loops(
3776 loops: &[Vec<Point3>],
3777 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3778) -> Vec<IntersectionCurve> {
3779 let mut curves = Vec::new();
3780 for pts in loops {
3781 if pts.len() < 4 {
3782 continue;
3783 }
3784 let ipts: Vec<IntersectionPoint> = pts
3785 .iter()
3786 .map(|&p| {
3787 let (param1, param2) = params(p);
3788 IntersectionPoint {
3789 point: p,
3790 param1,
3791 param2,
3792 }
3793 })
3794 .collect();
3795 let degree = 3.min(pts.len() - 1);
3796 if let Ok(curve) = interpolate(pts, degree) {
3797 curves.push(IntersectionCurve {
3798 curve,
3799 points: ipts,
3800 });
3801 }
3802 }
3803 curves
3804}
3805
3806#[allow(clippy::unnecessary_wraps)]
3832fn algebraic_parallel_cone_cylinder(
3833 cone: &ConicalSurface,
3834 cyl: &CylindricalSurface,
3835 v_range_cone: Option<(f64, f64)>,
3836 v_range_cyl: Option<(f64, f64)>,
3837) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3838 let axis = cone.axis();
3839 if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
3840 return Ok(None); }
3842
3843 let apex = cone.apex();
3844 let delta = cyl.origin() - apex;
3845 let along = delta.dot(axis);
3846 let perp = delta - axis * along;
3847 let d = perp.length();
3848 if d < 1e-9 {
3849 return Ok(None); }
3851
3852 let (e1, e2) = (cone.x_axis(), cone.y_axis());
3853 let phi0 = perp.dot(e2).atan2(perp.dot(e1));
3854
3855 let (sin_t, cos_t) = cone.half_angle().sin_cos();
3856 if cos_t < 1e-12 || sin_t < 1e-12 {
3857 return Ok(None);
3858 }
3859 let r = cyl.radius();
3860
3861 let mut v_min = (d - r).abs() / cos_t;
3863 let mut v_max = (d + r) / cos_t;
3864 if v_max <= v_min {
3865 return Ok(Some(vec![]));
3866 }
3867
3868 let mut lo = v_min;
3874 let mut hi = v_max;
3875 if let Some((a, b)) = v_range_cone {
3880 let (a, b) = if a <= b { (a, b) } else { (b, a) };
3881 lo = lo.max(a);
3882 hi = hi.min(b);
3883 }
3884 if let Some((a, b)) = v_range_cyl {
3885 let flip = cyl.axis().dot(axis);
3888 let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
3889 let (a, b) = (to_cone_v(a), to_cone_v(b));
3890 let (a, b) = if a <= b { (a, b) } else { (b, a) };
3891 lo = lo.max(a);
3892 hi = hi.min(b);
3893 }
3894 let (turn_lo, turn_hi) = (v_min, v_max);
3895 v_min = lo.max(v_min);
3896 v_max = hi.min(v_max);
3897 if v_max - v_min <= 1e-12 {
3898 return Ok(Some(vec![]));
3899 }
3900 let slack = Tolerance::new().linear;
3908 #[allow(clippy::cast_precision_loss)]
3909 let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
3910 if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
3911 let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
3912 .map(|i| {
3913 let (sin_u, cos_u) = ruling_u(i).sin_cos();
3914 let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
3915 let off = foot - apex;
3916 let across = off - axis * off.dot(axis);
3917 apex + across + axis * (across.length() * sin_t / cos_t)
3918 })
3919 .collect();
3920 pts.push(pts[0]);
3921 return Ok(Some(fit_ruling_loops(&[pts], |p| {
3922 (cone.project_point(p), cyl.project_point(p))
3923 })));
3924 }
3925
3926 let n_samples = 128;
3927 let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
3928 let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
3929 #[allow(clippy::cast_precision_loss)]
3930 for i in 0..=n_samples {
3931 let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
3932 let rho = v * cos_t;
3933 if rho < 1e-12 {
3934 if (d - r).abs() < 1e-12 {
3942 let apex = cone.evaluate(phi0, v);
3943 plus.push(apex);
3944 minus.push(apex);
3945 }
3946 continue;
3947 }
3948 let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
3949 let alpha = cos_alpha.acos();
3950 plus.push(cone.evaluate(phi0 + alpha, v));
3951 minus.push(cone.evaluate(phi0 - alpha, v));
3952 }
3953
3954 let mut curves = Vec::new();
3955 for pts in [&plus, &minus] {
3956 if pts.len() < 4 {
3959 continue;
3960 }
3961 let ipts: Vec<IntersectionPoint> = pts
3962 .iter()
3963 .map(|&p| IntersectionPoint {
3964 point: p,
3965 param1: cone.project_point(p),
3966 param2: cyl.project_point(p),
3967 })
3968 .collect();
3969 let degree = 3.min(pts.len() - 1);
3970 match interpolate(pts, degree) {
3971 Ok(curve) => curves.push(IntersectionCurve {
3972 curve,
3973 points: ipts,
3974 }),
3975 Err(_) => return Ok(None),
3980 }
3981 }
3982
3983 Ok(Some(curves))
3984}
3985
3986fn algebraic_sphere_sphere(
3994 s1: &SphericalSurface,
3995 s2: &SphericalSurface,
3996) -> Result<Vec<IntersectionCurve>, MathError> {
3997 let c1 = s1.center();
3998 let c2 = s2.center();
3999 let r1 = s1.radius();
4000 let r2 = s2.radius();
4001
4002 let delta = c2 - c1;
4003 let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
4004 let d = d_sq.sqrt();
4005
4006 if d < 1e-12 {
4007 return Ok(vec![]);
4009 }
4010
4011 if d > r1 + r2 + 1e-10 {
4013 return Ok(vec![]); }
4015 if d + r2.min(r1) + 1e-10 < r1.max(r2) {
4016 return Ok(vec![]); }
4018
4019 let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
4021
4022 let r_circle_sq = r1 * r1 - d1 * d1;
4024 if r_circle_sq < 0.0 {
4025 if r_circle_sq > -1e-10 {
4027 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4029 let tangent_pt = Point3::new(
4030 c1.x() + axis.x() * d1,
4031 c1.y() + axis.y() * d1,
4032 c1.z() + axis.z() * d1,
4033 );
4034 let ipt = IntersectionPoint {
4035 point: tangent_pt,
4036 param1: (0.0, 0.0),
4037 param2: (0.0, 0.0),
4038 };
4039 return Ok(vec![IntersectionCurve {
4041 curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
4042 points: vec![ipt],
4043 }]);
4044 }
4045 return Ok(vec![]);
4046 }
4047
4048 let r_circle = r_circle_sq.sqrt();
4049 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4050 let center = Point3::new(
4051 c1.x() + axis.x() * d1,
4052 c1.y() + axis.y() * d1,
4053 c1.z() + axis.z() * d1,
4054 );
4055
4056 let basis = Frame3::from_normal(center, axis)?;
4058 let u_dir = basis.x;
4059 let v_dir = basis.y;
4060
4061 let n_samples = 33; let mut points = Vec::with_capacity(n_samples);
4064 #[allow(clippy::cast_precision_loss)]
4065 for i in 0..n_samples {
4066 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4067 let (sin_t, cos_t) = theta.sin_cos();
4068 let pt = Point3::new(
4069 center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
4070 center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
4071 center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
4072 );
4073 points.push(IntersectionPoint {
4074 point: pt,
4075 param1: (0.0, 0.0),
4076 param2: (0.0, 0.0),
4077 });
4078 }
4079
4080 let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
4081
4082 Ok(vec![IntersectionCurve { curve, points }])
4083}
4084
4085#[allow(clippy::too_many_arguments)]
4091fn correct_to_intersection(
4092 a: &AnalyticSurface<'_>,
4093 b: &AnalyticSurface<'_>,
4094 surf_a: &dyn Fn(f64, f64) -> Point3,
4095 norm_a: &dyn Fn(f64, f64) -> Vec3,
4096 surf_b: &dyn Fn(f64, f64) -> Point3,
4097 norm_b: &dyn Fn(f64, f64) -> Vec3,
4098 point: Point3,
4099 u_range_a: (f64, f64),
4100 v_range_a: (f64, f64),
4101 u_range_b: (f64, f64),
4102 v_range_b: (f64, f64),
4103 max_iters: usize,
4104) -> Point3 {
4105 let mut p = point;
4106 for _ in 0..max_iters {
4107 let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
4108 let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
4109 let pa = surf_a(ua, va);
4110 let pb = surf_b(ub, vb);
4111 let na = norm_a(ua, va);
4112 let nb = norm_b(ub, vb);
4113 let pv = Vec3::new(p.x(), p.y(), p.z());
4114
4115 let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
4116 let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
4117
4118 if da.abs() < 1e-7 && db.abs() < 1e-7 {
4119 break;
4120 }
4121
4122 let t = na.cross(nb);
4123 let t_len = t.length();
4124 if t_len < 1e-10 {
4125 return Point3::new(
4127 (pa.x() + pb.x()) * 0.5,
4128 (pa.y() + pb.y()) * 0.5,
4129 (pa.z() + pb.z()) * 0.5,
4130 );
4131 }
4132 let t_hat = t * (1.0 / t_len);
4133
4134 let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4136 - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4137 + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
4138 if det.abs() < 1e-15 {
4139 return Point3::new(
4140 (pa.x() + pb.x()) * 0.5,
4141 (pa.y() + pb.y()) * 0.5,
4142 (pa.z() + pb.z()) * 0.5,
4143 );
4144 }
4145 let inv = 1.0 / det;
4146 let dx = inv
4148 * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4149 + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
4150 let dy = inv
4151 * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4152 - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
4153 let dz = inv
4154 * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
4155 + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
4156 let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
4157
4158 let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
4161 let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
4162 let pc_a = surf_a(uc, vc);
4163 let pc_b = surf_b(ud, vd);
4164 let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
4165 let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
4166 .dot(norm_a(uc, vc))
4167 .abs();
4168 let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
4169 .dot(norm_b(ud, vd))
4170 .abs();
4171 if da_new > da.abs() && db_new > db.abs() {
4172 return p;
4173 }
4174
4175 p = candidate;
4176 }
4177 p
4178}
4179
4180#[allow(clippy::too_many_arguments)]
4186fn march_analytic_intersection(
4187 a: &AnalyticSurface<'_>,
4188 b: &AnalyticSurface<'_>,
4189 surf_a: &dyn Fn(f64, f64) -> Point3,
4190 norm_a: &dyn Fn(f64, f64) -> Vec3,
4191 surf_b: &dyn Fn(f64, f64) -> Point3,
4192 norm_b: &dyn Fn(f64, f64) -> Vec3,
4193 seed: Point3,
4194 u_range_a: (f64, f64),
4195 v_range_a: (f64, f64),
4196 u_range_b: (f64, f64),
4197 v_range_b: (f64, f64),
4198 initial_step: f64,
4199 u_periodic_a: bool,
4200 u_periodic_b: bool,
4201 region: Option<Aabb3>,
4202) -> Vec<Point3> {
4203 let max_steps = 500;
4204 let h_min = 1e-6;
4205 let h_max = initial_step * 4.0;
4206 let closure_dist = initial_step * 5.0;
4210 let max_angle = 10.0_f64.to_radians();
4212 let min_angle = 2.0_f64.to_radians();
4213
4214 let mut forward = Vec::new();
4216 let mut backward = Vec::new();
4218
4219 for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
4220 let mut current = seed;
4221 let mut h = initial_step;
4222 let mut prev_tangent: Option<Vec3> = None;
4223
4224 for _ in 0..max_steps {
4225 let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
4226 let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
4227
4228 let na = norm_a(ua, va);
4229 let nb = norm_b(ub, vb);
4230
4231 let tangent = na.cross(nb);
4232 let t_len = tangent.length();
4233 if t_len < 1e-10 {
4234 break;
4235 }
4236 let t_dir = tangent * (direction / t_len);
4237
4238 if let Some(prev_t) = prev_tangent {
4240 let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
4241 let angle = cos_angle.acos();
4242 if angle > max_angle && h > h_min {
4243 h = (h * 0.5).max(h_min);
4244 } else if angle < min_angle {
4245 h = (h * 2.0).min(h_max);
4246 }
4247 }
4248 prev_tangent = Some(t_dir);
4249
4250 let next = Point3::new(
4251 h.mul_add(t_dir.x(), current.x()),
4252 h.mul_add(t_dir.y(), current.y()),
4253 h.mul_add(t_dir.z(), current.z()),
4254 );
4255
4256 let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
4257 let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
4258
4259 let pa = surf_a(ua2, va2);
4260 let pb = surf_b(ub2, vb2);
4261 let mid = Point3::new(
4262 (pa.x() + pb.x()) * 0.5,
4263 (pa.y() + pb.y()) * 0.5,
4264 (pa.z() + pb.z()) * 0.5,
4265 );
4266 let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
4267 || va2 <= v_range_a.0
4268 || va2 >= v_range_a.1;
4269 let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
4270 || vb2 <= v_range_b.0
4271 || vb2 >= v_range_b.1;
4272
4273 if out_a || out_b {
4274 break;
4275 }
4276 if region.is_some_and(|r| !r.contains_point(mid)) {
4277 points.push(mid);
4278 break;
4279 }
4280
4281 let dist_to_seed = (mid - seed).length();
4285 if points.len() > 10 && dist_to_seed < closure_dist {
4286 points.push(seed);
4287 break;
4288 }
4289
4290 points.push(mid);
4291 current = mid;
4292 }
4293 }
4294
4295 backward.reverse();
4297 let mut result = backward;
4298 result.push(seed);
4299 result.append(&mut forward);
4300
4301 for pt in &mut result {
4303 *pt = correct_to_intersection(
4304 a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
4305 5,
4306 );
4307 }
4308
4309 result
4310}
4311
4312fn project_analytic(
4316 surface: &AnalyticSurface<'_>,
4317 point: Point3,
4318 u_range: (f64, f64),
4319 v_range: (f64, f64),
4320) -> (f64, f64) {
4321 match surface {
4322 AnalyticSurface::Cylinder(cyl) => {
4323 let (u, v) = cyl.project_point(point);
4324 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4325 }
4326 AnalyticSurface::Sphere(sphere) => {
4327 let (u, v) = sphere.project_point(point);
4328 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4329 }
4330 AnalyticSurface::Cone(cone) => {
4331 let (u, v) = cone.project_point(point);
4332 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4333 }
4334 AnalyticSurface::Torus(torus) => {
4335 let (u, v) = torus.project_point(point);
4336 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4337 }
4338 }
4339}
4340
4341fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
4345 matches!(
4346 surface,
4347 AnalyticSurface::Cylinder(_)
4348 | AnalyticSurface::Cone(_)
4349 | AnalyticSurface::Sphere(_)
4350 | AnalyticSurface::Torus(_)
4351 )
4352}
4353
4354#[allow(clippy::type_complexity)]
4356fn surface_closures<'a>(
4357 surface: &'a AnalyticSurface<'a>,
4358) -> (
4359 Box<dyn Fn(f64, f64) -> Point3 + 'a>,
4360 Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
4361 (f64, f64),
4362 (f64, f64),
4363) {
4364 match surface {
4365 AnalyticSurface::Cylinder(cyl) => (
4366 Box::new(|u, v| cyl.evaluate(u, v)),
4367 Box::new(|u, v| cyl.normal(u, v)),
4368 (0.0, TAU),
4369 (-1.0, 1.0),
4370 ),
4371 AnalyticSurface::Cone(cone) => (
4372 Box::new(|u, v| cone.evaluate(u, v)),
4373 Box::new(|u, v| cone.normal(u, v)),
4374 (0.0, TAU),
4375 (0.01, 2.0),
4376 ),
4377 AnalyticSurface::Sphere(sphere) => (
4378 Box::new(|u, v| sphere.evaluate(u, v)),
4379 Box::new(|u, v| sphere.normal(u, v)),
4380 (0.0, TAU),
4381 (-FRAC_PI_2, FRAC_PI_2),
4382 ),
4383 AnalyticSurface::Torus(torus) => (
4384 Box::new(|u, v| torus.evaluate(u, v)),
4385 Box::new(|u, v| torus.normal(u, v)),
4386 (0.0, TAU),
4387 (0.0, TAU),
4388 ),
4389 }
4390}
4391
4392#[cfg(test)]
4393#[allow(clippy::unwrap_used, clippy::expect_used)]
4394mod tests {
4395 use super::*;
4396 use crate::tolerance::Tolerance;
4397
4398 #[test]
4402 fn plane_cone_conic_arcs_lie_on_both_surfaces() {
4403 let half_angle = 1.1_f64;
4404 let cone = ConicalSurface::new(
4405 Point3::new(0.0, 0.0, 0.0),
4406 Vec3::new(0.0, 0.0, 1.0),
4407 half_angle,
4408 )
4409 .unwrap();
4410 let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
4411 for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
4412 let chains =
4413 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
4414 .unwrap();
4415 let chain = chains
4416 .iter()
4417 .find_map(|c| match c {
4418 ExactIntersectionCurve::Points(chain) => Some(chain),
4419 _ => None,
4420 })
4421 .expect("a parabola or hyperbola section is sampled");
4422 let (from, to) = (chain[2], chain[chain.len() - 3]);
4423 let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
4424 .unwrap()
4425 .expect("an exact arc");
4426 let (t0, t1) = arc.domain();
4427 assert!((arc.evaluate(t0) - from).length() < 1e-12);
4428 assert!((arc.evaluate(t1) - to).length() < 1e-12);
4429 for i in 0..=200 {
4430 let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
4431 let w = q - Point3::new(0.0, 0.0, 0.0);
4432 let off_plane = (normal.dot(w) - d).abs();
4433 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4434 assert!(off_plane < 1e-9, "off the plane by {off_plane}");
4435 assert!(off_cone < 1e-9, "off the cone by {off_cone}");
4436 }
4437 }
4438 }
4439
4440 #[test]
4444 fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
4445 let half_angle = 1.1_f64;
4446 let cone = ConicalSurface::new(
4447 Point3::new(0.0, 0.0, 0.0),
4448 Vec3::new(0.0, 0.0, 1.0),
4449 half_angle,
4450 )
4451 .unwrap();
4452 for shortfall in [1e-10, 3e-10, 8e-10] {
4453 let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
4454 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
4455 let chains =
4456 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
4457 .unwrap();
4458 let Some(chain) = chains.iter().find_map(|c| match c {
4459 ExactIntersectionCurve::Points(chain) => Some(chain),
4460 _ => None,
4461 }) else {
4462 continue;
4463 };
4464 let (from, to) = (chain[2], chain[chain.len() - 3]);
4465 assert!(
4466 plane_cone_conic_arc(&cone, normal, 1.0, from, from)
4467 .unwrap()
4468 .is_none(),
4469 "coincident ends"
4470 );
4471 let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
4472 continue;
4473 };
4474 let (t0, t1) = arc.domain();
4475 for i in 0..=200 {
4476 let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
4477 - Point3::new(0.0, 0.0, 0.0);
4478 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4479 assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
4480 }
4481 }
4482 }
4483
4484 #[test]
4485 fn plane_cylinder_perpendicular() {
4486 let cyl =
4487 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
4488 .unwrap();
4489
4490 let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
4492 assert!(!curves.is_empty(), "should find intersection curve");
4493 assert!(
4494 curves[0].points.len() > 10,
4495 "should have many sample points"
4496 );
4497
4498 let tol = Tolerance::loose();
4499 for pt in &curves[0].points {
4500 assert!(
4501 tol.approx_eq(pt.point.z(), 3.0),
4502 "z should be ~3.0, got {}",
4503 pt.point.z()
4504 );
4505 let r = pt.point.x().hypot(pt.point.y());
4506 assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
4507 }
4508 }
4509
4510 #[test]
4511 fn plane_sphere_equator() {
4512 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4513
4514 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4515 assert!(!curves.is_empty());
4516
4517 let tol = Tolerance::loose();
4518 for pt in &curves[0].points {
4519 assert!(
4520 tol.approx_eq(pt.point.z(), 0.0),
4521 "z should be ~0, got {}",
4522 pt.point.z()
4523 );
4524 let r = pt.point.x().hypot(pt.point.y());
4525 assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
4526 }
4527 }
4528
4529 #[test]
4530 fn plane_sphere_no_intersection() {
4531 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
4532
4533 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
4534 assert!(curves.is_empty());
4535 }
4536
4537 #[test]
4538 fn plane_cone_cross_section() {
4539 let cone = ConicalSurface::new(
4540 Point3::new(0.0, 0.0, 0.0),
4541 Vec3::new(0.0, 0.0, 1.0),
4542 std::f64::consts::FRAC_PI_4,
4543 )
4544 .unwrap();
4545
4546 let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
4547 assert!(!curves.is_empty(), "should find intersection with cone");
4548 }
4549
4550 #[test]
4557 fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
4558 let c1 = ConicalSurface::new(
4559 Point3::new(
4560 -16.999_999_999_999_975,
4561 -16.999_999_999_999_975,
4562 5.849_999_999_999_951,
4563 ),
4564 Vec3::new(0.0, 0.0, -1.0),
4565 0.785_398_163_397_433_5,
4566 )
4567 .unwrap();
4568 let c2 = ConicalSurface::new(
4569 Point3::new(
4570 -16.750_000_000_000_036,
4571 -16.750_000_000_000_018,
4572 0.749_999_999_999_881,
4573 ),
4574 Vec3::new(0.0, 0.0, 1.0),
4575 0.785_398_163_397_467_6,
4576 )
4577 .unwrap();
4578
4579 let curves = exact_cone_cone(&c1, &c2)
4580 .unwrap()
4581 .expect("offset parallel equal-angle cones must take the radical-plane path");
4582 assert_eq!(curves.len(), 1, "expected exactly one section conic");
4583 assert!(
4584 matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
4585 "expected an ellipse section, got {:?}",
4586 curves[0]
4587 );
4588 let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
4589 return;
4590 };
4591
4592 for i in 0..16 {
4596 let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
4597 for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
4598 let rel = p - cone.apex();
4599 let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
4600 let axial = rel_v.dot(cone.axis());
4601 let radial = (rel_v - cone.axis() * axial).length();
4602 assert!(
4603 axial > 0.0,
4604 "{label}: sample on phantom nappe (axial {axial})"
4605 );
4606 let expect = cone.half_angle().tan() * axial;
4607 assert!(
4608 (radial - expect).abs() < 1e-9,
4609 "{label}: sample off surface by {}",
4610 (radial - expect).abs()
4611 );
4612 }
4613 }
4614 }
4615
4616 #[test]
4620 fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
4621 let c1 = ConicalSurface::new(
4622 Point3::new(0.0, 0.0, 5.0),
4623 Vec3::new(0.0, 0.0, -1.0),
4624 std::f64::consts::FRAC_PI_4,
4625 )
4626 .unwrap();
4627 let c2 = ConicalSurface::new(
4628 Point3::new(0.25, 0.25, 20.0),
4629 Vec3::new(0.0, 0.0, 1.0),
4630 std::f64::consts::FRAC_PI_4,
4631 )
4632 .unwrap();
4633 let curves = exact_cone_cone(&c1, &c2)
4634 .unwrap()
4635 .expect("radical-plane path");
4636 assert!(curves.is_empty(), "disjoint nappes must yield no curves");
4637 }
4638
4639 #[test]
4642 fn offset_parallel_cones_with_unequal_angles_defer() {
4643 let c1 = ConicalSurface::new(
4644 Point3::new(0.0, 0.0, 5.0),
4645 Vec3::new(0.0, 0.0, -1.0),
4646 std::f64::consts::FRAC_PI_4,
4647 )
4648 .unwrap();
4649 let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
4650 .unwrap();
4651 assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
4652 }
4653
4654 fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
4658 let cone = ConicalSurface::new(
4659 Point3::new(0.0, 0.0, 0.0),
4660 Vec3::new(0.0, 0.0, 1.0),
4661 std::f64::consts::FRAC_PI_4,
4662 )
4663 .unwrap();
4664 let (s, c) = 40.0_f64.to_radians().sin_cos();
4665 let tube =
4666 CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
4667 (cone, tube)
4668 }
4669
4670 #[test]
4671 fn marcher_keeps_to_its_region() {
4672 let (cone, tube) = cone_and_tilted_tube();
4673 let run = |region: Option<Aabb3>| {
4674 let (a, b) = (
4675 AnalyticSurface::Cone(&cone),
4676 AnalyticSurface::Cylinder(&tube),
4677 );
4678 let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
4679 match region {
4680 Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
4681 None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
4682 }
4683 .unwrap()
4684 };
4685 assert!(!run(None).is_empty());
4686 let near = Aabb3 {
4687 min: Point3::new(-0.5, -2.0, 0.8),
4688 max: Point3::new(0.7, -0.7, 2.0),
4689 };
4690 let curves = run(Some(near));
4691 assert!(!curves.is_empty(), "the loop through the region is kept");
4692 let reach = near.expanded(0.6);
4694 for curve in &curves {
4695 assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
4696 }
4697 let away = Aabb3 {
4698 min: Point3::new(5.0, 5.0, 5.0),
4699 max: Point3::new(6.0, 6.0, 6.0),
4700 };
4701 assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
4702 }
4703
4704 #[test]
4705 fn coaxial_cones_cross_at_single_circle() {
4706 let outer = ConicalSurface::new(
4711 Point3::new(0.0, 0.0, 50.0),
4712 Vec3::new(0.0, 0.0, -1.0),
4713 5.0_f64.atan(),
4714 )
4715 .unwrap();
4716 let inner = ConicalSurface::new(
4717 Point3::new(0.0, 0.0, 90.0),
4718 Vec3::new(0.0, 0.0, -1.0),
4719 10.0_f64.atan(),
4720 )
4721 .unwrap();
4722
4723 let curves = intersect_analytic_analytic_bounded(
4724 AnalyticSurface::Cone(&outer),
4725 AnalyticSurface::Cone(&inner),
4726 32,
4727 None,
4728 None,
4729 )
4730 .unwrap();
4731
4732 assert_eq!(
4733 curves.len(),
4734 1,
4735 "coaxial cones crossing at one circle must yield exactly one curve, got {}",
4736 curves.len()
4737 );
4738 for p in &curves[0].points {
4739 let r = p.point.x().hypot(p.point.y());
4740 assert!(
4741 (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
4742 "intersection point off the expected z=10,r=8 circle: {:?}",
4743 p.point
4744 );
4745 }
4746 }
4747
4748 #[test]
4749 fn plane_torus_cross_section() {
4750 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
4751
4752 let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4753 assert!(
4754 !curves.is_empty(),
4755 "should find intersection curves with torus"
4756 );
4757 }
4758
4759 #[test]
4762 fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
4763 for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
4764 let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
4765 for z in [3.0 - minor, 3.0 + minor] {
4766 let exact = exact_plane_analytic(
4767 AnalyticSurface::Torus(&torus),
4768 Vec3::new(0.0, 0.0, 1.0),
4769 z,
4770 )
4771 .unwrap();
4772 assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
4773 let circle = match &exact[0] {
4774 ExactIntersectionCurve::Circle(c) => Some(c),
4775 _ => None,
4776 };
4777 let c = circle.expect("a circle");
4778 assert!((c.radius() - major).abs() < 1e-12);
4779 assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
4780
4781 let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
4782 assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
4783 }
4784 let single = |normal: Vec3, d: f64| {
4786 matches!(
4787 exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
4788 .unwrap()
4789 .as_slice(),
4790 [ExactIntersectionCurve::Circle(_)]
4791 )
4792 };
4793 assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
4794 }
4795 }
4796
4797 #[test]
4801 fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
4802 let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
4803 let level = Vec3::new(0.0, 0.0, 1.0);
4804 let curves =
4805 |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
4806 assert!(matches!(
4807 curves(3.0 + 100.1).as_slice(),
4808 [ExactIntersectionCurve::Circle(_)]
4809 ));
4810 let inside = curves(3.0 + 100.1 - 4e-7);
4811 assert!(!matches!(
4812 inside.as_slice(),
4813 [ExactIntersectionCurve::Circle(_)]
4814 ));
4815 }
4816
4817 fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
4820 let rho = p.x().hypot(p.y());
4821 ((rho - major).hypot(p.z())) - minor
4822 }
4823
4824 #[test]
4830 fn oblique_cone_cylinder_traces_curves_on_both() {
4831 use crate::traits::ParametricCurve;
4832 let cone = ConicalSurface::new(
4836 Point3::new(0.0, 0.0, 3.0),
4837 Vec3::new(0.0, 0.0, -1.0),
4838 2.0_f64.atan(),
4839 )
4840 .unwrap();
4841 for (x0, loops) in [(0.5, 1), (0.0, 2)] {
4842 let cyl =
4843 CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
4844 .unwrap();
4845 for cone_first in [true, false] {
4846 let (a, b) = if cone_first {
4847 (
4848 AnalyticSurface::Cone(&cone),
4849 AnalyticSurface::Cylinder(&cyl),
4850 )
4851 } else {
4852 (
4853 AnalyticSurface::Cylinder(&cyl),
4854 AnalyticSurface::Cone(&cone),
4855 )
4856 };
4857 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
4858 assert_eq!(curves.len(), loops, "x0 {x0}: loops");
4859 for c in &curves {
4860 let (t0, t1) = c.curve.domain();
4861 for k in 0..=64 {
4862 let t = (t1 - t0).mul_add(f64::from(k) / 64.0, t0);
4863 let p = ParametricCurve::evaluate(&c.curve, t);
4864 let rod = (p.x() - x0).hypot(p.z() - 1.0);
4867 assert!(
4868 (rod - 0.6).abs() < 1e-4,
4869 "x0 {x0}: off the rod by {}",
4870 rod - 0.6
4871 );
4872 let cone_r = p.x().hypot(p.y());
4873 assert!(
4874 (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
4875 "x0 {x0}: off the cone at {p:?}"
4876 );
4877 }
4878 }
4879 }
4880 }
4881 }
4882
4883 #[test]
4884 fn a_rod_through_a_rings_tube_traces_four_loops() {
4885 use crate::traits::ParametricCurve;
4886 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
4887 let rod =
4890 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
4891 .unwrap();
4892 let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
4893 assert_eq!(curves.len(), 4);
4894 for c in &curves {
4895 let (t0, t1) = c.curve.domain();
4896 for k in 0..=64 {
4897 let p =
4898 ParametricCurve::evaluate(&c.curve, (t1 - t0).mul_add(f64::from(k) / 64.0, t0));
4899 let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
4900 let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
4901 assert!(
4902 on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
4903 "off by {on_rod}, {on_ring}"
4904 );
4905 }
4906 }
4907 let high =
4909 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
4910 .unwrap();
4911 assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
4912 let grazing =
4914 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
4915 .unwrap();
4916 assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
4917 let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
4919 let thin =
4920 CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
4921 .unwrap();
4922 assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
4923 }
4924
4925 #[test]
4926 fn a_pin_through_a_ball_traces_two_loops() {
4927 use crate::traits::ParametricCurve;
4928 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4929 let half = 0.08_f64.atan();
4932 let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
4933 let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
4934 for cone_first in [true, false] {
4935 let (a, b) = if cone_first {
4936 (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
4937 } else {
4938 (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
4939 };
4940 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
4941 assert_eq!(curves.len(), 2, "entry and exit loops");
4942 for c in &curves {
4943 let (t0, t1) = c.curve.domain();
4944 for k in 0..=64 {
4945 let p = ParametricCurve::evaluate(
4946 &c.curve,
4947 (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
4948 );
4949 let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
4950 let axial = apex.z() - p.z();
4951 let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
4952 assert!(
4953 on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
4954 "off by {on_ball}, {on_pin}"
4955 );
4956 }
4957 }
4958 }
4959 let coaxial =
4964 ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
4965 .unwrap();
4966 assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
4967 let aside = ConicalSurface::new(
4968 Point3::new(2.8, 0.0, 10.0),
4969 Vec3::new(0.0, 0.0, -1.0),
4970 FRAC_PI_2 - half,
4971 )
4972 .unwrap();
4973 assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
4974 let holding = ConicalSurface::new(
4975 Point3::new(1.0, 0.5, 1.0),
4976 Vec3::new(0.0, 0.0, -1.0),
4977 FRAC_PI_2 - half,
4978 )
4979 .unwrap();
4980 assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
4981 let away = ConicalSurface::new(
4982 Point3::new(1.0, 0.5, 10.0),
4983 Vec3::new(0.0, 0.0, 1.0),
4984 FRAC_PI_2 - half,
4985 )
4986 .unwrap();
4987 assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
4988 let step = TAU / 2048.0;
4992 let grazed =
4993 SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
4994 .unwrap();
4995 let wide =
4996 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
4997 assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
4998 }
4999
5000 #[test]
5001 fn a_ball_beside_a_cone_meets_it_in_one_loop() {
5002 use crate::traits::ParametricCurve;
5003 let cone = ConicalSurface::new(
5005 Point3::new(0.0, 0.0, 3.0),
5006 Vec3::new(0.0, 0.0, -1.0),
5007 2.0_f64.atan(),
5008 )
5009 .unwrap();
5010 for (centre, radius) in [
5011 (Point3::new(1.0, 0.8, 1.2), 1.1),
5012 (Point3::new(1.5, 0.0, 0.0), 0.8),
5013 ] {
5014 let ball = SphericalSurface::new(centre, radius).unwrap();
5015 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5016 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5017 let (t0, t1) = curves[0].curve.domain();
5018 for k in 0..=64 {
5019 let p = ParametricCurve::evaluate(
5020 &curves[0].curve,
5021 (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
5022 );
5023 let on_ball = (p - centre).length() - radius;
5024 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5025 assert!(
5026 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
5027 "ball at {centre:?}: off by {on_ball}, {on_cone}"
5028 );
5029 }
5030 }
5031 let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
5033 assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
5034 let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
5035 assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
5036 }
5037
5038 #[test]
5039 fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
5040 use crate::traits::ParametricCurve;
5041 let cone = ConicalSurface::new(
5042 Point3::new(0.0, 0.0, 3.0),
5043 Vec3::new(0.0, 0.0, -1.0),
5044 2.0_f64.atan(),
5045 )
5046 .unwrap();
5047 for (centre, radius) in [
5050 (Point3::new(0.5, 0.0, 2.5), 2.0),
5051 (Point3::new(-0.4, 0.3, 2.0), 1.5),
5052 (Point3::new(0.0, 0.8, 3.0), 0.8001),
5053 (Point3::new(0.0, 0.8, 3.0), 0.800_001),
5054 ] {
5055 let ball = SphericalSurface::new(centre, radius).unwrap();
5056 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5057 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5058 let (t0, t1) = curves[0].curve.domain();
5059 for k in 0..=4096 {
5060 let p = ParametricCurve::evaluate(
5061 &curves[0].curve,
5062 (t1 - t0).mul_add(f64::from(k) / 4096.0, t0),
5063 );
5064 let on_ball = (p - centre).length() - radius;
5065 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5066 assert!(
5067 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
5068 "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
5069 );
5070 }
5071 }
5072 }
5073
5074 #[test]
5075 fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
5076 let t = 2.0_f64.atan();
5077 let cone =
5078 ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
5079 let through_apex =
5081 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5082 .unwrap();
5083 assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
5084 let generator = Vec3::new(t.cos(), 0.0, -t.sin());
5086 let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
5087 assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
5088 let pin =
5091 ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
5092 let tube =
5093 CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
5094 .unwrap();
5095 assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
5096 }
5097
5098 #[test]
5099 fn parallel_cone_cylinder_gives_two_exact_branches() {
5100 use crate::traits::ParametricCurve;
5101 let cone = ConicalSurface::new(
5102 Point3::new(-5.45, -36.55, -4.85),
5103 Vec3::new(0.0, 0.0, 1.0),
5104 std::f64::consts::FRAC_PI_4,
5105 )
5106 .unwrap();
5107 let cyl = CylindricalSurface::new(
5108 Point3::new(-8.0, -34.0, -5.0),
5109 Vec3::new(0.0, 0.0, 1.0),
5110 4.45,
5111 )
5112 .unwrap();
5113 let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
5115 let curves = intersect_analytic_analytic_bounded(
5116 AnalyticSurface::Cone(&cone),
5117 AnalyticSurface::Cylinder(&cyl),
5118 32,
5119 Some(v_hint),
5120 Some((0.0, 2.5)),
5121 )
5122 .unwrap();
5123
5124 assert_eq!(curves.len(), 2, "expected exactly the two branches");
5125 for c in &curves {
5126 let (t0, t1) = c.curve.domain();
5127 for k in 0..=32 {
5128 let t = (t1 - t0).mul_add(f64::from(k) / 32.0, t0);
5129 let p = ParametricCurve::evaluate(&c.curve, t);
5130 let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
5132 assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
5133 let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
5135 assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
5136 assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
5138 }
5139 }
5140 }
5141
5142 #[test]
5143 fn parallel_rod_through_a_cones_wall_closes_one_loop() {
5144 use crate::traits::ParametricCurve;
5145 let cone = ConicalSurface::new(
5147 Point3::new(0.0, 0.0, 3.0),
5148 Vec3::new(0.0, 0.0, -1.0),
5149 2.0_f64.atan(),
5150 )
5151 .unwrap();
5152 for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
5154 let rod =
5155 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5156 .unwrap();
5157 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5158 .unwrap()
5159 .unwrap();
5160 assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
5161 let (t0, t1) = curves[0].curve.domain();
5162 let (first, last) = (
5163 ParametricCurve::evaluate(&curves[0].curve, t0),
5164 ParametricCurve::evaluate(&curves[0].curve, t1),
5165 );
5166 assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
5167 for k in 0..=64 {
5168 let p = ParametricCurve::evaluate(
5169 &curves[0].curve,
5170 (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
5171 );
5172 let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
5173 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5174 assert!(
5175 on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
5176 "({x}, {y}): off by {on_rod}, {on_cone}"
5177 );
5178 }
5179 }
5180 for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
5183 let rod =
5184 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5185 .unwrap();
5186 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5187 .unwrap()
5188 .unwrap();
5189 assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
5190 }
5191 }
5192
5193 #[test]
5196 fn coaxial_cone_cylinder_defers_to_other_paths() {
5197 let cone = ConicalSurface::new(
5198 Point3::new(0.0, 0.0, 0.0),
5199 Vec3::new(0.0, 0.0, 1.0),
5200 std::f64::consts::FRAC_PI_4,
5201 )
5202 .unwrap();
5203 let cyl =
5204 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
5205 .unwrap();
5206 assert!(
5207 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5208 .unwrap()
5209 .is_none()
5210 );
5211 }
5212
5213 #[test]
5214 fn oblique_cone_cylinder_defers_to_other_paths() {
5215 let cone = ConicalSurface::new(
5216 Point3::new(0.0, 0.0, 0.0),
5217 Vec3::new(0.0, 0.0, 1.0),
5218 std::f64::consts::FRAC_PI_4,
5219 )
5220 .unwrap();
5221 let cyl =
5222 CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5223 .unwrap();
5224 assert!(
5225 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5226 .unwrap()
5227 .is_none()
5228 );
5229 }
5230
5231 #[test]
5232 fn plane_torus_lobe_closes_and_stays_on_surface() {
5233 use crate::traits::ParametricCurve;
5234 let (major, minor) = (10.0, 3.0);
5235 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5236
5237 for (n, d) in [
5241 (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), ] {
5245 let curves = intersect_plane_torus(&torus, n, d).unwrap();
5246 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
5247 for c in &curves {
5248 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
5249 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
5250 assert!(
5251 (p0 - p1).length() < 1e-7,
5252 "lobe not closed: gap={} (n={n:?} d={d})",
5253 (p0 - p1).length()
5254 );
5255 for k in 0..=64 {
5257 let t = f64::from(k) / 64.0;
5258 let p = ParametricCurve::evaluate(&c.curve, t);
5259 assert!(
5260 torus_implicit(p, major, minor).abs() < 1e-2,
5261 "off-surface point {p:?} implicit={}",
5262 torus_implicit(p, major, minor)
5263 );
5264 }
5265 }
5266 }
5267 }
5268
5269 #[test]
5274 fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
5275 let (major, minor) = (10.0, 3.0);
5276 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5277 let curves =
5278 intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
5279 assert_eq!(curves.len(), 2, "one loop per lobe");
5280 let node = Point3::new(major - minor, 0.0, 0.0);
5281 let mut sides = Vec::new();
5282 for c in &curves {
5283 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5284 assert!((first - node).length() < 1e-6, "starts at {first:?}");
5285 assert_eq!(first, last, "closes on the node");
5286 for p in c.points.iter().map(|p| p.point) {
5287 assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
5288 assert!(
5289 torus_implicit(p, major, minor).abs() < 1e-6,
5290 "off the torus at {p:?}"
5291 );
5292 }
5293 let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
5294 sides.push(y > 0.0);
5295 assert!(
5296 c.points.iter().all(|p| p.point.y() * y >= -1e-9),
5297 "a lobe crosses y = 0"
5298 );
5299 }
5300 assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
5301 }
5302
5303 #[test]
5309 fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
5310 let (major, minor) = (3.0, 1.0);
5311 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5312 for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
5313 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
5314 assert_eq!(curves.len(), loops, "x = {x}");
5315 for c in &curves {
5316 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5317 assert_eq!(first, last, "x = {x}: the loop closes");
5318 for p in c.points.iter().map(|p| p.point) {
5319 assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
5320 assert!(
5321 torus_implicit(p, major, minor).abs() < 1e-6,
5322 "x = {x}: off the torus at {p:?}"
5323 );
5324 }
5325 }
5326 }
5327 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
5329 let low = curves[0]
5330 .points
5331 .iter()
5332 .map(|p| p.point)
5333 .filter(|p| p.y().abs() < 1e-6)
5334 .map(Point3::z)
5335 .collect::<Vec<_>>();
5336 let gap = (2.0001_f64 - 2.0)
5337 .mul_add(2.0, -(2.0001_f64 - 2.0).powi(2))
5338 .sqrt();
5339 assert!(
5340 low.iter().any(|z| (z - gap).abs() < 1e-6)
5341 && low.iter().any(|z| (z + gap).abs() < 1e-6),
5342 "turns at {low:?}, not at z = ±{gap}"
5343 );
5344 }
5345
5346 #[test]
5350 fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
5351 let (major, minor) = (3.0, 1.0);
5352 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5353 for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
5354 let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
5355 let node = torus.evaluate(0.0, v0);
5356 let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
5357 let curves = intersect_plane_torus(&torus, normal, d).unwrap();
5358 assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
5359 for c in &curves {
5360 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5361 assert!(
5362 (first - node).length() < 1e-6,
5363 "v0 {v0}: starts at {first:?}, not {node:?}"
5364 );
5365 assert_eq!(first, last, "v0 {v0}: closes on the node");
5366 for p in c.points.iter().map(|p| p.point) {
5367 let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
5368 assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
5369 assert!(
5370 torus_implicit(p, major, minor).abs() < 1e-6,
5371 "v0 {v0}: off the torus at {p:?}"
5372 );
5373 }
5374 }
5375 }
5376 }
5377
5378 #[test]
5383 fn plane_torus_wall_sections_close_into_their_loops() {
5384 for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
5385 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5386 for k in 1..200 {
5387 let (d, want) = match k.cmp(&100) {
5388 std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
5390 std::cmp::Ordering::Greater => (
5392 2.0f64.mul_add(minor * f64::from(k - 100) / 100.0, major - minor),
5393 1,
5394 ),
5395 std::cmp::Ordering::Equal => continue,
5396 };
5397 let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
5398 let closed = loops
5399 .iter()
5400 .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
5401 .count();
5402 assert_eq!(
5403 (loops.len(), closed),
5404 (want, want),
5405 "R {major} r {minor}, wall at {d}"
5406 );
5407 }
5408 }
5409 }
5410
5411 #[test]
5415 fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
5416 let (major, minor) = (4.0, 1.5);
5417 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5418 for tilt in [0.03_f64, 0.08, 0.2] {
5419 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
5420 let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
5421 assert_eq!(curves.len(), 2, "tilt {tilt}");
5422 for c in &curves {
5423 let (t0, t1) = c.curve.domain();
5424 let off = (0..=400)
5425 .map(|k| {
5426 let p = c
5427 .curve
5428 .evaluate((t1 - t0).mul_add(f64::from(k) / 400.0, t0));
5429 (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
5430 })
5431 .fold(0.0_f64, |m, e| m.max(e.abs()));
5432 assert!(
5433 off < 1e-6,
5434 "tilt {tilt}: fitted section {off} off the torus"
5435 );
5436 }
5437 }
5438 }
5439
5440 #[test]
5441 fn line_torus_box_edge_crossing_is_exact() {
5442 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5445 let ts = intersect_line_torus(
5446 &torus,
5447 Point3::new(6.0, -4.0, -5.0),
5448 Vec3::new(0.0, 0.0, 1.0),
5449 );
5450 assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
5452 let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
5453 let rho = 6.0_f64.hypot(4.0);
5454 let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
5455 assert!(
5456 (zs[0] - (-z_exp)).abs() < 1e-9,
5457 "z0={} exp={}",
5458 zs[0],
5459 -z_exp
5460 );
5461 assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
5462 for &t in &ts {
5464 let p = Point3::new(6.0, -4.0, -5.0 + t);
5465 let rho = p.x().hypot(p.y());
5466 let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
5467 assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
5468 }
5469 }
5470
5471 #[test]
5476 fn line_spindle_torus_roots_lie_on_their_tubes() {
5477 let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
5478 let origin = Point3::new(42.36, 18.31, 3.4);
5479 let dir = Vec3::new(
5480 0.573_576_436_351_046,
5481 0.740_535_693_464_567_5,
5482 0.350_889_803_483_932_2,
5483 );
5484 let ts = intersect_line_torus(&torus, origin, dir);
5485 let tube = |t: f64, across: f64| {
5486 let q = origin + dir * t;
5487 ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
5488 };
5489 for &t in &ts {
5490 assert!(
5491 tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
5492 "root {t} off both tubes in {ts:?}"
5493 );
5494 }
5495 for want in [0.124, 0.398] {
5496 assert!(
5497 ts.iter().any(|&t| (t - want).abs() < 1e-3),
5498 "no root near {want} in {ts:?}"
5499 );
5500 }
5501 }
5502
5503 #[test]
5504 fn line_torus_miss_and_tangent() {
5505 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5506 let miss = intersect_line_torus(
5508 &torus,
5509 Point3::new(20.0, 0.0, 0.0),
5510 Vec3::new(0.0, 0.0, 1.0),
5511 );
5512 assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
5513 let axis =
5515 intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
5516 assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
5517 }
5518
5519 #[test]
5520 fn dispatch_via_analytic_surface() {
5521 let cyl =
5522 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5523 .unwrap();
5524 let curves = intersect_plane_analytic(
5525 AnalyticSurface::Cylinder(&cyl),
5526 Vec3::new(0.0, 0.0, 1.0),
5527 0.0,
5528 )
5529 .unwrap();
5530 assert!(!curves.is_empty());
5531 }
5532
5533 #[test]
5534 fn perpendicular_cylinders_intersect() {
5535 let cyl_z =
5536 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5537 .unwrap();
5538 let cyl_x =
5539 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5540 .unwrap();
5541
5542 let curves = intersect_analytic_analytic(
5543 AnalyticSurface::Cylinder(&cyl_z),
5544 AnalyticSurface::Cylinder(&cyl_x),
5545 16,
5546 )
5547 .unwrap();
5548
5549 assert!(
5550 !curves.is_empty(),
5551 "perpendicular cylinders should intersect"
5552 );
5553
5554 for c in &curves {
5555 assert!(
5556 c.points.len() >= 2,
5557 "intersection curve should have >= 2 points, got {}",
5558 c.points.len()
5559 );
5560 }
5561 }
5562
5563 #[test]
5566 fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
5567 let cyl_z =
5568 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5569 .unwrap();
5570 let cyl_x =
5571 CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5572 .unwrap();
5573 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
5574 .unwrap()
5575 .unwrap();
5576 assert_eq!(curves.len(), 1);
5577 let curve = &curves[0].curve;
5578 let (t0, t1) = curve.domain();
5579 assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
5580 let off = |p: Point3| {
5581 let on_z = (p.x().hypot(p.y()) - 1.0).abs();
5582 let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
5583 on_z.max(on_x)
5584 };
5585 let worst = (0..=400)
5586 .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
5587 .fold(0.0, f64::max);
5588 assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
5589 }
5590
5591 #[test]
5595 fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
5596 let cyl_z =
5597 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5598 .unwrap();
5599 let cyl_x =
5600 CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
5601 .unwrap();
5602 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
5603 .unwrap()
5604 .expect("the thin cylinder's sweep finds the loop");
5605 assert_eq!(curves.len(), 1);
5606 }
5607
5608 #[test]
5613 fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
5614 let crossing = Point3::new(1.0, 2.0, 3.0);
5615 let (s, c) = 60.0_f64.to_radians().sin_cos();
5616 let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
5617 let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
5618 let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
5619 let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
5620 assert_eq!(curves.len(), 2);
5621 let off = |p: Point3, cyl: &CylindricalSurface| {
5622 let q = p - cyl.origin();
5623 ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
5624 };
5625 let ends = [
5626 crossing + Vec3::new(0.0, 1.5, 0.0),
5627 crossing - Vec3::new(0.0, 1.5, 0.0),
5628 ];
5629 let mut vertices: Vec<Point3> = Vec::new();
5630 for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
5631 let (t0, t1) = ic.curve.domain();
5632 for k in 0..=400 {
5633 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
5634 assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
5635 assert!(side * (p - crossing).dot(d1) > -1e-13);
5636 }
5637 assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
5638 assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
5639 let other = ends[usize::from(side > 0.0)];
5640 assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
5641 for t in [0.25, 0.75] {
5642 let vertex = ic.curve.evaluate(t);
5643 assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
5644 vertices.push(vertex);
5645 }
5646 }
5647 }
5648
5649 #[test]
5654 fn nearly_crossing_equal_cylinders_are_not_ellipses() {
5655 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5656 .unwrap();
5657 let x = |(x0, y): (f64, f64), r: f64| {
5658 CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
5659 };
5660 let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
5661 assert!(taken(&x((-2.0, 0.0), 1.0)));
5662 assert!(!taken(&x((-2.0, 1e-9), 1.0)));
5663 assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
5664 assert!(!taken(&x((-1e8, 1e-6), 1.0)));
5665 }
5666
5667 #[test]
5671 fn nearly_parallel_equal_cylinders_are_not_ellipses() {
5672 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
5673 .unwrap();
5674 for slope in [1e-8, 1.5e-5] {
5675 let tilted = CylindricalSurface::new(
5676 Point3::new(0.0, 0.0, 0.0),
5677 Vec3::new(slope, 0.0, 1.0),
5678 10.0,
5679 )
5680 .unwrap();
5681 assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
5682 }
5683 }
5684
5685 #[test]
5686 fn sphere_cylinder_intersect() {
5687 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
5688 let cyl =
5689 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5690 .unwrap();
5691
5692 let curves = intersect_analytic_analytic(
5693 AnalyticSurface::Sphere(&sphere),
5694 AnalyticSurface::Cylinder(&cyl),
5695 16,
5696 )
5697 .unwrap();
5698
5699 assert!(!curves.is_empty(), "sphere and cylinder should intersect");
5703 }
5704
5705 #[test]
5706 fn exact_sphere_cylinder_coaxial_two_circles() {
5707 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
5710 let cyl =
5711 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
5712 .unwrap();
5713 let circles = exact_sphere_cylinder(&sphere, &cyl)
5714 .unwrap()
5715 .expect("coaxial case returns Some");
5716 assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
5717 let mut zs: Vec<f64> = circles
5718 .iter()
5719 .filter_map(|c| match c {
5720 ExactIntersectionCurve::Circle(circle) => {
5721 assert!(
5722 (circle.radius() - 3.0).abs() < 1e-9,
5723 "rim radius == cyl radius"
5724 );
5725 Some(circle.center().z())
5726 }
5727 _ => None,
5728 })
5729 .collect();
5730 assert_eq!(zs.len(), 2, "both sections must be exact circles");
5731 zs.sort_by(f64::total_cmp);
5732 let z = 27.0_f64.sqrt();
5733 assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
5734 }
5735
5736 #[test]
5737 fn exact_sphere_cylinder_non_coaxial_defers() {
5738 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
5740 let cyl =
5741 CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
5742 .unwrap();
5743 assert!(
5744 exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
5745 "non-coaxial sphere/cylinder defers to the marcher"
5746 );
5747 }
5748
5749 #[test]
5750 fn a_ball_on_a_cones_axis_meets_it_in_circles() {
5751 let cone = ConicalSurface::new(
5753 Point3::new(0.0, 0.0, 3.0),
5754 Vec3::new(0.0, 0.0, -1.0),
5755 2.0_f64.atan(),
5756 )
5757 .unwrap();
5758 for (height, radius, count) in [
5759 (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), ] {
5765 let centre = Point3::new(0.0, 0.0, height);
5766 let ball = SphericalSurface::new(centre, radius).unwrap();
5767 let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
5768 let circles = circles_of(&curves);
5769 assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
5770 for circle in circles {
5771 for k in 0..16 {
5772 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
5773 let on_ball = (p - centre).length() - radius;
5774 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5775 assert!(
5776 on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
5777 "ball at {height}: off by {on_ball}, {on_cone}"
5778 );
5779 }
5780 }
5781 }
5782 let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
5783 assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
5784 let wide =
5787 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
5788 let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
5789 let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
5790 let circles = circles_of(&curves);
5791 assert_eq!(circles.len(), 1, "the touch");
5792 let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
5793 assert!(
5794 (circles[0].radius() - touch).abs() < 1e-3,
5795 "{}",
5796 circles[0].radius()
5797 );
5798 }
5799
5800 fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
5802 curves
5803 .iter()
5804 .filter_map(|c| match c {
5805 ExactIntersectionCurve::Circle(circle) => Some(circle),
5806 _ => None,
5807 })
5808 .collect()
5809 }
5810
5811 fn worst_off(
5814 circles: &[&Circle3D],
5815 torus: &ToroidalSurface,
5816 other: impl Fn(Point3) -> f64,
5817 ) -> f64 {
5818 let mut worst = 0.0_f64;
5819 for circle in circles {
5820 for k in 0..16 {
5821 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
5822 let q = p - torus.center();
5823 let along = q.dot(torus.z_axis());
5824 let rho = (q - torus.z_axis() * along).length();
5825 let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
5826 worst = worst.max(off).max(other(p).abs());
5827 }
5828 }
5829 worst
5830 }
5831
5832 #[test]
5833 fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
5834 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5835 for height in [0.0, 1.0] {
5836 let centre = Point3::new(0.0, 0.0, height);
5837 let sphere = SphericalSurface::new(centre, 3.0).unwrap();
5838 let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
5839 let circles = circles_of(&curves);
5840 assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
5841 let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
5842 assert!(worst < 1e-9, "height {height}: {worst}");
5843 }
5844 }
5845
5846 #[test]
5847 fn exact_sphere_torus_misses_touches_and_defers() {
5848 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5849 let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
5850 assert!(
5851 exact_sphere_torus(&ball(0.0, 1.0), &torus)
5852 .unwrap()
5853 .unwrap()
5854 .is_empty(),
5855 "a small ball in the hole misses"
5856 );
5857 let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
5858 .unwrap()
5859 .unwrap();
5860 let circles = circles_of(&touching);
5861 assert_eq!(
5862 circles.len(),
5863 1,
5864 "a ball in the hole touches the inner equator"
5865 );
5866 assert!((circles[0].radius() - 2.5).abs() < 1e-12);
5867 assert!(circles[0].center().z().abs() < 1e-12);
5868 assert!(
5869 exact_sphere_torus(&ball(1.0, 3.0), &torus)
5870 .unwrap()
5871 .is_none(),
5872 "a ball off the axis defers"
5873 );
5874 let spindle = ToroidalSurface::with_axis_and_ref_dir(
5875 Point3::new(0.0, 0.0, 0.0),
5876 1.0,
5877 2.0,
5878 Vec3::new(0.0, 0.0, 1.0),
5879 Vec3::new(1.0, 0.0, 0.0),
5880 )
5881 .unwrap();
5882 assert!(
5883 exact_sphere_torus(&ball(0.0, 2.5), &spindle)
5884 .unwrap()
5885 .is_none()
5886 );
5887 }
5888
5889 #[test]
5890 fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
5891 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5892 let z = Vec3::new(0.0, 0.0, 1.0);
5893 let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
5894 let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
5895 let circles = circles_of(&curves);
5896 assert_eq!((curves.len(), circles.len()), (2, 2));
5897 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
5898 assert!(worst < 1e-9, "{worst}");
5899 assert!(
5900 exact_cylinder_torus(&rod(2.0), &torus)
5901 .unwrap()
5902 .unwrap()
5903 .is_empty(),
5904 "a rod clear in the hole misses"
5905 );
5906 for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
5907 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
5908 let circles = circles_of(&curves);
5909 assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
5910 assert!(circles[0].center().z().abs() < 1e-12, "{label}");
5911 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
5912 assert!(worst < 1e-9, "{label}: {worst}");
5913 }
5914 assert!(
5915 exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
5916 .unwrap()
5917 .unwrap()
5918 .is_empty(),
5919 "a wall clear of the tube by more than the tolerance misses it"
5920 );
5921 assert_eq!(
5922 exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
5923 .unwrap()
5924 .unwrap()
5925 .len(),
5926 2,
5927 "a wall into the tube by more than the tolerance crosses it twice"
5928 );
5929 for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
5933 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
5934 assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
5935 }
5936 let tilted =
5937 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
5938 .unwrap();
5939 let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
5940 assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
5941 assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
5942 let spindle = ToroidalSurface::with_axis_and_ref_dir(
5943 Point3::new(0.0, 0.0, 0.0),
5944 1.0,
5945 2.0,
5946 z,
5947 Vec3::new(1.0, 0.0, 0.0),
5948 )
5949 .unwrap();
5950 assert!(
5951 exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
5952 "a spindle torus's inner lemon also meets the rod"
5953 );
5954 let spindle = ToroidalSurface::with_axis_and_ref_dir(
5957 Point3::new(0.0, 0.0, 4.7),
5958 0.1,
5959 2.45,
5960 z,
5961 Vec3::new(1.0, 0.0, 0.0),
5962 )
5963 .unwrap();
5964 let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
5965 let circles = circles_of(&curves);
5966 assert_eq!(circles.len(), 1);
5967 assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
5968 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
5969 assert!(worst < 1e-9, "{worst}");
5970 let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
5971 let circles = circles_of(&curves);
5972 assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
5973 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
5974 assert!(worst < 1e-9, "{worst}");
5975 }
5976
5977 fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
5980 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
5981 let cyl =
5982 CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
5983 .unwrap();
5984 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
5985 .unwrap()
5986 .unwrap();
5987 let mut worst: f64 = 0.0;
5988 for c in &curves {
5989 for ip in &c.points {
5990 let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
5991 let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
5992 worst = worst
5993 .max((on_sphere - ip.point).length())
5994 .max((on_cylinder - ip.point).length());
5995 }
5996 let (t0, t1) = c.curve.domain();
5997 assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
5998 for k in 0..=400 {
5999 let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6000 let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
6001 let on_cylinder = ((p.x() - cylinder_origin.x())
6002 .hypot(p.y() - cylinder_origin.y())
6003 - cylinder_radius)
6004 .abs();
6005 worst = worst.max(on_sphere).max(on_cylinder);
6006 }
6007 }
6008 (curves.len(), worst)
6009 }
6010
6011 #[test]
6014 fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
6015 let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
6016 assert_eq!(count, 2);
6017 assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
6018 }
6019
6020 #[test]
6022 fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
6023 let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
6024 assert_eq!(count, 1);
6025 assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
6026 }
6027
6028 #[test]
6029 fn disjoint_cylinders_no_intersection() {
6030 let cyl_a =
6031 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6032 .unwrap();
6033 let cyl_b =
6034 CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6035 .unwrap();
6036
6037 let curves = intersect_analytic_analytic(
6038 AnalyticSurface::Cylinder(&cyl_a),
6039 AnalyticSurface::Cylinder(&cyl_b),
6040 16,
6041 )
6042 .unwrap();
6043
6044 assert!(curves.is_empty(), "disjoint cylinders should not intersect");
6045 }
6046
6047 fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
6051 use crate::traits::ParametricCurve;
6052 match curve {
6053 ExactIntersectionCurve::Circle(c) => (0..=64)
6054 .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
6055 .collect(),
6056 ExactIntersectionCurve::Ellipse(e) => (0..=64)
6057 .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
6058 .collect(),
6059 ExactIntersectionCurve::Points(pts) => pts.clone(),
6060 }
6061 }
6062
6063 fn assert_on_plane_and_cone(
6066 curves: &[ExactIntersectionCurve],
6067 cone: &ConicalSurface,
6068 n: Vec3,
6069 d: f64,
6070 z_bound: (f64, f64),
6071 ) {
6072 assert!(!curves.is_empty(), "expected at least one section curve");
6073 let mut total = 0;
6074 for curve in curves {
6075 for p in collect_points(curve) {
6076 total += 1;
6077 let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
6078 assert!(
6079 plane_err < 1e-9,
6080 "point off plane by {plane_err:.2e}: {p:?}"
6081 );
6082 let (u, v) = cone.project_point(p);
6083 let q = cone.evaluate(u, v);
6084 let cone_err =
6085 ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
6086 .sqrt();
6087 assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
6088 assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
6089 assert!(
6090 p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
6091 "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
6092 p.z()
6093 );
6094 }
6095 }
6096 assert!(total >= 8, "too few section points ({total})");
6097 }
6098
6099 #[test]
6100 fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
6101 let cone = ConicalSurface::new(
6105 Point3::new(0.0, 0.0, 0.0),
6106 Vec3::new(0.0, 0.0, 1.0),
6107 std::f64::consts::FRAC_PI_4,
6108 )
6109 .unwrap();
6110 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6111 let d = n.z() * 5.0;
6113 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6114 assert!(
6115 curves
6116 .iter()
6117 .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
6118 "oblique steep plane × cone must yield an exact Ellipse"
6119 );
6120 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
6122 }
6123
6124 #[test]
6125 fn oblique_plane_cone_wrong_nappe_is_empty() {
6126 let cone = ConicalSurface::new(
6130 Point3::new(0.0, 0.0, 0.0),
6131 Vec3::new(0.0, 0.0, 1.0),
6132 std::f64::consts::FRAC_PI_4,
6133 )
6134 .unwrap();
6135 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6136 let d = n.z() * -5.0;
6137 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6138 assert!(
6139 curves.is_empty(),
6140 "plane on the phantom-nappe side must yield no real curve, got {}",
6141 curves.len()
6142 );
6143 }
6144
6145 #[test]
6146 fn oblique_plane_cone_parabola_on_both_single_branch() {
6147 let cone = ConicalSurface::new(
6150 Point3::new(0.0, 0.0, 0.0),
6151 Vec3::new(0.0, 0.0, 1.0),
6152 std::f64::consts::FRAC_PI_4,
6153 )
6154 .unwrap();
6155 let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
6156 let d = n.x() * 3.0 + n.z() * 3.0; let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6158 assert_eq!(
6159 curves.len(),
6160 1,
6161 "a parabola is a single branch, got {}",
6162 curves.len()
6163 );
6164 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
6166 }
6167
6168 #[test]
6169 fn oblique_plane_cone_hyperbola_real_nappe_only() {
6170 let cone = ConicalSurface::new(
6178 Point3::new(-59.0, -59.0, 15.85),
6179 Vec3::new(0.0, 0.0, -1.0),
6180 std::f64::consts::FRAC_PI_4,
6181 )
6182 .unwrap();
6183 let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
6184 let d = -58.360_56;
6185 let cos_theta = n.dot(cone.axis()).abs();
6186 assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
6187 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6188 assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
6191 for c in &curves {
6193 assert!(
6194 matches!(c, ExactIntersectionCurve::Points(_)),
6195 "hyperbola must be sampled Points, not a closed conic"
6196 );
6197 }
6198 }
6199
6200 #[test]
6204 fn sphere_sphere_meets_in_a_circle_on_both() {
6205 let ball = |x: f64, y: f64, z: f64, r: f64| {
6206 SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
6207 };
6208 let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
6209 let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
6210 assert_eq!(curves.len(), 1);
6211 let circle = match &curves[0] {
6212 ExactIntersectionCurve::Circle(circle) => circle,
6213 other => unreachable!("expected a circle, got {other:?}"),
6214 };
6215 for k in 0..16 {
6216 let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
6217 assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
6218 assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
6219 }
6220 assert!(
6221 exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
6222 .unwrap()
6223 .unwrap()
6224 .is_empty()
6225 );
6226 assert!(
6227 exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
6228 .unwrap()
6229 .unwrap()
6230 .is_empty()
6231 );
6232 assert!(
6233 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
6234 .unwrap()
6235 .unwrap()
6236 .is_empty()
6237 );
6238 assert!(
6239 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
6240 .unwrap()
6241 .is_none()
6242 );
6243
6244 let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
6247 match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
6248 [ExactIntersectionCurve::Circle(c)] => c.radius(),
6249 other => unreachable!("expected one circle, got {other:?}"),
6250 }
6251 };
6252 let tiny = ball(2.0, 0.0, 0.0, 1e-5);
6253 assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
6254 assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
6255 let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
6256 let far = radius(
6257 &ball(1e10, 0.0, 0.0, 2.0),
6258 &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
6259 );
6260 assert!(near > 1e-3);
6261 assert!((far - near).abs() < 1e-9 * near.max(1.0));
6262 }
6263
6264 #[allow(clippy::panic)]
6267 fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
6268 sections
6269 .iter()
6270 .map(|s| match s {
6271 PlaneSection::Line { line, ray } => (line.clone(), *ray),
6272 other => panic!("expected a line, got {other:?}"),
6273 })
6274 .collect()
6275 }
6276
6277 #[test]
6282 fn a_plane_along_a_cylinder_cuts_its_rulings() {
6283 let cyl =
6284 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6285 .unwrap();
6286 let y = Vec3::new(0.0, 1.0, 0.0);
6287 let surface = AnalyticSurface::Cylinder(&cyl);
6288 let on_both = |p: Point3, d: f64| {
6289 assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
6290 assert!(
6291 (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
6292 "{p:?} off the cylinder"
6293 );
6294 };
6295 for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
6296 assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
6297 let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
6298 assert_eq!(lines.len(), count, "plane y = {d}");
6299 let mut xs = Vec::new();
6300 for (line, ray) in lines {
6301 assert!(!ray);
6302 assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
6303 for t in [-3.0, 0.0, 3.0] {
6304 on_both(line.evaluate(t), d);
6305 }
6306 xs.push(line.evaluate(0.0).x());
6307 }
6308 if count == 2 {
6309 let apart = (xs[0] - xs[1]).abs();
6310 let want = 2.0 * (1.0 - d * d).sqrt();
6311 assert!(
6312 (apart - want).abs() < 1e-9 * want.max(1e-6),
6313 "{apart} apart"
6314 );
6315 }
6316 }
6317 }
6318
6319 #[test]
6324 #[allow(clippy::panic)]
6325 fn a_plane_through_a_cone_apex_cuts_its_rulings() {
6326 use std::f64::consts::FRAC_PI_4;
6327
6328 let cone = ConicalSurface::new(
6329 Point3::new(1.0, 2.0, 3.0),
6330 Vec3::new(0.0, 0.0, 1.0),
6331 FRAC_PI_4,
6332 )
6333 .unwrap();
6334 let surface = AnalyticSurface::Cone(&cone);
6335 let apex = cone.apex();
6336 let through = |n: Vec3| {
6337 let n = n.normalize().unwrap();
6338 let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
6339 assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
6340 (n, d, exact_plane_section(surface, n, d).unwrap())
6341 };
6342 for (n, count) in [
6343 (Vec3::new(1.0, 0.0, 0.0), 2),
6344 (Vec3::new(1.0, 0.0, -1.0), 1),
6345 ] {
6346 let (n, d, sections) = through(n);
6347 let rays = lines_of(§ions);
6348 assert_eq!(rays.len(), count, "plane normal {n:?}");
6349 for (line, ray) in rays {
6350 assert!(ray);
6351 assert!((line.evaluate(0.0) - apex).length() < 1e-12);
6352 let p = line.evaluate(2.0);
6353 assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
6354 let rel = p - apex;
6355 assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
6356 assert!(
6357 (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
6358 "{p:?} off the cone"
6359 );
6360 }
6361 }
6362 for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
6363 let (_, _, sections) = through(n);
6364 assert!(
6365 matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
6366 "{sections:?}"
6367 );
6368 }
6369
6370 let upright = ConicalSurface::new(
6371 Point3::new(0.0, 0.0, 0.0),
6372 Vec3::new(0.0, 0.0, 1.0),
6373 FRAC_PI_4,
6374 )
6375 .unwrap();
6376 let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
6377 let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
6378 let [PlaneSection::Ellipse(ellipse)] = §ions[..] else {
6379 panic!("{sections:?}");
6380 };
6381 assert!(
6382 ellipse.semi_major() > 1.0,
6383 "semi-major {}",
6384 ellipse.semi_major()
6385 );
6386 }
6387
6388 #[test]
6391 #[allow(clippy::panic)]
6392 fn a_plane_touching_a_sphere_meets_it_at_a_point() {
6393 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6394 let surface = AnalyticSurface::Sphere(&sphere);
6395 let z = Vec3::new(0.0, 0.0, 1.0);
6396 assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
6397 let sections = exact_plane_section(surface, z, 0.0).unwrap();
6398 assert!(
6399 matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
6400 "{sections:?}"
6401 );
6402 assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
6403 for height in [5e-15, 1e-12, 1e-8] {
6404 let sections = exact_plane_section(surface, z, height).unwrap();
6405 let [PlaneSection::Circle(circle)] = §ions[..] else {
6406 panic!("{sections:?}");
6407 };
6408 let want = (height * (2.0 - height)).sqrt();
6409 assert!(
6410 (circle.radius() - want).abs() < 1e-3 * want,
6411 "circle at z = {height}: radius {}, want {want}",
6412 circle.radius()
6413 );
6414 assert!((circle.center().z() - height).abs() < 1e-15);
6415 }
6416 }
6417
6418 fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
6420 let mut far = 0.0_f64;
6421 for ic in curves {
6422 let (t0, t1) = ic.curve.domain();
6423 for i in 0..=2000 {
6424 let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
6425 far = far.max(off(ic.curve.evaluate(t)));
6426 }
6427 }
6428 far
6429 }
6430
6431 #[test]
6434 fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
6435 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6436 let bore =
6437 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6438 .unwrap();
6439 let curves = intersect_analytic_analytic_bounded(
6440 AnalyticSurface::Sphere(&ball),
6441 AnalyticSurface::Cylinder(&bore),
6442 64,
6443 None,
6444 Some((0.0, 4.0)),
6445 )
6446 .unwrap();
6447 assert_eq!(curves.len(), 1);
6448 let far = farthest(&curves, |p| {
6449 let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
6450 on_ball
6451 .max((p.x().hypot(p.y()) - 1.0).abs())
6452 .max(p.z().abs())
6453 });
6454 assert!(far < 1e-14, "circle strays {far:.2e}");
6455 }
6456
6457 #[test]
6460 fn overlapping_balls_meet_on_an_exact_circle() {
6461 let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6462 let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
6463 let curves = intersect_analytic_analytic_bounded(
6464 AnalyticSurface::Sphere(&a),
6465 AnalyticSurface::Sphere(&b),
6466 64,
6467 None,
6468 None,
6469 )
6470 .unwrap();
6471 assert_eq!(curves.len(), 1);
6472 let far = farthest(&curves, |p| {
6473 let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
6474 on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
6475 });
6476 assert!(far < 1e-14, "circle strays {far:.2e}");
6477 }
6478
6479 #[test]
6482 fn a_conic_loop_is_its_ellipse() {
6483 let centre = Point3::new(1.0, -2.0, 0.5);
6484 let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
6485 let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
6486 let (t0, t1) = curve.domain();
6487 assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
6488 for i in 0..=2000 {
6489 let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
6490 let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
6491 assert!(
6492 (x.hypot(y) - 1.0).abs() < 1e-14,
6493 "off its ellipse by {}",
6494 x.hypot(y) - 1.0
6495 );
6496 assert!(p.dot(frame.z).abs() < 1e-14);
6497 }
6498 }
6499
6500 #[test]
6504 fn touching_coaxial_rings_meet_along_one_circle() {
6505 let z = Vec3::new(0.0, 0.0, 1.0);
6506 let x = Vec3::new(1.0, 0.0, 0.0);
6507 let ring =
6508 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
6509 .unwrap();
6510 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6511 let curves = intersect_analytic_analytic_bounded(
6512 AnalyticSurface::Sphere(&ball),
6513 AnalyticSurface::Torus(&ring),
6514 64,
6515 None,
6516 None,
6517 )
6518 .unwrap();
6519 assert_eq!(curves.len(), 1);
6520 let far = farthest(&curves, |p| {
6521 let q = p - Point3::new(0.0, 0.0, 0.0);
6522 let rho = q.x().hypot(q.y());
6523 let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
6524 on_ring.max((q.length() - 2.0).abs())
6525 });
6526 assert!(far < 1e-14, "circle strays {far:.2e}");
6527
6528 let wider =
6532 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
6533 .unwrap();
6534 let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
6535 let circles = circles_of(&touching);
6536 assert_eq!(circles.len(), 1);
6537 assert!(
6538 (circles[0].radius() - 3.6).abs() < 1e-12,
6539 "{}",
6540 circles[0].radius()
6541 );
6542 assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
6543 }
6544
6545 #[test]
6550 fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
6551 let z = Vec3::new(0.0, 0.0, 1.0);
6552 let x = Vec3::new(1.0, 0.0, 0.0);
6553 let ring = |big: f64| {
6554 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
6555 .unwrap()
6556 };
6557 let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
6558 .unwrap()
6559 .unwrap();
6560 let circles = circles_of(&crossing);
6561 assert_eq!(circles.len(), 2);
6562 for circle in circles {
6563 let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
6564 assert!(
6565 (circle.center().z().abs() - height).abs() < 1e-9,
6566 "{}",
6567 circle.center().z()
6568 );
6569 }
6570 let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
6571 .unwrap()
6572 .unwrap();
6573 assert!(apart.is_empty());
6574 }
6575
6576 #[test]
6580 fn a_plane_cuts_a_cones_open_conics() {
6581 let up = Vec3::new(0.0, 0.0, 1.0);
6582 let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
6583 let steep =
6584 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
6585 let slope = 60_f64.to_radians().tan();
6586 let along =
6587 exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
6588 .unwrap();
6589 let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
6590 unreachable!("{along:?}")
6591 };
6592 for i in -20..=20 {
6593 let p = h.evaluate(f64::from(i) / 5.0);
6594 assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
6595 assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
6596 }
6597 let even =
6598 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
6599 let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
6600 let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
6601 let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
6602 unreachable!("{above:?}")
6603 };
6604 for i in -20..=20 {
6605 let p = parabola.evaluate(f64::from(i) / 2.0);
6606 assert!(
6607 (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
6608 "{p:?}"
6609 );
6610 assert!(
6611 p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
6612 "{p:?}"
6613 );
6614 }
6615 let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
6616 assert!(below.is_empty(), "{below:?}");
6617 }
6618
6619 #[test]
6625 fn extreme_cones_give_sections_on_the_cone() {
6626 let up = Vec3::new(0.0, 0.0, 1.0);
6627 let apex = Point3::new(0.0, 0.0, 0.0);
6628 let holds = |cone: &ConicalSurface, q: Point3| {
6629 let w = q - apex;
6630 (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
6631 };
6632 let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
6633 let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
6634 let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
6635 for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
6636 let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
6637 assert!(!sections.is_empty());
6638 for section in §ions {
6639 let points: Vec<Point3> = match section {
6640 PlaneSection::Hyperbola(h) => {
6641 (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
6642 }
6643 PlaneSection::Parabola(q) => {
6644 (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
6645 }
6646 PlaneSection::Points(points) => points.clone(),
6647 other => unreachable!("{other:?}"),
6648 };
6649 for q in points {
6650 assert!(holds(cone, q), "{q:?} off the cone");
6651 }
6652 }
6653 }
6654 let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
6655 assert!(matches!(
6656 flat_section.as_slice(),
6657 [PlaneSection::Hyperbola(_)]
6658 ));
6659 }
6660
6661 fn parallel_rulings(
6664 (c1, r1, v1): (Point3, f64, (f64, f64)),
6665 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
6666 ) -> Vec<(Point3, Point3)> {
6667 rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
6668 }
6669
6670 fn rulings_within(
6673 (c1, r1, v1): (Point3, f64, (f64, f64)),
6674 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
6675 tolerance: f64,
6676 ) -> Vec<(Point3, Point3)> {
6677 let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
6678 let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
6679 let curves = intersect_analytic_analytic_bounded(
6680 AnalyticSurface::Cylinder(&a),
6681 AnalyticSurface::Cylinder(&b),
6682 32,
6683 Some(v1),
6684 Some(v2),
6685 )
6686 .unwrap();
6687 curves
6688 .iter()
6689 .map(|ic| {
6690 let (t0, t1) = ic.curve.domain();
6691 let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
6692 for i in 0..=100 {
6693 let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
6694 let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
6695 let w = x - c2;
6696 let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
6697 assert!(
6698 on_a.abs() < tolerance && on_b.abs() < tolerance,
6699 "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
6700 );
6701 }
6702 if p.z() <= q.z() { (p, q) } else { (q, p) }
6703 })
6704 .collect()
6705 }
6706
6707 #[test]
6711 fn overlapping_parallel_rods_meet_along_two_rulings() {
6712 let mut rulings = parallel_rulings(
6713 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
6714 (
6715 Point3::new(1.2, 0.0, 3.0),
6716 1.0,
6717 Vec3::new(0.0, 0.0, -1.0),
6718 (0.0, 2.0),
6719 ),
6720 );
6721 rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
6722 assert_eq!(rulings.len(), 2);
6723 for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
6724 assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
6725 assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
6726 }
6727 }
6728
6729 #[test]
6732 fn touching_parallel_rods_meet_along_one_ruling() {
6733 let up = Vec3::new(0.0, 0.0, 1.0);
6734 let beside = parallel_rulings(
6735 (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
6736 (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
6737 );
6738 assert_eq!(beside.len(), 1);
6739 assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
6740 assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
6741 let inside = parallel_rulings(
6742 (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
6743 (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
6744 );
6745 assert_eq!(inside.len(), 1);
6746 assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
6747 let apart = parallel_rulings(
6748 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
6749 (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
6750 );
6751 assert!(apart.is_empty());
6752 }
6753
6754 #[test]
6758 fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
6759 let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6760 .unwrap();
6761 let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
6762 let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
6763 let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
6764 assert!(span(100.0).unwrap().is_none());
6765 assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
6766 }
6767
6768 #[test]
6772 fn parallel_rods_keep_short_and_close_rulings() {
6773 let up = Vec3::new(0.0, 0.0, 1.0);
6774 let huge = rulings_within(
6775 (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
6776 (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
6777 1e-9,
6778 );
6779 assert_eq!(huge.len(), 2);
6780 assert!(
6781 huge.iter()
6782 .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
6783 );
6784 let mut close = rulings_within(
6785 (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
6786 (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
6787 1e-9,
6788 );
6789 assert_eq!(close.len(), 2);
6790 close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
6791 let apart = close[1].0.y() - close[0].0.y();
6792 assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
6793 }
6794}