use crate::{Rd, Result, bad};
const W: &str = "texture";
pub const HEADER_LEN: usize = 180;
pub const MAX_SIDE: u16 = 16384;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextureHeader {
pub unknown_00: [u8; 8],
pub kind: u32,
pub format: u32,
pub unknown_10: u32,
pub flags: u16,
pub width: u16,
pub height: u16,
pub depth: u16,
pub slices: u16,
pub mip_count: u8,
pub first_mip: u8,
pub unknown_20: [u8; 8],
pub chunk: [u8; 16],
pub mip_sizes: [u32; 15],
pub chunk_size: u32,
pub unknown_78: [u8; 60],
}
pub fn read(bytes: &[u8]) -> Result<TextureHeader> {
if bytes.len() != HEADER_LEN {
return Err(bad(W, 0, format!("{} bytes, not {HEADER_LEN}", bytes.len())));
}
let r = Rd::new(bytes, W);
let mut mip_sizes = [0u32; 15];
for (i, s) in mip_sizes.iter_mut().enumerate() {
*s = r.u32le(crate::at(0x38, i, 4))?;
}
let h = TextureHeader {
unknown_00: r.arr(0)?,
kind: r.u32le(0x08)?,
format: r.u32le(0x0c)?,
unknown_10: r.u32le(0x10)?,
flags: r.u16le(0x14)?,
width: r.u16le(0x16)?,
height: r.u16le(0x18)?,
depth: r.u16le(0x1a)?,
slices: r.u16le(0x1c)?,
mip_count: r.u8(0x1e)?,
first_mip: r.u8(0x1f)?,
unknown_20: r.arr(0x20)?,
chunk: r.arr(0x28)?,
mip_sizes,
chunk_size: r.u32le(0x74)?,
unknown_78: r.arr(0x78)?,
};
check(&h)?;
Ok(h)
}
fn check(h: &TextureHeader) -> Result<()> {
if !(1..=MAX_SIDE).contains(&h.width) || !(1..=MAX_SIDE).contains(&h.height) {
return Err(bad(W, 0x16, format!("dimensions {}x{}", h.width, h.height)));
}
if !(1..=15).contains(&h.mip_count) {
return Err(bad(W, 0x1e, format!("mip count {}", h.mip_count)));
}
Ok(())
}
pub fn write(h: &TextureHeader) -> Result<Vec<u8>> {
check(h)?;
let mut o = Vec::with_capacity(HEADER_LEN);
o.extend_from_slice(&h.unknown_00);
for w in [h.kind, h.format, h.unknown_10] {
o.extend_from_slice(&w.to_le_bytes());
}
for v in [h.flags, h.width, h.height, h.depth, h.slices] {
o.extend_from_slice(&v.to_le_bytes());
}
o.extend_from_slice(&[h.mip_count, h.first_mip]);
o.extend_from_slice(&h.unknown_20);
o.extend_from_slice(&h.chunk);
for s in h.mip_sizes {
o.extend_from_slice(&s.to_le_bytes());
}
o.extend_from_slice(&h.chunk_size.to_le_bytes());
o.extend_from_slice(&h.unknown_78);
debug_assert_eq!(o.len(), HEADER_LEN);
Ok(o)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Storage {
Texel(u32),
Block(u32),
}
pub fn block(format: u32) -> Option<Storage> {
Some(match format {
18 | 20 | 23 | 24 => Storage::Texel(4),
54..=57 => Storage::Block(8),
58..=61 | 66 | 67 => Storage::Block(16),
_ => return None,
})
}
pub fn level_size(s: Storage, width: u32, height: u32) -> Option<u32> {
match s {
Storage::Texel(n) => width.checked_mul(height)?.checked_mul(n),
Storage::Block(n) => width
.div_ceil(4)
.max(1)
.checked_mul(height.div_ceil(4).max(1))?
.checked_mul(n),
}
}
pub fn chain(s: Storage, width: u32, height: u32, mips: u8) -> Option<Vec<u32>> {
(0..u32::from(mips))
.map(|l| level_size(s, (width >> l).max(1), (height >> l).max(1)))
.collect()
}