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

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

simplify.rs240 lines · 10.3 KiBRaw
1//! Simplification, in two halves: annotate once, then filter per zoom.
2//!
3//! [`annotate`] runs Douglas-Peucker **once** over each unclipped source ring or
4//! line and records, on every vertex, how much shape that vertex is responsible
5//! for. [`filter`] then keeps a vertex when its significance clears the zoom's
6//! threshold. This is geojson-vt's design, and it is here for one reason:
7//!
8//! ## Why not Douglas-Peucker per tile
9//!
10//! [`crate::clip::clip_polygon`] clips each ring of a polygon on its own, so a hole
11//! that crossed a tile edge ends up sharing an edge **exactly** with the clipped
12//! exterior along the tile boundary. Running Douglas-Peucker on each ring
13//! afterwards anchors each at its own first and last vertex -- positions that have
14//! nothing to do with each other between two rings -- so those two coincident
15//! edges get thinned differently and move apart by up to a unit. The hole then
16//! straddles or escapes its exterior, earcut cannot express that, and the renderer
17//! has no choice but to drop the hole: every affected island and lake fills in
18//! solid.
19//!
20//! Annotating first fixes it by construction. A vertex's significance is a property
21//! of the vertex, not of the ring it is being simplified inside, so it is kept or
22//! dropped consistently in every ring and every tile it appears in. Vertices the
23//! clipper invents on the boundary carry [`crate::geom::ALWAYS`], so a clipped ring
24//! is never re-simplified along the edge it was cut at.
25//!
26//! ## Why annotating once is enough
27//!
28//! [`crate::geom::project`] is a pure scale by `2^z`, so every perpendicular
29//! distance at one zoom is the same constant multiple of the distance at another:
30//! significance is scale-invariant, and the zoom only picks the threshold. That is
31//! also why the annotation pass uses the tolerance at `max_zoom`, which
32//! [`tolerance_for`] defines as zero -- full recursion, so every vertex receives
33//! its true significance rather than only those above some floor.
34//!
35//! It is also cheaper than what it replaces: once per feature per zoom instead of
36//! once per feature per **tile**.
37//!
38//! ## Rings have two extra rules
39//!
40//! * **Closure is preserved.** A closed ring is filtered without its explicit
41//! closing vertex and re-closed with a copy of whichever vertex survived first,
42//! so the two can never disagree.
43//! * **A ring never drops below four vertices**, i.e. three distinct corners plus
44//! the repeated close. Fewer than that encloses no area, and an MVT polygon with
45//! a two-vertex ring is a renderer's problem rather than a small one. When
46//! filtering would go that far the **ring is dropped instead**, and if that ring
47//! was the exterior the whole polygon goes with it. Keeping a collapsed sliver
48//! would paint a hairline in the layer's fill colour, which is worse than the
49//! feature being absent at that zoom.
50//!
51//! ## The tolerance policy is ours, not tippecanoe's
52//!
53//! [`tolerance_for`] is a fixed number of tile-extent units, and it returns zero at
54//! the maximum zoom so the deepest tiles keep full detail. Because a tile is always
55//! `extent` units across whatever the zoom, a constant tolerance is already
56//! zoom-relative: the same 1 unit covers roughly 1000x more ground at z6 than at
57//! z16, which is exactly the behaviour a pyramid wants. This is a deliberate,
58//! documented policy rather than a reproduction of `--simplification`, and the
59//! tests assert the policy's own invariants -- never equality with tippecanoe.
60
61use crate::geom::{Geometry, SigPt, Vertex, ALWAYS};
62
63/// Simplification tolerance at [`crate::mvt::DEFAULT_EXTENT`], in extent units.
64///
65/// One unit is 1/4096 of a tile, which at z16 is under a metre. Below that,
66/// detail is not representable in the tile anyway.
67pub const DEFAULT_TOLERANCE: f64 = 1.0;
68
69/// The least a ring may be reduced to: three distinct corners plus the close.
70pub const MIN_RING_VERTICES: usize = 4;
71
72/// The tolerance to use at zoom `z`, given the archive's maximum zoom and a
73/// multiplier (1.0 for the default policy).
74///
75/// Zero at `max_zoom`: the deepest zoom is the one a user sees at full scale, and
76/// it is also the only zoom whose geometry cannot be recovered from a deeper one.
77pub fn tolerance_for(z: u8, max_zoom: u8, multiplier: f64) -> f64 {
78 if z >= max_zoom {
79 0.0
80 } else {
81 DEFAULT_TOLERANCE * multiplier
82 }
83}
84
85/// Record every vertex's significance, in place, on an unclipped geometry.
86///
87/// Must run **before** the clip: the whole point is that a vertex is measured
88/// against its neighbours in the source, not against wherever a tile boundary
89/// happened to cut the ring.
90///
91/// Points are left alone. There is nothing in a point to remove, and thinning a
92/// point layer is the drop policy's job.
93pub fn annotate(g: &mut Geometry<SigPt>) {
94 match g {
95 Geometry::Points(_) => {}
96 Geometry::Lines(lines) => lines.iter_mut().for_each(|l| annotate_path(l)),
97 Geometry::Polygons(polys) => {
98 polys.iter_mut().flatten().for_each(|ring| annotate_path(ring))
99 }
100 }
101}
102
103/// Keep the vertices whose significance clears `tolerance`.
104///
105/// A pure filter: no vertex is measured, moved or invented here, which is what
106/// makes two rings that share an edge agree along it.
107pub fn filter(g: &Geometry<SigPt>, tolerance: f64) -> Geometry<SigPt> {
108 if tolerance <= 0.0 {
109 return g.clone();
110 }
111 let tol_sq = tolerance * tolerance;
112 match g {
113 Geometry::Points(_) => g.clone(),
114 Geometry::Lines(lines) => Geometry::Lines(
115 lines.iter().map(|l| filter_line(l, tol_sq)).filter(|l| l.len() >= 2).collect(),
116 ),
117 Geometry::Polygons(polys) => Geometry::Polygons(
118 polys
119 .iter()
120 .filter_map(|rings| {
121 let mut out: Vec<Vec<SigPt>> = Vec::with_capacity(rings.len());
122 for (i, ring) in rings.iter().enumerate() {
123 match filter_ring(ring, tol_sq) {
124 Some(r) => out.push(r),
125 // The exterior collapsing takes the holes with it.
126 None if i == 0 => return None,
127 None => continue,
128 }
129 }
130 (!out.is_empty()).then_some(out)
131 })
132 .collect(),
133 ),
134 }
135}
136
137/// Filter an open polyline. Its endpoints carry [`ALWAYS`] -- either from
138/// [`annotate`], or from the clipper having put them on a tile boundary -- so they
139/// survive without a special case for them.
140pub fn filter_line(line: &[SigPt], tol_sq: f64) -> Vec<SigPt> {
141 line.iter().copied().filter(|v| v.sig > tol_sq).collect()
142}
143
144/// Filter a ring, or `None` when the result would enclose no area.
145///
146/// A closed ring (first == last) stays closed; an unclosed one stays unclosed, and
147/// its floor is one lower since it has no repeated vertex.
148pub fn filter_ring(ring: &[SigPt], tol_sq: f64) -> Option<Vec<SigPt>> {
149 let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
150 let floor = if closed { MIN_RING_VERTICES } else { MIN_RING_VERTICES - 1 };
151 if ring.len() < floor {
152 return None;
153 }
154 // The closing vertex is not filtered on its own: re-closing with a copy of the
155 // surviving first vertex is what makes it impossible to open the ring.
156 let open = &ring[..ring.len() - usize::from(closed)];
157 let mut out: Vec<SigPt> = open.iter().copied().filter(|v| v.sig > tol_sq).collect();
158 if out.len() + usize::from(closed) < floor {
159 return None;
160 }
161 if closed {
162 out.push(out[0]);
163 }
164 Some(out)
165}
166
167/// Run Douglas-Peucker to exhaustion over one path, writing each vertex's
168/// significance as it goes.
169///
170/// The path's own two ends are [`ALWAYS`]: a line must keep its endpoints, and for
171/// a closed ring the two ends are the same place, so anchoring both is what keeps
172/// the ring closed.
173pub fn annotate_path(pts: &mut [SigPt]) {
174 let Some(last) = pts.len().checked_sub(1) else { return };
175 pts[0].sig = ALWAYS;
176 pts[last].sig = ALWAYS;
177 if pts.len() < 3 {
178 return;
179 }
180 mark(pts, 0, last);
181}
182
183/// Measure every vertex between two anchors and recurse into both halves.
184///
185/// Iterative rather than recursive: a coastline ring can be hundreds of thousands
186/// of vertices, and the recursion depth is only bounded by the data.
187///
188/// There is no tolerance here -- recursion continues while any vertex is off the
189/// chord at all, which is [`tolerance_for`] at `max_zoom` and is what gives every
190/// vertex its true significance rather than a lower bound on it. A vertex that is
191/// exactly on every chord it is ever measured against keeps significance zero and
192/// is dropped by any non-zero threshold, which is correct: it carries no shape.
193fn mark(pts: &mut [SigPt], first: usize, last: usize) {
194 let mut stack = vec![(first, last)];
195 while let Some((a, b)) = stack.pop() {
196 if b <= a + 1 {
197 continue;
198 }
199 let mut worst = 0.0f64;
200 let mut worst_i = a;
201 for i in (a + 1)..b {
202 let d = seg_dist_sq(pts[i], pts[a], pts[b]);
203 if d > worst {
204 worst = d;
205 worst_i = i;
206 }
207 }
208 if worst > 0.0 {
209 pts[worst_i].sig = worst;
210 stack.push((a, worst_i));
211 stack.push((worst_i, b));
212 }
213 }
214}
215
216/// Squared distance from `p` to the **segment** `a -> b`.
217///
218/// The segment, not the infinite line it lies on. The two agree wherever the foot
219/// of the perpendicular is between the endpoints, which is the only case an open
220/// polyline's first pass produces -- but a closed ring's first chord is degenerate
221/// (`a == b`), and past that the chords are arbitrary, so a vertex beyond an
222/// endpoint would otherwise be scored by a perpendicular that misses the segment
223/// entirely. This is geojson-vt's `getSqSegDist`.
224pub fn seg_dist_sq(p: SigPt, a: SigPt, b: SigPt) -> f64 {
225 let (mut x, mut y) = (a.x, a.y);
226 let (dx, dy) = (b.x - x, b.y - y);
227 let len_sq = dx * dx + dy * dy;
228 if len_sq > 0.0 {
229 let t = ((p.x - x) * dx + (p.y - y) * dy) / len_sq;
230 if t > 1.0 {
231 x = b.x;
232 y = b.y;
233 } else if t > 0.0 {
234 x += dx * t;
235 y += dy * t;
236 }
237 }
238 let (dx, dy) = (p.x - x, p.y - y);
239 dx * dx + dy * dy
240}