1use std::collections::HashMap;
4use std::io::Cursor;
5
6use crate::domains::geospatial::adapters::AdapterHttpRequest;
7use crate::domains::geospatial::terrain_pipeline::{
8 compile_and_encode_10d_tile_with_media_type, compile_terrain_tile, GeodeticTerrainTile,
9};
10use crate::net::disclosure::NetworkDisclosureRegistry;
11use crate::NQuin;
12
13pub const DEFAULT_TERRARIUM_ENDPOINT: &str =
14 "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png";
15pub const TERRAIN_ATTRIBUTION_URL: &str =
16 "https://github.com/tilezen/joerd/blob/master/docs/attribution.md";
17pub const TERRAIN_ATTRIBUTION: &str = "Terrain data: Mapzen Terrain Tiles. ArcticDEM terrain data DEM(s) were created from DigitalGlobe, Inc., imagery and funded under National Science Foundation awards 1043681, 1559691, and 1542736; Australia terrain data © Commonwealth of Australia (Geoscience Australia) 2017; Austria terrain data © offene Daten Österreichs – Digitales Geländemodell (DGM) Österreich; Canada terrain data contains information licensed under the Open Government Licence – Canada; Europe terrain data produced using Copernicus data and information funded by the European Union - EU-DEM layers; Global ETOPO1 terrain data U.S. National Oceanic and Atmospheric Administration; Mexico terrain data source: INEGI, Continental relief, 2016; New Zealand terrain data Copyright 2011 Crown copyright (c) Land Information New Zealand and the New Zealand Government (All rights reserved); Norway terrain data © Kartverket; United Kingdom terrain data © Environment Agency copyright and/or database right 2015. All rights reserved; United States 3DEP (formerly NED) and global GMTED2010 and SRTM terrain data courtesy of the U.S. Geological Survey. See the Tilezen terrain attribution page.";
18const MAX_ZOOM: u8 = 15;
19const MAX_TILES: usize = 16;
20const MAX_HEIGHTFIELD_SAMPLES: usize = 1_048_576;
21const MAX_SOURCE_BUNDLE_BYTES: usize = 16 * 1024 * 1024;
22const TILE_SIZE: usize = 256;
23const EARTH_CIRCUMFERENCE_M: f64 = 40_075_016.685_578_49;
24const MERCATOR_MAX_LAT: f64 = 85.051_128_779_806_6;
25
26#[derive(Debug, Clone)]
28pub struct DemHeightfield {
29 pub values_m: Vec<f32>,
30 pub width: usize,
31 pub height: usize,
32 pub bbox: (f64, f64, f64, f64),
34 pub zoom: u8,
35 pub source_template: String,
36 pub cell_size_m: f64,
37 pub centre_lat: f64,
38 pub centre_lon: f64,
39 pub centre_alt_m: f64,
40 pub source_bundle: Vec<u8>,
42}
43
44#[derive(Debug, Clone)]
46pub struct DemTerrainAsset {
47 pub heightfield: DemHeightfield,
48 pub terrain: GeodeticTerrainTile,
49 pub encoded_10d: Vec<u8>,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
53struct TileKey {
54 x: u32,
55 y: u32,
56}
57
58pub struct DemAdapter {
62 pub id: &'static str,
63 pub endpoint: String,
64 pub zoom: u8,
65}
66
67impl DemAdapter {
68 pub fn new(id: &'static str, endpoint: &str) -> Self {
70 let endpoint =
71 if endpoint.contains("{z}") && endpoint.contains("{x}") && endpoint.contains("{y}") {
72 endpoint.to_string()
73 } else {
74 let base = endpoint.trim_end_matches('/');
75 let base = base.strip_suffix("/terrarium").unwrap_or(base);
76 format!("{}/terrarium/{{z}}/{{x}}/{{y}}.png", base)
77 };
78 Self {
79 id,
80 endpoint,
81 zoom: 12,
82 }
83 }
84
85 pub fn terrarium(id: &'static str) -> Self {
87 Self::new(id, DEFAULT_TERRARIUM_ENDPOINT)
88 }
89
90 pub fn with_zoom(mut self, zoom: u8) -> Result<Self, String> {
92 if zoom > MAX_ZOOM {
93 return Err(format!("Terrarium zoom must be in 0..={MAX_ZOOM}"));
94 }
95 self.zoom = zoom;
96 Ok(self)
97 }
98
99 pub fn adapter_id(&self) -> &'static str {
101 self.id
102 }
103
104 pub fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
106 estimate_tile_count(bbox, self.zoom).unwrap_or(0)
107 }
108
109 pub fn build_fetch_requests(
112 &self,
113 bbox: (f64, f64, f64, f64),
114 registry: &NetworkDisclosureRegistry,
115 ) -> Result<Vec<AdapterHttpRequest>, String> {
116 validate_bbox(bbox)?;
117 if self.zoom > MAX_ZOOM {
118 return Err(format!("Terrarium zoom must be in 0..={MAX_ZOOM}"));
119 }
120 let (west, south, east, north) = bbox;
121 if south < -MERCATOR_MAX_LAT || north > MERCATOR_MAX_LAT {
122 return Err(format!(
123 "Terrarium tiles cover latitudes between -{MERCATOR_MAX_LAT} and {MERCATOR_MAX_LAT}"
124 ));
125 }
126 let min = lon_lat_to_global_pixel(west, north, self.zoom);
127 let max = lon_lat_to_global_pixel(east, south, self.zoom);
128 let first_x = (min.0.floor() as usize / TILE_SIZE) as u32;
129 let first_y = (min.1.floor() as usize / TILE_SIZE) as u32;
130 let last_x = (max.0.floor() as usize / TILE_SIZE) as u32;
131 let last_y = (max.1.floor() as usize / TILE_SIZE) as u32;
132 let n = 1u32 << self.zoom;
133 let mut requests = Vec::new();
134 for y in first_y.min(n - 1)..=last_y.min(n - 1) {
135 for x in first_x.min(n - 1)..=last_x.min(n - 1) {
136 let url = self
137 .endpoint
138 .replace("{z}", &self.zoom.to_string())
139 .replace("{x}", &x.to_string())
140 .replace("{y}", &y.to_string());
141 if !registry.check_egress_consent(self.adapter_id(), &url) {
142 return Err(format!(
143 "Consent denied or unregistered for endpoint {url} by adapter {}",
144 self.adapter_id()
145 ));
146 }
147 requests.push(AdapterHttpRequest::get(url, "Terrarium elevation"));
148 if requests.len() > MAX_TILES {
149 return Err(format!(
150 "requested area spans more than {MAX_TILES} terrain tiles at zoom {}",
151 self.zoom
152 ));
153 }
154 }
155 }
156 if requests.is_empty() {
157 return Err("requested area does not intersect a terrain tile".into());
158 }
159 Ok(requests)
160 }
161
162 pub fn build_fetch_request(
166 &self,
167 bbox: (f64, f64, f64, f64),
168 _time_range: (u64, u64),
169 registry: &NetworkDisclosureRegistry,
170 ) -> Result<AdapterHttpRequest, String> {
171 self.build_fetch_requests(bbox, registry)?
172 .into_iter()
173 .next()
174 .ok_or_else(|| "requested area does not intersect a terrain tile".to_string())
175 }
176
177 #[cfg(not(target_arch = "wasm32"))]
179 pub fn fetch_region_dem(
180 &self,
181 bbox: (f64, f64, f64, f64),
182 registry: &NetworkDisclosureRegistry,
183 ) -> Result<DemTerrainAsset, String> {
184 let requests = self.build_fetch_requests(bbox, registry)?;
185 let mut tiles = HashMap::with_capacity(requests.len());
186 for request in &requests {
187 let bytes = super::execute_http_request_bytes(request)?;
188 let key = tile_key_from_url(&request.url)?;
189 tiles.insert(key, decode_terrarium_png(&bytes)?);
190 }
191 self.compile_region(bbox, tiles)
192 }
193
194 #[cfg(target_arch = "wasm32")]
196 pub async fn fetch_region_dem_async(
197 &self,
198 bbox: (f64, f64, f64, f64),
199 registry: &NetworkDisclosureRegistry,
200 ) -> Result<DemTerrainAsset, String> {
201 let requests = self.build_fetch_requests(bbox, registry)?;
202 let mut tiles = HashMap::with_capacity(requests.len());
203 for request in &requests {
204 let bytes = super::execute_http_request_bytes_async(request).await?;
205 let key = tile_key_from_url(&request.url)?;
206 tiles.insert(key, decode_terrarium_png(&bytes)?);
207 }
208 self.compile_region(bbox, tiles)
209 }
210
211 fn compile_region(
212 &self,
213 bbox: (f64, f64, f64, f64),
214 tiles: HashMap<TileKey, DecodedTerrainTile>,
215 ) -> Result<DemTerrainAsset, String> {
216 let heightfield = assemble_heightfield(bbox, self.zoom, &self.endpoint, tiles)?;
217 let terrain = compile_terrain_tile(
218 &heightfield.values_m,
219 heightfield.width,
220 heightfield.height,
221 heightfield.cell_size_m,
222 heightfield.centre_lat,
223 heightfield.centre_lon,
224 heightfield.centre_alt_m,
225 heightfield.centre_lat,
226 heightfield.centre_lon,
227 heightfield.centre_alt_m,
228 );
229 let metadata = serde_json::json!({
230 "@context": "https://schema.org",
231 "@type": "Dataset",
232 "name": "Terrarium terrain tile mosaic",
233 "provider": "Mapzen Terrain Tiles on AWS",
234 "url": self.endpoint,
235 "license": TERRAIN_ATTRIBUTION_URL,
236 "creditText": TERRAIN_ATTRIBUTION,
237 "spatialCoverage": {
238 "southwest": {"latitude": heightfield.bbox.1, "longitude": heightfield.bbox.0},
239 "northeast": {"latitude": heightfield.bbox.3, "longitude": heightfield.bbox.2}
240 },
241 "additionalProperty": [
242 {"name": "encoding", "value": "Terrarium RGB: (R*256 + G + B/256) - 32768 metres"},
243 {"name": "zoom", "value": heightfield.zoom},
244 {"name": "width", "value": heightfield.width},
245 {"name": "height", "value": heightfield.height},
246 {"name": "cellSizeMetres", "value": heightfield.cell_size_m},
247 {"name": "centreLatitude", "value": heightfield.centre_lat},
248 {"name": "centreLongitude", "value": heightfield.centre_lon},
249 {"name": "centreElevationMetres", "value": heightfield.centre_alt_m}
250 ]
251 });
252 let mut metadata_cbor = Vec::new();
253 ciborium::ser::into_writer(&metadata, &mut metadata_cbor)
254 .map_err(|error| format!("failed to encode DEM provenance metadata: {error}"))?;
255 let encoded_10d = compile_and_encode_10d_tile_with_media_type(
256 &heightfield.values_m,
257 heightfield.width,
258 heightfield.height,
259 heightfield.cell_size_m,
260 heightfield.source_bundle.clone(),
261 "application/vnd.tilezen.terrarium-tile-bundle".into(),
262 TERRAIN_ATTRIBUTION_URL.into(),
263 metadata_cbor,
264 )?;
265 Ok(DemTerrainAsset {
266 heightfield,
267 terrain,
268 encoded_10d,
269 })
270 }
271}
272
273#[derive(Debug, Clone)]
274struct DecodedTerrainTile {
275 values_m: Vec<f32>,
276 width: usize,
277 height: usize,
278 source_png: Vec<u8>,
279}
280
281fn decode_terrarium_png(bytes: &[u8]) -> Result<DecodedTerrainTile, String> {
282 let mut decoder = png::Decoder::new(Cursor::new(bytes));
283 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
284 let mut reader = decoder
285 .read_info()
286 .map_err(|error| format!("invalid Terrarium PNG header: {error}"))?;
287 let mut buffer = vec![0; reader.output_buffer_size()];
288 let info = reader
289 .next_frame(&mut buffer)
290 .map_err(|error| format!("invalid Terrarium PNG frame: {error}"))?;
291 if info.width as usize != TILE_SIZE || info.height as usize != TILE_SIZE {
292 return Err(format!(
293 "Terrarium tile must be {TILE_SIZE}x{TILE_SIZE}, received {}x{}",
294 info.width, info.height
295 ));
296 }
297 let channels = match info.color_type {
298 png::ColorType::Rgb => 3,
299 png::ColorType::Rgba => 4,
300 other => {
301 return Err(format!(
302 "Terrarium PNG must use RGB or RGBA pixels, received {other:?}"
303 ));
304 }
305 };
306 let data = &buffer[..info.buffer_size()];
307 let mut values_m = Vec::with_capacity(TILE_SIZE * TILE_SIZE);
308 for pixel in data.chunks_exact(channels) {
309 if channels == 4 && pixel[3] == 0 {
310 return Err("Terrarium PNG contains transparent elevation samples".into());
311 }
312 let metres =
313 (f64::from(pixel[0]) * 256.0 + f64::from(pixel[1]) + f64::from(pixel[2]) / 256.0)
314 - 32_768.0;
315 values_m.push(metres as f32);
316 }
317 Ok(DecodedTerrainTile {
318 values_m,
319 width: TILE_SIZE,
320 height: TILE_SIZE,
321 source_png: bytes.to_vec(),
322 })
323}
324
325fn assemble_heightfield(
326 bbox: (f64, f64, f64, f64),
327 zoom: u8,
328 source_template: &str,
329 tiles: HashMap<TileKey, DecodedTerrainTile>,
330) -> Result<DemHeightfield, String> {
331 validate_bbox(bbox)?;
332 let (west, south, east, north) = bbox;
333 if south < -MERCATOR_MAX_LAT || north > MERCATOR_MAX_LAT {
334 return Err("requested DEM area exceeds the Web Mercator latitude limit".into());
335 }
336 let start = lon_lat_to_global_pixel(west, north, zoom);
337 let end = lon_lat_to_global_pixel(east, south, zoom);
338 let span_x = end.0 - start.0;
339 let span_y = end.1 - start.1;
340 let width = span_x.ceil() as usize + 1;
341 let height = span_y.ceil() as usize + 1;
342 if width < 2 || height < 2 {
343 return Err("DEM extent must cover at least two samples in each dimension".into());
344 }
345 if width
346 .checked_mul(height)
347 .is_none_or(|samples| samples > MAX_HEIGHTFIELD_SAMPLES)
348 {
349 return Err(format!(
350 "requested DEM heightfield exceeds the {MAX_HEIGHTFIELD_SAMPLES} sample limit"
351 ));
352 }
353
354 let mut values_m = Vec::with_capacity(width * height);
355 for row in 0..height {
357 let global_y = end.1 - span_y * row as f64 / (height - 1) as f64;
358 let pixel_y = global_pixel_index(global_y);
359 let tile_y = (pixel_y / TILE_SIZE) as u32;
360 let local_y = pixel_y % TILE_SIZE;
361 for column in 0..width {
362 let global_x = start.0 + span_x * column as f64 / (width - 1) as f64;
363 let pixel_x = global_pixel_index(global_x);
364 let tile_x = (pixel_x / TILE_SIZE) as u32;
365 let local_x = pixel_x % TILE_SIZE;
366 let key = TileKey {
367 x: tile_x,
368 y: tile_y,
369 };
370 let tile = tiles
371 .get(&key)
372 .ok_or_else(|| format!("missing Terrarium tile {},{}", key.x, key.y))?;
373 if tile.width != TILE_SIZE || tile.height != TILE_SIZE {
374 return Err("decoded Terrarium tile dimensions are inconsistent".into());
375 }
376 values_m.push(tile.values_m[local_y * TILE_SIZE + local_x]);
377 }
378 }
379
380 let centre_lat = (north + south) * 0.5;
381 let centre_lon = (west + east) * 0.5;
382 let centre_alt_m = values_m[(height / 2) * width + width / 2] as f64;
383 let cell_size_m = EARTH_CIRCUMFERENCE_M * centre_lat.to_radians().cos()
384 / (TILE_SIZE as f64 * (1u32 << zoom) as f64);
385 let source_bundle = encode_source_bundle(zoom, &tiles)?;
386 if source_bundle.len() > MAX_SOURCE_BUNDLE_BYTES {
387 return Err(format!(
388 "DEM source provenance exceeds the {} MiB `.10d` sidecar limit",
389 MAX_SOURCE_BUNDLE_BYTES / (1024 * 1024)
390 ));
391 }
392 Ok(DemHeightfield {
393 values_m,
394 width,
395 height,
396 bbox,
397 zoom,
398 source_template: source_template.to_string(),
399 cell_size_m,
400 centre_lat,
401 centre_lon,
402 centre_alt_m,
403 source_bundle,
404 })
405}
406
407fn encode_source_bundle(
408 zoom: u8,
409 tiles: &HashMap<TileKey, DecodedTerrainTile>,
410) -> Result<Vec<u8>, String> {
411 let mut bundle = b"QDEMTR1\0".to_vec();
412 let mut keys: Vec<_> = tiles.keys().copied().collect();
413 keys.sort_unstable();
414 for key in keys {
415 let tile = tiles
416 .get(&key)
417 .ok_or_else(|| "internal error while encoding DEM provenance".to_string())?;
418 bundle.push(zoom);
419 bundle.extend_from_slice(&key.x.to_be_bytes());
420 bundle.extend_from_slice(&key.y.to_be_bytes());
421 let png_len = u32::try_from(tile.source_png.len())
422 .map_err(|_| "Terrarium source PNG exceeds the bundle size limit".to_string())?;
423 bundle.extend_from_slice(&png_len.to_be_bytes());
424 bundle.extend_from_slice(&tile.source_png);
425 }
426 Ok(bundle)
427}
428
429impl DemTerrainAsset {
430 pub fn to_quins(&self) -> Vec<NQuin> {
432 let subject = crate::lexicon::generate_60bit_token(
433 format!(
434 "urn:qualiadb:dem:{:.7}:{:.7}:{:.7}:{:.7}:z{}",
435 self.heightfield.bbox.0,
436 self.heightfield.bbox.1,
437 self.heightfield.bbox.2,
438 self.heightfield.bbox.3,
439 self.heightfield.zoom
440 )
441 .as_bytes(),
442 );
443 let predicates = vec![
444 (
445 "http://purl.org/dc/terms/source".to_string(),
446 self.heightfield.source_template.clone(),
447 ),
448 (
449 "http://purl.org/dc/terms/license".to_string(),
450 TERRAIN_ATTRIBUTION_URL.to_string(),
451 ),
452 (
453 "http://purl.org/dc/terms/description".to_string(),
454 TERRAIN_ATTRIBUTION.to_string(),
455 ),
456 (
457 "http://www.opengis.net/ont/geosparql#asWKT".to_string(),
458 format!(
459 "POLYGON(({} {}, {} {}, {} {}, {} {}, {} {}))",
460 self.heightfield.bbox.0,
461 self.heightfield.bbox.1,
462 self.heightfield.bbox.2,
463 self.heightfield.bbox.1,
464 self.heightfield.bbox.2,
465 self.heightfield.bbox.3,
466 self.heightfield.bbox.0,
467 self.heightfield.bbox.3,
468 self.heightfield.bbox.0,
469 self.heightfield.bbox.1
470 ),
471 ),
472 ];
473 predicates
474 .into_iter()
475 .map(|(predicate, object)| {
476 let predicate = crate::lexicon::generate_60bit_token(predicate.as_bytes());
477 let object = crate::lexicon::generate_60bit_token(object.as_bytes());
478 NQuin {
479 subject,
480 predicate,
481 object,
482 context: 0,
483 metadata: 0,
484 parity: subject ^ predicate ^ object,
485 }
486 })
487 .collect()
488 }
489}
490
491fn tile_key_from_url(url: &str) -> Result<TileKey, String> {
492 let path = url.split('?').next().unwrap_or(url);
493 let mut parts = path.rsplit('/');
494 let y = parts
495 .next()
496 .and_then(|part| part.strip_suffix(".png"))
497 .and_then(|part| part.parse().ok())
498 .ok_or_else(|| format!("cannot read tile y coordinate from {url}"))?;
499 let x = parts
500 .next()
501 .and_then(|part| part.parse().ok())
502 .ok_or_else(|| format!("cannot read tile x coordinate from {url}"))?;
503 Ok(TileKey { x, y })
504}
505
506fn lon_lat_to_global_pixel(lon: f64, lat: f64, zoom: u8) -> (f64, f64) {
507 let world_size = TILE_SIZE as f64 * (1u32 << zoom) as f64;
508 let x = ((lon + 180.0) / 360.0 * world_size).clamp(0.0, world_size - f64::EPSILON);
509 let sin_lat = lat.to_radians().sin();
510 let y = ((0.5
511 - (0.25 * (1.0 + sin_lat) / (1.0 - sin_lat)).ln() / (4.0 * std::f64::consts::PI))
512 * world_size)
513 .clamp(0.0, world_size - f64::EPSILON);
514 (x, y)
515}
516
517fn global_pixel_index(pixel: f64) -> usize {
518 pixel.floor().max(0.0) as usize
519}
520
521fn validate_bbox(bbox: (f64, f64, f64, f64)) -> Result<(), String> {
522 let (west, south, east, north) = bbox;
523 if ![west, south, east, north]
524 .iter()
525 .all(|value| value.is_finite())
526 || west < -180.0
527 || east > 180.0
528 || south < -90.0
529 || north > 90.0
530 || west >= east
531 || south >= north
532 {
533 return Err("invalid WGS84 bounding box; expected west < east and south < north".into());
534 }
535 Ok(())
536}
537
538fn estimate_tile_count(bbox: (f64, f64, f64, f64), zoom: u8) -> Result<u32, String> {
539 validate_bbox(bbox)?;
540 let (west, south, east, north) = bbox;
541 if south < -MERCATOR_MAX_LAT || north > MERCATOR_MAX_LAT {
542 return Err("requested area exceeds the Web Mercator latitude limit".into());
543 }
544 let min = lon_lat_to_global_pixel(west, north, zoom);
545 let max = lon_lat_to_global_pixel(east, south, zoom);
546 let x_count =
547 ((max.0.floor() as usize / TILE_SIZE) - (min.0.floor() as usize / TILE_SIZE) + 1) as u32;
548 let y_count =
549 ((max.1.floor() as usize / TILE_SIZE) - (min.1.floor() as usize / TILE_SIZE) + 1) as u32;
550 x_count
551 .checked_mul(y_count)
552 .ok_or_else(|| "terrain tile count overflow".into())
553}
554
555#[cfg(test)]
556mod tests {
557 use super::*;
558 use crate::domains::geospatial::adapters::DataAdapter;
559
560 fn solid_png(rgb: [u8; 3]) -> Vec<u8> {
561 let mut bytes = Vec::new();
562 {
563 let mut encoder = png::Encoder::new(&mut bytes, TILE_SIZE as u32, TILE_SIZE as u32);
564 encoder.set_color(png::ColorType::Rgb);
565 encoder.set_depth(png::BitDepth::Eight);
566 let mut writer = encoder.write_header().unwrap();
567 let mut pixels = vec![0u8; TILE_SIZE * TILE_SIZE * 3];
568 for pixel in pixels.chunks_exact_mut(3) {
569 pixel.copy_from_slice(&rgb);
570 }
571 writer.write_image_data(&pixels).unwrap();
572 }
573 bytes
574 }
575
576 #[test]
577 fn terrarium_rgb_decodes_metres_and_rejects_bad_tiles() {
578 let tile = decode_terrarium_png(&solid_png([128, 0, 0])).unwrap();
579 assert_eq!(tile.width, TILE_SIZE);
580 assert_eq!(tile.height, TILE_SIZE);
581 assert_eq!(tile.values_m[0], 0.0);
582 assert!(decode_terrarium_png(b"not a png").is_err());
583 }
584
585 #[test]
586 fn requests_are_consent_gated_and_cover_all_xyz_tiles() {
587 let adapter = DemAdapter::terrarium("dem_adapter").with_zoom(12).unwrap();
588 let bbox = (151.00, -33.88, 151.20, -33.86);
589 let mut registry = NetworkDisclosureRegistry::new();
590 assert!(adapter.build_fetch_requests(bbox, ®istry).is_err());
591 registry.register_egress(
592 adapter.adapter_id(),
593 "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/",
594 "Fetch Terrarium elevation tiles",
595 "User opens a real-world terrain region",
596 );
597 let requests = adapter.build_fetch_requests(bbox, ®istry).unwrap();
598 assert!(requests.len() > 1);
599 assert!(requests.iter().all(|request| request.url.ends_with(".png")));
600 }
601
602 #[test]
603 fn assembled_region_compiles_mesh_and_provenance_container() {
604 let adapter = DemAdapter::terrarium("dem_adapter").with_zoom(12).unwrap();
605 let bbox = (151.20, -33.88, 151.201, -33.879);
606 let start = lon_lat_to_global_pixel(bbox.0, bbox.3, adapter.zoom);
607 let end = lon_lat_to_global_pixel(bbox.2, bbox.1, adapter.zoom);
608 let first_x = (start.0.floor() as usize / TILE_SIZE) as u32;
609 let first_y = (start.1.floor() as usize / TILE_SIZE) as u32;
610 let last_x = (end.0.floor() as usize / TILE_SIZE) as u32;
611 let last_y = (end.1.floor() as usize / TILE_SIZE) as u32;
612 let tile = decode_terrarium_png(&solid_png([128, 0, 0])).unwrap();
613 let mut tiles = HashMap::new();
614 for y in first_y..=last_y {
615 for x in first_x..=last_x {
616 tiles.insert(TileKey { x, y }, tile.clone());
617 }
618 }
619 let asset = adapter.compile_region(bbox, tiles).unwrap();
620 assert!(asset.heightfield.width > 1);
621 assert_eq!(
622 asset.terrain.mesh.vertices.len(),
623 asset.heightfield.values_m.len()
624 );
625 assert!(!asset.encoded_10d.is_empty());
626 assert_eq!(asset.heightfield.centre_alt_m, 0.0);
627 }
628
629 #[test]
630 fn rejects_invalid_extent_and_excessive_heightfields() {
631 assert!(validate_bbox((2.0, 1.0, 1.0, 2.0)).is_err());
632 assert!(estimate_tile_count((-180.0, -80.0, 180.0, 80.0), MAX_ZOOM).is_ok());
633 let adapter = DemAdapter::terrarium("dem_adapter")
634 .with_zoom(MAX_ZOOM)
635 .unwrap();
636 assert!(adapter
637 .build_fetch_requests(
638 (-180.0, -80.0, 180.0, 80.0),
639 &NetworkDisclosureRegistry::new()
640 )
641 .is_err());
642 }
643
644 #[test]
645 fn generic_trait_describes_binary_fetches_and_estimates_tiles() {
646 let adapter = DemAdapter::terrarium("dem_adapter");
647 assert!(adapter.estimate_tile_count((2.0, 1.0, 1.0, 2.0)) == 0);
648 assert!(adapter.needs_fetch_body());
649 assert!(adapter
650 .handle_fetch_body("not a binary png")
651 .unwrap_err()
652 .contains("binary PNG"));
653 }
654}