use crate::{Rd, Result, bad, capacity};
const W: &str = "meshset";
pub const SECTION_SIZE: usize = 384;
pub const DECL_SIZE: usize = 100;
pub const DECL_AT: usize = 0x70;
pub const DECL2_AT: usize = 0xd4;
const KEY_AT: usize = 0x138;
pub const MAX_LODS: usize = (0x68 - 0x30) / 8;
pub mod usage {
pub const POSITION: u8 = 1;
pub const BLEND_INDICES: u8 = 2;
pub const BLEND_WEIGHTS: u8 = 4;
pub const COLOR0: u8 = 30;
pub const COLOR1: u8 = 31;
pub const TEXCOORD0: u8 = 33;
pub const TEXCOORD1: u8 = 34;
pub const SUBMATERIAL: u8 = 51;
pub const TANGENT_SPACE: u8 = 52;
}
pub mod format {
pub const FLOAT2: u8 = 0x02;
pub const FLOAT3: u8 = 0x03;
pub const FLOAT4: u8 = 0x04;
pub const HALF2: u8 = 0x06;
pub const HALF4: u8 = 0x08;
pub const UBYTE4: u8 = 0x0c;
pub const UBYTE4N: u8 = 0x0d;
pub const USHORT4: u8 = 0x17;
pub fn size(f: u8) -> Option<usize> {
Some(match f {
0x32 => 1, 0x05 | 0x0e | 0x12 => 2, 0x07 | 0x10 | 0x14 => 6, 0x01
| 0x06
| 0x0a..=0x0d
| 0x0f
| 0x13
| 0x16
| 0x18
| 0x1a
| 0x1d
| 0x20
| 0x23
| 0x26..=0x31 => 4,
0x02 | 0x08 | 0x11 | 0x15 | 0x17 | 0x19 | 0x1b | 0x1e | 0x21 | 0x24 => 8,
0x03 | 0x33 | 0x34 => 12, 0x04 | 0x1c | 0x1f | 0x22 | 0x25 => 16, _ => return None,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Element {
pub usage: u8,
pub format: u8,
pub offset: u8,
pub stream: u8,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Decl {
pub elements: Vec<Element>,
pub strides: Vec<u8>,
pub bytes: [u8; DECL_SIZE],
}
impl Default for Decl {
fn default() -> Self {
Self {
elements: Vec::new(),
strides: Vec::new(),
bytes: [0; DECL_SIZE],
}
}
}
impl Decl {
pub fn read(b: &[u8; DECL_SIZE]) -> Result<Self> {
let [.., ne, ns, _, _] = *b;
let (ne, ns) = (usize::from(ne), usize::from(ns));
if ne > 16 || ns > 16 {
return Err(bad(W, 96, format!("declaration of {ne} elements, {ns} streams")));
}
let elements = b
.as_chunks::<4>()
.0
.iter()
.take(ne)
.map(|&[usage, format, offset, stream]| Element {
usage,
format,
offset,
stream,
})
.collect();
let strides = b
.get(64..96)
.unwrap_or_default()
.as_chunks::<2>()
.0
.iter()
.take(ns)
.map(|&[stride, _]| stride)
.collect();
Ok(Self {
elements,
strides,
bytes: *b,
})
}
pub fn stride(&self) -> usize {
self.strides.iter().map(|&s| usize::from(s)).sum()
}
pub fn element(&self, usage: u8) -> Option<Element> {
self.elements.iter().copied().find(|e| e.usage == usage)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Section {
pub at: usize,
pub record: Vec<u8>,
pub name: String,
pub key: u64,
pub decl: Decl,
pub draw_decl: Decl,
pub flags: u8,
pub stride: u8,
pub primitives: u32,
pub start_index: u32,
pub vertex_offset: u32,
pub vertices: u32,
pub bones: Vec<u16>,
}
impl Section {
pub fn primitive_type(&self) -> Option<PrimitiveType> {
PrimitiveType::from_u8(self.record.get(SECTION_PRIMITIVE).copied()?)
}
pub fn stream_offset(&self, j: usize) -> Option<usize> {
let vertices = usize::try_from(self.vertices).ok()?;
self.decl
.strides
.get(..j)?
.iter()
.try_fold(usize::try_from(self.vertex_offset).ok()?, |at, &s| {
at.checked_add(usize::from(s).checked_mul(vertices)?)
})
}
fn vertex_end(&self) -> usize {
wide(self.vertex_offset).saturating_add(self.decl.stride().saturating_mul(wide(self.vertices)))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Lod {
pub at: usize,
pub record: Vec<u8>,
pub name: String,
pub name_parts: [NamePart; 2],
pub lists: [Vec<u8>; LISTS],
pub chunk: [u8; 16],
pub index_size: u8,
pub index_bytes: u32,
pub vertex_bytes: u32,
pub sections: Vec<Section>,
pub bone_masks: Option<Vec<[u8; MASK]>>,
pub bone_map: Option<Vec<u32>>,
}
impl Lod {
pub fn flags(&self) -> u32 {
word(&self.record, LOD_FLAGS)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MeshSet {
pub header: Vec<u8>,
pub name: String,
pub short_name: NamePart,
pub lods: Vec<Lod>,
pub bone_ids: Option<Vec<u16>>,
pub bone_bounds: Option<Vec<[u8; BOUNDS]>>,
pub tail: Vec<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MeshType {
Rigid = 0,
Skinned = 1,
Composite = 2,
}
impl MeshType {
pub fn from_u8(v: u8) -> Option<Self> {
Some(match v {
0 => Self::Rigid,
1 => Self::Skinned,
2 => Self::Composite,
_ => return None,
})
}
}
pub const HEADER_TYPE: usize = 0x7c;
pub const HEADER_FLAGS: usize = 0xa8;
pub const LOD_FLAGS: usize = 0x50;
pub const SECTION_PRIMITIVE: usize = 0x1f;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PrimitiveType {
PointList = 0,
LineList = 1,
LineStrip = 2,
TriangleList = 3,
TriangleStrip = 5,
QuadList = 7,
XenonRectList = 8,
TrianglePatch = 9,
}
impl PrimitiveType {
pub fn from_u8(v: u8) -> Option<Self> {
Some(match v {
0 => Self::PointList,
1 => Self::LineList,
2 => Self::LineStrip,
3 => Self::TriangleList,
5 => Self::TriangleStrip,
7 => Self::QuadList,
8 => Self::XenonRectList,
9 => Self::TrianglePatch,
_ => return None,
})
}
}
pub mod category {
pub const OPAQUE: usize = 0;
pub const TRANSPARENT: usize = 1;
pub const TRANSPARENT_DECAL: usize = 2;
pub const Z_ONLY: usize = 3;
pub const SHADOW: usize = 4;
}
pub mod set_flags {
pub const STREAMING_ENABLE: u32 = 1 << 0;
pub const STREAM_INSTANCING_ENABLE: u32 = 1 << 2;
}
pub mod lod_flags {
pub const STREAMING_ENABLE: u32 = 1 << 6;
pub const STREAM_INSTANCING_ENABLE: u32 = 1 << 4;
}
impl MeshSet {
pub fn mesh_type(&self) -> Option<MeshType> {
MeshType::from_u8(self.header.get(HEADER_TYPE).copied()?)
}
pub fn layout_flags(&self) -> u32 {
word(&self.header, HEADER_FLAGS)
}
pub fn lod_size(&self) -> usize {
wide(word(&self.header, 4))
}
}
pub const HEADER: usize = 0xd0;
pub const HEADER_BONES: usize = 0xe0;
pub const LOD_PLAIN: usize = 0xb0;
pub const LOD_MASKS: usize = 0xb8;
pub const LOD_MAP: usize = 0xbc;
pub const LISTS: usize = 5;
pub const MASK: usize = 24;
pub const BOUNDS: usize = 32;
pub fn bounds(b: &[u8; BOUNDS]) -> [[f32; 4]; 2] {
let quad = |half: &[u8]| {
let mut q = [0f32; 4];
for (v, c) in q.iter_mut().zip(half.as_chunks::<4>().0) {
*v = f32::from_le_bytes(*c);
}
q
};
let (min, max) = b.split_at(BOUNDS / 2);
[quad(min), quad(max)]
}
fn wide(v: u32) -> usize {
usize::try_from(v).unwrap_or(usize::MAX)
}
fn plus(at: usize, by: usize) -> usize {
at.saturating_add(by)
}
fn word(b: &[u8], at: usize) -> u32 {
b.get(at..)
.and_then(|b| b.first_chunk::<4>())
.map_or(0, |w| u32::from_le_bytes(*w))
}
fn check_draw(stored: &Decl, draw: &Decl) -> std::result::Result<(), String> {
if !draw.strides.starts_with(&stored.strides) {
return Err("the draw declaration's streams do not start with the stored ones".into());
}
if let Some(e) = stored.elements.iter().find(|e| !draw.elements.contains(e)) {
return Err(format!("stored element {e:?} missing from the draw declaration"));
}
for e in draw.elements.iter().filter(|e| !stored.elements.contains(e)) {
if e.stream == 255 {
continue;
}
let size = format::size(e.format).ok_or_else(|| format!("unknown element format {}", e.format))?;
let stride = *draw
.strides
.get(usize::from(e.stream))
.ok_or("draw element stream out of range")?;
if usize::from(e.offset).saturating_add(size) > usize::from(stride) {
return Err(format!("draw element {e:?} runs past its stream"));
}
}
Ok(())
}
fn ptr(r: &Rd, at: usize) -> Result<usize> {
let p = r.u64le(at)?;
usize::try_from(p)
.ok()
.and_then(|p| p.checked_add(16))
.ok_or_else(|| bad(W, at, "pointer out of range"))
}
fn without_pointers(b: &[u8], fields: &[usize]) -> Result<Vec<u8>> {
let mut v = b.to_vec();
for &f in fields {
put(&mut v, f, &[0; 8])?;
}
Ok(v)
}
fn opt_ptr(r: &Rd, at: usize) -> Result<Option<usize>> {
Ok(if r.u64le(at)? == 0 {
None
} else {
Some(ptr(r, at)?)
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NamePart {
At(usize),
Own(String),
}
impl Default for NamePart {
fn default() -> Self {
Self::At(0)
}
}
fn name<const N: usize>(r: &Rd, at: usize, parts: [usize; N]) -> Result<(String, [NamePart; N])> {
let a = ptr(r, at)?;
let s = r.cstr(a)?;
let mut out: [NamePart; N] = std::array::from_fn(|_| NamePart::default());
for (o, &p) in out.iter_mut().zip(&parts) {
let b = ptr(r, p)?;
*o = match b.checked_sub(a).filter(|&o| o <= s.len()) {
Some(o) => NamePart::At(o),
None => NamePart::Own(r.cstr(b)?),
};
}
Ok((s, out))
}
fn items<T>(r: &Rd, at: usize, n: usize, size: usize, item: impl Fn(usize) -> Result<T>) -> Result<Vec<T>> {
(0..capacity(W, n, size, r.data.len())?)
.map(|i| item(crate::at(at, i, size)))
.collect()
}
pub fn read(d: &[u8]) -> Result<MeshSet> {
let r = Rd::new(d, W);
let header_size = plus(r.size32le(0)?, 16);
if header_size != HEADER && header_size != HEADER_BONES {
return Err(bad(W, 0, format!("header of {header_size:#x} bytes")));
}
let lod_size = r.size32le(4)?;
if ![LOD_PLAIN, LOD_MASKS, LOD_MAP].contains(&lod_size) {
return Err(bad(W, 4, format!("LOD records of {lod_size:#x} bytes")));
}
let section_size = r.size32le(8)?;
if section_size != SECTION_SIZE {
return Err(bad(W, 8, format!("section records of {section_size:#x} bytes")));
}
let n = usize::from(r.u16le(0xb4)?);
if n > MAX_LODS {
return Err(bad(
W,
0xb4,
format!("{n} LODs, but only {MAX_LODS} record pointers fit between 0x30 and the name"),
));
}
let (name_, [short_name]) = name(&r, 0x68, [0x70])?;
let mut lods = Vec::with_capacity(n);
for l in 0..n {
let at = ptr(&r, crate::at(0x30, l, 8))?;
let field = |k: usize| plus(at, k);
let count = r.size32le(field(8))?;
let first = ptr(&r, field(0x0c))?;
let (lod_name, name_parts) = name(&r, field(0x8c), [field(0x94), field(0x9c)])?;
let mut lists: [Vec<u8>; LISTS] = Default::default();
for (k, list) in lists.iter_mut().enumerate() {
let c = r.size32le(crate::at(field(0x14), k, 12))?;
*list = r.bytes(ptr(&r, crate::at(field(0x18), k, 12))?, c)?.to_vec();
}
let bone_masks = match lod_size {
LOD_MASKS => opt_ptr(&r, field(0xb0))?
.map(|p| items(&r, p, count, MASK, |a| r.arr(a)))
.transpose()?,
_ => None,
};
let bone_map = match lod_size {
LOD_MAP => opt_ptr(&r, field(0xb4))?
.map(|p| items(&r, p, r.size32le(field(0xb0))?, 4, |a| r.u32le(a)))
.transpose()?,
_ => None,
};
let mut lod = Lod {
at,
record: without_pointers(
r.bytes(at, crate::align(lod_size, 16))?,
&[0x0c, 0x18, 0x24, 0x30, 0x3c, 0x48, 0x8c, 0x94, 0x9c]
.into_iter()
.chain(match lod_size {
LOD_MASKS => Some(0xb0),
LOD_MAP => Some(0xb4),
_ => None,
})
.collect::<Vec<_>>(),
)?,
name: lod_name,
name_parts,
lists,
chunk: r.arr(field(0x74))?,
index_size: match r.u32le(field(0x54))? {
0x21 => 2,
0x2e => 4,
f => return Err(bad(W, field(0x54), format!("unknown index format {f:#x}"))),
},
index_bytes: r.u32le(field(0x58))?,
vertex_bytes: r.u32le(field(0x5c))?,
sections: Vec::with_capacity(capacity(W, count, SECTION_SIZE, d.len())?),
bone_masks,
bone_map,
};
for s in 0..count {
let o = crate::at(first, s, SECTION_SIZE);
let field = |k: usize| plus(o, k);
let decl = Decl::read(&r.arr(field(DECL_AT))?)?;
let draw_decl = Decl::read(&r.arr(field(DECL2_AT))?)?;
check_draw(&decl, &draw_decl).map_err(|d| bad(W, o, d))?;
let sec = Section {
at: o,
record: without_pointers(r.bytes(o, SECTION_SIZE)?, &[0x08, 0x10])?,
name: r.cstr(ptr(&r, field(8))?)?,
key: r.u64le(field(KEY_AT))?,
decl,
draw_decl,
flags: r.u8(field(0x1b))?,
stride: r.u8(field(0x1e))?,
primitives: r.u32le(field(0x20))?,
start_index: r.u32le(field(0x24))?,
vertex_offset: r.u32le(field(0x28))?,
vertices: r.u32le(field(0x2c))?,
bones: match usize::from(r.u16le(field(0x18))?) {
0 => Vec::new(),
c => items(&r, ptr(&r, field(0x10))?, c, 2, |a| r.u16le(a))?,
},
};
if usize::from(sec.stride) != sec.decl.stride() {
return Err(bad(
W,
o,
format!(
"stride byte {} != declared streams {}",
sec.stride,
sec.decl.stride()
),
));
}
if r.u32le(field(0x54))? != sec.vertex_offset || r.u32le(field(0x140))? != sec.start_index {
return Err(bad(W, o, "repeated vertex offset / start index differ"));
}
for e in &sec.decl.elements {
let size = format::size(e.format)
.ok_or_else(|| bad(W, o, format!("unknown element format {}", e.format)))?;
let stride = *sec
.decl
.strides
.get(usize::from(e.stream))
.ok_or_else(|| bad(W, o, "element stream out of range"))?;
if usize::from(e.offset).saturating_add(size) > usize::from(stride) {
return Err(bad(W, o, "element runs past its stream"));
}
}
lod.sections.push(sec);
}
let vend = lod.sections.iter().map(Section::vertex_end).max().unwrap_or(0);
if !lod.vertex_bytes.is_multiple_of(16)
|| wide(lod.vertex_bytes)
.checked_sub(vend)
.is_none_or(|slack| slack >= 16)
{
return Err(bad(
W,
at,
format!(
"vertex buffer {} for vertex data ending at {vend}",
lod.vertex_bytes
),
));
}
let iend = lod
.sections
.iter()
.map(|s| {
usize::from(lod.index_size)
.saturating_mul(wide(s.start_index).saturating_add(wide(s.primitives).saturating_mul(3)))
})
.max()
.unwrap_or(0);
if wide(lod.index_bytes)
.checked_sub(iend)
.is_none_or(|slack| slack >= 4)
{
return Err(bad(
W,
at,
format!(
"index buffer {} for {}-byte indices ending at {iend}",
lod.index_bytes, lod.index_size
),
));
}
lods.push(lod);
}
let (mut bone_ids, mut bone_bounds) = (None, None);
if header_size == HEADER_BONES {
let (bones, bounded) = (usize::from(r.u16le(0xc4)?), usize::from(r.u16le(0xc6)?));
if let Some(p) = opt_ptr(&r, 0xc8)? {
bone_ids = Some(items(&r, p, bounded, 2, |a| r.u16le(a))?);
}
if let Some(p) = opt_ptr(&r, 0xd0)? {
let c = if bone_ids.is_some() { bounded } else { bones };
bone_bounds = Some(items(&r, p, c, BOUNDS, |a| r.arr(a))?);
}
}
Ok(MeshSet {
header: without_pointers(
r.bytes(0, header_size)?,
&(0..MAX_LODS)
.map(|l| crate::at(0x30, l, 8))
.chain([0x68, 0x70])
.chain(if header_size == HEADER_BONES {
vec![0xc8, 0xd0]
} else {
vec![]
})
.collect::<Vec<_>>(),
)?,
name: name_,
short_name,
lods,
bone_ids,
bone_bounds,
tail: Vec::new(),
})
}
fn pointer_fields(m: &MeshSet, lod_at: &[usize], sec_at: &[Vec<usize>]) -> Vec<usize> {
let mut f = Vec::new();
for ((lod, &at), secs) in m.lods.iter().zip(lod_at).zip(sec_at) {
f.push(plus(at, 0x0c));
for (sec, &o) in lod.sections.iter().zip(secs) {
f.push(plus(o, 8));
if !sec.bones.is_empty() {
f.push(plus(o, 0x10));
}
}
f.extend((0..LISTS).map(|k| crate::at(plus(at, 0x18), k, 12)));
f.extend([plus(at, 0x8c), plus(at, 0x94), plus(at, 0x9c)]);
if lod.bone_masks.is_some() {
f.push(plus(at, 0xb0));
}
if lod.bone_map.is_some() {
f.push(plus(at, 0xb4));
}
}
f.extend((0..m.lods.len()).map(|l| crate::at(0x30, l, 8)));
f.extend([0x68, 0x70]);
if m.bone_ids.is_some() {
f.push(0xc8);
}
if m.bone_bounds.is_some() {
f.push(0xd0);
}
f
}
pub fn read_resource(d: &[u8], meta: &[u8; 16]) -> Result<MeshSet> {
let mut m = read(d)?;
let w = |i: usize| wide(word(meta, crate::at(0, i, 4)));
let (table, size, trailing) = (w(0), w(1), w(2));
let end = crate::align(plus(table, size), 16);
if w(3) != 0 || !size.is_multiple_of(4) || end.checked_add(trailing) != Some(d.len()) {
return Err(bad(
W,
table,
format!("metadata {} for {} bytes", crate::hex(meta), d.len()),
));
}
let r = Rd::new(d, W);
let lod_at: Vec<usize> = m.lods.iter().map(|l| l.at).collect();
let sec_at: Vec<Vec<usize>> = m
.lods
.iter()
.map(|l| l.sections.iter().map(|s| s.at).collect())
.collect();
let fields = pointer_fields(&m, &lod_at, &sec_at);
let mut stored = items(&r, table, size / 4, 4, |a| r.u32le(a).map(|v| plus(wide(v), 16)))?;
let mut fields = fields;
stored.sort_unstable();
fields.sort_unstable();
if stored != fields {
return Err(bad(
W,
table,
format!(
"relocation table of {} entries, not the records' {} pointers",
stored.len(),
fields.len()
),
));
}
m.tail = d
.get(end..)
.ok_or_else(|| bad(W, end, "trailing data past the end"))?
.to_vec();
Ok(m)
}
fn put(out: &mut [u8], at: usize, v: &[u8]) -> Result<()> {
let total = out.len();
at.checked_add(v.len())
.and_then(|end| out.get_mut(at..end))
.ok_or_else(|| {
bad(
W,
at,
format!("{} bytes past the end of the {total}-byte block", v.len()),
)
})?
.copy_from_slice(v);
Ok(())
}
fn pad(out: &mut Vec<u8>, a: usize) {
out.resize(crate::align(out.len(), a), 0);
}
fn push_named<const N: usize>(
out: &mut Vec<u8>,
s: &str,
parts: &[NamePart; N],
) -> Result<(usize, [usize; N])> {
let at = push_name(out, s)?;
let mut places = [0; N];
for (place, part) in places.iter_mut().zip(parts) {
*place = match part {
NamePart::At(o) if *o <= s.len() => plus(at, *o),
NamePart::At(o) => return Err(bad(W, at, format!("part at {o} of {s:?}, past its end"))),
NamePart::Own(p) => push_name(out, p)?,
};
}
Ok((at, places))
}
fn push_name(out: &mut Vec<u8>, s: &str) -> Result<usize> {
let at = out.len();
let b = crate::latin1(s, W)?;
if b.contains(&0) {
return Err(bad(W, 0, format!("name {s:?} holds a zero")));
}
out.extend(b);
out.push(0);
Ok(at)
}
fn u32_of(n: usize, what: &str) -> Result<[u8; 4]> {
u32::try_from(n)
.map(u32::to_le_bytes)
.map_err(|_| bad(W, 0, format!("{n} {what}")))
}
fn nth<T: Copy>(table: &[T], i: usize, what: &str) -> Result<T> {
table
.get(i)
.copied()
.ok_or_else(|| bad(W, i, format!("no {what} {i} in the layout")))
}
fn u16_of(n: usize, at: usize, what: &str) -> Result<[u8; 2]> {
u16::try_from(n)
.map(u16::to_le_bytes)
.map_err(|_| bad(W, at, format!("{n} {what}")))
}
fn pointer(out: &mut [u8], at: usize, target: usize) -> Result<()> {
let relative = u64::try_from(target)
.ok()
.and_then(|t| t.checked_sub(16))
.ok_or_else(|| bad(W, at, format!("a pointer to {target:#x}")))?;
put(out, at, &relative.to_le_bytes())
}
pub fn write(m: &MeshSet) -> Result<(Vec<u8>, [u8; 16])> {
let hs = m.header.len();
if (hs != HEADER && hs != HEADER_BONES) || wide(word(&m.header, 0)).saturating_add(16) != hs {
return Err(bad(W, 0, format!("a header of {hs:#x} bytes")));
}
let lod_size = m.lod_size();
if ![LOD_PLAIN, LOD_MASKS, LOD_MAP].contains(&lod_size) || wide(word(&m.header, 8)) != SECTION_SIZE {
return Err(bad(W, 4, "LOD or section records of an unknown size"));
}
if m.lods.len() > MAX_LODS {
return Err(bad(W, 0xb4, format!("{} LODs", m.lods.len())));
}
if hs == HEADER && (m.bone_ids.is_some() || m.bone_bounds.is_some()) {
return Err(bad(W, 0xc8, "bone bounds need the 0xe0 header"));
}
let lod_stride = crate::align(lod_size, 16);
let mut out = m.header.clone();
let mut lod_at = Vec::with_capacity(m.lods.len());
for (l, lod) in m.lods.iter().enumerate() {
let refuse = |what: &str| Err(bad(W, l, format!("LOD {l}: {what}")));
if lod.record.len() != lod_stride {
return refuse("a record of another size than the header's");
}
if (lod.bone_masks.is_some() && lod_size != LOD_MASKS)
|| (lod.bone_map.is_some() && lod_size != LOD_MAP)
{
return refuse("a bone table its record has no room for");
}
if lod
.bone_masks
.as_ref()
.is_some_and(|b| b.len() != lod.sections.len())
{
return refuse("bone masks for other than its sections");
}
lod_at.push(out.len());
out.extend(&lod.record);
}
let mut sec_at = Vec::with_capacity(m.lods.len());
for (l, lod) in m.lods.iter().enumerate() {
let mut row = Vec::with_capacity(lod.sections.len());
for (s, sec) in lod.sections.iter().enumerate() {
if sec.record.len() != SECTION_SIZE {
return Err(bad(
W,
l,
format!("LOD {l} section {s}: a record of {} bytes", sec.record.len()),
));
}
row.push(out.len());
out.extend(&sec.record);
}
sec_at.push(row);
}
let mut bones_at = Vec::new();
for sec in m.lods.iter().flat_map(|l| &l.sections) {
bones_at.push(out.len());
sec.bones.iter().for_each(|b| out.extend(b.to_le_bytes()));
}
pad(&mut out, 16);
let (mut names_at, mut lod_name_at) = (Vec::new(), Vec::new());
for lod in &m.lods {
for sec in &lod.sections {
names_at.push(push_name(&mut out, &sec.name)?);
}
lod_name_at.push(push_named(&mut out, &lod.name, &lod.name_parts)?);
}
let (name_at, [short_at]) = push_named(&mut out, &m.name, std::array::from_ref(&m.short_name))?;
pad(&mut out, 16);
let mut lists_at = Vec::new();
for list in m.lods.iter().flat_map(|l| &l.lists) {
lists_at.push(out.len());
out.extend(list);
}
pad(&mut out, 16);
let mut tables_at = Vec::new();
for lod in &m.lods {
if let Some(masks) = &lod.bone_masks {
pad(&mut out, 16);
tables_at.push(out.len());
masks.iter().for_each(|b| out.extend(b));
} else if let Some(map) = &lod.bone_map {
pad(&mut out, 4);
tables_at.push(out.len());
map.iter().for_each(|b| out.extend(b.to_le_bytes()));
} else {
tables_at.push(0);
}
}
let ids_at = m.bone_ids.as_ref().map(|ids| {
pad(&mut out, 16);
let at = out.len();
ids.iter().for_each(|b| out.extend(b.to_le_bytes()));
at
});
let bounds_at = m.bone_bounds.as_ref().map(|bounds| {
pad(&mut out, 16);
let at = out.len();
bounds.iter().for_each(|b| out.extend(b));
at
});
pad(&mut out, 16);
let mut s_i = 0usize;
for (l, lod) in m.lods.iter().enumerate() {
let at = nth(&lod_at, l, "LOD record")?;
let field = |k: usize| plus(at, k);
put(&mut out, field(8), &u32_of(lod.sections.len(), "sections")?)?;
let first = nth_row(&sec_at, l)?.first().copied().unwrap_or(16);
pointer(&mut out, field(0x0c), first)?;
for (k, list) in lod.lists.iter().enumerate() {
put(
&mut out,
crate::at(field(0x14), k, 12),
&u32_of(list.len(), "list entries")?,
)?;
let list_at = nth(&lists_at, crate::at(k, l, LISTS), "list")?;
pointer(&mut out, crate::at(field(0x18), k, 12), list_at)?;
}
let format: u32 = match lod.index_size {
2 => 0x21,
4 => 0x2e,
n => return Err(bad(W, field(0x54), format!("LOD {l}: {n}-byte indices"))),
};
put(&mut out, field(0x54), &format.to_le_bytes())?;
put(&mut out, field(0x58), &lod.index_bytes.to_le_bytes())?;
put(&mut out, field(0x5c), &lod.vertex_bytes.to_le_bytes())?;
put(&mut out, field(0x74), &lod.chunk)?;
let (name_at, [path_at, last_at]) = nth(&lod_name_at, l, "LOD name")?;
pointer(&mut out, field(0x8c), name_at)?;
pointer(&mut out, field(0x94), path_at)?;
pointer(&mut out, field(0x9c), last_at)?;
match (lod_size, &lod.bone_masks, &lod.bone_map) {
(LOD_MASKS, Some(_), _) => pointer(&mut out, field(0xb0), nth(&tables_at, l, "bone table")?)?,
(LOD_MASKS, None, _) => put(&mut out, field(0xb0), &[0; 8])?,
(LOD_MAP, _, Some(map)) => {
put(&mut out, field(0xb0), &u32_of(map.len(), "mapped bones")?)?;
pointer(&mut out, field(0xb4), nth(&tables_at, l, "bone table")?)?;
}
(LOD_MAP, _, None) => put(&mut out, field(0xb0), &[0; 12])?,
_ => {}
}
for (s, sec) in lod.sections.iter().enumerate() {
let o = nth(nth_row(&sec_at, l)?, s, "section record")?;
let field = |k: usize| plus(o, k);
pointer(&mut out, field(8), nth(&names_at, s_i, "section name")?)?;
if sec.bones.is_empty() {
put(&mut out, field(0x10), &[0; 8])?;
} else {
pointer(&mut out, field(0x10), nth(&bones_at, s_i, "bone list")?)?;
}
put(&mut out, field(0x18), &u16_of(sec.bones.len(), o, "bones")?)?;
put(&mut out, field(0x1b), &[sec.flags])?;
put(&mut out, field(0x1e), &[sec.stride])?;
put(&mut out, field(0x20), &sec.primitives.to_le_bytes())?;
put(&mut out, field(0x24), &sec.start_index.to_le_bytes())?;
put(&mut out, field(0x140), &sec.start_index.to_le_bytes())?;
put(&mut out, field(0x28), &sec.vertex_offset.to_le_bytes())?;
put(&mut out, field(0x54), &sec.vertex_offset.to_le_bytes())?;
put(&mut out, field(0x2c), &sec.vertices.to_le_bytes())?;
put(&mut out, field(DECL_AT), &sec.decl.bytes)?;
put(&mut out, field(DECL2_AT), &sec.draw_decl.bytes)?;
put(&mut out, field(KEY_AT), &sec.key.to_le_bytes())?;
s_i = s_i.saturating_add(1);
}
}
for l in 0..MAX_LODS {
let field = crate::at(0x30, l, 8);
match lod_at.get(l) {
Some(&at) => pointer(&mut out, field, at)?,
None => put(&mut out, field, &[0; 8])?,
}
}
put(&mut out, 0xb4, &u16_of(m.lods.len(), 0xb4, "LODs")?)?;
pointer(&mut out, 0x68, name_at)?;
pointer(&mut out, 0x70, short_at)?;
if hs == HEADER_BONES {
let bones = usize::from(Rd::new(&out, W).u16le(0xc4)?);
let bounded = m.bone_ids.as_ref().map_or(0, Vec::len);
let bounds_for = if m.bone_ids.is_some() { bounded } else { bones };
if m.bone_bounds.as_ref().is_some_and(|b| b.len() != bounds_for) {
return Err(bad(
W,
0xd0,
format!("bone bounds for other than {bounds_for} bones"),
));
}
put(&mut out, 0xc6, &u16_of(bounded, 0xc6, "bounded bones")?)?;
match ids_at {
Some(at) => pointer(&mut out, 0xc8, at)?,
None => put(&mut out, 0xc8, &[0; 8])?,
}
match bounds_at {
Some(at) => pointer(&mut out, 0xd0, at)?,
None => put(&mut out, 0xd0, &[0; 8])?,
}
}
let table = out.len();
for f in pointer_fields(m, &lod_at, &sec_at) {
out.extend(u32_of(f.saturating_sub(16), "bytes")?);
}
let size = out.len().saturating_sub(table);
pad(&mut out, 16);
out.extend(&m.tail);
let mut meta = [0u8; 16];
put(&mut meta, 0, &u32_of(table, "bytes")?)?;
put(&mut meta, 4, &u32_of(size, "bytes")?)?;
put(&mut meta, 8, &u32_of(m.tail.len(), "bytes")?)?;
Ok((out, meta))
}
fn nth_row(rows: &[Vec<usize>], l: usize) -> Result<&[usize]> {
rows.get(l)
.map(Vec::as_slice)
.ok_or_else(|| bad(W, l, format!("no section row {l} in the layout")))
}