mln-rs-engine 0.0.23

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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! A map over terrain draws a drape again only when what it shows changed:
//! its layers or their values, the tiles or image they draw, their feature
//! state, the style's images, the zoom and the globe's scale, or the bearing
//! for a layer that draws by it, but not for a hillshade lit from the
//! viewport, which the surface shades. A byte cap halves the drapes of the
//! tiles farthest from the center first.

use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;

use mln_style::bitmap::PremultipliedImage;
use mln_style::feature::FeatureState;
use mln_style::geo::LatLng;
use mln_style::size::Size;
use mln_style::sources::GeoJSONOptions;
use mln_style::tile_id::CanonicalTileID;
use mln_style::time::Instant;
use mln_style::types::{ProjectionDefinition, ProjectionType};
use mln_style::{Edit, Style};
use parking_lot::Mutex;

use super::{TestRenderer, style_of, update_parameters};
use crate::camera::transform::Transform;
use crate::camera::{CameraOptions, ConstrainMode, Elevation};
use crate::map::{MapMode, TerrainOptions};
use crate::render::events::{RenderMode, RendererEvent};
use crate::render::update_parameters::UpdateParameters;
use crate::storage::{FileSource, Resource, Responder, Response};
use crate::tile::OverscaledTileID;
use crate::tile_store::tile::TileOperation;

const SIDE: u32 = 256;

/// A white map with a raster layer, a fill whose color follows the feature
/// state "hover", and a line, over a terrain of flat ground.
const STYLE: &str = r#"{
    "version": 8,
    "transition": {"duration": 0},
    "terrain": {"source": "dem"},
    "sources": {
        "dem": {"type": "raster-dem", "tiles": ["dem/{z}/{x}/{y}.png"], "tileSize": 256, "maxzoom": 10},
        "raster": {"type": "raster", "tiles": ["raster/{z}/{x}/{y}.png"], "tileSize": 256},
        "shapes": {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "id": 1,
                "properties": {},
                "geometry": {"type": "Polygon", "coordinates": [[[-80, 50], [-70, 50], [-70, 60], [-80, 60], [-80, 50]]]}
            }
        }
    },
    "layers": [
        {"id": "background", "type": "background", "paint": {"background-color": "white"}},
        {"id": "raster", "type": "raster", "source": "raster", "paint": {"raster-opacity": 0.5}},
        {
            "id": "fill",
            "type": "fill",
            "source": "shapes",
            "paint": {"fill-color": ["case", ["boolean", ["feature-state", "hover"], false], "red", "blue"]}
        },
        {"id": "line", "type": "line", "source": "shapes", "paint": {"line-width": 4}}
    ]
}"#;

/// A PNG of 256 pixels a side, every pixel `pixel`.
fn png(pixel: [u8; 4]) -> Response {
    let mut image = PremultipliedImage::new(Size::new(256, 256));
    for texel in image.data.as_chunks_mut::<4>().0 {
        *texel = pixel;
    }
    let mut response = Response::new();
    response.data = Some(Arc::new(crate::image::encode_png(&image)));
    response
}

/// Answers every tile request at once, sea level for the DEM, grey for the
/// raster source, but the raster tile `held`, which waits until released.
#[derive(Default)]
struct Tiles {
    held: Mutex<Option<CanonicalTileID>>,
    waiting: Mutex<Vec<(Responder, Response)>>,
}

impl FileSource for Tiles {
    fn load(&self, resource: &Resource, responder: Responder) {
        let data = resource.tile_data.as_ref().expect("only tiles are requested");
        let tile = CanonicalTileID::new(data.z as u8, data.x as u32, data.y as u32);
        let dem = data.url_template.starts_with("dem/");
        // (1 · 65536 + 134 · 256 + 160) · 0.1 − 10000 = 0 m.
        let response = png(if dem { [1, 134, 160, 255] } else { [128, 128, 128, 255] });
        if !dem && *self.held.lock() == Some(tile) {
            self.waiting.lock().push((responder, response));
        } else {
            responder.send(response);
        }
    }

    fn can_request(&self, _resource: &Resource) -> bool {
        true
    }
}

impl Tiles {
    /// Answers the held tile.
    fn release(&self) {
        *self.held.lock() = None;
        let waiting = std::mem::take(&mut *self.waiting.lock());
        for (responder, response) in waiting {
            responder.send(response);
        }
    }
}

/// The tiles that the renderer requested and that weren't answered yet, and
/// those being parsed, as its events tell.
#[derive(Default)]
struct TileWork {
    unanswered: BTreeSet<(String, OverscaledTileID)>,
    parsing: BTreeSet<(String, OverscaledTileID)>,
}

impl TileWork {
    fn record(&mut self, op: TileOperation, tile: (String, OverscaledTileID)) {
        match op {
            TileOperation::RequestedFromCache | TileOperation::RequestedFromNetwork => {
                self.unanswered.insert(tile);
            }
            TileOperation::LoadFromCache | TileOperation::LoadFromNetwork => {
                self.unanswered.remove(&tile);
            }
            TileOperation::StartParse => {
                self.parsing.insert(tile);
            }
            TileOperation::EndParse => {
                self.parsing.remove(&tile);
            }
            TileOperation::Error | TileOperation::Cancelled => {
                self.unanswered.remove(&tile);
                self.parsing.remove(&tile);
            }
            TileOperation::NullOp => {}
        }
    }

    /// Whether the renderer waits for no tile but `held` unanswered ones.
    fn idle(&self, held: usize) -> bool {
        self.unanswered.len() == held && self.parsing.is_empty()
    }
}

