mln-rs-engine 0.0.19

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
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
// A render layer is the renderer's side of a style layer: its type's layer
// (`Layer`), whose hooks see the frame's tiles and what they hold for
// the type (`TileInput`), and what the engine keeps of it around them
// (`Hosted`): its base, its values of its type, its value of each tile it
// draws and its draws. `RenderLayer` is what the engine does with a render
// layer of any type. The orchestrator owns the render layers, in the
// style's order.

use std::ops::Range;
use std::sync::Arc;

use mln_gfx::gpu::Gpu;
use mln_gfx::projection_variant::ProjectionVariant;
use mln_style::color::Color;
use mln_style::expression::Dependency;
use mln_style::layer::{ErasedLayerStyle, LayerStyle, PaintSet, SourceKind, StyleLayerType};
use mln_style::types::{LayerBlendType, VisibilityType};
use mln_style::{PropertyEvaluationParameters, TransitionParameters};
use smallvec::SmallVec;

use crate::camera::View;
use crate::draw::context::Context;
use crate::draw::draws::{DrawOrder, Draws, Group, LayerFrame, LendAt, Lent};
use crate::draw::resources::Resources;
use crate::draw::store::SharedTexture;
use crate::geo::ScreenCoordinate;
use crate::layer::bucket::ErasedBucket;
use crate::layer::layer_drawing::{ChangedBuckets, TileMap};
use crate::layer::layer_type::{ErasedEvaluatedLayer, EvaluatedLayer, entry};
use crate::layer::tile_input::input::Find;
use crate::layer::tile_input::{TileData, TileInput};
use crate::query::feature_index::QueryRegion;
use crate::render::paint_parameters::PaintParameters;
use crate::render::pass::RenderPass;
use crate::render::shared_targets::SharedTargets;
use crate::render::terrain::{SurfaceLight, TerrainElevation, TileGround};
use crate::render::tile::{FoundTile, FrameTile, RenderTile, TILE_BOUNDS, TileContent, TileStamp, overlaps};
use crate::render::update_parameters::UpdateParameters;
use crate::source::render_source::{RenderSource, TileOrder};
use crate::tile::feature::Feature;
use crate::tile::{OverscaledTileID, UnwrappedTileID};

/// A layer's bucket in a layout, which the layers of its layout group
/// share, with the layer's values it was laid out with, whichever the
/// layer's type.
#[derive(Clone, Copy)]
pub(crate) struct ErasedLayerBucket<'a> {
    pub(crate) bucket: &'a dyn ErasedBucket,
    /// The index of the bucket among the layout's buckets.
    pub(crate) bucket_index: usize,
    /// The values of the layer that the bucket was laid out with.
    pub(crate) layer: &'a dyn ErasedEvaluatedLayer,
}

/// A source's render tiles in a frame, with what each of them shows, and
/// the tiles that the frame's updates of the layers found
/// ([`LayerUpdateParameters::found`]), as the engine sees them.
#[derive(Clone, Copy)]
pub struct FrameSourceTiles<'a> {
    tiles: &'a [RenderTile],
    /// What each of `tiles` shows, at its index.
    contents: &'a [Option<TileContent<'a>>],
    found: &'a [FoundTile],
}

/// The tiles of a layer of the type `L` in a frame, each with what it shows
/// the layer, which keeps up to 64 of them on the stack.
pub(crate) type FrameTiles<'a, L> = SmallVec<[FrameTile<'a, L>; 64]>;

impl<'a> FrameSourceTiles<'a> {
    /// The render tiles `tiles`, which show `contents`, at their indexes,
    /// and the tiles of them that the frame's layers found.
    #[must_use]
    pub(crate) fn new(
        tiles: &'a [RenderTile],
        contents: &'a [Option<TileContent<'a>>],
        found: &'a [FoundTile],
    ) -> Self {
        FrameSourceTiles { tiles, contents, found }
    }

    /// What the tile at `index` shows.
    fn content(self, index: usize) -> Option<TileContent<'a>> {
        self.contents.get(index).copied().flatten()
    }

    /// The tiles at the indexes of `order`, in that order, as the layer
    /// `layer_id` of the type `T` sees them, each with what it shows the
    /// layer, found by the layer's id. `found` keeps where.
    fn find<L: Layer>(self, order: &[usize], layer_id: &str, found: &mut Vec<FoundTile>) -> FrameTiles<'a, L> {
        let mut tiles = FrameTiles::new();
        for &index in order {
            let Some(tile) = self.tiles.get(index) else { continue };
            let (frame_tile, view) = FrameTile::find(tile, self.content(index), layer_id);
            tiles.push(frame_tile);
            found.push(FoundTile { tile: index, view });
        }
        tiles
    }

    /// The found tiles at `found`, a range of them.
    pub(crate) fn found(self, found: Range<usize>) -> &'a [FoundTile] {
        self.found.get(found).unwrap_or_default()
    }

    /// The tiles of `found`, as [`find`](Self::find) found them for the
    /// layer `layer_id` of the type `T` in the same frame.
    pub(crate) fn at<'f, L: Layer>(
        self,
        found: impl IntoIterator<Item = &'f FoundTile>,
        layer_id: &str,
    ) -> FrameTiles<'a, L> {
        found
            .into_iter()
            .filter_map(|&FoundTile { tile, view }| {
                let render_tile = self.tiles.get(tile);
                debug_assert!(render_tile.is_some(), "a tile found past the frame's render tiles");
                Some(FrameTile::at(render_tile?, self.content(tile), layer_id, view))
            })
            .collect()
    }

    /// The tiles of the found tiles at `found`, as [`at`](Self::at) gives
    /// them, that overlap `tile` (what they show covers part of it), each in
    /// the world copy that does: on Mercator their own, so those of `tile`'s
    /// copy; on the `globe`, which has no copies, whatever their copy, one by
    /// `tile`'s. A drape of `tile` draws each in that copy
    /// ([`FrameTile::draw_id`]).
    pub(crate) fn overlapping<L: Layer>(
        self,
        found: Range<usize>,
        layer_id: &str,
        tile: UnwrappedTileID,
        globe: bool,
    ) -> FrameTiles<'a, L> {
        let found = self.found(found);
        self.overlaps(found, tile, globe)
            .map(|(&FoundTile { tile: index, view }, render_tile, wrap)| {
                FrameTile::at(render_tile, self.content(index), layer_id, view).in_copy(wrap)
            })
            .collect()
    }

    /// What a layer draws of the tiles that
    /// [`overlapping`](Self::overlapping) gives, in its order, under the ids
    /// it draws them in.
    pub(crate) fn stamps(
        self,
        found: Range<usize>,
        tile: UnwrappedTileID,
        globe: bool,
    ) -> impl Iterator<Item = TileStamp> {
        let found = self.found(found);
        self.overlaps(found, tile, globe).map(move |(&FoundTile { tile: index, view }, render_tile, wrap)| {
            let stamp = self.content(index).zip(view).and_then(|(content, place)| content.stamp(place));
            TileStamp {
                tile: OverscaledTileID { wrap, ..*render_tile.overscaled_tile_id() },
                bucket: stamp.map(|(bucket, _)| bucket),
                generations: stamp.map_or([0, 0], |(_, generations)| generations),
            }
        })
    }

    /// The tiles of `found` that overlap `tile`, with their render tiles and
    /// the world copies they overlap it in: on Mercator their own; on the
    /// `globe`, any of `tile`'s and the copies either side, which an image
    /// source's image that crosses the antimeridian reaches into.
    fn overlaps<'f>(
        self,
        found: &'f [FoundTile],
        tile: UnwrappedTileID,
        globe: bool,
    ) -> impl Iterator<Item = (&'f FoundTile, &'a RenderTile, i16)> {
        let found = found.iter().filter_map(move |found| Some((found, self.tiles.get(found.tile)?)));
        found.flat_map(move |(found, render_tile)| {
            let bounds = self.content(found.tile).map_or(TILE_BOUNDS, TileContent::bounds);
            let canonical = render_tile.id.canonical;
            let wraps = if globe { tile.wrap - 1..=tile.wrap + 1 } else { render_tile.id.wrap..=render_tile.id.wrap };
            wraps
                .filter(move |&wrap| overlaps(&UnwrappedTileID::with_wrap(wrap, canonical), bounds, &tile))
                .map(move |wrap| (found, render_tile, wrap))
        })
    }
}

