use std::{error::Error, fmt, io::Cursor};
use sim_engine::{Color, LogicalScreenPosition, LogicalScreenVector};
use crate::{
app::Application,
assets::ImageAssetError,
input::Action,
screen::{ImageFilter, ImageVisualError, ScreenImageVisual, ScreenRectangleVisual},
};
const WIDTH: u32 = 460;
const HEIGHT: u32 = 307;
const PIXEL_BYTES: usize = WIDTH as usize * HEIGHT as usize * 4;
const PNG: &[u8] = include_bytes!("assets/ferris.png");
pub fn draw_crab<A: Action>(
app: &mut Application<A>,
position: LogicalScreenPosition,
width: f32,
) -> Result<ScreenImageVisual, CrabDrawError> {
let size = LogicalScreenVector::new(width, width * (HEIGHT as f32 / WIDTH as f32));
ScreenRectangleVisual::new(position, size, Color::WHITE)
.map_err(|error| CrabDrawError::Visual(error.into()))?;
let image = if let Some(image) = app.crab_image {
image
} else {
let pixels = decode(PNG)?;
let image = app
.register_image_rgba8(WIDTH, HEIGHT, &pixels)
.map_err(CrabDrawError::Image)?;
app.crab_image = Some(image);
image
};
let mut visual =
ScreenImageVisual::new(image, position, size).map_err(CrabDrawError::Visual)?;
visual.set_filter(ImageFilter::Linear);
Ok(visual)
}
fn decode(bytes: &[u8]) -> Result<Vec<u8>, CrabDrawError> {
let mut decoder = png::Decoder::new_with_limits(
Cursor::new(bytes),
png::Limits {
bytes: 2 * 1024 * 1024,
},
);
decoder.set_ignore_text_chunk(true);
decoder.set_ignore_iccp_chunk(true);
let mut reader = decoder.read_info().map_err(CrabDrawError::Decode)?;
let info = reader.info();
if (info.width, info.height, info.color_type, info.bit_depth)
!= (WIDTH, HEIGHT, png::ColorType::Rgba, png::BitDepth::Eight)
|| info.animation_control.is_some()
|| reader.output_buffer_size() != Some(PIXEL_BYTES)
{
return Err(CrabDrawError::InvalidArtwork);
}
let mut pixels = Vec::new();
pixels
.try_reserve_exact(PIXEL_BYTES)
.map_err(|source| CrabDrawError::Image(ImageAssetError::AllocationFailed { source }))?;
pixels.resize(PIXEL_BYTES, 0);
let frame = reader
.next_frame(&mut pixels)
.map_err(CrabDrawError::Decode)?;
if frame.buffer_size() != PIXEL_BYTES {
return Err(CrabDrawError::InvalidArtwork);
}
Ok(pixels)
}
#[derive(Debug)]
#[non_exhaustive]
pub enum CrabDrawError {
Visual(ImageVisualError),
Image(ImageAssetError),
Decode(png::DecodingError),
InvalidArtwork,
}
impl fmt::Display for CrabDrawError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Visual(error) => write!(formatter, "crab placement failed: {error}"),
Self::Image(error) => write!(formatter, "crab image registration failed: {error}"),
Self::Decode(error) => write!(formatter, "embedded Ferris PNG failed: {error}"),
Self::InvalidArtwork => {
formatter.write_str("embedded Ferris must be a static 460x307 RGBA8 image")
}
}
}
}
impl Error for CrabDrawError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Visual(error) => Some(error),
Self::Image(error) => Some(error),
Self::Decode(error) => Some(error),
Self::InvalidArtwork => None,
}
}
}
#[cfg(test)]
mod tests;