Skip to main content

nadir_render/
tiles.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Tile layers: grids of tiles from a tile set, which the renderer draws in
16//! chunks of [`TileLayer::CHUNK`] × [`TileLayer::CHUNK`] tiles
17//! (`docs/subsystems/render.md`, "Tilemaps"; ADR-0023).
18
19use std::fmt;
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use nadir_assets::Handle;
23use nadir_core::{GenArena, IVec2, Rect, UVec2, Vec2};
24
25use crate::{Flip, Texture};
26
27/// A tile atlas: a texture cut into `columns` × `rows` equal tiles,
28/// numbered row by row from the top left.
29///
30/// In pixel-perfect mode a tile shows each texel as a whole number of
31/// pixels when the texture's width and height are whole multiples of the
32/// columns and rows, and the layer's tile size times the zoom is a whole
33/// multiple of a tile's texels, as for sprites (ADR-0018).
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct TileSet {
36    /// The texture.
37    pub texture: Handle<Texture>,
38    /// The tiles across. 0 counts as 1.
39    pub columns: u16,
40    /// The tiles down. 0 counts as 1.
41    pub rows: u16,
42}
43
44impl TileSet {
45    /// The region of the texture, normalized, of the block of `size` tiles
46    /// whose top-left tile is `index`: of that one tile for a size of
47    /// (1, 1). A tall tile is drawn as a sprite of such a block.
48    ///
49    /// An index past the last tile wraps around to the first, as in a
50    /// layer. A block that does not fit reaches past the texture's edge.
51    pub fn block_uv(&self, index: u16, size: UVec2) -> Rect {
52        let columns = u32::from(self.columns.max(1));
53        let rows = u32::from(self.rows.max(1));
54        let index = u32::from(index) % (columns * rows);
55        let corner = UVec2::new(index % columns, index / columns).as_vec2();
56        let grid = UVec2::new(columns, rows).as_vec2();
57        Rect::new(corner / grid, (corner + size.as_vec2()) / grid)
58    }
59}
60
61/// What a cell shows: a tile of its layer's tile set, or the frames of an
62/// animation, which the shader picks from [`RenderFrame::time`] with no
63/// work on the CPU.
64///
65/// [`RenderFrame::time`]: crate::RenderFrame::time
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub struct Tile {
68    /// The tile, or the first frame. An index past the tile set's last
69    /// tile wraps around to the first.
70    pub index: u16,
71    /// How many frames: tiles `index`, `index + 1` and so on, each shown in
72    /// turn, then again from the first. 0 and 1 are a still tile.
73    pub frames: u16,
74    /// How long each frame shows, in milliseconds. 0 counts as 1. Every
75    /// tile of the same frame length changes frame at the same moment.
76    pub frame_ms: u16,
77    /// Which way the tile is mirrored, in place.
78    pub flip: Flip,
79}
80
81impl Tile {
82    /// Tile `index`, still and unmirrored.
83    pub const fn new(index: u16) -> Self {
84        Self::animated(index, 1, 0)
85    }
86
87    /// `frames` tiles from `index`, each shown for `frame_ms`
88    /// milliseconds in turn.
89    pub const fn animated(index: u16, frames: u16, frame_ms: u16) -> Self {
90        Self {
91            index,
92            frames,
93            frame_ms,
94            flip: Flip { x: false, y: false },
95        }
96    }
97}
98
99/// The `f32`s of one tile instance, in the order of the `tile_chunk`
100/// shader's instance attributes (locations 0 and 1):
101///
102/// | Floats | Location | What |
103/// | :- | :- | :- |
104/// | 0, 1 | 0 | cell: its column and row in the layer |
105/// | 2 to 5 | 1 | tile: index, frames, frame length in ms, flip (1: x, 2: y) |
106pub const TILE_INSTANCE_FLOATS: usize = 6;
107
108/// The last revision handed out. Revisions are counted for the whole
109/// process, so that no two contents of a chunk, in any layer of any store,
110/// share one, and the renderer's cache can never take a chunk for one it
111/// has built (ADR-0023). 0 is never handed out.
112static REVISIONS: AtomicU64 = AtomicU64::new(0);
113
114fn next_revision() -> u64 {
115    // Only uniqueness matters, which every ordering keeps.
116    REVISIONS.fetch_add(1, Ordering::Relaxed) + 1
117}
118
119/// A layer of tiles: a grid of square cells in the world, each empty or
120/// showing a [`Tile`] of the layer's [`TileSet`].
121///
122/// Cell `(0, 0)` has its top-left corner at the origin; `x` grows to the
123/// right and `y` down, as in a `TileGrid` of the collision crate. The
124/// renderer draws a layer in chunks of [`TileLayer::CHUNK`] cells a side,
125/// those that the view shows, and packs a chunk's tiles again only after
126/// one of them changes.
127#[derive(Clone, Debug)]
128pub struct TileLayer {
129    tileset: TileSet,
130    size: UVec2,
131    tile_size: f32,
132    origin: Vec2,
133    /// Row by row.
134    cells: Vec<Option<Tile>>,
135    /// The revision of each chunk's contents, row by row: a new one each
136    /// time one of its cells changes.
137    revisions: Vec<u64>,
138}
139
140impl TileLayer {
141    /// The side of a chunk, in cells.
142    pub const CHUNK: u32 = 32;
143
144    /// A layer of `size` cells, columns by rows, all empty, of `tile_size`
145    /// world units a side, with its top-left corner at `origin`. A layer
146    /// with no columns or no rows draws nothing.
147    ///
148    /// Cells are placed in `f32`, exactly up to 2^24 cells a side.
149    ///
150    /// # Panics
151    ///
152    /// If `tile_size` is not a finite number above 0, or the layer has more
153    /// cells than memory can count.
154    pub fn new(tileset: TileSet, size: UVec2, tile_size: f32, origin: Vec2) -> Self {
155        assert!(
156            tile_size.is_finite() && tile_size > 0.0,
157            "a tile layer's tiles must have a finite size above 0, not {tile_size}"
158        );
159        let cells = usize::try_from(u64::from(size.x) * u64::from(size.y))
160            .expect("a tile layer has no more cells than memory can count");
161        let chunks = Self::chunks_of(size);
162        let revision = next_revision();
163        Self {
164            tileset,
165            size,
166            tile_size,
167            origin,
168            cells: vec![None; cells],
169            revisions: vec![revision; (chunks.x * chunks.y) as usize],
170        }
171    }
172
173    /// The tile set.
174    pub fn tileset(&self) -> TileSet {
175        self.tileset
176    }
177
178    /// The number of cells: columns by rows.
179    pub fn size(&self) -> UVec2 {
180        self.size
181    }
182
183    /// The side of a cell, in world units.
184    pub fn tile_size(&self) -> f32 {
185        self.tile_size
186    }
187
188    /// The top-left corner of cell `(0, 0)`.
189    pub fn origin(&self) -> Vec2 {
190        self.origin
191    }
192
193    /// The number of chunks: columns by rows. The last of a row or column
194    /// may be cut short by the layer's edge.
195    pub fn chunks(&self) -> UVec2 {
196        Self::chunks_of(self.size)
197    }
198
199    fn chunks_of(size: UVec2) -> UVec2 {
200        UVec2::new(size.x.div_ceil(Self::CHUNK), size.y.div_ceil(Self::CHUNK))
201    }
202
203    /// The tile of `cell`: `None` if it is empty, or outside the layer.
204    pub fn get(&self, cell: IVec2) -> Option<Tile> {
205        self.index(cell).and_then(|index| self.cells[index])
206    }
207
208    /// Shows `tile` in `cell`, or empties it with `None`. The chunk that
209    /// holds the cell is packed again before it is next drawn, if this
210    /// changed it.
211    ///
212    /// # Panics
213    ///
214    /// If `cell` is outside the layer.
215    pub fn set(&mut self, cell: IVec2, tile: Option<Tile>) {
216        let Some(index) = self.index(cell) else {
217            panic!(
218                "cell ({}, {}) is outside the {} × {} tile layer",
219                cell.x, cell.y, self.size.x, self.size.y
220            );
221        };
222        if self.cells[index] != tile {
223            self.cells[index] = tile;
224            // `index` found the cell inside the layer, so it is not
225            // negative.
226            let chunk = self.chunk_index(UVec2::new(
227                cell.x as u32 / Self::CHUNK,
228                cell.y as u32 / Self::CHUNK,
229            ));
230            self.revisions[chunk] = next_revision();
231        }
232    }
233
234    /// Appends the instances of the tiles of chunk `chunk` (its column and
235    /// row of chunks) to `out`, row by row, skipping empty cells:
236    /// [`TILE_INSTANCE_FLOATS`] floats each, as the renderer uploads them.
237    /// Returns how many there are; none for a chunk outside the layer.
238    ///
239    /// The renderer does this for each chunk the view shows that changed
240    /// since it last did. It is public so that it can be measured.
241    pub fn pack_chunk(&self, chunk: UVec2, out: &mut Vec<f32>) -> u32 {
242        let chunks = self.chunks();
243        if chunk.x >= chunks.x || chunk.y >= chunks.y {
244            return 0;
245        }
246        let first = chunk * Self::CHUNK;
247        let end = (first + UVec2::splat(Self::CHUNK)).min(self.size);
248        let mut count = 0;
249        for y in first.y..end.y {
250            let row = y as usize * self.size.x as usize;
251            for x in first.x..end.x {
252                let Some(tile) = self.cells[row + x as usize] else {
253                    continue;
254                };
255                let flip = u8::from(tile.flip.x) | u8::from(tile.flip.y) << 1;
256                out.extend_from_slice(&[
257                    x as f32,
258                    y as f32,
259                    f32::from(tile.index),
260                    f32::from(tile.frames),
261                    f32::from(tile.frame_ms),
262                    f32::from(flip),
263                ]);
264                count += 1;
265            }
266        }
267        count
268    }
269
270    /// The revision of the contents of chunk `chunk`, counted row by row. A
271    /// new one comes from the counter for the whole process each time the
272    /// chunk changes, so two chunks share one only when they hold the same:
273    /// a new layer's chunks, all empty, or a copy and its original.
274    pub(crate) fn revision(&self, chunk: usize) -> u64 {
275        self.revisions[chunk]
276    }
277
278    /// The index of chunk `chunk` in `revisions`; it must be in the layer.
279    pub(crate) fn chunk_index(&self, chunk: UVec2) -> usize {
280        chunk.y as usize * self.chunks().x as usize + chunk.x as usize
281    }
282
283    /// The index of `cell` in `cells`, if it is in the layer.
284    fn index(&self, cell: IVec2) -> Option<usize> {
285        let x = u32::try_from(cell.x).ok().filter(|&x| x < self.size.x)?;
286        let y = u32::try_from(cell.y).ok().filter(|&y| y < self.size.y)?;
287        Some(y as usize * self.size.x as usize + x as usize)
288    }
289}
290
291/// The game's tile layers. The renderer is given them beside each frame,
292/// whose [`TileLayerDraw`]s name the ones to draw, as its sprites name
293/// textures in the asset server (ADR-0023).
294#[derive(Default)]
295pub struct TileLayers {
296    layers: GenArena<TileLayer>,
297}
298
299impl TileLayers {
300    /// No layers.
301    pub fn new() -> Self {
302        Self::default()
303    }
304
305    /// Adds `layer`, and returns its handle.
306    ///
307    /// # Panics
308    ///
309    /// If there would be more than `u32::MAX` layers at once.
310    pub fn add(&mut self, layer: TileLayer) -> Handle<TileLayer> {
311        Handle::new(self.layers.insert(layer))
312    }
313
314    /// The layer of `handle`, if it is still here.
315    pub fn get(&self, handle: Handle<TileLayer>) -> Option<&TileLayer> {
316        self.layers.get(handle.id())
317    }
318
319    /// The layer of `handle`, to change, if it is still here.
320    pub fn get_mut(&mut self, handle: Handle<TileLayer>) -> Option<&mut TileLayer> {
321        self.layers.get_mut(handle.id())
322    }
323
324    /// Takes the layer of `handle` out. The renderer then frees what it
325    /// keeps of it on the GPU, at its next frame.
326    pub fn remove(&mut self, handle: Handle<TileLayer>) -> Option<TileLayer> {
327        self.layers.remove(handle.id())
328    }
329
330    /// The number of layers.
331    pub fn len(&self) -> usize {
332        self.layers.len()
333    }
334
335    /// Whether there are none.
336    pub fn is_empty(&self) -> bool {
337        self.layers.is_empty()
338    }
339}
340
341impl fmt::Debug for TileLayers {
342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343        f.debug_struct("TileLayers")
344            .field("len", &self.layers.len())
345            .finish_non_exhaustive()
346    }
347}
348
349/// A tile layer to draw in a frame.
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
351pub struct TileLayerDraw {
352    /// The layer, in the [`TileLayers`] the renderer is given. One that is
353    /// not there, or whose tile set's texture is not ready, is not drawn.
354    pub tiles: Handle<TileLayer>,
355    /// Higher layers are drawn in front of lower ones, sprites and tiles
356    /// alike.
357    pub layer: u8,
358    /// Where the tiles are among the sprites of their layer, as a sprite's
359    /// [`SortMode::Fixed`](crate::SortMode::Fixed): at 0 behind every
360    /// y-sorted sprite, at `u32::MAX` in front of every one. They are drawn
361    /// before the sprites of the same layer and depth, so tiles over every
362    /// sprite of a layer go in a higher layer.
363    pub depth: u32,
364}
365
366impl TileLayerDraw {
367    /// The tiles of `tiles`, in layer 0, behind every sprite there.
368    pub const fn new(tiles: Handle<TileLayer>) -> Self {
369        Self {
370            tiles,
371            layer: 0,
372            depth: 0,
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use nadir_core::GenIndex;
380
381    use super::*;
382
383    fn tileset() -> TileSet {
384        TileSet {
385            texture: Handle::new(GenIndex::new(0, std::num::NonZeroU32::MIN)),
386            columns: 8,
387            rows: 4,
388        }
389    }
390
391    /// A layer of `width` × `height` 16-pixel cells at the origin.
392    fn layer(width: u32, height: u32) -> TileLayer {
393        TileLayer::new(tileset(), UVec2::new(width, height), 16.0, Vec2::ZERO)
394    }
395
396    fn revisions(layer: &TileLayer) -> Vec<u64> {
397        layer.revisions.clone()
398    }
399
400    #[test]
401    fn a_layer_is_cut_into_chunks_the_last_ones_short() {
402        assert_eq!(layer(64, 48).chunks(), UVec2::new(2, 2));
403        assert_eq!(layer(33, 1).chunks(), UVec2::new(2, 1));
404        assert_eq!(layer(32, 32).chunks(), UVec2::new(1, 1));
405        assert_eq!(layer(0, 10).chunks(), UVec2::new(0, 1));
406        assert!(layer(0, 10).revisions.is_empty());
407    }
408
409    #[test]
410    fn a_change_marks_only_its_own_chunk() {
411        let mut layer = layer(64, 48);
412        let before = revisions(&layer);
413        // The last cell of chunk (0, 0), and the first of chunk (1, 0).
414        layer.set(IVec2::new(31, 0), Some(Tile::new(3)));
415        let after = revisions(&layer);
416        assert_ne!(after[0], before[0]);
417        assert_eq!(after[1..], before[1..]);
418        layer.set(IVec2::new(32, 0), Some(Tile::new(3)));
419        let later = revisions(&layer);
420        assert_eq!(later[0], after[0]);
421        assert_ne!(later[1], after[1]);
422        assert_eq!(later[2..], after[2..]);
423        // Row 32 is in the second row of chunks, short of 48.
424        layer.set(IVec2::new(63, 47), Some(Tile::new(1)));
425        assert_ne!(revisions(&layer)[3], later[3]);
426        assert_eq!(layer.get(IVec2::new(63, 47)), Some(Tile::new(1)));
427    }
428
429    #[test]
430    fn setting_what_is_there_changes_nothing() {
431        let mut layer = layer(40, 40);
432        layer.set(IVec2::new(5, 5), Some(Tile::new(2)));
433        let before = revisions(&layer);
434        layer.set(IVec2::new(5, 5), Some(Tile::new(2)));
435        layer.set(IVec2::new(6, 5), None);
436        assert_eq!(revisions(&layer), before);
437        // Emptying a cell is a change.
438        layer.set(IVec2::new(5, 5), None);
439        assert_ne!(revisions(&layer)[0], before[0]);
440        assert_eq!(layer.get(IVec2::new(5, 5)), None);
441    }
442
443    #[test]
444    fn cells_outside_are_empty() {
445        let layer = layer(4, 4);
446        for cell in [(-1, 0), (0, -1), (4, 0), (0, 4), (i32::MIN, i32::MAX)] {
447            assert_eq!(layer.get(IVec2::new(cell.0, cell.1)), None, "{cell:?}");
448        }
449    }
450
451    #[test]
452    #[should_panic(expected = "outside the 4 × 4 tile layer")]
453    fn setting_a_cell_outside_panics() {
454        layer(4, 4).set(IVec2::new(4, 0), Some(Tile::new(0)));
455    }
456
457    #[test]
458    #[should_panic(expected = "finite size above 0")]
459    fn tiles_have_a_size() {
460        TileLayer::new(tileset(), UVec2::ONE, 0.0, Vec2::ZERO);
461    }
462
463    #[test]
464    fn no_two_layers_share_a_revision_however_they_were_made() {
465        // The same size, filled in the same order with other tiles: a
466        // layer put in another's place must not look built.
467        let fill = |index: u16| {
468            let mut layer = layer(40, 40);
469            for y in 0..40 {
470                for x in 0..40 {
471                    layer.set(IVec2::new(x, y), Some(Tile::new(index)));
472                }
473            }
474            layer
475        };
476        let (a, b) = (fill(1), fill(2));
477        for (a, b) in a.revisions.iter().zip(&b.revisions) {
478            assert_ne!(a, b);
479        }
480        let (c, d) = (layer(40, 40), layer(40, 40));
481        assert_ne!(c.revisions, d.revisions);
482        // A copy has the same contents, so the same revisions.
483        assert_eq!(a.clone().revisions, a.revisions);
484        assert!(!a.revisions.contains(&0));
485    }
486
487    #[test]
488    fn two_layers_changed_in_turn_never_reach_the_same_revision() {
489        // Revisions counted per layer, even from a fresh start each, would
490        // meet here.
491        let (mut a, mut b) = (layer(4, 4), layer(4, 4));
492        let mut seen_a = std::collections::HashSet::new();
493        let mut seen_b = std::collections::HashSet::new();
494        for turn in 0..50_000u16 {
495            a.set(IVec2::ZERO, Some(Tile::new(turn % 2)));
496            seen_a.insert(a.revisions[0]);
497            if turn % 3 != 0 {
498                b.set(IVec2::ZERO, Some(Tile::new(turn % 2)));
499            }
500            seen_b.insert(b.revisions[0]);
501        }
502        assert!(seen_a.is_disjoint(&seen_b));
503    }
504
505    #[test]
506    fn a_chunk_packs_its_tiles_row_by_row() {
507        let mut layer = layer(40, 34);
508        let mut flipped = Tile::animated(9, 4, 120);
509        flipped.flip = Flip { x: true, y: true };
510        layer.set(IVec2::new(33, 1), Some(flipped));
511        layer.set(IVec2::new(32, 0), Some(Tile::new(7)));
512        layer.set(IVec2::new(0, 0), Some(Tile::new(1)));
513        layer.set(IVec2::new(39, 33), Some(Tile::new(2)));
514        let mut out = vec![-1.0];
515        assert_eq!(layer.pack_chunk(UVec2::new(1, 0), &mut out), 2);
516        assert_eq!(
517            out,
518            [
519                -1.0, // what was there stays
520                32.0, 0.0, 7.0, 1.0, 0.0, 0.0, //
521                33.0, 1.0, 9.0, 4.0, 120.0, 3.0,
522            ]
523        );
524        out.clear();
525        assert_eq!(layer.pack_chunk(UVec2::new(1, 1), &mut out), 1);
526        assert_eq!(out, [39.0, 33.0, 2.0, 1.0, 0.0, 0.0]);
527        out.clear();
528        assert_eq!(layer.pack_chunk(UVec2::new(2, 0), &mut out), 0);
529        assert_eq!(layer.pack_chunk(UVec2::new(0, 2), &mut out), 0);
530        assert!(out.is_empty());
531    }
532
533    #[test]
534    fn a_block_of_tiles_is_its_part_of_the_atlas() {
535        let set = tileset();
536        // Tile 11 of 8 × 4 is column 3, row 1.
537        assert_eq!(
538            set.block_uv(11, UVec2::ONE),
539            Rect::new(Vec2::new(3.0 / 8.0, 0.25), Vec2::new(0.5, 0.5))
540        );
541        // Two wide, three high, from tile 4.
542        assert_eq!(
543            set.block_uv(4, UVec2::new(2, 3)),
544            Rect::new(Vec2::new(0.5, 0.0), Vec2::new(0.75, 0.75))
545        );
546        // Past the last tile, it wraps; 0 columns and rows count as 1.
547        assert_eq!(set.block_uv(33, UVec2::ONE), set.block_uv(1, UVec2::ONE));
548        let single = TileSet {
549            columns: 0,
550            rows: 0,
551            ..set
552        };
553        assert_eq!(
554            single.block_uv(5, UVec2::ONE),
555            Rect::new(Vec2::ZERO, Vec2::ONE)
556        );
557    }
558
559    #[test]
560    fn layers_come_and_go_by_handle() {
561        let mut layers = TileLayers::new();
562        let a = layers.add(layer(2, 2));
563        let b = layers.add(layer(3, 3));
564        assert_eq!(layers.len(), 2);
565        assert_eq!(layers.get(b).map(TileLayer::size), Some(UVec2::new(3, 3)));
566        layers
567            .get_mut(a)
568            .expect("a is there")
569            .set(IVec2::ZERO, Some(Tile::new(1)));
570        assert!(layers.remove(a).is_some());
571        assert!(layers.get(a).is_none());
572        // A new layer in a's slot has another handle.
573        let c = layers.add(layer(2, 2));
574        assert_ne!(a, c);
575        assert!(layers.get(a).is_none());
576        assert_eq!(format!("{layers:?}"), "TileLayers { len: 2, .. }");
577    }
578}