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

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

clip.rs315 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().copied().filter(|p| finite(*p) && rect.contains(p.xy())).collect(),
57 ),
58 Geometry::Lines(lines) => {
59 let mut out = Vec::new();
60 for line in lines {
61 out.extend(clip_line(line, rect));
62 }
63 Geometry::Lines(out)
64 }
65 Geometry::Polygons(polys) => {
66 let mut out = Vec::new();
67 for rings in polys {
68 let clipped = clip_polygon(rings, rect);
69 if !clipped.is_empty() {
70 out.push(clipped);
71 }
72 }
73 Geometry::Polygons(out)
74 }
75 }
76}
77
78fn finite<V: Vertex>(v: V) -> bool {
79 let (x, y) = v.xy();
80 x.is_finite() && y.is_finite()
81}
82
83/// Clip one polyline, returning the pieces that fall inside `rect`.
84///
85/// Consecutive segments that survive the clip and still meet are welded back into
86/// one output line; a gap starts a new one. That is what makes the result a
87/// partition of the original rather than a bag of segments.
88pub fn clip_line<V: Vertex>(line: &[V], rect: &Rect) -> Vec<Vec<V>> {
89 let mut out: Vec<Vec<V>> = Vec::new();
90 let mut current: Vec<V> = Vec::new();
91
92 for w in line.windows(2) {
93 let (a, b) = (w[0], w[1]);
94 if !finite(a) || !finite(b) {
95 // Break the run: welding across a dropped vertex would invent an edge.
96 if current.len() > 1 {
97 out.push(std::mem::take(&mut current));
98 } else {
99 current.clear();
100 }
101 continue;
102 }
103 match clip_segment(a, b, rect) {
104 None => {
105 if current.len() > 1 {
106 out.push(std::mem::take(&mut current));
107 } else {
108 current.clear();
109 }
110 }
111 Some((ca, cb)) => {
112 // By position, not by vertex: the near end of this segment and the
113 // far end of the last are the same place but need not be the same
114 // vertex -- one may be a source vertex and the other a crossing.
115 if current.last().map(|v| v.xy()) == Some(ca.xy()) {
116 current.push(cb);
117 } else {
118 if current.len() > 1 {
119 out.push(std::mem::take(&mut current));
120 } else {
121 current.clear();
122 }
123 current.push(ca);
124 current.push(cb);
125 }
126 }
127 }
128 }
129 if current.len() > 1 {
130 out.push(current);
131 }
132 out
133}
134
135/// Liang-Barsky: clip the segment `a -> b` to `rect`.
136///
137/// Returns the surviving sub-segment, or `None` when the segment misses the rect.
138/// The algorithm narrows a parameter interval `[t0, t1]` along the segment against
139/// each of the four boundaries; the segment is outside as soon as the interval
140/// closes.
141///
142/// An endpoint the interval did not move is returned as itself, significance and
143/// all; an endpoint it did move is a new vertex on the boundary.
144///
145/// A non-finite endpoint is `None`. Every comparison below would be false for a
146/// `NaN`, so it would fall through as "inside" and emit a `NaN` intersection.
147pub fn clip_segment<V: Vertex>(a: V, b: V, rect: &Rect) -> Option<(V, V)> {
148 if !finite(a) || !finite(b) {
149 return None;
150 }
151 let (ax, ay) = a.xy();
152 let (bx, by) = b.xy();
153 let (dx, dy) = (bx - ax, by - ay);
154 let mut t0 = 0.0f64;
155 let mut t1 = 1.0f64;
156
157 // Each boundary is `p * t <= q`, where p is the direction component and q the
158 // distance to the boundary.
159 for &(p, q) in &[
160 (-dx, ax - rect.min_x),
161 (dx, rect.max_x - ax),
162 (-dy, ay - rect.min_y),
163 (dy, rect.max_y - ay),
164 ] {
165 if p == 0.0 {
166 // Parallel to this boundary: inside iff already on the right side.
167 if q < 0.0 {
168 return None;
169 }
170 continue;
171 }
172 let t = q / p;
173 if p < 0.0 {
174 // Entering: raise the lower bound.
175 if t > t1 {
176 return None;
177 }
178 if t > t0 {
179 t0 = t;
180 }
181 } else {
182 // Leaving: lower the upper bound.
183 if t < t0 {
184 return None;
185 }
186 if t < t1 {
187 t1 = t;
188 }
189 }
190 }
191 let at = |t: f64| (ax + t * dx, ay + t * dy);
192 Some((
193 if t0 == 0.0 { a } else { V::boundary(at(t0)) },
194 if t1 == 1.0 { b } else { V::boundary(at(t1)) },
195 ))
196}
197
198/// Clip a polygon's rings to `rect`.
199///
200/// A ring that clips away entirely is dropped. If the **exterior** ring
201/// disappears the whole polygon does, holes included: a hole with no surrounding
202/// area is not a shape, and emitting one would render as a solid patch of the
203/// wrong colour.
204pub fn clip_polygon<V: Vertex>(rings: &[Vec<V>], rect: &Rect) -> Vec<Vec<V>> {
205 let mut out: Vec<Vec<V>> = Vec::new();
206 for (i, ring) in rings.iter().enumerate() {
207 let clipped = clip_ring(ring, rect);
208 if clipped.len() < 3 {
209 if i == 0 {
210 return Vec::new();
211 }
212 continue;
213 }
214 out.push(clipped);
215 }
216 out
217}
218
219/// Sutherland-Hodgman: clip one ring against the four boundaries in turn.
220///
221/// The caller's closure convention is preserved: an explicitly closed ring
222/// (first == last) is normalised on the way in and re-closed on the way out with a
223/// **copy of the surviving first vertex**, so the two carry the same significance
224/// and no later filter can open the ring by keeping one and dropping the other. An
225/// unclosed ring stays unclosed. Fewer than three distinct vertices out means the
226/// ring did not survive.
227pub fn clip_ring<V: Vertex>(ring: &[V], rect: &Rect) -> Vec<V> {
228 let was_closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
229 let open: Vec<V> = ring[..ring.len() - usize::from(was_closed)]
230 .iter()
231 .copied()
232 .filter(|p| finite(*p))
233 .collect();
234 if open.len() < 3 {
235 return Vec::new();
236 }
237
238 let mut current = open;
239 for edge in [
240 Edge::Left(rect.min_x),
241 Edge::Right(rect.max_x),
242 Edge::Bottom(rect.min_y),
243 Edge::Top(rect.max_y),
244 ] {
245 if current.len() < 3 {
246 return Vec::new();
247 }
248 let mut next: Vec<V> = Vec::with_capacity(current.len() + 4);
249 for i in 0..current.len() {
250 let a = current[(i + current.len() - 1) % current.len()];
251 let b = current[i];
252 let (a_in, b_in) = (edge.inside(a.xy()), edge.inside(b.xy()));
253 if b_in {
254 // Entering: the crossing comes first, then the vertex itself.
255 if !a_in {
256 next.push(V::boundary(edge.intersect(a.xy(), b.xy())));
257 }
258 next.push(b);
259 } else if a_in {
260 // Leaving: only the crossing.
261 next.push(V::boundary(edge.intersect(a.xy(), b.xy())));
262 }
263 }
264 current = next;
265 }
266
267 // The clip can put two crossings on the same boundary point.
268 current.dedup_by(|a, b| a.xy() == b.xy());
269 if current.len() > 1 && current.first().map(|v| v.xy()) == current.last().map(|v| v.xy()) {
270 current.pop();
271 }
272 if current.len() < 3 {
273 return Vec::new();
274 }
275 if was_closed {
276 let first = current[0];
277 current.push(first);
278 }
279 current
280}
281
282/// Which side of a boundary a vertex is on, and where an edge crosses it.
283#[derive(Clone, Copy)]
284enum Edge {
285 Left(f64),
286 Right(f64),
287 Bottom(f64),
288 Top(f64),
289}
290
291impl Edge {
292 fn inside(self, (x, y): Pt) -> bool {
293 match self {
294 Edge::Left(v) => x >= v,
295 Edge::Right(v) => x <= v,
296 Edge::Bottom(v) => y >= v,
297 Edge::Top(v) => y <= v,
298 }
299 }
300
301 /// Where `a -> b` crosses this boundary. Only called when the two vertices are
302 /// on opposite sides, so the denominator cannot be zero.
303 fn intersect(self, a: Pt, b: Pt) -> Pt {
304 match self {
305 Edge::Left(v) | Edge::Right(v) => {
306 let t = (v - a.0) / (b.0 - a.0);
307 (v, a.1 + t * (b.1 - a.1))
308 }
309 Edge::Bottom(v) | Edge::Top(v) => {
310 let t = (v - a.1) / (b.1 - a.1);
311 (a.0 + t * (b.0 - a.0), v)
312 }
313 }
314 }
315}