/// What a layer reads in the frame's update, besides its tiles.
pub struct LayerUpdateParameters<'a> {
    /// The frame's camera.
    pub view: &'a View,
    /// The update the frame draws.
    pub update_parameters: &'a UpdateParameters,
    /// The layer's source, `None` for a layer without one or a source type
    /// the renderer has no render source for.
    pub(crate) source: Option<&'a dyn RenderSource>,
    /// What each of the source's render tiles shows, at its index.
    pub(crate) contents: &'a [Option<TileContent<'a>>],
    /// The images of the style.
    pub images: &'a crate::image::image_store::ImageStore,
    /// The tiles of the frame's layers, as their updates find them, which
    /// the update adds the layer's to: those the encode draws.
    pub(crate) found: &'a mut Vec<FoundTile>,
}

impl<'a> LayerUpdateParameters<'a> {
    /// The source's tiles, and their indexes in `order`; `None` for a layer
    /// without a source or a source without tiles.
    #[must_use]
    fn tiles(&self, order: TileOrder) -> Option<(FrameSourceTiles<'a>, &'a [usize])> {
        let source = self.source?;
        Some((FrameSourceTiles::new(source.render_tiles(), self.contents, &[]), source.tile_order(order)?))
    }
}

/// What every render layer has, whatever its type.
pub struct RenderLayerBase {
    pub(crate) evaluated_properties: Arc<dyn ErasedEvaluatedLayer>,
    pub style: Arc<dyn ErasedLayerStyle>,

    pub(crate) passes: RenderPass,
    /// What the layer's last evaluation said of how it draws.
    pub(crate) evaluation: Evaluation,
    pub(crate) style_dependencies: Dependency,
    /// Whether the frame draws the layer.
    pub(crate) is_renderable: bool,

    /// The projection variant this layer's draws are built with.
    pub projection_variant: ProjectionVariant,

    /// The shared target that the frame's draws of the layer draw into
    /// instead of the map, if any.
    pub(crate) route: Option<usize>,

    /// Where the tiles the layer's update found are among the frame's
    /// ([`LayerUpdateParameters::found`]).
    found: Range<usize>,
}

impl RenderLayerBase {
    /// The passes the layer draws in, as its last evaluation said.
    #[must_use]
    pub fn passes(&self) -> RenderPass {
        self.passes
    }

    /// Where the tiles the layer's update found are among the frame's
    /// ([`LayerUpdateParameters::found`]).
    pub(crate) fn found(&self) -> Range<usize> {
        self.found.clone()
    }

    pub(crate) fn new(properties: Arc<dyn ErasedEvaluatedLayer>) -> Self {
        let style = properties.shared_style();
        RenderLayerBase {
            evaluated_properties: properties,
            style,
            passes: RenderPass::None,
            evaluation: Evaluation::NONE,
            style_dependencies: Dependency::NONE,
            is_renderable: false,
            projection_variant: ProjectionVariant::Mercator,
            route: None,
            found: 0..0,
        }
    }
}

/// A layer's values of its style half `T`: its style, its paint values in
/// transition, and their evaluation for the last frame.
pub struct LayerValues<T: StyleLayerType> {
    pub style: Arc<LayerStyle<T>>,
    pub unevaluated: <T::PaintProperties as PaintSet>::Unevaluated,
    pub evaluated: Arc<EvaluatedLayer<T>>,
}

impl<T: StyleLayerType> LayerValues<T> {
    /// The values of the layer `style` of `layer_type`, before any
    /// transition, and the base of a render layer that holds them.
    pub(crate) fn new(
        style: Arc<LayerStyle<T>>,
        layer_type: &'static dyn crate::layer::layer_type::ErasedLayerType,
    ) -> (RenderLayerBase, Self) {
        let unevaluated = style.paint.untransitioned();
        let evaluated = Arc::new(EvaluatedLayer::new(Arc::clone(&style), layer_type));
        let mut base = RenderLayerBase::new(Arc::<EvaluatedLayer<T>>::clone(&evaluated));
        base.style_dependencies = T::PaintProperties::dependencies(&unevaluated);
        (base, LayerValues { style, unevaluated, evaluated })
    }

    /// The paint values evaluated for a frame, copying from the last
    /// evaluation each value that can't have changed, with the frame's
    /// cross-fade where the type `crossfades`, and no render passes yet.
    pub(crate) fn evaluate(
        &mut self,
        parameters: &PropertyEvaluationParameters,
        crossfades: bool,
    ) -> EvaluatedLayer<T> {
        let paint =
            T::PaintProperties::evaluate_with_previous(&mut self.unevaluated, parameters, &self.evaluated.paint);
        let layer_type = self.evaluated.layer_type;
        let mut evaluated = EvaluatedLayer::with_paint(Arc::clone(&self.style), paint, layer_type);
        if crossfades {
            evaluated.crossfade = parameters.get_crossfade_parameters();
        }
        evaluated
    }

