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 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 pub labels: crate::Labels,
33 pub features: Option<Vec<String>>,
36 pub auth_token: Option<String>,
40 pub fail_on_tile_error: bool,
43 pub pixel_ratio: f64,
49}
50
51impl RenderRequest {
52 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 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 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 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
139fn 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
154pub 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 (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
184pub 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 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
205pub 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 pub warnings: Vec<String>,
223}
224
225pub 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
238pub 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}