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