Skip to main content

qualia_core_db/render/
material_compile.rs

1//! Cold-path material/submesh compilation over the canonical `.10d` geometry compiler.
2
3use crate::container_10d::provenance_section::ProvenanceSidecar;
4use crate::container_10d::{
5    attach_material_section, attach_texture_coordinate_section, read_material_section_into,
6    MaterialContainerError, MaterialRecord, SubmeshRange, TextureCoordinateContainerError,
7};
8use crate::q_hash;
9use crate::render::assets::Mesh;
10use crate::render::compile_10d::{
11    compile_mesh_to_10d_with_extras_and_frames, Compile10dError, Compile10dExtras,
12};
13use crate::tensor::Tensor10D;
14
15#[derive(Debug, PartialEq, Eq)]
16pub enum MaterialCompileError {
17    Geometry(Compile10dError),
18    Materials(MaterialContainerError),
19    TextureCoordinates(TextureCoordinateContainerError),
20    IndexCountOverflow,
21    MaterialIdentityCollision,
22}
23
24/// Scope source-local imported material IDs to a stable asset URI and remap primitive ranges.
25/// This is cold-path construction; deterministic IDs keep separately compiled assets isolated.
26pub fn scope_material_bindings(
27    asset_uri: &str,
28    materials: &[MaterialRecord],
29    ranges: &[SubmeshRange],
30) -> Result<(Vec<MaterialRecord>, Vec<SubmeshRange>), MaterialCompileError> {
31    let mut scoped = Vec::with_capacity(materials.len());
32    for source in materials {
33        let key = format!("urn:qualia:material:{asset_uri}:{}", source.id);
34        let mut material = *source;
35        material.id = q_hash(&key);
36        if material.id == 0 {
37            material.id = q_hash(&format!("{key}:nonzero"));
38        }
39        scoped.push(material);
40    }
41    scoped.sort_by_key(|material| material.id);
42    if scoped.windows(2).any(|pair| pair[0].id == pair[1].id) {
43        return Err(MaterialCompileError::MaterialIdentityCollision);
44    }
45    let mut remapped = Vec::with_capacity(ranges.len());
46    for range in ranges {
47        let source = materials
48            .iter()
49            .find(|material| material.id == range.material_id)
50            .ok_or(MaterialCompileError::MaterialIdentityCollision)?;
51        let key = format!("urn:qualia:material:{asset_uri}:{}", source.id);
52        let mut scoped_id = q_hash(&key);
53        if scoped_id == 0 {
54            scoped_id = q_hash(&format!("{key}:nonzero"));
55        }
56        remapped.push(SubmeshRange {
57            material_id: scoped_id,
58            ..*range
59        });
60    }
61    Ok((scoped, remapped))
62}
63
64impl From<Compile10dError> for MaterialCompileError {
65    fn from(value: Compile10dError) -> Self {
66        Self::Geometry(value)
67    }
68}
69impl From<MaterialContainerError> for MaterialCompileError {
70    fn from(value: MaterialContainerError) -> Self {
71        Self::Materials(value)
72    }
73}
74impl From<TextureCoordinateContainerError> for MaterialCompileError {
75    fn from(value: TextureCoordinateContainerError) -> Self {
76        Self::TextureCoordinates(value)
77    }
78}
79
80/// Compile geometry and its optional streams, then attach validated material and submesh data.
81/// The output is a sealed `.10d` container; old static assets continue to use their implicit
82/// `MaterialRecord::legacy_default()` when no MAT1 section is present.
83pub fn compile_mesh_with_materials(
84    mesh: &Mesh,
85    nodes: &[Tensor10D],
86    provenance: Option<&ProvenanceSidecar>,
87    extras: Compile10dExtras,
88    surface_reading: Option<&[[f32; 4]]>,
89    normals: Option<&[[f32; 3]]>,
90    tangents: Option<&[[f32; 4]]>,
91    materials: &[MaterialRecord],
92    ranges: &[SubmeshRange],
93) -> Result<Vec<u8>, MaterialCompileError> {
94    let geometry = compile_mesh_to_10d_with_extras_and_frames(
95        mesh,
96        nodes,
97        provenance,
98        extras,
99        surface_reading,
100        normals,
101        tangents,
102    )?;
103    let mesh_index_count = u32::try_from(mesh.triangle_count().saturating_mul(3))
104        .map_err(|_| MaterialCompileError::IndexCountOverflow)?;
105    Ok(attach_material_section(
106        &geometry,
107        materials,
108        ranges,
109        mesh_index_count,
110    )?)
111}
112
113/// Convenience compile for a static mesh with material/submesh data and legacy defaults for all
114/// other optional streams.
115pub fn compile_mesh_to_10d_with_materials(
116    mesh: &Mesh,
117    materials: &[MaterialRecord],
118    ranges: &[SubmeshRange],
119) -> Result<Vec<u8>, MaterialCompileError> {
120    compile_mesh_with_materials(
121        mesh,
122        &[],
123        None,
124        Compile10dExtras::default(),
125        None,
126        None,
127        None,
128        materials,
129        ranges,
130    )
131}
132
133/// Seal a PBR mesh: MAT4 materials plus optional UV01 and SurfaceReading.
134/// Texture payloads stay encoded in HMC/deps; bind them with `pack_pbr_set`.
135pub fn compile_10d_pbr(
136    mesh: &Mesh,
137    materials: &[MaterialRecord],
138    ranges: &[SubmeshRange],
139    uv0: Option<&[[f32; 2]]>,
140    surface_reading: Option<&[[f32; 4]]>,
141) -> Result<Vec<u8>, MaterialCompileError> {
142    let mut bytes = compile_mesh_with_materials(
143        mesh,
144        &[],
145        None,
146        Compile10dExtras::default(),
147        surface_reading,
148        None,
149        None,
150        materials,
151        ranges,
152    )?;
153    if let Some(uv) = uv0 {
154        bytes = attach_texture_coordinate_section(&bytes, uv)?;
155    }
156    Ok(bytes)
157}
158
159/// Read the material records and submesh ranges from a compiled mesh container.
160pub fn decode_10d_materials_into(
161    container: &[u8],
162    mesh_index_count: u32,
163    materials_out: &mut [MaterialRecord],
164    ranges_out: &mut [SubmeshRange],
165) -> Result<(usize, usize), MaterialCompileError> {
166    Ok(read_material_section_into(
167        container,
168        mesh_index_count,
169        materials_out,
170        ranges_out,
171    )?)
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::render::assets::import_asset;
178
179    #[test]
180    fn material_compile_round_trips_mesh_and_stable_submesh_bindings() {
181        let mesh = import_asset(b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n", Some("obj")).unwrap();
182        let material = MaterialRecord::legacy_default();
183        let ranges = [SubmeshRange {
184            first_index: 0,
185            index_count: 3,
186            material_id: material.id,
187            semantic_id: 0xabc,
188        }];
189        let bytes = compile_mesh_to_10d_with_materials(&mesh, &[material], &ranges).unwrap();
190        let decoded_mesh = crate::render::compile_10d::decode_10d_mesh(&bytes).unwrap();
191        assert_eq!(decoded_mesh.triangle_count(), 1);
192
193        let mut materials_out = [MaterialRecord::legacy_default(); 1];
194        let mut ranges_out = [ranges[0]; 1];
195        assert_eq!(
196            decode_10d_materials_into(&bytes, 3, &mut materials_out, &mut ranges_out),
197            Ok((1, 1))
198        );
199        assert_eq!(materials_out, [material]);
200        assert_eq!(ranges_out, ranges);
201
202        let mut corrupted = bytes.clone();
203        let last = corrupted.len() - 1;
204        corrupted[last] ^= 1;
205        assert!(matches!(
206            decode_10d_materials_into(&corrupted, 3, &mut materials_out, &mut ranges_out),
207            Err(MaterialCompileError::Materials(
208                MaterialContainerError::Integrity(_)
209            ))
210        ));
211    }
212}