Skip to main content

mln_style/style/
mod.rs

1use std::sync::Arc;
2
3use feature::Value;
4use mln_util::error::Error;
5use mln_util::geo::LatLng;
6
7use crate::conversion::Convertible;
8use crate::expression::GlobalStateMap;
9use crate::filter::Filter;
10use crate::font_face::FontFaces;
11use crate::layer::{Layer, LayerList, SourceKind};
12use crate::light::Light;
13use crate::projection::Projection;
14use crate::property::transition::TransitionOptions;
15use crate::registry::StyleRegistry;
16use crate::sky::Sky;
17use crate::source::{Source, SourceList};
18use crate::sprite::Sprite;
19use crate::style::edit::Edit;
20use crate::style::parse::Parser;
21use crate::terrain::Terrain;
22use crate::{image, log_target};
23
24pub mod diff;
25pub(crate) mod edit;
26pub(crate) mod json;
27pub(crate) mod parse;
28
29/// The camera that a style's root properties set: `center`, `centerAltitude`,
30/// `zoom`, `bearing`, `pitch` and `roll`. A parsed style sets every member,
31/// to the style spec's default where the document leaves it out; an empty
32/// style sets none.
33#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct StyleCamera {
35    pub center: Option<LatLng>,
36    /// In meters above sea level.
37    pub center_altitude: Option<f64>,
38    pub zoom: Option<f64>,
39    /// In degrees.
40    pub bearing: Option<f64>,
41    /// In degrees.
42    pub pitch: Option<f64>,
43    /// In degrees.
44    pub roll: Option<f64>,
45}
46
47/// Why a style failed to load.
48#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
49#[error("{0}")]
50pub enum StyleLoadError {
51    /// The style document isn't a valid style.
52    Parse(String),
53    /// The style's request failed, such as with a 404 or a missing file.
54    Load(String),
55}
56
57impl StyleLoadError {
58    /// What failed, for people.
59    #[must_use]
60    pub fn message(&self) -> &str {
61        match self {
62            StyleLoadError::Parse(message) | StyleLoadError::Load(message) => message,
63        }
64    }
65}
66
67/// The images of a style, sorted by id.
68pub(crate) type ImageList = Vec<Arc<image::Impl>>;
69
70/// A version of a map's style: what a style document describes, after the
71/// edits made since.
72///
73/// A style is a value. [`apply`](Self::apply) makes an [`Edit`]; nothing
74/// else changes it. Its parts (layers, sources, images, light, sky,
75/// terrain, projection, global state and the document's own members) sit behind
76/// their own `Arc`s, so a clone is cheap and an edit copies only the part it
77/// changes. Two versions whose part `Arc`s are the same pointer have the
78/// same part, which [`is_same_version`](Self::is_same_version) and
79/// [`StyleDiff::between`](crate::diff::StyleDiff::between) read.
80#[derive(Clone)]
81pub struct Style {
82    registry: Arc<StyleRegistry>,
83    /// The document, for the root properties that edits don't change.
84    json: Arc<str>,
85    name: Arc<str>,
86    default_camera: StyleCamera,
87    layers: Arc<LayerList>,
88    /// The sources, in the order they were added.
89    sources: Arc<SourceList>,
90    images: Arc<ImageList>,
91    light: Arc<Light>,
92    sky: Option<Arc<Sky>>,
93    terrain: Option<Arc<Terrain>>,
94    projection: Arc<Projection>,
95    transition: TransitionOptions,
96    /// What the `global-state` expressions read.
97    global_state: Arc<GlobalStateMap>,
98    /// The defaults that the document's root `state` gives.
99    global_state_defaults: Arc<GlobalStateMap>,
100    sprites: Arc<[Sprite]>,
101    glyph_url: Arc<str>,
102    /// The document's `font-faces`, if it has them.
103    font_faces: Option<Arc<FontFaces>>,
104}
105
106// The map and a renderer on another thread share versions.
107const _: () = {
108    const fn assert_send_sync<T: Send + Sync>() {}
109    assert_send_sync::<Style>();
110};
111
112impl std::fmt::Debug for Style {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("Style")
115            .field("name", &self.name)
116            .field("layers", &self.layers)
117            .field("sources", &self.sources)
118            .finish_non_exhaustive()
119    }
120}
121
122impl Style {
123    /// An empty style whose JSON, layers and filters parse against
124    /// `registry`.
125    #[must_use]
126    pub fn new(registry: Arc<StyleRegistry>) -> Self {
127        Style {
128            registry,
129            json: Arc::from(""),
130            name: Arc::from(""),
131            default_camera: StyleCamera::default(),
132            layers: Arc::default(),
133            sources: Arc::default(),
134            images: Arc::default(),
135            light: Arc::default(),
136            sky: None,
137            terrain: None,
138            projection: Arc::default(),
139            transition: TransitionOptions::default(),
140            global_state: Arc::default(),
141            global_state_defaults: Arc::default(),
142            sprites: Arc::from([]),
143            glyph_url: Arc::from(""),
144            font_faces: None,
145        }
146    }
147
148    /// The style that the style document `json` describes, parsed against
149    /// `registry`. Fails with why `json` isn't a style.
150    pub fn from_json(registry: &Arc<StyleRegistry>, json: &str) -> Result<Style, Error> {
151        let mut parser = Parser::new(registry);
152        parser.parse(json)?;
153
154        let mut style = Style::new(Arc::clone(registry));
155        style.json = Arc::from(json);
156        style.transition = parser.transition;
157        style.global_state_defaults = Arc::new(std::mem::take(&mut parser.global_state_defaults));
158        style.global_state = Arc::clone(&style.global_state_defaults);
159
160        let mut sources = SourceList::default();
161        for source in std::mem::take(&mut parser.sources) {
162            // A parsed style cannot contain duplicate source ids (they are
163            // object keys).
164            if sources.get(source.id()).is_some() {
165                log::error!(target: log_target::PARSE_STYLE, "Source {} already exists", source.id());
166                continue;
167            }
168            sources.set(source);
169        }
170        style.sources = Arc::new(sources);
171
172        // The parser drops duplicate layer ids, so the layers go in at once
173        // without `AddLayer`'s lookup. A layer incompatible with its source
174        // is logged and skipped.
175        let global_state = Arc::clone(&style.global_state);
176        let mut layers = LayerList::default();
177        layers.extend(std::mem::take(&mut parser.layers).into_iter().filter_map(|mut layer| {
178            if let Err(error) = check_layer_source(&style.sources, &layer) {
179                log::error!(target: log_target::PARSE_STYLE, "{error}");
180                return None;
181            }
182            layer.reevaluate_visibility(&global_state);
183            Some(layer)
184        }));
185        style.layers = Arc::new(layers);
186
187        style.name = Arc::from(parser.name.as_str());
188        style.default_camera = StyleCamera {
189            center: Some(parser.lat_lng),
190            center_altitude: Some(parser.center_altitude),
191            zoom: Some(parser.zoom),
192            bearing: Some(parser.bearing),
193            pitch: Some(parser.pitch),
194            roll: Some(parser.roll),
195        };
196
197        style.light = Arc::new(std::mem::take(&mut parser.light));
198        style.sky = parser.sky.take().map(Arc::new);
199        style.terrain = parser
200            .terrain
201            .take()
202            .filter(|terrain| match check_terrain(&style.sources, terrain) {
203                Ok(()) => true,
204                Err(error) => {
205                    log::error!(target: log_target::PARSE_STYLE, "{error}");
206                    false
207                }
208            })
209            .map(Arc::new);
210        style.projection = Arc::new(std::mem::take(&mut parser.projection));
211
212        style.sprites = Arc::from(std::mem::take(&mut parser.sprites));
213        style.glyph_url = Arc::from(parser.glyph_url.as_str());
214        style.font_faces = parser.font_faces.take();
215        Ok(style)
216    }
217
218    #[must_use]
219    pub fn registry(&self) -> &Arc<StyleRegistry> {
220        &self.registry
221    }
222
223    /// The style document, without the edits made since it parsed.
224    #[must_use]
225    pub fn get_json(&self) -> &str {
226        &self.json
227    }
228
229    /// The document's sprites.
230    #[must_use]
231    pub fn get_sprites(&self) -> &[Sprite] {
232        &self.sprites
233    }
234
235    #[must_use]
236    pub fn get_name(&self) -> &str {
237        &self.name
238    }
239
240    #[must_use]
241    pub fn get_default_camera(&self) -> StyleCamera {
242        self.default_camera
243    }
244
245    #[must_use]
246    pub fn get_glyph_url(&self) -> &str {
247        &self.glyph_url
248    }
249
250    #[must_use]
251    pub fn get_font_faces(&self) -> Option<&Arc<FontFaces>> {
252        self.font_faces.as_ref()
253    }
254
255    #[must_use]
256    pub fn get_transition_options(&self) -> TransitionOptions {
257        self.transition
258    }
259
260    #[must_use]
261    pub fn get_light(&self) -> &Arc<Light> {
262        &self.light
263    }
264
265    #[must_use]
266    pub fn get_sky(&self) -> Option<&Arc<Sky>> {
267        self.sky.as_ref()
268    }
269
270    #[must_use]
271    pub fn get_terrain(&self) -> Option<&Arc<Terrain>> {
272        self.terrain.as_ref()
273    }
274
275    #[must_use]
276    pub fn get_projection(&self) -> &Arc<Projection> {
277        &self.projection
278    }
279
280    /// What the style's `global-state` expressions read.
281    #[must_use]
282    pub fn get_global_state(&self) -> &Arc<GlobalStateMap> {
283        &self.global_state
284    }
285
286    /// The defaults that the style's root `state` gives.
287    #[must_use]
288    pub fn get_global_state_defaults(&self) -> &Arc<GlobalStateMap> {
289        &self.global_state_defaults
290    }
291
292    /// The images, sorted by id.
293    #[must_use]
294    pub fn get_images(&self) -> &Arc<Vec<Arc<image::Impl>>> {
295        &self.images
296    }
297
298    #[must_use]
299    pub fn get_image(&self, id: &str) -> Option<&Arc<image::Impl>> {
300        self.images.iter().find(|image| image.id == id)
301    }
302
303    /// The style's sources, in the order they were added.
304    #[must_use]
305    pub fn get_sources(&self) -> &Arc<SourceList> {
306        &self.sources
307    }
308
309    /// The source `id`.
310    #[must_use]
311    pub fn get_source(&self, id: &str) -> Option<&Source> {
312        self.sources.get(id)
313    }
314
315    /// The layers in drawing order, bottom first.
316    #[must_use]
317    pub fn get_layer_list(&self) -> &Arc<LayerList> {
318        &self.layers
319    }
320
321    /// The layers, bottom first.
322    pub fn get_layers(&self) -> impl DoubleEndedIterator<Item = &Layer> + ExactSizeIterator {
323        self.layers.iter()
324    }
325
326    /// The place of the layer `id` in drawing order, bottom first.
327    #[must_use]
328    pub fn layer_index(&self, layer_id: &str) -> Option<usize> {
329        self.layers.index_of(layer_id)
330    }
331
332    #[must_use]
333    pub fn get_layer(&self, layer_id: &str) -> Option<&Layer> {
334        self.layers.get(layer_id)
335    }
336
337    /// Makes `edit`. Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind)
338    /// for a layer the style lacks, with `AlreadyExists` for a layer id it
339    /// has, and with `InvalidArgument` for a value that doesn't fit, and
340    /// leaves the style as it was when it fails. An edit that changes
341    /// nothing leaves every part's `Arc` as it was.
342    pub fn apply(&mut self, edit: Edit) -> Result<(), Error> {
343        match edit {
344            Edit::AddLayer { mut layer, before } => {
345                check_layer_source(&self.sources, &layer)?;
346                if self.layers.get(layer.get_id()).is_some() {
347                    return Err(Error::already_exists(format!("Layer {} already exists", layer.get_id())));
348                }
349                // The global state is not available while the layer itself is parsed.
350                layer.reevaluate_visibility(&self.global_state);
351                let inserted = Arc::make_mut(&mut self.layers).insert_before(layer, before.as_deref());
352                debug_assert!(inserted.is_ok());
353            }
354            Edit::RemoveLayer(id) => {
355                if self.layers.get(&id).is_none() {
356                    return Err(layer_not_found(&id));
357                }
358                Arc::make_mut(&mut self.layers).remove(&id);
359            }
360            Edit::MoveLayer { id, before } => {
361                if self.layers.get(&id).is_none() {
362                    return Err(layer_not_found(&id));
363                }
364                if before.as_deref() == Some(id.as_str()) {
365                    return Ok(());
366                }
367                Arc::make_mut(&mut self.layers).move_before(&id, before.as_deref());
368            }
369            Edit::SetLayer(layer) => {
370                check_layer_source(&self.sources, &layer)?;
371                let id = layer.get_id().to_owned();
372                self.update_layer(&id, |old| {
373                    *old = layer;
374                    Ok(())
375                })?;
376            }
377            Edit::SetLayerProperty { layer, name, value } => {
378                let sources = Arc::clone(&self.sources);
379                self.update_layer(&layer, |target| {
380                    set_layer_property(target, &name, &value)?;
381                    check_layer_source(&sources, target)
382                })?;
383            }
384            Edit::SetLayerFilter { layer, filter } => {
385                self.update_layer(&layer, |target| {
386                    target.set_filter(&filter);
387                    Ok(())
388                })?;
389            }
390            Edit::SetLayerZoomRange { layer, min, max } => {
391                self.update_layer(&layer, |target| {
392                    target.set_min_zoom(min);
393                    target.set_max_zoom(max);
394                    Ok(())
395                })?;
396            }
397            Edit::SetLayerVisibility { layer, visibility } => {
398                self.update_layer(&layer, |target| {
399                    target.set_visibility(visibility);
400                    Ok(())
401                })?;
402            }
403            Edit::SetLight(light) => self.light = Arc::new(light),
404            Edit::SetLightProperty { name, value } => {
405                let functions = Arc::clone(self.registry.functions());
406                let mut light = Arc::clone(&self.light);
407                if let Some(error) =
408                    Light::set_shared_property(&mut light, &name, &Convertible::from(&value), &functions)
409                {
410                    let context = format!("style light property \"{name}\"");
411                    return Err(Error::invalid_argument(format!("{context}: {}", error.message)));
412                }
413                self.light = light;
414            }
415            Edit::SetSky(sky) => self.sky = sky.map(Arc::new),
416            Edit::SetTerrain(terrain) => {
417                if let Some(terrain) = &terrain {
418                    check_terrain(&self.sources, terrain)?;
419                }
420                if self.terrain.as_deref() != terrain.as_ref() {
421                    self.terrain = terrain.map(Arc::new);
422                }
423            }
424            Edit::SetProjection(projection) => self.projection = Arc::new(projection),
425            Edit::SetTransition(options) => self.transition = options,
426            Edit::SetGlobalState { name, value } => self.set_global_state(&name, &value),
427            Edit::SetGlobalStateDefaults(defaults) => {
428                self.global_state_defaults = Arc::new(defaults);
429                self.global_state = Arc::clone(&self.global_state_defaults);
430                self.reevaluate_layer_visibilities();
431            }
432            Edit::AddImage(image) => {
433                let images = Arc::make_mut(&mut self.images);
434                let index = images.partition_point(|other| other.id < image.id);
435                if images.get(index).is_some_and(|other| other.id == image.id) {
436                    images[index] = image;
437                } else {
438                    images.insert(index, image);
439                }
440            }
441            Edit::RemoveImage(id) => {
442                let Some(index) = self.images.iter().position(|image| image.id == id) else {
443                    log::warn!(target: log_target::GENERAL, "Image '{id}' is not present in style, cannot remove");
444                    return Ok(());
445                };
446                Arc::make_mut(&mut self.images).remove(index);
447            }
448            Edit::AddImages(images) => self.add_images(images),
449            Edit::AddSource(source) => {
450                if self.sources.get(source.id()).is_some() {
451                    return Err(Error::already_exists(format!("source \"{}\" already exists", source.id())));
452                }
453                for layer in self.layers.iter().filter(|layer| layer.get_source_id() == source.id()) {
454                    check_source_feeds(&source, layer)?;
455                }
456                Arc::make_mut(&mut self.sources).set(source);
457            }
458            Edit::RemoveSource(id) => {
459                if self.sources.get(&id).is_none() {
460                    return Err(source_not_found(&id));
461                }
462                Arc::make_mut(&mut self.sources).remove(&id);
463            }
464            Edit::SetSourceDescription { id, instance, load, result } => {
465                let Some(source) = self.sources.get(&id) else { return Ok(()) };
466                if source.instance() != instance || source.data().load() != load {
467                    return Ok(());
468                }
469                if let Ok(description) = result
470                    && let Some(source) = source.with_description(description)
471                {
472                    Arc::make_mut(&mut self.sources).set(source);
473                }
474            }
475            Edit::SetSourceCommon { id, common } => {
476                let source = self.sources.get(&id).ok_or_else(|| source_not_found(&id))?;
477                if *source.common() != common {
478                    let source = source.with_common(common);
479                    Arc::make_mut(&mut self.sources).set(source);
480                }
481            }
482            Edit::UpdateSource { id, update } => {
483                let source = self.sources.get(&id).ok_or_else(|| source_not_found(&id))?;
484                let instance = source.instance();
485                if let Some(source) = update(source)? {
486                    debug_assert!(source.id() == id && source.instance() == instance, "an update keeps its source");
487                    Arc::make_mut(&mut self.sources).set(source);
488                }
489            }
490        }
491        Ok(())
492    }
493
494    /// Whether `other` is the same version as `self`: every part is the same
495    /// `Arc`, and the transitions are equal. O(1): it walks nothing.
496    #[must_use]
497    pub fn is_same_version(&self, other: &Style) -> bool {
498        fn same_option<T: ?Sized>(a: Option<&Arc<T>>, b: Option<&Arc<T>>) -> bool {
499            match (a, b) {
500                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
501                (None, None) => true,
502                _ => false,
503            }
504        }
505        Arc::ptr_eq(&self.layers, &other.layers)
506            && Arc::ptr_eq(&self.sources, &other.sources)
507            && Arc::ptr_eq(&self.images, &other.images)
508            && Arc::ptr_eq(&self.light, &other.light)
509            && same_option(self.sky.as_ref(), other.sky.as_ref())
510            && same_option(self.terrain.as_ref(), other.terrain.as_ref())
511            && Arc::ptr_eq(&self.projection, &other.projection)
512            && self.transition == other.transition
513            && Arc::ptr_eq(&self.global_state, &other.global_state)
514            && Arc::ptr_eq(&self.registry, &other.registry)
515            && Arc::ptr_eq(&self.json, &other.json)
516            && Arc::ptr_eq(&self.name, &other.name)
517            && self.default_camera == other.default_camera
518            && Arc::ptr_eq(&self.sprites, &other.sprites)
519            && Arc::ptr_eq(&self.glyph_url, &other.glyph_url)
520            && same_option(self.font_faces.as_ref(), other.font_faces.as_ref())
521            && Arc::ptr_eq(&self.global_state_defaults, &other.global_state_defaults)
522    }
523
524    /// Calls `f` with a copy of the layer `id`, and keeps the copy if `f`
525    /// succeeded and changed the layer's style data, with its visibility
526    /// re-evaluated.
527    fn update_layer(&mut self, id: &str, f: impl FnOnce(&mut Layer) -> Result<(), Error>) -> Result<(), Error> {
528        let Some((index, layer)) = self.layers.get_full(id) else {
529            return Err(layer_not_found(id));
530        };
531        let mut copy = layer.clone();
532        f(&mut copy)?;
533        if !Arc::ptr_eq(layer.style(), copy.style()) {
534            copy.reevaluate_visibility(&self.global_state);
535            Arc::make_mut(&mut self.layers).replace(index, copy);
536        }
537        Ok(())
538    }
539
540    /// Sets a global state property. A null value resets the property to the
541    /// default that the style's root `state` gives (or null).
542    fn set_global_state(&mut self, property: &str, value: &Value) {
543        let mut new_value = value;
544        if matches!(value, Value::Null)
545            && let Some(default) = self.global_state_defaults.get(property)
546        {
547            new_value = default;
548        }
549        if self.global_state.get(property).is_some_and(|current| state_values_equal(current, new_value)) {
550            return;
551        }
552        Arc::make_mut(&mut self.global_state).insert(property.to_owned(), new_value.clone());
553        self.reevaluate_layer_visibilities();
554    }
555
556    /// Re-evaluates the visibility expressions of all layers against the
557    /// current global state.
558    fn reevaluate_layer_visibilities(&mut self) {
559        let mut changed = Vec::new();
560        for (index, layer) in self.layers.iter().enumerate() {
561            let mut copy = layer.clone();
562            copy.reevaluate_visibility(&self.global_state);
563            if !Arc::ptr_eq(layer.style(), copy.style()) {
564                changed.push((index, copy));
565            }
566        }
567        if changed.is_empty() {
568            return;
569        }
570        let layers = Arc::make_mut(&mut self.layers);
571        for (index, layer) in changed {
572            layers.replace(index, layer);
573        }
574    }
575
576    /// Adds a sprite's images, each replacing the image with its id.
577    fn add_images(&mut self, images: Vec<Arc<image::Impl>>) {
578        let mut new_images = (*self.images).clone();
579        let mut remaining = Vec::new();
580        for image in images {
581            let first = new_images.partition_point(|a| a.id < image.id);
582            if first < new_images.len() && image.id == new_images[first].id {
583                new_images[first] = image;
584            } else {
585                remaining.push(image);
586            }
587        }
588        new_images.extend(remaining);
589        new_images.sort_by(|a, b| a.id.cmp(&b.id));
590        self.images = Arc::new(new_images);
591    }
592}
593
594fn source_not_found(id: &str) -> Error {
595    Error::not_found(format!("source \"{id}\" does not exist"))
596}
597
598/// Sets the property `name` of `layer` to the style JSON `value`: a layer
599/// type's property or transition, or `filter`, `minzoom`, `maxzoom`,
600/// `source` or `source-layer`, where null resets the ones with a default.
601fn set_layer_property(layer: &mut Layer, name: &str, value: &serde_json::Value) -> Result<(), Error> {
602    let type_info = layer.info();
603    let id = layer.get_id().to_owned();
604    if (name == "source" || name == "source-layer") && type_info.source == SourceKind::None {
605        // A layer that takes no source would ignore the value.
606        return Err(Error::invalid_argument(format!("{} layer \"{id}\" does not take a {name}", type_info.name)));
607    }
608    match name {
609        "filter" if value.is_null() => layer.set_filter(&Filter::default()),
610        "minzoom" if value.is_null() => layer.set_min_zoom(f32::NEG_INFINITY),
611        "maxzoom" if value.is_null() => layer.set_max_zoom(f32::INFINITY),
612        _ => {
613            if let Some(error) = layer.set_property(name, &Convertible::from(value), None) {
614                let context = format!("property \"{name}\" of layer \"{id}\"");
615                return Err(Error::invalid_argument(format!("{context}: {}", error.message)));
616            }
617        }
618    }
619    Ok(())
620}
621
622fn layer_not_found(id: &str) -> Error {
623    Error::not_found(format!("layer \"{id}\" does not exist"))
624}
625
626/// Fails when `layer`'s source is in `sources` and doesn't feed layers of
627/// the layer's type.
628fn check_layer_source(sources: &SourceList, layer: &Layer) -> Result<(), Error> {
629    match sources.get(layer.get_source_id()) {
630        Some(source) => check_source_feeds(source, layer),
631        None => Ok(()),
632    }
633}
634
635/// Fails when `layer` takes a source and `source` doesn't feed layers of its
636/// type.
637fn check_source_feeds(source: &Source, layer: &Layer) -> Result<(), Error> {
638    let kind = layer.info().source;
639    if kind != SourceKind::None && source.info().layer_kind != kind {
640        let message = format!("Layer '{}' is not compatible with source '{}'", layer.get_id(), source.id());
641        return Err(Error::invalid_argument(message));
642    }
643    Ok(())
644}
645
646/// Fails when `terrain`'s exaggeration isn't a finite number of at least 0, or
647/// its source is in `sources` and isn't a `raster-dem` source. A source the
648/// style lacks passes: the terrain waits for a source with that id.
649fn check_terrain(sources: &SourceList, terrain: &Terrain) -> Result<(), Error> {
650    if !(terrain.exaggeration >= 0.0 && terrain.exaggeration.is_finite()) {
651        return Err(Error::invalid_argument("Terrain exaggeration must be a finite number of at least 0"));
652    }
653    if let Some(source) = sources.get(&terrain.source)
654        && source.info().layer_kind != SourceKind::RasterDem
655    {
656        let message = format!("Terrain source '{}' is not a raster-dem source", terrain.source);
657        return Err(Error::invalid_argument(message));
658    }
659    Ok(())
660}
661
662/// Equality on state values that, unlike the exact-type variant equality,
663/// treats numerically equal numbers of different arithmetic types as equal
664/// (e.g. a style default parsed as an integer vs. a runtime-set double).
665fn state_values_equal(a: &Value, b: &Value) -> bool {
666    fn to_double(v: &Value) -> Option<f64> {
667        match v {
668            Value::Uint(u) => Some(*u as f64),
669            Value::Int(i) => Some(*i as f64),
670            Value::Double(d) => Some(*d),
671            _ => None,
672        }
673    }
674    if let Some(a) = to_double(a) {
675        return match to_double(b) {
676            Some(b) => a == b,
677            None => false,
678        };
679    }
680    match (a, b) {
681        (Value::Array(array_a), Value::Array(array_b)) => {
682            array_a.len() == array_b.len() && array_a.iter().zip(array_b.iter()).all(|(x, y)| state_values_equal(x, y))
683        }
684        (Value::Object(object_a), Value::Object(object_b)) => {
685            if object_a.len() != object_b.len() {
686                return false;
687            }
688            object_a.iter().all(|(key, value)| match object_b.get(key) {
689                Some(other) => state_values_equal(value, other),
690                None => false,
691            })
692        }
693        _ => a == b,
694    }
695}