use super::super::ToImageError;
use std::borrow::Cow;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum PixelFormat {
Bgra8Unorm,
Rgba8Unorm,
Rg8Snorm,
Rgba16Float,
Rgba32Float,
}
impl PixelFormat {
pub const fn channel_count(self) -> usize {
match self {
PixelFormat::Bgra8Unorm
| PixelFormat::Rgba8Unorm
| PixelFormat::Rgba16Float
| PixelFormat::Rgba32Float => 4,
PixelFormat::Rg8Snorm => 2,
}
}
pub const fn bytes_per_pixel(self) -> usize {
match self {
PixelFormat::Bgra8Unorm | PixelFormat::Rgba8Unorm => 4,
PixelFormat::Rg8Snorm => 2,
PixelFormat::Rgba16Float => 8,
PixelFormat::Rgba32Float => 16,
}
}
}
pub struct TexSurface<'a> {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
pub data: Cow<'a, [u8]>,
}
impl TexSurface<'_> {
pub fn as_pixels<P: bytemuck::AnyBitPattern>(&self) -> Option<&[P]> {
bytemuck::try_cast_slice(&self.data).ok()
}
pub fn into_rgba_image(self) -> Result<image::RgbaImage, ToImageError> {
let rgba: Vec<u8> = match self.format {
PixelFormat::Rgba8Unorm => self.data.into_owned(),
PixelFormat::Bgra8Unorm => self
.data
.chunks_exact(4)
.flat_map(|pixel| {
let [b, g, r, a] = pixel else { unreachable!() };
[*r, *g, *b, *a]
})
.collect(),
PixelFormat::Rg8Snorm => self
.data
.chunks_exact(2)
.flat_map(|pixel| {
let [r, g] = pixel else { unreachable!() };
[
snorm8_to_unorm8(*r as i8),
snorm8_to_unorm8(*g as i8),
0,
255,
]
})
.collect(),
PixelFormat::Rgba16Float => self
.data
.chunks_exact(2)
.map(|channel| {
let value = half::f16::from_le_bytes([channel[0], channel[1]]).to_f32();
(value.clamp(0.0, 1.0) * 255.0).round() as u8
})
.collect(),
PixelFormat::Rgba32Float => self
.data
.chunks_exact(4)
.map(|channel| {
let value =
f32::from_le_bytes([channel[0], channel[1], channel[2], channel[3]]);
(value.clamp(0.0, 1.0) * 255.0).round() as u8
})
.collect(),
};
image::RgbaImage::from_raw(self.width, self.height, rgba)
.ok_or(ToImageError::InvalidContainerSize)
}
}
fn snorm8_to_unorm8(v: i8) -> u8 {
let v = v.max(-127) as f32 / 127.0;
((v * 0.5 + 0.5) * 255.0).round() as u8
}