use byteorder::{ReadBytesExt, LE};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use std::{hint::unreachable_unchecked, io};
mod encode;
mod error;
mod format;
mod surface;
mod write;
pub use encode::*;
pub use error::*;
pub use format::*;
pub use surface::*;
use super::ReadError;
#[derive(Debug)]
pub struct Tex {
pub width: u16,
pub height: u16,
pub format: Format,
pub resource_type: u8,
pub flags: TextureFlags,
pub mip_count: u32,
data: Vec<u8>,
}
impl Tex {
pub const MAGIC: u32 = u32::from_le_bytes(*b"TEX\0");
pub fn has_mipmaps(&self) -> bool {
self.flags.contains(TextureFlags::HasMipMaps)
}
pub fn encode_rgba_image(
img: &image::RgbaImage,
options: EncodeOptions,
) -> Result<Self, EncodeError> {
let (width, height) = img.dimensions();
let (data, mip_count, flags) = if options.generate_mipmaps {
let (mip_data, mip_count) =
encode_rgba_with_mipmaps(img, options.format, options.mipmap_filter)?;
(mip_data, mip_count, TextureFlags::HasMipMaps)
} else {
let rgba_data = img.as_raw();
let encoded = encode_rgba(width, height, rgba_data, options.format)?;
(encoded, 1, TextureFlags::empty())
};
Ok(Self {
width: width as u16,
height: height as u16,
format: options.format,
resource_type: 0, flags,
mip_count,
data,
})
}
pub fn encode_dynamic_image(
img: image::DynamicImage,
options: EncodeOptions,
) -> Result<Self, EncodeError> {
Self::encode_rgba_image(&img.to_rgba8(), options)
}
}
impl Tex {
pub fn decode_mipmap(&self, level: u32) -> Result<TexSurface<'_>, DecodeErr> {
let level = level.min(self.mip_count - 1);
let width = self.width as usize;
let height = self.height as usize;
let (block_w, block_h) = self.format.block_size();
let mip_dims = |level: u32| ((width >> level).max(1), (height >> level).max(1));
let mip_bytes = |dims: (usize, usize)| {
(dims.0.div_ceil(block_w)) * (dims.1.div_ceil(block_h)) * self.format.bytes_per_block()
};
let off = (level + 1..self.mip_count)
.map(|level| mip_bytes(mip_dims(level)))
.sum::<usize>();
let (w, h) = mip_dims(level);
let data = match matches!(self.format, Format::Bgra8) {
true => TexSurfaceData::Bgra8Slice(
&self.data[off..off + (w * h * self.format.bytes_per_block())],
),
false => {
let mut data = vec![0; w * h];
let i = &self.data[off..off + mip_bytes((w, h))];
let o = &mut data;
match self.format {
Format::Etc1 => {
texture2ddecoder::decode_etc1(i, w, h, o).map_err(DecodeErr::Etc1)
}
Format::Bc1 => texture2ddecoder::decode_bc1(i, w, h, o).map_err(DecodeErr::Bc1),
Format::Bc3 => texture2ddecoder::decode_bc3(i, w, h, o).map_err(DecodeErr::Bc3),
Format::Etc2Eac => {
texture2ddecoder::decode_etc2_rgba8(i, w, h, o).map_err(DecodeErr::Etc2Eac)
}
Format::Bgra8 => unsafe { unreachable_unchecked() },
}?;
TexSurfaceData::Bgra8Owned(data)
}
};
Ok(TexSurface {
width: w as _,
height: h as _,
data,
})
}
pub fn from_reader<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, ReadError> {
let magic = reader.read_u32::<LE>()?; if magic != Self::MAGIC {
return Err(ReadError::UnexpectedMagic {
expected: Self::MAGIC,
got: magic,
});
}
Ok(Self::from_reader_no_magic(reader)?)
}
pub fn from_reader_no_magic<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, Error> {
let (width, height) = (reader.read_u16::<LE>()?, reader.read_u16::<LE>()?);
let _is_extended_format = reader.read_u8(); let format = Format::from_u8(reader.read_u8()?)?;
let resource_type = reader.read_u8()?;
let flags = reader.read_u8()?;
let flags = TextureFlags::from_bits(flags).ok_or(Error::InvalidTextureFlags(flags))?;
let mut data = Vec::new();
reader.read_to_end(&mut data)?;
Ok(Self {
width,
height,
format,
flags,
resource_type,
data,
mip_count: match flags.contains(TextureFlags::HasMipMaps) {
true => ((height.max(width) as f32).log2().floor() + 1.0) as u32,
false => 1,
},
})
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy)]
pub struct TextureFlags: u8 {
const HasMipMaps = 1;
const Mystery = 2;
}
}
#[derive(TryFromPrimitive, IntoPrimitive, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum TextureFilter {
None,
Nearest,
Linear,
}
#[derive(TryFromPrimitive, IntoPrimitive, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum TextureAddress {
Wrap,
Clamp,
}