use crate::geometry::mercator::TileCoord;
#[must_use]
pub const fn xy_to_hilbert(x: u32, y: u32, level: u8) -> u64 {
if level == 0 {
return 0;
}
let mut rx: u32;
let mut ry: u32;
let mut d: u64 = 0;
let mut x = x;
let mut y = y;
let mut s: u32 = 1 << (level - 1);
while s > 0 {
rx = if (x & s) > 0 { 1 } else { 0 };
ry = if (y & s) > 0 { 1 } else { 0 };
d += (s as u64) * (s as u64) * ((3 * rx) ^ ry) as u64;
if ry == 0 {
if rx == 1 {
x = s.wrapping_mul(2).wrapping_sub(1).wrapping_sub(x);
y = s.wrapping_mul(2).wrapping_sub(1).wrapping_sub(y);
}
std::mem::swap(&mut x, &mut y);
}
s >>= 1;
}
d
}
#[must_use]
pub const fn hilbert_to_xy(d: u64, level: u8) -> (u32, u32) {
let mut rx: u32;
let mut ry: u32;
let mut x: u32 = 0;
let mut y: u32 = 0;
let mut t = d;
let mut s: u32 = 1;
while s < (1u32 << level) {
rx = (1 & (t / 2)) as u32;
ry = (1 & (t ^ rx as u64)) as u32;
if ry == 0 {
if rx == 1 {
x = s.wrapping_sub(1).wrapping_sub(x);
y = s.wrapping_sub(1).wrapping_sub(y);
}
std::mem::swap(&mut x, &mut y);
}
x += s * rx;
y += s * ry;
t /= 4;
s *= 2;
}
(x, y)
}
#[must_use]
pub fn tile_to_pmtiles_id(tile: TileCoord) -> u64 {
let base: u64 = (0..tile.z).map(|z| 1u64 << (2 * z)).sum();
base + xy_to_hilbert(tile.x, tile.y, tile.z)
}
#[must_use]
pub const fn pmtiles_id_to_tile(id: u64) -> TileCoord {
let mut acc: u64 = 0;
let mut z: u8 = 0;
loop {
let tiles_at_z = 1u64 << (2 * z);
if acc + tiles_at_z > id {
break;
}
acc += tiles_at_z;
z += 1;
}
let (x, y) = hilbert_to_xy(id - acc, z);
TileCoord::new(z, x, y)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hilbert_roundtrip() {
for level in 1..=8u8 {
let n = 1u32 << level;
let max_d = (n as u64) * (n as u64);
for d in 0..max_d.min(256) {
let (x, y) = hilbert_to_xy(d, level);
let d2 = xy_to_hilbert(x, y, level);
assert_eq!(d, d2, "level={level}, d={d}");
}
}
}
#[test]
fn pmtiles_id_roundtrip() {
let cases = [
TileCoord::new(0, 0, 0),
TileCoord::new(1, 0, 0),
TileCoord::new(1, 1, 1),
TileCoord::new(2, 3, 3),
TileCoord::new(5, 10, 20),
];
for tile in cases {
let id = tile_to_pmtiles_id(tile);
let decoded = pmtiles_id_to_tile(id);
assert_eq!(tile, decoded, "tile={tile:?}");
}
}
#[test]
fn pmtiles_id_zoom_0_is_zero() {
assert_eq!(tile_to_pmtiles_id(TileCoord::new(0, 0, 0)), 0);
}
#[test]
fn pmtiles_id_zoom_1_starts_at_1() {
let id = tile_to_pmtiles_id(TileCoord::new(1, 0, 0));
assert!(id >= 1);
assert!(id < 5);
}
}