Skip to main content

mln_engine/
registry.rs

1//! The registrations that a runtime, its renderers and its tile workers
2//! share: the expression functions, the layer types, the source types, the
3//! extension members, the routers of layers into shared targets and the
4//! projections.
5//!
6//! An app fills a [`RegistryBuilder`] by explicit calls, `mln_builtins`'s
7//! `register_builtins` first, and builds the [`Registry`] once. Tile workers
8//! in other wasm instances make the same calls, since they run the app's own
9//! module.
10
11use std::sync::Arc;
12
13use mln_style::collections::VecMap;
14use mln_style::crs::{Crs, TileMatrixSet};
15use mln_style::expression::Functions;
16use mln_style::expression::functions::RegisterError;
17use mln_style::layer::{ErasedStyleLayerType, StyleLayerType};
18use mln_style::member::{ErasedMember, Member, Place};
19use mln_style::source::StyleSourceType;
20use mln_style::{Source, StyleRegistry};
21
22use crate::layer::layer_type::{ErasedLayerType, entry};
23use crate::layer::render_layer::Layer;
24use crate::layer::tile_input::input::Find;
25use crate::placement::{ErasedPlacement, Placement, participant};
26use crate::render::shared_targets::Router;
27use crate::source::erased::{self, ErasedSourceType};
28use crate::source::{SourceSummary, SourceType, kind};
29
30/// Makes a renderer's participant of a placing layer type.
31type MakePlacement = fn() -> Box<dyn ErasedPlacement>;
32
33/// What a [`Registry`] is built from.
34#[derive(Default)]
35pub struct RegistryBuilder {
36    functions: Functions,
37    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
38    placing_types: VecMap<&'static str, MakePlacement>,
39    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
40    members: Vec<&'static dyn ErasedMember>,
41    routers: Vec<&'static dyn Router>,
42    projections: VecMap<String, Arc<Crs>>,
43}
44
45impl std::fmt::Debug for RegistryBuilder {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("RegistryBuilder")
48            .field("functions", &self.functions)
49            .field("layer_types", &self.layer_types.keys().collect::<Vec<_>>())
50            .field("placing_types", &self.placing_types.keys().collect::<Vec<_>>())
51            .field("source_types", &self.source_types.keys().collect::<Vec<_>>())
52            .field("members", &self.members.iter().map(|member| member.name()).collect::<Vec<_>>())
53            .field("routers", &self.routers.len())
54            .field("projections", &self.projections.keys().collect::<Vec<_>>())
55            .finish()
56    }
57}
58
59impl RegistryBuilder {
60    #[must_use]
61    pub fn new() -> Self {
62        RegistryBuilder::default()
63    }
64
65    pub fn functions_mut(&mut self) -> &mut Functions {
66        &mut self.functions
67    }
68
69    /// Adds the layer type `L`, both its halves, under its style half's
70    /// name. Fails for a name that an earlier type took. A type whose input
71    /// is of another kind of source than its style half names doesn't
72    /// compile.
73    pub fn add_layer_type<L: Layer>(&mut self) -> Result<(), RegisterError> {
74        const {
75            assert!(
76                L::Style::INFO.source as u8 == <L::Input as Find<L::Style>>::KIND as u8,
77                "a layer type draws from the kind of source its style half names"
78            );
79        }
80        let name = L::Style::INFO.name;
81        if self.layer_types.contains_key(name) {
82            return Err(RegisterError::Duplicate(name.to_owned()));
83        }
84        self.layer_types.insert(name, entry::<L>());
85        Ok(())
86    }
87
88    /// Adds the layer type of `P`, a placement participant, both its
89    /// halves, whose layers place with `P` ([`Placement`]). Fails for a name
90    /// that an earlier type took.
91    pub fn add_placing_layer_type<P: Placement>(&mut self) -> Result<(), RegisterError> {
92        const { assert!(<P::Layer as Layer>::PLACES, "a placing layer type says that it places") }
93        self.add_layer_type::<P::Layer>()?;
94        self.placing_types.insert(<P::Layer as Layer>::Style::INFO.name, participant::<P>);
95        Ok(())
96    }
97
98    /// Adds the source type `T`, both its halves. Fails for a name that an
99    /// earlier type took. A type whose halves name different kinds of data
100    /// doesn't compile.
101    pub fn add_source_type<T: SourceType>(&mut self) -> Result<(), RegisterError> {
102        const {
103            assert!(
104                T::Style::INFO.layer_kind as u8 == <T::Data as kind::Deliver>::KIND as u8,
105                "a source type's halves name the same kind of data"
106            );
107        }
108        let name = T::Style::INFO.name;
109        if self.source_types.contains_key(name) {
110            return Err(RegisterError::Duplicate(name.to_owned()));
111        }
112        self.source_types.insert(name, erased::entry::<T>());
113        Ok(())
114    }
115
116    /// Adds the extension member `member`, which gives the style's members
117    /// of its place and name a type. Fails for a place and name that an
118    /// earlier member took.
119    pub fn add_member<T: Send + Sync + 'static>(&mut self, member: &'static Member<T>) -> Result<(), RegisterError> {
120        let taken = |added: &&dyn ErasedMember| added.place() == member.place() && added.name() == member.name();
121        if self.members.iter().any(taken) {
122            let place = match member.place() {
123                Place::Root => "root",
124                Place::Layer => "layer",
125            };
126            return Err(RegisterError::Duplicate(format!("{place} member {}", member.name())));
127        }
128        self.members.push(member);
129        Ok(())
130    }
131
132    /// Adds `router`, which declares the shared targets of the frames of
133    /// each version of a style and routes its layers' draws into them. The
134    /// routers route in the order they were added: of two routes of a
135    /// layer, the later stands.
136    pub fn add_router(&mut self, router: &'static dyn Router) {
137        self.routers.push(router);
138    }
139
140    /// Adds the projection `crs`, which a style's `projection.type` names.
141    /// Fails for a name without a colon, which built-in projections keep, a
142    /// name that an earlier projection took, and a tile matrix set whose
143    /// origin isn't finite or whose extent isn't positive and finite.
144    pub fn add_projection(&mut self, crs: Crs) -> Result<(), RegisterError> {
145        if !crs.name.contains(':') {
146            return Err(RegisterError::ProjectionName(crs.name));
147        }
148        self.insert_projection(crs)
149    }
150
151    /// Adds `crs`, of any name. Fails as [`add_projection`](Self::add_projection)
152    /// does for a taken name or a tile matrix set.
153    fn insert_projection(&mut self, crs: Crs) -> Result<(), RegisterError> {
154        if self.projections.contains_key(crs.name.as_str()) {
155            return Err(RegisterError::Duplicate(crs.name));
156        }
157        let TileMatrixSet { origin, extent_at_zoom0: extent } = crs.tile_matrix_set;
158        let valid = origin.iter().all(|value| value.is_finite()) && extent.is_finite() && extent > 0.0;
159        if !valid {
160            return Err(RegisterError::TileMatrixSet(crs.name));
161        }
162        self.projections.insert(crs.name.clone(), Arc::new(crs));
163        Ok(())
164    }
165
166    #[must_use]
167    pub fn build(self) -> Arc<Registry> {
168        let RegistryBuilder { functions, layer_types, placing_types, source_types, members, routers, projections } =
169            self;
170        let projections = projections.into_iter().map(|(_, crs)| crs);
171        Registry::new(Arc::new(functions), layer_types, placing_types, source_types, members, routers, projections)
172    }
173}
174
175/// Adds the built-in projections, whose names have no colon: `identity`
176/// ([`Crs::identity`]). Fails when an earlier call added them.
177pub fn register_builtin_projections(builder: &mut RegistryBuilder) -> Result<(), RegisterError> {
178    builder.insert_projection(Crs::identity())
179}
180
181fn style_half(layer_type: &'static dyn ErasedLayerType) -> &'static dyn ErasedStyleLayerType {
182    layer_type.style()
183}
184
185/// The expression functions, layer types, source types and extension
186/// members that a style parses against, its renderer draws and its tile
187/// workers lay out, and the projections that the style's `projection.type`
188/// names, built by a [`RegistryBuilder`]. It doesn't change once built.
189///
190/// A map and the renderer and tile workers that draw it must be given
191/// registries filled by the same calls: they identify functions, layer
192/// types and source types by name.
193pub struct Registry {
194    style: Arc<StyleRegistry>,
195    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
196    placing_types: VecMap<&'static str, MakePlacement>,
197    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
198    routers: Vec<&'static dyn Router>,
199}
200
201impl std::fmt::Debug for Registry {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        f.debug_struct("Registry").field("style", &self.style).finish_non_exhaustive()
204    }
205}
206
207impl Registry {
208    fn new(
209        functions: Arc<Functions>,
210        layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
211        placing_types: VecMap<&'static str, MakePlacement>,
212        source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
213        members: Vec<&'static dyn ErasedMember>,
214        routers: Vec<&'static dyn Router>,
215        projections: impl IntoIterator<Item = Arc<Crs>>,
216    ) -> Arc<Registry> {
217        let style_halves = layer_types.values().map(|&layer_type| style_half(layer_type));
218        let style_source_halves = source_types.values().map(|&source_type| source_type.style());
219        let style = StyleRegistry::new(functions, style_halves, style_source_halves, members, projections);
220        Arc::new(Registry { style: Arc::new(style), layer_types, placing_types, source_types, routers })
221    }
222
223    #[must_use]
224    pub fn style(&self) -> &Arc<StyleRegistry> {
225        &self.style
226    }
227
228    #[must_use]
229    pub fn functions(&self) -> &Arc<Functions> {
230        self.style.functions()
231    }
232
233    #[must_use]
234    pub fn layer_type(&self, name: &str) -> Option<&'static dyn ErasedLayerType> {
235        self.layer_types.get(name).copied()
236    }
237
238    /// The makers of the participants of the placing layer types, in the
239    /// order they registered.
240    pub(crate) fn placing_types(&self) -> impl Iterator<Item = MakePlacement> + '_ {
241        self.placing_types.values().copied()
242    }
243
244    /// The routers, in the order they were added.
245    pub(crate) fn routers(&self) -> &[&'static dyn Router] {
246        &self.routers
247    }
248
249    pub(crate) fn source_type(&self, name: &str) -> Option<&'static dyn ErasedSourceType> {
250        self.source_types.get(name).copied()
251    }
252
253    /// The attribution of `source`, as its type gives it: `None` for a type
254    /// the registry lacks.
255    #[must_use]
256    pub fn source_attribution(&self, source: &Source) -> Option<String> {
257        self.source_type(source.info().name)?.attribution(source)
258    }
259
260    /// What `source` reports about itself, as its type says: nothing for a
261    /// type the registry lacks.
262    #[must_use]
263    pub fn source_summary(&self, source: &Source) -> SourceSummary {
264        self.source_type(source.info().name).map(|source_type| source_type.summary(source)).unwrap_or_default()
265    }
266}
267
268/// A context in which the values that the worker codec reads resolve the
269/// registrations they name against this registry: layers' evaluated values
270/// their layer type, and as for a [`StyleRegistry`], layers' style data and
271/// compound expressions.
272impl mln_wire::Context for &Registry {
273    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
274        let registry: &'a Registry = self;
275        request.give(registry).give::<StyleRegistry>(registry.style()).give::<Functions>(registry.functions());
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn a_layer_type_registers_once() {
285        type Circles = crate::tests::types::layers::TestFeatures<mln_style::layers::Circle>;
286        let mut builder = RegistryBuilder::new();
287        builder.add_layer_type::<Circles>().unwrap();
288        assert_eq!(builder.add_layer_type::<Circles>(), Err(RegisterError::Duplicate("circle".to_owned())));
289    }
290
291    /// The identity CRS under the name `name`.
292    fn identity_named(name: &str) -> Crs {
293        let Crs { converter, tile_matrix_set, .. } = Crs::identity();
294        Crs { name: name.to_owned(), converter, tile_matrix_set }
295    }
296
297    // GL JS: addProjection registers a CRS under its name.
298    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/projection_crud.test.ts#L18-L22
299    #[test]
300    fn a_projection_registers_under_its_name() {
301        let mut builder = RegistryBuilder::new();
302        builder.add_projection(identity_named("test:crs")).unwrap();
303        let registry = builder.build();
304        let mapping = registry.style().projection("test:crs").expect("registered");
305        assert_eq!(mapping.name(), "test:crs");
306        assert!(registry.style().projection("test:other").is_none());
307    }
308
309    // GL JS: addProjection throws when the name is already registered.
310    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/projection_crud.test.ts#L24-L27
311    #[test]
312    fn a_projection_name_registers_once() {
313        let mut builder = RegistryBuilder::new();
314        builder.add_projection(identity_named("test:crs")).unwrap();
315        assert_eq!(
316            builder.add_projection(identity_named("test:crs")),
317            Err(RegisterError::Duplicate("test:crs".to_owned()))
318        );
319    }
320
321    // GL JS: addProjection throws for a name without a colon, built in or
322    // not, and registers nothing.
323    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/projection_crud.test.ts#L29-L35
324    #[test]
325    fn a_projection_name_needs_a_colon() {
326        let mut builder = RegistryBuilder::new();
327        let names = ["mercator", "globe", "vertical-perspective", "identity", "equal-earth"];
328        for name in names {
329            assert_eq!(
330                builder.add_projection(identity_named(name)),
331                Err(RegisterError::ProjectionName(name.to_owned()))
332            );
333        }
334        let registry = builder.build();
335        for name in names {
336            assert!(registry.style().projection(name).is_none(), "{name}");
337        }
338    }
339
340    // GL JS: addProjection throws for a zoom 0 extent that isn't positive.
341    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/projection_crud.test.ts#L37-L41
342    #[test]
343    fn a_tile_matrix_set_needs_a_finite_origin_and_a_positive_extent() {
344        let mut builder = RegistryBuilder::new();
345        let tile_matrix_sets = [
346            TileMatrixSet { origin: [0.0, 0.0], extent_at_zoom0: 0.0 },
347            TileMatrixSet { origin: [0.0, 0.0], extent_at_zoom0: -1.0 },
348            TileMatrixSet { origin: [0.0, 0.0], extent_at_zoom0: f64::NAN },
349            TileMatrixSet { origin: [0.0, 0.0], extent_at_zoom0: f64::INFINITY },
350            TileMatrixSet { origin: [f64::NAN, 0.0], extent_at_zoom0: 1.0 },
351            TileMatrixSet { origin: [0.0, f64::NEG_INFINITY], extent_at_zoom0: 1.0 },
352        ];
353        for tile_matrix_set in tile_matrix_sets {
354            let crs = Crs { tile_matrix_set, ..identity_named("test:crs") };
355            assert_eq!(builder.add_projection(crs), Err(RegisterError::TileMatrixSet("test:crs".to_owned())));
356        }
357        assert!(builder.build().style().projection("test:crs").is_none());
358    }
359
360    // GL JS: getRegisteredProjection finds the pre-registered identity
361    // projection.
362    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/projection_crud.test.ts#L45-L47
363    #[test]
364    fn the_builtin_projections_are_identity() {
365        let mut builder = RegistryBuilder::new();
366        register_builtin_projections(&mut builder).unwrap();
367        assert_eq!(register_builtin_projections(&mut builder), Err(RegisterError::Duplicate("identity".to_owned())));
368        let registry = builder.build();
369        let identity = registry.style().projection("identity").expect("identity");
370        assert_eq!(identity.tile_matrix_set(), TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 });
371        // Its coordinates are lng/lat unchanged, from -90 to 90 across the
372        // world square and from 90 to -90 down it.
373        let mut world = [[0.0; 2]; 2];
374        identity.world_from_lng_lats(&[[45.0, 45.0], [-90.0, -90.0]], &mut world);
375        assert_eq!(world, [[0.75, 0.25], [0.0, 1.0]]);
376        let mut lng_lats = [[0.0; 2]; 1];
377        identity.lng_lats_from_world(&[[0.75, 0.25]], &mut lng_lats);
378        assert_eq!(lng_lats, [[45.0, 45.0]]);
379        assert!(RegistryBuilder::new().build().style().projection("identity").is_none());
380    }
381}