    /// Makes `evaluated` the layer's values, drawing in `base`'s passes.
    pub(crate) fn set_evaluated(&mut self, base: &mut RenderLayerBase, mut evaluated: EvaluatedLayer<T>) {
        evaluated.render_passes = base.passes.underlying_type();
        self.evaluated = Arc::new(evaluated);
        base.evaluated_properties = Arc::<EvaluatedLayer<T>>::clone(&self.evaluated);
    }
}

/// What a layer's evaluation says of how it draws with its values.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Evaluation {
    /// Whether the layer draws anything.
    pub draws: bool,
    /// Whether the layer may draw in the opaque pass, which the frame draws
    /// front to back before it blends the rest.
    pub opaque: bool,
    /// The one solid color the layer is, which the frame clears to instead
    /// of drawing the layer when it is the style's bottom layer.
    pub solid: Option<Color>,
    /// Whether the layer draws a drape by the map's bearing: something of
    /// it is anchored to the viewport.
    pub drapes_by_bearing: bool,
}

impl Evaluation {
    /// The layer draws nothing.
    pub const NONE: Evaluation = Evaluation { draws: false, opaque: false, solid: None, drapes_by_bearing: false };
    /// The layer draws, translucent.
    pub const TRANSLUCENT: Evaluation = Evaluation { draws: true, ..Evaluation::NONE };
    /// The layer draws, and may draw in the opaque pass.
    pub const OPAQUE: Evaluation = Evaluation { opaque: true, ..Evaluation::TRANSLUCENT };

    /// The passes a layer of this evaluation draws in.
    fn passes(self) -> RenderPass {
        match self {
            Evaluation { draws: false, .. } => RenderPass::None,
            Evaluation { opaque: true, .. } => RenderPass::Opaque | RenderPass::Translucent,
            Evaluation { opaque: false, .. } => RenderPass::Translucent,
        }
    }
}

/// What a layer's [`Layer::evaluate`] reads and completes.
pub struct EvaluateCx<'a, L: Layer> {
    /// The layer's values before the evaluation: its style, its paint values
    /// in transition and their last evaluation.
    pub values: &'a LayerValues<L::Style>,
    /// What the values were evaluated for.
    pub parameters: &'a PropertyEvaluationParameters,
    /// The new evaluation of the values, which becomes the layer's once the
    /// hook returns.
    pub evaluated: &'a mut EvaluatedLayer<L::Style>,
}

/// How a layer type meets terrain.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnTerrain {
    /// The layer draws flat, at sea level.
    Flat,
    /// The layer drapes over terrain: it draws flat into the terrain tiles'
    /// textures (`RenderLayer::update_drape_draws`) rather than onto the
    /// frame.
    Drapes,
    /// The layer stands on terrain: over terrain, its draws are of the
    /// terrain variant ([`ProjectionVariant::stands`]), and their points
    /// stand on the frame's ground, whose heights a program reads where it
    /// declares [`GROUND_HEIGHT`](crate::draw::ground::GROUND_HEIGHT). One
    /// that `hides_behind_ground` hides its points behind the ground in
    /// front of them, which reads the ground's depth
    /// ([`GROUND_DEPTH`](crate::draw::ground::GROUND_DEPTH)).
    Stands { hides_behind_ground: bool },
}

impl OnTerrain {
    /// Whether the layer drapes over terrain.
    pub(crate) fn drapes(self) -> bool {
        self == OnTerrain::Drapes
    }

    /// Whether the layer stands on terrain.
    pub(crate) fn stands(self) -> bool {
        matches!(self, OnTerrain::Stands { .. })
    }

    /// Whether the layer hides behind the ground in front of it.
    pub(crate) fn hides_behind_ground(self) -> bool {
        self == OnTerrain::Stands { hides_behind_ground: true }
    }
}

/// What a layer's [`Layer::prepare`] reads and changes: its base and
/// values, its values of the tiles it draws (`TileMap`), which the frame
/// and its drapes share, by the tiles' own ids ([`FrameTile::id`]), and the
/// frame it makes its draws for, the map's or a drape's.
pub struct PrepareCx<'a, 'f, L: Layer> {
    pub base: &'a RenderLayerBase,
    pub values: &'a LayerValues<L::Style>,
    pub tiles: &'a mut TileMap<L::Tile>,
    /// For a layer that picks its tiles ([`Layer::PICKS_TILES`]),
    /// those the frame draws, in id order: those it picked, or a drape's
    /// tile. Empty for another layer.
    pub picked: &'a [OverscaledTileID],
    /// What the layer makes its meshes and targets with.
    pub res: Resources<'a>,
    pub frame: &'a LayerFrame<'f>,
    /// The frame's shared targets, in the map's frame.
    pub(crate) targets: Option<&'a mut SharedTargets>,
}

impl<L: Layer> PrepareCx<'_, '_, L> {
    /// The texture of the frame's shared target `name`
    /// ([`Router`](crate::layer::Router)), which the layer's
    /// draws sample: its texel at `(x, y)` is what the layers routed into it
    /// drew at the frame's device pixel `(x, y)`; the read orders the
    /// target's pass before the layer's draws. A layer reads the targets only
    /// in the map's frame, for its draws over the map: `None` in a drape,
    /// and, with a warning, for a name that the frame has no target of.
    pub fn read_target(&mut self, name: &str) -> Option<SharedTexture> {
        self.targets.as_deref_mut()?.read(&self.base.style.base().id, name)
    }
}

/// What a layer's [`Layer::tile`] reads to make a tile's value.
pub struct TileCx<'a, 'f, L: Layer> {
    pub base: &'a RenderLayerBase,
    pub values: &'a LayerValues<L::Style>,
    /// What the layer makes its meshes and targets with.
    pub res: Resources<'a>,
    /// The frame the value is made in: the map's, or for a layer that
    /// drapes, the drape's that first draws it, whose value every drape
    /// the tile overlaps draws.
    pub frame: &'a LayerFrame<'f>,
}

/// What a layer's [`Layer::update`] reads, besides its tiles.
pub struct UpdateCx<'a, 'p, L: Layer> {
    pub values: &'a LayerValues<L::Style>,
    pub parameters: &'a mut LayerUpdateParameters<'p>,
    picked: &'a mut Vec<OverscaledTileID>,
}

impl<L: Layer> UpdateCx<'_, '_, L> {
    /// The deepest zoom the layer's source has tiles of; `None` for a layer
    /// without a source or a source without tiles.
    #[must_use]
    pub fn source_max_zoom(&self) -> Option<u8> {
        self.parameters.source.and_then(RenderSource::max_zoom)
    }

