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 glam::{DMat4, Vec2};
11use mln_style::constants;
12use mln_style::types::TranslateAnchorType;
13
14use crate::camera::{ProjectionData, View};
15use crate::draw::identity::SimpleIdentity;
16use crate::layer::layer_drawing::MadeFrom;
17use crate::layer::render_layer::Layer;
18use crate::layer::tile_input::TileData;
19use crate::layer::tile_input::input::Find;
20use crate::render::paint_parameters::TransformParameters;
21use crate::render::pass::RenderPass;
22use crate::source::render_image_source::ImageTile;
23use crate::tile::{OverscaledTileID, UnwrappedTileID};
24use crate::tile_store::contents::Contents;
25use crate::tile_store::tile::Tile;
26
27/// A tile of a source that the frame draws: its id, its projection, and
28/// what of its contents the layers draw.
29pub struct RenderTile {
30    pub(crate) id: UnwrappedTileID,
31    /// The projection contract for this tile; `matrix` is its main matrix.
32    pub(crate) projection: ProjectionData,
33    pub(crate) matrix: DMat4,
34
35    /// `tile.id`.
36    tile_id: OverscaledTileID,
37    tile_hold_for_fade: bool,
38    /// Where the tile is among its source's, which finds its contents
39    /// first; `None` for a tile that isn't among a source's.
40    slot: Option<usize>,
41}
42
43impl RenderTile {
44    /// The render tile of `tile`, at `slot` of its source's tiles, drawn as
45    /// `id`, before its first update.
46    pub(crate) fn new(id: UnwrappedTileID, tile: &Tile, slot: usize, hold_for_fade: bool) -> Self {
47        RenderTile { slot: Some(slot), ..RenderTile::of_tile_id(id, tile.id, hold_for_fade) }
48    }
49
50    /// The render tile of the tile `tile_id`, drawn as `id`, before it is
51    /// updated, which isn't among a source's tiles.
52    pub(crate) fn of_tile_id(id: UnwrappedTileID, tile_id: OverscaledTileID, hold_for_fade: bool) -> Self {
53        RenderTile {
54            id,
55            projection: ProjectionData::default(),
56            // `set_projection` sets it.
57            matrix: DMat4::ZERO,
58            tile_id,
59            tile_hold_for_fade: hold_for_fade,
60            slot: None,
61        }
62    }
63
64    /// The layer's translation in tile units, rotated for its anchor.
65    #[must_use]
66    pub fn tile_unit_translation(
67        id: &UnwrappedTileID,
68        translation: [f32; 2],
69        anchor: TranslateAnchorType,
70        state: &View,
71    ) -> [f32; 2] {
72        if translation[0] == 0.0 && translation[1] == 0.0 {
73            return [0.0, 0.0];
74        }
75        let angle = if anchor == TranslateAnchorType::Viewport { (-state.angle()) as f32 } else { 0.0f32 };
76        let translate = Vec2::from_angle(angle).rotate(Vec2::new(translation[0], translation[1]));
77        let zoom = state.zoom() as f32;
78        [id.pixels_to_tile_units(translate.x, zoom), id.pixels_to_tile_units(translate.y, zoom)]
79    }
80
81    /// The id the tile draws as: its world copy of the tile.
82    #[must_use]
83    pub fn id(&self) -> UnwrappedTileID {
84        self.id
85    }
86
87    /// The tile's id.
88    #[must_use]
89    pub fn overscaled_tile_id(&self) -> &OverscaledTileID {
90        &self.tile_id
91    }
92
93    /// Where the tile is among its source's, as of its last update; `None`
94    /// for a tile that isn't among a source's.
95    #[must_use]
96    pub fn slot(&self) -> Option<usize> {
97        self.slot
98    }
99
100    /// Whether the tile stays only while a placement fades its marks out.
101    #[must_use]
102    pub fn hold_for_fade(&self) -> bool {
103        self.tile_hold_for_fade
104    }
105
106    /// The tile's projection in the frame.
107    #[must_use]
108    pub fn projection(&self) -> &ProjectionData {
109        &self.projection
110    }
111
112    /// The tile's main matrix in the frame: its projection's.
113    #[must_use]
114    pub fn matrix(&self) -> &DMat4 {
115        &self.matrix
116    }
117
118    /// Sets the tile's projection and its standard matrix for `transform`.
119    pub(crate) fn set_projection(&mut self, transform: &TransformParameters) {
120        self.projection = transform.view.projection_data_with(&self.id, &transform.proj_matrix);
121        self.matrix = self.projection.main_matrix;
122    }
123}
124
125/// What a frame's tile shows the layers of its source: its contents in the
126/// tile store, or an image source's image, which each of the source's
127/// tiles draws.
128#[derive(Clone, Copy)]
129pub(crate) enum TileContent<'a> {
130    Tile(&'a Contents),
131    Image(&'a ImageTile),
132}
133
134impl TileContent<'_> {
135    /// The bucket or the raster, raster-dem or image contents that the
136    /// content shows at `place`, with the generations of their mask or mesh
137    /// and of their DEM's border.
138    pub(crate) fn stamp(self, place: ViewPlace) -> Option<(SimpleIdentity, [u64; 2])> {
139        match (self, place) {
140            (TileContent::Tile(contents), place) => contents.stamp(place),
141            (TileContent::Image(image), ViewPlace::Own) => Some(image.stamp()),
142            (TileContent::Image(_), ViewPlace::Laid(_)) => None,
143        }
144    }
145
146    /// The box that the content draws over, in its tile's units: min x,
147    /// min y, max x, max y. A tile's contents draw over the tile; an image
148    /// source's image over the box of its quad's corners, which may reach
149    /// past the tile.
150    pub(crate) fn bounds(self) -> [i32; 4] {
151        match self {
152            TileContent::Tile(_) => TILE_BOUNDS,
153            TileContent::Image(image) => image.bounds,
154        }
155    }
156}
157
158/// The box of a whole tile, in its units.
159pub(crate) const TILE_BOUNDS: [i32; 4] = [0, 0, constants::EXTENT, constants::EXTENT];
160
161/// Whether `bounds`, a box in the units of the tile `tile`, covers part of
162/// the tile `other`. A box that only touches its edge doesn't.
163pub(crate) fn overlaps(tile: &UnwrappedTileID, bounds: [i32; 4], other: &UnwrappedTileID) -> bool {
164    // Both boxes in the tile units of the finer of the two zooms, from the
165    // west edge of world copy 0.
166    let zoom = tile.canonical.z.max(other.canonical.z);
167    let place = |id: &UnwrappedTileID| {
168        let scale = 1i64 << (zoom - id.canonical.z);
169        let extent = i64::from(constants::EXTENT) * scale;
170        let x = ((i64::from(id.wrap) << id.canonical.z) + i64::from(id.canonical.x)) * extent;
171        (x, i64::from(id.canonical.y) * extent, scale)
172    };
173    let (left, top, scale) = place(tile);
174    let [min_x, min_y, max_x, max_y] = bounds.map(|bound| i64::from(bound) * scale);
175    let (other_left, other_top, other_scale) = place(other);
176    let other_extent = i64::from(constants::EXTENT) * other_scale;
177    left + min_x < other_left + other_extent
178        && other_left < left + max_x
179        && top + min_y < other_top + other_extent
180        && other_top < top + max_y
181}
182
183/// Where a tile's contents keep what they show a layer. The frame's found
184/// tiles keep it for layers of every type in one list, so a place of one
185/// type's inputs can reach another's
186/// [`Find::at`](crate::layer::tile_input::input::Find::at), which asserts
187/// that it doesn't.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub(crate) enum ViewPlace {
190    /// The layer's place among the layers of the tile's layout.
191    Laid(usize),
192    /// The tile's own contents, a raster or raster-dem tile's or an image
193    /// source's image, which every layer of its source draws.
194    Own,
195}
196
197/// What a layer draws of a frame's tile: the tile, the bucket or contents
198/// it shows the layer, and the generations of their mask or mesh and of
199/// their DEM's border. It changes whenever the layer's draws of the tile
200/// would.
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub(crate) struct TileStamp {
203    pub(crate) tile: OverscaledTileID,
204    pub(crate) bucket: Option<SimpleIdentity>,
205    pub(crate) generations: [u64; 2],
206}
207
208/// A layer's tile of a frame, as the frame's update found it: its index
209/// among its source's render tiles, and where what it shows the layer is in
210/// its contents ([`Find::find`](crate::layer::tile_input::input::Find::find)).
211#[derive(Clone, Copy, Debug)]
212pub(crate) struct FoundTile {
213    pub(crate) tile: usize,
214    pub(crate) view: Option<ViewPlace>,
215}
216
217/// A render tile of a frame, with what it holds for a layer of the type
218/// `T` and the world copy the layer draws it in.
219pub struct FrameTile<'a, T: Layer> {
220    pub(crate) tile: &'a RenderTile,
221    /// The world copy the layer draws the tile in: its own, but in a drape
222    /// one by the drape's.
223    wrap: i16,
224    data: Option<TileData<'a, T>>,
225}
226
227impl<T: Layer> Clone for FrameTile<'_, T> {
228    fn clone(&self) -> Self {
229        *self
230    }
231}
232
233impl<T: Layer> Copy for FrameTile<'_, T> {}
234
235impl<'a, T: Layer> FrameTile<'a, T> {
236    /// The tile `tile`, which shows `content`, as the layer `layer_id`
237    /// sees it, and where it found what the tile holds for the layer.
238    #[must_use]
239    pub(crate) fn find(
240        tile: &'a RenderTile,
241        content: Option<TileContent<'a>>,
242        layer_id: &str,
243    ) -> (Self, Option<ViewPlace>) {
244        let found = content.and_then(|content| <T::Input as Find<T::Style>>::find(content, layer_id));
245        let frame_tile = FrameTile { tile, wrap: tile.id.wrap, data: found.map(|(data, _)| data) };
246        (frame_tile, found.map(|(_, place)| place))
247    }
248
249    /// The tile `tile`, which shows `content`, as the layer `layer_id`
250    /// sees it, with what it holds for the layer at `view` in `content`,
251    /// where [`find`](Self::find) found it.
252    #[must_use]
253    pub(crate) fn at(
254        tile: &'a RenderTile,
255        content: Option<TileContent<'a>>,
256        layer_id: &str,
257        view: Option<ViewPlace>,
258    ) -> Self {
259        let data = content.zip(view).and_then(|(content, place)| <T::Input as Find<T::Style>>::at(content, place));
260        debug_assert_eq!(data.is_some(), view.is_some(), "a tile's contents changed since the frame's update");
261        debug_assert!(
262            data.is_none_or(|data| <T::Input as Find<T::Style>>::is_for(data, layer_id)),
263            "a layer found at another's place"
264        );
265        FrameTile { tile, wrap: tile.id.wrap, data }
266    }
267
268    /// The tile, drawn in the world copy `wrap`.
269    #[must_use]
270    pub(crate) fn in_copy(self, wrap: i16) -> Self {
271        FrameTile { wrap, ..self }
272    }
273
274    /// What the layer's value of the tile is made from, if the tile holds
275    /// anything for the layer ([`TileContent::stamp`]).
276    pub(crate) fn made_from(self) -> Option<MadeFrom> {
277        self.data.map(<T::Input as Find<T::Style>>::made_from)
278    }
279
280    /// The tile as the frame draws it.
281    #[must_use]
282    pub fn render_tile(self) -> &'a RenderTile {
283        self.tile
284    }
285
286    /// What the tile holds for the layer, if anything.
287    pub fn data(self) -> Option<TileData<'a, T>> {
288        self.data
289    }
290
291    /// [`data`](Self::data), if it was laid out to draw in `pass`.
292    pub fn data_for_pass(self, pass: RenderPass) -> Option<TileData<'a, T>> {
293        self.data.filter(|&data| <T::Input as Find<T::Style>>::passes(data) & pass != RenderPass::None)
294    }
295
296    /// The tile's id.
297    #[must_use]
298    pub fn id(self) -> OverscaledTileID {
299        *self.tile.overscaled_tile_id()
300    }
301
302    /// The id that the layer draws the tile under: its own, but in a drape
303    /// in the world copy the drape draws it in.
304    #[must_use]
305    pub fn draw_id(self) -> OverscaledTileID {
306        OverscaledTileID { wrap: self.wrap, ..self.id() }
307    }
308}