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

Modern-Apps.git / scripts / maps / tile_build / tests / geom_part2.rs

geom_part2.rs367 lines · 14.8 KiBRaw
1#[cfg(test)]
2mod tests {
3 use tile_build::geom::*; use tile_build::mvt::DEFAULT_EXTENT;
4
5 #[test]
6 fn projection_anchors_are_right() {
7 // z0: the whole world is one tile, and 0,0 sits at its centre.
8 let (x, y) = project(0.0, 0.0, 0);
9 assert!((x - 0.5).abs() < 1e-9, "lon 0 -> x 0.5, got {x}");
10 assert!((y - 0.5).abs() < 1e-9, "lat 0 -> y 0.5, got {y}");
11 let (x, _) = project(-180.0, 0.0, 0);
12 assert!(x.abs() < 1e-9);
13 let (_, y) = project(0.0, 85.051_128_78, 0);
14 assert!(y.abs() < 1e-6, "Mercator top -> y 0, got {y}");
15 // A pole must clamp rather than diverge.
16 let (_, y) = project(0.0, 90.0, 4);
17 assert!(y.is_finite(), "lat 90 must clamp, got {y}");
18 // San Francisco at z11 is a well-known tile.
19 let (fx, fy) = project(-122.4194, 37.7749, 11);
20 assert_eq!((fx.floor() as u64, fy.floor() as u64), (327, 791));
21 }
22
23 #[test]
24 fn scaling_puts_a_point_inside_its_own_tile() {
25 let extent = DEFAULT_EXTENT;
26 let (wx, wy) = project_scaled(-122.4194, 37.7749, 11, extent);
27 let (tx, ty) = (327u64, 791u64);
28 let local = (wx - tx as f64 * extent as f64, wy - ty as f64 * extent as f64);
29 assert!(
30 (0.0..=extent as f64).contains(&local.0) && (0.0..=extent as f64).contains(&local.1),
31 "{local:?} must be inside [0,{extent}]"
32 );
33 }
34
35 #[test]
36 fn buffer_scales_with_the_extent() {
37 assert_eq!(buffer_for(DEFAULT_EXTENT), DEFAULT_BUFFER);
38 assert_eq!(buffer_for(8192), DEFAULT_BUFFER * 2.0);
39 assert_eq!(buffer_for(2048), DEFAULT_BUFFER / 2.0);
40 }
41
42 #[test]
43 fn bounds_cover_every_part_and_ignore_non_finite() {
44 let g = Geometry::Lines(vec![
45 vec![(0.0, 0.0), (10.0, 5.0)],
46 vec![(-3.0, 20.0), (4.0, 1.0)],
47 ]);
48 assert_eq!(
49 bounds(&g),
50 Some(Rect { min_x: -3.0, min_y: 0.0, max_x: 10.0, max_y: 20.0 })
51 );
52 assert_eq!(bounds(&Geometry::<Pt>::Points(vec![])), None);
53
54 // A NaN vertex is skipped rather than poisoning the whole box.
55 let g = Geometry::Points(vec![(1.0, 2.0), (f64::NAN, 0.0), (3.0, 4.0)]);
56 assert_eq!(
57 bounds(&g),
58 Some(Rect { min_x: 1.0, min_y: 2.0, max_x: 3.0, max_y: 4.0 })
59 );
60 assert_eq!(bounds(&Geometry::Points(vec![(f64::NAN, f64::NAN)])), None);
61 }
62
63 #[test]
64 fn a_tile_range_covers_exactly_the_tiles_touched() {
65 let e = 4096u32;
66 // Entirely inside tile (1,1).
67 let b = Rect { min_x: 1.5 * e as f64, min_y: 1.5 * e as f64, max_x: 1.6 * e as f64, max_y: 1.6 * e as f64 };
68 assert_eq!(
69 tile_range(&b, 4, e, 0.0),
70 Some(TileRange { x0: 1, y0: 1, x1: 1, y1: 1 })
71 );
72 // Straddling into (2,2).
73 let b = Rect { min_x: 1.5 * e as f64, min_y: 1.5 * e as f64, max_x: 2.5 * e as f64, max_y: 2.5 * e as f64 };
74 assert_eq!(
75 tile_range(&b, 4, e, 0.0),
76 Some(TileRange { x0: 1, y0: 1, x1: 2, y1: 2 })
77 );
78 }
79
80 #[test]
81 fn the_pad_pulls_in_the_neighbouring_tile() {
82 let e = 4096u32;
83 // Two units inside tile 1's left edge. With no pad it touches only tile 1;
84 // with a 5-unit pad it also reaches into tile 0's buffer, which is the
85 // whole reason the buffer exists.
86 let x = e as f64 + 2.0;
87 let b = Rect { min_x: x, min_y: x, max_x: x, max_y: x };
88 assert_eq!(
89 tile_range(&b, 4, e, 0.0),
90 Some(TileRange { x0: 1, y0: 1, x1: 1, y1: 1 })
91 );
92 assert_eq!(
93 tile_range(&b, 4, e, 5.0),
94 Some(TileRange { x0: 0, y0: 0, x1: 1, y1: 1 })
95 );
96 }
97
98 #[test]
99 fn a_tile_range_clamps_to_the_grid_and_rejects_the_wholly_outside() {
100 let e = 4096u32;
101 let n = 1u64 << 4;
102 // Overhanging both ends is clamped, not wrapped.
103 let b = Rect { min_x: -100.0, min_y: -100.0, max_x: (n as f64 + 3.0) * e as f64, max_y: (n as f64 + 3.0) * e as f64 };
104 assert_eq!(
105 tile_range(&b, 4, e, 0.0),
106 Some(TileRange { x0: 0, y0: 0, x1: n - 1, y1: n - 1 })
107 );
108 // Wholly off the grid.
109 let b = Rect { min_x: -10.0 * e as f64, min_y: 0.0, max_x: -9.0 * e as f64, max_y: e as f64 };
110 assert_eq!(tile_range(&b, 4, e, 0.0), None);
111 // NaN in, None out.
112 let b = Rect { min_x: f64::NAN, min_y: 0.0, max_x: 1.0, max_y: 1.0 };
113 assert_eq!(tile_range(&b, 4, e, 0.0), None);
114 }
115
116 /// The whole point of `tiles_touched`: a long diagonal must not claim the empty
117 /// corners of its bounding box. This is the case that made `transit_lines` at
118 /// planet scale take hours.
119 #[test]
120 fn a_diagonal_line_skips_the_corners_of_its_bounding_box() {
121 let extent = 4096u32;
122 let e = extent as f64;
123 // A staircase across a 40 x 40 tile square, one vertex per tile step, so the
124 // line genuinely passes through ~40 tiles out of 1600.
125 let pts: Vec<Pt> = (0..=40).map(|i| (i as f64 * e, i as f64 * e)).collect();
126 let g = Geometry::Lines(vec![pts]);
127
128 let mut touched = Vec::new();
129 tiles_touched(&g, 8, extent, 0.0, &mut touched);
130
131 let bbox = tile_range(&bounds(&g).unwrap(), 8, extent, 0.0).unwrap();
132 assert_eq!(bbox.len(), 41 * 41, "the box really is that big");
133 // Every vertex sits exactly on a tile corner here, which is the worst case:
134 // each segment's box spans 2x2 tiles rather than 1. Even so the walk is an
135 // order of magnitude below the box, and that ratio is what grows with zoom.
136 assert!(
137 (touched.len() as u64) * 10 < bbox.len(),
138 "walked {} tiles, more than a tenth of the box's {}",
139 touched.len(),
140 bbox.len()
141 );
142
143 // Every tile on the diagonal is present...
144 for i in 0..=40u64 {
145 assert!(touched.contains(&(i, i)), "tile ({i},{i}) is on the line");
146 }
147 // ...and the far corners, which the line never approaches, are not.
148 assert!(!touched.contains(&(0, 40)), "bottom-left corner is empty");
149 assert!(!touched.contains(&(40, 0)), "top-right corner is empty");
150 }
151
152 /// Safety property: it may over-include, never under-include. Everything it lists
153 /// is inside the feature's bounding box, and every point ON the line lands in a
154 /// tile it listed.
155 ///
156 /// Sampling the line rather than asserting each segment's whole box, because
157 /// bisection deliberately produces a tighter set than those boxes — that is the
158 /// optimisation. What must not change is that no part of the line is unreachable.
159 #[test]
160 fn tiles_touched_covers_every_point_on_the_line_and_nothing_outside_the_box() {
161 let extent = 4096u32;
162 let e = extent as f64;
163 let pts = vec![
164 (0.5 * e, 0.5 * e),
165 (3.5 * e, 1.5 * e),
166 (2.0 * e, 6.0 * e),
167 ];
168 let g = Geometry::Lines(vec![pts.clone()]);
169
170 let mut touched = Vec::new();
171 tiles_touched(&g, 8, extent, 0.0, &mut touched);
172
173 let bbox = tile_range(&bounds(&g).unwrap(), 8, extent, 0.0).unwrap();
174 let inside: Vec<(u64, u64)> = bbox.iter().collect();
175 for t in &touched {
176 assert!(inside.contains(t), "{t:?} is outside the bounding box");
177 }
178
179 // Walk each segment finely; every sample's tile must have been listed.
180 for seg in pts.windows(2) {
181 let steps = 2000;
182 for i in 0..=steps {
183 let t = i as f64 / steps as f64;
184 let x = seg[0].0 + (seg[1].0 - seg[0].0) * t;
185 let y = seg[0].1 + (seg[1].1 - seg[0].1) * t;
186 let tile = ((x / e).floor() as u64, (y / e).floor() as u64);
187 assert!(
188 touched.contains(&tile),
189 "point ({x}, {y}) is in tile {tile:?}, which was not listed"
190 );
191 }
192 }
193 }
194
195 /// Bisection is what makes the result independent of vertex density: a 4-vertex
196 /// line across a continent must walk about as many tiles as a 400-vertex one along
197 /// the same path, rather than filling its segment boxes.
198 #[test]
199 fn a_sparse_line_walks_as_tightly_as_a_dense_one() {
200 let extent = 4096u32;
201 let e = extent as f64;
202 let end = 40.0;
203
204 let sparse = Geometry::Lines(vec![vec![(0.0, 0.0), (end * e, end * e)]]);
205 let dense: Vec<Pt> = (0..=400)
206 .map(|i| {
207 let t = i as f64 / 400.0;
208 (end * e * t, end * e * t)
209 })
210 .collect();
211 let dense = Geometry::Lines(vec![dense]);
212
213 let (mut a, mut b) = (Vec::new(), Vec::new());
214 tiles_touched(&sparse, 8, extent, 0.0, &mut a);
215 tiles_touched(&dense, 8, extent, 0.0, &mut b);
216
217 let bbox = tile_range(&bounds(&sparse).unwrap(), 8, extent, 0.0).unwrap();
218 assert!(
219 (a.len() as u64) * 10 < bbox.len(),
220 "sparse walked {} of the box's {}",
221 a.len(),
222 bbox.len()
223 );
224 // Within a small factor of each other, not orders apart.
225 assert!(
226 a.len() < b.len() * 3 && b.len() < a.len() * 3,
227 "sparse {} vs dense {} should be comparable",
228 a.len(),
229 b.len()
230 );
231 }
232
233 /// A polygon covers its interior, so its footprint stays the whole ring box --
234 /// per-segment boxes would drop every tile strictly inside it.
235 #[test]
236 fn a_polygon_still_claims_its_interior_tiles() {
237 let extent = 4096u32;
238 let e = extent as f64;
239 let ring = vec![
240 (0.5 * e, 0.5 * e),
241 (5.5 * e, 0.5 * e),
242 (5.5 * e, 5.5 * e),
243 (0.5 * e, 5.5 * e),
244 (0.5 * e, 0.5 * e),
245 ];
246 let g = Geometry::Polygons(vec![vec![ring]]);
247
248 let mut touched = Vec::new();
249 tiles_touched(&g, 8, extent, 0.0, &mut touched);
250
251 // (3,3) is strictly inside and touches no edge.
252 assert!(touched.contains(&(3, 3)), "interior tile must be filled");
253 assert_eq!(touched.len(), 36, "the whole 6x6 footprint");
254 }
255
256 /// Adjacent segments share tiles; a duplicate would encode the geometry twice.
257 #[test]
258 fn tiles_touched_deduplicates_and_sorts() {
259 let extent = 4096u32;
260 let e = extent as f64;
261 // Many short segments all inside one tile.
262 let pts: Vec<Pt> = (0..20).map(|i| (0.1 * e + i as f64, 0.1 * e)).collect();
263 let mut touched = Vec::new();
264 tiles_touched(&Geometry::Lines(vec![pts]), 8, extent, 0.0, &mut touched);
265 assert_eq!(touched, vec![(0, 0)]);
266
267 let mut sorted = touched.clone();
268 sorted.sort_unstable();
269 assert_eq!(touched, sorted, "output is sorted for a deterministic pass");
270 }
271
272 #[test]
273 fn tile_range_iterates_row_major() {
274 let r = TileRange { x0: 2, y0: 5, x1: 3, y1: 6 };
275 assert_eq!(r.len(), 4);
276 assert_eq!(
277 r.iter().collect::<Vec<_>>(),
278 vec![(2, 5), (3, 5), (2, 6), (3, 6)]
279 );
280 }
281
282 #[test]
283 fn a_tile_rect_is_the_tile_plus_its_buffer() {
284 let r = tile_rect(2, 3, 4096, 5.0);
285 assert_eq!(
286 r,
287 Rect { min_x: 8192.0 - 5.0, min_y: 12288.0 - 5.0, max_x: 12288.0 + 5.0, max_y: 16384.0 + 5.0 }
288 );
289 assert!(r.contains((8192.0, 12288.0)));
290 assert!(r.contains((8192.0 - 4.0, 12288.0 - 4.0)), "inside the buffer");
291 assert!(!r.contains((8192.0 - 6.0, 12288.0)), "beyond the buffer");
292 }
293
294 #[test]
295 fn to_tile_translates_then_rounds() {
296 // A vertex at world (4096.4, 8191.6) is (0.4, 4095.6) inside tile (1,1),
297 // which rounds to (0, 4096).
298 let g = Geometry::Lines(vec![vec![(4096.4, 8191.6), (5000.0, 9000.0)]]);
299 let IntGeometry::Lines(lines) = to_tile(&g, 1, 1, 4096) else {
300 panic!("lines in, lines out")
301 };
302 assert_eq!(lines[0][0], (0, 4096));
303 assert_eq!(lines[0][1], (904, 4904));
304 }
305
306 #[test]
307 fn quantisation_drops_the_duplicates_it_creates() {
308 // Three vertices within a rounding unit of each other collapse to one.
309 let g = Geometry::Lines(vec![vec![
310 (10.1, 10.1),
311 (10.2, 10.3),
312 (9.9, 10.0),
313 (20.0, 20.0),
314 ]]);
315 let IntGeometry::Lines(lines) = quantize(&g) else { panic!() };
316 assert_eq!(lines[0], vec![(10, 10), (20, 20)]);
317
318 // Non-adjacent repeats are kept: a line that doubles back is a real shape.
319 let g = Geometry::Lines(vec![vec![(0.0, 0.0), (5.0, 0.0), (0.0, 0.0)]]);
320 let IntGeometry::Lines(lines) = quantize(&g) else { panic!() };
321 assert_eq!(lines[0], vec![(0, 0), (5, 0), (0, 0)]);
322 }
323
324 #[test]
325 fn quantisation_keeps_a_rings_closing_vertex() {
326 // ClosePath is applied by the encoder, not here, so the ring stays closed
327 // through simplification -- which needs the closure to measure against.
328 let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];
329 let IntGeometry::Polygons(polys) = quantize(&Geometry::Polygons(vec![vec![ring]])) else {
330 panic!()
331 };
332 assert_eq!(polys[0][0].len(), 5);
333 assert_eq!(polys[0][0].first(), polys[0][0].last());
334 }
335
336 #[test]
337 fn a_non_finite_vertex_saturates_rather_than_wrapping() {
338 // `f64::NAN as i32` is 0 in Rust and `1e300 as i32` is the saturated bound,
339 // but both are silent. Keeping the saturation explicit means an out-of-range
340 // vertex stays obviously out of range instead of landing somewhere
341 // plausible; a NaN has no meaningful bound, so it becomes the origin.
342 let g = Geometry::Points(vec![(f64::NAN, 1e300), (-1e300, 5.0)]);
343 let IntGeometry::Points(pts) = quantize(&g) else { panic!() };
344 assert_eq!(pts, vec![(0, i32::MAX), (i32::MIN, 5)]);
345 }
346
347 #[test]
348 fn emptiness_is_judged_per_geometry_kind() {
349 assert!(IntGeometry::Points(vec![]).is_empty());
350 assert!(!IntGeometry::Points(vec![(0, 0)]).is_empty());
351 assert!(IntGeometry::Lines(vec![vec![(0, 0)]]).is_empty());
352 assert!(!IntGeometry::Lines(vec![vec![(0, 0), (1, 1)]]).is_empty());
353 // Three distinct vertices are the least that can enclose an area.
354 assert!(IntGeometry::Polygons(vec![vec![vec![(0, 0), (1, 0)]]]).is_empty());
355 assert!(!IntGeometry::Polygons(vec![vec![vec![(0, 0), (1, 0), (1, 1)]]]).is_empty());
356 }
357
358 #[test]
359 fn rects_intersect_symmetrically_and_touch_counts() {
360 let a = Rect { min_x: 0.0, min_y: 0.0, max_x: 10.0, max_y: 10.0 };
361 let b = Rect { min_x: 10.0, min_y: 10.0, max_x: 20.0, max_y: 20.0 };
362 let c = Rect { min_x: 11.0, min_y: 0.0, max_x: 20.0, max_y: 10.0 };
363 assert!(a.intersects(&b) && b.intersects(&a), "touching corners overlap");
364 assert!(!a.intersects(&c) && !c.intersects(&a));
365 }
366}
367