    /// Makes `tiles` those that a layer that picks its tiles
    /// ([`Layer::PICKS_TILES`]) draws in the map's frame.
    pub fn pick_tiles(&mut self, tiles: impl IntoIterator<Item = OverscaledTileID>) {
        debug_assert!(L::PICKS_TILES, "a layer that doesn't pick its tiles picked some");
        self.picked.clear();
        self.picked.extend(tiles);
        self.picked.sort();
        self.picked.dedup();
    }
}

/// A drape a layer draws in: its terrain tile, whether the frame is on the
/// globe, and the tiles of every drape of the frame, in id order, which a
/// layer that picks its tiles keeps values of.
#[derive(Clone, Copy)]
pub struct DrapeTile<'a> {
    pub(crate) tile: OverscaledTileID,
    pub(crate) globe: bool,
    pub(crate) tiles: &'a [OverscaledTileID],
}

/// The draws a layer makes in a frame: the map's, which read the frame's
/// shared targets, or a drape's, into the drape's draws of the layer.
enum DrawsFor<'d> {
    Map(&'d mut SharedTargets),
    Drape(&'d mut Draws, &'d OverscaledTileID),
}

/// A layer type's render half: what it makes of its values, its tiles'
/// data and the frame, whose hooks the engine calls on a render layer of the
/// type (`Hosted`). The engine keeps the layer's base, its values of the
/// layer type `Type`, its value of each tile it draws, a `Tile`, which the
/// map's frame and every drape the tile overlaps draw, and its draws
/// ([`Draws`]) in the frame and in each drape it draws in.
pub trait Layer: Sized + 'static {
    /// The type's style half: its name, its kind of source and its
    /// properties.
    type Style: StyleLayerType;

    /// What the type's layers draw from: the features of a geometry
    /// source's tiles, which a layout lays out into a bucket per tile
    /// ([`Features`](crate::layer::tile_input::Features)), a raster or
    /// raster-dem source's tiles, or none, for a type without a source
    /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). Of another kind of
    /// source than the style half names, the registration doesn't compile.
    type Input: TileInput<Self::Style>;

    /// What the engine keeps of each tile the layer draws for it, from when
    /// the layer makes it ([`tile`](Self::tile)) until what the tile shows
    /// the layer changes.
    type Tile: 'static;

    /// The order the layer draws its source's tiles in.
    const TILE_ORDER: TileOrder = TileOrder::ById;

    /// How the layer meets terrain.
    const TERRAIN: OnTerrain = OnTerrain::Flat;

    /// Whether the layer draws 3D geometry, whose depth it writes in the
    /// range of `PaintParameters::depth_mode_for_3d`. The layers above the
    /// lowest such layer that draws draw without a depth test, and on the
    /// globe the planet's depth hides its geometry behind the horizon.
    const VOLUME: bool = false;

    /// Whether the frame's draws of the layer can draw into a shared target
    /// instead of the map
    /// ([`Router`](crate::layer::Router)): not those of 3D geometry.
    const ROUTES: bool = !Self::VOLUME;

    /// Whether a layer of a type without a source draws tiles it picks in
    /// its update ([`UpdateCx::pick_tiles`]), and in a drape the drape's
    /// tile ([`PrepareCx::picked`]); one that picks none draws nothing. One
    /// that doesn't pick draws without tiles.
    const PICKS_TILES: bool = false;

    /// Whether the layer's tile values hold nothing of its style's values,
    /// so that they stay through a restyle.
    const RESTYLE_KEEPS_TILES: bool = false;

    /// Whether the type has cross-faded properties, whose evaluation takes
    /// the frame's cross-fade.
    const CROSSFADES: bool = false;

    /// Whether the type's layers draw on the tiles that are fading out
    /// while a placement fades their marks out.
    const FADES_TILES: bool = false;

    /// Whether the type's layers place their marks, with a participant in
    /// placement ([`Placement`](crate::placement::Placement)) that registers
    /// with the type
    /// ([`add_placing_layer_type`](crate::RegistryBuilder::add_placing_layer_type)).
    const PLACES: bool = false;

    /// The layer of the values `values`, before they transition.
    fn new(values: &LayerValues<Self::Style>) -> Self;

    /// Called once the layer's paint values are evaluated for a frame,
    /// before they become the layer's: the layer derives the values of
    /// `cx.evaluated` that its type derives from others, remakes what it
    /// makes of them, such as a color ramp, and says how it draws with them.
    fn evaluate(&mut self, _cx: EvaluateCx<'_, Self>) -> Evaluation {
        Evaluation::TRANSLUCENT
    }

    /// The light that the terrain's surface can shade the layer's drapes
    /// with in `frame`, whose draws then put in them what it shades
    /// ([`LayerFrame::drape_lit`]); `None` for a layer whose drapes hold its
    /// colors.
    fn surface_light(&mut self, _values: &LayerValues<Self::Style>, _frame: &LayerFrame<'_>) -> Option<SurfaceLight> {
        None
    }

    /// Called in the frame's update of the layer with `tiles`, the frame's
    /// tiles of its source in the order the layer draws them, each with
    /// what it holds for the layer; none for a type without a source
    /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). The layer collects
    /// here what the update needs of its tiles' data; a type that places
    /// collects what it places in its participant instead
    /// (`Placement::collect`). One
    /// without a source that picks its tiles picks them here.
    fn update(&mut self, _cx: UpdateCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>]) {}

    /// Whether `tile`, a tile's value the layer made, still draws the tile
    /// with the layer's `values` of the frame. The engine retires a value
    /// the layer doesn't keep before the layer makes the frame's draws.
    fn keeps(&self, _values: &LayerValues<Self::Style>, _tile: &Self::Tile) -> bool {
        true
    }

    /// The value of `tile`, which holds `data` for the layer, for a tile
    /// the engine keeps no value of: none where the tile shows nothing to
    /// draw. The engine keeps it until the tile shows the layer something
    /// else (another bucket, or contents of another generation), leaves the
    /// frame, or the layer's draws drop. The map's frame and every drape
    /// the tile overlaps, in any world copy, draw the same value, so it
    /// holds nothing of the frame or the copy it is first drawn in.
    ///
    /// `previous` is the tile's value before, if the engine retired it
    /// rather than dropped it: when the tile came to show other contents or
    /// another generation of them, the layer stopped keeping it
    /// ([`keeps`](Self::keeps)), or its draws dropped for a restyle or the
    /// frame's projection. A layer takes from it what it made of contents
    /// that are still the tile's, such as a texture of the tile's image,
    /// rather than making them again.
    fn tile(
        &mut self,
        _cx: &mut TileCx<'_, '_, Self>,
        _tile: FrameTile<'_, Self>,
        _data: TileData<'_, Self>,
        _previous: Option<Self::Tile>,
    ) -> Option<Self::Tile> {
        None
    }

    /// Makes the layer's draws of the frame, the map's or a drape's, in the
    /// frame's encode, of a layer that draws in a pass and has tiles to draw,
    /// once the engine made the values of the tiles that had none
    /// ([`tile`](Self::tile)): from `tiles`, the frame's tiles of the layer,
    /// in the order the update gave them, each with what it holds for the
    /// layer, or in a drape those that overlap the drape's tile, each in the
    /// world copy the drape draws it in ([`FrameTile::draw_id`]); none for a
    /// type without a source, which draws the tiles it picked
    /// ([`PrepareCx::picked`]). The layer pushes its draws, with the values
    /// of their blocks, into `out`, which holds no draws yet, and copies
    /// again into the tile values what changed of their buckets
    /// (`TileEntry::take_changes`), which every frame that draws them
    /// then draws. The engine then writes, uploads and draws them, and draws
    /// the masks of the layer's tiles where a draw clips.
    fn prepare(&mut self, _cx: &mut PrepareCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>], _out: &mut Draws) {}

    /// Draws with the backend's commands that the frame lends the layer
    /// `at` its time in the frame, where its draws asked for them
    /// ([`Draws::lend`]): `lent`, which the layer may use only until this
    /// returns. A frame without commands to lend, such as one outside a
    /// pass at [`LendAt::Pass`], lends none.
    ///
    /// What the layer makes with the commands, the engine doesn't know of:
    /// the layer frees it through work it queues for after the GPU
    /// ([`Lent::after_gpu`]), at the latest as it drops, which is when it
    /// leaves the renderer.
    fn lend(&mut self, _at: LendAt, _lent: Lent<'_>) {}

    /// How far outside a feature of `data`, a tile's bucket of the layer, a
    /// query still hits it, from `layer`'s current values and the bucket's
    /// statistics of them. The engine asks only a type whose input lays
    /// out.
    fn query_radius(_data: TileData<'_, Self>, _layer: &EvaluatedLayer<Self::Style>) -> f32 {
        0.0
    }

    /// Whether a query hits the feature `feature` with `geometry`, with
    /// `feature_state`: whether it intersects `region` of its tile as the
    /// layer of `values` draws it at the view's zoom; false unless a layer
    /// type overrides it.
    fn hit(
        &self,
        _values: &LayerValues<Self::Style>,
        _region: &QueryRegion<'_>,
        _feature: &dyn mln_style::feature::GeometryTileFeature,
        _geometry: &mln_style::feature::GeometryCollection,
        _feature_state: &mln_style::feature::FeatureState,
    ) -> bool {
        false
    }

    /// Adds to `hits` the features that `query`'s geometry hits of what the
    /// layer shows other than its tiles' features, such as a mark it places
    /// itself, topmost first. As for tiles' features, a query answers for
    /// the last update: the engine asks a layer that the update would draw,
    /// with its view and values, which may come before a frame draws them,
    /// so a layer answers from `query` rather than from what it kept from
    /// drawing. The engine names the features' layer and source and keeps
    /// those that the query's filter takes.
    fn hit_frame(&self, _query: &FrameQuery<'_, Self>, _hits: &mut Vec<Feature>) {}
}

/// A rendered-feature query of a layer `L`, for what it shows other than
/// its tiles' features, as of the last update ([`Layer::hit_frame`]).
pub struct FrameQuery<'a, L: Layer> {
    values: &'a LayerValues<L::Style>,
    view: &'a View,
    geometry: &'a [ScreenCoordinate],
    ground: Option<&'a TerrainElevation>,
}

