rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! TileJSON metadata model for vector and raster tile sources.
//!
//! [TileJSON](https://github.com/mapbox/tilejson-spec) is the standard
//! metadata format used by MapLibre GL JS and Mapbox GL JS to describe
//! tile sources.  A typical vector tile endpoint exposes a
//! `tiles.json` (or inline `TileJSON`) that provides:
//!
//! - tile URL templates
//! - zoom range
//! - geographic bounds
//! - source-layer names (for vector tiles)
//! - attribution
//!
//! This module provides a parse-once, query-many [`TileJson`] struct
//! that the engine can use to configure tile managers and sources.
//!
//! ## Feature gate
//!
//! Parsing from JSON bytes requires the `style-json` feature (which
//! enables `serde` + `serde_json`).  The [`TileJson`] struct itself
//! is always available for programmatic construction.

use std::fmt;

// ---------------------------------------------------------------------------
// VectorLayer metadata
// ---------------------------------------------------------------------------

/// Metadata for a single source layer inside a vector tile source.
///
/// Mirrors the `vector_layers` entry in TileJSON 3.0.
#[derive(Debug, Clone, PartialEq)]
pub struct VectorLayerMeta {
    /// Machine-readable source-layer name (e.g. `"water"`, `"roads"`).
    pub id: String,
    /// Optional human-readable description.
    pub description: Option<String>,
    /// Minimum zoom at which this layer appears.
    pub min_zoom: Option<u8>,
    /// Maximum zoom at which this layer appears.
    pub max_zoom: Option<u8>,
}

impl VectorLayerMeta {
    /// Create metadata with only an id.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            description: None,
            min_zoom: None,
            max_zoom: None,
        }
    }
}

// ---------------------------------------------------------------------------
// TileJson
// ---------------------------------------------------------------------------

/// Parsed TileJSON metadata.
///
/// This is a framework-agnostic representation of the subset of
/// TileJSON fields that the engine needs to configure tile managers
/// and sources.
#[derive(Debug, Clone, PartialEq)]
pub struct TileJson {
    /// TileJSON spec version (e.g. `"3.0.0"`).
    pub tilejson: String,
    /// Optional human-readable name.
    pub name: Option<String>,
    /// Optional description.
    pub description: Option<String>,
    /// TileJSON version string (semver).
    pub version: Option<String>,
    /// Optional attribution HTML string.
    pub attribution: Option<String>,
    /// Tile URL templates with `{z}`, `{x}`, `{y}` placeholders.
    pub tiles: Vec<String>,
    /// Minimum zoom level supported by the source.
    pub min_zoom: u8,
    /// Maximum zoom level supported by the source.
    pub max_zoom: u8,
    /// Geographic bounds as `[west, south, east, north]` in WGS-84 degrees.
    ///
    /// `None` means the source covers the whole world.
    pub bounds: Option<[f64; 4]>,
    /// Default center + zoom as `[lon, lat, zoom]`.
    pub center: Option<[f64; 3]>,
    /// Tile encoding scheme.
    pub scheme: TileScheme,
    /// Vector layer metadata (only present for vector tile sources).
    pub vector_layers: Vec<VectorLayerMeta>,
}

impl Default for TileJson {
    fn default() -> Self {
        Self {
            tilejson: "3.0.0".into(),
            name: None,
            description: None,
            version: None,
            attribution: None,
            tiles: Vec::new(),
            min_zoom: 0,
            max_zoom: 22,
            bounds: None,
            center: None,
            scheme: TileScheme::Xyz,
            vector_layers: Vec::new(),
        }
    }
}

impl TileJson {
    /// Create a minimal TileJSON with a single tile URL template.
    pub fn with_tiles(tiles: Vec<String>) -> Self {
        Self {
            tiles,
            ..Self::default()
        }
    }

    /// Return the first tile URL template, if any.
    #[inline]
    pub fn first_tile_url(&self) -> Option<&str> {
        self.tiles.first().map(String::as_str)
    }

    /// Return `true` if this TileJSON describes a vector tile source
    /// (has `vector_layers`).
    #[inline]
    pub fn is_vector(&self) -> bool {
        !self.vector_layers.is_empty()
    }

    /// Return the names of all declared vector source layers.
    pub fn source_layer_names(&self) -> Vec<&str> {
        self.vector_layers.iter().map(|vl| vl.id.as_str()).collect()
    }

    /// Check whether a geographic coordinate is within the source bounds.
    ///
    /// Returns `true` when no bounds are set (unbounded source).
    pub fn contains_point(&self, lon: f64, lat: f64) -> bool {
        match self.bounds {
            Some([west, south, east, north]) => {
                lon >= west && lon <= east && lat >= south && lat <= north
            }
            None => true,
        }
    }
}

/// Tile coordinate scheme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TileScheme {
    /// Standard `z/x/y` (OSM / slippy map convention).
    #[default]
    Xyz,
    /// TMS convention where `y` is flipped.
    Tms,
}

impl fmt::Display for TileScheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TileScheme::Xyz => write!(f, "xyz"),
            TileScheme::Tms => write!(f, "tms"),
        }
    }
}

