1pub const WORLD_WIDTH: i64 = 360_000_000;
3pub const WORLD_HEIGHT: i64 = 180_000_000;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub struct GeoBounds {
7 pub x: i64,
8 pub y: i64,
9 pub width: i64,
10 pub height: i64,
11}
12impl Default for GeoBounds {
13 fn default() -> Self {
14 Self {
15 x: 0,
16 y: 0,
17 width: WORLD_WIDTH,
18 height: WORLD_HEIGHT,
19 }
20 }
21}
22impl GeoBounds {
23 pub fn cell(self, col: usize, row: usize, columns: usize, rows: usize) -> Self {
24 let edge =
25 |n: usize, size: i64, count: usize| (n as i64 * size + count as i64 - 1) / count as i64;
26 let left = edge(col, self.width, columns);
27 let top = edge(row, self.height, rows);
28 Self {
29 x: (self.x + left).rem_euclid(WORLD_WIDTH),
30 y: self.y + top,
31 width: edge(col + 1, self.width, columns) - left,
32 height: edge(row + 1, self.height, rows) - top,
33 }
34 }
35 pub fn project(self, x: i64, y: i64, columns: usize, rows: usize) -> Option<(usize, usize)> {
36 let dx = (x - self.x).rem_euclid(WORLD_WIDTH);
37 let dy = y - self.y;
38 (dx < self.width && dy >= 0 && dy < self.height).then(|| {
39 (
40 (dx * columns as i64 / self.width) as usize,
41 (dy * rows as i64 / self.height) as usize,
42 )
43 })
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum GeoFilter {
49 Cell(GeoBounds),
50 Missing,
51}
52
53pub fn coordinates(lat: Option<f64>, lon: Option<f64>) -> Option<(i64, i64)> {
54 let (lat, lon) = (lat?, lon?);
55 if !lat.is_finite()
56 || !lon.is_finite()
57 || !(-90.0..=90.0).contains(&lat)
58 || !(-180.0..=180.0).contains(&lon)
59 {
60 return None;
61 }
62 Some((
63 ((lon + 180.0) * 1e6).round() as i64 % WORLD_WIDTH,
64 (((90.0 - lat) * 1e6).round() as i64).clamp(0, WORLD_HEIGHT - 1),
65 ))
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71 #[test]
72 fn cells_partition_wrapped_viewports_without_gaps_or_overlap() {
73 for b in [
74 GeoBounds::default(),
75 GeoBounds {
76 x: 350_000_000,
77 y: 10,
78 width: 45_000_000,
79 height: 22_500_000,
80 },
81 ] {
82 for (w, h) in [(7, 3), (100, 25), (319, 79)] {
83 for (lat, lon) in [
84 (-90.0, -180.0),
85 (90.0, 180.0),
86 (0.0, 179.99),
87 (89.0, -179.99),
88 (45.0, 170.0),
89 ] {
90 let (x, y) = coordinates(Some(lat), Some(lon)).unwrap();
91 let projected = b.project(x, y, w, h);
92 let hits: Vec<_> = (0..h)
93 .flat_map(|r| (0..w).map(move |c| (c, r)))
94 .filter(|&(c, r)| b.cell(c, r, w, h).project(x, y, 1, 1).is_some())
95 .collect();
96 assert_eq!(hits, projected.into_iter().collect::<Vec<_>>());
97 }
98 }
99 }
100 }
101}