/// A continuous map of [`STYLE`], at zoom 2 over 10° E, 10° S,
/// seen from above over four terrain tiles, drawn frame by frame.
struct DrapedMap {
    renderer: TestRenderer,
    tiles: Arc<Tiles>,
    style: Arc<Style>,
    transform: Transform,
    /// The ground the renderer last told of, which the updates carry, as a
    /// map's do.
    elevation: Option<Arc<dyn Elevation>>,
    /// The terrain options the updates carry.
    terrain: TerrainOptions,
    /// Whether the updates report the camera as moving.
    camera_moving: bool,
    /// Whether the updates request a still image.
    still_image_request: bool,
    /// The held frame clock carried in updates, if any.
    time_point: Option<Instant>,
    work: TileWork,
    /// The pool of the renderer's background work, which runs between its
    /// frames.
    pool: crate::exec::pool::Pool,
    /// Set as a task arrives for the pool.
    queued: Arc<std::sync::atomic::AtomicBool>,
}

impl DrapedMap {
    fn new(tiles: Tiles) -> Self {
        let pool = crate::exec::pool::Pool::local();
        let queued = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let arrived = Arc::clone(&queued);
        pool.set_waker(Some(Arc::new(move || arrived.store(true, std::sync::atomic::Ordering::SeqCst))));
        let mut transform = Transform::new(ConstrainMode::HeightOnly);
        transform.resize(Size::new(SIDE, SIDE)).unwrap();
        transform.jump_to(&CameraOptions {
            center: Some(LatLng::new(-10.0, 10.0).unwrap()),
            zoom: Some(2.0),
            ..Default::default()
        });
        DrapedMap {
            renderer: TestRenderer::new(Size::new(SIDE, SIDE), &pool),
            tiles: Arc::new(tiles),
            style: Arc::new(style_of(STYLE)),
            transform,
            elevation: None,
            terrain: TerrainOptions::default(),
            camera_moving: false,
            still_image_request: false,
            time_point: None,
            work: TileWork::default(),
            pool,
            queued,
        }
    }

    /// Draws a frame, and returns whether everything it shows had loaded,
    /// whether it requested an immediate repaint, any scheduled repaint time,
    /// and the tiles and stacks of the drapes it drew.
    fn frame_info(&mut self) -> (bool, bool, Option<Instant>, BTreeSet<(OverscaledTileID, usize)>) {
        let file_source: Arc<dyn FileSource> = Arc::<Tiles>::clone(&self.tiles);
        let parameters = UpdateParameters {
            file_source: Some(file_source),
            terrain: self.terrain,
            elevation: self.elevation.clone(),
            camera_moving: self.camera_moving,
            still_image_request: self.still_image_request,
            time_point: self.time_point,
            ..update_parameters(Arc::clone(&self.style), self.transform.view().clone(), MapMode::Continuous)
        };
        let mut full = false;
        let mut repaint = false;
        let mut repaint_at = None;
        for event in self.renderer.frame(&Arc::new(parameters)) {
            match event {
                RendererEvent::RenderFrameFinished { mode, needs_repaint, repaint_at: at, error, .. } => {
                    assert!(error.is_none(), "the frame failed: {error:?}");
                    full = mode == RenderMode::Full;
                    repaint = needs_repaint;
                    repaint_at = at;
                }
                RendererEvent::TerrainElevation(elevation) => self.elevation = elevation,
                RendererEvent::TileAction { op, id, source_id } => self.work.record(op, (source_id, id)),
                _ => {}
            }
        }
        let renderer = &mut self.renderer.renderer;
        let drawn = renderer.terrain().drapes().drawn();
        assert_eq!(drawn.len(), renderer.rendering_stats().terrain.drapes_drawn);
        (full, repaint, repaint_at, drawn.into_iter().collect())
    }

    /// Draws a frame, and returns whether everything it shows had loaded,
    /// whether it requested another repaint, and the tiles and stacks of the
    /// drapes it drew.
    fn frame_status(&mut self) -> (bool, bool, BTreeSet<(OverscaledTileID, usize)>) {
        let (full, repaint, _, drawn) = self.frame_info();
        (full, repaint, drawn)
    }

    /// Draws a frame, and returns whether everything it shows had loaded and
    /// the tiles and stacks of the drapes it drew.
    fn frame(&mut self) -> (bool, BTreeSet<(OverscaledTileID, usize)>) {
        let (full, _, drawn) = self.frame_status();
        (full, drawn)
    }

    /// Draws frames, and runs the background work they start between them,
    /// until the renderer waits for nothing but the held tile, and then one
    /// more. Returns the tiles and stacks of the drapes they drew.
    fn settle(&mut self) -> BTreeSet<(OverscaledTileID, usize)> {
        let mut drawn = BTreeSet::new();
        loop {
            drawn.extend(self.frame().1);
            let worked = self.queued.swap(false, std::sync::atomic::Ordering::SeqCst);
            self.pool.run_all();
            if !worked && self.work.idle(self.tiles.waiting.lock().len()) {
                drawn.extend(self.frame().1);
                return drawn;
            }
        }
    }

    /// The tiles and stacks of the drapes that have a texture.
    fn textured(&mut self) -> BTreeSet<(OverscaledTileID, usize)> {
        self.renderer.renderer.terrain().drapes().textured().into_iter().collect()
    }

    /// The sides of the drapes, by tile, in the cover's order.
    fn sides(&mut self) -> Vec<(OverscaledTileID, u32)> {
        self.renderer.renderer.terrain().drapes().sizes()
    }

    fn edit(&mut self, edit: Edit) {
        let mut style = (*self.style).clone();
        style.apply(edit).unwrap();
        self.style = Arc::new(style);
    }

