frostbite-formats 0.2.0

Read and write the Frostbite containers and resources of skate. (2025): TOCs, bundles, CAS, EBX documents, shaders, meshes, physics, .fbmod mods
Documentation
//! Texture resources (type [`crate::TEXTURE`]): the 180-byte header skate. stores for a texture, whose pixels lie in
//! the chunk it names. Field layout after ReSkate's `Engine/Resource/texture.cpp` (`read_texture_header`, a port of
//! ReSkate Studio's texture resource), which reads the extended 180-byte form when the resource metadata's version is
//! 12 or 13; the fields it does not read are named from the stock install's textures (every texture resource of the
//! install read, 61,618 headers):
//!
//! ```text
//! 0x00  u32 mip1_block_offset, u32 mip2_block_offset
//!                         physical offsets into the chunk's stored range: see [`TextureHeader::mip_block_offsets`]
//! 0x08  u32 kind          0 a 2D texture, 1 a cube (depth and slices 6), 2 a volume (depth and slices its depth),
//!                         3 an array (depth and slices its layers)
//! 0x0c  u32 format        Frostbite format ordinal ([`block`])
//! 0x10  u32 pool_id       0 in every stock texture
//! 0x14  u16 flags, u16 width, u16 height, u16 depth, u16 slices
//! 0x1e  u8 mip count, u8 first mip
//! 0x20  8  unknown_20     skipped by ReSkate (extended form); byte 0x21 is the mip count in every stock texture
//! 0x28  16 chunk GUID     the chunk holding the pixels
//! 0x38  15 u32 mip sizes  bytes of each level of one slice, largest first
//! 0x74  u32 chunk size
//! 0x78  u32 name_hash     the djb2-xor hash ([`crate::djb2`]) of the resource's lowercase name
//! 0x7c  u32 unknown_7c    not understood: matches no hash of the name or its parts
//! 0x80  52 unknown_80     not read by ReSkate (a texture group name starts here in the base game's textures)
//! ```
//!
//! The fields no one reads are kept as stored, so a header read and written again is byte-identical. Refused: another
//! length, a width or height of 0 or over 16384, a mip count of 0 or over 15.

use crate::{Rd, Result, bad};

const W: &str = "texture";
/// The extended header's length.
pub const HEADER_LEN: usize = 180;
/// The largest side ReSkate accepts.
pub const MAX_SIDE: u16 = 16384;

/// The bits of [`TextureHeader::flags`] stock textures use. Every stock texture's flags are 0, [`flags::STREAMING`],
/// `STREAMING | ON_DEMAND_LOADED` or [`flags::NO_SKIPMIP`]; the names follow the community readings of the other bits.
pub mod flags {
    /// The pixels are streamed from a chunk (set in 49,670 of the 61,618 stock textures, 11,373 more with
    /// [`ON_DEMAND_LOADED`]).
    pub const STREAMING: u16 = 0x0001;
    /// The streamed pixels are loaded on demand.
    pub const ON_DEMAND_LOADED: u16 = 0x0008;
    /// The texture's top mips are never skipped (one stock texture).
    pub const NO_SKIPMIP: u16 = 0x0020;
}

