Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-tiler/src/tilemath.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Mathématiques de tuiles : Web Mercator (EPSG:3857), pyramide XYZ, identifiants de Hilbert (PMTiles v3).8889pub const EARTH_HALF: f64 = 20037508.342789244;90pub const EXTENT: u32 = 4096;91pub const MAX_ZOOM: u8 = 14;9293#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]94pub struct Tile {95 pub z: u8,96 pub x: u32,97 pub y: u32,98}99100impl Tile {101 /// Valide les bornes ; `None` pour toute requête absurde.102 pub fn new(z: u8, x: u32, y: u32) -> Option<Tile> {103 if z > MAX_ZOOM {104 return None;105 }106 let n = 1u32 << z;107 if x >= n || y >= n {108 return None;109 }110 Some(Tile { z, x, y })111 }112113 /// Emprise en mètres Web Mercator : (xmin, ymin, xmax, ymax).114 pub fn bounds_3857(&self) -> (f64, f64, f64, f64) {115 let n = (1u64 << self.z) as f64;116 let size = 2.0 * EARTH_HALF / n;117 let xmin = -EARTH_HALF + self.x as f64 * size;118 let ymax = EARTH_HALF - self.y as f64 * size;119 (xmin, ymax - size, xmin + size, ymax)120 }121122 /// Taille d'une unité de tuile (1/4096) en mètres Mercator.123 pub fn unit(&self) -> f64 {124 unit_at(self.z)125 }126127 pub fn parent(&self) -> Option<Tile> {128 if self.z == 0 {129 None130 } else {131 Some(Tile { z: self.z - 1, x: self.x / 2, y: self.y / 2 })132 }133 }134135 pub fn children(&self) -> [Tile; 4] {136 let (z, x, y) = (self.z + 1, self.x * 2, self.y * 2);137 [Tile { z, x, y }, Tile { z, x: x + 1, y }, Tile { z, x, y: y + 1 }, Tile { z, x: x + 1, y: y + 1 }]138 }139140 /// Identifiant PMTiles v3 : cumul des zooms précédents + position sur la courbe de Hilbert.141 pub fn hilbert_id(&self) -> u64 {142 let mut acc: u64 = 0;143 for i in 0..self.z {144 acc += 1u64 << (2 * i as u64);145 }146 let n: u64 = 1 << self.z;147 let (mut x, mut y) = (self.x as u64, self.y as u64);148 let mut d: u64 = 0;149 let mut s = n / 2;150 while s > 0 {151 let rx = ((x & s) > 0) as u64;152 let ry = ((y & s) > 0) as u64;153 d += s * s * ((3 * rx) ^ ry);154 // rotation155 if ry == 0 {156 if rx == 1 {157 x = s.wrapping_sub(1).wrapping_sub(x) & (n - 1);158 y = s.wrapping_sub(1).wrapping_sub(y) & (n - 1);159 // équivalent de x = n-1-x restreint au sous-carré courant160 }161 std::mem::swap(&mut x, &mut y);162 }163 s /= 2;164 }165 acc + d166 }167168 pub fn from_hilbert_id(id: u64) -> Option<Tile> {169 let mut acc: u64 = 0;170 for z in 0u8..=31 {171 let count = 1u64 << (2 * z as u64);172 if id < acc + count {173 let n: u64 = 1 << z;174 let mut t = id - acc;175 let (mut x, mut y) = (0u64, 0u64);176 let mut s: u64 = 1;177 while s < n {178 let rx = 1 & (t / 2);179 let ry = 1 & (t ^ rx);180 if ry == 0 {181 if rx == 1 {182 x = s - 1 - x;183 y = s - 1 - y;184 }185 std::mem::swap(&mut x, &mut y);186 }187 x += s * rx;188 y += s * ry;189 t /= 4;190 s *= 2;191 }192 return Some(Tile { z, x: x as u32, y: y as u32 });193 }194 acc += count;195 }196 None197 }198}199200pub fn unit_at(z: u8) -> f64 {201 2.0 * EARTH_HALF / (EXTENT as f64) / ((1u64 << z) as f64)202}203204pub fn lonlat_to_3857(lon: f64, lat: f64) -> (f64, f64) {205 let lat = lat.clamp(-85.0511287798066, 85.0511287798066);206 let x = lon * EARTH_HALF / 180.0;207 let y = ((90.0 + lat) * std::f64::consts::PI / 360.0).tan().ln() * EARTH_HALF / std::f64::consts::PI;208 (x, y)209}210211pub fn lonlat_to_tile(lon: f64, lat: f64, z: u8) -> Tile {212 let n = (1u64 << z) as f64;213 let (mx, my) = lonlat_to_3857(lon, lat);214 let fx = (mx + EARTH_HALF) / (2.0 * EARTH_HALF) * n;215 let fy = (EARTH_HALF - my) / (2.0 * EARTH_HALF) * n;216 let max = (n - 1.0).max(0.0);217 Tile { z, x: fx.floor().clamp(0.0, max) as u32, y: fy.floor().clamp(0.0, max) as u32 }218}219220/// Emprise géographique (degrés) : ouest, sud, est, nord.221#[derive(Clone, Copy, Debug, PartialEq)]222pub struct BBox {223 pub w: f64,224 pub s: f64,225 pub e: f64,226 pub n: f64,227}228229impl BBox {230 pub const WORLD: BBox = BBox { w: -180.0, s: -85.0511, e: 180.0, n: 85.0511 };231232 pub fn parse(s: &str) -> Option<BBox> {233 let v: Vec<f64> = s.split(',').map(|p| p.trim().parse::<f64>()).collect::<Result<_, _>>().ok()?;234 if v.len() != 4 || v[0] >= v[2] || v[1] >= v[3] {235 return None;236 }237 if v[0] < -180.0 || v[2] > 180.0 || v[1] < -90.0 || v[3] > 90.0 {238 return None;239 }240 Some(BBox { w: v[0], s: v[1], e: v[2], n: v[3] })241 }242243 /// Plage de tuiles couvrant l'emprise au zoom `z` : (xmin, ymin, xmax, ymax) inclusifs.244 pub fn tile_range(&self, z: u8) -> (u32, u32, u32, u32) {245 let a = lonlat_to_tile(self.w, self.n, z);246 // bord est/sud exclusif : on recule d'un epsilon pour ne pas déborder sur la tuile voisine247 let b = lonlat_to_tile(self.e - 1e-9, self.s + 1e-9, z);248 (a.x, a.y, b.x.max(a.x), b.y.max(a.y))249 }250251 pub fn tiles(&self, z: u8) -> Vec<Tile> {252 let (x0, y0, x1, y1) = self.tile_range(z);253 let mut v = Vec::with_capacity(((x1 - x0 + 1) as usize) * ((y1 - y0 + 1) as usize));254 for x in x0..=x1 {255 for y in y0..=y1 {256 v.push(Tile { z, x, y });257 }258 }259 v260 }261262 pub fn tile_count(&self, z: u8) -> u64 {263 let (x0, y0, x1, y1) = self.tile_range(z);264 (x1 - x0 + 1) as u64 * (y1 - y0 + 1) as u64265 }266}267268#[cfg(test)]269mod tests {270 use super::*;271272 #[test]273 fn validation() {274 assert!(Tile::new(0, 0, 0).is_some());275 assert!(Tile::new(0, 1, 0).is_none());276 assert!(Tile::new(14, 16383, 16383).is_some());277 assert!(Tile::new(14, 16384, 0).is_none());278 assert!(Tile::new(15, 0, 0).is_none());279 assert!(Tile::new(255, 0, 0).is_none());280 }281282 #[test]283 fn bounds() {284 let (a, b, c, d) = Tile::new(0, 0, 0).unwrap().bounds_3857();285 assert!((a + EARTH_HALF).abs() < 1e-6 && (b + EARTH_HALF).abs() < 1e-6);286 assert!((c - EARTH_HALF).abs() < 1e-6 && (d - EARTH_HALF).abs() < 1e-6);287 let (a, b, c, d) = Tile::new(1, 1, 0).unwrap().bounds_3857();288 assert!(a.abs() < 1e-6 && b.abs() < 1e-6 && (c - EARTH_HALF).abs() < 1e-6 && (d - EARTH_HALF).abs() < 1e-6);289 assert!((unit_at(14) - 0.5971642834779395).abs() < 1e-9);290 }291292 #[test]293 fn montreal_tile() {294 // Référence calculée indépendamment (formule OSM « slippy map ») : z14 → 4843/5861 ; z10 → 302/366.295 let t = lonlat_to_tile(-73.5674, 45.5019, 14);296 assert_eq!((t.x, t.y), (4843, 5861));297 let t10 = lonlat_to_tile(-73.5674, 45.5019, 10);298 assert_eq!((t10.x, t10.y), (302, 366));299 let (x0, y0, x1, y1) = t.bounds_3857();300 let (mx, my) = lonlat_to_3857(-73.5674, 45.5019);301 assert!(mx >= x0 && mx < x1 && my >= y0 && my < y1);302 assert_eq!(t.parent().unwrap().children().iter().filter(|c| **c == t).count(), 1);303 }304305 #[test]306 fn hilbert_reference_values() {307 // Valeurs de la spécification PMTiles v3.308 assert_eq!(Tile { z: 0, x: 0, y: 0 }.hilbert_id(), 0);309 assert_eq!(Tile { z: 1, x: 0, y: 0 }.hilbert_id(), 1);310 assert_eq!(Tile { z: 1, x: 0, y: 1 }.hilbert_id(), 2);311 assert_eq!(Tile { z: 1, x: 1, y: 1 }.hilbert_id(), 3);312 assert_eq!(Tile { z: 1, x: 1, y: 0 }.hilbert_id(), 4);313 assert_eq!(Tile { z: 2, x: 0, y: 0 }.hilbert_id(), 5);314 assert_eq!(Tile { z: 12, x: 3423, y: 1763 }.hilbert_id(), 19078479);315 }316317 #[test]318 fn hilbert_roundtrip_and_bijection() {319 for z in 0u8..=6 {320 let n = 1u32 << z;321 let mut seen = std::collections::HashSet::new();322 let base: u64 = (0..z).map(|i| 1u64 << (2 * i as u64)).sum();323 for x in 0..n {324 for y in 0..n {325 let t = Tile { z, x, y };326 let id = t.hilbert_id();327 assert!(id >= base && id < base + (n as u64) * (n as u64));328 assert!(seen.insert(id));329 assert_eq!(Tile::from_hilbert_id(id), Some(t));330 }331 }332 }333 for &(z, x, y) in &[(14u8, 4843u32, 5859u32), (14, 16383, 0), (13, 1, 8190), (10, 302, 366)] {334 let t = Tile { z, x, y };335 assert_eq!(Tile::from_hilbert_id(t.hilbert_id()), Some(t));336 }337 }338339 #[test]340 fn hilbert_adjacency() {341 // Deux identifiants consécutifs désignent des tuiles voisines (propriété de la courbe).342 for id in 5u64..(5 + 16 + 64 + 256 + 1024) {343 let a = Tile::from_hilbert_id(id).unwrap();344 let b = Tile::from_hilbert_id(id + 1).unwrap();345 if a.z == b.z {346 let d = (a.x as i64 - b.x as i64).abs() + (a.y as i64 - b.y as i64).abs();347 assert_eq!(d, 1, "{:?} {:?}", a, b);348 }349 }350 }351352 #[test]353 fn bbox_ranges() {354 let b = BBox::parse("-74.0,45.4,-73.4,45.7").unwrap();355 assert_eq!(b.tile_count(0), 1);356 let (x0, y0, x1, y1) = b.tile_range(10);357 assert!(x0 <= 302 && x1 >= 302 && y0 <= 366 && y1 >= 366);358 assert!(BBox::parse("1,2,3").is_none());359 assert!(BBox::parse("10,0,-10,5").is_none());360 assert_eq!(BBox::WORLD.tile_count(3), 64);361 }362}363