git clone https://garage44.eu/jeroen/cartopolis.git.. /crates/core/src/world.rs
//! Canonical coordinate + OSM tile mapping (ADR-006).
use serde::{Deserialize, Serialize};
/// OSM slippy-map tile key (z/x/y).
///
/// `Copy`, not just `Clone`: it is 20 bytes of plain data, and the client's tile
/// streamers rebuild whole desired-sets of it every frame — the z10–z17 clipmap
/// alone is ~850 keys per pass (`cartopolis::systems::map_stream`). As `Clone`-only
/// every one of those was an explicit `.clone()` in a hot loop that reads as if it
/// meant something.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct TileKey {
pub x: i64,
pub y: i64,
pub z: u32,
}
impl TileKey {
#[must_use]
pub fn new(x: i64, y: i64, z: u32) -> Self {
Self { x, y, z }
}
/// Path segment for `.../{z}/{x}/{y}.png`
#[must_use]
pub fn to_path(&self) -> String {
format!("{}/{}/{}", self.z, self.x, self.y)
}
}
const EARTH_RADIUS: f64 = 6_378_137.0;
const EARTH_CIRCUMFERENCE: f64 = 2.0 * std::f64::consts::PI * EARTH_RADIUS;
/// The zoom a lat/lng is turned into a tile key at when nothing else says
/// otherwise (ADR-004 / ADR-006) — street level.
pub const DEFAULT_TILE_ZOOM: u32 = 17;
/// Default map tile source: our **self-hosted** VersaTiles **vector** (Shortbread
/// MVT) server, the client-side tessellated-and-lit basemap of ADR-035. This is a
/// garage44 mirror of `download.versatiles.org`'s planet archive (z0–14), served by
/// the `versatiles` server behind Caddy — same schema and URL shape as the public
/// `tiles.versatiles.org`, so it is a drop-in origin swap off their hosting.
/// Shared so the sim's advertised default (`cartopolis_simulator::config`) and the client's
/// offline/`--shot` fallback (`cartopolis::systems::tile_loader`) cannot drift apart —
/// a mismatch there is how solo mode silently renders the old raster tiles instead
/// of the vector map.
///
/// A `{z}/{x}/{y}` template with **no extension**, which `tile_source_kind`
/// classifies as vector. Override per-run with `CARTO_TILE_URL` (client) or the
/// sim's `osm_tile_url_template` config; a raster template (e.g. one ending
/// `.png`) still works and falls back to the pre-rendered path.
pub const DEFAULT_TILE_URL_TEMPLATE: &str = "https://tiles.cartopolis.org/tiles/osm/{z}/{x}/{y}";
/// Build tile URL from template (`{z}`, `{x}`, `{y}`) or the default vector source
/// ([`DEFAULT_TILE_URL_TEMPLATE`], ADR-035). An empty template
/// only reaches here offline / under `--shot`; solo and split mode fill it from the
/// sim handshake first.
#[must_use]
pub fn format_osm_tile_url(template: &str, key: &TileKey) -> String {
let template = if template.is_empty() {
DEFAULT_TILE_URL_TEMPLATE
} else {
template
};
template
.replace("{z}", &key.z.to_string())
.replace("{x}", &key.x.to_string())
.replace("{y}", &key.y.to_string())
}
/// What a tile endpoint serves. Raster payloads are decoded by the `image` crate;
/// vector payloads are drawn by `cartopolis_geo::vector_tiles`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TileSourceKind {
Raster,
Vector,
}
/// Classify a URL template by the tail after its `{y}` placeholder: `.png`/`.webp`
/// → raster, nothing at all → vector (VersaTiles serves `/tiles/osm/{z}/{x}/{y}`
/// with no extension). `CARTO_TILE_FORMAT=vector|raster` overrides.
///
/// This has to be decided *before* the fetch rather than sniffed from the bytes,
/// because a vector source caps out at `MAX_SOURCE_ZOOM` and the deeper tiles the
/// map streamer asks for must be redirected to an ancestor — which changes which
/// URL we request. The byte sniff in `looks_like_raster` still runs afterwards as
/// a backstop, so a misclassified source degrades to "no overzoom" rather than to
/// a decode failure.
#[must_use]
pub fn tile_source_kind(template: &str) -> TileSourceKind {
if let Ok(v) = std::env::var("CARTO_TILE_FORMAT") {
match v.to_ascii_lowercase().as_str() {
"vector" | "mvt" | "pbf" => return TileSourceKind::Vector,
"raster" | "png" | "webp" | "jpeg" => return TileSourceKind::Raster,
_ => {}
}
}
match template.rsplit_once("{y}") {
// An extension right after `{y}` means pre-rendered pixels.
Some((_, tail)) => {
let tail = tail.split('?').next().unwrap_or("");
if tail.starts_with('.') {
TileSourceKind::Raster
} else {
TileSourceKind::Vector
}
}
// Empty/!templated → the built-in default, which is now the VersaTiles
// vector source (`DEFAULT_TILE_URL_TEMPLATE`), so classify it as such.
None => TileSourceKind::Vector,
}
}
/// WGS84 → fractional Web Mercator tile coordinate at a zoom (no flooring).
///
/// The sub-tile fraction is what anything positioning *within* a tile needs — the
/// streamer's centre offsets, the router's corridor endpoints, a metre offset
/// turned back into a tile coordinate.
#[must_use]
pub fn lat_lng_to_tile_frac(lat: f64, lng: f64, zoom: u32) -> (f64, f64) {
let n = 2.0_f64.powi(zoom as i32);
let x = (lng + 180.0) / 360.0 * n;
let lat_rad = lat.to_radians();
let y = (1.0 - (lat_rad.tan() + 1.0 / lat_rad.cos()).ln() / std::f64::consts::PI) / 2.0 * n;
(x, y)
}
/// WGS84 → OSM tile index (Web Mercator).
#[must_use]
pub fn lat_lng_to_tile(lat: f64, lng: f64, zoom: u32) -> (i64, i64) {
let (x, y) = lat_lng_to_tile_frac(lat, lng, zoom);
(x.floor() as i64, y.floor() as i64)
}
/// Fractional Web Mercator tile coordinate → WGS84, the exact inverse of
/// [`lat_lng_to_tile_frac`].
///
/// A place *inside* a tile is where most answers land — a metre offset in a
/// tile-local mesh, a tunnel's midpoint, a corridor endpoint — and saying where
/// one of those is on Earth took flooring to the corner and losing the rest.
#[must_use]
pub fn tile_frac_to_lat_lng(x: f64, y: f64, zoom: u32) -> (f64, f64) {
let n = 2.0_f64.powi(zoom as i32);
let lng = (x / n) * 360.0 - 180.0;
let lat_rad = ((1.0 - (2.0 * y) / n) * std::f64::consts::PI).sinh().atan();
(lat_rad.to_degrees(), lng)
}
/// Tile corner (north-west) as WGS84.
#[must_use]
pub fn tile_to_lat_lng(x: i64, y: i64, zoom: u32) -> (f64, f64) {
tile_frac_to_lat_lng(x as f64, y as f64, zoom)
}
#[must_use]
pub fn tile_to_meters(zoom: u32, lat: f64) -> f64 {
let lat_rad = lat.to_radians();
let meters_per_pixel =
(EARTH_CIRCUMFERENCE * lat_rad.cos()) / (256.0 * 2.0_f64.powi(zoom as i32));
meters_per_pixel * 256.0
}
#[must_use]
pub fn find_optimal_zoom(target_meters: f64, lat: f64) -> u32 {
let mut best_zoom = 0;
let mut best_diff = f64::INFINITY;
for zoom in 0..=19 {
let meters = tile_to_meters(zoom, lat);
let diff = (meters - target_meters).abs();
if diff < best_diff {
best_diff = diff;
best_zoom = zoom;
}
}
best_zoom
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_relative_eq;
#[test]
fn groningen_tile_roundtrip_rough() {
let lat = 53.2194_f64;
let lng = 6.5665_f64;
let (x, y) = lat_lng_to_tile(lat, lng, DEFAULT_TILE_ZOOM);
let (lat2, lng2) = tile_to_lat_lng(x, y, DEFAULT_TILE_ZOOM);
assert_relative_eq!(lat, lat2, epsilon = 0.05);
assert_relative_eq!(lng, lng2, epsilon = 0.05);
}
}