mln-rs-renderer 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! The render half of the source types: each marker type's [`SourceType`]
//! impl, which says how the renderer draws the type's sources. The registry
//! holds the types as `&'static dyn ErasedSourceType` ([`entry`]).
//!
//! A source with tiles draws through a
//! [`RenderTileSource`](crate::sources::render_tile_source::RenderTileSource),
//! which keeps its type's [`TileOrigin`]: what the type remembers between
//! updates and how a new version of the source changes the tiles.

use std::marker::PhantomData;
use std::sync::{Arc, Weak};

use mln_map_types::MapMode;
use mln_storage::FileSource;
use mln_style::Source;
use mln_style::layer_type::SourceKind;
use mln_style::source_type::{ErasedStyleSourceType, SourceData, SourceTypeEntry, StyleSourceType};
use mln_style::sources::custom::{CustomGeometryProvider, CustomVectorProvider};
use mln_style::sources::geojson::GeoJSONData;
use mln_style::sources::tileset::{TilesetKind, TilesetSourceType};
use mln_style::sources::{CustomGeometrySourceType, CustomVectorSourceType, GeoJsonSourceType, ImageSourceType};
use mln_util::constants;
use mln_util::error::Error;
use mln_util::geo::LatLngBounds;
use mln_util::range::Range;
use mln_util::tileset::{RasterEncoding, Tileset, VectorEncoding};

use crate::query::FeatureExtensionValue;
use crate::render_source::RenderSource;
use crate::sources::render_image_source::RenderImageSource;
use crate::sources::render_tile_source::RenderTileSource;
use crate::tile::loading::{CustomLoader, DataOrigin, VectorTileEncoding};
use crate::tile::source_tiles::SourceTiles;
use crate::tile::store::{StoreContext, TileStore};
use crate::tile::tile::TileKind;
use crate::tile_parameters::TileParameters;

/// A source type that the renderer draws.
pub(crate) trait SourceType: StyleSourceType {
    /// The render source of `source`, a source of the type, whose tiles, if
    /// it has any, go in `store`.
    fn render_source(source: &Source, store: &mut TileStore) -> Box<dyn RenderSource>;
}

/// What a source's tiles cover: their size in pixels, the zoom levels that
/// have tiles, and the bounds outside which there are none.
pub(crate) struct Cover {
    pub(crate) tile_size: u16,
    pub(crate) zoom_range: Range<u8>,
    pub(crate) bounds: Option<LatLngBounds>,
}

/// What a [`TileOrigin`] takes in with a new version of its source.
pub(crate) struct OriginUpdate<'a, 'p> {
    pub(crate) parameters: &'a TileParameters<'p>,
    pub(crate) needs_relayout: bool,
    pub(crate) fast_pfor_enabled: bool,
}

/// How a source type's tiles get their data: what its render source
/// remembers between updates, and how a new version of the source changes
/// the tiles.
pub(crate) trait TileOrigin {
    /// Takes in `source`, which replaces `previous`: sets the tiles' data
    /// origin and clears or reloads them as the type's rules say. Returns
    /// what the tiles cover, or `None` while the source has nothing to make
    /// tiles from.
    fn update(
        &mut self,
        previous: &Source,
        source: &Source,
        tiles: &mut SourceTiles,
        ctx: &mut StoreContext,
        update: &OriginUpdate<'_, '_>,
    ) -> Option<Cover>;

    /// The value of a feature extension of a feature of the source's tiles;
    /// a null value for a type without extensions.
    fn query_feature_extensions(
        &self,
        _feature: &mln_util::feature::Feature,
        _extension: &str,
        _extension_field: &str,
        _args: Option<&feature::PropertyMap>,
    ) -> Result<FeatureExtensionValue, Error> {
        Ok(FeatureExtensionValue::default())
    }

    /// The highest zoom level that has tiles, as far as the origin knows.
    fn max_zoom(&self) -> u8 {
        constants::TERRAIN_RGB_MAXZOOM
    }
}

/// A source type, whichever it is, that the renderer draws.
pub(crate) trait ErasedSourceType: ErasedStyleSourceType {
    /// [`SourceType::render_source`].
    fn create_render_source(&self, source: &Source, store: &mut TileStore) -> Box<dyn RenderSource>;
}

