mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Coordinate reference systems for the tests of registered projections.
pub(crate) mod crs;
// The log records a test catches.
pub(crate) mod log_capture;
// GeoJSON in a registered projection.
mod geojson_crs_test;
// Malformed vector tiles become tile errors, not panics.
mod malformed_tile_test;
// The context destroys what it released after what was made of it.
mod release_test;
// Textures with mips make them from what they upload.
mod texture_mips_test;
// A tile drives its layout jobs.
mod tile_jobs_test;
// What a tile shows as its loads end.
mod tile_state_test;
// The tile store keeps a tile's data, work and contents apart.
mod tile_store_test;

// The tests' own source types.
pub(crate) mod types;

// The tests' backend, which draws nothing.
pub(crate) mod fake_gpu;

/// The registrations that the tests' maps, renderers and styles use: the
/// specification's expression functions, the tests' layer types and source
/// types, and the built-in projections.
pub(crate) fn registry() -> std::sync::Arc<crate::Registry> {
    static REGISTRY: std::sync::LazyLock<std::sync::Arc<crate::Registry>> =
        std::sync::LazyLock::new(|| registry_builder().build());
    std::sync::Arc::clone(&REGISTRY)
}

/// A builder that holds [`registry`]'s registrations, for a test that adds
/// its own.
pub(crate) fn registry_builder() -> crate::RegistryBuilder {
    let mut builder = crate::RegistryBuilder::new();
    mln_style::expression::functions::register_builtin_functions(builder.functions_mut())
        .and_then(|()| crate::register_builtin_projections(&mut builder))
        .and_then(|()| types::layers::register_layer_types(&mut builder))
        .and_then(|()| types::register_source_types(&mut builder))
        .expect("the tests' types register into an empty builder");
    builder
}

/// The bytes of `relative`, a file of the package's testdata/.
pub(crate) fn testdata(relative: &str) -> Vec<u8> {
    let path = std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("testdata").join(relative);
    std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}

/// An opaque PNG whose pixels differ from their neighbours.
pub(crate) fn png(width: u32, height: u32) -> crate::storage::Data {
    let mut image = mln_style::bitmap::PremultipliedImage::new(mln_style::size::Size::new(width, height));
    for (i, pixel) in image.data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
        pixel.copy_from_slice(&[(i % 251) as u8, (i / 7 % 253) as u8, (i * 3 % 255) as u8, 255]);
    }
    std::sync::Arc::new(crate::image::encode_png(&image))
}

/// A 16 by 16 DEM image whose pixels differ from their neighbours and from
/// those of other `seed`s.
pub(crate) fn dem_png(seed: u32) -> crate::storage::Data {
    let mut image = mln_style::bitmap::PremultipliedImage::new(mln_style::size::Size::new(16, 16));
    for (i, pixel) in image.data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
        let i = i as u32;
        *pixel = [((seed * 37 + i) % 256) as u8, (i * 7 % 256) as u8, ((i * 3 + seed) % 256) as u8, 255];
    }
    std::sync::Arc::new(crate::image::encode_png(&image))
}

/// Tile workers in `count` worker instances on threads, reached only
/// through the worker codec.
pub(crate) fn remote_workers(count: usize) -> crate::worker::worker_codec::RemoteWorkers {
    use crate::worker::worker_codec::{RemoteWorkers, ThreadWorkerInstances};
    let registry = registry();
    RemoteWorkers::new(std::sync::Arc::clone(&registry), move |replies| {
        Box::new(ThreadWorkerInstances::new(count, registry, &replies))
    })
}

/// A pool for a test's background work.
pub(crate) fn pool() -> crate::exec::pool::Pool {
    crate::exec::pool::Pool::new(4)
}

/// The time a test's clock starts at, from which the test moves it. Any
/// time does, so it's the system's, read once: what the test checks then
/// happens at the times it gives, however slowly it runs.
pub(crate) fn start_time() -> mln_style::time::Instant {
    mln_style::time::Instant::now()
}

/// Holds `clock` at [`start_time`], which it returns: the animations,
/// fades and scheduled changes on it move only as the test moves it.
pub(crate) fn hold_clock(clock: &crate::camera::FrameClock) -> mln_style::time::Instant {
    let start = start_time();
    clock.hold(Some(start));
    start
}

