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

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

clip.rs319 lines · 11.3 KiBRaw
1//! Clipping geometry to a tile's buffered rect.
2//!
3//! Two different algorithms, because lines and polygons need different answers
4//! from a clip:
5//!
6//! * **Lines use Liang-Barsky.** A polyline crossing a tile can leave and re-enter
7//! it, so one input line yields **N output lines** -- the clip is a partition,
8//! not a truncation. Joining the pieces back up would draw a road straight
9//! across a bay it actually goes around.
10//! * **Polygons use Sutherland-Hodgman.** A polygon must stay a closed area after
11//! clipping, so the parts of the tile boundary that bound the clipped shape have
12//! to become real edges. Liang-Barsky would give a set of disconnected arcs with
13//! no interior.
14//!
15//! ## What Sutherland-Hodgman does and does not do
16//!
17//! It clips against each of the four half-planes in turn, and it is exact for a
18//! convex polygon. For a **concave** polygon whose clipped result is two or more
19//! disjoint pieces, it returns a single ring joined by a degenerate sliver running
20//! along the boundary. That sliver has zero area, so a scanline rasteriser fills
21//! the right pixels, but it is one ring where a strict result would be two, and
22//! that is not free: earcut cannot triangulate a self-touching ring reliably (see
23//! `library/map/src/main/rust/src/tess/fill.rs`), so the renderer is left doing
24//! the repair. Splitting them requires a general polygon clipper (Vatti or
25//! Greiner-Hormann), which is a large piece of work. Documented here rather than
26//! pretended away.
27//!
28//! ## Clip-introduced vertices are never removed
29//!
30//! A crossing this module interpolates is not in the source, so no annotation pass
31//! measured it: it comes out of [`crate::geom::Vertex::boundary`] with significance
32//! [`crate::geom::ALWAYS`]. That is what holds an exterior and a hole that both
33//! reach the same tile edge to the same vertices along it. Thinning those two
34//! coincident edges independently is what used to push a hole out through its own
35//! exterior.
36//!
37//! ## The `NaN` question
38//!
39//! Both algorithms compare and divide. A non-finite vertex would make every
40//! comparison false and could emit a `NaN` intersection, which
41//! [`crate::geom::quantize`] then turns into a vertex at the tile origin. So
42//! non-finite vertices are dropped on the way in; [`crate::geom::project`] clamps,
43//! so they should not arise, but the clipper is the last place that can still tell
44//! the difference between "outside" and "unknown".
45
46use crate::geom::{Geometry, Pt, Rect, Vertex};
47
48/// Clip a geometry to `rect`, in the same coordinate space as the input.
49///
50/// Points are kept or dropped whole; lines are partitioned; polygon rings are
51/// clipped into new rings. Parts that vanish entirely are removed, so an empty
52/// result means the geometry does not touch the rect at all.
53pub fn clip_geometry<V: Vertex>(g: &Geometry<V>, rect: &Rect) -> Geometry<V> {
54 match g {
55 Geometry::Points(pts) => Geometry::Points(
56 pts.iter()
57 .copied()
58 .filter(|p| finite(*p) && rect.contains(p.xy()))
59 .collect(),
60 ),
61 Geometry::Lines(lines) => {
62 let mut out = Vec::new();
63 for line in lines {
64 out.extend(clip_line(line, rect));
65 }
66 Geometry::Lines(out)
67 }
68 Geometry::Polygons(polys) => {
69 let mut out = Vec::new();
70 for rings in polys {
71 let clipped = clip_polygon(rings, rect);
72 if !clipped.is_empty() {
73 out.push(clipped);
74 }
75 }
76 Geometry::Polygons(out)
77 }
78 }
79}
80
81fn finite<V: Vertex>(v: V) -> bool {
82 let (x, y) = v.xy();
83 x.is_finite() && y.is_finite()
84}
85
86/// Clip one polyline, returning the pieces that fall inside `rect`.
87///
88/// Consecutive segments that survive the clip and still meet are welded back into
89/// one output line; a gap starts a new one. That is what makes the result a
90/// partition of the original rather than a bag of segments.
91pub fn clip_line<V: Vertex>(line: &[V], rect: &Rect) -> Vec<Vec<V>> {
92 let mut out: Vec<Vec<V>> = Vec::new();
93 let mut current: Vec<V> = Vec::new();
94
95 for w in line.windows(2) {
96 let (a, b) = (w[0], w[1]);
97 if !finite(a) || !finite(b) {
98 // Break the run: welding across a dropped vertex would invent an edge.
99 if current.len() > 1 {
100 out.push(std::mem::take(&mut current));
101 } else {
102 current.clear();
103 }
104 continue;
105 }
106 match clip_segment(a, b, rect) {
107 None => {
108 if current.len() > 1 {
109 out.push(std::mem::take(&mut current));
110 } else {
111 current.clear();
112 }
113 }
114 Some((ca, cb)) => {
115 // By position, not by vertex: the near end of this segment and the
116 // far end of the last are the same place but need not be the same
117 // vertex -- one may be a source vertex and the other a crossing.
118 if current.last().map(|v| v.xy()) == Some(ca.xy()) {
119 current.push(cb);
120 } else {
121 if current.len() > 1 {
122 out.push(std::mem::take(&mut current));
123 } else {
124 current.clear();
125 }
126 current.push(ca);
127 current.push(cb);
128 }
129 }
130 }
131 }
132 if current.len() > 1 {
133 out.push(current);
134 }
135 out
136}
137
138/// Liang-Barsky: clip the segment `a -> b` to `rect`.
139///
140/// Returns the surviving sub-segment, or `None` when the segment misses the rect.
141/// The algorithm narrows a parameter interval `[t0, t1]` along the segment against
142/// each of the four boundaries; the segment is outside as soon as the interval
143/// closes.
144///
145/// An endpoint the interval did not move is returned as itself, significance and
146/// all; an endpoint it did move is a new vertex on the boundary.
147///
148/// A non-finite endpoint is `None`. Every comparison below would be false for a
149/// `NaN`, so it would fall through as "inside" and emit a `NaN` intersection.
150pub fn clip_segment<V: Vertex>(a: V, b: V, rect: &Rect) -> Option<(V, V)> {
151 if !finite(a) || !finite(b) {
152 return None;
153 }
154 let (ax, ay) = a.xy();
155 let (bx, by) = b.xy();
156 let (dx, dy) = (bx - ax, by - ay);
157 let mut t0 = 0.0f64;
158 let mut t1 = 1.0f64;
159
160 // Each boundary is `p * t <= q`, where p is the direction component and q the
161 // distance to the boundary.
162 for &(p, q) in &[
163 (-dx, ax - rect.min_x),
164 (dx, rect.max_x - ax),
165 (-dy, ay - rect.min_y),
166 (dy, rect.max_y - ay),
167 ] {
168 if p == 0.0 {
169 // Parallel to this boundary: inside iff already on the right side.
170 if q < 0.0 {
171 return None;
172 }
173 continue;
174 }
175 let t = q / p;
176 if p < 0.0 {
177 // Entering: raise the lower bound.
178 if t > t1 {
179 return None;
180 }
181 if t > t0 {
182 t0 = t;
183 }
184 } else {
185 // Leaving: lower the upper bound.
186 if t < t0 {
187 return None;
188 }
189 if t < t1 {
190 t1 = t;
191 }
192 }
193 }
194 let at = |t: f64| (ax + t * dx, ay + t * dy);
195 Some((
196 if t0 == 0.0 { a } else { V::boundary(at(t0)) },
197 if t1 == 1.0 { b } else { V::boundary(at(t1)) },
198 ))
199}
200
201/// Clip a polygon's rings to `rect`.
202///
203/// A ring that clips away entirely is dropped. If the **exterior** ring
204/// disappears the whole polygon does, holes included: a hole with no surrounding
205/// area is not a shape, and emitting one would render as a solid patch of the
206/// wrong colour.
207pub fn clip_polygon<V: Vertex>(rings: &[Vec<V>], rect: &Rect) -> Vec<Vec<V>> {
208 let mut out: Vec<Vec<V>> = Vec::new();
209 for (i, ring) in rings.iter().enumerate() {
210 let clipped = clip_ring(ring, rect);
211 if clipped.len() < 3 {
212 if i == 0 {
213 return Vec::new();
214 }
215 continue;
216 }
217 out.push(clipped);
218 }
219 out
220}
221
222/// Sutherland-Hodgman: clip one ring against the four boundaries in turn.
223///
224/// The caller's closure convention is preserved: an explicitly closed ring
225/// (first == last) is normalised on the way in and re-closed on the way out with a
226/// **copy of the surviving first vertex**, so the two carry the same significance
227/// and no later filter can open the ring by keeping one and dropping the other. An
228/// unclosed ring stays unclosed. Fewer than three distinct vertices out means the
229/// ring did not survive.
230pub fn clip_ring<V: Vertex>(ring: &[V], rect: &Rect) -> Vec<V> {
231 let was_closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
232 let open: Vec<V> = ring[..ring.len() - usize::from(was_closed)]
233 .iter()
234 .copied()
235 .filter(|p| finite(*p))
236 .collect();
237 if open.len() < 3 {
238 return Vec::new();
239 }
240
241 let mut current = open;
242 for edge in [
243 Edge::Left(rect.min_x),
244 Edge::Right(rect.max_x),
245 Edge::Bottom(rect.min_y),
246 Edge::Top(rect.max_y),
247 ] {
248 if current.len() < 3 {
249 return Vec::new();
250 }
251 let mut next: Vec<V> = Vec::with_capacity(current.len() + 4);
252 for i in 0..current.len() {
253 let a = current[(i + current.len() - 1) % current.len()];
254 let b = current[i];
255 let (a_in, b_in) = (edge.inside(a.xy()), edge.inside(b.xy()));
256 if b_in {
257 // Entering: the crossing comes first, then the vertex itself.
258 if !a_in {
259 next.push(V::boundary(edge.intersect(a.xy(), b.xy())));
260 }
261 next.push(b);
262 } else if a_in {
263 // Leaving: only the crossing.
264 next.push(V::boundary(edge.intersect(a.xy(), b.xy())));
265 }
266 }
267 current = next;
268 }
269
270 // The clip can put two crossings on the same boundary point.
271 current.dedup_by(|a, b| a.xy() == b.xy());
272 if current.len() > 1 && current.first().map(|v| v.xy()) == current.last().map(|v| v.xy()) {
273 current.pop();
274 }
275 if current.len() < 3 {
276 return Vec::new();
277 }
278 if was_closed {
279 let first = current[0];
280 current.push(first);
281 }
282 current
283}
284
285/// Which side of a boundary a vertex is on, and where an edge crosses it.
286#[derive(Clone, Copy)]
287enum Edge {
288 Left(f64),
289 Right(f64),
290 Bottom(f64),
291 Top(f64),
292}
293
294impl Edge {
295 fn inside(self, (x, y): Pt) -> bool {
296 match self {
297 Edge::Left(v) => x >= v,
298 Edge::Right(v) => x <= v,
299 Edge::Bottom(v) => y >= v,
300 Edge::Top(v) => y <= v,
301 }
302 }
303
304 /// Where `a -> b` crosses this boundary. Only called when the two vertices are
305 /// on opposite sides, so the denominator cannot be zero.
306 fn intersect(self, a: Pt, b: Pt) -> Pt {
307 match self {
308 Edge::Left(v) | Edge::Right(v) => {
309 let t = (v - a.0) / (b.0 - a.0);
310 (v, a.1 + t * (b.1 - a.1))
311 }
312 Edge::Bottom(v) | Edge::Top(v) => {
313 let t = (v - a.1) / (b.1 - a.1);
314 (a.0 + t * (b.0 - a.0), v)
315 }
316 }
317 }
318}
319