Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_image/src/exr_texture_loader.rs
9366 views
1
use crate::{Image, TextureAccessError, TextureFormatPixelInfo};
2
use bevy_asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
3
use bevy_reflect::TypePath;
4
use image::ImageDecoder;
5
use serde::{Deserialize, Serialize};
6
use thiserror::Error;
7
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
8
9
/// Loads EXR textures as Texture assets
10
#[derive(Clone, Default, TypePath)]
11
#[cfg(feature = "exr")]
12
pub struct ExrTextureLoader;
13
14
#[derive(Serialize, Deserialize, Default, Debug)]
15
#[cfg(feature = "exr")]
16
pub struct ExrTextureLoaderSettings {
17
pub asset_usage: RenderAssetUsages,
18
}
19
20
/// Possible errors that can be produced by [`ExrTextureLoader`]
21
#[non_exhaustive]
22
#[derive(Debug, Error, TypePath)]
23
#[cfg(feature = "exr")]
24
pub enum ExrTextureLoaderError {
25
#[error(transparent)]
26
Io(#[from] std::io::Error),
27
#[error(transparent)]
28
ImageError(#[from] image::ImageError),
29
#[error("Texture access error: {0}")]
30
TextureAccess(#[from] TextureAccessError),
31
}
32
33
impl AssetLoader for ExrTextureLoader {
34
type Asset = Image;
35
type Settings = ExrTextureLoaderSettings;
36
type Error = ExrTextureLoaderError;
37
38
async fn load(
39
&self,
40
reader: &mut dyn Reader,
41
settings: &Self::Settings,
42
_load_context: &mut LoadContext<'_>,
43
) -> Result<Image, Self::Error> {
44
let format = TextureFormat::Rgba32Float;
45
debug_assert_eq!(
46
format.pixel_size()?,
47
4 * 4,
48
"Format should have 32bit x 4 size"
49
);
50
51
let mut bytes = Vec::new();
52
reader.read_to_end(&mut bytes).await?;
53
let decoder = image::codecs::openexr::OpenExrDecoder::with_alpha_preference(
54
std::io::Cursor::new(bytes),
55
Some(true),
56
)?;
57
let (width, height) = decoder.dimensions();
58
59
let total_bytes = decoder.total_bytes() as usize;
60
61
let mut buf = vec![0u8; total_bytes];
62
decoder.read_image(buf.as_mut_slice())?;
63
64
Ok(Image::new(
65
Extent3d {
66
width,
67
height,
68
depth_or_array_layers: 1,
69
},
70
TextureDimension::D2,
71
buf,
72
format,
73
settings.asset_usage,
74
))
75
}
76
77
fn extensions(&self) -> &[&str] {
78
&["exr"]
79
}
80
}
81
82