Skip to main content

geolith_tiles_builder/geometry/
tile_bounds.rs

1//! Pre-computed per-zoom tile ranges for bbox filtering.
2//!
3//! Converts a WGS84 bounding box into integer tile ranges at each zoom level,
4//! enabling O(1) tile containment checks (4 integer comparisons) instead of
5//! expensive coordinate-based intersection tests.
6//!
7//! This is the Rust equivalent of Planetiler's `TileExtents` — the single
8//! biggest performance optimization for regional (bbox-filtered) tile builds.
9
10use crate::geometry::mercator;
11use crate::source::bbox_filter::Bbox;
12
13/// Per-zoom tile range: (`min_x`, `max_x`, `min_y`, `max_y`) inclusive.
14#[derive(Debug, Clone, Copy)]
15struct ZoomRange {
16    min_x: u32,
17    max_x: u32,
18    min_y: u32,
19    max_y: u32,
20}
21
22/// Pre-computed tile ranges for a bounding box at every zoom level.
23///
24/// Created once at pipeline startup from the `--bbox` argument.
25/// Each `contains()` check is 4 integer comparisons — essentially free
26/// compared to the geometry processing it guards.
27#[derive(Debug, Clone)]
28pub struct TileBounds {
29    /// Per-zoom tile range, indexed by zoom level.
30    ranges: Vec<ZoomRange>,
31}
32
33impl TileBounds {
34    /// Build tile ranges for every zoom level from 0 to `max_zoom` (inclusive).
35    ///
36    /// Converts the WGS84 bbox corners to world coordinates, then to tile
37    /// indices at each zoom. Tile ranges are clamped to valid tile indices.
38    #[must_use]
39    pub fn from_bbox(bbox: &Bbox, max_zoom: u8) -> Self {
40        let (world_min_x, world_min_y) = mercator::wgs84_to_world(bbox.min_lon, bbox.max_lat);
41        let (world_max_x, world_max_y) = mercator::wgs84_to_world(bbox.max_lon, bbox.min_lat);
42
43        let mut ranges = Vec::with_capacity((max_zoom as usize) + 1);
44
45        for z in 0..=max_zoom {
46            let n = 1u32 << z;
47            let max_tile = n.saturating_sub(1);
48
49            // Convert world [0,1] to tile indices, clamped to valid range.
50            // Floor for min, floor for max (tile containing the max point).
51            let min_x = ((world_min_x * n as f64).floor() as u32).min(max_tile);
52            let max_x = ((world_max_x * n as f64).floor() as u32).min(max_tile);
53            let min_y = ((world_min_y * n as f64).floor() as u32).min(max_tile);
54            let max_y = ((world_max_y * n as f64).floor() as u32).min(max_tile);
55
56            ranges.push(ZoomRange {
57                min_x,
58                max_x,
59                min_y,
60                max_y,
61            });
62        }
63
64        Self { ranges }
65    }
66
67    /// Check if a tile coordinate falls within the pre-computed bounds.
68    ///
69    /// Returns `true` if the tile is within or on the boundary of the
70    /// bbox tile range at its zoom level. Tiles outside the range are
71    /// skipped, avoiding all downstream geometry processing.
72    #[inline]
73    #[must_use]
74    pub fn contains(&self, tile: &mercator::TileCoord) -> bool {
75        let z = tile.z as usize;
76        if z >= self.ranges.len() {
77            return false;
78        }
79        let r = &self.ranges[z];
80        tile.x >= r.min_x && tile.x <= r.max_x && tile.y >= r.min_y && tile.y <= r.max_y
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::geometry::mercator::TileCoord;
88
89    /// India Western Zone bbox from the benchmark.
90    fn western_zone_bbox() -> Bbox {
91        Bbox {
92            min_lon: 67.67,
93            min_lat: 14.39,
94            max_lon: 80.92,
95            max_lat: 24.72,
96        }
97    }
98
99    #[test]
100    fn zoom_0_always_contains_single_tile() {
101        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
102        assert!(bounds.contains(&TileCoord::new(0, 0, 0)));
103    }
104
105    #[test]
106    fn zoom_1_contains_correct_quadrant() {
107        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
108        // India Western Zone is in the eastern hemisphere, northern half
109        // Tile (1, 1, 0) = NE quadrant — should contain
110        assert!(bounds.contains(&TileCoord::new(1, 1, 0)));
111        // Tile (1, 0, 1) = SW quadrant — should NOT contain
112        assert!(!bounds.contains(&TileCoord::new(1, 0, 1)));
113    }
114
115    #[test]
116    fn tiles_outside_bbox_rejected() {
117        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
118        // Tile at zoom 4: x=0 is western Americas — far from India
119        assert!(!bounds.contains(&TileCoord::new(4, 0, 5)));
120        // Tile at zoom 4: x=15 is far east Pacific — far from India
121        assert!(!bounds.contains(&TileCoord::new(4, 15, 5)));
122    }
123
124    #[test]
125    fn tiles_inside_bbox_accepted() {
126        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
127        // At zoom 4, India Western Zone should be around x=11, y=5-6
128        // lon 67.67 → world_x = (67.67+180)/360 ≈ 0.688 → tile_x = floor(0.688*16) = 11
129        // lat 24.72 → world_y ≈ 0.412 → tile_y = floor(0.412*16) = 6
130        assert!(bounds.contains(&TileCoord::new(4, 11, 6)));
131    }
132
133    #[test]
134    fn zoom_beyond_max_returns_false() {
135        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 10);
136        // Zoom 11 is beyond max_zoom=10 — should return false
137        assert!(!bounds.contains(&TileCoord::new(11, 0, 0)));
138    }
139
140    #[test]
141    fn full_planet_bbox_accepts_all_tiles() {
142        let planet = Bbox {
143            min_lon: -180.0,
144            min_lat: -85.05,
145            max_lon: 180.0,
146            max_lat: 85.05,
147        };
148        let bounds = TileBounds::from_bbox(&planet, 5);
149        // Every tile at every zoom should be accepted
150        for z in 0..=5 {
151            let n = 1u32 << z;
152            for x in 0..n {
153                for y in 0..n {
154                    assert!(
155                        bounds.contains(&TileCoord::new(z, x, y)),
156                        "planet bbox should contain tile z={z} x={x} y={y}"
157                    );
158                }
159            }
160        }
161    }
162
163    #[test]
164    fn monaco_bbox_rejects_most_tiles_at_zoom_8() {
165        let monaco = Bbox {
166            min_lon: 7.40,
167            min_lat: 43.72,
168            max_lon: 7.44,
169            max_lat: 43.75,
170        };
171        let bounds = TileBounds::from_bbox(&monaco, 15);
172        let n = 1u32 << 8;
173        let mut accepted = 0u32;
174        for x in 0..n {
175            for y in 0..n {
176                if bounds.contains(&TileCoord::new(8, x, y)) {
177                    accepted += 1;
178                }
179            }
180        }
181        // Monaco is tiny — should accept very few tiles at zoom 8
182        assert!(accepted <= 4, "expected ≤4 tiles, got {accepted}");
183        assert!(accepted >= 1, "expected ≥1 tile, got {accepted}");
184    }
185}