Skip to main content

mln_engine/layer/
tile_input.rs

1//! What a layer type draws from: its [`TileInput`], a kind of tile and what
2//! such a tile holds for a layer of the type, its [`Data`](TileInput::Data).
3//! The kinds are the engine's: [`Features`] of a geometry source, which a
4//! layout turns into a bucket per tile, the images of [`RasterTiles`] (a
5//! raster source's tiles, or the one image of an image source), the
6//! elevations of [`DemTiles`], and [`NoTiles`] for a layer without a source.
7//! The registry checks that a type's input is of the kind of source its
8//! style half names.
9
10use std::marker::PhantomData;
11use std::sync::Arc;
12
13use mln_style::bitmap::PremultipliedImage;
14use mln_style::layer::{SourceKind, StyleLayerType};
15
16use crate::draw::identity::SimpleIdentity;
17use crate::draw::tile_render_data::TileAtlasTextures;
18use crate::layer::bucket::Bucket;
19use crate::layer::bucket_geometry::BucketGeometry;
20use crate::layer::layer_type::EvaluatedLayer;
21use crate::layer::layout::Layout;
22use crate::layer::render_layer::Layer;
23use crate::query::feature_index::FeatureIndex;
24use crate::render::tile::{TileContent, ViewPlace};
25use crate::source::render_image_source::{ImageQuad, ImageTile};
26use crate::source::{DemTiles, RasterTiles};
27use crate::text::atlas::ImagePosition;
28use crate::tile_store::contents::GeometryContents;
29use crate::tile_store::dem::DemContents;
30use crate::tile_store::raster::RasterContents;
31
32/// What a layer of the style half `T` draws from: a kind of tile and what
33/// such a tile holds for the layer, its [`Data`](Self::Data).
34#[expect(private_bounds, reason = "the engine's tile kinds are the only ones: `input::Find` seals the trait")]
35pub trait TileInput<T: StyleLayerType>: input::Find<T> + 'static {
36    /// What a frame's tile holds for the layer.
37    type Data<'a>: Copy;
38}
39
40/// What a frame's tile holds for a layer of the type `L`: its
41/// [`Layer::Input`]'s [`Data`](TileInput::Data).
42pub type TileData<'a, L> = <<L as Layer>::Input as TileInput<<L as Layer>::Style>>::Data<'a>;
43
44/// The tiles of a geometry source, whose features the layout `L` turns into
45/// a bucket per tile. A tile's data is its [`LayerBucket`].
46pub struct Features<L>(PhantomData<fn() -> L>);
47
48impl<T: StyleLayerType, L: Layout<T>> TileInput<T> for Features<L> {
49    type Data<'a> = LayerBucket<'a, T, L::Bucket>;
50}
51
52/// No tiles, for a layer without a source, which picks what it draws
53/// itself.
54pub enum NoTiles {}
55
56impl<T: StyleLayerType> TileInput<T> for NoTiles {
57    type Data<'a> = std::convert::Infallible;
58}
59
60/// The tiles of a raster source, or of an image source, which draws its one
61/// image in the tiles it covers. A tile's data is its [`RasterTile`].
62impl<T: StyleLayerType> TileInput<T> for RasterTiles {
63    type Data<'a> = RasterTile<'a>;
64}
65
66/// The tiles of a raster-dem source. A tile's data is its DEM.
67impl<T: StyleLayerType> TileInput<T> for DemTiles {
68    type Data<'a> = &'a DemContents;
69}
70
71/// A bucket of a layer of the type `T` in a tile's layout, of the bucket
72/// type `B`, with the layer's values it was laid out with and the rest of
73/// what the layout's contents hold for the tile's draws.
74pub struct LayerBucket<'a, T: StyleLayerType, B> {
75    pub bucket: &'a B,
76    /// The bucket's identity, which tells apart what layers made of it.
77    pub(crate) id: SimpleIdentity,
78    /// The index of the bucket among the layout's buckets, which its
79    /// [`BucketKey`](crate::placement::BucketKey) names.
80    pub bucket_index: usize,
81    /// The values of the layer that the bucket was laid out with.
82    pub layer: &'a EvaluatedLayer<T>,
83    contents: &'a GeometryContents,
84}
85
86impl<T: StyleLayerType, B> Clone for LayerBucket<'_, T, B> {
87    fn clone(&self) -> Self {
88        *self
89    }
90}
91
92impl<T: StyleLayerType, B> Copy for LayerBucket<'_, T, B> {}
93
94impl<'a, T: StyleLayerType, B: Bucket> LayerBucket<'a, T, B> {
95    /// The bucket of the layer at `index` among those `contents` laid out,
96    /// if the layout laid it out as a layer of the type `T` into a `B`.
97    pub(crate) fn laid(contents: &'a GeometryContents, index: usize) -> Option<Self> {
98        let laid = contents.result.layer_render_data.laid(index)?;
99        let layer: &dyn std::any::Any = laid.layer;
100        Some(LayerBucket {
101            bucket: laid.bucket.downcast_ref::<B>()?,
102            id: laid.bucket.id(),
103            bucket_index: laid.bucket_index,
104            layer: layer.downcast_ref()?,
105            contents,
106        })
107    }
108}
109
110impl<'a, T: StyleLayerType, B> LayerBucket<'a, T, B> {
111    /// The geometry of the layout's buckets in the context's stores, which
112    /// the draws bind.
113    #[must_use]
114    pub fn geometry(self) -> &'a BucketGeometry {
115        &self.contents.bucket_geometry
116    }
117
118    /// The feature index of the layout, which queries of the tile's
119    /// features read.
120    #[must_use]
121    pub fn feature_index(self) -> &'a Arc<FeatureIndex> {
122        &self.contents.result.feature_index
123    }
124
125    /// Where the pattern `pattern` is in the tile's icon atlas.
126    #[must_use]
127    pub fn pattern(self, pattern: &str) -> Option<ImagePosition> {
128        self.contents.pattern_positions()?.get(pattern).cloned()
129    }
130
131    /// The textures of the tile's glyph and icon atlases.
132    #[must_use]
133    pub fn atlas_textures(self) -> &'a TileAtlasTextures {
134        &self.contents.textures
135    }
136}
137
138/// What a raster tile, or a tile that an image source's image draws in,
139/// holds for a layer: an image, and the parts of the tile it draws.
140#[derive(Clone, Copy)]
141pub enum RasterTile<'a> {
142    /// A raster tile's image, drawn on the parts of the tile that its mask
143    /// keeps.
144    Tile(&'a RasterContents),
145    /// An image source's image, drawn on its mesh, which the image's quad
146    /// puts in the tile.
147    Image(&'a ImageTile),
148}
149
150/// The identity of a raster or raster-dem tile's image, by which a layer
151/// keeps its texture: the same while the image is.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
153pub struct ImageId(SimpleIdentity);
154
155impl ImageId {
156    pub(crate) fn new(id: SimpleIdentity) -> Self {
157        ImageId(id)
158    }
159}
160
161impl<'a> RasterTile<'a> {
162    /// The identity of the image, by which a layer keeps its texture.
163    #[must_use]
164    pub fn id(self) -> ImageId {
165        ImageId(match self {
166            RasterTile::Tile(raster) => raster.id(),
167            RasterTile::Image(image) => image.id(),
168        })
169    }
170
171    /// The tile's image.
172    #[must_use]
173    pub fn image(self) -> &'a PremultipliedImage {
174        match self {
175            RasterTile::Tile(raster) => &raster.image,
176            RasterTile::Image(image) => &image.image,
177        }
178    }
179
180    /// Where a draw puts the vertices of the tile's geometry: on the tile
181    /// itself, or on an image source's quad. Every tile of a source draws on
182    /// the same quad.
183    #[must_use]
184    pub fn quad(self) -> ImageQuad {
185        match self {
186            RasterTile::Tile(_) => ImageQuad::TILE,
187            RasterTile::Image(image) => image.quad,
188        }
189    }
190}
191
192pub(crate) mod input {
193    use std::sync::Arc;
194
195    use mln_style::error::Error;
196    use mln_wire::Reader;
197
198    use super::{
199        DemTiles, Features, LayerBucket, NoTiles, RasterTile, RasterTiles, SourceKind, StyleLayerType, TileContent,
200        TileInput, ViewPlace,
201    };
202    use crate::layer::bucket::{ErasedBucket, Stored};
203    use crate::layer::layer_drawing::MadeFrom;
204    use crate::layer::layer_type::{self, ErasedEvaluatedLayer, ErasedLayout};
205    use crate::layer::layout::{Layout, LayoutParameters, SourceLayer};
206    use crate::render::pass::RenderPass;
207    use crate::source::GeometryTiles;
208    use crate::source::kind::Deliver;
209    use crate::tile_store::contents::{Contents, GeometryContents};
210
211    /// The engine's side of a [`TileInput`]: the kind of source whose tiles
212    /// hold it, the layout of a tile's features for an input that lays
213    /// out, and what a frame's tile holds for a layer of it. It seals
214    /// [`TileInput`].
215    pub(crate) trait Find<T: StyleLayerType> {
216        /// The kind of source whose tiles hold the input.
217        const KIND: SourceKind;
218
219        /// [`Layout::needs_resources`] of `group`, for an input that lays
220        /// out; false otherwise.
221        fn needs_resources(_group: &[Arc<dyn ErasedEvaluatedLayer>]) -> bool {
222            false
223        }
224
225        /// The layout of `group`, layers of the same layout on
226        /// `source_layer`, with the dependencies it records in
227        /// `parameters`; `None` for an input that doesn't lay out. Fails for
228        /// a layer of another type.
229        fn create_layout(
230            _group: &[Arc<dyn ErasedEvaluatedLayer>],
231            _parameters: LayoutParameters<'_>,
232            _source_layer: SourceLayer,
233        ) -> Result<Option<Box<dyn ErasedLayout>>, Error> {
234            Ok(None)
235        }
236
237        /// Reads a bucket of the input's layout.
238        fn read_bucket(r: &mut Reader<'_>) -> Option<Box<dyn ErasedBucket>> {
239            r.fail("a bucket of a layer type that doesn't lay out")
240        }
241
242        /// What `contents`, a tile's layout, holds for the layer `layer_id`,
243        /// for an input that lays out.
244        fn laid<'a>(_contents: &'a GeometryContents, _layer_id: &str) -> Option<<Self as TileInput<T>>::Data<'a>>
245        where
246            Self: TileInput<T>,
247        {
248            None
249        }
250
251        /// What `content` holds for the layer `layer_id`, if anything, and
252        /// where it is in it.
253        fn find<'a>(content: TileContent<'a>, layer_id: &str) -> Option<(<Self as TileInput<T>>::Data<'a>, ViewPlace)>
254        where
255            Self: TileInput<T>;
256
257        /// What `content` holds at `place`, where [`find`](Self::find)
258        /// found what it holds for a layer in the same content.
259        fn at(content: TileContent<'_>, place: ViewPlace) -> Option<<Self as TileInput<T>>::Data<'_>>
260        where
261            Self: TileInput<T>;
262
263        /// What a layer's value of a tile that holds `data` is made from:
264        /// [`TileContent::stamp`] of where the tile holds it.
265        fn made_from(data: <Self as TileInput<T>>::Data<'_>) -> MadeFrom
266        where
267            Self: TileInput<T>;
268
269        /// Whether `data` is what a tile holds for the layer `layer_id`,
270        /// rather than for another layer.
271        fn is_for(_data: <Self as TileInput<T>>::Data<'_>, _layer_id: &str) -> bool
272        where
273            Self: TileInput<T>,
274        {
275            true
276        }
277
278        /// The passes that `data` was laid out to draw in, which its layer
279        /// draws in too; none for data that isn't laid out.
280        fn passes(_data: <Self as TileInput<T>>::Data<'_>) -> RenderPass
281        where
282            Self: TileInput<T>,
283        {
284            RenderPass::None
285        }
286    }
287
288    impl<T: StyleLayerType, L: Layout<T>> Find<T> for Features<L> {
289        const KIND: SourceKind = <GeometryTiles as Deliver>::KIND;
290
291        fn needs_resources(group: &[Arc<dyn ErasedEvaluatedLayer>]) -> bool {
292            layer_type::needs_resources::<T, L>(group)
293        }
294
295        fn create_layout(
296            group: &[Arc<dyn ErasedEvaluatedLayer>],
297            parameters: LayoutParameters<'_>,
298            source_layer: SourceLayer,
299        ) -> Result<Option<Box<dyn ErasedLayout>>, Error> {
300            layer_type::create_layout::<T, L>(group, parameters, source_layer).map(Some)
301        }
302
303        fn read_bucket(r: &mut Reader<'_>) -> Option<Box<dyn ErasedBucket>> {
304            Some(Box::new(Stored::new(<L::Bucket as mln_wire::Wire>::read(r)?)))
305        }
306
307        fn laid<'a>(contents: &'a GeometryContents, layer_id: &str) -> Option<<Self as TileInput<T>>::Data<'a>> {
308            LayerBucket::laid(contents, contents.result.layer_render_data.find(layer_id)?)
309        }
310
311        fn find<'a>(content: TileContent<'a>, layer_id: &str) -> Option<(<Self as TileInput<T>>::Data<'a>, ViewPlace)> {
312            let TileContent::Tile(contents) = content else { return None };
313            let contents = contents.geometry()?;
314            let index = contents.result.layer_render_data.find(layer_id)?;
315            Some((LayerBucket::laid(contents, index)?, ViewPlace::Laid(index)))
316        }
317
318        fn at(content: TileContent<'_>, place: ViewPlace) -> Option<<Self as TileInput<T>>::Data<'_>> {
319            let ViewPlace::Laid(index) = place else {
320                debug_assert!(false, "a tile's own contents' place for a laid-out layer");
321                return None;
322            };
323            let TileContent::Tile(contents) = content else { return None };
324            LayerBucket::laid(contents.geometry()?, index)
325        }
326
327        fn made_from(data: <Self as TileInput<T>>::Data<'_>) -> MadeFrom {
328            (data.id, [0, 0])
329        }
330
331        fn is_for(data: <Self as TileInput<T>>::Data<'_>, layer_id: &str) -> bool {
332            data.layer.style.id == layer_id
333        }
334
335        fn passes(data: <Self as TileInput<T>>::Data<'_>) -> RenderPass {
336            RenderPass(data.layer.render_passes)
337        }
338    }
339
340    impl<T: StyleLayerType> Find<T> for RasterTiles {
341        const KIND: SourceKind = <RasterTiles as Deliver>::KIND;
342
343        fn find<'a>(
344            content: TileContent<'a>,
345            _layer_id: &str,
346        ) -> Option<(<Self as TileInput<T>>::Data<'a>, ViewPlace)> {
347            Some((<Self as Find<T>>::at(content, ViewPlace::Own)?, ViewPlace::Own))
348        }
349
350        fn at(content: TileContent<'_>, place: ViewPlace) -> Option<<Self as TileInput<T>>::Data<'_>> {
351            debug_assert_eq!(place, ViewPlace::Own, "a laid-out layer's place for a tile's own contents");
352            match content {
353                TileContent::Tile(Contents::Raster(raster)) => Some(RasterTile::Tile(raster)),
354                TileContent::Image(image) => Some(RasterTile::Image(image)),
355                TileContent::Tile(_) => None,
356            }
357        }
358
359        fn made_from(data: <Self as TileInput<T>>::Data<'_>) -> MadeFrom {
360            match data {
361                RasterTile::Tile(raster) => raster.stamp(),
362                RasterTile::Image(image) => image.stamp(),
363            }
364        }
365    }
366
367    impl<T: StyleLayerType> Find<T> for DemTiles {
368        const KIND: SourceKind = <DemTiles as Deliver>::KIND;
369
370        fn find<'a>(
371            content: TileContent<'a>,
372            _layer_id: &str,
373        ) -> Option<(<Self as TileInput<T>>::Data<'a>, ViewPlace)> {
374            Some((<Self as Find<T>>::at(content, ViewPlace::Own)?, ViewPlace::Own))
375        }
376
377        fn at(content: TileContent<'_>, place: ViewPlace) -> Option<<Self as TileInput<T>>::Data<'_>> {
378            debug_assert_eq!(place, ViewPlace::Own, "a laid-out layer's place for a tile's own contents");
379            match content {
380                TileContent::Tile(Contents::Dem(dem)) => Some(dem),
381                _ => None,
382            }
383        }
384
385        fn made_from(data: <Self as TileInput<T>>::Data<'_>) -> MadeFrom {
386            data.stamp()
387        }
388    }
389
390    impl<T: StyleLayerType> Find<T> for NoTiles {
391        const KIND: SourceKind = SourceKind::None;
392
393        fn find<'a>(
394            _content: TileContent<'a>,
395            _layer_id: &str,
396        ) -> Option<(<Self as TileInput<T>>::Data<'a>, ViewPlace)> {
397            None
398        }
399
400        fn at(_content: TileContent<'_>, _place: ViewPlace) -> Option<<Self as TileInput<T>>::Data<'_>> {
401            None
402        }
403
404        fn made_from(data: <Self as TileInput<T>>::Data<'_>) -> MadeFrom {
405            match data {}
406        }
407    }
408}