Skip to main content

nadir_render/
atlas.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//! The atlas asset: a cooked atlas file, `atlas/<group>.kbj`, which says
16//! where each sprite's frames are on the atlas's pages (ADR-0033), and the
17//! clips an Aseprite export's tags make of them (ADR-0035).
18
19use std::time::Duration;
20
21use nadir_assets::{
22    Asset, AssetError, AssetPath, AssetServer, DecodeCtx, FinalizeCtx, Handle, Scope,
23};
24use nadir_codec::atlas::{self, SpriteKind};
25use nadir_core::{Rect, UVec2, Vec2};
26
27use crate::{Texture, TileSet};
28
29/// An atlas the cook made: its pages, and its sprites by name, each with
30/// its frames on the pages and its clips. A game loads it, then its pages as
31/// the [`Texture`]s they are ([`Atlas::load_pages`]).
32///
33/// It needs no GPU, so [`Asset::finalize`] needs nothing in its context,
34/// and a game can make it before its window opens, with
35/// [`AssetServer::load_now`](nadir_assets::AssetServer::load_now). It has
36/// no placeholder: a sprite that is not there has no region to stand in
37/// for.
38#[derive(Clone, Debug, PartialEq)]
39pub struct Atlas {
40    pages: Vec<AtlasPage>,
41    sprites: Vec<AtlasSprite>,
42}
43
44/// A page of an atlas: a texture of its own.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct AtlasPage {
47    path: String,
48    size: UVec2,
49}
50
51/// A sprite of an atlas: an image, a sheet of frames, an Aseprite export,
52/// or a tile set.
53#[derive(Clone, Debug, PartialEq)]
54pub struct AtlasSprite {
55    name: String,
56    frames: Vec<AtlasFrame>,
57    pivot: Option<Vec2>,
58    tile_size: Option<UVec2>,
59    clips: Vec<AtlasClip>,
60}
61
62/// A clip of a sprite, from a tag of its Aseprite export: frames of the
63/// sprite shown one after another, looping or once. The facade makes a
64/// `Clip` of each (`Clips::add_atlas`).
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct AtlasClip {
67    name: String,
68    looping: bool,
69    frames: Vec<AtlasClipFrame>,
70}
71
72/// One step of an [`AtlasClip`]: a frame of its sprite, shown for a time.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct AtlasClipFrame {
75    frame: usize,
76    duration: Duration,
77}
78
79/// Where a frame is on its page, trimmed to its pixels, and where it was in
80/// its untrimmed cell.
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub struct AtlasFrame {
83    page: usize,
84    uv: Rect,
85    size: UVec2,
86    offset: UVec2,
87    source_size: UVec2,
88}
89
90impl Atlas {
91    /// The pages: the packed pages, then the tile sets'.
92    pub fn pages(&self) -> &[AtlasPage] {
93        &self.pages
94    }
95
96    /// The page of `frame`.
97    pub fn page(&self, frame: &AtlasFrame) -> Option<&AtlasPage> {
98        self.pages.get(frame.page)
99    }
100
101    /// Loads every page with `server`, in `scope`, as a [`Texture`], and
102    /// returns their handles in the order of [`Atlas::pages`], so that a
103    /// frame's texture is `handles[frame.page()]`. Load the pages in the
104    /// scope the atlas was loaded in, so that unloading it frees them too.
105    pub fn load_pages(&self, server: &mut AssetServer, scope: Scope) -> Vec<Handle<Texture>> {
106        self.pages
107            .iter()
108            .map(|page| server.load_in(&page.path, scope))
109            .collect()
110    }
111
112    /// The sprites, in byte order of their names.
113    pub fn sprites(&self) -> &[AtlasSprite] {
114        &self.sprites
115    }
116
117    /// The sprite named `name`: the image's path in the source assets
118    /// without `.png`, such as `sprites/person`.
119    pub fn sprite(&self, name: &str) -> Option<&AtlasSprite> {
120        let index = self
121            .sprites
122            .binary_search_by(|sprite| sprite.name.as_bytes().cmp(name.as_bytes()))
123            .ok()?;
124        self.sprites.get(index)
125    }
126}
127
128impl AtlasPage {
129    /// Its path among the cooked files, such as `atlas/sprites_0.qoi`, to
130    /// load it by.
131    pub fn path(&self) -> &str {
132        &self.path
133    }
134
135    /// Its size in pixels.
136    pub fn size(&self) -> UVec2 {
137        self.size
138    }
139}
140
141impl AtlasSprite {
142    /// Its name.
143    pub fn name(&self) -> &str {
144        &self.name
145    }
146
147    /// Its frames, in the sheet's order: one at least.
148    pub fn frames(&self) -> &[AtlasFrame] {
149        &self.frames
150    }
151
152    /// Frame `index`.
153    pub fn frame(&self, index: usize) -> Option<&AtlasFrame> {
154        self.frames.get(index)
155    }
156
157    /// Its pivot, in its untrimmed frame's pixels, from (0, 0) at the
158    /// top-left corner: `None` for a tile set.
159    pub fn pivot(&self) -> Option<Vec2> {
160        self.pivot
161    }
162
163    /// A tile's width and height in pixels, if it is a tile set.
164    pub fn tile_size(&self) -> Option<UVec2> {
165        self.tile_size
166    }
167
168    /// Its clips, in byte order of their names: none for a tile set, or for
169    /// a sprite that is not an Aseprite export with tags.
170    pub fn clips(&self) -> &[AtlasClip] {
171        &self.clips
172    }
173
174    /// Its clip named `name`, the tag's name, such as `walk`.
175    pub fn clip(&self, name: &str) -> Option<&AtlasClip> {
176        let index = self
177            .clips
178            .binary_search_by(|clip| clip.name.as_bytes().cmp(name.as_bytes()))
179            .ok()?;
180        self.clips.get(index)
181    }
182
183    /// It as a tile set of `texture`, which must be its page, if it is one.
184    pub fn tile_set(&self, texture: Handle<Texture>) -> Option<TileSet> {
185        let tile = self.tile_size?;
186        let size = self.frames.first()?.source_size;
187        Some(TileSet {
188            texture,
189            columns: u16::try_from(size.x / tile.x).ok()?,
190            rows: u16::try_from(size.y / tile.y).ok()?,
191        })
192    }
193}
194
195impl AtlasClip {
196    /// Its name within its sprite: not empty, with no `/`.
197    pub fn name(&self) -> &str {
198        &self.name
199    }
200
201    /// Whether it starts again at its end; otherwise it stops on its last
202    /// frame.
203    pub fn is_looping(&self) -> bool {
204        self.looping
205    }
206
207    /// What it shows, in order: one at least.
208    pub fn frames(&self) -> &[AtlasClipFrame] {
209        &self.frames
210    }
211}
212
213impl AtlasClipFrame {
214    /// The frame, an index into its sprite's [`AtlasSprite::frames`].
215    pub fn frame(&self) -> usize {
216        self.frame
217    }
218
219    /// How long it shows: a whole number of milliseconds, 1 or more.
220    pub fn duration(&self) -> Duration {
221        self.duration
222    }
223}
224
225impl AtlasFrame {
226    /// Its page, an index into [`Atlas::pages`].
227    pub fn page(&self) -> usize {
228        self.page
229    }
230
231    /// Its region of its page, normalized: (0, 0) to (1, 1) is all of it.
232    /// For an empty frame, an empty region.
233    pub fn uv(&self) -> Rect {
234        self.uv
235    }
236
237    /// Its size once trimmed, in pixels: (0, 0) for an empty frame.
238    pub fn size(&self) -> UVec2 {
239        self.size
240    }
241
242    /// How far its top-left corner is from its untrimmed cell's.
243    pub fn offset(&self) -> UVec2 {
244        self.offset
245    }
246
247    /// Its untrimmed cell's size, in pixels.
248    pub fn source_size(&self) -> UVec2 {
249        self.source_size
250    }
251
252    /// Whether it has no pixels: the cook trimmed it to nothing.
253    pub fn is_empty(&self) -> bool {
254        self.size == UVec2::ZERO
255    }
256
257    /// `pivot`, in the untrimmed cell's pixels, as a point of this frame's
258    /// trimmed quad, normalized: (0, 0) its top-left corner, (1, 1) its
259    /// bottom-right. A quad of [`AtlasFrame::size`] with that pivot at an
260    /// entity's position covers the pixels the untrimmed cell would. For an
261    /// empty frame, `pivot` over the cell's size.
262    pub fn pivot_in(&self, pivot: Vec2) -> Vec2 {
263        if self.is_empty() {
264            return pivot / self.source_size.as_vec2();
265        }
266        (pivot - self.offset.as_vec2()) / self.size.as_vec2()
267    }
268}
269
270impl Asset for Atlas {
271    type Decoded = Atlas;
272    const EXTENSIONS: &'static [&'static str] = &["kbj"];
273
274    fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Atlas, AssetError> {
275        let file = atlas::parse(bytes, ctx.limits()).map_err(AssetError::Decode)?;
276        let mut pages = Vec::with_capacity(file.pages.len());
277        for (index, page) in file.pages.into_iter().enumerate() {
278            let path = AssetPath::new(&page.path)
279                .ok()
280                .filter(|path| path.as_str() == page.path && path.extension() == Some("qoi"))
281                .ok_or_else(|| {
282                    AssetError::Invalid(format!(
283                        "page {index}, `{}`, is not the path of a QOI texture",
284                        page.path
285                    ))
286                })?;
287            pages.push(AtlasPage {
288                path: path.as_str().to_string(),
289                size: UVec2::new(page.width, page.height),
290            });
291        }
292        let sprites = file
293            .sprites
294            .into_iter()
295            .map(|sprite| AtlasSprite {
296                name: sprite.name,
297                frames: sprite
298                    .frames
299                    .iter()
300                    .map(|frame| AtlasFrame::new(frame, &pages))
301                    .collect(),
302                pivot: match sprite.kind {
303                    SpriteKind::Pivot([x, y]) => Some(Vec2::new(x, y)),
304                    _ => None,
305                },
306                tile_size: match sprite.kind {
307                    SpriteKind::Tiles([w, h]) => Some(UVec2::new(w, h)),
308                    _ => None,
309                },
310                clips: sprite
311                    .clips
312                    .into_iter()
313                    .map(|clip| AtlasClip {
314                        name: clip.name,
315                        looping: clip.looping,
316                        frames: clip
317                            .frames
318                            .iter()
319                            .map(|step| AtlasClipFrame {
320                                frame: step.frame as usize,
321                                duration: Duration::from_millis(u64::from(step.millis)),
322                            })
323                            .collect(),
324                    })
325                    .collect(),
326            })
327            .collect();
328        Ok(Atlas { pages, sprites })
329    }
330
331    fn finalize(decoded: Atlas, _: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
332        Ok(decoded)
333    }
334}
335
336impl AtlasFrame {
337    /// A frame of the file, on `pages`, which the parser has checked it
338    /// lies on.
339    fn new(frame: &atlas::Frame, pages: &[AtlasPage]) -> Self {
340        let page = frame.page as usize;
341        let page_size = pages
342            .get(page)
343            .map_or(Vec2::ONE, |page| page.size.as_vec2());
344        let corner = Vec2::new(frame.x as f32, frame.y as f32);
345        let size = UVec2::new(frame.width, frame.height);
346        Self {
347            page,
348            uv: Rect::new(corner / page_size, (corner + size.as_vec2()) / page_size),
349            size,
350            offset: UVec2::new(frame.offset_x, frame.offset_y),
351            source_size: UVec2::new(frame.source_width, frame.source_height),
352        }
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use nadir_codec::{Limits, json, kbj};
360
361    /// The atlas `text` describes, in JSON.
362    fn decoded(text: &str) -> Result<Atlas, AssetError> {
363        let value = json::parse(text, Limits::default()).expect("the test's JSON");
364        let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
365        Atlas::decode(
366            &bytes,
367            &DecodeCtx::new("atlas/sprites.kbj", Limits::default()),
368        )
369    }
370
371    const ATLAS: &str = r#"{ "version": 2,
372        "pages": [ { "path": "atlas/sprites_0.qoi", "w": 128, "h": 128 },
373                   { "path": "atlas/sprites/tiles.tiles.qoi", "w": 128, "h": 64 } ],
374        "sprites": [
375          { "name": "sprites/person",
376            "frames": [ { "page": 0, "x": 33, "y": 85, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
377                        { "page": 0, "x": 0, "y": 0, "w": 0, "h": 0, "ox": 0, "oy": 0, "sw": 12, "sh": 20 } ],
378            "pivot": [6.0, 20.0],
379            "clips": [ { "name": "blink", "loop": false, "frames": [[0, 250], [1, 40], [0, 1000]] },
380                       { "name": "stand", "loop": true, "frames": [[0, 100]] } ] },
381          { "name": "sprites/tiles",
382            "frames": [ { "page": 1, "x": 0, "y": 0, "w": 128, "h": 64, "ox": 0, "oy": 0, "sw": 128, "sh": 64 } ],
383            "tiles": [16, 16] },
384          { "name": "sprites/tree",
385            "frames": [ { "page": 0, "x": 1, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
386            "pivot": [12.0, 48.0] } ] }"#;
387
388    #[test]
389    fn sprites_are_found_by_name_with_their_regions() {
390        let atlas = decoded(ATLAS).expect("an atlas");
391        assert_eq!(atlas.pages().len(), 2);
392        assert_eq!(atlas.pages()[1].path(), "atlas/sprites/tiles.tiles.qoi");
393        assert_eq!(atlas.pages()[1].size(), UVec2::new(128, 64));
394        assert!(atlas.sprite("sprites/rock").is_none());
395        assert!(atlas.sprite("sprites").is_none());
396
397        let person = atlas.sprite("sprites/person").expect("the person");
398        assert_eq!(person.name(), "sprites/person");
399        assert_eq!(person.pivot(), Some(Vec2::new(6.0, 20.0)));
400        assert_eq!(person.tile_size(), None);
401        let frame = person.frame(0).expect("a frame");
402        assert_eq!(frame.page(), 0);
403        assert_eq!(
404            frame.uv(),
405            Rect::new(
406                Vec2::new(33.0 / 128.0, 85.0 / 128.0),
407                Vec2::new(43.0 / 128.0, 105.0 / 128.0)
408            )
409        );
410        assert_eq!(
411            (frame.size(), frame.offset(), frame.source_size()),
412            (UVec2::new(10, 20), UVec2::new(1, 0), UVec2::new(12, 20))
413        );
414        assert_eq!(
415            atlas.page(frame).map(AtlasPage::path),
416            Some("atlas/sprites_0.qoi")
417        );
418        assert!(!frame.is_empty());
419        assert!(person.frame(1).expect("a frame").is_empty());
420        assert!(person.frame(2).is_none());
421    }
422
423    #[test]
424    fn a_trimmed_frame_s_pivot_keeps_its_pixels_where_the_cell_had_them() {
425        let atlas = decoded(ATLAS).expect("an atlas");
426        let tree = atlas.sprite("sprites/tree").expect("the tree");
427        let frame = tree.frames()[0];
428        // Trimmed 4 pixels from the top: the feet stay at the bottom.
429        let pivot = frame.pivot_in(tree.pivot().expect("a pivot"));
430        assert_eq!(pivot, Vec2::new(0.5, 1.0));
431        // Placed so, the quad's top-left corner is the cell's moved by the
432        // offset.
433        let feet = Vec2::new(100.0, 200.0);
434        let corner = feet - pivot * frame.size().as_vec2();
435        let cell = feet - Vec2::new(12.0, 48.0);
436        assert_eq!(corner, cell + frame.offset().as_vec2());
437
438        let person = atlas.sprite("sprites/person").expect("the person");
439        let pivot = person.pivot().expect("a pivot");
440        assert_eq!(person.frames()[0].pivot_in(pivot), Vec2::new(0.5, 1.0));
441        // An empty frame: over its cell.
442        assert_eq!(person.frames()[1].pivot_in(pivot), Vec2::new(0.5, 1.0));
443    }
444
445    #[test]
446    fn a_tile_set_gives_its_grid() {
447        let atlas = decoded(ATLAS).expect("an atlas");
448        let tiles = atlas.sprite("sprites/tiles").expect("the tiles");
449        assert_eq!(tiles.tile_size(), Some(UVec2::new(16, 16)));
450        assert_eq!(tiles.pivot(), None);
451        let texture = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
452        let set = tiles.tile_set(texture).expect("a tile set");
453        assert_eq!((set.texture, set.columns, set.rows), (texture, 8, 4));
454        let tree = atlas.sprite("sprites/tree").expect("the tree");
455        assert_eq!(tree.tile_set(texture), None);
456    }
457
458    #[test]
459    fn a_page_whose_path_is_not_a_qoi_asset_path_is_refused() {
460        for path in [
461            "atlas/../page.qoi",
462            "atlas/page.png",
463            "Atlas/page.qoi",
464            "/atlas/page.qoi",
465        ] {
466            let text = ATLAS.replacen("atlas/sprites_0.qoi", path, 1);
467            assert_eq!(
468                decoded(&text),
469                Err(AssetError::Invalid(format!(
470                    "page 0, `{path}`, is not the path of a QOI texture"
471                ))),
472                "{path}"
473            );
474        }
475        // And the file itself is checked by the codec: version 1, which had
476        // no clips, and later ones are refused.
477        for version in [1, 9] {
478            let text = ATLAS.replacen(r#""version": 2"#, &format!(r#""version": {version}"#), 1);
479            assert!(text.contains(&format!(r#""version": {version}"#)));
480            assert!(
481                matches!(
482                    decoded(&text),
483                    Err(AssetError::Decode(nadir_codec::CodecError::Atlas { ref at, .. })) if at == "version"
484                ),
485                "version {version}"
486            );
487        }
488    }
489
490    #[test]
491    fn a_sprite_s_clips_are_found_by_name_with_their_frames_and_times() {
492        let atlas = decoded(ATLAS).expect("an atlas");
493        let person = atlas.sprite("sprites/person").expect("the person");
494        let names: Vec<&str> = person.clips().iter().map(AtlasClip::name).collect();
495        assert_eq!(names, ["blink", "stand"]);
496        let blink = person.clip("blink").expect("a clip");
497        assert!(!blink.is_looping());
498        let steps: Vec<(usize, Duration)> = blink
499            .frames()
500            .iter()
501            .map(|step| (step.frame(), step.duration()))
502            .collect();
503        assert_eq!(
504            steps,
505            [
506                (0, Duration::from_millis(250)),
507                (1, Duration::from_millis(40)),
508                (0, Duration::from_secs(1)),
509            ]
510        );
511        assert!(person.clip("stand").expect("a clip").is_looping());
512        assert!(person.clip("walk").is_none());
513        assert!(person.clip("").is_none());
514        // Sprites with none.
515        assert!(
516            atlas
517                .sprite("sprites/tree")
518                .expect("the tree")
519                .clips()
520                .is_empty()
521        );
522        assert!(
523            atlas
524                .sprite("sprites/tiles")
525                .expect("the tiles")
526                .clips()
527                .is_empty()
528        );
529    }
530
531    #[test]
532    fn its_pages_load_as_textures_in_the_scope_given() {
533        let atlas = decoded(ATLAS).expect("an atlas");
534        let mut server = AssetServer::new("no-such-folder", nadir_assets::OnFailure::Nothing);
535        let pages = atlas.load_pages(&mut server, Scope::Level);
536        assert_eq!(pages.len(), 2);
537        assert_eq!(server.path(pages[0]), Some("atlas/sprites_0.qoi"));
538        assert_eq!(server.path(pages[1]), Some("atlas/sprites/tiles.tiles.qoi"));
539        // In that scope alone: unloading it frees them.
540        assert_eq!(server.unload_scope(Scope::Level), 2);
541        assert_eq!(server.state(pages[0]), None);
542    }
543
544    #[test]
545    fn it_is_made_with_nothing_in_its_context() {
546        let atlas = decoded(ATLAS).expect("an atlas");
547        let made = Atlas::finalize(atlas.clone(), &mut FinalizeCtx::new());
548        assert_eq!(made, Ok(atlas));
549    }
550}