Skip to main content

clairlune_sprites/
sheet.rs

1//! Decoding and validating an exported sprite sheet into animations.
2
3use crate::aseprite::{Export, Slice};
4use clairlune_scene::Rgb;
5use std::collections::BTreeMap;
6use std::fmt;
7
8/// Palette budget for all character colours (PLAN.md section 4.5).
9pub const MAX_CHARACTER_COLORS: usize = 16;
10/// Every frame needs this anchor: feet baseline x body centre.
11pub const ORIGIN: &str = "origin";
12
13/// One animation frame. Pixels are row-major, `None` is transparent.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct Frame {
16    pub width: u32,
17    pub height: u32,
18    pub pixels: Vec<Option<Rgb>>,
19    pub duration_ms: u32,
20    /// Anchor points in frame pixels (`origin`, `hand_l`, `item_tip`, ...).
21    pub anchors: BTreeMap<String, (i32, i32)>,
22}
23
24impl Frame {
25    pub fn pixel(&self, x: u32, y: u32) -> Option<Rgb> {
26        self.pixels[(y * self.width + x) as usize]
27    }
28
29    /// The `origin` anchor (validated to exist).
30    pub fn origin(&self) -> (i32, i32) {
31        self.anchors[ORIGIN]
32    }
33}
34
35/// A tagged animation (one state).
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Animation {
38    pub name: String,
39    pub frames: Vec<Frame>,
40}
41
42impl Animation {
43    pub fn duration_ms(&self) -> u64 {
44        self.frames.iter().map(|f| u64::from(f.duration_ms)).sum()
45    }
46
47    /// Frame shown `elapsed_ms` after the state started. Looping animations wrap;
48    /// one-shots hold their last frame.
49    pub fn frame_at(&self, elapsed_ms: u64, looping: bool) -> &Frame {
50        &self.frames[self.frame_index_at(elapsed_ms, looping)]
51    }
52
53    /// Index of the frame shown `elapsed_ms` after the state started.
54    pub fn frame_index_at(&self, elapsed_ms: u64, looping: bool) -> usize {
55        let total = self.duration_ms().max(1);
56        let mut t = if looping {
57            elapsed_ms % total
58        } else {
59            elapsed_ms.min(total - 1)
60        };
61        for (i, f) in self.frames.iter().enumerate() {
62            let d = u64::from(f.duration_ms);
63            if t < d {
64                return i;
65            }
66            t -= d;
67        }
68        self.frames.len() - 1
69    }
70}
71
72/// A decoded sheet: one animation per tag.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct SpriteSheet {
75    pub animations: BTreeMap<String, Animation>,
76    /// Distinct opaque colours, in first-seen order.
77    pub colors: Vec<Rgb>,
78    pub source_sha256: Option<String>,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum SheetError {
83    Json(String),
84    Png(String),
85    Rotated(String),
86    OutOfBounds(String),
87    PartialAlpha {
88        frame: usize,
89        x: u32,
90        y: u32,
91        alpha: u8,
92    },
93    TooManyColors(usize),
94    BadTag(String),
95    MissingOrigin {
96        tag: String,
97        frame: usize,
98    },
99    NoTags,
100}
101
102impl fmt::Display for SheetError {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            SheetError::Json(e) => write!(f, "sheet JSON: {e}"),
106            SheetError::Png(e) => write!(f, "sheet PNG: {e}"),
107            SheetError::Rotated(n) => write!(f, "frame `{n}` is rotated; export without rotation"),
108            SheetError::OutOfBounds(n) => write!(f, "frame `{n}` lies outside the sheet image"),
109            SheetError::PartialAlpha { frame, x, y, alpha } => write!(
110                f,
111                "frame {frame} pixel ({x}, {y}) has alpha {alpha}; pixels must be fully opaque or transparent"
112            ),
113            SheetError::TooManyColors(n) => {
114                write!(
115                    f,
116                    "{n} colours; the character may use at most {MAX_CHARACTER_COLORS}"
117                )
118            }
119            SheetError::BadTag(t) => write!(f, "tag `{t}` has an invalid frame range or direction"),
120            SheetError::MissingOrigin { tag, frame } => {
121                write!(f, "tag `{tag}` frame {frame} has no `{ORIGIN}` slice key")
122            }
123            SheetError::NoTags => write!(f, "the sheet has no tags; every state needs one"),
124        }
125    }
126}
127
128impl std::error::Error for SheetError {}
129
130/// Decodes a PNG to `(width, height, rgba8)`.
131fn decode_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), SheetError> {
132    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
133    decoder.set_transformations(png::Transformations::normalize_to_color8());
134    let mut reader = decoder
135        .read_info()
136        .map_err(|e| SheetError::Png(e.to_string()))?;
137    let mut buf = vec![
138        0;
139        reader
140            .output_buffer_size()
141            .ok_or_else(|| SheetError::Png("image too large".into()))?
142    ];
143    let info = reader
144        .next_frame(&mut buf)
145        .map_err(|e| SheetError::Png(e.to_string()))?;
146    let (w, h) = (info.width, info.height);
147    let n = (w * h) as usize;
148    let rgba = match info.color_type {
149        png::ColorType::Rgba => buf[..n * 4].to_vec(),
150        png::ColorType::Rgb => buf[..n * 3]
151            .as_chunks::<3>()
152            .0
153            .iter()
154            .flat_map(|&[r, g, b]| [r, g, b, 255])
155            .collect(),
156        png::ColorType::GrayscaleAlpha => buf[..n * 2]
157            .as_chunks::<2>()
158            .0
159            .iter()
160            .flat_map(|&[g, a]| [g, g, g, a])
161            .collect(),
162        png::ColorType::Grayscale => buf[..n].iter().flat_map(|&g| [g, g, g, 255]).collect(),
163        png::ColorType::Indexed => {
164            return Err(SheetError::Png("indexed PNG was not expanded".into()));
165        }
166    };
167    Ok((w, h, rgba))
168}
169
170/// Anchor of a slice at a frame: the latest key at or before it, as the slice's
171/// centre pixel (1x1 slices give their own pixel).
172/// Slice bounds are in canvas coordinates; frames are exported untrimmed, so
173/// they map 1:1 onto frame pixels.
174fn anchor_at(slice: &Slice, frame: usize) -> Option<(i32, i32)> {
175    let key = slice
176        .keys
177        .iter()
178        .filter(|k| k.frame <= frame)
179        .max_by_key(|k| k.frame)?;
180    let b = key.bounds;
181    Some(((b.x + b.w / 2) as i32, (b.y + b.h / 2) as i32))
182}
183
184impl SpriteSheet {
185    /// Parses an Aseprite `json-array` export and its sheet image.
186    pub fn parse(json: &str, png_bytes: &[u8]) -> Result<Self, SheetError> {
187        let export: Export =
188            serde_json::from_str(json).map_err(|e| SheetError::Json(e.to_string()))?;
189        let (iw, ih, rgba) = decode_rgba(png_bytes)?;
190
191        let mut colors: Vec<Rgb> = Vec::new();
192        let mut frames = Vec::with_capacity(export.frames.len());
193        for (i, fe) in export.frames.iter().enumerate() {
194            if fe.rotated {
195                return Err(SheetError::Rotated(fe.filename.clone()));
196            }
197            let r = fe.frame;
198            if r.x + r.w > iw || r.y + r.h > ih {
199                return Err(SheetError::OutOfBounds(fe.filename.clone()));
200            }
201            let mut pixels = Vec::with_capacity((r.w * r.h) as usize);
202            for y in 0..r.h {
203                for x in 0..r.w {
204                    let o = (((r.y + y) * iw + r.x + x) * 4) as usize;
205                    let a = rgba[o + 3];
206                    match a {
207                        0 => pixels.push(None),
208                        255 => {
209                            let c = Rgb {
210                                r: rgba[o],
211                                g: rgba[o + 1],
212                                b: rgba[o + 2],
213                            };
214                            if !colors.contains(&c) {
215                                colors.push(c);
216                            }
217                            pixels.push(Some(c));
218                        }
219                        alpha => {
220                            return Err(SheetError::PartialAlpha {
221                                frame: i,
222                                x,
223                                y,
224                                alpha,
225                            });
226                        }
227                    }
228                }
229            }
230            let anchors = export
231                .meta
232                .slices
233                .iter()
234                .filter_map(|s| anchor_at(s, i).map(|p| (s.name.clone(), p)))
235                .collect();
236            frames.push(Frame {
237                width: r.w,
238                height: r.h,
239                pixels,
240                duration_ms: fe.duration,
241                anchors,
242            });
243        }
244        if colors.len() > MAX_CHARACTER_COLORS {
245            return Err(SheetError::TooManyColors(colors.len()));
246        }
247        if export.meta.frame_tags.is_empty() {
248            return Err(SheetError::NoTags);
249        }
250
251        let mut animations = BTreeMap::new();
252        for tag in &export.meta.frame_tags {
253            if tag.from > tag.to || tag.to >= frames.len() {
254                return Err(SheetError::BadTag(tag.name.clone()));
255            }
256            let forward: Vec<usize> = (tag.from..=tag.to).collect();
257            let order: Vec<usize> = match tag.direction.as_str() {
258                "forward" => forward,
259                "reverse" => forward.into_iter().rev().collect(),
260                "pingpong" => {
261                    let back: Vec<usize> = forward
262                        .iter()
263                        .rev()
264                        .skip(1)
265                        .take(forward.len().saturating_sub(2))
266                        .copied()
267                        .collect();
268                    forward.into_iter().chain(back).collect()
269                }
270                _ => return Err(SheetError::BadTag(tag.name.clone())),
271            };
272            for &i in &order {
273                if !frames[i].anchors.contains_key(ORIGIN) {
274                    return Err(SheetError::MissingOrigin {
275                        tag: tag.name.clone(),
276                        frame: i,
277                    });
278                }
279            }
280            let anim = Animation {
281                name: tag.name.clone(),
282                frames: order.iter().map(|&i| frames[i].clone()).collect(),
283            };
284            animations.insert(tag.name.clone(), anim);
285        }
286        Ok(Self {
287            animations,
288            colors,
289            source_sha256: export.meta.source_sha256,
290        })
291    }
292}
293
294#[cfg(test)]
295pub(crate) mod tests {
296    use super::*;
297
298    /// Builds a sheet PNG + JSON in memory: `frames` 4x4 frames side by side.
299    pub(crate) fn fixture(frames: u32, alpha_of_first: u8, extra_colors: u32) -> (String, Vec<u8>) {
300        let (fw, fh) = (4u32, 4u32);
301        let w = fw * frames;
302        let mut rgba = vec![0u8; (w * fh * 4) as usize];
303        for f in 0..frames {
304            for y in 1..fh {
305                for x in 1..3 {
306                    let o = ((y * w + f * fw + x) * 4) as usize;
307                    rgba[o..o + 4].copy_from_slice(&[0xD9, 0x78, 0x5C, 255]);
308                }
309            }
310        }
311        rgba[3] = alpha_of_first; // pixel (0,0) of frame 0
312        for i in 0..extra_colors {
313            let o = ((i % w) * 4) as usize;
314            rgba[o..o + 4].copy_from_slice(&[i as u8, 7, 9, 255]);
315        }
316        let mut png_bytes = Vec::new();
317        {
318            let mut enc = png::Encoder::new(&mut png_bytes, w, fh);
319            enc.set_color(png::ColorType::Rgba);
320            enc.set_depth(png::BitDepth::Eight);
321            let mut wr = enc.write_header().unwrap();
322            wr.write_image_data(&rgba).unwrap();
323        }
324        let frame_json: Vec<String> = (0..frames)
325            .map(|f| {
326                format!(
327                    r#"{{"filename":"t#{f}","frame":{{"x":{},"y":0,"w":4,"h":4}},"rotated":false,"trimmed":false,"duration":{}}}"#,
328                    f * fw,
329                    100 + f * 10
330                )
331            })
332            .collect();
333        let json = format!(
334            r##"{{"frames":[{}],"meta":{{"app":"test","image":"t.png","frameTags":[{{"name":"idle","from":0,"to":{},"direction":"forward"}},{{"name":"bob","from":0,"to":{},"direction":"pingpong"}}],"slices":[{{"name":"origin","color":"#0000ffff","keys":[{{"frame":0,"bounds":{{"x":2,"y":3,"w":1,"h":1}}}}]}},{{"name":"hand_r","keys":[{{"frame":0,"bounds":{{"x":3,"y":2,"w":1,"h":1}}}},{{"frame":1,"bounds":{{"x":3,"y":1,"w":1,"h":1}}}}]}}],"source_sha256":"abc"}}}}"##,
335            frame_json.join(","),
336            frames - 1,
337            frames - 1
338        );
339        (json, png_bytes)
340    }
341
342    #[test]
343    fn parses_tags_durations_and_anchors() {
344        let (json, png) = fixture(3, 0, 0);
345        let sheet = SpriteSheet::parse(&json, &png).unwrap();
346        assert_eq!(sheet.colors, vec![Rgb::hex(0xD9785C)]);
347        assert_eq!(sheet.source_sha256.as_deref(), Some("abc"));
348        let idle = &sheet.animations["idle"];
349        assert_eq!(idle.frames.len(), 3);
350        assert_eq!(idle.duration_ms(), 100 + 110 + 120);
351        assert_eq!(idle.frames[0].origin(), (2, 3));
352        // Slice keys apply until the next key.
353        assert_eq!(idle.frames[0].anchors["hand_r"], (3, 2));
354        assert_eq!(idle.frames[2].anchors["hand_r"], (3, 1));
355        // Pingpong: 0 1 2 1.
356        let bob = &sheet.animations["bob"];
357        assert_eq!(bob.frames.len(), 4);
358        assert_eq!(bob.frames[3], idle.frames[1]);
359        // Frame lookup by time.
360        assert_eq!(idle.frame_at(105, true), &idle.frames[1]);
361        assert_eq!(idle.frame_at(330 + 5, true), &idle.frames[0]);
362        assert_eq!(idle.frame_at(10_000, false), &idle.frames[2]);
363    }
364
365    #[test]
366    fn rejects_partial_alpha_and_too_many_colours() {
367        let (json, png) = fixture(2, 128, 0);
368        assert!(matches!(
369            SpriteSheet::parse(&json, &png),
370            Err(SheetError::PartialAlpha { alpha: 128, .. })
371        ));
372        let (json, png) = fixture(8, 0, 20);
373        assert!(matches!(
374            SpriteSheet::parse(&json, &png),
375            Err(SheetError::TooManyColors(_))
376        ));
377    }
378
379    #[test]
380    fn rejects_missing_origin() {
381        let (json, png) = fixture(2, 0, 0);
382        let json = json.replace("\"name\":\"origin\"", "\"name\":\"feet\"");
383        assert!(matches!(
384            SpriteSheet::parse(&json, &png),
385            Err(SheetError::MissingOrigin { .. })
386        ));
387    }
388}