impl<T: SourceType> ErasedSourceType for SourceTypeEntry<T> {
    fn create_render_source(&self, source: &Source, store: &mut TileStore) -> Box<dyn RenderSource> {
        T::render_source(source, store)
    }
}

/// The source type `T` as a value.
pub(crate) const fn entry<T: SourceType>() -> &'static dyn ErasedSourceType {
    SourceTypeEntry::<T>::INSTANCE
}

// MARK: - Tilesets

/// Whether the tiles of the tileset kind `K` are vector tiles: always the
/// default size, in the encoding that the tileset names.
fn is_vector<K: TilesetKind>() -> bool {
    K::INFO.layer_kind == SourceKind::Geometry
}

impl<K: TilesetKind> SourceType for TilesetSourceType<K> {
    fn render_source(source: &Source, store: &mut TileStore) -> Box<dyn RenderSource> {
        let origin = TilesetOrigin::<K> { tileset: None, kind: PhantomData };
        let kind = match K::INFO.layer_kind {
            SourceKind::Raster => TileKind::Raster,
            // The tileset decides the encoding once it loads.
            SourceKind::RasterDem => TileKind::Dem(RasterEncoding::Mapbox),
            SourceKind::Geometry | SourceKind::None => TileKind::Geometry,
        };
        Box::new(RenderTileSource::new(source.clone(), kind, false, Box::new(origin), store))
    }
}

/// A tileset source's tiles: the tileset they were made from.
struct TilesetOrigin<K> {
    tileset: Option<Tileset>,
    kind: PhantomData<fn() -> K>,
}

impl<K: TilesetKind> TileOrigin for TilesetOrigin<K> {
    fn update(
        &mut self,
        _previous: &Source,
        source: &Source,
        tiles: &mut SourceTiles,
        ctx: &mut StoreContext,
        update: &OriginUpdate<'_, '_>,
    ) -> Option<Cover> {
        let data = SourceData::<TilesetSourceType<K>>::recover(source)?;
        let parameters = update.parameters;
        let loaded = data.description.clone();
        // In Continuous mode, keep the existing tiles if the new tileset is
        // not yet available, thus providing smart style transitions without
        // flickering. In other modes, allow clearing the tiles first, before
        // the early return in order to avoid render tests being flaky.
        let can_update_tileset = loaded.is_some() || parameters.mode != MapMode::Continuous;
        if can_update_tileset && self.tileset != loaded {
            self.tileset = loaded;
            // TODO: this removes existing buckets, and will cause flickering.
            // Should instead refresh tile data in place.
            tiles.clear_all(ctx);
            tiles.info.origin = None;
        }
        // A tileset without tiles makes no tiles, and the source counts as
        // loaded until its tiles are set.
        let tileset = self.tileset.clone().filter(|tileset| !tileset.tiles.is_empty())?;
        let encoding = if is_vector::<K>() && tileset.vector_encoding == Some(VectorEncoding::MLT) {
            // The encoding is decided once, from the first tileset (`isMLT`).
            VectorTileEncoding::Mlt { fast_pfor_enabled: update.fast_pfor_enabled }
        } else {
            VectorTileEncoding::Mvt
        };
        if let TileKind::Dem(_) = tiles.info.kind {
            tiles.info.kind = TileKind::Dem(tileset.raster_encoding.unwrap_or(RasterEncoding::Mapbox));
        }
        let file_source = parameters.file_source.clone();
        let current = matches!(
            &tiles.info.origin,
            Some(DataOrigin::Tileset { tileset: origin, encoding: current, file_source: current_file_source })
                if *origin == tileset
                    && *current == encoding
                    && same_file_source(current_file_source.as_ref(), file_source.as_ref())
        );
        if !current {
            tiles.info.origin = Some(DataOrigin::Tileset { tileset: tileset.clone(), encoding, file_source });
        }
        let tile_size = if is_vector::<K>() { constants::TILE_SIZE_I } else { data.options.tile_size };
        Some(Cover { tile_size, zoom_range: tileset.zoom_range, bounds: tileset.bounds })
    }

    fn max_zoom(&self) -> u8 {
        self.tileset.as_ref().map_or(constants::TERRAIN_RGB_MAXZOOM, |tileset| tileset.zoom_range.max)
    }
}

/// Whether `a` and `b` are both absent or the same file source.
fn same_file_source(a: Option<&Arc<dyn FileSource>>, b: Option<&Arc<dyn FileSource>>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)),
        _ => false,
    }
}

