geolith 0.1.6

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! WGS84 ↔ Web Mercator coordinate transforms.
//!
//! All transforms use the standard Web Mercator (EPSG:3857) projection.
//! World coordinates are normalized to [0, 1] range for tile calculations.

use std::f64::consts::PI;

/// Maximum latitude for Web Mercator projection (~85.051°).
pub const MAX_LAT: f64 = 85.051_128_779_806_59;

/// Minimum latitude for Web Mercator projection (~-85.051°).
pub const MIN_LAT: f64 = -MAX_LAT;

/// Convert longitude to world-X coordinate in [0, 1].
#[inline]
#[must_use]
pub fn lon_to_world_x(lon: f64) -> f64 {
    (lon + 180.0) / 360.0
}

/// Convert latitude to world-Y coordinate in [0, 1].
///
/// Uses the standard Mercator formula with latitude clamped to ±85.051°.
#[inline]
#[must_use]
pub fn lat_to_world_y(lat: f64) -> f64 {
    let lat_rad = lat.clamp(MIN_LAT, MAX_LAT).to_radians();
    let y = (1.0 - (lat_rad.tan() + 1.0 / lat_rad.cos()).ln() / PI) / 2.0;
    y.clamp(0.0, 1.0)
}

/// Convert world-X coordinate [0, 1] back to longitude.
#[inline]
#[must_use]
pub fn world_x_to_lon(x: f64) -> f64 {
    x * 360.0 - 180.0
}

/// Convert world-Y coordinate [0, 1] back to latitude.
#[inline]
#[must_use]
pub fn world_y_to_lat(y: f64) -> f64 {
    let n = PI * (1.0 - 2.0 * y);
    n.sinh().atan().to_degrees()
}

/// Convert WGS84 (lon, lat) to world coordinates (x, y) in [0, 1].
#[inline]
#[must_use]
pub fn wgs84_to_world(lon: f64, lat: f64) -> (f64, f64) {
    (lon_to_world_x(lon), lat_to_world_y(lat))
}

/// Convert world coordinates (x, y) in [0, 1] to WGS84 (lon, lat).
#[inline]
#[must_use]
pub fn world_to_wgs84(x: f64, y: f64) -> (f64, f64) {
    (world_x_to_lon(x), world_y_to_lat(y))
}

/// Tile coordinate at a given zoom level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TileCoord {
    /// Zoom level (0–15).
    pub z: u8,
    /// Tile column.
    pub x: u32,
    /// Tile row.
    pub y: u32,
}

impl TileCoord {
    /// Create a new tile coordinate.
    #[inline]
    #[must_use]
    pub const fn new(z: u8, x: u32, y: u32) -> Self {
        Self { z, x, y }
    }
}

/// Convert world coordinates to the tile that contains them at the given zoom.
#[inline]
#[must_use]
pub fn world_to_tile(x: f64, y: f64, zoom: u8) -> TileCoord {
    let n = (1u32 << zoom) as f64;
    let tx = (x * n).floor() as u32;
    let ty = (y * n).floor() as u32;
    let max = (1u32 << zoom) - 1;
    TileCoord::new(zoom, tx.min(max), ty.min(max))
}

/// Convert world coordinates to fractional tile coordinates at the given zoom.
///
/// Returns `(tile_x_frac, tile_y_frac)` where the integer part is the tile
/// index and the fractional part is the position within the tile.
#[inline]
#[must_use]
pub fn world_to_tile_frac(x: f64, y: f64, zoom: u8) -> (f64, f64) {
    let n = (1u32 << zoom) as f64;
    (x * n, y * n)
}

/// Convert world coordinates to pixel coordinates within a specific tile.
///
/// Returns `(px, py)` in [0, extent) where `extent` is the tile coordinate space
/// (typically 4096 for MVT).
#[inline]
#[must_use]
pub fn world_to_tile_pixel(x: f64, y: f64, tile: TileCoord, extent: u32) -> (f64, f64) {
    let n = (1u32 << tile.z) as f64;
    let px = (x * n - tile.x as f64) * extent as f64;
    let py = (y * n - tile.y as f64) * extent as f64;
    (px, py)
}

/// Douglas-Peucker simplification tolerance per zoom level (in world coordinates).
///
/// At zoom z, features smaller than this tolerance can be simplified away.
/// Roughly: 1 pixel at 256px tile size → tolerance = 1 / (256 * 2^z).
#[inline]
#[must_use]
pub fn simplify_tolerance(zoom: u8) -> f64 {
    1.0 / (256.0 * (1u64 << zoom) as f64)
}

/// The bounding box of a tile in world coordinates.
#[inline]
#[must_use]
pub fn tile_bounds_world(tile: TileCoord) -> (f64, f64, f64, f64) {
    let n = (1u32 << tile.z) as f64;
    let x0 = tile.x as f64 / n;
    let y0 = tile.y as f64 / n;
    let x1 = (tile.x + 1) as f64 / n;
    let y1 = (tile.y + 1) as f64 / n;
    (x0, y0, x1, y1)
}

/// The bounding box of a tile in WGS84 (lon, lat) coordinates.
///
/// Returns `(min_lon, min_lat, max_lon, max_lat)`.
#[must_use]
pub fn tile_bounds_wgs84(tile: TileCoord) -> (f64, f64, f64, f64) {
    let (x0, y0, x1, y1) = tile_bounds_world(tile);
    let (lon0, lat1) = world_to_wgs84(x0, y0); // y0 → higher lat (north)
    let (lon1, lat0) = world_to_wgs84(x1, y1); // y1 → lower lat (south)
    (lon0, lat0, lon1, lat1)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrip_world_coords() {
        let (lon, lat) = (-122.4194, 37.7749); // San Francisco
        let (x, y) = wgs84_to_world(lon, lat);
        let (lon2, lat2) = world_to_wgs84(x, y);
        assert!((lon - lon2).abs() < 1e-10);
        assert!((lat - lat2).abs() < 1e-10);
    }

    #[test]
    fn origin_is_top_left() {
        let (x, y) = wgs84_to_world(-180.0, MAX_LAT);
        assert!((x - 0.0).abs() < 1e-10);
        assert!((y - 0.0).abs() < 1e-3);
    }

    #[test]
    fn tile_at_zoom_0() {
        let tile = world_to_tile(0.5, 0.5, 0);
        assert_eq!(tile, TileCoord::new(0, 0, 0));
    }

    #[test]
    fn tile_at_zoom_1() {
        // Bottom-right quadrant
        let tile = world_to_tile(0.75, 0.75, 1);
        assert_eq!(tile, TileCoord::new(1, 1, 1));
    }

    #[test]
    fn world_to_tile_pixel_center() {
        let tile = TileCoord::new(0, 0, 0);
        let (px, py) = world_to_tile_pixel(0.5, 0.5, tile, 4096);
        assert!((px - 2048.0).abs() < 1e-10);
        assert!((py - 2048.0).abs() < 1e-10);
    }

    #[test]
    fn tile_bounds_zoom_0() {
        let (x0, y0, x1, y1) = tile_bounds_world(TileCoord::new(0, 0, 0));
        assert!((x0 - 0.0).abs() < 1e-10);
        assert!((y0 - 0.0).abs() < 1e-10);
        assert!((x1 - 1.0).abs() < 1e-10);
        assert!((y1 - 1.0).abs() < 1e-10);
    }

    #[test]
    fn simplify_tolerance_decreases_with_zoom() {
        for z in 0..14 {
            assert!(simplify_tolerance(z) > simplify_tolerance(z + 1));
        }
    }
}