    /// Adds the first layer of `json`, a style's, with its sources, before
    /// the layer `before` or on top.
    fn add_layer(&mut self, json: &str, before: Option<&str>) {
        let parsed = Style::from_json(crate::tests::registry().style(), json).expect("the style");
        for source in parsed.sources().iter() {
            self.edit(Edit::AddSource(crate::tests::ready(source.clone())));
        }
        let layer = parsed.layer_list().iter().next().expect("the layer").clone();
        self.edit(Edit::AddLayer { layer, before: before.map(str::to_owned) });
    }
}

/// The map, settled, and the tiles and stacks of its drapes, one stack over
/// four tiles.
fn settled(tiles: Tiles) -> (DrapedMap, BTreeSet<(OverscaledTileID, usize)>) {
    let mut map = DrapedMap::new(tiles);
    map.settle();
    let drapes = map.textured();
    assert_eq!(4, drapes.len(), "drapes: {drapes:?}");
    (map, drapes)
}

/// The terrain tile at zoom 2 north-west of the view's center, which holds
/// the shapes.
fn north_west() -> OverscaledTileID {
    OverscaledTileID::new(2, 0, CanonicalTileID::new(2, 1, 1))
}

#[test]
fn a_map_at_rest_draws_no_drape_again() {
    let (mut map, drapes) = settled(Tiles::default());
    let (full, drawn) = map.frame();
    assert!(full);
    assert!(drawn.is_empty(), "drapes drawn again: {drawn:?}");
    assert_eq!(drapes, map.textured());
}

/// A change of the zoom changes what a drape shows, line widths and the
/// layers' values, so every drape draws again, once.
#[test]
fn a_zoom_change_draws_every_drape_again() {
    let (mut map, drapes) = settled(Tiles::default());
    map.transform.jump_to(&CameraOptions { zoom: Some(2.1), ..Default::default() });
    let (_, drawn) = map.frame();
    assert_eq!(drapes, map.textured(), "the same drapes cover the view");
    assert_eq!(drapes, drawn);
    assert!(map.frame().1.is_empty(), "the drapes are drawn again once only");
}

/// A pan that keeps the view over the same terrain tiles keeps their
/// drapes.
#[test]
fn a_pan_keeps_the_drapes() {
    let (mut map, drapes) = settled(Tiles::default());
    map.transform.jump_to(&CameraOptions { center: Some(LatLng::new(-9.0, 11.0).unwrap()), ..Default::default() });
    let drawn = map.settle();
    assert_eq!(drapes, map.textured(), "the same drapes cover the view");
    assert!(drawn.is_empty(), "drapes drawn again: {drawn:?}");
}

/// On the globe, a drape's lines take their width from the globe's pixel
/// scale, so a change of it at the same zoom, as through the projection's
/// transition, draws the drapes again, once.
#[test]
fn a_change_of_the_globes_scale_draws_every_drape_again() {
    let globe = |transition| ProjectionDefinition {
        from: ProjectionType::Mercator,
        to: ProjectionType::VerticalPerspective,
        transition,
    };
    let mut map = DrapedMap::new(Tiles::default());
    map.transform.set_projection(globe(1.0).into());
    map.settle();
    let drapes = map.textured();
    map.transform.set_projection(globe(0.5).into());
    let (_, drawn) = map.frame();
    assert_eq!(drapes, map.textured(), "the same drapes cover the view");
    assert_eq!(drapes, drawn);
    assert!(map.frame().1.is_empty(), "the drapes are drawn again once only");
}

/// A circle at one point, in the north-west drape's tile.
const CIRCLE: &str = r#"{
    "version": 8,
    "sources": {
        "point": {"type": "geojson", "data": {"type": "Point", "coordinates": [-75, 55]}}
    },
    "layers": [{"id": "circle", "type": "circle", "source": "point"}]
}"#;

/// A change of a layer in the second of two stacks draws only that stack's
/// drapes again.
#[test]
fn a_paint_change_in_a_stack_draws_only_its_drapes_again() {
    let (mut map, drapes) = settled(Tiles::default());
    map.add_layer(CIRCLE, Some("raster"));
    map.settle();
    let both: BTreeSet<_> = drapes.iter().flat_map(|&(tile, _)| [(tile, 0), (tile, 1)]).collect();
    assert_eq!(both, map.textured(), "two stacks that both draw in every tile");
    assert!(map.frame().1.is_empty());
    map.edit(Edit::SetLayerProperty {
        layer: "raster".to_owned(),
        name: "raster-opacity".to_owned(),
        value: serde_json::json!(0.7),
    });
    let second: BTreeSet<_> = drapes.iter().map(|&(tile, _)| (tile, 1)).collect();
    assert_eq!(second, map.frame().1);
    assert!(map.frame().1.is_empty(), "the drapes are drawn again once only");
}

/// New data for a source draws again the drapes whose tiles show something
/// else.
#[test]
fn new_data_draws_the_drapes_whose_tiles_changed_again() {
    let (mut map, _) = settled(Tiles::default());
    let geojson: geojson::GeoJson = r#"{
        "type": "Feature",
        "id": 1,
        "properties": {},
        "geometry": {"type": "Polygon", "coordinates": [[[-60, 50], [-50, 50], [-50, 60], [-60, 60], [-60, 50]]]}
    }"#
    .parse()
    .unwrap();
    let data = crate::tests::types::geojson::TestGeoJson::new(geojson, &GeoJSONOptions::default_options()).unwrap();
    map.edit(crate::tests::types::geojson::set_data("shapes", Some(data)));
    // The source indexes its new data in the background before its tiles
    // lay out again.
    let mut drawn = map.settle();
    drawn.extend(map.settle());
    assert_eq!(BTreeSet::from([(north_west(), 0)]), drawn, "only the north-west tile shows the polygon");
}

