1use super::*;
2use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, 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 frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
62 make_arc(
63 frame.origin.add(frame.axis.scale(z)),
64 frame.x_axis,
65 frame.y_axis,
66 rho,
67 0.0,
68 std::f64::consts::TAU,
69 )
70 .ok()
71}
72
73pub fn intersect_analytic_pair(
77 first: &NurbsSurface,
78 second: &NurbsSurface,
79 tolerance: f64,
80) -> Option<Vec<NurbsCurve>> {
81 if let Some(curves) = intersect_recognized_pair(first, second, tolerance) {
82 return Some(curves);
83 }
84 if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
85 return Some(curves);
86 }
87 if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
88 return Some(curves);
89 }
90 intersect_axial_plane_revolution(second, first, tolerance)
91}
92
93fn intersect_axial_plane_revolution(
99 plane_surface: &NurbsSurface,
100 revolved: &NurbsSurface,
101 _tolerance: f64,
102) -> Option<Vec<NurbsCurve>> {
103 let plane = match plane_surface.analytic()? {
104 AnalyticSurface::Plane {
105 origin,
106 u_dir,
107 v_dir,
108 ..
109 } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
110 _ => return None,
111 };
112 let structure = revolution_structure(revolved)?;
113 if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
114 return None;
115 }
116 let scale = surface_scale(plane_surface)
117 .max(surface_scale(revolved))
118 .max(1.0);
119 let (plane_origin, plane_normal) = plane;
120 if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
121 return None;
122 }
123 if structure
124 .frame
125 .origin
126 .sub(plane_origin)
127 .dot(plane_normal)
128 .abs()
129 > 1e-9 * scale
130 {
131 return None;
132 }
133 let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
134 let tau = std::f64::consts::TAU;
135 let mut curves = Vec::new();
136 for direction in [radial, radial.scale(-1.0)] {
137 let mut angle = direction
138 .dot(structure.frame.y_axis)
139 .atan2(direction.dot(structure.frame.x_axis));
140 if angle < -1e-9 {
141 angle += tau;
142 }
143 if angle <= structure.sweep + 1e-9 {
144 curves.push(rotate_curve_about_axis(
145 &structure.generatrix,
146 structure.frame.origin,
147 structure.frame.axis,
148 angle.clamp(0.0, structure.sweep),
149 )?);
150 }
151 }
152 Some(curves)
153}
154
155fn intersect_recognized_pair(
156 first: &NurbsSurface,
157 second: &NurbsSurface,
158 tolerance: f64,
159) -> Option<Vec<NurbsCurve>> {
160 let a = first.analytic()?;
161 let b = second.analytic()?;
162 if !matches!(b, AnalyticSurface::Plane { .. }) {
163 if let Some(plane) = plane_data(a) {
164 return intersect_plane_quadric(&plane, b, tolerance);
165 }
166 }
167 if !matches!(a, AnalyticSurface::Plane { .. }) {
168 if let Some(plane) = plane_data(b) {
169 return intersect_plane_quadric(&plane, a, tolerance);
170 }
171 }
172 match (a, b) {
173 (AnalyticSurface::Plane { .. }, AnalyticSurface::Plane { .. }) => None,
180 (
181 AnalyticSurface::Sphere {
182 frame: frame_a,
183 radius: radius_a,
184 },
185 AnalyticSurface::Sphere {
186 frame: frame_b,
187 radius: radius_b,
188 },
189 ) => intersect_sphere_sphere(
190 frame_a.origin,
191 *radius_a,
192 frame_b.origin,
193 *radius_b,
194 tolerance,
195 ),
196 _ => None,
197 }
198}
199
200fn ruled_revolution_data(quadric: &AnalyticSurface) -> Option<(RevolutionFrame, f64, f64, f64)> {
207 match quadric {
208 AnalyticSurface::RuledRevolution {
209 frame,
210 rho0,
211 rho1,
212 height,
213 } => Some((frame.clone(), *rho0, *rho1, *height)),
214 AnalyticSurface::Revolution {
215 frame, generatrix, ..
216 } => {
217 let controls = &generatrix.control_points;
218 if generatrix.degree != 1
219 || controls.len() != 2
220 || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
221 || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
222 {
223 return None;
224 }
225 let (_, rho0, z0) = frame.cylindrical(controls[0].point().ok()?);
226 let (_, rho1, z1) = frame.cylindrical(controls[1].point().ok()?);
227 let height = z1 - z0;
228 if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
229 return None;
230 }
231 let origin = frame.origin.add(frame.axis.scale(z0));
232 Some((
233 RevolutionFrame {
234 origin,
235 ..frame.clone()
236 },
237 rho0,
238 rho1,
239 height,
240 ))
241 }
242 _ => None,
243 }
244}
245
246fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
267 if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
268 return false;
269 }
270 let delta = rho1 - rho0;
271 delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
272}
273
274fn intersect_plane_quadric(
275 plane: &PlaneData,
276 quadric: &AnalyticSurface,
277 tolerance: f64,
278) -> Option<Vec<NurbsCurve>> {
279 match quadric {
280 AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
281 if ruled_revolution_data(quadric).is_some() =>
282 {
283 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric)?;
284 let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
285 let alignment = plane.normal.dot(frame.axis);
286 if alignment.abs() >= 1.0 - 1e-12 {
287 let z = plane.origin.sub(frame.origin).dot(frame.axis);
289 let t = z / height;
290 if !(-1e-9..=1.0 + 1e-9).contains(&t) {
291 return Some(Vec::new());
292 }
293 let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
294 if rho <= tolerance {
295 return Some(Vec::new());
296 }
297 return Some(vec![frame_circle(frame, rho, z)?]);
298 }
299 if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
300 if alignment.abs() <= 1e-12 {
302 return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
305 }
306 let circle = frame_circle(frame, *rho0, 0.0)?;
309 let denominator = alignment;
310 let origin_dot = plane.origin.dot(plane.normal);
311 let normal = plane.normal;
312 let axis = frame.axis;
313 let ellipse = map_rational_curve(&circle, |p| {
314 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
315 crate::Vec4 {
316 x: p.x + axis.x * t,
317 y: p.y + axis.y * t,
318 z: p.z + axis.z * t,
319 w: p.w,
320 }
321 })?;
322 if !section_within_band(&ellipse, frame, *height, tolerance) {
323 return Some(Vec::new());
324 }
325 return Some(vec![ellipse]);
326 }
327 let apex_t = rho0 / (rho0 - rho1);
331 let apex = frame.origin.add(frame.axis.scale(height * apex_t));
332 let reference_rho = if rho0.abs() > rho1.abs() {
333 *rho0
334 } else {
335 *rho1
336 };
337 let reference_z = if rho0.abs() > rho1.abs() {
338 0.0
339 } else {
340 *height
341 };
342 let circle = frame_circle(frame, reference_rho, reference_z)?;
343 let k = plane.origin.sub(apex).dot(plane.normal);
344 if k.abs() <= tolerance {
345 return None;
347 }
348 let normal = plane.normal;
349 let conic = map_rational_curve(&circle, |p| {
350 let relative =
351 Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
352 let w_new = relative.dot(normal);
353 let scaled = relative.scale(k);
354 crate::Vec4 {
355 x: apex.x * w_new + scaled.x,
356 y: apex.y * w_new + scaled.y,
357 z: apex.z * w_new + scaled.z,
358 w: w_new,
359 }
360 })?;
361 if !section_within_band(&conic, frame, *height, tolerance) {
362 return Some(Vec::new());
363 }
364 Some(vec![conic])
365 }
366 AnalyticSurface::Sphere { frame, radius } => {
367 let distance = frame.origin.sub(plane.origin).dot(plane.normal);
368 if distance.abs() >= radius - tolerance {
369 return Some(Vec::new());
370 }
371 let center = frame.origin.sub(plane.normal.scale(distance));
372 let circle_radius = (radius * radius - distance * distance).sqrt();
373 let x_axis = plane.normal.perpendicular().ok()?;
374 let y_axis = plane.normal.cross(x_axis);
375 Some(vec![make_arc(
376 center,
377 x_axis,
378 y_axis,
379 circle_radius,
380 0.0,
381 std::f64::consts::TAU,
382 )
383 .ok()?])
384 }
385 AnalyticSurface::Torus {
386 frame,
387 major_radius,
388 minor_radius,
389 } => {
390 let alignment = plane.normal.dot(frame.axis);
391 if alignment.abs() < 1.0 - 1e-12 {
392 return None;
393 }
394 let z = plane.origin.sub(frame.origin).dot(frame.axis);
395 if z.abs() >= minor_radius - tolerance {
396 return Some(Vec::new());
397 }
398 let offset = (minor_radius * minor_radius - z * z).sqrt();
399 let mut circles = Vec::new();
400 for rho in [major_radius - offset, major_radius + offset] {
401 if rho > tolerance {
402 circles.push(frame_circle(frame, rho, z)?);
403 }
404 }
405 Some(circles)
406 }
407 AnalyticSurface::Plane { .. } => None,
408 AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. } => None,
411 }
412}
413
414fn section_within_band(
431 curve: &NurbsCurve,
432 frame: &RevolutionFrame,
433 height: f64,
434 tolerance: f64,
435) -> bool {
436 let (band_low, band_high) = if height >= 0.0 {
437 (0.0, height)
438 } else {
439 (height, 0.0)
440 };
441 let margin = tolerance.max(1e-9) + 1e-9;
442 let mut min_z = f64::INFINITY;
443 let mut max_z = f64::NEG_INFINITY;
444 for p in &curve.control_points {
445 let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
446 .sub(frame.origin)
447 .dot(frame.axis);
448 min_z = min_z.min(z);
449 max_z = max_z.max(z);
450 }
451 max_z >= band_low - margin && min_z <= band_high + margin
453}
454
455fn cylinder_parallel_plane_lines(
456 plane: &PlaneData,
457 frame: &RevolutionFrame,
458 radius: f64,
459 height: f64,
460 tolerance: f64,
461) -> Option<Vec<NurbsCurve>> {
462 let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
464 if axis_to_plane.abs() >= radius - tolerance {
465 return Some(Vec::new());
466 }
467 let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
469 let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
470 let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
471 let mut lines = Vec::new();
472 for sign in [-1.0, 1.0] {
473 let base = foot.add(chord_direction.scale(sign * chord_half));
474 let top = base.add(frame.axis.scale(height));
475 lines.push(crate::make_line(base, top).ok()?);
476 }
477 Some(lines)
478}
479
480fn intersect_sphere_sphere(
481 center_a: Vec3,
482 radius_a: f64,
483 center_b: Vec3,
484 radius_b: f64,
485 tolerance: f64,
486) -> Option<Vec<NurbsCurve>> {
487 let offset = center_b.sub(center_a);
488 let distance = offset.length();
489 if distance <= tolerance {
490 return if (radius_a - radius_b).abs() <= tolerance {
493 None
494 } else {
495 Some(Vec::new())
496 };
497 }
498 if distance >= radius_a + radius_b - tolerance
499 || distance <= (radius_a - radius_b).abs() + tolerance
500 {
501 return Some(Vec::new());
502 }
503 let normal = offset.scale(1.0 / distance);
504 let along =
505 (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
506 let circle_radius_squared = radius_a * radius_a - along * along;
507 if circle_radius_squared <= tolerance * tolerance {
508 return Some(Vec::new());
509 }
510 let center = center_a.add(normal.scale(along));
511 let x_axis = normal.perpendicular().ok()?;
512 let y_axis = normal.cross(x_axis);
513 Some(vec![make_arc(
514 center,
515 x_axis,
516 y_axis,
517 circle_radius_squared.sqrt(),
518 0.0,
519 std::f64::consts::TAU,
520 )
521 .ok()?])
522}