Skip to main content

sim_logic/rendering/easter_eggs/
mod.rs

1//! Optional Ferris mascot; ordinary managed images do all the actual drawing.
2
3use std::{error::Error, fmt, io::Cursor};
4
5use sim_engine::{Color, LogicalScreenPosition, LogicalScreenVector};
6
7use crate::{
8    app::Application,
9    assets::ImageAssetError,
10    input::Action,
11    screen::{ImageFilter, ImageVisualError, ScreenImageVisual, ScreenRectangleVisual},
12};
13
14const WIDTH: u32 = 460;
15const HEIGHT: u32 = 307;
16const PIXEL_BYTES: usize = WIDTH as usize * HEIGHT as usize * 4;
17const PNG: &[u8] = include_bytes!("assets/ferris.png");
18
19/// Prepares Ferris for drawing at a logical screen top-left and positive width.
20///
21/// Requires the `easter-eggs` feature. Call before starting the application,
22/// then spawn the returned [`ScreenImageVisual`] normally. Height preserves
23/// the original 460:307 aspect ratio; sampling is linear, tint is white, and
24/// layer/depth are the normal screen-image defaults. No entity, window, GPU
25/// resource, camera or System is created by this function.
26///
27/// The first successful call registers one immutable 460 by 307 RGBA image
28/// (564,880 pixel bytes). Further calls reuse that application's handle, even
29/// when its image registry is full. Geometry is checked before any image work.
30/// Asset failure publishes no image or cached handle; existing assets remain
31/// unchanged. PNG decoding needs temporary memory on first registration only.
32/// No process-wide cache or runtime file/network access is involved.
33///
34/// Ordinary image, entity and rendering limits still apply and are never
35/// increased automatically. Enable screen images and texture/pass allowances
36/// before startup. Copy the visual or change its position, size, tint and
37/// layer for more crabs; assets survive World replacement in their application.
38///
39/// ```
40/// use sim_logic::prelude::*;
41/// # fn main() -> LogicResult {
42/// let mut config = AppConfig::default();
43/// config.set_render_limits(RenderLimits::default()
44///     .with_max_screen_images(1)
45///     .with_frame_limits(FrameLimits::new(2, 1, 6, 4096, 1024 * 1024, 1)));
46/// let mut app = Application::<u8>::new(config)?;
47/// let crab = draw_crab(&mut app, LogicalScreenPosition::new(24.0, 24.0), 230.0)?;
48/// let camera = ActiveCamera2d::centered(1.0)?;
49/// let initial = app.register_world("ferris", move |world| {
50///     world.spawn(camera)?;
51///     world.spawn(crab)?;
52///     Ok(())
53/// })?;
54/// let runner = app.build_headless(initial)?;
55/// assert_eq!(runner.image_asset_count(), 1);
56/// # Ok(())
57/// # }
58/// ```
59pub fn draw_crab<A: Action>(
60    app: &mut Application<A>,
61    position: LogicalScreenPosition,
62    width: f32,
63) -> Result<ScreenImageVisual, CrabDrawError> {
64    let size = LogicalScreenVector::new(width, width * (HEIGHT as f32 / WIDTH as f32));
65    // Same geometry/tint checks as ScreenImageVisual, before registry mutation.
66    ScreenRectangleVisual::new(position, size, Color::WHITE)
67        .map_err(|error| CrabDrawError::Visual(error.into()))?;
68    let image = if let Some(image) = app.crab_image {
69        image
70    } else {
71        let pixels = decode(PNG)?;
72        let image = app
73            .register_image_rgba8(WIDTH, HEIGHT, &pixels)
74            .map_err(CrabDrawError::Image)?;
75        app.crab_image = Some(image);
76        image
77    };
78    let mut visual =
79        ScreenImageVisual::new(image, position, size).map_err(CrabDrawError::Visual)?;
80    visual.set_filter(ImageFilter::Linear);
81    Ok(visual)
82}
83
84fn decode(bytes: &[u8]) -> Result<Vec<u8>, CrabDrawError> {
85    let mut decoder = png::Decoder::new_with_limits(
86        Cursor::new(bytes),
87        png::Limits {
88            bytes: 2 * 1024 * 1024,
89        },
90    );
91    decoder.set_ignore_text_chunk(true);
92    decoder.set_ignore_iccp_chunk(true);
93    let mut reader = decoder.read_info().map_err(CrabDrawError::Decode)?;
94    let info = reader.info();
95    if (info.width, info.height, info.color_type, info.bit_depth)
96        != (WIDTH, HEIGHT, png::ColorType::Rgba, png::BitDepth::Eight)
97        || info.animation_control.is_some()
98        || reader.output_buffer_size() != Some(PIXEL_BYTES)
99    {
100        return Err(CrabDrawError::InvalidArtwork);
101    }
102    let mut pixels = Vec::new();
103    pixels
104        .try_reserve_exact(PIXEL_BYTES)
105        .map_err(|source| CrabDrawError::Image(ImageAssetError::AllocationFailed { source }))?;
106    pixels.resize(PIXEL_BYTES, 0);
107    let frame = reader
108        .next_frame(&mut pixels)
109        .map_err(CrabDrawError::Decode)?;
110    if frame.buffer_size() != PIXEL_BYTES {
111        return Err(CrabDrawError::InvalidArtwork);
112    }
113    Ok(pixels)
114}
115
116/// Failed Ferris preparation; no World or renderer is modified.
117#[derive(Debug)]
118#[non_exhaustive]
119pub enum CrabDrawError {
120    /// Destination geometry cannot be represented as a valid screen image.
121    Visual(ImageVisualError),
122    /// Pixel allocation or normal application image registration failed.
123    Image(ImageAssetError),
124    /// The embedded PNG could not be decoded.
125    Decode(png::DecodingError),
126    /// The embedded artwork did not have its expected static RGBA layout.
127    InvalidArtwork,
128}
129
130impl fmt::Display for CrabDrawError {
131    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Self::Visual(error) => write!(formatter, "crab placement failed: {error}"),
134            Self::Image(error) => write!(formatter, "crab image registration failed: {error}"),
135            Self::Decode(error) => write!(formatter, "embedded Ferris PNG failed: {error}"),
136            Self::InvalidArtwork => {
137                formatter.write_str("embedded Ferris must be a static 460x307 RGBA8 image")
138            }
139        }
140    }
141}
142
143impl Error for CrabDrawError {
144    fn source(&self) -> Option<&(dyn Error + 'static)> {
145        match self {
146            Self::Visual(error) => Some(error),
147            Self::Image(error) => Some(error),
148            Self::Decode(error) => Some(error),
149            Self::InvalidArtwork => None,
150        }
151    }
152}
153
154#[cfg(test)]
155mod tests;