/// A tile store whose jobs run on `workers` and which frees and
/// parses glyphs on `pool`, with no images and no sprite loaded.
pub(crate) fn tile_store(
    pool: &crate::exec::pool::TaskGroup,
    workers: Box<dyn crate::worker::tile_workers::TileWorkers>,
) -> crate::tile_store::store::TileStore {
    waking_store(pool, workers, std::sync::Arc::new(|| {}))
}

/// A [`tile_store`] that calls `wake` whenever a reply or glyphs arrive for
/// it, for a test that waits for them.
pub(crate) fn waking_store(
    pool: &crate::exec::pool::TaskGroup,
    workers: Box<dyn crate::worker::tile_workers::TileWorkers>,
    wake: crate::tile_store::inbox::Waker,
) -> crate::tile_store::store::TileStore {
    let glyphs = crate::text::glyph_store::GlyphStore::new(
        crate::text::local_fonts::LocalGlyphs::default(),
        std::sync::Arc::default(),
        pool.clone(),
        crate::text::font_face_engine::default_engine(),
        std::sync::Arc::clone(&wake),
    );
    crate::tile_store::store::TileStore::new(
        workers,
        glyphs,
        crate::image::image_store::ImageStore::default(),
        pool.clone(),
        wake,
    )
}

/// A [`waking_store`] whose jobs run on `pool`, which wakes `run_loop`: a
/// test that runs the loop parks it until a task or a reply arrives.
pub(crate) fn pool_store_waking(
    pool: &crate::exec::pool::TaskGroup,
    run_loop: &crate::exec::queue::Queue<()>,
) -> crate::tile_store::store::TileStore {
    let run_loop = run_loop.downgrade();
    waking_store(
        pool,
        Box::new(crate::worker::tile_workers::PoolWorkers::new(pool.clone(), 8)),
        std::sync::Arc::new(move || {
            if let Some(run_loop) = run_loop.upgrade() {
                run_loop.wake();
            }
        }),
    )
}

/// A tile store whose jobs run on `pool`.
pub(crate) fn pool_store(pool: &crate::exec::pool::TaskGroup) -> crate::tile_store::store::TileStore {
    tile_store(pool, Box::new(crate::worker::tile_workers::PoolWorkers::new(pool.clone(), 8)))
}

/// One update of `store`'s tiles, as the renderer's: gives the
/// images asked for their update, takes in what arrived and starts the next
/// jobs. Returns whether a tile of a source with synchronous updates laid
/// out.
pub(crate) fn update(store: &mut crate::tile_store::store::TileStore) -> bool {
    store.images_mut().begin_update();
    store.receive();
    store.drive()
}

/// An origin whose tiles load nothing themselves: the test gives
/// them their data, at once or as a reply to a load it began, which
/// delivers the item it holds. Its tiles cover 512-pixel tiles of every
/// zoom.
pub(crate) struct Given<K>(std::marker::PhantomData<fn() -> K>);

impl<K: crate::source::TileKind> crate::source::DataOrigin for Given<K>
where
    K::Item: Send,
{
    type Data = K;
    type Tile = ();
    type Reply = Option<K::Item>;

    fn update(&mut self, _: &mut crate::source::OriginUpdate<'_, Self>) -> Option<crate::source::Cover> {
        Some(given_cover(<K as crate::source::kind::Deliver>::KIND))
    }

    fn start(&mut self, _: &mut crate::source::LoadContext<'_, '_, Self>, _: Option<crate::source::WorldCopy<'_, ()>>) {
    }

    fn receive(&mut self, (): &mut (), item: Option<K::Item>, cx: &mut crate::source::LoadContext<'_, '_, Self>) {
        cx.deliver(item);
    }
}

/// What a [`Given`] origin's tiles of `kind` cover, chosen as a tileset's
/// of the kind.
fn given_cover(kind: mln_style::layer::SourceKind) -> crate::source::Cover {
    let raster = kind != mln_style::layer::SourceKind::Geometry;
    crate::source::Cover {
        tile_size: mln_style::constants::TILE_SIZE_I,
        zoom_range: mln_style::range::Range::new(0, 22),
        bounds: None,
        round_zoom: raster,
        overscale: !raster,
        prefetch: true,
        synchronous: false,
    }
}

/// A [`Given`] origin of tiles of `kind`.
pub(crate) fn given(kind: mln_style::layer::SourceKind) -> Box<dyn crate::source::erased::ErasedOrigin> {
    use mln_style::layer::SourceKind;
    match kind {
        SourceKind::Geometry | SourceKind::None | SourceKind::Any => {
            Box::new(Given::<crate::source::GeometryTiles>(std::marker::PhantomData))
        }
        SourceKind::Raster => Box::new(Given::<crate::source::RasterTiles>(std::marker::PhantomData)),
        SourceKind::RasterDem => Box::new(Given::<crate::source::DemTiles>(std::marker::PhantomData)),
    }
}

