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