1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
pub use image::ImageError;
use librashader_common::Size;
use std::marker::PhantomData;
use std::path::Path;
pub struct Image<P: PixelFormat = RGBA8> {
pub bytes: Vec<u8>,
pub size: Size<u32>,
pub pitch: usize,
_pd: PhantomData<P>,
}
pub struct RGBA8;
pub struct BGRA8;
pub trait PixelFormat {
#[doc(hidden)]
fn convert(pixels: &mut Vec<u8>);
}
impl PixelFormat for RGBA8 {
fn convert(_pixels: &mut Vec<u8>) {}
}
impl PixelFormat for BGRA8 {
fn convert(pixels: &mut Vec<u8>) {
for [r, _g, b, _a] in pixels.array_chunks_mut::<4>() {
std::mem::swap(b, r)
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum UVDirection {
TopLeft,
BottomLeft,
}
impl<P: PixelFormat> Image<P> {
pub fn load(path: impl AsRef<Path>, direction: UVDirection) -> Result<Self, ImageError> {
let mut image = image::open(path.as_ref())?;
if direction == UVDirection::BottomLeft {
image = image.flipv();
}
let image = image.to_rgba8();
let height = image.height();
let width = image.width();
let pitch = image
.sample_layout()
.height_stride
.max(image.sample_layout().width_stride);
let mut bytes = image.into_raw();
P::convert(&mut bytes);
Ok(Image {
bytes,
pitch,
size: Size { height, width },
_pd: Default::default(),
})
}
}