Skip to main content

mln_engine/layer/
layout.rs

1//! How a layer type lays out a tile's features on a worker: its [`Layout`],
2//! which selects the features with a [`LayoutCx`] and builds the bucket
3//! with a [`BuildCx`].
4//!
5//! A `TileLayer` borrows its `TileData`, and the worker keeps layouts with
6//! pending dependencies across messages, so layouts keep the indexes of the
7//! features they select, and the contexts borrow the layer again from the
8//! engine's [`SourceLayer`] when they run.
9
10use std::sync::Arc;
11
12use mln_style::PropertyEvaluationParameters;
13use mln_style::collections::{VecMap, VecSet};
14use mln_style::error::Error;
15use mln_style::expression::{EvaluationContext, GlobalStateMap, UnavailableImages, Value};
16use mln_style::feature::{GeometryCollection, GeometryTileFeature};
17use mln_style::filter::Filter;
18use mln_style::layer::{PaintSet, StyleLayerType};
19use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
20use mln_style::tile_id::CanonicalTileID;
21
22use crate::image::image_store::{ImageDependencies, ImageType};
23use crate::layer::bucket::Bucket;
24use crate::layer::bucket_parameters::BucketParameters;
25use crate::layer::filter_groups::FilterGroups;
26use crate::layer::layer_type::EvaluatedLayer;
27use crate::layer::paint_property_binder::{LayerBinders, PaintBinders, PatternLayerMap};
28use crate::layer::tile_layout::Resolved;
29use crate::map::MapMode;
30use crate::query::feature_index::FeatureIndexBuilder;
31use crate::text::atlas::ImagePositions;
32use crate::text::glyph::{FontFaces, GlyphDependencies};
33use crate::tile::{OverscaledTileID, TileData, TileLayer};
34
35/// How a group of layers of the type `T` that share their layout becomes a
36/// tile's bucket, on a tile worker: [`new`](Self::new) selects the tile's
37/// features, and once the glyphs and images it asked for are resolved,
38/// [`build`](Self::build) makes the bucket.
39pub trait Layout<T: StyleLayerType>: Send + Sized + 'static {
40    /// The bucket the layout makes.
41    type Bucket: Bucket;
42
43    /// Whether the layout of `group` may ask for glyphs or images. The
44    /// engine makes such a layout before it resolves them, and builds it
45    /// once they are, after every other.
46    fn needs_resources(_group: &[Arc<EvaluatedLayer<T>>]) -> bool {
47        false
48    }
49
50    /// Selects the features of the tile that the bucket draws.
51    fn new(cx: &mut LayoutCx<'_, T>) -> Result<Self, Error>;
52
53    /// Makes the bucket of the selected features; `None` for one with
54    /// nothing to draw. A feature that fails to decode fails the bucket,
55    /// which the engine reports as the tile's error.
56    fn build(self, cx: &mut BuildCx<'_, T>) -> Result<Option<Self::Bucket>, Error>;
57}
58
59/// The layer a layout reads: its tile data and its name.
60#[derive(Clone)]
61pub struct SourceLayer {
62    pub(crate) data: TileData,
63    pub(crate) name: String,
64}
65
66impl SourceLayer {
67    pub(crate) fn new(data: TileData, name: impl Into<String>) -> Self {
68        SourceLayer { data, name: name.into() }
69    }
70
71    /// The layer. The worker only creates layouts for layers the data has,
72    /// so neither error is expected.
73    pub(crate) fn layer(&self) -> Result<TileLayer<'_>, Error> {
74        self.data
75            .layer(&self.name)?
76            .ok_or_else(|| Error::native(format!("SourceLayer: the tile data has no layer {:?}", self.name)))
77    }
78}
79
80/// What a tile's layouts read apart from their group, and where they record
81/// the glyphs and images they need.
82pub struct LayoutParameters<'a> {
83    pub(crate) bucket_parameters: &'a BucketParameters,
84    /// The style's font faces, and its fallback faces after them.
85    pub(crate) font_faces: Option<&'a Arc<FontFaces>>,
86    /// Whether the style has a `glyphs` URL.
87    pub(crate) glyph_pbfs: bool,
88    pub(crate) glyph_dependencies: &'a mut GlyphDependencies,
89    pub(crate) image_dependencies: &'a mut ImageDependencies,
90    pub(crate) available_images: &'a VecSet<String>,
91    /// Where `image` expressions record the images not in `available_images`.
92    pub(crate) unavailable_images: &'a UnavailableImages,
93    /// The tile's feature groups, shared by the layouts' filters.
94    pub(crate) filter_groups: &'a mut FilterGroups,
95}
96
97/// What a layout reads of its tile while it selects features.
98pub struct LayoutCx<'a, T: StyleLayerType> {
99    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
100    pub(crate) source_layer: &'a SourceLayer,
101    pub(crate) parameters: LayoutParameters<'a>,
102}
103
104impl<'a, T: StyleLayerType> LayoutCx<'a, T> {
105    /// The layers of the group, its leader first, whose style the layout's
106    /// layout properties and filter are.
107    #[must_use]
108    pub fn layers(&self) -> &'a [Arc<EvaluatedLayer<T>>] {
109        self.layers
110    }
111
112    /// The tile.
113    #[must_use]
114    pub fn tile(&self) -> OverscaledTileID {
115        self.parameters.bucket_parameters.tile_id
116    }
117
118    /// The tile's zoom.
119    #[must_use]
120    pub fn zoom(&self) -> f32 {
121        f32::from(self.tile().overscaled_z)
122    }
123
124    /// How the map renders.
125    #[must_use]
126    pub fn mode(&self) -> MapMode {
127        self.parameters.bucket_parameters.mode
128    }
129
130    /// The device pixels per logical pixel that the map draws at.
131    #[must_use]
132    pub fn pixel_ratio(&self) -> f32 {
133        self.parameters.bucket_parameters.pixel_ratio
134    }
135
136    /// The style's global state, which `global-state` expressions read.
137    #[must_use]
138    pub fn global_state(&self) -> Option<&'a Arc<GlobalStateMap>> {
139        self.parameters.bucket_parameters.global_state.as_ref()
140    }
141
142    /// What the layout properties evaluate with: the tile's zoom and the
143    /// style's global state.
144    #[must_use]
145    pub fn parameters(&self) -> PropertyEvaluationParameters {
146        let mut parameters = PropertyEvaluationParameters::new(self.zoom());
147        parameters.global_state = self.global_state().cloned();
148        parameters
149    }
150
151    /// The style's font faces, which draw text in the scripts of their
152    /// ranges, and its fallback faces after them.
153    #[must_use]
154    pub fn font_faces(&self) -> Option<&'a Arc<FontFaces>> {
155        self.parameters.font_faces
156    }
157
158    /// Whether the style has glyphs of its own, a `glyphs` URL.
159    #[must_use]
160    pub fn has_glyphs(&self) -> bool {
161        self.parameters.glyph_pbfs
162    }
163
164    /// The images that exist, which `image` expressions branch on.
165    #[must_use]
166    pub fn available_images(&self) -> &'a VecSet<String> {
167        self.parameters.available_images
168    }
169
170    /// Where `image` expressions record the images they find unavailable.
171    #[must_use]
172    pub fn unavailable_images(&self) -> &'a UnavailableImages {
173        self.parameters.unavailable_images
174    }
175
176    /// The tile's source layer.
177    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
178        self.source_layer.layer()
179    }
180
181    /// The name of the tile's source layer that the layers lay out.
182    #[must_use]
183    pub fn source_layer_name(&self) -> &'a str {
184        &self.source_layer.name
185    }
186
187    /// What the leader's filter evaluates with apart from the feature: the
188    /// tile's zoom and id and the style's global state.
189    #[must_use]
190    pub fn filter_context(&self) -> EvaluationContext<'a> {
191        let parameters = self.parameters.bucket_parameters;
192        EvaluationContext::new(self.zoom())
193            .with_canonical_tile_id(Some(&parameters.tile_id.canonical))
194            .with_global_state(parameters.global_state.as_deref())
195    }
196
197    /// The features of `layer`, the tile's source layer, that the leader's
198    /// filter selects, evaluated with `context` ([`filter_context`](Self::filter_context)).
199    pub fn select(&mut self, layer: &TileLayer<'_>, context: EvaluationContext<'a>) -> Selection<'a> {
200        let leader = &self.layers[0].style;
201        let filter = &leader.filter;
202        let passes = |feature: &dyn GeometryTileFeature| {
203            filter.evaluate(&EvaluationContext { feature: Some(feature), ..context })
204        };
205        let selected = self.parameters.filter_groups.select(&leader.source_layer, layer, filter, &context, passes);
206        Selection { selected, filter, context }
207    }
208
209    /// Asks for the style's image `id`, as `kind`, unless it is asked for.
210    pub fn need_image(&mut self, id: &str, kind: ImageType) {
211        if !self.parameters.image_dependencies.contains_key(id) {
212            self.parameters.image_dependencies.insert(id.to_owned(), kind);
213        }
214    }
215
216    /// The glyphs and shapings the layout asks for.
217    pub fn glyphs(&mut self) -> &mut GlyphDependencies {
218        self.parameters.glyph_dependencies
219    }
220}
221
222/// The features of a tile's source layer that a filter selects
223/// ([`LayoutCx::select`]).
224pub struct Selection<'a> {
225    /// Whether the filter selects each feature, where feature groups
226    /// answered it; `None` where it evaluates each feature.
227    selected: Option<Vec<bool>>,
228    filter: &'a Filter,
229    context: EvaluationContext<'a>,
230}
231
232impl Selection<'_> {
233    /// The indexes of the selected features of `layer`, in feature order,
234    /// decoding only those that the filter evaluates.
235    pub fn indexes(&self, layer: &TileLayer<'_>) -> Result<Vec<usize>, Error> {
236        let mut indexes = Vec::new();
237        for i in 0..layer.len() {
238            let selects = match &self.selected {
239                Some(selected) => selected[i],
240                None => self.filter.evaluate(&EvaluationContext { feature: Some(&layer.feature(i)?), ..self.context }),
241            };
242            if selects {
243                indexes.push(i);
244            }
245        }
246        Ok(indexes)
247    }
248
249    /// Whether the filter may select the feature at `index`: false for one
250    /// that its feature group's evaluation rejected, which needn't decode.
251    #[inline]
252    #[must_use]
253    pub fn may_select(&self, index: usize) -> bool {
254        self.selected.as_ref().is_none_or(|selected| selected[index])
255    }
256
257    /// Whether the filter selects `feature`, a feature that it
258    /// [`may_select`](Self::may_select).
259    #[inline]
260    #[must_use]
261    pub fn selects(&self, feature: &dyn GeometryTileFeature) -> bool {
262        self.selected.is_some() || self.filter.evaluate(&EvaluationContext { feature: Some(feature), ..self.context })
263    }
264}
265
266/// What a layout reads and writes while it builds its bucket.
267pub struct BuildCx<'a, T: StyleLayerType> {
268    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
269    pub(crate) parameters: &'a BucketParameters,
270    pub(crate) first_load: bool,
271    pub(crate) source_layer: &'a SourceLayer,
272    pub(crate) resolved: Option<&'a Resolved>,
273    pub(crate) feature_index: &'a mut FeatureIndexBuilder,
274}
275
276impl<'a, T: StyleLayerType> BuildCx<'a, T> {
277    /// The group's layers by id, the first of each id kept.
278    #[must_use]
279    pub fn layers_by_id(&self) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
280        layers_by_id(self.layers)
281    }
282
283    /// The tile.
284    #[must_use]
285    pub fn tile(&self) -> OverscaledTileID {
286        self.parameters.tile_id
287    }
288
289    /// The tile's id, without its overscaling.
290    #[must_use]
291    pub fn canonical(&self) -> &'a CanonicalTileID {
292        &self.parameters.tile_id.canonical
293    }
294
295    /// The tile's zoom.
296    #[must_use]
297    pub(crate) fn zoom(&self) -> f32 {
298        f32::from(self.parameters.tile_id.overscaled_z)
299    }
300
301    /// How the map renders.
302    #[must_use]
303    pub fn mode(&self) -> MapMode {
304        self.parameters.mode
305    }
306
307    /// Whether the tile had no layout before this one.
308    #[must_use]
309    pub fn first_load(&self) -> bool {
310        self.first_load
311    }
312
313    /// How finely geometry splits to follow the globe's curve.
314    #[must_use]
315    pub fn subdivision_granularity(&self) -> SubdivisionGranularitySetting {
316        self.parameters.subdivision_granularity
317    }
318
319    /// What the glyphs and images the layout asked for resolved to; `None`
320    /// for a layout that asked for none.
321    #[must_use]
322    pub fn resolved(&self) -> Option<&'a Resolved> {
323        self.resolved
324    }
325
326    /// Where the resolved patterns are, or none.
327    #[must_use]
328    pub fn pattern_positions(&self) -> &'a ImagePositions {
329        static NONE: std::sync::LazyLock<ImagePositions> = std::sync::LazyLock::new(ImagePositions::default);
330        self.resolved.map_or(&NONE, |resolved| &resolved.patterns)
331    }
332
333    /// The tile's source layer.
334    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
335        self.source_layer.layer()
336    }
337
338    /// Binders of type `P` for each layer of the group, of its evaluated
339    /// paint values at the tile's zoom.
340    #[must_use]
341    pub fn binders<P>(&self) -> LayerBinders<P>
342    where
343        P: PaintBinders<Paint = <T::PaintProperties as PaintSet>::Evaluated>,
344    {
345        LayerBinders::new(self.layers, self.zoom())
346    }
347
348    /// Writes the values of `feature`, the feature at `index`, into
349    /// `binders` for the vertices up to `vertices`, those added since the
350    /// last call. `section` is the formatted section of the feature's text
351    /// that the vertices draw, which a property's `["get", ..]` of the
352    /// section reads; `patterns` the feature's patterns by layer, which the
353    /// values take where the resolved patterns put them. A layer whose
354    /// vertices draw neither passes `None` for both.
355    pub fn populate<P: PaintBinders>(
356        &self,
357        binders: &mut LayerBinders<P>,
358        index: usize,
359        feature: &dyn GeometryTileFeature,
360        vertices: usize,
361        section: Option<&Value>,
362        patterns: Option<&PatternLayerMap>,
363    ) {
364        static NO_SECTION: Value = Value::Null;
365        let no_patterns = ImagePositions::default();
366        let positions = if patterns.is_some() { self.pattern_positions() } else { &no_patterns };
367        let section = section.unwrap_or(&NO_SECTION);
368        binders.populate(feature, vertices, index, positions, patterns, self.canonical(), section);
369    }
370
371    /// Adds `geometry`, the geometry of the feature at `index`, to the
372    /// tile's feature index, which queries search. A layer type that places
373    /// its features leaves them out: queries find what placement shows.
374    pub fn index(&mut self, index: usize, geometry: &GeometryCollection) {
375        let leader = &self.layers[0].style;
376        self.feature_index.insert(geometry, index, &leader.source_layer, &leader.id);
377    }
378}
379
380/// The group's layers by id, the first of each id kept.
381pub fn layers_by_id<T: StyleLayerType>(group: &[Arc<EvaluatedLayer<T>>]) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
382    let mut layers = VecMap::new();
383    for layer in group {
384        layers.entry(layer.style.id.clone()).or_insert_with(|| Arc::clone(layer));
385    }
386    layers
387}