// MARK: - GeoJSON

impl SourceType for GeoJsonSourceType {
    fn render_source(source: &Source, store: &mut TileStore) -> Box<dyn RenderSource> {
        let origin = GeoJsonOrigin { data: None, synchronous: false };
        Box::new(RenderTileSource::new(source.clone(), TileKind::Geometry, true, Box::new(origin), store))
    }
}

/// A GeoJSON source's tiles: the data they were made from, and whether they
/// were made with synchronous updates.
struct GeoJsonOrigin {
    data: Option<Weak<dyn GeoJSONData>>,
    synchronous: bool,
}

/// Whether `a` and `b` are both empty or both the same object.
fn same_data(a: Option<&Arc<dyn GeoJSONData>>, b: Option<&Arc<dyn GeoJSONData>>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)),
        _ => false,
    }
}

impl TileOrigin for GeoJsonOrigin {
    fn update(
        &mut self,
        _previous: &Source,
        source: &Source,
        tiles: &mut SourceTiles,
        ctx: &mut StoreContext,
        update: &OriginUpdate<'_, '_>,
    ) -> Option<Cover> {
        let source = SourceData::<GeoJsonSourceType>::recover(source)?;
        let parameters = update.parameters;
        // A tile lays out in the mode it was created with, so a mode change
        // recreates the tiles.
        if parameters.is_update_synchronous != self.synchronous {
            self.synchronous = parameters.is_update_synchronous;
            tiles.clear_all(ctx);
        }
        let data = source.description.clone();
        let previous = self.data.as_ref().and_then(Weak::upgrade);
        if !same_data(previous.as_ref(), data.as_ref()) {
            self.data = data.as_ref().map(Arc::downgrade);
            tiles.info.origin = data.as_ref().map(|data| DataOrigin::GeoJson(Arc::clone(data)));
            tiles.info.synchronous = parameters.is_update_synchronous;
            if parameters.mode != MapMode::Continuous {
                // Clearing the tiles in order to avoid render tests being
                // flaky.
                tiles.clear_all(ctx);
            } else if let Some(data) = &data {
                tiles.reduce_memory_use(ctx);
                let max_z = source.options.get_zoom_range().max;
                tiles.update_each(
                    ctx,
                    |slot| !slot.place().is_cached() && slot.tile.id.canonical.z <= max_z,
                    |tile| tile.load_geojson(data, update.needs_relayout),
                );
            }
        }
        data?;
        Some(Cover { tile_size: constants::TILE_SIZE_I, zoom_range: source.options.get_zoom_range(), bounds: None })
    }

    /// The "supercluster" extension of a GeoJSON source: a cluster feature's
    /// "children", "leaves" (`args` "limit", default 10, and "offset",
    /// default 0) or "expansion-zoom". Anything else is a null value.
    fn query_feature_extensions(
        &self,
        feature: &mln_util::feature::Feature,
        extension: &str,
        extension_field: &str,
        args: Option<&feature::PropertyMap>,
    ) -> Result<FeatureExtensionValue, Error> {
        if extension != "supercluster" {
            return Ok(FeatureExtensionValue::default());
        }
        let Some(cluster_id) = get_uint_property(&feature.properties, "cluster_id") else {
            return Ok(FeatureExtensionValue::default());
        };
        let Some(json_data) = self.data.as_ref().and_then(Weak::upgrade) else {
            return Ok(FeatureExtensionValue::default());
        };
        supercluster_extension(&*json_data, extension_field, cluster_id as u32, args)
            .unwrap_or_else(|| Ok(FeatureExtensionValue::default()))
    }
}

/// The property `name`, if it is an unsigned integer.
fn get_uint_property(properties: &feature::PropertyMap, name: &str) -> Option<u64> {
    match properties.get(name) {
        Some(feature::Value::Uint(value)) => Some(*value),
        _ => None,
    }
}

