Skip to main content

qualia_core_db/container_10d/
material_container.rs

1//! Container-level attach/read helpers for the optional MAT1 section.
2
3use super::header::{Container10dHeader, HeaderParseError};
4use super::integrity::{compute_whole_file_crc32c, seal_whole_file_crc32c, IntegrityError};
5use super::material_section::{
6    decode_material_section_into, encode_material_section, material_section_counts, MaterialRecord,
7    MaterialSectionError, SubmeshRange,
8};
9use super::section::{
10    encode_container, parse_section_table, AlignmentTier, SectionInput, SectionTableError,
11    SectionType,
12};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum MaterialContainerError {
16    Header(HeaderParseError),
17    Integrity(IntegrityError),
18    Section(SectionTableError),
19    Material(MaterialSectionError),
20    AlreadyPresent,
21    Missing,
22    TooManySections,
23}
24
25impl From<HeaderParseError> for MaterialContainerError {
26    fn from(value: HeaderParseError) -> Self {
27        Self::Header(value)
28    }
29}
30impl From<IntegrityError> for MaterialContainerError {
31    fn from(value: IntegrityError) -> Self {
32        Self::Integrity(value)
33    }
34}
35impl From<SectionTableError> for MaterialContainerError {
36    fn from(value: SectionTableError) -> Self {
37        Self::Section(value)
38    }
39}
40impl From<MaterialSectionError> for MaterialContainerError {
41    fn from(value: MaterialSectionError) -> Self {
42        Self::Material(value)
43    }
44}
45
46/// Add MAT1 to an already sealed container, preserving its existing sections and resealing CRC.
47pub fn attach_material_section(
48    container: &[u8],
49    materials: &[MaterialRecord],
50    ranges: &[SubmeshRange],
51    mesh_index_count: u32,
52) -> Result<Vec<u8>, MaterialContainerError> {
53    let header = Container10dHeader::parse(container)?;
54    verify_integrity(container, header.header_crc32c)?;
55    let descriptors = parse_section_table(container, &header)?;
56    if descriptors
57        .iter()
58        .any(|d| d.typ() == Some(SectionType::Materials))
59    {
60        return Err(MaterialContainerError::AlreadyPresent);
61    }
62    if descriptors.len() >= crate::container_10d::header::MAX_SECTION_COUNT as usize {
63        return Err(MaterialContainerError::TooManySections);
64    }
65
66    let material_len = super::material_section::encoded_len(materials.len(), ranges.len())
67        .ok_or(MaterialSectionError::CountLimit)?;
68    let mut material_bytes = vec![0u8; material_len];
69    let written =
70        encode_material_section(materials, ranges, mesh_index_count, &mut material_bytes)?;
71    material_bytes.truncate(written);
72
73    // Construction is cold and bounded by the section-count and material-count limits.
74    let mut inputs = Vec::with_capacity(descriptors.len() + 1);
75    for descriptor in descriptors {
76        let start = descriptor.byte_offset as usize;
77        let end = start
78            .checked_add(descriptor.byte_length as usize)
79            .filter(|&end| end <= container.len())
80            .ok_or(SectionTableError::OutOfBounds {
81                index: 0,
82                offset: descriptor.byte_offset,
83                length: descriptor.byte_length,
84                file_len: container.len(),
85            })?;
86        inputs.push(SectionInput {
87            section_type: descriptor
88                .typ()
89                .ok_or(SectionTableError::UndefinedSectionType {
90                    index: 0,
91                    got: descriptor.section_type,
92                })?,
93            alignment_tier: descriptor
94                .tier()
95                .ok_or(SectionTableError::UndefinedAlignmentTier {
96                    index: 0,
97                    got: descriptor.alignment_tier,
98                })?,
99            stride: descriptor.stride,
100            element_count: descriptor.element_count,
101            payload: &container[start..end],
102        });
103    }
104    inputs.push(SectionInput {
105        section_type: SectionType::Materials,
106        alignment_tier: AlignmentTier::CacheLine,
107        stride: 0,
108        element_count: 0,
109        payload: &material_bytes,
110    });
111
112    let needed = match encode_container(&header, &inputs, &mut []) {
113        Err(SectionTableError::OutputBufferTooSmall { needed, .. }) => needed,
114        Ok(size) => size,
115        Err(error) => return Err(error.into()),
116    };
117    let mut output = vec![0u8; needed];
118    let written = encode_container(&header, &inputs, &mut output)?;
119    output.truncate(written);
120    seal_whole_file_crc32c(&mut output);
121    Ok(output)
122}
123
124/// Read MAT1 into caller-owned buffers after validating the enclosing container and mesh ranges.
125pub fn read_material_section_into(
126    container: &[u8],
127    mesh_index_count: u32,
128    materials_out: &mut [MaterialRecord],
129    ranges_out: &mut [SubmeshRange],
130) -> Result<(usize, usize), MaterialContainerError> {
131    let header = Container10dHeader::parse(container)?;
132    verify_integrity(container, header.header_crc32c)?;
133    let descriptors = parse_section_table(container, &header)?;
134    let descriptor = descriptors
135        .iter()
136        .find(|d| d.typ() == Some(SectionType::Materials))
137        .ok_or(MaterialContainerError::Missing)?;
138    let start = descriptor.byte_offset as usize;
139    let end = start
140        .checked_add(descriptor.byte_length as usize)
141        .filter(|&end| end <= container.len())
142        .ok_or(SectionTableError::OutOfBounds {
143            index: 0,
144            offset: descriptor.byte_offset,
145            length: descriptor.byte_length,
146            file_len: container.len(),
147        })?;
148    Ok(decode_material_section_into(
149        &container[start..end],
150        mesh_index_count,
151        materials_out,
152        ranges_out,
153    )?)
154}
155
156/// Validate the sealed container and MAT1 header, then return bounded material/range counts.
157pub fn material_container_counts(
158    container: &[u8],
159) -> Result<(usize, usize), MaterialContainerError> {
160    let header = Container10dHeader::parse(container)?;
161    verify_integrity(container, header.header_crc32c)?;
162    let descriptors = parse_section_table(container, &header)?;
163    let descriptor = descriptors
164        .iter()
165        .find(|d| d.typ() == Some(SectionType::Materials))
166        .ok_or(MaterialContainerError::Missing)?;
167    let start = descriptor.byte_offset as usize;
168    let end = start
169        .checked_add(descriptor.byte_length as usize)
170        .filter(|&end| end <= container.len())
171        .ok_or(SectionTableError::OutOfBounds {
172            index: 0,
173            offset: descriptor.byte_offset,
174            length: descriptor.byte_length,
175            file_len: container.len(),
176        })?;
177    Ok(material_section_counts(&container[start..end])?)
178}
179
180fn verify_integrity(container: &[u8], expected: u32) -> Result<(), IntegrityError> {
181    let actual = compute_whole_file_crc32c(container);
182    if actual == expected {
183        Ok(())
184    } else {
185        Err(IntegrityError::WholeFileCrcMismatch {
186            expected,
187            got: actual,
188        })
189    }
190}