1use super::*;
2pub use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, intersect_cylinder_radius_invariant, rotate_curve_about_axis};
4
5struct PlaneData {
7 origin: Vec3,
8 normal: Vec3,
9}
10
11fn plane_data(analytic: &AnalyticSurface) -> Option<PlaneData> {
12 match analytic {
13 AnalyticSurface::Plane {
14 origin,
15 u_dir,
16 v_dir,
17 ..
18 } => Some(PlaneData {
19 origin: *origin,
20 normal: u_dir.cross(*v_dir).normalized().ok()?,
21 }),
22 _ => None,
23 }
24}
25
26fn map_rational_curve(
31 curve: &NurbsCurve,
32 map: impl Fn(crate::Vec4) -> crate::Vec4,
33) -> Option<NurbsCurve> {
34 let mut controls = Vec::with_capacity(curve.control_points.len());
35 let mut sign = 0.0f64;
36 for point in &curve.control_points {
37 let image = map(*point);
38 if image.w == 0.0 || !image.w.is_finite() {
39 return None;
40 }
41 if sign == 0.0 {
42 sign = image.w.signum();
43 } else if image.w.signum() != sign {
44 return None;
45 }
46 controls.push(image);
47 }
48 if sign < 0.0 {
49 for point in &mut controls {
50 point.x = -point.x;
51 point.y = -point.y;
52 point.z = -point.z;
53 point.w = -point.w;
54 }
55 }
56 NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
57}
58
59fn cone_plane_open_section_enabled() -> bool {
64 crate::switch!(live "BREP_CONE_PLANE_OPEN_SECTION", false)
65}
66
67#[allow(clippy::too_many_arguments)]
78fn cone_plane_open_section(
79 frame: &RevolutionFrame,
80 height: f64,
81 apex: Vec3,
82 reference_rho: f64,
83 reference_z: f64,
84 k: f64,
85 normal: Vec3,
86 tolerance: f64,
87 project: &dyn Fn(crate::Vec4) -> crate::Vec4,
88) -> Option<Vec<NurbsCurve>> {
89 let center = frame.origin.add(frame.axis.scale(reference_z));
90 let a = center.sub(apex).dot(normal);
91 let b = reference_rho * frame.x_axis.dot(normal);
92 let c = reference_rho * frame.y_axis.dot(normal);
93 let r = (b * b + c * c).sqrt();
94 let z_apex = apex.sub(frame.origin).dot(frame.axis);
95 let big_k = k * (reference_z - z_apex);
97 let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
98 let margin = tolerance.max(1e-12);
99 let axial = |theta: f64| -> Option<f64> {
100 let w = a + b * theta.cos() + c * theta.sin();
101 (w.abs() > 1e-300).then(|| z_apex + big_k / w)
102 };
103 let mut roots: Vec<f64> = Vec::new();
104 let mut solve = |target: f64| {
105 if r <= 0.0 {
107 return;
108 }
109 let ratio = (target - a) / r;
110 if ratio.abs() > 1.0 {
111 return;
112 }
113 let phi = c.atan2(b);
114 let spread = ratio.acos();
115 for theta in [phi + spread, phi - spread] {
116 roots.push(theta.rem_euclid(std::f64::consts::TAU));
117 }
118 };
119 solve(0.0);
120 for end in [band_low, band_high] {
121 let offset = end - z_apex;
122 if offset.abs() > 1e-300 {
123 solve(big_k / offset);
124 }
125 }
126 roots.sort_by(f64::total_cmp);
127 roots.dedup();
128 if roots.is_empty() {
129 roots.push(0.0);
130 }
131 let mut arcs = Vec::new();
132 for index in 0..roots.len() {
133 let start = roots[index];
134 let mut end = if index + 1 < roots.len() { roots[index + 1] } else { roots[0] + std::f64::consts::TAU };
135 if roots.len() == 1 {
136 end = start + std::f64::consts::TAU;
137 }
138 if !(end > start) {
142 continue;
143 }
144 let middle = 0.5 * (start + end);
145 let Some(z) = axial(middle) else { continue };
146 if z < band_low - margin || z > band_high + margin {
147 continue;
148 }
149 let arc = make_arc(center, frame.x_axis, frame.y_axis, reference_rho, start, end).ok()?;
150 arcs.push(map_rational_curve(&arc, project)?);
152 }
153 Some(arcs)
154}
155
156fn frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
159 make_arc(
160 frame.origin.add(frame.axis.scale(z)),
161 frame.x_axis,
162 frame.y_axis,
163 rho,
164 0.0,
165 std::f64::consts::TAU,
166 )
167 .ok()
168}
169
170pub fn intersect_analytic_pair(
174 first: &NurbsSurface,
175 second: &NurbsSurface,
176 tolerance: f64,
177) -> Option<Vec<NurbsCurve>> {
178 intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RuledGate {
185 Count,
187 Geometry,
191}
192
193pub fn ruled_gate() -> RuledGate {
199 if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
200 RuledGate::Count
201 } else {
202 RuledGate::Geometry
203 }
204}
205
206pub fn intersect_analytic_pair_with(
209 first: &NurbsSurface,
210 second: &NurbsSurface,
211 tolerance: f64,
212 gate: RuledGate,
213) -> Option<Vec<NurbsCurve>> {
214 if let Some(curves) = super::sphere_cylinder_tangent::intersect_sphere_cylinder_tangent(first, second, tolerance) {
217 return Some(curves);
218 }
219 if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
220 return Some(curves);
221 }
222 if crate::switch!("BREP_EXTRUSION_SECTIONS", true) {
223 for (plane, swept) in [(first,second),(second,first)] {
224 if matches!(swept.analytic(),Some(AnalyticSurface::Plane { .. })) { continue; }
225 if let (Some(plane),Some(extrusion)) = (plane.analytic().and_then(plane_data),swept.linear_extrusion()) {
226 if let Some(curves) = super::plane_extrusion_section(extrusion,plane.origin,plane.normal,tolerance) { return Some(curves); }
227 }
228 }
229 if !matches!(first.analytic(),Some(AnalyticSurface::Plane { .. })) && !matches!(second.analytic(),Some(AnalyticSurface::Plane { .. })) {
230 if let (Some(a),Some(b)) = (first.linear_extrusion(),second.linear_extrusion()) {
231 if let Some(curves) = super::parallel_extrusion_sections(a,b,tolerance) { return Some(curves); }
232 }
233 }
234 }
235 if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
236 return Some(curves);
237 }
238 if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
239 return Some(curves);
240 }
241 if coaxial_iso_section_enabled() {
242 if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
243 return Some(curves);
244 }
245 if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
246 return Some(curves);
247 }
248 }
249 if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
253 if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
254 return Some(curves);
255 }
256 if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
257 return Some(curves);
258 }
259 }
260 if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
261 return Some(curves);
262 }
263 intersect_axial_plane_revolution(second, first, tolerance)
264}
265
266fn coaxial_iso_section_enabled() -> bool {
271 crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
272}
273
274fn plane_revolution_section_enabled() -> bool {
292 crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
293}
294
295fn intersect_perpendicular_plane_revolution(
296 plane_surface: &NurbsSurface,
297 revolution: &NurbsSurface,
298 tolerance: f64,
299) -> Option<Vec<NurbsCurve>> {
300 let plane = plane_data(plane_surface.analytic()?)?;
301 if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
302 return None;
303 }
304 let structure = super::revolution::revolution_structure(revolution)?;
305 let frame = &structure.frame;
306 if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
307 return None;
308 }
309 let generatrix = &structure.generatrix;
310 let [start, end] = generatrix.domain().ok()?;
311 let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
312 let scale = surface_scale(revolution).max(1.0);
313 let band = tolerance.max(1e-9 * scale);
314 let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
315 let stations = 64 * spans;
316 let mut previous_t = start;
317 let mut previous = height(start)?;
318 if previous.abs() <= band || height(end)?.abs() <= band {
320 return None;
321 }
322 let mut roots = Vec::new();
323 for index in 1..=stations {
324 let t = start + (end - start) * index as f64 / stations as f64;
325 let value = height(t)?;
326 if value.abs() <= band && index < stations {
327 return None;
330 }
331 if (previous < 0.0) != (value < 0.0) {
332 let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
333 for _ in 0..200 {
334 let middle = 0.5 * (lo + hi);
335 if middle <= lo || middle >= hi {
336 break;
337 }
338 let middle_value = height(middle)?;
339 if (middle_value < 0.0) == (lo_value < 0.0) {
340 lo = middle;
341 lo_value = middle_value;
342 } else {
343 hi = middle;
344 }
345 }
346 roots.push(0.5 * (lo + hi));
347 }
348 previous_t = t;
349 previous = value;
350 }
351 if roots.is_empty() {
352 return None;
353 }
354 let mut coefficient_signs = Vec::new();
359 for control in &generatrix.control_points {
360 if control.w <= 0.0 {
361 return None;
362 }
363 let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
364 if value.abs() <= band {
365 return None;
366 }
367 coefficient_signs.push(value > 0.0);
368 }
369 let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
370 if sign_changes != roots.len() {
371 return None;
372 }
373 let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
374 let mut curves = Vec::new();
375 for root in roots {
376 let derivatives = generatrix.derivatives(root, 1).ok()?;
377 let tangent = derivatives.get(1)?.normalized().ok()?;
378 if tangent.dot(plane.normal).abs() <= 1e-9 {
379 return None;
380 }
381 let point = generatrix.evaluate(root).ok()?;
382 let (_, radius, axial) = frame.cylindrical(point);
383 if radius <= radius_floor {
384 return None;
385 }
386 let center = frame.origin.add(frame.axis.scale(axial));
387 let phase = if generatrix_is_meridional_half_ray(generatrix, frame) {
390 0.0
391 } else {
392 let radial = point.sub(center);
393 radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis))
394 };
395 curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, phase, phase + structure.sweep).ok()?);
396 }
397 Some(curves)
398}
399
400fn intersect_axial_plane_revolution(
406 plane_surface: &NurbsSurface,
407 revolved: &NurbsSurface,
408 _tolerance: f64,
409) -> Option<Vec<NurbsCurve>> {
410 let plane = match plane_surface.analytic()? {
411 AnalyticSurface::Plane {
412 origin,
413 u_dir,
414 v_dir,
415 ..
416 } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
417 _ => return None,
418 };
419 let structure = revolution_structure(revolved)?;
420 if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
421 return None;
422 }
423 let scale = surface_scale(plane_surface)
424 .max(surface_scale(revolved))
425 .max(1.0);
426 let (plane_origin, plane_normal) = plane;
427 if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
428 return None;
429 }
430 if structure
431 .frame
432 .origin
433 .sub(plane_origin)
434 .dot(plane_normal)
435 .abs()
436 > 1e-9 * scale
437 {
438 return None;
439 }
440 let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
441 let tau = std::f64::consts::TAU;
442 let mut curves = Vec::new();
443 for direction in [radial, radial.scale(-1.0)] {
444 let mut angle = direction
445 .dot(structure.frame.y_axis)
446 .atan2(direction.dot(structure.frame.x_axis));
447 if angle < -1e-9 {
448 angle += tau;
449 }
450 if angle <= structure.sweep + 1e-9 {
451 curves.push(rotate_curve_about_axis(
452 &structure.generatrix,
453 structure.frame.origin,
454 structure.frame.axis,
455 angle.clamp(0.0, structure.sweep),
456 )?);
457 }
458 }
459 Some(curves)
460}
461
462fn intersect_plane_affine_sphere(
467 first: &NurbsSurface,
468 second: &NurbsSurface,
469 tolerance: f64,
470) -> Option<Vec<NurbsCurve>> {
471 for (plane_surface, other) in [(first, second), (second, first)] {
472 let Some(ellipsoid) = other.affine_sphere() else { continue };
473 let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
474 return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
475 }
476 None
477}
478
479fn intersect_recognized_pair(
480 first: &NurbsSurface,
481 second: &NurbsSurface,
482 tolerance: f64,
483 gate: RuledGate,
484) -> Option<Vec<NurbsCurve>> {
485 let a = first.analytic()?;
486 let b = second.analytic()?;
487 if !matches!(b, AnalyticSurface::Plane { .. }) {
488 if let Some(plane) = plane_data(a) {
489 return intersect_plane_quadric(&plane, b, tolerance, gate);
490 }
491 }
492 if !matches!(a, AnalyticSurface::Plane { .. }) {
493 if let Some(plane) = plane_data(b) {
494 return intersect_plane_quadric(&plane, a, tolerance, gate);
495 }
496 }
497 if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
500 (a.sphere_geometry(), b.sphere_geometry())
501 {
502 return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
503 }
504 if let Some(curves) = intersect_sphere_coaxial_ruled(a, b, tolerance, gate)
505 .or_else(|| intersect_sphere_coaxial_ruled(b, a, tolerance, gate))
506 {
507 return Some(curves);
508 }
509 if let Some(curves) = intersect_equal_cylinders_meeting_axes(first, second, a, b, tolerance, gate) {
510 return Some(curves);
511 }
512 if let Some(curves) = intersect_cones_sharing_a_ruling(a, b, tolerance, gate)
516 .or_else(|| intersect_cones_sharing_a_ruling(b, a, tolerance, gate))
517 {
518 return Some(curves);
519 }
520 None
527}
528
529fn sphere_cone_coaxial_enabled() -> bool {
533 crate::switch!(live "BREP_SPHERE_CONE_COAXIAL", false)
534}
535
536fn intersect_sphere_coaxial_ruled(
544 sphere: &AnalyticSurface,
545 ruled: &AnalyticSurface,
546 tolerance: f64,
547 gate: RuledGate,
548) -> Option<Vec<NurbsCurve>> {
549 if !sphere_cone_coaxial_enabled() {
550 return None;
551 }
552 let (center, radius) = sphere.sphere_geometry()?;
553 let (frame, rho0, rho1, height) = ruled_revolution_data(ruled, tolerance, gate)?;
554 let offset = center.sub(frame.origin);
555 let center_z = offset.dot(frame.axis);
556 let off_axis = offset.sub(frame.axis.scale(center_z)).length();
557 if off_axis > tolerance.max(1e-12) * (1.0 + radius) {
562 return None;
563 }
564 let margin = tolerance.max(1e-12);
565 let slope = (rho1 - rho0) / height;
566 let rho_center = rho0 + slope * center_z;
570 let a = 1.0 + slope * slope;
571 let b = 2.0 * slope * rho_center;
572 let c = rho_center * rho_center - radius * radius;
573 let discriminant = b * b - 4.0 * a * c;
574 let mut heights = Vec::new();
575 if discriminant > 0.0 {
576 let root = discriminant.sqrt();
577 let q = -0.5 * (b + if b >= 0.0 { root } else { -root });
578 if q != 0.0 {
579 heights.push(center_z + q / a);
580 heights.push(center_z + c / q);
581 } else {
582 heights.push(center_z);
583 }
584 }
585 let separation_bar = 2e-6 * radius * a;
593 if discriminant.abs() <= 1e-9 * (b * b + (4.0 * a * c).abs()).max(radius * radius * 1e-24)
594 || (discriminant > 0.0 && discriminant <= separation_bar * separation_bar)
595 {
596 return None;
597 }
598 let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
599 let mut circles = Vec::new();
600 for z in heights {
601 let rho = rho0 + slope * z;
602 if rho < -margin || z < band_low - margin || z > band_high + margin || rho <= margin {
603 continue;
604 }
605 circles.push(frame_circle(&frame, rho, z)?);
606 }
607 Some(circles)
608}
609
610fn cone_shared_ruling_enabled() -> bool {
613 crate::switch!(live "BREP_CONE_SHARED_RULING", false)
614}
615
616struct ConeData {
619 apex: Vec3,
620 axis: Vec3,
621 cos2: f64,
622 frame: RevolutionFrame,
623 height: f64,
624 sweep: f64,
626 size: f64,
628}
629
630fn cone_data(quadric: &AnalyticSurface, tolerance: f64, gate: RuledGate) -> Option<ConeData> {
631 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
632 let slope = (rho1 - rho0) / height;
633 if !(slope.is_finite() && slope.abs() > 1e-9) {
634 return None;
635 }
636 let apex = frame.origin.add(frame.axis.scale(-rho0 / slope));
637 let sweep = match quadric {
638 AnalyticSurface::Revolution { sweep, .. } => *sweep,
639 _ => std::f64::consts::TAU,
640 };
641 let size = height.abs().max(rho0.abs()).max(rho1.abs());
642 Some(ConeData { apex, axis: frame.axis, cos2: 1.0 / (1.0 + slope * slope), frame, height, sweep, size })
643}
644
645impl ConeData {
646 fn value(&self, point: Vec3) -> f64 {
648 let d = point.sub(self.apex);
649 let along = d.dot(self.axis);
650 along * along - self.cos2 * d.dot(d)
651 }
652
653 fn distance(&self, point: Vec3) -> f64 {
655 let d = point.sub(self.apex);
656 let gradient = self.axis.scale(2.0 * d.dot(self.axis)).sub(d.scale(2.0 * self.cos2));
657 let norm = gradient.length();
658 if norm > 0.0 { self.value(point).abs() / norm } else { d.length() }
659 }
660
661 fn matrix(&self) -> [[f64; 4]; 4] {
663 let d = [self.axis.x, self.axis.y, self.axis.z];
664 let a = [self.apex.x, self.apex.y, self.apex.z];
665 let mut m = [[0.0; 4]; 4];
666 let mut da = [0.0; 3];
667 for i in 0..3 {
668 for j in 0..3 {
669 m[i][j] = d[i] * d[j] - if i == j { self.cos2 } else { 0.0 };
670 }
671 }
672 for i in 0..3 {
673 da[i] = (0..3).map(|j| m[i][j] * a[j]).sum();
674 }
675 for i in 0..3 {
676 m[i][3] = -da[i];
677 m[3][i] = -da[i];
678 }
679 m[3][3] = (0..3).map(|i| a[i] * da[i]).sum();
680 m
681 }
682
683 fn within_sweep(&self, point: Vec3, slack: f64) -> bool {
686 if self.sweep >= std::f64::consts::TAU - 1e-12 {
687 return true;
688 }
689 match self.frame.cylindrical(point).0 {
690 None => true,
691 Some(theta) => theta <= self.sweep + slack || theta >= std::f64::consts::TAU - slack,
692 }
693 }
694
695 fn within_extent(&self, point: Vec3, slack: f64) -> bool {
698 let axial = point.sub(self.frame.origin).dot(self.frame.axis);
699 axial >= 0.0_f64.min(self.height) - slack && axial <= 0.0_f64.max(self.height) + slack
700 }
701
702 fn extent_along(&self, origin: Vec3, direction: Vec3) -> Option<[f64; 2]> {
705 let rate = direction.dot(self.frame.axis);
706 if rate.abs() <= 1e-12 {
707 return None;
708 }
709 let at = origin.sub(self.frame.origin).dot(self.frame.axis);
710 let (low, high) = (0.0_f64.min(self.height), 0.0_f64.max(self.height));
711 let (s0, s1) = ((low - at) / rate, (high - at) / rate);
712 Some([s0.min(s1), s0.max(s1)])
713 }
714}
715
716fn pieces_within_extent(curve: &NurbsCurve, cone: &ConeData, slack: f64) -> Option<Vec<NurbsCurve>> {
724 if curve.degree > 2 {
725 return None;
726 }
727 let (low, high) = (0.0_f64.min(cone.height) - slack, 0.0_f64.max(cone.height) + slack);
728 let axial_times_weight = |t: f64, bound: f64| -> Option<f64> {
729 let h = curve.evaluate_homogeneous(t).ok()?;
730 let along = Vec3::new(h.x, h.y, h.z).sub(cone.frame.origin.scale(h.w)).dot(cone.frame.axis);
731 Some(along - bound * h.w)
732 };
733 let mut breaks: Vec<f64> = curve.knots.iter().copied().collect();
734 breaks.sort_by(f64::total_cmp);
735 breaks.dedup();
736 let mut cuts = Vec::new();
737 for pair in breaks.windows(2) {
738 let (t0, t1) = (pair[0], pair[1]);
739 if !(t1 > t0) {
740 continue;
741 }
742 for bound in [low, high] {
743 let (f0, fm, f1) = (axial_times_weight(t0, bound)?, axial_times_weight(0.5 * (t0 + t1), bound)?, axial_times_weight(t1, bound)?);
745 let a = 2.0 * f1 - 4.0 * fm + 2.0 * f0;
746 let b = 4.0 * fm - f1 - 3.0 * f0;
747 let c = f0;
748 let mut roots = Vec::new();
749 if a.abs() <= 1e-14 * (b.abs() + c.abs()).max(1e-300) {
750 if b != 0.0 {
751 roots.push(-c / b);
752 }
753 } else {
754 let discriminant = b * b - 4.0 * a * c;
755 if discriminant >= 0.0 {
756 let root = discriminant.sqrt();
757 let q = -0.5 * (b + b.signum() * root);
758 if q != 0.0 {
759 roots.push(q / a);
760 roots.push(c / q);
761 }
762 }
763 }
764 for s in roots {
767 if s >= -1e-12 && s <= 1.0 + 1e-12 {
768 cuts.push(t0 + s.clamp(0.0, 1.0) * (t1 - t0));
769 }
770 }
771 }
772 }
773 cuts.sort_by(f64::total_cmp);
774 cuts.dedup();
775 let inside = |point: Vec3| cone.within_extent(point, slack);
776 let mut pieces = Vec::new();
777 let mut rest = curve.clone();
778 for cut in cuts {
779 let [r0, r1] = rest.domain().ok()?;
780 if cut <= r0 + 1e-12 * (r1 - r0).abs().max(1.0) || cut >= r1 - 1e-12 * (r1 - r0).abs().max(1.0) {
781 continue;
782 }
783 let (left, right) = rest.split(cut).ok()?;
784 pieces.push(left);
785 rest = right;
786 }
787 pieces.push(rest);
788 let mut kept = Vec::new();
789 for piece in pieces {
790 let [p0, p1] = piece.domain().ok()?;
791 if inside(piece.evaluate(0.5 * (p0 + p1)).ok()?) {
792 kept.push(piece);
793 }
794 }
795 Some(kept)
796}
797
798fn intersect_cones_sharing_a_ruling(
817 a: &AnalyticSurface,
818 b: &AnalyticSurface,
819 tolerance: f64,
820 gate: RuledGate,
821) -> Option<Vec<NurbsCurve>> {
822 if !cone_shared_ruling_enabled() {
823 return None;
824 }
825 let (first, second) = (cone_data(a, tolerance, gate)?, cone_data(b, tolerance, gate)?);
826 let between = second.apex.sub(first.apex);
827 let length = between.length();
828 let scale = 1.0 + first.size.max(second.size);
830 if !(length > 1e-9 * scale) {
831 return None;
832 }
833 let line = between.scale(1.0 / length);
834 for cone in [&first, &second] {
836 let along = line.dot(cone.axis);
837 if (along * along - cone.cos2).abs() > 1e-9 {
838 return None;
839 }
840 }
841 let normal_first = first.axis.cross(line).cross(line).normalized().ok()?;
843 let normal_second = second.axis.cross(line).cross(line).normalized().ok()?;
844 if normal_first.cross(normal_second).length() > 1e-9 {
845 return None;
846 }
847 let off = first.apex.add(normal_first.cross(line).scale(length.max(1.0)));
849 let (value_first, value_second) = (first.value(off), second.value(off));
850 if !(value_second.abs() > 1e-12 * (1.0 + value_first.abs())) {
851 return None;
852 }
853 let lambda = value_first / value_second;
854 let (m_first, m_second) = (first.matrix(), second.matrix());
855 let mut pencil = [[0.0; 4]; 4];
856 for i in 0..4 {
857 for j in 0..4 {
858 pencil[i][j] = m_first[i][j] - lambda * m_second[i][j];
859 }
860 }
861 let t = [normal_first.x, normal_first.y, normal_first.z, -normal_first.dot(first.apex)];
862 let homogeneous = |point: Vec3| [point.x, point.y, point.z, 1.0];
863 let apply = |m: &[[f64; 4]; 4], x: [f64; 4]| -> [f64; 4] {
864 let mut out = [0.0; 4];
865 for i in 0..4 {
866 out[i] = (0..4).map(|j| m[i][j] * x[j]).sum();
867 }
868 out
869 };
870 let dot4 = |p: [f64; 4], q: [f64; 4]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3];
871 let y = homogeneous(first.apex.add(normal_first.scale(length.max(1.0))));
873 let s = dot4(t, y);
874 if !(s.abs() > 1e-12) {
875 return None;
876 }
877 let py = apply(&pencil, y);
878 let pi_y = dot4(y, py) / s;
879 let mut pi = [0.0; 4];
880 for i in 0..4 {
881 pi[i] = (2.0 * py[i] - t[i] * pi_y) / s;
882 }
883 for probe in [second.apex.add(Vec3::new(0.37, -0.21, 0.53).scale(length)), first.apex.add(Vec3::new(-0.44, 0.61, 0.17).scale(length)), off.add(line.scale(0.3 * length))] {
885 let x = homogeneous(probe);
886 let member = dot4(x, apply(&pencil, x));
887 let pair = dot4(t, x) * dot4(pi, x);
888 if (member - pair).abs() > 1e-8 * (1.0 + member.abs().max(pair.abs())) {
889 return None;
890 }
891 }
892 let mut curves = Vec::new();
893 if let (Some([a0, a1]), Some([b0, b1])) = (first.extent_along(first.apex, line), second.extent_along(first.apex, line)) {
895 let (s0, s1) = (a0.max(b0), a1.min(b1));
896 let (start, end) = (first.apex.add(line.scale(s0)), first.apex.add(line.scale(s1)));
897 let middle = start.add(end).scale(0.5);
898 if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
899 eprintln!(
900 "cone ruling: s [{s0:.6}, {s1:.6}] from {start:?} to {end:?}; middle theta first {:?} (sweep {:.6}) second {:?} (sweep {:.6})",
901 first.frame.cylindrical(middle).0, first.sweep, second.frame.cylindrical(middle).0, second.sweep
902 );
903 }
904 if s1 - s0 > tolerance.max(1e-12) && first.within_sweep(middle, 1e-9) && second.within_sweep(middle, 1e-9) {
907 curves.push(crate::make_line(start, end).ok()?);
908 }
909 }
910 let pi_normal = Vec3::new(pi[0], pi[1], pi[2]);
912 let pi_length = pi_normal.length();
913 if pi_length > 1e-12 * (1.0 + pi[3].abs()) {
914 let unit = pi_normal.scale(1.0 / pi_length);
915 let origin = pi_normal.scale(-pi[3] / (pi_length * pi_length));
916 let same_as_t = unit.cross(normal_first).length() <= 1e-9 && (unit.dot(first.apex) + pi[3] / pi_length).abs() <= tolerance;
917 if !same_as_t {
918 let plane = PlaneData { origin, normal: unit };
919 let conics = intersect_plane_quadric(&plane, a, tolerance, gate)?;
920 for conic in conics {
921 let [c0, c1] = conic.domain().ok()?;
922 let (mut inside, mut outside) = (0, 0);
923 for k in 0..=32 {
924 let point = conic.evaluate(c0 + (c1 - c0) * k as f64 / 32.0).ok()?;
925 if second.distance(point) > 1e3 * tolerance.max(1e-12) * scale {
926 return None;
927 }
928 if first.within_sweep(point, 1e-9) && second.within_sweep(point, 1e-9) {
929 inside += 1;
930 } else {
931 outside += 1;
932 }
933 }
934 if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
935 let ends = (conic.evaluate(c0).ok(), conic.evaluate(c1).ok());
936 eprintln!("cone ruling conic: inside {inside} outside {outside}; ends {ends:?}; sweeps {:.6} {:.6}", first.sweep, second.sweep);
937 }
938 let slack = tolerance.max(1e-12) * scale;
948 curves.extend(pieces_within_extent(&conic, &second, slack)?);
949 }
950 }
951 }
952 Some(curves)
953}
954
955fn equal_cylinder_sections_enabled() -> bool {
958 crate::switch!(live "BREP_EQUAL_CYLINDER_SECTIONS", true)
959}
960
961fn intersect_equal_cylinders_meeting_axes(
973 surface_a: &NurbsSurface,
974 surface_b: &NurbsSurface,
975 a: &AnalyticSurface,
976 b: &AnalyticSurface,
977 tolerance: f64,
978 gate: RuledGate,
979) -> Option<Vec<NurbsCurve>> {
980 if !equal_cylinder_sections_enabled() {
981 return None;
982 }
983 let (frame_a, rho0_a, rho1_a, _) = ruled_revolution_data(a, tolerance, gate)?;
984 let (frame_b, rho0_b, rho1_b, _) = ruled_revolution_data(b, tolerance, gate)?;
985 let band = tolerance.max(4.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs()));
990 let same_radius = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs());
995 if (rho0_a - rho1_a).abs() > band || (rho0_b - rho1_b).abs() > band || (rho0_a - rho0_b).abs() > same_radius || rho0_a <= band {
996 return None;
997 }
998 let (radius, radius_b) = (rho0_a, rho0_b);
999 let (da, mut db) = (frame_a.axis.normalized().ok()?, frame_b.axis.normalized().ok()?);
1000 if da.dot(db) < 0.0 {
1001 db = db.scale(-1.0);
1002 }
1003 let cross = da.cross(db);
1004 let sine = cross.length();
1005 if sine <= 1e-6 {
1008 return None;
1009 }
1010 let offset = frame_b.origin.sub(frame_a.origin);
1014 let skew = offset.dot(cross.scale(1.0 / sine)).abs();
1015 let meet = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(frame_a.origin.length()).max(frame_b.origin.length());
1016 if std::env::var_os("BREP_DEBUG_EQUAL_CYLINDERS").is_some() {
1017 eprintln!("equal cylinders: skew {skew:.3e} (round-off bar {meet:.3e}), radii {rho0_a} / {rho0_b}");
1018 }
1019 if skew > meet {
1020 return None;
1021 }
1022 let s = offset.cross(db).dot(cross) / (sine * sine);
1024 let centre = frame_a.origin.add(da.scale(s));
1025 let off_axis = |point: Vec3, origin: Vec3, axis: Vec3, rho: f64| {
1026 let delta = point.sub(origin);
1027 (delta.sub(axis.scale(delta.dot(axis))).length() - rho).abs()
1028 };
1029 for (surface, origin, axis, rho) in [(surface_a, frame_a.origin, da, radius), (surface_b, frame_b.origin, db, radius_b)] {
1033 let ([u0, u1], [v0, v1]) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
1034 for i in 0..=6 {
1035 for j in 0..=6 {
1036 let point = surface.evaluate(u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0).ok()?;
1037 if off_axis(point, origin, axis, rho) > band {
1038 return None;
1039 }
1040 }
1041 }
1042 }
1043 let on_b = |point: Vec3| off_axis(point, frame_b.origin, db, radius_b);
1044 let across = cross.scale(radius / sine);
1046 let tangent_points = [centre.add(across), centre.sub(across)];
1047 let mut curves = Vec::new();
1048 for normal in [da.sub(db), da.add(db)] {
1049 let normal = normal.normalized().ok()?;
1050 let plane = PlaneData { origin: centre, normal };
1051 for curve in intersect_plane_quadric(&plane, a, tolerance, gate)? {
1052 let [t0, t1] = curve.domain().ok()?;
1053 for index in 0..=16 {
1054 let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?;
1055 if on_b(point) > band * 10.0 {
1056 return None;
1057 }
1058 }
1059 if equal_cylinder_tangent_split_enabled() {
1060 curves.extend(split_at_points(curve, &tangent_points, band * 10.0)?);
1061 } else {
1062 curves.push(curve);
1063 }
1064 }
1065 }
1066 Some(curves)
1067}
1068
1069fn equal_cylinder_tangent_split_enabled() -> bool {
1076 crate::switch!(live "BREP_EQUAL_CYLINDER_TANGENT_SPLIT", true)
1077}
1078
1079fn split_at_points(curve: NurbsCurve, points: &[Vec3], reach: f64) -> Option<Vec<NurbsCurve>> {
1086 let [t0, t1] = curve.domain().ok()?;
1087 let (start, end) = (curve.evaluate(t0).ok()?, curve.evaluate(t1).ok()?);
1088 let mut cuts: Vec<(f64, Vec3)> = Vec::new();
1089 for &point in points {
1090 if start.sub(point).length() <= reach || end.sub(point).length() <= reach {
1091 continue;
1092 }
1093 let foot = crate::project_point_to_curve(&curve, point).ok()?;
1094 if foot.distance <= reach {
1095 if !(foot.u > t0 && foot.u < t1) {
1096 return None;
1097 }
1098 cuts.push((foot.u, point));
1099 }
1100 }
1101 cuts.sort_by(|a, b| a.0.total_cmp(&b.0));
1102 cuts.dedup_by(|a, b| (a.0 - b.0).abs() <= 1e-12 * (t1 - t0));
1103 let mut pieces = Vec::new();
1104 let mut rest = curve;
1105 for (cut, point) in cuts.into_iter().rev() {
1106 let (left, right) = rest.split(cut).ok()?;
1107 let [_, left_end] = left.domain().ok()?;
1108 let [right_start, _] = right.domain().ok()?;
1109 if left.evaluate(left_end).ok()?.sub(point).length() > reach || right.evaluate(right_start).ok()?.sub(point).length() > reach {
1110 return None;
1111 }
1112 pieces.push(right);
1113 rest = left;
1114 }
1115 pieces.push(rest);
1116 pieces.reverse();
1117 Some(pieces)
1118}
1119
1120fn ruled_revolution_data(
1127 quadric: &AnalyticSurface,
1128 tolerance: f64,
1129 gate: RuledGate,
1130) -> Option<(RevolutionFrame, f64, f64, f64)> {
1131 match quadric {
1132 AnalyticSurface::RuledRevolution {
1133 frame,
1134 rho0,
1135 rho1,
1136 height,
1137 } => Some((frame.clone(), *rho0, *rho1, *height)),
1138 AnalyticSurface::Revolution {
1139 frame, generatrix, ..
1140 } => {
1141 if !generatrix_is_meridional_half_ray(generatrix, frame) {
1144 return None;
1145 }
1146 let (start, end) = match gate {
1147 RuledGate::Count => {
1148 let controls = &generatrix.control_points;
1149 if generatrix.degree != 1
1150 || controls.len() != 2
1151 || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
1152 || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
1153 {
1154 return None;
1155 }
1156 (controls[0].point().ok()?, controls[1].point().ok()?)
1157 }
1158 RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
1159 };
1160 let (_, rho0, z0) = frame.cylindrical(start);
1161 let (_, rho1, z1) = frame.cylindrical(end);
1162 let height = z1 - z0;
1163 if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
1164 return None;
1165 }
1166 let origin = frame.origin.add(frame.axis.scale(z0));
1167 Some((
1168 RevolutionFrame {
1169 origin,
1170 ..frame.clone()
1171 },
1172 rho0,
1173 rho1,
1174 height,
1175 ))
1176 }
1177 _ => None,
1178 }
1179}
1180
1181pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
1185 let quadric = surface.analytic()?;
1186 let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
1187 return None;
1188 };
1189 let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
1190 let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
1191 if count == geometry {
1192 return None;
1193 }
1194 let controls = &generatrix.control_points;
1195 let points: Vec<Vec3> = controls
1196 .iter()
1197 .map(|control| control.point().unwrap_or_default())
1198 .collect();
1199 let (first, last) = (points[0], points[points.len() - 1]);
1200 let direction = last.sub(first);
1201 let length_squared = direction.length_squared();
1202 let mut collinearity = 0.0_f64;
1203 for point in &points {
1204 collinearity = collinearity.max(if length_squared <= 0.0 {
1205 point.sub(first).length()
1206 } else {
1207 let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
1208 point.sub(first.add(direction.scale(fraction))).length()
1209 });
1210 }
1211 let unit_weights = controls
1212 .iter()
1213 .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
1214 Some(format!(
1215 "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
1216 count_gate={count} geometry_gate={geometry}",
1217 generatrix.degree,
1218 controls.len()
1219 ))
1220}
1221
1222fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
1243 if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
1244 return false;
1245 }
1246 let delta = rho1 - rho0;
1247 delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
1248}
1249
1250pub fn plane_ruled_section_arc(
1286 plane_origin: Vec3,
1287 plane_normal: Vec3,
1288 frame: &RevolutionFrame,
1289 rho0: f64,
1290 rho1: f64,
1291 height: f64,
1292 start_azimuth: f64,
1293 sweep: f64,
1294 tolerance: f64,
1295) -> Result<NurbsCurve, String> {
1296 let tau = std::f64::consts::TAU;
1297 if !(start_azimuth.is_finite() && sweep.is_finite()) {
1298 return Err("plane_ruled_section_arc: non-finite azimuth range".into());
1299 }
1300 if sweep <= 1e-12 || sweep > tau + 1e-9 {
1301 return Err(format!(
1302 "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
1303 positive arc of at most one turn — refusing"
1304 ));
1305 }
1306 let normal = plane_normal.normalized()?;
1307 let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
1308 let axis = frame.axis;
1309 let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
1310 || degenerate_apex_frustum(rho0, rho1, height);
1311 let curve = if is_cylinder {
1312 let alignment = normal.dot(axis);
1313 if alignment.abs() <= 1e-12 {
1314 return Err(
1315 "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
1316 section is a generatrix pair rather than a conic — refusing"
1317 .into(),
1318 );
1319 }
1320 if rho0.abs() <= tolerance {
1321 return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
1322 }
1323 let base = make_arc(
1324 frame.origin,
1325 frame.x_axis,
1326 frame.y_axis,
1327 rho0.abs(),
1328 start_azimuth,
1329 start_azimuth + sweep,
1330 )?;
1331 let origin_dot = plane_origin.dot(normal);
1332 map_rational_curve(&base, |p| {
1333 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
1334 crate::Vec4 {
1335 x: p.x + axis.x * t,
1336 y: p.y + axis.y * t,
1337 z: p.z + axis.z * t,
1338 w: p.w,
1339 }
1340 })
1341 .ok_or_else(|| {
1342 "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
1343 — refusing"
1344 .to_string()
1345 })?
1346 } else {
1347 let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
1348 let k = plane_origin.sub(apex).dot(normal);
1349 if k.abs() <= tolerance {
1350 return Err(
1351 "plane_ruled_section_arc: the plane passes through the cone apex, so the \
1352 section is a line pair rather than a conic — refusing"
1353 .into(),
1354 );
1355 }
1356 let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
1357 (rho0.abs(), 0.0)
1358 } else {
1359 (rho1.abs(), height)
1360 };
1361 if reference_rho <= tolerance {
1362 return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
1363 }
1364 let base = make_arc(
1365 frame.origin.add(axis.scale(reference_z)),
1366 frame.x_axis,
1367 frame.y_axis,
1368 reference_rho,
1369 start_azimuth,
1370 start_azimuth + sweep,
1371 )?;
1372 map_rational_curve(&base, |p| {
1373 let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1374 let w_new = relative.dot(normal);
1375 let scaled = relative.scale(k);
1376 crate::Vec4 {
1377 x: apex.x * w_new + scaled.x,
1378 y: apex.y * w_new + scaled.y,
1379 z: apex.z * w_new + scaled.z,
1380 w: w_new,
1381 }
1382 })
1383 .ok_or_else(|| {
1384 "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
1385 or hyperbolic branch, whose weights change sign) — refusing"
1386 .to_string()
1387 })?
1388 };
1389 let [d0, d1] = curve.domain()?;
1393 let slope = if height == 0.0 {
1394 0.0
1395 } else {
1396 (rho1 - rho0) / height
1397 };
1398 for step in 0..=8 {
1399 let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
1400 let delta = point.sub(frame.origin);
1401 let axial = delta.dot(axis);
1402 let radial = delta.sub(axis.scale(axial)).length();
1403 let off_ruled = (radial - (rho0 + slope * axial)).abs();
1404 let off_plane = point.sub(plane_origin).dot(normal).abs();
1405 if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
1406 return Err(format!(
1407 "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
1408 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
1409 ));
1410 }
1411 }
1412 Ok(curve)
1413}
1414
1415fn intersect_plane_quadric(
1416 plane: &PlaneData,
1417 quadric: &AnalyticSurface,
1418 tolerance: f64,
1419 gate: RuledGate,
1420) -> Option<Vec<NurbsCurve>> {
1421 match quadric {
1422 AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
1423 if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
1424 {
1425 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
1426 let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
1427 let alignment = plane.normal.dot(frame.axis);
1428 if alignment.abs() >= 1.0 - 1e-12 {
1429 let z = plane.origin.sub(frame.origin).dot(frame.axis);
1431 let t = z / height;
1432 if !(-1e-9..=1.0 + 1e-9).contains(&t) {
1433 return Some(Vec::new());
1434 }
1435 let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
1436 if rho <= tolerance {
1437 return Some(Vec::new());
1438 }
1439 return Some(vec![frame_circle(frame, rho, z)?]);
1440 }
1441 if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
1442 if alignment.abs() <= 1e-12 {
1444 return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
1447 }
1448 let circle = frame_circle(frame, *rho0, 0.0)?;
1451 let denominator = alignment;
1452 let origin_dot = plane.origin.dot(plane.normal);
1453 let normal = plane.normal;
1454 let axis = frame.axis;
1455 let ellipse = map_rational_curve(&circle, |p| {
1456 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
1457 crate::Vec4 {
1458 x: p.x + axis.x * t,
1459 y: p.y + axis.y * t,
1460 z: p.z + axis.z * t,
1461 w: p.w,
1462 }
1463 })?;
1464 if !section_within_band(&ellipse, frame, *height, tolerance) {
1465 return Some(Vec::new());
1466 }
1467 return Some(vec![ellipse]);
1468 }
1469 let apex_t = rho0 / (rho0 - rho1);
1473 let apex = frame.origin.add(frame.axis.scale(height * apex_t));
1474 let reference_rho = if rho0.abs() > rho1.abs() {
1475 *rho0
1476 } else {
1477 *rho1
1478 };
1479 let reference_z = if rho0.abs() > rho1.abs() {
1480 0.0
1481 } else {
1482 *height
1483 };
1484 let circle = frame_circle(frame, reference_rho, reference_z)?;
1485 let k = plane.origin.sub(apex).dot(plane.normal);
1486 if k.abs() <= tolerance {
1487 if cone_apex_plane_rulings_enabled() {
1489 return cone_apex_plane_rulings(plane, frame, *rho0, *rho1, *height, apex, apex_t, tolerance);
1490 }
1491 return None;
1492 }
1493 let normal = plane.normal;
1494 let project = |p: crate::Vec4| {
1495 let relative =
1496 Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1497 let w_new = relative.dot(normal);
1498 let scaled = relative.scale(k);
1499 crate::Vec4 {
1500 x: apex.x * w_new + scaled.x,
1501 y: apex.y * w_new + scaled.y,
1502 z: apex.z * w_new + scaled.z,
1503 w: w_new,
1504 }
1505 };
1506 let Some(conic) = map_rational_curve(&circle, project) else {
1507 if cone_plane_open_section_enabled() {
1509 return cone_plane_open_section(frame, *height, apex, reference_rho, reference_z, k, normal, tolerance, &project);
1510 }
1511 return None;
1512 };
1513 if !section_within_band(&conic, frame, *height, tolerance) {
1514 return Some(Vec::new());
1515 }
1516 Some(vec![conic])
1517 }
1518 AnalyticSurface::Sphere { frame, radius } => {
1519 plane_sphere_section(plane, frame.origin, *radius, tolerance)
1520 }
1521 AnalyticSurface::Torus {
1522 frame,
1523 major_radius,
1524 minor_radius,
1525 } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
1526 AnalyticSurface::Plane { .. } => None,
1527 AnalyticSurface::RuledRevolution { .. } => None,
1528 AnalyticSurface::Revolution { .. } => {
1534 if let Some((center, radius)) = quadric.sphere_geometry() {
1535 return plane_sphere_section(plane, center, radius, tolerance);
1536 }
1537 if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
1538 return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
1539 }
1540 None
1541 }
1542 }
1543}
1544
1545fn plane_sphere_section(
1548 plane: &PlaneData,
1549 center: Vec3,
1550 radius: f64,
1551 tolerance: f64,
1552) -> Option<Vec<NurbsCurve>> {
1553 let distance = center.sub(plane.origin).dot(plane.normal);
1554 if distance.abs() >= radius - tolerance {
1555 return Some(Vec::new());
1556 }
1557 let circle_center = center.sub(plane.normal.scale(distance));
1558 let circle_radius = (radius * radius - distance * distance).sqrt();
1559 let x_axis = plane.normal.perpendicular().ok()?;
1560 let y_axis = plane.normal.cross(x_axis);
1561 Some(vec![make_arc(
1562 circle_center,
1563 x_axis,
1564 y_axis,
1565 circle_radius,
1566 0.0,
1567 std::f64::consts::TAU,
1568 )
1569 .ok()?])
1570}
1571
1572fn plane_torus_section(
1577 plane: &PlaneData,
1578 frame: &RevolutionFrame,
1579 major_radius: f64,
1580 minor_radius: f64,
1581 tolerance: f64,
1582) -> Option<Vec<NurbsCurve>> {
1583 let alignment = plane.normal.dot(frame.axis);
1584 if alignment.abs() < 1.0 - 1e-12 {
1585 return None;
1586 }
1587 let z = plane.origin.sub(frame.origin).dot(frame.axis);
1588 if z.abs() >= minor_radius - tolerance {
1589 return Some(Vec::new());
1590 }
1591 let offset = (minor_radius * minor_radius - z * z).sqrt();
1592 let mut circles = Vec::new();
1593 for rho in [major_radius - offset, major_radius + offset] {
1594 if rho > tolerance {
1595 circles.push(frame_circle(frame, rho, z)?);
1596 }
1597 }
1598 Some(circles)
1599}
1600
1601fn section_within_band(
1618 curve: &NurbsCurve,
1619 frame: &RevolutionFrame,
1620 height: f64,
1621 tolerance: f64,
1622) -> bool {
1623 let (band_low, band_high) = if height >= 0.0 {
1624 (0.0, height)
1625 } else {
1626 (height, 0.0)
1627 };
1628 let margin = tolerance.max(1e-9) + 1e-9;
1629 let mut min_z = f64::INFINITY;
1630 let mut max_z = f64::NEG_INFINITY;
1631 for p in &curve.control_points {
1632 let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
1633 .sub(frame.origin)
1634 .dot(frame.axis);
1635 min_z = min_z.min(z);
1636 max_z = max_z.max(z);
1637 }
1638 max_z >= band_low - margin && min_z <= band_high + margin
1640}
1641
1642fn cone_apex_plane_rulings_enabled() -> bool {
1645 crate::switch!(live "BREP_CONE_APEX_PLANE_RULINGS", true)
1646}
1647
1648#[allow(clippy::too_many_arguments)]
1663fn cone_apex_plane_rulings(
1664 plane: &PlaneData,
1665 frame: &RevolutionFrame,
1666 rho0: f64,
1667 rho1: f64,
1668 height: f64,
1669 apex: Vec3,
1670 apex_t: f64,
1671 tolerance: f64,
1672) -> Option<Vec<NurbsCurve>> {
1673 if !(apex_t.is_finite() && height.is_finite()) || height == 0.0 {
1674 return None;
1675 }
1676 let normal = plane.normal.normalized().ok()?;
1677 let apex_z = height * apex_t;
1680 let (end_a, end_b) = ((0.0 - apex_z).abs(), (height - apex_z).abs());
1681 let (near, far) = (end_a.min(end_b), end_a.max(end_b));
1682 let toward = if 0.5 * height - apex_z >= 0.0 { 1.0 } else { -1.0 };
1683 let axis = frame.axis.normalized().ok()?.scale(toward);
1684 let tan_alpha = (rho1 - rho0).abs() / height.abs();
1685 let cos_alpha = 1.0 / (1.0 + tan_alpha * tan_alpha).sqrt();
1686 let along = axis.dot(normal);
1687 let in_plane = axis.sub(normal.scale(along));
1688 let sin_beta = in_plane.length();
1689 if sin_beta <= 1e-12 {
1690 return Some(Vec::new());
1693 }
1694 let depth = far * (tan_alpha - along.abs() / sin_beta);
1695 if depth <= tolerance {
1696 return Some(Vec::new());
1697 }
1698 let e1 = in_plane.scale(1.0 / sin_beta);
1701 let e2 = normal.cross(e1);
1702 let cos_phi = (cos_alpha / sin_beta).min(1.0);
1703 let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt();
1704 let foot = apex.sub(normal.scale(apex.sub(plane.origin).dot(normal)));
1706 let mut lines = Vec::new();
1707 for sign in [1.0, -1.0] {
1708 let direction = e1.scale(cos_phi).add(e2.scale(sign * sin_phi));
1709 let start = foot.add(direction.scale(near / cos_alpha));
1710 let end = foot.add(direction.scale(far / cos_alpha));
1711 lines.push(crate::make_line(start, end).ok()?);
1712 }
1713 Some(lines)
1714}
1715
1716fn cylinder_parallel_plane_lines(
1717 plane: &PlaneData,
1718 frame: &RevolutionFrame,
1719 radius: f64,
1720 height: f64,
1721 tolerance: f64,
1722) -> Option<Vec<NurbsCurve>> {
1723 let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
1725 if axis_to_plane.abs() >= radius - tolerance {
1726 return Some(Vec::new());
1727 }
1728 let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
1730 let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
1731 let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
1732 let mut lines = Vec::new();
1733 for sign in [-1.0, 1.0] {
1734 let base = foot.add(chord_direction.scale(sign * chord_half));
1735 let top = base.add(frame.axis.scale(height));
1736 lines.push(crate::make_line(base, top).ok()?);
1737 }
1738 Some(lines)
1739}
1740
1741fn intersect_sphere_sphere(
1742 center_a: Vec3,
1743 radius_a: f64,
1744 center_b: Vec3,
1745 radius_b: f64,
1746 tolerance: f64,
1747) -> Option<Vec<NurbsCurve>> {
1748 let offset = center_b.sub(center_a);
1749 let distance = offset.length();
1750 if distance <= tolerance {
1751 return if (radius_a - radius_b).abs() <= tolerance {
1754 None
1755 } else {
1756 Some(Vec::new())
1757 };
1758 }
1759 if distance >= radius_a + radius_b - tolerance
1760 || distance <= (radius_a - radius_b).abs() + tolerance
1761 {
1762 return Some(Vec::new());
1763 }
1764 let normal = offset.scale(1.0 / distance);
1765 let along =
1766 (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
1767 let circle_radius_squared = radius_a * radius_a - along * along;
1768 if circle_radius_squared <= tolerance * tolerance {
1769 return Some(Vec::new());
1770 }
1771 let center = center_a.add(normal.scale(along));
1772 let x_axis = normal.perpendicular().ok()?;
1773 let y_axis = normal.cross(x_axis);
1774 Some(vec![make_arc(
1775 center,
1776 x_axis,
1777 y_axis,
1778 circle_radius_squared.sqrt(),
1779 0.0,
1780 std::f64::consts::TAU,
1781 )
1782 .ok()?])
1783}
1784
1785
1786
1787
1788