Skip to main content

basemapper_core/
bbox.rs

1use crate::error::BasemapError;
2use crate::style::StyleInput;
3
4const EARTH_HALF: f64 = 20_037_508.342_789_244;
5const EARTH_CIRC: f64 = EARTH_HALF * 2.0;
6
7#[derive(Debug, Clone)]
8pub struct SpatialBounds {
9    pub xmin: f64,
10    pub ymin: f64,
11    pub xmax: f64,
12    pub ymax: f64,
13    pub crs_epsg: u32,
14}
15
16#[derive(Debug, Clone)]
17pub struct RenderRequest {
18    pub bbox: [f64; 4],
19    pub width: u32,
20    pub height: u32,
21    pub style_input: StyleInput,
22    /// Tile detail override: the tile zoom on the 256 px grid (vector
23    /// sources use one less, their 512 px tiles), instead of the zoom the
24    /// view implies. `None` (the default) picks tiles as MapLibre does.
25    pub tile_zoom: Option<u8>,
26    pub tile_timeout_ms: u32,
27    pub max_tiles: u32,
28    pub tile_concurrency: u32,
29    pub layers: Option<Vec<String>>,
30    /// Keep every layer, drop the labels, or keep only the labels (see
31    /// [`crate::features`]).
32    pub labels: crate::Labels,
33    /// Feature filter: plain names keep those features, `-`-prefixed names
34    /// drop them (see [`crate::features::FEATURES`]).
35    pub features: Option<Vec<String>>,
36    /// Optional authentication token. Sent as `Authorization: Bearer <token>`
37    /// for raster sources; appended as `?access_token=<token>` for Mapbox
38    /// vector sources.
39    pub auth_token: Option<String>,
40    /// When `false`, individual tile fetch failures are logged and skipped
41    /// rather than aborting the entire render.
42    pub fail_on_tile_error: bool,
43    /// Device pixels per CSS pixel (MapLibre's devicePixelRatio). `width` and
44    /// `height` are CSS pixels and set the view and zoom; the image is
45    /// `pixel_ratio` times larger, with lines, labels and icons drawn at the
46    /// same size relative to the map (e.g. 2 for a sharp 2x image, or
47    /// dpi / 96 for print). Vector styles use the `@2x` sprite above 1.
48    pub pixel_ratio: f64,
49}
50
51impl RenderRequest {
52    /// A request with default settings: automatic zoom, pixel ratio 1, all
53    /// layers, 10 s tile timeout, at most 256 tiles, 16 parallel fetches,
54    /// failed tiles left empty.
55    pub fn new(bbox: [f64; 4], width: u32, height: u32, style_input: crate::StyleInput) -> Self {
56        RenderRequest {
57            bbox,
58            width,
59            height,
60            style_input,
61            tile_zoom: None,
62            tile_timeout_ms: 10_000,
63            max_tiles: 256,
64            tile_concurrency: 16,
65            layers: None,
66            labels: crate::Labels::All,
67            features: None,
68            auth_token: None,
69            fail_on_tile_error: false,
70            pixel_ratio: 1.0,
71        }
72    }
73
74    pub fn validate(&self) -> Result<(), BasemapError> {
75        let [xmin, ymin, xmax, ymax] = self.bbox;
76        if !xmin.is_finite() || !ymin.is_finite() || !xmax.is_finite() || !ymax.is_finite() {
77            return Err(BasemapError::InvalidBbox(
78                "bbox contains non-finite values".into(),
79            ));
80        }
81        // Zero-width bbox is always invalid (normal or anti-meridian).
82        if xmin == xmax {
83            return Err(BasemapError::InvalidBbox(format!(
84                "[{xmin}, {ymin}, {xmax}, {ymax}]: bbox has zero width (xmin == xmax)"
85            )));
86        }
87        if ymin >= ymax {
88            return Err(BasemapError::InvalidBbox(format!(
89                "[{xmin}, {ymin}, {xmax}, {ymax}]: ymin ({ymin}) must be < ymax ({ymax})"
90            )));
91        }
92        // y must be within the Web Mercator extent. x may extend up to one
93        // world width beyond ±180° (a view showing a wrapped world copy, as
94        // MapLibre draws it), as long as the bbox spans at most one world.
95        if ymin < -EARTH_HALF || ymax > EARTH_HALF {
96            return Err(BasemapError::InvalidBbox(format!(
97                "[{xmin}, {ymin}, {xmax}, {ymax}]: y must be within \
98                 ±{EARTH_HALF:.0} (Web Mercator bounds)"
99            )));
100        }
101        let x_limit = EARTH_HALF + 2.0 * EARTH_HALF;
102        if xmin < -x_limit || xmax > x_limit || (xmin < xmax && xmax - xmin > 2.0 * EARTH_HALF) {
103            return Err(BasemapError::InvalidBbox(format!(
104                "[{xmin}, {ymin}, {xmax}, {ymax}]: x must be within ±{x_limit:.0} \
105                 and span at most one world width"
106            )));
107        }
108        // xmin > xmax is the anti-meridian case — accepted and handled by render().
109        if self.width == 0 || self.height == 0 || self.width > 16_384 || self.height > 16_384 {
110            return Err(BasemapError::InvalidDimensions(self.width, self.height));
111        }
112        if !self.pixel_ratio.is_finite() || self.pixel_ratio <= 0.0 || self.pixel_ratio > 16.0 {
113            return Err(BasemapError::InvalidBbox(format!(
114                "pixel_ratio {} must be > 0 and at most 16",
115                self.pixel_ratio
116            )));
117        }
118        let (dw, dh) = (self.width as f64 * self.pixel_ratio, self.height as f64 * self.pixel_ratio);
119        if dw.round() > 16_384.0 || dh.round() > 16_384.0 {
120            return Err(BasemapError::InvalidDimensions(dw.round() as u32, dh.round() as u32));
121        }
122        if let Some(z) = self.tile_zoom {
123            if z > 22 {
124                return Err(BasemapError::InvalidBbox(format!(
125                    "zoom {z} out of range 0–22"
126                )));
127            }
128        }
129        if let Some(ref layers) = self.layers {
130            validate_layers(layers)?;
131        }
132        if let Some(ref features) = self.features {
133            crate::features::validate_features(features)?;
134        }
135        Ok(())
136    }
137}
138
139/// Rejects lists that mix plain IDs and minus-prefixed IDs (H3 spec requirement).
140fn validate_layers(layers: &[String]) -> Result<(), BasemapError> {
141    if layers.is_empty() {
142        return Ok(());
143    }
144    let has_positive = layers.iter().any(|l| !l.starts_with('-'));
145    let has_negative = layers.iter().any(|l| l.starts_with('-'));
146    if has_positive && has_negative {
147        return Err(BasemapError::InvalidLayerFilter(
148            "layer filter mixes positive and negation (-) entries; use one mode only".into(),
149        ));
150    }
151    Ok(())
152}
153
154/// Compute tile zoom from bbox width and target pixel width.
155///
156/// Handles anti-meridian bboxes (xmin > xmax) by computing the wrapped width:
157/// `(EARTH_HALF − xmin) + (xmax + EARTH_HALF)`.
158/// Raster tile zoom as MapLibre picks it for a raster source with tiles of
159/// `tile_size` px: `round(zoom + log2(512 / tile_size))` (its `roundZoom`),
160/// i.e. the rounded zoom at which one tile spans `tile_size` canvas px.
161pub fn raster_tile_zoom(bbox: [f64; 4], width_px: u32, tile_size: f64) -> u8 {
162    let bbox_width_m = if bbox[0] <= bbox[2] {
163        bbox[2] - bbox[0]
164    } else {
165        (EARTH_HALF - bbox[0]) + (bbox[2] + EARTH_HALF)
166    };
167    let mpp = bbox_width_m / width_px as f64;
168    let zoom = (EARTH_CIRC / (tile_size * mpp)).log2().round() as i32;
169    zoom.clamp(0, 22) as u8
170}
171
172pub fn compute_zoom(bbox: [f64; 4], width_px: u32) -> u8 {
173    let bbox_width_m = if bbox[0] <= bbox[2] {
174        bbox[2] - bbox[0]
175    } else {
176        // Anti-meridian: west side + east side
177        (EARTH_HALF - bbox[0]) + (bbox[2] + EARTH_HALF)
178    };
179    let mpp = bbox_width_m / width_px as f64;
180    let zoom = (EARTH_CIRC / (256.0 * mpp)).log2().floor() as i32;
181    zoom.clamp(0, 22) as u8
182}
183
184/// Count how many tiles cover a bbox at a given zoom level.
185///
186/// Handles anti-meridian bboxes (xmin > xmax) correctly: tiles from
187/// `[x0..max_tile]` plus `[0..x1]` across the dateline.
188pub fn tile_count(bbox: [f64; 4], zoom: u8) -> u32 {
189    let (x0, y0) = mercator_to_tile(bbox[0], bbox[3], zoom);
190    let (x1, y1) = mercator_to_tile(bbox[2], bbox[1], zoom);
191    if y1 < y0 {
192        return 0;
193    }
194    let y_count = y1 - y0 + 1;
195    let x_count = if x0 <= x1 {
196        x1 - x0 + 1
197    } else {
198        // Anti-meridian: [x0..max_tile] + [0..x1]
199        let max_tile = (1u32 << zoom).saturating_sub(1);
200        (max_tile - x0 + 1).saturating_add(x1 + 1)
201    };
202    x_count.saturating_mul(y_count)
203}
204
205/// Convert Web Mercator metres to slippy-map tile coordinates.
206pub fn mercator_to_tile(x: f64, y: f64, zoom: u8) -> (u32, u32) {
207    let n = 2u32.pow(zoom as u32) as f64;
208    let tx = ((x + EARTH_HALF) / EARTH_CIRC * n).floor() as u32;
209    let ty = ((EARTH_HALF - y) / EARTH_CIRC * n).floor() as u32;
210    (tx.min(n as u32 - 1), ty.min(n as u32 - 1))
211}
212
213#[derive(Debug, Clone)]
214pub struct RenderResult {
215    pub pixels: Vec<u8>,
216    pub bounds: SpatialBounds,
217    pub width: u32,
218    pub height: u32,
219    pub zoom_used: u8,
220    /// Filter names (`layers`, `features`) that matched no layer: for a
221    /// stack, those that matched nothing in any of its styles.
222    pub warnings: Vec<String>,
223}
224
225/// EPSG:3857 bbox of a `width x height` CSS-pixel view centred on
226/// (`lon`, `lat`) at MapLibre zoom `zoom` (512 px tiles; fractional zooms
227/// allowed), as MapLibre's camera shows it.
228pub fn bbox_from_center(lon: f64, lat: f64, zoom: f64, width: u32, height: u32) -> [f64; 4] {
229    let r = EARTH_HALF / std::f64::consts::PI;
230    let cx = lon.to_radians() * r;
231    let lat = lat.clamp(-85.051_128_779_806_59, 85.051_128_779_806_59);
232    let cy = (std::f64::consts::FRAC_PI_4 + lat.to_radians() / 2.0).tan().ln() * r;
233    let mpp = EARTH_CIRC / (512.0 * 2f64.powf(zoom));
234    let (hw, hh) = (width as f64 * mpp / 2.0, height as f64 * mpp / 2.0);
235    [cx - hw, cy - hh, cx + hw, cy + hh]
236}
237
238/// MapLibre zoom at which a `width x height` CSS-pixel view fits the
239/// EPSG:3857 `bounds` (fitBounds without padding), and the bounds' centre
240/// as (lon, lat).
241pub fn fit_bounds(bounds: [f64; 4], width: u32, height: u32) -> (f64, f64, f64) {
242    let r = EARTH_HALF / std::f64::consts::PI;
243    let mpp = ((bounds[2] - bounds[0]) / width as f64).max((bounds[3] - bounds[1]) / height as f64);
244    let zoom = (EARTH_CIRC / (512.0 * mpp)).log2();
245    let (cx, cy) = ((bounds[0] + bounds[2]) / 2.0, (bounds[1] + bounds[3]) / 2.0);
246    let lon = (cx / r).to_degrees();
247    let lat = (2.0 * (cy / r).exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees();
248    (lon, lat, zoom)
249}