impl<'a, L: Layer> FrameQuery<'a, L> {
    /// The layer's values of the last update.
    #[must_use]
    pub fn values(&self) -> &'a LayerValues<L::Style> {
        self.values
    }

    /// The last update's camera and projection.
    #[must_use]
    pub fn view(&self) -> &'a View {
        self.view
    }

    /// The query's geometry, in the view's logical pixels from its top left:
    /// one point, or a closed ring.
    #[must_use]
    pub fn geometry(&self) -> &'a [ScreenCoordinate] {
        self.geometry
    }

    /// Over terrain, the ground the frame drew under the points of `tile`,
    /// for a layer that meets terrain ([`Layer::TERRAIN`]); `None` without
    /// terrain or for a layer that draws flat.
    #[must_use]
    pub fn ground(&self, tile: UnwrappedTileID) -> Option<TileGround<'a>> {
        self.ground.map(|ground| TileGround::new(ground, tile))
    }
}

/// A render layer of a [`Layer`] `L`: the layer, and what the engine
/// keeps of it, its base, its values, its tile values and its draws of the
/// map's frame.
pub(crate) struct Hosted<L: Layer> {
    base: RenderLayerBase,
    values: LayerValues<L::Style>,
    tiles: TileMap<L::Tile>,
    /// The tiles that a layer that picks its tiles picked in its update,
    /// in id order, which it draws in the map's frame.
    picked: Vec<OverscaledTileID>,
    draws: Draws,
    layer: L,
}

impl<L: Layer> Hosted<L> {
    /// The render layer of the layer `style`, before its values transition.
    pub(crate) fn new(style: Arc<LayerStyle<L::Style>>) -> Self {
        let (base, values) = LayerValues::new(style, entry::<L>());
        let layer = L::new(&values);
        Hosted { base, values, tiles: TileMap::default(), picked: Vec::new(), draws: Draws::default(), layer }
    }

    /// [`new`](Self::new), boxed as a [`RenderLayer`].
    pub(crate) fn boxed(style: Arc<LayerStyle<L::Style>>) -> Box<dyn RenderLayer> {
        Box::new(Self::new(style))
    }

    /// The layer and its values, which benchmarks fill as the layer's
    /// update would.
    #[cfg(feature = "bench")]
    pub(crate) fn layer_mut(&mut self) -> (&mut L, &LayerValues<L::Style>) {
        (&mut self.layer, &self.values)
    }

    /// Makes `variant` the projection the layer draws in: where its draws
    /// were of another, drops them and retires its tile values.
    fn use_projection_variant(&mut self, variant: ProjectionVariant) {
        if variant != self.base.projection_variant {
            self.base.projection_variant = variant;
            self.retire_draws();
        }
    }

    /// Drops the frame's draws of the layer and retires its tile values,
    /// which the next values of their tiles may take from: until the
    /// layer's next draws are done, the draws keep what they kept for the
    /// retired values' meshes. The tiles stay.
    fn retire_draws(&mut self) {
        self.tiles.retire();
        self.draws.clear();
    }

