Skip to main content

mln_engine/source/
render_image_source.rs

1// An image source draws one image, stretched over the quad of its
2// coordinates, in the tiles that the quad covers: its render tiles, one in
3// each world copy it draws in, which all show its one image tile.
4
5use std::sync::Arc;
6
7use mln_style::bitmap::PremultipliedImage;
8use mln_style::crs::WorldBox;
9use mln_style::feature::GeometryCoordinates;
10use mln_style::geo::LatLngBounds;
11use mln_style::geometry::Point;
12use mln_style::range::Range;
13use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
14use mln_style::{Source, constants};
15
16use crate::camera::tile_coordinate::TileCoordinatePoint;
17use crate::draw::context::Context;
18use crate::draw::identity::SimpleIdentity;
19use crate::draw::indexes::{IndexBuffer, Indexes};
20use crate::draw::range::DrawRange;
21use crate::draw::vertices::VertexBuffer;
22use crate::layer::layer_drawing::MadeFrom;
23use crate::layer::layer_type::ErasedEvaluatedLayer;
24use crate::log_target;
25use crate::render::tile::{RenderTile, TileContent};
26use crate::source::render_source::{RenderSource, RenderSourceBase, RenderTileParameters, TileOrder};
27use crate::source::{ImageOf, SourceImage};
28use crate::tile::UnwrappedTileID;
29use crate::tile::tile_range::TileRange;
30use crate::tile_store::store::TileStore;
31use crate::tile_store::tile_cover::{TileCoverParameters, tile_cover, tile_cover_bounds};
32use crate::tile_store::tile_parameters::TileParameters;
33
34// The mapping from the unit square onto the image's corners: the perspective
35// terms of the projective warp and how far it is blended towards the
36// bilinear one, as the "auto" warp blends them, after Heckbert,
37// "Fundamentals of Texture Mapping and Image Warping" (1989), 2.2.3 and A.2.
38#[derive(Clone, Copy, Debug)]
39struct ImageWarp {
40    perspective_x: f64,
41    perspective_y: f64,
42    blend: f64,
43}
44
45impl Default for ImageWarp {
46    fn default() -> Self {
47        ImageWarp { perspective_x: 0.0, perspective_y: 0.0, blend: 1.0 }
48    }
49}
50
51/// The cells across a side of the grid that draws a warp blended towards
52/// the bilinear one.
53const BLENDED_WARP_CELLS: u32 = 16;
54
55fn is_parallelogram(corners: &GeometryCoordinates) -> bool {
56    let [top_left, top_right, bottom_right, bottom_left] =
57        [corners[0], corners[1], corners[2], corners[3]].map(|p| (i32::from(p.x), i32::from(p.y)));
58    top_left.0 + bottom_right.0 == top_right.0 + bottom_left.0
59        && top_left.1 + bottom_right.1 == top_right.1 + bottom_left.1
60}
61
62/// The corner of a concave quad of `corners` (top left, top right, bottom
63/// right, bottom left) that points into it, by its index; `None` for a
64/// quad that isn't concave.
65fn concave_corner(corners: &GeometryCoordinates) -> Option<usize> {
66    let point = |i: usize| (i64::from(corners[i % 4].x), i64::from(corners[i % 4].y));
67    // Which way the outline turns at each corner: a concave quad turns
68    // against the other three at one.
69    let turns = [0, 1, 2, 3].map(|i| {
70        let ((ax, ay), (bx, by), (cx, cy)) = (point(i + 3), point(i), point(i + 1));
71        ((bx - ax) * (cy - by) - (by - ay) * (cx - bx)).signum()
72    });
73    (0..4).find(|&i| turns[i] != 0 && (0..4).all(|j| j == i || turns[j] == -turns[i]))
74}
75
76fn image_warp(corners: &GeometryCoordinates) -> ImageWarp {
77    const PROJECTIVE_FORESHORTENING: f64 = 4.0;
78    const BILINEAR_FORESHORTENING: f64 = 512.0;
79    // A parallelogram is warped affinely either way.
80    if is_parallelogram(corners) {
81        return ImageWarp::default();
82    }
83    let top_left = corners[0];
84    let top_right = corners[1];
85    let bottom_right = corners[2];
86    let bottom_left = corners[3];
87    let (tl_x, tl_y) = (i32::from(top_left.x), i32::from(top_left.y));
88    let (tr_x, tr_y) = (i32::from(top_right.x), i32::from(top_right.y));
89    let (br_x, br_y) = (i32::from(bottom_right.x), i32::from(bottom_right.y));
90    let (bl_x, bl_y) = (i32::from(bottom_left.x), i32::from(bottom_left.y));
91    let sum_x = f64::from(tl_x - tr_x + br_x - bl_x);
92    let sum_y = f64::from(tl_y - tr_y + br_y - bl_y);
93    let right_x = f64::from(tr_x - br_x);
94    let right_y = f64::from(tr_y - br_y);
95    let down_x = f64::from(bl_x - br_x);
96    let down_y = f64::from(bl_y - br_y);
97    let determinant = right_x * down_y - right_y * down_x;
98    let perspective_x = (sum_x * down_y - down_x * sum_y) / determinant;
99    let perspective_y = (right_x * sum_y - sum_x * right_y) / determinant;
100    // The homogeneous denominator at the four corners, normalized to one at
101    // the top left; its spread is the foreshortening, and it stays finite
102    // and positive only while the quad is a perspective view of the image.
103    let denominators = [1.0, 1.0 + perspective_x, 1.0 + perspective_x + perspective_y, 1.0 + perspective_y];
104    // The first largest and smallest, which comparisons with a NaN keep.
105    let mut largest = denominators[0];
106    let mut smallest = denominators[0];
107    for &denominator in &denominators[1..] {
108        if largest < denominator {
109            largest = denominator;
110        }
111        if denominator < smallest {
112            smallest = denominator;
113        }
114    }
115    let foreshortening = largest / smallest;
116    let blend_term = (1.0 - PROJECTIVE_FORESHORTENING / foreshortening)
117        / (1.0 - PROJECTIVE_FORESHORTENING / BILINEAR_FORESHORTENING);
118    let blend = if 0.0 < blend_term { blend_term } else { 0.0 };
119    if !foreshortening.is_finite() || foreshortening < 1.0 || foreshortening > BILINEAR_FORESHORTENING || blend >= 1.0 {
120        return ImageWarp::default();
121    }
122    ImageWarp { perspective_x, perspective_y, blend }
123}
124
125/// Where the raster shader puts the unit square that a draw's vertices span
126/// (0 to `EXTENT` on both axes), in its tile's units: onto the quad of four
127/// corners, warped by an `ImageWarp`. The shader evaluates the warp per
128/// vertex and interpolates the texture coordinates projectively, so a
129/// projective warp draws exactly on two triangles.
130#[derive(Clone, Copy, Debug, PartialEq)]
131pub struct ImageQuad {
132    /// The top left corner's x and y, and the top right's.
133    pub coords_top: [f32; 4],
134    /// The bottom left corner's x and y, and the bottom right's.
135    pub coords_bottom: [f32; 4],
136    /// The warp's perspective terms and its blend towards the bilinear warp,
137    /// then padding.
138    pub warp: [f32; 4],
139}
140
141impl ImageQuad {
142    /// The quad of a tile itself, which draws the vertices where they are.
143    pub const TILE: ImageQuad = {
144        let extent = constants::EXTENT as f32;
145        ImageQuad {
146            coords_top: [0.0, 0.0, extent, 0.0],
147            coords_bottom: [0.0, extent, extent, extent],
148            warp: [0.0, 0.0, 1.0, 0.0],
149        }
150    };
151
152    fn new(corners: &GeometryCoordinates, warp: &ImageWarp) -> ImageQuad {
153        let [top_left, top_right, bottom_right, bottom_left] =
154            [corners[0], corners[1], corners[2], corners[3]].map(|p| [f32::from(p.x), f32::from(p.y)]);
155        ImageQuad {
156            coords_top: [top_left[0], top_left[1], top_right[0], top_right[1]],
157            coords_bottom: [bottom_left[0], bottom_left[1], bottom_right[0], bottom_right[1]],
158            warp: [warp.perspective_x as f32, warp.perspective_y as f32, warp.blend as f32, 0.0],
159        }
160    }
161}
162
163fn to_vertex_coordinate(value: f64) -> i16 {
164    mln_style::math::clamp_f64(value.round(), f64::from(i16::MIN), f64::from(i16::MAX)) as i16
165}
166
167/// The tiles at `zoom` that the rectangle from `min` to `max` in the world
168/// square reaches into ([`TileRange::from_world_box`]), row by row from its
169/// top left: none for a rectangle outside the square.
170fn world_square_cover(min: TileCoordinatePoint, max: TileCoordinatePoint, zoom: u8) -> Vec<UnwrappedTileID> {
171    let tiles = TileRange::from_world_box(&WorldBox { min, max }, zoom, zoom);
172    if tiles.zoom_range.min > tiles.zoom_range.max {
173        return Vec::new();
174    }
175    let (columns, rows) = (tiles.range.min.x..=tiles.range.max.x, tiles.range.min.y..=tiles.range.max.y);
176    rows.flat_map(|y| columns.clone().map(move |x| UnwrappedTileID::new(zoom, i64::from(x), i64::from(y)))).collect()
177}
178
179// The unit square as a grid of `cells` x `cells`, textured edge to edge,
180// which the raster shader puts on the image's quad, each cell split along
181// its diagonal from the top right, or from the top left if `from_top_left`.
182fn build_image_mesh(tile: &mut ImageTile, cells: u32, from_top_left: bool) {
183    let rows = cells + 1;
184    let extent = constants::EXTENT as u32;
185    let mut vertices = Vec::with_capacity((rows * rows) as usize);
186    for j in 0..rows {
187        for i in 0..rows {
188            let (x, y) = ((i * extent / cells) as u16, (j * extent / cells) as u16);
189            vertices.push(RasterLayoutVertex::new(Point::new(x as i16, y as i16), Point::new(x, y)));
190        }
191    }
192    let mut indices: Vec<u16> = Vec::with_capacity((cells * cells * 6) as usize);
193    for j in 0..cells {
194        for i in 0..cells {
195            let top_left = (j * rows + i) as u16;
196            let top_right = top_left.wrapping_add(1);
197            let bottom_left = top_left.wrapping_add(rows as u16);
198            let bottom_right = bottom_left.wrapping_add(1);
199            if from_top_left {
200                indices.extend_from_slice(&[top_left, top_right, bottom_right]);
201                indices.extend_from_slice(&[top_left, bottom_right, bottom_left]);
202            } else {
203                indices.extend_from_slice(&[top_left, top_right, bottom_left]);
204                indices.extend_from_slice(&[top_right, bottom_left, bottom_right]);
205            }
206        }
207    }
208    tile.set_mesh(vertices, indices);
209}
210
211/// A vertex of an image source's mesh: its position in tile units (`a1`,
212/// the attribute `pos`), and where it samples the image (`a2`,
213/// `texture_pos`), in the same units over the image.
214#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
215#[repr(C)]
216pub struct RasterLayoutVertex {
217    pub a1: [i16; 2],
218    pub a2: [u16; 2],
219}
220
221crate::vertex_attributes!(RasterLayoutVertex { a1 => "pos": Short2, a2 => "texture_pos": Short2 });
222
223impl RasterLayoutVertex {
224    /// The vertex at `p` that samples the image at `t`.
225    #[must_use]
226    pub fn new(p: Point<i16>, t: Point<u16>) -> RasterLayoutVertex {
227        RasterLayoutVertex { a1: [p.x, p.y], a2: [t.x, t.y] }
228    }
229}
230
231/// An image source's mesh in the context's stores, which the raster layers
232/// that draw the source share: triangles over [`RasterLayoutVertex`]es.
233pub struct ImageMesh {
234    pub vertices: VertexBuffer,
235    pub indexes: IndexBuffer,
236    /// The draw call that draws the triangles.
237    pub range: DrawRange,
238}
239
240/// Where an image tile's mesh is.
241enum Mesh {
242    /// It has none yet.
243    None,
244    /// Its vertices and indices, until their upload moves them.
245    Data { vertices: Vec<RasterLayoutVertex>, indices: Vec<u16> },
246    /// In the context's stores.
247    Stored(ImageMesh),
248}
249
250/// What an image source shows in each of its tiles: its image, and the mesh
251/// of the unit square that the image's quad puts in the tile. The raster
252/// layers that draw the source share them.
253pub struct ImageTile {
254    id: SimpleIdentity,
255    pub(crate) image: Arc<PremultipliedImage>,
256    mesh: Mesh,
257    /// Counts the changes of the mesh, after which the layers build their
258    /// draws of the image again.
259    generation: u64,
260    /// The box of the quad's corners, in the tile units of the source's
261    /// tiles' canonical tile: min x, min y, max x, max y.
262    pub(crate) bounds: [i32; 4],
263    /// Where the mesh's vertices draw, in the same units.
264    pub(crate) quad: ImageQuad,
265}
266
267impl ImageTile {
268    /// The tile of `image`, which it shares, without a mesh.
269    #[must_use]
270    fn new(image: Arc<PremultipliedImage>) -> Self {
271        ImageTile {
272            id: SimpleIdentity::new(),
273            image,
274            mesh: Mesh::None,
275            generation: 0,
276            bounds: [0; 4],
277            quad: ImageQuad::TILE,
278        }
279    }
280
281    /// The tile's identity, by which the layers keep the image's texture.
282    #[must_use]
283    pub(crate) fn id(&self) -> SimpleIdentity {
284        self.id
285    }
286
287    /// What a layer's value of the tile is made from: its identity, with
288    /// the number of times its mesh changed.
289    #[must_use]
290    pub(crate) fn stamp(&self) -> MadeFrom {
291        (self.id, [self.generation, 0])
292    }
293
294    /// Whether the tile has a mesh.
295    #[must_use]
296    fn has_mesh(&self) -> bool {
297        !matches!(self.mesh, Mesh::None)
298    }
299
300    /// Makes the mesh the triangles of `indices` over `vertices`.
301    fn set_mesh(&mut self, vertices: Vec<RasterLayoutVertex>, indices: Vec<u16>) {
302        self.mesh = Mesh::Data { vertices, indices };
303        self.generation += 1;
304    }
305
306    /// The mesh in the context's stores, once its upload moved it.
307    #[must_use]
308    pub fn mesh(&self) -> Option<&ImageMesh> {
309        match &self.mesh {
310            Mesh::Stored(quads) => Some(quads),
311            Mesh::Data { vertices, .. } => {
312                debug_assert!(vertices.is_empty(), "an image source's mesh drawn before its upload");
313                None
314            }
315            Mesh::None => None,
316        }
317    }
318
319    /// Moves the mesh into `context`'s stores, unless it is there or there
320    /// is none.
321    fn upload(&mut self, context: &mut Context) {
322        self.mesh = match std::mem::replace(&mut self.mesh, Mesh::None) {
323            Mesh::Data { vertices, indices } if !vertices.is_empty() => {
324                let range = DrawRange::indexes(indices.len());
325                let vertices = context.add_vertices(vertices);
326                Mesh::Stored(ImageMesh { vertices, indexes: context.add_indexes(Indexes::new(indices)), range })
327            }
328            mesh => mesh,
329        };
330    }
331}
332
333pub(crate) struct RenderImageSource {
334    base: RenderSourceBase,
335    /// Reads the image from each version of the source.
336    image_of: ImageOf,
337    tile: Option<ImageTile>,
338    /// The tile the image draws in, in each world copy it draws in: one
339    /// canonical tile under different wraps.
340    tile_ids: Vec<UnwrappedTileID>,
341    /// The tiles of `tile_ids` that the frame draws, and their order.
342    render_tiles: Vec<RenderTile>,
343    order: Vec<usize>,
344    mesh_corners: GeometryCoordinates,
345    mesh_cells: u32,
346}
347
348impl RenderImageSource {
349    #[must_use]
350    pub(crate) fn new(style_source: Source, image_of: ImageOf) -> Self {
351        RenderImageSource {
352            base: RenderSourceBase::new(style_source),
353            image_of,
354            tile: None,
355            tile_ids: Vec::new(),
356            render_tiles: Vec::new(),
357            order: Vec::new(),
358            mesh_corners: GeometryCoordinates::new(),
359            mesh_cells: 0,
360        }
361    }
362
363    /// Whether the source's image has arrived. A source without an image
364    /// (one made without a url) has nothing to load, so a still render of it
365    /// finishes.
366    fn loaded(&self) -> bool {
367        self.tile.is_some() || self.image().is_none_or(|image| image.image.is_none())
368    }
369
370    fn image(&self) -> Option<SourceImage> {
371        (self.image_of)(&self.base.style_source)
372    }
373}
374
375impl RenderSource for RenderImageSource {
376    fn base(&self) -> &RenderSourceBase {
377        &self.base
378    }
379
380    // A source that draws nowhere holds no frame back: the style tracks
381    // the load of its image.
382    fn is_loaded(&self, _store: &TileStore) -> bool {
383        !self.base.enabled || self.loaded()
384    }
385
386    fn update(
387        &mut self,
388        _store: &mut TileStore,
389        style_source: Source,
390        _layers: &[Arc<dyn ErasedEvaluatedLayer>],
391        needs_rendering: bool,
392        _needs_relayout: bool,
393        parameters: &TileParameters<'_>,
394    ) {
395        self.base.enabled = needs_rendering;
396        if !needs_rendering {
397            return;
398        }
399
400        let view = parameters.view;
401        self.base.style_source = style_source;
402
403        let Some(source_image) = self.image() else {
404            self.base.enabled = false;
405            return;
406        };
407        let coords = source_image.coordinates;
408        let image = source_image.image;
409
410        let Some(image) = image.filter(|image| image.valid()) else {
411            self.base.enabled = false;
412            return;
413        };
414
415        // Compute the z0 tile coordinates for the given LatLngs, in the world
416        // the map draws in
417        let world = view.world();
418        let mut ne_point: TileCoordinatePoint = Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
419        let mut sw_point: TileCoordinatePoint = Point::new(f64::INFINITY, f64::INFINITY);
420        let mut tile_coordinates: Vec<TileCoordinatePoint> = Vec::new();
421        for lat_lng in &coords {
422            let point = world.world_from_lat_lng(lat_lng);
423            tile_coordinates.push(point);
424            sw_point.x = if point.x < sw_point.x { point.x } else { sw_point.x };
425            ne_point.x = if ne_point.x < point.x { point.x } else { ne_point.x };
426            sw_point.y = if point.y < sw_point.y { point.y } else { sw_point.y };
427            ne_point.y = if ne_point.y < point.y { point.y } else { ne_point.y };
428        }
429        // A corner that a registered projection has no place for leaves the
430        // image nowhere to draw.
431        if !tile_coordinates.iter().all(|point| point.x.is_finite() && point.y.is_finite()) {
432            self.base.enabled = false;
433            return;
434        }
435
436        // Calculate the optimum zoom level to determine the tile ids to use
437        // for transforms
438        let dx = ne_point.x - sw_point.x;
439        let dy = ne_point.y - sw_point.y;
440        let d_max = if dx < dy { dy } else { dx };
441        let floor = (-d_max.log2()).floor();
442        let zoom = (if 0.0 < floor { floor } else { 0.0 }) as u8;
443
444        // Only enable if the long side of the image is > 2 pixels. Resulting
445        // in a display of at least 2 x 1 px image
446        self.base.enabled = d_max * 2.0f64.powf(view.zoom()) * constants::TILE_SIZE_D > 2.0;
447        if !self.base.enabled {
448            return;
449        }
450
451        let tile_cover_ids = if world.wraps() {
452            let mut image_bounds = LatLngBounds::hull(coords[0], coords[1]);
453            image_bounds.extend(&coords[2]);
454            image_bounds.extend(&coords[3]);
455            tile_cover_bounds(&image_bounds, zoom)
456        } else {
457            // In a registered projection, the lng/lat box of the corners can
458            // lie far from the image.
459            world_square_cover(sw_point, ne_point, zoom)
460        };
461        self.tile_ids.clear();
462        // The cover is empty, for example, when the image lies wholly outside
463        // the latitudes a Web Mercator map can show (beyond about ±85.05°), or
464        // outside a registered projection's world square.
465        if tile_cover_ids.is_empty() {
466            self.base.enabled = false;
467            return;
468        }
469        self.tile_ids.push(tile_cover_ids[0]);
470
471        let mut has_visible_tile = false;
472        // A wrap does not move a tile on the globe, so the image draws once
473        // there, in the world copy the cover chose.
474        let globe = view.is_globe();
475        // The image draws in each world copy whose quad overlaps the view's
476        // tiles: while terrain draws, the terrain's, raised ground's too, as
477        // every source covers the view then.
478        let ideal_tiles = match parameters.terrain {
479            Some(terrain) => terrain.tiles.iter().map(|tile| tile.id).collect(),
480            None => tile_cover(
481                &TileCoverParameters {
482                    view: view.clone(),
483                    tile_lod_min_radius: parameters.tile_lod_min_radius,
484                    tile_lod_scale: parameters.tile_lod_scale,
485                    tile_lod_pitch_threshold: parameters.tile_lod_pitch_threshold,
486                    tile_lod_mode: parameters.tile_lod_mode,
487                    requested_zoom: None,
488                    round_zoom: false,
489                    max_content_elevation: 0.0,
490                    // The image ends at its quad's edges.
491                    content_overflows: false,
492                },
493                view.integer_zoom(),
494                Range::new(0u8, zoom),
495                None,
496            ),
497        };
498        for tile in &ideal_tiles {
499            for covering_tile in &tile_cover_ids {
500                if covering_tile.canonical == tile.canonical
501                    || covering_tile.canonical.is_child_of(&tile.canonical)
502                    || tile.canonical.is_child_of(&covering_tile.canonical)
503                {
504                    // The copy that puts this covering tile on the view's
505                    // tile: where the quad crosses the antimeridian, the
506                    // covering tile may lie in the world next to the
507                    // first's, and one view tile may see two copies. A
508                    // copy too many worlds from the first has no tile id.
509                    let wrap = i32::from(tile.wrap) - i32::from(covering_tile.wrap) + i32::from(tile_cover_ids[0].wrap);
510                    let Ok(wrap) = i16::try_from(wrap) else {
511                        continue;
512                    };
513                    has_visible_tile = true;
514                    let wrapped_tile_id = UnwrappedTileID::with_wrap(wrap, tile_cover_ids[0].canonical);
515                    if globe {
516                        self.tile_ids = vec![wrapped_tile_id];
517                        break;
518                    }
519                    if !self.tile_ids.contains(&wrapped_tile_id) {
520                        self.tile_ids.push(wrapped_tile_id);
521                    }
522                }
523            }
524            if globe && has_visible_tile {
525                break;
526            }
527        }
528
529        self.base.enabled = has_visible_tile;
530        if !self.base.enabled {
531            return;
532        }
533
534        // The corners in the units of the cover's first tile, rounded to the
535        // nearest unit, so that an edge falls on the pixels the render
536        // tests' expected images draw it on.
537        let tile = tile_cover_ids[0];
538        let scale = 2.0f64.powi(i32::from(tile.canonical.z));
539        let extent = f64::from(constants::EXTENT);
540        let geom_coords: GeometryCoordinates = tile_coordinates
541            .iter()
542            .map(|point| {
543                let x = point.x * scale - f64::from(tile.canonical.x) - f64::from(tile.wrap) * scale;
544                let y = point.y * scale - f64::from(tile.canonical.y);
545                Point::new(to_vertex_coordinate(x * extent), to_vertex_coordinate(y * extent))
546            })
547            .collect();
548
549        // A changed image gets a new tile, whose id tells the layers to make
550        // its texture.
551        let tile = match &mut self.tile {
552            Some(tile) if Arc::ptr_eq(&tile.image, &image) => tile,
553            slot => slot.insert(ImageTile::new(image)),
554        };
555
556        // The globe bends the quad over the sphere with the tile mesh
557        // granularity of its tile. Two triangles draw a parallelogram's
558        // affine warp and a projective warp exactly; one blended towards the
559        // bilinear warp is neither, and would bend along their diagonal, so
560        // it draws on a grid. A concave quad's bilinear warp folds over
561        // itself, out of the quad: it draws on two triangles split along the
562        // diagonal inside it.
563        let warp = image_warp(&geom_coords);
564        let concave = concave_corner(&geom_coords);
565        let cells = if view.is_globe() {
566            SubdivisionGranularitySetting::globe().tile.granularity_for_zoom_level(self.tile_ids[0].canonical.z)
567        } else if warp.blend > 0.0 && !is_parallelogram(&geom_coords) && concave.is_none() {
568            BLENDED_WARP_CELLS
569        } else {
570            1
571        };
572        if !tile.has_mesh() || geom_coords != self.mesh_corners || cells != self.mesh_cells {
573            build_image_mesh(tile, cells, matches!(concave, Some(0 | 2)));
574            tile.quad = ImageQuad::new(&geom_coords, &warp);
575            let mut bounds = [i32::MAX, i32::MAX, i32::MIN, i32::MIN];
576            for corner in &geom_coords {
577                let (x, y) = (i32::from(corner.x), i32::from(corner.y));
578                bounds = [bounds[0].min(x), bounds[1].min(y), bounds[2].max(x), bounds[3].max(y)];
579            }
580            tile.bounds = bounds;
581            self.mesh_corners = geom_coords;
582            self.mesh_cells = cells;
583        }
584    }
585
586    /// Makes a render tile of each tile the image draws in, once it has
587    /// arrived. An image shrunk out of sight or out of view draws in none.
588    fn update_render_tiles(&mut self, _store: &mut TileStore, parameters: &RenderTileParameters<'_>) {
589        self.render_tiles.clear();
590        self.order.clear();
591        if !self.base.enabled || !self.loaded() {
592            return;
593        }
594        for (index, id) in self.tile_ids.iter().enumerate() {
595            let mut tile = RenderTile::of_tile_id(*id, id.overscale_to(id.canonical.z), false);
596            tile.set_projection(parameters.transform);
597            self.render_tiles.push(tile);
598            self.order.push(index);
599        }
600    }
601
602    /// A disabled source's tile ids and corners may be of other
603    /// coordinates: it draws in no tile.
604    fn release_render_data(&mut self) {
605        self.render_tiles.clear();
606        self.order.clear();
607    }
608
609    fn upload(&mut self, _store: &mut TileStore, context: &mut Context) {
610        if let Some(tile) = &mut self.tile {
611            tile.upload(context);
612        }
613    }
614
615    fn render_tiles(&self) -> &[RenderTile] {
616        &self.render_tiles
617    }
618
619    /// The tiles in the order they cover the image, for every order: they
620    /// are copies of one tile.
621    fn tile_order(&self, _order: TileOrder) -> Option<&[usize]> {
622        Some(&self.order)
623    }
624
625    fn tile_contents<'a>(&'a self, _store: &'a TileStore, contents: &mut Vec<Option<TileContent<'a>>>) {
626        let tile = self.tile.as_ref().map(TileContent::Image);
627        contents.extend(self.render_tiles.iter().map(|_| tile));
628    }
629
630    fn dump_debug_logs(&self) {
631        tracing::info!(
632            target: log_target::GENERAL,
633            "Image source {}: loaded {}",
634            self.base.style_source.id(),
635            self.loaded()
636        );
637    }
638
639    fn max_zoom(&self) -> Option<u8> {
640        None
641    }
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    // In a registered projection, an image's tiles are those that the
649    // rectangle of its corners reaches into, so that a far edge on a tile's
650    // edge takes no tile past it.
651    #[test]
652    fn a_far_edge_on_a_tile_edge_takes_no_tile_past_it() {
653        let cover = world_square_cover(Point::new(0.25, 0.4), Point::new(0.5, 0.6), 2);
654        assert_eq!(vec![UnwrappedTileID::new(2, 1, 1), UnwrappedTileID::new(2, 1, 2)], cover);
655        assert_eq!(Vec::<UnwrappedTileID>::new(), world_square_cover(Point::new(1.1, 0.4), Point::new(1.2, 0.6), 2));
656    }
657}