Skip to main content

tiles_client/
tile.rs

1use std::path::PathBuf;
2
3/// Information about the tile.
4pub struct Tile
5{
6  pub(crate) tile_x: u32,
7  pub(crate) tile_y: u32,
8  pub(crate) tile_z: u32,
9  /// Filename with the data for the tiles
10  pub(crate) filename: PathBuf,
11  pub(crate) bounding_box: geo::Rect,
12  pub(crate) image: ccutils::sync::ArcMutex<Option<image::DynamicImage>>,
13}
14
15impl Tile
16{
17  fn load_image(&self)
18  {
19    if !self.filename.exists() || self.image.lock().is_ok_and(|x| x.is_some())
20    {
21      return;
22    }
23    let image = image::open(&self.filename);
24    match image
25    {
26      Ok(image) =>
27      {
28        *self.image.lock().unwrap() = Some(image);
29      }
30      Err(e) =>
31      {
32        log::error!(
33          "Failed to read image {} with {:?}",
34          self.filename.display(),
35          e
36        );
37      }
38    }
39  }
40  /// Return the x-index
41  pub fn tile_x(&self) -> u32
42  {
43    self.tile_x
44  }
45  /// Return the y-index
46  pub fn tile_y(&self) -> u32
47  {
48    self.tile_y
49  }
50  /// Return the zoom level index
51  pub fn tile_z(&self) -> u32
52  {
53    self.tile_z
54  }
55  /// Return the bounding box, in geographic coordinates
56  pub fn bounding_box(&self) -> geo::Rect
57  {
58    self.bounding_box
59  }
60  /// Return the filename
61  pub fn filename(&self) -> &PathBuf
62  {
63    &self.filename
64  }
65  /// Return if the file was downloaded
66  pub fn is_cached(&self) -> bool
67  {
68    self.filename.exists()
69  }
70  /// Size of the tile in pixel, return `(width,height)`
71  pub fn pixel_size(&self) -> (u32, u32)
72  {
73    self.load_image();
74    self.image.lock().map_or(Default::default(), |x| {
75      x.as_ref()
76        .map_or(Default::default(), |x| (x.width(), x.height()))
77    })
78  }
79  /// rgba 8bit data
80  pub fn rgba_data(&self) -> Vec<u8>
81  {
82    self.load_image();
83    self.image.lock().map_or(Default::default(), |x| {
84      x.as_ref()
85        .map_or(Default::default(), |x| x.to_rgba8().into_raw().to_vec())
86    })
87  }
88}