/// The origin that the tests' type of `source` supplies.
pub(crate) fn origin_of(source: &mln_style::Source) -> Box<dyn crate::source::erased::ErasedOrigin> {
    let registry = registry();
    let source_type = registry.source_type(source.info().name).expect("a source type of the tests");
    match source_type.supply(source) {
        crate::source::Supplied::Tiles(origin) => origin,
        crate::source::Supplied::Image(_) => panic!("a source with tiles"),
    }
}

/// How the tests' type of `source`, an image source, reads its
/// image.
pub(crate) fn image_of(source: &mln_style::Source) -> crate::source::ImageOf {
    let registry = registry();
    let source_type = registry.source_type(source.info().name).expect("a source type of the tests");
    match source_type.supply(source) {
        crate::source::Supplied::Image(image_of) => image_of,
        crate::source::Supplied::Tiles(_) => panic!("an image source"),
    }
}

/// The tileset origin's state of `tile`, a tile of a tileset
/// source.
pub(crate) fn tileset_tile(tile: &crate::tile_store::tile::Tile) -> &types::tileset::TestTilesetTile {
    let state = tile.load.state.as_deref().expect("the origin's state of the tile");
    state.downcast_ref().expect("a tileset tile")
}

/// What a test's map says of its tiles: drawn for `mode`, loaded
/// through `file_source`.
pub(crate) fn map_settings(
    mode: crate::map::MapMode,
    file_source: Option<std::sync::Arc<dyn crate::storage::FileSource>>,
) -> crate::source::MapSettings {
    crate::source::MapSettings {
        mode,
        pixel_ratio: 1.0,
        world: mln_style::crs::WorldMapping::default(),
        max_zoom: 22.0,
        file_source,
    }
}

/// One tile of a source of its own in a store, driven as the
/// renderer drives it, whose data the test gives it.
pub(crate) struct OneTile {
    pub(crate) store: crate::tile_store::store::TileStore,
    pub(crate) key: crate::worker::job::SourceKey,
    pub(crate) id: crate::tile::OverscaledTileID,
    mode: crate::map::MapMode,
}

impl OneTile {
    /// Tile `id` of kind `kind` in `store`, laid out for `mode`.
    pub(crate) fn new(
        mut store: crate::tile_store::store::TileStore,
        kind: mln_style::layer::SourceKind,
        id: crate::tile::OverscaledTileID,
        mode: crate::map::MapMode,
    ) -> Self {
        let key = store.add_source("s".to_owned(), given(kind));
        let (source, _) = store.source_mut(key).expect("the source");
        source.info.cover = Some(given_cover(kind));
        let mut tiles = OneTile { store, key, id, mode };
        tiles.add(id);
        tiles
    }

    fn params(&self) -> crate::layer::tile_layout::LayoutParams {
        crate::layer::tile_layout::LayoutParams {
            mode: self.mode,
            pixel_ratio: 1.0,
            subdivision_granularity: mln_style::subdivision_granularity::SubdivisionGranularitySetting::none(),
            first_load: true,
        }
    }

    /// Tiles `ids` of `source`, in `store`, whose data comes from the
    /// origin its type supplies, loaded through `file_source` and
    /// laid out for `mode`. The origin takes in `source`, then the tiles'
    /// loads start as a cover starts them.
    pub(crate) fn with_origin(
        mut store: crate::tile_store::store::TileStore,
        source: &mln_style::Source,
        file_source: Option<std::sync::Arc<dyn crate::storage::FileSource>>,
        ids: &[crate::tile::OverscaledTileID],
        mode: crate::map::MapMode,
    ) -> Self {
        let key = store.add_source("source".to_owned(), origin_of(source));
        let mut tiles = OneTile { store, key, id: ids[0], mode };
        let params = tiles.params();
        let (tiles_of_source, ctx) = tiles.store.source_mut(key).expect("the source");
        let cover = tiles_of_source.update_origin(source, ctx, &map_settings(mode, file_source), false);
        assert!(cover.is_some(), "the source has tiles");
        for id in ids {
            tiles_of_source.add_tile(*id, params, false, ctx).expect("a tile");
        }
        tiles
    }