/// A texture's 180-byte header: its dimensions, format, mip chain and the chunk that holds the pixels. Offsets are in the module documentation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextureHeader {
    /// The u32s at 0x00 and 0x04: the byte offset, from the start of the pixel chunk's stored range in its CAS
    /// archive (block headers counted), of the 64 KiB block that holds the first byte of mip level 1 and of level 2.
    /// In the 39,632 stock textures whose chunk is in the TOC table and which carry them (not both zero) this holds
    /// for both; they are zero for a chunk of one block and for some chunks of several (5,213 in the stock install,
    /// a rule not found).
    pub mip_block_offsets: [u32; 2],
    /// 0 a 2D texture, 1 a cube, 2 a volume, 3 an array: the only kinds stock textures use.
    pub kind: u32,
    /// Frostbite format ordinal.
    pub format: u32,
    /// The u32 at 0x10: a pool id, 0 in every stock texture.
    pub pool_id: u32,
    /// The u16 at 0x14, kept as stored: bits of [`flags`].
    pub flags: u16,
    /// Width in texels (u16 at 0x16); 1 to [`MAX_SIDE`].
    pub width: u16,
    /// Height in texels (u16 at 0x18); 1 to [`MAX_SIDE`].
    pub height: u16,
    /// Depth (u16 at 0x1a): 6 for a cube, the depth of a volume, the layer count of an array.
    pub depth: u16,
    /// Slice count (u16 at 0x1c); equal to `depth` for the cube, volume and array kinds.
    pub slices: u16,
    /// Number of mip levels (u8 at 0x1e); 1 to 15.
    pub mip_count: u8,
    /// Index of the first mip level (u8 at 0x1f).
    pub first_mip: u8,
    /// The 8 bytes at 0x20, kept as stored; byte 1 is the mip count in every stock texture and byte 0 is never below
    /// the first mip level.
    pub unknown_20: [u8; 8],
    /// GUID of the chunk that holds the pixels (16 bytes at 0x28), in the byte order of the TOC's chunk table.
    pub chunk: [u8; 16],
    /// Bytes of each level of one slice, largest first; the levels past `mip_count` are 0 in the game's textures.
    pub mip_sizes: [u32; 15],
    /// Size in bytes of the pixel chunk (u32 at 0x74).
    pub chunk_size: u32,
    /// The u32 at 0x78: the [`crate::djb2`] hash of the resource's lowercase name (all 61,618 stock textures).
    pub name_hash: u32,
    /// The u32 at 0x7c, kept as stored; its meaning is not known.
    pub unknown_7c: u32,
    /// The 52 bytes at 0x80, kept as stored (a texture group name starts here in the base game's textures).
    pub unknown_80: [u8; 52],
}

/// Read a texture header. Refused: see the module documentation.
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 {
        mip_block_offsets: [r.u32le(0)?, r.u32le(4)?],
        kind: r.u32le(0x08)?,
        format: r.u32le(0x0c)?,
        pool_id: 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)?,
        name_hash: r.u32le(0x78)?,
        unknown_7c: r.u32le(0x7c)?,
        unknown_80: r.arr(0x80)?,
    };
    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(())
}

/// Write a texture header: the reader's counterpart. Refused as [`read`] refuses.
pub fn write(h: &TextureHeader) -> Result<Vec<u8>> {
    check(h)?;
    let mut o = Vec::with_capacity(HEADER_LEN);
    for w in [
        h.mip_block_offsets[0],
        h.mip_block_offsets[1],
        h.kind,
        h.format,
        h.pool_id,
    ] {
        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.name_hash.to_le_bytes());
    o.extend_from_slice(&h.unknown_7c.to_le_bytes());
    o.extend_from_slice(&h.unknown_80);
    debug_assert_eq!(o.len(), HEADER_LEN);
    Ok(o)
}

/// How a format ordinal stores texels (ReSkate's colour-format table): bytes per texel, or per 4x4 block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Storage {
    /// Uncompressed, this many bytes a texel: 18 and 20 RGBA8, 23 and 24 BGRA8.
    Texel(u32),
    /// Block-compressed, this many bytes a 4x4 block: 54-57 BC1, 58-59 BC2, 60-61 BC3, 66-67 BC7.
    Block(u32),
}

/// The storage of format ordinal `format`, for the colour formats ReSkate decodes; `None` for any other.
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,
    })
}

/// The bytes of a `width` x `height` level stored as `s` (blocks cover partial edges); `None` on overflow.
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),
    }
}

/// The level sizes of a full chain of `mips` levels from `width` x `height` (each side halved, at least 1), largest
/// first; `None` on overflow.
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()
}