unbanished_formats/types/
image.rs1use super::*;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ImageFormat {
8 Bc1,
10 Bc3,
12 A8,
14 R8,
16 Bgra8,
18 R32F,
20 R24G8,
22}
23
24#[derive(Debug, Clone)]
26pub struct ImageBuffer {
27 pub width: u32,
29 pub height: u32,
31 pub image_type: u32,
33 pub usage: u32,
35 pub format: ImageFormat,
37 pub generate_mips: bool,
39 pub address: [u32; 3],
41 pub filter: u32,
43 pub source: String,
45 pub levels: Vec<Vec<u8>>,
47}
48
49impl ImageFormat {
50 pub(super) fn from_raw(v: u32) -> Result<Self> {
51 Ok(match v {
52 0 => Self::Bc1,
53 1 | 2 => Self::Bc3,
54 3 => Self::A8,
55 4 => Self::R8,
56 5 => Self::Bgra8,
57 6 => Self::R32F,
58 7 => Self::R24G8,
59 _ => return Err(Error::Unsupported(format!("image format {v}"))),
60 })
61 }
62
63 pub fn level_size(self, w: u32, h: u32) -> usize {
65 let (w, h) = (w.max(1) as usize, h.max(1) as usize);
66 let blocks = w.div_ceil(4) * h.div_ceil(4);
67 match self {
68 Self::Bc1 => blocks * 8,
69 Self::Bc3 => blocks * 16,
70 Self::A8 | Self::R8 => w * h,
71 Self::Bgra8 | Self::R32F | Self::R24G8 => w * h * 4,
72 }
73 }
74}
75
76impl ImageBuffer {
77 pub const CLASS: &'static str = "ImageBuffer";
79
80 pub fn read(r: &mut Reader) -> Result<Self> {
84 r.block(|r, _| {
85 let width = r.u32()?;
86 let height = r.u32()?;
87 let image_type = r.u32()?;
88 let usage = r.u32()?;
89 let format = ImageFormat::from_raw(r.u32()?)?;
90 let generate_mips = r.u32()? != 0;
91 let address = [r.u32()?, r.u32()?, r.u32()?];
92 let filter = r.u32()?;
93 let source = r.string()?;
94 let mut levels = Vec::new();
95 if !matches!(usage, 4 | 5) {
96 for _ in 0..r.count()? {
97 let n = r.count()?;
98 levels.push(r.bytes(n)?.to_vec());
99 }
100 }
101 Ok(ImageBuffer {
102 width,
103 height,
104 image_type,
105 usage,
106 format,
107 generate_mips,
108 address,
109 filter,
110 source,
111 levels,
112 })
113 })
114 }
115
116 pub fn faces(&self) -> usize {
118 if self.image_type == 0 {
119 1
120 } else {
121 6
122 }
123 }
124
125 pub fn mip_count(&self) -> usize {
127 self.levels.len() / self.faces()
128 }
129}