1use crate::madd::Madd;
8use std::cell::RefCell;
9use std::f64::consts::{FRAC_PI_2, TAU};
10
11use crate::MathError;
12use crate::aabb::Aabb3;
13use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
14use crate::frame::Frame3;
15use crate::nurbs::curve::NurbsCurve;
16use crate::nurbs::fitting::interpolate;
17use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
18use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
19use crate::tolerance::Tolerance;
20use crate::vec::{Point3, Vec3};
21
22mod cover;
23mod section_fit;
24use section_fit::{crosses_at, fit_section, settle_on_section};
25
26#[derive(Debug, Clone)]
28pub enum ExactIntersectionCurve {
29 Circle(Circle3D),
31 Ellipse(Ellipse3D),
33 Points(Vec<Point3>),
35}
36
37#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub enum PlaneSection {
41 Circle(Circle3D),
43 Ellipse(Ellipse3D),
45 Line {
49 line: Line3D,
51 ray: bool,
53 },
54 Point(Point3),
56 Points(Vec<Point3>),
58 Parabola(Parabola3D),
60 Hyperbola(Hyperbola3D),
63}
64
65impl From<ExactIntersectionCurve> for PlaneSection {
66 fn from(curve: ExactIntersectionCurve) -> Self {
67 match curve {
68 ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
69 ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
70 ExactIntersectionCurve::Points(points) => Self::Points(points),
71 }
72 }
73}
74
75pub fn exact_plane_section(
90 surface: AnalyticSurface<'_>,
91 normal: Vec3,
92 d: f64,
93) -> Result<Vec<PlaneSection>, MathError> {
94 match surface {
95 AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
96 return plane_cylinder_rulings(cyl, normal, d);
97 }
98 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
99 return plane_cone_apex_rulings(cone, normal);
100 }
101 AnalyticSurface::Cone(cone) => {
102 if let Some(open) = plane_cone_open_section(cone, normal, d)? {
103 return Ok(open);
104 }
105 }
106 AnalyticSurface::Sphere(sphere) => {
107 let h = dot_np(normal, sphere.center()) - d;
108 let r = sphere.radius();
109 if (r - h.abs()).abs() <= TOUCH * r {
110 return Ok(vec![PlaneSection::Point(Point3::new(
111 h.madd(-normal.x(), sphere.center().x()),
112 h.madd(-normal.y(), sphere.center().y()),
113 h.madd(-normal.z(), sphere.center().z()),
114 ))]);
115 }
116 }
117 AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
118 }
119 Ok(exact_plane_analytic(surface, normal, d)?
120 .into_iter()
121 .map(PlaneSection::from)
122 .collect())
123}
124
125const PARABOLIC: f64 = 1e-12;
128
129const HYPERBOLIC: f64 = 1e-6;
133
134#[allow(clippy::many_single_char_names)]
141fn plane_cone_open_section(
142 cone: &ConicalSurface,
143 normal: Vec3,
144 d: f64,
145) -> Result<Option<Vec<PlaneSection>>, MathError> {
146 let axis = cone.axis();
147 let c = normal.dot(axis);
148 let p2 = c.madd(-c, 1.0).max(0.0);
149 let p = p2.sqrt();
150 let rise = cone.half_angle().sin();
151 let k = rise * rise;
152 let a_coeff = p2 - k;
153 let eccentric = a_coeff / k;
154 let m = axis - normal * c;
155 let m_len = m.length();
156 if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
157 {
158 return Ok(None);
159 }
160 let e1 = m * (1.0 / m_len);
161 let e2 = normal.cross(e1);
162 let apex = cone.apex();
163 let e = d - dot_np(normal, apex);
164 let origin = apex + normal * e;
165 let real = |s: f64| e.madd(c, s * p) >= 0.0;
168 let holds = |q: Point3| {
171 let w = q - apex;
172 let reach = w.length();
173 reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
174 };
175 if eccentric <= PARABOLIC {
176 let ecp = e * c * p;
179 let vertex_s = -e * (c * c - k) / (2.0 * c * p);
180 let focal = ecp.abs() / (2.0 * k);
181 if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
182 return Ok(None);
183 }
184 if !real(vertex_s) {
185 return Ok(Some(Vec::new()));
186 }
187 let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
188 if ![0.0, focal, -focal]
189 .iter()
190 .all(|&t| holds(parabola.evaluate(t)))
191 {
192 return Ok(None);
193 }
194 return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
195 }
196 let centre_s = -e * c * p / a_coeff;
199 let rhs = e * e * k * (1.0 - k) / a_coeff;
200 let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
201 if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
202 return Ok(None);
203 }
204 let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
205 let hyperbola = Hyperbola3D::with_axes(
206 origin + e1 * centre_s,
207 real_axis,
208 imaginary_axis,
209 toward,
210 e2,
211 )?;
212 if ![0.0, 1.0, -1.0]
213 .iter()
214 .all(|&t| holds(hyperbola.evaluate(t)))
215 {
216 return Ok(None);
217 }
218 Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
219}
220
221const TOUCH: f64 = 4.0 * f64::EPSILON;
224
225fn plane_cylinder_rulings(
228 cyl: &CylindricalSurface,
229 normal: Vec3,
230 d: f64,
231) -> Result<Vec<PlaneSection>, MathError> {
232 let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
235 let amp = a.hypot(b);
236 if amp < 1e-12 {
237 return Ok(vec![]);
238 }
239 let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
240 if ratio.abs() > 1.0 + TOUCH {
241 return Ok(vec![]);
242 }
243 let phi = b.atan2(a);
244 let spread = ratio.clamp(-1.0, 1.0).acos();
245 let at = if ratio.abs() >= 1.0 - TOUCH {
246 vec![phi + spread]
247 } else {
248 vec![phi + spread, phi - spread]
249 };
250 at.into_iter()
251 .map(|u| {
252 Ok(PlaneSection::Line {
253 line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
254 ray: false,
255 })
256 })
257 .collect()
258}
259
260fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
262 let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
263 (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
264}
265
266fn plane_cone_apex_rulings(
270 cone: &ConicalSurface,
271 normal: Vec3,
272) -> Result<Vec<PlaneSection>, MathError> {
273 let (sin_a, cos_a) = cone.half_angle().sin_cos();
276 let a = cos_a * normal.dot(cone.x_axis());
277 let b = cos_a * normal.dot(cone.y_axis());
278 let c = sin_a * normal.dot(cone.axis());
279 let amp = a.hypot(b);
280 let apex = cone.apex();
281 if amp < 1e-12 * c.abs().max(1.0) {
282 return Ok(vec![PlaneSection::Point(apex)]);
283 }
284 let ratio = -c / amp;
285 if ratio.abs() > 1.0 + TOUCH {
286 return Ok(vec![PlaneSection::Point(apex)]);
287 }
288 let phi = b.atan2(a);
289 let spread = ratio.clamp(-1.0, 1.0).acos();
290 let at = if ratio.abs() >= 1.0 - TOUCH {
291 vec![phi + spread]
292 } else {
293 vec![phi + spread, phi - spread]
294 };
295 at.into_iter()
296 .map(|u| {
297 Ok(PlaneSection::Line {
298 line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
299 ray: true,
300 })
301 })
302 .collect()
303}
304
305pub fn exact_plane_analytic(
320 surface: AnalyticSurface<'_>,
321 plane_normal: Vec3,
322 plane_d: f64,
323) -> Result<Vec<ExactIntersectionCurve>, MathError> {
324 exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
325}
326
327pub fn exact_plane_analytic_reaching(
335 surface: AnalyticSurface<'_>,
336 plane_normal: Vec3,
337 plane_d: f64,
338 reach: f64,
339) -> Result<Vec<ExactIntersectionCurve>, MathError> {
340 match surface {
341 AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
342 AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
343 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
344 AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
345 AnalyticSurface::Torus(torus) => {
346 if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
347 return Ok(circles);
348 }
349 if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
350 return Ok(loops
351 .into_iter()
352 .map(ExactIntersectionCurve::Points)
353 .collect());
354 }
355 let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
357 Ok(chains
358 .into_iter()
359 .map(ExactIntersectionCurve::Points)
360 .collect())
361 }
362 }
363}
364
365fn exact_plane_torus(
379 torus: &ToroidalSurface,
380 normal: Vec3,
381 d: f64,
382) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
383 let len = normal.length();
384 let n = normal.normalize()?;
385 let d = d / len;
386 let axis = torus.z_axis();
387 let center = torus.center();
388 let (big, small) = (torus.major_radius(), torus.minor_radius());
389 let height = d - dot_np(n, center);
390 let along = n.dot(axis);
391 if along.abs() > 1.0 - 1e-10 {
392 if height.abs() >= small - 1e-10 * small {
393 if height.abs() > small + 1e-10 * small {
394 return Ok(Some(Vec::new()));
395 }
396 if big <= 1e-10 * small
403 || axis.cross(n).length() > 1e-12
404 || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
405 {
406 return Ok(None);
407 }
408 let middle = center + n * height;
409 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
410 middle, n, big,
411 )?)]));
412 }
413 let reach = small.madd(small, -(height * height)).sqrt();
414 if big - reach <= 1e-10 * big {
415 return Ok(None);
416 }
417 let middle = center + n * height;
418 return Ok(Some(vec![
419 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
420 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
421 ]));
422 }
423 if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
424 let out = axis.cross(n).normalize()?;
425 return Ok(Some(vec![
426 ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
427 ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
428 ]));
429 }
430 Ok(None)
431}
432
433fn exact_plane_cylinder(
439 cyl: &CylindricalSurface,
440 normal: Vec3,
441 d: f64,
442) -> Result<Vec<ExactIntersectionCurve>, MathError> {
443 let axis = cyl.axis();
444 let cos_theta = normal.dot(axis).abs();
445 let r = cyl.radius();
446
447 if cos_theta < 1e-10 {
448 return Ok(vec![]);
451 }
452
453 let n_dot_axis = normal.dot(axis);
456 let n_dot_origin = dot_np(normal, cyl.origin());
457 let t = (d - n_dot_origin) / n_dot_axis;
458 let center_on_axis = Point3::new(
459 cyl.origin().x() + t * axis.x(),
460 cyl.origin().y() + t * axis.y(),
461 cyl.origin().z() + t * axis.z(),
462 );
463
464 if cos_theta > 1.0 - 1e-10 {
465 let circle = Circle3D::new(center_on_axis, normal, r)?;
467 Ok(vec![ExactIntersectionCurve::Circle(circle)])
468 } else {
469 let semi_minor = r;
473 let semi_major = r / cos_theta;
474
475 let axis_proj = Vec3::new(
479 axis.x() - n_dot_axis * normal.x(),
480 axis.y() - n_dot_axis * normal.y(),
481 axis.z() - n_dot_axis * normal.z(),
482 );
483 let u_axis = axis_proj.normalize()?;
484 let v_axis = normal.cross(u_axis);
485
486 let ellipse = Ellipse3D::with_axes(
487 center_on_axis,
488 normal,
489 semi_major,
490 semi_minor,
491 u_axis,
492 v_axis,
493 )?;
494 Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
495 }
496}
497
498fn exact_plane_sphere(
502 sphere: &SphericalSurface,
503 normal: Vec3,
504 d: f64,
505) -> Result<Vec<ExactIntersectionCurve>, MathError> {
506 let h = dot_np(normal, sphere.center()) - d;
507 let r = sphere.radius();
508
509 if r - h.abs() <= TOUCH * r {
512 return Ok(vec![]);
513 }
514
515 let circle_r = (r.madd(r, -(h * h))).sqrt();
516 let circle_center = Point3::new(
517 h.madd(-normal.x(), sphere.center().x()),
518 h.madd(-normal.y(), sphere.center().y()),
519 h.madd(-normal.z(), sphere.center().z()),
520 );
521
522 let circle = Circle3D::new(circle_center, normal, circle_r)?;
523 Ok(vec![ExactIntersectionCurve::Circle(circle)])
524}
525
526pub fn exact_sphere_sphere(
538 s1: &SphericalSurface,
539 s2: &SphericalSurface,
540) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
541 let delta = s2.center() - s1.center();
542 let d = delta.length();
543 let (r1, r2) = (s1.radius(), s2.radius());
544 let scale = r1.max(r2);
545 if d <= 1e-12 * scale {
546 return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
548 }
549 let normal = delta * (1.0 / d);
550 let (centre, toward, r_small, r_big) = if r1 <= r2 {
553 (s1.center(), normal, r1, r2)
554 } else {
555 (s2.center(), -normal, r2, r1)
556 };
557 let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
558 if along.abs() > r_small - 1e-10 * scale.max(1.0) {
559 return Ok(Some(Vec::new()));
560 }
561 let radius = r_small.madd(r_small, -(along * along)).sqrt();
562 let circle = Circle3D::new(centre + toward * along, normal, radius)?;
563 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
564}
565
566fn exact_plane_cone(
575 cone: &ConicalSurface,
576 normal: Vec3,
577 d: f64,
578 reach: f64,
579) -> Result<Vec<ExactIntersectionCurve>, MathError> {
580 let axis = cone.axis();
581 let cos_theta = normal.dot(axis).abs();
582 let half_angle = cone.half_angle();
583
584 if cos_theta > 1.0 - 1e-10 {
585 let n_dot_axis = normal.dot(axis);
588 let n_dot_apex = dot_np(normal, cone.apex());
589 let t = (d - n_dot_apex) / n_dot_axis;
590
591 if t.abs() < 1e-10 {
596 return Ok(vec![]);
597 }
598
599 let center = Point3::new(
600 cone.apex().x() + t * axis.x(),
601 cone.apex().y() + t * axis.y(),
602 cone.apex().z() + t * axis.z(),
603 );
604 let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
608 if circle_r < 1e-15 {
609 return Ok(vec![]);
610 }
611
612 let circle = Circle3D::new(center, normal, circle_r)?;
613 return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
614 }
615
616 let c = normal.dot(axis);
628 let p2 = (1.0 - c * c).max(0.0);
629 let p = p2.sqrt();
630 let k = half_angle.sin().powi(2);
631 let a_coeff = p2 - k;
632
633 let m = Vec3::new(
635 axis.x() - c * normal.x(),
636 axis.y() - c * normal.y(),
637 axis.z() - c * normal.z(),
638 );
639 let m_len = m.length();
640 if m_len < 1e-12 {
641 let chains = sample_plane_cone(cone, normal, d, reach)?;
644 return Ok(chains
645 .into_iter()
646 .map(ExactIntersectionCurve::Points)
647 .collect());
648 }
649 let e1 = m * (1.0 / m_len);
650 let e2 = normal.cross(e1);
651 let apex = cone.apex();
652 let e = d - dot_np(normal, apex);
653
654 if a_coeff < -1e-9 {
657 let abs_a = -a_coeff; if e * c < 0.0 {
664 return Ok(vec![]);
665 }
666 let s_c = e * c * p / abs_a;
669 let rhs = e * e * k * (1.0 - k) / abs_a;
670 if rhs <= 0.0 {
671 return Ok(vec![]);
672 }
673 let semi_s = (rhs / abs_a).sqrt(); let semi_t = (rhs / k).sqrt(); if semi_s < 1e-12 || semi_t < 1e-12 {
676 return Ok(vec![]);
677 }
678 let center = apex + normal * e + e1 * s_c;
679 let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
680 (semi_s, semi_t, e1, e2)
681 } else {
682 (semi_t, semi_s, e2, e1)
683 };
684 let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
685 return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
686 }
687
688 let chains = sample_plane_cone(cone, normal, d, reach)?;
691 Ok(chains
692 .into_iter()
693 .map(ExactIntersectionCurve::Points)
694 .collect())
695}
696
697#[allow(clippy::many_single_char_names)]
712pub fn plane_cone_conic_arc(
713 cone: &ConicalSurface,
714 normal: Vec3,
715 d: f64,
716 from: Point3,
717 to: Point3,
718) -> Result<Option<NurbsCurve>, MathError> {
719 let len = normal.length();
720 if len < 1e-15 {
721 return Err(MathError::ZeroVector);
722 }
723 let (normal, d) = (normal * (1.0 / len), d / len);
724 let axis = cone.axis();
725 let c = normal.dot(axis);
726 let p2 = (1.0 - c * c).max(0.0);
727 let p = p2.sqrt();
728 let k = cone.half_angle().sin().powi(2);
729 let a_coeff = p2 - k;
730 let m = Vec3::new(
731 axis.x() - c * normal.x(),
732 axis.y() - c * normal.y(),
733 axis.z() - c * normal.z(),
734 );
735 let m_len = m.length();
736 if m_len < 1e-12 || a_coeff < -1e-9 {
737 return Ok(None);
738 }
739 let e1 = m * (1.0 / m_len);
740 let e2 = normal.cross(e1);
741 let apex = cone.apex();
742 let e = d - dot_np(normal, apex);
743 let origin = apex + normal * e;
744 let plane_st = |q: Point3| {
745 let w = q - origin;
746 (w.dot(e1), w.dot(e2))
747 };
748 let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
749 let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
750 if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
751 return Ok(None);
752 }
753 let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
754 let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
755 let (control, weights) = if a_coeff.abs() <= 1e-9 {
756 let lin = 2.0 * e * c * p;
758 if lin.abs() < 1e-12 * scale {
759 return Ok(None);
760 }
761 let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
762 if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
763 || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
764 {
765 return Ok(None);
766 }
767 let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
768 (vec![from, mid, to], vec![1.0; 3])
769 } else {
770 let s_c = -e * c * p / a_coeff;
772 let r = e * e * k * (1.0 - k) / a_coeff;
773 if r <= 0.0 {
774 return Ok(None);
775 }
776 let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
777 let (x0, x1) = (s0 - s_c, s1 - s_c);
778 if x0 * x1 <= 0.0 {
779 return Ok(None);
780 }
781 let side = x0.signum();
782 let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
783 let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
784 if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
785 return Ok(None);
786 }
787 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
788 let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
789 let mut control = vec![from];
790 let mut weights = vec![1.0];
791 for i in 0..pieces {
792 #[allow(clippy::cast_precision_loss)]
793 let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
794 let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
795 let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
796 let w = half.cosh();
797 control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
798 weights.push(w);
799 control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
800 weights.push(1.0);
801 }
802 (control, weights)
803 };
804 let pieces = (control.len() - 1) / 2;
805 let mut knots = vec![0.0; 3];
806 for i in 1..pieces {
807 #[allow(clippy::cast_precision_loss)]
808 knots.extend([i as f64; 2]);
809 }
810 #[allow(clippy::cast_precision_loss)]
811 knots.extend([pieces as f64; 3]);
812 let curve = NurbsCurve::new(2, knots, control, weights)?;
813 let (sin_a, cos_a) = cone.half_angle().sin_cos();
818 let off_cone = |q: Point3| {
819 let w = q - apex;
820 let h = w.dot(axis);
821 (w - axis * h)
822 .length()
823 .madd(sin_a, -(h.abs() * cos_a))
824 .abs()
825 };
826 for i in 0..pieces {
827 for f in [0.25, 0.5, 0.75] {
828 #[allow(clippy::cast_precision_loss)]
829 if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
830 return Ok(None);
831 }
832 }
833 }
834 Ok(Some(curve))
835}
836
837#[derive(Clone, Copy)]
839pub enum AnalyticSurface<'a> {
840 Cylinder(&'a CylindricalSurface),
842 Cone(&'a ConicalSurface),
844 Sphere(&'a SphericalSurface),
846 Torus(&'a ToroidalSurface),
848}
849
850fn dot_np(n: Vec3, p: Point3) -> f64 {
852 n.dot(Vec3::new(p.x(), p.y(), p.z()))
853}
854
855pub fn intersect_plane_analytic(
863 surface: AnalyticSurface<'_>,
864 normal: Vec3,
865 d: f64,
866) -> Result<Vec<IntersectionCurve>, MathError> {
867 match surface {
868 AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
869 AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
870 AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
871 AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
872 }
873}
874
875pub fn sample_plane_analytic(
886 surface: AnalyticSurface<'_>,
887 normal: Vec3,
888 d: f64,
889) -> Result<Vec<Vec<Point3>>, MathError> {
890 match surface {
891 AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
892 AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
893 AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
894 AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
895 }
896}
897
898#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
900fn sample_plane_cylinder(
901 cyl: &CylindricalSurface,
902 normal: Vec3,
903 d: f64,
904) -> Result<Vec<Vec<Point3>>, MathError> {
905 let n_samples = 64_usize;
906 let mut points = Vec::with_capacity(n_samples + 1);
907
908 for i in 0..=n_samples {
909 let u = TAU * (i as f64) / (n_samples as f64);
910 let base = cyl.evaluate(u, 0.0);
911 let n_dot_axis = normal.dot(cyl.axis());
912 let n_dot_base = dot_np(normal, base);
913
914 if n_dot_axis.abs() < 1e-12 {
915 if (n_dot_base - d).abs() < 1e-6 {
916 points.push(base);
917 }
918 } else {
919 let v = (d - n_dot_base) / n_dot_axis;
920 if v.abs() <= 100.0 {
921 points.push(cyl.evaluate(u, v));
922 }
923 }
924 }
925
926 if points.len() < 2 {
927 Ok(vec![])
928 } else {
929 Ok(vec![points])
930 }
931}
932
933#[allow(clippy::cast_precision_loss)]
935fn sample_plane_sphere(
936 sphere: &SphericalSurface,
937 normal: Vec3,
938 d: f64,
939) -> Result<Vec<Vec<Point3>>, MathError> {
940 let h = dot_np(normal, sphere.center()) - d;
941 let r = sphere.radius();
942
943 if h.abs() > r - 1e-10 {
944 return Ok(vec![]);
945 }
946
947 let circle_r = (r.madd(r, -(h * h))).sqrt();
948 let circle_center = Point3::new(
949 h.madd(-normal.x(), sphere.center().x()),
950 h.madd(-normal.y(), sphere.center().y()),
951 h.madd(-normal.z(), sphere.center().z()),
952 );
953
954 let basis = Frame3::from_normal(circle_center, normal)?;
955 let u_dir = basis.x;
956 let v_dir = basis.y;
957
958 let n_samples = 64_usize;
959 let mut points = Vec::with_capacity(n_samples + 1);
960
961 for i in 0..=n_samples {
962 let theta = TAU * (i as f64) / (n_samples as f64);
963 let (sin_t, cos_t) = theta.sin_cos();
964 points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
965 }
966
967 Ok(vec![points])
968}
969
970#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
982fn sample_plane_cone(
983 cone: &ConicalSurface,
984 normal: Vec3,
985 d: f64,
986 reach: f64,
987) -> Result<Vec<Vec<Point3>>, MathError> {
988 let apex = cone.apex();
989 let n_dot_apex = dot_np(normal, apex);
990 let e = d - n_dot_apex;
991
992 let n_samples = 512_usize;
996 let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
997 let mut v_min = f64::INFINITY;
998 for i in 0..n_samples {
999 let u = TAU * (i as f64) / (n_samples as f64);
1000 let g = cone.evaluate(u, 1.0) - apex;
1001 let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
1002 if n_dot_g.abs() < 1e-12 {
1003 vs.push(None);
1004 continue;
1005 }
1006 let v = e / n_dot_g;
1007 if v >= -1e-12 {
1008 let v = v.max(0.0);
1009 v_min = v_min.min(v);
1010 vs.push(Some(v));
1011 } else {
1012 vs.push(None);
1013 }
1014 }
1015
1016 if !v_min.is_finite() {
1017 return Ok(Vec::new());
1018 }
1019
1020 let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1029
1030 let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1033
1034 let point_at = |u: f64, v: f64| -> Point3 {
1035 let g = cone.evaluate(u, 1.0) - apex;
1036 apex + g * v
1037 };
1038 #[allow(clippy::cast_precision_loss)]
1039 let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1040 let n_dot_g_at = |u: f64| -> f64 {
1041 let g = cone.evaluate(u, 1.0) - apex;
1042 normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1043 };
1044
1045 if kept.iter().all(Option::is_some) {
1046 let mut pts: Vec<Point3> = kept
1048 .iter()
1049 .enumerate()
1050 .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1051 .collect();
1052 if let Some(&first) = pts.first() {
1053 pts.push(first);
1054 }
1055 return Ok(vec![pts]);
1056 }
1057
1058 let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1067 let Some(v_end) = kept[i_end] else {
1068 return Vec::new();
1069 };
1070 let u_end = u_of(i_end);
1071 #[allow(clippy::cast_precision_loss)]
1072 let pitch = TAU / (n_samples as f64);
1073 let u_next = if forward {
1074 u_end + pitch
1075 } else {
1076 u_end - pitch
1077 };
1078 let target = e / v_max;
1079 let h_end = n_dot_g_at(u_end) - target;
1080 let h_next = n_dot_g_at(u_next) - target;
1081 if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1082 return Vec::new();
1083 }
1084 let (mut lo, mut hi) = (u_end, u_next);
1085 for _ in 0..60 {
1086 let mid = f64::midpoint(lo, hi);
1087 if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1088 lo = mid;
1089 } else {
1090 hi = mid;
1091 }
1092 }
1093 let u_star = f64::midpoint(lo, hi);
1094 let tail_n = 8_usize;
1095 (1..=tail_n)
1096 .filter_map(|k| {
1097 #[allow(clippy::cast_precision_loss)]
1098 let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1099 let ng = n_dot_g_at(u);
1100 if ng.abs() < 1e-12 {
1101 return None;
1102 }
1103 let v = e / ng;
1104 (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1105 })
1106 .collect()
1107 };
1108
1109 let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1112 let mut chains: Vec<Vec<Point3>> = Vec::new();
1113 let mut run: Vec<usize> = Vec::new();
1114 let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1115 if run.len() >= 2 {
1116 let first = run[0];
1117 let last = run[run.len() - 1];
1118 let mut pts: Vec<Point3> = tail(first, false, &kept);
1119 pts.reverse();
1120 pts.extend(
1121 run.iter()
1122 .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1123 );
1124 pts.extend(tail(last, true, &kept));
1125 chains.push(pts);
1126 }
1127 run.clear();
1128 };
1129 for k in 0..n_samples {
1130 let idx = (gap + k) % n_samples;
1131 if kept[idx].is_some() {
1132 run.push(idx);
1133 } else {
1134 flush(&mut run, &mut chains);
1135 }
1136 }
1137 flush(&mut run, &mut chains);
1138 Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1139}
1140
1141#[allow(clippy::unnecessary_wraps)] fn sample_plane_torus(
1147 torus: &ToroidalSurface,
1148 normal: Vec3,
1149 d: f64,
1150) -> Result<Vec<Vec<Point3>>, MathError> {
1151 Ok(plane_torus_loops(torus, normal, d, 128)
1152 .into_iter()
1153 .map(|run| run.into_iter().map(|p| p.point).collect())
1154 .collect())
1155}
1156
1157#[allow(clippy::cast_precision_loss)]
1167pub fn intersect_plane_cylinder(
1168 cyl: &CylindricalSurface,
1169 normal: Vec3,
1170 d: f64,
1171) -> Result<Vec<IntersectionCurve>, MathError> {
1172 let n_samples = 64_usize;
1173 let mut points_3d = Vec::new();
1174 let mut ipoints = Vec::new();
1175
1176 for i in 0..=n_samples {
1177 let u = TAU * (i as f64) / (n_samples as f64);
1178 let base = cyl.evaluate(u, 0.0);
1181 let n_dot_axis = normal.dot(cyl.axis());
1182 let n_dot_base = dot_np(normal, base);
1183
1184 if n_dot_axis.abs() < 1e-12 {
1185 if (n_dot_base - d).abs() < 1e-6 {
1187 let pt = base;
1188 points_3d.push(pt);
1189 ipoints.push(IntersectionPoint {
1190 point: pt,
1191 param1: (u, 0.0),
1192 param2: (0.0, 0.0),
1193 });
1194 }
1195 } else {
1196 let v = (d - n_dot_base) / n_dot_axis;
1197 if v.abs() <= 100.0 {
1199 let pt = cyl.evaluate(u, v);
1200 points_3d.push(pt);
1201 ipoints.push(IntersectionPoint {
1202 point: pt,
1203 param1: (u, v),
1204 param2: (0.0, 0.0),
1205 });
1206 }
1207 }
1208 }
1209
1210 build_curves_from_points(&points_3d, ipoints)
1211}
1212
1213#[allow(clippy::cast_precision_loss)]
1222pub fn intersect_plane_sphere(
1223 sphere: &SphericalSurface,
1224 normal: Vec3,
1225 d: f64,
1226) -> Result<Vec<IntersectionCurve>, MathError> {
1227 let h = dot_np(normal, sphere.center()) - d;
1228 let r = sphere.radius();
1229
1230 if h.abs() > r - 1e-10 {
1232 return Ok(vec![]);
1233 }
1234
1235 let circle_r = (r.madd(r, -(h * h))).sqrt();
1236 let circle_center = Point3::new(
1237 h.madd(-normal.x(), sphere.center().x()),
1238 h.madd(-normal.y(), sphere.center().y()),
1239 h.madd(-normal.z(), sphere.center().z()),
1240 );
1241
1242 let basis = Frame3::from_normal(circle_center, normal)?;
1244 let u_dir = basis.x;
1245 let v_dir = basis.y;
1246
1247 let n_samples = 64_usize;
1248 let mut points_3d = Vec::new();
1249 let mut ipoints = Vec::new();
1250
1251 for i in 0..=n_samples {
1252 let theta = TAU * (i as f64) / (n_samples as f64);
1253 let (sin_t, cos_t) = theta.sin_cos();
1254 let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1255 points_3d.push(pt);
1256 ipoints.push(IntersectionPoint {
1257 point: pt,
1258 param1: (theta, 0.0),
1259 param2: (0.0, 0.0),
1260 });
1261 }
1262
1263 build_curves_from_points(&points_3d, ipoints)
1264}
1265
1266#[allow(clippy::cast_precision_loss)]
1275pub fn intersect_plane_cone(
1276 cone: &ConicalSurface,
1277 normal: Vec3,
1278 d: f64,
1279) -> Result<Vec<IntersectionCurve>, MathError> {
1280 let n_samples = 64_usize;
1281 let mut points_3d = Vec::new();
1282 let mut ipoints = Vec::new();
1283
1284 for i in 0..n_samples {
1285 let u = TAU * (i as f64) / (n_samples as f64);
1286 let apex = cone.apex();
1289 let n_dot_apex = dot_np(normal, apex);
1290 let p1 = cone.evaluate(u, 1.0);
1292 let dir = p1 - apex;
1293 let n_dot_dir = normal.dot(dir);
1294
1295 if n_dot_dir.abs() < 1e-12 {
1296 continue;
1297 }
1298
1299 let v = (d - n_dot_apex) / n_dot_dir;
1300 if v.abs() > 1e-10 && v.abs() < 100.0 {
1302 let pt = cone.evaluate(u, v);
1303 points_3d.push(pt);
1304 ipoints.push(IntersectionPoint {
1305 point: pt,
1306 param1: (u, v),
1307 param2: (0.0, 0.0),
1308 });
1309 }
1310 }
1311
1312 build_curves_from_points(&points_3d, ipoints)
1313}
1314
1315#[allow(clippy::unnecessary_wraps)]
1327pub fn intersect_plane_torus(
1328 torus: &ToroidalSurface,
1329 normal: Vec3,
1330 d: f64,
1331) -> Result<Vec<IntersectionCurve>, MathError> {
1332 let mut curves = Vec::new();
1336 for ipts in plane_torus_loops(torus, normal, d, 128) {
1337 let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1338 if let Ok(curve) = fit_plane_torus_section(torus, normal, d, &pts) {
1339 curves.push(IntersectionCurve {
1340 curve,
1341 points: ipts,
1342 });
1343 }
1344 }
1345
1346 Ok(curves)
1347}
1348
1349#[must_use]
1361pub fn plane_torus_section_point(
1362 torus: &ToroidalSurface,
1363 normal: Vec3,
1364 d: f64,
1365 p: Point3,
1366) -> Option<Point3> {
1367 plane_torus_newton(torus, normal, d, p, 0.0)
1368}
1369
1370fn plane_torus_newton(
1375 torus: &ToroidalSurface,
1376 normal: Vec3,
1377 d: f64,
1378 p: Point3,
1379 short: f64,
1380) -> Option<Point3> {
1381 let scale = normal.length();
1382 if scale <= 0.0 || !scale.is_finite() {
1383 return None;
1384 }
1385 let n = normal * (1.0 / scale);
1386 let d = d / scale;
1387 let (axis, centre) = (torus.z_axis(), torus.center());
1388 let (big, small) = (torus.major_radius(), torus.minor_radius());
1389 let radial_of = |x: Point3| {
1390 let w = x - centre;
1391 w - axis * axis.dot(w)
1392 };
1393 let side = {
1396 let radial = radial_of(p);
1397 let rho = radial.length();
1398 let h = axis.dot(p - centre);
1399 if (rho + big).hypot(h) - small < ((rho - big).hypot(h) - small).abs() {
1400 -1.0
1401 } else {
1402 1.0
1403 }
1404 };
1405 let residuals = |x: Point3| -> Option<(f64, f64, Vec3)> {
1407 let radial = radial_of(x);
1408 let rho = radial.length();
1409 if rho <= 0.0 {
1410 return None;
1411 }
1412 let to = (x - centre) - radial * (side * big / rho);
1413 let reach = to.length();
1414 if reach <= 0.0 {
1415 return None;
1416 }
1417 Some((dot_np(n, x) - d, reach - small, to * (1.0 / reach)))
1418 };
1419 let rounding = 16.0 * f64::EPSILON * (big + small + (p - centre).length());
1420 let mut x = p;
1421 for _ in 0..16 {
1422 let (f_plane, f_torus, g) = residuals(x)?;
1423 if f_plane.abs() <= rounding && f_torus.abs() <= rounding {
1424 return Some(x);
1425 }
1426 let c = n.dot(g);
1427 let det = c.madd(-c, 1.0);
1428 if det < 1e-12 {
1429 return None;
1430 }
1431 let along_n = c.madd(-f_torus, f_plane) / det;
1432 let along_g = c.madd(-f_plane, f_torus) / det;
1433 x = x - n * along_n - g * along_g;
1434 if (x - p).length() < short {
1435 return Some(x);
1436 }
1437 }
1438 let (f_plane, f_torus, _) = residuals(x)?;
1439 (f_plane.abs() <= 1e3 * rounding && f_torus.abs() <= 1e3 * rounding).then_some(x)
1440}
1441
1442const PLANE_TORUS_FIT: f64 = 1e-9;
1445
1446const PLANE_TORUS_FIT_POINTS: usize = 4096;
1448
1449pub fn fit_plane_torus_section(
1469 torus: &ToroidalSurface,
1470 normal: Vec3,
1471 d: f64,
1472 points: &[Point3],
1473) -> Result<NurbsCurve, MathError> {
1474 let tol = PLANE_TORUS_FIT.madd(
1475 torus.major_radius() + torus.minor_radius(),
1476 64.0 * f64::EPSILON * (torus.center() - Point3::new(0.0, 0.0, 0.0)).length(),
1477 );
1478 let strays = |p: Point3| {
1481 let w = p - torus.center();
1482 let height = torus.z_axis().dot(w);
1483 let rho = (w - torus.z_axis() * height).length();
1484 let off_torus = [1.0, -1.0]
1485 .into_iter()
1486 .map(|side: f64| {
1487 (side.madd(-torus.major_radius(), rho).hypot(height) - torus.minor_radius()).abs()
1488 })
1489 .fold(f64::INFINITY, f64::min);
1490 ((dot_np(normal, p) - d) / normal.length())
1491 .abs()
1492 .max(off_torus)
1493 };
1494 let mut pts = points.to_vec();
1495 let mut passes = 0;
1496 loop {
1497 passes += 1;
1498 let curve = interpolate(&pts, 3.min(pts.len().saturating_sub(1)))?;
1499 let params = crate::nurbs::fitting::chord_length_params(&pts);
1500 let mut finer = Vec::with_capacity(2 * pts.len());
1501 let mut added = false;
1502 for (i, pair) in pts.windows(2).enumerate() {
1503 finer.push(pair[0]);
1504 let gap = (pair[1] - pair[0]).length();
1505 let middle = curve.evaluate(f64::midpoint(params[i], params[i + 1]));
1506 let on = plane_torus_newton(torus, normal, d, middle, 0.25 * tol)
1509 .filter(|on| (*on - middle).length() < 0.5 * gap);
1510 match on {
1511 Some(on) if (on - middle).length() <= tol => {}
1512 Some(on) => {
1513 finer.push(on);
1514 added = true;
1515 }
1516 None if strays(middle) <= tol => {}
1517 None => return Err(MathError::ConvergenceFailure { iterations: passes }),
1518 }
1519 }
1520 if !added {
1521 return Ok(curve);
1522 }
1523 if let Some(&last) = pts.last() {
1524 finer.push(last);
1525 }
1526 if finer.len() > PLANE_TORUS_FIT_POINTS {
1527 return Err(MathError::ConvergenceFailure { iterations: passes });
1528 }
1529 pts = finer;
1530 }
1531}
1532
1533const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1536
1537#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1560fn plane_torus_loops(
1561 torus: &ToroidalSurface,
1562 normal: Vec3,
1563 d: f64,
1564 n_v: usize,
1565) -> Vec<Vec<IntersectionPoint>> {
1566 let big_r = torus.major_radius();
1567 let small_r = torus.minor_radius();
1568 let a = normal.dot(torus.x_axis());
1569 let b = normal.dot(torus.y_axis());
1570 let c = normal.dot(torus.z_axis());
1571 let s = a.hypot(b);
1572 let phi = b.atan2(a);
1573 let d_local = d - dot_np(normal, torus.center());
1574 let point = |u: f64, v: f64| IntersectionPoint {
1575 point: torus.evaluate(u, v),
1576 param1: (u, v.rem_euclid(TAU)),
1577 param2: (0.0, 0.0),
1578 };
1579 let closed = |mut run: Vec<IntersectionPoint>| {
1580 run.push(run[0]);
1581 run
1582 };
1583
1584 if s < 1e-12 {
1586 if c.abs() < 1e-12 {
1587 return Vec::new();
1588 }
1589 let sin_v = d_local / (small_r * c);
1590 if sin_v.abs() > 1.0 + 1e-9 {
1591 return Vec::new();
1592 }
1593 let v0 = sin_v.clamp(-1.0, 1.0).asin();
1594 let v1 = std::f64::consts::PI - v0;
1595 let mut vs = vec![v0];
1596 let apart = (v1 - v0).rem_euclid(TAU);
1599 if apart.min(TAU - apart) > 1e-9 {
1600 vs.push(v1);
1601 }
1602 return vs
1603 .into_iter()
1604 .map(|v| {
1605 closed(
1606 (0..n_v)
1607 .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1608 .collect(),
1609 )
1610 })
1611 .collect();
1612 }
1613
1614 let length = normal.length();
1616 TorusSection {
1617 torus,
1618 phi,
1619 num: [d_local, 0.0, -small_r * c],
1620 den: [s * big_r, s * small_r],
1621 clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1622 slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1623 }
1624 .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1625}
1626
1627struct TorusSection<'a, F> {
1635 torus: &'a ToroidalSurface,
1636 phi: f64,
1637 num: [f64; 3],
1639 den: [f64; 2],
1641 clearance: F,
1643 slack: f64,
1645}
1646
1647impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1648 fn rhs(&self, v: f64) -> f64 {
1649 let [n0, n1, n2] = self.num;
1650 let [d0, d1] = self.den;
1651 let (sin, cos) = v.sin_cos();
1652 n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1653 }
1654
1655 fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1656 IntersectionPoint {
1657 point: self.torus.evaluate(u, v),
1658 param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1659 param2: (0.0, 0.0),
1660 }
1661 }
1662
1663 fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1664 self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1665 }
1666
1667 fn node(&self, v: f64) -> IntersectionPoint {
1669 let u = if self.rhs(v) >= 0.0 {
1670 self.phi
1671 } else {
1672 self.phi + std::f64::consts::PI
1673 };
1674 self.point(u, v)
1675 }
1676
1677 fn depth(&self, v: f64) -> f64 {
1680 (self.clearance)(self.node(v).point).abs()
1681 }
1682
1683 fn crossings(&self) -> Vec<f64> {
1687 let [n0, n1, n2] = self.num;
1688 let [d0, d1] = self.den;
1689 let mut roots = Vec::with_capacity(4);
1690 for c in [1.0_f64, -1.0] {
1691 let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1692 let m = beta.hypot(gamma);
1693 let ratio = -alpha / m;
1694 if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1695 continue;
1696 }
1697 let theta = gamma.atan2(beta);
1698 let delta = ratio.clamp(-1.0, 1.0).acos();
1699 roots.push((theta - delta).rem_euclid(TAU));
1700 roots.push((theta + delta).rem_euclid(TAU));
1701 }
1702 roots.sort_by(f64::total_cmp);
1703 roots
1704 }
1705
1706 fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1712 let roots = self.crossings();
1713 let n = roots.len();
1714 if n == 0 {
1715 let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1716 return if whole {
1717 vec![(0.0, TAU, None, true)]
1718 } else {
1719 Vec::new()
1720 };
1721 }
1722 let arcs: Vec<(f64, f64)> = (0..n)
1723 .map(|i| {
1724 (
1725 roots[i],
1726 if i + 1 < n {
1727 roots[i + 1]
1728 } else {
1729 roots[0] + TAU
1730 },
1731 )
1732 })
1733 .collect();
1734 let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1735 let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1736 let shallow: Vec<bool> = (0..n)
1737 .map(|i| self.depth(middle(i)) <= self.slack)
1738 .collect();
1739 let deep_beside = |i: usize, back: bool| {
1740 (1..n)
1741 .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1742 .find(|&j| !shallow[j])
1743 };
1744 let kept: Vec<bool> = (0..n)
1745 .map(|i| {
1746 if !shallow[i] {
1747 return inside[i];
1748 }
1749 matches!(
1750 (deep_beside(i, true), deep_beside(i, false)),
1751 (Some(a), Some(b)) if inside[a] && inside[b]
1752 )
1753 })
1754 .collect();
1755 let node_in = |from: usize, len: usize| {
1756 (0..len).find_map(|j| {
1757 let i = (from + j) % n;
1758 let wraps = if from + j >= n { TAU } else { 0.0 };
1759 shallow[i].then(|| middle(i) + wraps)
1760 })
1761 };
1762 let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1763 return if kept.iter().all(|&k| k) {
1764 let node = node_in(0, n);
1765 let lo = node.unwrap_or(roots[0]);
1766 vec![(lo, lo + TAU, node, true)]
1767 } else {
1768 Vec::new()
1769 };
1770 };
1771 let mut runs = Vec::new();
1772 let mut j = 0;
1773 while j < n {
1774 let i = (first + j) % n;
1775 if !kept[i] {
1776 j += 1;
1777 continue;
1778 }
1779 let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1780 let last = i + len - 1;
1781 let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1782 runs.push((arcs[i].0, hi, node_in(i, len), false));
1783 j += len;
1784 }
1785 runs
1786 }
1787
1788 #[allow(
1795 clippy::cast_precision_loss,
1796 clippy::cast_possible_truncation,
1797 clippy::cast_sign_loss
1798 )]
1799 fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1800 let closed = |mut run: Vec<IntersectionPoint>| {
1801 run.push(run[0]);
1802 run
1803 };
1804 let step = TAU / (n_v as f64);
1805 let mut loops = Vec::new();
1806 for (t_lo, t_hi, at_node, whole) in self.runs() {
1807 if whole {
1808 for sign in [1.0, -1.0] {
1809 loops.push(closed(match at_node {
1810 Some(v_node) => std::iter::once(self.node(v_node))
1811 .chain(
1812 (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1813 )
1814 .collect(),
1815 None => (0..n_v)
1816 .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1817 .collect(),
1818 }));
1819 }
1820 continue;
1821 }
1822 let len = ((t_hi - t_lo) / step).ceil();
1830 let probes = (len as usize).max(8);
1831 let (u_lo, u_hi) = (0..=probes)
1832 .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1833 .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1834 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1835 (lo.min(u), hi.max(u))
1836 });
1837 let m = len
1838 .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1839 .max(fewest)
1840 .min(most)
1841 .ceil();
1842 let steps = m as usize;
1843 if let Some(v_node) = at_node {
1844 for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1847 let along = |k: usize| {
1848 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1849 (to - from).madd(f, from)
1850 };
1851 let mut pts = vec![self.node(v_node)];
1852 pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1853 pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1854 loops.push(closed(pts));
1855 }
1856 } else {
1857 let at = |k: usize| {
1858 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1859 (t_hi - t_lo).madd(f, t_lo)
1860 };
1861 let mut pts: Vec<IntersectionPoint> =
1862 (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1863 pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1864 loops.push(closed(pts));
1865 }
1866 }
1867 loops
1868 }
1869
1870 fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1873 let half = |from: f64, to: f64| {
1874 let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1875 0.5_f64.madd(gap, from)
1876 };
1877 let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1878 let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1879 let miss =
1880 |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1881 let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1882 1.0
1883 } else {
1884 -1.0
1885 };
1886 self.branch(v, sign)
1887 }
1888}
1889
1890#[allow(clippy::cast_precision_loss)]
1899fn plane_torus_winding_loops(
1900 torus: &ToroidalSurface,
1901 normal: Vec3,
1902 d: f64,
1903 n_v: usize,
1904) -> Option<Vec<Vec<Point3>>> {
1905 let big_r = torus.major_radius();
1906 let small_r = torus.minor_radius();
1907 let a = normal.dot(torus.x_axis());
1908 let b = normal.dot(torus.y_axis());
1909 let c = normal.dot(torus.z_axis());
1910 let s = a.hypot(b);
1911 if s < 1e-12 * normal.length() || small_r >= big_r {
1912 return None;
1913 }
1914 let phi = b.atan2(a);
1915 let d_local = d - dot_np(normal, torus.center());
1916 let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1917 let dense = 8 * n_v;
1918 if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1919 return None;
1920 }
1921 let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1922 for i in 0..n_v {
1923 let v = TAU * i as f64 / n_v as f64;
1924 let delta = rhs(v).acos();
1925 loops[0].push(torus.evaluate(phi + delta, v));
1926 loops[1].push(torus.evaluate(phi - delta, v));
1927 }
1928 Some(
1929 loops
1930 .into_iter()
1931 .map(|mut run| {
1932 run.push(run[0]);
1933 run
1934 })
1935 .collect(),
1936 )
1937}
1938
1939#[must_use]
1953pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1954 let c = torus.center();
1955 let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1956 let big_r = torus.major_radius();
1957 let small_r = torus.minor_radius();
1958
1959 let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1961 let (a0, a1) = (xa.dot(o), xa.dot(dir));
1962 let (b0, b1) = (ya.dot(o), ya.dot(dir));
1963 let (c0, c1) = (za.dot(o), za.dot(dir));
1964
1965 let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1967 let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1968 let g0 = a0.madd(
1969 a0,
1970 b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1971 );
1972
1973 let four_rr = 4.0 * big_r * big_r;
1975 let h2 = four_rr * a1.madd(a1, b1 * b1);
1976 let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1977 let h0 = four_rr * a0.madd(a0, b0 * b0);
1978
1979 let e4 = g2 * g2;
1981 let e3 = 2.0 * g2 * g1;
1982 let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1983 let e1 = 2.0f64.madd(g1 * g0, -h1);
1984 let e0 = g0.madd(g0, -h0);
1985
1986 let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1987 let tube = |t: f64, across: bool| -> f64 {
1993 let p = origin + dir * t;
1994 let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1995 let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1996 let centre = if across { -big_r } else { big_r };
1997 (a.hypot(b) - centre).hypot(cc) - small_r
1998 };
1999 for t in &mut roots {
2000 let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
2001 for _ in 0..8 {
2002 let eps = 1e-7;
2003 let f = tube(*t, across);
2004 let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
2005 if df.abs() <= 1e-12 {
2006 break;
2007 }
2008 let step = f / df;
2009 *t -= step;
2010 if step.abs() < 1e-14 * (1.0 + t.abs()) {
2011 break;
2012 }
2013 }
2014 }
2015 roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2016 roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
2017 roots
2018}
2019
2020fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
2023 if c4.abs() < 1e-14 {
2025 return real_roots_cubic(c3, c2, c1, c0);
2026 }
2027 let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
2029 let eval = |z: Complex| -> Complex {
2030 let mut acc = Complex::new(1.0, 0.0);
2032 acc = acc * z + Complex::new(a, 0.0);
2033 acc = acc * z + Complex::new(b, 0.0);
2034 acc = acc * z + Complex::new(c, 0.0);
2035 acc * z + Complex::new(d, 0.0)
2036 };
2037 let seed = Complex::new(0.4, 0.9);
2039 let mut r = [
2040 Complex::new(1.0, 0.0),
2041 seed,
2042 seed * seed,
2043 seed * seed * seed,
2044 ];
2045 for _ in 0..100 {
2046 let mut max_step = 0.0_f64;
2047 for i in 0..4 {
2048 let mut denom = Complex::new(1.0, 0.0);
2049 for j in 0..4 {
2050 if i != j {
2051 denom = denom * (r[i] - r[j]);
2052 }
2053 }
2054 if denom.norm() < 1e-300 {
2055 continue;
2056 }
2057 let step = eval(r[i]) / denom;
2058 r[i] = r[i] - step;
2059 max_step = max_step.max(step.norm());
2060 }
2061 if max_step < 1e-14 {
2062 break;
2063 }
2064 }
2065 let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
2072 let mut out: Vec<f64> = Vec::new();
2073 for z in r {
2074 if z.im.abs() >= 1e-7 {
2075 continue;
2076 }
2077 let x = z.re;
2078 let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
2081 if p_real(x).abs() > 1e-6 * scale {
2082 continue;
2083 }
2084 if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
2085 continue;
2086 }
2087 out.push(x);
2088 }
2089 out
2090}
2091
2092fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
2094 if a.abs() < 1e-14 {
2095 return real_roots_quadratic(b, c, d);
2096 }
2097 let (b, c, d) = (b / a, c / a, d / a);
2099 let p = c - b * b / 3.0;
2100 let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
2101 let shift = -b / 3.0;
2102 let disc = q * q / 4.0 + p * p * p / 27.0;
2103 if disc > 1e-14 {
2104 let sq = disc.sqrt();
2105 let u = (-q / 2.0 + sq).cbrt();
2106 let v = (-q / 2.0 - sq).cbrt();
2107 vec![u + v + shift]
2108 } else if disc < -1e-14 {
2109 let m = 2.0 * (-p / 3.0).sqrt();
2111 let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
2112 (0..3)
2113 .map(|k| {
2114 m.madd(
2115 (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
2116 shift,
2117 )
2118 })
2119 .collect()
2120 } else {
2121 let u = (-q / 2.0).cbrt();
2123 vec![2.0 * u + shift, -u + shift]
2124 }
2125}
2126
2127fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
2129 if a.abs() < 1e-14 {
2130 if b.abs() < 1e-14 {
2131 return Vec::new();
2132 }
2133 return vec![-c / b];
2134 }
2135 let disc = b * b - 4.0 * a * c;
2136 if disc < 0.0 {
2137 Vec::new()
2138 } else {
2139 let sq = disc.sqrt();
2140 vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
2141 }
2142}
2143
2144#[derive(Clone, Copy)]
2146struct Complex {
2147 re: f64,
2148 im: f64,
2149}
2150
2151impl Complex {
2152 const fn new(re: f64, im: f64) -> Self {
2153 Self { re, im }
2154 }
2155 fn norm(self) -> f64 {
2156 self.re.hypot(self.im)
2157 }
2158}
2159
2160impl std::ops::Add for Complex {
2161 type Output = Self;
2162 fn add(self, o: Self) -> Self {
2163 Self::new(self.re + o.re, self.im + o.im)
2164 }
2165}
2166
2167impl std::ops::Sub for Complex {
2168 type Output = Self;
2169 fn sub(self, o: Self) -> Self {
2170 Self::new(self.re - o.re, self.im - o.im)
2171 }
2172}
2173
2174impl std::ops::Mul for Complex {
2175 type Output = Self;
2176 fn mul(self, o: Self) -> Self {
2177 Self::new(
2178 self.re.madd(o.re, -(self.im * o.im)),
2179 self.re.madd(o.im, self.im * o.re),
2180 )
2181 }
2182}
2183
2184impl std::ops::Div for Complex {
2185 type Output = Self;
2186 fn div(self, o: Self) -> Self {
2187 let den = o.re.madd(o.re, o.im * o.im);
2188 Self::new(
2189 self.re.madd(o.re, self.im * o.im) / den,
2190 self.im.madd(o.re, -(self.re * o.im)) / den,
2191 )
2192 }
2193}
2194
2195fn build_curves_from_points(
2199 points_3d: &[Point3],
2200 ipoints: Vec<IntersectionPoint>,
2201) -> Result<Vec<IntersectionCurve>, MathError> {
2202 if points_3d.len() < 2 {
2203 return Ok(vec![]);
2204 }
2205
2206 let degree = 3.min(points_3d.len() - 1);
2207 let curve = interpolate(points_3d, degree)?;
2208 Ok(vec![IntersectionCurve {
2209 curve,
2210 points: ipoints,
2211 }])
2212}
2213
2214#[allow(
2226 clippy::cast_precision_loss,
2227 clippy::too_many_lines,
2228 clippy::similar_names,
2229 clippy::unnecessary_wraps,
2230 clippy::type_complexity
2231)]
2232pub fn intersect_analytic_analytic(
2233 a: AnalyticSurface<'_>,
2234 b: AnalyticSurface<'_>,
2235 grid_res: usize,
2236) -> Result<Vec<IntersectionCurve>, MathError> {
2237 intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2238}
2239
2240pub fn intersect_analytic_analytic_bounded(
2251 a: AnalyticSurface<'_>,
2252 b: AnalyticSurface<'_>,
2253 grid_res: usize,
2254 v_range_hint_a: Option<(f64, f64)>,
2255 v_range_hint_b: Option<(f64, f64)>,
2256) -> Result<Vec<IntersectionCurve>, MathError> {
2257 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2258}
2259
2260pub fn intersect_analytic_analytic_in_region(
2273 a: AnalyticSurface<'_>,
2274 b: AnalyticSurface<'_>,
2275 grid_res: usize,
2276 v_range_hint_a: Option<(f64, f64)>,
2277 v_range_hint_b: Option<(f64, f64)>,
2278 region: Aabb3,
2279) -> Result<Vec<IntersectionCurve>, MathError> {
2280 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2281}
2282
2283fn intersect_analytic_analytic_impl(
2284 a: AnalyticSurface<'_>,
2285 b: AnalyticSurface<'_>,
2286 grid_res: usize,
2287 v_range_hint_a: Option<(f64, f64)>,
2288 v_range_hint_b: Option<(f64, f64)>,
2289 region: Option<Aabb3>,
2290) -> Result<Vec<IntersectionCurve>, MathError> {
2291 if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2294 return Ok(result);
2295 }
2296 marched_sections(a, b, grid_res, v_range_hint_a, v_range_hint_b, region)
2297}
2298
2299fn add_product(x: f64, y: f64, t: f64) -> f64 {
2303 let split = |v: f64| {
2304 let c = 134_217_729.0 * v;
2305 let hi = c - (c - v);
2306 (hi, v - hi)
2307 };
2308 let p = y * t;
2309 let ((yh, yl), (th, tl)) = (split(y), split(t));
2310 let p_err = yl.madd(tl, yl.madd(th, yh.madd(tl, yh.madd(th, -p))));
2311 let s = x + p;
2312 let back = s - x;
2313 let s_err = (x - (s - back)) + (p - back);
2314 s + (s_err + p_err)
2315}
2316
2317enum Moved {
2319 Cylinder(CylindricalSurface),
2320 Cone(ConicalSurface),
2321 Sphere(SphericalSurface),
2322 Torus(ToroidalSurface),
2323}
2324
2325impl Moved {
2326 fn new(surface: &AnalyticSurface<'_>, anchor: Point3) -> (Self, f64, f64) {
2340 let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2341 let shift = Point3::new(0.0, 0.0, 0.0) - anchor;
2342 match surface {
2343 AnalyticSurface::Cylinder(c) => {
2344 let (o, a) = (c.origin(), c.axis());
2345 let along = a.dot(anchor - o);
2346 let foot = Point3::new(
2347 add_product(o.x(), a.x(), along),
2348 add_product(o.y(), a.y(), along),
2349 add_product(o.z(), a.z(), along),
2350 );
2351 let near = foot + shift;
2352 let error = 4.0 * f64::EPSILON * (size(foot) + size(near));
2353 (Self::Cylinder(c.framed_at(near)), along, error)
2354 }
2355 AnalyticSurface::Cone(c) => {
2356 let near = c.translated(shift);
2357 let error = 2.0 * f64::EPSILON * size(near.apex());
2358 (Self::Cone(near), 0.0, error)
2359 }
2360 AnalyticSurface::Sphere(s) => {
2361 let near = s.translated(shift);
2362 let error = 2.0 * f64::EPSILON * size(near.center());
2363 (Self::Sphere(near), 0.0, error)
2364 }
2365 AnalyticSurface::Torus(t) => {
2366 let near = t.translated(shift);
2367 let error = 2.0 * f64::EPSILON * size(near.center());
2368 (Self::Torus(near), 0.0, error)
2369 }
2370 }
2371 }
2372
2373 const fn surface(&self) -> AnalyticSurface<'_> {
2374 match self {
2375 Self::Cylinder(c) => AnalyticSurface::Cylinder(c),
2376 Self::Cone(c) => AnalyticSurface::Cone(c),
2377 Self::Sphere(s) => AnalyticSurface::Sphere(s),
2378 Self::Torus(t) => AnalyticSurface::Torus(t),
2379 }
2380 }
2381}
2382
2383fn marched_sections(
2398 a: AnalyticSurface<'_>,
2399 b: AnalyticSurface<'_>,
2400 grid_res: usize,
2401 v_range_hint_a: Option<(f64, f64)>,
2402 v_range_hint_b: Option<(f64, f64)>,
2403 region: Option<Aabb3>,
2404) -> Result<Vec<IntersectionCurve>, MathError> {
2405 let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2406 let (anchor, reach) = if let Some(r) = region {
2407 (r.min + (r.max - r.min) * 0.5, (r.max - r.min).length())
2408 } else {
2409 let (surf_a, _, (u0, u1), default_v_a) = surface_closures(&a);
2410 let (v0, v1) = v_range_hint_a.unwrap_or(default_v_a);
2411 let (first, last) = (surf_a(u0, v0), surf_a(u1, v1));
2412 let reach = patch_diagonal(surf_a.as_ref(), (u0, u1), (v0, v1));
2413 (first + (last - first) * 0.5, reach)
2414 };
2415 let shift = anchor - Point3::new(0.0, 0.0, 0.0);
2416 let ((near_a, dv_a, moved_a), (near_b, dv_b, moved_b)) =
2417 (Moved::new(&a, anchor), Moved::new(&b, anchor));
2418 let v_range = |surface: &AnalyticSurface<'_>, hint: Option<(f64, f64)>, dv: f64| {
2419 let (lo, hi) = hint.unwrap_or_else(|| surface_closures(surface).3);
2420 Some((lo - dv, hi - dv))
2421 };
2422 let linear = Tolerance::new().linear;
2423 let fit_tol =
2424 ((-f64::EPSILON).madd(size(anchor) + reach, linear) - moved_a - moved_b).min(linear);
2425 let near_region = region.map(|r| Aabb3 {
2426 min: r.min - shift,
2427 max: r.max - shift,
2428 });
2429 let curves = marched_sections_near(
2430 near_a.surface(),
2431 near_b.surface(),
2432 grid_res,
2433 v_range(&a, v_range_hint_a, dv_a),
2434 v_range(&b, v_range_hint_b, dv_b),
2435 near_region,
2436 fit_tol,
2437 )?;
2438 curves
2439 .into_iter()
2440 .map(|c| {
2441 let ctrl = c
2442 .curve
2443 .control_points()
2444 .iter()
2445 .map(|&p| p + shift)
2446 .collect();
2447 let curve = NurbsCurve::new(
2448 c.curve.degree(),
2449 c.curve.knots().to_vec(),
2450 ctrl,
2451 c.curve.weights().to_vec(),
2452 )?;
2453 let points = c
2454 .points
2455 .into_iter()
2456 .map(|ip| IntersectionPoint {
2457 point: ip.point + shift,
2458 ..ip
2459 })
2460 .collect();
2461 Ok(IntersectionCurve { curve, points })
2462 })
2463 .collect()
2464}
2465
2466#[allow(clippy::too_many_lines, clippy::similar_names)]
2470fn marched_sections_near(
2471 a: AnalyticSurface<'_>,
2472 b: AnalyticSurface<'_>,
2473 grid_res: usize,
2474 v_range_hint_a: Option<(f64, f64)>,
2475 v_range_hint_b: Option<(f64, f64)>,
2476 region: Option<Aabb3>,
2477 fit_tol: f64,
2478) -> Result<Vec<IntersectionCurve>, MathError> {
2479 let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2480 let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2481 let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2482 let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2483
2484 let diag_a = patch_diagonal(surf_a.as_ref(), u_range_a, v_range_a);
2486 let diag_b = patch_diagonal(surf_b.as_ref(), u_range_b, v_range_b);
2487 let char_size = diag_a.min(diag_b).max(0.1);
2488
2489 let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2490 let meet = region;
2491 #[allow(clippy::cast_precision_loss)]
2492 let margin = 2.0 * char_size / grid_res as f64;
2493 let region = region.map(|r| r.expanded(margin));
2494
2495 let cells = |surface: &AnalyticSurface<'_>,
2504 surf: &dyn Fn(f64, f64) -> Point3,
2505 (u_range, v_range): ((f64, f64), (f64, f64)),
2506 other: &AnalyticSurface<'_>,
2507 near: Option<Aabb3>| {
2508 #[allow(clippy::cast_precision_loss)]
2509 let n = grid_res as f64;
2510 let (du, dv) = ((u_range.1 - u_range.0) / n, (v_range.1 - v_range.0) / n);
2511 let mut found = Vec::new();
2512 let mut kept = Vec::new();
2513 let mut held: Option<Aabb3> = None;
2514 for i in 0..grid_res {
2515 for j in 0..grid_res {
2516 #[allow(clippy::cast_precision_loss)]
2517 let (u, v) = (
2518 du.madd(i as f64 + 0.5, u_range.0),
2519 dv.madd(j as f64 + 0.5, v_range.0),
2520 );
2521 let middle = surf(u, v);
2522 let reach = cell_reach(surface, (0.5 * du, 0.5 * dv), v);
2523 let placed = reach.is_finite()
2524 && middle.x().is_finite()
2525 && middle.y().is_finite()
2526 && middle.z().is_finite();
2527 if placed && near.is_some_and(|r| !r.expanded(reach).contains_point(middle)) {
2528 continue;
2529 }
2530 let reading = section_fit::Carrier::distance(other, middle)
2531 .filter(|(d, n)| d.is_finite() && n.length().is_finite());
2532 let slack = || {
2535 let size = middle.x().abs().max(middle.y().abs()).max(middle.z().abs());
2536 128.0
2537 * f64::EPSILON
2538 * (section_fit::Carrier::scale(surface, middle)
2539 + section_fit::Carrier::scale(other, middle)
2540 + size)
2541 };
2542 let (dist, seed) = match reading {
2543 Some((d, _))
2544 if placed
2545 && d.abs() > reach
2546 && (d.abs() > 2.0 * reach || d.abs() - slack() > reach) =>
2547 {
2548 continue;
2549 }
2550 Some((d, n)) => (d.abs(), middle - n * (0.5 * d)),
2551 None => (f64::INFINITY, middle),
2552 };
2553 found.push((dist, seed));
2554 kept.push((i, j));
2555 let cell = if placed {
2556 Aabb3 {
2557 min: middle,
2558 max: middle,
2559 }
2560 .expanded(reach)
2561 } else {
2562 Aabb3 {
2563 min: Point3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2564 max: Point3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2565 }
2566 };
2567 held = Some(held.map_or(cell, |h| h.union(cell)));
2568 }
2569 }
2570 (found, held, kept)
2571 };
2572 let (mut candidates, held, kept_a) =
2573 cells(&a, surf_a.as_ref(), (u_range_a, v_range_a), &b, region);
2574
2575 let Some(held) = held else {
2580 return Ok(vec![]);
2581 };
2582 let mut cover = cover::Cover::new(
2590 &a,
2591 &b,
2592 (u_range_a, v_range_a),
2593 v_range_b,
2594 grid_res,
2595 &kept_a,
2596 meet.zip(region),
2597 Tolerance::new().linear,
2598 cover::MOST_LEAVES,
2599 );
2600 if !cover.complete() {
2604 candidates.extend(cells(&b, surf_b.as_ref(), (u_range_b, v_range_b), &a, Some(held)).0);
2605 }
2606 candidates.sort_by(|p, q| p.0.total_cmp(&q.0));
2607
2608 let settle = |mid: Point3| {
2619 let on = settle_on_section(&a, &b, mid).or_else(|| {
2620 let mut p = mid;
2621 for _ in 0..8 {
2622 let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2623 let pa = surf_a(ua, va);
2624 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2625 let pb = surf_b(ub, vb);
2626 p = Point3::new(
2627 (pa.x() + pb.x()) * 0.5,
2628 (pa.y() + pb.y()) * 0.5,
2629 (pa.z() + pb.z()) * 0.5,
2630 );
2631 if (pa - pb).length() < 1e-9 {
2632 break;
2633 }
2634 }
2635 settle_on_section(&a, &b, p)
2636 });
2637 let near_patches = |q: Point3| {
2640 let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2641 let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2642 (q - surf_a(ua, va)).length() <= march_step
2643 && (q - surf_b(ub, vb)).length() <= march_step
2644 };
2645 let Some(on) = on.filter(|&on| {
2646 crosses_at(&a, &b, on)
2647 && near_patches(on)
2648 && region.is_none_or(|r| r.contains_point(on))
2649 }) else {
2650 return Ok(None);
2651 };
2652 station(&a, &b, on, Vec3::new(0.0, 0.0, 0.0))
2655 .map(Some)
2656 .ok_or(MathError::ConvergenceFailure { iterations: 0 })
2657 };
2658 let off_patch = |q: Point3| {
2659 let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2660 let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2661 (!is_u_periodic(&a) && (ua <= u_range_a.0 || ua >= u_range_a.1))
2662 || va <= v_range_a.0
2663 || va >= v_range_a.1
2664 || (!is_u_periodic(&b) && (ub <= u_range_b.0 || ub >= u_range_b.1))
2665 || vb <= v_range_b.0
2666 || vb >= v_range_b.1
2667 };
2668
2669 let trace = |seed: Point3,
2679 marched: &mut Vec<Vec<Point3>>,
2680 curves: &mut Vec<IntersectionCurve>|
2681 -> Result<Option<Vec<Point3>>, MathError> {
2682 let march_result = march_analytic_intersection(
2683 &a,
2684 &b,
2685 surf_a.as_ref(),
2686 norm_a.as_ref(),
2687 surf_b.as_ref(),
2688 norm_b.as_ref(),
2689 seed,
2690 u_range_a,
2691 v_range_a,
2692 u_range_b,
2693 v_range_b,
2694 march_step,
2695 is_u_periodic(&a),
2696 is_u_periodic(&b),
2697 region,
2698 )
2699 .ok_or(MathError::ConvergenceFailure {
2700 iterations: MARCH_STEPS,
2701 })?;
2702 if march_result.len() < 2 {
2703 return Ok(None);
2704 }
2705 let middle = march_result[march_result.len() / 2];
2706 if marched.iter().any(|m| on_march(&a, &b, middle, m)) {
2707 return Ok(Some(march_result));
2708 }
2709
2710 let crowd = 1e-3 * march_step;
2712 let mut spaced: Vec<Point3> = Vec::with_capacity(march_result.len());
2713 for (k, &p) in march_result.iter().enumerate() {
2714 let last = k + 1 == march_result.len();
2715 match spaced.last() {
2716 Some(&q) if (p - q).length() < crowd => {
2717 if last && spaced.len() > 1 {
2718 spaced.pop();
2719 spaced.push(p);
2720 }
2721 }
2722 _ => spaced.push(p),
2723 }
2724 }
2725 if spaced.len() < 2 {
2726 match (march_result.first(), march_result.last()) {
2729 (Some(&first), Some(&last)) if (last - first).length() > 0.0 => {
2730 spaced = vec![first, last];
2731 }
2732 _ => return Ok(None),
2733 }
2734 }
2735 if fit_tol < 0.5 * Tolerance::new().linear {
2736 return Err(MathError::ConvergenceFailure { iterations: 0 });
2737 }
2738 let (curve, points) = fit_section(&a, &b, &spaced, fit_tol)?;
2739 let ipts: Vec<IntersectionPoint> = points
2740 .iter()
2741 .map(|&pt| IntersectionPoint {
2742 point: pt,
2743 param1: (0.0, 0.0),
2744 param2: (0.0, 0.0),
2745 })
2746 .collect();
2747 marched.push(march_result.clone());
2748 curves.push(IntersectionCurve {
2749 curve,
2750 points: ipts,
2751 });
2752 Ok(Some(march_result))
2753 };
2754
2755 let mut curves = Vec::new();
2756 let mut marched: Vec<Vec<Point3>> = Vec::new();
2757 let mut past_edges = Vec::new();
2758 let mut k = 0;
2759 while k < candidates.len() + past_edges.len() {
2760 let seed = if k < candidates.len() {
2761 let mid = candidates[k].1;
2762 k += 1;
2763 let Some(seed) = settle(mid)? else {
2764 continue;
2765 };
2766 if off_patch(seed.p) {
2767 past_edges.push(seed);
2768 continue;
2769 }
2770 seed
2771 } else {
2772 k += 1;
2773 past_edges[k - 1 - candidates.len()]
2774 };
2775 if marched.iter().any(|m| on_march(&a, &b, seed.p, m)) {
2776 continue;
2777 }
2778 trace(seed.p, &mut marched, &mut curves)?;
2779 }
2780
2781 for m in &marched {
2782 cover.mark_marched(m);
2783 }
2784 let (marched, curves) = (RefCell::new(marched), RefCell::new(curves));
2785 let fitted = |cover: &cover::Cover<'_, '_>, class: &[usize], z: Point3| {
2789 curves.borrow().iter().any(|c| {
2790 crate::nurbs::projection::project_point_to_curve(&c.curve, z, 1e-12)
2791 .is_ok_and(|f| cover.holds(class, f.point, fit_tol))
2792 })
2793 };
2794 let mut seed = |z: Point3| -> Result<Option<Vec<Point3>>, MathError> {
2796 let Some(seed) = settle(z)? else {
2797 return Ok(None);
2798 };
2799 if marched.borrow().iter().any(|m| on_march(&a, &b, seed.p, m)) {
2800 return Ok(Some(vec![seed.p]));
2801 }
2802 let traced = trace(seed.p, &mut marched.borrow_mut(), &mut curves.borrow_mut())?;
2803 Ok(Some(traced.unwrap_or_default()))
2804 };
2805 while cover.complete() {
2808 let classes = cover.classes();
2809 if classes.is_empty() {
2810 break;
2811 }
2812 for class in classes {
2813 cover.resolve(&class, &fitted, &mut seed)?;
2814 }
2815 }
2816
2817 Ok(curves.into_inner())
2818}
2819
2820fn cell_reach(surface: &AnalyticSurface<'_>, (du, dv): (f64, f64), v: f64) -> f64 {
2824 match surface {
2825 AnalyticSurface::Cylinder(c) => du.madd(c.radius(), dv),
2826 AnalyticSurface::Cone(c) => (du * c.half_angle().cos()).madd(v.abs() + dv, dv),
2827 AnalyticSurface::Sphere(s) => (du + dv) * s.radius(),
2828 AnalyticSurface::Torus(t) => {
2829 du.madd(t.major_radius() + t.minor_radius(), dv * t.minor_radius())
2830 }
2831 }
2832}
2833
2834fn on_march(
2845 a: &AnalyticSurface<'_>,
2846 b: &AnalyticSurface<'_>,
2847 p: Point3,
2848 points: &[Point3],
2849) -> bool {
2850 use section_fit::Carrier;
2851 let nearest = points
2852 .windows(2)
2853 .map(|w| {
2854 let chord = w[1] - w[0];
2855 let len2 = chord.dot(chord);
2856 let s = if len2 > 0.0 {
2857 ((p - w[0]).dot(chord) / len2).clamp(0.0, 1.0)
2858 } else {
2859 0.0
2860 };
2861 let foot = w[0] + chord * s;
2862 ((p - foot).length(), len2.sqrt(), foot, w)
2863 })
2864 .min_by(|x, y| x.0.total_cmp(&y.0));
2865 let Some((off, len, foot, w)) = nearest else {
2866 return false;
2867 };
2868 let sheets = |q: Point3| (a.sheet(q), b.sheet(q));
2869 if off > MARCH_TURN * len || sheets(w[0]) != sheets(p) || sheets(w[1]) != sheets(p) {
2870 return false;
2871 }
2872 let tol = Tolerance::new().linear;
2873 let mut guess = foot;
2874 for _ in 0..8 {
2875 let Some(q) = settle_on_section(a, b, guess) else {
2876 return false;
2877 };
2878 if sheets(q) != sheets(p) {
2879 return false;
2880 }
2881 let miss = p - q;
2882 if miss.length() <= tol {
2883 return true;
2884 }
2885 let (Some((_, na)), Some((_, nb))) = (a.distance(q), b.distance(q)) else {
2886 return false;
2887 };
2888 let t = na.cross(nb);
2889 let sin = t.length();
2890 if sin <= 0.0 {
2891 return false;
2892 }
2893 let t = t * (1.0 / sin);
2894 guess = q + t * miss.dot(t);
2895 }
2896 false
2897}
2898
2899fn patch_diagonal(
2904 surf: &dyn Fn(f64, f64) -> Point3,
2905 (u0, u1): (f64, f64),
2906 (v0, v1): (f64, f64),
2907) -> f64 {
2908 let corner = (surf(u0, v0) - surf(u1, v1)).length();
2909 let middle = (surf(u0, v0) - surf(f64::midpoint(u0, u1), f64::midpoint(v0, v1))).length();
2910 if corner > 1e-9 * middle {
2911 corner
2912 } else {
2913 middle
2914 }
2915}
2916
2917#[allow(clippy::too_many_lines)]
2931fn try_algebraic_intersection(
2932 a: &AnalyticSurface<'_>,
2933 b: &AnalyticSurface<'_>,
2934 v_range_a: Option<(f64, f64)>,
2935 v_range_b: Option<(f64, f64)>,
2936) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2937 match (a, b) {
2938 (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2939 algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2940 .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2941 ),
2942 (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2943 algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2944 .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2945 ),
2946 (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2947 algebraic_sphere_sphere(s1, s2).map(Some)
2948 }
2949 (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2950 let axis_dot = c1.axis().dot(c2.axis()).abs();
2951 if axis_dot > 1.0 - 1e-10 {
2952 let delta = c2.origin() - c1.origin();
2954 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2955 let along = delta_vec.dot(c1.axis());
2956 let perp = (delta_vec - c1.axis() * along).length();
2957 if perp < 1e-8 {
2958 if (c1.radius() - c2.radius()).abs() < 1e-8 {
2961 return Ok(None); }
2963 return Ok(Some(vec![])); }
2965 if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2966 return Ok(Some(rulings));
2967 }
2968 }
2969 algebraic_cylinder_cylinder(c1, c2)
2971 }
2972 (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2974 algebraic_sphere_cylinder(s, c, true)
2975 }
2976 (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2977 algebraic_sphere_cylinder(s, c, false)
2978 }
2979 (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2980 if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2981 return Ok(Some(rulings));
2982 }
2983 if let Some(curves) = algebraic_cone_cone(c1, c2)? {
2984 return Ok(Some(curves));
2985 }
2986 Ok(algebraic_parallel_cone_cone(c1, c2, v_range_a, v_range_b))
2987 }
2988 (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2989 Ok(ruling_cone_sphere(cone, sphere, true))
2990 }
2991 (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2992 Ok(ruling_cone_sphere(cone, sphere, false))
2993 }
2994 (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2995 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2996 return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2997 .map(Some);
2998 }
2999 Ok(parallel_axis_torus_cylinder(t, c, true)
3000 .or_else(|| ruling_torus_cylinder(t, c, true)))
3001 }
3002 (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
3003 if let Some(exacts) = exact_cylinder_torus(c, t)? {
3004 return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
3005 .map(Some);
3006 }
3007 Ok(parallel_axis_torus_cylinder(t, c, false)
3008 .or_else(|| ruling_torus_cylinder(t, c, false)))
3009 }
3010 (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
3011 match exact_sphere_torus(s, t)? {
3012 Some(exacts) => {
3013 exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
3014 .map(Some)
3015 }
3016 None => Ok(sphere_torus_curves(s, t, true)),
3017 }
3018 }
3019 (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
3020 match exact_sphere_torus(s, t)? {
3021 Some(exacts) => {
3022 exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
3023 .map(Some)
3024 }
3025 None => Ok(sphere_torus_curves(s, t, false)),
3026 }
3027 }
3028 (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
3029 .map(|exacts| {
3030 exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
3031 })
3032 .transpose(),
3033 (AnalyticSurface::Cone(c), AnalyticSurface::Torus(t)) => exact_cone_torus(c, t)?
3034 .map(|exacts| exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p))))
3035 .transpose(),
3036 (AnalyticSurface::Torus(t), AnalyticSurface::Cone(c)) => exact_cone_torus(c, t)?
3037 .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p))))
3038 .transpose(),
3039 }
3040}
3041
3042fn parallel_axis_torus_cylinder(
3049 torus: &ToroidalSurface,
3050 cyl: &CylindricalSurface,
3051 torus_first: bool,
3052) -> Option<Vec<IntersectionCurve>> {
3053 let axis = torus.z_axis();
3054 let along = cyl.axis().dot(axis);
3055 if along.abs() < 1.0 - 1e-10 {
3056 return None;
3057 }
3058 let offset = cyl.origin() - torus.center();
3059 if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
3060 return None;
3061 }
3062 let (major, minor) = (torus.major_radius(), torus.minor_radius());
3063 let roots = |u: f64| {
3064 let q = cyl.evaluate(u, 0.0) - torus.center();
3065 let height = q.dot(axis);
3066 let rho = (q - axis * height).length();
3067 let reach = minor * minor - (rho - major) * (rho - major);
3068 ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
3069 };
3070 let samples = ruling_samples(cyl, &roots);
3071 let loops = if samples.iter().all(Option::is_some) {
3072 closed_ruling_loops(cyl, &roots, &samples)
3073 } else {
3074 partial_ruling_loops(cyl, &roots, &samples)
3075 };
3076 if loops.is_empty() {
3077 return None;
3078 }
3079 Some(fit_ruling_loops(&loops, |p| {
3080 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3081 }))
3082}
3083
3084fn meridian_crossings(
3091 first: (f64, f64, f64),
3092 second: (f64, f64, f64),
3093 scale: f64,
3094) -> Option<Vec<(f64, f64)>> {
3095 let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
3096 let (dx, dz) = (x2 - x1, z2 - z1);
3097 let dist = dx.hypot(dz);
3098 let slack = 1e-9 * scale;
3099 if dist < slack {
3100 return None;
3101 }
3102 let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
3103 if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
3104 return Some(Vec::new());
3105 }
3106 let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
3107 let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
3108 let (ux, uz) = (dx / dist, dz / dist);
3109 let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
3110 &[0.0]
3111 } else {
3112 &[1.0, -1.0]
3113 };
3114 let mut crossings = Vec::with_capacity(sides.len());
3115 for side in sides {
3116 let rho = x1 + along * ux - side * across * uz;
3117 if rho <= slack {
3118 return None;
3119 }
3120 crossings.push((rho, z1 + along * uz + side * across * ux));
3121 }
3122 Some(crossings)
3123}
3124
3125fn exact_circle_curves(
3129 exacts: Vec<ExactIntersectionCurve>,
3130 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3131) -> Result<Vec<IntersectionCurve>, MathError> {
3132 let mut curves = Vec::with_capacity(exacts.len());
3133 for exact in exacts {
3134 match exact {
3135 ExactIntersectionCurve::Circle(circle) => {
3136 let points = (0..=32)
3137 .map(|i| {
3138 let point = circle.evaluate(TAU * f64::from(i) / 32.0);
3139 let (param1, param2) = params(point);
3140 IntersectionPoint {
3141 point,
3142 param1,
3143 param2,
3144 }
3145 })
3146 .collect();
3147 let r = circle.radius();
3148 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3149 curves.push(IntersectionCurve { curve, points });
3150 }
3151 ExactIntersectionCurve::Points(points) if points.len() == 1 => {
3153 let point = points[0];
3154 let (param1, param2) = params(point);
3155 curves.push(IntersectionCurve {
3156 curve: interpolate(&[point, point], 1)?,
3157 points: vec![IntersectionPoint {
3158 point,
3159 param1,
3160 param2,
3161 }],
3162 });
3163 }
3164 ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
3165 }
3166 }
3167 Ok(curves)
3168}
3169
3170fn circles_about_axis(
3172 base: Point3,
3173 axis: Vec3,
3174 crossings: &[(f64, f64)],
3175) -> Result<Vec<ExactIntersectionCurve>, MathError> {
3176 crossings
3177 .iter()
3178 .map(|&(rho, z)| {
3179 Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
3180 })
3181 .collect()
3182}
3183
3184pub fn exact_torus_torus(
3196 first: &ToroidalSurface,
3197 second: &ToroidalSurface,
3198) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3199 let axis = first.z_axis();
3200 let scale = first.major_radius() + second.major_radius();
3201 let offset = second.center() - first.center();
3202 if first.minor_radius() >= first.major_radius()
3204 || second.minor_radius() >= second.major_radius()
3205 || axis.cross(second.z_axis()).length() > 1e-9
3206 || offset.cross(axis).length() > 1e-9 * scale
3207 {
3208 return Ok(None);
3209 }
3210 let Some(crossings) = meridian_crossings(
3211 (first.major_radius(), 0.0, first.minor_radius()),
3212 (
3213 second.major_radius(),
3214 offset.dot(axis),
3215 second.minor_radius(),
3216 ),
3217 scale,
3218 ) else {
3219 return Ok(None);
3220 };
3221 circles_about_axis(first.center(), axis, &crossings).map(Some)
3222}
3223
3224pub fn exact_cylinder_torus(
3238 cylinder: &CylindricalSurface,
3239 torus: &ToroidalSurface,
3240) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3241 let axis = torus.z_axis();
3242 let scale = torus.major_radius() + cylinder.radius();
3243 let offset = cylinder.origin() - torus.center();
3244 let linear = crate::tolerance::Tolerance::default().linear;
3245 if axis.cross(cylinder.axis()).length() > 1e-9
3246 || offset.cross(axis).length() > 1e-9 * scale
3247 || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
3248 {
3249 return Ok(None);
3250 }
3251 let gap = cylinder.radius() - torus.major_radius();
3252 let small = torus.minor_radius();
3253 if (gap.abs() - small).abs() <= linear {
3257 return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
3258 }
3259 if gap.abs() > small {
3260 return Ok(Some(Vec::new()));
3261 }
3262 let height = small.madd(small, -(gap * gap)).sqrt();
3263 circles_about_axis(
3264 torus.center(),
3265 axis,
3266 &[(cylinder.radius(), height), (cylinder.radius(), -height)],
3267 )
3268 .map(Some)
3269}
3270
3271pub fn exact_cone_torus(
3291 cone: &ConicalSurface,
3292 torus: &ToroidalSurface,
3293) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3294 let axis = cone.axis();
3295 let (major, minor) = (torus.major_radius(), torus.minor_radius());
3296 let offset = torus.center() - cone.apex();
3297 if minor >= major
3300 || axis.cross(torus.z_axis()).length() > 1e-9
3301 || offset.cross(axis).length() > 1e-9 * (major + minor)
3302 {
3303 return Ok(None);
3304 }
3305 let linear = Tolerance::new().linear;
3306 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3307 let height = offset.dot(axis);
3308 let foot = major.madd(cos_a, height * sin_a);
3309 let reach = major.madd(sin_a, -(height * cos_a)).abs();
3310 let roots = if (reach - minor).abs() <= linear {
3311 vec![foot]
3312 } else if reach > minor {
3313 Vec::new()
3314 } else {
3315 let half = ((minor - reach) * (minor + reach)).sqrt();
3316 vec![foot - half, foot + half]
3317 };
3318 let crossings: Vec<(f64, f64)> = roots
3319 .into_iter()
3320 .filter(|&v| v * cos_a > linear)
3321 .map(|v| (v * cos_a, v * sin_a))
3322 .collect();
3323 circles_about_axis(cone.apex(), axis, &crossings).map(Some)
3324}
3325
3326pub fn exact_sphere_torus(
3341 sphere: &SphericalSurface,
3342 torus: &ToroidalSurface,
3343) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3344 let axis = torus.z_axis();
3345 let scale = torus.major_radius() + sphere.radius();
3346 let offset = sphere.center() - torus.center();
3347 if torus.minor_radius() >= torus.major_radius() {
3349 return Ok(None);
3350 }
3351 if offset.cross(axis).length() > 1e-9 * scale {
3352 let radial = offset - axis * offset.dot(axis);
3358 let slack = 64.0
3359 * f64::EPSILON
3360 * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
3361 let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
3362 + (sphere.radius() - torus.minor_radius()).abs();
3363 if stray <= slack.min(Tolerance::new().linear) {
3364 let along = axis.cross(radial).normalize()?;
3365 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
3366 sphere.center(),
3367 along,
3368 sphere.radius(),
3369 )?)]));
3370 }
3371 return Ok(
3372 off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
3373 );
3374 }
3375 let Some(crossings) = meridian_crossings(
3376 (0.0, offset.dot(axis), sphere.radius()),
3377 (torus.major_radius(), 0.0, torus.minor_radius()),
3378 scale,
3379 ) else {
3380 return Ok(None);
3381 };
3382 circles_about_axis(torus.center(), axis, &crossings).map(Some)
3383}
3384
3385const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
3389
3390fn sphere_torus_section<'a>(
3399 sphere: &SphericalSurface,
3400 torus: &'a ToroidalSurface,
3401) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
3402 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3403 let offset = sphere.center() - torus.center();
3404 let (a, b, h) = (
3405 offset.dot(torus.x_axis()),
3406 offset.dot(torus.y_axis()),
3407 offset.dot(torus.z_axis()),
3408 );
3409 let s = a.hypot(b);
3410 if small >= big || s <= 1e-9 * (big + radius) {
3411 return None;
3412 }
3413 let centre = sphere.center();
3414 Some(TorusSection {
3415 torus,
3416 phi: b.atan2(a),
3417 num: [
3418 big.madd(
3419 big,
3420 small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
3421 ),
3422 2.0 * big * small,
3423 -2.0 * h * small,
3424 ],
3425 den: [2.0 * s * big, 2.0 * s * small],
3426 clearance: move |p: Point3| (p - centre).length() - radius,
3427 slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
3428 })
3429}
3430
3431const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
3433
3434fn sphere_torus_curves(
3442 sphere: &SphericalSurface,
3443 torus: &ToroidalSurface,
3444 sphere_first: bool,
3445) -> Option<Vec<IntersectionCurve>> {
3446 let section = sphere_torus_section(sphere, torus)?;
3447 let tol = Tolerance::new().linear;
3448 let (big, small) = (torus.major_radius(), torus.minor_radius());
3449 let offset = sphere.center() - torus.center();
3454 let rise = offset.dot(torus.z_axis());
3455 let reach = (offset - torus.z_axis() * rise).length();
3456 let (nearest, farthest) = (
3457 ((reach - big).hypot(rise) - small).abs(),
3458 (reach + big).hypot(rise) + small,
3459 );
3460 let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
3461 let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
3462 let off = |p: Point3| {
3463 let local = p - torus.center();
3464 let (x, y, z) = (
3465 local.dot(torus.x_axis()),
3466 local.dot(torus.y_axis()),
3467 local.dot(torus.z_axis()),
3468 );
3469 let on_torus = (x.hypot(y) - big).hypot(z) - small;
3470 on_torus.abs().max((section.clearance)(p).abs())
3471 };
3472 let centre = sphere.center();
3476 let polish = |q: IntersectionPoint| {
3477 let (mut u, mut v) = q.param1;
3478 let mut best = q;
3479 for _ in 0..4 {
3480 let gap = (section.clearance)(best.point);
3481 let (sin_u, cos_u) = u.sin_cos();
3482 let (sin_v, cos_v) = v.sin_cos();
3483 let rho = small.madd(cos_v, big);
3484 let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
3485 let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
3486 let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
3487 let away = best.point - centre;
3488 let normal = away * (1.0 / away.length());
3489 let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
3490 let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
3491 let reach = g_u.madd(w_u, g_v * w_v);
3492 if reach <= f64::MIN_POSITIVE {
3493 break;
3494 }
3495 let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
3496 if (section.clearance)(next.point).abs() >= gap.abs() {
3497 break;
3498 }
3499 (u, v) = next.param1;
3500 best = next;
3501 }
3502 best
3503 };
3504 let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
3505 if loops.is_empty() && crosses {
3506 return None;
3507 }
3508 let mut curves = Vec::new();
3509 for points in loops {
3510 let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
3511 if points.iter().any(|q| off(q.point) > tol) {
3512 return None;
3513 }
3514 points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
3517 let mut rounds = 0;
3518 let curve = loop {
3519 let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
3520 let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
3521 let params = crate::nurbs::fitting::chord_length_params(&positions);
3522 let strays: Vec<usize> = (0..positions.len() - 1)
3523 .filter(|&k| {
3524 off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
3525 })
3526 .collect();
3527 if strays.is_empty() {
3528 break curve;
3529 }
3530 if rounds == SPHERE_TORUS_FIT_ROUNDS {
3531 return None;
3532 }
3533 rounds += 1;
3534 for &k in strays.iter().rev() {
3535 let mid = polish(section.between(points[k].param1, points[k + 1].param1));
3536 if off(mid.point) > tol {
3537 return None;
3538 }
3539 points.insert(k + 1, mid);
3540 }
3541 };
3542 for q in &mut points {
3543 let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
3544 (q.param1, q.param2) = if sphere_first {
3545 (on_sphere, on_torus)
3546 } else {
3547 (on_torus, on_sphere)
3548 };
3549 }
3550 curves.push(IntersectionCurve { curve, points });
3551 }
3552 Some(curves)
3553}
3554
3555fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
3563 let axis = torus.z_axis();
3564 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3565 let offset = sphere.center() - torus.center();
3566 let radial = offset - axis * offset.dot(axis);
3567 let out = radial * (1.0 / radial.length());
3568 let near = torus.center() + out * big;
3569 let far = torus.center() - out * big;
3570 let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
3571 let (d_near, d_far) = (to_near.length(), to_far.length());
3572 let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
3573 if d_near > slack
3576 && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
3577 {
3578 return Some(near + to_near * (small / d_near));
3579 }
3580 ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
3581}
3582
3583pub fn exact_cone_cone(
3608 c1: &ConicalSurface,
3609 c2: &ConicalSurface,
3610) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3611 let axis = c1.axis();
3612 let axis2 = c2.axis();
3613
3614 if axis.dot(axis2).abs() < 1.0 - 1e-10 {
3616 return Ok(None); }
3618 let apex1 = c1.apex();
3619 let apex2 = c2.apex();
3620 let delta = apex2 - apex1;
3621 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3622 let along = delta_v.dot(axis);
3623 if (delta_v - axis * along).length() > 1e-8 {
3624 return offset_parallel_cone_cone(c1, c2);
3625 }
3626
3627 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3628 if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
3629 return Ok(None); }
3631 let m1 = c1.half_angle().cos() / s1;
3632 let m2 = c2.half_angle().cos() / s2;
3633 let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
3634 let d2 = along; let denom = m1 - m2 * sigma;
3637 if denom.abs() < 1e-12 {
3638 if sigma > 0.0 && d2.abs() < 1e-9 {
3641 return Ok(None);
3642 }
3643 return Ok(Some(vec![]));
3644 }
3645
3646 let t_star = (-m2 * sigma * d2) / denom;
3647 let radius = m1 * t_star;
3648 if radius < 1e-12 {
3649 return Ok(Some(vec![])); }
3651
3652 let center = Point3::new(
3653 apex1.x() + axis.x() * t_star,
3654 apex1.y() + axis.y() * t_star,
3655 apex1.z() + axis.z() * t_star,
3656 );
3657 let circle = Circle3D::new(center, axis, radius)?;
3658 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3659}
3660
3661fn offset_parallel_cone_cone(
3672 c1: &ConicalSurface,
3673 c2: &ConicalSurface,
3674) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3675 if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
3676 return Ok(None); }
3678 let t1 = c1.half_angle().tan();
3679 let t2 = c2.half_angle().tan();
3680 if !t1.is_finite() || !t2.is_finite() {
3681 return Ok(None);
3682 }
3683 if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
3684 return Ok(None);
3685 }
3686
3687 let w = c1.axis();
3688 let apex1 = c1.apex();
3689 let apex2 = c2.apex();
3690 let delta = apex2 - apex1;
3691 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3692 let s = delta_v.dot(w);
3693 let tm = 0.5 * (t1 + t2);
3694 let k = 1.0 + tm * tm;
3695
3696 let n = (delta_v - w * (k * s)) * 2.0;
3700 let n_len = n.length();
3701 if n_len < 1e-12 {
3702 return Ok(None);
3703 }
3704 let n_hat = n * (1.0 / n_len);
3705 let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3706
3707 let axis2 = c2.axis();
3713 let scale = 1.0 + delta_v.length();
3714 let mut out = Vec::new();
3715 for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3716 let samples: Vec<Point3> = match &curve {
3717 ExactIntersectionCurve::Circle(c) => (0..4)
3718 .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3719 .collect(),
3720 ExactIntersectionCurve::Ellipse(e) => (0..4)
3721 .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3722 .collect(),
3723 ExactIntersectionCurve::Points(_) => return Ok(None),
3724 };
3725 let on_real_nappe = |p: &Point3| {
3726 let rel = *p - apex2;
3727 Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3728 };
3729 let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3730 match hits {
3731 0 => {}
3732 4 => out.push(curve),
3733 _ => return Ok(None),
3734 }
3735 }
3736 Ok(Some(out))
3737}
3738
3739pub fn exact_cone_cylinder(
3759 cone: &ConicalSurface,
3760 cyl: &CylindricalSurface,
3761) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3762 let axis = cone.axis();
3763 let cyl_axis = cyl.axis();
3764
3765 if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3767 return Ok(None);
3768 }
3769 let apex = cone.apex();
3770 let delta = apex - cyl.origin();
3771 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3772 let along = delta_v.dot(cyl_axis);
3773 if (delta_v - cyl_axis * along).length() > 1e-8 {
3774 return Ok(None);
3775 }
3776
3777 let s = cone.half_angle().sin();
3778 if s.abs() < 1e-12 {
3779 return Ok(None); }
3781 let m = cone.half_angle().cos() / s; if m.abs() < 1e-12 {
3783 return Ok(None); }
3785
3786 let t_star = cyl.radius() / m; if t_star.abs() < 1e-12 {
3788 return Ok(Some(vec![])); }
3790 let center = Point3::new(
3791 apex.x() + axis.x() * t_star,
3792 apex.y() + axis.y() * t_star,
3793 apex.z() + axis.z() * t_star,
3794 );
3795 let circle = Circle3D::new(center, axis, cyl.radius())?;
3796 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3797}
3798
3799fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3804 let w = std::f64::consts::FRAC_1_SQRT_2;
3805 let corners: [(f64, f64); 9] = [
3806 (1.0, 0.0),
3807 (1.0, 1.0),
3808 (0.0, 1.0),
3809 (-1.0, 1.0),
3810 (-1.0, 0.0),
3811 (-1.0, -1.0),
3812 (0.0, -1.0),
3813 (1.0, -1.0),
3814 (1.0, 0.0),
3815 ];
3816 let points = corners
3817 .iter()
3818 .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3819 .collect();
3820 let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3821 let knots = vec![
3822 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3823 ];
3824 NurbsCurve::new(2, knots, points, weights)
3825}
3826
3827fn shared_apex_cones(
3839 c1: &ConicalSurface,
3840 c2: &ConicalSurface,
3841 v1: Option<(f64, f64)>,
3842 v2: Option<(f64, f64)>,
3843) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3844 let (Some(v1), Some(v2)) = (v1, v2) else {
3845 return Ok(None);
3846 };
3847 let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3848 let across = a1.cross(a2);
3849 let sin = across.length();
3850 if sin < 1e-9 {
3851 return Ok(None);
3852 }
3853 let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3854 let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3855 if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3856 return Ok(None);
3857 }
3858 let normal = across * (1.0 / sin);
3859 let tol = Tolerance::new().linear;
3860 if f64::EPSILON * reach > 0.1 * tol * sin {
3864 return Ok(None);
3865 }
3866 let toward = normal.cross(a1);
3868 let cos = a1.dot(a2);
3869 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3870 let params = |cone: &ConicalSurface, p: Point3| {
3872 let (u, v) = cone.project_point(p);
3873 if v < 0.0 {
3874 ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3875 } else {
3876 (u, v)
3877 }
3878 };
3879 let mut curves = Vec::new();
3880 for nappe in [1.0, -1.0] {
3881 let t2 = nappe * s2;
3882 let side = cos.madd(-s1, t2) / sin;
3883 let foot = a1 * s1 + toward * side;
3884 let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3885 let rounding = 4.0 * f64::EPSILON;
3886 let lifts = if lift_sq.abs() <= rounding {
3887 if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3892 return Ok(None);
3893 }
3894 vec![0.0]
3895 } else if lift_sq < 0.0 {
3896 Vec::new()
3897 } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3898 vec![0.0]
3899 } else {
3900 vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3901 };
3902 let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3903 let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3904 if hi - lo <= tol {
3905 continue;
3906 }
3907 for lift in lifts {
3908 let d = (foot + normal * lift).normalize()?;
3909 let pieces = if lo < 0.0 && hi > 0.0 {
3910 vec![(lo, 0.0), (0.0, hi)]
3911 } else {
3912 vec![(lo, hi)]
3913 };
3914 for (from, to) in pieces {
3915 curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3916 (params(c1, p), params(c2, p))
3917 })?);
3918 }
3919 }
3920 }
3921 Ok(Some(curves))
3922}
3923
3924fn crossing_equal_cylinders(
3937 c1: &CylindricalSurface,
3938 c2: &CylindricalSurface,
3939) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3940 let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3941 if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3942 return Ok(None);
3943 }
3944 let bisectors = [d1 - d2, d1 + d2];
3949 let tol = Tolerance::new().linear;
3950 if bisectors
3951 .iter()
3952 .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3953 {
3954 return Ok(None);
3955 }
3956 let across = d1.cross(d2);
3957 let sin = across.length();
3958 let normal = across * (1.0 / sin);
3959 let w = c1.origin() - c2.origin();
3960 let cos = d1.dot(d2);
3961 let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3962 let centre = c1.origin() + d1 * along;
3963 let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3967 if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3968 return Ok(None);
3969 }
3970 let majors = bisectors.map(|bisector| {
3973 let length = bisector.length();
3974 let major = (bisector * (1.0 / length)).cross(normal);
3975 let major = if major.dot(d1) < 0.0 { -major } else { major };
3976 (major, 2.0 * r / length)
3977 });
3978 let corner = std::f64::consts::FRAC_1_SQRT_2;
3979 let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3980 let mut curves = Vec::with_capacity(2);
3981 for side in [1.0, -1.0] {
3982 let [(m1, a1), (m2, a2)] = majors;
3983 let out = half
3984 .iter()
3985 .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3986 let back = half[1..]
3987 .iter()
3988 .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3989 let curve = NurbsCurve::new(
3990 2,
3991 vec![
3992 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3993 ],
3994 out.chain(back).collect(),
3995 vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3996 )?;
3997 #[allow(clippy::cast_precision_loss)]
3998 let points = (0..=32)
3999 .map(|i| {
4000 let point = curve.evaluate(i as f64 / 32.0);
4001 IntersectionPoint {
4002 point,
4003 param1: c1.project_point(point),
4004 param2: c2.project_point(point),
4005 }
4006 })
4007 .collect();
4008 curves.push(IntersectionCurve { curve, points });
4009 }
4010 Ok(Some(curves))
4011}
4012
4013fn algebraic_cone_cone(
4022 c1: &ConicalSurface,
4023 c2: &ConicalSurface,
4024) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4025 let Some(exacts) = exact_cone_cone(c1, c2)? else {
4026 return Ok(None);
4027 };
4028 let mut curves = Vec::new();
4029 for exact in exacts {
4030 let n_samples = 33;
4031 let mut points = Vec::with_capacity(n_samples);
4032 #[allow(clippy::cast_precision_loss)]
4033 for i in 0..n_samples {
4034 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4035 let pt = match &exact {
4036 ExactIntersectionCurve::Circle(circle) => {
4037 crate::traits::ParametricCurve::evaluate(circle, theta)
4038 }
4039 ExactIntersectionCurve::Ellipse(ellipse) => {
4040 crate::traits::ParametricCurve::evaluate(ellipse, theta)
4041 }
4042 ExactIntersectionCurve::Points(_) => break,
4043 };
4044 points.push(IntersectionPoint {
4045 point: pt,
4046 param1: (0.0, 0.0),
4047 param2: (0.0, 0.0),
4048 });
4049 }
4050 let curve = match &exact {
4051 ExactIntersectionCurve::Circle(c) => {
4052 conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
4053 }
4054 ExactIntersectionCurve::Ellipse(e) => conic_loop(
4055 e.center(),
4056 e.u_axis(),
4057 e.v_axis(),
4058 e.semi_major(),
4059 e.semi_minor(),
4060 )?,
4061 ExactIntersectionCurve::Points(_) => continue,
4062 };
4063 curves.push(IntersectionCurve { curve, points });
4064 }
4065 Ok(Some(curves))
4066}
4067
4068pub fn exact_sphere_cylinder(
4088 sphere: &SphericalSurface,
4089 cyl: &CylindricalSurface,
4090) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4091 let sc = sphere.center();
4092 let r_sphere = sphere.radius();
4093 let co = cyl.origin();
4094 let axis = cyl.axis();
4095 let r_cyl = cyl.radius();
4096
4097 let delta = sc - co;
4099 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
4100 let along = delta_vec.dot(axis);
4101 let perp_vec = delta_vec - axis * along;
4102 let d_perp = perp_vec.length();
4103
4104 if d_perp > 1e-7 {
4107 return Ok(None);
4108 }
4109
4110 if r_cyl > r_sphere + 1e-10 {
4113 return Ok(Some(vec![]));
4114 }
4115 let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
4116 if z_sq < 0.0 {
4117 return Ok(Some(vec![]));
4118 }
4119 let z = z_sq.sqrt();
4120
4121 let center_axis_pt = Point3::new(
4124 co.x() + axis.x() * along,
4125 co.y() + axis.y() * along,
4126 co.z() + axis.z() * along,
4127 );
4128
4129 let mut circles = Vec::new();
4130 let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
4131 for &z_offset in offsets {
4132 let center = Point3::new(
4133 center_axis_pt.x() + axis.x() * z_offset,
4134 center_axis_pt.y() + axis.y() * z_offset,
4135 center_axis_pt.z() + axis.z() * z_offset,
4136 );
4137 let circle = Circle3D::new(center, axis, r_cyl)?;
4138 circles.push(ExactIntersectionCurve::Circle(circle));
4139 }
4140 Ok(Some(circles))
4141}
4142
4143pub fn exact_cone_sphere(
4161 cone: &ConicalSurface,
4162 sphere: &SphericalSurface,
4163) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4164 let offset = cone.apex() - sphere.center();
4165 let along = offset.dot(cone.axis());
4166 if (offset - cone.axis() * along).length() > 1e-7 {
4167 return Ok(None);
4168 }
4169 let lin_tol = Tolerance::new().linear;
4170 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4171 let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
4172 let b = 2.0 * sin_a * along;
4173 let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
4174 let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
4177 if disc < -noise {
4178 return Ok(Some(vec![]));
4179 }
4180 let roots: &[f64] = if far - near < lin_tol {
4181 &[far]
4182 } else {
4183 &[near, far]
4184 };
4185 let mut circles = Vec::new();
4186 for &v in roots {
4187 if v * cos_a > lin_tol {
4188 let centre = cone.apex() + cone.axis() * (v * sin_a);
4189 let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
4190 circles.push(ExactIntersectionCurve::Circle(circle));
4191 }
4192 }
4193 Ok(Some(circles))
4194}
4195
4196fn algebraic_sphere_cylinder(
4205 sphere: &SphericalSurface,
4206 cyl: &CylindricalSurface,
4207 sphere_first: bool,
4208) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4209 let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
4210 return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
4211 };
4212
4213 let mut curves = Vec::new();
4214 for exact in exacts {
4215 let ExactIntersectionCurve::Circle(circle) = exact else {
4216 continue;
4217 };
4218 let n_samples = 33;
4219 let mut points = Vec::with_capacity(n_samples);
4220 #[allow(clippy::cast_precision_loss)]
4221 for i in 0..n_samples {
4222 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4223 let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
4224 let (param1, param2) = in_order(
4225 sphere.project_point(pt),
4226 cyl.project_point(pt),
4227 sphere_first,
4228 );
4229 points.push(IntersectionPoint {
4230 point: pt,
4231 param1,
4232 param2,
4233 });
4234 }
4235 let r = circle.radius();
4236 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
4237 curves.push(IntersectionCurve { curve, points });
4238 }
4239
4240 Ok(Some(curves))
4241}
4242
4243fn off_axis_sphere_cylinder(
4252 sphere: &SphericalSurface,
4253 cyl: &CylindricalSurface,
4254 sphere_first: bool,
4255) -> Option<Vec<IntersectionCurve>> {
4256 let (centre, radius) = (sphere.center(), sphere.radius());
4257 let axis = cyl.axis();
4258 let offset = centre - cyl.origin();
4259 let axis_distance = (offset - axis * offset.dot(axis)).length();
4260 let lin_tol = Tolerance::new().linear;
4261 if axis_distance > radius + cyl.radius() + lin_tol
4262 || axis_distance + radius < cyl.radius() - lin_tol
4263 {
4264 return Some(Vec::new());
4265 }
4266 let roots = |u: f64| {
4267 let q = cyl.evaluate(u, 0.0) - centre;
4268 ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
4269 };
4270 let samples = ruling_samples(cyl, &roots);
4271 let loops = if samples.iter().all(Option::is_some) {
4272 closed_ruling_loops(cyl, &roots, &samples)
4273 } else {
4274 partial_ruling_loops(cyl, &roots, &samples)
4275 };
4276 if loops.is_empty() {
4277 return None;
4278 }
4279 Some(fit_ruling_loops(&loops, |p| {
4280 in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
4281 }))
4282}
4283
4284const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
4287 if a_first { (a, b) } else { (b, a) }
4288}
4289
4290fn parallel_cylinders(
4300 c1: &CylindricalSurface,
4301 c2: &CylindricalSurface,
4302 v_range_1: Option<(f64, f64)>,
4303 v_range_2: Option<(f64, f64)>,
4304) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4305 let axis = c1.axis();
4306 let delta = c2.origin() - c1.origin();
4307 let along = delta.dot(axis);
4308 let across = delta - axis * along;
4309 let d = across.length();
4310 let (r1, r2) = (c1.radius(), c2.radius());
4311 let flip = c2.axis().dot(axis);
4313 let ranges = [
4314 v_range_1,
4315 v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
4316 ];
4317 let (lo, hi) = ranges
4318 .into_iter()
4319 .flatten()
4320 .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
4321 (lo.max(a.min(b)), hi.min(a.max(b)))
4322 });
4323 if !lo.is_finite() || !hi.is_finite() {
4324 return Ok(None);
4325 }
4326 let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
4327 if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
4328 return Ok(Some(Vec::new()));
4329 }
4330 let toward = across * (1.0 / d);
4331 let side = axis.cross(toward);
4332 let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
4333 let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
4334 let linear = Tolerance::new().linear;
4335 let feet = if 2.0 * y <= linear {
4336 vec![toward * x]
4337 } else {
4338 vec![toward * x + side * y, toward * x - side * y]
4339 };
4340 let on_second = |p: Point3| {
4341 let w = p - c2.origin();
4342 ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
4343 };
4344 let mut rulings = Vec::with_capacity(feet.len());
4345 for foot in feet {
4346 let base = c1.origin() + foot;
4347 let (from, to) = (base + axis * lo, base + axis * hi);
4348 if !on_second(from) || !on_second(to) {
4349 return Ok(None);
4350 }
4351 rulings.push(ruling_segment(from, to, |p| {
4352 (c1.project_point(p), c2.project_point(p))
4353 })?);
4354 }
4355 Ok(Some(rulings))
4356}
4357
4358fn ruling_segment(
4361 from: Point3,
4362 to: Point3,
4363 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4364) -> Result<IntersectionCurve, MathError> {
4365 let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
4366 let points = [from, from + (to - from) * 0.5, to]
4367 .into_iter()
4368 .map(|point| {
4369 let (param1, param2) = params(point);
4370 IntersectionPoint {
4371 point,
4372 param1,
4373 param2,
4374 }
4375 })
4376 .collect();
4377 Ok(IntersectionCurve { curve, points })
4378}
4379
4380#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
4394fn algebraic_cylinder_cylinder(
4395 c1: &CylindricalSurface,
4396 c2: &CylindricalSurface,
4397) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4398 if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
4399 return Ok(Some(halves));
4400 }
4401 let alpha = c1.axis().dot(c2.axis());
4402 let a_coeff = 1.0 - alpha * alpha;
4403
4404 if a_coeff.abs() < 1e-12 {
4406 return Ok(None);
4407 }
4408
4409 let r1 = c1.radius();
4410 let r2 = c2.radius();
4411 let o1 = c1.origin();
4412 let o2 = c2.origin();
4413 let a1 = c1.axis();
4414 let a2 = c2.axis();
4415
4416 let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
4419 let cross = a1.cross(a2);
4420 let cross_len = cross.length();
4421 if cross_len > 1e-12 {
4422 let axis_dist = delta.dot(cross).abs() / cross_len;
4423 if axis_dist > r1 + r2 + Tolerance::new().linear {
4424 return Ok(Some(vec![])); }
4426 }
4427
4428 let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
4434 let (o, a, radius) = (other.origin(), other.axis(), other.radius());
4435 let alpha = sweep.axis().dot(a);
4436 let quad = 1.0 - alpha * alpha;
4437 let (axis, sweep) = (sweep.axis(), sweep.clone());
4438 move |u: f64| {
4439 let q = sweep.evaluate(u, 0.0) - o;
4440 let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
4441 let b = 2.0 * (q_a1 - alpha * q_a2);
4442 let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
4443 ruling_quadratic(quad, b, c)
4444 }
4445 };
4446 let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
4447 let samples1 = ruling_samples(c1, &roots1);
4448 let loops = if samples1.iter().all(Option::is_some) {
4449 closed_ruling_loops(c1, &roots1, &samples1)
4450 } else {
4451 let samples2 = ruling_samples(c2, &roots2);
4452 if samples2.iter().all(Option::is_some) {
4453 closed_ruling_loops(c2, &roots2, &samples2)
4454 } else if samples1.iter().any(Option::is_some) {
4455 partial_ruling_loops(c1, &roots1, &samples1)
4456 } else {
4457 partial_ruling_loops(c2, &roots2, &samples2)
4458 }
4459 };
4460 if loops.is_empty() {
4461 return Ok(None);
4462 }
4463 Ok(Some(fit_ruling_loops(&loops, |p| {
4464 (c1.project_point(p), c2.project_point(p))
4465 })))
4466}
4467
4468fn ruling_cone_cylinder(
4475 cone: &ConicalSurface,
4476 cyl: &CylindricalSurface,
4477 cone_first: bool,
4478) -> Option<Vec<IntersectionCurve>> {
4479 let (sin_t, cos_t) = cone.half_angle().sin_cos();
4480 if sin_t < 1e-12 || cos_t < 1e-12 {
4481 return None;
4482 }
4483 let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
4484 let s = 1.0 / (sin_t * sin_t);
4485 let alpha = w.dot(d);
4486 let quad = 1.0 - s * alpha * alpha;
4487 if quad.abs() < 1e-9 {
4488 return None;
4489 }
4490 let roots = |u: f64| {
4491 let delta = cyl.evaluate(u, 0.0) - apex;
4492 let (dd, dw) = (delta.dot(d), delta.dot(w));
4493 let b = 2.0 * (dw - s * dd * alpha);
4494 let c = delta.dot(delta) - s * dd * dd;
4495 ruling_quadratic(quad, b, c)
4496 };
4497 let lin_tol = Tolerance::new().linear;
4498 let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
4499 #[allow(clippy::cast_precision_loss)]
4500 let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
4501 let (disc, vp, vm) = roots(u);
4502 disc >= -lin_tol
4503 && [vp, vm]
4504 .iter()
4505 .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
4506 });
4507 if far_nappe {
4508 return None;
4509 }
4510 let samples = ruling_samples(cyl, &roots);
4511 let meeting: Vec<Option<(Point3, Point3)>> = samples
4515 .iter()
4516 .enumerate()
4517 .map(|(i, &pair)| pair.filter(|_| roots(ruling_u(i)).0 >= 0.0))
4518 .collect();
4519 let scan = WINDOW_SCAN * RULING_SAMPLES;
4525 #[allow(clippy::cast_precision_loss)]
4526 let scan_u = |k: usize| TAU * (k as f64 + 0.5) / scan as f64;
4527 let discs: Vec<f64> = (0..scan).map(|k| roots(scan_u(k)).0).collect();
4528 for k in 0..scan {
4532 let (before, here, after) = (
4533 discs[(k + scan - 1) % scan],
4534 discs[k],
4535 discs[(k + 1) % scan],
4536 );
4537 if here >= -lin_tol || here < before || here < after {
4538 continue;
4539 }
4540 let (mut lo, mut hi) = (scan_u(k) - TAU / scan as f64, scan_u(k) + TAU / scan as f64);
4541 for _ in 0..100 {
4542 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4543 if roots(a).0 < roots(b).0 {
4544 lo = a;
4545 } else {
4546 hi = b;
4547 }
4548 }
4549 if roots(f64::midpoint(lo, hi)).0 >= -lin_tol {
4550 return None;
4551 }
4552 }
4553 let meets = |k: usize| discs[k % scan] >= -lin_tol;
4556 if let Some(start) = (0..scan).find(|&k| !meets(k)) {
4557 let mut k = start;
4558 while k < start + scan {
4559 if !meets(k) {
4560 k += 1;
4561 continue;
4562 }
4563 let first = k;
4564 while k < start + scan && meets(k) {
4565 k += 1;
4566 }
4567 let sampled = (first..k).any(|j| {
4568 j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1
4569 && meeting[(j / WINDOW_SCAN) % RULING_SAMPLES].is_some()
4570 });
4571 if !sampled {
4572 return None;
4573 }
4574 }
4575 }
4576 let loops = if samples.iter().all(Option::is_some) {
4577 closed_ruling_loops(cyl, &roots, &samples)
4578 } else {
4579 partial_ruling_loops(cyl, &roots, &meeting)
4580 };
4581 if loops.is_empty() {
4582 return None;
4583 }
4584 Some(fit_ruling_loops(&loops, |p| {
4585 in_order(cone.project_point(p), cyl.project_point(p), cone_first)
4586 }))
4587}
4588
4589fn ruling_torus_cylinder(
4599 torus: &ToroidalSurface,
4600 cyl: &CylindricalSurface,
4601 torus_first: bool,
4602) -> Option<Vec<IntersectionCurve>> {
4603 if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
4604 || torus.minor_radius() >= torus.major_radius()
4605 {
4606 return None;
4607 }
4608 let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
4609 let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
4610 let count = rows[0].len();
4611 let scan = WINDOW_SCAN * RULING_SAMPLES;
4612 #[allow(clippy::cast_precision_loss)]
4613 if count == 0
4614 || count % 2 == 1
4615 || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
4616 {
4617 return None;
4618 }
4619 let loops: Vec<Vec<Point3>> = (0..count)
4620 .map(|j| {
4621 let mut pts: Vec<Point3> = rows
4622 .iter()
4623 .enumerate()
4624 .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
4625 .collect();
4626 pts.push(pts[0]);
4627 pts
4628 })
4629 .collect();
4630 Some(fit_ruling_loops(&loops, |p| {
4631 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
4632 }))
4633}
4634
4635fn ruling_cone_sphere(
4644 cone: &ConicalSurface,
4645 sphere: &SphericalSurface,
4646 cone_first: bool,
4647) -> Option<Vec<IntersectionCurve>> {
4648 let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
4649 let offset = apex - centre;
4650 let lin_tol = Tolerance::new().linear;
4651 let along = offset.dot(cone.axis());
4652 let across = (offset - cone.axis() * along).length();
4653 if across < lin_tol {
4654 return None;
4655 }
4656 let k = offset.dot(offset) - radius * radius;
4662 if radius - offset.length() > lin_tol {
4663 let exit = |u: f64| {
4664 let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
4665 let root = h.madd(h, -k).sqrt();
4666 cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
4667 };
4668 let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
4673 .map(|i| (ruling_u(i), exit(ruling_u(i))))
4674 .collect();
4675 for _ in 0..10 {
4676 let mut refined = Vec::with_capacity(2 * samples.len());
4677 for pair in samples.windows(2) {
4678 let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
4679 refined.push(pair[0]);
4680 let um = 0.5 * (u0 + u1);
4681 let pm = exit(um);
4682 let chord = (p1 - p0).length();
4683 if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
4684 refined.push((um, pm));
4685 }
4686 }
4687 refined.extend(samples.last().copied());
4688 if refined.len() == samples.len() {
4689 break;
4690 }
4691 samples = refined;
4692 }
4693 let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
4694 if let Some(last) = pts.last_mut() {
4695 *last = samples[0].1;
4696 }
4697 return Some(fit_ruling_loops(&[pts], |p| {
4698 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4699 }));
4700 }
4701 let crossing = |h: f64| {
4705 let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
4706 (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
4707 };
4708 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4713 if crossing(sin_a.madd(along, cos_a * across)).is_none()
4714 || crossing(sin_a.madd(along, -cos_a * across)).is_none()
4715 {
4716 return window_cone_sphere(cone, sphere, cone_first);
4717 }
4718 let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
4719 .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
4720 .collect::<Option<_>>()?;
4721 let loops: Vec<Vec<Point3>> = [0, 1]
4722 .iter()
4723 .map(|&j| {
4724 let mut pts: Vec<Point3> = rows
4725 .iter()
4726 .enumerate()
4727 .map(|(i, &(near, far))| {
4728 cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4729 })
4730 .collect();
4731 pts.push(pts[0]);
4732 pts
4733 })
4734 .collect();
4735 Some(fit_ruling_loops(&loops, |p| {
4736 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4737 }))
4738}
4739
4740fn window_cone_sphere(
4755 cone: &ConicalSurface,
4756 sphere: &SphericalSurface,
4757 cone_first: bool,
4758) -> Option<Vec<IntersectionCurve>> {
4759 let offset = cone.apex() - sphere.center();
4760 let lin_tol = Tolerance::new().linear;
4761 if offset.length() - sphere.radius() <= lin_tol {
4762 return None;
4763 }
4764 let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4765 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4766 let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4767 let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4768 if a < lin_tol {
4769 return None;
4770 }
4771 let reach = (-k.sqrt() - c) / a;
4772 if reach <= -1.0 {
4773 return Some(Vec::new());
4774 }
4775 if reach >= 1.0 {
4776 return None;
4777 }
4778 let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4779 let half = std::f64::consts::PI - half;
4780 let n = RULING_SAMPLES;
4781 let mut pts: Vec<Point3> = (0..n)
4782 .map(|i| {
4783 #[allow(clippy::cast_precision_loss)]
4784 let theta = TAU * i as f64 / n as f64;
4785 let u = half.madd(-theta.cos(), mid);
4786 let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4787 let split = h.madd(h, -k).max(0.0).sqrt();
4788 cone.evaluate(u, -h - split.copysign(theta.sin()))
4789 })
4790 .collect();
4791 pts.push(pts[0]);
4792 Some(fit_ruling_loops(&[pts], |p| {
4793 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4794 }))
4795}
4796
4797const WINDOW_SCAN: usize = 16;
4800
4801const RULING_SAMPLES: usize = 128;
4805
4806#[allow(clippy::cast_precision_loss)]
4807fn ruling_u(i: usize) -> f64 {
4808 TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4809}
4810
4811fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4813 let disc = b * b - 4.0 * quad * c;
4814 let root = disc.max(0.0).sqrt();
4815 (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4816}
4817
4818fn ruling_samples(
4822 sweep: &CylindricalSurface,
4823 roots: &impl Fn(f64) -> (f64, f64, f64),
4824) -> Vec<Option<(Point3, Point3)>> {
4825 let lin_tol = Tolerance::new().linear;
4826 (0..RULING_SAMPLES)
4827 .map(|i| {
4828 let u = ruling_u(i);
4829 let (disc, vp, vm) = roots(u);
4830 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4831 })
4832 .collect()
4833}
4834
4835fn closed_ruling_loops(
4842 sweep: &CylindricalSurface,
4843 roots: &impl Fn(f64) -> (f64, f64, f64),
4844 samples: &[Option<(Point3, Point3)>],
4845) -> Vec<Vec<Point3>> {
4846 let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4847 if let Some((neck, touching)) = narrowest_ruling(roots) {
4848 let count = 2 * RULING_SAMPLES;
4849 #[allow(clippy::cast_precision_loss)]
4850 (0..count)
4851 .map(|i| {
4852 let t = i as f64 / count as f64;
4853 let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4854 let (_, vp, vm) = roots(u);
4855 if i == 0 && touching {
4856 let at = sweep.evaluate(u, 0.5 * (vp + vm));
4857 (at, at)
4858 } else {
4859 (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4860 }
4861 })
4862 .unzip()
4863 } else {
4864 samples.iter().flatten().copied().unzip()
4865 };
4866 plus.push(plus[0]);
4867 minus.push(minus[0]);
4868 vec![plus, minus]
4869}
4870
4871fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4879 let scan = WINDOW_SCAN * RULING_SAMPLES;
4880 #[allow(clippy::cast_precision_loss)]
4881 let step = TAU / scan as f64;
4882 let gap = |u: f64| {
4883 let (_, vp, vm) = roots(u);
4884 (vp - vm).abs()
4885 };
4886 #[allow(clippy::cast_precision_loss)]
4887 let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4888 let widest = gaps.iter().copied().fold(0.0, f64::max);
4889 let tol = Tolerance::new().linear * (1.0 + widest);
4890 let mut necks = Vec::new();
4891 for k in 0..scan {
4892 let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4893 if here > before || here >= after || here >= 0.25 * widest {
4894 continue;
4895 }
4896 #[allow(clippy::cast_precision_loss)]
4897 let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4898 for _ in 0..100 {
4899 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4900 if gap(a) < gap(b) {
4901 hi = b;
4902 } else {
4903 lo = a;
4904 }
4905 }
4906 let u = 0.5 * (lo + hi);
4907 necks.push((u, gap(u) <= tol));
4908 }
4909 match necks[..] {
4910 [neck] => Some(neck),
4911 _ => None,
4912 }
4913}
4914
4915fn partial_ruling_loops(
4926 sweep: &CylindricalSurface,
4927 roots: &impl Fn(f64) -> (f64, f64, f64),
4928 samples: &[Option<(Point3, Point3)>],
4929) -> Vec<Vec<Point3>> {
4930 let lin_tol = Tolerance::new().linear;
4931 let branch_u = |inside: usize, outside: usize| -> f64 {
4934 let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4935 if (hi - lo).abs() > std::f64::consts::PI {
4936 hi += if hi < lo { TAU } else { -TAU };
4937 }
4938 for _ in 0..60 {
4939 let mid = 0.5 * (lo + hi);
4940 if roots(mid).0 >= 0.0 {
4941 lo = mid;
4942 } else {
4943 hi = mid;
4944 }
4945 }
4946 lo
4947 };
4948 let joint = |u: f64| {
4949 let (_, vp, vm) = roots(u);
4950 sweep.evaluate(u, 0.5 * (vp + vm))
4951 };
4952 let Some(first_gap) = samples.iter().position(Option::is_none) else {
4953 return Vec::new();
4954 };
4955 let mut loops = Vec::new();
4956 let mut k = 0;
4957 while k < RULING_SAMPLES {
4958 let i = (first_gap + k) % RULING_SAMPLES;
4959 if samples[i].is_none() {
4960 k += 1;
4961 continue;
4962 }
4963 let start = i;
4964 let mut run = Vec::new();
4965 while k < RULING_SAMPLES {
4966 let j = (first_gap + k) % RULING_SAMPLES;
4967 let Some(pair) = samples[j] else { break };
4968 run.push(pair);
4969 k += 1;
4970 }
4971 let end = (start + run.len() - 1) % RULING_SAMPLES;
4972 let u_head = branch_u(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4973 let u_tail = branch_u(end, (end + 1) % RULING_SAMPLES);
4974 let span = (u_tail - u_head).rem_euclid(TAU);
4975 #[allow(clippy::cast_precision_loss)]
4976 let fresh: Option<Vec<(Point3, Point3)>> = (1..RULING_SAMPLES)
4977 .map(|n| {
4978 let t = n as f64 / RULING_SAMPLES as f64;
4979 let u = span.madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), u_head);
4980 let (disc, vp, vm) = roots(u);
4981 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4982 })
4983 .collect();
4984 let run = fresh.unwrap_or(run);
4987 let (head, tail) = (joint(u_head), joint(u_head + span));
4988 let mut pts = vec![head];
4989 pts.extend(run.iter().map(|p| p.0));
4990 pts.push(tail);
4991 pts.extend(run.iter().rev().map(|p| p.1));
4992 pts.push(head);
4993 loops.push(pts);
4994 }
4995 loops
4996}
4997
4998fn fit_ruling_loops(
5001 loops: &[Vec<Point3>],
5002 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
5003) -> Vec<IntersectionCurve> {
5004 let mut curves = Vec::new();
5005 for pts in loops {
5006 if pts.len() < 4 {
5007 continue;
5008 }
5009 let ipts: Vec<IntersectionPoint> = pts
5010 .iter()
5011 .map(|&p| {
5012 let (param1, param2) = params(p);
5013 IntersectionPoint {
5014 point: p,
5015 param1,
5016 param2,
5017 }
5018 })
5019 .collect();
5020 let degree = 3.min(pts.len() - 1);
5021 if let Ok(curve) = interpolate(pts, degree) {
5022 curves.push(IntersectionCurve {
5023 curve,
5024 points: ipts,
5025 });
5026 }
5027 }
5028 curves
5029}
5030
5031#[allow(clippy::unnecessary_wraps)]
5057fn algebraic_parallel_cone_cylinder(
5058 cone: &ConicalSurface,
5059 cyl: &CylindricalSurface,
5060 v_range_cone: Option<(f64, f64)>,
5061 v_range_cyl: Option<(f64, f64)>,
5062) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
5063 let axis = cone.axis();
5064 if axis.cross(cyl.axis()).length() > Tolerance::new().angular {
5065 return Ok(None); }
5067
5068 let apex = cone.apex();
5069 let delta = cyl.origin() - apex;
5070 let along = delta.dot(axis);
5071 let perp = delta - axis * along;
5072 let d = perp.length();
5073 if d < 1e-9 {
5074 return Ok(None); }
5076
5077 let (e1, e2) = (cone.x_axis(), cone.y_axis());
5078 let phi0 = perp.dot(e2).atan2(perp.dot(e1));
5079
5080 let (sin_t, cos_t) = cone.half_angle().sin_cos();
5081 if cos_t < 1e-12 || sin_t < 1e-12 {
5082 return Ok(None);
5083 }
5084 let r = cyl.radius();
5085
5086 let mut v_min = (d - r).abs() / cos_t;
5088 let mut v_max = (d + r) / cos_t;
5089 if v_max <= v_min {
5090 return Ok(Some(vec![]));
5091 }
5092
5093 let mut lo = v_min;
5099 let mut hi = v_max;
5100 if let Some((a, b)) = v_range_cone {
5105 let (a, b) = if a <= b { (a, b) } else { (b, a) };
5106 lo = lo.max(a);
5107 hi = hi.min(b);
5108 }
5109 if let Some((a, b)) = v_range_cyl {
5110 let flip = cyl.axis().dot(axis);
5113 let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
5114 let (a, b) = (to_cone_v(a), to_cone_v(b));
5115 let (a, b) = if a <= b { (a, b) } else { (b, a) };
5116 lo = lo.max(a);
5117 hi = hi.min(b);
5118 }
5119 let (turn_lo, turn_hi) = (v_min, v_max);
5120 v_min = lo.max(v_min);
5121 v_max = hi.min(v_max);
5122 if v_max - v_min <= 1e-12 {
5123 return Ok(Some(vec![]));
5124 }
5125 let slack = Tolerance::new().linear;
5133 #[allow(clippy::cast_precision_loss)]
5134 let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
5135 if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
5136 let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
5137 .map(|i| {
5138 let (sin_u, cos_u) = ruling_u(i).sin_cos();
5139 let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
5140 let off = foot - apex;
5141 let across = off - axis * off.dot(axis);
5142 apex + across + axis * (across.length() * sin_t / cos_t)
5143 })
5144 .collect();
5145 pts.push(pts[0]);
5146 return Ok(Some(fit_ruling_loops(&[pts], |p| {
5147 (cone.project_point(p), cyl.project_point(p))
5148 })));
5149 }
5150
5151 let n_samples = 128;
5152 let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5153 let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5154 #[allow(clippy::cast_precision_loss)]
5155 for i in 0..=n_samples {
5156 let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
5157 let rho = v * cos_t;
5158 if rho < 1e-12 {
5159 if (d - r).abs() < 1e-12 {
5167 let apex = cone.evaluate(phi0, v);
5168 plus.push(apex);
5169 minus.push(apex);
5170 }
5171 continue;
5172 }
5173 let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
5174 let alpha = cos_alpha.acos();
5175 plus.push(cone.evaluate(phi0 + alpha, v));
5176 minus.push(cone.evaluate(phi0 - alpha, v));
5177 }
5178
5179 let mut curves = Vec::new();
5180 for pts in [&plus, &minus] {
5181 if pts.len() < 4 {
5184 continue;
5185 }
5186 let ipts: Vec<IntersectionPoint> = pts
5187 .iter()
5188 .map(|&p| IntersectionPoint {
5189 point: p,
5190 param1: cone.project_point(p),
5191 param2: cyl.project_point(p),
5192 })
5193 .collect();
5194 let degree = 3.min(pts.len() - 1);
5195 match interpolate(pts, degree) {
5196 Ok(curve) => curves.push(IntersectionCurve {
5197 curve,
5198 points: ipts,
5199 }),
5200 Err(_) => return Ok(None),
5205 }
5206 }
5207
5208 Ok(Some(curves))
5209}
5210
5211const PARALLEL_CONES_FIT_ROUNDS: usize = 8;
5214
5215fn cone_wall_distance(cone: &ConicalSurface, p: Point3) -> f64 {
5218 let rel = p - cone.apex();
5219 let along = rel.dot(cone.axis());
5220 let across = (rel - cone.axis() * along).length();
5221 let (sin, cos) = cone.half_angle().sin_cos();
5222 across.madd(sin, -along * cos)
5223}
5224
5225fn algebraic_parallel_cone_cone(
5249 c1: &ConicalSurface,
5250 c2: &ConicalSurface,
5251 v_range_1: Option<(f64, f64)>,
5252 v_range_2: Option<(f64, f64)>,
5253) -> Option<Vec<IntersectionCurve>> {
5254 let tol = Tolerance::new();
5255 if [v_range_1, v_range_2]
5257 .into_iter()
5258 .flatten()
5259 .any(|(p, q)| p.min(q) < -tol.linear)
5260 {
5261 return None;
5262 }
5263 let axis = c1.axis();
5264 if axis.cross(c2.axis()).length() > tol.angular {
5265 return None;
5266 }
5267 let sigma = axis.dot(c2.axis()).signum();
5268 let delta = c2.apex() - c1.apex();
5269 let along = delta.dot(axis);
5270 let perp = delta - axis * along;
5271 let d = perp.length();
5272 if d < 1e-9 {
5273 return None;
5274 }
5275 let phi0 = perp.dot(c1.y_axis()).atan2(perp.dot(c1.x_axis()));
5276 let (sin1, cos1) = c1.half_angle().sin_cos();
5277 let (sin2, cos2) = c2.half_angle().sin_cos();
5278 if [sin1, cos1, sin2, cos2].iter().any(|&x| x < 1e-12) {
5279 return None;
5280 }
5281 let slope2 = cos2 / sin2;
5284 let (a, b) = (-sigma * along * slope2, sigma * sin1 * slope2);
5285 let (mut lo, mut hi) = (0.0_f64, f64::INFINITY);
5287 let (mut lo_touch, mut hi_touch) = (false, false);
5288 for (k, c, touch) in [
5291 (b, a, false),
5292 (cos1 + b, a - d, true),
5293 (b - cos1, a + d, true),
5294 (cos1 - b, d - a, true),
5295 ] {
5296 if k > 0.0 {
5299 if -c / k > lo {
5300 (lo, lo_touch) = (-c / k, touch);
5301 }
5302 } else if k < 0.0 {
5303 if -c / k < hi {
5304 (hi, hi_touch) = (-c / k, touch);
5305 }
5306 } else if c < 0.0 {
5307 return Some(Vec::new());
5308 }
5309 }
5310 let mut clip = |p: f64, q: f64| {
5311 if p.min(q) > lo {
5312 (lo, lo_touch) = (p.min(q), false);
5313 }
5314 if p.max(q) < hi {
5315 (hi, hi_touch) = (p.max(q), false);
5316 }
5317 };
5318 if let Some((p, q)) = v_range_1 {
5319 clip(p, q);
5320 }
5321 if let Some((p, q)) = v_range_2 {
5322 let to_v1 = |v2: f64| sigma.madd(v2 * sin2, along) / sin1;
5323 clip(to_v1(p), to_v1(q));
5324 }
5325 if !hi.is_finite() {
5326 return None;
5327 }
5328 if hi - lo <= 1e-12 {
5329 return Some(Vec::new());
5330 }
5331
5332 let at = |v: f64, touch: bool| -> Option<(Point3, Point3)> {
5334 let rho1 = v * cos1;
5335 let rho2 = b.madd(v, a);
5336 if rho1 < 1e-12 {
5337 return ((rho2 - d).abs() < 1e-12).then(|| (c1.apex(), c1.apex()));
5340 }
5341 let cos_alpha = (d.madd(d, rho1 * rho1) - rho2 * rho2) / (2.0 * d * rho1);
5342 if touch {
5343 let p = c1.evaluate(
5346 if cos_alpha >= 0.0 {
5347 phi0
5348 } else {
5349 phi0 + std::f64::consts::PI
5350 },
5351 v,
5352 );
5353 return Some((p, p));
5354 }
5355 let alpha = cos_alpha.clamp(-1.0, 1.0).acos();
5356 Some((c1.evaluate(phi0 + alpha, v), c1.evaluate(phi0 - alpha, v)))
5357 };
5358 let v_at = |t: f64| (hi - lo).madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), lo);
5361 let n_samples = 128;
5362 let mut plus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5363 let mut minus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5364 #[allow(clippy::cast_precision_loss)]
5365 for i in 0..=n_samples {
5366 let t = i as f64 / n_samples as f64;
5367 let touch = (i == 0 && lo_touch) || (i == n_samples && hi_touch);
5368 if let Some((p, m)) = at(v_at(t), touch) {
5369 plus.push((t, p));
5370 minus.push((t, m));
5371 }
5372 }
5373
5374 let off = |p: Point3| {
5375 cone_wall_distance(c1, p)
5376 .abs()
5377 .max(cone_wall_distance(c2, p).abs())
5378 };
5379 let mut curves = Vec::new();
5380 for (branch, side) in [(&mut plus, 0), (&mut minus, 1)] {
5381 if branch.len() < 4 {
5382 continue;
5383 }
5384 let mut rounds = 0;
5385 let curve = loop {
5388 let positions: Vec<Point3> = branch.iter().map(|&(_, p)| p).collect();
5389 let curve = interpolate(&positions, 3).ok()?;
5390 let params = crate::nurbs::fitting::chord_length_params(&positions);
5391 let errors: Vec<f64> = (0..positions.len() - 1)
5392 .map(|k| off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))))
5393 .collect();
5394 if errors.iter().all(|&e| e <= 0.25 * tol.linear) {
5395 break curve;
5396 }
5397 if rounds == PARALLEL_CONES_FIT_ROUNDS {
5398 return None;
5399 }
5400 rounds += 1;
5401 let mut split: Vec<usize> = (0..errors.len())
5405 .filter(|&k| errors[k] > 0.0625 * tol.linear)
5406 .flat_map(|k| {
5407 let stray = errors[k] > 0.25 * tol.linear;
5408 let (first, last) = if stray {
5409 (k.saturating_sub(1), k + 1)
5410 } else {
5411 (k, k)
5412 };
5413 first..=last.min(errors.len() - 1)
5414 })
5415 .collect();
5416 split.sort_unstable();
5417 split.dedup();
5418 for &k in split.iter().rev() {
5419 let t = f64::midpoint(branch[k].0, branch[k + 1].0);
5420 let (p, m) = at(v_at(t), false)?;
5421 branch.insert(k + 1, (t, if side == 0 { p } else { m }));
5422 }
5423 };
5424 let points = branch
5425 .iter()
5426 .map(|&(_, p)| IntersectionPoint {
5427 point: p,
5428 param1: c1.project_point(p),
5429 param2: c2.project_point(p),
5430 })
5431 .collect();
5432 curves.push(IntersectionCurve { curve, points });
5433 }
5434 Some(curves)
5435}
5436
5437fn algebraic_sphere_sphere(
5445 s1: &SphericalSurface,
5446 s2: &SphericalSurface,
5447) -> Result<Vec<IntersectionCurve>, MathError> {
5448 let c1 = s1.center();
5449 let c2 = s2.center();
5450 let r1 = s1.radius();
5451 let r2 = s2.radius();
5452
5453 let delta = c2 - c1;
5454 let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
5455 let d = d_sq.sqrt();
5456
5457 if d < 1e-12 {
5458 return Ok(vec![]);
5460 }
5461
5462 if d > r1 + r2 + 1e-10 {
5464 return Ok(vec![]); }
5466 if d + r2.min(r1) + 1e-10 < r1.max(r2) {
5467 return Ok(vec![]); }
5469
5470 let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
5472
5473 let r_circle_sq = r1 * r1 - d1 * d1;
5475 if r_circle_sq < 0.0 {
5476 if r_circle_sq > -1e-10 {
5478 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5480 let tangent_pt = Point3::new(
5481 c1.x() + axis.x() * d1,
5482 c1.y() + axis.y() * d1,
5483 c1.z() + axis.z() * d1,
5484 );
5485 let ipt = IntersectionPoint {
5486 point: tangent_pt,
5487 param1: (0.0, 0.0),
5488 param2: (0.0, 0.0),
5489 };
5490 return Ok(vec![IntersectionCurve {
5492 curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
5493 points: vec![ipt],
5494 }]);
5495 }
5496 return Ok(vec![]);
5497 }
5498
5499 let r_circle = r_circle_sq.sqrt();
5500 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5501 let center = Point3::new(
5502 c1.x() + axis.x() * d1,
5503 c1.y() + axis.y() * d1,
5504 c1.z() + axis.z() * d1,
5505 );
5506
5507 let basis = Frame3::from_normal(center, axis)?;
5509 let u_dir = basis.x;
5510 let v_dir = basis.y;
5511
5512 let n_samples = 33; let mut points = Vec::with_capacity(n_samples);
5515 #[allow(clippy::cast_precision_loss)]
5516 for i in 0..n_samples {
5517 let theta = TAU * i as f64 / (n_samples - 1) as f64;
5518 let (sin_t, cos_t) = theta.sin_cos();
5519 let pt = Point3::new(
5520 center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
5521 center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
5522 center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
5523 );
5524 points.push(IntersectionPoint {
5525 point: pt,
5526 param1: (0.0, 0.0),
5527 param2: (0.0, 0.0),
5528 });
5529 }
5530
5531 let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
5532
5533 Ok(vec![IntersectionCurve { curve, points }])
5534}
5535
5536#[allow(clippy::too_many_arguments)]
5542fn correct_to_intersection(
5543 a: &AnalyticSurface<'_>,
5544 b: &AnalyticSurface<'_>,
5545 surf_a: &dyn Fn(f64, f64) -> Point3,
5546 norm_a: &dyn Fn(f64, f64) -> Vec3,
5547 surf_b: &dyn Fn(f64, f64) -> Point3,
5548 norm_b: &dyn Fn(f64, f64) -> Vec3,
5549 point: Point3,
5550 u_range_a: (f64, f64),
5551 v_range_a: (f64, f64),
5552 u_range_b: (f64, f64),
5553 v_range_b: (f64, f64),
5554 max_iters: usize,
5555) -> Point3 {
5556 let mut p = point;
5557 for _ in 0..max_iters {
5558 let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
5559 let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
5560 let pa = surf_a(ua, va);
5561 let pb = surf_b(ub, vb);
5562 let na = norm_a(ua, va);
5563 let nb = norm_b(ub, vb);
5564 let pv = Vec3::new(p.x(), p.y(), p.z());
5565
5566 let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
5567 let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
5568
5569 if da.abs() < 1e-7 && db.abs() < 1e-7 {
5570 break;
5571 }
5572
5573 let t = na.cross(nb);
5574 let t_len = t.length();
5575 if t_len < 1e-10 {
5576 return Point3::new(
5578 (pa.x() + pb.x()) * 0.5,
5579 (pa.y() + pb.y()) * 0.5,
5580 (pa.z() + pb.z()) * 0.5,
5581 );
5582 }
5583 let t_hat = t * (1.0 / t_len);
5584
5585 let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5587 - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5588 + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
5589 if det.abs() < 1e-15 {
5590 return Point3::new(
5591 (pa.x() + pb.x()) * 0.5,
5592 (pa.y() + pb.y()) * 0.5,
5593 (pa.z() + pb.z()) * 0.5,
5594 );
5595 }
5596 let inv = 1.0 / det;
5597 let dx = inv
5599 * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5600 + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
5601 let dy = inv
5602 * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5603 - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
5604 let dz = inv
5605 * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
5606 + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
5607 let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
5608
5609 let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
5612 let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
5613 let pc_a = surf_a(uc, vc);
5614 let pc_b = surf_b(ud, vd);
5615 let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
5616 let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
5617 .dot(norm_a(uc, vc))
5618 .abs();
5619 let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
5620 .dot(norm_b(ud, vd))
5621 .abs();
5622 if da_new > da.abs() && db_new > db.abs() {
5623 return p;
5624 }
5625
5626 p = candidate;
5627 }
5628 p
5629}
5630
5631const MARCH_TURN: f64 = 0.2;
5633
5634const MARCH_BASIN: f64 = 0.25;
5637
5638const MARCH_STEPS: usize = 4096;
5640
5641#[derive(Clone, Copy)]
5644struct Station {
5645 p: Point3,
5646 t: Vec3,
5648 bend: f64,
5650 gap: f64,
5654}
5655
5656fn station(
5667 a: &AnalyticSurface<'_>,
5668 b: &AnalyticSurface<'_>,
5669 p: Point3,
5670 toward: Vec3,
5671) -> Option<Station> {
5672 use section_fit::Carrier;
5673 let (_, na) = a.distance(p)?;
5674 let (_, nb) = b.distance(p)?;
5675 let cross = na.cross(nb);
5676 let sin = cross.length();
5677 if sin < 1e-6 {
5678 return None;
5679 }
5680 let mut t = cross * (1.0 / sin);
5681 if t.dot(toward) < 0.0 {
5682 t = -t;
5683 }
5684 let (ka, kb) = (a.bend(p, t)?, b.bend(p, t)?);
5685 let c = na.dot(nb);
5686 let det = sin * sin;
5687 let along_a = c.madd(kb, -ka) / det;
5688 let along_b = c.madd(ka, -kb) / det;
5689 let bend = (2.0 * along_a * along_b)
5690 .madd(c, along_a.madd(along_a, along_b * along_b))
5691 .max(0.0)
5692 .sqrt();
5693 let (qa, qb) = (a.bend(p, t.cross(na))?, b.bend(p, t.cross(nb))?);
5694 let spread = qa.abs() + qb.abs();
5695 let gap = if spread > 0.0 {
5696 2.0 * sin / spread
5697 } else {
5698 f64::INFINITY
5699 };
5700 bend.is_finite().then_some(Station { p, t, bend, gap })
5701}
5702
5703impl Station {
5704 fn reach(&self, longest: f64) -> f64 {
5708 if self.bend > 0.0 {
5709 longest
5710 .min(MARCH_TURN / self.bend)
5711 .min((2.0 * MARCH_BASIN * self.gap / self.bend).sqrt())
5712 } else {
5713 longest
5714 }
5715 }
5716}
5717
5718fn singular_point(
5741 a: &AnalyticSurface<'_>,
5742 b: &AnalyticSurface<'_>,
5743 p: Point3,
5744 reach: f64,
5745) -> Option<Point3> {
5746 use section_fit::Carrier;
5747 let axes = [
5748 Vec3::new(1.0, 0.0, 0.0),
5749 Vec3::new(0.0, 1.0, 0.0),
5750 Vec3::new(0.0, 0.0, 1.0),
5751 ];
5752 let miss = |x: Point3| {
5753 let (Some((da, na)), Some((_, nb))) = (a.distance(x), b.distance(x)) else {
5754 return f64::INFINITY;
5755 };
5756 da.hypot(reach * na.cross(nb).length())
5757 };
5758 let mut best: Option<(f64, Point3, bool)> = None;
5759 let mut q = p;
5760 for _ in 0..32 {
5761 let (da, na) = a.distance(q)?;
5762 let (db, nb) = b.distance(q)?;
5763 let cross = na.cross(nb);
5764 let mut hessians = [[Vec3::new(0.0, 0.0, 0.0); 3]; 2];
5765 for (h, s) in hessians.iter_mut().zip([a, b]) {
5766 for (j, &v) in axes.iter().enumerate() {
5767 let mut row = [0.0; 3];
5768 for (k, &e) in axes.iter().enumerate() {
5769 row[k] = 0.25 * (s.bend(q, e + v)? - s.bend(q, e - v)?);
5770 }
5771 h[j] = Vec3::new(row[0], row[1], row[2]);
5772 }
5773 }
5774 let curvature = |h: &[Vec3; 3]| h.iter().fold(0.0, |m: f64, v| m.max(v.length()));
5775 let (ka, kb) = (curvature(&hessians[0]), curvature(&hessians[1]));
5776 let near = 64.0 * f64::EPSILON * (a.scale(q) + b.scale(q));
5777 let parallel = (64.0 * f64::EPSILON * ka.madd(a.scale(q), kb.madd(b.scale(q), 2.0)))
5778 .max(f64::EPSILON.sqrt());
5779 let here = cross.length();
5780 let holds = da.abs() <= near && db.abs() <= near && here <= parallel;
5781 if best.is_none_or(|(c, _, _)| here < c) {
5782 best = Some((here, q, holds));
5783 }
5784 let mut rows = vec![(na, da)];
5787 for (k, &e) in axes.iter().enumerate() {
5788 let grad = Vec3::new(
5789 (hessians[0][0].cross(nb) + na.cross(hessians[1][0])).dot(e),
5790 (hessians[0][1].cross(nb) + na.cross(hessians[1][1])).dot(e),
5791 (hessians[0][2].cross(nb) + na.cross(hessians[1][2])).dot(e),
5792 );
5793 let value = [cross.x(), cross.y(), cross.z()][k];
5794 rows.push((grad * reach, value * reach));
5795 }
5796 let mut m = [[0.0; 3]; 3];
5797 let mut rhs = [0.0; 3];
5798 for (g, r) in &rows {
5799 let g = [g.x(), g.y(), g.z()];
5800 for i in 0..3 {
5801 rhs[i] -= g[i] * r;
5802 for j in 0..3 {
5803 m[i][j] = g[i].madd(g[j], m[i][j]);
5804 }
5805 }
5806 }
5807 let damp = 1e-12 * (m[0][0] + m[1][1] + m[2][2]);
5808 for (i, row) in m.iter_mut().enumerate() {
5809 row[i] += damp;
5810 }
5811 let Some(step) = solve3(m, rhs) else {
5812 break;
5813 };
5814 let onto_a = |x: Point3| a.distance(x).map_or(x, |(d, n)| x - n * d);
5817 let next = [1.0, 2.0, 3.0]
5818 .iter()
5819 .map(|&k| onto_a(q + step * k))
5820 .min_by(|x, y| miss(*x).total_cmp(&miss(*y)))?;
5821 if (next - p).length() > reach || miss(next) >= miss(q) {
5822 break;
5823 }
5824 q = next;
5825 }
5826 best.and_then(|(_, x, holds)| holds.then_some(x))
5827}
5828
5829fn solve3(m: [[f64; 3]; 3], rhs: [f64; 3]) -> Option<Vec3> {
5832 let det = |c: [[f64; 3]; 3]| {
5833 c[0][0] * c[1][1].madd(c[2][2], -c[1][2] * c[2][1])
5834 - c[0][1] * c[1][0].madd(c[2][2], -c[1][2] * c[2][0])
5835 + c[0][2] * c[1][0].madd(c[2][1], -c[1][1] * c[2][0])
5836 };
5837 let d = det(m);
5838 if d.abs() <= 0.0 || !d.is_finite() {
5839 return None;
5840 }
5841 let mut out = [0.0; 3];
5842 for (k, x) in out.iter_mut().enumerate() {
5843 let mut c = m;
5844 for (row, r) in c.iter_mut().zip(rhs) {
5845 row[k] = r;
5846 }
5847 *x = det(c) / d;
5848 }
5849 Some(Vec3::new(out[0], out[1], out[2]))
5850}
5851
5852#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
5870fn march_analytic_intersection(
5871 a: &AnalyticSurface<'_>,
5872 b: &AnalyticSurface<'_>,
5873 surf_a: &dyn Fn(f64, f64) -> Point3,
5874 norm_a: &dyn Fn(f64, f64) -> Vec3,
5875 surf_b: &dyn Fn(f64, f64) -> Point3,
5876 norm_b: &dyn Fn(f64, f64) -> Vec3,
5877 seed: Point3,
5878 u_range_a: (f64, f64),
5879 v_range_a: (f64, f64),
5880 u_range_b: (f64, f64),
5881 v_range_b: (f64, f64),
5882 initial_step: f64,
5883 u_periodic_a: bool,
5884 u_periodic_b: bool,
5885 region: Option<Aabb3>,
5886) -> Option<Vec<Point3>> {
5887 let h_max = initial_step * 4.0;
5888 let h_min = initial_step * 1e-6;
5889
5890 let off_patch = |q: Point3| {
5892 let (ua, va) = project_analytic(a, q, u_range_a, v_range_a);
5893 let (ub, vb) = project_analytic(b, q, u_range_b, v_range_b);
5894 (!u_periodic_a && (ua <= u_range_a.0 || ua >= u_range_a.1))
5895 || va <= v_range_a.0
5896 || va >= v_range_a.1
5897 || (!u_periodic_b && (ub <= u_range_b.0 || ub >= u_range_b.1))
5898 || vb <= v_range_b.0
5899 || vb >= v_range_b.1
5900 };
5901 let on_curve = |from: Point3, step: Vec3| {
5903 correct_to_intersection(
5904 a,
5905 b,
5906 surf_a,
5907 norm_a,
5908 surf_b,
5909 norm_b,
5910 from + step,
5911 u_range_a,
5912 v_range_a,
5913 u_range_b,
5914 v_range_b,
5915 5,
5916 )
5917 };
5918 let last_on_patch = |from: Point3, step: Vec3| {
5922 let (mut lo, mut hi) = (0.0, 1.0);
5923 for _ in 0..48 {
5924 let s = f64::midpoint(lo, hi);
5925 if off_patch(on_curve(from, step * s)) {
5926 hi = s;
5927 } else {
5928 lo = s;
5929 }
5930 }
5931 (lo > 0.0).then(|| on_curve(from, step * lo))
5932 };
5933
5934 let start = station(a, b, seed, Vec3::new(0.0, 0.0, 0.0))?;
5935 let sheets = |q: Point3| {
5937 use section_fit::Carrier;
5938 (a.sheet(q), b.sheet(q))
5939 };
5940 let home_sheets = sheets(seed);
5941
5942 let mut forward = Vec::new();
5944 let mut backward = Vec::new();
5946
5947 let mut looped = false;
5950 for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
5951 if looped {
5952 break;
5953 }
5954 let home = start.t * direction;
5955 let mut here = Station { t: home, ..start };
5956 let mut h = here.reach(h_max.min(initial_step));
5957 let mut ended = false;
5958
5959 for _ in 0..MARCH_STEPS {
5960 h = h.min(here.reach(h_max));
5961 if !points.is_empty() {
5962 let to_seed = seed - here.p;
5963 let ahead = to_seed.dot(here.t);
5964 let aside = (to_seed - here.t * ahead).length();
5965 if ahead > 0.0
5966 && ahead <= h
5967 && aside <= MARCH_TURN * ahead
5968 && aside <= MARCH_BASIN * here.gap.min(start.gap)
5969 && home.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5970 {
5971 points.push(seed);
5972 looped = true;
5973 ended = true;
5974 break;
5975 }
5976 }
5977
5978 let next = loop {
5979 if h < h_min {
5980 break None;
5981 }
5982 let guess = Point3::new(
5983 h.madd(here.t.x(), here.p.x()),
5984 h.madd(here.t.y(), here.p.y()),
5985 h.madd(here.t.z(), here.p.z()),
5986 );
5987 let taken = settle_on_section(a, b, guess)
5988 .and_then(|q| station(a, b, q, here.t))
5989 .filter(|next| {
5990 let missed = (next.p - guess).length();
5991 missed <= MARCH_BASIN * here.gap.min(next.gap)
5992 && missed <= 0.5 * h
5993 && next.t.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5994 && (next.p - here.p).dot(here.t) >= 0.5 * h
5995 && sheets(next.p) == home_sheets
5996 });
5997 match taken {
5998 Some(next) => break Some(next),
5999 None => h *= 0.5,
6000 }
6001 };
6002 let Some(next) = next else {
6008 let end = singular_point(a, b, here.p, initial_step)?;
6009 points.push(end);
6010 ended = true;
6011 break;
6012 };
6013
6014 if off_patch(next.p) {
6015 points.extend(last_on_patch(here.p, next.p - here.p));
6019 ended = true;
6020 break;
6021 }
6022 if region.is_some_and(|r| !r.contains_point(next.p)) {
6023 points.push(next.p);
6024 ended = true;
6025 break;
6026 }
6027 points.push(next.p);
6028 here = next;
6029 h *= 2.0;
6030 }
6031 if !ended {
6032 return None;
6033 }
6034 }
6035
6036 backward.reverse();
6038 let mut result = backward;
6039 result.push(seed);
6040 result.append(&mut forward);
6041
6042 if let [first, second, ..] = result[..]
6046 && off_patch(first)
6047 && !off_patch(second)
6048 && let Some(edge) = last_on_patch(second, first - second)
6049 {
6050 result[0] = edge;
6051 }
6052 if let [.., second, last] = result[..]
6053 && off_patch(last)
6054 && !off_patch(second)
6055 && let Some(edge) = last_on_patch(second, last - second)
6056 && let Some(end) = result.last_mut()
6057 {
6058 *end = edge;
6059 }
6060
6061 for pt in &mut result {
6064 let from = *pt;
6065 *pt = settle_on_section(a, b, from)
6066 .filter(|on| (*on - from).length() <= initial_step)
6067 .unwrap_or_else(|| {
6068 correct_to_intersection(
6069 a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b,
6070 v_range_b, 5,
6071 )
6072 });
6073 }
6074
6075 Some(result)
6076}
6077
6078fn project_analytic(
6082 surface: &AnalyticSurface<'_>,
6083 point: Point3,
6084 u_range: (f64, f64),
6085 v_range: (f64, f64),
6086) -> (f64, f64) {
6087 match surface {
6088 AnalyticSurface::Cylinder(cyl) => {
6089 let (u, v) = cyl.project_point(point);
6090 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6091 }
6092 AnalyticSurface::Sphere(sphere) => {
6093 let (u, v) = sphere.project_point(point);
6094 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6095 }
6096 AnalyticSurface::Cone(cone) => {
6099 let (u, v) = cone.project_point(point);
6100 let v = v.clamp(v_range.0, v_range.1);
6101 let u = if v < 0.0 {
6102 (u + std::f64::consts::PI).rem_euclid(TAU)
6103 } else {
6104 u
6105 };
6106 (u.clamp(u_range.0, u_range.1), v)
6107 }
6108 AnalyticSurface::Torus(torus) => {
6109 let (u, v) = torus.project_point(point);
6110 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6111 }
6112 }
6113}
6114
6115fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
6119 matches!(
6120 surface,
6121 AnalyticSurface::Cylinder(_)
6122 | AnalyticSurface::Cone(_)
6123 | AnalyticSurface::Sphere(_)
6124 | AnalyticSurface::Torus(_)
6125 )
6126}
6127
6128#[allow(clippy::type_complexity)]
6130fn surface_closures<'a>(
6131 surface: &'a AnalyticSurface<'a>,
6132) -> (
6133 Box<dyn Fn(f64, f64) -> Point3 + 'a>,
6134 Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
6135 (f64, f64),
6136 (f64, f64),
6137) {
6138 match surface {
6139 AnalyticSurface::Cylinder(cyl) => (
6140 Box::new(|u, v| cyl.evaluate(u, v)),
6141 Box::new(|u, v| cyl.normal(u, v)),
6142 (0.0, TAU),
6143 (-1.0, 1.0),
6144 ),
6145 AnalyticSurface::Cone(cone) => (
6146 Box::new(|u, v| cone.evaluate(u, v)),
6147 Box::new(|u, v| cone.normal(u, v)),
6148 (0.0, TAU),
6149 (0.01, 2.0),
6150 ),
6151 AnalyticSurface::Sphere(sphere) => (
6152 Box::new(|u, v| sphere.evaluate(u, v)),
6153 Box::new(|u, v| sphere.normal(u, v)),
6154 (0.0, TAU),
6155 (-FRAC_PI_2, FRAC_PI_2),
6156 ),
6157 AnalyticSurface::Torus(torus) => (
6158 Box::new(|u, v| torus.evaluate(u, v)),
6159 Box::new(|u, v| torus.normal(u, v)),
6160 (0.0, TAU),
6161 (0.0, TAU),
6162 ),
6163 }
6164}
6165
6166#[cfg(test)]
6167#[allow(clippy::unwrap_used, clippy::expect_used)]
6168mod tests {
6169 use super::*;
6170 use crate::tolerance::Tolerance;
6171
6172 #[test]
6176 fn plane_cone_conic_arcs_lie_on_both_surfaces() {
6177 let half_angle = 1.1_f64;
6178 let cone = ConicalSurface::new(
6179 Point3::new(0.0, 0.0, 0.0),
6180 Vec3::new(0.0, 0.0, 1.0),
6181 half_angle,
6182 )
6183 .unwrap();
6184 let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
6185 for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
6186 let chains =
6187 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
6188 .unwrap();
6189 let chain = chains
6190 .iter()
6191 .find_map(|c| match c {
6192 ExactIntersectionCurve::Points(chain) => Some(chain),
6193 _ => None,
6194 })
6195 .expect("a parabola or hyperbola section is sampled");
6196 let (from, to) = (chain[2], chain[chain.len() - 3]);
6197 let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
6198 .unwrap()
6199 .expect("an exact arc");
6200 let (t0, t1) = arc.domain();
6201 assert!((arc.evaluate(t0) - from).length() < 1e-12);
6202 assert!((arc.evaluate(t1) - to).length() < 1e-12);
6203 for i in 0..=200 {
6204 let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
6205 let w = q - Point3::new(0.0, 0.0, 0.0);
6206 let off_plane = (normal.dot(w) - d).abs();
6207 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6208 assert!(off_plane < 1e-9, "off the plane by {off_plane}");
6209 assert!(off_cone < 1e-9, "off the cone by {off_cone}");
6210 }
6211 }
6212 }
6213
6214 #[test]
6218 fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
6219 let half_angle = 1.1_f64;
6220 let cone = ConicalSurface::new(
6221 Point3::new(0.0, 0.0, 0.0),
6222 Vec3::new(0.0, 0.0, 1.0),
6223 half_angle,
6224 )
6225 .unwrap();
6226 for shortfall in [1e-10, 3e-10, 8e-10] {
6227 let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
6228 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
6229 let chains =
6230 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
6231 .unwrap();
6232 let Some(chain) = chains.iter().find_map(|c| match c {
6233 ExactIntersectionCurve::Points(chain) => Some(chain),
6234 _ => None,
6235 }) else {
6236 continue;
6237 };
6238 let (from, to) = (chain[2], chain[chain.len() - 3]);
6239 assert!(
6240 plane_cone_conic_arc(&cone, normal, 1.0, from, from)
6241 .unwrap()
6242 .is_none(),
6243 "coincident ends"
6244 );
6245 let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
6246 continue;
6247 };
6248 let (t0, t1) = arc.domain();
6249 for i in 0..=200 {
6250 let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
6251 - Point3::new(0.0, 0.0, 0.0);
6252 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6253 assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
6254 }
6255 }
6256 }
6257
6258 #[test]
6259 fn plane_cylinder_perpendicular() {
6260 let cyl =
6261 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
6262 .unwrap();
6263
6264 let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
6266 assert!(!curves.is_empty(), "should find intersection curve");
6267 assert!(
6268 curves[0].points.len() > 10,
6269 "should have many sample points"
6270 );
6271
6272 let tol = Tolerance::loose();
6273 for pt in &curves[0].points {
6274 assert!(
6275 tol.approx_eq(pt.point.z(), 3.0),
6276 "z should be ~3.0, got {}",
6277 pt.point.z()
6278 );
6279 let r = pt.point.x().hypot(pt.point.y());
6280 assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
6281 }
6282 }
6283
6284 #[test]
6285 fn plane_sphere_equator() {
6286 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6287
6288 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6289 assert!(!curves.is_empty());
6290
6291 let tol = Tolerance::loose();
6292 for pt in &curves[0].points {
6293 assert!(
6294 tol.approx_eq(pt.point.z(), 0.0),
6295 "z should be ~0, got {}",
6296 pt.point.z()
6297 );
6298 let r = pt.point.x().hypot(pt.point.y());
6299 assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
6300 }
6301 }
6302
6303 #[test]
6304 fn plane_sphere_no_intersection() {
6305 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6306
6307 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
6308 assert!(curves.is_empty());
6309 }
6310
6311 #[test]
6312 fn plane_cone_cross_section() {
6313 let cone = ConicalSurface::new(
6314 Point3::new(0.0, 0.0, 0.0),
6315 Vec3::new(0.0, 0.0, 1.0),
6316 std::f64::consts::FRAC_PI_4,
6317 )
6318 .unwrap();
6319
6320 let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6321 assert!(!curves.is_empty(), "should find intersection with cone");
6322 }
6323
6324 #[test]
6331 fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
6332 let c1 = ConicalSurface::new(
6333 Point3::new(
6334 -16.999_999_999_999_975,
6335 -16.999_999_999_999_975,
6336 5.849_999_999_999_951,
6337 ),
6338 Vec3::new(0.0, 0.0, -1.0),
6339 0.785_398_163_397_433_5,
6340 )
6341 .unwrap();
6342 let c2 = ConicalSurface::new(
6343 Point3::new(
6344 -16.750_000_000_000_036,
6345 -16.750_000_000_000_018,
6346 0.749_999_999_999_881,
6347 ),
6348 Vec3::new(0.0, 0.0, 1.0),
6349 0.785_398_163_397_467_6,
6350 )
6351 .unwrap();
6352
6353 let curves = exact_cone_cone(&c1, &c2)
6354 .unwrap()
6355 .expect("offset parallel equal-angle cones must take the radical-plane path");
6356 assert_eq!(curves.len(), 1, "expected exactly one section conic");
6357 assert!(
6358 matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
6359 "expected an ellipse section, got {:?}",
6360 curves[0]
6361 );
6362 let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
6363 return;
6364 };
6365
6366 for i in 0..16 {
6370 let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
6371 for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
6372 let rel = p - cone.apex();
6373 let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
6374 let axial = rel_v.dot(cone.axis());
6375 let radial = (rel_v - cone.axis() * axial).length();
6376 assert!(
6377 axial > 0.0,
6378 "{label}: sample on phantom nappe (axial {axial})"
6379 );
6380 let expect = cone.half_angle().tan() * axial;
6381 assert!(
6382 (radial - expect).abs() < 1e-9,
6383 "{label}: sample off surface by {}",
6384 (radial - expect).abs()
6385 );
6386 }
6387 }
6388 }
6389
6390 #[test]
6394 fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
6395 let c1 = ConicalSurface::new(
6396 Point3::new(0.0, 0.0, 5.0),
6397 Vec3::new(0.0, 0.0, -1.0),
6398 std::f64::consts::FRAC_PI_4,
6399 )
6400 .unwrap();
6401 let c2 = ConicalSurface::new(
6402 Point3::new(0.25, 0.25, 20.0),
6403 Vec3::new(0.0, 0.0, 1.0),
6404 std::f64::consts::FRAC_PI_4,
6405 )
6406 .unwrap();
6407 let curves = exact_cone_cone(&c1, &c2)
6408 .unwrap()
6409 .expect("radical-plane path");
6410 assert!(curves.is_empty(), "disjoint nappes must yield no curves");
6411 }
6412
6413 #[test]
6416 fn offset_parallel_cones_with_unequal_angles_defer() {
6417 let c1 = ConicalSurface::new(
6418 Point3::new(0.0, 0.0, 5.0),
6419 Vec3::new(0.0, 0.0, -1.0),
6420 std::f64::consts::FRAC_PI_4,
6421 )
6422 .unwrap();
6423 let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
6424 .unwrap();
6425 assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
6426 }
6427
6428 fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
6432 let cone = ConicalSurface::new(
6433 Point3::new(0.0, 0.0, 0.0),
6434 Vec3::new(0.0, 0.0, 1.0),
6435 std::f64::consts::FRAC_PI_4,
6436 )
6437 .unwrap();
6438 let (s, c) = 40.0_f64.to_radians().sin_cos();
6439 let tube =
6440 CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
6441 (cone, tube)
6442 }
6443
6444 #[test]
6445 fn marcher_keeps_to_its_region() {
6446 let (cone, tube) = cone_and_tilted_tube();
6447 let run = |region: Option<Aabb3>| {
6448 let (a, b) = (
6449 AnalyticSurface::Cone(&cone),
6450 AnalyticSurface::Cylinder(&tube),
6451 );
6452 let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
6453 match region {
6454 Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
6455 None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
6456 }
6457 .unwrap()
6458 };
6459 assert!(!run(None).is_empty());
6460 let near = Aabb3 {
6461 min: Point3::new(-0.5, -2.0, 0.8),
6462 max: Point3::new(0.7, -0.7, 2.0),
6463 };
6464 let curves = run(Some(near));
6465 assert!(!curves.is_empty(), "the loop through the region is kept");
6466 let reach = near.expanded(0.6);
6468 for curve in &curves {
6469 assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
6470 }
6471 let away = Aabb3 {
6472 min: Point3::new(5.0, 5.0, 5.0),
6473 max: Point3::new(6.0, 6.0, 6.0),
6474 };
6475 assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
6476 }
6477
6478 #[test]
6479 fn coaxial_cones_cross_at_single_circle() {
6480 let outer = ConicalSurface::new(
6485 Point3::new(0.0, 0.0, 50.0),
6486 Vec3::new(0.0, 0.0, -1.0),
6487 5.0_f64.atan(),
6488 )
6489 .unwrap();
6490 let inner = ConicalSurface::new(
6491 Point3::new(0.0, 0.0, 90.0),
6492 Vec3::new(0.0, 0.0, -1.0),
6493 10.0_f64.atan(),
6494 )
6495 .unwrap();
6496
6497 let curves = intersect_analytic_analytic_bounded(
6498 AnalyticSurface::Cone(&outer),
6499 AnalyticSurface::Cone(&inner),
6500 32,
6501 None,
6502 None,
6503 )
6504 .unwrap();
6505
6506 assert_eq!(
6507 curves.len(),
6508 1,
6509 "coaxial cones crossing at one circle must yield exactly one curve, got {}",
6510 curves.len()
6511 );
6512 for p in &curves[0].points {
6513 let r = p.point.x().hypot(p.point.y());
6514 assert!(
6515 (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
6516 "intersection point off the expected z=10,r=8 circle: {:?}",
6517 p.point
6518 );
6519 }
6520 }
6521
6522 #[test]
6523 fn plane_torus_cross_section() {
6524 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
6525
6526 let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6527 assert!(
6528 !curves.is_empty(),
6529 "should find intersection curves with torus"
6530 );
6531 }
6532
6533 #[test]
6536 fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
6537 for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
6538 let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
6539 for z in [3.0 - minor, 3.0 + minor] {
6540 let exact = exact_plane_analytic(
6541 AnalyticSurface::Torus(&torus),
6542 Vec3::new(0.0, 0.0, 1.0),
6543 z,
6544 )
6545 .unwrap();
6546 assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
6547 let circle = match &exact[0] {
6548 ExactIntersectionCurve::Circle(c) => Some(c),
6549 _ => None,
6550 };
6551 let c = circle.expect("a circle");
6552 assert!((c.radius() - major).abs() < 1e-12);
6553 assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
6554
6555 let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
6556 assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
6557 }
6558 let single = |normal: Vec3, d: f64| {
6560 matches!(
6561 exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
6562 .unwrap()
6563 .as_slice(),
6564 [ExactIntersectionCurve::Circle(_)]
6565 )
6566 };
6567 assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
6568 }
6569 }
6570
6571 #[test]
6575 fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
6576 let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
6577 let level = Vec3::new(0.0, 0.0, 1.0);
6578 let curves =
6579 |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
6580 assert!(matches!(
6581 curves(3.0 + 100.1).as_slice(),
6582 [ExactIntersectionCurve::Circle(_)]
6583 ));
6584 let inside = curves(3.0 + 100.1 - 4e-7);
6585 assert!(!matches!(
6586 inside.as_slice(),
6587 [ExactIntersectionCurve::Circle(_)]
6588 ));
6589 }
6590
6591 fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
6594 let rho = p.x().hypot(p.y());
6595 ((rho - major).hypot(p.z())) - minor
6596 }
6597
6598 #[test]
6604 fn oblique_cone_cylinder_traces_curves_on_both() {
6605 use crate::traits::ParametricCurve;
6606 let cone = ConicalSurface::new(
6610 Point3::new(0.0, 0.0, 3.0),
6611 Vec3::new(0.0, 0.0, -1.0),
6612 2.0_f64.atan(),
6613 )
6614 .unwrap();
6615 for (x0, loops) in [(0.5, 1), (0.0, 2)] {
6616 let cyl =
6617 CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6618 .unwrap();
6619 for cone_first in [true, false] {
6620 let (a, b) = if cone_first {
6621 (
6622 AnalyticSurface::Cone(&cone),
6623 AnalyticSurface::Cylinder(&cyl),
6624 )
6625 } else {
6626 (
6627 AnalyticSurface::Cylinder(&cyl),
6628 AnalyticSurface::Cone(&cone),
6629 )
6630 };
6631 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6632 assert_eq!(curves.len(), loops, "x0 {x0}: loops");
6633 for c in &curves {
6634 let (t0, t1) = c.curve.domain();
6635 for k in 0..=64 {
6636 let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
6637 let p = ParametricCurve::evaluate(&c.curve, t);
6638 let rod = (p.x() - x0).hypot(p.z() - 1.0);
6641 assert!(
6642 (rod - 0.6).abs() < 1e-4,
6643 "x0 {x0}: off the rod by {}",
6644 rod - 0.6
6645 );
6646 let cone_r = p.x().hypot(p.y());
6647 assert!(
6648 (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
6649 "x0 {x0}: off the cone at {p:?}"
6650 );
6651 }
6652 }
6653 }
6654 }
6655 }
6656
6657 #[test]
6658 fn a_rod_through_a_rings_tube_traces_four_loops() {
6659 use crate::traits::ParametricCurve;
6660 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6661 let rod =
6664 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
6665 .unwrap();
6666 let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
6667 assert_eq!(curves.len(), 4);
6668 for c in &curves {
6669 let (t0, t1) = c.curve.domain();
6670 for k in 0..=64 {
6671 let p =
6672 ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
6673 let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
6674 let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6675 assert!(
6676 on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
6677 "off by {on_rod}, {on_ring}"
6678 );
6679 }
6680 }
6681 let high =
6683 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6684 .unwrap();
6685 assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
6686 let grazing =
6688 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
6689 .unwrap();
6690 assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
6691 let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
6693 let thin =
6694 CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
6695 .unwrap();
6696 assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
6697 }
6698
6699 #[test]
6700 fn a_pin_through_a_ball_traces_two_loops() {
6701 use crate::traits::ParametricCurve;
6702 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6703 let half = 0.08_f64.atan();
6706 let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
6707 let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
6708 for cone_first in [true, false] {
6709 let (a, b) = if cone_first {
6710 (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
6711 } else {
6712 (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
6713 };
6714 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6715 assert_eq!(curves.len(), 2, "entry and exit loops");
6716 for c in &curves {
6717 let (t0, t1) = c.curve.domain();
6718 for k in 0..=64 {
6719 let p = ParametricCurve::evaluate(
6720 &c.curve,
6721 (t1 - t0).madd(f64::from(k) / 64.0, t0),
6722 );
6723 let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
6724 let axial = apex.z() - p.z();
6725 let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
6726 assert!(
6727 on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
6728 "off by {on_ball}, {on_pin}"
6729 );
6730 }
6731 }
6732 }
6733 let coaxial =
6738 ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
6739 .unwrap();
6740 assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
6741 let aside = ConicalSurface::new(
6742 Point3::new(2.8, 0.0, 10.0),
6743 Vec3::new(0.0, 0.0, -1.0),
6744 FRAC_PI_2 - half,
6745 )
6746 .unwrap();
6747 assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
6748 let holding = ConicalSurface::new(
6749 Point3::new(1.0, 0.5, 1.0),
6750 Vec3::new(0.0, 0.0, -1.0),
6751 FRAC_PI_2 - half,
6752 )
6753 .unwrap();
6754 assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
6755 let away = ConicalSurface::new(
6756 Point3::new(1.0, 0.5, 10.0),
6757 Vec3::new(0.0, 0.0, 1.0),
6758 FRAC_PI_2 - half,
6759 )
6760 .unwrap();
6761 assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
6762 let step = TAU / 2048.0;
6766 let grazed =
6767 SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
6768 .unwrap();
6769 let wide =
6770 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
6771 assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
6772 }
6773
6774 #[test]
6775 fn a_ball_beside_a_cone_meets_it_in_one_loop() {
6776 use crate::traits::ParametricCurve;
6777 let cone = ConicalSurface::new(
6779 Point3::new(0.0, 0.0, 3.0),
6780 Vec3::new(0.0, 0.0, -1.0),
6781 2.0_f64.atan(),
6782 )
6783 .unwrap();
6784 for (centre, radius) in [
6785 (Point3::new(1.0, 0.8, 1.2), 1.1),
6786 (Point3::new(1.5, 0.0, 0.0), 0.8),
6787 ] {
6788 let ball = SphericalSurface::new(centre, radius).unwrap();
6789 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6790 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6791 let (t0, t1) = curves[0].curve.domain();
6792 for k in 0..=64 {
6793 let p = ParametricCurve::evaluate(
6794 &curves[0].curve,
6795 (t1 - t0).madd(f64::from(k) / 64.0, t0),
6796 );
6797 let on_ball = (p - centre).length() - radius;
6798 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6799 assert!(
6800 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
6801 "ball at {centre:?}: off by {on_ball}, {on_cone}"
6802 );
6803 }
6804 }
6805 let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
6807 assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
6808 let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
6809 assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
6810 }
6811
6812 #[test]
6813 fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
6814 use crate::traits::ParametricCurve;
6815 let cone = ConicalSurface::new(
6816 Point3::new(0.0, 0.0, 3.0),
6817 Vec3::new(0.0, 0.0, -1.0),
6818 2.0_f64.atan(),
6819 )
6820 .unwrap();
6821 for (centre, radius) in [
6824 (Point3::new(0.5, 0.0, 2.5), 2.0),
6825 (Point3::new(-0.4, 0.3, 2.0), 1.5),
6826 (Point3::new(0.0, 0.8, 3.0), 0.8001),
6827 (Point3::new(0.0, 0.8, 3.0), 0.800_001),
6828 ] {
6829 let ball = SphericalSurface::new(centre, radius).unwrap();
6830 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6831 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6832 let (t0, t1) = curves[0].curve.domain();
6833 for k in 0..=4096 {
6834 let p = ParametricCurve::evaluate(
6835 &curves[0].curve,
6836 (t1 - t0).madd(f64::from(k) / 4096.0, t0),
6837 );
6838 let on_ball = (p - centre).length() - radius;
6839 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6840 assert!(
6841 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
6842 "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
6843 );
6844 }
6845 }
6846 }
6847
6848 #[test]
6855 fn a_pin_tip_between_two_samples_is_not_traced_from_a_miss() {
6856 use std::f64::consts::{FRAC_PI_2, PI};
6857 let slope = 0.04375_f64;
6858 let pin = ConicalSurface::new(
6859 Point3::new(0.0, 5.005, 10.0),
6860 Vec3::new(0.0, -1.0, 0.0),
6861 (1.0 / slope).atan(),
6862 )
6863 .unwrap();
6864 let turn = FRAC_PI_2 + 5e-5 - PI / 128.0;
6865 let rod = CylindricalSurface::with_ref_dir(
6866 Point3::new(0.0, 0.0, 0.0),
6867 Vec3::new(0.0, 0.0, 1.0),
6868 5.0,
6869 Vec3::new(turn.cos(), turn.sin(), 0.0),
6870 )
6871 .unwrap();
6872 assert!(ruling_cone_cylinder(&pin, &rod, true).is_none());
6873 }
6874
6875 #[test]
6879 fn a_taper_pin_through_a_turned_rod_traces_both_loops() {
6880 use crate::traits::ParametricCurve;
6881 let slope = 0.7_f64 / 16.0;
6882 let half = (1.0 / slope).atan();
6883 for flip in [false, true] {
6884 let (apex_y, axis_y) = if flip {
6885 (-8.0 - 0.8 / slope, 1.0)
6886 } else {
6887 (-8.0 + 1.5 / slope, -1.0)
6888 };
6889 let pin = ConicalSurface::new(
6890 Point3::new(0.0, apex_y, 10.0),
6891 Vec3::new(0.0, axis_y, 0.0),
6892 half,
6893 )
6894 .unwrap();
6895 for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
6896 let rod = CylindricalSurface::with_ref_dir(
6897 Point3::new(0.0, 0.0, 0.0),
6898 Vec3::new(0.0, 0.0, 1.0),
6899 5.0,
6900 Vec3::new(spin.cos(), spin.sin(), 0.0),
6901 )
6902 .unwrap();
6903 let curves = ruling_cone_cylinder(&pin, &rod, true);
6904 assert!(curves.is_some(), "spin {spin} flip {flip}: no trace");
6905 let curves = curves.unwrap();
6906 assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
6907 for c in &curves {
6908 let (t0, t1) = c.curve.domain();
6909 for k in 0..=1000 {
6910 let p = ParametricCurve::evaluate(
6911 &c.curve,
6912 (t1 - t0).madd(f64::from(k) / 1000.0, t0),
6913 );
6914 let on_rod = p.x().hypot(p.y()) - 5.0;
6915 let on_pin = p.x().hypot(p.z() - 10.0) - slope * (p.y() - apex_y).abs();
6916 assert!(
6917 on_rod.abs() < 1e-7 && on_pin.abs() < 1e-7,
6918 "spin {spin} flip {flip}: off by {on_rod:.2e}, {on_pin:.2e}"
6919 );
6920 }
6921 }
6922 }
6923 }
6924 }
6925
6926 #[test]
6927 fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
6928 let t = 2.0_f64.atan();
6929 let cone =
6930 ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
6931 let through_apex =
6933 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6934 .unwrap();
6935 assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
6936 let generator = Vec3::new(t.cos(), 0.0, -t.sin());
6938 let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
6939 assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
6940 let pin =
6943 ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
6944 let tube =
6945 CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
6946 .unwrap();
6947 assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
6948 }
6949
6950 #[test]
6951 fn parallel_cone_cylinder_gives_two_exact_branches() {
6952 use crate::traits::ParametricCurve;
6953 let cone = ConicalSurface::new(
6954 Point3::new(-5.45, -36.55, -4.85),
6955 Vec3::new(0.0, 0.0, 1.0),
6956 std::f64::consts::FRAC_PI_4,
6957 )
6958 .unwrap();
6959 let cyl = CylindricalSurface::new(
6960 Point3::new(-8.0, -34.0, -5.0),
6961 Vec3::new(0.0, 0.0, 1.0),
6962 4.45,
6963 )
6964 .unwrap();
6965 let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
6967 let curves = intersect_analytic_analytic_bounded(
6968 AnalyticSurface::Cone(&cone),
6969 AnalyticSurface::Cylinder(&cyl),
6970 32,
6971 Some(v_hint),
6972 Some((0.0, 2.5)),
6973 )
6974 .unwrap();
6975
6976 assert_eq!(curves.len(), 2, "expected exactly the two branches");
6977 for c in &curves {
6978 let (t0, t1) = c.curve.domain();
6979 for k in 0..=32 {
6980 let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
6981 let p = ParametricCurve::evaluate(&c.curve, t);
6982 let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
6984 assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
6985 let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
6987 assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
6988 assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
6990 }
6991 }
6992 }
6993
6994 #[test]
6995 fn parallel_rod_through_a_cones_wall_closes_one_loop() {
6996 use crate::traits::ParametricCurve;
6997 let cone = ConicalSurface::new(
6999 Point3::new(0.0, 0.0, 3.0),
7000 Vec3::new(0.0, 0.0, -1.0),
7001 2.0_f64.atan(),
7002 )
7003 .unwrap();
7004 for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
7006 let rod =
7007 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7008 .unwrap();
7009 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7010 .unwrap()
7011 .unwrap();
7012 assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
7013 let (t0, t1) = curves[0].curve.domain();
7014 let (first, last) = (
7015 ParametricCurve::evaluate(&curves[0].curve, t0),
7016 ParametricCurve::evaluate(&curves[0].curve, t1),
7017 );
7018 assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
7019 for k in 0..=64 {
7020 let p = ParametricCurve::evaluate(
7021 &curves[0].curve,
7022 (t1 - t0).madd(f64::from(k) / 64.0, t0),
7023 );
7024 let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
7025 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7026 assert!(
7027 on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
7028 "({x}, {y}): off by {on_rod}, {on_cone}"
7029 );
7030 }
7031 }
7032 for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
7035 let rod =
7036 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7037 .unwrap();
7038 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7039 .unwrap()
7040 .unwrap();
7041 assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
7042 }
7043 }
7044
7045 #[test]
7051 fn parallel_cones_give_two_exact_branches() {
7052 use crate::traits::ParametricCurve;
7053 let frustum = |x: f64, r_big: f64, r_small: f64, h: f64| {
7054 let apex = h + r_small * h / (r_big - r_small);
7055 let cone = ConicalSurface::new(
7056 Point3::new(x, 0.0, apex),
7057 Vec3::new(0.0, 0.0, -1.0),
7058 apex.atan2(r_big),
7059 )
7060 .unwrap();
7061 let v = move |z: f64| (apex - z) / apex.atan2(r_big).sin();
7063 (cone, v(h), v(0.0))
7064 };
7065 let (big, big_top, big_base) = frustum(0.0, 72.0, 50.0, 84.0);
7066 for (x, flip) in [(-70.0_f64, false), (70.0, true)] {
7067 let (small, small_top, small_base) = frustum(x, 10.0, 5.0, 44.0);
7068 let (first, second) = if flip {
7069 (AnalyticSurface::Cone(&small), AnalyticSurface::Cone(&big))
7070 } else {
7071 (AnalyticSurface::Cone(&big), AnalyticSurface::Cone(&small))
7072 };
7073 let (hint_first, hint_second) = if flip {
7074 ((small_top, small_base), (big_top, big_base))
7075 } else {
7076 ((big_top, big_base), (small_top, small_base))
7077 };
7078 let curves = intersect_analytic_analytic_bounded(
7079 first,
7080 second,
7081 32,
7082 Some(hint_first),
7083 Some(hint_second),
7084 )
7085 .unwrap();
7086 assert_eq!(curves.len(), 2, "x = {x}: the two branches");
7087 let touch = 12.0 / (22.0 / 84.0 + 5.0 / 44.0);
7089 let mut tops = Vec::new();
7090 for c in &curves {
7091 let (t0, t1) = c.curve.domain();
7092 let ends = [
7093 ParametricCurve::evaluate(&c.curve, t0),
7094 ParametricCurve::evaluate(&c.curve, t1),
7095 ];
7096 let (low, high) = if ends[0].z() < ends[1].z() {
7097 (ends[0], ends[1])
7098 } else {
7099 (ends[1], ends[0])
7100 };
7101 assert!(low.z().abs() < 1e-9, "x = {x}: starts at z = {}", low.z());
7102 assert!((high.z() - touch).abs() < 1e-9, "x = {x}: tops at {high:?}");
7103 tops.push(high);
7104 for k in 0..=256 {
7105 let p = ParametricCurve::evaluate(
7106 &c.curve,
7107 (t1 - t0).madd(f64::from(k) / 256.0, t0),
7108 );
7109 let on_big = p.x().hypot(p.y()) - (72.0 - 22.0 * p.z() / 84.0);
7110 let on_small = (p.x() - x).hypot(p.y()) - (10.0 - 5.0 * p.z() / 44.0);
7111 assert!(
7112 on_big.abs() < 1e-6 && on_small.abs() < 1e-6,
7113 "x = {x}: {p:?} off by {on_big}, {on_small}"
7114 );
7115 }
7116 }
7117 assert!((tops[0] - tops[1]).length() < 1e-9, "x = {x}: {tops:?}");
7118 }
7119 }
7120
7121 #[test]
7126 fn parallel_cones_of_nearly_equal_slope_trace_on_both() {
7127 use crate::traits::ParametricCurve;
7128 let up = Vec3::new(0.0, 0.0, 1.0);
7129 let first =
7130 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7131 .unwrap();
7132 let second =
7133 ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, (1.0 / 1.001_f64).atan()).unwrap();
7134 let curves = algebraic_parallel_cone_cone(&first, &second, None, None).unwrap();
7135 assert_eq!(curves.len(), 2, "the two branches");
7136 let mut ends = Vec::new();
7137 for c in &curves {
7138 let (t0, t1) = c.curve.domain();
7139 ends.push(ParametricCurve::evaluate(&c.curve, t0));
7140 ends.push(ParametricCurve::evaluate(&c.curve, t1));
7141 for k in 0..=4096 {
7142 let p =
7143 ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 4096.0, t0));
7144 let on_first = p.x().hypot(p.y()) - p.z();
7145 let on_second = (p.x() - 1.0).hypot(p.y()) - 1.001 * p.z();
7146 assert!(
7147 on_first.abs() < 1e-7 && on_second.abs() < 1e-7,
7148 "{p:?} off by {on_first}, {on_second}"
7149 );
7150 }
7151 }
7152 let (low, high) = (1.0 / 2.001, 1000.0);
7153 for (k, z) in [(0, low), (1, high)] {
7154 let (a, b) = (ends[k], ends[2 + k]);
7155 assert!(
7156 (a.z() - z).abs() < 1e-6 * z,
7157 "branch end at {a:?}, not z = {z}"
7158 );
7159 assert!((a - b).length() < 1e-9, "branches part at {a:?} and {b:?}");
7160 }
7161 }
7162
7163 #[test]
7168 fn nearly_equal_slopes_meet_far_out() {
7169 let up = Vec3::new(0.0, 0.0, 1.0);
7170 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7171 .unwrap();
7172 let (sin1, cos1) = std::f64::consts::FRAC_PI_4.sin_cos();
7173 let slope = (cos1 + 5e-13) / sin1;
7176 let along = 2.0 / slope;
7177 let narrow =
7178 ConicalSurface::new(Point3::new(1.0, 0.0, along), up, (1.0 / slope).atan()).unwrap();
7179 let curves = algebraic_parallel_cone_cone(&wide, &narrow, Some((0.0, 4e12)), None);
7180 assert!(
7181 !curves.as_ref().is_some_and(Vec::is_empty),
7182 "called apart: {:?}",
7183 curves.map(|c| c.len())
7184 );
7185 }
7186
7187 #[test]
7193 fn parallel_cones_bounded_on_their_negative_nappes_go_to_the_marcher() {
7194 let up = Vec3::new(0.0, 0.0, 1.0);
7195 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7196 .unwrap();
7197 let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
7198 let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
7199 for cone in [&wide, &narrow] {
7200 assert!(off_cone(cone, shared).0 < 1e-12);
7201 }
7202 let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
7203 let curves = algebraic_parallel_cone_cone(
7204 &wide,
7205 &narrow,
7206 Some((-r1, -r1 / 3.0)),
7207 Some((-r2, -r2 / 3.0)),
7208 );
7209 assert!(curves.is_none(), "{:?} curves", curves.map(|c| c.len()));
7210 }
7211
7212 #[test]
7216 fn nearly_parallel_axes_take_neither_parallel_path() {
7217 let tilt = 1e-5_f64;
7218 let down = Vec3::new(0.0, 0.0, -1.0);
7219 let tilted = Vec3::new(tilt.sin(), 0.0, -tilt.cos());
7220 let big = ConicalSurface::new(
7221 Point3::new(0.0, 0.0, 274.909_090_909),
7222 down,
7223 274.909_090_909_f64.atan2(72.0),
7224 )
7225 .unwrap();
7226 let small =
7227 ConicalSurface::new(Point3::new(-70.0, 0.0, 88.0), tilted, 88.0_f64.atan2(10.0))
7228 .unwrap();
7229 assert!(algebraic_parallel_cone_cone(&big, &small, None, None).is_none());
7230 let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), down, 2.0_f64.atan()).unwrap();
7231 let rod = CylindricalSurface::new(Point3::new(1.2, 0.5, -10.0), tilted, 0.6).unwrap();
7232 assert!(
7233 algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7234 .unwrap()
7235 .is_none()
7236 );
7237 }
7238
7239 #[test]
7242 fn coaxial_cone_cylinder_defers_to_other_paths() {
7243 let cone = ConicalSurface::new(
7244 Point3::new(0.0, 0.0, 0.0),
7245 Vec3::new(0.0, 0.0, 1.0),
7246 std::f64::consts::FRAC_PI_4,
7247 )
7248 .unwrap();
7249 let cyl =
7250 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
7251 .unwrap();
7252 assert!(
7253 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7254 .unwrap()
7255 .is_none()
7256 );
7257 }
7258
7259 #[test]
7260 fn oblique_cone_cylinder_defers_to_other_paths() {
7261 let cone = ConicalSurface::new(
7262 Point3::new(0.0, 0.0, 0.0),
7263 Vec3::new(0.0, 0.0, 1.0),
7264 std::f64::consts::FRAC_PI_4,
7265 )
7266 .unwrap();
7267 let cyl =
7268 CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7269 .unwrap();
7270 assert!(
7271 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7272 .unwrap()
7273 .is_none()
7274 );
7275 }
7276
7277 #[test]
7278 fn plane_torus_lobe_closes_and_stays_on_surface() {
7279 use crate::traits::ParametricCurve;
7280 let (major, minor) = (10.0, 3.0);
7281 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7282
7283 for (n, d) in [
7287 (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), ] {
7291 let curves = intersect_plane_torus(&torus, n, d).unwrap();
7292 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7293 for c in &curves {
7294 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
7295 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
7296 assert!(
7297 (p0 - p1).length() < 1e-7,
7298 "lobe not closed: gap={} (n={n:?} d={d})",
7299 (p0 - p1).length()
7300 );
7301 for k in 0..=64 {
7303 let t = f64::from(k) / 64.0;
7304 let p = ParametricCurve::evaluate(&c.curve, t);
7305 assert!(
7306 torus_implicit(p, major, minor).abs() < 1e-2,
7307 "off-surface point {p:?} implicit={}",
7308 torus_implicit(p, major, minor)
7309 );
7310 }
7311 }
7312 }
7313 }
7314
7315 #[test]
7319 fn plane_torus_fits_stay_on_the_section_where_it_turns_tightly() {
7320 use crate::traits::ParametricCurve;
7321 let (major, minor) = (4.0, 1.5);
7322 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7323 for (n, d) in [
7324 (Vec3::new(0.0, 1.0, 0.0), 2.1),
7325 (Vec3::new(1.0, 0.0, 0.0), -1.9),
7326 (Vec3::new(0.0, 0.6, 0.8), 3.5),
7327 ] {
7328 let curves = intersect_plane_torus(&torus, n, d).unwrap();
7329 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7330 for c in &curves {
7331 for k in 0..=4000 {
7332 let p = ParametricCurve::evaluate(&c.curve, f64::from(k) / 4000.0);
7333 let off = ((p.x().hypot(p.y()) - major).hypot(p.z()) - minor).abs();
7334 assert!(off <= 1e-8, "{off} off the torus at {p:?} (n={n:?} d={d})");
7335 let off_plane = (n.dot(Vec3::new(p.x(), p.y(), p.z())) - d).abs();
7336 assert!(off_plane <= 1e-12, "{off_plane} off the plane at {p:?}");
7337 }
7338 }
7339 }
7340 }
7341
7342 #[test]
7347 fn a_plane_torus_fit_it_cannot_check_is_refused() {
7348 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7349 let across = [Point3::new(5.5, 0.0, 0.0), Point3::new(-5.5, 0.0, 0.0)];
7350 assert!(fit_plane_torus_section(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0, &across).is_err());
7351 }
7352
7353 #[test]
7358 fn a_short_newton_check_reads_each_middle_as_the_full_one_does() {
7359 let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7360 let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7361 let tol = PLANE_TORUS_FIT * 5.5;
7362 for ipts in plane_torus_loops(&torus, n, d, 128) {
7363 for (ip, power) in ipts.iter().zip((0..10).cycle()) {
7364 let off = Vec3::new(0.3, -0.7, 0.2) * (1e-13 * 10f64.powi(power));
7365 let p = ip.point + off;
7366 let full = plane_torus_section_point(&torus, n, d, p).unwrap();
7367 let short = plane_torus_newton(&torus, n, d, p, 0.25 * tol).unwrap();
7368 if (short - p).length() < 0.25 * tol {
7369 assert!((full - p).length() <= tol, "{:.2e}", (full - p).length());
7370 assert!((full - short).length() < 1e-15);
7371 } else {
7372 assert_eq!(full, short);
7373 }
7374 }
7375 }
7376 }
7377
7378 #[test]
7381 fn plane_torus_section_points_lie_on_both_surfaces() {
7382 let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7383 let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7384 for ipts in plane_torus_loops(&torus, n, d, 128) {
7385 for ip in ipts.iter().step_by(5) {
7386 let near = ip.point + Vec3::new(1e-4, -2e-4, 3e-4);
7387 let on = plane_torus_section_point(&torus, n, d, near).unwrap();
7388 let w = on - torus.center();
7389 let off = ((w.x().hypot(w.y()) - 4.0).hypot(w.z()) - 1.5).abs();
7390 assert!(off <= 1e-14, "{off} off the torus");
7391 assert!(
7392 (on.y() - 0.1).abs() <= 1e-14,
7393 "{} off the plane",
7394 on.y() - 0.1
7395 );
7396 assert!((on - near).length() < 1e-3);
7397 }
7398 }
7399 }
7400
7401 #[test]
7406 fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
7407 let (major, minor) = (10.0, 3.0);
7408 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7409 let curves =
7410 intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
7411 assert_eq!(curves.len(), 2, "one loop per lobe");
7412 let node = Point3::new(major - minor, 0.0, 0.0);
7413 let mut sides = Vec::new();
7414 for c in &curves {
7415 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7416 assert!((first - node).length() < 1e-6, "starts at {first:?}");
7417 assert_eq!(first, last, "closes on the node");
7418 for p in c.points.iter().map(|p| p.point) {
7419 assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
7420 assert!(
7421 torus_implicit(p, major, minor).abs() < 1e-6,
7422 "off the torus at {p:?}"
7423 );
7424 }
7425 let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
7426 sides.push(y > 0.0);
7427 assert!(
7428 c.points.iter().all(|p| p.point.y() * y >= -1e-9),
7429 "a lobe crosses y = 0"
7430 );
7431 }
7432 assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
7433 }
7434
7435 #[test]
7441 fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
7442 let (major, minor) = (3.0, 1.0);
7443 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7444 for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
7445 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
7446 assert_eq!(curves.len(), loops, "x = {x}");
7447 for c in &curves {
7448 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7449 assert_eq!(first, last, "x = {x}: the loop closes");
7450 for p in c.points.iter().map(|p| p.point) {
7451 assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
7452 assert!(
7453 torus_implicit(p, major, minor).abs() < 1e-6,
7454 "x = {x}: off the torus at {p:?}"
7455 );
7456 }
7457 }
7458 }
7459 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
7461 let low = curves[0]
7462 .points
7463 .iter()
7464 .map(|p| p.point)
7465 .filter(|p| p.y().abs() < 1e-6)
7466 .map(Point3::z)
7467 .collect::<Vec<_>>();
7468 let gap = (2.0001_f64 - 2.0)
7469 .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
7470 .sqrt();
7471 assert!(
7472 low.iter().any(|z| (z - gap).abs() < 1e-6)
7473 && low.iter().any(|z| (z + gap).abs() < 1e-6),
7474 "turns at {low:?}, not at z = ±{gap}"
7475 );
7476 }
7477
7478 #[test]
7482 fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
7483 let (major, minor) = (3.0, 1.0);
7484 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7485 for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
7486 let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
7487 let node = torus.evaluate(0.0, v0);
7488 let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
7489 let curves = intersect_plane_torus(&torus, normal, d).unwrap();
7490 assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
7491 for c in &curves {
7492 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7493 assert!(
7494 (first - node).length() < 1e-6,
7495 "v0 {v0}: starts at {first:?}, not {node:?}"
7496 );
7497 assert_eq!(first, last, "v0 {v0}: closes on the node");
7498 for p in c.points.iter().map(|p| p.point) {
7499 let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
7500 assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
7501 assert!(
7502 torus_implicit(p, major, minor).abs() < 1e-6,
7503 "v0 {v0}: off the torus at {p:?}"
7504 );
7505 }
7506 }
7507 }
7508 }
7509
7510 #[test]
7515 fn plane_torus_wall_sections_close_into_their_loops() {
7516 for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
7517 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7518 for k in 1..200 {
7519 let (d, want) = match k.cmp(&100) {
7520 std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
7522 std::cmp::Ordering::Greater => (
7524 2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
7525 1,
7526 ),
7527 std::cmp::Ordering::Equal => continue,
7528 };
7529 let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
7530 let closed = loops
7531 .iter()
7532 .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
7533 .count();
7534 assert_eq!(
7535 (loops.len(), closed),
7536 (want, want),
7537 "R {major} r {minor}, wall at {d}"
7538 );
7539 }
7540 }
7541 }
7542
7543 #[test]
7547 fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
7548 let (major, minor) = (4.0, 1.5);
7549 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7550 for tilt in [0.03_f64, 0.08, 0.2] {
7551 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
7552 let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
7553 assert_eq!(curves.len(), 2, "tilt {tilt}");
7554 for c in &curves {
7555 let (t0, t1) = c.curve.domain();
7556 let off = (0..=400)
7557 .map(|k| {
7558 let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
7559 (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
7560 })
7561 .fold(0.0_f64, |m, e| m.max(e.abs()));
7562 assert!(
7563 off < 1e-6,
7564 "tilt {tilt}: fitted section {off} off the torus"
7565 );
7566 }
7567 }
7568 }
7569
7570 #[test]
7571 fn line_torus_box_edge_crossing_is_exact() {
7572 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7575 let ts = intersect_line_torus(
7576 &torus,
7577 Point3::new(6.0, -4.0, -5.0),
7578 Vec3::new(0.0, 0.0, 1.0),
7579 );
7580 assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
7582 let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
7583 let rho = 6.0_f64.hypot(4.0);
7584 let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
7585 assert!(
7586 (zs[0] - (-z_exp)).abs() < 1e-9,
7587 "z0={} exp={}",
7588 zs[0],
7589 -z_exp
7590 );
7591 assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
7592 for &t in &ts {
7594 let p = Point3::new(6.0, -4.0, -5.0 + t);
7595 let rho = p.x().hypot(p.y());
7596 let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
7597 assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
7598 }
7599 }
7600
7601 #[test]
7606 fn line_spindle_torus_roots_lie_on_their_tubes() {
7607 let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
7608 let origin = Point3::new(42.36, 18.31, 3.4);
7609 let dir = Vec3::new(
7610 0.573_576_436_351_046,
7611 0.740_535_693_464_567_5,
7612 0.350_889_803_483_932_2,
7613 );
7614 let ts = intersect_line_torus(&torus, origin, dir);
7615 let tube = |t: f64, across: f64| {
7616 let q = origin + dir * t;
7617 ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
7618 };
7619 for &t in &ts {
7620 assert!(
7621 tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
7622 "root {t} off both tubes in {ts:?}"
7623 );
7624 }
7625 for want in [0.124, 0.398] {
7626 assert!(
7627 ts.iter().any(|&t| (t - want).abs() < 1e-3),
7628 "no root near {want} in {ts:?}"
7629 );
7630 }
7631 }
7632
7633 #[test]
7634 fn line_torus_miss_and_tangent() {
7635 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7636 let miss = intersect_line_torus(
7638 &torus,
7639 Point3::new(20.0, 0.0, 0.0),
7640 Vec3::new(0.0, 0.0, 1.0),
7641 );
7642 assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
7643 let axis =
7645 intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
7646 assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
7647 }
7648
7649 #[test]
7650 fn dispatch_via_analytic_surface() {
7651 let cyl =
7652 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7653 .unwrap();
7654 let curves = intersect_plane_analytic(
7655 AnalyticSurface::Cylinder(&cyl),
7656 Vec3::new(0.0, 0.0, 1.0),
7657 0.0,
7658 )
7659 .unwrap();
7660 assert!(!curves.is_empty());
7661 }
7662
7663 #[test]
7664 fn perpendicular_cylinders_intersect() {
7665 let cyl_z =
7666 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7667 .unwrap();
7668 let cyl_x =
7669 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7670 .unwrap();
7671
7672 let curves = intersect_analytic_analytic(
7673 AnalyticSurface::Cylinder(&cyl_z),
7674 AnalyticSurface::Cylinder(&cyl_x),
7675 16,
7676 )
7677 .unwrap();
7678
7679 assert!(
7680 !curves.is_empty(),
7681 "perpendicular cylinders should intersect"
7682 );
7683
7684 for c in &curves {
7685 assert!(
7686 c.points.len() >= 2,
7687 "intersection curve should have >= 2 points, got {}",
7688 c.points.len()
7689 );
7690 }
7691 }
7692
7693 #[test]
7696 fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
7697 let cyl_z =
7698 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7699 .unwrap();
7700 let cyl_x =
7701 CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7702 .unwrap();
7703 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7704 .unwrap()
7705 .unwrap();
7706 assert_eq!(curves.len(), 1);
7707 let curve = &curves[0].curve;
7708 let (t0, t1) = curve.domain();
7709 assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
7710 let off = |p: Point3| {
7711 let on_z = (p.x().hypot(p.y()) - 1.0).abs();
7712 let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
7713 on_z.max(on_x)
7714 };
7715 let worst = (0..=400)
7716 .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
7717 .fold(0.0, f64::max);
7718 assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
7719 }
7720
7721 #[test]
7725 fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
7726 let cyl_z =
7727 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7728 .unwrap();
7729 let cyl_x =
7730 CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
7731 .unwrap();
7732 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7733 .unwrap()
7734 .expect("the thin cylinder's sweep finds the loop");
7735 assert_eq!(curves.len(), 1);
7736 }
7737
7738 #[test]
7743 fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
7744 let crossing = Point3::new(1.0, 2.0, 3.0);
7745 let (s, c) = 60.0_f64.to_radians().sin_cos();
7746 let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
7747 let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
7748 let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
7749 let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
7750 assert_eq!(curves.len(), 2);
7751 let off = |p: Point3, cyl: &CylindricalSurface| {
7752 let q = p - cyl.origin();
7753 ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
7754 };
7755 let ends = [
7756 crossing + Vec3::new(0.0, 1.5, 0.0),
7757 crossing - Vec3::new(0.0, 1.5, 0.0),
7758 ];
7759 let mut vertices: Vec<Point3> = Vec::new();
7760 for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
7761 let (t0, t1) = ic.curve.domain();
7762 for k in 0..=400 {
7763 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
7764 assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
7765 assert!(side * (p - crossing).dot(d1) > -1e-13);
7766 }
7767 assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
7768 assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
7769 let other = ends[usize::from(side > 0.0)];
7770 assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
7771 for t in [0.25, 0.75] {
7772 let vertex = ic.curve.evaluate(t);
7773 assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
7774 vertices.push(vertex);
7775 }
7776 }
7777 }
7778
7779 #[test]
7784 fn nearly_crossing_equal_cylinders_are_not_ellipses() {
7785 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7786 .unwrap();
7787 let x = |(x0, y): (f64, f64), r: f64| {
7788 CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
7789 };
7790 let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
7791 assert!(taken(&x((-2.0, 0.0), 1.0)));
7792 assert!(!taken(&x((-2.0, 1e-9), 1.0)));
7793 assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
7794 assert!(!taken(&x((-1e8, 1e-6), 1.0)));
7795 }
7796
7797 #[test]
7801 fn nearly_parallel_equal_cylinders_are_not_ellipses() {
7802 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
7803 .unwrap();
7804 for slope in [1e-8, 1.5e-5] {
7805 let tilted = CylindricalSurface::new(
7806 Point3::new(0.0, 0.0, 0.0),
7807 Vec3::new(slope, 0.0, 1.0),
7808 10.0,
7809 )
7810 .unwrap();
7811 assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
7812 }
7813 }
7814
7815 #[test]
7816 fn sphere_cylinder_intersect() {
7817 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7818 let cyl =
7819 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7820 .unwrap();
7821
7822 let curves = intersect_analytic_analytic(
7823 AnalyticSurface::Sphere(&sphere),
7824 AnalyticSurface::Cylinder(&cyl),
7825 16,
7826 )
7827 .unwrap();
7828
7829 assert!(!curves.is_empty(), "sphere and cylinder should intersect");
7833 }
7834
7835 #[test]
7836 fn exact_sphere_cylinder_coaxial_two_circles() {
7837 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7840 let cyl =
7841 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7842 .unwrap();
7843 let circles = exact_sphere_cylinder(&sphere, &cyl)
7844 .unwrap()
7845 .expect("coaxial case returns Some");
7846 assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
7847 let mut zs: Vec<f64> = circles
7848 .iter()
7849 .filter_map(|c| match c {
7850 ExactIntersectionCurve::Circle(circle) => {
7851 assert!(
7852 (circle.radius() - 3.0).abs() < 1e-9,
7853 "rim radius == cyl radius"
7854 );
7855 Some(circle.center().z())
7856 }
7857 _ => None,
7858 })
7859 .collect();
7860 assert_eq!(zs.len(), 2, "both sections must be exact circles");
7861 zs.sort_by(f64::total_cmp);
7862 let z = 27.0_f64.sqrt();
7863 assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
7864 }
7865
7866 #[test]
7867 fn exact_sphere_cylinder_non_coaxial_defers() {
7868 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7870 let cyl =
7871 CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7872 .unwrap();
7873 assert!(
7874 exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
7875 "non-coaxial sphere/cylinder defers to the marcher"
7876 );
7877 }
7878
7879 #[test]
7880 fn a_ball_on_a_cones_axis_meets_it_in_circles() {
7881 let cone = ConicalSurface::new(
7883 Point3::new(0.0, 0.0, 3.0),
7884 Vec3::new(0.0, 0.0, -1.0),
7885 2.0_f64.atan(),
7886 )
7887 .unwrap();
7888 for (height, radius, count) in [
7889 (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), ] {
7895 let centre = Point3::new(0.0, 0.0, height);
7896 let ball = SphericalSurface::new(centre, radius).unwrap();
7897 let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
7898 let circles = circles_of(&curves);
7899 assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
7900 for circle in circles {
7901 for k in 0..16 {
7902 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7903 let on_ball = (p - centre).length() - radius;
7904 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7905 assert!(
7906 on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
7907 "ball at {height}: off by {on_ball}, {on_cone}"
7908 );
7909 }
7910 }
7911 }
7912 let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
7913 assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
7914 let wide =
7917 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
7918 let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
7919 let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
7920 let circles = circles_of(&curves);
7921 assert_eq!(circles.len(), 1, "the touch");
7922 let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
7923 assert!(
7924 (circles[0].radius() - touch).abs() < 1e-3,
7925 "{}",
7926 circles[0].radius()
7927 );
7928 }
7929
7930 fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
7932 curves
7933 .iter()
7934 .filter_map(|c| match c {
7935 ExactIntersectionCurve::Circle(circle) => Some(circle),
7936 _ => None,
7937 })
7938 .collect()
7939 }
7940
7941 fn worst_off(
7944 circles: &[&Circle3D],
7945 torus: &ToroidalSurface,
7946 other: impl Fn(Point3) -> f64,
7947 ) -> f64 {
7948 let mut worst = 0.0_f64;
7949 for circle in circles {
7950 for k in 0..16 {
7951 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7952 let q = p - torus.center();
7953 let along = q.dot(torus.z_axis());
7954 let rho = (q - torus.z_axis() * along).length();
7955 let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
7956 worst = worst.max(off).max(other(p).abs());
7957 }
7958 }
7959 worst
7960 }
7961
7962 #[test]
7963 fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
7964 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7965 for height in [0.0, 1.0] {
7966 let centre = Point3::new(0.0, 0.0, height);
7967 let sphere = SphericalSurface::new(centre, 3.0).unwrap();
7968 let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
7969 let circles = circles_of(&curves);
7970 assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
7971 let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
7972 assert!(worst < 1e-9, "height {height}: {worst}");
7973 }
7974 }
7975
7976 #[test]
7982 fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
7983 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7984 let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
7985 for (centre, radius, loops) in [
7986 (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
7987 (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
7988 (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
7989 (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
7990 ] {
7991 let ball = SphericalSurface::new(centre, radius).unwrap();
7992 let on_ball = |p: Point3| (p - centre).length() - radius;
7993 for ball_first in [true, false] {
7994 let (a, b) = if ball_first {
7995 (
7996 AnalyticSurface::Sphere(&ball),
7997 AnalyticSurface::Torus(&torus),
7998 )
7999 } else {
8000 (
8001 AnalyticSurface::Torus(&torus),
8002 AnalyticSurface::Sphere(&ball),
8003 )
8004 };
8005 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8006 let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
8007 assert_eq!(curves.len(), loops, "{case}");
8008 for ic in &curves {
8009 for q in &ic.points {
8010 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8011 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8012 let (on_ball_at, on_torus_at) = if ball_first {
8013 (q.param1, q.param2)
8014 } else {
8015 (q.param2, q.param1)
8016 };
8017 let (pb, pt) = (
8018 ball.evaluate(on_ball_at.0, on_ball_at.1),
8019 torus.evaluate(on_torus_at.0, on_torus_at.1),
8020 );
8021 assert!(
8022 (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
8023 "{case}: a point's parameters miss it"
8024 );
8025 }
8026 let (t0, t1) = ic.curve.domain();
8027 for k in 0..=400 {
8028 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8029 let off = on_ball(p).abs().max(on_torus(p).abs());
8030 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8031 }
8032 }
8033 }
8034 }
8035 }
8036
8037 #[test]
8044 fn balls_meet_tori_in_loops_a_scan_would_miss() {
8045 for (big, small, centre, radius, loops) in [
8046 (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
8047 (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
8048 (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
8049 (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
8050 ] {
8051 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
8052 let ball = SphericalSurface::new(centre, radius).unwrap();
8053 let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
8054 let on_ball = |p: Point3| (p - centre).length() - radius;
8055 for ball_first in [true, false] {
8056 let (a, b) = if ball_first {
8057 (
8058 AnalyticSurface::Sphere(&ball),
8059 AnalyticSurface::Torus(&torus),
8060 )
8061 } else {
8062 (
8063 AnalyticSurface::Torus(&torus),
8064 AnalyticSurface::Sphere(&ball),
8065 )
8066 };
8067 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8068 let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
8069 assert_eq!(curves.len(), loops, "{case}");
8070 for ic in &curves {
8071 for q in &ic.points {
8072 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8073 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8074 }
8075 let (t0, t1) = ic.curve.domain();
8076 for k in 0..=2000 {
8077 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8078 let off = on_ball(p).abs().max(on_torus(p).abs());
8079 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8080 }
8081 }
8082 }
8083 }
8084 }
8085
8086 #[test]
8092 fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
8093 let origin = Point3::new(0.0, 0.0, 0.0);
8094 let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
8095 let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
8096 let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
8097 assert_eq!((unit, scaled), (1, 1));
8098
8099 let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
8100 let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
8101 assert!(sphere_torus_curves(&speck, &large, true).is_none());
8102
8103 let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
8104 let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
8105 assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
8106 assert!(sphere_torus_curves(&ball, &ring, true).is_none());
8107 }
8108
8109 #[test]
8113 fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
8114 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8115 let centre = Point3::new(4.0, 0.0, 0.0);
8116 let ball = SphericalSurface::new(centre, 1.5).unwrap();
8117 for (a, b) in [
8118 (
8119 AnalyticSurface::Sphere(&ball),
8120 AnalyticSurface::Torus(&torus),
8121 ),
8122 (
8123 AnalyticSurface::Torus(&torus),
8124 AnalyticSurface::Sphere(&ball),
8125 ),
8126 ] {
8127 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8128 assert_eq!(curves.len(), 1);
8129 let (t0, t1) = curves[0].curve.domain();
8130 for k in 0..=100 {
8131 let p = curves[0]
8132 .curve
8133 .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
8134 let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
8135 assert!(off < 1e-9, "the circle strays {off:.2e}");
8136 }
8137 }
8138 }
8139
8140 #[test]
8141 fn exact_sphere_torus_misses_touches_and_defers() {
8142 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8143 let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
8144 assert!(
8145 exact_sphere_torus(&ball(0.0, 1.0), &torus)
8146 .unwrap()
8147 .unwrap()
8148 .is_empty(),
8149 "a small ball in the hole misses"
8150 );
8151 let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
8152 .unwrap()
8153 .unwrap();
8154 let circles = circles_of(&touching);
8155 assert_eq!(
8156 circles.len(),
8157 1,
8158 "a ball in the hole touches the inner equator"
8159 );
8160 assert!((circles[0].radius() - 2.5).abs() < 1e-12);
8161 assert!(circles[0].center().z().abs() < 1e-12);
8162 assert!(
8163 exact_sphere_torus(&ball(1.0, 3.0), &torus)
8164 .unwrap()
8165 .is_none(),
8166 "a ball off the axis defers"
8167 );
8168 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8169 Point3::new(0.0, 0.0, 0.0),
8170 1.0,
8171 2.0,
8172 Vec3::new(0.0, 0.0, 1.0),
8173 Vec3::new(1.0, 0.0, 0.0),
8174 )
8175 .unwrap();
8176 assert!(
8177 exact_sphere_torus(&ball(0.0, 2.5), &spindle)
8178 .unwrap()
8179 .is_none()
8180 );
8181 }
8182
8183 #[test]
8188 fn a_marched_loop_closes_on_both_surfaces() {
8189 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8190 let rod =
8191 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
8192 .unwrap();
8193 let region = Aabb3 {
8194 min: Point3::new(-0.1, -5.5, 0.4),
8195 max: Point3::new(1.1, 5.5, 1.5),
8196 };
8197 let curves = intersect_analytic_analytic_in_region(
8198 AnalyticSurface::Cylinder(&rod),
8199 AnalyticSurface::Torus(&torus),
8200 32,
8201 Some((-10.0, 10.0)),
8202 None,
8203 region,
8204 )
8205 .unwrap();
8206 assert_eq!(curves.len(), 2);
8207 for c in &curves {
8208 let (t0, t1) = c.curve.domain();
8209 let worst = (0..=4000)
8210 .map(|k| {
8211 let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 4000.0, t0));
8212 let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
8213 let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
8214 on_torus.max(on_rod)
8215 })
8216 .fold(0.0, f64::max);
8217 assert!(worst <= 1e-7, "off the surfaces by {worst}");
8218 }
8219 }
8220
8221 #[test]
8226 fn a_marched_loop_round_an_axis_runs_round_it_once() {
8227 let skin = 1.6 * std::f64::consts::SQRT_2;
8228 let tilt = 0.001_f64;
8229 let torus = ToroidalSurface::with_axis(
8230 Point3::new(0.0, 0.0, 70.5),
8231 80.8 + skin / 2.0,
8232 2.0,
8233 Vec3::new(0.0, -tilt.sin(), tilt.cos()),
8234 )
8235 .unwrap();
8236 let cone = ConicalSurface::new(
8237 Point3::new(0.0, 0.0, -9.5 - skin),
8238 Vec3::new(0.0, 0.0, 1.0),
8239 std::f64::consts::FRAC_PI_4,
8240 )
8241 .unwrap();
8242 let region = Aabb3 {
8243 min: Point3::new(-84.0, -84.0, 68.0),
8244 max: Point3::new(84.0, 84.0, 73.0),
8245 };
8246 let curves = intersect_analytic_analytic_in_region(
8247 AnalyticSurface::Cone(&cone),
8248 AnalyticSurface::Torus(&torus),
8249 32,
8250 Some((16.6, 116.3)),
8251 None,
8252 region,
8253 )
8254 .unwrap();
8255 assert_eq!(curves.len(), 1);
8256 let (t0, t1) = curves[0].curve.domain();
8257 let (start, end) = (curves[0].curve.evaluate(t0), curves[0].curve.evaluate(t1));
8258 assert!((start - end).length() < 1e-9, "{start:?} to {end:?}");
8259 let n = 4000;
8260 let mut turn = 0.0;
8261 let mut last = start.y().atan2(start.x());
8262 for k in 1..=n {
8263 let p = curves[0]
8264 .curve
8265 .evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0));
8266 let at = p.y().atan2(p.x());
8267 turn += (at - last + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
8268 last = at;
8269 }
8270 assert!((turn.abs() - TAU).abs() < 1e-6, "turns {}", turn / TAU);
8271 }
8272
8273 #[test]
8277 fn exact_cone_torus_meets_a_coaxial_cone_in_circles() {
8278 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8279 let z = Vec3::new(0.0, 0.0, 1.0);
8280 let quarter = std::f64::consts::FRAC_PI_4;
8281 let cone = |apex: f64, axis: Vec3| {
8282 ConicalSurface::new(Point3::new(0.0, 0.0, apex), axis, quarter).unwrap()
8283 };
8284 let on_cone = |apex: f64| move |p: Point3| p.x().hypot(p.y()) - (p.z() - apex);
8285 let curves = exact_cone_torus(&cone(-5.0, z), &torus).unwrap().unwrap();
8286 let circles = circles_of(&curves);
8287 assert_eq!(
8288 (curves.len(), circles.len()),
8289 (2, 2),
8290 "a wall through the tube"
8291 );
8292 let worst = worst_off(&circles, &torus, on_cone(-5.0));
8293 assert!(worst < 1e-12, "{worst}");
8294 assert!(
8295 exact_cone_torus(&cone(-8.0, z), &torus)
8296 .unwrap()
8297 .unwrap()
8298 .is_empty(),
8299 "a wall clear of the tube misses it"
8300 );
8301 let touch = -4.0 - 1.5 * std::f64::consts::SQRT_2;
8302 let curves = exact_cone_torus(&cone(touch, z), &torus).unwrap().unwrap();
8303 let circles = circles_of(&curves);
8304 assert_eq!(circles.len(), 1, "a wall touching the tube");
8305 let worst = worst_off(&circles, &torus, on_cone(touch));
8306 assert!(worst < 1e-12, "{worst}");
8307 assert_eq!(
8308 exact_cone_torus(&cone(touch + 1e-6, z), &torus)
8309 .unwrap()
8310 .unwrap()
8311 .len(),
8312 2,
8313 "a wall into the tube by more than the tolerance crosses it twice"
8314 );
8315 let below = ConicalSurface::new(Point3::new(0.0, 0.0, 5.0), -z, quarter).unwrap();
8317 let curves = exact_cone_torus(&below, &torus).unwrap().unwrap();
8318 let circles = circles_of(&curves);
8319 assert_eq!(circles.len(), 2);
8320 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - (5.0 - p.z()));
8321 assert!(worst < 1e-12, "{worst}");
8322 let tilted = cone(-5.0, Vec3::new(0.0, 0.1, 1.0));
8323 let offset = ConicalSurface::new(Point3::new(0.5, 0.0, -5.0), z, quarter).unwrap();
8324 assert!(exact_cone_torus(&tilted, &torus).unwrap().is_none());
8325 assert!(exact_cone_torus(&offset, &torus).unwrap().is_none());
8326 let far = ConicalSurface::new(Point3::new(0.0005, 0.0, -1e6), z, (1e6_f64 / 4.75).atan())
8329 .unwrap();
8330 assert!(
8331 exact_cone_torus(&far, &torus).unwrap().is_none(),
8332 "a cone off the torus's axis by 0.0005 is not coaxial, however far its apex"
8333 );
8334 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8335 Point3::new(0.0, 0.0, 0.0),
8336 1.0,
8337 2.0,
8338 z,
8339 Vec3::new(1.0, 0.0, 0.0),
8340 )
8341 .unwrap();
8342 assert!(
8343 exact_cone_torus(&cone(-5.0, z), &spindle)
8344 .unwrap()
8345 .is_none(),
8346 "a spindle torus's tube reaches the axis"
8347 );
8348 }
8349
8350 #[test]
8351 fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
8352 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8353 let z = Vec3::new(0.0, 0.0, 1.0);
8354 let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
8355 let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
8356 let circles = circles_of(&curves);
8357 assert_eq!((curves.len(), circles.len()), (2, 2));
8358 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
8359 assert!(worst < 1e-9, "{worst}");
8360 assert!(
8361 exact_cylinder_torus(&rod(2.0), &torus)
8362 .unwrap()
8363 .unwrap()
8364 .is_empty(),
8365 "a rod clear in the hole misses"
8366 );
8367 for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
8368 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8369 let circles = circles_of(&curves);
8370 assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
8371 assert!(circles[0].center().z().abs() < 1e-12, "{label}");
8372 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
8373 assert!(worst < 1e-9, "{label}: {worst}");
8374 }
8375 assert!(
8376 exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
8377 .unwrap()
8378 .unwrap()
8379 .is_empty(),
8380 "a wall clear of the tube by more than the tolerance misses it"
8381 );
8382 assert_eq!(
8383 exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
8384 .unwrap()
8385 .unwrap()
8386 .len(),
8387 2,
8388 "a wall into the tube by more than the tolerance crosses it twice"
8389 );
8390 for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
8394 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8395 assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
8396 }
8397 let tilted =
8398 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
8399 .unwrap();
8400 let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
8401 assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
8402 assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
8403 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8404 Point3::new(0.0, 0.0, 0.0),
8405 1.0,
8406 2.0,
8407 z,
8408 Vec3::new(1.0, 0.0, 0.0),
8409 )
8410 .unwrap();
8411 assert!(
8412 exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
8413 "a spindle torus's inner lemon also meets the rod"
8414 );
8415 let spindle = ToroidalSurface::with_axis_and_ref_dir(
8418 Point3::new(0.0, 0.0, 4.7),
8419 0.1,
8420 2.45,
8421 z,
8422 Vec3::new(1.0, 0.0, 0.0),
8423 )
8424 .unwrap();
8425 let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
8426 let circles = circles_of(&curves);
8427 assert_eq!(circles.len(), 1);
8428 assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
8429 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
8430 assert!(worst < 1e-9, "{worst}");
8431 let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
8432 let circles = circles_of(&curves);
8433 assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
8434 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
8435 assert!(worst < 1e-9, "{worst}");
8436 }
8437
8438 fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
8441 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
8442 let cyl =
8443 CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
8444 .unwrap();
8445 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8446 .unwrap()
8447 .unwrap();
8448 let mut worst: f64 = 0.0;
8449 for c in &curves {
8450 for ip in &c.points {
8451 let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
8452 let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
8453 worst = worst
8454 .max((on_sphere - ip.point).length())
8455 .max((on_cylinder - ip.point).length());
8456 }
8457 let (t0, t1) = c.curve.domain();
8458 assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
8459 for k in 0..=400 {
8460 let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8461 let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
8462 let on_cylinder = ((p.x() - cylinder_origin.x())
8463 .hypot(p.y() - cylinder_origin.y())
8464 - cylinder_radius)
8465 .abs();
8466 worst = worst.max(on_sphere).max(on_cylinder);
8467 }
8468 }
8469 (curves.len(), worst)
8470 }
8471
8472 #[test]
8475 fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
8476 let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
8477 assert_eq!(count, 2);
8478 assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
8479 }
8480
8481 #[test]
8483 fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
8484 let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
8485 assert_eq!(count, 1);
8486 assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
8487 }
8488
8489 #[test]
8493 fn a_ball_through_a_wide_wall_meets_it_in_one_close_loop() {
8494 let centre = Point3::new(7.35, 0.0, 0.0);
8495 let sphere = SphericalSurface::new(centre, 2.4145).unwrap();
8496 let cyl =
8497 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 9.15)
8498 .unwrap();
8499 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8500 .unwrap()
8501 .unwrap();
8502 assert_eq!(curves.len(), 1);
8503 let (t0, t1) = curves[0].curve.domain();
8504 let mut worst: f64 = 0.0;
8505 for k in 0..=2000 {
8506 let p = curves[0]
8507 .curve
8508 .evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8509 let on_sphere = ((p - centre).length() - 2.4145).abs();
8510 let on_cylinder = (p.x().hypot(p.y()) - 9.15).abs();
8511 worst = worst.max(on_sphere).max(on_cylinder);
8512 }
8513 assert!(worst < 1e-6, "the loop leaves the surfaces by {worst}");
8514 }
8515
8516 #[test]
8519 fn a_whole_torus_patch_spans_its_ring() {
8520 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 50.0, 10.0).unwrap();
8521 let size = patch_diagonal(&|u, v| torus.evaluate(u, v), (0.0, TAU), (0.0, TAU));
8522 assert!((size - 100.0).abs() < 1e-9, "size {size}");
8523 }
8524
8525 #[test]
8529 fn marched_cone_cylinder_curves_end_on_the_band_edges() {
8530 let half_angle = 14.0_f64.atan2(10.0);
8531 let cone = ConicalSurface::new(
8532 Point3::new(0.0, 0.0, 273.2),
8533 Vec3::new(0.0, 0.0, -1.0),
8534 half_angle,
8535 )
8536 .unwrap();
8537 let cyl = CylindricalSurface::new(
8538 Point3::new(0.0, -50.0, 215.0),
8539 Vec3::new(0.0, 1.0, 0.0),
8540 60.0,
8541 )
8542 .unwrap();
8543 let v_cone = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8546 let region = Aabb3 {
8547 min: Point3::new(-59.98, -40.0, 178.0),
8548 max: Point3::new(-47.23, 40.0, 192.0),
8549 };
8550 let curves = intersect_analytic_analytic_in_region(
8551 AnalyticSurface::Cone(&cone),
8552 AnalyticSurface::Cylinder(&cyl),
8553 32,
8554 Some(v_cone),
8555 Some((10.0, 90.0)),
8556 region,
8557 )
8558 .unwrap();
8559 assert_eq!(curves.len(), 2);
8560 for c in &curves {
8561 let (t0, t1) = c.curve.domain();
8562 for p in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
8563 let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8564 assert!(on_edge, "a curve ends at {p:?}");
8565 }
8566 }
8567 }
8568
8569 #[test]
8573 fn long_march_steps_end_on_the_band_edges() {
8574 let half_angle = 14.0_f64.atan2(10.0);
8575 let cone = ConicalSurface::new(
8576 Point3::new(0.0, 0.0, 273.2),
8577 Vec3::new(0.0, 0.0, -1.0),
8578 half_angle,
8579 )
8580 .unwrap();
8581 let cyl = CylindricalSurface::new(
8582 Point3::new(0.0, -50.0, 215.0),
8583 Vec3::new(0.0, 1.0, 0.0),
8584 60.0,
8585 )
8586 .unwrap();
8587 let (a, b) = (
8588 AnalyticSurface::Cone(&cone),
8589 AnalyticSurface::Cylinder(&cyl),
8590 );
8591 let (surf_a, norm_a, u_a, _) = surface_closures(&a);
8592 let (surf_b, norm_b, u_b, _) = surface_closures(&b);
8593 let v_a = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8594 let v_b = (10.0, 90.0);
8595 let seed = correct_to_intersection(
8596 &a,
8597 &b,
8598 surf_a.as_ref(),
8599 norm_a.as_ref(),
8600 surf_b.as_ref(),
8601 norm_b.as_ref(),
8602 Point3::new(-53.0, -30.0, 187.0),
8603 u_a,
8604 v_a,
8605 u_b,
8606 v_b,
8607 20,
8608 );
8609 for step in [0.5, 1.0, 2.0, 3.0] {
8610 let points = march_analytic_intersection(
8611 &a,
8612 &b,
8613 surf_a.as_ref(),
8614 norm_a.as_ref(),
8615 surf_b.as_ref(),
8616 norm_b.as_ref(),
8617 seed,
8618 u_a,
8619 v_a,
8620 u_b,
8621 v_b,
8622 step,
8623 true,
8624 true,
8625 None,
8626 )
8627 .unwrap();
8628 for p in [points[0], points[points.len() - 1]] {
8629 let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8630 assert!(on_edge, "step {step}: the march ends at {p:?}");
8631 }
8632 }
8633 }
8634
8635 #[test]
8636 fn disjoint_cylinders_no_intersection() {
8637 let cyl_a =
8638 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8639 .unwrap();
8640 let cyl_b =
8641 CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8642 .unwrap();
8643
8644 let curves = intersect_analytic_analytic(
8645 AnalyticSurface::Cylinder(&cyl_a),
8646 AnalyticSurface::Cylinder(&cyl_b),
8647 16,
8648 )
8649 .unwrap();
8650
8651 assert!(curves.is_empty(), "disjoint cylinders should not intersect");
8652 }
8653
8654 fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
8658 use crate::traits::ParametricCurve;
8659 match curve {
8660 ExactIntersectionCurve::Circle(c) => (0..=64)
8661 .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
8662 .collect(),
8663 ExactIntersectionCurve::Ellipse(e) => (0..=64)
8664 .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
8665 .collect(),
8666 ExactIntersectionCurve::Points(pts) => pts.clone(),
8667 }
8668 }
8669
8670 fn assert_on_plane_and_cone(
8673 curves: &[ExactIntersectionCurve],
8674 cone: &ConicalSurface,
8675 n: Vec3,
8676 d: f64,
8677 z_bound: (f64, f64),
8678 ) {
8679 assert!(!curves.is_empty(), "expected at least one section curve");
8680 let mut total = 0;
8681 for curve in curves {
8682 for p in collect_points(curve) {
8683 total += 1;
8684 let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
8685 assert!(
8686 plane_err < 1e-9,
8687 "point off plane by {plane_err:.2e}: {p:?}"
8688 );
8689 let (u, v) = cone.project_point(p);
8690 let q = cone.evaluate(u, v);
8691 let cone_err =
8692 ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
8693 .sqrt();
8694 assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
8695 assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
8696 assert!(
8697 p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
8698 "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
8699 p.z()
8700 );
8701 }
8702 }
8703 assert!(total >= 8, "too few section points ({total})");
8704 }
8705
8706 #[test]
8707 fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
8708 let cone = ConicalSurface::new(
8712 Point3::new(0.0, 0.0, 0.0),
8713 Vec3::new(0.0, 0.0, 1.0),
8714 std::f64::consts::FRAC_PI_4,
8715 )
8716 .unwrap();
8717 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8718 let d = n.z() * 5.0;
8720 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8721 assert!(
8722 curves
8723 .iter()
8724 .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
8725 "oblique steep plane × cone must yield an exact Ellipse"
8726 );
8727 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
8729 }
8730
8731 #[test]
8732 fn oblique_plane_cone_wrong_nappe_is_empty() {
8733 let cone = ConicalSurface::new(
8737 Point3::new(0.0, 0.0, 0.0),
8738 Vec3::new(0.0, 0.0, 1.0),
8739 std::f64::consts::FRAC_PI_4,
8740 )
8741 .unwrap();
8742 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8743 let d = n.z() * -5.0;
8744 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8745 assert!(
8746 curves.is_empty(),
8747 "plane on the phantom-nappe side must yield no real curve, got {}",
8748 curves.len()
8749 );
8750 }
8751
8752 #[test]
8753 fn oblique_plane_cone_parabola_on_both_single_branch() {
8754 let cone = ConicalSurface::new(
8757 Point3::new(0.0, 0.0, 0.0),
8758 Vec3::new(0.0, 0.0, 1.0),
8759 std::f64::consts::FRAC_PI_4,
8760 )
8761 .unwrap();
8762 let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
8763 let d = n.x() * 3.0 + n.z() * 3.0; let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8765 assert_eq!(
8766 curves.len(),
8767 1,
8768 "a parabola is a single branch, got {}",
8769 curves.len()
8770 );
8771 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
8773 }
8774
8775 #[test]
8776 fn oblique_plane_cone_hyperbola_real_nappe_only() {
8777 let cone = ConicalSurface::new(
8785 Point3::new(-59.0, -59.0, 15.85),
8786 Vec3::new(0.0, 0.0, -1.0),
8787 std::f64::consts::FRAC_PI_4,
8788 )
8789 .unwrap();
8790 let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
8791 let d = -58.360_56;
8792 let cos_theta = n.dot(cone.axis()).abs();
8793 assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
8794 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8795 assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
8798 for c in &curves {
8800 assert!(
8801 matches!(c, ExactIntersectionCurve::Points(_)),
8802 "hyperbola must be sampled Points, not a closed conic"
8803 );
8804 }
8805 }
8806
8807 #[test]
8811 fn sphere_sphere_meets_in_a_circle_on_both() {
8812 let ball = |x: f64, y: f64, z: f64, r: f64| {
8813 SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
8814 };
8815 let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
8816 let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
8817 assert_eq!(curves.len(), 1);
8818 let circle = match &curves[0] {
8819 ExactIntersectionCurve::Circle(circle) => circle,
8820 other => unreachable!("expected a circle, got {other:?}"),
8821 };
8822 for k in 0..16 {
8823 let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
8824 assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
8825 assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
8826 }
8827 assert!(
8828 exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
8829 .unwrap()
8830 .unwrap()
8831 .is_empty()
8832 );
8833 assert!(
8834 exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
8835 .unwrap()
8836 .unwrap()
8837 .is_empty()
8838 );
8839 assert!(
8840 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
8841 .unwrap()
8842 .unwrap()
8843 .is_empty()
8844 );
8845 assert!(
8846 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
8847 .unwrap()
8848 .is_none()
8849 );
8850
8851 let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
8854 match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
8855 [ExactIntersectionCurve::Circle(c)] => c.radius(),
8856 other => unreachable!("expected one circle, got {other:?}"),
8857 }
8858 };
8859 let tiny = ball(2.0, 0.0, 0.0, 1e-5);
8860 assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
8861 assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
8862 let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
8863 let far = radius(
8864 &ball(1e10, 0.0, 0.0, 2.0),
8865 &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
8866 );
8867 assert!(near > 1e-3);
8868 assert!((far - near).abs() < 1e-9 * near.max(1.0));
8869 }
8870
8871 #[allow(clippy::panic)]
8874 fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
8875 sections
8876 .iter()
8877 .map(|s| match s {
8878 PlaneSection::Line { line, ray } => (line.clone(), *ray),
8879 other => panic!("expected a line, got {other:?}"),
8880 })
8881 .collect()
8882 }
8883
8884 #[test]
8889 fn a_plane_along_a_cylinder_cuts_its_rulings() {
8890 let cyl =
8891 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
8892 .unwrap();
8893 let y = Vec3::new(0.0, 1.0, 0.0);
8894 let surface = AnalyticSurface::Cylinder(&cyl);
8895 let on_both = |p: Point3, d: f64| {
8896 assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
8897 assert!(
8898 (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
8899 "{p:?} off the cylinder"
8900 );
8901 };
8902 for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
8903 assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
8904 let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
8905 assert_eq!(lines.len(), count, "plane y = {d}");
8906 let mut xs = Vec::new();
8907 for (line, ray) in lines {
8908 assert!(!ray);
8909 assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
8910 for t in [-3.0, 0.0, 3.0] {
8911 on_both(line.evaluate(t), d);
8912 }
8913 xs.push(line.evaluate(0.0).x());
8914 }
8915 if count == 2 {
8916 let apart = (xs[0] - xs[1]).abs();
8917 let want = 2.0 * (1.0 - d * d).sqrt();
8918 assert!(
8919 (apart - want).abs() < 1e-9 * want.max(1e-6),
8920 "{apart} apart"
8921 );
8922 }
8923 }
8924 }
8925
8926 #[test]
8931 #[allow(clippy::panic)]
8932 fn a_plane_through_a_cone_apex_cuts_its_rulings() {
8933 use std::f64::consts::FRAC_PI_4;
8934
8935 let cone = ConicalSurface::new(
8936 Point3::new(1.0, 2.0, 3.0),
8937 Vec3::new(0.0, 0.0, 1.0),
8938 FRAC_PI_4,
8939 )
8940 .unwrap();
8941 let surface = AnalyticSurface::Cone(&cone);
8942 let apex = cone.apex();
8943 let through = |n: Vec3| {
8944 let n = n.normalize().unwrap();
8945 let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
8946 assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
8947 (n, d, exact_plane_section(surface, n, d).unwrap())
8948 };
8949 for (n, count) in [
8950 (Vec3::new(1.0, 0.0, 0.0), 2),
8951 (Vec3::new(1.0, 0.0, -1.0), 1),
8952 ] {
8953 let (n, d, sections) = through(n);
8954 let rays = lines_of(§ions);
8955 assert_eq!(rays.len(), count, "plane normal {n:?}");
8956 for (line, ray) in rays {
8957 assert!(ray);
8958 assert!((line.evaluate(0.0) - apex).length() < 1e-12);
8959 let p = line.evaluate(2.0);
8960 assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
8961 let rel = p - apex;
8962 assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
8963 assert!(
8964 (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
8965 "{p:?} off the cone"
8966 );
8967 }
8968 }
8969 for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
8970 let (_, _, sections) = through(n);
8971 assert!(
8972 matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
8973 "{sections:?}"
8974 );
8975 }
8976
8977 let upright = ConicalSurface::new(
8978 Point3::new(0.0, 0.0, 0.0),
8979 Vec3::new(0.0, 0.0, 1.0),
8980 FRAC_PI_4,
8981 )
8982 .unwrap();
8983 let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
8984 let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
8985 let [PlaneSection::Ellipse(ellipse)] = §ions[..] else {
8986 panic!("{sections:?}");
8987 };
8988 assert!(
8989 ellipse.semi_major() > 1.0,
8990 "semi-major {}",
8991 ellipse.semi_major()
8992 );
8993 }
8994
8995 #[test]
8998 #[allow(clippy::panic)]
8999 fn a_plane_touching_a_sphere_meets_it_at_a_point() {
9000 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
9001 let surface = AnalyticSurface::Sphere(&sphere);
9002 let z = Vec3::new(0.0, 0.0, 1.0);
9003 assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
9004 let sections = exact_plane_section(surface, z, 0.0).unwrap();
9005 assert!(
9006 matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
9007 "{sections:?}"
9008 );
9009 assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
9010 for height in [5e-15, 1e-12, 1e-8] {
9011 let sections = exact_plane_section(surface, z, height).unwrap();
9012 let [PlaneSection::Circle(circle)] = §ions[..] else {
9013 panic!("{sections:?}");
9014 };
9015 let want = (height * (2.0 - height)).sqrt();
9016 assert!(
9017 (circle.radius() - want).abs() < 1e-3 * want,
9018 "circle at z = {height}: radius {}, want {want}",
9019 circle.radius()
9020 );
9021 assert!((circle.center().z() - height).abs() < 1e-15);
9022 }
9023 }
9024
9025 fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
9027 let mut far = 0.0_f64;
9028 for ic in curves {
9029 let (t0, t1) = ic.curve.domain();
9030 for i in 0..=2000 {
9031 let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
9032 far = far.max(off(ic.curve.evaluate(t)));
9033 }
9034 }
9035 far
9036 }
9037
9038 #[test]
9041 fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
9042 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9043 let bore =
9044 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9045 .unwrap();
9046 let curves = intersect_analytic_analytic_bounded(
9047 AnalyticSurface::Sphere(&ball),
9048 AnalyticSurface::Cylinder(&bore),
9049 64,
9050 None,
9051 Some((0.0, 4.0)),
9052 )
9053 .unwrap();
9054 assert_eq!(curves.len(), 1);
9055 let far = farthest(&curves, |p| {
9056 let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9057 on_ball
9058 .max((p.x().hypot(p.y()) - 1.0).abs())
9059 .max(p.z().abs())
9060 });
9061 assert!(far < 1e-14, "circle strays {far:.2e}");
9062 }
9063
9064 #[test]
9067 fn overlapping_balls_meet_on_an_exact_circle() {
9068 let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9069 let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
9070 let curves = intersect_analytic_analytic_bounded(
9071 AnalyticSurface::Sphere(&a),
9072 AnalyticSurface::Sphere(&b),
9073 64,
9074 None,
9075 None,
9076 )
9077 .unwrap();
9078 assert_eq!(curves.len(), 1);
9079 let far = farthest(&curves, |p| {
9080 let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9081 on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
9082 });
9083 assert!(far < 1e-14, "circle strays {far:.2e}");
9084 }
9085
9086 #[test]
9089 fn a_conic_loop_is_its_ellipse() {
9090 let centre = Point3::new(1.0, -2.0, 0.5);
9091 let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
9092 let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
9093 let (t0, t1) = curve.domain();
9094 assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
9095 for i in 0..=2000 {
9096 let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
9097 let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
9098 assert!(
9099 (x.hypot(y) - 1.0).abs() < 1e-14,
9100 "off its ellipse by {}",
9101 x.hypot(y) - 1.0
9102 );
9103 assert!(p.dot(frame.z).abs() < 1e-14);
9104 }
9105 }
9106
9107 #[test]
9111 fn touching_coaxial_rings_meet_along_one_circle() {
9112 let z = Vec3::new(0.0, 0.0, 1.0);
9113 let x = Vec3::new(1.0, 0.0, 0.0);
9114 let ring =
9115 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
9116 .unwrap();
9117 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
9118 let curves = intersect_analytic_analytic_bounded(
9119 AnalyticSurface::Sphere(&ball),
9120 AnalyticSurface::Torus(&ring),
9121 64,
9122 None,
9123 None,
9124 )
9125 .unwrap();
9126 assert_eq!(curves.len(), 1);
9127 let far = farthest(&curves, |p| {
9128 let q = p - Point3::new(0.0, 0.0, 0.0);
9129 let rho = q.x().hypot(q.y());
9130 let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
9131 on_ring.max((q.length() - 2.0).abs())
9132 });
9133 assert!(far < 1e-14, "circle strays {far:.2e}");
9134
9135 let wider =
9139 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
9140 .unwrap();
9141 let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
9142 let circles = circles_of(&touching);
9143 assert_eq!(circles.len(), 1);
9144 assert!(
9145 (circles[0].radius() - 3.6).abs() < 1e-12,
9146 "{}",
9147 circles[0].radius()
9148 );
9149 assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
9150 }
9151
9152 #[test]
9157 fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
9158 let z = Vec3::new(0.0, 0.0, 1.0);
9159 let x = Vec3::new(1.0, 0.0, 0.0);
9160 let ring = |big: f64| {
9161 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
9162 .unwrap()
9163 };
9164 let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
9165 .unwrap()
9166 .unwrap();
9167 let circles = circles_of(&crossing);
9168 assert_eq!(circles.len(), 2);
9169 for circle in circles {
9170 let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
9171 assert!(
9172 (circle.center().z().abs() - height).abs() < 1e-9,
9173 "{}",
9174 circle.center().z()
9175 );
9176 }
9177 let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
9178 .unwrap()
9179 .unwrap();
9180 assert!(apart.is_empty());
9181 }
9182
9183 #[test]
9187 fn a_plane_cuts_a_cones_open_conics() {
9188 let up = Vec3::new(0.0, 0.0, 1.0);
9189 let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
9190 let steep =
9191 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
9192 let slope = 60_f64.to_radians().tan();
9193 let along =
9194 exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
9195 .unwrap();
9196 let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
9197 unreachable!("{along:?}")
9198 };
9199 for i in -20..=20 {
9200 let p = h.evaluate(f64::from(i) / 5.0);
9201 assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
9202 assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
9203 }
9204 let even =
9205 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
9206 let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
9207 let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
9208 let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
9209 unreachable!("{above:?}")
9210 };
9211 for i in -20..=20 {
9212 let p = parabola.evaluate(f64::from(i) / 2.0);
9213 assert!(
9214 (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
9215 "{p:?}"
9216 );
9217 assert!(
9218 p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
9219 "{p:?}"
9220 );
9221 }
9222 let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
9223 assert!(below.is_empty(), "{below:?}");
9224 }
9225
9226 #[test]
9232 fn extreme_cones_give_sections_on_the_cone() {
9233 let up = Vec3::new(0.0, 0.0, 1.0);
9234 let apex = Point3::new(0.0, 0.0, 0.0);
9235 let holds = |cone: &ConicalSurface, q: Point3| {
9236 let w = q - apex;
9237 (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
9238 };
9239 let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
9240 let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
9241 let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
9242 for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
9243 let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
9244 assert!(!sections.is_empty());
9245 for section in §ions {
9246 let points: Vec<Point3> = match section {
9247 PlaneSection::Hyperbola(h) => {
9248 (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
9249 }
9250 PlaneSection::Parabola(q) => {
9251 (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
9252 }
9253 PlaneSection::Points(points) => points.clone(),
9254 other => unreachable!("{other:?}"),
9255 };
9256 for q in points {
9257 assert!(holds(cone, q), "{q:?} off the cone");
9258 }
9259 }
9260 }
9261 let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
9262 assert!(matches!(
9263 flat_section.as_slice(),
9264 [PlaneSection::Hyperbola(_)]
9265 ));
9266 }
9267
9268 fn parallel_rulings(
9271 (c1, r1, v1): (Point3, f64, (f64, f64)),
9272 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9273 ) -> Vec<(Point3, Point3)> {
9274 rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
9275 }
9276
9277 fn rulings_within(
9280 (c1, r1, v1): (Point3, f64, (f64, f64)),
9281 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9282 tolerance: f64,
9283 ) -> Vec<(Point3, Point3)> {
9284 let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
9285 let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
9286 let curves = intersect_analytic_analytic_bounded(
9287 AnalyticSurface::Cylinder(&a),
9288 AnalyticSurface::Cylinder(&b),
9289 32,
9290 Some(v1),
9291 Some(v2),
9292 )
9293 .unwrap();
9294 curves
9295 .iter()
9296 .map(|ic| {
9297 let (t0, t1) = ic.curve.domain();
9298 let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
9299 for i in 0..=100 {
9300 let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
9301 let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
9302 let w = x - c2;
9303 let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
9304 assert!(
9305 on_a.abs() < tolerance && on_b.abs() < tolerance,
9306 "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
9307 );
9308 }
9309 if p.z() <= q.z() { (p, q) } else { (q, p) }
9310 })
9311 .collect()
9312 }
9313
9314 #[test]
9318 fn overlapping_parallel_rods_meet_along_two_rulings() {
9319 let mut rulings = parallel_rulings(
9320 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
9321 (
9322 Point3::new(1.2, 0.0, 3.0),
9323 1.0,
9324 Vec3::new(0.0, 0.0, -1.0),
9325 (0.0, 2.0),
9326 ),
9327 );
9328 rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9329 assert_eq!(rulings.len(), 2);
9330 for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
9331 assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
9332 assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
9333 }
9334 }
9335
9336 #[test]
9339 fn touching_parallel_rods_meet_along_one_ruling() {
9340 let up = Vec3::new(0.0, 0.0, 1.0);
9341 let beside = parallel_rulings(
9342 (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
9343 (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
9344 );
9345 assert_eq!(beside.len(), 1);
9346 assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
9347 assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
9348 let inside = parallel_rulings(
9349 (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
9350 (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9351 );
9352 assert_eq!(inside.len(), 1);
9353 assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
9354 let apart = parallel_rulings(
9355 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
9356 (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9357 );
9358 assert!(apart.is_empty());
9359 }
9360
9361 #[test]
9365 fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
9366 let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9367 .unwrap();
9368 let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
9369 let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
9370 let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
9371 assert!(span(100.0).unwrap().is_none());
9372 assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
9373 }
9374
9375 #[test]
9379 fn parallel_rods_keep_short_and_close_rulings() {
9380 let up = Vec3::new(0.0, 0.0, 1.0);
9381 let huge = rulings_within(
9382 (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
9383 (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
9384 1e-9,
9385 );
9386 assert_eq!(huge.len(), 2);
9387 assert!(
9388 huge.iter()
9389 .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
9390 );
9391 let mut close = rulings_within(
9392 (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
9393 (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
9394 1e-9,
9395 );
9396 assert_eq!(close.len(), 2);
9397 close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9398 let apart = close[1].0.y() - close[0].0.y();
9399 assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
9400 }
9401
9402 fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
9404 let q = p - cone.apex();
9405 let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
9406 ((along.abs() - s * q.length()).abs(), along / s)
9407 }
9408
9409 #[test]
9413 fn cones_sharing_an_apex_touch_along_one_ruling() {
9414 let apex = Point3::new(1.0, 2.0, 3.0);
9415 let a = 20.0_f64.to_radians();
9416 let half = std::f64::consts::FRAC_PI_2 - a;
9417 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9418 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9419 let curves = intersect_analytic_analytic_bounded(
9420 AnalyticSurface::Cone(&c1),
9421 AnalyticSurface::Cone(&c2),
9422 64,
9423 Some((0.2, 3.0)),
9424 Some((0.5, 4.0)),
9425 )
9426 .unwrap();
9427 assert_eq!(curves.len(), 1);
9428 let curve = &curves[0].curve;
9429 let (t0, t1) = curve.domain();
9430 let x = Vec3::new(1.0, 0.0, 0.0);
9431 assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
9432 assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
9433 }
9434
9435 #[test]
9439 fn cones_sharing_an_apex_cross_along_two_rulings() {
9440 let apex = Point3::new(-1.0, 0.5, 2.0);
9441 let b = 20.0_f64.to_radians();
9442 let half = 60.0_f64.to_radians();
9443 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9444 let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
9445 for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
9446 let curves = intersect_analytic_analytic_bounded(
9447 AnalyticSurface::Cone(&c1),
9448 AnalyticSurface::Cone(&c2),
9449 64,
9450 Some(range),
9451 Some(range),
9452 )
9453 .unwrap();
9454 assert_eq!(curves.len(), pieces, "{range:?}");
9455 for ic in &curves {
9456 let (t0, t1) = ic.curve.domain();
9457 for k in 0..=20 {
9458 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
9459 for cone in [&c1, &c2] {
9460 let (off, v) = off_cone(cone, p);
9461 assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
9462 assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
9463 }
9464 }
9465 if pieces == 4 {
9466 let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
9467 assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
9468 }
9469 for point in &ic.points {
9470 let (on1, on2) = (point.param1, point.param2);
9471 assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
9472 assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
9473 }
9474 }
9475 }
9476 }
9477
9478 #[test]
9483 fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
9484 let apex = Point3::new(0.0, 0.0, 0.0);
9485 let half = 60.0_f64.to_radians();
9486 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9487 let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
9488 .unwrap();
9489 let near = Some((0.5, 2.0));
9490 assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
9491 let a = 20.0_f64.to_radians();
9492 let half = std::f64::consts::FRAC_PI_2 - a;
9493 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9494 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9495 let far = Some((0.5, 1e6));
9496 assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
9497 }
9498
9499 #[test]
9502 fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
9503 let apex = Point3::new(0.0, 0.0, 0.0);
9504 let half = std::f64::consts::FRAC_PI_4 - 1e-15;
9505 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9506 let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
9507 let range = Some((0.5, 1e6));
9508 let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
9509 assert_eq!(curves.len(), 2);
9510 let ends: Vec<Point3> = curves
9511 .iter()
9512 .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
9513 .collect();
9514 assert!((ends[0] - ends[1]).length() > 0.05);
9515 }
9516
9517 #[test]
9524 fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
9525 let o = Point3::new(1.0, 2.0, 3.0);
9526 let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
9527 let (s, c) = 30.0_f64.to_radians().sin_cos();
9528 let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
9529 let on_ring = |p: Point3| {
9530 let q = p - o;
9531 ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
9532 };
9533 let balls = [
9534 (o + out * 5.0, 1.0),
9535 (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
9536 (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
9537 ];
9538 let mut touches = Vec::new();
9539 for (centre, radius) in balls {
9540 let ball = SphericalSurface::new(centre, radius).unwrap();
9541 let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
9542 let p = match exacts.as_slice() {
9543 [ExactIntersectionCurve::Points(points)] => points[0],
9544 _ => unreachable!("one touching point"),
9545 };
9546 assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
9547 let curves = intersect_analytic_analytic(
9548 AnalyticSurface::Sphere(&ball),
9549 AnalyticSurface::Torus(&ring),
9550 16,
9551 )
9552 .unwrap();
9553 assert_eq!(curves.len(), 1);
9554 let (t0, t1) = curves[0].curve.domain();
9555 assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
9556 assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
9557 touches.push(p);
9558 }
9559 assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
9560 let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
9561 assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
9562 let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
9563 let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
9564 let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
9565 unreachable!("one meridian circle");
9566 };
9567 assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
9568 assert!((circle.radius() - 1.0).abs() < 1e-12);
9569 }
9570
9571 fn taper_pin_and_rod(
9575 flip: bool,
9576 spin: f64,
9577 ) -> (ConicalSurface, (f64, f64), f64, CylindricalSurface) {
9578 let slope = 0.7_f64 / 16.0;
9579 let half = (1.0 / slope).atan();
9580 let (apex_y, axis_y) = if flip {
9581 (-8.0 - 0.8 / slope, 1.0)
9582 } else {
9583 (-8.0 + 1.5 / slope, -1.0)
9584 };
9585 let pin = ConicalSurface::new(
9586 Point3::new(0.0, apex_y, 10.0),
9587 Vec3::new(0.0, axis_y, 0.0),
9588 half,
9589 )
9590 .unwrap();
9591 let (h0, h1) = ((-8.0 - apex_y).abs(), (8.0 - apex_y).abs());
9592 let v_pin = (h0.min(h1) / half.sin(), h0.max(h1) / half.sin());
9593 let rod = CylindricalSurface::with_ref_dir(
9594 Point3::new(0.0, 0.0, 0.0),
9595 Vec3::new(0.0, 0.0, 1.0),
9596 5.0,
9597 Vec3::new(spin.cos(), spin.sin(), 0.0),
9598 )
9599 .unwrap();
9600 (pin, v_pin, apex_y, rod)
9601 }
9602
9603 const TAPER_PIN_REGION: Aabb3 = Aabb3 {
9605 min: Point3::new(-1.6, -5.1, 8.4),
9606 max: Point3::new(1.6, 5.1, 11.6),
9607 };
9608
9609 fn farthest_along(curve: &NurbsCurve, n: u32, off: impl Fn(Point3) -> f64) -> f64 {
9611 let (t0, t1) = curve.domain();
9612 (0..=n)
9613 .map(|k| off(curve.evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0))))
9614 .fold(0.0, f64::max)
9615 }
9616
9617 #[test]
9624 fn marched_cone_cylinder_sections_stay_on_both_between_their_points() {
9625 let lin = Tolerance::new().linear;
9626 for flip in [false, true] {
9627 for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
9628 let (pin, v_pin, apex_y, rod) = taper_pin_and_rod(flip, spin);
9629 let half = pin.half_angle();
9630 let off_pin = |p: Point3| {
9631 let rho = p.x().hypot(p.z() - 10.0);
9632 let h = (p.y() - apex_y).abs();
9633 rho.madd(half.sin(), -h * half.cos()).abs()
9634 };
9635 let off_rod = |p: Point3| (p.x().hypot(p.y()) - 5.0).abs();
9636 for rod_first in [true, false] {
9637 let (a, b, va, vb) = if rod_first {
9638 (
9639 AnalyticSurface::Cylinder(&rod),
9640 AnalyticSurface::Cone(&pin),
9641 Some((0.0, 20.0)),
9642 Some(v_pin),
9643 )
9644 } else {
9645 (
9646 AnalyticSurface::Cone(&pin),
9647 AnalyticSurface::Cylinder(&rod),
9648 Some(v_pin),
9649 Some((0.0, 20.0)),
9650 )
9651 };
9652 let curves =
9653 marched_sections(a, b, 32, va, vb, Some(TAPER_PIN_REGION)).unwrap();
9654 assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
9655 for c in &curves {
9656 let worst = farthest_along(&c.curve, 4000, |p| off_pin(p).max(off_rod(p)));
9657 assert!(worst <= lin, "spin {spin} flip {flip}: off by {worst:.2e}");
9658 }
9659 }
9660 }
9661 }
9662
9663 let (cone, tube) = cone_and_tilted_tube();
9664 let curves = intersect_analytic_analytic_bounded(
9665 AnalyticSurface::Cone(&cone),
9666 AnalyticSurface::Cylinder(&tube),
9667 32,
9668 Some((0.5, 4.0)),
9669 Some((-5.0, 5.0)),
9670 )
9671 .unwrap();
9672 assert!(!curves.is_empty());
9673 let (sin, cos) = cone.half_angle().sin_cos();
9674 let axis = tube.axis();
9675 for c in &curves {
9676 let worst = farthest_along(&c.curve, 4000, |p| {
9677 let on_cone = p.x().hypot(p.y()).madd(sin, -p.z().abs() * cos).abs();
9678 let w = p - tube.origin();
9679 let on_tube = ((w - axis * axis.dot(w)).length() - 0.1).abs();
9680 on_cone.max(on_tube)
9681 });
9682 assert!(worst <= lin, "tilted tube: off by {worst:.2e}");
9683 }
9684
9685 let half_angle = 14.0_f64.atan2(10.0);
9686 let cone = ConicalSurface::new(
9687 Point3::new(0.0, 0.0, 273.2),
9688 Vec3::new(0.0, 0.0, -1.0),
9689 half_angle,
9690 )
9691 .unwrap();
9692 let cyl = CylindricalSurface::new(
9693 Point3::new(0.0, -50.0, 215.0),
9694 Vec3::new(0.0, 1.0, 0.0),
9695 60.0,
9696 )
9697 .unwrap();
9698 let curves = intersect_analytic_analytic_in_region(
9699 AnalyticSurface::Cone(&cone),
9700 AnalyticSurface::Cylinder(&cyl),
9701 32,
9702 Some((81.2 / half_angle.sin(), 95.2 / half_angle.sin())),
9703 Some((10.0, 90.0)),
9704 Aabb3 {
9705 min: Point3::new(-59.98, -40.0, 178.0),
9706 max: Point3::new(-47.23, 40.0, 192.0),
9707 },
9708 )
9709 .unwrap();
9710 assert_eq!(curves.len(), 2);
9711 let (sin, cos) = half_angle.sin_cos();
9712 for c in &curves {
9713 let worst = farthest_along(&c.curve, 4000, |p| {
9714 let on_cone = p.x().hypot(p.y()).madd(sin, -(273.2 - p.z()) * cos).abs();
9715 let on_cyl = (p.x().hypot(p.z() - 215.0) - 60.0).abs();
9716 on_cone.max(on_cyl)
9717 });
9718 assert!(worst <= lin, "band: off by {worst:.2e}");
9719 }
9720 }
9721
9722 #[test]
9731 fn a_seed_where_two_walls_pass_closest_starts_no_march() {
9732 let (pin, v_pin, _, rod) = taper_pin_and_rod(false, 0.9);
9733 let (a, b) = (AnalyticSurface::Cylinder(&rod), AnalyticSurface::Cone(&pin));
9734 let stalled = Point3::new(
9735 -2.503_835_657_485_280_5,
9736 -3.349_109_255_073_426,
9737 9.881_016_348_226_973,
9738 );
9739 let off_rod = |p: Point3| section_fit::Carrier::distance(&a, p).unwrap().0;
9740 let off_pin = |p: Point3| section_fit::Carrier::distance(&b, p).unwrap().0;
9741 assert!(off_rod(stalled).abs() > 0.8);
9742 let on = settle_on_section(&a, &b, stalled).unwrap();
9743 let (d_rod, d_pin) = (off_rod(on), off_pin(on));
9744 assert!(
9745 d_rod.abs() < 1e-12 && d_pin.abs() < 1e-12,
9746 "{d_rod:.1e}, {d_pin:.1e}"
9747 );
9748
9749 let curves = marched_sections(
9750 a,
9751 b,
9752 32,
9753 Some((0.0, 20.0)),
9754 Some(v_pin),
9755 Some(TAPER_PIN_REGION),
9756 )
9757 .unwrap();
9758 assert_eq!(curves.len(), 2);
9759 for c in &curves {
9760 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
9761 assert!((first - last).length() < 1e-9, "{first:?} to {last:?}");
9762 assert!(c.points.len() < 400, "{} points", c.points.len());
9763 }
9764
9765 let ball = SphericalSurface::new(Point3::new(3.0, 0.0, 0.0), 1.0).unwrap();
9767 let post =
9768 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9769 .unwrap();
9770 let gap = Point3::new(1.5, 0.0, 0.0);
9771 assert!(
9772 settle_on_section(
9773 &AnalyticSurface::Sphere(&ball),
9774 &AnalyticSurface::Cylinder(&post),
9775 gap
9776 )
9777 .is_none()
9778 );
9779 }
9780
9781 #[test]
9787 fn rods_that_only_touch_trace_no_section() {
9788 let wall =
9789 CylindricalSurface::new(Point3::new(1.1, 1.1, 1.2), Vec3::new(0.0, 0.0, 1.0), 2.55)
9790 .unwrap();
9791 let air =
9792 CylindricalSurface::new(Point3::new(-3.9, 1.1, 4.7), Vec3::new(0.0, 1.0, 0.0), 2.45)
9793 .unwrap();
9794 let (a, b) = (
9795 AnalyticSurface::Cylinder(&wall),
9796 AnalyticSurface::Cylinder(&air),
9797 );
9798 let touch = Point3::new(-1.45, 1.1, 4.7);
9799 assert!(!crosses_at(&a, &b, touch));
9800 let region = Aabb3 {
9801 min: Point3::new(-2.1625, 0.3875, 1.5375),
9802 max: Point3::new(-0.7375, 1.8125, 5.4125),
9803 };
9804 let curves = marched_sections(
9805 a,
9806 b,
9807 32,
9808 Some((1.05, 12.45)),
9809 Some((0.0, 30.9)),
9810 Some(region),
9811 )
9812 .unwrap();
9813 assert!(curves.is_empty(), "{} sections", curves.len());
9814 }
9815
9816 fn off_double_cone(cone: &ConicalSurface, p: Point3) -> f64 {
9819 let w = p - cone.apex();
9820 let h = cone.axis().dot(w);
9821 let rho = (w - cone.axis() * h).length();
9822 let (sin, cos) = cone.half_angle().sin_cos();
9823 rho.madd(sin, -h.abs() * cos).abs()
9824 }
9825
9826 #[test]
9833 fn negative_nappe_sections_are_marched_on_both_cones() {
9834 let up = Vec3::new(0.0, 0.0, 1.0);
9835 let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
9836 .unwrap();
9837 let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
9838 let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
9839 for cone in [&wide, &narrow] {
9840 let (off, _) =
9841 section_fit::Carrier::distance(&AnalyticSurface::Cone(cone), shared).unwrap();
9842 assert!(off.abs() < 1e-12, "{off}");
9843 }
9844 let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
9845 let (v_wide, v_narrow) = ((-r1, -r1 / 3.0), (-r2, -r2 / 3.0));
9846 for wide_first in [true, false] {
9847 let (a, b, va, vb) = if wide_first {
9848 (
9849 AnalyticSurface::Cone(&wide),
9850 AnalyticSurface::Cone(&narrow),
9851 v_wide,
9852 v_narrow,
9853 )
9854 } else {
9855 (
9856 AnalyticSurface::Cone(&narrow),
9857 AnalyticSurface::Cone(&wide),
9858 v_narrow,
9859 v_wide,
9860 )
9861 };
9862 let curves = marched_sections(a, b, 32, Some(va), Some(vb), None).unwrap();
9863 assert!(!curves.is_empty(), "wide first {wide_first}: no section");
9864 for c in &curves {
9865 let worst = farthest_along(&c.curve, 4000, |p| {
9866 off_double_cone(&wide, p).max(off_double_cone(&narrow, p))
9867 });
9868 assert!(worst <= 1e-7, "wide first {wide_first}: off by {worst:.2e}");
9869 let below = farthest_along(&c.curve, 4000, |p| (p.z() + 1.0 / 3.0).max(0.0));
9870 assert!(
9871 below < 1e-9,
9872 "wide first {wide_first}: above z = -1/3 by {below:.2e}"
9873 );
9874 }
9875 }
9876 }
9877
9878 #[test]
9885 fn a_fit_along_a_negative_ruling_is_bounded() {
9886 let cone = ConicalSurface::new(
9887 Point3::new(0.0, 0.0, 0.0),
9888 Vec3::new(0.0, 0.0, 1.0),
9889 std::f64::consts::FRAC_PI_4,
9890 )
9891 .unwrap();
9892 let along = Vec3::new(1.0, 0.0, -1.0) * std::f64::consts::FRAC_1_SQRT_2;
9893 let rod = CylindricalSurface::new(Point3::new(0.0, 1.0, 0.0), along, 1.0).unwrap();
9894 let (a, b) = (
9895 AnalyticSurface::Cone(&cone),
9896 AnalyticSurface::Cylinder(&rod),
9897 );
9898 let ruling: Vec<Point3> = (1..=4)
9899 .map(|k| Point3::new(f64::from(k), 0.0, -f64::from(k)))
9900 .collect();
9901 let ctrl = [ruling[0], ruling[1], ruling[2], ruling[3]];
9902 let bound = section_fit::Carrier::bound(&a, &ctrl).unwrap();
9903 assert!(bound < 1e-12, "{bound:.2e}");
9904 let (curve, points) = fit_section(&a, &b, &ruling, 1e-7).unwrap();
9905 assert_eq!(points.len(), 4);
9906 let worst = farthest_along(&curve, 1000, |p| p.y().abs().max((p.x() + p.z()).abs()));
9907 assert!(worst < 1e-12, "{worst:.2e}");
9908 let through_apex = [
9909 Point3::new(-1.0, 0.0, 1.0),
9910 Point3::new(-1.0 / 3.0, 0.0, 1.0 / 3.0),
9911 Point3::new(1.0 / 3.0, 0.0, -1.0 / 3.0),
9912 Point3::new(1.0, 0.0, -1.0),
9913 ];
9914 assert!(section_fit::Carrier::bound(&a, &through_apex).is_none());
9915 }
9916
9917 #[test]
9926 fn a_touch_far_from_the_origin_settles_as_one_near_it_does() {
9927 for o in [
9928 Vec3::new(0.0, 0.0, 0.0),
9929 Vec3::new(1e6, 0.0, 0.0),
9930 Vec3::new(1e12, 0.0, 0.0),
9931 Vec3::new(0.0, 1e12, 0.0),
9932 Vec3::new(0.0, 0.0, 1e12),
9933 ] {
9934 let post = CylindricalSurface::new(
9935 Point3::new(0.0, 0.0, 0.0) + o,
9936 Vec3::new(0.0, 0.0, 1.0),
9937 1.0,
9938 )
9939 .unwrap();
9940 let beam = CylindricalSurface::new(
9941 Point3::new(3.0, 0.0, 0.0) + o,
9942 Vec3::new(0.0, 1.0, 0.0),
9943 2.0,
9944 )
9945 .unwrap();
9946 let (a, b) = (
9947 AnalyticSurface::Cylinder(&post),
9948 AnalyticSurface::Cylinder(&beam),
9949 );
9950 if o.length() == 0.0 {
9951 let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
9952 assert!(
9953 settled.is_none_or(|p| !crosses_at(&a, &b, p)),
9954 "settles on a crossing at {settled:?}"
9955 );
9956 }
9957 let region = Aabb3 {
9958 min: Point3::new(0.5, -0.5, -0.5) + o,
9959 max: Point3::new(1.5, 0.5, 0.5) + o,
9960 };
9961 let curves =
9962 marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some(region))
9963 .unwrap();
9964 assert!(curves.is_empty(), "moved {o:?}: {} sections", curves.len());
9965 }
9966 }
9967
9968 #[test]
9974 fn fits_on_slender_and_flat_cones_are_bounded() {
9975 use std::f64::consts::FRAC_PI_2;
9976 for half in [FRAC_PI_2 - 0.01, FRAC_PI_2 - 0.001, 0.01, 0.001] {
9977 let cone =
9978 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), half)
9979 .unwrap();
9980 let v = 10.0;
9981 let (rho, h) = (v * half.cos(), v * half.sin());
9982 let rod =
9983 CylindricalSurface::new(Point3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0), rho)
9984 .unwrap();
9985 let (a, b) = (
9986 AnalyticSurface::Cone(&cone),
9987 AnalyticSurface::Cylinder(&rod),
9988 );
9989 let circle: Vec<Point3> = (0..=12)
9990 .map(|k| {
9991 let t = TAU * f64::from(k) / 12.0;
9992 Point3::new(rho * t.cos(), rho * t.sin(), h)
9993 })
9994 .collect();
9995 let (curve, points) = fit_section(&a, &b, &circle, 1e-7).unwrap();
9996 let worst = farthest_along(&curve, 4000, |p| {
9997 off_double_cone(&cone, p).max((p.x().hypot(p.y()) - rho).abs())
9998 });
9999 assert!(worst <= 1e-7, "half {half}: off by {worst:.2e}");
10000 assert!(points.len() < 2000, "half {half}: {} points", points.len());
10001 }
10002 }
10003
10004 #[test]
10011 fn a_section_far_from_the_origin_is_traced_as_near_it() {
10012 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10013 let run = |o: Vec3| {
10014 let torus = ring.translated(o);
10015 let rod = CylindricalSurface::new(
10016 Point3::new(0.5, 0.0, 1.0) + o,
10017 Vec3::new(0.0, 1.0, 0.0),
10018 0.6,
10019 )
10020 .unwrap();
10021 let region = Aabb3 {
10022 min: Point3::new(-0.1, -5.5, 0.4) + o,
10023 max: Point3::new(1.1, 5.5, 1.5) + o,
10024 };
10025 intersect_analytic_analytic_in_region(
10026 AnalyticSurface::Cylinder(&rod),
10027 AnalyticSurface::Torus(&torus),
10028 32,
10029 Some((-10.0, 10.0)),
10030 None,
10031 region,
10032 )
10033 };
10034 for o in [
10035 Vec3::new(0.0, 0.0, 0.0),
10036 Vec3::new(1e6, 0.0, 0.0),
10037 Vec3::new(0.0, 1e6, 0.0),
10038 Vec3::new(0.0, 0.0, 1e6),
10039 ] {
10040 let curves = run(o).unwrap();
10041 assert_eq!(curves.len(), 2, "moved {o:?}");
10042 for c in &curves {
10043 let worst = farthest_along(&c.curve, 4000, |p| {
10044 let q = p - o;
10045 let on_torus = ((q.x().hypot(q.y()) - 4.0).hypot(q.z()) - 1.5).abs();
10046 let on_rod = ((q.x() - 0.5).hypot(q.z() - 1.0) - 0.6).abs();
10047 on_torus.max(on_rod)
10048 });
10049 assert!(worst <= 1e-7, "moved {o:?}: off by {worst:.2e}");
10050 }
10051 }
10052 for o in [
10053 Vec3::new(1e9, 0.0, 0.0),
10054 Vec3::new(0.0, 1e9, 0.0),
10055 Vec3::new(0.0, 0.0, 1e9),
10056 ] {
10057 assert!(
10058 matches!(run(o), Err(MathError::ConvergenceFailure { iterations: 0 })),
10059 "moved {o:?}: not refused before its fit"
10060 );
10061 }
10062 }
10063
10064 #[test]
10073 fn frames_far_along_a_rods_axis_read_as_near_ones() {
10074 let post =
10075 CylindricalSurface::new(Point3::new(0.0, 0.0, -1e6), Vec3::new(0.0, 0.0, 1.0), 1.0)
10076 .unwrap();
10077 let beam =
10078 CylindricalSurface::new(Point3::new(3.0, -1e6, 0.0), Vec3::new(0.0, 1.0, 0.0), 2.0)
10079 .unwrap();
10080 let (a, b) = (
10081 AnalyticSurface::Cylinder(&post),
10082 AnalyticSurface::Cylinder(&beam),
10083 );
10084 let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
10085 assert!(
10086 settled.is_none_or(|p| !crosses_at(&a, &b, p)),
10087 "settles on a crossing at {settled:?}"
10088 );
10089 let region = Aabb3 {
10090 min: Point3::new(0.5, -0.5, -0.5),
10091 max: Point3::new(1.5, 0.5, 0.5),
10092 };
10093 let far = Some((1e6 - 1.0, 1e6 + 1.0));
10094 let curves = marched_sections(a, b, 32, far, far, Some(region)).unwrap();
10095 assert!(curves.is_empty(), "{} sections", curves.len());
10096
10097 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10098 let boxes = |frame: f64| {
10099 let rod = CylindricalSurface::new(
10100 Point3::new(0.5, -frame, 1.0),
10101 Vec3::new(0.0, 1.0, 0.0),
10102 0.6,
10103 )
10104 .unwrap();
10105 let region = Aabb3 {
10106 min: Point3::new(-0.1, -5.5, 0.4),
10107 max: Point3::new(1.1, 5.5, 1.5),
10108 };
10109 let curves = intersect_analytic_analytic_in_region(
10110 AnalyticSurface::Cylinder(&rod),
10111 AnalyticSurface::Torus(&ring),
10112 32,
10113 Some((frame - 10.0, frame + 10.0)),
10114 None,
10115 region,
10116 )
10117 .unwrap();
10118 let mut boxes: Vec<Aabb3> = curves
10119 .iter()
10120 .map(|c| {
10121 let worst = farthest_along(&c.curve, 4000, |p| {
10122 let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10123 let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
10124 on_torus.max(on_rod)
10125 });
10126 assert!(worst <= 1e-7, "frame {frame}: off by {worst:.2e}");
10127 Aabb3::try_from_points(c.points.iter().map(|ip| ip.point)).unwrap()
10128 })
10129 .collect();
10130 boxes.sort_by(|p, q| p.min.y().total_cmp(&q.min.y()));
10131 boxes
10132 };
10133 let (near, far) = (boxes(0.0), boxes(1e6));
10134 assert_eq!(near.len(), 2);
10135 assert_eq!(far.len(), near.len());
10136 for (n, f) in near.iter().zip(&far) {
10137 assert!((n.min - f.min).length() < 1e-6 && (n.max - f.max).length() < 1e-6);
10138 }
10139 }
10140
10141 fn two_sum(a: f64, b: f64) -> (f64, f64) {
10143 let s = a + b;
10144 let back = s - a;
10145 (s, (a - (s - back)) + (b - back))
10146 }
10147
10148 fn two_prod(a: f64, b: f64) -> (f64, f64) {
10150 let split = |v: f64| {
10151 let c = 134_217_729.0 * v;
10152 let hi = c - (c - v);
10153 (hi, v - hi)
10154 };
10155 let p = a * b;
10156 let ((ah, al), (bh, bl)) = (split(a), split(b));
10157 (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl)
10158 }
10159
10160 fn off_line(o: Point3, a: Vec3, p: Point3) -> f64 {
10164 let w = [
10165 two_sum(p.x(), -o.x()),
10166 two_sum(p.y(), -o.y()),
10167 two_sum(p.z(), -o.z()),
10168 ];
10169 let a = [a.x(), a.y(), a.z()];
10170 let dot = |y: &[(f64, f64); 3]| {
10172 let (mut hi, mut lo) = (0.0, 0.0);
10173 for (ai, (yh, yl)) in a.iter().zip(y) {
10174 let (prod, prod_err) = two_prod(*ai, *yh);
10175 let (sum, sum_err) = two_sum(hi, prod);
10176 hi = sum;
10177 lo += sum_err + prod_err + ai * yl;
10178 }
10179 two_sum(hi, lo)
10180 };
10181 let (aw, aw_err) = dot(&w);
10182 let (aa, aa_err) = dot(&a.map(|x| (x, 0.0)));
10183 let s = aw / aa;
10186 let (sa, sa_err) = two_prod(s, aa);
10187 let rest = ((aw - sa) - sa_err) + aw_err - s * aa_err;
10188 let s_err = rest / aa;
10189 let across = a.iter().zip(w).map(|(ai, (hi, lo))| {
10190 let (prod, prod_err) = two_prod(*ai, s);
10191 let (diff, diff_err) = two_sum(hi, -prod);
10192 diff + (diff_err + lo - prod_err - ai * s_err)
10193 });
10194 across.map(|c| c * c).sum::<f64>().sqrt()
10195 }
10196
10197 #[test]
10205 fn a_tilted_rod_framed_far_along_its_axis_is_traced_on_it() {
10206 let along = Vec3::new(0.3, 0.4, 0.5);
10207 let through = Point3::new(4.0, 0.0, 0.0);
10208 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10209 let near_rod = CylindricalSurface::new(through, along, 0.6).unwrap();
10210 let axis = near_rod.axis();
10211 let far = through + axis * 1e12;
10212 let rod = CylindricalSurface::new(far, along, 0.6).unwrap();
10213 let anchor = Point3::new(4.0, 0.0, 0.0);
10214 let (moved, dv, error) = Moved::new(&AnalyticSurface::Cylinder(&rod), anchor);
10215 let AnalyticSurface::Cylinder(moved) = moved.surface() else {
10216 unreachable!("a rod moves to a rod");
10217 };
10218 let foot = moved.origin() + (anchor - Point3::new(0.0, 0.0, 0.0));
10219 let off = off_line(rod.origin(), rod.axis(), foot);
10220 assert!(
10221 off <= error && error < 1e-14,
10222 "the frame lies {off:.2e} off the axis"
10223 );
10224 assert!((dv + 1e12).abs() < 1.0, "v moved by {dv}");
10225
10226 let region = Aabb3 {
10227 min: Point3::new(2.0, -2.0, -2.0),
10228 max: Point3::new(6.0, 2.0, 2.0),
10229 };
10230 let sweep = (1e12 - 10.0, 1e12 + 10.0);
10231 let result = marched_sections(
10232 AnalyticSurface::Cylinder(&rod),
10233 AnalyticSurface::Torus(&ring),
10234 32,
10235 Some((-sweep.1, -sweep.0)),
10236 None,
10237 Some(region),
10238 );
10239 let curves = result.unwrap();
10240 assert_eq!(curves.len(), 2);
10241 {
10242 for c in &curves {
10243 let worst = farthest_along(&c.curve, 4000, |p| {
10244 let on_rod = (off_line(rod.origin(), rod.axis(), p) - 0.6).abs();
10245 let on_ring = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10246 on_rod.max(on_ring)
10247 });
10248 assert!(worst <= 1e-7, "off by {worst:.2e}");
10249 }
10250 }
10251 }
10252
10253 #[test]
10257 fn each_surface_bends_as_its_distance_does() {
10258 use section_fit::Carrier;
10259 let cyl =
10260 CylindricalSurface::new(Point3::new(0.3, -0.2, 0.5), Vec3::new(0.2, 0.3, 1.0), 0.7)
10261 .unwrap();
10262 let ball = SphericalSurface::new(Point3::new(-0.4, 0.1, 0.2), 1.3).unwrap();
10263 let cone = ConicalSurface::new(Point3::new(0.1, 0.2, -0.3), Vec3::new(-0.3, 0.1, 1.0), 0.6)
10264 .unwrap();
10265 let ring = ToroidalSurface::new(Point3::new(0.2, -0.1, 0.1), 2.0, 0.6).unwrap();
10266 let surfaces = [
10267 AnalyticSurface::Cylinder(&cyl),
10268 AnalyticSurface::Sphere(&ball),
10269 AnalyticSurface::Cone(&cone),
10270 AnalyticSurface::Torus(&ring),
10271 ];
10272 let directions = [
10273 Vec3::new(1.0, 0.0, 0.0),
10274 Vec3::new(0.0, 1.0, 0.0),
10275 Vec3::new(0.0, 0.0, 1.0),
10276 Vec3::new(0.6, -0.48, 0.64),
10277 ];
10278 let (_, _, _, cone_v) = surface_closures(&AnalyticSurface::Cone(&cone));
10279 for (k, s) in surfaces.iter().enumerate() {
10280 let (surf, norm, _, (v0, v1)) = surface_closures(s);
10281 let (v0, v1) = if matches!(s, AnalyticSurface::Cone(_)) {
10282 (cone_v.0.max(0.5), cone_v.1)
10283 } else {
10284 (v0, v1)
10285 };
10286 for (u, v) in [(0.3, 0.25), (1.9, 0.5), (4.4, 0.75)] {
10287 let v = (v1 - v0).madd(v, v0);
10288 for off in [0.0, 0.05, -0.05] {
10289 let p = surf(u, v) + norm(u, v) * off;
10290 let f = |q: Point3| s.distance(q).unwrap().0;
10291 for d in directions {
10292 let d = d * (1.0 / d.length());
10293 let h = 1e-4;
10294 let second = (f(p + d * h) - 2.0 * f(p) + f(p - d * h)) / (h * h);
10295 let exact = s.bend(p, d).unwrap();
10296 assert!(
10297 (second - exact).abs() <= 1e-5 * (1.0 + exact.abs()),
10298 "surface {k} at {p:?} along {d:?}: {exact} against {second}"
10299 );
10300 }
10301 }
10302 }
10303 }
10304 }
10305
10306 #[test]
10313 fn a_cone_reads_no_curvature_on_its_apex_plane() {
10314 use section_fit::Carrier;
10315 let axis = Vec3::new(0.0, 0.0, 1.0);
10316 let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), axis, 0.7).unwrap();
10317 let rod =
10318 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
10319 .unwrap();
10320 let (a, b) = (
10321 AnalyticSurface::Cone(&cone),
10322 AnalyticSurface::Cylinder(&rod),
10323 );
10324 let across = Vec3::new(1.0, 0.0, 0.0);
10325 for on in [
10326 Point3::new(2.0, 0.0, 0.0),
10327 Point3::new(2.0, 0.0, 1e-17),
10328 Point3::new(2.0, 0.0, -1e-17),
10329 ] {
10330 assert!(a.distance(on).is_some());
10331 assert!(a.bend(on, axis).is_none(), "{on:?} along the axis");
10332 assert!(a.bend(on, across).is_none(), "{on:?} across");
10333 assert!(station(&a, &b, on, axis).is_none(), "{on:?} station");
10334 assert!(singular_point(&a, &b, on, 1.0).is_none(), "{on:?} touch");
10335 }
10336 for off in [Point3::new(2.0, 0.0, 1e-3), Point3::new(2.0, 0.0, -1e-3)] {
10337 assert!(a.bend(off, axis).is_some(), "{off:?} along the axis");
10338 assert!(a.bend(off, across).is_some(), "{off:?} across");
10339 }
10340 }
10341
10342 fn three_poses() -> [crate::mat::Mat4; 3] {
10344 use crate::mat::Mat4;
10345 [
10346 Mat4::identity(),
10347 Mat4::translation(-3.7, 5.5, 14.0) * Mat4::rotation_z(0.7) * Mat4::rotation_x(-0.9),
10348 Mat4::scale(-1.0, 1.0, 1.0) * Mat4::rotation_y(0.4),
10349 ]
10350 }
10351
10352 fn posed_cone_and_rod(
10357 pose: &crate::mat::Mat4,
10358 half: f64,
10359 z0: f64,
10360 r: f64,
10361 n: u32,
10362 ) -> (ConicalSurface, CylindricalSurface, Vec<Point3>) {
10363 let o = Point3::new(0.0, 0.0, 0.0);
10364 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10365 let cone =
10366 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half).unwrap();
10367 let rod = CylindricalSurface::new(
10368 pose.mul_point(Point3::new(0.0, 0.0, z0)),
10369 along(Vec3::new(1.0, 0.0, 0.0)),
10370 r,
10371 )
10372 .unwrap();
10373 let mut truth = Vec::new();
10374 for k in 0..n {
10375 let phi = TAU * f64::from(k) / f64::from(n);
10376 let (y, z) = (r * phi.sin(), r.madd(-phi.cos(), z0));
10377 let rho = z.abs() / half.tan();
10378 let x2 = rho.madd(rho, -y * y);
10379 if x2 >= 0.0 {
10380 for x in [x2.sqrt(), -x2.sqrt()] {
10381 truth.push(pose.mul_point(Point3::new(x, y, z)));
10382 }
10383 }
10384 }
10385 (cone, rod, truth)
10386 }
10387
10388 #[test]
10400 fn thin_loops_on_flat_and_slender_cones_are_marched_round() {
10401 use std::f64::consts::FRAC_PI_2;
10402 let lin = Tolerance::new().linear;
10403 let cases = [
10404 (0.01, 0.1, 0.05),
10405 (FRAC_PI_2 - 0.01, 3.0, 0.05),
10406 (FRAC_PI_2 - 0.01, 10.0, 0.05),
10407 (FRAC_PI_2 - 0.01, 10.0, 0.2),
10408 ];
10409 for (half, z0, r) in cases {
10410 for (p, pose) in three_poses().iter().enumerate() {
10411 let (cone, rod, truth) = posed_cone_and_rod(pose, half, z0, r, 360);
10412 for cone_first in [true, false] {
10413 let label =
10414 format!("half {half} z0 {z0} r {r} pose {p} cone first {cone_first}");
10415 let (a, b, va, vb) = if cone_first {
10416 (
10417 AnalyticSurface::Cone(&cone),
10418 AnalyticSurface::Cylinder(&rod),
10419 (1.0, 20.0),
10420 (-20.0, 20.0),
10421 )
10422 } else {
10423 (
10424 AnalyticSurface::Cylinder(&rod),
10425 AnalyticSurface::Cone(&cone),
10426 (-20.0, 20.0),
10427 (1.0, 20.0),
10428 )
10429 };
10430 let result = marched_sections(a, b, 32, Some(va), Some(vb), None);
10431 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10432 let curves = result.unwrap();
10433 assert_eq!(curves.len(), 2, "{label}: loops");
10434 let off_rod = |p: Point3| {
10435 let (w, ax) = (p - rod.origin(), rod.axis());
10436 ((w - ax * ax.dot(w)).length() - r).abs()
10437 };
10438 for c in &curves {
10439 let worst = farthest_along(&c.curve, 4000, |p| {
10440 off_double_cone(&cone, p).max(off_rod(p))
10441 });
10442 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10443 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10444 assert!((first - last).length() < 1e-9, "{label}: open");
10445 }
10446 for &t in &truth {
10447 let near = curves
10448 .iter()
10449 .map(|c| {
10450 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10451 .unwrap()
10452 .distance
10453 })
10454 .fold(f64::INFINITY, f64::min);
10455 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10456 }
10457 }
10458 }
10459 }
10460 }
10461
10462 #[test]
10473 fn sections_on_both_nappes_of_a_flat_cone_are_each_marched() {
10474 let (half, r) = (0.001_f64, 0.05_f64);
10475 let lin = Tolerance::new().linear;
10476 let t2 = half.tan() * half.tan();
10477 for (k, pose) in three_poses().iter().enumerate() {
10478 let o = Point3::new(0.0, 0.0, 0.0);
10479 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10480 let cone =
10481 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10482 .unwrap();
10483 let rod =
10484 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10485 .unwrap();
10486 let mut truth = Vec::new();
10487 for j in 0..=90 {
10488 let x = 0.9 * (f64::from(j) / 45.0 - 1.0);
10489 let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10490 let y = z.madd(-z, r * r).sqrt();
10491 for (sy, sz) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
10492 truth.push(pose.mul_point(Point3::new(x, sy * y, sz * z)));
10493 }
10494 }
10495 let off_rod = |p: Point3| {
10496 let (w, ax) = (p - rod.origin(), rod.axis());
10497 ((w - ax * ax.dot(w)).length() - r).abs()
10498 };
10499 for cone_first in [true, false] {
10500 let label = format!("pose {k} cone first {cone_first}");
10501 let (a, b) = if cone_first {
10502 (
10503 AnalyticSurface::Cone(&cone),
10504 AnalyticSurface::Cylinder(&rod),
10505 )
10506 } else {
10507 (
10508 AnalyticSurface::Cylinder(&rod),
10509 AnalyticSurface::Cone(&cone),
10510 )
10511 };
10512 let result = marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), None);
10513 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10514 let curves = result.unwrap();
10515 assert_eq!(curves.len(), 4, "{label}: curves");
10516 for c in &curves {
10517 let worst = farthest_along(&c.curve, 4000, |p| {
10518 off_double_cone(&cone, p).max(off_rod(p))
10519 });
10520 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10521 }
10522 for &t in &truth {
10523 let near = curves
10524 .iter()
10525 .map(|c| {
10526 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10527 .unwrap()
10528 .distance
10529 })
10530 .fold(f64::INFINITY, f64::min);
10531 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10532 }
10533 }
10534 }
10535 }
10536
10537 #[test]
10546 fn a_shallow_crossing_too_tight_to_march_is_refused_not_dropped() {
10547 let (half, r) = (2e-6_f64, 0.1_f64);
10548 let t2 = half.tan() * half.tan();
10549 for (k, pose) in three_poses().iter().enumerate() {
10550 let o = Point3::new(0.0, 0.0, 0.0);
10551 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10552 let cone =
10553 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10554 .unwrap();
10555 let rod =
10556 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10557 .unwrap();
10558 let mut truth = Vec::new();
10559 for j in 0..=100 {
10560 let x = 40_000.0 + 99.9 * f64::from(j);
10561 let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10562 if z < r {
10563 let y = z.madd(-z, r * r).sqrt();
10564 for sy in [1.0, -1.0] {
10565 truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10566 }
10567 }
10568 }
10569 for cone_first in [true, false] {
10570 let label = format!("pose {k} cone first {cone_first}");
10571 let (a, b) = if cone_first {
10572 (
10573 AnalyticSurface::Cone(&cone),
10574 AnalyticSurface::Cylinder(&rod),
10575 )
10576 } else {
10577 (
10578 AnalyticSurface::Cylinder(&rod),
10579 AnalyticSurface::Cone(&cone),
10580 )
10581 };
10582 let range = Some((40_000.0, 60_000.0));
10583 let Ok(curves) = marched_sections(a, b, 32, range, range, None) else {
10584 continue;
10585 };
10586 for &t in &truth {
10587 let near = curves
10588 .iter()
10589 .map(|c| {
10590 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10591 .unwrap()
10592 .distance
10593 })
10594 .fold(f64::INFINITY, f64::min);
10595 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10596 }
10597 }
10598 }
10599 }
10600
10601 #[test]
10608 fn a_section_that_crosses_itself_is_traced_through_the_node() {
10609 let lin = Tolerance::new().linear;
10610 for (k, pose) in three_poses().iter().enumerate() {
10611 let o = Point3::new(0.0, 0.0, 0.0);
10612 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10613 let ball = SphericalSurface::new(pose.mul_point(o), 2.0).unwrap();
10614 let rod = CylindricalSurface::new(
10615 pose.mul_point(Point3::new(1.0, 0.0, 0.0)),
10616 along(Vec3::new(0.0, 0.0, 1.0)),
10617 1.0,
10618 )
10619 .unwrap();
10620 let node = pose.mul_point(Point3::new(2.0, 0.0, 0.0));
10621 let mut truth = Vec::new();
10622 for j in 1..360 {
10623 let t = TAU * f64::from(j) / 360.0;
10624 let z = 2.0 * (0.5 * t).sin().abs();
10625 for sz in [1.0, -1.0] {
10626 truth.push(pose.mul_point(Point3::new(1.0 + t.cos(), t.sin(), sz * z)));
10627 }
10628 }
10629 let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - 2.0).abs();
10630 let off_rod = |p: Point3| {
10631 let (w, ax) = (p - rod.origin(), rod.axis());
10632 ((w - ax * ax.dot(w)).length() - 1.0).abs()
10633 };
10634 for ball_first in [true, false] {
10635 let label = format!("pose {k} ball first {ball_first}");
10636 let (a, b, va, vb) = if ball_first {
10637 (
10638 AnalyticSurface::Sphere(&ball),
10639 AnalyticSurface::Cylinder(&rod),
10640 None,
10641 Some((-3.0, 3.0)),
10642 )
10643 } else {
10644 (
10645 AnalyticSurface::Cylinder(&rod),
10646 AnalyticSurface::Sphere(&ball),
10647 Some((-3.0, 3.0)),
10648 None,
10649 )
10650 };
10651 let result = marched_sections(a, b, 32, va, vb, None);
10652 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10653 let curves = result.unwrap();
10654 assert!(!curves.is_empty(), "{label}: no section");
10655 for c in &curves {
10656 let worst = farthest_along(&c.curve, 4000, |p| off_ball(p).max(off_rod(p)));
10657 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10658 let (t0, t1) = c.curve.domain();
10659 let (first, last) = (c.curve.evaluate(t0), c.curve.evaluate(t1));
10660 if (first - last).length() > lin {
10661 for end in [first, last] {
10662 let miss = (end - node).length();
10663 assert!(miss <= lin, "{label}: an end lies {miss:.1e} from the node");
10664 }
10665 }
10666 }
10667 for &t in &truth {
10668 let near = curves
10669 .iter()
10670 .map(|c| {
10671 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10672 .unwrap()
10673 .distance
10674 })
10675 .fold(f64::INFINITY, f64::min);
10676 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10677 }
10678 }
10679 }
10680 }
10681
10682 #[test]
10692 fn a_marched_branch_that_runs_into_a_touch_ends_on_it() {
10693 let lin = Tolerance::new().linear;
10694 for (k, pose) in three_poses().iter().enumerate() {
10695 let o = Point3::new(0.0, 0.0, 0.0);
10696 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10697 let leg =
10698 CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 3.0)
10699 .unwrap();
10700 let bend = ToroidalSurface::with_axis(
10701 pose.mul_point(Point3::new(20.0, 0.0, 30.0)),
10702 20.0,
10703 3.0,
10704 along(Vec3::new(0.0, 1.0, 0.0)),
10705 )
10706 .unwrap();
10707 let touches = [
10708 pose.mul_point(Point3::new(0.0, 3.0, 30.0)),
10709 pose.mul_point(Point3::new(0.0, -3.0, 30.0)),
10710 ];
10711 let mut truth = Vec::new();
10712 for j in 1..=120 {
10713 let x = 3.0 * f64::from(j) / 120.0;
10714 let z = 30.0 - (80.0 * x).sqrt();
10715 let y = x.madd(-x, 9.0).max(0.0).sqrt();
10716 for sy in [1.0, -1.0] {
10717 truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10718 }
10719 }
10720 let back = pose.inverse().unwrap();
10721 let off_leg = |p: Point3| {
10722 let (w, ax) = (p - leg.origin(), leg.axis());
10723 ((w - ax * ax.dot(w)).length() - 3.0).abs()
10724 };
10725 let off_bend = |p: Point3| {
10726 let q = back.mul_point(p);
10727 (((q.x() - 20.0).hypot(q.z() - 30.0) - 20.0).hypot(q.y()) - 3.0).abs()
10728 };
10729 for leg_first in [true, false] {
10730 let label = format!("pose {k} leg first {leg_first}");
10731 let (a, b, va, vb) = if leg_first {
10732 (
10733 AnalyticSurface::Cylinder(&leg),
10734 AnalyticSurface::Torus(&bend),
10735 Some((0.0, 30.0)),
10736 None,
10737 )
10738 } else {
10739 (
10740 AnalyticSurface::Torus(&bend),
10741 AnalyticSurface::Cylinder(&leg),
10742 None,
10743 Some((0.0, 30.0)),
10744 )
10745 };
10746 let result = marched_sections(a, b, 32, va, vb, None);
10747 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10748 let curves = result.unwrap();
10749 assert_eq!(curves.len(), 1, "{label}: curves");
10750 let c = &curves[0];
10751 let worst = farthest_along(&c.curve, 4000, |p| off_leg(p).max(off_bend(p)));
10752 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10753 let (t0, t1) = c.curve.domain();
10754 for end in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
10755 let miss = touches
10756 .iter()
10757 .map(|&t| (end - t).length())
10758 .fold(f64::INFINITY, f64::min);
10759 assert!(
10760 miss <= 1e-5,
10761 "{label}: an end lies {miss:.1e} from the touch"
10762 );
10763 }
10764 for &t in &truth {
10765 let near = crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10766 .unwrap()
10767 .distance;
10768 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10769 }
10770 }
10771 }
10772 }
10773
10774 #[test]
10783 fn cells_centred_on_a_balls_centre_are_kept() {
10784 use std::f64::consts::FRAC_PI_4;
10785 let lin = Tolerance::new().linear;
10786 let (radius, h) = (0.1_f64, 0.1 * FRAC_PI_4.sin());
10787 let rho = 0.1 * FRAC_PI_4.cos();
10788 for (k, pose) in three_poses().iter().enumerate() {
10789 let o = Point3::new(0.0, 0.0, 0.0);
10790 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10791 let cone = ConicalSurface::new(
10792 pose.mul_point(o),
10793 along(Vec3::new(0.0, 0.0, 1.0)),
10794 FRAC_PI_4,
10795 )
10796 .unwrap();
10797 let ball = SphericalSurface::new(pose.mul_point(o), radius).unwrap();
10798 let mut truth = Vec::new();
10799 for j in 0..72 {
10800 let t = TAU * f64::from(j) / 72.0;
10801 for z in [h, -h] {
10802 truth.push(pose.mul_point(Point3::new(rho * t.cos(), rho * t.sin(), z)));
10803 }
10804 }
10805 let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - radius).abs();
10806 for cone_first in [true, false] {
10807 let label = format!("pose {k} cone first {cone_first}");
10808 let (a, b, va, vb) = if cone_first {
10809 (
10810 AnalyticSurface::Cone(&cone),
10811 AnalyticSurface::Sphere(&ball),
10812 Some((-0.5, 31.5)),
10813 None,
10814 )
10815 } else {
10816 (
10817 AnalyticSurface::Sphere(&ball),
10818 AnalyticSurface::Cone(&cone),
10819 None,
10820 Some((-0.5, 31.5)),
10821 )
10822 };
10823 let result = marched_sections(a, b, 32, va, vb, None);
10824 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10825 let curves = result.unwrap();
10826 assert_eq!(curves.len(), 2, "{label}: circles");
10827 for c in &curves {
10828 let worst = farthest_along(&c.curve, 4000, |p| {
10829 off_double_cone(&cone, p).max(off_ball(p))
10830 });
10831 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10832 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10833 assert!((first - last).length() < 1e-9, "{label}: open");
10834 }
10835 for &t in &truth {
10836 let near = curves
10837 .iter()
10838 .map(|c| {
10839 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10840 .unwrap()
10841 .distance
10842 })
10843 .fold(f64::INFINITY, f64::min);
10844 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10845 }
10846 }
10847 }
10848 }
10849
10850 #[test]
10859 fn a_crossing_on_a_nearly_flat_cone_is_traced_or_refused() {
10860 let lin = Tolerance::new().linear;
10861 for (k, pose) in three_poses().iter().enumerate() {
10862 let o = Point3::new(0.0, 0.0, 0.0);
10863 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10864 let cone =
10865 ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 1e-14)
10866 .unwrap();
10867 let rod = CylindricalSurface::new(
10868 pose.mul_point(Point3::new(3.0, 0.0, 0.0)),
10869 along(Vec3::new(0.0, 0.0, 1.0)),
10870 1.0,
10871 )
10872 .unwrap();
10873 let truth: Vec<Point3> = (0..72)
10874 .map(|j| {
10875 let t = TAU * f64::from(j) / 72.0;
10876 let (x, y) = (3.0 + t.cos(), t.sin());
10877 pose.mul_point(Point3::new(x, y, 1e-14_f64.tan() * x.hypot(y)))
10878 })
10879 .collect();
10880 let off_rod = |p: Point3| {
10881 let (w, ax) = (p - rod.origin(), rod.axis());
10882 ((w - ax * ax.dot(w)).length() - 1.0).abs()
10883 };
10884 for cone_first in [true, false] {
10885 let label = format!("pose {k} cone first {cone_first}");
10886 let (a, b, va, vb) = if cone_first {
10887 (
10888 AnalyticSurface::Cone(&cone),
10889 AnalyticSurface::Cylinder(&rod),
10890 Some((1.0, 5.0)),
10891 Some((-1.0, 1.0)),
10892 )
10893 } else {
10894 (
10895 AnalyticSurface::Cylinder(&rod),
10896 AnalyticSurface::Cone(&cone),
10897 Some((-1.0, 1.0)),
10898 Some((1.0, 5.0)),
10899 )
10900 };
10901 let Ok(curves) = marched_sections(a, b, 32, va, vb, None) else {
10902 continue;
10903 };
10904 assert!(!curves.is_empty(), "{label}: no section and no refusal");
10905 for c in &curves {
10906 let worst = farthest_along(&c.curve, 4000, |p| {
10907 off_double_cone(&cone, p).max(off_rod(p))
10908 });
10909 assert!(worst <= lin, "{label}: off by {worst:.2e}");
10910 }
10911 for &t in &truth {
10912 let near = curves
10913 .iter()
10914 .map(|c| {
10915 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10916 .unwrap()
10917 .distance
10918 })
10919 .fold(f64::INFINITY, f64::min);
10920 assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10921 }
10922 }
10923 }
10924 }
10925
10926 #[test]
10941 fn two_loops_in_one_cell_of_each_patch_are_both_traced() {
10942 let lin = Tolerance::new().linear;
10943 let turn = crate::mat::Mat4::rotation_z(0.75 * TAU / 32.0);
10944 let (delta, depth) = (0.007_f64, 8e-6_f64);
10945 let (y0, z0) = (4.0 - delta, 2.1 - depth);
10946 for (k, pose) in three_poses().iter().enumerate() {
10947 let pose = *pose * turn;
10948 let o = Point3::new(0.0, 0.0, 0.0);
10949 let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10950 let centre = pose.mul_point(o);
10951 let up = along(Vec3::new(0.0, 0.0, 1.0));
10952 let ring = ToroidalSurface::with_axis(centre, 4.0, 1.5, up).unwrap();
10953 let start = pose.mul_point(Point3::new(0.0, y0, z0));
10954 let dir = along(Vec3::new(1.0, 0.0, 0.0));
10955 let rod = CylindricalSurface::new(start, dir, 0.6).unwrap();
10956 let ring_normal = |p: Point3| {
10957 let w = p - centre;
10958 let across = w - up * up.dot(w);
10959 let tube = centre + across * (4.0 / across.length());
10960 (p - tube) * (1.0 / (p - tube).length())
10961 };
10962 let rod_normal = |p: Point3| {
10963 let w = p - start;
10964 let across = w - dir * dir.dot(w);
10965 across * (1.0 / across.length())
10966 };
10967 let off_ring = |p: Point3| {
10968 let w = p - centre;
10969 let h = up.dot(w);
10970 ((w - up * h).length() - 4.0).hypot(h) - 1.5
10971 };
10972 let off_rod = |p: Point3| {
10973 let w = p - start;
10974 ((w - dir * dir.dot(w)).length() - 0.6).abs()
10975 };
10976 let mut truth = Vec::new();
10979 for j in -300..=300 {
10980 let phi = f64::from(j) * 1e-4;
10981 let from =
10982 pose.mul_point(Point3::new(0.0, y0 + 0.6 * phi.sin(), z0 - 0.6 * phi.cos()));
10983 for t in intersect_line_torus(&ring, from, dir) {
10984 if t.abs() < 2.0 {
10985 truth.push(from + dir * t);
10986 }
10987 }
10988 }
10989 assert!(truth.len() > 100, "pose {k}: {} points", truth.len());
10990 for rod_first in [true, false] {
10991 let label = format!("pose {k} rod first {rod_first}");
10992 let along_rod = Some((-9.6875, 10.3125));
10993 let result = if rod_first {
10994 marched_sections(
10995 AnalyticSurface::Cylinder(&rod),
10996 AnalyticSurface::Torus(&ring),
10997 32,
10998 along_rod,
10999 None,
11000 None,
11001 )
11002 } else {
11003 marched_sections(
11004 AnalyticSurface::Torus(&ring),
11005 AnalyticSurface::Cylinder(&rod),
11006 32,
11007 None,
11008 along_rod,
11009 None,
11010 )
11011 };
11012 assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
11013 let curves = result.unwrap();
11014 assert_eq!(curves.len(), 2, "{label}: loops");
11015 for c in &curves {
11016 let worst =
11017 farthest_along(&c.curve, 4000, |p| off_ring(p).abs().max(off_rod(p)));
11018 assert!(worst <= lin, "{label}: off by {worst:.2e}");
11019 }
11020 for &t in &truth {
11021 let sin = ring_normal(t).cross(rod_normal(t)).length();
11022 let bound = (4.0 * lin / sin).max(1e-5);
11023 let near = curves
11024 .iter()
11025 .map(|c| {
11026 crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
11027 .unwrap()
11028 .distance
11029 })
11030 .fold(f64::INFINITY, f64::min);
11031 assert!(
11032 near <= bound,
11033 "{label}: {t:?} lies {near:.1e} off, past {bound:.1e}"
11034 );
11035 }
11036 }
11037 }
11038 }
11039}