// ---------------------------------------------------------------------------
// TileJSON error
// ---------------------------------------------------------------------------

/// Errors that can occur when parsing TileJSON.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TileJsonError {
    /// The JSON was malformed.
    InvalidJson(String),
    /// A required field was missing.
    MissingField(&'static str),
    /// A field had an unexpected type or value.
    InvalidField {
        /// Field name.
        field: &'static str,
        /// Description of the problem.
        reason: String,
    },
}

impl fmt::Display for TileJsonError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TileJsonError::InvalidJson(msg) => write!(f, "invalid TileJSON: {msg}"),
            TileJsonError::MissingField(field) => {
                write!(f, "missing required TileJSON field: `{field}`")
            }
            TileJsonError::InvalidField { field, reason } => {
                write!(f, "invalid TileJSON field `{field}`: {reason}")
            }
        }
    }
}

impl std::error::Error for TileJsonError {}

// ---------------------------------------------------------------------------
// Parsing (requires serde_json via the style-json feature)
// ---------------------------------------------------------------------------

#[cfg(feature = "style-json")]
mod parsing {
    use super::*;
    use serde_json::Value;

    /// Parse TileJSON from raw JSON bytes.
    pub fn parse_tilejson(bytes: &[u8]) -> Result<TileJson, TileJsonError> {
        let value: Value =
            serde_json::from_slice(bytes).map_err(|e| TileJsonError::InvalidJson(e.to_string()))?;
        parse_tilejson_value(&value)
    }

    /// Parse TileJSON from a `serde_json::Value`.
    pub fn parse_tilejson_value(value: &Value) -> Result<TileJson, TileJsonError> {
        let obj = value
            .as_object()
            .ok_or(TileJsonError::InvalidJson("root is not an object".into()))?;

        let tilejson = obj
            .get("tilejson")
            .and_then(|v| v.as_str())
            .unwrap_or("3.0.0")
            .to_owned();

        let tiles = obj
            .get("tiles")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(ToOwned::to_owned))
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        if tiles.is_empty() {
            return Err(TileJsonError::MissingField("tiles"));
        }

        let min_zoom = obj
            .get("minzoom")
            .and_then(|v| v.as_u64())
            .map(|v| v.min(30) as u8)
            .unwrap_or(0);

        let max_zoom = obj
            .get("maxzoom")
            .and_then(|v| v.as_u64())
            .map(|v| v.min(30) as u8)
            .unwrap_or(22);

        let bounds = obj.get("bounds").and_then(|v| {
            let arr = v.as_array()?;
            if arr.len() >= 4 {
                Some([
                    arr[0].as_f64()?,
                    arr[1].as_f64()?,
                    arr[2].as_f64()?,
                    arr[3].as_f64()?,
                ])
            } else {
                None
            }
        });

        let center = obj.get("center").and_then(|v| {
            let arr = v.as_array()?;
            if arr.len() >= 3 {
                Some([arr[0].as_f64()?, arr[1].as_f64()?, arr[2].as_f64()?])
            } else {
                None
            }
        });

        let scheme = obj
            .get("scheme")
            .and_then(|v| v.as_str())
            .map(|s| match s {
                "tms" => TileScheme::Tms,
                _ => TileScheme::Xyz,
            })
            .unwrap_or(TileScheme::Xyz);

        let name = obj
            .get("name")
            .and_then(|v| v.as_str())
            .map(ToOwned::to_owned);
        let description = obj
            .get("description")
            .and_then(|v| v.as_str())
            .map(ToOwned::to_owned);
        let version = obj
            .get("version")
            .and_then(|v| v.as_str())
            .map(ToOwned::to_owned);
        let attribution = obj
            .get("attribution")
            .and_then(|v| v.as_str())
            .map(ToOwned::to_owned);

        let vector_layers = obj
            .get("vector_layers")
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(parse_vector_layer_meta).collect())
            .unwrap_or_default();

        Ok(TileJson {
            tilejson,
            name,
            description,
            version,
            attribution,
            tiles,
            min_zoom,
            max_zoom,
            bounds,
            center,
            scheme,
            vector_layers,
        })
    }

    fn parse_vector_layer_meta(value: &Value) -> Option<VectorLayerMeta> {
        let obj = value.as_object()?;
        let id = obj.get("id")?.as_str()?.to_owned();
        let description = obj
            .get("description")
            .and_then(|v| v.as_str())
            .map(ToOwned::to_owned);
        let min_zoom = obj
            .get("minzoom")
            .and_then(|v| v.as_u64())
            .map(|v| v.min(30) as u8);
        let max_zoom = obj
            .get("maxzoom")
            .and_then(|v| v.as_u64())
            .map(|v| v.min(30) as u8);
        Some(VectorLayerMeta {
            id,
            description,
            min_zoom,
            max_zoom,
        })
    }
}

