use crate::crpix::CrpixArt;
use crate::{Direction, Sheet};
use core::fmt;
use std::path::Path;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Baked {
pub png: Vec<u8>,
pub json: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BakeError {
Png(String),
ZeroTickRate,
}
impl fmt::Display for BakeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Png(message) => write!(f, "encoding the sheet as PNG failed: {message}"),
Self::ZeroTickRate => write!(
f,
"a tick rate of zero: frame durations are `hold * 1000 / tick_hz`"
),
}
}
}
impl core::error::Error for BakeError {}
pub fn bake(art: &CrpixArt, image: &str, tick_hz: u32) -> Result<Baked, BakeError> {
if tick_hz == 0 {
return Err(BakeError::ZeroTickRate);
}
let (rgba, sheet) = art.to_sheet();
Ok(Baked {
png: encode_png(&rgba, sheet.width, sheet.height)?,
json: art
.needs_metadata()
.then(|| aseprite_json(&sheet, image, tick_hz)),
})
}
pub fn encode_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, BakeError> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_compression(png::Compression::Balanced);
let mut writer = encoder
.write_header()
.map_err(|error| BakeError::Png(error.to_string()))?;
writer
.write_image_data(rgba)
.map_err(|error| BakeError::Png(error.to_string()))?;
writer
.finish()
.map_err(|error| BakeError::Png(error.to_string()))?;
Ok(out)
}
#[must_use]
pub fn aseprite_json(sheet: &Sheet, image: &str, tick_hz: u32) -> String {
let tick_hz = tick_hz.max(1);
let mut out = String::with_capacity(512);
out.push_str("{\n \"frames\": [\n");
for (index, frame) in sheet.frames.iter().enumerate() {
let rect = frame.rect;
out.push_str(" {\"filename\": ");
push_json_string(&mut out, &frame.name);
out.push_str(&format!(
", \"frame\": {{\"x\": {}, \"y\": {}, \"w\": {}, \"h\": {}}}, \
\"rotated\": false, \"trimmed\": false, \
\"spriteSourceSize\": {{\"x\": 0, \"y\": 0, \"w\": {}, \"h\": {}}}, \
\"sourceSize\": {{\"w\": {}, \"h\": {}}}, \"duration\": {}}}",
rect.x,
rect.y,
rect.w,
rect.h,
rect.w,
rect.h,
rect.w,
rect.h,
duration_ms(frame.hold, tick_hz),
));
if index + 1 < sheet.frames.len() {
out.push(',');
}
out.push('\n');
}
out.push_str(" ],\n \"meta\": {\n");
out.push_str(" \"app\": \"https://github.com/kryptic-sh/crcbl\",\n");
out.push_str(" \"version\": \"crcbl-sprite bake\",\n");
out.push_str(" \"image\": ");
push_json_string(&mut out, image);
out.push_str(",\n \"format\": \"RGBA8888\",\n");
out.push_str(&format!(
" \"size\": {{\"w\": {}, \"h\": {}}},\n \"scale\": \"1\"",
sheet.width, sheet.height
));
if !sheet.clips.is_empty() {
out.push_str(",\n \"frameTags\": [\n");
for (index, clip) in sheet.clips.iter().enumerate() {
let from = clip.frames.first().copied().unwrap_or(0);
let to = clip.frames.last().copied().unwrap_or(from);
out.push_str(" {\"name\": ");
push_json_string(&mut out, &clip.name);
out.push_str(&format!(
", \"from\": {from}, \"to\": {to}, \"direction\": \"{}\"",
match clip.direction {
Direction::Forward => "forward",
Direction::Reverse => "reverse",
Direction::PingPong => "pingpong",
}
));
if !clip.looping {
out.push_str(", \"repeat\": \"1\"");
}
out.push('}');
if index + 1 < sheet.clips.len() {
out.push(',');
}
out.push('\n');
}
out.push_str(" ]");
}
if let Some(nine) = sheet.nine
&& let Some(first) = sheet.frames.first()
{
let rect = first.rect;
let centre_w = rect.w.saturating_sub(nine.left + nine.right);
let centre_h = rect.h.saturating_sub(nine.top + nine.bottom);
out.push_str(",\n \"slices\": [\n");
out.push_str(&format!(
" {{\"name\": \"nine\", \"color\": \"#0000ffff\", \"keys\": [\
{{\"frame\": 0, \"bounds\": {{\"x\": {}, \"y\": {}, \"w\": {}, \"h\": {}}}, \
\"center\": {{\"x\": {}, \"y\": {}, \"w\": {centre_w}, \"h\": {centre_h}}}}}]}}\n",
rect.x, rect.y, rect.w, rect.h, nine.left, nine.top,
));
out.push_str(" ]");
}
out.push_str("\n }\n}\n");
out
}
#[must_use]
pub fn duration_ms(hold: u32, tick_hz: u32) -> u32 {
let ms = (u64::from(hold) * 1000).div_ceil(u64::from(tick_hz));
u32::try_from(ms).unwrap_or(u32::MAX).max(1)
}
fn push_json_string(out: &mut String, text: &str) {
out.push('"');
for ch in text.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Visibility {
Public,
Crate,
}
impl Visibility {
#[must_use]
pub fn keyword(self) -> &'static str {
match self {
Self::Public => "pub",
Self::Crate => "pub(crate)",
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct BakeDir<'a> {
pub manifest_dir: &'a Path,
pub out_dir: &'a Path,
pub stems: &'a [&'a str],
pub tick_hz: u32,
pub visibility: Visibility,
pub table_name: &'a str,
pub source_label: &'a str,
}
pub fn bake_dir(request: &BakeDir<'_>) {
let mut table = format!(
"// @generated by build.rs from {}/*.crpix — do not edit.\n\n",
request.source_label
);
let vis = request.visibility.keyword();
table.push_str(&format!(
"/// The tick rate `{}`'s holds were baked at, from `build.rs`.\n\
{vis} const ART_TICK_HZ: u32 = {};\n\n",
request.source_label, request.tick_hz,
));
for stem in request.stems {
let relative = format!("assets/{stem}.crpix");
println!("cargo::rerun-if-changed={relative}");
let source = request.manifest_dir.join(&relative);
let text = std::fs::read_to_string(&source)
.unwrap_or_else(|error| fail(&format!("{relative}: {error}")));
let art =
crate::crpix::parse(&text).unwrap_or_else(|error| fail(&format!("{relative}:{error}")));
let image = format!("{stem}.png");
let baked = bake(&art, &image, request.tick_hz)
.unwrap_or_else(|error| fail(&format!("{relative}: {error}")));
let png = request.out_dir.join(&image);
write(&png, &baked.png);
let upper = stem.to_uppercase();
table.push_str(&format!(
"{vis} static {upper}_PNG: &[u8] = include_bytes!({:?});\n",
png.display().to_string()
));
match &baked.json {
Some(json) => {
let sidecar = request.out_dir.join(format!("{stem}.json"));
write(&sidecar, json.as_bytes());
table.push_str(&format!(
"{vis} static {upper}_JSON: Option<&str> = Some(include_str!({:?}));\n",
sidecar.display().to_string()
));
}
None => {
table.push_str(&format!(
"{vis} static {upper}_JSON: Option<&str> = None;\n"
));
}
}
}
write(&request.out_dir.join(request.table_name), table.as_bytes());
}
fn write(path: &Path, bytes: &[u8]) {
std::fs::write(path, bytes)
.unwrap_or_else(|error| fail(&format!("writing {}: {error}", path.display())));
}
fn fail(message: &str) -> ! {
println!("cargo::error={message}");
std::process::exit(1);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::crpix;
#[test]
fn a_crate_visible_static_is_not_a_public_one() {
assert_eq!(Visibility::Public.keyword(), "pub");
assert_eq!(Visibility::Crate.keyword(), "pub(crate)");
assert_ne!(
Visibility::Crate.keyword(),
Visibility::Public.keyword(),
"the whole point of the parameter"
);
}
const BIRD: &str = "\
crpix: 2 2 2 2 1
palette:
. c None
k c #112233
frame up:
.k
k.
frame down:
k.
.k
clip flap: up down @ 6 loop
nine: 1 0 1 0
";
fn bird() -> crpix::CrpixArt {
crpix::parse(BIRD).expect("the fixture parses")
}
#[test]
fn the_sheet_bakes_to_a_png_that_decodes_to_the_art() {
let baked = bake(&bird(), "bird.png", 60).expect("this bakes");
assert_eq!(&baked.png[1..4], b"PNG", "not a PNG at all");
let decoder = png::Decoder::new(std::io::Cursor::new(&baked.png));
let mut reader = decoder.read_info().expect("the PNG is readable");
let mut buffer = vec![0; reader.output_buffer_size().expect("a known size")];
let info = reader.next_frame(&mut buffer).expect("one frame");
assert_eq!(
(info.width, info.height),
(4, 2),
"two 2x2 frames in a strip"
);
assert_eq!(info.color_type, png::ColorType::Rgba);
let at = |x: usize, y: usize| &buffer[(y * 4 + x) * 4..(y * 4 + x) * 4 + 4];
assert_eq!(at(0, 0), [0, 0, 0, 0], "frame `up` starts transparent");
assert_eq!(at(1, 0), [0x11, 0x22, 0x33, 0xff]);
assert_eq!(at(2, 0), [0x11, 0x22, 0x33, 0xff], "frame `down` is next");
assert_eq!(at(3, 0), [0, 0, 0, 0]);
}
#[test]
fn baking_the_same_sprite_twice_gives_byte_identical_output() {
let first = bake(&bird(), "bird.png", 60).expect("this bakes");
let second = bake(&bird(), "bird.png", 60).expect("this bakes");
assert_eq!(first, second);
}
#[test]
fn the_sidecar_is_the_aseprite_schema() {
let baked = bake(&bird(), "bird.png", 60).expect("this bakes");
let json = baked.json.expect("two frames need a sidecar");
assert!(json.contains("\"filename\": \"up\""), "{json}");
assert!(
json.contains("\"frame\": {\"x\": 2, \"y\": 0, \"w\": 2, \"h\": 2}"),
"the second frame is at x=2: {json}"
);
assert!(json.contains("\"duration\": 100"), "{json}");
assert!(
json.contains("\"name\": \"flap\", \"from\": 0, \"to\": 1, \"direction\": \"forward\""),
"{json}"
);
assert!(
!json.contains("\"repeat\""),
"a looping clip repeats forever"
);
assert!(
json.contains("\"center\": {\"x\": 1, \"y\": 1, \"w\": 1, \"h\": 1}"),
"{json}"
);
assert!(json.contains("\"image\": \"bird.png\""));
assert!(json.contains("\"format\": \"RGBA8888\""));
assert!(json.contains("\"size\": {\"w\": 4, \"h\": 2}"));
}
#[test]
fn the_nine_slice_survives_a_round_trip_through_the_schema() {
let art = crpix::parse(
"crpix: 8 6 1 1 1\n\npalette:\n k c #000\n\nframe a:\n kkkkkkkk\n kkkkkkkk\n \
kkkkkkkk\n kkkkkkkk\n kkkkkkkk\n kkkkkkkk\n\nnine: 2 3 1 4\n",
)
.expect("this parses");
let (_, sheet) = art.to_sheet();
let json = aseprite_json(&sheet, "a.png", 60);
assert!(
json.contains("\"center\": {\"x\": 2, \"y\": 1, \"w\": 3, \"h\": 1}"),
"{json}"
);
let read_back = crate::NineSlice::from_center(
crate::Rect::new(0, 0, 8, 6),
crate::Rect::new(2, 1, 3, 1),
)
.expect("the centre is inside the frame");
assert_eq!(read_back, sheet.nine.expect("the sheet has one"));
}
#[test]
fn a_still_sprite_bakes_to_a_png_and_nothing_else() {
let art = crpix::parse("crpix: 1 1 1 1 1\n\npalette:\n k c #000\n\nframe a:\n k\n")
.expect("parses");
let baked = bake(&art, "a.png", 60).expect("this bakes");
assert_eq!(baked.json, None);
assert!(!baked.png.is_empty());
}
#[test]
fn a_one_shot_clip_writes_its_repeat() {
let art = crpix::parse(
"crpix: 1 1 2 1 1\n\npalette:\n k c #000\n\nframe a:\n k\n\nframe b:\n k\n\n\
clip die: a b\n",
)
.expect("parses");
let json = bake(&art, "a.png", 60)
.expect("bakes")
.json
.expect("a clip");
assert!(json.contains("\"repeat\": \"1\""), "{json}");
}
#[test]
fn a_hold_in_ticks_becomes_milliseconds_at_the_rate_it_is_given() {
assert_eq!(duration_ms(6, 60), 100);
assert_eq!(duration_ms(1, 60), 17, "rounded up, not truncated to 16");
assert_eq!(duration_ms(30, 30), 1000);
assert_eq!(duration_ms(1, 240), 5);
assert_eq!(duration_ms(1, 100_000), 1, "never zero");
assert_eq!(duration_ms(u32::MAX, 1), u32::MAX);
}
#[test]
fn a_zero_tick_rate_is_refused() {
assert_eq!(bake(&bird(), "bird.png", 0), Err(BakeError::ZeroTickRate));
}
#[test]
fn names_are_escaped_into_the_json() {
let mut out = String::new();
push_json_string(&mut out, "a \"quoted\\name\"\twith\ncontrol\u{1}chars");
assert_eq!(
out,
"\"a \\\"quoted\\\\name\\\"\\twith\\ncontrol\\u0001chars\""
);
}
}