pub const WORLD_EXTENT: f64 = 20_037_508.342_789_244;
#[must_use]
pub fn mercator_to_tile_fraction(x: f64, y: f64, zoom: u8) -> (f64, f64) {
let scale = f64::from(1_u32 << zoom);
let tx = (x + WORLD_EXTENT) / (2.0 * WORLD_EXTENT) * scale;
let ty = (WORLD_EXTENT - y) / (2.0 * WORLD_EXTENT) * scale;
(tx, ty)
}
#[must_use]
pub fn tile_range_for_bounds(bounds: (f64, f64, f64, f64), zoom: u8) -> (u32, u32, u32, u32) {
let (min_lon, min_lat, max_lon, max_lat) = bounds;
let max_index = (1_u32 << zoom) - 1;
let (min_x, max_y_merc) = wgs84_to_mercator(min_lon, min_lat);
let (max_x, min_y_merc) = wgs84_to_mercator(max_lon, max_lat);
let (tx0, ty0) = mercator_to_tile_fraction(min_x, min_y_merc, zoom);
let (tx1, ty1) = mercator_to_tile_fraction(max_x, max_y_merc, zoom);
(
(tx0.floor().max(0.0) as u32).min(max_index),
(ty0.floor().max(0.0) as u32).min(max_index),
(tx1.ceil().max(0.0) as u32).min(max_index),
(ty1.ceil().max(0.0) as u32).min(max_index),
)
}
#[must_use]
pub fn wgs84_to_mercator(lon: f64, lat: f64) -> (f64, f64) {
const R: f64 = 6_378_137.0;
let x = lon.to_radians() * R;
let clamped = lat.clamp(-85.051_128_78, 85.051_128_78).to_radians();
let y = (std::f64::consts::FRAC_PI_4 + clamped / 2.0).tan().ln() * R;
(x, y)
}