1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
use std::{collections::HashMap, path::PathBuf, sync::Arc};

use crate::asset_manager::{load_texture_from_internal_data, InternalData};
use nalgebra as na;
use raylib::{
    camera::Camera2D,
    color::Color,
    math::Vector2,
    prelude::{RaylibDraw, RaylibDrawHandle, RaylibMode2D},
    texture::Texture2D,
    RaylibHandle, RaylibThread,
};
use tiled::{Loader, Map, ResourceCache, ResourcePath, ResourcePathBuf, Tileset};

/// Possible errors generated by the map loading process
#[derive(Debug, thiserror::Error)]
pub enum MapRenderError {
    #[error("Could not load embedded asset: {0}")]
    AssetNotFound(String),
    #[error(transparent)]
    TiledError(#[from] tiled::Error),
}

#[derive(Debug)]
struct ProgramDataTileCache {
    tilesets: HashMap<ResourcePathBuf, Arc<Tileset>>,
    internal_loader: Loader,
}

impl ProgramDataTileCache {
    fn new() -> Self {
        Self {
            tilesets: HashMap::new(),
            internal_loader: Loader::new(),
        }
    }
}

impl ResourceCache for ProgramDataTileCache {
    /// Load the tileset. First attempts to pull from an in-RAM cache, otherwise attempts to load from disk.
    fn get_tileset(&self, path: impl AsRef<ResourcePath>) -> Option<Arc<Tileset>> {
        let possibly_cached_tileset = self.tilesets.get(path.as_ref()).map(Clone::clone);
        if let Some(tileset) = possibly_cached_tileset {
            return Some(tileset);
        } else {
            // Pull the TSX from storage and parse it
            InternalData::get(path.as_ref().to_str().unwrap()).map(|file| {
                let data = file.data.into_owned();
                Arc::new(
                    self.internal_loader
                        .load_tsx_tileset_from(data.as_slice(), path)
                        .unwrap(),
                )
            })
        }
    }

    fn get_or_try_insert_tileset_with<F, E>(
        &mut self,
        path: ResourcePathBuf,
        f: F,
    ) -> Result<Arc<Tileset>, E>
    where
        F: FnOnce() -> Result<Tileset, E>,
    {
        Ok(match self.tilesets.entry(path) {
            std::collections::hash_map::Entry::Occupied(o) => o.into_mut(),
            std::collections::hash_map::Entry::Vacant(v) => v.insert(Arc::new(f()?)),
        }
        .clone())
    }
}

#[derive(Debug)]
pub struct MapRenderer {
    map: Map,
    tile_textures: HashMap<PathBuf, Texture2D>,
}

impl MapRenderer {
    /// Construct a new MapRenderer.
    pub fn new(
        tmx_path: &str,
        raylib: &mut RaylibHandle,
        raylib_thread: &RaylibThread,
    ) -> Result<Self, MapRenderError> {
        // Pull the TMX from storage
        let data = InternalData::get(tmx_path)
            .ok_or(MapRenderError::AssetNotFound(tmx_path.to_string()))?
            .data
            .into_owned();

        // Attempt to parse the TMX file
        let mut loader = Loader::with_cache(ProgramDataTileCache::new());
        let map = loader.load_tmx_map_from(data.as_slice(), tmx_path)?;

        // Iterate over all images in the map
        let mut tile_textures = HashMap::new();
        for tileset in map.tilesets() {
            for (idx, tile) in tileset.tiles() {
                if let Some(image) = &tile.data.image {
                    // We now have a path to an image
                    let image_path = image.source.clone();

                    // Load the texture
                    let texture = load_texture_from_internal_data(
                        raylib,
                        raylib_thread,
                        image_path.to_str().unwrap(),
                    )
                    .unwrap();

                    // Store the texture in the cache
                    tile_textures.insert(image_path, texture);
                }
            }
        }

        Ok(Self { map, tile_textures })
    }

    pub fn sample_friction_at(&self, position: na::Vector2<f32>) -> f32 {
        todo!()
    }

    pub fn sample_temperature_at(&self, position: na::Vector2<f32>) -> f32 {
        todo!()
    }

    pub fn render_map(&self, draw_handle: &mut RaylibMode2D<RaylibDrawHandle>, camera: &Camera2D, show_debug_grid:bool) {
        // Get the window corners in world space
        let screen_width = draw_handle.get_screen_width();
        let screen_height = draw_handle.get_screen_height();
        let world_win_top_left = draw_handle.get_screen_to_world2D(Vector2::new(0.0, 0.0), camera);
        let world_win_bottom_right = draw_handle.get_screen_to_world2D(
            Vector2::new(screen_width as f32, screen_height as f32),
            camera,
        );

        // Handle each layer from the bottom up
        for layer in self.map.layers() {
            // Handle different layer types
            match layer.layer_type() {
                tiled::LayerType::TileLayer(layer) => {
                    // Keep track of our sampler X and Y values
                    let mut sampler_x = 0;
                    let mut sampler_y = 0;

                    // Get the tile width and height
                    let tile_width = 128;
                    let tile_height = 128;

                    // Loop until we have covered all tiles on the screen
                    for y in (world_win_top_left.y as i64)..(world_win_bottom_right.y as i64) {
                        // Convert the pixel coordinates to tile coordinates
                        let tile_y = (y as f32 / tile_height as f32).floor() as i32;

                        // If we are looking at a new tile, update the sampler
                        if sampler_y != tile_y {
                            sampler_y = tile_y;

                            for x in
                                (world_win_top_left.x as i64)..(world_win_bottom_right.x as i64)
                            {
                                // Convert the pixel coordinates to tile coordinates
                                let tile_x = (x as f32 / tile_width as f32).floor() as i32;
                                // debug!("Tile: ({}, {})", tile_x, tile_y);

                                // If we are looking at a new tile, update the sampler
                                if sampler_x != tile_x {
                                    sampler_x = tile_x;

                                    // Get the tile at this coordinate
                                    if let Some(tile) = layer.get_tile(sampler_x, sampler_y) {
                                        // debug!("Tile: ({}, {})", tile_x, tile_y);
                                        // Fetch the texture for this tile
                                        let real_tile = tile.get_tile().unwrap();
                                        let texture = self
                                            .tile_textures
                                            .get(&real_tile.image.as_ref().unwrap().source)
                                            .unwrap();

                                        // Draw the tile
                                        draw_handle.draw_texture(
                                            texture,
                                            tile_x * tile_width as i32,
                                            tile_y * tile_height as i32,
                                            Color::WHITE,
                                        );
                                    } 
                                    
                                    if show_debug_grid {
                                        draw_handle.draw_rectangle_lines(
                                            tile_x * tile_width as i32,
                                            tile_y * tile_height as i32,
                                            self.map.tile_width as i32,
                                            self.map.tile_height as i32,
                                            Color::RED,
                                        );
                                        draw_handle.draw_pixel(x as i32, y as i32, Color::BLUE);
                                    }
                                }
                            }
                        }
                    }
                }
                tiled::LayerType::ObjectLayer(_) => todo!(),
                tiled::LayerType::ImageLayer(_) => todo!(),
                tiled::LayerType::GroupLayer(_) => todo!(),
            }
        }
    }
}