Skip to main content

brepkit_math/
filtered.rs

1//! Filtered exact arithmetic for geometric predicates.
2//!
3//! Provides fast-path floating-point computation with automatic fallback
4//! to exact arithmetic when the result is ambiguous. In practice, 95%+
5//! of predicate evaluations resolve in the fast path.
6//!
7//! Based on Shewchuk's adaptive precision arithmetic (1997).
8//!
9//! CDT (`cdt.rs`) and mesh booleans (`mesh_boolean.rs` in brepkit-operations)
10//! can switch their `orient2d`/`in_circle` calls to these filtered versions
11//! for a significant performance improvement without sacrificing robustness.
12
13#![allow(
14    clippy::suboptimal_flops,
15    clippy::many_single_char_names,
16    clippy::similar_names
17)]
18
19use crate::madd::Madd;
20use crate::vec::{Point2, Point3};
21
22/// Filtered orient2d: fast f64 path with exact fallback.
23///
24/// Returns a positive value if `(a, b, c)` are in counter-clockwise order,
25/// negative if clockwise, and zero if collinear.
26///
27/// Uses error-free transformations to bound the rounding error. If the
28/// computed result is larger than the error bound, the sign is guaranteed
29/// correct. Otherwise, falls back to exact arithmetic.
30#[must_use]
31pub fn filtered_orient2d(a: Point2, b: Point2, c: Point2) -> f64 {
32    let acx = a.x() - c.x();
33    let bcx = b.x() - c.x();
34    let acy = a.y() - c.y();
35    let bcy = b.y() - c.y();
36
37    let det = acx * bcy - acy * bcx;
38
39    // Compute error bound using Shewchuk's method
40    let det_sum = (acx * bcy).abs() + (acy * bcx).abs();
41
42    // The error bound for orient2d: (3 + 16*eps) * eps * |detsum|
43    let eps = f64::EPSILON;
44    let err_bound = (3.0 + 16.0 * eps) * eps * det_sum;
45
46    if det.abs() > err_bound {
47        det
48    } else {
49        // Fall back to exact arithmetic
50        crate::predicates::orient2d(a, b, c)
51    }
52}
53
54/// Filtered orient3d: fast f64 path with exact fallback.
55///
56/// Returns a positive value if `d` is below the plane defined by `(a, b, c)`
57/// (with CCW orientation), negative if above, zero if coplanar.
58#[must_use]
59pub fn filtered_orient3d(a: Point3, b: Point3, c: Point3, d: Point3) -> f64 {
60    let adx = a.x() - d.x();
61    let bdx = b.x() - d.x();
62    let cdx = c.x() - d.x();
63    let ady = a.y() - d.y();
64    let bdy = b.y() - d.y();
65    let cdy = c.y() - d.y();
66    let adz = a.z() - d.z();
67    let bdz = b.z() - d.z();
68    let cdz = c.z() - d.z();
69
70    let det = adx * (bdy * cdz - bdz * cdy) - bdx * (ady * cdz - adz * cdy)
71        + cdx * (ady * bdz - adz * bdy);
72
73    // Error bound for orient3d
74    let permanent = (adx.abs() * ((bdy * cdz).abs() + (bdz * cdy).abs()))
75        + (bdx.abs() * ((ady * cdz).abs() + (adz * cdy).abs()))
76        + (cdx.abs() * ((ady * bdz).abs() + (adz * bdy).abs()));
77
78    let eps = f64::EPSILON;
79    let err_bound = (7.0 + 56.0 * eps) * eps * permanent;
80
81    if det.abs() > err_bound {
82        det
83    } else {
84        crate::predicates::orient3d(a, b, c, d)
85    }
86}
87
88/// Filtered in-circle: fast f64 path with exact fallback.
89///
90/// Returns a positive value if `d` is inside the circumcircle of `(a, b, c)`,
91/// negative if outside, zero if exactly on the circle.
92/// Assumes `(a, b, c)` are in counter-clockwise order.
93#[must_use]
94pub fn filtered_in_circle(a: Point2, b: Point2, c: Point2, d: Point2) -> f64 {
95    let adx = a.x() - d.x();
96    let ady = a.y() - d.y();
97    let bdx = b.x() - d.x();
98    let bdy = b.y() - d.y();
99    let cdx = c.x() - d.x();
100    let cdy = c.y() - d.y();
101
102    let abdet = adx * bdy - bdx * ady;
103    let bcdet = bdx * cdy - cdx * bdy;
104    let cadet = cdx * ady - adx * cdy;
105    let alift = adx * adx + ady * ady;
106    let blift = bdx * bdx + bdy * bdy;
107    let clift = cdx * cdx + cdy * cdy;
108
109    let det = alift * bcdet + blift * cadet + clift * abdet;
110
111    // Error bound for in_circle
112    let permanent = alift * ((bcdet).abs() + (bdx * cdy).abs() + (cdx * bdy).abs())
113        + blift * ((cadet).abs() + (cdx * ady).abs() + (adx * cdy).abs())
114        + clift * ((abdet).abs() + (adx * bdy).abs() + (bdx * ady).abs());
115
116    let eps = f64::EPSILON;
117    let err_bound = (10.0 + 96.0 * eps) * eps * permanent;
118
119    if det.abs() > err_bound {
120        det
121    } else {
122        crate::predicates::in_circle(a, b, c, d)
123    }
124}
125
126// ---------------------------------------------------------------------------
127// Segment intersection
128// ---------------------------------------------------------------------------
129
130/// Result of a 2D segment-segment intersection test.
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub enum SegmentIntersection {
133    /// No intersection.
134    None,
135    /// Segments intersect at a single point.
136    Point {
137        /// The intersection point.
138        point: Point2,
139        /// Parameter on the first segment (0..1).
140        t1: f64,
141        /// Parameter on the second segment (0..1).
142        t2: f64,
143    },
144    /// Segments overlap (collinear) along a range.
145    Overlap {
146        /// Start of the overlap.
147        start: Point2,
148        /// End of the overlap.
149        end: Point2,
150    },
151}
152
153/// Compute the intersection of two 2D line segments using filtered predicates.
154///
155/// Handles all degeneracies: T-intersections, endpoint-on-segment,
156/// collinear overlap, and parallel/disjoint segments.
157///
158/// Uses [`filtered_orient2d`] for robust classification.
159#[must_use]
160#[allow(clippy::too_many_lines)]
161pub fn segment_intersection(a1: Point2, a2: Point2, b1: Point2, b2: Point2) -> SegmentIntersection {
162    // Orient2d tests for segment classification
163    let d1 = filtered_orient2d(a1, a2, b1);
164    let d2 = filtered_orient2d(a1, a2, b2);
165    let d3 = filtered_orient2d(b1, b2, a1);
166    let d4 = filtered_orient2d(b1, b2, a2);
167
168    // Standard crossing test: opposite signs
169    if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0))
170        && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
171    {
172        // Proper crossing: compute intersection point
173        let denom = (a2.x() - a1.x()) * (b2.y() - b1.y()) - (a2.y() - a1.y()) * (b2.x() - b1.x());
174
175        if denom.abs() < f64::EPSILON * 1e3 {
176            return SegmentIntersection::None; // Degenerate
177        }
178
179        let t =
180            ((b1.x() - a1.x()) * (b2.y() - b1.y()) - (b1.y() - a1.y()) * (b2.x() - b1.x())) / denom;
181
182        let u =
183            ((b1.x() - a1.x()) * (a2.y() - a1.y()) - (b1.y() - a1.y()) * (a2.x() - a1.x())) / denom;
184
185        let px = (a2.x() - a1.x()).madd(t, a1.x());
186        let py = (a2.y() - a1.y()).madd(t, a1.y());
187
188        return SegmentIntersection::Point {
189            point: Point2::new(px, py),
190            t1: t,
191            t2: u,
192        };
193    }
194
195    // Check collinear overlap first (all four orientations are zero)
196    if d1 == 0.0 && d2 == 0.0 && d3 == 0.0 && d4 == 0.0 {
197        return collinear_overlap(a1, a2, b1, b2);
198    }
199
200    // Check endpoint-on-segment cases (T-intersections)
201    if d1 == 0.0 && on_segment(a1, a2, b1) {
202        let t = segment_param(a1, a2, b1);
203        return SegmentIntersection::Point {
204            point: b1,
205            t1: t,
206            t2: 0.0,
207        };
208    }
209    if d2 == 0.0 && on_segment(a1, a2, b2) {
210        let t = segment_param(a1, a2, b2);
211        return SegmentIntersection::Point {
212            point: b2,
213            t1: t,
214            t2: 1.0,
215        };
216    }
217    if d3 == 0.0 && on_segment(b1, b2, a1) {
218        let u = segment_param(b1, b2, a1);
219        return SegmentIntersection::Point {
220            point: a1,
221            t1: 0.0,
222            t2: u,
223        };
224    }
225    if d4 == 0.0 && on_segment(b1, b2, a2) {
226        let u = segment_param(b1, b2, a2);
227        return SegmentIntersection::Point {
228            point: a2,
229            t1: 1.0,
230            t2: u,
231        };
232    }
233
234    SegmentIntersection::None
235}
236
237/// Check if point `p` lies on segment `(a, b)` (assuming collinearity).
238fn on_segment(a: Point2, b: Point2, p: Point2) -> bool {
239    let min_x = a.x().min(b.x());
240    let max_x = a.x().max(b.x());
241    let min_y = a.y().min(b.y());
242    let max_y = a.y().max(b.y());
243
244    p.x() >= min_x - f64::EPSILON
245        && p.x() <= max_x + f64::EPSILON
246        && p.y() >= min_y - f64::EPSILON
247        && p.y() <= max_y + f64::EPSILON
248}
249
250/// Compute the parameter of point `p` on segment `(a, b)`.
251fn segment_param(a: Point2, b: Point2, p: Point2) -> f64 {
252    let dx = b.x() - a.x();
253    let dy = b.y() - a.y();
254
255    if dx.abs() > dy.abs() {
256        (p.x() - a.x()) / dx
257    } else if dy.abs() > f64::EPSILON {
258        (p.y() - a.y()) / dy
259    } else {
260        0.0
261    }
262}
263
264/// Handle collinear overlap of two segments.
265fn collinear_overlap(a1: Point2, a2: Point2, b1: Point2, b2: Point2) -> SegmentIntersection {
266    // Project onto the axis with greater extent
267    let dx = (a2.x() - a1.x()).abs().max((b2.x() - b1.x()).abs());
268    let dy = (a2.y() - a1.y()).abs().max((b2.y() - b1.y()).abs());
269
270    let (_ta1, _ta2, tb1_param, tb2_param) = if dx >= dy {
271        let dir = a2.x() - a1.x();
272        if dir.abs() < f64::EPSILON {
273            return SegmentIntersection::None;
274        }
275        (0.0, 1.0, (b1.x() - a1.x()) / dir, (b2.x() - a1.x()) / dir)
276    } else {
277        let dir = a2.y() - a1.y();
278        if dir.abs() < f64::EPSILON {
279            return SegmentIntersection::None;
280        }
281        (0.0, 1.0, (b1.y() - a1.y()) / dir, (b2.y() - a1.y()) / dir)
282    };
283
284    let (tb_lo, tb_hi) = if tb1_param < tb2_param {
285        (tb1_param, tb2_param)
286    } else {
287        (tb2_param, tb1_param)
288    };
289    let lo = 0.0_f64.max(tb_lo);
290    let hi = 1.0_f64.min(tb_hi);
291
292    if lo > hi + f64::EPSILON {
293        SegmentIntersection::None
294    } else if (hi - lo).abs() < f64::EPSILON {
295        // Single point overlap
296        let px = (a2.x() - a1.x()).madd(lo, a1.x());
297        let py = (a2.y() - a1.y()).madd(lo, a1.y());
298        let pt = Point2::new(px, py);
299        SegmentIntersection::Point {
300            point: pt,
301            t1: lo,
302            t2: segment_param(b1, b2, pt),
303        }
304    } else {
305        let sx = (a2.x() - a1.x()).madd(lo, a1.x());
306        let sy = (a2.y() - a1.y()).madd(lo, a1.y());
307        let ex = (a2.x() - a1.x()).madd(hi, a1.x());
308        let ey = (a2.y() - a1.y()).madd(hi, a1.y());
309        SegmentIntersection::Overlap {
310            start: Point2::new(sx, sy),
311            end: Point2::new(ex, ey),
312        }
313    }
314}
315
316#[cfg(test)]
317#[allow(
318    clippy::unwrap_used,
319    clippy::expect_used,
320    clippy::float_cmp,
321    clippy::suboptimal_flops,
322    clippy::panic,
323    clippy::cast_lossless
324)]
325mod tests {
326
327    use super::*;
328    use crate::vec::{Point2, Point3};
329
330    // -- filtered_orient2d -------------------------------------------------
331
332    #[test]
333    fn filtered_orient2d_ccw() {
334        let a = Point2::new(0.0, 0.0);
335        let b = Point2::new(1.0, 0.0);
336        let c = Point2::new(0.0, 1.0);
337        assert!(filtered_orient2d(a, b, c) > 0.0);
338    }
339
340    #[test]
341    fn filtered_orient2d_cw() {
342        let a = Point2::new(0.0, 0.0);
343        let b = Point2::new(0.0, 1.0);
344        let c = Point2::new(1.0, 0.0);
345        assert!(filtered_orient2d(a, b, c) < 0.0);
346    }
347
348    #[test]
349    fn filtered_orient2d_collinear() {
350        let a = Point2::new(0.0, 0.0);
351        let b = Point2::new(1.0, 1.0);
352        let c = Point2::new(2.0, 2.0);
353        assert_eq!(filtered_orient2d(a, b, c), 0.0);
354    }
355
356    #[test]
357    fn filtered_orient2d_near_collinear() {
358        // Points very close to collinear -- should still give correct answer
359        let a = Point2::new(0.0, 0.0);
360        let b = Point2::new(1.0, 1.0);
361        let c = Point2::new(2.0, 2.0 + 1e-15);
362        // The exact predicate should resolve this
363        let result = filtered_orient2d(a, b, c);
364        // c is slightly above the line, so should be positive (CCW)
365        assert!(result >= 0.0);
366    }
367
368    // -- filtered_in_circle ------------------------------------------------
369
370    #[test]
371    fn filtered_in_circle_inside() {
372        let a = Point2::new(0.0, 0.0);
373        let b = Point2::new(1.0, 0.0);
374        let c = Point2::new(0.0, 1.0);
375        let d = Point2::new(0.25, 0.25);
376        assert!(filtered_in_circle(a, b, c, d) > 0.0);
377    }
378
379    #[test]
380    fn filtered_in_circle_outside() {
381        let a = Point2::new(0.0, 0.0);
382        let b = Point2::new(1.0, 0.0);
383        let c = Point2::new(0.0, 1.0);
384        let d = Point2::new(3.0, 3.0);
385        assert!(filtered_in_circle(a, b, c, d) < 0.0);
386    }
387
388    // -- filtered_orient3d -------------------------------------------------
389
390    #[test]
391    fn filtered_orient3d_basic() {
392        let a = Point3::new(0.0, 0.0, 0.0);
393        let b = Point3::new(1.0, 0.0, 0.0);
394        let c = Point3::new(0.0, 1.0, 0.0);
395        // d above the plane => negative (matches robust crate convention)
396        let above = Point3::new(0.0, 0.0, 1.0);
397        assert!(filtered_orient3d(a, b, c, above) < 0.0);
398        // d below the plane => positive
399        let below = Point3::new(0.0, 0.0, -1.0);
400        assert!(filtered_orient3d(a, b, c, below) > 0.0);
401        // d on the plane => zero
402        let on = Point3::new(0.5, 0.5, 0.0);
403        assert_eq!(filtered_orient3d(a, b, c, on), 0.0);
404    }
405
406    // -- segment_intersection ----------------------------------------------
407
408    #[test]
409    fn segment_intersection_crossing() {
410        let a1 = Point2::new(0.0, 0.0);
411        let a2 = Point2::new(1.0, 1.0);
412        let b1 = Point2::new(0.0, 1.0);
413        let b2 = Point2::new(1.0, 0.0);
414
415        match segment_intersection(a1, a2, b1, b2) {
416            SegmentIntersection::Point { point, t1, t2 } => {
417                assert!((point.x() - 0.5).abs() < 1e-10);
418                assert!((point.y() - 0.5).abs() < 1e-10);
419                assert!((t1 - 0.5).abs() < 1e-10);
420                assert!((t2 - 0.5).abs() < 1e-10);
421            }
422            other => panic!("expected Point, got {other:?}"),
423        }
424    }
425
426    #[test]
427    fn segment_intersection_parallel() {
428        let a1 = Point2::new(0.0, 0.0);
429        let a2 = Point2::new(1.0, 0.0);
430        let b1 = Point2::new(0.0, 1.0);
431        let b2 = Point2::new(1.0, 1.0);
432
433        assert_eq!(
434            segment_intersection(a1, a2, b1, b2),
435            SegmentIntersection::None
436        );
437    }
438
439    #[test]
440    fn segment_intersection_t_junction() {
441        let a1 = Point2::new(0.0, 0.0);
442        let a2 = Point2::new(1.0, 0.0);
443        let b1 = Point2::new(0.5, -1.0);
444        let b2 = Point2::new(0.5, 0.0); // endpoint on segment a
445
446        match segment_intersection(a1, a2, b1, b2) {
447            SegmentIntersection::Point { point, .. } => {
448                assert!((point.x() - 0.5).abs() < 1e-10);
449                assert!(point.y().abs() < 1e-10);
450            }
451            other => panic!("expected Point, got {other:?}"),
452        }
453    }
454
455    #[test]
456    fn segment_intersection_collinear_overlap() {
457        let a1 = Point2::new(0.0, 0.0);
458        let a2 = Point2::new(2.0, 0.0);
459        let b1 = Point2::new(1.0, 0.0);
460        let b2 = Point2::new(3.0, 0.0);
461
462        match segment_intersection(a1, a2, b1, b2) {
463            SegmentIntersection::Overlap { start, end } => {
464                assert!((start.x() - 1.0).abs() < 1e-10);
465                assert!((end.x() - 2.0).abs() < 1e-10);
466            }
467            other => panic!("expected Overlap, got {other:?}"),
468        }
469    }
470
471    #[test]
472    fn segment_intersection_disjoint_collinear() {
473        let a1 = Point2::new(0.0, 0.0);
474        let a2 = Point2::new(1.0, 0.0);
475        let b1 = Point2::new(2.0, 0.0);
476        let b2 = Point2::new(3.0, 0.0);
477
478        assert_eq!(
479            segment_intersection(a1, a2, b1, b2),
480            SegmentIntersection::None
481        );
482    }
483
484    #[test]
485    fn segment_intersection_no_intersection() {
486        let a1 = Point2::new(0.0, 0.0);
487        let a2 = Point2::new(1.0, 0.0);
488        let b1 = Point2::new(2.0, 2.0);
489        let b2 = Point2::new(3.0, 3.0);
490
491        assert_eq!(
492            segment_intersection(a1, a2, b1, b2),
493            SegmentIntersection::None
494        );
495    }
496}