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::SharedTexture;
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::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.get_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.underlying_type();
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<SharedTexture> {
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; false unless a layer
649    /// type overrides it.
650    fn hit(
651        &self,
652        _values: &LayerValues<Self::Style>,
653        _region: &QueryRegion<'_>,
654        _feature: &dyn mln_style::feature::GeometryTileFeature,
655        _geometry: &mln_style::feature::GeometryCollection,
656        _feature_state: &mln_style::feature::FeatureState,
657    ) -> bool {
658        false
659    }
660
661    /// Adds to `hits` the features that `query`'s geometry hits of what the
662    /// layer shows other than its tiles' features, such as a mark it places
663    /// itself, topmost first. As for tiles' features, a query answers for
664    /// the last update: the engine asks a layer that the update would draw,
665    /// with its view and values, which may come before a frame draws them,
666    /// so a layer answers from `query` rather than from what it kept from
667    /// drawing. The engine names the features' layer and source and keeps
668    /// those that the query's filter takes.
669    fn hit_frame(&self, _query: &FrameQuery<'_, Self>, _hits: &mut Vec<Feature>) {}
670}
671
672/// A rendered-feature query of a layer `L`, for what it shows other than
673/// its tiles' features, as of the last update ([`Layer::hit_frame`]).
674pub struct FrameQuery<'a, L: Layer> {
675    values: &'a LayerValues<L::Style>,
676    view: &'a View,
677    geometry: &'a [ScreenCoordinate],
678    ground: Option<&'a TerrainElevation>,
679}
680
681impl<'a, L: Layer> FrameQuery<'a, L> {
682    /// The layer's values of the last update.
683    #[must_use]
684    pub fn values(&self) -> &'a LayerValues<L::Style> {
685        self.values
686    }
687
688    /// The last update's camera and projection.
689    #[must_use]
690    pub fn view(&self) -> &'a View {
691        self.view
692    }
693
694    /// The query's geometry, in the view's logical pixels from its top left:
695    /// one point, or a closed ring.
696    #[must_use]
697    pub fn geometry(&self) -> &'a [ScreenCoordinate] {
698        self.geometry
699    }
700
701    /// Over terrain, the ground the frame drew under the points of `tile`,
702    /// for a layer that meets terrain ([`Layer::TERRAIN`]); `None` without
703    /// terrain or for a layer that draws flat.
704    #[must_use]
705    pub fn ground(&self, tile: UnwrappedTileID) -> Option<TileGround<'a>> {
706        self.ground.map(|ground| TileGround::new(ground, tile))
707    }
708}
709
710/// A render layer of a [`Layer`] `L`: the layer, and what the engine
711/// keeps of it, its base, its values, its tile values and its draws of the
712/// map's frame.
713pub(crate) struct Hosted<L: Layer> {
714    base: RenderLayerBase,
715    values: LayerValues<L::Style>,
716    tiles: TileMap<L::Tile>,
717    /// The tiles that a layer that picks its tiles picked in its update,
718    /// in id order, which it draws in the map's frame.
719    picked: Vec<OverscaledTileID>,
720    draws: Draws,
721    layer: L,
722}
723
724impl<L: Layer> Hosted<L> {
725    /// The render layer of the layer `style`, before its values transition.
726    pub(crate) fn new(style: Arc<LayerStyle<L::Style>>) -> Self {
727        let (base, values) = LayerValues::new(style, entry::<L>());
728        let layer = L::new(&values);
729        Hosted { base, values, tiles: TileMap::default(), picked: Vec::new(), draws: Draws::default(), layer }
730    }
731
732    /// [`new`](Self::new), boxed as a [`RenderLayer`].
733    pub(crate) fn boxed(style: Arc<LayerStyle<L::Style>>) -> Box<dyn RenderLayer> {
734        Box::new(Self::new(style))
735    }
736
737    /// The layer and its values, which benchmarks fill as the layer's
738    /// update would.
739    #[cfg(feature = "bench")]
740    pub(crate) fn layer_mut(&mut self) -> (&mut L, &LayerValues<L::Style>) {
741        (&mut self.layer, &self.values)
742    }
743
744    /// Makes `variant` the projection the layer draws in: where its draws
745    /// were of another, drops them and retires its tile values.
746    fn use_projection_variant(&mut self, variant: ProjectionVariant) {
747        if variant != self.base.projection_variant {
748            self.base.projection_variant = variant;
749            self.retire_draws();
750        }
751    }
752
753    /// Drops the frame's draws of the layer and retires its tile values,
754    /// which the next values of their tiles may take from: until the
755    /// layer's next draws are done, the draws keep what they kept for the
756    /// retired values' meshes. The tiles stay.
757    fn retire_draws(&mut self) {
758        self.tiles.retire();
759        self.draws.clear();
760    }
761
762    /// Readies the values of `tiles`, the tiles the layer draws, before the
763    /// layer makes its draws of them: retires each that was made from
764    /// something else than what its tile shows the layer, or that the layer
765    /// doesn't keep ([`Layer::keeps`]), and makes those the layer has
766    /// none of ([`Layer::tile`]), from their previous values. For a
767    /// layer that picks its tiles, retires those of its picked tiles that it
768    /// doesn't keep.
769    fn ready_tiles(
770        &mut self,
771        gpu: &mut dyn Gpu,
772        context: &mut Context,
773        frame: &LayerFrame<'_>,
774        tiles: &[FrameTile<'_, L>],
775    ) {
776        let Hosted { base, values, tiles: map, layer, .. } = self;
777        if !has_tiles::<L>() {
778            for (_, mut entry) in map.entries() {
779                if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
780                    entry.retire();
781                }
782            }
783            return;
784        }
785        for &tile in tiles {
786            let Some(mut entry) = map.entry(&tile.id()) else { continue };
787            entry.show(tile.made_from());
788            if entry.value.as_ref().is_some_and(|value| !layer.keeps(values, value)) {
789                entry.retire();
790            }
791            if entry.value.is_none()
792                && let Some(data) = tile.data()
793            {
794                // A new value copies its bucket as it is.
795                entry.take_changes();
796                let previous = entry.take_previous();
797                let res = Resources::new(&mut *gpu, &mut *context);
798                *entry.value = layer.tile(&mut TileCx { base, values, res, frame }, tile, data, previous);
799            }
800        }
801    }
802
803    /// Makes the layer's draws of `into`'s frame, the map's or a drape's,
804    /// if it draws in a pass: starts them, readies its tile values of
805    /// `tiles` ([`ready_tiles`](Self::ready_tiles)), runs its
806    /// [`Layer::prepare`] and writes the buffers of the draws it made,
807    /// with the paint parameters of `parameters`' frame where it has its own
808    /// (a drape's), and the masks of `tiles` where a draw clips. One that
809    /// draws in no pass with its values of the frame draws nothing, and
810    /// keeps its tile values.
811    fn draw(
812        &mut self,
813        gpu: &mut dyn Gpu,
814        parameters: &mut PaintParameters<'_>,
815        tiles: &[FrameTile<'_, L>],
816        into: DrawsFor<'_>,
817    ) {
818        if self.values.evaluated.render_passes == RenderPass::None.underlying_type() {
819            match into {
820                DrawsFor::Map(_) => self.draws.begin(),
821                DrawsFor::Drape(draws, _) => draws.begin(),
822            }
823            return;
824        }
825        let frame = parameters.frame();
826        self.ready_tiles(gpu, parameters.context, &frame, tiles);
827        let Hosted { base, values, tiles: map, picked, draws, layer } = self;
828        let (draws, picked, targets) = match into {
829            DrawsFor::Map(targets) => (draws, &picked[..], Some(targets)),
830            DrawsFor::Drape(draws, tile) => (draws, std::slice::from_ref(tile), None),
831        };
832        draws.begin();
833        let res = Resources::new(&mut *gpu, &mut *parameters.context);
834        layer.prepare(&mut PrepareCx { base, values, tiles: map, picked, res, frame: &frame, targets }, tiles, draws);
835        let paint_params = parameters.own_paint_params();
836        let clip_tiles = tiles.iter().map(|tile| tile.draw_id().to_unwrapped());
837        draws.finish(gpu, parameters.context, paint_params.as_ref(), clip_tiles);
838    }
839}
840
841/// Lends `layer` the backend's commands of `gpu` `at` its time in the frame
842/// of `parameters`, where the frame has them to lend: in a pass, the open
843/// one. A lend that fails fails the frame.
844fn lend<L: Layer>(layer: &mut L, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, at: LendAt) {
845    let Some(projection) = parameters.lent_projection else { return };
846    let frame = parameters.frame();
847    let layer_depth = match at {
848        LendAt::BeforePasses => None,
849        LendAt::Pass if parameters.pass_target().is_some() => Some(f64::from(parameters.layer_depth())),
850        LendAt::Pass => return,
851    };
852    let after_gpu = parameters.context.after_gpu().handle();
853    let lent = gpu
854        .lend(&mut |raw| layer.lend(at, Lent { raw, frame: &frame, projection: &projection, layer_depth, after_gpu }));
855    if let Err(error) = lent {
856        parameters.context.fail(format!("Lending a layer the frame's commands failed: {error}"));
857    }
858}
859
860/// Whether layers of `L`'s type draw from their source's tiles: false for a
861/// type without a source.
862fn has_tiles<L: Layer>() -> bool {
863    <L::Input as Find<L::Style>>::KIND != SourceKind::None
864}
865
866/// What the engine does with a render layer, whatever its type: its base,
867/// its values, which this transitions without knowing their type, its tile
868/// values and its draws, which it writes, uploads and draws. It runs
869/// the layer's [`Layer`] hooks with what is common to every layer type
870/// around them.
871pub trait RenderLayer {
872    fn base(&self) -> &RenderLayerBase;
873
874    /// The layer's id.
875    fn id(&self) -> &str {
876        &self.base().style.base().id
877    }
878
879    /// The order the layer draws its source's tiles in.
880    fn tile_order(&self) -> TileOrder;
881
882    /// Makes `style`, the changed style of the layer (of the same id and
883    /// type), the layer's, drops the draws, which were built for the
884    /// previous style's values, with the tile values unless the layer keeps
885    /// them ([`Layer::RESTYLE_KEEPS_TILES`]), and begins transitions to
886    /// the new values. A style of another type leaves the layer's. The next
887    /// encode builds the draws again from the tiles' buckets.
888    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>);
889
890    /// Begins transitions for the paint values that changed since the last
891    /// frame, to those of the layer's style.
892    fn transition(&mut self, parameters: &TransitionParameters);
893
894    /// Evaluates the layer's paint values for a frame of `parameters`,
895    /// which the layer completes ([`Layer::evaluate`]), and sets the
896    /// passes the layer draws in with them.
897    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters);
898
899    /// Whether a paint value of the layer is still in transition.
900    fn has_transition(&self) -> bool;
901
902    /// Whether the layer has a pattern property and is in a cross-fade.
903    fn has_crossfade(&self) -> bool;
904
905    /// The frame's update of the layer: finds the tiles of `parameters`'
906    /// source the layer draws, which it adds to `parameters.found`, adds the
907    /// passes their buckets were laid out for to the layer's, runs the
908    /// layer's [`Layer::update`], and keeps entries for the tiles; or,
909    /// for a type without a source, runs its update without tiles.
910    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>);
911
912    /// The encode's update of the layer's draws: picks the shader variant
913    /// for the frame's projection, standing on the frame's ground where the
914    /// layer stands and the frame has one, dropping the draws and tile values
915    /// when it changed; drops them of a layer that has nothing to draw, and
916    /// otherwise starts its draws of the frame; for a layer that draws in a
917    /// pass, readies the tile values and runs the layer's
918    /// [`Layer::prepare`] with the tiles of its type that its update
919    /// found in `source`, or none for a type without a source, and writes
920    /// the buffers of its draws.
921    fn update_draws(
922        &mut self,
923        gpu: &mut dyn Gpu,
924        parameters: &mut PaintParameters<'_>,
925        source: Option<FrameSourceTiles<'_>>,
926        targets: &mut SharedTargets,
927    );
928
929    /// How the layer meets terrain ([`Layer::TERRAIN`]).
930    fn terrain(&self) -> OnTerrain;
931
932    /// Whether the layer draws 3D geometry ([`Layer::VOLUME`]).
933    fn volume(&self) -> bool;
934
935    /// Whether the layer's draws can draw into a shared target
936    /// ([`Layer::ROUTES`]).
937    fn routes(&self) -> bool;
938
939    /// Makes `route` the shared target that the frame's draws of the layer
940    /// draw into instead of the map, or with `None` the map.
941    fn set_route(&mut self, route: Option<usize>);
942
943    /// Whether the layer's blend with its values of the frame reads what is
944    /// drawn beneath it, which a shared target's pass can't give it.
945    fn reads_backdrop(&self) -> bool;
946
947    /// Whether the layer blends with what is under it otherwise than by
948    /// covering it, with its values of the frame: a layer blend
949    /// ([`StyleLayerType::layer_blend`]) other than `normal`.
950    fn blends(&self) -> bool;
951
952    /// The light the terrain's surface can shade the layer's drapes with
953    /// ([`Layer::surface_light`]).
954    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight>;
955
956    /// Where the tiles the layer's update found are among the frame's
957    /// ([`LayerUpdateParameters::found`]); `None` for a type without a
958    /// source.
959    fn found(&self) -> Option<Range<usize>>;
960
961    /// The encode's update of the layer's draws into `drape`, `draws`, as
962    /// [`update_draws`](Self::update_draws) makes the frame's, with the
963    /// drape's `parameters`, from the tiles of `source` the layer's update
964    /// found that overlap the drape's tile
965    /// ([`FrameSourceTiles::overlapping`]), or from the drape's tile itself
966    /// for a type without a source that picks its tiles, in the Mercator
967    /// projection, a drape's. The drape draws the layer's tile values,
968    /// which the frame's other drapes share: for a layer that picks its
969    /// tiles, those of the tiles of every drape.
970    fn update_drape_draws(
971        &mut self,
972        gpu: &mut dyn Gpu,
973        parameters: &mut PaintParameters<'_>,
974        source: Option<FrameSourceTiles<'_>>,
975        drape: DrapeTile<'_>,
976        draws: &mut Draws,
977    );
978
979    /// Records that the buckets in `changed` changed, for the tiles whose
980    /// values were made from them.
981    fn mark_changed(&mut self, changed: &ChangedBuckets);
982
983    /// Moves the layer's value of each tile to the tile `wrap_delta` world
984    /// copies east of it: the tiles are the same ones under new ids once the
985    /// map's center has crossed the antimeridian, and their values stay
986    /// rather than being made again.
987    fn handle_wrap_jump(&mut self, wrap_delta: i16);
988
989    /// Includes the layer in the frame's drawing or excludes it. A layer
990    /// excluded drops its draws and its tiles with their values, previous
991    /// ones too: its updates don't run until it is included again, and they
992    /// then rebuild everything from the source's tiles.
993    fn set_renderable(&mut self, renderable: bool);
994
995    /// Drops the layer's tile values, previous ones too, and the frame's
996    /// draws of the layer, which then let go of what they kept for the
997    /// values' meshes. The tiles stay.
998    fn remove_all_draws(&mut self);
999
1000    /// Drops the map frame's draws of the layer, which a frame over terrain
1001    /// draws only in drapes; its tile values stay, for the drapes.
1002    fn remove_frame_draws(&mut self);
1003
1004    /// Visits the groups of the layer's draws of the frame that take a place
1005    /// in the layers' order and depth, in drawing order: none unless the
1006    /// frame draws the layer. They are the groups `upload` and `render`
1007    /// upload and draw.
1008    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group));
1009
1010    /// Uploads the meshes of the layer's draws, before the frame draws them.
1011    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context);
1012
1013    /// Draws the pass's draws of the layer's groups into the open pass of
1014    /// `gpu`, the context's, in `order`, each at its depth, and, in the
1015    /// translucent pass, lends the layer the pass after its main group where
1016    /// its draws asked for it ([`LendAt::Pass`]): the map's pass, or with
1017    /// `routed` the pass of the shared target the layer is routed into. In
1018    /// the other, the layer takes its depth and draws nothing.
1019    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool);
1020
1021    /// Before the frame's passes, outside any pass of `gpu`, the context's:
1022    /// draws into the targets of the layer's draws of the frame
1023    /// ([`Draws::target`]), and then lends the layer the frame's commands
1024    /// where its draws asked for them ([`LendAt::BeforePasses`]).
1025    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>);
1026
1027    /// See [`Layer::hit`].
1028    fn hit(
1029        &self,
1030        region: &QueryRegion<'_>,
1031        feature: &dyn mln_style::feature::GeometryTileFeature,
1032        geometry: &mln_style::feature::GeometryCollection,
1033        feature_state: &mln_style::feature::FeatureState,
1034    ) -> bool;
1035
1036    /// See [`Layer::hit_frame`]: what `geometry`, in `view`'s logical pixels,
1037    /// hits of what the layer shows, over `ground` where the map has
1038    /// terrain. Nothing for a layer the last update wouldn't draw.
1039    fn hit_frame(
1040        &self,
1041        view: &View,
1042        geometry: &[ScreenCoordinate],
1043        ground: Option<&TerrainElevation>,
1044        hits: &mut Vec<Feature>,
1045    );
1046
1047    /// Whether the layer draws in a pass and is visible.
1048    fn needs_rendering(&self) -> bool {
1049        self.base().passes != RenderPass::None && self.base().style.base().visibility != VisibilityType::None
1050    }
1051
1052    /// Whether the layer draws at `zoom`. A minimum zoom of 0 is no
1053    /// minimum: the globe zooms below 0 toward the poles.
1054    fn supports_zoom(&self, zoom: f32) -> bool {
1055        let zoom_or_zero = if zoom < 0.0 { 0.0 } else { zoom };
1056        self.base().style.base().min_zoom <= zoom_or_zero && zoom < self.base().style.base().max_zoom
1057    }
1058
1059    /// Whether the frame draws the layer.
1060    fn is_renderable(&self) -> bool {
1061        self.base().is_renderable
1062    }
1063
1064    /// What the layer's paint values depend on.
1065    fn style_dependencies(&self) -> Dependency {
1066        self.base().style_dependencies
1067    }
1068}
1069
1070impl<L: Layer> RenderLayer for Hosted<L> {
1071    fn base(&self) -> &RenderLayerBase {
1072        &self.base
1073    }
1074
1075    fn tile_order(&self) -> TileOrder {
1076        L::TILE_ORDER
1077    }
1078
1079    fn restyle(&mut self, parameters: &TransitionParameters, style: &Arc<dyn ErasedLayerStyle>) {
1080        if L::RESTYLE_KEEPS_TILES {
1081            self.draws.clear();
1082        } else {
1083            self.retire_draws();
1084        }
1085        if let Some(recovered) = LayerStyle::recover(style) {
1086            self.values.style = recovered;
1087            self.base.style = Arc::clone(style);
1088        }
1089        self.transition(parameters);
1090    }
1091
1092    fn transition(&mut self, parameters: &TransitionParameters) {
1093        let values = &mut self.values;
1094        let prior = std::mem::take(&mut values.unevaluated);
1095        values.unevaluated = values.style.paint.transitioned(parameters, prior);
1096        self.base.style_dependencies = <L::Style as StyleLayerType>::PaintProperties::dependencies(&values.unevaluated);
1097    }
1098
1099    fn evaluate(&mut self, parameters: &PropertyEvaluationParameters) {
1100        let mut evaluated = self.values.evaluate(parameters, L::CROSSFADES);
1101        let evaluation =
1102            self.layer.evaluate(EvaluateCx { values: &self.values, parameters, evaluated: &mut evaluated });
1103        self.base.passes = evaluation.passes();
1104        self.base.evaluation = evaluation;
1105        self.values.set_evaluated(&mut self.base, evaluated);
1106    }
1107
1108    fn has_transition(&self) -> bool {
1109        <L::Style as StyleLayerType>::PaintProperties::has_transition(&self.values.unevaluated)
1110    }
1111
1112    fn has_crossfade(&self) -> bool {
1113        L::CROSSFADES && self.values.evaluated.crossfade.t != 1.0
1114    }
1115
1116    fn update(&mut self, parameters: &mut LayerUpdateParameters<'_>) {
1117        let Hosted { base, values, tiles: map, picked, layer, .. } = self;
1118        if !has_tiles::<L>() {
1119            layer.update(UpdateCx { values, parameters, picked }, &[]);
1120            return;
1121        }
1122        let start = parameters.found.len();
1123        let tiles = match parameters.tiles(L::TILE_ORDER) {
1124            Some((tiles, order)) => tiles.find::<L>(order, &base.style.base().id, parameters.found),
1125            None => FrameTiles::new(),
1126        };
1127        base.found = start..parameters.found.len();
1128        for data in tiles.iter().filter_map(|tile| tile.data()) {
1129            base.passes |= <L::Input as Find<L::Style>>::passes(data);
1130        }
1131        layer.update(UpdateCx { values, parameters, picked }, &tiles);
1132        map.set_tiles(tiles.iter().map(|tile| tile.id()));
1133    }
1134
1135    fn update_draws(
1136        &mut self,
1137        gpu: &mut dyn Gpu,
1138        parameters: &mut PaintParameters<'_>,
1139        source: Option<FrameSourceTiles<'_>>,
1140        targets: &mut SharedTargets,
1141    ) {
1142        let stands = L::TERRAIN.stands() && parameters.ground.is_some();
1143        self.use_projection_variant(ProjectionVariant::new(parameters.view.is_globe(), stands));
1144        if !has_tiles::<L>() {
1145            // A layer that picks tiles draws those its update picked.
1146            if L::PICKS_TILES {
1147                self.tiles.set_tiles(self.picked.iter().copied());
1148            }
1149            if L::PICKS_TILES && self.tiles.is_empty() {
1150                self.remove_all_draws();
1151            } else {
1152                self.draw(gpu, parameters, &[], DrawsFor::Map(targets));
1153            }
1154            return;
1155        }
1156        match source.map(|source| (source, source.found(self.base.found.clone()))) {
1157            Some((source, found)) if !found.is_empty() => {
1158                let tiles = source.at::<L>(found, self.id());
1159                self.draw(gpu, parameters, &tiles, DrawsFor::Map(targets));
1160            }
1161            _ => self.remove_all_draws(),
1162        }
1163    }
1164
1165    fn terrain(&self) -> OnTerrain {
1166        L::TERRAIN
1167    }
1168
1169    fn volume(&self) -> bool {
1170        L::VOLUME
1171    }
1172
1173    fn routes(&self) -> bool {
1174        L::ROUTES
1175    }
1176
1177    fn set_route(&mut self, route: Option<usize>) {
1178        self.base.route = route;
1179    }
1180
1181    fn reads_backdrop(&self) -> bool {
1182        crate::render::layer_composite::reads_backdrop(L::Style::layer_blend(&self.values.evaluated.paint))
1183    }
1184
1185    fn blends(&self) -> bool {
1186        L::Style::layer_blend(&self.values.evaluated.paint) != LayerBlendType::Normal
1187    }
1188
1189    fn surface_light(&mut self, parameters: &PaintParameters<'_>) -> Option<SurfaceLight> {
1190        self.layer.surface_light(&self.values, &parameters.frame())
1191    }
1192
1193    fn found(&self) -> Option<Range<usize>> {
1194        has_tiles::<L>().then(|| self.base.found.clone())
1195    }
1196
1197    fn update_drape_draws(
1198        &mut self,
1199        gpu: &mut dyn Gpu,
1200        parameters: &mut PaintParameters<'_>,
1201        source: Option<FrameSourceTiles<'_>>,
1202        drape: DrapeTile<'_>,
1203        draws: &mut Draws,
1204    ) {
1205        // Only a layer that drapes builds the code of its draws in a drape.
1206        if !L::TERRAIN.drapes() {
1207            debug_assert!(false, "a layer that doesn't drape in a drape");
1208            return;
1209        }
1210        // A drape is flat: the layer's draws are Mercator's.
1211        self.use_projection_variant(ProjectionVariant::Mercator);
1212        if !has_tiles::<L>() {
1213            if L::PICKS_TILES {
1214                self.tiles.set_tiles(drape.tiles.iter().copied());
1215            }
1216            self.draw(gpu, parameters, &[], DrawsFor::Drape(draws, &drape.tile));
1217            return;
1218        }
1219        let tiles = match source {
1220            Some(source) => {
1221                source.overlapping::<L>(self.base.found.clone(), self.id(), drape.tile.to_unwrapped(), drape.globe)
1222            }
1223            None => FrameTiles::new(),
1224        };
1225        if tiles.is_empty() {
1226            draws.clear();
1227        } else {
1228            self.draw(gpu, parameters, &tiles, DrawsFor::Drape(draws, &drape.tile));
1229        }
1230    }
1231
1232    fn mark_changed(&mut self, changed: &ChangedBuckets) {
1233        self.tiles.mark_changed(changed);
1234    }
1235
1236    fn handle_wrap_jump(&mut self, wrap_delta: i16) {
1237        self.tiles.shift_wraps(wrap_delta);
1238    }
1239
1240    fn set_renderable(&mut self, renderable: bool) {
1241        self.base.is_renderable = renderable;
1242        if !renderable {
1243            self.tiles.clear_tiles();
1244            self.draws.clear();
1245        }
1246    }
1247
1248    fn remove_all_draws(&mut self) {
1249        self.tiles.clear();
1250        self.draws.clear();
1251    }
1252
1253    fn remove_frame_draws(&mut self) {
1254        self.draws.clear();
1255    }
1256
1257    fn visit_draw_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
1258        if self.base.is_renderable {
1259            self.draws.visit_groups(visit);
1260        }
1261    }
1262
1263    fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
1264        if self.base.is_renderable {
1265            self.draws.upload(gpu, context);
1266        }
1267    }
1268
1269    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder, routed: bool) {
1270        let Hosted { base, draws, layer, .. } = self;
1271        if base.is_renderable && base.route.is_some() != routed {
1272            draws.skip(parameters, order);
1273        } else if base.is_renderable {
1274            let lends = draws.lends(LendAt::Pass) && parameters.pass == RenderPass::Translucent;
1275            let mut lend_pass = |gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>| {
1276                lend(layer, gpu, parameters, LendAt::Pass);
1277            };
1278            draws.render(gpu, parameters, order, lends.then_some(&mut lend_pass));
1279        }
1280    }
1281
1282    fn before_passes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
1283        if self.base.is_renderable {
1284            self.draws.render_targets(gpu, parameters);
1285            if self.draws.lends(LendAt::BeforePasses) {
1286                lend(&mut self.layer, gpu, parameters, LendAt::BeforePasses);
1287            }
1288        }
1289    }
1290
1291    fn hit(
1292        &self,
1293        region: &QueryRegion<'_>,
1294        feature: &dyn mln_style::feature::GeometryTileFeature,
1295        geometry: &mln_style::feature::GeometryCollection,
1296        feature_state: &mln_style::feature::FeatureState,
1297    ) -> bool {
1298        self.layer.hit(&self.values, region, feature, geometry, feature_state)
1299    }
1300
1301    fn hit_frame(
1302        &self,
1303        view: &View,
1304        geometry: &[ScreenCoordinate],
1305        ground: Option<&TerrainElevation>,
1306        hits: &mut Vec<Feature>,
1307    ) {
1308        if self.base.is_renderable {
1309            let ground = ground.filter(|_| L::TERRAIN != OnTerrain::Flat);
1310            self.layer.hit_frame(&FrameQuery { values: &self.values, view, geometry, ground }, hits);
1311        }
1312    }
1313}