1use ogeom_core::{OgeomResult, Tolerances, ogeom_bail};
34use ogeom_geom::{BSpline2d, BSplineCurve, Surface, SurfaceGeometry};
35use ogeom_math::Point2;
36
37use crate::march::Traced;
38
39#[derive(Debug, Clone, PartialEq)]
41pub struct IntersectionCurve {
42 pub curve: BSplineCurve,
44 pub on_a: BSpline2d,
46 pub on_b: BSpline2d,
48 pub fit_error: f64,
54 pub met: bool,
56 pub closed: bool,
58}
59
60pub fn approximate_branch(
67 a: &SurfaceGeometry,
68 b: &SurfaceGeometry,
69 branch: &Traced,
70 tolerance: f64,
71 tol: Tolerances,
72) -> OgeomResult<IntersectionCurve> {
73 if branch.points.len() < 2 {
74 ogeom_bail!(
75 Construction,
76 "a branch of {} points is not a curve",
77 branch.points.len()
78 );
79 }
80
81 let mut points: Vec<ogeom_math::Point> = Vec::with_capacity(branch.points.len());
87 let mut kept_a = Vec::with_capacity(branch.on_a.len());
88 let mut kept_b = Vec::with_capacity(branch.on_b.len());
89 let agrees = |i: usize, p: &ogeom_math::Point| -> bool {
95 let limit = tolerance.max(tol.confusion());
96 let (ua, va) = branch.on_a[i];
97 let (ub, vb) = branch.on_b[i];
98 a.point_at(ua, va, tol)
99 .is_ok_and(|q| q.distance(*p) <= limit)
100 && b.point_at(ub, vb, tol)
101 .is_ok_and(|q| q.distance(*p) <= limit)
102 };
103 for (i, p) in branch.points.iter().enumerate() {
104 let end = i == 0 || i + 1 == branch.points.len();
105 if let Some(last) = points.last()
106 && last.distance(*p) <= tol.confusion() * 10.0
107 && i + 1 != branch.points.len()
108 {
109 continue;
110 }
111 if !end && !agrees(i, p) {
112 continue;
113 }
114 points.push(*p);
115 kept_a.push(branch.on_a[i]);
116 kept_b.push(branch.on_b[i]);
117 }
118 if points.len() < 2 {
119 ogeom_bail!(Construction, "a branch of coincident points is not a curve");
120 }
121
122 let unwrapped_a = unwrap_periodic(a, &kept_a, tol);
130 let unwrapped_b = unwrap_periodic(b, &kept_b, tol);
131 let (space, on_a, on_b) = if branch.closed() {
135 ogeom_geom::fit::fit_points_joint_closed(
136 &points,
137 &unwrapped_a,
138 &unwrapped_b,
139 3,
140 tolerance,
141 tol,
142 )?
143 } else {
144 ogeom_geom::fit::fit_points_joint(&points, &unwrapped_a, &unwrapped_b, 3, tolerance, tol)?
145 };
146
147 Ok(IntersectionCurve {
148 fit_error: space
149 .error
150 .max(space_error(a, &(on_a.clone(), space.met, space.error), tol))
151 .max(space_error(b, &(on_b.clone(), space.met, space.error), tol)),
152 met: space.met,
153 curve: space.curve,
154 on_a,
155 on_b,
156 closed: branch.closed(),
157 })
158}
159
160fn space_error(surface: &SurfaceGeometry, fitted: &(BSpline2d, bool, f64), tol: Tolerances) -> f64 {
170 use ogeom_geom::Curve2d;
171 let (pcurve, _, parameter_error) = fitted;
172 let (lo, hi) = pcurve.domain();
175 let mut worst = 0.0_f64;
176 for i in 0..=16 {
177 #[allow(clippy::cast_precision_loss)]
178 let u = lo + (hi - lo) * f64::from(i) / 16.0;
179 let Ok(at) = pcurve.point_at(u, tol) else {
180 continue;
181 };
182 let Ok((du, dv)) = surface.d1_at(at.x, at.y, tol) else {
183 continue;
184 };
185 let stretch = du.magnitude().max(dv.magnitude());
186 worst = worst.max(parameter_error * stretch);
187 }
188 worst
189}
190
191fn unwrap_periodic(
198 surface: &SurfaceGeometry,
199 samples: &[(f64, f64)],
200 tol: Tolerances,
201) -> Vec<Point2> {
202 let ((ua, ub), (va, vb)) = surface.domain();
203 let u_period = if surface.is_periodic_u() || surface.is_closed_u(tol) {
210 Some(ub - ua)
211 } else {
212 None
213 };
214 let v_period = if surface.is_periodic_v() || surface.is_closed_v(tol) {
215 Some(vb - va)
216 } else {
217 None
218 };
219 let fold = |previous: f64, next: f64, period: Option<f64>| match period {
220 None => next,
221 Some(period) => {
222 let mut candidate = next;
223 while candidate - previous > period * 0.5 {
224 candidate -= period;
225 }
226 while previous - candidate > period * 0.5 {
227 candidate += period;
228 }
229 candidate
230 }
231 };
232
233 let mut out = Vec::with_capacity(samples.len());
234 let mut at = Point2::new(samples[0].0, samples[0].1);
235 out.push(at);
236 for sample in &samples[1..] {
237 at = Point2::new(
238 fold(at.x, sample.0, u_period),
239 fold(at.y, sample.1, v_period),
240 );
241 out.push(at);
242 }
243 out
244}
245
246#[cfg(test)]
247#[allow(clippy::unwrap_used)]
248mod tests {
249 use super::*;
250 use crate::march::{Marching, branches};
251 use ogeom_geom::{Curve2d, Curve3d, CylinderSurface, PlaneSurface, SphereSurface};
252 use ogeom_math::{Cylinder, Direction, Frame, Plane, Point, Sphere, Vector};
253
254 const T: Tolerances = Tolerances::millimetres();
255
256 fn sphere(radius: f64) -> SurfaceGeometry {
257 SphereSurface::new(Sphere::centred(Point::ORIGIN, radius, T).unwrap()).into()
258 }
259
260 fn cylinder(radius: f64) -> SurfaceGeometry {
261 CylinderSurface::new(Cylinder::new(Frame::WORLD, radius, T).unwrap(), (-4.0, 4.0))
262 .unwrap()
263 .into()
264 }
265
266 fn plane(origin: Point, normal: Vector) -> SurfaceGeometry {
267 PlaneSurface::over(
268 Plane::through(origin, Direction::new(normal, T).unwrap()),
269 (-6.0, 6.0),
270 (-6.0, 6.0),
271 )
272 .unwrap()
273 .into()
274 }
275
276 fn options() -> Marching {
277 Marching {
278 chord: 1e-5,
279 ..Marching::default()
280 }
281 }
282
283 fn fitted_deviation(a: &SurfaceGeometry, b: &SurfaceGeometry, curve: &BSplineCurve) -> f64 {
289 let off = |surface: &SurfaceGeometry, p: Point| match surface {
290 SurfaceGeometry::Plane(x) => x.plane().distance_to(p),
291 SurfaceGeometry::Sphere(x) => x.sphere().distance_to(p),
292 SurfaceGeometry::Cylinder(x) => x.cylinder().distance_to(p),
293 _ => 0.0,
294 };
295 let (lo, hi) = curve.knots().domain();
296 let mut worst = 0.0_f64;
297 for i in 0..=800 {
298 #[allow(clippy::cast_precision_loss)]
299 let u = lo + (hi - lo) * f64::from(i) / 800.0;
300 if let Ok(p) = curve.point_at(u, T) {
301 worst = worst.max(off(a, p).abs().max(off(b, p).abs()));
302 }
303 }
304 worst
305 }
306
307 #[test]
308 fn a_fitted_branch_lies_on_both_surfaces_to_the_stated_total() {
309 let a = sphere(3.0);
313 let b = cylinder(1.5);
314 let found = branches(&a, &b, options(), T).unwrap();
315 assert_eq!(found.len(), 2);
316
317 for branch in &found {
318 let fitted = approximate_branch(&a, &b, branch, 1e-4, T).unwrap();
319 assert!(fitted.met, "fit error {:e}", fitted.fit_error);
320 assert!(fitted.closed);
321 let off = fitted_deviation(&a, &b, &fitted.curve);
322 assert!(
323 off <= 1e-4 + 1e-5,
324 "the fitted curve is {off:e} off the surfaces"
325 );
326 assert!(
328 fitted.curve.control_points().len() * 4 < branch.points.len(),
329 "{} control points for {} samples",
330 fitted.curve.control_points().len(),
331 branch.points.len()
332 );
333 }
334 }
335
336 #[test]
337 fn the_pcurves_lift_back_onto_the_curve() {
338 let a = sphere(3.0);
342 let b = cylinder(1.5);
343 let found = branches(&a, &b, options(), T).unwrap();
344 let branch = &found[0];
345 let fitted = approximate_branch(&a, &b, branch, 1e-4, T).unwrap();
346
347 for (surface, pcurve) in [(&a, &fitted.on_a), (&b, &fitted.on_b)] {
348 let (lo, hi) = pcurve.domain();
349 for i in 0..=200 {
350 #[allow(clippy::cast_precision_loss)]
351 let u = lo + (hi - lo) * f64::from(i) / 200.0;
352 let at = pcurve.point_at(u, T).unwrap();
353 let lifted = surface.point_at(at.x, at.y, T).unwrap();
354 let off = match (surface as &SurfaceGeometry, &a, &b) {
358 _ if core::ptr::eq(surface, &a) => match &b {
359 SurfaceGeometry::Cylinder(c) => c.cylinder().distance_to(lifted),
360 _ => 0.0,
361 },
362 _ => match &a {
363 SurfaceGeometry::Sphere(s) => s.sphere().distance_to(lifted),
364 _ => 0.0,
365 },
366 };
367 assert!(
368 off.abs() < 5e-4,
369 "a lifted pcurve point is {off:e} off the intersection"
370 );
371 }
372 }
373 }
374
375 #[test]
376 fn a_branch_across_the_seam_gets_a_continuous_pcurve() {
377 let a = cylinder(2.0);
382 let b = plane(Point::ORIGIN, Vector::new(0.0, 0.4, 1.0));
383 let found = branches(&a, &b, options(), T).unwrap();
384 assert_eq!(found.len(), 1, "an oblique plane cuts one ellipse");
385 let fitted = approximate_branch(&a, &b, &found[0], 1e-4, T).unwrap();
386
387 let (lo, hi) = fitted.on_a.domain();
390 let mut previous = fitted.on_a.point_at(lo, T).unwrap();
391 for i in 1..=400 {
392 #[allow(clippy::cast_precision_loss)]
393 let u = lo + (hi - lo) * f64::from(i) / 400.0;
394 let at = fitted.on_a.point_at(u, T).unwrap();
395 assert!(
396 (at.x - previous.x).abs() < 1.0,
397 "the pcurve tears at the seam: {} to {}",
398 previous.x,
399 at.x
400 );
401 previous = at;
402 }
403 }
404
405 #[test]
415 fn a_loop_cut_at_a_converted_drum_s_seam_is_closed() {
416 let drum: SurfaceGeometry = cylinder(2.0).to_bspline(T).unwrap().into();
417 assert!(matches!(drum, SurfaceGeometry::BSpline(_)));
418 let cut = plane(Point::new(0.0, 0.0, 1.0), Vector::new(0.0, 0.2, 1.0));
419 let found = branches(&drum, &cut, options(), T).unwrap();
420 assert_eq!(found.len(), 1, "an oblique plane cuts one loop");
421 assert!(found[0].closed(), "the loop closes on the seam");
422 let fitted = approximate_branch(&drum, &cut, &found[0], 1e-4, T).unwrap();
423 assert!(fitted.closed);
424 assert!(
425 fitted.fit_error < 1e-3,
426 "the loop fits as one: {}",
427 fitted.fit_error
428 );
429 let (lo, hi) = fitted.on_a.domain();
430 let mut previous = fitted.on_a.point_at(lo, T).unwrap();
431 for i in 1..=400 {
432 let u = lo + (hi - lo) * f64::from(i) / 400.0;
433 let at = fitted.on_a.point_at(u, T).unwrap();
434 assert!(
435 (at.x - previous.x).abs() < 0.5,
436 "the chart image tears at the seam: {} to {}",
437 previous.x,
438 at.x
439 );
440 previous = at;
441 }
442 }
443
444 #[test]
445 fn what_cannot_be_fitted_is_refused() {
446 let a = sphere(1.0);
447 let b = plane(Point::ORIGIN, Vector::Z);
448 let found = branches(&a, &b, options(), T).unwrap();
449 assert!(approximate_branch(&a, &b, &found[0], 0.0, T).is_err());
450 assert!(approximate_branch(&a, &b, &found[0], -1.0, T).is_err());
451
452 let empty = Traced {
453 points: vec![],
454 on_a: vec![],
455 on_b: vec![],
456 stopped: crate::march::Stopped::Stalled,
457 };
458 assert!(approximate_branch(&a, &b, &empty, 1e-4, T).is_err());
459 }
460}