/// The drapes' keys don't tell what the style's images draw.
#[test]
fn a_new_image_draws_every_drape_again() {
    let (mut map, drapes) = settled(Tiles::default());
    let image = PremultipliedImage::from_vec(Size::new(2, 2), [255, 0, 0, 255].repeat(4));
    let image = mln_style::image::StyleImage::new(
        "red".to_owned(),
        image,
        1.0,
        false,
        Vec::new(),
        Vec::new(),
        None,
        None,
        None,
    )
    .expect("an image");
    map.edit(Edit::AddImage(Arc::new(image)));
    assert_eq!(drapes, map.frame().1);
    assert!(map.frame().1.is_empty());
}

#[test]
fn a_new_source_tile_draws_the_drapes_it_overlaps_again() {
    let held = CanonicalTileID::new(3, 3, 3);
    let (mut map, drapes) = settled(Tiles { held: Mutex::new(Some(held)), ..Tiles::default() });
    assert!(!map.tiles.waiting.lock().is_empty(), "the held tile was requested");
    map.tiles.release();
    let drawn = map.settle();
    let overlapping: BTreeSet<_> = drapes.into_iter().filter(|(drape, _)| held.is_child_of(&drape.canonical)).collect();
    assert_eq!(1, overlapping.len());
    assert_eq!(overlapping, drawn);
}

#[test]
fn a_feature_state_change_draws_its_drapes_again() {
    let (mut map, _) = settled(Tiles::default());
    let mut hover = FeatureState::new();
    hover.insert("hover".into(), mln_style::feature::Value::Bool(true));
    map.renderer.renderer.set_feature_state("shapes", None, "1", &hover);
    assert_eq!(BTreeSet::from([(north_west(), 0)]), map.frame().1);
    assert!(map.frame().1.is_empty());
}

/// A line translated in the viewport, which draws by the bearing, in the
/// north-west tile.
const VIEWPORT_SHIFTED_LINE: &str = r#"{
    "version": 8,
    "sources": {
        "shifted": {"type": "geojson", "data": {"type": "LineString", "coordinates": [[-80, 50], [-70, 60]]}}
    },
    "layers": [{
        "id": "shifted",
        "type": "line",
        "source": "shifted",
        "paint": {"line-width": 8, "line-translate": [20, 0], "line-translate-anchor": "viewport"}
    }]
}"#;

/// A hillshade of the DEM's tiles, lit from the viewport, as hillshades are
/// by default.
const VIEWPORT_LIT_HILLSHADE: &str = r#"{
    "version": 8,
    "sources": {
        "hills": {"type": "raster-dem", "tiles": ["dem/{z}/{x}/{y}.png"], "tileSize": 256, "maxzoom": 10}
    },
    "layers": [{"id": "hillshade", "type": "hillshade", "source": "hills"}]
}"#;

/// A fill that multiplies what is under it, in the north-west tile.
const MULTIPLIED_FILL: &str = r#"{
    "version": 8,
    "sources": {
        "multiplied": {
            "type": "geojson",
            "data": {"type": "Polygon", "coordinates": [[[-80, 50], [-70, 50], [-70, 60], [-80, 50]]]}
        }
    },
    "layers": [{"id": "multiplied", "type": "fill", "source": "multiplied", "paint": {"fill-layer-blend": "multiply"}}]
}"#;