    /// Sets how much tile `id` is needed.
    pub(crate) fn set_necessity(
        &mut self,
        id: &crate::tile::OverscaledTileID,
        necessity: crate::tile_store::tile::TileNecessity,
    ) {
        self.with_at(id, |tile| tile.set_necessity(necessity));
    }

    /// Adds another tile, `id`, to the source, which loads nothing itself.
    pub(crate) fn add(&mut self, id: crate::tile::OverscaledTileID) {
        let params = self.params();
        let (source, _) = self.store.source_mut(self.key).expect("the source");
        let mut tile = source.info.new_tile(id, params).expect("a tile");
        tile.load.state = Some(Box::new(()));
        source.insert(tile);
    }

    pub(crate) fn tile(&self) -> &crate::tile_store::tile::Tile {
        self.tile_at(&self.id)
    }

    /// The layout parameters of the tile.
    pub(crate) fn tile_params(&self) -> crate::layer::tile_layout::LayoutParams {
        self.layout().params
    }

    /// The layout of the tile, a geometry tile.
    pub(crate) fn layout(&self) -> &crate::tile_store::pipeline::Layout {
        self.tile().pipeline.layout().expect("a geometry tile")
    }

    pub(crate) fn tile_at(&self, id: &crate::tile::OverscaledTileID) -> &crate::tile_store::tile::Tile {
        self.store.source(self.key).and_then(|source| source.tile(id)).expect("the tile")
    }

