Skip to main content

clairlune_render/
package.rs

1//! Frozen scene packages (PLAN.md section 9c): how saved wallpapers are kept.
2//!
3//! A package holds the *output* of the generator for one scene at one size,
4//! not its inputs: for each theme the scene supports, the scene graph (layout,
5//! character track, props, emitters, lighting), the palette, the glyph masks
6//! and the baked background; plus the activity definition, the character
7//! frames the scene can show and the props' pixel art. Playback reads only the
8//! package, never the generator, the activity catalog or the built-in art, so
9//! a saved scene plays the same after any of them change.
10//!
11//! ```text
12//! scene/
13//! ├── package.json          format, recipe, size, art, per-theme scene data
14//! ├── background-dark.png   indexed, no animated elements
15//! ├── background-light.png
16//! ├── sprites.png           the character frames, stacked (RGBA)
17//! └── journey-dark-0.png    a journey's moving layers (format 2), one per
18//!                           theme and layer: glyph as grey, shade as alpha
19//! ```
20//!
21//! What is *code* rather than data (particle motion, lighting bands, the
22//! state machine, palette layout) is the package player for formats 1 and 2; a
23//! committed golden package (`tests/golden/packages`) pins its output.
24
25use crate::art::{OwnedPixmap, Pixmap, SceneArt};
26use crate::atlas::GlyphAtlas;
27use crate::bake::bake_static;
28use crate::clock::Clock;
29use crate::frame::{IncrementalFrame, PixelRect, hero_time_with_art, render_frame_with_art};
30use crate::journey::JourneyBake;
31use crate::palette::IndexedPalette;
32use crate::{IndexedImage, encode_png};
33use clairlune_scene::activity::{Activity, Catalog, builtin_catalog};
34use clairlune_scene::{
35    BuildError, BuildOptions, Rgb, SceneGraph, SceneRecipe, SpriteKind, Theme, build_with,
36};
37use clairlune_sprites::{Animation, Character, Frame, PackagedCharacter, builtin_character};
38use serde::{Deserialize, Serialize};
39use std::collections::BTreeMap;
40use std::fmt;
41use std::path::Path;
42use std::sync::OnceLock;
43
44/// The newest package format this build writes and reads. Older formats
45/// stay readable. Format 2 adds a journey's moving layers; a package without
46/// one is still written as format 1, so older versions can play it.
47pub const PACKAGE_FORMAT: u32 = 2;
48
49#[derive(Debug)]
50pub enum PackageError {
51    Io(std::io::Error),
52    Json(serde_json::Error),
53    Png(String),
54    /// Written by a newer Clairlune.
55    UnsupportedFormat(u32),
56    Invalid(String),
57}
58
59impl fmt::Display for PackageError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            PackageError::Io(e) => write!(f, "{e}"),
63            PackageError::Json(e) => write!(f, "package.json: {e}"),
64            PackageError::Png(e) => write!(f, "image: {e}"),
65            PackageError::UnsupportedFormat(v) => write!(
66                f,
67                "scene package format {v} is newer than this version reads ({PACKAGE_FORMAT})"
68            ),
69            PackageError::Invalid(e) => write!(f, "scene package: {e}"),
70        }
71    }
72}
73
74impl std::error::Error for PackageError {}
75
76impl From<std::io::Error> for PackageError {
77    fn from(e: std::io::Error) -> Self {
78        PackageError::Io(e)
79    }
80}
81
82impl From<serde_json::Error> for PackageError {
83    fn from(e: serde_json::Error) -> Self {
84        PackageError::Json(e)
85    }
86}
87
88/// The art a package carries.
89#[derive(Clone, Debug)]
90pub struct PackageArt {
91    activity: Option<Activity>,
92    character: PackagedCharacter,
93    props: Vec<(SpriteKind, OwnedPixmap)>,
94}
95
96impl SceneArt for PackageArt {
97    fn activity(&self) -> Option<&Activity> {
98        self.activity.as_ref()
99    }
100    fn character(&self) -> &dyn Character {
101        &self.character
102    }
103    fn prop(&self, kind: SpriteKind) -> Option<&dyn Pixmap> {
104        self.props
105            .iter()
106            .find(|(k, _)| *k == kind)
107            .map(|(_, p)| p as &dyn Pixmap)
108    }
109}
110
111/// One theme's frozen scene.
112#[derive(Clone, Debug)]
113struct ThemeScene {
114    theme: Theme,
115    /// Laid out with Clawd; `graph_unattended` is the same with Buddy off.
116    graph: SceneGraph,
117    graph_unattended: SceneGraph,
118    palette: IndexedPalette,
119    atlas: GlyphAtlas,
120    background: IndexedImage,
121    hero_ms: u64,
122    /// A journey's moving layers, baked on first use (they are large, and
123    /// a live wallpaper only ever plays one theme).
124    journey: OnceLock<Option<JourneyBake>>,
125}
126
127impl ThemeScene {
128    fn journey(&self) -> Option<&JourneyBake> {
129        self.journey
130            .get_or_init(|| JourneyBake::new(&self.graph, &self.atlas))
131            .as_ref()
132    }
133}
134
135/// A frozen scene: plays without the generator.
136#[derive(Clone, Debug)]
137pub struct ScenePackage {
138    pub recipe: SceneRecipe,
139    pub width: u32,
140    pub height: u32,
141    /// The generator that made it (for information; playback ignores it).
142    pub generator_version: u32,
143    art: PackageArt,
144    themes: Vec<ThemeScene>,
145}
146
147impl ScenePackage {
148    /// Builds the scene in every theme it supports and freezes the result.
149    pub fn capture(recipe: &SceneRecipe, width: u32, height: u32) -> Result<Self, BuildError> {
150        Self::capture_with(
151            recipe,
152            width,
153            height,
154            builtin_catalog(),
155            builtin_character(),
156        )
157    }
158
159    /// [`capture`](Self::capture) with another activity catalog and character
160    /// (the developer preview loads both from disk).
161    pub fn capture_with(
162        recipe: &SceneRecipe,
163        width: u32,
164        height: u32,
165        catalog: &Catalog,
166        character: &dyn Character,
167    ) -> Result<Self, BuildError> {
168        let mut themes = Vec::new();
169        let mut graphs = Vec::new();
170        for theme in [Theme::Dark, Theme::Light] {
171            let opts = BuildOptions {
172                width,
173                height,
174                theme,
175                buddy: true,
176            };
177            match build_with(catalog, recipe, &opts) {
178                Ok(g) => graphs.push(g),
179                Err(BuildError::ThemeLocked(_)) => {}
180                Err(e) => return Err(e),
181            }
182        }
183        let first = graphs.first().ok_or(BuildError::ThemeLocked(Theme::Dark))?;
184        let activity = first
185            .activity
186            .as_deref()
187            .and_then(|id| catalog.get(id))
188            .cloned();
189        let art = PackageArt {
190            character: capture_character(character, activity.as_ref()),
191            props: capture_props(&graphs),
192            activity,
193        };
194        for mut graph in graphs {
195            let atlas = GlyphAtlas::for_grid(&graph.grid);
196            let palette = IndexedPalette::for_graph(&graph)
197                .with_sprite_colors(character_colors(&art.character));
198            let background = bake_static(&graph, &atlas);
199            // The background replaces the cells; a loaded package has none.
200            graph.cells = Vec::new();
201            let hero_ms = hero_time_with_art(&graph, &art);
202            let mut graph_unattended = graph.clone();
203            graph_unattended.buddy = false;
204            themes.push(ThemeScene {
205                theme: graph.theme,
206                graph,
207                graph_unattended,
208                palette,
209                atlas,
210                background,
211                hero_ms,
212                journey: OnceLock::new(),
213            });
214        }
215        Ok(ScenePackage {
216            recipe: recipe.clone(),
217            width,
218            height,
219            generator_version: recipe.generator_version,
220            art,
221            themes,
222        })
223    }
224
225    /// Themes this scene has, dark first.
226    pub fn themes(&self) -> Vec<Theme> {
227        self.themes.iter().map(|t| t.theme).collect()
228    }
229
230    /// Keeps only `theme` (when the scene has it): a wallpaper on screen
231    /// plays one, and each theme carries a full-size background and its
232    /// own layout. Saved after this, the package has only that theme.
233    pub fn keep_only(&mut self, theme: Theme) {
234        if self.theme(theme).is_some() {
235            self.themes.retain(|t| t.theme == theme);
236        }
237    }
238
239    fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
240        self.themes.iter().find(|t| t.theme == theme)
241    }
242
243    /// The still-frame time in a theme.
244    pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
245        self.theme(theme).map(|t| t.hero_ms)
246    }
247
248    /// One frame, or `None` if the scene has no such theme.
249    pub fn frame(
250        &self,
251        theme: Theme,
252        buddy: bool,
253        t_ms: u64,
254        clock: Clock,
255    ) -> Option<(IndexedImage, &IndexedPalette)> {
256        let t = self.theme(theme)?;
257        let graph = if buddy { &t.graph } else { &t.graph_unattended };
258        let moved = t
259            .journey()
260            .map(|j| j.background_at(graph, &t.background, t_ms));
261        let img = render_frame_with_art(
262            moved.as_ref().unwrap_or(&t.background),
263            graph,
264            &t.atlas,
265            &t.palette,
266            t_ms,
267            clock,
268            &self.art,
269        );
270        Some((img, &t.palette))
271    }
272
273    /// A frame to play the scene live, starting from the bare background;
274    /// move it with [`ScenePackage::advance`].
275    pub fn incremental(&self, theme: Theme) -> Option<IncrementalFrame> {
276        self.theme(theme)
277            .map(|t| IncrementalFrame::new(&t.background))
278    }
279
280    /// Moves a live frame to `t_ms` and returns the rectangles that changed;
281    /// the frame then equals [`ScenePackage::frame`] at that time.
282    pub fn advance(
283        &self,
284        frame: &mut IncrementalFrame,
285        theme: Theme,
286        buddy: bool,
287        t_ms: u64,
288        clock: Clock,
289    ) -> Option<Vec<PixelRect>> {
290        let t = self.theme(theme)?;
291        let graph = if buddy { &t.graph } else { &t.graph_unattended };
292        if let Some(j) = t.journey() {
293            return Some(frame.advance_journey(
294                j,
295                &t.background,
296                graph,
297                &t.atlas,
298                &t.palette,
299                t_ms,
300                clock,
301                &self.art,
302            ));
303        }
304        Some(frame.advance(
305            &t.background,
306            graph,
307            &t.atlas,
308            &t.palette,
309            t_ms,
310            clock,
311            &self.art,
312        ))
313    }
314
315    /// The still (hero) frame in a theme.
316    pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
317        let t = self.hero_ms(theme)?;
318        self.frame(theme, buddy, t, Clock::Live)
319    }
320
321    /// The palette in a theme.
322    pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
323        self.theme(theme).map(|t| &t.palette)
324    }
325
326    /// The scene graph in a theme (layout, emitters, loop length).
327    pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
328        self.theme(theme).map(|t| &t.graph)
329    }
330
331    /// Writes the package into `dir` (created if needed).
332    pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
333        std::fs::create_dir_all(dir)?;
334        let mut sheet = SpriteSheetWriter::default();
335        let character = self
336            .art
337            .character
338            .iter()
339            .map(|((activity, state), anim)| AnimationFile {
340                activity: activity.clone(),
341                state: state.clone(),
342                name: anim.name.clone(),
343                frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
344            })
345            .collect();
346        let journeys = self.themes.iter().any(|t| t.graph.journey.is_some());
347        let file = PackageFile {
348            format: if journeys { 2 } else { 1 },
349            generator_version: self.generator_version,
350            recipe: self.recipe.clone(),
351            width: self.width,
352            height: self.height,
353            activity: self.art.activity.clone(),
354            character,
355            props: self
356                .art
357                .props
358                .iter()
359                .map(|(k, p)| PropFile {
360                    kind: *k,
361                    width: p.width,
362                    height: p.height,
363                    pixels: p.pixels.clone(),
364                })
365                .collect(),
366            themes: self
367                .themes
368                .iter()
369                .map(|t| ThemeFile {
370                    theme: t.theme,
371                    graph: t.graph.clone(),
372                    palette: t.palette.colors().to_vec(),
373                    atlas: t.atlas.clone(),
374                    hero_ms: t.hero_ms,
375                })
376                .collect(),
377        };
378        for t in &self.themes {
379            let mut png = Vec::new();
380            encode_png(&t.background, &t.palette, &mut png)
381                .map_err(|e| PackageError::Png(e.to_string()))?;
382            std::fs::write(dir.join(background_name(t.theme)), png)?;
383            if let Some(j) = &t.graph.journey {
384                for (i, layer) in j.layers.iter().enumerate() {
385                    let png = encode_layer(layer.cols, t.graph.grid.rows, &layer.cells)?;
386                    std::fs::write(dir.join(layer_name(t.theme, i)), png)?;
387                }
388            }
389        }
390        std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
391        let json = serde_json::to_string(&file)?;
392        let tmp = dir.join("package.json.part");
393        std::fs::write(&tmp, json)?;
394        std::fs::rename(tmp, dir.join("package.json"))?;
395        Ok(())
396    }
397
398    /// Reads a package written by this or an older version.
399    pub fn load(dir: &Path) -> Result<Self, PackageError> {
400        let text = std::fs::read_to_string(dir.join("package.json"))?;
401        let probe: FormatProbe = serde_json::from_str(&text)?;
402        if probe.format > PACKAGE_FORMAT || probe.format == 0 {
403            return Err(PackageError::UnsupportedFormat(probe.format));
404        }
405        let file: PackageFile = serde_json::from_str(&text)?;
406        let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
407        let mut character = PackagedCharacter::default();
408        for a in &file.character {
409            let frames = a
410                .frames
411                .iter()
412                .map(|f| sheet.frame(f))
413                .collect::<Result<Vec<_>, _>>()?;
414            character.insert(
415                &a.activity,
416                &a.state,
417                Animation {
418                    name: a.name.clone(),
419                    frames,
420                },
421            );
422        }
423        let art = PackageArt {
424            activity: file.activity,
425            character,
426            props: file
427                .props
428                .into_iter()
429                .map(|p| {
430                    let len = (p.width as usize).checked_mul(p.height as usize);
431                    if len != Some(p.pixels.len()) || p.width == 0 || p.height == 0 {
432                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
433                    }
434                    Ok((
435                        p.kind,
436                        OwnedPixmap {
437                            width: p.width,
438                            height: p.height,
439                            pixels: p.pixels,
440                        },
441                    ))
442                })
443                .collect::<Result<_, _>>()?,
444        };
445        if art.activity.as_ref().is_some_and(|a| !a.playable()) {
446            return Err(PackageError::Invalid(
447                "activity has a state with no way on".into(),
448            ));
449        }
450        let mut themes = Vec::new();
451        for t in file.themes {
452            let (background, colors) =
453                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
454            let palette = IndexedPalette::from_colors(t.palette);
455            if colors != palette.rgb_bytes()
456                || (background.width, background.height) != (file.width, file.height)
457            {
458                return Err(PackageError::Invalid(format!(
459                    "{} background does not match its palette or size",
460                    t.theme.as_str()
461                )));
462            }
463            check_graph(&t.graph, &t.atlas, file.width, file.height)?;
464            check_colors(&art, &palette)?;
465            let mut graph = t.graph;
466            if let Some(j) = &mut graph.journey {
467                let rows = graph.grid.rows;
468                for (i, layer) in j.layers.iter_mut().enumerate() {
469                    let bytes = std::fs::read(dir.join(layer_name(t.theme, i)))?;
470                    layer.cells = decode_layer(&bytes, layer.cols, rows)?;
471                }
472                let width = j.layers.last().map_or(0, |l| l.cols * graph.grid.cell_w);
473                if j.ground.len() != width as usize || j.loop_ms == 0 {
474                    return Err(PackageError::Invalid("journey ground or loop".into()));
475                }
476            }
477            let mut graph_unattended = graph.clone();
478            graph_unattended.buddy = false;
479            themes.push(ThemeScene {
480                theme: t.theme,
481                graph,
482                graph_unattended,
483                palette,
484                atlas: t.atlas,
485                background,
486                hero_ms: t.hero_ms,
487                journey: OnceLock::new(),
488            });
489        }
490        if themes.is_empty() {
491            return Err(PackageError::Invalid("no themes".into()));
492        }
493        Ok(ScenePackage {
494            recipe: file.recipe,
495            width: file.width,
496            height: file.height,
497            generator_version: file.generator_version,
498            art,
499            themes,
500        })
501    }
502}
503
504/// A loaded theme's graph and atlas agree with each other and the image,
505/// so playback can index without checks (a damaged file is an error, not a
506/// crash).
507fn check_graph(
508    graph: &SceneGraph,
509    atlas: &GlyphAtlas,
510    width: u32,
511    height: u32,
512) -> Result<(), PackageError> {
513    let bad = |what: &str| {
514        Err(PackageError::Invalid(format!(
515            "{} {what}",
516            graph.theme.as_str()
517        )))
518    };
519    if (graph.width, graph.height) != (width, height) {
520        return bad("scene size differs from the package's");
521    }
522    let g = &graph.grid;
523    let fits = |origin: u32, n: u32, cell: u32, room: u32| {
524        cell > 0 && u64::from(origin) + u64::from(n) * u64::from(cell) <= u64::from(room)
525    };
526    if !fits(g.origin_x, g.cols, g.cell_w, width) || !fits(g.origin_y, g.rows, g.cell_h, height) {
527        return bad("grid doesn't fit the image");
528    }
529    if !atlas.fits(g.cell_w, g.cell_h) {
530        return bad("glyph atlas doesn't fit the grid");
531    }
532    if !graph.emitters.iter().all(|e| e.is_sound()) {
533        return bad("particles");
534    }
535    Ok(())
536}
537
538/// Every colour of the packaged art is in a theme's palette.
539fn check_colors(art: &PackageArt, palette: &IndexedPalette) -> Result<(), PackageError> {
540    let known = |rgb: &Rgb| palette.sprite_index(*rgb).is_some();
541    let props = art
542        .props
543        .iter()
544        .flat_map(|(_, p)| p.pixels.iter().flatten());
545    let character = art
546        .character
547        .iter()
548        .flat_map(|(_, a)| a.frames.iter().flat_map(|f| f.pixels.iter().flatten()));
549    if props.chain(character).all(known) {
550        Ok(())
551    } else {
552        Err(PackageError::Invalid(
553            "art colour missing from the palette".into(),
554        ))
555    }
556}
557
558fn background_name(theme: Theme) -> String {
559    format!("background-{}.png", theme.as_str())
560}
561
562fn layer_name(theme: Theme, i: usize) -> String {
563    format!("journey-{}-{i}.png", theme.as_str())
564}
565
566/// A journey layer's cells as a grey-and-alpha PNG: one pixel per cell,
567/// the glyph as grey and the shade as alpha.
568fn encode_layer(
569    cols: u32,
570    rows: u32,
571    cells: &[clairlune_scene::Cell],
572) -> Result<Vec<u8>, PackageError> {
573    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
574    let mut out = Vec::new();
575    let mut enc = png::Encoder::new(&mut out, cols, rows);
576    enc.set_color(png::ColorType::GrayscaleAlpha);
577    enc.set_depth(png::BitDepth::Eight);
578    let mut w = enc.write_header().map_err(|e| png_err(&e))?;
579    let data: Vec<u8> = cells.iter().flat_map(|c| [c.glyph, c.shade]).collect();
580    w.write_image_data(&data).map_err(|e| png_err(&e))?;
581    w.finish().map_err(|e| png_err(&e))?;
582    Ok(out)
583}
584
585fn decode_layer(
586    bytes: &[u8],
587    cols: u32,
588    rows: u32,
589) -> Result<Vec<clairlune_scene::Cell>, PackageError> {
590    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
591    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
592    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
593    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
594    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
595    if info.color_type != png::ColorType::GrayscaleAlpha
596        || info.bit_depth != png::BitDepth::Eight
597        || (info.width, info.height) != (cols, rows)
598    {
599        return Err(PackageError::Png(
600            "journey layer: wrong kind or size".into(),
601        ));
602    }
603    let glyphs = clairlune_scene::glyphs::GLYPHS.len() as u8;
604    buf[..info.buffer_size()]
605        .as_chunks::<2>()
606        .0
607        .iter()
608        .map(|&[glyph, shade]| {
609            if glyph < glyphs {
610                Ok(clairlune_scene::Cell { glyph, shade })
611            } else {
612                Err(PackageError::Invalid("journey layer: unknown glyph".into()))
613            }
614        })
615        .collect()
616}
617
618/// Every `(activity, state)` the scene can show: all states of its activity
619/// (the state machine may reach any), or the idle fallback.
620fn capture_character(from: &dyn Character, activity: Option<&Activity>) -> PackagedCharacter {
621    match activity {
622        Some(a) => PackagedCharacter::capture(
623            from,
624            a.animation
625                .states
626                .keys()
627                .map(|s| (a.id.as_str(), s.as_str())),
628        ),
629        None => PackagedCharacter::capture(from, [("", "idle")]),
630    }
631}
632
633/// Every colour the captured frames use, in a stable order.
634fn character_colors(c: &PackagedCharacter) -> Vec<Rgb> {
635    let mut out: Vec<Rgb> = Vec::new();
636    for (_, anim) in c.iter() {
637        for f in &anim.frames {
638            for rgb in f.pixels.iter().flatten() {
639                if !out.contains(rgb) {
640                    out.push(*rgb);
641                }
642            }
643        }
644    }
645    out
646}
647
648/// The pixel art of every prop the scene places, in either Buddy state.
649fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
650    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
651    for g in graphs {
652        for s in g.props.iter().chain(&g.unattended) {
653            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
654                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
655            }
656        }
657    }
658    out
659}
660
661// ---- On-disk format (1, and 2 with a journey's layer images) -----------
662
663#[derive(Deserialize)]
664struct FormatProbe {
665    format: u32,
666}
667
668#[derive(Serialize, Deserialize)]
669struct PackageFile {
670    format: u32,
671    generator_version: u32,
672    recipe: SceneRecipe,
673    width: u32,
674    height: u32,
675    activity: Option<Activity>,
676    character: Vec<AnimationFile>,
677    props: Vec<PropFile>,
678    themes: Vec<ThemeFile>,
679}
680
681#[derive(Serialize, Deserialize)]
682struct AnimationFile {
683    activity: String,
684    state: String,
685    name: String,
686    frames: Vec<FrameFile>,
687}
688
689/// A frame's place in `sprites.png` and its timing and anchors.
690#[derive(Serialize, Deserialize)]
691struct FrameFile {
692    y: u32,
693    width: u32,
694    height: u32,
695    duration_ms: u32,
696    anchors: BTreeMap<String, (i32, i32)>,
697}
698
699#[derive(Serialize, Deserialize)]
700struct PropFile {
701    kind: SpriteKind,
702    width: u32,
703    height: u32,
704    pixels: Vec<Option<Rgb>>,
705}
706
707#[derive(Serialize, Deserialize)]
708struct ThemeFile {
709    theme: Theme,
710    graph: SceneGraph,
711    palette: Vec<Rgb>,
712    atlas: GlyphAtlas,
713    hero_ms: u64,
714}
715
716/// Stacks frames top to bottom in one RGBA image; identical frames share
717/// their pixels.
718#[derive(Default)]
719struct SpriteSheetWriter {
720    width: u32,
721    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
722    height: u32,
723}
724
725impl SpriteSheetWriter {
726    fn add(&mut self, f: &Frame) -> FrameFile {
727        let y = match self
728            .rows
729            .iter()
730            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
731        {
732            Some((y, _, _)) => *y,
733            None => {
734                let y = self.height;
735                self.rows.push((y, f.width, f.pixels.clone()));
736                self.height += f.height;
737                self.width = self.width.max(f.width);
738                y
739            }
740        };
741        FrameFile {
742            y,
743            width: f.width,
744            height: f.height,
745            duration_ms: f.duration_ms,
746            anchors: f.anchors.clone(),
747        }
748    }
749
750    fn png(&self) -> Result<Vec<u8>, PackageError> {
751        let (w, h) = (self.width.max(1), self.height.max(1));
752        let mut rgba = vec![0u8; (w * h * 4) as usize];
753        for (y0, fw, px) in &self.rows {
754            for (i, p) in px.iter().enumerate() {
755                let Some(c) = p else { continue };
756                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
757                let o = ((y * w + x) * 4) as usize;
758                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
759            }
760        }
761        let mut out = Vec::new();
762        let mut enc = png::Encoder::new(&mut out, w, h);
763        enc.set_color(png::ColorType::Rgba);
764        enc.set_depth(png::BitDepth::Eight);
765        let mut writer = enc
766            .write_header()
767            .map_err(|e| PackageError::Png(e.to_string()))?;
768        writer
769            .write_image_data(&rgba)
770            .map_err(|e| PackageError::Png(e.to_string()))?;
771        writer
772            .finish()
773            .map_err(|e| PackageError::Png(e.to_string()))?;
774        Ok(out)
775    }
776}
777
778struct SpriteSheetReader {
779    width: u32,
780    height: u32,
781    rgba: Vec<u8>,
782}
783
784impl SpriteSheetReader {
785    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
786        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
787        dec.set_transformations(png::Transformations::EXPAND);
788        let mut reader = dec
789            .read_info()
790            .map_err(|e| PackageError::Png(e.to_string()))?;
791        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
792        let info = reader
793            .next_frame(&mut buf)
794            .map_err(|e| PackageError::Png(e.to_string()))?;
795        if info.color_type != png::ColorType::Rgba {
796            return Err(PackageError::Png("sprites.png must be RGBA".into()));
797        }
798        buf.truncate(info.buffer_size());
799        Ok(SpriteSheetReader {
800            width: info.width,
801            height: info.height,
802            rgba: buf,
803        })
804    }
805
806    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
807        if f.width > self.width
808            || f.y
809                .checked_add(f.height)
810                .is_none_or(|end| end > self.height)
811        {
812            return Err(PackageError::Invalid(
813                "a frame lies outside sprites.png".into(),
814            ));
815        }
816        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
817        for y in f.y..f.y + f.height {
818            for x in 0..f.width {
819                let o = ((y * self.width + x) * 4) as usize;
820                let p = &self.rgba[o..o + 4];
821                pixels.push((p[3] != 0).then_some(Rgb {
822                    r: p[0],
823                    g: p[1],
824                    b: p[2],
825                }));
826            }
827        }
828        Ok(Frame {
829            width: f.width,
830            height: f.height,
831            pixels,
832            duration_ms: f.duration_ms,
833            anchors: f.anchors.clone(),
834        })
835    }
836}
837
838/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
839fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
840    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
841    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
842    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
843    let palette = reader
844        .info()
845        .palette
846        .as_ref()
847        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
848        .to_vec();
849    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
850    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
851    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
852        return Err(PackageError::Png("background must be 8-bit indexed".into()));
853    }
854    buf.truncate(info.buffer_size());
855    Ok((
856        IndexedImage {
857            width: info.width,
858            height: info.height,
859            pixels: buf,
860        },
861        palette,
862    ))
863}