/// A turn of the map draws again the drapes of a stack with a layer that
/// draws by the bearing, and only them, whatever the bearing: none for the
/// layers that draw the same at every bearing; the stack over a circle
/// with a line translated in the viewport, while the stack under it keeps
/// its drapes; none for a hillshade lit from the viewport, which has a
/// stack to itself whose drapes hold its slopes for the surface to shade
/// with the frame's bearing; and every drape of the one stack of a layer
/// that blends over such a hillshade, over its colors.
#[test]
fn a_rotation_draws_again_only_the_stacks_that_draw_by_the_bearing() {
    type Drapes = BTreeSet<(OverscaledTileID, usize)>;
    type Layers = [(&'static str, Option<&'static str>)];
    type Expected<'a> = dyn Fn(&Drapes) -> (Drapes, Drapes) + 'a;
    let in_stack = |drapes: &Drapes, stack| drapes.iter().map(|&(tile, _)| (tile, stack)).collect::<Drapes>();
    let cases: [(&Layers, &Expected<'_>); 4] = [
        (&[], &|drapes| (drapes.clone(), Drapes::new())),
        (&[(CIRCLE, None), (VIEWPORT_SHIFTED_LINE, None)], &|drapes| {
            let shifted = Drapes::from([(north_west(), 1)]);
            (&shifted | drapes, shifted)
        }),
        (&[(VIEWPORT_LIT_HILLSHADE, Some("fill"))], &|drapes| {
            let stacks = &(&in_stack(drapes, 0) | &in_stack(drapes, 1)) | &Drapes::from([(north_west(), 2)]);
            (stacks, Drapes::new())
        }),
        (&[(VIEWPORT_LIT_HILLSHADE, Some("fill")), (MULTIPLIED_FILL, None)], &|drapes| {
            (drapes.clone(), drapes.clone())
        }),
    ];
    for (layers, expected) in cases {
        let (mut map, drapes) = settled(Tiles::default());
        for &(layer, before) in layers {
            map.add_layer(layer, before);
        }
        map.settle();
        let (textured, turned) = expected(&drapes);
        assert_eq!(textured, map.textured(), "{layers:?}");
        for bearing in [1.0, 2.0] {
            map.transform.jump_to(&CameraOptions { bearing: Some(bearing), ..Default::default() });
            assert_eq!(turned, map.frame().1, "the drapes drawn at bearing {bearing}: {layers:?}");
        }
        assert!(map.frame().1.is_empty(), "a drape drawn again at the same bearing: {layers:?}");
    }
}

/// The center at `longitude`, at 10° S.
fn center(longitude: f64) -> CameraOptions {
    CameraOptions { center: Some(LatLng::new(-10.0, longitude).unwrap()), ..Default::default() }
}

/// Once the map's center crosses the antimeridian, the terrain tiles over
/// the same ground are in another world copy, and the map has the drapes
/// that a map that started there has.
#[test]
fn a_pan_across_the_antimeridian_drapes_as_a_new_map_does() {
    let mut map = DrapedMap::new(Tiles::default());
    map.transform.jump_to(&center(179.0));
    map.settle();
    let before = map.textured();
    map.transform.jump_to(&center(-179.0));
    map.settle();
    // The tiles over the ground in view before, a world copy west.
    let shifted = before.iter().map(|&(tile, stack)| (OverscaledTileID { wrap: tile.wrap - 1, ..tile }, stack));
    assert!(
        shifted.clone().any(|drape| map.textured().contains(&drape)),
        "the view crossed into another world copy: {before:?}, then {:?}",
        map.textured()
    );

    let mut fresh = DrapedMap::new(Tiles::default());
    fresh.transform.jump_to(&center(-179.0));
    fresh.settle();
    assert_eq!(fresh.textured(), map.textured(), "the drapes of a map that started there");
    assert_eq!(fresh.sides(), map.sides());
}

/// The rendering stats count the drapes, their bytes and what each frame
/// drew of them.
#[test]
fn the_rendering_stats_count_the_drapes() {
    let (mut map, drapes) = settled(Tiles::default());
    map.edit(Edit::SetLayerProperty {
        layer: "line".to_owned(),
        name: "line-color".to_owned(),
        value: serde_json::json!("green"),
    });
    map.frame();
    let terrain = map.renderer.renderer.rendering_stats().terrain;
    // The DEM's tiles of 256 pixels make terrain tiles of 512, and drapes
    // of 1024 texels a side, with their mips, which draw with a depth and
    // stencil of that side, and no layer composite.
    assert_eq!(drapes.len(), terrain.drapes);
    assert_eq!(drapes.len() as u64 * DRAPE_BYTES + DEPTH_STENCIL_BYTES, terrain.mem_drapes as u64);
    assert_eq!(drapes.len(), terrain.drapes_drawn, "the line's stack");

    map.frame();
    let at_rest = map.renderer.renderer.rendering_stats().terrain;
    assert_eq!(0, at_rest.drapes_drawn);
    assert_eq!(terrain.mem_drapes, at_rest.mem_drapes);
}

/// A drape of 1024 texels a side, with its mips, and a depth and stencil of
/// that side.
const DRAPE_BYTES: u64 = 4 * 1024 * 1024 * 4 / 3;
const DEPTH_STENCIL_BYTES: u64 = 4 * 1024 * 1024;

/// A memory limit under what the drapes would hold halves the drapes of the
/// tiles farthest from the view's center, last in the cover, which draw
/// again once, smaller; every tile keeps its drape. Raised again, it lets
/// them draw again at their whole side.
#[test]
fn a_memory_limit_halves_the_drapes_of_the_farthest_tiles_first() {
    let (mut map, drapes) = settled(Tiles::default());
    let whole: Vec<_> = map.sides().into_iter().map(|(tile, _)| (tile, 1024)).collect();
    assert_eq!(whole, map.sides());

    map.terrain.drape_memory_limit = Some(4 * DRAPE_BYTES + DEPTH_STENCIL_BYTES - 1);
    let (_, drawn) = map.frame();
    let sides = map.sides();
    let (last, _) = *sides.last().unwrap();
    assert_eq!([&whole[..3], &[(last, 512)]].concat(), sides, "the farthest tile's drape halved");
    assert_eq!(BTreeSet::from([(last, 0)]), drawn, "the halved drape draws again");
    let terrain = map.renderer.renderer.rendering_stats().terrain;
    assert_eq!(drapes.len(), terrain.drapes, "every tile keeps its drape");
    assert!((terrain.mem_drapes as u64) < 4 * DRAPE_BYTES + DEPTH_STENCIL_BYTES, "{terrain:?}");
    assert!(map.frame().1.is_empty(), "the drapes are drawn again once only");

    map.terrain.drape_memory_limit = None;
    assert_eq!(BTreeSet::from([(last, 0)]), map.frame().1);
    assert_eq!(whole, map.sides());
}

/// A zoom change draws again only the stacks whose layers depend on zoom:
/// a stack with plain background and constant raster, a viewport-lit hillshade
/// stack, and a fill colored only by feature-state keep their drapes across
/// zoom changes; a line stack (or a stack with a zoom-interpolated paint
/// property) draws again.
#[test]
fn a_zoom_change_draws_again_only_the_stacks_that_draw_by_zoom() {
    let (mut map, drapes) = settled(Tiles::default());
    map.add_layer(VIEWPORT_LIT_HILLSHADE, Some("fill"));
    map.add_layer(CIRCLE, Some("line"));
    map.settle();
    let in_stack = |stack| drapes.iter().map(|&(tile, _)| (tile, stack)).collect::<BTreeSet<_>>();
    // Stack 0: background + raster (constant opacity).
    // Stack 1: viewport-lit hillshade.
    // Stack 2: fill (feature-state expression, zoom-constant; only in north-west).
    // Stack 3: line (only in north-west).
    let expected_textured = &(&in_stack(0) | &in_stack(1)) | &BTreeSet::from([(north_west(), 2), (north_west(), 3)]);
    assert_eq!(expected_textured, map.textured());
    assert!(map.frame().1.is_empty());

    map.transform.jump_to(&CameraOptions { zoom: Some(2.1), ..Default::default() });
    assert_eq!(BTreeSet::from([(north_west(), 3)]), map.frame().1, "only the line stack redraws");
    assert!(map.frame().1.is_empty());

    // An unrelated global-state edit keeps every drape.
    map.edit(Edit::SetGlobalState { name: "unused".to_owned(), value: mln_style::feature::Value::Bool(true) });
    assert!(map.frame().1.is_empty(), "unrelated global state keeps drapes");

    // A zoom-dependent paint expression on raster makes stack 0 redraw on zoom,
    // while the hillshade and feature-state fill stacks still keep their drapes.
    map.edit(Edit::SetLayerProperty {
        layer: "raster".to_owned(),
        name: "raster-opacity".to_owned(),
        value: serde_json::json!(["interpolate", ["linear"], ["zoom"], 0, 0.2, 10, 0.8]),
    });
    assert_eq!(in_stack(0), map.frame().1);
    map.transform.jump_to(&CameraOptions { zoom: Some(2.2), ..Default::default() });
    let expected = &in_stack(0) | &BTreeSet::from([(north_west(), 3)]);
    assert_eq!(
        expected,
        map.frame().1,
        "zoom-interpolated raster and line stacks redraw, hillshade and fill keep drapes"
    );
    assert!(map.frame().1.is_empty());
}

/// Continuous zooming defers zoom-only drape redraws while zoom stays within
/// the step threshold, requests a repaint, redraws once zoom drifts past the
/// threshold, and refines to the exact zoom once zooming stops. Style edits
/// and still-image requests during active zoom redraw immediately.
#[test]
fn continuous_zoom_defers_drape_redraws_until_step_or_settle() {
    let (mut map, drapes) = settled(Tiles::default());

    // First zoom step from rest (camera_moving == false) redraws immediately.
    map.transform.jump_to(&CameraOptions { zoom: Some(2.05), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn);
    assert!(!repaint);

    // Consecutive zoom frames within 0.5 zoom of 2.05 defer and request repaint.
    for zoom in [2.15, 2.35] {
        map.transform.jump_to(&CameraOptions { zoom: Some(zoom), ..Default::default() });
        let (_, repaint, drawn) = map.frame_status();
        assert!(drawn.is_empty(), "deferred at zoom {zoom}");
        assert!(repaint, "repaint requested while deferred at zoom {zoom}");
    }

    // Crossing the 0.5 zoom step staggers redraws at 2 drapes/frame (nearest first).
    map.transform.jump_to(&CameraOptions { zoom: Some(2.60), ..Default::default() });
    let (_, repaint, first_batch) = map.frame_status();
    assert_eq!(2, first_batch.len(), "staggered to 2 drapes on step frame: {first_batch:?}");
    assert!(repaint, "immediate repaint requested for remaining 2 drapes");

    // Next frame at zoom 2.60 drains the remaining 2 drapes.
    let (_, repaint, second_batch) = map.frame_status();
    assert_eq!(2, second_batch.len());
    assert_eq!(drapes, &first_batch | &second_batch, "all 4 drapes updated across 2 frames");
    assert!(!repaint);

    // Consecutive zoom steps defer, then refine progressively (2/frame) when zoom settles.
    map.transform.jump_to(&CameraOptions { zoom: Some(2.65), ..Default::default() });
    assert_eq!(drapes, map.frame_status().2, "first jump after rest redraws immediately");
    map.transform.jump_to(&CameraOptions { zoom: Some(2.70), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert!(drawn.is_empty());
    assert!(repaint);

    // Zoom stops changing: follow-up frames refine 2 drapes/frame to exact zoom 2.70.
    let (_, repaint, r1) = map.frame_status();
    assert_eq!(2, r1.len(), "first refine batch draws 2 drapes");
    assert!(repaint);
    let (_, repaint, r2) = map.frame_status();
    assert_eq!(2, r2.len(), "second refine batch draws remaining 2 drapes");
    assert_eq!(drapes, &r1 | &r2);
    assert!(!repaint);
    let (_, repaint, drawn) = map.frame_status();
    assert!(drawn.is_empty());
    assert!(!repaint);

    // Style edits and still-image requests during active zoom redraw immediately.
    map.camera_moving = true;
    map.transform.jump_to(&CameraOptions { zoom: Some(2.65), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert!(drawn.is_empty(), "camera_moving defers from the first zoom frame");
    assert!(repaint);

    map.transform.jump_to(&CameraOptions { zoom: Some(2.60), ..Default::default() });
    map.edit(Edit::SetLayerProperty {
        layer: "line".to_owned(),
        name: "line-color".to_owned(),
        value: serde_json::json!("green"),
    });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn, "style edit redraws immediately even while zooming");
    assert!(!repaint);

    map.transform.jump_to(&CameraOptions { zoom: Some(2.55), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert!(drawn.is_empty());
    assert!(repaint);

    map.still_image_request = true;
    map.transform.jump_to(&CameraOptions { zoom: Some(2.50), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn, "still image request redraws immediately even while zooming");
    assert!(!repaint);
    map.still_image_request = false;

    // A held gesture whose zoom stops changing refines (2/frame) instead of looping.
    map.transform.jump_to(&CameraOptions { zoom: Some(2.45), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert!(drawn.is_empty());
    assert!(repaint);

    let (_, repaint, g1) = map.frame_status();
    assert_eq!(2, g1.len());
    assert!(repaint);
    let (_, repaint, g2) = map.frame_status();
    assert_eq!(drapes, &g1 | &g2, "held gesture refines once zoom pauses");
    assert!(!repaint);
}

/// A zoom step on `hillshade-illumination-anchor` that switches a standalone
/// hillshade between viewport lighting (slopes) and map lighting (shaded
/// colors) redraws immediately even while actively zooming.
#[test]
fn a_hillshade_lighting_mode_switch_redraws_while_zooming() {
    let (mut map, drapes) = settled(Tiles::default());
    // Isolate hillshade in its own stack (stack 1) regardless of whether it is
    // viewport-lit or map-lit, by bracketing it with non-draped circle layers.
    map.add_layer(CIRCLE, Some("fill"));
    map.add_layer(VIEWPORT_LIT_HILLSHADE, Some("fill"));
    map.add_layer(
        r#"{
            "version": 8,
            "sources": {},
            "layers": [{"id": "circle2", "type": "circle", "source": "point"}]
        }"#,
        Some("fill"),
    );
    map.edit(Edit::SetLayerProperty {
        layer: "hillshade".to_owned(),
        name: "hillshade-illumination-anchor".to_owned(),
        value: serde_json::json!(["step", ["zoom"], "viewport", 2.15, "map"]),
    });
    map.settle();
    let hillshade: BTreeSet<_> = drapes.iter().map(|&(tile, _)| (tile, 1)).collect();
    assert!(map.frame().1.is_empty());

    // Crossing the step while actively zooming (within ZOOM_DRAPE_STEP)
    // switches stack 1 from lit (slopes) to unlit (colors) and must redraw.
    map.camera_moving = true;
    map.transform.jump_to(&CameraOptions { zoom: Some(2.20), ..Default::default() });
    let (_, _, drawn) = map.frame_status();
    assert_eq!(hillshade, drawn, "standalone hillshade stack must redraw when lighting mode flips");
}

/// A paint transition that finishes on the same frame as a zoom move redraws
/// immediately so the drape does not stay stuck on a mid-transition sample.
#[test]
fn a_finishing_paint_transition_redraws_even_while_zooming() {
    let (mut map, drapes) = settled(Tiles::default());
    let start = crate::tests::start_time();
    map.time_point = Some(start);
    map.edit(Edit::SetTransition(mln_style::TransitionOptions {
        duration: Some(Duration::from_millis(100)),
        ..Default::default()
    }));
    map.frame();

    // Start a 100ms paint transition on line-opacity at `start`.
    map.edit(Edit::SetLayerProperty {
        layer: "line".to_owned(),
        name: "line-opacity".to_owned(),
        value: serde_json::json!(0.2),
    });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn);
    assert!(repaint);

    // Mid-transition while zooming: redraws (transition active).
    map.camera_moving = true;
    map.time_point = Some(start + Duration::from_millis(50));
    map.transform.jump_to(&CameraOptions { zoom: Some(2.05), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn, "active transition redraws while zooming");
    assert!(repaint);

    // On the completion frame, `has_transition()` becomes false; moving zoom
    // on that frame must still draw the final transitioned value.
    map.time_point = Some(start + Duration::from_millis(100));
    map.transform.jump_to(&CameraOptions { zoom: Some(2.10), ..Default::default() });
    let (_, repaint, drawn) = map.frame_status();
    assert_eq!(drapes, drawn, "transition completion frame redraws even while zooming");
    assert!(!repaint);

    // Once the completed frame is drawn, subsequent zoom frames defer again
    // and schedule a settle repaint via `repaint_at`.
    let deferred_at = start + Duration::from_millis(150);
    map.time_point = Some(deferred_at);
    map.transform.jump_to(&CameraOptions { zoom: Some(2.15), ..Default::default() });
    let (_, repaint, repaint_at, drawn) = map.frame_info();
    assert!(drawn.is_empty(), "post-transition zoom frame defers");
    assert!(!repaint, "zoom-only deferral waits for settle timer rather than immediate repaint");
    assert_eq!(repaint_at, Some(deferred_at + Duration::from_millis(100)));
}

/// With a frame clock, zoom-only deferral schedules a settle repaint via
/// `repaint_at` so brief gaps between camera updates do not flush deferred
/// drapes mid-motion, while ending motion or reaching the settle deadline
/// refines drapes progressively (2/frame) and goes idle.
#[test]
fn zoom_deferral_debounces_settle_with_repaint_at() {
    let (mut map, drapes) = settled(Tiles::default());
    let start = crate::tests::start_time();
    map.time_point = Some(start);
    map.frame();

    // Zoom moves while camera_moving: defers and schedules settle at +100ms.
    map.camera_moving = true;
    map.time_point = Some(start + Duration::from_millis(16));
    map.transform.jump_to(&CameraOptions { zoom: Some(2.05), ..Default::default() });
    let (_, repaint, repaint_at, drawn) = map.frame_info();
    assert!(drawn.is_empty());
    assert!(!repaint);
    assert_eq!(repaint_at, Some(start + Duration::from_millis(116)));

    // An inter-event frame 16ms later with unchanged zoom stays deferred.
    map.time_point = Some(start + Duration::from_millis(32));
    let (_, repaint, repaint_at, drawn) = map.frame_info();
    assert!(drawn.is_empty(), "inter-event frame must not prematurely flush deferred drapes");
    assert!(!repaint);
    assert_eq!(repaint_at, Some(start + Duration::from_millis(116)));

    // Once the 100ms settle deadline passes (even with camera_moving still true),
    // drapes refine progressively (2/frame) with immediate repaint until exact.
    map.time_point = Some(start + Duration::from_millis(116));
    let (_, repaint, repaint_at, r1) = map.frame_info();
    assert_eq!(2, r1.len());
    assert!(repaint);
    assert!(repaint_at.is_none());

    map.time_point = Some(start + Duration::from_millis(132));
    let (_, repaint, repaint_at, r2) = map.frame_info();
    assert_eq!(drapes, &r1 | &r2);
    assert!(!repaint);
    assert!(repaint_at.is_none());

    // Ending camera_moving on the same frame that zoom reaches its final value
    // starts refining immediately without waiting for the 100ms settle timer.
    map.camera_moving = true;
    map.time_point = Some(start + Duration::from_millis(200));
    map.transform.jump_to(&CameraOptions { zoom: Some(2.10), ..Default::default() });
    assert!(map.frame_info().3.is_empty());

    map.camera_moving = false;
    map.time_point = Some(start + Duration::from_millis(216));
    map.transform.jump_to(&CameraOptions { zoom: Some(2.12), ..Default::default() });
    let (_, repaint, repaint_at, e1) = map.frame_info();
    assert_eq!(2, e1.len(), "ending camera motion on final zoom frame begins refine immediately");
    assert!(repaint);
    assert!(repaint_at.is_none());
    map.time_point = Some(start + Duration::from_millis(232));
    let (_, repaint, repaint_at, e2) = map.frame_info();
    assert_eq!(drapes, &e1 | &e2);
    assert!(!repaint);
    assert!(repaint_at.is_none());
}

/// When zooming across a terrain tile boundary, brand-new child tiles render
/// progressively (2/frame) while the remaining children sample their retired
/// parent's drape texture at the child's UV sub-rect; once all children finish
/// rendering, the retired parent is dropped.
#[test]
fn new_child_drapes_sample_retired_ancestor_while_rendering_progressively() {
    let mut map = DrapedMap::new(Tiles::default());
    // Center on (0, 0), the seam of 4 tiles at every zoom level z >= 1.
    map.transform.jump_to(&CameraOptions {
        center: Some(LatLng::new(0.0, 0.0).unwrap()),
        zoom: Some(2.0),
        ..Default::default()
    });
    map.settle();
    assert_eq!(4, map.textured().len());

    // Zoom into z=3.5 so 4 brand-new z=3 child tiles replace the 4 settled z=2 tiles.
    map.transform.jump_to(&CameraOptions { zoom: Some(3.5), ..Default::default() });
    let (_, repaint, drawn1) = map.frame_status();
    let drapes = map.renderer.renderer.terrain().drapes();
    let stand_ins = drapes.stand_ins();
    assert_eq!(2, drawn1.len(), "caps brand-new child drapes to 2 on the split frame: {drawn1:?}");
    assert_eq!(2, stand_ins.len(), "remaining 2 child drapes sample their retired z=2 parents: {stand_ins:?}");
    assert_eq!(2, drapes.retired_count(), "only the 2 referenced retired parents are held");
    assert!(repaint, "immediate repaint requested to finish remaining child drapes");
    for (tile, _, coords) in &stand_ins {
        assert_eq!(tile.canonical.z, 3);
        assert_eq!(coords[0], 0.5, "z=3 child samples a 0.5x0.5 sub-rect of its z=2 parent");
        assert!(coords[1] == 0.0 || coords[1] == 0.5, "offset_x={}", coords[1]);
        assert!(coords[2] == 0.0 || coords[2] == 0.5, "offset_y={}", coords[2]);
    }

    // Next frame renders the remaining 2 child drapes and drops all retired parents.
    let (_, repaint, drawn2) = map.frame_status();
    assert_eq!(2, drawn2.len());
    assert!(!repaint);
    let drapes = map.renderer.renderer.terrain().drapes();
    assert!(drapes.stand_ins().is_empty(), "no stand-ins remain after draining");
    assert_eq!(0, drapes.retired_count(), "retired parents are dropped once all children render");

    // Under a memory cap sized for 4 drapes, 2 new children + 2 retired parents
    // coexist within the cap on frame 1 (keeping the 2-drape budget), and frame 2
    // finishes the remaining 2 children without exceeding the cap.
    let limit = 4 * DRAPE_BYTES + DEPTH_STENCIL_BYTES;
    map.terrain.drape_memory_limit = Some(limit);
    map.transform.jump_to(&CameraOptions { zoom: Some(4.5), ..Default::default() });
    let (_, repaint, capped1) = map.frame_status();
    let terrain1 = map.renderer.renderer.rendering_stats().terrain;
    assert_eq!(2, capped1.len(), "keeps 2-drape budget when coexisting children + parents fit cap");
    assert!(repaint);
    assert!((terrain1.mem_drapes as u64) <= limit, "frame 1 within cap: {terrain1:?}");
    assert_eq!(2, map.renderer.renderer.terrain().drapes().retired_count());

    let (_, repaint, capped2) = map.frame_status();
    let terrain2 = map.renderer.renderer.rendering_stats().terrain;
    assert_eq!(2, capped2.len(), "finishes remaining 2 children on frame 2");
    assert!(!repaint);
    assert!((terrain2.mem_drapes as u64) <= limit, "frame 2 within cap: {terrain2:?}");
    assert_eq!(0, map.renderer.renderer.terrain().drapes().retired_count());
}