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