1use std::fmt;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, mln_wire::Wire)]
15pub struct CanonicalTileID {
16 pub z: u8,
17 pub x: u32,
18 pub y: u32,
19}
20
21impl CanonicalTileID {
22 #[must_use]
23 pub fn new(z: u8, x: u32, y: u32) -> Self {
24 debug_assert!(z <= 32);
25 debug_assert!(u64::from(x) < (1u64 << z));
26 debug_assert!(u64::from(y) < (1u64 << z));
27 CanonicalTileID { z, x, y }
28 }
29
30 #[must_use]
31 pub fn is_child_of(&self, parent: &CanonicalTileID) -> bool {
32 parent.z == 0
35 || (parent.z < self.z
36 && parent.x == self.x.wrapping_shr(u32::from(self.z - parent.z))
37 && parent.y == self.y.wrapping_shr(u32::from(self.z - parent.z)))
38 }
39
40 #[must_use]
43 pub fn scaled_to(&self, target_z: u8) -> CanonicalTileID {
44 if target_z <= self.z {
45 let shift = (i32::from(self.z) - i32::from(target_z)) as u32;
47 CanonicalTileID::new(target_z, self.x.wrapping_shr(shift), self.y.wrapping_shr(shift))
48 } else {
49 let shift = (i32::from(target_z) - i32::from(self.z)) as u32;
51 CanonicalTileID::new(target_z, self.x.wrapping_shl(shift), self.y.wrapping_shl(shift))
52 }
53 }
54
55 #[must_use]
56 pub fn children(&self) -> [CanonicalTileID; 4] {
57 let child_z = self.z.wrapping_add(1);
58 let child_x = self.x.wrapping_mul(2);
59 let child_y = self.y.wrapping_mul(2);
60 [
61 CanonicalTileID::new(child_z, child_x, child_y),
62 CanonicalTileID::new(child_z, child_x, child_y.wrapping_add(1)),
63 CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y),
64 CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y.wrapping_add(1)),
65 ]
66 }
67}
68
69impl fmt::Display for CanonicalTileID {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "{}/{}/{}", self.z, self.x, self.y)
73 }
74}
75
76#[cfg(test)]
77#[path = "tile_id_test.rs"]
78mod tile_id_test;