use std::time::Duration;
use nadir_assets::{
Asset, AssetError, AssetPath, AssetServer, DecodeCtx, FinalizeCtx, Handle, Scope,
};
use nadir_codec::atlas::{self, SpriteKind};
use nadir_core::{Rect, UVec2, Vec2};
use crate::{Texture, TileSet};
#[derive(Clone, Debug, PartialEq)]
pub struct Atlas {
pages: Vec<AtlasPage>,
sprites: Vec<AtlasSprite>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AtlasPage {
path: String,
size: UVec2,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AtlasSprite {
name: String,
frames: Vec<AtlasFrame>,
pivot: Option<Vec2>,
tile_size: Option<UVec2>,
clips: Vec<AtlasClip>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AtlasClip {
name: String,
looping: bool,
frames: Vec<AtlasClipFrame>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AtlasClipFrame {
frame: usize,
duration: Duration,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AtlasFrame {
page: usize,
uv: Rect,
size: UVec2,
offset: UVec2,
source_size: UVec2,
}
impl Atlas {
pub fn pages(&self) -> &[AtlasPage] {
&self.pages
}
pub fn page(&self, frame: &AtlasFrame) -> Option<&AtlasPage> {
self.pages.get(frame.page)
}
pub fn load_pages(&self, server: &mut AssetServer, scope: Scope) -> Vec<Handle<Texture>> {
self.pages
.iter()
.map(|page| server.load_in(&page.path, scope))
.collect()
}
pub fn sprites(&self) -> &[AtlasSprite] {
&self.sprites
}
pub fn sprite(&self, name: &str) -> Option<&AtlasSprite> {
let index = self
.sprites
.binary_search_by(|sprite| sprite.name.as_bytes().cmp(name.as_bytes()))
.ok()?;
self.sprites.get(index)
}
}
impl AtlasPage {
pub fn path(&self) -> &str {
&self.path
}
pub fn size(&self) -> UVec2 {
self.size
}
}
impl AtlasSprite {
pub fn name(&self) -> &str {
&self.name
}
pub fn frames(&self) -> &[AtlasFrame] {
&self.frames
}
pub fn frame(&self, index: usize) -> Option<&AtlasFrame> {
self.frames.get(index)
}
pub fn pivot(&self) -> Option<Vec2> {
self.pivot
}
pub fn tile_size(&self) -> Option<UVec2> {
self.tile_size
}
pub fn clips(&self) -> &[AtlasClip] {
&self.clips
}
pub fn clip(&self, name: &str) -> Option<&AtlasClip> {
let index = self
.clips
.binary_search_by(|clip| clip.name.as_bytes().cmp(name.as_bytes()))
.ok()?;
self.clips.get(index)
}
pub fn tile_set(&self, texture: Handle<Texture>) -> Option<TileSet> {
let tile = self.tile_size?;
let size = self.frames.first()?.source_size;
Some(TileSet {
texture,
columns: u16::try_from(size.x / tile.x).ok()?,
rows: u16::try_from(size.y / tile.y).ok()?,
})
}
}
impl AtlasClip {
pub fn name(&self) -> &str {
&self.name
}
pub fn is_looping(&self) -> bool {
self.looping
}
pub fn frames(&self) -> &[AtlasClipFrame] {
&self.frames
}
}
impl AtlasClipFrame {
pub fn frame(&self) -> usize {
self.frame
}
pub fn duration(&self) -> Duration {
self.duration
}
}
impl AtlasFrame {
pub fn page(&self) -> usize {
self.page
}
pub fn uv(&self) -> Rect {
self.uv
}
pub fn size(&self) -> UVec2 {
self.size
}
pub fn offset(&self) -> UVec2 {
self.offset
}
pub fn source_size(&self) -> UVec2 {
self.source_size
}
pub fn is_empty(&self) -> bool {
self.size == UVec2::ZERO
}
pub fn pivot_in(&self, pivot: Vec2) -> Vec2 {
if self.is_empty() {
return pivot / self.source_size.as_vec2();
}
(pivot - self.offset.as_vec2()) / self.size.as_vec2()
}
}
impl Asset for Atlas {
type Decoded = Atlas;
const EXTENSIONS: &'static [&'static str] = &["kbj"];
fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Atlas, AssetError> {
let file = atlas::parse(bytes, ctx.limits()).map_err(AssetError::Decode)?;
let mut pages = Vec::with_capacity(file.pages.len());
for (index, page) in file.pages.into_iter().enumerate() {
let path = AssetPath::new(&page.path)
.ok()
.filter(|path| path.as_str() == page.path && path.extension() == Some("qoi"))
.ok_or_else(|| {
AssetError::Invalid(format!(
"page {index}, `{}`, is not the path of a QOI texture",
page.path
))
})?;
pages.push(AtlasPage {
path: path.as_str().to_string(),
size: UVec2::new(page.width, page.height),
});
}
let sprites = file
.sprites
.into_iter()
.map(|sprite| AtlasSprite {
name: sprite.name,
frames: sprite
.frames
.iter()
.map(|frame| AtlasFrame::new(frame, &pages))
.collect(),
pivot: match sprite.kind {
SpriteKind::Pivot([x, y]) => Some(Vec2::new(x, y)),
_ => None,
},
tile_size: match sprite.kind {
SpriteKind::Tiles([w, h]) => Some(UVec2::new(w, h)),
_ => None,
},
clips: sprite
.clips
.into_iter()
.map(|clip| AtlasClip {
name: clip.name,
looping: clip.looping,
frames: clip
.frames
.iter()
.map(|step| AtlasClipFrame {
frame: step.frame as usize,
duration: Duration::from_millis(u64::from(step.millis)),
})
.collect(),
})
.collect(),
})
.collect();
Ok(Atlas { pages, sprites })
}
fn finalize(decoded: Atlas, _: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
Ok(decoded)
}
}
impl AtlasFrame {
fn new(frame: &atlas::Frame, pages: &[AtlasPage]) -> Self {
let page = frame.page as usize;
let page_size = pages
.get(page)
.map_or(Vec2::ONE, |page| page.size.as_vec2());
let corner = Vec2::new(frame.x as f32, frame.y as f32);
let size = UVec2::new(frame.width, frame.height);
Self {
page,
uv: Rect::new(corner / page_size, (corner + size.as_vec2()) / page_size),
size,
offset: UVec2::new(frame.offset_x, frame.offset_y),
source_size: UVec2::new(frame.source_width, frame.source_height),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use nadir_codec::{Limits, json, kbj};
fn decoded(text: &str) -> Result<Atlas, AssetError> {
let value = json::parse(text, Limits::default()).expect("the test's JSON");
let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
Atlas::decode(
&bytes,
&DecodeCtx::new("atlas/sprites.kbj", Limits::default()),
)
}
const ATLAS: &str = r#"{ "version": 2,
"pages": [ { "path": "atlas/sprites_0.qoi", "w": 128, "h": 128 },
{ "path": "atlas/sprites/tiles.tiles.qoi", "w": 128, "h": 64 } ],
"sprites": [
{ "name": "sprites/person",
"frames": [ { "page": 0, "x": 33, "y": 85, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
{ "page": 0, "x": 0, "y": 0, "w": 0, "h": 0, "ox": 0, "oy": 0, "sw": 12, "sh": 20 } ],
"pivot": [6.0, 20.0],
"clips": [ { "name": "blink", "loop": false, "frames": [[0, 250], [1, 40], [0, 1000]] },
{ "name": "stand", "loop": true, "frames": [[0, 100]] } ] },
{ "name": "sprites/tiles",
"frames": [ { "page": 1, "x": 0, "y": 0, "w": 128, "h": 64, "ox": 0, "oy": 0, "sw": 128, "sh": 64 } ],
"tiles": [16, 16] },
{ "name": "sprites/tree",
"frames": [ { "page": 0, "x": 1, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
"pivot": [12.0, 48.0] } ] }"#;
#[test]
fn sprites_are_found_by_name_with_their_regions() {
let atlas = decoded(ATLAS).expect("an atlas");
assert_eq!(atlas.pages().len(), 2);
assert_eq!(atlas.pages()[1].path(), "atlas/sprites/tiles.tiles.qoi");
assert_eq!(atlas.pages()[1].size(), UVec2::new(128, 64));
assert!(atlas.sprite("sprites/rock").is_none());
assert!(atlas.sprite("sprites").is_none());
let person = atlas.sprite("sprites/person").expect("the person");
assert_eq!(person.name(), "sprites/person");
assert_eq!(person.pivot(), Some(Vec2::new(6.0, 20.0)));
assert_eq!(person.tile_size(), None);
let frame = person.frame(0).expect("a frame");
assert_eq!(frame.page(), 0);
assert_eq!(
frame.uv(),
Rect::new(
Vec2::new(33.0 / 128.0, 85.0 / 128.0),
Vec2::new(43.0 / 128.0, 105.0 / 128.0)
)
);
assert_eq!(
(frame.size(), frame.offset(), frame.source_size()),
(UVec2::new(10, 20), UVec2::new(1, 0), UVec2::new(12, 20))
);
assert_eq!(
atlas.page(frame).map(AtlasPage::path),
Some("atlas/sprites_0.qoi")
);
assert!(!frame.is_empty());
assert!(person.frame(1).expect("a frame").is_empty());
assert!(person.frame(2).is_none());
}
#[test]
fn a_trimmed_frame_s_pivot_keeps_its_pixels_where_the_cell_had_them() {
let atlas = decoded(ATLAS).expect("an atlas");
let tree = atlas.sprite("sprites/tree").expect("the tree");
let frame = tree.frames()[0];
let pivot = frame.pivot_in(tree.pivot().expect("a pivot"));
assert_eq!(pivot, Vec2::new(0.5, 1.0));
let feet = Vec2::new(100.0, 200.0);
let corner = feet - pivot * frame.size().as_vec2();
let cell = feet - Vec2::new(12.0, 48.0);
assert_eq!(corner, cell + frame.offset().as_vec2());
let person = atlas.sprite("sprites/person").expect("the person");
let pivot = person.pivot().expect("a pivot");
assert_eq!(person.frames()[0].pivot_in(pivot), Vec2::new(0.5, 1.0));
assert_eq!(person.frames()[1].pivot_in(pivot), Vec2::new(0.5, 1.0));
}
#[test]
fn a_tile_set_gives_its_grid() {
let atlas = decoded(ATLAS).expect("an atlas");
let tiles = atlas.sprite("sprites/tiles").expect("the tiles");
assert_eq!(tiles.tile_size(), Some(UVec2::new(16, 16)));
assert_eq!(tiles.pivot(), None);
let texture = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
let set = tiles.tile_set(texture).expect("a tile set");
assert_eq!((set.texture, set.columns, set.rows), (texture, 8, 4));
let tree = atlas.sprite("sprites/tree").expect("the tree");
assert_eq!(tree.tile_set(texture), None);
}
#[test]
fn a_page_whose_path_is_not_a_qoi_asset_path_is_refused() {
for path in [
"atlas/../page.qoi",
"atlas/page.png",
"Atlas/page.qoi",
"/atlas/page.qoi",
] {
let text = ATLAS.replacen("atlas/sprites_0.qoi", path, 1);
assert_eq!(
decoded(&text),
Err(AssetError::Invalid(format!(
"page 0, `{path}`, is not the path of a QOI texture"
))),
"{path}"
);
}
for version in [1, 9] {
let text = ATLAS.replacen(r#""version": 2"#, &format!(r#""version": {version}"#), 1);
assert!(text.contains(&format!(r#""version": {version}"#)));
assert!(
matches!(
decoded(&text),
Err(AssetError::Decode(nadir_codec::CodecError::Atlas { ref at, .. })) if at == "version"
),
"version {version}"
);
}
}
#[test]
fn a_sprite_s_clips_are_found_by_name_with_their_frames_and_times() {
let atlas = decoded(ATLAS).expect("an atlas");
let person = atlas.sprite("sprites/person").expect("the person");
let names: Vec<&str> = person.clips().iter().map(AtlasClip::name).collect();
assert_eq!(names, ["blink", "stand"]);
let blink = person.clip("blink").expect("a clip");
assert!(!blink.is_looping());
let steps: Vec<(usize, Duration)> = blink
.frames()
.iter()
.map(|step| (step.frame(), step.duration()))
.collect();
assert_eq!(
steps,
[
(0, Duration::from_millis(250)),
(1, Duration::from_millis(40)),
(0, Duration::from_secs(1)),
]
);
assert!(person.clip("stand").expect("a clip").is_looping());
assert!(person.clip("walk").is_none());
assert!(person.clip("").is_none());
assert!(
atlas
.sprite("sprites/tree")
.expect("the tree")
.clips()
.is_empty()
);
assert!(
atlas
.sprite("sprites/tiles")
.expect("the tiles")
.clips()
.is_empty()
);
}
#[test]
fn its_pages_load_as_textures_in_the_scope_given() {
let atlas = decoded(ATLAS).expect("an atlas");
let mut server = AssetServer::new("no-such-folder", nadir_assets::OnFailure::Nothing);
let pages = atlas.load_pages(&mut server, Scope::Level);
assert_eq!(pages.len(), 2);
assert_eq!(server.path(pages[0]), Some("atlas/sprites_0.qoi"));
assert_eq!(server.path(pages[1]), Some("atlas/sprites/tiles.tiles.qoi"));
assert_eq!(server.unload_scope(Scope::Level), 2);
assert_eq!(server.state(pages[0]), None);
}
#[test]
fn it_is_made_with_nothing_in_its_context() {
let atlas = decoded(ATLAS).expect("an atlas");
let made = Atlas::finalize(atlas.clone(), &mut FinalizeCtx::new());
assert_eq!(made, Ok(atlas));
}
}