Skip to main content

qualia_core_db/container_10d/
skeletal_container.rs

1//! Caller-buffered SKL1 / SKL2 attachment and integrity-checked readback.
2use super::header::{Container10dHeader, HeaderParseError, MAX_SECTION_COUNT};
3use super::integrity::{compute_whole_file_crc32c, seal_whole_file_crc32c};
4use super::mesh_section::{parse_mesh_header, MeshSectionError};
5use super::section::{
6    encode_container, parse_section_table, AlignmentTier, SectionInput, SectionTableError,
7    SectionType,
8};
9use super::skeletal_section::{
10    SkeletalSection, SkeletalSectionError, SkeletalSectionPayload, SKL2_MAGIC,
11};
12
13#[derive(Debug, PartialEq, Eq)]
14pub enum SkeletalContainerError {
15    Header(HeaderParseError),
16    Sections(SectionTableError),
17    Mesh(MeshSectionError),
18    Payload(SkeletalSectionError),
19    Integrity,
20    AlreadyPresent,
21    MissingMesh,
22    Missing,
23    TooManySections,
24    CountLimit,
25    InvalidDescriptor,
26}
27
28fn checked_header(bytes: &[u8]) -> Result<Container10dHeader, SkeletalContainerError> {
29    if bytes.len() > 42 * 1024 * 1024 {
30        return Err(SkeletalContainerError::CountLimit);
31    }
32    let header = Container10dHeader::parse(bytes).map_err(SkeletalContainerError::Header)?;
33    if compute_whole_file_crc32c(bytes) != header.header_crc32c {
34        return Err(SkeletalContainerError::Integrity);
35    }
36    Ok(header)
37}
38
39/// Parsed skeletal animation payload stored inside `SectionType::SkeletalAnimation`.
40pub enum ContainerSkeletalSection<'a> {
41    Skl1(SkeletalSection<'a>),
42    Skl2(SkeletalSectionPayload),
43}
44
45fn find_skeletal_slice(
46    bytes: &[u8],
47) -> Result<(usize, &[u8]), SkeletalContainerError> {
48    let header = checked_header(bytes)?;
49    let sections = parse_section_table(bytes, &header).map_err(SkeletalContainerError::Sections)?;
50    let mesh = sections
51        .iter()
52        .find(|s| s.typ() == Some(SectionType::QuantizedMesh))
53        .ok_or(SkeletalContainerError::MissingMesh)?;
54    let (mesh_header, _) = parse_mesh_header(
55        &bytes[mesh.byte_offset as usize..(mesh.byte_offset + mesh.byte_length) as usize],
56    )
57    .map_err(SkeletalContainerError::Mesh)?;
58    let section = sections
59        .iter()
60        .find(|s| s.typ() == Some(SectionType::SkeletalAnimation))
61        .ok_or(SkeletalContainerError::Missing)?;
62    if section.stride != 0 || section.element_count != 0 {
63        return Err(SkeletalContainerError::InvalidDescriptor);
64    }
65    let slice =
66        &bytes[section.byte_offset as usize..(section.byte_offset + section.byte_length) as usize];
67    Ok((mesh_header.vertex_count as usize, slice))
68}
69
70/// Read the optional SKL1 section after validating the existing container envelope,
71/// whole-file seal, per-section seals and actual QuantizedMesh vertex count.
72pub fn read_skeletal_section(bytes: &[u8]) -> Result<SkeletalSection<'_>, SkeletalContainerError> {
73    let (vertex_count, slice) = find_skeletal_slice(bytes)?;
74    SkeletalSection::parse(slice, vertex_count).map_err(SkeletalContainerError::Payload)
75}
76
77/// Read an SKL1 or SKL2 section payload from `SectionType::SkeletalAnimation`.
78pub fn read_skeletal_section_payload(
79    bytes: &[u8],
80) -> Result<ContainerSkeletalSection<'_>, SkeletalContainerError> {
81    let (vertex_count, slice) = find_skeletal_slice(bytes)?;
82    if slice.starts_with(&SKL2_MAGIC) {
83        SkeletalSectionPayload::from_bytes(slice)
84            .map(ContainerSkeletalSection::Skl2)
85            .map_err(SkeletalContainerError::Payload)
86    } else {
87        SkeletalSection::parse(slice, vertex_count)
88            .map(ContainerSkeletalSection::Skl1)
89            .map_err(SkeletalContainerError::Payload)
90    }
91}
92
93/// Read an SKL2 payload from `SectionType::SkeletalAnimation`, failing if missing or SKL1-only.
94pub fn read_skl2_section(
95    bytes: &[u8],
96) -> Result<SkeletalSectionPayload, SkeletalContainerError> {
97    let (_vertex_count, slice) = find_skeletal_slice(bytes)?;
98    SkeletalSectionPayload::from_bytes(slice).map_err(SkeletalContainerError::Payload)
99}
100
101/// Attach an already encoded SKL1 or SKL2 payload to a sealed container, retaining all
102/// existing fields. Output remains untouched on validation or capacity failure.
103/// The section writer reports the required capacity in its structured error.
104pub fn attach_skeletal_section_into(
105    bytes: &[u8],
106    payload: &[u8],
107    out: &mut [u8],
108) -> Result<usize, SkeletalContainerError> {
109    let header = checked_header(bytes)?;
110    let sections = parse_section_table(bytes, &header).map_err(SkeletalContainerError::Sections)?;
111    if sections.len() >= MAX_SECTION_COUNT as usize {
112        return Err(SkeletalContainerError::TooManySections);
113    }
114    if sections
115        .iter()
116        .any(|s| s.typ() == Some(SectionType::SkeletalAnimation))
117    {
118        return Err(SkeletalContainerError::AlreadyPresent);
119    }
120    let mesh = sections
121        .iter()
122        .find(|s| s.typ() == Some(SectionType::QuantizedMesh))
123        .ok_or(SkeletalContainerError::MissingMesh)?;
124    let (mesh_header, _) = parse_mesh_header(
125        &bytes[mesh.byte_offset as usize..(mesh.byte_offset + mesh.byte_length) as usize],
126    )
127    .map_err(SkeletalContainerError::Mesh)?;
128    if payload.starts_with(&SKL2_MAGIC) {
129        SkeletalSectionPayload::from_bytes(payload).map_err(SkeletalContainerError::Payload)?;
130    } else {
131        SkeletalSection::parse(payload, mesh_header.vertex_count as usize)
132            .map_err(SkeletalContainerError::Payload)?;
133    }
134    let empty = SectionInput {
135        section_type: SectionType::Undefined,
136        alignment_tier: AlignmentTier::Byte,
137        stride: 0,
138        element_count: 0,
139        payload: &[],
140    };
141    let mut inputs = [empty; MAX_SECTION_COUNT as usize];
142    for (i, section) in sections.iter().enumerate() {
143        inputs[i] = SectionInput {
144            section_type: section
145                .typ()
146                .ok_or(SkeletalContainerError::InvalidDescriptor)?,
147            alignment_tier: section
148                .tier()
149                .ok_or(SkeletalContainerError::InvalidDescriptor)?,
150            stride: section.stride,
151            element_count: section.element_count,
152            payload: &bytes[section.byte_offset as usize
153                ..(section.byte_offset + section.byte_length) as usize],
154        };
155    }
156    inputs[sections.len()] = SectionInput {
157        section_type: SectionType::SkeletalAnimation,
158        alignment_tier: AlignmentTier::Word,
159        stride: 0,
160        element_count: 0,
161        payload,
162    };
163    // Admission before writes also enforces the enclosing execution budget.
164    let needed = match encode_container(&header, &inputs[..sections.len() + 1], &mut []) {
165        Err(SectionTableError::OutputBufferTooSmall { needed, .. }) => needed,
166        Err(error) => return Err(SkeletalContainerError::Sections(error)),
167        Ok(needed) => needed,
168    };
169    if needed > 42 * 1024 * 1024 {
170        return Err(SkeletalContainerError::CountLimit);
171    }
172    let written = encode_container(&header, &inputs[..sections.len() + 1], out)
173        .map_err(SkeletalContainerError::Sections)?;
174    seal_whole_file_crc32c(&mut out[..written]);
175    Ok(written)
176}
177
178/// Encode an `SKL2` payload into caller-supplied workspace and attach it to a sealed `.10d`
179/// container without extra heap allocation on the hot path.
180pub fn attach_skl2_section_into(
181    bytes: &[u8],
182    payload: &SkeletalSectionPayload,
183    scratch: &mut [u8],
184    out: &mut [u8],
185) -> Result<usize, SkeletalContainerError> {
186    let written = payload
187        .encode_v2_into(scratch)
188        .map_err(SkeletalContainerError::Payload)?;
189    attach_skeletal_section_into(bytes, &scratch[..written], out)
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate::container_10d::skeletal_section::{
196        KinematicSolverRegime, Skl2JointDescriptorV2, SwingTwistConeLimits, SKL2_NONE_INDEX,
197        SKL2_VERSION_1, SKL2_VERSION_2,
198    };
199    use crate::render::assets::Mesh;
200    use crate::render::compile_10d::{compile_mesh_to_10d_with_nodes, decode_10d_mesh};
201
202    fn sample_mesh_container() -> Vec<u8> {
203        let mesh = Mesh {
204            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
205            triangles: vec![[0, 1, 2]],
206            min: [0.0; 3],
207            max: [1.0, 1.0, 0.0],
208        };
209        compile_mesh_to_10d_with_nodes(&mesh, &[]).unwrap()
210    }
211
212    fn sample_skl2() -> SkeletalSectionPayload {
213        SkeletalSectionPayload::new(vec![
214            Skl2JointDescriptorV2::new(
215                101,
216                SKL2_NONE_INDEX,
217                SwingTwistConeLimits::symmetric(0.4, 0.25),
218                KinematicSolverRegime::ArticulatedRigidBodyDca,
219                1180.0,
220                0.35,
221                0.30,
222                14.0,
223                0,
224                1,
225                250,
226            ),
227            Skl2JointDescriptorV2::new(
228                102,
229                0,
230                SwingTwistConeLimits::new(0.7, 0.5, -0.3, 0.3),
231                KinematicSolverRegime::CosseratRodContinuum,
232                920.0,
233                0.24,
234                0.22,
235                3.1,
236                1,
237                2,
238                215,
239            ),
240        ])
241    }
242
243    #[test]
244    fn attach_and_readback_skl2_v2_preserves_mesh_and_descriptors() {
245        let original = sample_mesh_container();
246        let skl2 = sample_skl2();
247        let mut scratch = [0u8; 512];
248        let mut output = [0u8; 8192];
249        let len = attach_skl2_section_into(&original, &skl2, &mut scratch, &mut output).unwrap();
250
251        match read_skeletal_section_payload(&output[..len]).unwrap() {
252            ContainerSkeletalSection::Skl2(decoded) => {
253                assert_eq!(decoded.source_version, SKL2_VERSION_2);
254                assert_eq!(decoded.joints, skl2.joints);
255            }
256            ContainerSkeletalSection::Skl1(_) => panic!("expected SKL2 payload"),
257        }
258
259        let direct = read_skl2_section(&output[..len]).unwrap();
260        assert_eq!(direct.joints, skl2.joints);
261
262        // SKL1 strict parser must reject SKL2 magic cleanly.
263        assert!(matches!(
264            read_skeletal_section(&output[..len]),
265            Err(SkeletalContainerError::Payload(SkeletalSectionError::Header))
266        ));
267
268        // Existing mesh remains intact.
269        assert_eq!(decode_10d_mesh(&output[..len]).unwrap().triangles, vec![[0, 1, 2]]);
270    }
271
272    #[test]
273    fn attach_skl2_v1_upgrades_on_readback() {
274        let original = sample_mesh_container();
275        let skl2 = sample_skl2();
276        let v1_bytes = skl2.to_bytes_v1().unwrap();
277        let mut output = [0u8; 8192];
278        let len = attach_skeletal_section_into(&original, &v1_bytes, &mut output).unwrap();
279
280        let decoded = read_skl2_section(&output[..len]).unwrap();
281        assert_eq!(decoded.source_version, SKL2_VERSION_1);
282        assert_eq!(decoded.joints.len(), 2);
283        assert_eq!(decoded.joints[1].parent_index, 0);
284        assert_eq!(decoded.joints[1].swing_twist, skl2.joints[1].swing_twist);
285    }
286
287    #[test]
288    fn skl2_container_corruption_fails_closed() {
289        let original = sample_mesh_container();
290        let skl2 = sample_skl2();
291        let mut scratch = [0u8; 512];
292        let mut output = [0u8; 8192];
293        let len = attach_skl2_section_into(&original, &skl2, &mut scratch, &mut output).unwrap();
294
295        output[len - 1] ^= 0x01;
296        assert!(matches!(
297            read_skl2_section(&output[..len]),
298            Err(SkeletalContainerError::Integrity)
299        ));
300    }
301}