/// The supercluster `extensionGetters`: the `extension_field` of cluster
/// `cluster_id`, or `None` for a field it doesn't have.
fn supercluster_extension(
    cluster_data: &dyn GeoJSONData,
    extension_field: &str,
    cluster_id: u32,
    args: Option<&feature::PropertyMap>,
) -> Option<Result<FeatureExtensionValue, Error>> {
    Some(match extension_field {
        "children" => cluster_data.get_children(cluster_id).map(FeatureExtensionValue::FeatureCollection),
        "leaves" => {
            // Offset cannot be set without limit.
            let (limit, offset) = match args.and_then(|args| Some((get_uint_property(args, "limit")?, args))) {
                Some((limit, args)) => {
                    (limit as u32, get_uint_property(args, "offset").map_or(0, |offset| offset as u32))
                }
                None => (10, 0),
            };
            cluster_data.get_leaves(cluster_id, limit, offset).map(FeatureExtensionValue::FeatureCollection)
        }
        "expansion-zoom" => cluster_data
            .get_cluster_expansion_zoom(cluster_id)
            .map(|zoom| FeatureExtensionValue::Value(feature::Value::Uint(u64::from(zoom)))),
        _ => return None,
    })
}

// MARK: - Images

impl SourceType for ImageSourceType {
    fn render_source(source: &Source, _store: &mut TileStore) -> Box<dyn RenderSource> {
        Box::new(RenderImageSource::new(source.clone()))
    }
}

// MARK: - Custom sources

impl SourceType for CustomGeometrySourceType {
    fn render_source(source: &Source, store: &mut TileStore) -> Box<dyn RenderSource> {
        Box::new(RenderTileSource::new(source.clone(), TileKind::Geometry, true, Box::new(CustomGeometryOrigin), store))
    }
}

impl SourceType for CustomVectorSourceType {
    fn render_source(source: &Source, store: &mut TileStore) -> Box<dyn RenderSource> {
        Box::new(RenderTileSource::new(source.clone(), TileKind::Geometry, false, Box::new(CustomVectorOrigin), store))
    }
}

/// Points the tiles of a custom source at its provider. New options, zoom
/// range or provider clear them.
fn update_custom<T: StyleSourceType>(
    previous: &Source,
    source: &Source,
    tiles: &mut SourceTiles,
    ctx: &mut StoreContext,
    update: &OriginUpdate<'_, '_>,
    differs: impl FnOnce(&SourceData<T>, &SourceData<T>) -> bool,
    parts: impl FnOnce(&SourceData<T>) -> (Arc<dyn CustomLoader>, u16, Range<u8>),
) -> Option<Cover> {
    let data = SourceData::<T>::recover(source)?;
    let same = Source::ptr_eq(previous, source);
    let differs = SourceData::<T>::recover(previous).is_none_or(|previous| differs(data, previous));
    if !same && differs {
        tiles.clear_all(ctx);
    }
    let (loader, tile_size, zoom_range) = parts(data);
    if tiles.info.origin.is_none() || !same {
        tiles.info.origin = Some(DataOrigin::Custom { loader, fast_pfor_enabled: update.fast_pfor_enabled });
    }
    Some(Cover { tile_size, zoom_range, bounds: None })
}

/// A custom geometry source's tiles, which take their features from its
/// provider.
struct CustomGeometryOrigin;

impl TileOrigin for CustomGeometryOrigin {
    fn update(
        &mut self,
        previous: &Source,
        source: &Source,
        tiles: &mut SourceTiles,
        ctx: &mut StoreContext,
        update: &OriginUpdate<'_, '_>,
    ) -> Option<Cover> {
        update_custom::<CustomGeometrySourceType>(
            previous,
            source,
            tiles,
            ctx,
            update,
            SourceData::<CustomGeometrySourceType>::differs,
            |data| {
                let options = &data.options;
                let provider: Arc<dyn CustomLoader> = Arc::<CustomGeometryProvider>::clone(&options.provider);
                (provider, options.tile_options.tile_size, options.zoom_range)
            },
        )
    }
}

/// A custom vector source's tiles, which decode the bytes its provider
/// gives.
struct CustomVectorOrigin;

impl TileOrigin for CustomVectorOrigin {
    fn update(
        &mut self,
        previous: &Source,
        source: &Source,
        tiles: &mut SourceTiles,
        ctx: &mut StoreContext,
        update: &OriginUpdate<'_, '_>,
    ) -> Option<Cover> {
        update_custom::<CustomVectorSourceType>(
            previous,
            source,
            tiles,
            ctx,
            update,
            SourceData::<CustomVectorSourceType>::differs,
            |data| {
                let provider: Arc<dyn CustomLoader> = Arc::<CustomVectorProvider>::clone(&data.options.provider);
                (provider, constants::TILE_SIZE_I, data.options.zoom_range)
            },
        )
    }
}