use crate::art::{OwnedPixmap, Pixmap, SceneArt};
use crate::atlas::GlyphAtlas;
use crate::bake::bake_static;
use crate::clock::Clock;
use crate::frame::{IncrementalFrame, PixelRect, hero_time_with_art, render_frame_with_art};
use crate::palette::IndexedPalette;
use crate::{IndexedImage, encode_png};
use clairlune_scene::activity::{Activity, builtin_catalog};
use clairlune_scene::{
BuildError, BuildOptions, Rgb, SceneGraph, SceneRecipe, SpriteKind, Theme, build,
};
use clairlune_sprites::{Animation, Character, Frame, PackagedCharacter, builtin_character};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;
pub const PACKAGE_FORMAT: u32 = 1;
#[derive(Debug)]
pub enum PackageError {
Io(std::io::Error),
Json(serde_json::Error),
Png(String),
UnsupportedFormat(u32),
Invalid(String),
}
impl fmt::Display for PackageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PackageError::Io(e) => write!(f, "{e}"),
PackageError::Json(e) => write!(f, "package.json: {e}"),
PackageError::Png(e) => write!(f, "image: {e}"),
PackageError::UnsupportedFormat(v) => write!(
f,
"scene package format {v} is newer than this version reads ({PACKAGE_FORMAT})"
),
PackageError::Invalid(e) => write!(f, "scene package: {e}"),
}
}
}
impl std::error::Error for PackageError {}
impl From<std::io::Error> for PackageError {
fn from(e: std::io::Error) -> Self {
PackageError::Io(e)
}
}
impl From<serde_json::Error> for PackageError {
fn from(e: serde_json::Error) -> Self {
PackageError::Json(e)
}
}
#[derive(Clone, Debug)]
pub struct PackageArt {
activity: Option<Activity>,
character: PackagedCharacter,
props: Vec<(SpriteKind, OwnedPixmap)>,
}
impl SceneArt for PackageArt {
fn activity(&self) -> Option<&Activity> {
self.activity.as_ref()
}
fn character(&self) -> &dyn Character {
&self.character
}
fn prop(&self, kind: SpriteKind) -> Option<&dyn Pixmap> {
self.props
.iter()
.find(|(k, _)| *k == kind)
.map(|(_, p)| p as &dyn Pixmap)
}
}
#[derive(Clone, Debug)]
struct ThemeScene {
theme: Theme,
graph: SceneGraph,
graph_unattended: SceneGraph,
palette: IndexedPalette,
atlas: GlyphAtlas,
background: IndexedImage,
hero_ms: u64,
}
#[derive(Clone, Debug)]
pub struct ScenePackage {
pub recipe: SceneRecipe,
pub width: u32,
pub height: u32,
pub generator_version: u32,
art: PackageArt,
themes: Vec<ThemeScene>,
}
impl ScenePackage {
pub fn capture(recipe: &SceneRecipe, width: u32, height: u32) -> Result<Self, BuildError> {
let mut themes = Vec::new();
let mut graphs = Vec::new();
for theme in [Theme::Dark, Theme::Light] {
let opts = BuildOptions {
width,
height,
theme,
buddy: true,
};
match build(recipe, &opts) {
Ok(g) => graphs.push(g),
Err(BuildError::ThemeLocked(_)) => {}
Err(e) => return Err(e),
}
}
let first = graphs.first().ok_or(BuildError::ThemeLocked(Theme::Dark))?;
let activity = first
.activity
.as_deref()
.and_then(|id| builtin_catalog().get(id))
.cloned();
let art = PackageArt {
character: capture_character(activity.as_ref()),
props: capture_props(&graphs),
activity,
};
for mut graph in graphs {
let atlas = GlyphAtlas::for_grid(&graph.grid);
let palette = IndexedPalette::new(&graph.family);
let background = bake_static(&graph, &atlas);
graph.cells = Vec::new();
let hero_ms = hero_time_with_art(&graph, &art);
let mut graph_unattended = graph.clone();
graph_unattended.buddy = false;
themes.push(ThemeScene {
theme: graph.theme,
graph,
graph_unattended,
palette,
atlas,
background,
hero_ms,
});
}
Ok(ScenePackage {
recipe: recipe.clone(),
width,
height,
generator_version: recipe.generator_version,
art,
themes,
})
}
pub fn themes(&self) -> Vec<Theme> {
self.themes.iter().map(|t| t.theme).collect()
}
fn theme(&self, theme: Theme) -> Option<&ThemeScene> {
self.themes.iter().find(|t| t.theme == theme)
}
pub fn hero_ms(&self, theme: Theme) -> Option<u64> {
self.theme(theme).map(|t| t.hero_ms)
}
pub fn frame(
&self,
theme: Theme,
buddy: bool,
t_ms: u64,
clock: Clock,
) -> Option<(IndexedImage, &IndexedPalette)> {
let t = self.theme(theme)?;
let graph = if buddy { &t.graph } else { &t.graph_unattended };
let img = render_frame_with_art(
&t.background,
graph,
&t.atlas,
&t.palette,
t_ms,
clock,
&self.art,
);
Some((img, &t.palette))
}
pub fn incremental(&self, theme: Theme) -> Option<IncrementalFrame> {
self.theme(theme)
.map(|t| IncrementalFrame::new(&t.background))
}
pub fn advance(
&self,
frame: &mut IncrementalFrame,
theme: Theme,
buddy: bool,
t_ms: u64,
clock: Clock,
) -> Option<Vec<PixelRect>> {
let t = self.theme(theme)?;
let graph = if buddy { &t.graph } else { &t.graph_unattended };
Some(frame.advance(
&t.background,
graph,
&t.atlas,
&t.palette,
t_ms,
clock,
&self.art,
))
}
pub fn still(&self, theme: Theme, buddy: bool) -> Option<(IndexedImage, &IndexedPalette)> {
let t = self.hero_ms(theme)?;
self.frame(theme, buddy, t, Clock::Live)
}
pub fn palette(&self, theme: Theme) -> Option<&IndexedPalette> {
self.theme(theme).map(|t| &t.palette)
}
pub fn graph(&self, theme: Theme) -> Option<&SceneGraph> {
self.theme(theme).map(|t| &t.graph)
}
pub fn save(&self, dir: &Path) -> Result<(), PackageError> {
std::fs::create_dir_all(dir)?;
let mut sheet = SpriteSheetWriter::default();
let character = self
.art
.character
.iter()
.map(|((activity, state), anim)| AnimationFile {
activity: activity.clone(),
state: state.clone(),
name: anim.name.clone(),
frames: anim.frames.iter().map(|f| sheet.add(f)).collect(),
})
.collect();
let file = PackageFile {
format: PACKAGE_FORMAT,
generator_version: self.generator_version,
recipe: self.recipe.clone(),
width: self.width,
height: self.height,
activity: self.art.activity.clone(),
character,
props: self
.art
.props
.iter()
.map(|(k, p)| PropFile {
kind: *k,
width: p.width,
height: p.height,
pixels: p.pixels.clone(),
})
.collect(),
themes: self
.themes
.iter()
.map(|t| ThemeFile {
theme: t.theme,
graph: t.graph.clone(),
palette: t.palette.colors().to_vec(),
atlas: t.atlas.clone(),
hero_ms: t.hero_ms,
})
.collect(),
};
for t in &self.themes {
let mut png = Vec::new();
encode_png(&t.background, &t.palette, &mut png)
.map_err(|e| PackageError::Png(e.to_string()))?;
std::fs::write(dir.join(background_name(t.theme)), png)?;
}
std::fs::write(dir.join("sprites.png"), sheet.png()?)?;
let json = serde_json::to_string(&file)?;
let tmp = dir.join("package.json.part");
std::fs::write(&tmp, json)?;
std::fs::rename(tmp, dir.join("package.json"))?;
Ok(())
}
pub fn load(dir: &Path) -> Result<Self, PackageError> {
let text = std::fs::read_to_string(dir.join("package.json"))?;
let probe: FormatProbe = serde_json::from_str(&text)?;
if probe.format > PACKAGE_FORMAT || probe.format == 0 {
return Err(PackageError::UnsupportedFormat(probe.format));
}
let file: PackageFile = serde_json::from_str(&text)?;
let sheet = SpriteSheetReader::open(&std::fs::read(dir.join("sprites.png"))?)?;
let mut character = PackagedCharacter::default();
for a in &file.character {
let frames = a
.frames
.iter()
.map(|f| sheet.frame(f))
.collect::<Result<Vec<_>, _>>()?;
character.insert(
&a.activity,
&a.state,
Animation {
name: a.name.clone(),
frames,
},
);
}
let art = PackageArt {
activity: file.activity,
character,
props: file
.props
.into_iter()
.map(|p| {
if p.pixels.len() != (p.width * p.height) as usize {
return Err(PackageError::Invalid(format!("prop {:?} size", p.kind)));
}
Ok((
p.kind,
OwnedPixmap {
width: p.width,
height: p.height,
pixels: p.pixels,
},
))
})
.collect::<Result<_, _>>()?,
};
let mut themes = Vec::new();
for t in file.themes {
let (background, colors) =
decode_indexed(&std::fs::read(dir.join(background_name(t.theme)))?)?;
let palette = IndexedPalette::from_colors(t.palette);
if colors != palette.rgb_bytes()
|| (background.width, background.height) != (file.width, file.height)
{
return Err(PackageError::Invalid(format!(
"{} background does not match its palette or size",
t.theme.as_str()
)));
}
let mut graph_unattended = t.graph.clone();
graph_unattended.buddy = false;
themes.push(ThemeScene {
theme: t.theme,
graph: t.graph,
graph_unattended,
palette,
atlas: t.atlas,
background,
hero_ms: t.hero_ms,
});
}
if themes.is_empty() {
return Err(PackageError::Invalid("no themes".into()));
}
Ok(ScenePackage {
recipe: file.recipe,
width: file.width,
height: file.height,
generator_version: file.generator_version,
art,
themes,
})
}
}
fn background_name(theme: Theme) -> String {
format!("background-{}.png", theme.as_str())
}
fn capture_character(activity: Option<&Activity>) -> PackagedCharacter {
let from = builtin_character();
match activity {
Some(a) => PackagedCharacter::capture(
from,
a.animation
.states
.keys()
.map(|s| (a.id.as_str(), s.as_str())),
),
None => PackagedCharacter::capture(from, [("", "idle")]),
}
}
fn capture_props(graphs: &[SceneGraph]) -> Vec<(SpriteKind, OwnedPixmap)> {
let mut out: Vec<(SpriteKind, OwnedPixmap)> = Vec::new();
for g in graphs {
for s in g.props.iter().chain(&g.unattended) {
if s.kind != SpriteKind::Character && !out.iter().any(|(k, _)| *k == s.kind) {
out.push((s.kind, OwnedPixmap::copy_of(s.kind.map())));
}
}
}
out
}
#[derive(Deserialize)]
struct FormatProbe {
format: u32,
}
#[derive(Serialize, Deserialize)]
struct PackageFile {
format: u32,
generator_version: u32,
recipe: SceneRecipe,
width: u32,
height: u32,
activity: Option<Activity>,
character: Vec<AnimationFile>,
props: Vec<PropFile>,
themes: Vec<ThemeFile>,
}
#[derive(Serialize, Deserialize)]
struct AnimationFile {
activity: String,
state: String,
name: String,
frames: Vec<FrameFile>,
}
#[derive(Serialize, Deserialize)]
struct FrameFile {
y: u32,
width: u32,
height: u32,
duration_ms: u32,
anchors: BTreeMap<String, (i32, i32)>,
}
#[derive(Serialize, Deserialize)]
struct PropFile {
kind: SpriteKind,
width: u32,
height: u32,
pixels: Vec<Option<Rgb>>,
}
#[derive(Serialize, Deserialize)]
struct ThemeFile {
theme: Theme,
graph: SceneGraph,
palette: Vec<Rgb>,
atlas: GlyphAtlas,
hero_ms: u64,
}
#[derive(Default)]
struct SpriteSheetWriter {
width: u32,
rows: Vec<(u32, u32, Vec<Option<Rgb>>)>,
height: u32,
}
impl SpriteSheetWriter {
fn add(&mut self, f: &Frame) -> FrameFile {
let y = match self
.rows
.iter()
.find(|(_, w, px)| *w == f.width && *px == f.pixels)
{
Some((y, _, _)) => *y,
None => {
let y = self.height;
self.rows.push((y, f.width, f.pixels.clone()));
self.height += f.height;
self.width = self.width.max(f.width);
y
}
};
FrameFile {
y,
width: f.width,
height: f.height,
duration_ms: f.duration_ms,
anchors: f.anchors.clone(),
}
}
fn png(&self) -> Result<Vec<u8>, PackageError> {
let (w, h) = (self.width.max(1), self.height.max(1));
let mut rgba = vec![0u8; (w * h * 4) as usize];
for (y0, fw, px) in &self.rows {
for (i, p) in px.iter().enumerate() {
let Some(c) = p else { continue };
let (x, y) = (i as u32 % fw, y0 + i as u32 / fw);
let o = ((y * w + x) * 4) as usize;
rgba[o..o + 4].copy_from_slice(&[c.r, c.g, c.b, 255]);
}
}
let mut out = Vec::new();
let mut enc = png::Encoder::new(&mut out, w, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut writer = enc
.write_header()
.map_err(|e| PackageError::Png(e.to_string()))?;
writer
.write_image_data(&rgba)
.map_err(|e| PackageError::Png(e.to_string()))?;
writer
.finish()
.map_err(|e| PackageError::Png(e.to_string()))?;
Ok(out)
}
}
struct SpriteSheetReader {
width: u32,
height: u32,
rgba: Vec<u8>,
}
impl SpriteSheetReader {
fn open(bytes: &[u8]) -> Result<Self, PackageError> {
let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
dec.set_transformations(png::Transformations::EXPAND);
let mut reader = dec
.read_info()
.map_err(|e| PackageError::Png(e.to_string()))?;
let mut buf = vec![0; reader.output_buffer_size().unwrap_or(0)];
let info = reader
.next_frame(&mut buf)
.map_err(|e| PackageError::Png(e.to_string()))?;
if info.color_type != png::ColorType::Rgba {
return Err(PackageError::Png("sprites.png must be RGBA".into()));
}
buf.truncate(info.buffer_size());
Ok(SpriteSheetReader {
width: info.width,
height: info.height,
rgba: buf,
})
}
fn frame(&self, f: &FrameFile) -> Result<Frame, PackageError> {
if f.width > self.width || f.y + f.height > self.height {
return Err(PackageError::Invalid(
"a frame lies outside sprites.png".into(),
));
}
let mut pixels = Vec::with_capacity((f.width * f.height) as usize);
for y in f.y..f.y + f.height {
for x in 0..f.width {
let o = ((y * self.width + x) * 4) as usize;
let p = &self.rgba[o..o + 4];
pixels.push((p[3] != 0).then_some(Rgb {
r: p[0],
g: p[1],
b: p[2],
}));
}
}
Ok(Frame {
width: f.width,
height: f.height,
pixels,
duration_ms: f.duration_ms,
anchors: f.anchors.clone(),
})
}
}
fn decode_indexed(bytes: &[u8]) -> Result<(IndexedImage, Vec<u8>), PackageError> {
let png_err = |e: &dyn fmt::Display| PackageError::Png(e.to_string());
let dec = png::Decoder::new(std::io::Cursor::new(bytes));
let mut reader = dec.read_info().map_err(|e| png_err(&e))?;
let palette = reader
.info()
.palette
.as_ref()
.ok_or_else(|| PackageError::Png("background must be indexed".into()))?
.to_vec();
let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
let info = reader.next_frame(&mut buf).map_err(|e| png_err(&e))?;
if info.color_type != png::ColorType::Indexed || info.bit_depth != png::BitDepth::Eight {
return Err(PackageError::Png("background must be 8-bit indexed".into()));
}
buf.truncate(info.buffer_size());
Ok((
IndexedImage {
width: info.width,
height: info.height,
pixels: buf,
},
palette,
))
}