Skip to main content

lib_jsl_geometry/algorithms/
polygon_boolean.rs

1//! Boolean operations on simple polygons by the Greiner-Hormann algorithm.
2//!
3//! Both polygons are walked as cyclic vertex lists with their mutual edge intersections
4//! inserted; each intersection is classified as an entry into or exit from the other polygon,
5//! and the result is traced by following one polygon until the next intersection, then
6//! switching to the other. Degenerate configurations (a vertex on the other polygon's boundary,
7//! overlapping collinear edges) are resolved by perturbing the clip polygon by a relative 1e-9,
8//! so results are exact up to that tolerance. Results are counter-clockwise outer boundaries
9//! and clockwise holes. Holes arise in a difference when the clip polygon lies strictly inside
10//! the subject, and in a union when the two polygons enclose a region between them; areas add
11//! up correctly when the holes' negative signed areas are included.
12//!
13//! See the book entry [Convex hulls and polygon booleans](https://jwkunz.github.io/lib_jsl/book/geometry/hulls-booleans.html#the-greinerhormann-algorithm).
14
15/// The boolean operation.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17
18pub enum BooleanOperation {
19    Intersection,
20    Union,
21    /// The subject minus the clip polygon.
22    Difference,
23}
24
25type P = [f64; 2];
26
27fn signed_area(poly: &[P]) -> f64 {
28    (0..poly.len()).map(|k| { let (a, b) = (poly[k], poly[(k + 1) % poly.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>() / 2.0
29}
30
31/// Whether `p` is inside the polygon (even-odd rule).
32pub fn point_in_polygon(p: P, poly: &[P]) -> bool {
33    let mut inside = false;
34    for k in 0..poly.len() {
35        let (a, b) = (poly[k], poly[(k + 1) % poly.len()]);
36        if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
37            inside = !inside;
38        }
39    }
40    inside
41}
42
43#[derive(Clone)]
44
45struct Node {
46    p: P,
47    /// Index of the matching node in the other list, for intersections.
48    neighbour: Option<usize>,
49    entry: bool,
50    visited: bool,
51}
52
53enum Outcome {
54    Degenerate,
55    Crossing(Vec<Node>, Vec<Node>),
56    Disjoint,
57}
58
59/// Inserts the edge intersections into both vertex lists.
60fn build(s: &[P], c: &[P]) -> Outcome {
61    // Must stay well below the perturbation applied on degeneracy.
62    let eps = 1e-12;
63    let mut on_s: Vec<Vec<(f64, usize)>> = vec![Vec::new(); s.len()];
64    let mut on_c: Vec<Vec<(f64, usize)>> = vec![Vec::new(); c.len()];
65    let mut points = Vec::new();
66    for i in 0..s.len() {
67        let (a, b) = (s[i], s[(i + 1) % s.len()]);
68        for j in 0..c.len() {
69            let (p, q) = (c[j], c[(j + 1) % c.len()]);
70            let r = [b[0] - a[0], b[1] - a[1]];
71            let d = [q[0] - p[0], q[1] - p[1]];
72            let denominator = r[0] * d[1] - r[1] * d[0];
73            let scale = (r[0].abs() + r[1].abs()) * (d[0].abs() + d[1].abs());
74            let w = [p[0] - a[0], p[1] - a[1]];
75            if denominator.abs() <= 1e-14 * scale {
76                // Parallel: degenerate only if collinear and overlapping.
77                if (w[0] * r[1] - w[1] * r[0]).abs() <= 1e-12 * scale.max(1e-300) {
78                    let rr = r[0] * r[0] + r[1] * r[1];
79                    let t0 = (w[0] * r[0] + w[1] * r[1]) / rr;
80                    let t1 = ((q[0] - a[0]) * r[0] + (q[1] - a[1]) * r[1]) / rr;
81                    if t0.max(t1) >= -eps && t0.min(t1) <= 1.0 + eps {
82                        return Outcome::Degenerate;
83                    }
84                }
85                continue;
86            }
87            let t = (w[0] * d[1] - w[1] * d[0]) / denominator;
88            let u = (w[0] * r[1] - w[1] * r[0]) / denominator;
89            if t < -eps || t > 1.0 + eps || u < -eps || u > 1.0 + eps {
90                continue;
91            }
92            if t < eps || t > 1.0 - eps || u < eps || u > 1.0 - eps {
93                return Outcome::Degenerate;
94            }
95            let id = points.len();
96            points.push([a[0] + t * r[0], a[1] + t * r[1]]);
97            on_s[i].push((t, id));
98            on_c[j].push((u, id));
99        }
100    }
101    if points.is_empty() {
102        return Outcome::Disjoint;
103    }
104    let make = |poly: &[P], on: &mut [Vec<(f64, usize)>]| -> (Vec<Node>, Vec<Option<usize>>) {
105        let mut nodes = Vec::new();
106        let mut position = vec![None; points.len()];
107        for (k, list) in on.iter_mut().enumerate() {
108            nodes.push(Node { p: poly[k], neighbour: None, entry: false, visited: false });
109            list.sort_by(|x, y| x.0.total_cmp(&y.0));
110            for &(_, id) in list.iter() {
111                position[id] = Some(nodes.len());
112                nodes.push(Node { p: points[id], neighbour: Some(usize::MAX), entry: false, visited: false });
113            }
114        }
115        (nodes, position)
116    };
117    let (mut ns, ps) = make(s, &mut on_s);
118    let (mut nc, pc) = make(c, &mut on_c);
119    for id in 0..points.len() {
120        let (a, b) = (ps[id].expect("inserted"), pc[id].expect("inserted"));
121        ns[a].neighbour = Some(b);
122        nc[b].neighbour = Some(a);
123    }
124    Outcome::Crossing(ns, nc)
125}
126
127fn mark_entries(nodes: &mut [Node], other: &[P], flip: bool) {
128    let mut entry = !point_in_polygon(nodes[0].p, other);
129    for n in nodes.iter_mut().filter(|n| n.neighbour.is_some()) {
130        n.entry = entry != flip;
131        entry = !entry;
132    }
133}
134
135fn trace(mut ns: Vec<Node>, mut nc: Vec<Node>) -> Vec<Vec<P>> {
136    let mut result = Vec::new();
137    while let Some(start) = (0..ns.len()).find(|&i| ns[i].neighbour.is_some() && !ns[i].visited) {
138        let mut polygon = vec![ns[start].p];
139        let (mut on_subject, mut i) = (true, start);
140        loop {
141            let (list, other) = if on_subject { (&mut ns, &mut nc) } else { (&mut nc, &mut ns) };
142            list[i].visited = true;
143            let j = list[i].neighbour.expect("intersection");
144            other[j].visited = true;
145            let forward = list[i].entry;
146            let len = list.len();
147            loop {
148                i = if forward { (i + 1) % len } else { (i + len - 1) % len };
149                polygon.push(list[i].p);
150                if list[i].neighbour.is_some() {
151                    break;
152                }
153            }
154            let j = list[i].neighbour.expect("intersection");
155            on_subject = !on_subject;
156            i = j;
157            let back = if on_subject { &ns } else { &nc };
158            if back[i].visited {
159                break;
160            }
161        }
162        polygon.pop(); // the closing point repeats the start
163        if polygon.len() >= 3 && signed_area(&polygon).abs() > 0.0 {
164            result.push(polygon);
165        }
166    }
167    result
168}
169
170/// Orients traced loops by nesting depth: loops inside an even number of other loops are outer
171/// boundaries (counter-clockwise), the others holes (clockwise).
172fn orient_by_nesting(mut loops: Vec<Vec<P>>) -> Vec<Vec<P>> {
173    let probes: Vec<P> = loops.iter().map(|l| [(l[0][0] + l[1][0]) / 2.0, (l[0][1] + l[1][1]) / 2.0]).collect();
174    let depth: Vec<usize> = (0..loops.len()).map(|i| (0..loops.len()).filter(|&j| j != i && point_in_polygon(probes[i], &loops[j])).count()).collect();
175    for (l, d) in loops.iter_mut().zip(depth) {
176        if (signed_area(l) > 0.0) != d.is_multiple_of(2) {
177            l.reverse();
178        }
179    }
180    loops
181}
182
183/// Applies `operation` to the simple polygons `subject` and `clip` (either orientation).
184pub fn polygon_boolean(subject: &[P], clip: &[P], operation: BooleanOperation) -> Vec<Vec<P>> {
185    if subject.len() < 3 || clip.len() < 3 {
186        return match operation {
187            BooleanOperation::Intersection => Vec::new(),
188            _ if subject.len() >= 3 => vec![subject.to_vec()],
189            BooleanOperation::Union if clip.len() >= 3 => vec![clip.to_vec()],
190            _ => Vec::new(),
191        };
192    }
193    let ccw = |p: &[P]| -> Vec<P> { if signed_area(p) < 0.0 { p.iter().rev().copied().collect() } else { p.to_vec() } };
194    let s = ccw(subject);
195    let mut c = ccw(clip);
196    let scale = s.iter().chain(&c).flat_map(|p| p.iter()).fold(0.0f64, |m, v| m.max(v.abs())).max(1.0);
197    let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
198    for _attempt in 0..20 {
199        match build(&s, &c) {
200            Outcome::Degenerate => {
201                // Nudge the clip polygon off the degeneracy.
202                for p in c.iter_mut() {
203                    for v in p.iter_mut() {
204                        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
205                        *v += 1e-9 * scale * ((seed >> 11) as f64 / (1u64 << 53) as f64 - 0.5);
206                    }
207                }
208            }
209            Outcome::Disjoint => {
210                let s_in_c = point_in_polygon(s[0], &c);
211                let c_in_s = point_in_polygon(c[0], &s);
212                return match operation {
213                    BooleanOperation::Intersection if s_in_c => vec![s],
214                    BooleanOperation::Intersection if c_in_s => vec![c],
215                    BooleanOperation::Intersection => Vec::new(),
216                    BooleanOperation::Union if s_in_c => vec![c],
217                    BooleanOperation::Union if c_in_s => vec![s],
218                    BooleanOperation::Union => vec![s, c],
219                    BooleanOperation::Difference if s_in_c => Vec::new(),
220                    BooleanOperation::Difference if c_in_s => vec![s, c.into_iter().rev().collect()],
221                    BooleanOperation::Difference => vec![s],
222                };
223            }
224            Outcome::Crossing(mut ns, mut nc) => {
225                let (flip_s, flip_c) = match operation {
226                    BooleanOperation::Intersection => (false, false),
227                    BooleanOperation::Union => (true, true),
228                    BooleanOperation::Difference => (true, false),
229                };
230                mark_entries(&mut ns, &c, flip_s);
231                mark_entries(&mut nc, &s, flip_c);
232                return orient_by_nesting(trace(ns, nc));
233            }
234        }
235    }
236    Vec::new()
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use BooleanOperation::*;
243
244    fn area(polys: &[Vec<P>]) -> f64 {
245        polys.iter().map(|p| signed_area(p)).sum()
246    }
247
248    fn square(x: f64, y: f64, side: f64) -> Vec<P> {
249        vec![[x, y], [x + side, y], [x + side, y + side], [x, y + side]]
250    }
251
252    #[test]
253    fn overlapping_squares_satisfy_the_area_identities() {
254        let (a, b) = (square(0.0, 0.0, 2.0), square(1.0, 1.0, 2.0));
255        let inter = polygon_boolean(&a, &b, Intersection);
256        assert_eq!(inter.len(), 1);
257        assert!((area(&inter) - 1.0).abs() < 1e-12);
258        assert!((area(&polygon_boolean(&a, &b, Union)) - 7.0).abs() < 1e-12);
259        assert!((area(&polygon_boolean(&a, &b, Difference)) - 3.0).abs() < 1e-12);
260        assert!((area(&polygon_boolean(&b, &a, Difference)) - 3.0).abs() < 1e-12);
261        // Orientation of the inputs does not matter.
262        let reversed: Vec<P> = b.iter().rev().copied().collect();
263        assert!((area(&polygon_boolean(&a, &reversed, Intersection)) - 1.0).abs() < 1e-12);
264    }
265
266    #[test]
267    fn a_union_can_enclose_a_hole() {
268        // A "C" open to the right, closed off by a rectangle: the gap between them is a hole.
269        let c = vec![[0.0, 0.0], [3.0, 0.0], [3.0, 1.0], [1.0, 1.0], [1.0, 2.0], [3.0, 2.0], [3.0, 3.0], [0.0, 3.0]];
270        let bar = vec![[2.0, 0.5], [4.0, 0.5], [4.0, 2.5], [2.0, 2.5]];
271        let u = polygon_boolean(&c, &bar, Union);
272        let holes: Vec<&Vec<P>> = u.iter().filter(|p| signed_area(p) < 0.0).collect();
273        assert_eq!((u.len(), holes.len()), (2, 1));
274        assert!((signed_area(holes[0]) + 1.0).abs() < 1e-9);
275        assert!((area(&u) - 10.0).abs() < 1e-9);
276    }
277
278    #[test]
279    fn concave_shapes_split_into_several_pieces() {
280        // A U shape cut by a horizontal bar through both arms: two pieces.
281        let u = vec![[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [2.0, 3.0], [2.0, 1.0], [1.0, 1.0], [1.0, 3.0], [0.0, 3.0]];
282        let bar = vec![[-1.0, 2.0], [4.0, 2.0], [4.0, 2.5], [-1.0, 2.5]];
283        let pieces = polygon_boolean(&u, &bar, Intersection);
284        assert_eq!(pieces.len(), 2);
285        assert!((area(&pieces) - 1.0).abs() < 1e-12);
286        let (au, ab) = (signed_area(&u), signed_area(&bar));
287        let union = area(&polygon_boolean(&u, &bar, Union));
288        assert!((union - (au + ab - 1.0)).abs() < 1e-9, "{union}");
289        assert!((area(&polygon_boolean(&u, &bar, Difference)) - (au - 1.0)).abs() < 1e-9);
290    }
291
292    #[test]
293    fn nested_disjoint_and_degenerate_cases() {
294        let (outer, inner, far) = (square(0.0, 0.0, 4.0), square(1.0, 1.0, 1.0), square(10.0, 10.0, 1.0));
295        assert!((area(&polygon_boolean(&outer, &inner, Intersection)) - 1.0).abs() < 1e-12);
296        assert!((area(&polygon_boolean(&outer, &inner, Union)) - 16.0).abs() < 1e-12);
297        let holed = polygon_boolean(&outer, &inner, Difference);
298        assert!(holed.len() == 2 && (area(&holed) - 15.0).abs() < 1e-12);
299        assert!(polygon_boolean(&outer, &far, Intersection).is_empty());
300        assert!((area(&polygon_boolean(&outer, &far, Union)) - 17.0).abs() < 1e-12);
301        // Shared edges and vertices are handled by perturbation.
302        let (left, right) = (square(0.0, 0.0, 1.0), square(1.0, 0.0, 1.0));
303        assert!((area(&polygon_boolean(&left, &right, Union)) - 2.0).abs() < 1e-8);
304        assert!(area(&polygon_boolean(&left, &right, Intersection)).abs() < 1e-8);
305        let corner = square(1.0, 1.0, 1.0);
306        assert!((area(&polygon_boolean(&left, &corner, Union)) - 2.0).abs() < 1e-8);
307        let same = polygon_boolean(&left, &left, Intersection);
308        assert!((area(&same) - 1.0).abs() < 1e-8);
309    }
310}