Skip to main content

qualia_core_db/render/assets/
glb_skins_anims.rs

1//! Rigid glTF 2.0 / GLB → `.10d` Living Container Compiler (`SKL1`, `MRP1`, `PROC1`, `EONT1`,
2//! KHR Material Extensions & `KHR_lights_punctual`).
3
4use serde_json::Value;
5#[path = "glb_rigid_animation.rs"]
6mod rigid_animation;
7#[path = "glb_rigid_skin.rs"]
8mod rigid_skin;
9#[cfg(test)]
10#[path = "glb_rigid_tests.rs"]
11mod rigid_tests;
12
13use super::glb::{import_glb_with_normals, read_vec3, read_vec4};
14use super::{AssetError, ImportedMesh, CHUNK_BIN, CHUNK_JSON, GLB_MAGIC};
15use crate::container_10d::morph_section::{
16    encode_morph_section, morph_section_encoded_len, quantize_morph_delta, MorphSectionHeader,
17    QuantizedMorphDelta, FLAG_MORPH_HAS_NORMALS, FLAG_MORPH_HAS_TANGENTS,
18    FLAG_MORPH_ONTOGENETIC_BIND, FLAG_MORPH_SPARSE, MAGIC_MRP1, MORPH_SECTION_VERSION,
19};
20use crate::container_10d::procedural_synthesis::{
21    ProceduralSynthesisHeader, FLAG_ALLOMETRIC_GROWTH, FLAG_CELLULAR_VORONOI,
22    FLAG_PGA_MOTOR_DYNAMICS, MAGIC_PROC, PROCEDURAL_SYNTHESIS_SECTION_VERSION,
23};
24use crate::container_10d::skeletal_section::{
25    encode_skeletal_section_into, ClipRecord, Counts, SkeletalData,
26};
27use crate::container_10d::{EntityOntologyMiniHeader, MAGIC_EONT};
28use crate::q_hash;
29use crate::render::skeletal::{Joint, Key, Motor, SkinWeight, Track};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum GlbInterpolation {
33    Step,
34    Linear,
35    CubicSpline,
36}
37
38#[derive(Debug, Clone, PartialEq)]
39pub struct GlbNodeRecord {
40    pub name: Option<String>,
41    pub parent: Option<u16>,
42    pub children: Vec<u16>,
43    pub local_motor: Motor,
44    pub scale: [f32; 3],
45    pub mesh_index: Option<u32>,
46    pub skin_index: Option<u32>,
47    pub light_index: Option<u32>,
48    pub weights: Vec<f32>,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct KhrMaterialExtensions {
53    pub clearcoat_factor: f32,
54    pub clearcoat_roughness: f32,
55    pub sheen_color: [f32; 3],
56    pub sheen_roughness: f32,
57    pub transmission_factor: f32,
58    pub volume_thickness: f32,
59    pub volume_attenuation_distance: f32,
60    pub volume_attenuation_color: [f32; 3],
61    pub ior: f32,
62    pub anisotropy_strength: f32,
63    pub anisotropy_rotation: f32,
64    pub emissive_strength: f32,
65}
66
67impl Default for KhrMaterialExtensions {
68    fn default() -> Self {
69        Self {
70            clearcoat_factor: 0.0,
71            clearcoat_roughness: 0.0,
72            sheen_color: [0.0; 3],
73            sheen_roughness: 0.0,
74            transmission_factor: 0.0,
75            volume_thickness: 0.0,
76            volume_attenuation_distance: f32::INFINITY,
77            volume_attenuation_color: [1.0, 1.0, 1.0],
78            ior: 1.5,
79            anisotropy_strength: 0.0,
80            anisotropy_rotation: 0.0,
81            emissive_strength: 1.0,
82        }
83    }
84}
85
86#[derive(Debug, Clone, PartialEq)]
87pub struct KhrPunctualLight {
88    pub name: Option<String>,
89    pub kind: String,
90    pub color: [f32; 3],
91    pub intensity: f32,
92    pub range: Option<f32>,
93    pub inner_cone_angle: f32,
94    pub outer_cone_angle: f32,
95}
96
97#[derive(Debug, Clone, PartialEq)]
98pub struct GlbMorphWeightTrack {
99    pub node_index: u16,
100    pub interpolation: GlbInterpolation,
101    pub times: Vec<f32>,
102    pub values: Vec<f32>,
103}
104
105#[derive(Debug, Clone)]
106pub struct GlbLivingScene {
107    pub imported_mesh: ImportedMesh,
108    pub scene_roots: Vec<u16>,
109    pub nodes: Vec<GlbNodeRecord>,
110    pub joints: Vec<Joint>,
111    pub joint_ids: Vec<u64>,
112    pub skin_weights: Vec<SkinWeight>,
113    pub clips: Vec<ClipRecord>,
114    pub tracks: Vec<Track>,
115    pub keys: Vec<Key>,
116    pub skl1_section: Option<Vec<u8>>,
117    pub morph_header: Option<MorphSectionHeader>,
118    pub morph_deltas: Vec<QuantizedMorphDelta>,
119    pub mrp1_section: Option<Vec<u8>>,
120    pub morph_weight_tracks: Vec<GlbMorphWeightTrack>,
121    pub material_extensions: Vec<KhrMaterialExtensions>,
122    pub punctual_lights: Vec<KhrPunctualLight>,
123    pub proc1_header: ProceduralSynthesisHeader,
124    pub eont1_header: EntityOntologyMiniHeader,
125}
126
127pub type MotorAndScale = (Motor, [f32; 3]);
128
129/// Decompose a column-major 4x4 affine matrix into `(Motor, scale: [f32; 3])`.
130pub fn matrix4_to_motor_and_scale(m: &[f32; 16]) -> MotorAndScale {
131    let (tx, ty, tz) = (m[12] as f64, m[13] as f64, m[14] as f64);
132    let sx = (m[0] * m[0] + m[1] * m[1] + m[2] * m[2]).sqrt().max(1e-6);
133    let sy = (m[4] * m[4] + m[5] * m[5] + m[6] * m[6]).sqrt().max(1e-6);
134    let sz = (m[8] * m[8] + m[9] * m[9] + m[10] * m[10]).sqrt().max(1e-6);
135    let (r00, r10, r20) = ((m[0] / sx) as f64, (m[1] / sx) as f64, (m[2] / sx) as f64);
136    let (r01, r11, r21) = ((m[4] / sy) as f64, (m[5] / sy) as f64, (m[6] / sy) as f64);
137    let (r02, r12, r22) = ((m[8] / sz) as f64, (m[9] / sz) as f64, (m[10] / sz) as f64);
138    let trace = r00 + r11 + r22;
139    let (qw, qx, qy, qz) = if trace > 0.0 {
140        let s = (trace + 1.0).sqrt() * 2.0;
141        (0.25 * s, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s)
142    } else if r00 > r11 && r00 > r22 {
143        let s = (1.0 + r00 - r11 - r22).sqrt() * 2.0;
144        ((r21 - r12) / s, 0.25 * s, (r01 + r10) / s, (r02 + r20) / s)
145    } else if r11 > r22 {
146        let s = (1.0 + r11 - r00 - r22).sqrt() * 2.0;
147        ((r02 - r20) / s, (r01 + r10) / s, 0.25 * s, (r12 + r21) / s)
148    } else {
149        let s = (1.0 + r22 - r00 - r11).sqrt() * 2.0;
150        ((r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, 0.25 * s)
151    };
152    let len = (qw * qw + qx * qx + qy * qy + qz * qz).sqrt().max(1e-12);
153    (
154        Motor::from_rotation_translation([qw / len, qx / len, qy / len, qz / len], [tx, ty, tz]),
155        [sx, sy, sz],
156    )
157}
158
159/// Parse a binary glTF (`.glb`) into a rigid `.10d` Living Scene (`SKL1`, `MRP1`, `PROC1`, `EONT1`,
160/// KHR material extensions, and `KHR_lights_punctual`).
161pub fn parse_glb_living_scene(bytes: &[u8]) -> Result<GlbLivingScene, AssetError> {
162    let imported_mesh = import_glb_with_normals(bytes)?;
163    if bytes.len() < 12 || u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) != GLB_MAGIC
164    {
165        return Err(AssetError::UnknownFormat);
166    }
167    let (mut json_chunk, mut bin_chunk, mut off) = (None, None, 12usize);
168    while off + 8 <= bytes.len() {
169        let clen = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()) as usize;
170        let ctype = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap());
171        let dend = off + 8 + clen;
172        if ctype == CHUNK_JSON {
173            json_chunk = Some(&bytes[off + 8..dend]);
174        } else if ctype == CHUNK_BIN {
175            bin_chunk = Some(&bytes[off + 8..dend]);
176        }
177        off = dend;
178    }
179    let gltf: Value =
180        serde_json::from_slice(json_chunk.ok_or_else(|| AssetError::Parse("no JSON".into()))?)
181            .map_err(|e| AssetError::Parse(format!("glTF JSON: {e}")))?;
182    let (bin, empty) = (bin_chunk.unwrap_or(&[]), Vec::new());
183    let (accessors, bvs) = (
184        gltf["accessors"].as_array().unwrap_or(&empty),
185        gltf["bufferViews"].as_array().unwrap_or(&empty),
186    );
187
188    rigid_skin::validate_hierarchy(&gltf)?;
189    let (nodes, scene_roots) = parse_nodes_and_scenes(&gltf)?;
190    let mut skin_weights = parse_primitive_skin_weights(
191        &gltf,
192        accessors,
193        bvs,
194        bin,
195        imported_mesh.mesh.vertex_count(),
196    )?;
197    let skin = rigid_skin::parse_skins(&gltf, &nodes, accessors, bvs, bin, &mut skin_weights)?;
198    let (clips, tracks, keys, morph_weight_tracks) =
199        rigid_animation::parse_animations(&gltf, &nodes, &skin, accessors, bvs, bin)?;
200    let rigid_skin::RigidSkin {
201        joints, joint_ids, ..
202    } = skin;
203
204    let skl1_section = if !joints.is_empty() && !skin_weights.is_empty() {
205        let counts = Counts {
206            joints: joints.len(),
207            vertices: skin_weights.len(),
208            clips: clips.len(),
209            tracks: tracks.len(),
210            keys: keys.len(),
211        };
212        let len = counts.encoded_len().ok_or_else(|| {
213            AssetError::Parse("native skeletal section exceeds its explicit format bounds".into())
214        })?;
215        let mut bytes = vec![0u8; len];
216        let data = SkeletalData {
217            joints: &joints,
218            joint_ids: &joint_ids,
219            skin: &skin_weights,
220            clips: &clips,
221            tracks: &tracks,
222            keys: &keys,
223        };
224        encode_skeletal_section_into(&data, &mut bytes).map_err(|error| {
225            AssetError::Parse(format!(
226                "native skeletal section admission failed: {error:?}"
227            ))
228        })?;
229        Some(bytes)
230    } else {
231        None
232    };
233
234    let (morph_header, morph_deltas, mrp1_section) = parse_morph_targets(
235        &gltf,
236        accessors,
237        bvs,
238        bin,
239        imported_mesh.mesh.vertex_count(),
240    )?;
241    let material_extensions = parse_khr_material_extensions(&gltf);
242    let punctual_lights = parse_khr_lights_punctual(&gltf);
243    let (proc1_header, eont1_header) = build_living_headers(&gltf, &imported_mesh);
244
245    Ok(GlbLivingScene {
246        imported_mesh,
247        scene_roots,
248        nodes,
249        joints,
250        joint_ids,
251        skin_weights,
252        clips,
253        tracks,
254        keys,
255        skl1_section,
256        morph_header,
257        morph_deltas,
258        mrp1_section,
259        morph_weight_tracks,
260        material_extensions,
261        punctual_lights,
262        proc1_header,
263        eont1_header,
264    })
265}
266
267fn parse_nodes_and_scenes(gltf: &Value) -> Result<(Vec<GlbNodeRecord>, Vec<u16>), AssetError> {
268    let empty = Vec::new();
269    let raw_nodes = gltf["nodes"].as_array().unwrap_or(&empty);
270    let mut nodes = Vec::with_capacity(raw_nodes.len());
271    for n in raw_nodes {
272        let (local_motor, scale) = if let Some(mat_arr) = n["matrix"].as_array() {
273            if mat_arr.len() != 16 {
274                return Err(AssetError::Parse("node.matrix must have 16 floats".into()));
275            }
276            let mut m = [0.0f32; 16];
277            for (i, v) in mat_arr.iter().enumerate() {
278                m[i] = v.as_f64().unwrap_or(0.0) as f32;
279            }
280            matrix4_to_motor_and_scale(&m)
281        } else {
282            let t = n["translation"]
283                .as_array()
284                .map(|a| {
285                    [
286                        a.first().and_then(|v| v.as_f64()).unwrap_or(0.0),
287                        a.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0),
288                        a.get(2).and_then(|v| v.as_f64()).unwrap_or(0.0),
289                    ]
290                })
291                .unwrap_or([0.0; 3]);
292            let r = n["rotation"]
293                .as_array()
294                .map(|a| {
295                    let (x, y) = (
296                        a.first().and_then(|v| v.as_f64()).unwrap_or(0.0),
297                        a.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0),
298                    );
299                    let (z, w) = (
300                        a.get(2).and_then(|v| v.as_f64()).unwrap_or(0.0),
301                        a.get(3).and_then(|v| v.as_f64()).unwrap_or(1.0),
302                    );
303                    let l = (w * w + x * x + y * y + z * z).sqrt().max(1e-12);
304                    [w / l, x / l, y / l, z / l]
305                })
306                .unwrap_or([1.0, 0.0, 0.0, 0.0]);
307            let s = n["scale"]
308                .as_array()
309                .map(|a| {
310                    [
311                        a.first().and_then(|v| v.as_f64()).unwrap_or(1.0) as f32,
312                        a.get(1).and_then(|v| v.as_f64()).unwrap_or(1.0) as f32,
313                        a.get(2).and_then(|v| v.as_f64()).unwrap_or(1.0) as f32,
314                    ]
315                })
316                .unwrap_or([1.0; 3]);
317            (Motor::from_rotation_translation(r, t), s)
318        };
319        let children = n["children"]
320            .as_array()
321            .into_iter()
322            .flatten()
323            .filter_map(|c| c.as_u64().map(|v| v as u16))
324            .collect();
325        let weights = n["weights"]
326            .as_array()
327            .into_iter()
328            .flatten()
329            .filter_map(|w| w.as_f64().map(|v| v as f32))
330            .collect();
331        let light_index = n["extensions"]["KHR_lights_punctual"]["light"]
332            .as_u64()
333            .map(|v| v as u32);
334        nodes.push(GlbNodeRecord {
335            name: n["name"].as_str().map(String::from),
336            parent: None,
337            children,
338            local_motor,
339            scale,
340            mesh_index: n["mesh"].as_u64().map(|v| v as u32),
341            skin_index: n["skin"].as_u64().map(|v| v as u32),
342            light_index,
343            weights,
344        });
345    }
346    for parent_idx in 0..nodes.len() {
347        let ch = nodes[parent_idx].children.clone();
348        for c in ch {
349            if let Some(child_node) = nodes.get_mut(c as usize) {
350                child_node.parent = Some(parent_idx as u16);
351            }
352        }
353    }
354    let scene_idx = gltf["scene"].as_u64().unwrap_or(0) as usize;
355    let scene_roots = gltf["scenes"]
356        .as_array()
357        .and_then(|s| s.get(scene_idx))
358        .and_then(|s| s["nodes"].as_array())
359        .into_iter()
360        .flatten()
361        .filter_map(|v| v.as_u64().map(|u| u as u16))
362        .collect();
363    Ok((nodes, scene_roots))
364}
365
366fn parse_primitive_skin_weights(
367    gltf: &Value,
368    accessors: &[Value],
369    bvs: &[Value],
370    bin: &[u8],
371    total_vertices: usize,
372) -> Result<Vec<SkinWeight>, AssetError> {
373    let empty = Vec::new();
374    let mut out = Vec::new();
375    for mesh in gltf["meshes"].as_array().unwrap_or(&empty) {
376        for prim in mesh["primitives"].as_array().into_iter().flatten() {
377            if prim["mode"].as_u64().unwrap_or(4) != 4 {
378                continue;
379            }
380            if prim["attributes"].get("JOINTS_1").is_some()
381                || prim["attributes"].get("WEIGHTS_1").is_some()
382            {
383                return Err(AssetError::Parse(
384                    "more than four skin influences require an influence-preserving native profile"
385                        .into(),
386                ));
387            }
388            let j_idx = prim["attributes"]["JOINTS_0"].as_u64();
389            let w_idx = prim["attributes"]["WEIGHTS_0"].as_u64();
390            if j_idx.is_some() != w_idx.is_some() {
391                return Err(AssetError::Parse(
392                    "JOINTS_0/WEIGHTS_0 must be paired".into(),
393                ));
394            }
395            let (Some(j_idx), Some(w_idx)) = (j_idx, w_idx) else {
396                continue;
397            };
398            let j_acc = accessors
399                .get(j_idx as usize)
400                .ok_or_else(|| AssetError::Parse("JOINTS_0 OOB".into()))?;
401            let w_acc = accessors
402                .get(w_idx as usize)
403                .ok_or_else(|| AssetError::Parse("WEIGHTS_0 OOB".into()))?;
404            let (joints, weights) = (
405                read_joints_0(j_acc, bvs, bin)?,
406                read_weights_0(w_acc, bvs, bin)?,
407            );
408            if joints.len() != weights.len() {
409                return Err(AssetError::Parse(
410                    "JOINTS_0/WEIGHTS_0 count mismatch".into(),
411                ));
412            }
413            for (j, w) in joints.into_iter().zip(weights) {
414                if w.iter().any(|v| !v.is_finite() || *v < 0.0) {
415                    return Err(AssetError::Parse("invalid skin weights".into()));
416                }
417                let sum: f32 = w.iter().sum();
418                if !sum.is_finite() || sum <= 0.0 {
419                    return Err(AssetError::Parse(
420                        "zero or non-finite skin weight sum".into(),
421                    ));
422                }
423                let norm_w = w.map(|v| v / sum);
424                out.push(SkinWeight {
425                    joints: j,
426                    weights: norm_w,
427                });
428            }
429        }
430    }
431    if !out.is_empty() && out.len() != total_vertices {
432        return Err(AssetError::Parse(
433            "skin vertex remapping must preserve vertex alignment".into(),
434        ));
435    }
436    Ok(out)
437}
438
439fn read_joints_0(acc: &Value, bvs: &[Value], bin: &[u8]) -> Result<Vec<[u16; 4]>, AssetError> {
440    if acc["type"].as_str() != Some("VEC4") {
441        return Err(AssetError::Parse("JOINTS_0 VEC4".into()));
442    }
443    let (comp, count) = (
444        acc["componentType"].as_u64().unwrap_or(0),
445        acc["count"]
446            .as_u64()
447            .ok_or_else(|| AssetError::Parse("JOINTS_0 count".into()))? as usize,
448    );
449    let bv = bvs
450        .get(acc["bufferView"].as_u64().unwrap_or(0) as usize)
451        .ok_or_else(|| AssetError::Parse("JOINTS_0 bv".into()))?;
452    let start = bv["byteOffset"].as_u64().unwrap_or(0) as usize
453        + acc["byteOffset"].as_u64().unwrap_or(0) as usize;
454    let elem_bytes = match comp {
455        5121 => 4usize,
456        5123 => 8usize,
457        _ => return Err(AssetError::Parse("JOINTS_0 comp".into())),
458    };
459    rigid_skin::checked_accessor(acc, bvs, bin, elem_bytes, 262144)?;
460    let stride = bv["byteStride"]
461        .as_u64()
462        .map(|s| s as usize)
463        .unwrap_or(elem_bytes);
464    (0..count)
465        .map(|i| {
466            let s = bin
467                .get(start + i * stride..start + i * stride + elem_bytes)
468                .ok_or_else(|| AssetError::Parse("JOINTS_0 OOB".into()))?;
469            Ok(if comp == 5121 {
470                [s[0] as u16, s[1] as u16, s[2] as u16, s[3] as u16]
471            } else {
472                [
473                    u16::from_le_bytes([s[0], s[1]]),
474                    u16::from_le_bytes([s[2], s[3]]),
475                    u16::from_le_bytes([s[4], s[5]]),
476                    u16::from_le_bytes([s[6], s[7]]),
477                ]
478            })
479        })
480        .collect()
481}
482
483fn read_weights_0(acc: &Value, bvs: &[Value], bin: &[u8]) -> Result<Vec<[f32; 4]>, AssetError> {
484    if acc["type"].as_str() != Some("VEC4") {
485        return Err(AssetError::Parse("WEIGHTS_0 VEC4".into()));
486    }
487    let (comp, count) = (
488        acc["componentType"].as_u64().unwrap_or(0),
489        acc["count"]
490            .as_u64()
491            .ok_or_else(|| AssetError::Parse("WEIGHTS_0 count".into()))? as usize,
492    );
493    let bv = bvs
494        .get(acc["bufferView"].as_u64().unwrap_or(0) as usize)
495        .ok_or_else(|| AssetError::Parse("WEIGHTS_0 bv".into()))?;
496    let start = bv["byteOffset"].as_u64().unwrap_or(0) as usize
497        + acc["byteOffset"].as_u64().unwrap_or(0) as usize;
498    let elem_bytes = match comp {
499        5121 => 4usize,
500        5123 => 8usize,
501        5126 => 16usize,
502        _ => return Err(AssetError::Parse("WEIGHTS_0 comp".into())),
503    };
504    if comp != 5126 && acc["normalized"].as_bool() != Some(true) {
505        return Err(AssetError::Parse(
506            "integer WEIGHTS_0 must be normalized".into(),
507        ));
508    }
509    rigid_skin::checked_accessor(acc, bvs, bin, elem_bytes, 262144)?;
510    let stride = bv["byteStride"]
511        .as_u64()
512        .map(|s| s as usize)
513        .unwrap_or(elem_bytes);
514    (0..count)
515        .map(|i| {
516            let s = bin
517                .get(start + i * stride..start + i * stride + elem_bytes)
518                .ok_or_else(|| AssetError::Parse("WEIGHTS_0 OOB".into()))?;
519            Ok(match comp {
520                5121 => [
521                    s[0] as f32 / 255.0,
522                    s[1] as f32 / 255.0,
523                    s[2] as f32 / 255.0,
524                    s[3] as f32 / 255.0,
525                ],
526                5123 => [
527                    u16::from_le_bytes([s[0], s[1]]) as f32 / 65535.0,
528                    u16::from_le_bytes([s[2], s[3]]) as f32 / 65535.0,
529                    u16::from_le_bytes([s[4], s[5]]) as f32 / 65535.0,
530                    u16::from_le_bytes([s[6], s[7]]) as f32 / 65535.0,
531                ],
532                _ => [
533                    f32::from_le_bytes(s[0..4].try_into().unwrap()),
534                    f32::from_le_bytes(s[4..8].try_into().unwrap()),
535                    f32::from_le_bytes(s[8..12].try_into().unwrap()),
536                    f32::from_le_bytes(s[12..16].try_into().unwrap()),
537                ],
538            })
539        })
540        .collect()
541}
542
543fn read_f32_scalars(acc: &Value, bvs: &[Value], bin: &[u8]) -> Result<Vec<f32>, AssetError> {
544    if acc["type"].as_str() != Some("SCALAR") || acc["componentType"].as_u64() != Some(5126) {
545        return Err(AssetError::Parse(
546            "animation scalar must be FLOAT SCALAR".into(),
547        ));
548    }
549    rigid_skin::checked_accessor(acc, bvs, bin, 4, crate::render::skeletal::MAX_KEYS * 16 * 3)?;
550    let (count, bv) = (
551        acc["count"].as_u64().unwrap_or(0) as usize,
552        bvs.get(acc["bufferView"].as_u64().unwrap_or(0) as usize)
553            .ok_or_else(|| AssetError::Parse("scalar bv".into()))?,
554    );
555    let (start, stride) = (
556        bv["byteOffset"].as_u64().unwrap_or(0) as usize
557            + acc["byteOffset"].as_u64().unwrap_or(0) as usize,
558        bv["byteStride"].as_u64().map(|s| s as usize).unwrap_or(4),
559    );
560    (0..count)
561        .map(|i| {
562            let s = bin
563                .get(start + i * stride..start + i * stride + 4)
564                .ok_or_else(|| AssetError::Parse("scalar OOB".into()))?;
565            Ok(f32::from_le_bytes(s.try_into().unwrap()))
566        })
567        .collect()
568}
569
570fn parse_morph_targets(
571    gltf: &Value,
572    accessors: &[Value],
573    bvs: &[Value],
574    bin: &[u8],
575    total_vertices: usize,
576) -> Result<
577    (
578        Option<MorphSectionHeader>,
579        Vec<QuantizedMorphDelta>,
580        Option<Vec<u8>>,
581    ),
582    AssetError,
583> {
584    let empty = Vec::new();
585    let mut raw_deltas: Vec<(u8, u32, [f32; 3], [f32; 3], [f32; 3])> = Vec::new();
586    let (mut max_disp, mut target_count, mut has_normals, mut has_tangents, mut v_base) =
587        (0.0f32, 0u16, false, false, 0u32);
588    for mesh in gltf["meshes"].as_array().unwrap_or(&empty) {
589        for prim in mesh["primitives"].as_array().into_iter().flatten() {
590            if prim["mode"].as_u64().unwrap_or(4) != 4 {
591                continue;
592            }
593            let pos_idx = prim["attributes"]["POSITION"].as_u64().unwrap_or(0) as usize;
594            let prim_vcount = accessors
595                .get(pos_idx)
596                .and_then(|a| a["count"].as_u64())
597                .unwrap_or(0) as u32;
598            if let Some(targets) = prim["targets"].as_array() {
599                target_count = target_count.max(targets.len() as u16);
600                for (t_idx, target) in targets.iter().enumerate() {
601                    let Some(p_acc_i) = target["POSITION"].as_u64() else {
602                        continue;
603                    };
604                    let p_deltas = read_vec3(
605                        accessors
606                            .get(p_acc_i as usize)
607                            .ok_or_else(|| AssetError::Parse("morph POS".into()))?,
608                        bvs,
609                        bin,
610                        "morph.POSITION",
611                    )?;
612                    let n_deltas = if let Some(n_i) = target["NORMAL"].as_u64() {
613                        has_normals = true;
614                        read_vec3(
615                            accessors
616                                .get(n_i as usize)
617                                .ok_or_else(|| AssetError::Parse("morph NRM".into()))?,
618                            bvs,
619                            bin,
620                            "morph.NORMAL",
621                        )?
622                    } else {
623                        vec![[0.0; 3]; p_deltas.len()]
624                    };
625                    let t_deltas = if let Some(t_i) = target["TANGENT"].as_u64() {
626                        has_tangents = true;
627                        read_vec3(
628                            accessors
629                                .get(t_i as usize)
630                                .ok_or_else(|| AssetError::Parse("morph TAN".into()))?,
631                            bvs,
632                            bin,
633                            "morph.TANGENT",
634                        )?
635                    } else {
636                        vec![[0.0; 3]; p_deltas.len()]
637                    };
638                    for (vi, &pd) in p_deltas.iter().enumerate() {
639                        let (nd, td) = (
640                            n_deltas.get(vi).copied().unwrap_or([0.0; 3]),
641                            t_deltas.get(vi).copied().unwrap_or([0.0; 3]),
642                        );
643                        let mag = pd[0].abs().max(pd[1].abs()).max(pd[2].abs());
644                        if mag > 1e-6 || nd != [0.0; 3] {
645                            max_disp = max_disp.max(mag);
646                            raw_deltas.push((
647                                t_idx as u8,
648                                (v_base + vi as u32).min(total_vertices.saturating_sub(1) as u32),
649                                pd,
650                                nd,
651                                td,
652                            ));
653                        }
654                    }
655                }
656            }
657            v_base = v_base.saturating_add(prim_vcount);
658        }
659    }
660    if target_count == 0 || raw_deltas.is_empty() {
661        return Ok((None, Vec::new(), None));
662    }
663    let max_displacement = max_disp.max(1e-4);
664    let flags = FLAG_MORPH_SPARSE
665        | FLAG_MORPH_ONTOGENETIC_BIND
666        | if has_normals {
667            FLAG_MORPH_HAS_NORMALS
668        } else {
669            0
670        }
671        | if has_tangents {
672            FLAG_MORPH_HAS_TANGENTS
673        } else {
674            0
675        };
676    let header = MorphSectionHeader {
677        magic: MAGIC_MRP1,
678        version: MORPH_SECTION_VERSION,
679        target_count,
680        vertex_count: total_vertices as u32,
681        flags,
682        max_displacement,
683        ontogenetic_bind_mask: (1u32 << target_count.min(16)) - 1,
684        reserved: [0u8; 8],
685    };
686    let deltas: Vec<QuantizedMorphDelta> = raw_deltas
687        .into_iter()
688        .map(|(ti, vi, pd, nd, td)| quantize_morph_delta(pd, nd, td, max_displacement, ti, vi))
689        .collect();
690    let len = morph_section_encoded_len(deltas.len())
691        .ok_or_else(|| AssetError::Parse("MRP1 length overflow".into()))?;
692    let mut buf = vec![0u8; len];
693    encode_morph_section(&header, &deltas, &mut buf)
694        .map_err(|e| AssetError::Parse(format!("MRP1 admission: {e:?}")))?;
695    Ok((Some(header), deltas, Some(buf)))
696}
697
698fn parse_khr_material_extensions(gltf: &Value) -> Vec<KhrMaterialExtensions> {
699    let empty = Vec::new();
700    gltf["materials"]
701        .as_array()
702        .unwrap_or(&empty)
703        .iter()
704        .map(|m| {
705            let (ext, mut khr) = (&m["extensions"], KhrMaterialExtensions::default());
706            if let Some(cc) = ext.get("KHR_materials_clearcoat") {
707                khr.clearcoat_factor = cc["clearcoatFactor"].as_f64().unwrap_or(0.0) as f32;
708                khr.clearcoat_roughness =
709                    cc["clearcoatRoughnessFactor"].as_f64().unwrap_or(0.0) as f32;
710            }
711            if let Some(sh) = ext.get("KHR_materials_sheen") {
712                if let Some(c) = sh["sheenColorFactor"].as_array().filter(|c| c.len() == 3) {
713                    khr.sheen_color = [
714                        c[0].as_f64().unwrap_or(0.0) as f32,
715                        c[1].as_f64().unwrap_or(0.0) as f32,
716                        c[2].as_f64().unwrap_or(0.0) as f32,
717                    ];
718                }
719                khr.sheen_roughness = sh["sheenRoughnessFactor"].as_f64().unwrap_or(0.0) as f32;
720            }
721            if let Some(tr) = ext.get("KHR_materials_transmission") {
722                khr.transmission_factor = tr["transmissionFactor"].as_f64().unwrap_or(0.0) as f32;
723            }
724            if let Some(vol) = ext.get("KHR_materials_volume") {
725                khr.volume_thickness = vol["thicknessFactor"].as_f64().unwrap_or(0.0) as f32;
726                khr.volume_attenuation_distance = vol["attenuationDistance"]
727                    .as_f64()
728                    .map(|v| v as f32)
729                    .unwrap_or(f32::INFINITY);
730                if let Some(c) = vol["attenuationColor"].as_array().filter(|c| c.len() == 3) {
731                    khr.volume_attenuation_color = [
732                        c[0].as_f64().unwrap_or(1.0) as f32,
733                        c[1].as_f64().unwrap_or(1.0) as f32,
734                        c[2].as_f64().unwrap_or(1.0) as f32,
735                    ];
736                }
737            }
738            if let Some(ior) = ext.get("KHR_materials_ior") {
739                khr.ior = ior["ior"].as_f64().unwrap_or(1.5) as f32;
740            }
741            if let Some(aniso) = ext.get("KHR_materials_anisotropy") {
742                khr.anisotropy_strength =
743                    aniso["anisotropyStrength"].as_f64().unwrap_or(0.0) as f32;
744                khr.anisotropy_rotation =
745                    aniso["anisotropyRotation"].as_f64().unwrap_or(0.0) as f32;
746            }
747            if let Some(em) = ext.get("KHR_materials_emissive_strength") {
748                khr.emissive_strength = em["emissiveStrength"].as_f64().unwrap_or(1.0) as f32;
749            }
750            khr
751        })
752        .collect()
753}
754
755fn parse_khr_lights_punctual(gltf: &Value) -> Vec<KhrPunctualLight> {
756    let empty = Vec::new();
757    gltf["extensions"]["KHR_lights_punctual"]["lights"]
758        .as_array()
759        .unwrap_or(&empty)
760        .iter()
761        .map(|l| {
762            let color = l["color"]
763                .as_array()
764                .filter(|c| c.len() == 3)
765                .map(|c| {
766                    [
767                        c[0].as_f64().unwrap_or(1.0) as f32,
768                        c[1].as_f64().unwrap_or(1.0) as f32,
769                        c[2].as_f64().unwrap_or(1.0) as f32,
770                    ]
771                })
772                .unwrap_or([1.0, 1.0, 1.0]);
773            KhrPunctualLight {
774                name: l["name"].as_str().map(String::from),
775                kind: l["type"].as_str().unwrap_or("point").to_string(),
776                color,
777                intensity: l["intensity"].as_f64().unwrap_or(1.0) as f32,
778                range: l["range"].as_f64().map(|v| v as f32),
779                inner_cone_angle: l["spot"]["innerConeAngle"].as_f64().unwrap_or(0.0) as f32,
780                outer_cone_angle: l["spot"]["outerConeAngle"]
781                    .as_f64()
782                    .unwrap_or(core::f64::consts::FRAC_PI_4)
783                    as f32,
784            }
785        })
786        .collect()
787}
788
789fn build_living_headers(
790    gltf: &Value,
791    imported: &ImportedMesh,
792) -> (ProceduralSynthesisHeader, EntityOntologyMiniHeader) {
793    let extras = &gltf["asset"]["extras"]["qualia"];
794    let seed = extras["seed"].as_u64().unwrap_or(0x5155_414C_4941_3130);
795    let proc1 = ProceduralSynthesisHeader {
796        magic: MAGIC_PROC,
797        version: PROCEDURAL_SYNTHESIS_SECTION_VERSION,
798        flags: (FLAG_CELLULAR_VORONOI | FLAG_ALLOMETRIC_GROWTH | FLAG_PGA_MOTOR_DYNAMICS) as u16,
799        seed,
800        voronoi_frequency: extras["voronoi_frequency"].as_f64().unwrap_or(12.0) as f32,
801        voronoi_jitter: 0.85,
802        fillet_blend_radius: 0.08,
803        fillet_threshold: 0.02,
804        allometry_exponent_k: extras["allometry_k"].as_f64().unwrap_or(1.25) as f32,
805        allometry_base_b: 1.0,
806        spiral_growth_rate_k: 0.15,
807        spiral_initial_radius_a: 0.1,
808        motor_frequency_hz: extras["motor_frequency_hz"].as_f64().unwrap_or(1.8) as f32,
809        motor_damping_ratio: 0.15,
810        critical_stress_threshold: 50.0,
811        reserved_f32: 0.0,
812    };
813    let taxon = extras["taxon_iri"]
814        .as_str()
815        .unwrap_or("urn:qualia:taxon:living_asset");
816    let eont1 = EntityOntologyMiniHeader {
817        magic: MAGIC_EONT,
818        version: 1,
819        stage: extras["stage"].as_u64().unwrap_or(2) as u8,
820        reserved_u8: 0,
821        entity_did_hash: q_hash(taxon),
822        taxon_iri_hash: q_hash(taxon),
823        energy_permill: 1000,
824        damage_permill: 0,
825        hydration_permill: 1000,
826        wear_permill: 0,
827        affordance_count: imported.submeshes.len() as u32,
828        reserved_u32: 0,
829    };
830    (proc1, eont1)
831}