geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Pre-computed per-zoom tile ranges for bbox filtering.
//!
//! Converts a WGS84 bounding box into integer tile ranges at each zoom level,
//! enabling O(1) tile containment checks (4 integer comparisons) instead of
//! expensive coordinate-based intersection tests.
//!
//! This is the Rust equivalent of Planetiler's `TileExtents` — the single
//! biggest performance optimization for regional (bbox-filtered) tile builds.

use crate::geometry::mercator;
use crate::source::bbox_filter::Bbox;

/// Per-zoom tile range: (`min_x`, `max_x`, `min_y`, `max_y`) inclusive.
#[derive(Debug, Clone, Copy)]
struct ZoomRange {
    min_x: u32,
    max_x: u32,
    min_y: u32,
    max_y: u32,
}

/// Pre-computed tile ranges for a bounding box at every zoom level.
///
/// Created once at pipeline startup from the `--bbox` argument.
/// Each `contains()` check is 4 integer comparisons — essentially free
/// compared to the geometry processing it guards.
#[derive(Debug, Clone)]
pub struct TileBounds {
    /// Per-zoom tile range, indexed by zoom level.
    ranges: Vec<ZoomRange>,
}

impl TileBounds {
    /// Build tile ranges for every zoom level from 0 to `max_zoom` (inclusive).
    ///
    /// Converts the WGS84 bbox corners to world coordinates, then to tile
    /// indices at each zoom. Tile ranges are clamped to valid tile indices.
    #[must_use]
    pub fn from_bbox(bbox: &Bbox, max_zoom: u8) -> Self {
        let (world_min_x, world_min_y) = mercator::wgs84_to_world(bbox.min_lon, bbox.max_lat);
        let (world_max_x, world_max_y) = mercator::wgs84_to_world(bbox.max_lon, bbox.min_lat);

        let mut ranges = Vec::with_capacity((max_zoom as usize) + 1);

        for z in 0..=max_zoom {
            let n = 1u32 << z;
            let max_tile = n.saturating_sub(1);

            // Convert world [0,1] to tile indices, clamped to valid range.
            // Floor for min, floor for max (tile containing the max point).
            let min_x = ((world_min_x * n as f64).floor() as u32).min(max_tile);
            let max_x = ((world_max_x * n as f64).floor() as u32).min(max_tile);
            let min_y = ((world_min_y * n as f64).floor() as u32).min(max_tile);
            let max_y = ((world_max_y * n as f64).floor() as u32).min(max_tile);

            ranges.push(ZoomRange {
                min_x,
                max_x,
                min_y,
                max_y,
            });
        }

        Self { ranges }
    }

    /// Check if a tile coordinate falls within the pre-computed bounds.
    ///
    /// Returns `true` if the tile is within or on the boundary of the
    /// bbox tile range at its zoom level. Tiles outside the range are
    /// skipped, avoiding all downstream geometry processing.
    #[inline]
    #[must_use]
    pub fn contains(&self, tile: &mercator::TileCoord) -> bool {
        let z = tile.z as usize;
        if z >= self.ranges.len() {
            return false;
        }
        let r = &self.ranges[z];
        tile.x >= r.min_x && tile.x <= r.max_x && tile.y >= r.min_y && tile.y <= r.max_y
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::mercator::TileCoord;

    /// India Western Zone bbox from the benchmark.
    fn western_zone_bbox() -> Bbox {
        Bbox {
            min_lon: 67.67,
            min_lat: 14.39,
            max_lon: 80.92,
            max_lat: 24.72,
        }
    }

    #[test]
    fn zoom_0_always_contains_single_tile() {
        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
        assert!(bounds.contains(&TileCoord::new(0, 0, 0)));
    }

    #[test]
    fn zoom_1_contains_correct_quadrant() {
        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
        // India Western Zone is in the eastern hemisphere, northern half
        // Tile (1, 1, 0) = NE quadrant — should contain
        assert!(bounds.contains(&TileCoord::new(1, 1, 0)));
        // Tile (1, 0, 1) = SW quadrant — should NOT contain
        assert!(!bounds.contains(&TileCoord::new(1, 0, 1)));
    }

    #[test]
    fn tiles_outside_bbox_rejected() {
        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
        // Tile at zoom 4: x=0 is western Americas — far from India
        assert!(!bounds.contains(&TileCoord::new(4, 0, 5)));
        // Tile at zoom 4: x=15 is far east Pacific — far from India
        assert!(!bounds.contains(&TileCoord::new(4, 15, 5)));
    }

    #[test]
    fn tiles_inside_bbox_accepted() {
        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 15);
        // At zoom 4, India Western Zone should be around x=11, y=5-6
        // lon 67.67 → world_x = (67.67+180)/360 ≈ 0.688 → tile_x = floor(0.688*16) = 11
        // lat 24.72 → world_y ≈ 0.412 → tile_y = floor(0.412*16) = 6
        assert!(bounds.contains(&TileCoord::new(4, 11, 6)));
    }

    #[test]
    fn zoom_beyond_max_returns_false() {
        let bounds = TileBounds::from_bbox(&western_zone_bbox(), 10);
        // Zoom 11 is beyond max_zoom=10 — should return false
        assert!(!bounds.contains(&TileCoord::new(11, 0, 0)));
    }

    #[test]
    fn full_planet_bbox_accepts_all_tiles() {
        let planet = Bbox {
            min_lon: -180.0,
            min_lat: -85.05,
            max_lon: 180.0,
            max_lat: 85.05,
        };
        let bounds = TileBounds::from_bbox(&planet, 5);
        // Every tile at every zoom should be accepted
        for z in 0..=5 {
            let n = 1u32 << z;
            for x in 0..n {
                for y in 0..n {
                    assert!(
                        bounds.contains(&TileCoord::new(z, x, y)),
                        "planet bbox should contain tile z={z} x={x} y={y}"
                    );
                }
            }
        }
    }

    #[test]
    fn monaco_bbox_rejects_most_tiles_at_zoom_8() {
        let monaco = Bbox {
            min_lon: 7.40,
            min_lat: 43.72,
            max_lon: 7.44,
            max_lat: 43.75,
        };
        let bounds = TileBounds::from_bbox(&monaco, 15);
        let n = 1u32 << 8;
        let mut accepted = 0u32;
        for x in 0..n {
            for y in 0..n {
                if bounds.contains(&TileCoord::new(8, x, y)) {
                    accepted += 1;
                }
            }
        }
        // Monaco is tiny — should accept very few tiles at zoom 8
        assert!(accepted <= 4, "expected ≤4 tiles, got {accepted}");
        assert!(accepted >= 1, "expected ≥1 tile, got {accepted}");
    }
}