    /// Changes the tile through `f`.
    pub(crate) fn with<R>(&mut self, f: impl FnOnce(&mut crate::tile_store::tile_mut::TileMut<'_>) -> R) -> R {
        let id = self.id;
        self.with_at(&id, f)
    }

    /// Changes tile `id` through `f`.
    pub(crate) fn with_at<R>(
        &mut self,
        id: &crate::tile::OverscaledTileID,
        f: impl FnOnce(&mut crate::tile_store::tile_mut::TileMut<'_>) -> R,
    ) -> R {
        let (source, ctx) = self.store.source_mut(self.key).expect("the source");
        source.update(id, ctx, f).expect("the tile")
    }

    pub(crate) fn set_style(&mut self, style: &std::sync::Arc<crate::worker::job::SourceStyle>) {
        let params = self.params();
        self.with(|tile| tile.set_style(style, params.pixel_ratio, params.subdivision_granularity));
    }

    /// Gives a geometry tile `data`, as a load of its own.
    pub(crate) fn set_data(&mut self, data: Option<crate::tile::TileData>) {
        self.with(|tile| tile.take_data(data, false));
    }

    /// Gives raster tile `id` the image `data`, as a load of its own.
    pub(crate) fn set_image(&mut self, id: &crate::tile::OverscaledTileID, data: Option<crate::storage::Data>) {
        self.with_at(id, |tile| tile.take_image(data, false));
    }

    /// Gives tile `id` no data, as a load that finds the tileset has no
    /// tile there.
    pub(crate) fn set_missing(&mut self, id: &crate::tile::OverscaledTileID) {
        self.with_at(id, |tile| {
            tile.take_missing();
        });
    }

    /// What the store reported its tiles went through since the last call.
    pub(crate) fn actions(&mut self) -> Vec<crate::tile_store::tile::TileOperation> {
        self.store
            .take_events()
            .into_iter()
            .filter_map(|event| match event {
                crate::tile_store::store::StoreEvent::Action { op, .. } => Some(op),
                crate::tile_store::store::StoreEvent::Changed | crate::tile_store::store::StoreEvent::Error { .. } => {
                    None
                }
            })
            .collect()
    }

    /// The errors the store reported since the last call.
    pub(crate) fn errors(&mut self) -> Vec<String> {
        self.store
            .take_events()
            .into_iter()
            .filter_map(|event| match event {
                crate::tile_store::store::StoreEvent::Error { error, .. } => Some(error.to_string()),
                crate::tile_store::store::StoreEvent::Changed | crate::tile_store::store::StoreEvent::Action { .. } => {
                    None
                }
            })
            .collect()
    }

    /// One update of the store.
    pub(crate) fn update(&mut self) -> bool {
        update(&mut self.store)
    }

    /// Updates the store until the tiles `ids` are all complete, updating at
    /// least once.
    pub(crate) fn settle(&mut self, ids: &[crate::tile::OverscaledTileID]) {
        loop {
            self.update();
            if ids.iter().all(|id| self.tile_at(id).is_complete()) {
                return;
            }
            std::thread::yield_now();
        }
    }

    /// Whether the tile shows a layout.
    pub(crate) fn shows_layout(&self) -> bool {
        self.tile().contents().and_then(crate::tile_store::contents::Contents::geometry).is_some()
    }

    /// Lets go of the tile, as its source does when it leaves the cache.
    pub(crate) fn drop_tile(&mut self) {
        let id = self.id;
        self.drop_tile_at(&id);
    }

    /// Lets go of tile `id`.
    pub(crate) fn drop_tile_at(&mut self, id: &crate::tile::OverscaledTileID) {
        let (source, ctx) = self.store.source_mut(self.key).expect("the source");
        source.release(id, ctx);
    }
}

/// A source's style of `layers`, without global state or font
/// faces.
pub(crate) fn style(
    layers: &[std::sync::Arc<dyn crate::layer::layer_type::ErasedEvaluatedLayer>],
) -> std::sync::Arc<crate::worker::job::SourceStyle> {
    std::sync::Arc::new(crate::worker::job::SourceStyle {
        version: 0,
        layers: layers.to_vec(),
        global_state: None,
        font_faces: None,
        glyph_pbfs: true,
        world: mln_style::crs::WorldMapping::default(),
        layer_groups: std::sync::OnceLock::new(),
    })
}

/// A layer from its style JSON on source `s`, evaluated at zoom 0 as the
/// `RenderOrchestrator` evaluates it.
pub(crate) fn layer(mut json: serde_json::Value) -> std::sync::Arc<dyn crate::layer::layer_type::ErasedEvaluatedLayer> {
    json["source"] = serde_json::json!("s");
    let mut error = mln_style::conversion::Error::default();
    let layer = mln_style::layer::convert_layer(
        registry().style(),
        &mln_style::conversion::Convertible::from(&json),
        &mut error,
    )
    .unwrap_or_else(|| panic!("{}", error.message));
    let mut render_layer = render_layer(layer.style());
    render_layer.evaluate(&mln_style::property::evaluation::PropertyEvaluationParameters::new(0.0));
    std::sync::Arc::clone(&render_layer.base().evaluated_properties)
}

/// The render layer of the layer `style`, of a type of the registry.
pub(crate) fn render_layer(
    style: &std::sync::Arc<dyn mln_style::layer::ErasedLayerStyle>,
) -> Box<dyn crate::layer::render_layer::RenderLayer> {
    let registry = registry();
    let layer_type = registry.layer_type(style.info().name).expect("a layer type of the registry");
    layer_type.create_render_layer(style).expect("a layer of its type")
}

/// The render source of `source`, through the tests' registry.
pub(crate) fn create_render_source(
    source: &mln_style::Source,
    store: &mut crate::tile_store::store::TileStore,
) -> Box<dyn crate::source::render_source::RenderSource> {
    crate::source::render_source::create(&registry(), source, store).expect("a source type of the tests")
}

/// `source` with the description that its type knows without a fetch, such
/// as the tileset or the GeoJSON a style lists, as the map's loader gives it
/// on a Mercator map.
pub(crate) fn ready(source: mln_style::Source) -> mln_style::Source {
    let source_type = registry().source_type(source.info().name).expect("a source type of the tests");
    match source_type.plan_load(&source) {
        crate::source::Load::Ready(description) => source.with_description(Some(description)),
        crate::source::Load::Describe => {
            let (sender, receiver) = std::sync::mpsc::channel();
            source_type.describe_job(&source, &mln_style::crs::WorldMapping::default(), None)(Box::new(
                move |described| {
                    let _ = sender.send(described);
                },
            ));
            let described = receiver.recv().expect("an answer").expect("a description");
            source.with_description(described)
        }
        _ => source,
    }
}

/// Runs `f` with a [`FakeGpu`](fake_gpu::FakeGpu) and a context over it,
/// which it then tears down, checking that the teardown destroyed everything
/// that wasn't destroyed before.
pub(crate) fn with_context(f: impl FnOnce(&mut dyn mln_gfx::gpu::Gpu, &mut crate::draw::context::Context)) {
    use mln_gfx::gpu::Gpu as _;
    let mut gpu = fake_gpu::FakeGpu::default();
    let mut context = crate::draw::context::Context::new(*gpu.caps(), 1.0);
    f(&mut gpu, &mut context);
    context.tear_down(&mut gpu);
    assert_eq!(0, gpu.live(), "the context's teardown left resources live");
}