use std::path::Path;
use crate::error::Error;
use crate::textures::Texture;
pub struct TextureLoader;
impl Default for TextureLoader {
fn default() -> Self {
Self::new()
}
}
impl TextureLoader {
pub fn new() -> Self {
Self
}
pub fn load<P: AsRef<Path>>(&self, url: P) -> Result<Texture, Error> {
let path = url.as_ref();
let bytes = crate::io::read(path)?;
let image = decode_image(path, &bytes)?;
Ok(Texture::new(image.width, image.height, Some(image.data)))
}
pub fn from_bytes(&self, bytes: &[u8], mime_type: Option<&str>) -> Result<Texture, Error> {
let path = Path::new("<glTF image>");
let image = match mime_type {
Some("image/png") => decode_png(path, bytes)?,
Some("image/jpeg") => decode_jpeg_bytes(path, bytes)?,
Some("image/webp") => decode_webp(path, bytes)?,
_ => decode_image(path, bytes)?,
};
Ok(Texture::new(image.width, image.height, Some(image.data)))
}
}
pub(crate) fn decode_image(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
if bytes.starts_with(b"GIF") {
super::gif::decode(path, bytes)
} else if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
decode_png(path, bytes)
} else if is_webp(bytes) {
decode_webp(path, bytes)
} else if is_avif(bytes) {
Err(Error::image(
path,
"AVIF is not decoded: no pure-Rust AV1 decoder is fit yet (issue #179)",
))
} else {
decode_jpeg_bytes(path, bytes)
}
}
pub(crate) fn decode_png(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder
.read_info()
.map_err(|e| Error::image(path, e.to_string()))?;
let mut buffer = vec![0; reader.output_buffer_size()];
let info = reader
.next_frame(&mut buffer)
.map_err(|e| Error::image(path, e.to_string()))?;
buffer.truncate(info.buffer_size());
let pixels = (info.width as usize) * (info.height as usize);
let data = match info.color_type {
png::ColorType::Rgba => buffer,
png::ColorType::Rgb => {
let mut out = Vec::with_capacity(pixels * 4);
for pixel in buffer.as_chunks::<3>().0 {
out.extend_from_slice(pixel);
out.push(255);
}
out
}
png::ColorType::Grayscale => {
let mut out = Vec::with_capacity(pixels * 4);
for &value in &buffer {
out.extend_from_slice(&[value, value, value, 255]);
}
out
}
png::ColorType::GrayscaleAlpha => {
let mut out = Vec::with_capacity(pixels * 4);
for pixel in buffer.as_chunks::<2>().0 {
out.extend_from_slice(&[pixel[0], pixel[0], pixel[0], pixel[1]]);
}
out
}
png::ColorType::Indexed => {
return Err(Error::image(path, "the PNG palette was not expanded"));
}
};
Ok(crate::textures::Image {
width: info.width,
height: info.height,
data,
})
}
pub(crate) fn decode_jpeg_bytes(
path: &Path,
bytes: &[u8],
) -> Result<crate::textures::Image, Error> {
let options = zune_jpeg::zune_core::options::DecoderOptions::default()
.jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::RGBA);
let mut decoder =
zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(bytes), options);
let data = decoder
.decode()
.map_err(|e| Error::image(path, e.to_string()))?;
let (width, height) = decoder
.dimensions()
.ok_or_else(|| Error::image(path, "the JPEG has no dimensions"))?;
Ok(crate::textures::Image {
width: width as u32,
height: height as u32,
data,
})
}
fn is_webp(bytes: &[u8]) -> bool {
bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP"
}
fn is_avif(bytes: &[u8]) -> bool {
bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && matches!(&bytes[8..12], b"avif" | b"avis")
}
pub(crate) fn decode_webp(path: &Path, bytes: &[u8]) -> Result<crate::textures::Image, Error> {
let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes))
.map_err(|e| Error::image(path, e.to_string()))?;
let (width, height) = decoder.dimensions();
let size = decoder
.output_buffer_size()
.ok_or_else(|| Error::image(path, "the WebP is too large to decode"))?;
let mut buffer = vec![0; size];
decoder
.read_image(&mut buffer)
.map_err(|e| Error::image(path, e.to_string()))?;
let data = if decoder.has_alpha() {
buffer
} else {
let mut out = Vec::with_capacity(buffer.len() / 3 * 4);
for pixel in buffer.as_chunks::<3>().0 {
out.extend_from_slice(pixel);
out.push(255);
}
out
};
Ok(crate::textures::Image {
width,
height,
data,
})
}
#[cfg(test)]
mod tests {
use super::*;
const RED_LOSSLESS: [u8; 36] = [
0x52, 0x49, 0x46, 0x46, 0x1c, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38,
0x4c, 0x0f, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x07, 0x10, 0xfd, 0x8f, 0xfe,
0x07, 0x22, 0xa2, 0xff, 0x01, 0x00,
];
#[test]
fn webp_is_sniffed_and_decoded() {
assert!(is_webp(&RED_LOSSLESS));
for texture in [
TextureLoader::new().from_bytes(&RED_LOSSLESS, Some("image/webp")),
TextureLoader::new().from_bytes(&RED_LOSSLESS, None),
] {
let texture = texture.unwrap();
assert_eq!(texture.size(), (1, 1));
assert_eq!(
texture.borrow().data.as_deref(),
Some(&[255, 0, 0, 255][..])
);
}
}
#[test]
fn avif_is_refused_by_name() {
let header = b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf";
assert!(is_avif(header));
let error = TextureLoader::new()
.from_bytes(header, Some("image/avif"))
.err()
.unwrap()
.to_string();
assert!(error.contains("AVIF"), "{error}");
}
}