Skip to main content

euv_core/game/tilemap/
impl.rs

1use super::*;
2
3/// Tile lookup, mutation, and world-space queries for `TileMap`.
4impl TileMap {
5    /// Creates an empty `columns x rows` tilemap with cell size `tile_size`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Number of columns.
10    /// - `usize` - Number of rows.
11    /// - `f32` - Tile width/height in world units.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Initialized tilemap with default air entry at index `0`.
16    #[must_use]
17    pub fn empty(columns: usize, rows: usize, tile_size: f32) -> Self {
18        let c: usize = columns.max(1);
19        let r: usize = rows.max(1);
20        Self {
21            columns: c,
22            rows: r,
23            tile_size: tile_size.max(4.0),
24            cells: vec![0; c.saturating_mul(r)],
25            palette: vec![TilePaletteEntry::new(
26                COLOR_TRANSPARENT,
27                COLOR_TRANSPARENT,
28                false,
29            )],
30        }
31    }
32
33    /// Registers a new palette entry and returns its assigned tile ID.
34    ///
35    /// # Arguments
36    ///
37    /// - `&Self` - Mutable tilemap.
38    /// - `TilePaletteEntry` - Visual and solidity properties.
39    ///
40    /// # Returns
41    ///
42    /// - `u16` - Assigned tile identifier.
43    pub fn add_palette_entry(&mut self, entry: TilePaletteEntry) -> u16 {
44        let id: u16 = self.get_palette().len() as u16;
45        self.get_mut_palette().push(entry);
46        id
47    }
48
49    /// Sets the tile identifier at grid coordinate `(col, row)`.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Mutable tilemap.
54    /// - `usize` - Column index.
55    /// - `usize` - Row index.
56    /// - `u16` - Tile identifier.
57    pub fn set_tile(&mut self, col: usize, row: usize, tile_id: u16) {
58        if col < self.get_columns() && row < self.get_rows() {
59            let idx: usize = row * self.get_columns() + col;
60            self.get_mut_cells()[idx] = tile_id;
61        }
62    }
63
64    /// Reads the tile identifier at `(col, row)`, returning `0` when out of bounds.
65    ///
66    /// # Arguments
67    ///
68    /// - `&Self` - Tilemap reference.
69    /// - `usize` - Column index.
70    /// - `usize` - Row index.
71    ///
72    /// # Returns
73    ///
74    /// - `u16` - Tile ID at `(col, row)`.
75    #[must_use]
76    pub fn tile_at(&self, col: usize, row: usize) -> u16 {
77        if col < self.get_columns() && row < self.get_rows() {
78            self.get_cells()[row * self.get_columns() + col]
79        } else {
80            0
81        }
82    }
83
84    /// Returns `true` if the world-space point `world_pt` falls inside a solid tile.
85    ///
86    /// # Arguments
87    ///
88    /// - `&Self` - Tilemap reference.
89    /// - `Point` - World-space query coordinate.
90    ///
91    /// # Returns
92    ///
93    /// - `bool` - Whether the tile at `world_pt` is solid.
94    #[must_use]
95    pub fn is_solid_at_world(&self, world_pt: Point) -> bool {
96        if world_pt.get_x() < 0.0 || world_pt.get_y() < 0.0 {
97            return false;
98        }
99        let col: usize = (world_pt.get_x() / self.get_tile_size()).floor() as usize;
100        let row: usize = (world_pt.get_y() / self.get_tile_size()).floor() as usize;
101        let tid: u16 = self.tile_at(col, row);
102        self.get_palette()
103            .get(tid as usize)
104            .map(TilePaletteEntry::get_solid)
105            .unwrap_or(false)
106    }
107
108    /// Returns total world-space dimensions `(width, height)` of the tilemap.
109    ///
110    /// # Arguments
111    ///
112    /// - `&Self` - Tilemap reference.
113    ///
114    /// # Returns
115    ///
116    /// - `Rect` - World bounds rectangle starting at `(0, 0)`.
117    #[must_use]
118    pub fn world_bounds(&self) -> Rect {
119        Rect::new(
120            0.0,
121            0.0,
122            (self.get_columns() as f32) * self.get_tile_size(),
123            (self.get_rows() as f32) * self.get_tile_size(),
124        )
125    }
126}
127
128/// Frame slicing helpers for `SpriteSheet`.
129impl SpriteSheet {
130    /// Creates a `SpriteSheet` over `texture` with fixed `(frame_width, frame_height)` cells.
131    ///
132    /// # Arguments
133    ///
134    /// - `ImageBuffer` - Backing RGBA8 sprite atlas image.
135    /// - `u32` - Width of each frame in pixels.
136    /// - `u32` - Height of each frame in pixels.
137    ///
138    /// # Returns
139    ///
140    /// - `Self` - Constructed sprite sheet.
141    #[must_use]
142    pub fn from_grid(texture: ImageBuffer, frame_width: u32, frame_height: u32) -> Self {
143        let fw: u32 = frame_width.max(1);
144        let fh: u32 = frame_height.max(1);
145        let cols: u32 = (texture.get_width() / fw).max(1);
146        Self {
147            texture,
148            frame_width: fw,
149            frame_height: fh,
150            columns: cols,
151        }
152    }
153
154    /// Computes the source pixel sub-rectangle for frame index `frame_index`.
155    ///
156    /// # Arguments
157    ///
158    /// - `&Self` - Sprite sheet reference.
159    /// - `u32` - Zero-based frame index.
160    ///
161    /// # Returns
162    ///
163    /// - `Rect` - Pixel sub-rectangle `(x, y, frame_width, frame_height)`.
164    #[must_use]
165    pub fn frame_rect(&self, frame_index: u32) -> Rect {
166        let col: u32 = frame_index % self.get_columns().max(1);
167        let row: u32 = frame_index / self.get_columns().max(1);
168        Rect::new(
169            (col * self.get_frame_width()) as f32,
170            (row * self.get_frame_height()) as f32,
171            self.get_frame_width() as f32,
172            self.get_frame_height() as f32,
173        )
174    }
175}
176
177/// Playback stepping and current-frame queries for `SpriteAnimator`.
178impl SpriteAnimator {
179    /// Advances animation playback clock by `dt_secs` and returns the active frame index.
180    ///
181    /// # Arguments
182    ///
183    /// - `&Self` - Mutable sprite animator.
184    /// - `f32` - Elapsed time delta in seconds.
185    ///
186    /// # Returns
187    ///
188    /// - `u32` - Active sprite sheet frame index.
189    pub fn tick(&mut self, dt_secs: f32) -> u32 {
190        let next: f32 = self.get_elapsed_secs() + dt_secs.max(0.0);
191        self.set_elapsed_secs(next);
192        self.current_frame()
193    }
194
195    /// Computes the active frame index from `elapsed_secs`.
196    ///
197    /// # Arguments
198    ///
199    /// - `&Self` - Sprite animator reference.
200    ///
201    /// # Returns
202    ///
203    /// - `u32` - Current sprite sheet frame index.
204    #[must_use]
205    pub fn current_frame(&self) -> u32 {
206        let count: u32 = self.get_frame_count().max(1);
207        let raw: u32 = (self.get_elapsed_secs() * self.get_fps().max(0.1)).floor() as u32;
208        let offset: u32 = if self.get_looping() {
209            raw % count
210        } else {
211            raw.min(count - 1)
212        };
213        self.get_start_frame().saturating_add(offset)
214    }
215}