Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / map / src / main / rust / src / tile / sprite_extra.rs

sprite_extra.rs46 lines · 2.1 KiBRaw
1//! The PNG decode behind [`crate::tile::sprite`]'s atlas, moved wholesale
2//! out of `sprite.rs` to keep that file under the `rustFileLength` limit.
3//!
4//! No logic changes: [`decode_rgba8`] is called from
5//! [`SpriteAtlas::build`](crate::tile::sprite::SpriteAtlas::build) exactly as before.
6
7/// Decode a PNG to tightly-packed RGBA8.
8///
9/// `EXPAND` normalises palette, greyscale and sub-8-bit inputs to 8-bit colour, so the
10/// only cases left here are RGB (widened) and RGBA (taken as is). Anything else is a sheet
11/// this renderer was not given, and is refused rather than sampled as noise.
12pub(crate) fn decode_rgba8(bytes: &[u8]) -> Result<(Vec<u8>, u32, u32), String> {
13 // `Cursor`, because png 0.18's `Decoder` takes `BufRead + Seek` and a `&[u8]` is only
14 // the former.
15 let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
16 decoder.set_transformations(png::Transformations::EXPAND);
17 let mut reader = decoder.read_info().map_err(|e| format!("sprite PNG header: {e}"))?;
18 let mut buffer = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
19 let info = reader.next_frame(&mut buffer).map_err(|e| format!("sprite PNG data: {e}"))?;
20 if info.bit_depth != png::BitDepth::Eight {
21 return Err(format!("the sprite sheet is {:?}, not 8-bit", info.bit_depth));
22 }
23 let (width, height) = (info.width, info.height);
24 let texels = (width as usize) * (height as usize);
25 let pixels = match info.color_type {
26 png::ColorType::Rgba => {
27 buffer.truncate(texels * 4);
28 buffer
29 }
30 png::ColorType::Rgb => {
31 let mut out = Vec::with_capacity(texels * 4);
32 for rgb in buffer.chunks_exact(3).take(texels) {
33 out.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFF]);
34 }
35 out
36 }
37 other => return Err(format!("the sprite sheet is {other:?}, not RGB or RGBA")),
38 };
39 if pixels.len() != texels * 4 {
40 return Err(format!(
41 "the sprite sheet decoded to {} bytes for {width}x{height}",
42 pixels.len()
43 ));
44 }
45 Ok((pixels, width, height))
46}