    /// Readies the values of `tiles`, the tiles the layer draws, before the
    /// layer makes its draws of them: retires each that was made from
    /// something else than what its tile shows the layer, or that the layer
    /// doesn't keep ([`Layer::keeps`]), and makes those the layer has
    /// none of ([`Layer::tile`]), from their previous values. For a
    /// layer that picks its tiles, retires those of its picked tiles that it
    /// doesn't keep.
    fn ready_tiles(
        &mut self,
        gpu: &mut dyn Gpu,
        context: &mut Context,
        frame: &LayerFrame<'_>,
        tiles: &[FrameTile<'_, L>],
    ) {
        let Hosted { base, values, tiles: map, layer, .. } = self;
        if !has_tiles::<L>() {
            for (_, mut entry) in map.entries() {
                if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
                    entry.retire();
                }
            }
            return;
        }
        for &tile in tiles {
            let Some(mut entry) = map.entry(&tile.id()) else { continue };
            entry.show(tile.made_from());
            if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
                entry.retire();
            }
            if entry.value.is_none()
                && let Some(data) = tile.data()
            {
                // A new value copies its bucket as it is.
                entry.take_changes();
                let previous = entry.take_previous();
                let res = Resources::new(&mut *gpu, &mut *context);
                *entry.value = layer.tile(&mut TileCx { base, values, res, frame }, tile, data, previous);
            }
        }
    }

    /// Makes the layer's draws of `into`'s frame, the map's or a drape's,
    /// if it draws in a pass: starts them, readies its tile values of
    /// `tiles` ([`ready_tiles`](Self::ready_tiles)), runs its
    /// [`Layer::prepare`] and writes the buffers of the draws it made,
    /// with the paint parameters of `parameters`' frame where it has its own
    /// (a drape's), and the masks of `tiles` where a draw clips. One that
    /// draws in no pass with its values of the frame draws nothing, and
    /// keeps its tile values.
    fn draw(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        tiles: &[FrameTile<'_, L>],
        into: DrawsFor<'_>,
    ) {
        if self.values.evaluated.render_passes == RenderPass::None.underlying_type() {
            match into {
                DrawsFor::Map(_) => self.draws.begin(),
                DrawsFor::Drape(draws, _) => draws.begin(),
            }
            return;
        }
        let frame = parameters.frame();
        self.ready_tiles(gpu, parameters.context, &frame, tiles);
        let Hosted { base, values, tiles: map, picked, draws, layer } = self;
        let (draws, picked, targets) = match into {
            DrawsFor::Map(targets) => (draws, &picked[..], Some(targets)),
            DrawsFor::Drape(draws, tile) => (draws, std::slice::from_ref(tile), None),
        };
        draws.begin();
        let res = Resources::new(&mut *gpu, &mut *parameters.context);
        layer.prepare(&mut PrepareCx { base, values, tiles: map, picked, res, frame: &frame, targets }, tiles, draws);
        let paint_params = parameters.own_paint_params();
        let clip_tiles = tiles.iter().map(|tile| tile.draw_id().to_unwrapped());
        draws.finish(gpu, parameters.context, paint_params.as_ref(), clip_tiles);
    }
}

/// Lends `layer` the backend's commands of `gpu` `at` its time in the frame
/// of `parameters`, where the frame has them to lend: in a pass, the open
/// one. A lend that fails fails the frame.
fn lend<L: Layer>(layer: &mut L, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, at: LendAt) {
    let Some(projection) = parameters.lent_projection else { return };
    let frame = parameters.frame();
    let layer_depth = match at {
        LendAt::BeforePasses => None,
        LendAt::Pass if parameters.pass_target().is_some() => Some(f64::from(parameters.layer_depth())),
        LendAt::Pass => return,
    };
    let after_gpu = parameters.context.after_gpu().handle();
    let lent = gpu
        .lend(&mut |raw| layer.lend(at, Lent { raw, frame: &frame, projection: &projection, layer_depth, after_gpu }));
    if let Err(error) = lent {
        parameters.context.fail(format!("Lending a layer the frame's commands failed: {error}"));
    }
}

/// Whether layers of `L`'s type draw from their source's tiles: false for a
/// type without a source.
fn has_tiles<L: Layer>() -> bool {
    <L::Input as Find<L::Style>>::KIND != SourceKind::None
}

/// What the engine does with a render layer, whatever its type: its base,
/// its values, which this transitions without knowing their type, its tile
/// values and its draws, which it writes, uploads and draws. It runs
/// the layer's [`Layer`] hooks with what is common to every layer type
/// around them.
pub trait RenderLayer {
    fn base(&self) -> &RenderLayerBase;

    /// The layer's id.
    fn id(&self) -> &str {
        &self.base().style.base().id
    }

    /// The order the layer draws its source's tiles in.
    fn tile_order(&self) -> TileOrder;

