Skip to main content

mln_engine/render/
tile.rs

1// A render tile is a tile as a frame draws it: where it draws, its
2// matrices, and what it copies of the tile and its render entry (its id,
3// hold-for-fade state and whether it draws a visible layer) when the
4// frame's update makes it. It lives in its render source, apart from the
5// tile store. The frame's phases look the tile's contents up through its
6// source, in the store by the tile's slot and id (`TileContent`, `FrameTile`);
7// the store changes them only in the frame's update, before the layers read
8// them.
9
10use std::time::Duration;
11
12use glam::{DMat4, Vec2};
13use mln_style::constants;
14use mln_style::types::TranslateAnchorType;
15
16use crate::camera::{ProjectionData, View};
17use crate::draw::identity::SimpleIdentity;
18use crate::layer::layer_drawing::MadeFrom;
19use crate::layer::render_layer::Layer;
20use crate::layer::tile_input::TileData;
21use crate::layer::tile_input::input::Find;
22use crate::render::paint_parameters::TransformParameters;
23use crate::render::pass::RenderPass;
24use crate::source::render_image_source::ImageTile;
25use crate::tile::{OverscaledTileID, UnwrappedTileID};
26use crate::tile_store::contents::Contents;
27use crate::tile_store::tile::Tile;
28
29/// A tile of a source that the frame draws: its id, its projection, and
30/// what of its contents the layers draw.
31pub struct RenderTile {
32    pub(crate) id: UnwrappedTileID,
33    /// The projection contract for this tile; `matrix` is its main matrix.
34    pub(crate) projection: ProjectionData,
35    pub(crate) matrix: DMat4,
36
37    /// `tile.id`.
38    tile_id: OverscaledTileID,
39    tile_hold_for_fade: bool,
40    /// Where the tile is among its source's, which finds its contents
41    /// first; `None` for a tile that isn't among a source's.
42    slot: Option<usize>,
43    /// How the tile fades, while it does.
44    pub(crate) fade: Option<RenderFade>,
45    /// Whether the frame has the tile only for another that fades with its
46    /// image: no layer draws it.
47    pub(crate) fade_parent_only: bool,
48}
49
50/// How a render tile fades
51/// ([`TileFade`](crate::tile_store::source_tiles::TileFade)), with its
52/// parent's index among its source's render tiles.
53#[derive(Clone, Copy, Debug)]
54pub(crate) struct RenderFade {
55    pub(crate) parent: Option<usize>,
56    pub(crate) elapsed: Duration,
57    pub(crate) fade_in: bool,
58}
59
60impl RenderTile {
61    /// The render tile of `tile`, at `slot` of its source's tiles, drawn as
62    /// `id`, before its first update.
63    pub(crate) fn new(id: UnwrappedTileID, tile: &Tile, slot: usize, hold_for_fade: bool) -> Self {
64        RenderTile { slot: Some(slot), ..RenderTile::of_tile_id(id, tile.id, hold_for_fade) }
65    }
66
67    /// The render tile of the tile `tile_id`, drawn as `id`, before it is
68    /// updated, which isn't among a source's tiles.
69    pub(crate) fn of_tile_id(id: UnwrappedTileID, tile_id: OverscaledTileID, hold_for_fade: bool) -> Self {
70        RenderTile {
71            id,
72            projection: ProjectionData::default(),
73            // `set_projection` sets it.
74            matrix: DMat4::ZERO,
75            tile_id,
76            tile_hold_for_fade: hold_for_fade,
77            slot: None,
78            fade: None,
79            fade_parent_only: false,
80        }
81    }
82
83    /// The layer's translation in tile units, rotated for its anchor.
84    #[must_use]
85    pub fn tile_unit_translation(
86        id: &UnwrappedTileID,
87        translation: [f32; 2],
88        anchor: TranslateAnchorType,
89        state: &View,
90    ) -> [f32; 2] {
91        if translation[0] == 0.0 && translation[1] == 0.0 {
92            return [0.0, 0.0];
93        }
94        let angle = if anchor == TranslateAnchorType::Viewport { (-state.angle()) as f32 } else { 0.0f32 };
95        let translate = Vec2::from_angle(angle).rotate(Vec2::new(translation[0], translation[1]));
96        let zoom = state.zoom() as f32;
97        [id.pixels_to_tile_units(translate.x, zoom), id.pixels_to_tile_units(translate.y, zoom)]
98    }
99
100    /// The id the tile draws as: its world copy of the tile.
101    #[must_use]
102    pub fn id(&self) -> UnwrappedTileID {
103        self.id
104    }
105
106    /// The tile's id.
107    #[must_use]
108    pub fn overscaled_tile_id(&self) -> &OverscaledTileID {
109        &self.tile_id
110    }
111
112    /// Where the tile is among its source's, as of its last update; `None`
113    /// for a tile that isn't among a source's.
114    #[must_use]
115    pub fn slot(&self) -> Option<usize> {
116        self.slot
117    }
118
119    /// Whether the tile stays only while a placement fades its marks out.
120    #[must_use]
121    pub fn hold_for_fade(&self) -> bool {
122        self.tile_hold_for_fade
123    }
124
125    /// The tile's projection in the frame.
126    #[must_use]
127    pub fn projection(&self) -> &ProjectionData {
128        &self.projection
129    }
130
131    /// The tile's main matrix in the frame: its projection's.
132    #[must_use]
133    pub fn matrix(&self) -> &DMat4 {
134        &self.matrix
135    }
136
137    /// Sets the tile's projection and its standard matrix for `transform`.
138    pub(crate) fn set_projection(&mut self, transform: &TransformParameters) {
139        self.projection = transform.view.projection_data_with(&self.id, &transform.proj_matrix);
140        self.matrix = self.projection.main_matrix;
141    }
142}
143
144/// What a frame's tile shows the layers of its source: its contents in the
145/// tile store, or an image source's image, which each of the source's
146/// tiles draws.
147#[derive(Clone, Copy)]
148pub(crate) enum TileContent<'a> {
149    Tile(&'a Contents),
150    Image(&'a ImageTile),
151}
152
153impl TileContent<'_> {
154    /// The bucket or the raster, raster-dem or image contents that the
155    /// content shows at `place`, with the generations of their mask or mesh
156    /// and of their DEM's border.
157    pub(crate) fn stamp(self, place: ViewPlace) -> Option<(SimpleIdentity, [u64; 2])> {
158        match (self, place) {
159            (TileContent::Tile(contents), place) => contents.stamp(place),
160            (TileContent::Image(image), ViewPlace::Own) => Some(image.stamp()),
161            (TileContent::Image(_), ViewPlace::Laid(_)) => None,
162        }
163    }
164
165    /// The box that the content draws over, in its tile's units: min x,
166    /// min y, max x, max y. A tile's contents draw over the tile; an image
167    /// source's image over the box of its quad's corners, which may reach
168    /// past the tile.
169    pub(crate) fn bounds(self) -> [i32; 4] {
170        match self {
171            TileContent::Tile(_) => TILE_BOUNDS,
172            TileContent::Image(image) => image.bounds,
173        }
174    }
175}
176
177/// The box of a whole tile, in its units.
178pub(crate) const TILE_BOUNDS: [i32; 4] = [0, 0, constants::EXTENT, constants::EXTENT];
179
180/// Whether `bounds`, a box in the units of the tile `tile`, covers part of
181/// the tile `other`. A box that only touches its edge doesn't.
182pub(crate) fn overlaps(tile: &UnwrappedTileID, bounds: [i32; 4], other: &UnwrappedTileID) -> bool {
183    // Both boxes in the tile units of the finer of the two zooms, from the
184    // west edge of world copy 0.
185    let zoom = tile.canonical.z.max(other.canonical.z);
186    let place = |id: &UnwrappedTileID| {
187        let scale = 1i64 << (zoom - id.canonical.z);
188        let extent = i64::from(constants::EXTENT) * scale;
189        let x = ((i64::from(id.wrap) << id.canonical.z) + i64::from(id.canonical.x)) * extent;
190        (x, i64::from(id.canonical.y) * extent, scale)
191    };
192    let (left, top, scale) = place(tile);
193    let [min_x, min_y, max_x, max_y] = bounds.map(|bound| i64::from(bound) * scale);
194    let (other_left, other_top, other_scale) = place(other);
195    let other_extent = i64::from(constants::EXTENT) * other_scale;
196    left + min_x < other_left + other_extent
197        && other_left < left + max_x
198        && top + min_y < other_top + other_extent
199        && other_top < top + max_y
200}
201
202/// Where a tile's contents keep what they show a layer. The frame's found
203/// tiles keep it for layers of every type in one list, so a place of one
204/// type's inputs can reach another's
205/// [`Find::at`](crate::layer::tile_input::input::Find::at), which asserts
206/// that it doesn't.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub(crate) enum ViewPlace {
209    /// The layer's place among the layers of the tile's layout.
210    Laid(usize),
211    /// The tile's own contents, a raster or raster-dem tile's or an image
212    /// source's image, which every layer of its source draws.
213    Own,
214}
215
216/// What a layer draws of a frame's tile: the tile, the bucket or contents
217/// it shows the layer, and the generations of their mask or mesh and of
218/// their DEM's border. It changes whenever the layer's draws of the tile
219/// would.
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub(crate) struct TileStamp {
222    pub(crate) tile: OverscaledTileID,
223    pub(crate) bucket: Option<SimpleIdentity>,
224    pub(crate) generations: [u64; 2],
225}
226
227/// A layer's tile of a frame, as the frame's update found it: its index
228/// among its source's render tiles, and where what it shows the layer is in
229/// its contents ([`Find::find`](crate::layer::tile_input::input::Find::find)).
230#[derive(Clone, Copy, Debug)]
231pub(crate) struct FoundTile {
232    pub(crate) tile: usize,
233    pub(crate) view: Option<ViewPlace>,
234}
235
236/// A render tile of a frame, with what it holds for a layer of the type
237/// `T` and the world copy the layer draws it in.
238pub struct FrameTile<'a, T: Layer> {
239    pub(crate) tile: &'a RenderTile,
240    /// The world copy the layer draws the tile in: its own, but in a drape
241    /// one by the drape's.
242    wrap: i16,
243    data: Option<TileData<'a, T>>,
244    fade: Option<TileFade<'a, T>>,
245}
246
247/// How a frame's tile fades in, from its parent's image or from nothing,
248/// or out to the parent's image, as its parent replaces it, for a layer of
249/// the type `T` that fades tiles
250/// ([`Layer::tile_fade`](crate::layer::Layer::tile_fade)).
251pub struct TileFade<'a, T: Layer> {
252    parent: Option<(OverscaledTileID, TileData<'a, T>)>,
253    elapsed: Duration,
254    fade_in: bool,
255}
256
257impl<T: Layer> Clone for TileFade<'_, T> {
258    fn clone(&self) -> Self {
259        *self
260    }
261}
262
263impl<T: Layer> Copy for TileFade<'_, T> {}
264
265impl<'a, T: Layer> TileFade<'a, T> {
266    pub(crate) fn new(parent: Option<(OverscaledTileID, TileData<'a, T>)>, elapsed: Duration, fade_in: bool) -> Self {
267        TileFade { parent, elapsed, fade_in }
268    }
269
270    /// The loaded tile above the tile, whose image it blends with, and what
271    /// that holds for the layer; `None` for a tile that fades in over what
272    /// is under it.
273    #[must_use]
274    pub fn parent(self) -> Option<(OverscaledTileID, TileData<'a, T>)> {
275        self.parent
276    }
277
278    /// How much of the tile shows at the frame's time, from 0 to 1, for a
279    /// layer that fades tiles over `duration`: of its own image rather than
280    /// its parent's where it has a parent, and otherwise its opacity.
281    #[must_use]
282    pub fn shown(self, duration: Duration) -> f32 {
283        let done =
284            if duration.is_zero() { 1.0 } else { (self.elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.0) };
285        if self.fade_in { done } else { 1.0 - done }
286    }
287}
288
289impl<T: Layer> Clone for FrameTile<'_, T> {
290    fn clone(&self) -> Self {
291        *self
292    }
293}
294
295impl<T: Layer> Copy for FrameTile<'_, T> {}
296
297impl<'a, T: Layer> FrameTile<'a, T> {
298    /// The tile `tile`, which shows `content`, as the layer `layer_id`
299    /// sees it, and where it found what the tile holds for the layer.
300    #[must_use]
301    pub(crate) fn find(
302        tile: &'a RenderTile,
303        content: Option<TileContent<'a>>,
304        layer_id: &str,
305    ) -> (Self, Option<ViewPlace>) {
306        let found = content.and_then(|content| <T::Input as Find<T::Style>>::find(content, layer_id));
307        let frame_tile = FrameTile { tile, wrap: tile.id.wrap, data: found.map(|(data, _)| data), fade: None };
308        (frame_tile, found.map(|(_, place)| place))
309    }
310
311    /// The tile `tile`, which shows `content`, as the layer `layer_id`
312    /// sees it, with what it holds for the layer at `view` in `content`,
313    /// where [`find`](Self::find) found it.
314    #[must_use]
315    pub(crate) fn at(
316        tile: &'a RenderTile,
317        content: Option<TileContent<'a>>,
318        layer_id: &str,
319        view: Option<ViewPlace>,
320    ) -> Self {
321        let data = content.zip(view).and_then(|(content, place)| <T::Input as Find<T::Style>>::at(content, place));
322        debug_assert_eq!(data.is_some(), view.is_some(), "a tile's contents changed since the frame's update");
323        debug_assert!(
324            data.is_none_or(|data| <T::Input as Find<T::Style>>::is_for(data, layer_id)),
325            "a layer found at another's place"
326        );
327        FrameTile { tile, wrap: tile.id.wrap, data, fade: None }
328    }
329
330    /// The tile, which fades as `fade` says.
331    #[must_use]
332    pub(crate) fn with_fade(self, fade: Option<TileFade<'a, T>>) -> Self {
333        FrameTile { fade, ..self }
334    }
335
336    /// How the tile fades in the map's frame, while it does; never in a
337    /// drape.
338    #[must_use]
339    pub fn fade(self) -> Option<TileFade<'a, T>> {
340        self.fade
341    }
342
343    /// The tile, drawn in the world copy `wrap`.
344    #[must_use]
345    pub(crate) fn in_copy(self, wrap: i16) -> Self {
346        FrameTile { wrap, ..self }
347    }
348
349    /// What the layer's value of the tile is made from, if the tile holds
350    /// anything for the layer ([`TileContent::stamp`]).
351    pub(crate) fn made_from(self) -> Option<MadeFrom> {
352        self.data.map(<T::Input as Find<T::Style>>::made_from)
353    }
354
355    /// The tile as the frame draws it.
356    #[must_use]
357    pub fn render_tile(self) -> &'a RenderTile {
358        self.tile
359    }
360
361    /// What the tile holds for the layer, if anything.
362    pub fn data(self) -> Option<TileData<'a, T>> {
363        self.data
364    }
365
366    /// [`data`](Self::data), if it was laid out to draw in `pass`.
367    pub fn data_for_pass(self, pass: RenderPass) -> Option<TileData<'a, T>> {
368        self.data.filter(|&data| <T::Input as Find<T::Style>>::passes(data) & pass != RenderPass::NONE)
369    }
370
371    /// The tile's id.
372    #[must_use]
373    pub fn id(self) -> OverscaledTileID {
374        *self.tile.overscaled_tile_id()
375    }
376
377    /// The id that the layer draws the tile under: its own, but in a drape
378    /// in the world copy the drape draws it in.
379    #[must_use]
380    pub fn draw_id(self) -> OverscaledTileID {
381        OverscaledTileID { wrap: self.wrap, ..self.id() }
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use mln_style::constants::EXTENT;
388    use mln_style::tile_id::CanonicalTileID;
389
390    use super::*;
391
392    fn tile(wrap: i16, z: u8, x: u32, y: u32) -> UnwrappedTileID {
393        UnwrappedTileID::with_wrap(wrap, CanonicalTileID::new(z, x, y))
394    }
395
396    /// A box overlaps the tiles it covers part of, in its tile's world copy:
397    /// the neighbors it reaches into, but not those it only touches, and
398    /// coarser tiles that hold part of it and finer tiles it covers part of.
399    #[test]
400    fn a_box_overlaps_the_tiles_it_covers_part_of() {
401        let inside = [1000, 1000, 7000, 7000];
402        // From the tile's west half to a quarter into its eastern neighbor.
403        let east = [EXTENT / 2, 0, EXTENT + EXTENT / 4, EXTENT];
404        // West of its tile, in the next world copy's westernmost tile.
405        let west = [-EXTENT / 4, 0, EXTENT / 4, EXTENT];
406        // The tile's north-east quarter, and a sliver past its east edge.
407        let sliver = [EXTENT / 2, 0, EXTENT + 8, EXTENT / 2];
408        let cases = [
409            // Each world copy of a box overlaps the tiles of its own.
410            (tile(0, 3, 5, 2), inside, tile(0, 3, 5, 2), true),
411            (tile(0, 3, 5, 2), inside, tile(-1, 3, 5, 2), false),
412            (tile(-1, 3, 5, 2), inside, tile(-1, 3, 5, 2), true),
413            (tile(-1, 3, 5, 2), inside, tile(0, 3, 5, 2), false),
414            (tile(0, 3, 5, 2), east, tile(0, 3, 6, 2), true),
415            (tile(0, 3, 5, 2), east, tile(0, 3, 4, 2), false),
416            (tile(0, 3, 5, 2), east, tile(0, 3, 5, 3), false),
417            (tile(0, 3, 5, 2), east, tile(0, 3, 5, 1), false),
418            (tile(1, 3, 0, 2), west, tile(0, 3, 7, 2), true),
419            (tile(1, 3, 0, 2), west, tile(1, 3, 0, 2), true),
420            (tile(1, 3, 0, 2), west, tile(1, 3, 7, 2), false),
421            // The parent and the world hold the sliver's box, and so does
422            // the parent's eastern neighbor, which the sliver reaches.
423            (tile(0, 3, 5, 2), sliver, tile(0, 2, 2, 1), true),
424            (tile(0, 3, 5, 2), sliver, tile(0, 0, 0, 0), true),
425            (tile(0, 3, 5, 2), sliver, tile(0, 2, 3, 1), true),
426            (tile(0, 3, 5, 2), sliver, tile(0, 2, 2, 0), false),
427            // Of the tile's children only the north-east one, and of the
428            // eastern neighbor's only the north-west one.
429            (tile(0, 3, 5, 2), sliver, tile(0, 4, 11, 4), true),
430            (tile(0, 3, 5, 2), sliver, tile(0, 4, 10, 4), false),
431            (tile(0, 3, 5, 2), sliver, tile(0, 4, 11, 5), false),
432            (tile(0, 3, 5, 2), sliver, tile(0, 4, 12, 4), true),
433            (tile(0, 3, 5, 2), sliver, tile(0, 4, 12, 5), false),
434            // At zoom 10, the sliver is the first of eight columns of the
435            // eastern neighbor's tiles.
436            (tile(0, 3, 5, 2), sliver, tile(0, 10, 6 * 128, 2 * 128), true),
437            (tile(0, 3, 5, 2), sliver, tile(0, 10, 6 * 128 + 1, 2 * 128), false),
438        ];
439        for (tile, bounds, other, expected) in cases {
440            assert_eq!(expected, overlaps(&tile, bounds, &other), "{bounds:?} of {tile:?} over {other:?}");
441        }
442    }
443}