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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use std::{collections::HashMap, path::PathBuf, sync::Arc};

use crate::{
    asset_manager::{load_texture_from_internal_data, InternalData},
    model::{world_object::WorldSpaceObjectCollider, world_object_package::WorldObjectPackage},
};
use nalgebra as na;
use raylib::{
    camera::Camera2D,
    color::Color,
    math::{Rectangle, Vector2},
    prelude::{RaylibDraw, RaylibDrawHandle, RaylibMode2D},
    texture::Texture2D,
    RaylibHandle, RaylibThread,
};
use tiled::{Loader, Map, PropertyValue, 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>,
    world_objects: WorldObjectPackage,
}

impl MapRenderer {
    /// Construct a new MapRenderer.
    pub fn new(
        tmx_path: &str,
        objects_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);
                }
            }
        }

        // Load the world objects
        let world_objects = WorldObjectPackage::load(raylib, raylib_thread, objects_path).unwrap();

        Ok(Self {
            map,
            tile_textures,
            world_objects,
        })
    }

    /// Gets the map size
    pub fn get_map_size(&self) -> na::Vector2<f32> {
        na::Vector2::new(
            self.map.width as f32 * 128.0,
            self.map.height as f32 * 128.0,
        )
    }

    pub fn sample_friction_at(&self, world_position: na::Vector2<f32>) -> Option<f32> {
        // Convert to a tile position
        let tile_position = na::Vector2::new(
            (world_position.x / 128.0).floor() as i32,
            (world_position.y / 128.0).floor() as i32,
        );

        // If there is an object here, let it override the output
        for obj_ref in &self.world_objects.object_references {
            if obj_ref.get_world_space_position().x == tile_position.x as f32
                && obj_ref.get_world_space_position().y == tile_position.y as f32
            {
                // Get access to the actual object definition
                let object_key = obj_ref.into_key();
                let obj_def = self
                    .world_objects
                    .object_definitions
                    .get(&object_key)
                    .unwrap();

                // Check if there is a friction property
                if let Some(friction) = obj_def.friction {
                    return Some(friction);
                }
            }
        }

        // Get the first layer
        let layer = self.map.layers().next().unwrap();

        // Handle the layer type
        match layer.layer_type() {
            tiled::LayerType::TileLayer(layer) => {
                // Get the tile
                if let Some(tile) = layer.get_tile(tile_position.x, tile_position.y) {
                    if let Some(tile) = tile.get_tile() {
                        if let Some(data) = tile.data.properties.get("friction") {
                            match data {
                                PropertyValue::FloatValue(f) => Some(*f),
                                _ => None,
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    pub fn sample_temperature_at(&self, world_position: na::Vector2<f32>) -> Option<f32> {
        // Convert to a tile position
        let tile_position = na::Vector2::new(
            (world_position.x / 128.0).floor() as i32,
            (world_position.y / 128.0).floor() as i32,
        );

        // If there is an object here, let it override the output
        for obj_ref in &self.world_objects.object_references {
            if obj_ref.get_world_space_position().x == tile_position.x as f32
                && obj_ref.get_world_space_position().y == tile_position.y as f32
            {
                // Get access to the actual object definition
                let object_key = obj_ref.into_key();
                let obj_def = self
                    .world_objects
                    .object_definitions
                    .get(&object_key)
                    .unwrap();

                // Check if there is a temperature property
                if let Some(temperature) = obj_def.temperature {
                    return Some(temperature);
                }
            }
        }

        // Get the first layer
        let layer = self.map.layers().next().unwrap();

        // Handle the layer type
        match layer.layer_type() {
            tiled::LayerType::TileLayer(layer) => {
                // Get the tile
                if let Some(tile) = layer.get_tile(tile_position.x, tile_position.y) {
                    if let Some(tile) = tile.get_tile() {
                        if let Some(data) = tile.data.properties.get("temperature") {
                            match data {
                                PropertyValue::FloatValue(f) => Some(*f),
                                _ => None,
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    pub fn render_map(
        &mut self,
        draw_handle: &mut RaylibMode2D<RaylibDrawHandle>,
        camera: &Camera2D,
        show_debug_grid: bool,
        player_position: na::Vector2<f32>,
    ) {
        // 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,
        );
        let player_position = na::Vector2::new(
            player_position.x,
            player_position.y * -1.0,
        );

        // 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,
                                        );
                                    }

                                    // Check if there is an object at this tile
                                    for obj_ref in &self.world_objects.object_references {
                                        if obj_ref.get_tile_space_position().x == sampler_x as f32
                                            && obj_ref.get_tile_space_position().y == sampler_y as f32
                                        {
                                            // Get access to the actual object definition
                                            let object_key = obj_ref.into_key();
                                            // debug!("Found object: {}", object_key);
                                            let obj_def = self
                                                .world_objects
                                                .object_definitions
                                                .get(&object_key)
                                                .unwrap();

                                            // We need to render the base layer of the object
                                            if obj_def.bottom_texture.animated.unwrap_or(false) {
                                                let tex = self
                                                    .world_objects
                                                    .bottom_animated_textures
                                                    .get_mut(&object_key)
                                                    .unwrap();
                                                tex.render_automatic(
                                                    draw_handle,
                                                    obj_ref.get_world_space_position() - (tex.size() / 2.0),
                                                    None,
                                                    Some(tex.size() / 2.0),
                                                    Some(obj_ref.rotation_degrees),
                                                    None,
                                                );
                                            } else {
                                                let tex = self
                                                    .world_objects
                                                    .bottom_static_textures
                                                    .get_mut(&object_key)
                                                    .unwrap();
                                                let p: Vector2 = obj_ref.get_world_space_position().into();
                                                let r1 = Rectangle {
                                                    x: 0.0,
                                                    y: 0.0,
                                                    width: tex.width as f32,
                                                    height: tex.height as f32,
                                                };
                                                let r2 = Rectangle {
                                                    x: p.x,
                                                    y: p.y,
                                                    width: tex.width as f32,
                                                    height: tex.height as f32,
                                                };

                                                draw_handle.draw_texture_pro(
                                                    &tex,
                                                    r1,
                                                    r2,
                                                    Vector2::new(
                                                        tex.width as f32 / 2.0,
                                                        tex.height as f32 / 2.0,
                                                    ),
                                                    obj_ref.rotation_degrees,
                                                    Color::WHITE,
                                                );
                                            }

                                            // If needed we can render the top layer of the object
                                            if let Some(top_texture) = &obj_def.top_texture {
                                                // We need to detect if the player is in the footprint of the object
                                                let mut tint = Color::WHITE;
                                                if let Some(footprint_radius) =
                                                    obj_def.visualization_radius
                                                {
                                                    let player_dist_to_object =
                                                        (obj_ref.get_world_space_position() - player_position).norm();
                                                    // debug!(
                                                    //     "Player dist to object: {}",
                                                    //     player_dist_to_object
                                                    // );
                                                    if player_dist_to_object <= footprint_radius {
                                                        tint.a = 128;
                                                    }
                                                }

                                                if top_texture.animated.unwrap_or(false) {
                                                    let tex = self
                                                        .world_objects
                                                        .top_animated_textures
                                                        .get_mut(&object_key)
                                                        .unwrap();
                                                    tex.render_automatic(
                                                        draw_handle,
                                                        obj_ref.get_world_space_position() - (tex.size() / 2.0),
                                                        None,
                                                        Some(tex.size() / 2.0),
                                                        Some(obj_ref.rotation_degrees),
                                                        Some(tint),
                                                    );
                                                } else {
                                                    let tex = self
                                                        .world_objects
                                                        .top_static_textures
                                                        .get_mut(&object_key)
                                                        .unwrap();
                                                    let p: Vector2 = obj_ref.get_world_space_position().into();
                                                    let r1 = Rectangle {
                                                        x: 0.0,
                                                        y: 0.0,
                                                        width: tex.width as f32,
                                                        height: tex.height as f32,
                                                    };
                                                    let r2 = Rectangle {
                                                        x: p.x,
                                                        y: p.y,
                                                        width: tex.width as f32,
                                                        height: tex.height as f32,
                                                    };

                                                    draw_handle.draw_texture_pro(
                                                        &tex,
                                                        r1,
                                                        r2,
                                                        Vector2::new(
                                                            tex.width as f32 / 2.0,
                                                            tex.height as f32 / 2.0,
                                                        ),
                                                        obj_ref.rotation_degrees,
                                                        tint,
                                                    );
                                                }
                                            }
                                        }
                                    }

                                    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!(),
            }
        }
    }

    /// Get the list of world colliders
    pub fn get_world_colliders(&self) -> Vec<WorldSpaceObjectCollider> {
        self.world_objects.world_space_colliders.clone()
    }

    // /// Used to modify the player's velocity based on the effects of the world
    // pub fn effect_velocity_with_collisions(
    //     &self,
    //     player_position: na::Vector2<f32>,
    //     player_velocity: na::Vector2<f32>,
    // ) -> na::Vector2<f32> {
    //     // If the player is not moving, we don't need to do anything
    //     if player_velocity.norm() == 0.0 {
    //         return player_velocity;
    //     }

    //     // Get the velocity unit vector
    //     let player_velocity_unit_vector = player_velocity.normalize();

    //     // Find the position 1 pixel infront of the player
    //     let player_position_1_pixel_infront = player_position + player_velocity_unit_vector;
    //     let next_player_position = player_position + player_velocity;

    //     // Check if this is in the collision zone of any objects
    //     for obj_ref in &self.world_objects.object_references {
    //         // Filter out anything more than 1000 pixels away
    //         if (obj_ref.position - player_position).norm() > 1000.0 {
    //             continue;
    //         }

    //         // Get the object definition
    //         let object_key =  obj_ref.into_key();
    //         let obj_def = self
    //             .world_objects
    //             .object_definitions
    //             .get(&object_key)
    //             .unwrap();

    //         // Check if the player is about to be in a collision zone
    //         for collider in &obj_def.physics_colliders {
    //             // Handle a radius collider vs a size collider
    //             if let Some(radius) = collider.radius {
    //                 // Check if we are about to collide with the circle
    //                 if (next_player_position - obj_ref.position).norm() < radius {
    //                     // Get the angle from the player to the center of the collider
    //                     let angle_to_center =
    //                         (obj_ref.position - player_position).angle(&na::Vector2::new(0.0, 0.0));
    //                     if angle_to_center.abs() <= std::f32::consts::FRAC_PI_2 {
    //                         // Apply the inverse of the velocity to the player
    //                         return na::Vector2::zeros();
    //                     }
    //                 }
    //             } else if let Some(size) = collider.size {
    //                 // TODO: make this work for regular and rotated objects
    //             }
    //         }
    //     }

    //     // Check if the player is about to leave the map
    //     let mut player_velocity = player_velocity;
    //     if next_player_position.x < 0.0 {
    //         player_velocity.x = 0.0;
    //     } else if next_player_position.x > self.map.width as f32 * 128.0 {
    //         player_velocity.x = 0.0;
    //     }
    //     if next_player_position.y > 0.0 {
    //         player_velocity.y = 0.0;
    //     } else if next_player_position.y < self.map.height as f32 * -128.0 {
    //         player_velocity.y = 0.0;
    //     }

    //     // If we got here, the player is not in a collision zone
    //     player_velocity
    // }
}