    /// Makes `style`, the changed style of the layer (of the same id and
    /// type), the layer's, drops the draws, which were built for the
    /// previous style's values, with the tile values unless the layer keeps
    /// them ([`Layer::RESTYLE_KEEPS_TILES`]), and begins transitions to
    /// the new values. A style of another type leaves the layer's. The next
    /// encode builds the draws again from the tiles' buckets.
    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>);

    /// Begins transitions for the paint values that changed since the last
    /// frame, to those of the layer's style.
    fn transition(&mut self, parameters: &TransitionParameters);

    /// Evaluates the layer's paint values for a frame of `parameters`,
    /// which the layer completes ([`Layer::evaluate`]), and sets the
    /// passes the layer draws in with them.
    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters);

    /// Whether a paint value of the layer is still in transition.
    fn has_transition(&self) -> bool;

    /// Whether the layer has a pattern property and is in a cross-fade.
    fn has_crossfade(&self) -> bool;

    /// The frame's update of the layer: finds the tiles of `parameters`'
    /// source the layer draws, which it adds to `parameters.found`, adds the
    /// passes their buckets were laid out for to the layer's, runs the
    /// layer's [`Layer::update`], and keeps entries for the tiles; or,
    /// for a type without a source, runs its update without tiles.
    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>);

    /// The encode's update of the layer's draws: picks the shader variant
    /// for the frame's projection, standing on the frame's ground where the
    /// layer stands and the frame has one, dropping the draws and tile values
    /// when it changed; drops them of a layer that has nothing to draw, and
    /// otherwise starts its draws of the frame; for a layer that draws in a
    /// pass, readies the tile values and runs the layer's
    /// [`Layer::prepare`] with the tiles of its type that its update
    /// found in `source`, or none for a type without a source, and writes
    /// the buffers of its draws.
    fn update_draws(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        source: Option<FrameSourceTiles<'_>>,
        targets: &mut SharedTargets,
    );

    /// How the layer meets terrain ([`Layer::TERRAIN`]).
    fn terrain(&self) -> OnTerrain;

    /// Whether the layer draws 3D geometry ([`Layer::VOLUME`]).
    fn volume(&self) -> bool;

    /// Whether the layer's draws can draw into a shared target
    /// ([`Layer::ROUTES`]).
    fn routes(&self) -> bool;

    /// Makes `route` the shared target that the frame's draws of the layer
    /// draw into instead of the map, or with `None` the map.
    fn set_route(&mut self, route: Option<usize>);

    /// Whether the layer's blend with its values of the frame reads what is
    /// drawn beneath it, which a shared target's pass can't give it.
    fn reads_backdrop(&self) -> bool;

    /// Whether the layer blends with what is under it otherwise than by
    /// covering it, with its values of the frame: a layer blend
    /// ([`StyleLayerType::layer_blend`]) other than `normal`.
    fn blends(&self) -> bool;

    /// The light the terrain's surface can shade the layer's drapes with
    /// ([`Layer::surface_light`]).
    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight>;

    /// Where the tiles the layer's update found are among the frame's
    /// ([`LayerUpdateParameters::found`]); `None` for a type without a
    /// source.
    fn found(&self) -> Option<Range<usize>>;

    /// The encode's update of the layer's draws into `drape`, `draws`, as
    /// [`update_draws`](Self::update_draws) makes the frame's, with the
    /// drape's `parameters`, from the tiles of `source` the layer's update
    /// found that overlap the drape's tile
    /// ([`FrameSourceTiles::overlapping`]), or from the drape's tile itself
    /// for a type without a source that picks its tiles, in the Mercator
    /// projection, a drape's. The drape draws the layer's tile values,
    /// which the frame's other drapes share: for a layer that picks its
    /// tiles, those of the tiles of every drape.
    fn update_drape_draws(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        source: Option<FrameSourceTiles<'_>>,
        drape: DrapeTile<'_>,
        draws: &mut Draws,
    );

    /// Records that the buckets in `changed` changed, for the tiles whose
    /// values were made from them.
    fn mark_changed(&mut self, changed: &ChangedBuckets);

    /// Moves the layer's value of each tile to the tile `wrap_delta` world
    /// copies east of it: the tiles are the same ones under new ids once the
    /// map's center has crossed the antimeridian, and their values stay
    /// rather than being made again.
    fn handle_wrap_jump(&mut self, wrap_delta: i16);

    /// Includes the layer in the frame's drawing or excludes it. A layer
    /// excluded drops its draws and its tiles with their values, previous
    /// ones too: its updates don't run until it is included again, and they
    /// then rebuild everything from the source's tiles.
    fn set_renderable(&mut self, renderable: bool);

    /// Drops the layer's tile values, previous ones too, and the frame's
    /// draws of the layer, which then let go of what they kept for the
    /// values' meshes. The tiles stay.
    fn remove_all_draws(&mut self);

    /// Drops the map frame's draws of the layer, which a frame over terrain
    /// draws only in drapes; its tile values stay, for the drapes.
    fn remove_frame_draws(&mut self);

    /// Visits the groups of the layer's draws of the frame that take a place
    /// in the layers' order and depth, in drawing order: none unless the
    /// frame draws the layer. They are the groups `upload` and `render`
    /// upload and draw.
    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group));

    /// Uploads the meshes of the layer's draws, before the frame draws them.
    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context);

    /// Draws the pass's draws of the layer's groups into the open pass of
    /// `gpu`, the context's, in `order`, each at its depth, and, in the
    /// translucent pass, lends the layer the pass after its main group where
    /// its draws asked for it ([`LendAt::Pass`]): the map's pass, or with
    /// `routed` the pass of the shared target the layer is routed into. In
    /// the other, the layer takes its depth and draws nothing.
    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool);

    /// Before the frame's passes, outside any pass of `gpu`, the context's:
    /// draws into the targets of the layer's draws of the frame
    /// ([`Draws::target`]), and then lends the layer the frame's commands
    /// where its draws asked for them ([`LendAt::BeforePasses`]).
    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>);

    /// See [`Layer::hit`].
    fn hit(
        &self,
        region: &QueryRegion<'_>,
        feature: &dyn mln_style::feature::GeometryTileFeature,
        geometry: &mln_style::feature::GeometryCollection,
        feature_state: &mln_style::feature::FeatureState,
    ) -> bool;

    /// See [`Layer::hit_frame`]: what `geometry`, in `view`'s logical pixels,
    /// hits of what the layer shows, over `ground` where the map has
    /// terrain. Nothing for a layer the last update wouldn't draw.
    fn hit_frame(
        &self,
        view: &View,
        geometry: &[ScreenCoordinate],
        ground: Option<&TerrainElevation>,
        hits: &mut Vec<Feature>,
    );

    /// Whether the layer draws in a pass and is visible.
    fn needs_rendering(&self) -> bool {
        self.base().passes != RenderPass::None && self.base().style.base().visibility != VisibilityType::None
    }

    /// Whether the layer draws at `zoom`. A minimum zoom of 0 is no
    /// minimum: the globe zooms below 0 toward the poles.
    fn supports_zoom(&self, zoom: f32) -> bool {
        let zoom_or_zero = if zoom < 0.0 { 0.0 } else { zoom };
        self.base().style.base().min_zoom <= zoom_or_zero && zoom < self.base().style.base().max_zoom
    }

    /// Whether the frame draws the layer.
    fn is_renderable(&self) -> bool {
        self.base().is_renderable
    }

    /// What the layer's paint values depend on.
    fn style_dependencies(&self) -> Dependency {
        self.base().style_dependencies
    }
}

impl<L: Layer> RenderLayer for Hosted<L> {
    fn base(&self) -> &RenderLayerBase {
        &self.base
    }

