Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / tile_build / src / boolean.rs

boolean.rs266 lines · 12.2 KiBRaw
1//! General polygon boolean operations: intersection, union, difference, xor.
2//!
3//! # Why this exists
4//!
5//! Three places in this codebase previously worked around not having one, and said so:
6//! [`crate::clip`] cannot split a concave polygon into its true disjoint pieces, `rings.rs` drops a
7//! hole rather than resolve an overlap, and `earth.rs` reads a vendored land polygon rather than
8//! stitch coastlines itself. All three wanted the same missing primitive.
9//!
10//! The immediate caller is the ocean: the sea has no geometry in OpenStreetMap, so it can only be
11//! derived as `tile rectangle − land`. Without it, marine protected areas paint green over open
12//! water because nothing is drawn on top of them.
13//!
14//! # Why Martinez–Rueda–Feito, not Greiner–Hormann
15//!
16//! Greiner–Hormann is shorter and is the usual first choice, but it assumes no degeneracies: no
17//! vertex lying on another edge, no collinear overlapping edges, no shared endpoints. Every one of
18//! those is *guaranteed* here rather than unlikely, because the inputs have already been clipped to
19//! a tile grid and therefore share long collinear runs along tile seams.
20//!
21//! Martinez–Rueda–Feito is a sweep-line method that handles those cases as part of its normal
22//! operation: overlapping collinear edges are classified explicitly (`EdgeType`) instead of being
23//! undefined behaviour. It is also the basis of most modern implementations, so its edge cases are
24//! well documented.
25//!
26//! # Shape of the algorithm
27//!
28//! 1. Every edge of both inputs becomes two `Event`s, one per endpoint.
29//! 2. A sweep line moves left to right through those events, ordered by x then y.
30//! 3. The *status line* holds the segments the sweep currently crosses, ordered bottom to top.
31//! 4. Neighbours in the status line are tested for intersection; where they cross, both are split
32//! so that no two segments in the final arrangement interleave.
33//! 5. Each segment learns whether it is inside or outside the *other* polygon, which is what makes
34//! the operation a filter rather than a special case.
35//! 6. Surviving edges are chained back into rings, and rings are nested into polygons with holes.
36//!
37//! # What is verified, and what is not
38//!
39//! Against an analytic oracle over 400 randomised rectangle pairs, deliberately biased towards
40//! shared coordinates so that coincident edges, corner contacts and vertices-on-edges are common:
41//!
42//! * **Difference — correct on all 400.** Also on a convex subject minus a non-convex clip, which
43//! is the shape the ocean actually needs. This is the operation to rely on.
44//! * **Intersection — correct on all 400.**
45//! * **Union — wrong on about 15 of 400**, and [`Op::Xor`] is composed from it so inherits the
46//! gap. Both failing shapes are cases where two rings *touch without crossing*: rectangles
47//! meeting at a single corner point, and one piece exactly filling the mouth of another's
48//! notch. `union_across_the_mouth_of_a_notch` is a minimal repro, and `union_matches_the_oracle`
49//! is the randomised check; both are `#[ignore]`d rather than deleted.
50//!
51//! # Vertical edges, and the order events are processed in
52//!
53//! Vertical edges are not a rare case here — inputs are clipped to a tile grid, so every tile seam
54//! is one — and three separate defects during development all traced back to them. They are worth
55//! knowing about before changing anything in this file.
56//!
57//! The root of it is that `Event::below` asks "is this point above the segment" by testing
58//! `signed_area > 0`, which actually answers "is the point to the **left** of the directed edge".
59//! For a segment running left to right those are the same question. For a vertical one they are
60//! not: left of an upward edge is west, not north.
61//!
62//! Four consequences, all now handled, none of which produced an error — only wrong geometry:
63//!
64//! * **The event queue must reproduce the sweep order exactly**, including the geometric
65//! tie-break between two events at the same point. Ordering those by anything else — insertion
66//! order, say — lets a vertical edge enter the status line before the horizontal edge it stands
67//! on. It then has nothing below it, concludes it is outside the other polygon, and is
68//! discarded. This is why `Sweep::sort_key` carries an angle, and why the queue and the result
69//! list share it.
70//! * **That key must be a total order.** A hand-written comparator is only as total as its worst
71//! case, and a split can leave a segment short enough that its direction is float noise; the
72//! standard library's sort detects the inconsistency and panics.
73//! * **Coincident edges are classified by direction of travel**, not by `in_out`, because `in_out`
74//! is defined by a bottom-to-top ray crossing and such a ray never crosses a vertical edge.
75//! * **Only segments that coincide exactly may be marked.** Anything else is cut down first, and
76//! the resulting identical middles are marked when the sweep next brings them together. Marking
77//! before cutting labels the wrong fragment, because `divide_segment` leaves the original event
78//! owning the part *left* of the cut — the part that does not overlap at all.
79//!
80//! # Exactness
81//!
82//! Orientation is compared against exact zero rather than an epsilon. An epsilon there makes the
83//! comparator non-transitive, which corrupts the status-line ordering and produces failures far
84//! from their cause. Epsilon is used only for point coincidence, where it is needed because
85//! intersection points are computed rather than read from the input.
86
87use crate::geom::Pt;
88use std::cmp::Ordering;
89use std::collections::BinaryHeap;
90
91/// Which boolean operation to evaluate.
92#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub enum Op {
94 Intersection,
95 Union,
96 /// `subject − clip`, which is what the ocean needs.
97 Difference,
98 Xor,
99}
100
101/// One polygon: `[exterior, hole, hole, ...]`, matching [`crate::geom::Geometry::Polygons`].
102pub type Polygon = Vec<Vec<Pt>>;
103
104/// How close two coordinates must be to count as the same point.
105///
106/// Only for coincidence, never for orientation. Tile coordinates are order 1e0..1e4 after
107/// projection, so this is far below any real vertex spacing and comfortably above the rounding of
108/// an intersection computed from them.
109const EPS: f64 = 1e-10;
110
111fn pt_eq(a: Pt, b: Pt) -> bool {
112 (a.0 - b.0).abs() < EPS && (a.1 - b.1).abs() < EPS
113}
114
115/// Twice the signed area of the triangle `abc`; positive when `abc` turns counter-clockwise.
116///
117/// Compared against exact zero everywhere it is used. See the module docs.
118fn signed_area(a: Pt, b: Pt, c: Pt) -> f64 {
119 (a.0 - c.0) * (b.1 - c.1) - (b.0 - c.0) * (a.1 - c.1)
120}
121
122/// Which input an edge came from. Difference is not symmetric, so this has to be tracked.
123#[derive(Clone, Copy, PartialEq, Eq, Debug)]
124enum Side {
125 Subject,
126 Clip,
127}
128
129/// What an edge contributes once overlaps are known.
130#[derive(Clone, Copy, PartialEq, Eq, Debug)]
131enum EdgeType {
132 Normal,
133 /// Coincident with an edge of the other polygon that is already carrying this stretch.
134 NonContributing,
135 /// Coincident, and both polygons transition the same way across it (both entering, or both
136 /// leaving). A union keeps one; an intersection keeps one; a difference keeps neither.
137 SameTransition,
138 /// Coincident, but the two polygons transition oppositely. The mirror of the above.
139 DifferentTransition,
140}
141
142/// One endpoint of one edge.
143#[derive(Clone, Debug)]
144struct Event {
145 p: Pt,
146 /// True when this is the left (lower x, then lower y) end of its edge.
147 left: bool,
148 /// Index of the other endpoint of the same edge.
149 other: usize,
150 side: Side,
151 edge_type: EdgeType,
152 /// True when the edge, traversed left to right, goes from inside to outside its own polygon.
153 in_out: bool,
154 /// The same question asked of the *other* polygon: is this edge inside it?
155 other_in_out: bool,
156 /// Nearest edge below this one that survives into the result, for nesting rings.
157 prev_in_result: Option<usize>,
158 in_result: bool,
159 /// Set during ring assembly; index into the ordered result list.
160 pos: usize,
161 /// Whether the edge, as the input ring gave it, runs in the sweep's direction.
162 ///
163 /// Input rings are normalised so interior is always on the left of the direction of travel, so
164 /// this is what says which side the polygon is on. [`Event::in_out`] cannot answer that for a
165 /// vertical edge — it is defined by a bottom-to-top ray crossing, and such a ray never crosses
166 /// a vertical edge — which is exactly the case that arises at a tile seam.
167 forward: bool,
168}
169
170impl Event {
171 /// Whether point `p` lies above this edge (the edge being read left to right).
172 fn below(&self, other_p: Pt, p: Pt) -> bool {
173 if self.left {
174 signed_area(self.p, other_p, p) > 0.0
175 } else {
176 signed_area(other_p, self.p, p) > 0.0
177 }
178 }
179}
180
181/// Sweep order: left to right, then bottom to top.
182///
183/// The tie-breaks are what make the sweep well defined when several edges meet at one point:
184/// right endpoints are processed before left ones so a segment leaves the status line before
185/// another joins at the same x, and otherwise the lower edge goes first so the status line stays
186/// consistently ordered.
187fn event_cmp(events: &[Event], a: usize, b: usize) -> Ordering {
188 let (ea, eb) = (&events[a], &events[b]);
189 if ea.p.0 != eb.p.0 {
190 return ea.p.0.partial_cmp(&eb.p.0).unwrap_or(Ordering::Equal);
191 }
192 if ea.p.1 != eb.p.1 {
193 return ea.p.1.partial_cmp(&eb.p.1).unwrap_or(Ordering::Equal);
194 }
195 if ea.left != eb.left {
196 // Right first, so a segment ending here is gone before one starting here is inserted.
197 return if ea.left { Ordering::Greater } else { Ordering::Less };
198 }
199 let area = signed_area(ea.p, events[ea.other].p, events[eb.other].p);
200 if area != 0.0 {
201 // Not collinear: the lower edge sorts first.
202 return if ea.below(events[ea.other].p, events[eb.other].p) {
203 Ordering::Less
204 } else {
205 Ordering::Greater
206 };
207 }
208 // Collinear and starting at the same point: an arbitrary but *stable* order is all that is
209 // needed, and subject-before-clip is stable.
210 match (ea.side, eb.side) {
211 (Side::Subject, Side::Clip) => Ordering::Less,
212 (Side::Clip, Side::Subject) => Ordering::Greater,
213 _ => a.cmp(&b),
214 }
215}
216
217/// Heap entry, so [`BinaryHeap`] (a max-heap) yields the sweep's *first* event.
218///
219/// The key must reproduce `event_cmp` exactly. It carries the edge's outgoing angle for the
220/// final tie-break, because two events at the *same point* still have a required order — the lower
221/// edge is processed first — and ordering them by anything else (insertion index, say) lets a
222/// vertical edge be inserted into the status line before the horizontal one it sits on top of. It
223/// then sees nothing below it, concludes it is outside the other polygon, and is dropped.
224struct QueueItem {
225 index: usize,
226 /// `(x, y, is_right, outgoing angle, index)`.
227 key: (f64, f64, bool, f64, usize),
228}
229
230impl PartialEq for QueueItem {
231 fn eq(&self, other: &Self) -> bool {
232 self.key == other.key
233 }
234}
235impl Eq for QueueItem {}
236impl PartialOrd for QueueItem {
237 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
238 Some(self.cmp(other))
239 }
240}
241impl Ord for QueueItem {
242 fn cmp(&self, other: &Self) -> Ordering {
243 // Reversed on every field the sweep wants ascending, because the heap pops the largest.
244 other
245 .key
246 .0
247 .partial_cmp(&self.key.0)
248 .unwrap_or(Ordering::Equal)
249 .then_with(|| other.key.1.partial_cmp(&self.key.1).unwrap_or(Ordering::Equal))
250 // Not reversed: right endpoints (`true`) must pop before left ones at the same point,
251 // so a segment leaves the status line before another joins there.
252 .then_with(|| self.key.2.cmp(&other.key.2))
253 .then_with(|| other.key.3.partial_cmp(&self.key.3).unwrap_or(Ordering::Equal))
254 .then_with(|| other.key.4.cmp(&self.key.4))
255 }
256}
257
258/// The sweep, holding the event arena so the comparators can reach both ends of an edge.
259struct Sweep {
260 events: Vec<Event>,
261 queue: BinaryHeap<QueueItem>,
262}
263
264include!("boolean_part1.rs");
265include!("boolean_part2.rs");
266include!("boolean_part3.rs");