use crate::{
image::{Image, ImageFormat, ImageType, TextureError},
TextureReinterpretationError,
};
use bevy_asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
use bevy_reflect::TypePath;
use thiserror::Error;
use super::{CompressedImageFormats, ImageSampler};
use serde::{Deserialize, Serialize};
#[derive(Clone, TypePath)]
pub struct ImageLoader {
supported_compressed_formats: CompressedImageFormats,
}
impl ImageLoader {
pub const SUPPORTED_FORMATS: &'static [ImageFormat] = &[
#[cfg(feature = "basis-universal")]
ImageFormat::Basis,
#[cfg(feature = "bmp")]
ImageFormat::Bmp,
#[cfg(feature = "dds")]
ImageFormat::Dds,
#[cfg(feature = "ff")]
ImageFormat::Farbfeld,
#[cfg(feature = "gif")]
ImageFormat::Gif,
#[cfg(feature = "ico")]
ImageFormat::Ico,
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg,
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2,
#[cfg(feature = "png")]
ImageFormat::Png,
#[cfg(feature = "pnm")]
ImageFormat::Pnm,
#[cfg(feature = "qoi")]
ImageFormat::Qoi,
#[cfg(feature = "tga")]
ImageFormat::Tga,
#[cfg(feature = "tiff")]
ImageFormat::Tiff,
#[cfg(feature = "webp")]
ImageFormat::WebP,
];
const COUNT_FILE_EXTENSIONS: usize = {
let mut count = 0;
let mut idx = 0;
while idx < Self::SUPPORTED_FORMATS.len() {
count += Self::SUPPORTED_FORMATS[idx].to_file_extensions().len();
idx += 1;
}
count
};
pub const SUPPORTED_FILE_EXTENSIONS: &'static [&'static str] = &{
let mut exts = [""; Self::COUNT_FILE_EXTENSIONS];
let mut ext_idx = 0;
let mut fmt_idx = 0;
while fmt_idx < Self::SUPPORTED_FORMATS.len() {
let mut off = 0;
let fmt_exts = Self::SUPPORTED_FORMATS[fmt_idx].to_file_extensions();
while off < fmt_exts.len() {
exts[ext_idx] = fmt_exts[off];
off += 1;
ext_idx += 1;
}
fmt_idx += 1;
}
exts
};
pub fn new(supported_compressed_formats: CompressedImageFormats) -> Self {
Self {
supported_compressed_formats,
}
}
}
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub enum ImageFormatSetting {
#[default]
FromExtension,
Format(ImageFormat),
Guess,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum ImageArrayLayout {
RowCount {
rows: u32,
},
RowHeight {
pixels: u32,
},
GridCount {
columns: u32,
rows: u32,
},
GridSize {
tile_width_pixels: u32,
tile_height_pixels: u32,
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ImageLoaderSettings {
pub format: ImageFormatSetting,
#[serde(default)]
pub texture_format: Option<wgpu_types::TextureFormat>,
pub is_srgb: bool,
pub sampler: ImageSampler,
pub asset_usage: RenderAssetUsages,
#[serde(default)]
pub array_layout: Option<ImageArrayLayout>,
#[serde(default = "default_expand_grayscale")]
pub expand_grayscale: bool,
}
fn default_expand_grayscale() -> bool {
true
}
impl Default for ImageLoaderSettings {
fn default() -> Self {
Self {
format: ImageFormatSetting::default(),
texture_format: None,
is_srgb: true,
sampler: ImageSampler::Default,
asset_usage: RenderAssetUsages::default(),
array_layout: None,
expand_grayscale: true,
}
}
}
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ImageLoaderError {
#[error("Failed to load image bytes: {0}")]
Io(#[from] std::io::Error),
#[error("Could not load texture file: {0}")]
FileTexture(#[from] FileTextureError),
#[error("Invalid array layout: {0}")]
ArrayLayout(#[from] TextureReinterpretationError),
}
impl AssetLoader for ImageLoader {
type Asset = Image;
type Settings = ImageLoaderSettings;
type Error = ImageLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &ImageLoaderSettings,
load_context: &mut LoadContext<'_>,
) -> Result<Image, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let image_type = match settings.format {
ImageFormatSetting::FromExtension => {
let ext = load_context
.path()
.path()
.extension()
.unwrap()
.to_str()
.unwrap();
ImageType::Extension(ext)
}
ImageFormatSetting::Format(format) => ImageType::Format(format),
ImageFormatSetting::Guess => {
let format = image::guess_format(&bytes).map_err(|err| FileTextureError {
error: err.into(),
path: format!("{}", load_context.path().path().display()),
})?;
ImageType::Format(ImageFormat::from_image_crate_format(format).ok_or_else(
|| FileTextureError {
error: TextureError::UnsupportedTextureFormat(format!("{format:?}")),
path: format!("{}", load_context.path().path().display()),
},
)?)
}
};
let expand_grayscale = settings.expand_grayscale
&& !settings.texture_format.is_some_and(|f| f.components() <= 2);
let mut image = Image::from_buffer_inner(
&bytes,
image_type,
self.supported_compressed_formats,
settings.is_srgb,
expand_grayscale,
settings.sampler.clone(),
settings.asset_usage,
)
.map_err(|err| FileTextureError {
error: err,
path: format!("{}", load_context.path().path().display()),
})?;
if let Some(format) = settings.texture_format {
image.texture_descriptor.format = format;
}
if let Some(array_layout) = settings.array_layout {
let image = match array_layout {
ImageArrayLayout::RowCount { rows } => {
image.reinterpret_stacked_2d_as_array(rows)?;
image
}
ImageArrayLayout::RowHeight { pixels } => {
image.reinterpret_stacked_2d_as_array(image.height() / pixels)?;
image
}
ImageArrayLayout::GridCount { columns, rows } => {
image.create_stacked_array_from_2d_grid(rows, columns)?
}
ImageArrayLayout::GridSize {
tile_width_pixels,
tile_height_pixels,
} => image.create_stacked_array_from_2d_grid(
image.height() / tile_height_pixels,
image.width() / tile_width_pixels,
)?,
};
return Ok(image);
}
Ok(image)
}
fn extensions(&self) -> &[&str] {
Self::SUPPORTED_FILE_EXTENSIONS
}
}
#[derive(Error, Debug)]
#[error("Error reading image file {path}: {error}.")]
pub struct FileTextureError {
error: TextureError,
path: String,
}
#[cfg(test)]
mod tests {
use super::ImageLoaderSettings;
#[test]
fn missing_expand_grayscale_defaults_to_true() {
let mut value = serde_json::to_value(ImageLoaderSettings::default()).unwrap();
value.as_object_mut().unwrap().remove("expand_grayscale");
let settings: ImageLoaderSettings = serde_json::from_value(value).unwrap();
assert!(settings.expand_grayscale);
}
}