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

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

boolean_part1.rs480 lines · 20.1 KiBRaw
1impl Sweep {
2 fn new() -> Sweep {
3 Sweep { events: Vec::new(), queue: BinaryHeap::new() }
4 }
5
6 /// The sweep's total order over events, as a comparable key.
7 ///
8 /// One key shared by the queue and by the result sort, for two reasons. The algorithm wants
9 /// both to agree — the ring walk steps between neighbouring result entries and relies on them
10 /// being in the order the sweep produced. And a lexicographic key over scalars is a *total*
11 /// order by construction, where a hand-written comparator is only as total as its worst case:
12 /// a split can leave a segment short enough that its direction is float noise, and the standard
13 /// library's sort detects the resulting inconsistency and panics.
14 fn sort_key(&self, index: usize) -> (f64, f64, bool, f64, usize) {
15 let e = &self.events[index];
16 let o = self.events[e.other].p;
17 // The direction the edge leaves this endpoint in. Two events at one point are ordered by
18 // it, smallest first, which puts the lower edge into the status line first: a rightward
19 // horizontal is angle 0, a vertical going up is pi/2, so the horizontal is processed first
20 // and the vertical lands above it rather than below everything.
21 let angle = (o.1 - e.p.1).atan2(o.0 - e.p.0);
22 (e.p.0, e.p.1, !e.left, angle, index)
23 }
24
25 fn push_queue(&mut self, index: usize) {
26 let key = self.sort_key(index);
27 self.queue.push(QueueItem { index, key });
28 }
29
30 /// Add both endpoints of one edge.
31 fn add_edge(&mut self, a: Pt, b: Pt, side: Side) {
32 if pt_eq(a, b) {
33 return; // A zero-length edge carries no boundary.
34 }
35 let ia = self.events.len();
36 let ib = ia + 1;
37 let a_is_left = match a.0.partial_cmp(&b.0) {
38 Some(Ordering::Less) => true,
39 Some(Ordering::Greater) => false,
40 _ => a.1 < b.1,
41 };
42 self.events.push(Event {
43 p: a,
44 left: a_is_left,
45 other: ib,
46 side,
47 edge_type: EdgeType::Normal,
48 in_out: false,
49 other_in_out: false,
50 prev_in_result: None,
51 in_result: false,
52 pos: 0,
53 forward: a_is_left,
54 });
55 self.events.push(Event {
56 p: b,
57 left: !a_is_left,
58 other: ia,
59 side,
60 edge_type: EdgeType::Normal,
61 in_out: false,
62 other_in_out: false,
63 prev_in_result: None,
64 in_result: false,
65 pos: 0,
66 forward: a_is_left,
67 });
68 self.push_queue(ia);
69 self.push_queue(ib);
70 }
71
72 fn add_polygons(&mut self, polys: &[Polygon], side: Side) {
73 for poly in polys {
74 for (at, ring) in poly.iter().enumerate() {
75 if ring.len() < 3 {
76 continue;
77 }
78 // Tolerate both closed and open rings.
79 let closed = pt_eq(ring[0], ring[ring.len() - 1]);
80 let n = if closed { ring.len() - 1 } else { ring.len() };
81 if n < 3 {
82 continue;
83 }
84 // Normalised so the interior is always to the left of the direction of travel:
85 // counter-clockwise for an exterior, clockwise for a hole. The input makes no
86 // promise about winding, and without this `forward` would mean nothing.
87 let oriented = orient(ring[..n].to_vec(), at == 0);
88 for i in 0..n {
89 self.add_edge(oriented[i], oriented[(i + 1) % n], side);
90 }
91 }
92 }
93 }
94
95 /// Order two segments as the status line sees them: bottom to top at the sweep's x.
96 fn segment_cmp(&self, a: usize, b: usize) -> Ordering {
97 if a == b {
98 return Ordering::Equal;
99 }
100 let (ea, eb) = (&self.events[a], &self.events[b]);
101 let (oa, ob) = (self.events[ea.other].p, self.events[eb.other].p);
102 if signed_area(ea.p, oa, eb.p) != 0.0 || signed_area(ea.p, oa, ob) != 0.0 {
103 // Not collinear.
104 if pt_eq(ea.p, eb.p) {
105 return if ea.below(oa, ob) { Ordering::Less } else { Ordering::Greater };
106 }
107 // Whichever segment starts first is the one whose line the other is measured against.
108 // Getting this pair the wrong way round is subtly wrong for sloped segments and badly
109 // wrong for vertical ones, because `below` really answers "is the point LEFT of the
110 // directed edge" and left of an upward vertical is west, not north.
111 if event_cmp(&self.events, a, b) == Ordering::Less {
112 return if ea.below(oa, eb.p) { Ordering::Less } else { Ordering::Greater };
113 }
114 return if eb.below(ob, ea.p) { Ordering::Greater } else { Ordering::Less };
115 }
116 // Collinear: keep subject below clip so the order is total and stable.
117 if ea.side != eb.side {
118 return if ea.side == Side::Subject { Ordering::Less } else { Ordering::Greater };
119 }
120 if pt_eq(ea.p, eb.p) {
121 return a.cmp(&b);
122 }
123 event_cmp(&self.events, a, b)
124 }
125
126 /// Decide what an edge is inside, from the edge below it in the status line.
127 fn compute_fields(&mut self, index: usize, below: Option<usize>) {
128 match below {
129 None => {
130 // Nothing below: outside both polygons, so this edge enters its own.
131 self.events[index].in_out = false;
132 self.events[index].other_in_out = true;
133 }
134 Some(b) => {
135 if self.events[index].side == self.events[b].side {
136 // Same polygon: the transition flips, the other polygon's state carries over.
137 self.events[index].in_out = !self.events[b].in_out;
138 self.events[index].other_in_out = self.events[b].other_in_out;
139 } else {
140 // Crossing into the other polygon: the roles swap.
141 self.events[index].in_out = !self.events[b].other_in_out;
142 self.events[index].other_in_out = if self.is_vertical(b) {
143 !self.events[b].in_out
144 } else {
145 self.events[b].in_out
146 };
147 }
148 // Nearest surviving edge below, for nesting later.
149 self.events[index].prev_in_result =
150 if !self.events[b].in_result || self.is_vertical(b) {
151 self.events[b].prev_in_result
152 } else {
153 Some(b)
154 };
155 }
156 }
157 }
158
159 fn in_result(&self, index: usize, op: Op) -> bool {
160 let e = &self.events[index];
161 match e.edge_type {
162 EdgeType::Normal => match op {
163 Op::Intersection => !e.other_in_out,
164 Op::Union => e.other_in_out,
165 Op::Difference => {
166 (e.side == Side::Subject && e.other_in_out)
167 || (e.side == Side::Clip && !e.other_in_out)
168 }
169 Op::Xor => true,
170 },
171 // Of two coincident edges only one may survive, and only for the ops where a shared
172 // boundary is still a boundary of the answer.
173 EdgeType::SameTransition => matches!(op, Op::Intersection | Op::Union),
174 EdgeType::DifferentTransition => op == Op::Difference,
175 EdgeType::NonContributing => false,
176 }
177 }
178
179 /// Split an edge at `p`, so the arrangement has no partially overlapping segments.
180 fn divide_segment(&mut self, index: usize, p: Pt) {
181 let other = self.events[index].other;
182 let side = self.events[index].side;
183 // Both halves run the same way as the edge they came from.
184 let forward = self.events[index].forward;
185
186 let right_of_left = self.events.len(); // new right endpoint for the left half
187 self.events.push(Event {
188 p,
189 left: false,
190 other: index,
191 side,
192 edge_type: EdgeType::Normal,
193 in_out: false,
194 other_in_out: false,
195 prev_in_result: None,
196 in_result: false,
197 pos: 0,
198 forward,
199 });
200 let left_of_right = self.events.len(); // new left endpoint for the right half
201 self.events.push(Event {
202 p,
203 left: true,
204 other,
205 side,
206 edge_type: EdgeType::Normal,
207 in_out: false,
208 other_in_out: false,
209 prev_in_result: None,
210 in_result: false,
211 pos: 0,
212 forward,
213 });
214
215 self.events[index].other = right_of_left;
216 self.events[other].other = left_of_right;
217
218 self.push_queue(right_of_left);
219 self.push_queue(left_of_right);
220 }
221
222 /// Test two status-line neighbours, splitting them where they meet.
223 ///
224 /// Returns true when the pair turned out to be collinear and overlapping, because the caller
225 /// must then not treat them as an ordinary crossing.
226 fn possible_intersection(&mut self, a: usize, b: usize) -> bool {
227 let (a1, a2) = (self.events[a].p, self.events[self.events[a].other].p);
228 let (b1, b2) = (self.events[b].p, self.events[self.events[b].other].p);
229
230 let (count, ip1, _ip2) = intersect(a1, a2, b1, b2);
231 if count == 0 {
232 return false;
233 }
234 if count == 1 {
235 // A single crossing. Split whichever segments do not already end there.
236 if !pt_eq(a1, ip1) && !pt_eq(a2, ip1) {
237 self.divide_segment(a, ip1);
238 }
239 if !pt_eq(b1, ip1) && !pt_eq(b2, ip1) {
240 self.divide_segment(b, ip1);
241 }
242 return false;
243 }
244
245 // Collinear overlap — the case Greiner-Hormann cannot express, and the normal case at a
246 // tile seam.
247 if self.events[a].side == self.events[b].side {
248 // Two edges of the *same* polygon lying on each other: degenerate input. Leave them;
249 // the in/out bookkeeping cancels them out.
250 return true;
251 }
252
253 // Only segments that coincide *exactly* can be marked, because marking is a statement about
254 // one shared stretch. Anything else is first cut down until the overlapping middles do
255 // coincide, and those get marked when the sweep next brings them together. Marking before
256 // cutting labels the wrong fragment — `divide_segment` leaves `a` as the part to the left
257 // of the cut, which is the part that does not overlap at all.
258 let (ar, br) = (self.events[a].other, self.events[b].other);
259 let left_shared = pt_eq(self.events[a].p, self.events[b].p);
260 let right_shared = pt_eq(self.events[ar].p, self.events[br].p);
261
262 if left_shared && right_shared {
263 // Exactly the same stretch. One carries it, the other goes silent.
264 let same = self.events[a].forward == self.events[b].forward;
265 self.events[a].edge_type = EdgeType::NonContributing;
266 self.events[b].edge_type =
267 if same { EdgeType::SameTransition } else { EdgeType::DifferentTransition };
268 return true;
269 }
270
271 if left_shared {
272 // Same start, different lengths: mark the shared start-to-shorter-end stretch, then
273 // cut the longer one there so the remainder is an ordinary segment.
274 let a_first = self.sort_key(ar) < self.sort_key(br);
275 let (shorter_end, longer) = if a_first { (ar, b) } else { (br, a) };
276 let same = self.events[a].forward == self.events[b].forward;
277 self.events[a].edge_type = EdgeType::NonContributing;
278 self.events[b].edge_type =
279 if same { EdgeType::SameTransition } else { EdgeType::DifferentTransition };
280 let at = self.events[shorter_end].p;
281 self.divide_segment(longer, at);
282 return true;
283 }
284
285 if right_shared {
286 // Same end: cut the one that starts earlier at the other's start.
287 let a_first = self.sort_key(a) < self.sort_key(b);
288 let (earlier, at) =
289 if a_first { (a, self.events[b].p) } else { (b, self.events[a].p) };
290 self.divide_segment(earlier, at);
291 return true;
292 }
293
294 // No shared endpoint. Either one segment contains the other, or they stagger.
295 let a_starts_first = self.sort_key(a) < self.sort_key(b);
296 let (first, second) = if a_starts_first { (a, b) } else { (b, a) };
297 let (first_end, second_end) = if a_starts_first { (ar, br) } else { (br, ar) };
298 if self.sort_key(second_end) < self.sort_key(first_end) {
299 // `first` swallows `second`: cut it at both of `second`'s ends. After the first cut,
300 // the piece carrying the far end is reachable through that end's partner.
301 let (lo, hi) = (self.events[second].p, self.events[second_end].p);
302 self.divide_segment(first, lo);
303 let right_piece = self.events[first_end].other;
304 self.divide_segment(right_piece, hi);
305 } else {
306 // Staggered: cut each at the other's inner endpoint.
307 let lo = self.events[second].p;
308 let hi = self.events[first_end].p;
309 self.divide_segment(first, lo);
310 self.divide_segment(second, hi);
311 }
312 true
313 }
314
315 fn run(&mut self, op: Op) -> Vec<Polygon> {
316 // The status line: indices of left events whose segments the sweep currently crosses,
317 // ordered bottom to top. A sorted `Vec` rather than a balanced tree — insertion is O(n),
318 // but n is the number of segments crossing one vertical line, which for tile-sized input is
319 // small, and the constant factor of a flat array beats the pointer chasing.
320 let mut status: Vec<usize> = Vec::new();
321 let mut done: Vec<usize> = Vec::new();
322
323 while let Some(item) = self.queue.pop() {
324 let index = item.index;
325 if self.events[index].left {
326 let at = status.partition_point(|&s| self.segment_cmp(s, index) == Ordering::Less);
327 status.insert(at, index);
328 let below = if at > 0 { Some(status[at - 1]) } else { None };
329 let above = status.get(at + 1).copied();
330 self.compute_fields(index, below);
331
332 if let Some(nx) = above {
333 if self.possible_intersection(index, nx) {
334 // Recompute: the overlap classification changed what these edges mean.
335 self.compute_fields(index, below);
336 let at2 = status.iter().position(|&s| s == nx);
337 if let Some(at2) = at2 {
338 let b2 = if at2 > 0 { Some(status[at2 - 1]) } else { None };
339 self.compute_fields(nx, b2);
340 }
341 }
342 }
343 if let Some(pv) = below {
344 if self.possible_intersection(pv, index) {
345 let at2 = status.iter().position(|&s| s == index);
346 if let Some(at2) = at2 {
347 let b2 = if at2 > 0 { Some(status[at2 - 1]) } else { None };
348 self.compute_fields(index, b2);
349 }
350 }
351 }
352 } else {
353 // Right endpoint: its partner leaves the status line, and the neighbours it was
354 // separating become adjacent and must be tested against each other.
355 let left = self.events[index].other;
356 if let Some(at) = status.iter().position(|&s| s == left) {
357 let below = if at > 0 { Some(status[at - 1]) } else { None };
358 let above = status.get(at + 1).copied();
359 done.push(left);
360 status.remove(at);
361 if let (Some(pv), Some(nx)) = (below, above) {
362 self.possible_intersection(pv, nx);
363 }
364 } else {
365 // Its left event was already taken out of the status line by a split. The edge
366 // still contributes — dropping it here silently loses a side of the answer,
367 // which is how a square came back as a triangle.
368 done.push(left);
369 }
370 }
371 }
372
373
374 self.connect(done, op)
375 }
376
377 /// Chain surviving edges into rings, then nest rings into polygons.
378 fn connect(&mut self, done: Vec<usize>, op: Op) -> Vec<Polygon> {
379 // Survival is decided here rather than as each edge leaves the sweep. An edge's
380 // `other_in_out` can still be rewritten by a later `possible_intersection` between its old
381 // neighbours, so asking during the sweep reads a field that is not final yet.
382 for &e in &done {
383 self.events[e].in_result = self.in_result(e, op);
384 }
385
386 // Both endpoints of every surviving edge, in sweep order. A ring is then walked by
387 // stepping to the far end of an edge and then to whichever other edge shares that point.
388 let mut result: Vec<usize> = Vec::new();
389 for &e in &done {
390 if self.events[e].in_result {
391 result.push(e);
392 result.push(self.events[e].other);
393 }
394 }
395 if result.is_empty() {
396 return Vec::new();
397 }
398 result.sort_by(|&a, &b| {
399 let (ka, kb) = (self.sort_key(a), self.sort_key(b));
400 ka.0
401 .total_cmp(&kb.0)
402 .then_with(|| ka.1.total_cmp(&kb.1))
403 // Right endpoints first at a shared point, as in the queue.
404 .then_with(|| kb.2.cmp(&ka.2))
405 .then_with(|| ka.3.total_cmp(&kb.3))
406 .then_with(|| ka.4.cmp(&kb.4))
407 });
408 for (i, &e) in result.iter().enumerate() {
409 self.events[e].pos = i;
410 }
411
412 let mut used = vec![false; result.len()];
413 let mut rings: Vec<Vec<Pt>> = Vec::new();
414
415 for start in 0..result.len() {
416 if used[start] {
417 continue;
418 }
419 let mut ring: Vec<Pt> = vec![self.events[result[start]].p];
420 let mut pos = start;
421 loop {
422 used[pos] = true;
423 // The far end of the edge at `pos`.
424 pos = self.events[self.events[result[pos]].other].pos;
425 used[pos] = true;
426 ring.push(self.events[result[pos]].p);
427 match self.next_unused(&result, &used, pos, start) {
428 Some(next) => pos = next,
429 None => break,
430 }
431 }
432 // The walk returns to its start, so the closing duplicate is dropped.
433 if ring.len() > 1 && pt_eq(ring[0], ring[ring.len() - 1]) {
434 ring.pop();
435 }
436 if ring.len() >= 3 {
437 rings.push(ring);
438 }
439 }
440
441 assemble(rings)
442 }
443
444 /// The next unused entry sharing `pos`'s point, searched forward then back.
445 ///
446 /// Bounded below by `start` so a walk cannot wander into a ring that has already been closed.
447 fn next_unused(
448 &self,
449 result: &[usize],
450 used: &[bool],
451 pos: usize,
452 start: usize,
453 ) -> Option<usize> {
454 let p = self.events[result[pos]].p;
455 let mut i = pos + 1;
456 while i < result.len() && pt_eq(self.events[result[i]].p, p) {
457 if !used[i] {
458 return Some(i);
459 }
460 i += 1;
461 }
462 let mut j = pos;
463 while j > start {
464 j -= 1;
465 if !pt_eq(self.events[result[j]].p, p) {
466 return None;
467 }
468 if !used[j] {
469 return Some(j);
470 }
471 }
472 None
473 }
474
475 /// A segment with no horizontal extent, which `compute_fields` must not treat as a crossing.
476 fn is_vertical(&self, index: usize) -> bool {
477 self.events[index].p.0 == self.events[self.events[index].other].p.0
478 }
479
480}