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    /// Bytes a journey's baked layers take in a theme (baking them now), 0
231    /// for a scene that stays put.
232    pub fn journey_bytes(&self, theme: Theme) -> usize {
233        self.theme(theme)
234            .and_then(ThemeScene::journey)
235            .map_or(0, JourneyBake::bytes)
236    }
237
238    /// Keeps only `theme` (when the scene has it): a wallpaper on screen
239    /// plays one, and each theme carries a full-size background and its
240    /// own layout. Saved after this, the package has only that theme.
241    pub fn keep_only(&mut self, theme: Theme) {
242        if self.theme(theme).is_some() {
243            self.themes.retain(|t| t.theme == theme);
244        }
245    }
246
247    fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
248        self.themes.iter().find(|t| t.theme == theme)
249    }
250
251    /// The still-frame time in a theme.
252    pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
253        self.theme(theme).map(|t| t.hero_ms)
254    }
255
256    /// One frame, or `None` if the scene has no such theme.
257    pub fn frame(
258        &self,
259        theme: Theme,
260        buddy: bool,
261        t_ms: u64,
262        clock: Clock,
263    ) -> Option<(IndexedImage, &IndexedPalette)> {
264        let t = self.theme(theme)?;
265        let graph = if buddy { &t.graph } else { &t.graph_unattended };
266        let moved = t
267            .journey()
268            .map(|j| j.background_at(graph, &t.background, t_ms));
269        let img = render_frame_with_art(
270            moved.as_ref().unwrap_or(&t.background),
271            graph,
272            &t.atlas,
273            &t.palette,
274            t_ms,
275            clock,
276            &self.art,
277        );
278        Some((img, &t.palette))
279    }
280
281    /// A frame to play the scene live, starting from the bare background;
282    /// move it with [`ScenePackage::advance`].
283    pub fn incremental(&self, theme: Theme) -> Option<IncrementalFrame> {
284        self.theme(theme)
285            .map(|t| IncrementalFrame::new(&t.background))
286    }
287
288    /// Moves a live frame to `t_ms` and returns the rectangles that changed;
289    /// the frame then equals [`ScenePackage::frame`] at that time.
290    pub fn advance(
291        &self,
292        frame: &mut IncrementalFrame,
293        theme: Theme,
294        buddy: bool,
295        t_ms: u64,
296        clock: Clock,
297    ) -> Option<Vec<PixelRect>> {
298        let t = self.theme(theme)?;
299        let graph = if buddy { &t.graph } else { &t.graph_unattended };
300        if let Some(j) = t.journey() {
301            return Some(frame.advance_journey(
302                j,
303                &t.background,
304                graph,
305                &t.atlas,
306                &t.palette,
307                t_ms,
308                clock,
309                &self.art,
310            ));
311        }
312        Some(frame.advance(
313            &t.background,
314            graph,
315            &t.atlas,
316            &t.palette,
317            t_ms,
318            clock,
319            &self.art,
320        ))
321    }
322
323    /// The still (hero) frame in a theme.
324    pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
325        let t = self.hero_ms(theme)?;
326        self.frame(theme, buddy, t, Clock::Live)
327    }
328
329    /// The palette in a theme.
330    pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
331        self.theme(theme).map(|t| &t.palette)
332    }
333
334    /// The scene graph in a theme (layout, emitters, loop length).
335    pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
336        self.theme(theme).map(|t| &t.graph)
337    }
338
339    /// Writes the package into `dir` (created if needed).
340    pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
341        std::fs::create_dir_all(dir)?;
342        let mut sheet = SpriteSheetWriter::default();
343        let character = self
344            .art
345            .character
346            .iter()
347            .map(|((activity, state), anim)| AnimationFile {
348                activity: activity.clone(),
349                state: state.clone(),
350                name: anim.name.clone(),
351                frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
352            })
353            .collect();
354        let journeys = self.themes.iter().any(|t| t.graph.journey.is_some());
355        let file = PackageFile {
356            format: if journeys { 2 } else { 1 },
357            generator_version: self.generator_version,
358            recipe: self.recipe.clone(),
359            width: self.width,
360            height: self.height,
361            activity: self.art.activity.clone(),
362            character,
363            props: self
364                .art
365                .props
366                .iter()
367                .map(|(k, p)| PropFile {
368                    kind: *k,
369                    width: p.width,
370                    height: p.height,
371                    pixels: p.pixels.clone(),
372                })
373                .collect(),
374            themes: self
375                .themes
376                .iter()
377                .map(|t| ThemeFile {
378                    theme: t.theme,
379                    graph: t.graph.clone(),
380                    palette: t.palette.colors().to_vec(),
381                    atlas: t.atlas.clone(),
382                    hero_ms: t.hero_ms,
383                })
384                .collect(),
385        };
386        for t in &self.themes {
387            let mut png = Vec::new();
388            encode_png(&t.background, &t.palette, &mut png)
389                .map_err(|e| PackageError::Png(e.to_string()))?;
390            std::fs::write(dir.join(background_name(t.theme)), png)?;
391            if let Some(j) = &t.graph.journey {
392                for (i, layer) in j.layers.iter().enumerate() {
393                    let png = encode_layer(layer.cols, t.graph.grid.rows, &layer.cells)?;
394                    std::fs::write(dir.join(layer_name(t.theme, i)), png)?;
395                }
396            }
397        }
398        std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
399        let json = serde_json::to_string(&file)?;
400        let tmp = dir.join("package.json.part");
401        std::fs::write(&tmp, json)?;
402        std::fs::rename(tmp, dir.join("package.json"))?;
403        Ok(())
404    }
405
406    /// Reads a package written by this or an older version.
407    pub fn load(dir: &Path) -> Result<Self, PackageError> {
408        let text = std::fs::read_to_string(dir.join("package.json"))?;
409        let probe: FormatProbe = serde_json::from_str(&text)?;
410        if probe.format > PACKAGE_FORMAT || probe.format == 0 {
411            return Err(PackageError::UnsupportedFormat(probe.format));
412        }
413        let file: PackageFile = serde_json::from_str(&text)?;
414        let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
415        let mut character = PackagedCharacter::default();
416        for a in &file.character {
417            let frames = a
418                .frames
419                .iter()
420                .map(|f| sheet.frame(f))
421                .collect::<Result<Vec<_>, _>>()?;
422            character.insert(
423                &a.activity,
424                &a.state,
425                Animation {
426                    name: a.name.clone(),
427                    frames,
428                },
429            );
430        }
431        let art = PackageArt {
432            activity: file.activity,
433            character,
434            props: file
435                .props
436                .into_iter()
437                .map(|p| {
438                    let len = (p.width as usize).checked_mul(p.height as usize);
439                    if len != Some(p.pixels.len()) || p.width == 0 || p.height == 0 {
440                        return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
441                    }
442                    Ok((
443                        p.kind,
444                        OwnedPixmap {
445                            width: p.width,
446                            height: p.height,
447                            pixels: p.pixels,
448                        },
449                    ))
450                })
451                .collect::<Result<_, _>>()?,
452        };
453        if art.activity.as_ref().is_some_and(|a| !a.playable()) {
454            return Err(PackageError::Invalid(
455                "activity has a state with no way on".into(),
456            ));
457        }
458        let mut themes = Vec::new();
459        for t in file.themes {
460            let (background, colors) =
461                decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
462            let palette = IndexedPalette::from_colors(t.palette);
463            if colors != palette.rgb_bytes()
464                || (background.width, background.height) != (file.width, file.height)
465            {
466                return Err(PackageError::Invalid(format!(
467                    "{} background does not match its palette or size",
468                    t.theme.as_str()
469                )));
470            }
471            check_graph(&t.graph, &t.atlas, file.width, file.height)?;
472            check_colors(&art, &palette)?;
473            let mut graph = t.graph;
474            if let Some(j) = &mut graph.journey {
475                let rows = graph.grid.rows;
476                for (i, layer) in j.layers.iter_mut().enumerate() {
477                    let bytes = std::fs::read(dir.join(layer_name(t.theme, i)))?;
478                    layer.cells = decode_layer(&bytes, layer.cols, rows)?;
479                }
480                let width = j.layers.last().map_or(0, |l| l.cols * graph.grid.cell_w);
481                if j.ground.len() != width as usize || j.loop_ms == 0 {
482                    return Err(PackageError::Invalid("journey ground or loop".into()));
483                }
484            }
485            let mut graph_unattended = graph.clone();
486            graph_unattended.buddy = false;
487            themes.push(ThemeScene {
488                theme: t.theme,
489                graph,
490                graph_unattended,
491                palette,
492                atlas: t.atlas,
493                background,
494                hero_ms: t.hero_ms,
495                journey: OnceLock::new(),
496            });
497        }
498        if themes.is_empty() {
499            return Err(PackageError::Invalid("no themes".into()));
500        }
501        Ok(ScenePackage {
502            recipe: file.recipe,
503            width: file.width,
504            height: file.height,
505            generator_version: file.generator_version,
506            art,
507            themes,
508        })
509    }
510}
511
512/// A loaded theme's graph and atlas agree with each other and the image,
513/// so playback can index without checks (a damaged file is an error, not a
514/// crash).
515fn check_graph(
516    graph: &SceneGraph,
517    atlas: &GlyphAtlas,
518    width: u32,
519    height: u32,
520) -> Result<(), PackageError> {
521    let bad = |what: &str| {
522        Err(PackageError::Invalid(format!(
523            "{} {what}",
524            graph.theme.as_str()
525        )))
526    };
527    if (graph.width, graph.height) != (width, height) {
528        return bad("scene size differs from the package's");
529    }
530    let g = &graph.grid;
531    let fits = |origin: u32, n: u32, cell: u32, room: u32| {
532        cell > 0 && u64::from(origin) + u64::from(n) * u64::from(cell) <= u64::from(room)
533    };
534    if !fits(g.origin_x, g.cols, g.cell_w, width) || !fits(g.origin_y, g.rows, g.cell_h, height) {
535        return bad("grid doesn't fit the image");
536    }
537    if !atlas.fits(g.cell_w, g.cell_h) {
538        return bad("glyph atlas doesn't fit the grid");
539    }
540    if !graph.emitters.iter().all(|e| e.is_sound()) {
541        return bad("particles");
542    }
543    Ok(())
544}
545
546/// Every colour of the packaged art is in a theme's palette.
547fn check_colors(art: &PackageArt, palette: &IndexedPalette) -> Result<(), PackageError> {
548    let known = |rgb: &Rgb| palette.sprite_index(*rgb).is_some();
549    let props = art
550        .props
551        .iter()
552        .flat_map(|(_, p)| p.pixels.iter().flatten());
553    let character = art
554        .character
555        .iter()
556        .flat_map(|(_, a)| a.frames.iter().flat_map(|f| f.pixels.iter().flatten()));
557    if props.chain(character).all(known) {
558        Ok(())
559    } else {
560        Err(PackageError::Invalid(
561            "art colour missing from the palette".into(),
562        ))
563    }
564}
565
566fn background_name(theme: Theme) -> String {
567    format!("background-{}.png", theme.as_str())
568}
569
570fn layer_name(theme: Theme, i: usize) -> String {
571    format!("journey-{}-{i}.png", theme.as_str())
572}
573
574/// A journey layer's cells as a grey-and-alpha PNG: one pixel per cell,
575/// the glyph as grey and the shade as alpha.
576fn encode_layer(
577    cols: u32,
578    rows: u32,
579    cells: &[clairlune_scene::Cell],
580) -> Result<Vec<u8>, PackageError> {
581    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
582    let mut out = Vec::new();
583    let mut enc = png::Encoder::new(&mut out, cols, rows);
584    enc.set_color(png::ColorType::GrayscaleAlpha);
585    enc.set_depth(png::BitDepth::Eight);
586    let mut w = enc.write_header().map_err(|e| png_err(&e))?;
587    let data: Vec<u8> = cells.iter().flat_map(|c| [c.glyph, c.shade]).collect();
588    w.write_image_data(&data).map_err(|e| png_err(&e))?;
589    w.finish().map_err(|e| png_err(&e))?;
590    Ok(out)
591}
592
593fn decode_layer(
594    bytes: &[u8],
595    cols: u32,
596    rows: u32,
597) -> Result<Vec<clairlune_scene::Cell>, PackageError> {
598    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
599    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
600    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
601    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
602    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
603    if info.color_type != png::ColorType::GrayscaleAlpha
604        || info.bit_depth != png::BitDepth::Eight
605        || (info.width, info.height) != (cols, rows)
606    {
607        return Err(PackageError::Png(
608            "journey layer: wrong kind or size".into(),
609        ));
610    }
611    let glyphs = clairlune_scene::glyphs::GLYPHS.len() as u8;
612    buf[..info.buffer_size()]
613        .as_chunks::<2>()
614        .0
615        .iter()
616        .map(|&[glyph, shade]| {
617            if glyph < glyphs {
618                Ok(clairlune_scene::Cell { glyph, shade })
619            } else {
620                Err(PackageError::Invalid("journey layer: unknown glyph".into()))
621            }
622        })
623        .collect()
624}
625
626/// Every `(activity, state)` the scene can show: all states of its activity
627/// (the state machine may reach any), or the idle fallback.
628fn capture_character(from: &dyn Character, activity: Option<&Activity>) -> PackagedCharacter {
629    match activity {
630        Some(a) => PackagedCharacter::capture(
631            from,
632            a.animation
633                .states
634                .keys()
635                .map(|s| (a.id.as_str(), s.as_str())),
636        ),
637        None => PackagedCharacter::capture(from, [("", "idle")]),
638    }
639}
640
641/// Every colour the captured frames use, in a stable order.
642fn character_colors(c: &PackagedCharacter) -> Vec<Rgb> {
643    let mut out: Vec<Rgb> = Vec::new();
644    for (_, anim) in c.iter() {
645        for f in &anim.frames {
646            for rgb in f.pixels.iter().flatten() {
647                if !out.contains(rgb) {
648                    out.push(*rgb);
649                }
650            }
651        }
652    }
653    out
654}
655
656/// The pixel art of every prop the scene places, in either Buddy state.
657fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
658    let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
659    for g in graphs {
660        for s in g.props.iter().chain(&g.unattended) {
661            if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
662                out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
663            }
664        }
665    }
666    out
667}
668
669// ---- On-disk format (1, and 2 with a journey's layer images) -----------
670
671#[derive(Deserialize)]
672struct FormatProbe {
673    format: u32,
674}
675
676#[derive(Serialize, Deserialize)]
677struct PackageFile {
678    format: u32,
679    generator_version: u32,
680    recipe: SceneRecipe,
681    width: u32,
682    height: u32,
683    activity: Option<Activity>,
684    character: Vec<AnimationFile>,
685    props: Vec<PropFile>,
686    themes: Vec<ThemeFile>,
687}
688
689#[derive(Serialize, Deserialize)]
690struct AnimationFile {
691    activity: String,
692    state: String,
693    name: String,
694    frames: Vec<FrameFile>,
695}
696
697/// A frame's place in `sprites.png` and its timing and anchors.
698#[derive(Serialize, Deserialize)]
699struct FrameFile {
700    y: u32,
701    width: u32,
702    height: u32,
703    duration_ms: u32,
704    anchors: BTreeMap<String, (i32, i32)>,
705}
706
707#[derive(Serialize, Deserialize)]
708struct PropFile {
709    kind: SpriteKind,
710    width: u32,
711    height: u32,
712    pixels: Vec<Option<Rgb>>,
713}
714
715#[derive(Serialize, Deserialize)]
716struct ThemeFile {
717    theme: Theme,
718    graph: SceneGraph,
719    palette: Vec<Rgb>,
720    atlas: GlyphAtlas,
721    hero_ms: u64,
722}
723
724/// Stacks frames top to bottom in one RGBA image; identical frames share
725/// their pixels.
726#[derive(Default)]
727struct SpriteSheetWriter {
728    width: u32,
729    rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
730    height: u32,
731}
732
733impl SpriteSheetWriter {
734    fn add(&mut self, f: &Frame) -> FrameFile {
735        let y = match self
736            .rows
737            .iter()
738            .find(|(_, w, px)| *w == f.width && *px == f.pixels)
739        {
740            Some((y, _, _)) => *y,
741            None => {
742                let y = self.height;
743                self.rows.push((y, f.width, f.pixels.clone()));
744                self.height += f.height;
745                self.width = self.width.max(f.width);
746                y
747            }
748        };
749        FrameFile {
750            y,
751            width: f.width,
752            height: f.height,
753            duration_ms: f.duration_ms,
754            anchors: f.anchors.clone(),
755        }
756    }
757
758    fn png(&self) -> Result<Vec<u8>, PackageError> {
759        let (w, h) = (self.width.max(1), self.height.max(1));
760        let mut rgba = vec![0u8; (w * h * 4) as usize];
761        for (y0, fw, px) in &self.rows {
762            for (i, p) in px.iter().enumerate() {
763                let Some(c) = p else { continue };
764                let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
765                let o = ((y * w + x) * 4) as usize;
766                rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
767            }
768        }
769        let mut out = Vec::new();
770        let mut enc = png::Encoder::new(&mut out, w, h);
771        enc.set_color(png::ColorType::Rgba);
772        enc.set_depth(png::BitDepth::Eight);
773        let mut writer = enc
774            .write_header()
775            .map_err(|e| PackageError::Png(e.to_string()))?;
776        writer
777            .write_image_data(&rgba)
778            .map_err(|e| PackageError::Png(e.to_string()))?;
779        writer
780            .finish()
781            .map_err(|e| PackageError::Png(e.to_string()))?;
782        Ok(out)
783    }
784}
785
786struct SpriteSheetReader {
787    width: u32,
788    height: u32,
789    rgba: Vec<u8>,
790}
791
792impl SpriteSheetReader {
793    fn open(bytes: &[u8]) -> Result<Self, PackageError> {
794        let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
795        dec.set_transformations(png::Transformations::EXPAND);
796        let mut reader = dec
797            .read_info()
798            .map_err(|e| PackageError::Png(e.to_string()))?;
799        let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
800        let info = reader
801            .next_frame(&mut buf)
802            .map_err(|e| PackageError::Png(e.to_string()))?;
803        if info.color_type != png::ColorType::Rgba {
804            return Err(PackageError::Png("sprites.png must be RGBA".into()));
805        }
806        buf.truncate(info.buffer_size());
807        Ok(SpriteSheetReader {
808            width: info.width,
809            height: info.height,
810            rgba: buf,
811        })
812    }
813
814    fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
815        if f.width > self.width
816            || f.y
817                .checked_add(f.height)
818                .is_none_or(|end| end > self.height)
819        {
820            return Err(PackageError::Invalid(
821                "a frame lies outside sprites.png".into(),
822            ));
823        }
824        let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
825        for y in f.y..f.y + f.height {
826            for x in 0..f.width {
827                let o = ((y * self.width + x) * 4) as usize;
828                let p = &self.rgba[o..o + 4];
829                pixels.push((p[3] != 0).then_some(Rgb {
830                    r: p[0],
831                    g: p[1],
832                    b: p[2],
833                }));
834            }
835        }
836        Ok(Frame {
837            width: f.width,
838            height: f.height,
839            pixels,
840            duration_ms: f.duration_ms,
841            anchors: f.anchors.clone(),
842        })
843    }
844}
845
846/// Decodes an 8-bit indexed PNG to its indices and palette bytes.
847fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
848    let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
849    let dec = png::Decoder::new(std::io::Cursor::new(bytes));
850    let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
851    let palette = reader
852        .info()
853        .palette
854        .as_ref()
855        .ok_or_else(|| PackageError::Png("background must be indexed".into()))?
856        .to_vec();
857    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
858    let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
859    if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
860        return Err(PackageError::Png("background must be 8-bit indexed".into()));
861    }
862    buf.truncate(info.buffer_size());
863    Ok((
864        IndexedImage {
865            width: info.width,
866            height: info.height,
867            pixels: buf,
868        },
869        palette,
870    ))
871}