Skip to main content

mln_engine/tile/
tile_range.rs

1use geometry::Point;
2use mln_style::constants;
3use mln_style::geo::{LatLng, LatLngBounds};
4use mln_style::math::{clamp_f64, wrap};
5use mln_style::range::Range;
6use mln_style::tile_id::CanonicalTileID;
7
8use crate::geo::projection::Projection;
9
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct TileRange {
12    pub range: Range<Point<u32>>,
13    pub(crate) zoom_range: Range<u8>,
14}
15
16impl TileRange {
17    /// Compute the range of tiles covered by the bounds at maxZoom.
18    #[must_use]
19    pub fn from_lat_lng_bounds_range(bounds: &LatLngBounds, mut min_zoom: u8, mut max_zoom: u8) -> TileRange {
20        if min_zoom > max_zoom {
21            std::mem::swap(&mut min_zoom, &mut max_zoom);
22        }
23
24        // Wrap the west edge into the world and keep the bounds' width, so
25        // unwrapped longitudes name the same columns as wrapped ones. `%` (fmod)
26        // is exact, so it goes first, before any rounding: a huge longitude
27        // still lands on its own meridian. The width of bounds with huge
28        // longitudes can overflow to infinity, which covers the world. An
29        // inverted interval counts as its west edge.
30        let west = wrap(bounds.west() % constants::DEGREES_MAX, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
31        let width = f64::max(bounds.east() - bounds.west(), 0.0);
32        let covers_world = width.is_nan() || width >= constants::DEGREES_MAX;
33        let max_tile = 2.0f64.powf(f64::from(max_zoom));
34        // C++ `LatLng(lat, lon)` throws for a NaN or infinite edge, which
35        // these finite, in-range edges can't be.
36        let (Ok(sw), Ok(ne)) = (
37            LatLng::new(bounds.south(), west),
38            LatLng::new(bounds.north(), if covers_world { west } else { west + width }),
39        ) else {
40            debug_assert!(false, "LatLng from LatLngBounds coordinates");
41            let max = (max_tile - 1.0) as u32;
42            return TileRange {
43                range: Range::new(Point::new(0, 0), Point::new(max, max)),
44                zoom_range: Range::new(min_zoom, max_zoom),
45            };
46        };
47        let sw_proj = Projection::project_zoom(&sw, i32::from(max_zoom));
48        let ne_proj = Projection::project_zoom(&ne, i32::from(max_zoom));
49
50        // Port-only, ahead of ffi patch 0076 (maplibre-native-ffi#1759): an
51        // east edge at 180° ends in the last column. Uncapped, it named the
52        // column past the last, which wrapped to column 0. A west edge just
53        // under 180° can round to 180° when projected, so it's capped too.
54        let west_column = sw_proj.x.floor().min(max_tile - 1.0);
55        let east_column = if west + width <= constants::LONGITUDE_MAX {
56            ne_proj.x.floor().min(max_tile - 1.0)
57        } else {
58            ne_proj.x.floor()
59        };
60        let mut min_x = 0u32;
61        let mut max_x = (max_tile - 1.0) as u32;
62        // Bounds that reach every column cover the world. Otherwise, bounds
63        // that cross the antimeridian end east of the last column, and wrap.
64        if !covers_world && east_column - west_column + 1.0 < max_tile {
65            min_x = west_column as u32;
66            max_x = (if east_column < max_tile { east_column } else { east_column - max_tile }) as u32;
67        }
68        let min_y = clamp_f64(ne_proj.y.floor(), 0.0, max_tile) as u32;
69        let max_y = clamp_f64(sw_proj.y.floor(), 0.0, max_tile) as u32;
70
71        TileRange {
72            range: Range::new(Point::new(min_x, min_y), Point::new(max_x, max_y)),
73            zoom_range: Range::new(min_zoom, max_zoom),
74        }
75    }
76
77    /// Compute the range of tiles covered by the bounds.
78    #[must_use]
79    pub fn from_lat_lng_bounds(bounds: &LatLngBounds, z: u8) -> TileRange {
80        Self::from_lat_lng_bounds_range(bounds, z, z)
81    }
82
83    #[must_use]
84    pub fn contains(&self, tile_id: &CanonicalTileID) -> bool {
85        if tile_id.z <= self.zoom_range.max && tile_id.z >= self.zoom_range.min {
86            if tile_id.z == 0 {
87                return true;
88            }
89            let dz = self.zoom_range.max - tile_id.z;
90            let x0 = self.range.min.x.wrapping_shr(u32::from(dz));
91            let x1 = self.range.max.x.wrapping_shr(u32::from(dz));
92            let y0 = self.range.min.y.wrapping_shr(u32::from(dz));
93            let y1 = self.range.max.y.wrapping_shr(u32::from(dz));
94            return (if self.range.min.x > self.range.max.x {
95                // For wrapped bounds
96                tile_id.x >= x0 || tile_id.x <= x1
97            } else {
98                tile_id.x <= x1 && tile_id.x >= x0
99            }) && tile_id.y <= y1
100                && tile_id.y >= y0;
101        }
102        false
103    }
104}