Skip to main content

egui_map_view/layers/
tile.rs

1//! A layer for tile maps on the map.
2
3use egui::{Color32, Painter, Response};
4use std::{any::Any, collections::HashMap};
5
6use crate::{
7    Tile, TileId, config::MapConfig, draw_tile, layers::Layer, load_tile,
8    projection::MapProjection, visible_tiles,
9};
10
11/// A layer that manages and renders map tiles on the map view.
12pub struct TileLayer {
13    tiles: HashMap<TileId, Tile>,
14    visible_tiles: Vec<(TileId, egui::Pos2)>,
15    /// Color tint applied to the tile images when rendering
16    pub tint: Color32,
17    config: Box<dyn MapConfig>,
18}
19
20impl TileLayer {
21    /// Creates a new tile layer with the given map configuration.
22    pub fn new(config: impl MapConfig + 'static) -> Self {
23        Self {
24            tiles: Default::default(),
25            visible_tiles: Default::default(),
26            tint: Color32::WHITE,
27            config: Box::new(config),
28        }
29    }
30}
31
32impl Layer for TileLayer {
33    fn as_any(&self) -> &dyn Any {
34        self
35    }
36
37    fn as_any_mut(&mut self) -> &mut dyn Any {
38        self
39    }
40
41    fn handle_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
42        self.visible_tiles = visible_tiles(projection).collect();
43        for (tile_id, _) in &self.visible_tiles {
44            load_tile(
45                &mut self.tiles,
46                self.config.as_ref(),
47                &response.ctx,
48                *tile_id,
49            );
50        }
51        return false;
52    }
53
54    fn draw(&self, painter: &Painter, _: &MapProjection) {
55        for (tile_id, tile_pos) in &self.visible_tiles {
56            draw_tile(&self.tiles, painter, tile_id, *tile_pos, self.tint);
57        }
58    }
59}