Skip to main content

qualia_core_db/container_10d/
material_section.rs

1//! Versioned `.10d` material and submesh sidecar.
2//!
3//! MAT4 stores the MAT3 material contract plus an explicit foliage-wind flag;
4//! readers remain compatible with MAT1, MAT2 and MAT3. Texture payloads remain in HMC/asset dependencies.
5//! Materials and submesh ranges are cold-path data encoded with caller buffers and bounded counts.
6
7pub const MATERIAL_SECTION_VERSION: u16 = 4;
8pub const MATERIAL_SECTION_HEADER_SIZE: usize = 24;
9pub const MATERIAL_RECORD_SIZE: usize = 464;
10pub const PREVIOUS_MATERIAL_RECORD_SIZE: usize = 448;
11pub const MATERIAL_V1_RECORD_SIZE: usize = 256;
12pub const SUBMESH_RANGE_SIZE: usize = 24;
13pub const MAX_MATERIALS: usize = 4096;
14pub const MAX_SUBMESH_RANGES: usize = 1_048_576;
15pub const MAX_EMISSIVE_FACTOR: f32 = 65_504.0;
16pub const TEXTURE_SAMPLER_RECORD_SIZE: usize = 8;
17pub(super) const MAGIC: [u8; 4] = *b"MAT4";
18pub(super) const PREVIOUS_MAGIC: [u8; 4] = *b"MAT3";
19pub(super) const PREVIOUS_VERSION: u16 = 3;
20pub(super) const PREVIOUS_PREVIOUS_MAGIC: [u8; 4] = *b"MAT2";
21pub(super) const PREVIOUS_PREVIOUS_VERSION: u16 = 2;
22pub(super) const LEGACY_MAGIC: [u8; 4] = *b"MAT1";
23pub(super) const LEGACY_VERSION: u16 = 1;
24const FLAG_DOUBLE_SIDED: u16 = 1 << 0;
25const FLAG_CASTS_SHADOW: u16 = 1 << 1;
26const FLAG_RECEIVES_SHADOW: u16 = 1 << 2;
27const FLAG_PICKABLE: u16 = 1 << 3;
28const FLAG_VERTEX_COLOR_MULTIPLY: u16 = 1 << 4;
29const KNOWN_FLAGS: u16 = FLAG_DOUBLE_SIDED
30    | FLAG_CASTS_SHADOW
31    | FLAG_RECEIVES_SHADOW
32    | FLAG_PICKABLE
33    | FLAG_VERTEX_COLOR_MULTIPLY;
34
35/// Material shading model. Stylized shading uses the same material and resource contract.
36#[repr(u8)]
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum ShadingModel {
39    MetallicRoughness = 0,
40    Stylized = 1,
41}
42
43impl ShadingModel {
44    fn from_raw(value: u8) -> Option<Self> {
45        match value {
46            0 => Some(Self::MetallicRoughness),
47            1 => Some(Self::Stylized),
48            _ => None,
49        }
50    }
51}
52
53/// How alpha affects coverage and blending.
54#[repr(u8)]
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum OpacityMode {
57    Opaque = 0,
58    Mask = 1,
59    Blend = 2,
60}
61
62/// glTF-compatible UV transform. `tex_coord` selects the source vertex set; current runtime supports
63/// set zero and rejects other sets until their vertex streams are present end-to-end.
64#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct TextureTransform {
66    pub offset: [f32; 2],
67    pub scale: [f32; 2],
68    pub rotation: f32,
69    pub tex_coord: u32,
70}
71
72/// glTF-compatible texture address mode.
73#[repr(u8)]
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub enum TextureAddressMode {
76    ClampToEdge = 0,
77    MirroredRepeat = 1,
78    Repeat = 2,
79}
80
81/// Magnification filter. glTF permits nearest or linear.
82#[repr(u8)]
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub enum TextureFilterMode {
85    Nearest = 0,
86    Linear = 1,
87}
88
89/// Minification filter including its mip selection policy.
90#[repr(u8)]
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub enum TextureMinFilter {
93    Nearest = 0,
94    Linear = 1,
95    NearestMipmapNearest = 2,
96    LinearMipmapNearest = 3,
97    NearestMipmapLinear = 4,
98    LinearMipmapLinear = 5,
99}
100
101/// Per-map sampler state. Defaults follow glTF: repeat, linear magnification and trilinear minification.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103pub struct TextureSampler {
104    pub wrap_s: TextureAddressMode,
105    pub wrap_t: TextureAddressMode,
106    pub mag_filter: TextureFilterMode,
107    pub min_filter: TextureMinFilter,
108}
109
110impl TextureSampler {
111    pub const GLTF_DEFAULT: Self = Self {
112        wrap_s: TextureAddressMode::Repeat,
113        wrap_t: TextureAddressMode::Repeat,
114        mag_filter: TextureFilterMode::Linear,
115        min_filter: TextureMinFilter::LinearMipmapLinear,
116    };
117
118    /// Stable index into the bounded 3×3×2×6 WebGPU sampler cache.
119    pub const fn cache_index(self) -> usize {
120        (((self.wrap_s as usize * 3 + self.wrap_t as usize) * 2 + self.mag_filter as usize) * 6)
121            + self.min_filter as usize
122    }
123
124    /// True when any filtering stage is non-nearest (requires a filtered
125    /// sampler rather than a point-sampling one).
126    pub const fn needs_filtering(self) -> bool {
127        matches!(self.mag_filter, TextureFilterMode::Linear)
128            || matches!(
129                self.min_filter,
130                TextureMinFilter::Linear
131                    | TextureMinFilter::LinearMipmapNearest
132                    | TextureMinFilter::NearestMipmapLinear
133                    | TextureMinFilter::LinearMipmapLinear
134            )
135    }
136
137    /// Copy with mag/min filters forced to nearest (point sampling);
138    /// wrap modes are preserved.
139    pub const fn nearest_variant(self) -> Self {
140        Self {
141            mag_filter: TextureFilterMode::Nearest,
142            min_filter: TextureMinFilter::NearestMipmapNearest,
143            ..self
144        }
145    }
146
147    /// Copy with mag/min filters forced to linear + trilinear mipmapping;
148    /// wrap modes are preserved.
149    pub const fn filtering_variant(self) -> Self {
150        Self {
151            mag_filter: TextureFilterMode::Linear,
152            min_filter: TextureMinFilter::LinearMipmapLinear,
153            ..self
154        }
155    }
156}
157
158impl TextureTransform {
159    pub const IDENTITY: Self = Self {
160        offset: [0.0; 2],
161        scale: [1.0; 2],
162        rotation: 0.0,
163        tex_coord: 0,
164    };
165}
166
167impl OpacityMode {
168    fn from_raw(value: u8) -> Option<Self> {
169        match value {
170            0 => Some(Self::Opaque),
171            1 => Some(Self::Mask),
172            2 => Some(Self::Blend),
173            _ => None,
174        }
175    }
176}
177
178/// Stable, renderer-independent material record. Colours are linear; each texture field is a
179/// SHA-256 HMC/resource digest, or all-zero when that slot is unbound.
180#[derive(Debug, Clone, Copy, PartialEq)]
181pub struct MaterialRecord {
182    pub id: u64,
183    pub shading_model: ShadingModel,
184    pub opacity_mode: OpacityMode,
185    pub double_sided: bool,
186    pub casts_shadow: bool,
187    pub receives_shadow: bool,
188    pub pickable: bool,
189    pub multiply_vertex_color: bool,
190    /// Enables the renderer's restrained, time-based vertex wind response.
191    pub wind_animated: bool,
192    pub base_color: [f32; 4],
193    pub emissive: [f32; 3],
194    pub metallic: f32,
195    pub roughness: f32,
196    pub specular: f32,
197    pub normal_scale: f32,
198    pub occlusion_strength: f32,
199    pub alpha_cutoff: f32,
200    pub base_color_texture: [u8; 32],
201    pub normal_texture: [u8; 32],
202    /// glTF metallic-roughness texture dependency.
203    pub metallic_roughness_texture: [u8; 32],
204    /// glTF occlusion texture dependency; may differ from metallic-roughness.
205    pub occlusion_texture: [u8; 32],
206    pub emissive_texture: [u8; 32],
207    /// Optional authored toon-ramp dependency; used only by `Stylized` materials.
208    pub stylized_ramp_texture: [u8; 32],
209    /// Base colour, normal, metallic-roughness, occlusion, emissive, stylized ramp.
210    pub texture_transforms: [TextureTransform; 6],
211    /// Base colour, normal, metallic-roughness, occlusion, emissive, stylized ramp.
212    pub texture_samplers: [TextureSampler; 6],
213}
214
215impl MaterialRecord {
216    /// Compatibility material for legacy static meshes without a material section.
217    pub const fn legacy_default() -> Self {
218        Self {
219            id: crate::q_hash("urn:qualia:material:legacy-default"),
220            shading_model: ShadingModel::MetallicRoughness,
221            opacity_mode: OpacityMode::Opaque,
222            double_sided: false,
223            casts_shadow: true,
224            receives_shadow: true,
225            pickable: true,
226            multiply_vertex_color: true,
227            wind_animated: false,
228            base_color: [1.0, 1.0, 1.0, 1.0],
229            emissive: [0.0, 0.0, 0.0],
230            metallic: 0.0,
231            roughness: 1.0,
232            specular: 1.0,
233            normal_scale: 1.0,
234            occlusion_strength: 1.0,
235            alpha_cutoff: 0.5,
236            base_color_texture: [0; 32],
237            normal_texture: [0; 32],
238            metallic_roughness_texture: [0; 32],
239            occlusion_texture: [0; 32],
240            emissive_texture: [0; 32],
241            stylized_ramp_texture: [0; 32],
242            texture_transforms: [TextureTransform::IDENTITY; 6],
243            texture_samplers: [TextureSampler::GLTF_DEFAULT; 6],
244        }
245    }
246}
247
248/// A contiguous triangle-index interval bound to one stable material identity.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub struct SubmeshRange {
251    pub first_index: u32,
252    pub index_count: u32,
253    pub material_id: u64,
254    /// Optional stable semantic entity hash; zero means no per-submesh identity.
255    pub semantic_id: u64,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub enum MaterialSectionError {
260    Empty,
261    CountLimit,
262    SizeOverflow,
263    OutputTooSmall { needed: usize, got: usize },
264    Header,
265    Version(u16),
266    Layout,
267    UnknownFlags(u16),
268    InvalidModel(u8),
269    InvalidOpacity(u8),
270    InvalidMaterial { index: usize },
271    MaterialOrder { index: usize },
272    UnknownMaterial { range: usize, id: u64 },
273    InvalidRange { index: usize },
274    RangeOrder { index: usize },
275    PayloadLength { expected: usize, got: usize },
276    OutputCountTooSmall,
277}
278
279impl std::fmt::Display for MaterialSectionError {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        write!(f, ".10d MAT4/MAT3/MAT2/MAT1 material section: {self:?}")
282    }
283}
284
285impl std::error::Error for MaterialSectionError {}
286
287/// Exact encoded size. `None` means an invalid count or arithmetic overflow.
288pub fn encoded_len(material_count: usize, range_count: usize) -> Option<usize> {
289    if material_count == 0
290        || range_count == 0
291        || material_count > MAX_MATERIALS
292        || range_count > MAX_SUBMESH_RANGES
293    {
294        return None;
295    }
296    MATERIAL_SECTION_HEADER_SIZE
297        .checked_add(material_count.checked_mul(MATERIAL_RECORD_SIZE)?)?
298        .checked_add(range_count.checked_mul(SUBMESH_RANGE_SIZE)?)
299}
300
301/// Write the current canonical MAT4 section into a caller-owned output buffer.
302pub fn encode_material_section(
303    materials: &[MaterialRecord],
304    ranges: &[SubmeshRange],
305    mesh_index_count: u32,
306    out: &mut [u8],
307) -> Result<usize, MaterialSectionError> {
308    super::material_section_codec::encode(materials, ranges, mesh_index_count, out)
309}
310
311/// Decode MAT1 through MAT4 into caller-owned arrays. Both outputs must fit the encoded counts.
312pub fn decode_material_section_into(
313    bytes: &[u8],
314    mesh_index_count: u32,
315    materials_out: &mut [MaterialRecord],
316    ranges_out: &mut [SubmeshRange],
317) -> Result<(usize, usize), MaterialSectionError> {
318    super::material_section_codec::decode(bytes, mesh_index_count, materials_out, ranges_out)
319}
320
321/// Inspect validated MAT1–MAT4 layout/counts without allocating output records.
322pub fn material_section_counts(bytes: &[u8]) -> Result<(usize, usize), MaterialSectionError> {
323    super::material_section_codec::counts(bytes)
324}
325
326/// Validate material/range arrays with the exact rules used by MAT4 encoding.
327pub fn validate_material_bindings(
328    materials: &[MaterialRecord],
329    ranges: &[SubmeshRange],
330    mesh_index_count: u32,
331) -> Result<(), MaterialSectionError> {
332    validate_records(materials, ranges, mesh_index_count)
333}
334
335/// Shared record/range validator behind `validate_material_bindings`.
336///
337/// Fails closed on: empty inputs, counts above `MAX_MATERIALS` /
338/// `MAX_SUBMESH_RANGES`, `id == 0` or non-monotonic material ordering,
339/// non-finite or out-of-bounds scalar fields (colour 0–1, emissive
340/// 0–`MAX_EMISSIVE_FACTOR`, normal scale 0–8, etc.), unsupported
341/// `tex_coord` values, and submesh ranges that are non-triangle-aligned,
342/// out of `mesh_index_count`, reference an unknown material, or do not
343/// tile `[0, mesh_index_count)` contiguously in declared order.
344pub(super) fn validate_records(
345    materials: &[MaterialRecord],
346    ranges: &[SubmeshRange],
347    mesh_index_count: u32,
348) -> Result<(), MaterialSectionError> {
349    if materials.is_empty() || ranges.is_empty() {
350        return Err(MaterialSectionError::Empty);
351    }
352    if materials.len() > MAX_MATERIALS || ranges.len() > MAX_SUBMESH_RANGES {
353        return Err(MaterialSectionError::CountLimit);
354    }
355    for (index, material) in materials.iter().enumerate() {
356        let floats = material
357            .base_color
358            .iter()
359            .chain(material.emissive.iter())
360            .copied()
361            .chain([
362                material.metallic,
363                material.roughness,
364                material.specular,
365                material.normal_scale,
366                material.occlusion_strength,
367                material.alpha_cutoff,
368            ]);
369        if material.id == 0
370            || floats.clone().any(|value| !value.is_finite())
371            || material
372                .base_color
373                .iter()
374                .any(|&value| !(0.0..=1.0).contains(&value))
375            || material
376                .emissive
377                .iter()
378                .any(|&value| !(0.0..=MAX_EMISSIVE_FACTOR).contains(&value))
379            || !(0.0..=1.0).contains(&material.metallic)
380            || !(0.0..=1.0).contains(&material.roughness)
381            || !(0.0..=1.0).contains(&material.specular)
382            || !(0.0..=8.0).contains(&material.normal_scale)
383            || !(0.0..=1.0).contains(&material.occlusion_strength)
384            || !(0.0..=1.0).contains(&material.alpha_cutoff)
385            || material.texture_transforms.iter().any(|transform| {
386                transform
387                    .offset
388                    .iter()
389                    .chain(transform.scale.iter())
390                    .chain(std::iter::once(&transform.rotation))
391                    .any(|value| !value.is_finite() || value.abs() > 1_000_000.0)
392                    || transform.tex_coord != 0
393            })
394            || (index > 0 && materials[index - 1].id >= material.id)
395        {
396            return Err(if index > 0 && materials[index - 1].id >= material.id {
397                MaterialSectionError::MaterialOrder { index }
398            } else {
399                MaterialSectionError::InvalidMaterial { index }
400            });
401        }
402    }
403    let mut previous_end = 0u32;
404    for (index, range) in ranges.iter().enumerate() {
405        if materials
406            .binary_search_by_key(&range.material_id, |material| material.id)
407            .is_err()
408        {
409            return Err(MaterialSectionError::UnknownMaterial {
410                range: index,
411                id: range.material_id,
412            });
413        }
414        let Some(end) = range.first_index.checked_add(range.index_count) else {
415            return Err(MaterialSectionError::InvalidRange { index });
416        };
417        if range.index_count == 0
418            || range.first_index % 3 != 0
419            || range.index_count % 3 != 0
420            || end > mesh_index_count
421        {
422            return Err(MaterialSectionError::InvalidRange { index });
423        }
424        if range.first_index != previous_end {
425            return Err(MaterialSectionError::RangeOrder { index });
426        }
427        previous_end = end;
428    }
429    if previous_end != mesh_index_count {
430        return Err(MaterialSectionError::RangeOrder {
431            index: ranges.len(),
432        });
433    }
434    Ok(())
435}
436
437/// Serialise the MAT1-compatible 256-byte record: `id`, shading/opacity
438/// tags, the packed flag word, 13 LE `f32` PBR scalars, then six 32-byte
439/// texture digests. `out` must be at least `MATERIAL_V1_RECORD_SIZE`.
440pub(super) fn encode_material(material: &MaterialRecord, out: &mut [u8]) {
441    out[..8].copy_from_slice(&material.id.to_le_bytes());
442    out[8] = material.shading_model as u8;
443    out[9] = material.opacity_mode as u8;
444    let flags = u16::from(material.double_sided) * FLAG_DOUBLE_SIDED
445        | u16::from(material.casts_shadow) * FLAG_CASTS_SHADOW
446        | u16::from(material.receives_shadow) * FLAG_RECEIVES_SHADOW
447        | u16::from(material.pickable) * FLAG_PICKABLE
448        | u16::from(material.multiply_vertex_color) * FLAG_VERTEX_COLOR_MULTIPLY;
449    out[10..12].copy_from_slice(&flags.to_le_bytes());
450    let mut offset = 12;
451    for value in material.base_color.into_iter().chain(material.emissive) {
452        write_f32(out, &mut offset, value);
453    }
454    for value in [
455        material.metallic,
456        material.roughness,
457        material.specular,
458        material.normal_scale,
459        material.occlusion_strength,
460        material.alpha_cutoff,
461    ] {
462        write_f32(out, &mut offset, value);
463    }
464    for digest in [
465        material.base_color_texture,
466        material.normal_texture,
467        material.metallic_roughness_texture,
468        material.occlusion_texture,
469        material.emissive_texture,
470        material.stylized_ramp_texture,
471    ] {
472        out[offset..offset + 32].copy_from_slice(&digest);
473        offset += 32;
474    }
475}
476
477/// Decode one MAT1-compatible record. Fails on unknown shading/opacity
478/// tags, flag bits outside `KNOWN_FLAGS`, or `id == 0` (reported as
479/// `InvalidMaterial { index }` using the caller's record position).
480/// Fields beyond the v1 layout (transforms, samplers, `wind_animated`)
481/// come back as defaults for the versioned wrapper to overwrite.
482pub(super) fn decode_material(
483    bytes: &[u8],
484    index: usize,
485) -> Result<MaterialRecord, MaterialSectionError> {
486    let model =
487        ShadingModel::from_raw(bytes[8]).ok_or(MaterialSectionError::InvalidModel(bytes[8]))?;
488    let opacity =
489        OpacityMode::from_raw(bytes[9]).ok_or(MaterialSectionError::InvalidOpacity(bytes[9]))?;
490    let flags = read_u16(bytes, 10);
491    if flags & !KNOWN_FLAGS != 0 {
492        return Err(MaterialSectionError::UnknownFlags(flags));
493    }
494    let mut offset = 12;
495    let mut values = [0.0f32; 13];
496    for value in &mut values {
497        *value = read_f32(bytes, offset);
498        offset += 4;
499    }
500    let record = MaterialRecord {
501        id: read_u64(bytes, 0),
502        shading_model: model,
503        opacity_mode: opacity,
504        double_sided: flags & FLAG_DOUBLE_SIDED != 0,
505        casts_shadow: flags & FLAG_CASTS_SHADOW != 0,
506        receives_shadow: flags & FLAG_RECEIVES_SHADOW != 0,
507        pickable: flags & FLAG_PICKABLE != 0,
508        multiply_vertex_color: flags & FLAG_VERTEX_COLOR_MULTIPLY != 0,
509        wind_animated: false,
510        base_color: values[..4].try_into().expect("fixed material base color"),
511        emissive: values[4..7].try_into().expect("fixed material emissive"),
512        metallic: values[7],
513        roughness: values[8],
514        specular: values[9],
515        normal_scale: values[10],
516        occlusion_strength: values[11],
517        alpha_cutoff: values[12],
518        base_color_texture: bytes[64..96].try_into().expect("checked record bounds"),
519        normal_texture: bytes[96..128].try_into().expect("checked record bounds"),
520        metallic_roughness_texture: bytes[128..160].try_into().expect("checked record bounds"),
521        occlusion_texture: bytes[160..192].try_into().expect("checked record bounds"),
522        emissive_texture: bytes[192..224].try_into().expect("checked record bounds"),
523        stylized_ramp_texture: bytes[224..256].try_into().expect("checked record bounds"),
524        texture_transforms: [TextureTransform::IDENTITY; 6],
525        texture_samplers: [TextureSampler::GLTF_DEFAULT; 6],
526    };
527    if record.id == 0 {
528        return Err(MaterialSectionError::InvalidMaterial { index });
529    }
530    Ok(record)
531}
532
533fn write_f32(out: &mut [u8], offset: &mut usize, value: f32) {
534    out[*offset..*offset + 4].copy_from_slice(&value.to_le_bytes());
535    *offset += 4;
536}
537/// Little-endian `u16` at `offset`; panics if `bytes[offset..offset+2]`
538/// is out of range (callers pre-validate record bounds).
539pub(super) fn read_u16(bytes: &[u8], offset: usize) -> u16 {
540    u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
541}
542/// Little-endian `u32` at `offset`; panics on out-of-range slice.
543pub(super) fn read_u32(bytes: &[u8], offset: usize) -> u32 {
544    u32::from_le_bytes(
545        bytes[offset..offset + 4]
546            .try_into()
547            .expect("checked record bounds"),
548    )
549}
550/// Little-endian `u64` at `offset`; panics on out-of-range slice.
551pub(super) fn read_u64(bytes: &[u8], offset: usize) -> u64 {
552    u64::from_le_bytes(
553        bytes[offset..offset + 8]
554            .try_into()
555            .expect("checked record bounds"),
556    )
557}
558fn read_f32(bytes: &[u8], offset: usize) -> f32 {
559    f32::from_le_bytes(
560        bytes[offset..offset + 4]
561            .try_into()
562            .expect("checked record bounds"),
563    )
564}
565
566#[cfg(test)]
567#[path = "material_section_tests.rs"]
568mod tests;