Skip to main content

mln_engine/layer/
render_layer.rs

1// A render layer is the renderer's side of a style layer: its type's layer
2// (`Layer`), whose hooks see the frame's tiles and what they hold for
3// the type (`TileInput`), and what the engine keeps of it around them
4// (`Hosted`): its base, its values of its type, its value of each tile it
5// draws and its draws. `RenderLayer` is what the engine does with a render
6// layer of any type. The orchestrator owns the render layers, in the
7// style's order.
8
9use std::ops::Range;
10use std::sync::Arc;
11
12use mln_gfx::gpu::Gpu;
13use mln_gfx::projection_variant::ProjectionVariant;
14use mln_style::color::Color;
15use mln_style::expression::Dependency;
16use mln_style::layer::{ErasedLayerStyle, LayerStyle, PaintSet, SourceKind, StyleLayerType};
17use mln_style::types::{LayerBlendType, VisibilityType};
18use mln_style::{PropertyEvaluationParameters, TransitionParameters};
19use smallvec::SmallVec;
20
21use crate::camera::View;
22use crate::draw::context::Context;
23use crate::draw::draws::{DrawOrder, Draws, Group, LayerFrame, LendAt, Lent};
24use crate::draw::resources::Resources;
25use crate::draw::store::Texture;
26use crate::geo::ScreenCoordinate;
27use crate::layer::bucket::ErasedBucket;
28use crate::layer::layer_drawing::{ChangedBuckets, TileMap};
29use crate::layer::layer_type::{ErasedEvaluatedLayer, EvaluatedLayer, entry};
30use crate::layer::tile_input::input::Find;
31use crate::layer::tile_input::{TileData, TileInput};
32use crate::query::feature_index::{Hit, QueryRegion};
33use crate::render::paint_parameters::PaintParameters;
34use crate::render::pass::RenderPass;
35use crate::render::shared_targets::SharedTargets;
36use crate::render::terrain::{SurfaceLight, TerrainElevation, TileGround};
37use crate::render::tile::{FoundTile, FrameTile, RenderTile, TILE_BOUNDS, TileContent, TileStamp, overlaps};
38use crate::render::update_parameters::UpdateParameters;
39use crate::source::render_source::{RenderSource, TileOrder};
40use crate::tile::feature::Feature;
41use crate::tile::{OverscaledTileID, UnwrappedTileID};
42
43/// A layer's bucket in a layout, which the layers of its layout group
44/// share, with the layer's values it was laid out with, whichever the
45/// layer's type.
46#[derive(Clone, Copy)]
47pub(crate) struct ErasedLayerBucket<'a> {
48    pub(crate) bucket: &'a dyn ErasedBucket,
49    /// The index of the bucket among the layout's buckets.
50    pub(crate) bucket_index: usize,
51    /// The values of the layer that the bucket was laid out with.
52    pub(crate) layer: &'a dyn ErasedEvaluatedLayer,
53}
54
55/// A source's render tiles in a frame, with what each of them shows, and
56/// the tiles that the frame's updates of the layers found
57/// ([`LayerUpdateParameters::found`]), as the engine sees them.
58#[derive(Clone, Copy)]
59pub struct FrameSourceTiles<'a> {
60    tiles: &'a [RenderTile],
61    /// What each of `tiles` shows, at its index.
62    contents: &'a [Option<TileContent<'a>>],
63    found: &'a [FoundTile],
64}
65
66/// The tiles of a layer of the type `L` in a frame, each with what it shows
67/// the layer, which keeps up to 64 of them on the stack.
68pub(crate) type FrameTiles<'a, L> = SmallVec<[FrameTile<'a, L>; 64]>;
69
70impl<'a> FrameSourceTiles<'a> {
71    /// The render tiles `tiles`, which show `contents`, at their indexes,
72    /// and the tiles of them that the frame's layers found.
73    #[must_use]
74    pub(crate) fn new(
75        tiles: &'a [RenderTile],
76        contents: &'a [Option<TileContent<'a>>],
77        found: &'a [FoundTile],
78    ) -> Self {
79        FrameSourceTiles { tiles, contents, found }
80    }
81
82    /// What the tile at `index` shows.
83    fn content(self, index: usize) -> Option<TileContent<'a>> {
84        self.contents.get(index).copied().flatten()
85    }
86
87    /// The tiles at the indexes of `order`, in that order, as the layer
88    /// `layer_id` of the type `T` sees them, each with what it shows the
89    /// layer, found by the layer's id. `found` keeps where.
90    fn find<L: Layer>(self, order: &[usize], layer_id: &str, found: &mut Vec<FoundTile>) -> FrameTiles<'a, L> {
91        let mut tiles = FrameTiles::new();
92        for &index in order {
93            let Some(tile) = self.tiles.get(index) else { continue };
94            let (frame_tile, view) = FrameTile::find(tile, self.content(index), layer_id);
95            tiles.push(frame_tile);
96            found.push(FoundTile { tile: index, view });
97        }
98        tiles
99    }
100
101    /// The found tiles at `found`, a range of them.
102    pub(crate) fn found(self, found: Range<usize>) -> &'a [FoundTile] {
103        self.found.get(found).unwrap_or_default()
104    }
105
106    /// The tiles of `found`, as [`find`](Self::find) found them for the
107    /// layer `layer_id` of the type `T` in the same frame.
108    pub(crate) fn at<'f, L: Layer>(
109        self,
110        found: impl IntoIterator<Item = &'f FoundTile>,
111        layer_id: &str,
112    ) -> FrameTiles<'a, L> {
113        found
114            .into_iter()
115            .filter_map(|&FoundTile { tile, view }| {
116                let render_tile = self.tiles.get(tile);
117                debug_assert!(render_tile.is_some(), "a tile found past the frame's render tiles");
118                Some(FrameTile::at(render_tile?, self.content(tile), layer_id, view))
119            })
120            .collect()
121    }
122
123    /// The tiles of the found tiles at `found`, as [`at`](Self::at) gives
124    /// them, that overlap `tile` (what they show covers part of it), each in
125    /// the world copy that does: on Mercator their own, so those of `tile`'s
126    /// copy; on the `globe`, which has no copies, whatever their copy, one by
127    /// `tile`'s. A drape of `tile` draws each in that copy
128    /// ([`FrameTile::draw_id`]).
129    pub(crate) fn overlapping<L: Layer>(
130        self,
131        found: Range<usize>,
132        layer_id: &str,
133        tile: UnwrappedTileID,
134        globe: bool,
135    ) -> FrameTiles<'a, L> {
136        let found = self.found(found);
137        self.overlaps(found, tile, globe)
138            .map(|(&FoundTile { tile: index, view }, render_tile, wrap)| {
139                FrameTile::at(render_tile, self.content(index), layer_id, view).in_copy(wrap)
140            })
141            .collect()
142    }
143
144    /// What a layer draws of the tiles that
145    /// [`overlapping`](Self::overlapping) gives, in its order, under the ids
146    /// it draws them in.
147    pub(crate) fn stamps(
148        self,
149        found: Range<usize>,
150        tile: UnwrappedTileID,
151        globe: bool,
152    ) -> impl Iterator<Item = TileStamp> {
153        let found = self.found(found);
154        self.overlaps(found, tile, globe).map(move |(&FoundTile { tile: index, view }, render_tile, wrap)| {
155            let stamp = self.content(index).zip(view).and_then(|(content, place)| content.stamp(place));
156            TileStamp {
157                tile: OverscaledTileID { wrap, ..*render_tile.overscaled_tile_id() },
158                bucket: stamp.map(|(bucket, _)| bucket),
159                generations: stamp.map_or([0, 0], |(_, generations)| generations),
160            }
161        })
162    }
163
164    /// The tiles of `found` that overlap `tile`, with their render tiles and
165    /// the world copies they overlap it in: on Mercator their own; on the
166    /// `globe`, any of `tile`'s and the copies either side, which an image
167    /// source's image that crosses the antimeridian reaches into.
168    fn overlaps<'f>(
169        self,
170        found: &'f [FoundTile],
171        tile: UnwrappedTileID,
172        globe: bool,
173    ) -> impl Iterator<Item = (&'f FoundTile, &'a RenderTile, i16)> {
174        let found = found.iter().filter_map(move |found| Some((found, self.tiles.get(found.tile)?)));
175        found.flat_map(move |(found, render_tile)| {
176            let bounds = self.content(found.tile).map_or(TILE_BOUNDS, TileContent::bounds);
177            let canonical = render_tile.id.canonical;
178            let wraps = if globe { tile.wrap - 1..=tile.wrap + 1 } else { render_tile.id.wrap..=render_tile.id.wrap };
179            wraps
180                .filter(move |&wrap| overlaps(&UnwrappedTileID::with_wrap(wrap, canonical), bounds, &tile))
181                .map(move |wrap| (found, render_tile, wrap))
182        })
183    }
184}
185
186/// What a layer reads in the frame's update, besides its tiles.
187pub struct LayerUpdateParameters<'a> {
188    /// The frame's camera.
189    pub view: &'a View,
190    /// The update the frame draws.
191    pub update_parameters: &'a UpdateParameters,
192    /// The layer's source, `None` for a layer without one or a source type
193    /// the renderer has no render source for.
194    pub(crate) source: Option<&'a dyn RenderSource>,
195    /// What each of the source's render tiles shows, at its index.
196    pub(crate) contents: &'a [Option<TileContent<'a>>],
197    /// The images of the style.
198    pub images: &'a crate::image::image_store::ImageStore,
199    /// The tiles of the frame's layers, as their updates find them, which
200    /// the update adds the layer's to: those the encode draws.
201    pub(crate) found: &'a mut Vec<FoundTile>,
202}
203
204impl<'a> LayerUpdateParameters<'a> {
205    /// The source's tiles, and their indexes in `order`; `None` for a layer
206    /// without a source or a source without tiles.
207    #[must_use]
208    fn tiles(&self, order: TileOrder) -> Option<(FrameSourceTiles<'a>, &'a [usize])> {
209        let source = self.source?;
210        Some((FrameSourceTiles::new(source.render_tiles(), self.contents, &[]), source.tile_order(order)?))
211    }
212}
213
214/// What every render layer has, whatever its type.
215pub struct RenderLayerBase {
216    pub(crate) evaluated_properties: Arc<dyn ErasedEvaluatedLayer>,
217    pub style: Arc<dyn ErasedLayerStyle>,
218
219    pub(crate) passes: RenderPass,
220    /// What the layer's last evaluation said of how it draws.
221    pub(crate) evaluation: Evaluation,
222    pub(crate) style_dependencies: Dependency,
223    /// Whether the frame draws the layer.
224    pub(crate) is_renderable: bool,
225
226    /// The projection variant this layer's draws are built with.
227    pub projection_variant: ProjectionVariant,
228
229    /// The shared target that the frame's draws of the layer draw into
230    /// instead of the map, if any.
231    pub(crate) route: Option<usize>,
232
233    /// Where the tiles the layer's update found are among the frame's
234    /// ([`LayerUpdateParameters::found`]).
235    found: Range<usize>,
236}
237
238impl RenderLayerBase {
239    /// The passes the layer draws in, as its last evaluation said.
240    #[must_use]
241    pub fn passes(&self) -> RenderPass {
242        self.passes
243    }
244
245    /// Where the tiles the layer's update found are among the frame's
246    /// ([`LayerUpdateParameters::found`]).
247    pub(crate) fn found(&self) -> Range<usize> {
248        self.found.clone()
249    }
250
251    pub(crate) fn new(properties: Arc<dyn ErasedEvaluatedLayer>) -> Self {
252        let style = properties.shared_style();
253        RenderLayerBase {
254            evaluated_properties: properties,
255            style,
256            passes: RenderPass::NONE,
257            evaluation: Evaluation::NONE,
258            style_dependencies: Dependency::NONE,
259            is_renderable: false,
260            projection_variant: ProjectionVariant::Mercator,
261            route: None,
262            found: 0..0,
263        }
264    }
265}
266
267/// A layer's values of its style half `T`: its style, its paint values in
268/// transition, and their evaluation for the last frame.
269pub struct LayerValues<T: StyleLayerType> {
270    pub style: Arc<LayerStyle<T>>,
271    pub unevaluated: <T::PaintProperties as PaintSet>::Unevaluated,
272    pub evaluated: Arc<EvaluatedLayer<T>>,
273}
274
275impl<T: StyleLayerType> LayerValues<T> {
276    /// The values of the layer `style` of `layer_type`, before any
277    /// transition, and the base of a render layer that holds them.
278    pub(crate) fn new(
279        style: Arc<LayerStyle<T>>,
280        layer_type: &'static dyn crate::layer::layer_type::ErasedLayerType,
281    ) -> (RenderLayerBase, Self) {
282        let unevaluated = style.paint.untransitioned();
283        let evaluated = Arc::new(EvaluatedLayer::new(Arc::clone(&style), layer_type));
284        let mut base = RenderLayerBase::new(Arc::<EvaluatedLayer<T>>::clone(&evaluated));
285        base.style_dependencies = T::PaintProperties::dependencies(&unevaluated);
286        (base, LayerValues { style, unevaluated, evaluated })
287    }
288
289    /// The paint values evaluated for a frame, copying from the last
290    /// evaluation each value that can't have changed, with the frame's
291    /// cross-fade where the type `crossfades`, and no render passes yet.
292    pub(crate) fn evaluate(
293        &mut self,
294        parameters: &PropertyEvaluationParameters,
295        crossfades: bool,
296    ) -> EvaluatedLayer<T> {
297        let paint =
298            T::PaintProperties::evaluate_with_previous(&mut self.unevaluated, parameters, &self.evaluated.paint);
299        let layer_type = self.evaluated.layer_type;
300        let mut evaluated = EvaluatedLayer::with_paint(Arc::clone(&self.style), paint, layer_type);
301        if crossfades {
302            evaluated.crossfade = parameters.crossfade_parameters();
303        }
304        evaluated
305    }
306
307    /// Makes `evaluated` the layer's values, drawing in `base`'s passes.
308    pub(crate) fn set_evaluated(&mut self, base: &mut RenderLayerBase, mut evaluated: EvaluatedLayer<T>) {
309        evaluated.render_passes = base.passes.bits();
310        self.evaluated = Arc::new(evaluated);
311        base.evaluated_properties = Arc::<EvaluatedLayer<T>>::clone(&self.evaluated);
312    }
313}
314
315/// What a layer's evaluation says of how it draws with its values.
316#[derive(Clone, Copy, Debug, Default, PartialEq)]
317pub struct Evaluation {
318    /// Whether the layer draws anything.
319    pub draws: bool,
320    /// Whether the layer may draw in the opaque pass, which the frame draws
321    /// front to back before it blends the rest.
322    pub opaque: bool,
323    /// The one solid color the layer is, which the frame clears to instead
324    /// of drawing the layer when it is the style's bottom layer.
325    pub solid: Option<Color>,
326    /// Whether the layer draws a drape by the map's bearing: something of
327    /// it is anchored to the viewport.
328    pub drapes_by_bearing: bool,
329}
330
331impl Evaluation {
332    /// The layer draws nothing.
333    pub const NONE: Evaluation = Evaluation { draws: false, opaque: false, solid: None, drapes_by_bearing: false };
334    /// The layer draws, translucent.
335    pub const TRANSLUCENT: Evaluation = Evaluation { draws: true, ..Evaluation::NONE };
336    /// The layer draws, and may draw in the opaque pass.
337    pub const OPAQUE: Evaluation = Evaluation { opaque: true, ..Evaluation::TRANSLUCENT };
338
339    /// The passes a layer of this evaluation draws in.
340    fn passes(self) -> RenderPass {
341        match self {
342            Evaluation { draws: false, .. } => RenderPass::NONE,
343            Evaluation { opaque: true, .. } => RenderPass::OPAQUE | RenderPass::TRANSLUCENT,
344            Evaluation { opaque: false, .. } => RenderPass::TRANSLUCENT,
345        }
346    }
347}
348
349/// What a layer's [`Layer::evaluate`] reads and completes.
350pub struct EvaluateCx<'a, L: Layer> {
351    /// The layer's values before the evaluation: its style, its paint values
352    /// in transition and their last evaluation.
353    pub values: &'a LayerValues<L::Style>,
354    /// What the values were evaluated for.
355    pub parameters: &'a PropertyEvaluationParameters,
356    /// The new evaluation of the values, which becomes the layer's once the
357    /// hook returns.
358    pub evaluated: &'a mut EvaluatedLayer<L::Style>,
359}
360
361/// How a layer type meets terrain.
362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
363pub enum OnTerrain {
364    /// The layer draws flat, at sea level.
365    Flat,
366    /// The layer drapes over terrain: it draws flat into the terrain tiles'
367    /// textures (`RenderLayer::update_drape_draws`) rather than onto the
368    /// frame.
369    Drapes,
370    /// The layer stands on terrain: over terrain, its draws are of the
371    /// terrain variant ([`ProjectionVariant::stands`]), and their points
372    /// stand on the frame's ground, whose heights a program reads where it
373    /// declares [`GROUND_HEIGHT`](crate::draw::ground::GROUND_HEIGHT). One
374    /// that `hides_behind_ground` hides its points behind the ground in
375    /// front of them, which reads the ground's depth
376    /// ([`GROUND_DEPTH`](crate::draw::ground::GROUND_DEPTH)).
377    Stands { hides_behind_ground: bool },
378}
379
380impl OnTerrain {
381    /// Whether the layer drapes over terrain.
382    pub(crate) fn drapes(self) -> bool {
383        self == OnTerrain::Drapes
384    }
385
386    /// Whether the layer stands on terrain.
387    pub(crate) fn stands(self) -> bool {
388        matches!(self, OnTerrain::Stands { .. })
389    }
390
391    /// Whether the layer hides behind the ground in front of it.
392    pub(crate) fn hides_behind_ground(self) -> bool {
393        self == OnTerrain::Stands { hides_behind_ground: true }
394    }
395}
396
397/// What a layer's [`Layer::prepare`] reads and changes: its base and
398/// values, its values of the tiles it draws (`TileMap`), which the frame
399/// and its drapes share, by the tiles' own ids ([`FrameTile::id`]), and the
400/// frame it makes its draws for, the map's or a drape's.
401pub struct PrepareCx<'a, 'f, L: Layer> {
402    pub base: &'a RenderLayerBase,
403    pub values: &'a LayerValues<L::Style>,
404    pub tiles: &'a mut TileMap<L::Tile>,
405    /// For a layer that picks its tiles ([`Layer::PICKS_TILES`]),
406    /// those the frame draws, in id order: those it picked, or a drape's
407    /// tile. Empty for another layer.
408    pub picked: &'a [OverscaledTileID],
409    /// What the layer makes its meshes and targets with.
410    pub res: Resources<'a>,
411    pub frame: &'a LayerFrame<'f>,
412    /// The frame's shared targets, in the map's frame.
413    pub(crate) targets: Option<&'a mut SharedTargets>,
414}
415
416impl<L: Layer> PrepareCx<'_, '_, L> {
417    /// The texture of the frame's shared target `name`
418    /// ([`Router`](crate::layer::Router)), which the layer's
419    /// draws sample: its texel at `(x, y)` is what the layers routed into it
420    /// drew at the frame's device pixel `(x, y)`; the read orders the
421    /// target's pass before the layer's draws. A layer reads the targets only
422    /// in the map's frame, for its draws over the map: `None` in a drape,
423    /// and, with a warning, for a name that the frame has no target of.
424    pub fn read_target(&mut self, name: &str) -> Option<Texture> {
425        self.targets.as_deref_mut()?.read(&self.base.style.base().id, name)
426    }
427}
428
429/// What a layer's [`Layer::tile`] reads to make a tile's value.
430pub struct TileCx<'a, 'f, L: Layer> {
431    pub base: &'a RenderLayerBase,
432    pub values: &'a LayerValues<L::Style>,
433    /// What the layer makes its meshes and targets with.
434    pub res: Resources<'a>,
435    /// The frame the value is made in: the map's, or for a layer that
436    /// drapes, the drape's that first draws it, whose value every drape
437    /// the tile overlaps draws.
438    pub frame: &'a LayerFrame<'f>,
439}
440
441/// What a layer's [`Layer::update`] reads, besides its tiles.
442pub struct UpdateCx<'a, 'p, L: Layer> {
443    pub values: &'a LayerValues<L::Style>,
444    pub parameters: &'a mut LayerUpdateParameters<'p>,
445    picked: &'a mut Vec<OverscaledTileID>,
446}
447
448impl<L: Layer> UpdateCx<'_, '_, L> {
449    /// The deepest zoom the layer's source has tiles of; `None` for a layer
450    /// without a source or a source without tiles.
451    #[must_use]
452    pub fn source_max_zoom(&self) -> Option<u8> {
453        self.parameters.source.and_then(RenderSource::max_zoom)
454    }
455
456    /// Makes `tiles` those that a layer that picks its tiles
457    /// ([`Layer::PICKS_TILES`]) draws in the map's frame.
458    pub fn pick_tiles(&mut self, tiles: impl IntoIterator<Item = OverscaledTileID>) {
459        debug_assert!(L::PICKS_TILES, "a layer that doesn't pick its tiles picked some");
460        self.picked.clear();
461        self.picked.extend(tiles);
462        self.picked.sort();
463        self.picked.dedup();
464    }
465}
466
467/// A drape a layer draws in: its terrain tile, whether the frame is on the
468/// globe, and the tiles of every drape of the frame, in id order, which a
469/// layer that picks its tiles keeps values of.
470#[derive(Clone, Copy)]
471pub struct DrapeTile<'a> {
472    pub(crate) tile: OverscaledTileID,
473    pub(crate) globe: bool,
474    pub(crate) tiles: &'a [OverscaledTileID],
475}
476
477/// The draws a layer makes in a frame: the map's, which read the frame's
478/// shared targets, or a drape's, into the drape's draws of the layer.
479enum DrawsFor<'d> {
480    Map(&'d mut SharedTargets),
481    Drape(&'d mut Draws, &'d OverscaledTileID),
482}
483
484/// A layer type's render half: what it makes of its values, its tiles'
485/// data and the frame, whose hooks the engine calls on a render layer of the
486/// type (`Hosted`). The engine keeps the layer's base, its values of the
487/// layer type `Type`, its value of each tile it draws, a `Tile`, which the
488/// map's frame and every drape the tile overlaps draw, and its draws
489/// ([`Draws`]) in the frame and in each drape it draws in.
490pub trait Layer: Sized + 'static {
491    /// The type's style half: its name, its kind of source and its
492    /// properties.
493    type Style: StyleLayerType;
494
495    /// What the type's layers draw from: the features of a geometry
496    /// source's tiles, which a layout lays out into a bucket per tile
497    /// ([`Features`](crate::layer::tile_input::Features)), a raster or
498    /// raster-dem source's tiles, or none, for a type without a source
499    /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). Of another kind of
500    /// source than the style half names, the registration doesn't compile.
501    type Input: TileInput<Self::Style>;
502
503    /// What the engine keeps of each tile the layer draws for it, from when
504    /// the layer makes it ([`tile`](Self::tile)) until what the tile shows
505    /// the layer changes.
506    type Tile: 'static;
507
508    /// The order the layer draws its source's tiles in.
509    const TILE_ORDER: TileOrder = TileOrder::ById;
510
511    /// How the layer meets terrain.
512    const TERRAIN: OnTerrain = OnTerrain::Flat;
513
514    /// Whether the layer draws 3D geometry, whose depth it writes in the
515    /// range of `PaintParameters::depth_mode_for_3d`. The layers above the
516    /// lowest such layer that draws draw without a depth test, and on the
517    /// globe the planet's depth hides its geometry behind the horizon.
518    const VOLUME: bool = false;
519
520    /// Whether the frame's draws of the layer can draw into a shared target
521    /// instead of the map
522    /// ([`Router`](crate::layer::Router)): not those of 3D geometry.
523    const ROUTES: bool = !Self::VOLUME;
524
525    /// Whether a layer of a type without a source draws tiles it picks in
526    /// its update ([`UpdateCx::pick_tiles`]), and in a drape the drape's
527    /// tile ([`PrepareCx::picked`]); one that picks none draws nothing. One
528    /// that doesn't pick draws without tiles.
529    const PICKS_TILES: bool = false;
530
531    /// Whether the layer's tile values hold nothing of its style's values,
532    /// so that they stay through a restyle.
533    const RESTYLE_KEEPS_TILES: bool = false;
534
535    /// Whether the type has cross-faded properties, whose evaluation takes
536    /// the frame's cross-fade.
537    const CROSSFADES: bool = false;
538
539    /// Whether the type's layers draw on the tiles that are fading out
540    /// while a placement fades their marks out.
541    const FADES_TILES: bool = false;
542
543    /// Whether the type's layers place their marks, with a participant in
544    /// placement ([`Placement`](crate::placement::Placement)) that registers
545    /// with the type
546    /// ([`add_placing_layer_type`](crate::RegistryBuilder::add_placing_layer_type)).
547    const PLACES: bool = false;
548
549    /// The layer of the values `values`, before they transition.
550    fn new(values: &LayerValues<Self::Style>) -> Self;
551
552    /// Called once the layer's paint values are evaluated for a frame,
553    /// before they become the layer's: the layer derives the values of
554    /// `cx.evaluated` that its type derives from others, remakes what it
555    /// makes of them, such as a color ramp, and says how it draws with them.
556    fn evaluate(&mut self, _cx: EvaluateCx<'_, Self>) -> Evaluation {
557        Evaluation::TRANSLUCENT
558    }
559
560    /// The light that the terrain's surface can shade the layer's drapes
561    /// with in `frame`, whose draws then put in them what it shades
562    /// ([`LayerFrame::drape_lit`]); `None` for a layer whose drapes hold its
563    /// colors.
564    fn surface_light(&mut self, _values: &LayerValues<Self::Style>, _frame: &LayerFrame<'_>) -> Option<SurfaceLight> {
565        None
566    }
567
568    /// Called in the frame's update of the layer with `tiles`, the frame's
569    /// tiles of its source in the order the layer draws them, each with
570    /// what it holds for the layer; none for a type without a source
571    /// ([`NoTiles`](crate::layer::tile_input::NoTiles)). The layer collects
572    /// here what the update needs of its tiles' data; a type that places
573    /// collects what it places in its participant instead
574    /// (`Placement::collect`). One
575    /// without a source that picks its tiles picks them here.
576    fn update(&mut self, _cx: UpdateCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>]) {}
577
578    /// Whether `tile`, a tile's value the layer made, still draws the tile
579    /// with the layer's `values` of the frame. The engine retires a value
580    /// the layer doesn't keep before the layer makes the frame's draws.
581    fn keeps(&self, _values: &LayerValues<Self::Style>, _tile: &Self::Tile) -> bool {
582        true
583    }
584
585    /// The value of `tile`, which holds `data` for the layer, for a tile
586    /// the engine keeps no value of: none where the tile shows nothing to
587    /// draw. The engine keeps it until the tile shows the layer something
588    /// else (another bucket, or contents of another generation), leaves the
589    /// frame, or the layer's draws drop. The map's frame and every drape
590    /// the tile overlaps, in any world copy, draw the same value, so it
591    /// holds nothing of the frame or the copy it is first drawn in.
592    ///
593    /// `previous` is the tile's value before, if the engine retired it
594    /// rather than dropped it: when the tile came to show other contents or
595    /// another generation of them, the layer stopped keeping it
596    /// ([`keeps`](Self::keeps)), or its draws dropped for a restyle or the
597    /// frame's projection. A layer takes from it what it made of contents
598    /// that are still the tile's, such as a texture of the tile's image,
599    /// rather than making them again.
600    fn tile(
601        &mut self,
602        _cx: &mut TileCx<'_, '_, Self>,
603        _tile: FrameTile<'_, Self>,
604        _data: TileData<'_, Self>,
605        _previous: Option<Self::Tile>,
606    ) -> Option<Self::Tile> {
607        None
608    }
609
610    /// Makes the layer's draws of the frame, the map's or a drape's, in the
611    /// frame's encode, of a layer that draws in a pass and has tiles to draw,
612    /// once the engine made the values of the tiles that had none
613    /// ([`tile`](Self::tile)): from `tiles`, the frame's tiles of the layer,
614    /// in the order the update gave them, each with what it holds for the
615    /// layer, or in a drape those that overlap the drape's tile, each in the
616    /// world copy the drape draws it in ([`FrameTile::draw_id`]); none for a
617    /// type without a source, which draws the tiles it picked
618    /// ([`PrepareCx::picked`]). The layer pushes its draws, with the values
619    /// of their blocks, into `out`, which holds no draws yet, and copies
620    /// again into the tile values what changed of their buckets
621    /// (`TileEntry::take_changes`), which every frame that draws them
622    /// then draws. The engine then writes, uploads and draws them, and draws
623    /// the masks of the layer's tiles where a draw clips.
624    fn prepare(&mut self, _cx: &mut PrepareCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>], _out: &mut Draws) {}
625
626    /// Draws with the backend's commands that the frame lends the layer
627    /// `at` its time in the frame, where its draws asked for them
628    /// ([`Draws::lend`]): `lent`, which the layer may use only until this
629    /// returns. A frame without commands to lend, such as one outside a
630    /// pass at [`LendAt::Pass`], lends none.
631    ///
632    /// What the layer makes with the commands, the engine doesn't know of:
633    /// the layer frees it through work it queues for after the GPU
634    /// ([`Lent::after_gpu`]), at the latest as it drops, which is when it
635    /// leaves the renderer.
636    fn lend(&mut self, _at: LendAt, _lent: Lent<'_>) {}
637
638    /// How far outside a feature of `data`, a tile's bucket of the layer, a
639    /// query still hits it, from `layer`'s current values and the bucket's
640    /// statistics of them. The engine asks only a type whose input lays
641    /// out.
642    fn query_radius(_data: TileData<'_, Self>, _layer: &EvaluatedLayer<Self::Style>) -> f32 {
643        0.0
644    }
645
646    /// Whether a query hits the feature `feature` with `geometry`, with
647    /// `feature_state`: whether it intersects `region` of its tile as the
648    /// layer of `values` draws it at the view's zoom; a miss unless a layer
649    /// type overrides it. A type whose features stand at points and hide
650    /// behind the ground ([`OnTerrain::Stands`]) hits only those that show,
651    /// which [`QueryRegion::shows`] tells. A type that draws 3D geometry
652    /// ([`Layer::VOLUME`]) tells how far from the camera it hits
653    /// ([`Hit::At`]).
654    fn hit(
655        &self,
656        _values: &LayerValues<Self::Style>,
657        _region: &QueryRegion<'_>,
658        _feature: &dyn mln_style::feature::GeometryTileFeature,
659        _geometry: &mln_style::feature::GeometryCollection,
660        _feature_state: &mln_style::feature::FeatureState,
661    ) -> Hit {
662        Hit::Miss
663    }
664
665    /// Adds to `hits` the features that `query`'s geometry hits of what the
666    /// layer shows other than its tiles' features, such as a mark it places
667    /// itself, topmost first. As for tiles' features, a query answers for
668    /// the last update: the engine asks a layer that the update would draw,
669    /// with its view and values, which may come before a frame draws them,
670    /// so a layer answers from `query` rather than from what it kept from
671    /// drawing. The engine names the features' layer and source and keeps
672    /// those that the query's filter takes.
673    fn hit_frame(&self, _query: &FrameQuery<'_, Self>, _hits: &mut Vec<Feature>) {}
674}
675
676/// A rendered-feature query of a layer `L`, for what it shows other than
677/// its tiles' features, as of the last update ([`Layer::hit_frame`]).
678pub struct FrameQuery<'a, L: Layer> {
679    values: &'a LayerValues<L::Style>,
680    view: &'a View,
681    geometry: &'a [ScreenCoordinate],
682    ground: Option<&'a TerrainElevation>,
683}
684
685impl<'a, L: Layer> FrameQuery<'a, L> {
686    /// The layer's values of the last update.
687    #[must_use]
688    pub fn values(&self) -> &'a LayerValues<L::Style> {
689        self.values
690    }
691
692    /// The last update's camera and projection.
693    #[must_use]
694    pub fn view(&self) -> &'a View {
695        self.view
696    }
697
698    /// The query's geometry, in the view's logical pixels from its top left:
699    /// one point, or a closed ring.
700    #[must_use]
701    pub fn geometry(&self) -> &'a [ScreenCoordinate] {
702        self.geometry
703    }
704
705    /// Over terrain, the ground the frame drew under the points of `tile`,
706    /// for a layer that meets terrain ([`Layer::TERRAIN`]); `None` without
707    /// terrain or for a layer that draws flat.
708    #[must_use]
709    pub fn ground(&self, tile: UnwrappedTileID) -> Option<TileGround<'a>> {
710        self.ground.map(|ground| TileGround::new(ground, tile))
711    }
712}
713
714/// A render layer of a [`Layer`] `L`: the layer, and what the engine
715/// keeps of it, its base, its values, its tile values and its draws of the
716/// map's frame.
717pub(crate) struct Hosted<L: Layer> {
718    base: RenderLayerBase,
719    values: LayerValues<L::Style>,
720    tiles: TileMap<L::Tile>,
721    /// The tiles that a layer that picks its tiles picked in its update,
722    /// in id order, which it draws in the map's frame.
723    picked: Vec<OverscaledTileID>,
724    draws: Draws,
725    layer: L,
726}
727
728impl<L: Layer> Hosted<L> {
729    /// The render layer of the layer `style`, before its values transition.
730    pub(crate) fn new(style: Arc<LayerStyle<L::Style>>) -> Self {
731        let (base, values) = LayerValues::new(style, entry::<L>());
732        let layer = L::new(&values);
733        Hosted { base, values, tiles: TileMap::default(), picked: Vec::new(), draws: Draws::default(), layer }
734    }
735
736    /// [`new`](Self::new), boxed as a [`RenderLayer`].
737    pub(crate) fn boxed(style: Arc<LayerStyle<L::Style>>) -> Box<dyn RenderLayer> {
738        Box::new(Self::new(style))
739    }
740
741    /// The layer and its values, which benchmarks fill as the layer's
742    /// update would.
743    #[cfg(feature = "bench")]
744    pub(crate) fn layer_mut(&mut self) -> (&mut L, &LayerValues<L::Style>) {
745        (&mut self.layer, &self.values)
746    }
747
748    /// Makes `variant` the projection the layer draws in: where its draws
749    /// were of another, drops them and retires its tile values.
750    fn use_projection_variant(&mut self, variant: ProjectionVariant) {
751        if variant != self.base.projection_variant {
752            self.base.projection_variant = variant;
753            self.retire_draws();
754        }
755    }
756
757    /// Drops the frame's draws of the layer and retires its tile values,
758    /// which the next values of their tiles may take from: until the
759    /// layer's next draws are done, the draws keep what they kept for the
760    /// retired values' meshes. The tiles stay.
761    fn retire_draws(&mut self) {
762        self.tiles.retire();
763        self.draws.clear();
764    }
765
766    /// Readies the values of `tiles`, the tiles the layer draws, before the
767    /// layer makes its draws of them: retires each that was made from
768    /// something else than what its tile shows the layer, or that the layer
769    /// doesn't keep ([`Layer::keeps`]), and makes those the layer has
770    /// none of ([`Layer::tile`]), from their previous values. For a
771    /// layer that picks its tiles, retires those of its picked tiles that it
772    /// doesn't keep.
773    fn ready_tiles(
774        &mut self,
775        gpu: &mut dyn Gpu,
776        context: &mut Context,
777        frame: &LayerFrame<'_>,
778        tiles: &[FrameTile<'_, L>],
779    ) {
780        let Hosted { base, values, tiles: map, layer, .. } = self;
781        if !has_tiles::<L>() {
782            for (_, mut entry) in map.entries() {
783                if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
784                    entry.retire();
785                }
786            }
787            return;
788        }
789        for &tile in tiles {
790            let Some(mut entry) = map.entry(&tile.id()) else { continue };
791            entry.show(tile.made_from());
792            if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
793                entry.retire();
794            }
795            if entry.value.is_none()
796                && let Some(data) = tile.data()
797            {
798                // A new value copies its bucket as it is.
799                entry.take_changes();
800                let previous = entry.take_previous();
801                let res = Resources::new(&mut *gpu, &mut *context);
802                *entry.value = layer.tile(&mut TileCx { base, values, res, frame }, tile, data, previous);
803            }
804        }
805    }
806
807    /// Makes the layer's draws of `into`'s frame, the map's or a drape's,
808    /// if it draws in a pass: starts them, readies its tile values of
809    /// `tiles` ([`ready_tiles`](Self::ready_tiles)), runs its
810    /// [`Layer::prepare`] and writes the buffers of the draws it made,
811    /// with the paint parameters of `parameters`' frame where it has its own
812    /// (a drape's), and the masks of `tiles` where a draw clips. One that
813    /// draws in no pass with its values of the frame draws nothing, and
814    /// keeps its tile values.
815    fn draw(
816        &mut self,
817        gpu: &mut dyn Gpu,
818        parameters: &mut PaintParameters<'_>,
819        tiles: &[FrameTile<'_, L>],
820        into: DrawsFor<'_>,
821    ) {
822        if self.values.evaluated.render_passes == RenderPass::NONE.bits() {
823            match into {
824                DrawsFor::Map(_) => self.draws.begin(),
825                DrawsFor::Drape(draws, _) => draws.begin(),
826            }
827            return;
828        }
829        let frame = parameters.frame();
830        self.ready_tiles(gpu, parameters.context, &frame, tiles);
831        let Hosted { base, values, tiles: map, picked, draws, layer } = self;
832        let (draws, picked, targets) = match into {
833            DrawsFor::Map(targets) => (draws, &picked[..], Some(targets)),
834            DrawsFor::Drape(draws, tile) => (draws, std::slice::from_ref(tile), None),
835        };
836        draws.begin();
837        let res = Resources::new(&mut *gpu, &mut *parameters.context);
838        layer.prepare(&mut PrepareCx { base, values, tiles: map, picked, res, frame: &frame, targets }, tiles, draws);
839        let paint_params = parameters.own_paint_params();
840        let clip_tiles = tiles.iter().map(|tile| tile.draw_id().to_unwrapped());
841        draws.finish(gpu, parameters.context, paint_params.as_ref(), clip_tiles);
842    }
843}
844
845/// Lends `layer` the backend's commands of `gpu` `at` its time in the frame
846/// of `parameters`, where the frame has them to lend: in a pass, the open
847/// one. A lend that fails fails the frame.
848fn lend<L: Layer>(layer: &mut L, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, at: LendAt) {
849    let Some(projection) = parameters.lent_projection else { return };
850    let frame = parameters.frame();
851    let layer_depth = match at {
852        LendAt::BeforePasses => None,
853        LendAt::Pass if parameters.pass_target().is_some() => Some(f64::from(parameters.layer_depth())),
854        LendAt::Pass => return,
855    };
856    let after_gpu = parameters.context.after_gpu().handle();
857    let lent = gpu
858        .lend(&mut |raw| layer.lend(at, Lent { raw, frame: &frame, projection: &projection, layer_depth, after_gpu }));
859    if let Err(error) = lent {
860        parameters.context.fail(format!("Lending a layer the frame's commands failed: {error}"));
861    }
862}
863
864/// Whether layers of `L`'s type draw from their source's tiles: false for a
865/// type without a source.
866fn has_tiles<L: Layer>() -> bool {
867    <L::Input as Find<L::Style>>::KIND != SourceKind::None
868}
869
870/// What the engine does with a render layer, whatever its type: its base,
871/// its values, which this transitions without knowing their type, its tile
872/// values and its draws, which it writes, uploads and draws. It runs
873/// the layer's [`Layer`] hooks with what is common to every layer type
874/// around them.
875pub trait RenderLayer {
876    fn base(&self) -> &RenderLayerBase;
877
878    /// The layer's id.
879    fn id(&self) -> &str {
880        &self.base().style.base().id
881    }
882
883    /// The order the layer draws its source's tiles in.
884    fn tile_order(&self) -> TileOrder;
885
886    /// Makes `style`, the changed style of the layer (of the same id and
887    /// type), the layer's, drops the draws, which were built for the
888    /// previous style's values, with the tile values unless the layer keeps
889    /// them ([`Layer::RESTYLE_KEEPS_TILES`]), and begins transitions to
890    /// the new values. A style of another type leaves the layer's. The next
891    /// encode builds the draws again from the tiles' buckets.
892    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>);
893
894    /// Begins transitions for the paint values that changed since the last
895    /// frame, to those of the layer's style.
896    fn transition(&mut self, parameters: &TransitionParameters);
897
898    /// Evaluates the layer's paint values for a frame of `parameters`,
899    /// which the layer completes ([`Layer::evaluate`]), and sets the
900    /// passes the layer draws in with them.
901    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters);
902
903    /// Whether a paint value of the layer is still in transition.
904    fn has_transition(&self) -> bool;
905
906    /// Whether the layer has a pattern property and is in a cross-fade.
907    fn has_crossfade(&self) -> bool;
908
909    /// The frame's update of the layer: finds the tiles of `parameters`'
910    /// source the layer draws, which it adds to `parameters.found`, adds the
911    /// passes their buckets were laid out for to the layer's, runs the
912    /// layer's [`Layer::update`], and keeps entries for the tiles; or,
913    /// for a type without a source, runs its update without tiles.
914    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>);
915
916    /// The encode's update of the layer's draws: picks the shader variant
917    /// for the frame's projection, standing on the frame's ground where the
918    /// layer stands and the frame has one, dropping the draws and tile values
919    /// when it changed; drops them of a layer that has nothing to draw, and
920    /// otherwise starts its draws of the frame; for a layer that draws in a
921    /// pass, readies the tile values and runs the layer's
922    /// [`Layer::prepare`] with the tiles of its type that its update
923    /// found in `source`, or none for a type without a source, and writes
924    /// the buffers of its draws.
925    fn update_draws(
926        &mut self,
927        gpu: &mut dyn Gpu,
928        parameters: &mut PaintParameters<'_>,
929        source: Option<FrameSourceTiles<'_>>,
930        targets: &mut SharedTargets,
931    );
932
933    /// How the layer meets terrain ([`Layer::TERRAIN`]).
934    fn terrain(&self) -> OnTerrain;
935
936    /// Whether the layer draws 3D geometry ([`Layer::VOLUME`]).
937    fn volume(&self) -> bool;
938
939    /// Whether the layer's draws can draw into a shared target
940    /// ([`Layer::ROUTES`]).
941    fn routes(&self) -> bool;
942
943    /// Makes `route` the shared target that the frame's draws of the layer
944    /// draw into instead of the map, or with `None` the map.
945    fn set_route(&mut self, route: Option<usize>);
946
947    /// Whether the layer's blend with its values of the frame reads what is
948    /// drawn beneath it, which a shared target's pass can't give it.
949    fn reads_backdrop(&self) -> bool;
950
951    /// Whether the layer blends with what is under it otherwise than by
952    /// covering it, with its values of the frame: a layer blend
953    /// ([`StyleLayerType::layer_blend`]) other than `normal`.
954    fn blends(&self) -> bool;
955
956    /// The light the terrain's surface can shade the layer's drapes with
957    /// ([`Layer::surface_light`]).
958    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight>;
959
960    /// Where the tiles the layer's update found are among the frame's
961    /// ([`LayerUpdateParameters::found`]); `None` for a type without a
962    /// source.
963    fn found(&self) -> Option<Range<usize>>;
964
965    /// The encode's update of the layer's draws into `drape`, `draws`, as
966    /// [`update_draws`](Self::update_draws) makes the frame's, with the
967    /// drape's `parameters`, from the tiles of `source` the layer's update
968    /// found that overlap the drape's tile
969    /// ([`FrameSourceTiles::overlapping`]), or from the drape's tile itself
970    /// for a type without a source that picks its tiles, in the Mercator
971    /// projection, a drape's. The drape draws the layer's tile values,
972    /// which the frame's other drapes share: for a layer that picks its
973    /// tiles, those of the tiles of every drape.
974    fn update_drape_draws(
975        &mut self,
976        gpu: &mut dyn Gpu,
977        parameters: &mut PaintParameters<'_>,
978        source: Option<FrameSourceTiles<'_>>,
979        drape: DrapeTile<'_>,
980        draws: &mut Draws,
981    );
982
983    /// Records that the buckets in `changed` changed, for the tiles whose
984    /// values were made from them.
985    fn mark_changed(&mut self, changed: &ChangedBuckets);
986
987    /// Moves the layer's value of each tile to the tile `wrap_delta` world
988    /// copies east of it: the tiles are the same ones under new ids once the
989    /// map's center has crossed the antimeridian, and their values stay
990    /// rather than being made again.
991    fn handle_wrap_jump(&mut self, wrap_delta: i16);
992
993    /// Includes the layer in the frame's drawing or excludes it. A layer
994    /// excluded drops its draws and its tiles with their values, previous
995    /// ones too: its updates don't run until it is included again, and they
996    /// then rebuild everything from the source's tiles.
997    fn set_renderable(&mut self, renderable: bool);
998
999    /// Drops the layer's tile values, previous ones too, and the frame's
1000    /// draws of the layer, which then let go of what they kept for the
1001    /// values' meshes. The tiles stay.
1002    fn remove_all_draws(&mut self);
1003
1004    /// Drops the map frame's draws of the layer, which a frame over terrain
1005    /// draws only in drapes; its tile values stay, for the drapes.
1006    fn remove_frame_draws(&mut self);
1007
1008    /// Visits the groups of the layer's draws of the frame that take a place
1009    /// in the layers' order and depth, in drawing order: none unless the
1010    /// frame draws the layer. They are the groups `upload` and `render`
1011    /// upload and draw.
1012    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group));
1013
1014    /// Uploads the meshes of the layer's draws, before the frame draws them.
1015    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context);
1016
1017    /// Draws the pass's draws of the layer's groups into the open pass of
1018    /// `gpu`, the context's, in `order`, each at its depth, and, in the
1019    /// translucent pass, lends the layer the pass after its main group where
1020    /// its draws asked for it ([`LendAt::Pass`]): the map's pass, or with
1021    /// `routed` the pass of the shared target the layer is routed into. In
1022    /// the other, the layer takes its depth and draws nothing.
1023    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool);
1024
1025    /// Before the frame's passes, outside any pass of `gpu`, the context's:
1026    /// draws into the targets of the layer's draws of the frame
1027    /// ([`Draws::target`]), and then lends the layer the frame's commands
1028    /// where its draws asked for them ([`LendAt::BeforePasses`]).
1029    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>);
1030
1031    /// See [`Layer::hit`].
1032    fn hit(
1033        &self,
1034        region: &QueryRegion<'_>,
1035        feature: &dyn mln_style::feature::GeometryTileFeature,
1036        geometry: &mln_style::feature::GeometryCollection,
1037        feature_state: &mln_style::feature::FeatureState,
1038    ) -> Hit;
1039
1040    /// See [`Layer::hit_frame`]: what `geometry`, in `view`'s logical pixels,
1041    /// hits of what the layer shows, over `ground` where the map has
1042    /// terrain. Nothing for a layer the last update wouldn't draw.
1043    fn hit_frame(
1044        &self,
1045        view: &View,
1046        geometry: &[ScreenCoordinate],
1047        ground: Option<&TerrainElevation>,
1048        hits: &mut Vec<Feature>,
1049    );
1050
1051    /// Whether the layer draws in a pass and is visible.
1052    fn needs_rendering(&self) -> bool {
1053        self.base().passes != RenderPass::NONE && self.base().style.base().visibility != VisibilityType::None
1054    }
1055
1056    /// Whether the layer draws at `zoom`. A minimum zoom of 0 is no
1057    /// minimum: the globe zooms below 0 toward the poles.
1058    fn supports_zoom(&self, zoom: f64) -> bool {
1059        let zoom_or_zero = if zoom < 0.0 { 0.0 } else { zoom };
1060        let style = self.base().style.base();
1061        style.min_zoom <= zoom_or_zero && zoom < style.max_zoom
1062    }
1063
1064    /// Whether the frame draws the layer.
1065    fn is_renderable(&self) -> bool {
1066        self.base().is_renderable
1067    }
1068
1069    /// What the layer's paint values depend on.
1070    fn style_dependencies(&self) -> Dependency {
1071        self.base().style_dependencies
1072    }
1073}
1074
1075impl<L: Layer> RenderLayer for Hosted<L> {
1076    fn base(&self) -> &RenderLayerBase {
1077        &self.base
1078    }
1079
1080    fn tile_order(&self) -> TileOrder {
1081        L::TILE_ORDER
1082    }
1083
1084    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>) {
1085        if L::RESTYLE_KEEPS_TILES {
1086            self.draws.clear();
1087        } else {
1088            self.retire_draws();
1089        }
1090        if let Some(recovered) = LayerStyle::recover(style) {
1091            self.values.style = recovered;
1092            self.base.style = Arc::clone(style);
1093        }
1094        self.transition(parameters);
1095    }
1096
1097    fn transition(&mut self, parameters: &TransitionParameters) {
1098        let values = &mut self.values;
1099        let prior = std::mem::take(&mut values.unevaluated);
1100        values.unevaluated = values.style.paint.transitioned(parameters, prior);
1101        self.base.style_dependencies = <L::Style as StyleLayerType>::PaintProperties::dependencies(&values.unevaluated);
1102    }
1103
1104    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters) {
1105        let mut evaluated = self.values.evaluate(parameters, L::CROSSFADES);
1106        let evaluation =
1107            self.layer.evaluate(EvaluateCx { values: &self.values, parameters, evaluated: &mut evaluated });
1108        self.base.passes = evaluation.passes();
1109        self.base.evaluation = evaluation;
1110        self.values.set_evaluated(&mut self.base, evaluated);
1111    }
1112
1113    fn has_transition(&self) -> bool {
1114        <L::Style as StyleLayerType>::PaintProperties::has_transition(&self.values.unevaluated)
1115    }
1116
1117    fn has_crossfade(&self) -> bool {
1118        L::CROSSFADES && self.values.evaluated.crossfade.t != 1.0
1119    }
1120
1121    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>) {
1122        let Hosted { base, values, tiles: map, picked, layer, .. } = self;
1123        if !has_tiles::<L>() {
1124            layer.update(UpdateCx { values, parameters, picked }, &[]);
1125            return;
1126        }
1127        let start = parameters.found.len();
1128        let tiles = match parameters.tiles(L::TILE_ORDER) {
1129            Some((tiles, order)) => tiles.find::<L>(order, &base.style.base().id, parameters.found),
1130            None => FrameTiles::new(),
1131        };
1132        base.found = start..parameters.found.len();
1133        for data in tiles.iter().filter_map(|tile| tile.data()) {
1134            base.passes |= <L::Input as Find<L::Style>>::passes(data);
1135        }
1136        layer.update(UpdateCx { values, parameters, picked }, &tiles);
1137        map.set_tiles(tiles.iter().map(|tile| tile.id()));
1138    }
1139
1140    fn update_draws(
1141        &mut self,
1142        gpu: &mut dyn Gpu,
1143        parameters: &mut PaintParameters<'_>,
1144        source: Option<FrameSourceTiles<'_>>,
1145        targets: &mut SharedTargets,
1146    ) {
1147        let stands = L::TERRAIN.stands() && parameters.ground.is_some();
1148        self.use_projection_variant(ProjectionVariant::new(parameters.view.is_globe(), stands));
1149        if !has_tiles::<L>() {
1150            // A layer that picks tiles draws those its update picked.
1151            if L::PICKS_TILES {
1152                self.tiles.set_tiles(self.picked.iter().copied());
1153            }
1154            if L::PICKS_TILES && self.tiles.is_empty() {
1155                self.remove_all_draws();
1156            } else {
1157                self.draw(gpu, parameters, &[], DrawsFor::Map(targets));
1158            }
1159            return;
1160        }
1161        match source.map(|source| (source, source.found(self.base.found.clone()))) {
1162            Some((source, found)) if !found.is_empty() => {
1163                let tiles = source.at::<L>(found, self.id());
1164                self.draw(gpu, parameters, &tiles, DrawsFor::Map(targets));
1165            }
1166            _ => self.remove_all_draws(),
1167        }
1168    }
1169
1170    fn terrain(&self) -> OnTerrain {
1171        L::TERRAIN
1172    }
1173
1174    fn volume(&self) -> bool {
1175        L::VOLUME
1176    }
1177
1178    fn routes(&self) -> bool {
1179        L::ROUTES
1180    }
1181
1182    fn set_route(&mut self, route: Option<usize>) {
1183        self.base.route = route;
1184    }
1185
1186    fn reads_backdrop(&self) -> bool {
1187        crate::render::layer_composite::reads_backdrop(L::Style::layer_blend(&self.values.evaluated.paint))
1188    }
1189
1190    fn blends(&self) -> bool {
1191        L::Style::layer_blend(&self.values.evaluated.paint) != LayerBlendType::Normal
1192    }
1193
1194    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight> {
1195        self.layer.surface_light(&self.values, &parameters.frame())
1196    }
1197
1198    fn found(&self) -> Option<Range<usize>> {
1199        has_tiles::<L>().then(|| self.base.found.clone())
1200    }
1201
1202    fn update_drape_draws(
1203        &mut self,
1204        gpu: &mut dyn Gpu,
1205        parameters: &mut PaintParameters<'_>,
1206        source: Option<FrameSourceTiles<'_>>,
1207        drape: DrapeTile<'_>,
1208        draws: &mut Draws,
1209    ) {
1210        // Only a layer that drapes builds the code of its draws in a drape.
1211        if !L::TERRAIN.drapes() {
1212            debug_assert!(false, "a layer that doesn't drape in a drape");
1213            return;
1214        }
1215        // A drape is flat: the layer's draws are Mercator's.
1216        self.use_projection_variant(ProjectionVariant::Mercator);
1217        if !has_tiles::<L>() {
1218            if L::PICKS_TILES {
1219                self.tiles.set_tiles(drape.tiles.iter().copied());
1220            }
1221            self.draw(gpu, parameters, &[], DrawsFor::Drape(draws, &drape.tile));
1222            return;
1223        }
1224        let tiles = match source {
1225            Some(source) => {
1226                source.overlapping::<L>(self.base.found.clone(), self.id(), drape.tile.to_unwrapped(), drape.globe)
1227            }
1228            None => FrameTiles::new(),
1229        };
1230        if tiles.is_empty() {
1231            draws.clear();
1232        } else {
1233            self.draw(gpu, parameters, &tiles, DrawsFor::Drape(draws, &drape.tile));
1234        }
1235    }
1236
1237    fn mark_changed(&mut self, changed: &ChangedBuckets) {
1238        self.tiles.mark_changed(changed);
1239    }
1240
1241    fn handle_wrap_jump(&mut self, wrap_delta: i16) {
1242        self.tiles.shift_wraps(wrap_delta);
1243    }
1244
1245    fn set_renderable(&mut self, renderable: bool) {
1246        self.base.is_renderable = renderable;
1247        if !renderable {
1248            self.tiles.clear_tiles();
1249            self.draws.clear();
1250        }
1251    }
1252
1253    fn remove_all_draws(&mut self) {
1254        self.tiles.clear();
1255        self.draws.clear();
1256    }
1257
1258    fn remove_frame_draws(&mut self) {
1259        self.draws.clear();
1260    }
1261
1262    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
1263        if self.base.is_renderable {
1264            self.draws.visit_groups(visit);
1265        }
1266    }
1267
1268    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
1269        if self.base.is_renderable {
1270            self.draws.upload(gpu, context);
1271        }
1272    }
1273
1274    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool) {
1275        let Hosted { base, draws, layer, .. } = self;
1276        if base.is_renderable && base.route.is_some() != routed {
1277            draws.skip(parameters, order);
1278        } else if base.is_renderable {
1279            let lends = draws.lends(LendAt::Pass) && parameters.pass == RenderPass::TRANSLUCENT;
1280            let mut lend_pass = |gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>| {
1281                lend(layer, gpu, parameters, LendAt::Pass);
1282            };
1283            draws.render(gpu, parameters, order, lends.then_some(&mut lend_pass));
1284        }
1285    }
1286
1287    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
1288        if self.base.is_renderable {
1289            self.draws.render_targets(gpu, parameters);
1290            if self.draws.lends(LendAt::BeforePasses) {
1291                lend(&mut self.layer, gpu, parameters, LendAt::BeforePasses);
1292            }
1293        }
1294    }
1295
1296    fn hit(
1297        &self,
1298        region: &QueryRegion<'_>,
1299        feature: &dyn mln_style::feature::GeometryTileFeature,
1300        geometry: &mln_style::feature::GeometryCollection,
1301        feature_state: &mln_style::feature::FeatureState,
1302    ) -> Hit {
1303        self.layer.hit(&self.values, region, feature, geometry, feature_state)
1304    }
1305
1306    fn hit_frame(
1307        &self,
1308        view: &View,
1309        geometry: &[ScreenCoordinate],
1310        ground: Option<&TerrainElevation>,
1311        hits: &mut Vec<Feature>,
1312    ) {
1313        if self.base.is_renderable {
1314            let ground = ground.filter(|_| L::TERRAIN != OnTerrain::Flat);
1315            self.layer.hit_frame(&FrameQuery { values: &self.values, view, geometry, ground }, hits);
1316        }
1317    }
1318}