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

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

simplify.rs245 lines · 10.4 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) => polys
98 .iter_mut()
99 .flatten()
100 .for_each(|ring| annotate_path(ring)),
101 }
102}
103
104/// Keep the vertices whose significance clears `tolerance`.
105///
106/// A pure filter: no vertex is measured, moved or invented here, which is what
107/// makes two rings that share an edge agree along it.
108pub fn filter(g: &Geometry<SigPt>, tolerance: f64) -> Geometry<SigPt> {
109 if tolerance <= 0.0 {
110 return g.clone();
111 }
112 let tol_sq = tolerance * tolerance;
113 match g {
114 Geometry::Points(_) => g.clone(),
115 Geometry::Lines(lines) => Geometry::Lines(
116 lines
117 .iter()
118 .map(|l| filter_line(l, tol_sq))
119 .filter(|l| l.len() >= 2)
120 .collect(),
121 ),
122 Geometry::Polygons(polys) => Geometry::Polygons(
123 polys
124 .iter()
125 .filter_map(|rings| {
126 let mut out: Vec<Vec<SigPt>> = Vec::with_capacity(rings.len());
127 for (i, ring) in rings.iter().enumerate() {
128 match filter_ring(ring, tol_sq) {
129 Some(r) => out.push(r),
130 // The exterior collapsing takes the holes with it.
131 None if i == 0 => return None,
132 None => continue,
133 }
134 }
135 (!out.is_empty()).then_some(out)
136 })
137 .collect(),
138 ),
139 }
140}
141
142/// Filter an open polyline. Its endpoints carry [`ALWAYS`] -- either from
143/// [`annotate`], or from the clipper having put them on a tile boundary -- so they
144/// survive without a special case for them.
145pub fn filter_line(line: &[SigPt], tol_sq: f64) -> Vec<SigPt> {
146 line.iter().copied().filter(|v| v.sig > tol_sq).collect()
147}
148
149/// Filter a ring, or `None` when the result would enclose no area.
150///
151/// A closed ring (first == last) stays closed; an unclosed one stays unclosed, and
152/// its floor is one lower since it has no repeated vertex.
153pub fn filter_ring(ring: &[SigPt], tol_sq: f64) -> Option<Vec<SigPt>> {
154 let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
155 let floor = if closed { MIN_RING_VERTICES } else { MIN_RING_VERTICES - 1 };
156 if ring.len() < floor {
157 return None;
158 }
159 // The closing vertex is not filtered on its own: re-closing with a copy of the
160 // surviving first vertex is what makes it impossible to open the ring.
161 let open = &ring[..ring.len() - usize::from(closed)];
162 let mut out: Vec<SigPt> = open.iter().copied().filter(|v| v.sig > tol_sq).collect();
163 if out.len() + usize::from(closed) < floor {
164 return None;
165 }
166 if closed {
167 out.push(out[0]);
168 }
169 Some(out)
170}
171
172/// Run Douglas-Peucker to exhaustion over one path, writing each vertex's
173/// significance as it goes.
174///
175/// The path's own two ends are [`ALWAYS`]: a line must keep its endpoints, and for
176/// a closed ring the two ends are the same place, so anchoring both is what keeps
177/// the ring closed.
178pub fn annotate_path(pts: &mut [SigPt]) {
179 let Some(last) = pts.len().checked_sub(1) else { return };
180 pts[0].sig = ALWAYS;
181 pts[last].sig = ALWAYS;
182 if pts.len() < 3 {
183 return;
184 }
185 mark(pts, 0, last);
186}
187
188/// Measure every vertex between two anchors and recurse into both halves.
189///
190/// Iterative rather than recursive: a coastline ring can be hundreds of thousands
191/// of vertices, and the recursion depth is only bounded by the data.
192///
193/// There is no tolerance here -- recursion continues while any vertex is off the
194/// chord at all, which is [`tolerance_for`] at `max_zoom` and is what gives every
195/// vertex its true significance rather than a lower bound on it. A vertex that is
196/// exactly on every chord it is ever measured against keeps significance zero and
197/// is dropped by any non-zero threshold, which is correct: it carries no shape.
198fn mark(pts: &mut [SigPt], first: usize, last: usize) {
199 let mut stack = vec![(first, last)];
200 while let Some((a, b)) = stack.pop() {
201 if b <= a + 1 {
202 continue;
203 }
204 let mut worst = 0.0f64;
205 let mut worst_i = a;
206 for i in (a + 1)..b {
207 let d = seg_dist_sq(pts[i], pts[a], pts[b]);
208 if d > worst {
209 worst = d;
210 worst_i = i;
211 }
212 }
213 if worst > 0.0 {
214 pts[worst_i].sig = worst;
215 stack.push((a, worst_i));
216 stack.push((worst_i, b));
217 }
218 }
219}
220
221/// Squared distance from `p` to the **segment** `a -> b`.
222///
223/// The segment, not the infinite line it lies on. The two agree wherever the foot
224/// of the perpendicular is between the endpoints, which is the only case an open
225/// polyline's first pass produces -- but a closed ring's first chord is degenerate
226/// (`a == b`), and past that the chords are arbitrary, so a vertex beyond an
227/// endpoint would otherwise be scored by a perpendicular that misses the segment
228/// entirely. This is geojson-vt's `getSqSegDist`.
229pub fn seg_dist_sq(p: SigPt, a: SigPt, b: SigPt) -> f64 {
230 let (mut x, mut y) = (a.x, a.y);
231 let (dx, dy) = (b.x - x, b.y - y);
232 let len_sq = dx * dx + dy * dy;
233 if len_sq > 0.0 {
234 let t = ((p.x - x) * dx + (p.y - y) * dy) / len_sq;
235 if t > 1.0 {
236 x = b.x;
237 y = b.y;
238 } else if t > 0.0 {
239 x += dx * t;
240 y += dy * t;
241 }
242 }
243 let (dx, dy) = (p.x - x, p.y - y);
244 dx * dx + dy * dy
245}