#[cfg(feature = "style-json")]
pub use parsing::{parse_tilejson, parse_tilejson_value};

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_tilejson_has_sensible_values() {
        let tj = TileJson::default();
        assert_eq!(tj.tilejson, "3.0.0");
        assert_eq!(tj.min_zoom, 0);
        assert_eq!(tj.max_zoom, 22);
        assert!(tj.tiles.is_empty());
        assert!(!tj.is_vector());
        assert!(tj.source_layer_names().is_empty());
    }

    #[test]
    fn with_tiles_constructor() {
        let tj = TileJson::with_tiles(vec!["https://example.com/{z}/{x}/{y}.pbf".into()]);
        assert_eq!(tj.tiles.len(), 1);
        assert_eq!(
            tj.first_tile_url(),
            Some("https://example.com/{z}/{x}/{y}.pbf")
        );
    }

    #[test]
    fn is_vector_when_layers_present() {
        let mut tj = TileJson::default();
        assert!(!tj.is_vector());
        tj.vector_layers.push(VectorLayerMeta::new("water"));
        assert!(tj.is_vector());
        assert_eq!(tj.source_layer_names(), vec!["water"]);
    }

    #[test]
    fn contains_point_unbounded() {
        let tj = TileJson::default();
        assert!(tj.contains_point(0.0, 0.0));
        assert!(tj.contains_point(180.0, 90.0));
    }

    #[test]
    fn contains_point_bounded() {
        let tj = TileJson {
            bounds: Some([-10.0, -20.0, 30.0, 40.0]),
            ..TileJson::default()
        };
        assert!(tj.contains_point(0.0, 0.0));
        assert!(tj.contains_point(-10.0, -20.0));
        assert!(tj.contains_point(30.0, 40.0));
        assert!(!tj.contains_point(-11.0, 0.0));
        assert!(!tj.contains_point(0.0, 41.0));
    }

    #[test]
    fn tile_scheme_display() {
        assert_eq!(TileScheme::Xyz.to_string(), "xyz");
        assert_eq!(TileScheme::Tms.to_string(), "tms");
    }

    #[test]
    fn tilejson_error_display() {
        let err = TileJsonError::MissingField("tiles");
        assert!(err.to_string().contains("tiles"));
    }

    #[cfg(feature = "style-json")]
    mod json_parsing {
        use super::*;

        #[test]
        fn parse_minimal_vector_tilejson() {
            let json = br#"{
                "tilejson": "3.0.0",
                "tiles": ["https://example.com/{z}/{x}/{y}.pbf"],
                "minzoom": 0,
                "maxzoom": 14,
                "vector_layers": [
                    {"id": "water", "minzoom": 0, "maxzoom": 14},
                    {"id": "roads", "description": "Road network"}
                ]
            }"#;

            let tj = parse_tilejson(json).expect("valid tilejson");
            assert_eq!(tj.tilejson, "3.0.0");
            assert_eq!(tj.tiles.len(), 1);
            assert_eq!(tj.min_zoom, 0);
            assert_eq!(tj.max_zoom, 14);
            assert!(tj.is_vector());
            assert_eq!(tj.vector_layers.len(), 2);
            assert_eq!(tj.vector_layers[0].id, "water");
            assert_eq!(tj.vector_layers[0].min_zoom, Some(0));
            assert_eq!(tj.vector_layers[0].max_zoom, Some(14));
            assert_eq!(tj.vector_layers[1].id, "roads");
            assert_eq!(
                tj.vector_layers[1].description.as_deref(),
                Some("Road network")
            );
        }

        #[test]
        fn parse_raster_tilejson() {
            let json = br#"{
                "tilejson": "2.2.0",
                "tiles": ["https://tile.example.com/{z}/{x}/{y}.png"],
                "minzoom": 0,
                "maxzoom": 18,
                "bounds": [-180, -85.05, 180, 85.05],
                "center": [0, 0, 2],
                "name": "OpenStreetMap",
                "attribution": "&copy; OSM contributors"
            }"#;

            let tj = parse_tilejson(json).expect("valid tilejson");
            assert_eq!(tj.tilejson, "2.2.0");
            assert!(!tj.is_vector());
            assert_eq!(tj.name.as_deref(), Some("OpenStreetMap"));
            assert!(tj.attribution.is_some());
            assert!(tj.bounds.is_some());
            assert!(tj.center.is_some());
            let bounds = tj.bounds.expect("bounds");
            assert!((bounds[0] - (-180.0)).abs() < 1e-9);
        }

        #[test]
        fn parse_tilejson_missing_tiles_fails() {
            let json = br#"{"tilejson": "3.0.0"}"#;
            let err = parse_tilejson(json).expect_err("should fail");
            assert!(matches!(err, TileJsonError::MissingField("tiles")));
        }

        #[test]
        fn parse_tilejson_invalid_json() {
            let err = parse_tilejson(b"not json").expect_err("should fail");
            assert!(matches!(err, TileJsonError::InvalidJson(_)));
        }

        #[test]
        fn parse_tilejson_with_scheme() {
            let json = br#"{
                "tiles": ["https://example.com/{z}/{x}/{y}.pbf"],
                "scheme": "tms"
            }"#;
            let tj = parse_tilejson(json).expect("valid tilejson");
            assert_eq!(tj.scheme, TileScheme::Tms);
        }
    }
}