librashader/librashader-runtime/src/image.rs

46 lines
1.1 KiB
Rust
Raw Normal View History

2022-12-02 09:11:42 +11:00
use librashader_common::Size;
pub use image::ImageError;
2022-11-17 16:08:11 +11:00
use std::path::Path;
pub struct Image {
pub bytes: Vec<u8>,
2022-11-26 18:38:15 +11:00
pub size: Size<u32>,
pub pitch: usize,
2022-11-17 16:08:11 +11:00
}
2022-12-02 09:11:42 +11:00
/// The direction of UV coordinates to load the image for.
2022-12-01 14:50:57 +11:00
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum UVDirection {
2022-12-02 09:11:42 +11:00
/// Origin is at the top left (Direct3D, Vulkan)
2022-12-01 14:50:57 +11:00
TopLeft,
2022-12-02 09:11:42 +11:00
/// Origin is at the bottom left (OpenGL)
2022-12-01 14:50:57 +11:00
BottomLeft,
}
2022-12-02 09:11:42 +11:00
2022-11-17 16:08:11 +11:00
impl Image {
2022-12-02 09:11:42 +11:00
/// Load the image from the path as RGBA8.
2022-12-01 14:50:57 +11:00
pub fn load(path: impl AsRef<Path>, direction: UVDirection) -> Result<Self, ImageError> {
let mut image = image::open(path.as_ref())?;
2022-12-02 09:11:42 +11:00
if direction == UVDirection::BottomLeft {
2022-12-01 14:50:57 +11:00
image = image.flipv();
}
let image = image.to_rgba8();
2022-11-21 18:13:22 +11:00
2022-11-17 16:08:11 +11:00
let height = image.height();
let width = image.width();
2022-11-30 17:38:05 +11:00
let pitch = image
.sample_layout()
.height_stride
.max(image.sample_layout().width_stride);
2022-11-22 08:21:50 +11:00
2022-11-17 16:08:11 +11:00
Ok(Image {
2022-11-26 18:38:15 +11:00
bytes: image.into_raw(),
pitch,
2022-11-30 17:38:05 +11:00
size: Size { height, width },
2022-11-17 16:08:11 +11:00
})
}
2022-11-22 08:21:50 +11:00
}