    fn tile_order(&self) -> TileOrder {
        L::TILE_ORDER
    }

    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>) {
        if L::RESTYLE_KEEPS_TILES {
            self.draws.clear();
        } else {
            self.retire_draws();
        }
        if let Some(recovered) = LayerStyle::recover(style) {
            self.values.style = recovered;
            self.base.style = Arc::clone(style);
        }
        self.transition(parameters);
    }

    fn transition(&mut self, parameters: &TransitionParameters) {
        let values = &mut self.values;
        let prior = std::mem::take(&mut values.unevaluated);
        values.unevaluated = values.style.paint.transitioned(parameters, prior);
        self.base.style_dependencies = <L::Style as StyleLayerType>::PaintProperties::dependencies(&values.unevaluated);
    }

    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters) {
        let mut evaluated = self.values.evaluate(parameters, L::CROSSFADES);
        let evaluation =
            self.layer.evaluate(EvaluateCx { values: &self.values, parameters, evaluated: &mut evaluated });
        self.base.passes = evaluation.passes();
        self.base.evaluation = evaluation;
        self.values.set_evaluated(&mut self.base, evaluated);
    }

    fn has_transition(&self) -> bool {
        <L::Style as StyleLayerType>::PaintProperties::has_transition(&self.values.unevaluated)
    }

    fn has_crossfade(&self) -> bool {
        L::CROSSFADES && self.values.evaluated.crossfade.t != 1.0
    }

    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>) {
        let Hosted { base, values, tiles: map, picked, layer, .. } = self;
        if !has_tiles::<L>() {
            layer.update(UpdateCx { values, parameters, picked }, &[]);
            return;
        }
        let start = parameters.found.len();
        let tiles = match parameters.tiles(L::TILE_ORDER) {
            Some((tiles, order)) => tiles.find::<L>(order, &base.style.base().id, parameters.found),
            None => FrameTiles::new(),
        };
        base.found = start..parameters.found.len();
        for data in tiles.iter().filter_map(|tile| tile.data()) {
            base.passes |= <L::Input as Find<L::Style>>::passes(data);
        }
        layer.update(UpdateCx { values, parameters, picked }, &tiles);
        map.set_tiles(tiles.iter().map(|tile| tile.id()));
    }

    fn update_draws(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        source: Option<FrameSourceTiles<'_>>,
        targets: &mut SharedTargets,
    ) {
        let stands = L::TERRAIN.stands() && parameters.ground.is_some();
        self.use_projection_variant(ProjectionVariant::new(parameters.view.is_globe(), stands));
        if !has_tiles::<L>() {
            // A layer that picks tiles draws those its update picked.
            if L::PICKS_TILES {
                self.tiles.set_tiles(self.picked.iter().copied());
            }
            if L::PICKS_TILES && self.tiles.is_empty() {
                self.remove_all_draws();
            } else {
                self.draw(gpu, parameters, &[], DrawsFor::Map(targets));
            }
            return;
        }
        match source.map(|source| (source, source.found(self.base.found.clone()))) {
            Some((source, found)) if !found.is_empty() => {
                let tiles = source.at::<L>(found, self.id());
                self.draw(gpu, parameters, &tiles, DrawsFor::Map(targets));
            }
            _ => self.remove_all_draws(),
        }
    }

    fn terrain(&self) -> OnTerrain {
        L::TERRAIN
    }

    fn volume(&self) -> bool {
        L::VOLUME
    }

    fn routes(&self) -> bool {
        L::ROUTES
    }

    fn set_route(&mut self, route: Option<usize>) {
        self.base.route = route;
    }

    fn reads_backdrop(&self) -> bool {
        crate::render::layer_composite::reads_backdrop(L::Style::layer_blend(&self.values.evaluated.paint))
    }

    fn blends(&self) -> bool {
        L::Style::layer_blend(&self.values.evaluated.paint) != LayerBlendType::Normal
    }

    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight> {
        self.layer.surface_light(&self.values, &parameters.frame())
    }

    fn found(&self) -> Option<Range<usize>> {
        has_tiles::<L>().then(|| self.base.found.clone())
    }

    fn update_drape_draws(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        source: Option<FrameSourceTiles<'_>>,
        drape: DrapeTile<'_>,
        draws: &mut Draws,
    ) {
        // Only a layer that drapes builds the code of its draws in a drape.
        if !L::TERRAIN.drapes() {
            debug_assert!(false, "a layer that doesn't drape in a drape");
            return;
        }
        // A drape is flat: the layer's draws are Mercator's.
        self.use_projection_variant(ProjectionVariant::Mercator);
        if !has_tiles::<L>() {
            if L::PICKS_TILES {
                self.tiles.set_tiles(drape.tiles.iter().copied());
            }
            self.draw(gpu, parameters, &[], DrawsFor::Drape(draws, &drape.tile));
            return;
        }
        let tiles = match source {
            Some(source) => {
                source.overlapping::<L>(self.base.found.clone(), self.id(), drape.tile.to_unwrapped(), drape.globe)
            }
            None => FrameTiles::new(),
        };
        if tiles.is_empty() {
            draws.clear();
        } else {
            self.draw(gpu, parameters, &tiles, DrawsFor::Drape(draws, &drape.tile));
        }
    }

    fn mark_changed(&mut self, changed: &ChangedBuckets) {
        self.tiles.mark_changed(changed);
    }

    fn handle_wrap_jump(&mut self, wrap_delta: i16) {
        self.tiles.shift_wraps(wrap_delta);
    }

    fn set_renderable(&mut self, renderable: bool) {
        self.base.is_renderable = renderable;
        if !renderable {
            self.tiles.clear_tiles();
            self.draws.clear();
        }
    }

    fn remove_all_draws(&mut self) {
        self.tiles.clear();
        self.draws.clear();
    }

    fn remove_frame_draws(&mut self) {
        self.draws.clear();
    }

    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
        if self.base.is_renderable {
            self.draws.visit_groups(visit);
        }
    }

    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
        if self.base.is_renderable {
            self.draws.upload(gpu, context);
        }
    }

    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool) {
        let Hosted { base, draws, layer, .. } = self;
        if base.is_renderable && base.route.is_some() != routed {
            draws.skip(parameters, order);
        } else if base.is_renderable {
            let lends = draws.lends(LendAt::Pass) && parameters.pass == RenderPass::Translucent;
            let mut lend_pass = |gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>| {
                lend(layer, gpu, parameters, LendAt::Pass);
            };
            draws.render(gpu, parameters, order, lends.then_some(&mut lend_pass));
        }
    }

    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
        if self.base.is_renderable {
            self.draws.render_targets(gpu, parameters);
            if self.draws.lends(LendAt::BeforePasses) {
                lend(&mut self.layer, gpu, parameters, LendAt::BeforePasses);
            }
        }
    }

    fn hit(
        &self,
        region: &QueryRegion<'_>,
        feature: &dyn mln_style::feature::GeometryTileFeature,
        geometry: &mln_style::feature::GeometryCollection,
        feature_state: &mln_style::feature::FeatureState,
    ) -> bool {
        self.layer.hit(&self.values, region, feature, geometry, feature_state)
    }

    fn hit_frame(
        &self,
        view: &View,
        geometry: &[ScreenCoordinate],
        ground: Option<&TerrainElevation>,
        hits: &mut Vec<Feature>,
    ) {
        if self.base.is_renderable {
            let ground = ground.filter(|_| L::TERRAIN != OnTerrain::Flat);
            self.layer.hit_frame(&FrameQuery { values: &self.values, view, geometry, ground }, hits);
        }
    }
}