Skip to main content

euv_core/game/engine3d/gltf/
fn.rs

1use super::*;
2
3/// Returns the number of scalar components per element for a glTF 2.0 accessor `type` string.
4///
5/// # Arguments
6///
7/// - `&str` - Accessor `type` string (`SCALAR`, `VEC2`, `VEC3`, `VEC4`, `MAT2`, `MAT3`, `MAT4`).
8///
9/// # Returns
10///
11/// - `usize` - Component count per element (`0` if unrecognized).
12#[must_use]
13fn gltf_type_components(type_str: &str) -> usize {
14    match type_str {
15        ACC_TYPE_SCALAR => 1,
16        ACC_TYPE_VEC2 => 2,
17        ACC_TYPE_VEC3 => 3,
18        ACC_TYPE_VEC4 | ACC_TYPE_MAT2 => 4,
19        ACC_TYPE_MAT3 => 9,
20        ACC_TYPE_MAT4 => 16,
21        _ => 0,
22    }
23}
24
25/// Returns byte size per scalar component for a glTF 2.0 `componentType` code.
26///
27/// # Arguments
28///
29/// - `u32` - glTF `componentType` code (`5120..=5126`).
30///
31/// # Returns
32///
33/// - `usize` - Component byte width (`0` if unsupported).
34#[must_use]
35fn gltf_component_byte_size(comp_type: u32) -> usize {
36    match comp_type {
37        GLTF_COMP_I8 | GLTF_COMP_U8 => 1,
38        GLTF_COMP_I16 | GLTF_COMP_U16 => 2,
39        GLTF_COMP_U32 | GLTF_COMP_F32 => 4,
40        _ => 0,
41    }
42}
43
44/// Reads a single scalar component from `bytes` at `offset` as `f32`, applying glTF normalization when `normalized` is set.
45///
46/// # Arguments
47///
48/// - `&[u8]` - Backing binary buffer slice.
49/// - `usize` - Byte offset of the scalar component.
50/// - `u32` - glTF `componentType` code.
51/// - `bool` - Whether integer values are normalized (`KHR_mesh_quantization` / `COLOR_0` / `WEIGHTS_0`).
52///
53/// # Returns
54///
55/// - `Result<f32, String>` - Decoded floating-point component or bounds error.
56fn read_gltf_scalar_f32(
57    bytes: &[u8],
58    offset: usize,
59    comp_type: u32,
60    normalized: bool,
61) -> Result<f32, String> {
62    let size: usize = gltf_component_byte_size(comp_type);
63    if size == 0 || offset.saturating_add(size) > bytes.len() {
64        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
65    }
66    let val: f32 = match comp_type {
67        GLTF_COMP_I8 => {
68            let raw: f32 = f32::from(bytes[offset] as i8);
69            if normalized {
70                (raw / 127.0).max(-1.0)
71            } else {
72                raw
73            }
74        }
75        GLTF_COMP_U8 => {
76            let raw: f32 = f32::from(bytes[offset]);
77            if normalized { raw / 255.0 } else { raw }
78        }
79        GLTF_COMP_I16 => {
80            let raw: f32 = f32::from(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
81            if normalized {
82                (raw / 32_767.0).max(-1.0)
83            } else {
84                raw
85            }
86        }
87        GLTF_COMP_U16 => {
88            let raw: f32 = f32::from(u16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
89            if normalized { raw / 65_535.0 } else { raw }
90        }
91        GLTF_COMP_U32 => u32::from_le_bytes([
92            bytes[offset],
93            bytes[offset + 1],
94            bytes[offset + 2],
95            bytes[offset + 3],
96        ]) as f32,
97        GLTF_COMP_F32 => f32::from_le_bytes([
98            bytes[offset],
99            bytes[offset + 1],
100            bytes[offset + 2],
101            bytes[offset + 3],
102        ]),
103        _ => return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
104    };
105    Ok(val)
106}
107
108/// Reads an unsigned integer index from `bytes` at `offset` for `u8`, `u16`, or `u32` glTF component types.
109///
110/// # Arguments
111///
112/// - `&[u8]` - Backing binary buffer slice.
113/// - `usize` - Byte offset.
114/// - `u32` - glTF `componentType` code.
115///
116/// # Returns
117///
118/// - `Result<u32, String>` - Decoded unsigned integer or bounds error.
119fn read_gltf_scalar_u32(bytes: &[u8], offset: usize, comp_type: u32) -> Result<u32, String> {
120    let size: usize = gltf_component_byte_size(comp_type);
121    if size == 0 || offset.saturating_add(size) > bytes.len() {
122        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
123    }
124    match comp_type {
125        GLTF_COMP_U8 => Ok(u32::from(bytes[offset])),
126        GLTF_COMP_U16 => Ok(u32::from(u16::from_le_bytes([
127            bytes[offset],
128            bytes[offset + 1],
129        ]))),
130        GLTF_COMP_U32 => Ok(u32::from_le_bytes([
131            bytes[offset],
132            bytes[offset + 1],
133            bytes[offset + 2],
134            bytes[offset + 3],
135        ])),
136        GLTF_COMP_I16 => Ok(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]).max(0) as u32),
137        GLTF_COMP_I8 => Ok((bytes[offset] as i8).max(0) as u32),
138        _ => Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
139    }
140}
141
142/// Un-zigzags an 8-bit meshopt signed delta back to a wrapping unsigned byte delta.
143///
144/// # Arguments
145///
146/// - `u8` - Zigzag-encoded byte.
147///
148/// # Returns
149///
150/// - `u8` - Wrapping signed delta as `u8`.
151#[must_use]
152fn meshopt_unzigzag8(val: u8) -> u8 {
153    ((val & 1).wrapping_neg()) ^ (val >> 1)
154}
155
156/// Un-zigzags a 32-bit meshopt signed delta back to a wrapping `u32`.
157///
158/// # Arguments
159///
160/// - `u32` - Zigzag-encoded 32-bit integer.
161///
162/// # Returns
163///
164/// - `u32` - Wrapping signed delta as `u32`.
165#[must_use]
166fn meshopt_unzigzag32(val: u32) -> u32 {
167    ((val & 1).wrapping_neg()) ^ (val >> 1)
168}
169
170/// Reads an unsigned LEB128 varint from `data` advancing `cursor`.
171///
172/// # Arguments
173///
174/// - `&[u8]` - Compressed stream slice.
175/// - `&mut usize` - Mutable cursor position.
176///
177/// # Returns
178///
179/// - `Result<u32, String>` - Decoded 32-bit integer or error.
180fn meshopt_read_varint(data: &[u8], cursor: &mut usize) -> Result<u32, String> {
181    let mut acc: u32 = 0;
182    let mut shift: u32 = 0;
183    for _ in 0..5 {
184        if *cursor >= data.len() {
185            return Err(ERR_GLTF_MESHOPT.to_string());
186        }
187        let byte_val: u8 = data[*cursor];
188        *cursor += 1;
189        acc |= u32::from(byte_val & 0x7f) << shift;
190        if (byte_val & 0x80) == 0 {
191            return Ok(acc);
192        }
193        shift += 7;
194    }
195    Err(ERR_GLTF_MESHOPT.to_string())
196}
197
198/// Decodes a `meshopt` v0 vertex attribute stream (`EXT_meshopt_compression` `ATTRIBUTES` mode).
199///
200/// # Arguments
201///
202/// - `&[u8]` - Compressed vertex buffer slice.
203/// - `usize` - Number of vertices (`count`).
204/// - `usize` - Stride per vertex in bytes (`byteStride`, `4..=256`, multiple of 4).
205///
206/// # Returns
207///
208/// - `Result<Vec<u8>, String>` - Decompressed vertex buffer of exact length `count * stride`.
209pub fn decode_meshopt_vertex_buffer(
210    data: &[u8],
211    count: usize,
212    stride: usize,
213) -> Result<Vec<u8>, String> {
214    let bad_stride: bool = stride == 0 || stride > 256;
215    if bad_stride || !stride.is_multiple_of(4) {
216        return Err(ERR_GLTF_MESHOPT.to_string());
217    }
218    if count == 0 {
219        return Ok(Vec::new());
220    }
221    if data.len() < 1 + stride {
222        return Err(ERR_GLTF_MESHOPT.to_string());
223    }
224    let header: u8 = data[0];
225    if (header & 0xf0) != 0xa0 || (header & 0x0f) > 1 {
226        return Err(ERR_GLTF_MESHOPT.to_string());
227    }
228    let payload_end: usize = data.len() - stride;
229    let mut last_vertex: Vec<u8> = data[payload_end..].to_vec();
230    let mut cursor: usize = 1;
231    let raw_block: usize = (8192 / stride) & !15usize;
232    let block_size: usize = raw_block.clamp(16, 256);
233    let mut out: Vec<u8> = vec![0u8; count.saturating_mul(stride)];
234    let mut vertex_offset: usize = 0;
235    while vertex_offset < count {
236        let block_count: usize = (count - vertex_offset).min(block_size);
237        let group_count: usize = block_count.div_ceil(16);
238        let ctrl_bytes: usize = group_count.div_ceil(4);
239        for k in 0..stride {
240            if cursor + ctrl_bytes > payload_end {
241                return Err(ERR_GLTF_MESHOPT.to_string());
242            }
243            let ctrl: &[u8] = &data[cursor..(cursor + ctrl_bytes)];
244            cursor += ctrl_bytes;
245            let mut last_byte: u8 = last_vertex[k];
246            let mut decoded_in_block: usize = 0;
247            for g in 0..group_count {
248                let bits: u8 = (ctrl[g >> 2] >> ((g & 3) * 2)) & 0x03;
249                let mut deltas: [u8; 16] = [0u8; 16];
250                match bits {
251                    0 => {}
252                    1 => {
253                        if cursor + 4 > payload_end {
254                            return Err(ERR_GLTF_MESHOPT.to_string());
255                        }
256                        for b_idx in 0..4 {
257                            let packed: u8 = data[cursor + b_idx];
258                            deltas[b_idx * 4] = (packed >> 6) & 0x03;
259                            deltas[b_idx * 4 + 1] = (packed >> 4) & 0x03;
260                            deltas[b_idx * 4 + 2] = (packed >> 2) & 0x03;
261                            deltas[b_idx * 4 + 3] = packed & 0x03;
262                        }
263                        cursor += 4;
264                    }
265                    2 => {
266                        if cursor + 8 > payload_end {
267                            return Err(ERR_GLTF_MESHOPT.to_string());
268                        }
269                        for b_idx in 0..8 {
270                            let packed: u8 = data[cursor + b_idx];
271                            deltas[b_idx * 2] = packed >> 4;
272                            deltas[b_idx * 2 + 1] = packed & 0x0f;
273                        }
274                        cursor += 8;
275                    }
276                    _ => {
277                        if cursor + 16 > payload_end {
278                            return Err(ERR_GLTF_MESHOPT.to_string());
279                        }
280                        deltas.copy_from_slice(&data[cursor..(cursor + 16)]);
281                        cursor += 16;
282                    }
283                }
284                let take_n: usize = (block_count - decoded_in_block).min(16);
285                for delta_val in deltas.iter().take(take_n) {
286                    let next_byte: u8 = last_byte.wrapping_add(meshopt_unzigzag8(*delta_val));
287                    out[(vertex_offset + decoded_in_block) * stride + k] = next_byte;
288                    last_byte = next_byte;
289                    decoded_in_block += 1;
290                }
291            }
292            last_vertex[k] = last_byte;
293        }
294        vertex_offset += block_count;
295    }
296    Ok(out)
297}
298
299/// Decodes a `meshopt` index triangle stream (`EXT_meshopt_compression` `TRIANGLES` mode).
300///
301/// # Arguments
302///
303/// - `&[u8]` - Compressed triangle index stream.
304/// - `usize` - Total index count (must be a multiple of `3`).
305/// - `usize` - Output index stride (`2` for `u16` or `4` for `u32`).
306///
307/// # Returns
308///
309/// - `Result<Vec<u8>, String>` - Decompressed little-endian index buffer bytes.
310pub fn decode_meshopt_index_buffer(
311    data: &[u8],
312    index_count: usize,
313    index_size: usize,
314) -> Result<Vec<u8>, String> {
315    if !index_count.is_multiple_of(3) || (index_size != 2 && index_size != 4) {
316        return Err(ERR_GLTF_MESHOPT.to_string());
317    }
318    if index_count == 0 {
319        return Ok(Vec::new());
320    }
321    let tri_count: usize = index_count / 3;
322    if data.len() < 1 + tri_count + 16 {
323        return Err(ERR_GLTF_MESHOPT.to_string());
324    }
325    let header: u8 = data[0];
326    if (header & 0xf0) != 0xe0 || (header & 0x0f) > 1 {
327        return Err(ERR_GLTF_MESHOPT.to_string());
328    }
329    let code_stream: &[u8] = &data[1..(1 + tri_count)];
330    let data_end: usize = data.len() - 16;
331    let codeaux_table: &[u8] = &data[data_end..];
332    let mut cursor: usize = 1 + tri_count;
333    let mut edge_fifo: [(u32, u32); 16] = [(0, 0); 16];
334    let mut edge_off: usize = 0;
335    let mut vert_fifo: [u32; 16] = [0; 16];
336    let mut vert_off: usize = 0;
337    let mut next_vert: u32 = 0;
338    let mut last_vert: u32 = 0;
339    let mut out: Vec<u8> = Vec::with_capacity(index_count.saturating_mul(index_size));
340    let decode_idx: fn(&[u8], &mut usize, &mut u32, &mut u32) -> Result<u32, String> =
341        |buf: &[u8], pos: &mut usize, next: &mut u32, last: &mut u32| -> Result<u32, String> {
342            let v: u32 = meshopt_read_varint(buf, pos)?;
343            if v == 0 {
344                let res: u32 = *next;
345                *next = next.wrapping_add(1);
346                Ok(res)
347            } else {
348                let d: u32 = meshopt_unzigzag32(v - 1);
349                *last = last.wrapping_add(d);
350                Ok(*last)
351            }
352        };
353    for &code in code_stream.iter() {
354        let fea: usize = usize::from(code >> 4);
355        let fec: usize = usize::from(code & 0x0f);
356        let (a, b, c): (u32, u32, u32) = if fea < 15 {
357            let (ea, eb): (u32, u32) = edge_fifo[(edge_off.wrapping_sub(1 + fea)) & 15];
358            let cv: u32 = if fec == 0 {
359                let res: u32 = next_vert;
360                next_vert = next_vert.wrapping_add(1);
361                vert_fifo[vert_off] = res;
362                vert_off = (vert_off + 1) & 15;
363                res
364            } else if fec < 15 {
365                vert_fifo[(vert_off.wrapping_sub(fec)) & 15]
366            } else {
367                let res: u32 = decode_idx(
368                    &data[..data_end],
369                    &mut cursor,
370                    &mut next_vert,
371                    &mut last_vert,
372                )?;
373                vert_fifo[vert_off] = res;
374                vert_off = (vert_off + 1) & 15;
375                res
376            };
377            edge_fifo[edge_off] = (cv, eb);
378            edge_off = (edge_off + 1) & 15;
379            edge_fifo[edge_off] = (ea, cv);
380            edge_off = (edge_off + 1) & 15;
381            (ea, eb, cv)
382        } else {
383            let codeaux: u8 = if fec < 15 {
384                codeaux_table[fec]
385            } else {
386                if cursor >= data_end {
387                    return Err(ERR_GLTF_MESHOPT.to_string());
388                }
389                let raw: u8 = data[cursor];
390                cursor += 1;
391                raw
392            };
393            let (av, bv, cv): (u32, u32, u32) = if fec == 15 && codeaux == 0 {
394                let a0: u32 = decode_idx(
395                    &data[..data_end],
396                    &mut cursor,
397                    &mut next_vert,
398                    &mut last_vert,
399                )?;
400                let b0: u32 = decode_idx(
401                    &data[..data_end],
402                    &mut cursor,
403                    &mut next_vert,
404                    &mut last_vert,
405                )?;
406                let c0: u32 = decode_idx(
407                    &data[..data_end],
408                    &mut cursor,
409                    &mut next_vert,
410                    &mut last_vert,
411                )?;
412                (a0, b0, c0)
413            } else {
414                let feb: u32 = u32::from(codeaux >> 4);
415                let fec_lo: u32 = u32::from(codeaux & 0x0f);
416                let a0: u32 = next_vert;
417                next_vert = next_vert.wrapping_add(1);
418                let b0: u32 = if feb == 0 {
419                    let res: u32 = next_vert;
420                    next_vert = next_vert.wrapping_add(1);
421                    res
422                } else if feb < 15 {
423                    a0.wrapping_sub(feb)
424                } else {
425                    decode_idx(
426                        &data[..data_end],
427                        &mut cursor,
428                        &mut next_vert,
429                        &mut last_vert,
430                    )?
431                };
432                let c0: u32 = if fec_lo == 0 {
433                    let res: u32 = next_vert;
434                    next_vert = next_vert.wrapping_add(1);
435                    res
436                } else if fec_lo < 15 {
437                    a0.wrapping_sub(fec_lo)
438                } else {
439                    decode_idx(
440                        &data[..data_end],
441                        &mut cursor,
442                        &mut next_vert,
443                        &mut last_vert,
444                    )?
445                };
446                (a0, b0, c0)
447            };
448            vert_fifo[vert_off] = av;
449            vert_off = (vert_off + 1) & 15;
450            vert_fifo[vert_off] = bv;
451            vert_off = (vert_off + 1) & 15;
452            vert_fifo[vert_off] = cv;
453            vert_off = (vert_off + 1) & 15;
454            edge_fifo[edge_off] = (bv, av);
455            edge_off = (edge_off + 1) & 15;
456            edge_fifo[edge_off] = (cv, bv);
457            edge_off = (edge_off + 1) & 15;
458            edge_fifo[edge_off] = (av, cv);
459            edge_off = (edge_off + 1) & 15;
460            (av, bv, cv)
461        };
462        for idx_val in [a, b, c] {
463            if index_size == 2 {
464                out.extend_from_slice(&(idx_val as u16).to_le_bytes());
465            } else {
466                out.extend_from_slice(&idx_val.to_le_bytes());
467            }
468        }
469    }
470    Ok(out)
471}
472
473/// Decodes a `meshopt` index sequence stream (`EXT_meshopt_compression` `INDICES` mode).
474///
475/// # Arguments
476///
477/// - `&[u8]` - Compressed index sequence bytes.
478/// - `usize` - Total index count.
479/// - `usize` - Output index stride (`2` or `4` bytes).
480///
481/// # Returns
482///
483/// - `Result<Vec<u8>, String>` - Decompressed little-endian index buffer bytes.
484pub fn decode_meshopt_index_sequence(
485    data: &[u8],
486    index_count: usize,
487    index_size: usize,
488) -> Result<Vec<u8>, String> {
489    if index_size != 2 && index_size != 4 {
490        return Err(ERR_GLTF_MESHOPT.to_string());
491    }
492    if index_count == 0 {
493        return Ok(Vec::new());
494    }
495    if data.len() < 5 {
496        return Err(ERR_GLTF_MESHOPT.to_string());
497    }
498    let header: u8 = data[0];
499    if (header & 0xf0) != 0xd0 || (header & 0x0f) > 1 {
500        return Err(ERR_GLTF_MESHOPT.to_string());
501    }
502    let payload_end: usize = data.len() - 4;
503    let baseline: u32 = u32::from_le_bytes([
504        data[payload_end],
505        data[payload_end + 1],
506        data[payload_end + 2],
507        data[payload_end + 3],
508    ]);
509    let mut cursor: usize = 1;
510    let mut last: [u32; 2] = [baseline, baseline];
511    let mut out: Vec<u8> = Vec::with_capacity(index_count.saturating_mul(index_size));
512    for _ in 0..index_count {
513        let v: u32 = meshopt_read_varint(&data[..payload_end], &mut cursor)?;
514        let lane: usize = (v & 1) as usize;
515        let delta: u32 = meshopt_unzigzag32(v >> 1);
516        last[lane] = last[lane].wrapping_add(delta);
517        if index_size == 2 {
518            out.extend_from_slice(&(last[lane] as u16).to_le_bytes());
519        } else {
520            out.extend_from_slice(&last[lane].to_le_bytes());
521        }
522    }
523    Ok(out)
524}
525
526/// Applies the `EXT_meshopt_compression` `OCTAHEDRAL` post-decode filter in-place (4-byte `i8x4` or 8-byte `i16x4`).
527///
528/// # Arguments
529///
530/// - `&mut [u8]` - Decompressed attribute buffer.
531/// - `usize` - Element count.
532/// - `usize` - Byte stride (`4` or `8`).
533fn apply_meshopt_filter_octahedral(buf: &mut [u8], count: usize, stride: usize) {
534    if stride == 4 {
535        for idx in 0..count {
536            let base: usize = idx * 4;
537            if base + 4 > buf.len() {
538                break;
539            }
540            let x: f32 = f32::from(buf[base] as i8);
541            let y: f32 = f32::from(buf[base + 1] as i8);
542            let one: f32 = f32::from(buf[base + 2] as i8);
543            let z: f32 = one - x.abs() - y.abs();
544            let t: f32 = (-z).max(0.0);
545            let nx: f32 = x + if x >= 0.0 { -t } else { t };
546            let ny: f32 = y + if y >= 0.0 { -t } else { t };
547            let len: f32 = (nx * nx + ny * ny + z * z).sqrt().max(1e-6);
548            let scale: f32 = 127.0 / len;
549            buf[base] = (nx * scale).round().clamp(-127.0, 127.0) as i8 as u8;
550            buf[base + 1] = (ny * scale).round().clamp(-127.0, 127.0) as i8 as u8;
551            buf[base + 2] = (z * scale).round().clamp(-127.0, 127.0) as i8 as u8;
552        }
553    } else if stride == 8 {
554        for idx in 0..count {
555            let base: usize = idx * 8;
556            if base + 8 > buf.len() {
557                break;
558            }
559            let x: f32 = f32::from(i16::from_le_bytes([buf[base], buf[base + 1]]));
560            let y: f32 = f32::from(i16::from_le_bytes([buf[base + 2], buf[base + 3]]));
561            let one: f32 = f32::from(i16::from_le_bytes([buf[base + 4], buf[base + 5]]));
562            let z: f32 = one - x.abs() - y.abs();
563            let t: f32 = (-z).max(0.0);
564            let nx: f32 = x + if x >= 0.0 { -t } else { t };
565            let ny: f32 = y + if y >= 0.0 { -t } else { t };
566            let len: f32 = (nx * nx + ny * ny + z * z).sqrt().max(1e-6);
567            let scale: f32 = 32_767.0 / len;
568            let qx: i16 = (nx * scale).round().clamp(-32_767.0, 32_767.0) as i16;
569            let qy: i16 = (ny * scale).round().clamp(-32_767.0, 32_767.0) as i16;
570            let qz: i16 = (z * scale).round().clamp(-32_767.0, 32_767.0) as i16;
571            buf[base..(base + 2)].copy_from_slice(&qx.to_le_bytes());
572            buf[(base + 2)..(base + 4)].copy_from_slice(&qy.to_le_bytes());
573            buf[(base + 4)..(base + 6)].copy_from_slice(&qz.to_le_bytes());
574        }
575    }
576}
577
578/// Applies the `EXT_meshopt_compression` `QUATERNION` post-decode filter in-place (`i16x4`, stride `8`).
579///
580/// # Arguments
581///
582/// - `&mut [u8]` - Decompressed quaternion attribute buffer.
583/// - `usize` - Element count.
584fn apply_meshopt_filter_quaternion(buf: &mut [u8], count: usize) {
585    let inv_sqrt2: f32 = 1.0 / SQRT_2;
586    for idx in 0..count {
587        let base: usize = idx * 8;
588        if base + 8 > buf.len() {
589            break;
590        }
591        let i0: i16 = i16::from_le_bytes([buf[base], buf[base + 1]]);
592        let i1: i16 = i16::from_le_bytes([buf[base + 2], buf[base + 3]]);
593        let i2: i16 = i16::from_le_bytes([buf[base + 4], buf[base + 5]]);
594        let i3: i16 = i16::from_le_bytes([buf[base + 6], buf[base + 7]]);
595        let max_comp: usize = (i3 & 3) as usize;
596        let denom: f32 = f32::from((i3 >> 2).max(1));
597        let scale: f32 = inv_sqrt2 / denom;
598        let x: f32 = f32::from(i0) * scale;
599        let y: f32 = f32::from(i1) * scale;
600        let z: f32 = f32::from(i2) * scale;
601        let w: f32 = (1.0 - x * x - y * y - z * z).max(0.0).sqrt();
602        let vals: [f32; 4] = [x, y, z, w];
603        let mut out_q: [i16; 4] = [0; 4];
604        for (lane, slot) in out_q.iter_mut().enumerate() {
605            let src_idx: usize = (lane + 3 - max_comp) & 3;
606            *slot = (vals[src_idx] * 32_767.0)
607                .round()
608                .clamp(-32_767.0, 32_767.0) as i16;
609        }
610        for (lane, qv) in out_q.iter().enumerate() {
611            buf[(base + lane * 2)..(base + lane * 2 + 2)].copy_from_slice(&qv.to_le_bytes());
612        }
613    }
614}
615
616/// Applies the `EXT_meshopt_compression` `EXPONENTIAL` post-decode filter in-place (`stride % 4 == 0`).
617///
618/// # Arguments
619///
620/// - `&mut [u8]` - Decompressed exponential-encoded float buffer.
621/// - `usize` - Element count.
622/// - `usize` - Byte stride (multiple of 4).
623fn apply_meshopt_filter_exponential(buf: &mut [u8], count: usize, stride: usize) {
624    let lanes: usize = count.saturating_mul(stride / 4);
625    for idx in 0..lanes {
626        let base: usize = idx * 4;
627        if base + 4 > buf.len() {
628            break;
629        }
630        let packed: u32 =
631            u32::from_le_bytes([buf[base], buf[base + 1], buf[base + 2], buf[base + 3]]);
632        let exp: i32 = (packed as i32) >> 24;
633        let mantissa: i32 = ((packed << 8) as i32) >> 8;
634        let val: f32 = (mantissa as f32) * 2.0f32.powi(exp);
635        buf[base..(base + 4)].copy_from_slice(&val.to_le_bytes());
636    }
637}
638
639/// Pre-decodes all `bufferViews` carrying `extensions.EXT_meshopt_compression` into uncompressed byte slices.
640///
641/// # Arguments
642///
643/// - `&Value` - Root glTF JSON object.
644/// - `&[Cow<'_, [u8]>]` - Loaded raw buffer slices (zero-copy for GLB binary chunk).
645///
646/// # Returns
647///
648/// - `Result<HashMap<usize, Vec<u8>>, String>` - Map from `bufferView` index to decompressed payload.
649fn decode_meshopt_buffer_views(
650    root: &Value,
651    buffers: &[Cow<'_, [u8]>],
652) -> Result<HashMap<usize, Vec<u8>>, String> {
653    let mut decoded: HashMap<usize, Vec<u8>> = HashMap::new();
654    let Some(views) = root.get(KEY_BUFFER_VIEWS).and_then(Value::as_array) else {
655        return Ok(decoded);
656    };
657    for (view_idx, view) in views.iter().enumerate() {
658        let Some(ext) = view
659            .get(KEY_EXTENSIONS)
660            .and_then(|e: &Value| e.get(GLTF_EXT_MESHOPT))
661        else {
662            continue;
663        };
664        let buf_idx: usize = ext
665            .get(KEY_BUFFER)
666            .and_then(Value::as_u64)
667            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
668        let byte_offset: usize = ext
669            .get(KEY_BYTE_OFFSET)
670            .and_then(Value::as_u64)
671            .unwrap_or(0) as usize;
672        let byte_length: usize = ext
673            .get(KEY_BYTE_LENGTH)
674            .and_then(Value::as_u64)
675            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
676        let byte_stride: usize = ext
677            .get(KEY_BYTE_STRIDE)
678            .and_then(Value::as_u64)
679            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
680        let count: usize = ext
681            .get(KEY_COUNT)
682            .and_then(Value::as_u64)
683            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
684        let mode: &str = ext
685            .get(KEY_MODE)
686            .and_then(Value::as_str)
687            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())?;
688        let raw_buf: &[u8] = buffers
689            .get(buf_idx)
690            .map(Cow::as_ref)
691            .ok_or_else(|| ERR_GLTF_MESHOPT.to_string())?;
692        let end: usize = byte_offset.saturating_add(byte_length);
693        if end > raw_buf.len() {
694            return Err(ERR_GLTF_MESHOPT.to_string());
695        }
696        let compressed: &[u8] = &raw_buf[byte_offset..end];
697        let mut raw_out: Vec<u8> = match mode {
698            MESHOPT_MODE_ATTRIBUTES => {
699                decode_meshopt_vertex_buffer(compressed, count, byte_stride)?
700            }
701            MESHOPT_MODE_TRIANGLES => decode_meshopt_index_buffer(compressed, count, byte_stride)?,
702            MESHOPT_MODE_INDICES => decode_meshopt_index_sequence(compressed, count, byte_stride)?,
703            _ => return Err(ERR_GLTF_MESHOPT.to_string()),
704        };
705        if let Some(filter) = ext.get(KEY_FILTER).and_then(Value::as_str) {
706            match filter {
707                MESHOPT_FILTER_OCTAHEDRAL => {
708                    apply_meshopt_filter_octahedral(&mut raw_out, count, byte_stride);
709                }
710                MESHOPT_FILTER_QUATERNION if byte_stride == 8 => {
711                    apply_meshopt_filter_quaternion(&mut raw_out, count);
712                }
713                MESHOPT_FILTER_EXPONENTIAL if byte_stride.is_multiple_of(4) => {
714                    apply_meshopt_filter_exponential(&mut raw_out, count, byte_stride);
715                }
716                _ => {}
717            }
718        }
719        let _: Option<Vec<u8>> = decoded.insert(view_idx, raw_out);
720    }
721    Ok(decoded)
722}
723
724/// Resolves a `bufferViews[view_idx]` byte slice (using zero-copy slices or pre-decoded `EXT_meshopt_compression` data) and optional `byteStride`.
725///
726/// # Arguments
727///
728/// - `&Value` - Root glTF JSON object.
729/// - `&'a [Cow<'a, [u8]>]` - Loaded raw buffer slices.
730/// - `&'a HashMap<usize, Vec<u8>>` - Pre-decoded `EXT_meshopt_compression` buffer view map.
731/// - `usize` - Index into `bufferViews`.
732///
733/// # Returns
734///
735/// - `Result<(&'a [u8], Option<usize>), String>` - Validated slice and optional stride.
736fn resolve_buffer_view<'a>(
737    root: &Value,
738    buffers: &'a [Cow<'a, [u8]>],
739    meshopt_views: &'a HashMap<usize, Vec<u8>>,
740    view_idx: usize,
741) -> Result<(&'a [u8], Option<usize>), String> {
742    let view: &Value = root
743        .get(KEY_BUFFER_VIEWS)
744        .and_then(Value::as_array)
745        .and_then(|arr: &Vec<Value>| arr.get(view_idx))
746        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
747    let byte_stride: Option<usize> = view
748        .get(KEY_BYTE_STRIDE)
749        .and_then(Value::as_u64)
750        .map(|val: u64| val as usize);
751    if let Some(decoded_buf) = meshopt_views.get(&view_idx) {
752        return Ok((decoded_buf.as_slice(), byte_stride));
753    }
754    let buf_idx: usize = view
755        .get(KEY_BUFFER)
756        .and_then(Value::as_u64)
757        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
758    let byte_offset: usize = view
759        .get(KEY_BYTE_OFFSET)
760        .and_then(Value::as_u64)
761        .unwrap_or(0) as usize;
762    let byte_length: usize = view
763        .get(KEY_BYTE_LENGTH)
764        .and_then(Value::as_u64)
765        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
766    let buf: &[u8] = buffers
767        .get(buf_idx)
768        .map(Cow::as_ref)
769        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
770    let end: usize = byte_offset.saturating_add(byte_length);
771    if end > buf.len() {
772        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
773    }
774    Ok((&buf[byte_offset..end], byte_stride))
775}
776
777/// Decodes a glTF 2.0 accessor (including `KHR_mesh_quantization`, `EXT_meshopt_compression`, and `sparse` overrides) into flat `f32` values and component count.
778///
779/// # Arguments
780///
781/// - `&Value` - Root glTF JSON object.
782/// - `&[Cow<'_, [u8]>]` - Loaded raw buffer slices.
783/// - `&HashMap<usize, Vec<u8>>` - Pre-decoded `EXT_meshopt_compression` view map.
784/// - `usize` - Index into `accessors`.
785///
786/// # Returns
787///
788/// - `Result<(Vec<f32>, usize, usize), String>` - Tuple `(flat_floats, element_count, components_per_element)`.
789fn decode_accessor_f32(
790    root: &Value,
791    buffers: &[Cow<'_, [u8]>],
792    meshopt_views: &HashMap<usize, Vec<u8>>,
793    accessor_idx: usize,
794) -> Result<(Vec<f32>, usize, usize), String> {
795    let acc: &Value = root
796        .get(KEY_ACCESSORS)
797        .and_then(Value::as_array)
798        .and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
799        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
800    let comp_type: u32 = acc
801        .get(KEY_COMPONENT_TYPE)
802        .and_then(Value::as_u64)
803        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
804    let count: usize = acc
805        .get(KEY_COUNT)
806        .and_then(Value::as_u64)
807        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
808    let type_str: &str = acc
809        .get(KEY_TYPE)
810        .and_then(Value::as_str)
811        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
812    let comps: usize = gltf_type_components(type_str);
813    let comp_size: usize = gltf_component_byte_size(comp_type);
814    if comps == 0 || comp_size == 0 {
815        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
816    }
817    let normalized: bool = acc
818        .get(KEY_NORMALIZED)
819        .and_then(Value::as_bool)
820        .unwrap_or(false);
821    let mut out: Vec<f32> = vec![0.0; count.saturating_mul(comps)];
822    if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
823        let (view_slice, stride_opt): (&[u8], Option<usize>) =
824            resolve_buffer_view(root, buffers, meshopt_views, view_idx as usize)?;
825        let acc_off: usize = acc
826            .get(KEY_BYTE_OFFSET)
827            .and_then(Value::as_u64)
828            .unwrap_or(0) as usize;
829        let elem_bytes: usize = comps * comp_size;
830        let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
831        for elem_idx in 0..count {
832            let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
833            for c_idx in 0..comps {
834                let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
835                out[elem_idx * comps + c_idx] =
836                    read_gltf_scalar_f32(view_slice, off, comp_type, normalized)?;
837            }
838        }
839    }
840    if let Some(sparse) = acc.get(KEY_SPARSE) {
841        let sparse_count: usize =
842            sparse.get(KEY_COUNT).and_then(Value::as_u64).unwrap_or(0) as usize;
843        if sparse_count > 0 {
844            let idx_obj: &Value = sparse
845                .get(KEY_INDICES)
846                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
847            let val_obj: &Value = sparse
848                .get(KEY_VALUES)
849                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
850            let idx_view_id: usize = idx_obj
851                .get(KEY_BUFFER_VIEW)
852                .and_then(Value::as_u64)
853                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
854                as usize;
855            let idx_off: usize = idx_obj
856                .get(KEY_BYTE_OFFSET)
857                .and_then(Value::as_u64)
858                .unwrap_or(0) as usize;
859            let idx_comp_type: u32 = idx_obj
860                .get(KEY_COMPONENT_TYPE)
861                .and_then(Value::as_u64)
862                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
863                as u32;
864            let idx_step: usize = gltf_component_byte_size(idx_comp_type);
865            let val_view_id: usize = val_obj
866                .get(KEY_BUFFER_VIEW)
867                .and_then(Value::as_u64)
868                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
869                as usize;
870            let val_off: usize = val_obj
871                .get(KEY_BYTE_OFFSET)
872                .and_then(Value::as_u64)
873                .unwrap_or(0) as usize;
874            let (idx_slice, _): (&[u8], Option<usize>) =
875                resolve_buffer_view(root, buffers, meshopt_views, idx_view_id)?;
876            let (val_slice, _): (&[u8], Option<usize>) =
877                resolve_buffer_view(root, buffers, meshopt_views, val_view_id)?;
878            let val_elem_bytes: usize = comps * comp_size;
879            for sparse_i in 0..sparse_count {
880                let target_idx: usize = read_gltf_scalar_u32(
881                    idx_slice,
882                    idx_off.saturating_add(sparse_i.saturating_mul(idx_step)),
883                    idx_comp_type,
884                )? as usize;
885                if target_idx >= count {
886                    return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
887                }
888                let src_base: usize =
889                    val_off.saturating_add(sparse_i.saturating_mul(val_elem_bytes));
890                for c_idx in 0..comps {
891                    let off: usize = src_base.saturating_add(c_idx.saturating_mul(comp_size));
892                    out[target_idx * comps + c_idx] =
893                        read_gltf_scalar_f32(val_slice, off, comp_type, normalized)?;
894                }
895            }
896        }
897    }
898    Ok((out, count, comps))
899}
900
901/// Decodes a glTF 2.0 scalar or vector unsigned-integer accessor (indices or `JOINTS_n`).
902///
903/// # Arguments
904///
905/// - `&Value` - Root glTF JSON object.
906/// - `&[Cow<'_, [u8]>]` - Loaded raw buffer slices.
907/// - `&HashMap<usize, Vec<u8>>` - Pre-decoded `EXT_meshopt_compression` view map.
908/// - `usize` - Index into `accessors`.
909///
910/// # Returns
911///
912/// - `Result<(Vec<u32>, usize, usize), String>` - Tuple `(flat_u32, element_count, components_per_element)`.
913fn decode_accessor_u32(
914    root: &Value,
915    buffers: &[Cow<'_, [u8]>],
916    meshopt_views: &HashMap<usize, Vec<u8>>,
917    accessor_idx: usize,
918) -> Result<(Vec<u32>, usize, usize), String> {
919    let acc: &Value = root
920        .get(KEY_ACCESSORS)
921        .and_then(Value::as_array)
922        .and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
923        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
924    let comp_type: u32 = acc
925        .get(KEY_COMPONENT_TYPE)
926        .and_then(Value::as_u64)
927        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
928    let count: usize = acc
929        .get(KEY_COUNT)
930        .and_then(Value::as_u64)
931        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
932    let type_str: &str = acc
933        .get(KEY_TYPE)
934        .and_then(Value::as_str)
935        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
936    let comps: usize = gltf_type_components(type_str);
937    let comp_size: usize = gltf_component_byte_size(comp_type);
938    if comps == 0 || comp_size == 0 {
939        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
940    }
941    let mut out: Vec<u32> = vec![0u32; count.saturating_mul(comps)];
942    if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
943        let (view_slice, stride_opt): (&[u8], Option<usize>) =
944            resolve_buffer_view(root, buffers, meshopt_views, view_idx as usize)?;
945        let acc_off: usize = acc
946            .get(KEY_BYTE_OFFSET)
947            .and_then(Value::as_u64)
948            .unwrap_or(0) as usize;
949        let elem_bytes: usize = comps * comp_size;
950        let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
951        for elem_idx in 0..count {
952            let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
953            for c_idx in 0..comps {
954                let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
955                out[elem_idx * comps + c_idx] = read_gltf_scalar_u32(view_slice, off, comp_type)?;
956            }
957        }
958    }
959    Ok((out, count, comps))
960}
961
962/// Decodes a `data:...;base64,...` URI into raw bytes.
963///
964/// # Arguments
965///
966/// - `&str` - RFC 2397 data URI string.
967///
968/// # Returns
969///
970/// - `Result<Vec<u8>, String>` - Decoded payload bytes or error.
971fn decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
972    let marker_pos: usize = uri
973        .find(GLTF_BASE64_MARKER)
974        .ok_or_else(|| ERR_GLTF_URI_RESOLVE.to_string())?;
975    let b64_str: &str = &uri[(marker_pos + GLTF_BASE64_MARKER.len())..];
976    decode_base64(b64_str)
977}
978
979/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 2]`.
980///
981/// # Arguments
982///
983/// - `Option<&Value>` - Optional JSON array value.
984/// - `[f32; 2]` - Default fallback values.
985///
986/// # Returns
987///
988/// - `[f32; 2]` - Parsed 2-element float array.
989#[must_use]
990fn json_f32_2(value: Option<&Value>, default: [f32; 2]) -> [f32; 2] {
991    let Some(arr) = value.and_then(Value::as_array) else {
992        return default;
993    };
994    if arr.len() < 2 {
995        return default;
996    }
997    [
998        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
999        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
1000    ]
1001}
1002
1003/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 3]`.
1004///
1005/// # Arguments
1006///
1007/// - `Option<&Value>` - Optional JSON array value.
1008/// - `[f32; 3]` - Default fallback values.
1009///
1010/// # Returns
1011///
1012/// - `[f32; 3]` - Parsed 3-element float array.
1013#[must_use]
1014fn json_f32_3(value: Option<&Value>, default: [f32; 3]) -> [f32; 3] {
1015    let Some(arr) = value.and_then(Value::as_array) else {
1016        return default;
1017    };
1018    if arr.len() < 3 {
1019        return default;
1020    }
1021    [
1022        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
1023        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
1024        arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
1025    ]
1026}
1027
1028/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 4]`.
1029///
1030/// # Arguments
1031///
1032/// - `Option<&Value>` - Optional JSON array value.
1033/// - `[f32; 4]` - Default fallback values.
1034///
1035/// # Returns
1036///
1037/// - `[f32; 4]` - Parsed 4-element float array.
1038#[must_use]
1039fn json_f32_4(value: Option<&Value>, default: [f32; 4]) -> [f32; 4] {
1040    let Some(arr) = value.and_then(Value::as_array) else {
1041        return default;
1042    };
1043    if arr.len() < 4 {
1044        return default;
1045    }
1046    [
1047        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
1048        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
1049        arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
1050        arr[3].as_f64().unwrap_or(f64::from(default[3])) as f32,
1051    ]
1052}
1053
1054/// Parses a glTF textureInfo object including `KHR_texture_transform` overrides.
1055///
1056/// # Arguments
1057///
1058/// - `Option<&Value>` - Optional texture info JSON object.
1059///
1060/// # Returns
1061///
1062/// - `Option<TextureSlot3D>` - Parsed texture slot when `index` is present.
1063#[must_use]
1064fn parse_texture_slot(info_opt: Option<&Value>) -> Option<TextureSlot3D> {
1065    let info: &Value = info_opt?;
1066    let tex_index: u32 = info.get(KEY_INDEX).and_then(Value::as_u64)? as u32;
1067    let mut tex_coord: u8 = info.get(KEY_TEX_COORD).and_then(Value::as_u64).unwrap_or(0) as u8;
1068    let mut transform: TextureTransform3D = TextureTransform3D::default();
1069    if let Some(tt) = info
1070        .get(KEY_EXTENSIONS)
1071        .and_then(|ext: &Value| ext.get(GLTF_EXT_TEX_TRANSFORM))
1072    {
1073        let offset_arr: [f32; 2] = json_f32_2(tt.get(KEY_OFFSET), [0.0, 0.0]);
1074        let rotation: f32 = tt.get(KEY_ROTATION).and_then(Value::as_f64).unwrap_or(0.0) as f32;
1075        let scale_arr: [f32; 2] = json_f32_2(tt.get(KEY_SCALE), [1.0, 1.0]);
1076        if let Some(override_uv) = tt.get(KEY_TEX_COORD).and_then(Value::as_u64) {
1077            tex_coord = override_uv as u8;
1078        }
1079        transform = TextureTransform3D::from_trs(
1080            Vec2::from_array(offset_arr),
1081            rotation,
1082            Vec2::from_array(scale_arr),
1083        );
1084    }
1085    Some(TextureSlot3D {
1086        texture_index: tex_index,
1087        tex_coord,
1088        transform,
1089    })
1090}
1091
1092/// Parses a single glTF 2.0 material entry into a 1:1 `PrincipledMaterial3D` with all KHR PBR extensions.
1093///
1094/// # Arguments
1095///
1096/// - `&Value` - Material JSON object.
1097/// - `usize` - Material index used for default fallback naming.
1098///
1099/// # Returns
1100///
1101/// - `PrincipledMaterial3D` - Populated Principled BSDF material.
1102#[must_use]
1103fn parse_principled_material(mat_val: &Value, mat_idx: usize) -> PrincipledMaterial3D {
1104    let mut mat: PrincipledMaterial3D = PrincipledMaterial3D::default();
1105    let name: String = mat_val
1106        .get(KEY_NAME)
1107        .and_then(Value::as_str)
1108        .map(str::to_string)
1109        .unwrap_or_else(|| format!("material_{mat_idx}"));
1110    mat.set_name(name);
1111    if let Some(pbr) = mat_val.get(KEY_PBR_MR) {
1112        mat.set_base_color_factor(json_f32_4(
1113            pbr.get(KEY_BASE_COLOR_FACTOR),
1114            [1.0, 1.0, 1.0, 1.0],
1115        ));
1116        mat.set_base_color_texture(parse_texture_slot(pbr.get(KEY_BASE_COLOR_TEX)));
1117        let metallic: f32 = pbr
1118            .get(KEY_METALLIC_FACTOR)
1119            .and_then(Value::as_f64)
1120            .unwrap_or(1.0) as f32;
1121        let roughness: f32 = pbr
1122            .get(KEY_ROUGHNESS_FACTOR)
1123            .and_then(Value::as_f64)
1124            .unwrap_or(1.0) as f32;
1125        mat.set_metallic_factor(metallic.clamp(0.0, 1.0));
1126        mat.set_roughness_factor(roughness.clamp(0.04, 1.0));
1127        mat.set_metallic_roughness_texture(parse_texture_slot(pbr.get(KEY_MR_TEX)));
1128    }
1129    if let Some(norm_obj) = mat_val.get(KEY_NORMAL_TEX) {
1130        mat.set_normal_texture(parse_texture_slot(Some(norm_obj)));
1131        let scale: f32 = norm_obj
1132            .get(KEY_SCALE)
1133            .and_then(Value::as_f64)
1134            .unwrap_or(1.0) as f32;
1135        mat.set_normal_scale(scale);
1136    }
1137    if let Some(occ_obj) = mat_val.get(KEY_OCCLUSION_TEX) {
1138        mat.set_occlusion_texture(parse_texture_slot(Some(occ_obj)));
1139        let strength: f32 = occ_obj
1140            .get(KEY_STRENGTH)
1141            .and_then(Value::as_f64)
1142            .unwrap_or(1.0) as f32;
1143        mat.set_occlusion_strength(strength.clamp(0.0, 1.0));
1144    }
1145    mat.set_emissive_factor(json_f32_3(
1146        mat_val.get(KEY_EMISSIVE_FACTOR),
1147        [0.0, 0.0, 0.0],
1148    ));
1149    mat.set_emissive_texture(parse_texture_slot(mat_val.get(KEY_EMISSIVE_TEX)));
1150    if let Some(alpha_str) = mat_val.get(KEY_ALPHA_MODE).and_then(Value::as_str) {
1151        let mode: AlphaMode3D = if alpha_str == ALPHA_MODE_MASK {
1152            AlphaMode3D::Mask
1153        } else if alpha_str == ALPHA_MODE_BLEND {
1154            AlphaMode3D::Blend
1155        } else {
1156            AlphaMode3D::Opaque
1157        };
1158        mat.set_alpha_mode(mode);
1159    }
1160    if let Some(cutoff) = mat_val.get(KEY_ALPHA_CUTOFF).and_then(Value::as_f64) {
1161        mat.set_alpha_cutoff(cutoff as f32);
1162    }
1163    if let Some(ds) = mat_val.get(KEY_DOUBLE_SIDED).and_then(Value::as_bool) {
1164        mat.set_double_sided(ds);
1165    }
1166    if let Some(ext) = mat_val.get(KEY_EXTENSIONS) {
1167        if let Some(em_ext) = ext.get(GLTF_EXT_EMISSIVE_STRENGTH)
1168            && let Some(val) = em_ext.get(KEY_EMISSIVE_STRENGTH).and_then(Value::as_f64)
1169        {
1170            mat.set_emissive_strength((val as f32).max(0.0));
1171        }
1172        if let Some(ior_ext) = ext.get(GLTF_EXT_IOR)
1173            && let Some(val) = ior_ext.get("ior").and_then(Value::as_f64)
1174        {
1175            mat.set_ior((val as f32).max(1.0));
1176        }
1177        if let Some(spec_ext) = ext.get(GLTF_EXT_SPECULAR) {
1178            if let Some(sf) = spec_ext.get(KEY_SPECULAR_FACTOR).and_then(Value::as_f64) {
1179                mat.set_specular_factor((sf as f32).clamp(0.0, 1.0));
1180            }
1181            mat.set_specular_color_factor(json_f32_3(
1182                spec_ext.get(KEY_SPECULAR_COLOR_FACTOR),
1183                [1.0, 1.0, 1.0],
1184            ));
1185            mat.set_specular_texture(parse_texture_slot(spec_ext.get(KEY_SPECULAR_TEX)));
1186            mat.set_specular_color_texture(parse_texture_slot(
1187                spec_ext.get(KEY_SPECULAR_COLOR_TEX),
1188            ));
1189        }
1190        if let Some(cc_ext) = ext.get(GLTF_EXT_CLEARCOAT) {
1191            if let Some(cf) = cc_ext.get(KEY_CLEARCOAT_FACTOR).and_then(Value::as_f64) {
1192                mat.set_clearcoat_factor((cf as f32).clamp(0.0, 1.0));
1193            }
1194            if let Some(cr) = cc_ext.get(KEY_CLEARCOAT_ROUGHNESS).and_then(Value::as_f64) {
1195                mat.set_clearcoat_roughness_factor((cr as f32).clamp(0.0, 1.0));
1196            }
1197            mat.set_clearcoat_texture(parse_texture_slot(cc_ext.get(KEY_CLEARCOAT_TEX)));
1198            mat.set_clearcoat_roughness_texture(parse_texture_slot(
1199                cc_ext.get(KEY_CLEARCOAT_ROUGH_TEX),
1200            ));
1201            mat.set_clearcoat_normal_texture(parse_texture_slot(
1202                cc_ext.get(KEY_CLEARCOAT_NORM_TEX),
1203            ));
1204        }
1205        if let Some(tr_ext) = ext.get(GLTF_EXT_TRANSMISSION) {
1206            if let Some(tf) = tr_ext.get(KEY_TRANSMISSION_FACTOR).and_then(Value::as_f64) {
1207                mat.set_transmission_factor((tf as f32).clamp(0.0, 1.0));
1208            }
1209            mat.set_transmission_texture(parse_texture_slot(tr_ext.get(KEY_TRANSMISSION_TEX)));
1210        }
1211        if let Some(vol_ext) = ext.get(GLTF_EXT_VOLUME) {
1212            if let Some(th) = vol_ext.get(KEY_THICKNESS_FACTOR).and_then(Value::as_f64) {
1213                mat.set_thickness_factor((th as f32).max(0.0));
1214            }
1215            if let Some(ad) = vol_ext.get(KEY_ATTENUATION_DIST).and_then(Value::as_f64) {
1216                mat.set_attenuation_distance((ad as f32).max(1e-4));
1217            }
1218            mat.set_attenuation_color(json_f32_3(
1219                vol_ext.get(KEY_ATTENUATION_COLOR),
1220                [1.0, 1.0, 1.0],
1221            ));
1222        }
1223        if let Some(sh_ext) = ext.get(GLTF_EXT_SHEEN) {
1224            mat.set_sheen_color_factor(json_f32_3(sh_ext.get(KEY_SHEEN_COLOR), [0.0, 0.0, 0.0]));
1225            if let Some(sr) = sh_ext.get(KEY_SHEEN_ROUGHNESS).and_then(Value::as_f64) {
1226                mat.set_sheen_roughness_factor((sr as f32).clamp(0.0, 1.0));
1227            }
1228            mat.set_sheen_color_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_COLOR_TEX)));
1229            mat.set_sheen_roughness_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_ROUGH_TEX)));
1230        }
1231        if ext.get(GLTF_EXT_UNLIT).is_some() {
1232            mat.set_unlit(true);
1233        }
1234        if let Some(aniso_ext) = ext.get(GLTF_EXT_ANISOTROPY)
1235            && let Some(strength) = aniso_ext
1236                .get(KEY_ANISOTROPY_STRENGTH)
1237                .and_then(Value::as_f64)
1238        {
1239            let clamped: f32 = (strength as f32).clamp(0.0, 1.0);
1240            if clamped > 0.0 && ext.get(GLTF_EXT_SPECULAR).is_none() {
1241                mat.set_specular_factor(
1242                    (mat.get_specular_factor() + clamped * 0.25).clamp(0.0, 1.5),
1243                );
1244            }
1245        }
1246        if let Some(iri_ext) = ext.get(GLTF_EXT_IRIDESCENCE) {
1247            let factor: f32 = iri_ext
1248                .get(KEY_IRIDESCENCE_FACTOR)
1249                .and_then(Value::as_f64)
1250                .unwrap_or(0.0) as f32;
1251            let iri_ior: f32 = iri_ext
1252                .get(KEY_IRIDESCENCE_IOR)
1253                .and_then(Value::as_f64)
1254                .unwrap_or(1.3) as f32;
1255            if factor > 0.0 {
1256                if ext.get(GLTF_EXT_IOR).is_none() {
1257                    mat.set_ior(iri_ior.max(1.0));
1258                }
1259                if ext.get(GLTF_EXT_SHEEN).is_none() {
1260                    let clamped: f32 = factor.clamp(0.0, 1.0);
1261                    mat.set_sheen_color_factor([clamped * 0.65, clamped * 0.85, clamped]);
1262                    mat.set_sheen_roughness_factor(0.25);
1263                }
1264            }
1265        }
1266    }
1267    mat
1268}
1269
1270/// Extracts `KHR_materials_anisotropy` and `KHR_materials_iridescence` extension records from a single glTF material JSON object.
1271///
1272/// # Arguments
1273///
1274/// - `&Value` - Material JSON object.
1275/// - `usize` - Material index used for fallback naming.
1276///
1277/// # Returns
1278///
1279/// - `GltfMaterialExtensionData` - Parsed anisotropy and iridescence parameters.
1280#[must_use]
1281fn parse_material_extension_record(mat_val: &Value, mat_idx: usize) -> GltfMaterialExtensionData {
1282    let name: String = mat_val
1283        .get(KEY_NAME)
1284        .and_then(Value::as_str)
1285        .map(str::to_string)
1286        .unwrap_or_else(|| format!("material_{mat_idx}"));
1287    let mut data: GltfMaterialExtensionData = GltfMaterialExtensionData {
1288        name,
1289        anisotropy_strength: 0.0,
1290        anisotropy_rotation: 0.0,
1291        anisotropy_texture: None,
1292        iridescence_factor: 0.0,
1293        iridescence_ior: 1.3,
1294        iridescence_thickness_min: 100.0,
1295        iridescence_thickness_max: 400.0,
1296        iridescence_texture: None,
1297        iridescence_thickness_texture: None,
1298    };
1299    if let Some(ext) = mat_val.get(KEY_EXTENSIONS) {
1300        if let Some(aniso_ext) = ext.get(GLTF_EXT_ANISOTROPY) {
1301            if let Some(s) = aniso_ext
1302                .get(KEY_ANISOTROPY_STRENGTH)
1303                .and_then(Value::as_f64)
1304            {
1305                data.set_anisotropy_strength((s as f32).clamp(0.0, 1.0));
1306            }
1307            if let Some(r) = aniso_ext
1308                .get(KEY_ANISOTROPY_ROTATION)
1309                .and_then(Value::as_f64)
1310            {
1311                data.set_anisotropy_rotation(r as f32);
1312            }
1313            data.set_anisotropy_texture(parse_texture_slot(aniso_ext.get(KEY_ANISOTROPY_TEX)));
1314        }
1315        if let Some(iri_ext) = ext.get(GLTF_EXT_IRIDESCENCE) {
1316            if let Some(f) = iri_ext.get(KEY_IRIDESCENCE_FACTOR).and_then(Value::as_f64) {
1317                data.set_iridescence_factor((f as f32).clamp(0.0, 1.0));
1318            }
1319            if let Some(ior) = iri_ext.get(KEY_IRIDESCENCE_IOR).and_then(Value::as_f64) {
1320                data.set_iridescence_ior((ior as f32).max(1.0));
1321            }
1322            if let Some(tmin) = iri_ext
1323                .get(KEY_IRIDESCENCE_THICK_MIN)
1324                .and_then(Value::as_f64)
1325            {
1326                data.set_iridescence_thickness_min((tmin as f32).max(0.0));
1327            }
1328            if let Some(tmax) = iri_ext
1329                .get(KEY_IRIDESCENCE_THICK_MAX)
1330                .and_then(Value::as_f64)
1331            {
1332                data.set_iridescence_thickness_max((tmax as f32).max(0.0));
1333            }
1334            data.set_iridescence_texture(parse_texture_slot(iri_ext.get(KEY_IRIDESCENCE_TEX)));
1335            data.set_iridescence_thickness_texture(parse_texture_slot(
1336                iri_ext.get(KEY_IRIDESCENCE_THICK_TEX),
1337            ));
1338        }
1339    }
1340    data
1341}
1342
1343/// Parses all `KHR_materials_anisotropy` and `KHR_materials_iridescence` extension blocks from a glTF 2.0 JSON document.
1344///
1345/// # Arguments
1346///
1347/// - `&str` - UTF-8 glTF 2.0 JSON document text.
1348///
1349/// # Returns
1350///
1351/// - `Result<Vec<GltfMaterialExtensionData>, String>` - Per-material extension parameter table aligned with `materials`.
1352pub fn parse_gltf_material_extensions(
1353    json_source: &str,
1354) -> Result<Vec<GltfMaterialExtensionData>, String> {
1355    let root: Value = from_str::<Value>(json_source)
1356        .ok()
1357        .ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
1358    let mut out: Vec<GltfMaterialExtensionData> = Vec::new();
1359    if let Some(mats_arr) = root.get(KEY_MATERIALS).and_then(Value::as_array) {
1360        out.reserve(mats_arr.len());
1361        for (mat_idx, mat_val) in mats_arr.iter().enumerate() {
1362            out.push(parse_material_extension_record(mat_val, mat_idx));
1363        }
1364    }
1365    Ok(out)
1366}
1367
1368/// Converts primitive vertex index stream into triangle triplets respecting glTF `TRIANGLES`, `TRIANGLE_STRIP`, or `TRIANGLE_FAN`.
1369///
1370/// # Arguments
1371///
1372/// - `&[u32]` - Raw vertex index list.
1373/// - `u32` - glTF primitive mode constant (`4`, `5`, or `6`).
1374///
1375/// # Returns
1376///
1377/// - `Vec<[u32; 3]>` - Triangle index triplets.
1378#[must_use]
1379fn assemble_primitive_triangles(raw_indices: &[u32], mode: u32) -> Vec<[u32; 3]> {
1380    let mut tris: Vec<[u32; 3]> = Vec::new();
1381    match mode {
1382        GLTF_MODE_TRIANGLE_STRIP => {
1383            if raw_indices.len() >= 3 {
1384                tris.reserve(raw_indices.len() - 2);
1385                for idx in 0..(raw_indices.len() - 2) {
1386                    let i0: u32 = raw_indices[idx];
1387                    let i1: u32 = raw_indices[idx + 1];
1388                    let i2: u32 = raw_indices[idx + 2];
1389                    if i0 == i1 || i1 == i2 || i0 == i2 {
1390                        continue;
1391                    }
1392                    if (idx & 1) == 0 {
1393                        tris.push([i0, i1, i2]);
1394                    } else {
1395                        tris.push([i1, i0, i2]);
1396                    }
1397                }
1398            }
1399        }
1400        GLTF_MODE_TRIANGLE_FAN => {
1401            if raw_indices.len() >= 3 {
1402                tris.reserve(raw_indices.len() - 2);
1403                let anchor: u32 = raw_indices[0];
1404                for idx in 1..(raw_indices.len() - 1) {
1405                    tris.push([anchor, raw_indices[idx], raw_indices[idx + 1]]);
1406                }
1407            }
1408        }
1409        _ => {
1410            tris.reserve(raw_indices.len() / 3);
1411            for tri in raw_indices.as_chunks::<3>().0 {
1412                tris.push(*tri);
1413            }
1414        }
1415    }
1416    tris
1417}
1418
1419/// Parses a single glTF 2.0 JSON document together with optional GLB binary buffer chunk and URI resolver.
1420///
1421/// # Arguments
1422///
1423/// - `&str` - UTF-8 glTF 2.0 JSON document text.
1424/// - `Option<&[u8]>` - Optional GLB `BIN\0` chunk backing `buffers[0]`.
1425/// - `Option<&dyn GltfBufferResolver>` - Optional external buffer/image URI resolver.
1426///
1427/// # Returns
1428///
1429/// - `Result<ImportedScene3D, String>` - Fully parsed scene bundle or diagnostic error.
1430pub fn parse_gltf_document(
1431    json_source: &str,
1432    glb_bin_chunk: Option<&[u8]>,
1433    resolver: Option<&dyn GltfBufferResolver>,
1434) -> Result<ImportedScene3D, String> {
1435    let root: Value = from_str::<Value>(json_source)
1436        .ok()
1437        .ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
1438    let generator: String = root
1439        .get(KEY_ASSET)
1440        .and_then(|asset: &Value| asset.get(KEY_GENERATOR))
1441        .and_then(Value::as_str)
1442        .unwrap_or(GLTF_DEFAULT_SCENE_NAME)
1443        .to_string();
1444    let default_scene_idx: usize =
1445        root.get(KEY_SCENE).and_then(Value::as_u64).unwrap_or(0) as usize;
1446    let scene_name: String = root
1447        .get(KEY_SCENES)
1448        .and_then(Value::as_array)
1449        .and_then(|arr: &Vec<Value>| arr.get(default_scene_idx))
1450        .and_then(|sc: &Value| sc.get(KEY_NAME))
1451        .and_then(Value::as_str)
1452        .map(str::to_string)
1453        .unwrap_or_else(|| generator.clone());
1454    let mut buffers: Vec<Cow<'_, [u8]>> = Vec::new();
1455    if let Some(bufs_arr) = root.get(KEY_BUFFERS).and_then(Value::as_array) {
1456        for (buf_idx, buf_val) in bufs_arr.iter().enumerate() {
1457            if let Some(uri) = buf_val.get("uri").and_then(Value::as_str) {
1458                if uri.starts_with(GLTF_DATA_URI_PREFIX) {
1459                    buffers.push(Cow::Owned(decode_data_uri(uri)?));
1460                } else if let Some(res) = resolver {
1461                    buffers.push(Cow::Owned(res.resolve_buffer(uri)?));
1462                } else {
1463                    return Err(ERR_GLTF_URI_RESOLVE.to_string());
1464                }
1465            } else if buf_idx == 0
1466                && let Some(bin) = glb_bin_chunk
1467            {
1468                buffers.push(Cow::Borrowed(bin));
1469            } else {
1470                buffers.push(Cow::Borrowed(&[]));
1471            }
1472        }
1473    } else if let Some(bin) = glb_bin_chunk {
1474        buffers.push(Cow::Borrowed(bin));
1475    }
1476    let meshopt_views: HashMap<usize, Vec<u8>> = decode_meshopt_buffer_views(&root, &buffers)?;
1477    let mut materials: Vec<PrincipledMaterial3D> = Vec::new();
1478    let mut mat_ext_records: Vec<GltfMaterialExtensionData> = Vec::new();
1479    if let Some(mats_arr) = root.get(KEY_MATERIALS).and_then(Value::as_array) {
1480        for (mat_idx, mat_val) in mats_arr.iter().enumerate() {
1481            materials.push(parse_principled_material(mat_val, mat_idx));
1482            mat_ext_records.push(parse_material_extension_record(mat_val, mat_idx));
1483        }
1484    }
1485    let mut tex_spaces: HashMap<u32, TextureColorSpace> = HashMap::new();
1486    for mat in materials.iter() {
1487        if let Some(slot) = mat.try_get_base_color_texture() {
1488            let _: Option<TextureColorSpace> =
1489                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
1490        }
1491        if let Some(slot) = mat.try_get_emissive_texture() {
1492            let _: Option<TextureColorSpace> =
1493                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
1494        }
1495        if let Some(slot) = mat.try_get_sheen_color_texture() {
1496            let _: Option<TextureColorSpace> =
1497                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
1498        }
1499        if let Some(slot) = mat.try_get_normal_texture() {
1500            let _: Option<TextureColorSpace> =
1501                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
1502        }
1503        if let Some(slot) = mat.try_get_clearcoat_normal_texture() {
1504            let _: Option<TextureColorSpace> =
1505                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
1506        }
1507        for slot in [
1508            mat.try_get_metallic_roughness_texture(),
1509            mat.try_get_occlusion_texture(),
1510            mat.try_get_clearcoat_texture(),
1511            mat.try_get_clearcoat_roughness_texture(),
1512            mat.try_get_transmission_texture(),
1513            mat.try_get_specular_texture(),
1514            mat.try_get_sheen_roughness_texture(),
1515        ]
1516        .into_iter()
1517        .flatten()
1518        {
1519            let _: &mut TextureColorSpace = tex_spaces
1520                .entry(slot.get_texture_index())
1521                .or_insert(TextureColorSpace::Linear);
1522        }
1523    }
1524    for ext_rec in mat_ext_records.iter() {
1525        for slot in [
1526            ext_rec.try_get_anisotropy_texture(),
1527            ext_rec.try_get_iridescence_texture(),
1528            ext_rec.try_get_iridescence_thickness_texture(),
1529        ]
1530        .into_iter()
1531        .flatten()
1532        {
1533            let _: &mut TextureColorSpace = tex_spaces
1534                .entry(slot.get_texture_index())
1535                .or_insert(TextureColorSpace::Linear);
1536        }
1537    }
1538    let mut samplers: Vec<TextureSampler3D> = Vec::new();
1539    if let Some(samps_arr) = root.get(KEY_SAMPLERS).and_then(Value::as_array) {
1540        for samp_val in samps_arr.iter() {
1541            let mag: TextureFilterMode = samp_val
1542                .get(KEY_MAG_FILTER)
1543                .and_then(Value::as_u64)
1544                .map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
1545                .unwrap_or(TextureFilterMode::Linear);
1546            let min: TextureFilterMode = samp_val
1547                .get(KEY_MIN_FILTER)
1548                .and_then(Value::as_u64)
1549                .map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
1550                .unwrap_or(TextureFilterMode::LinearMipmapLinear);
1551            let wrap_s: TextureWrapMode = samp_val
1552                .get(KEY_WRAP_S)
1553                .and_then(Value::as_u64)
1554                .map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
1555                .unwrap_or(TextureWrapMode::Repeat);
1556            let wrap_t: TextureWrapMode = samp_val
1557                .get(KEY_WRAP_T)
1558                .and_then(Value::as_u64)
1559                .map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
1560                .unwrap_or(TextureWrapMode::Repeat);
1561            samplers.push(TextureSampler3D::new(mag, min, wrap_s, wrap_t));
1562        }
1563    }
1564    let mut raw_images: Vec<(String, Vec<u8>)> = Vec::new();
1565    if let Some(imgs_arr) = root.get(KEY_IMAGES).and_then(Value::as_array) {
1566        for (img_idx, img_val) in imgs_arr.iter().enumerate() {
1567            let img_name: String = img_val
1568                .get(KEY_NAME)
1569                .and_then(Value::as_str)
1570                .map(str::to_string)
1571                .unwrap_or_else(|| format!("image_{img_idx}"));
1572            let img_bytes: Vec<u8> =
1573                if let Some(view_idx) = img_val.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
1574                    let (slice, _): (&[u8], Option<usize>) =
1575                        resolve_buffer_view(&root, &buffers, &meshopt_views, view_idx as usize)?;
1576                    slice.to_vec()
1577                } else if let Some(uri) = img_val.get("uri").and_then(Value::as_str) {
1578                    if uri.starts_with(GLTF_DATA_URI_PREFIX) {
1579                        decode_data_uri(uri)?
1580                    } else if let Some(res) = resolver {
1581                        res.resolve_image(uri)?
1582                    } else {
1583                        Vec::new()
1584                    }
1585                } else {
1586                    Vec::new()
1587                };
1588            raw_images.push((img_name, img_bytes));
1589        }
1590    }
1591    let mut textures: Vec<Texture2D3D> = Vec::new();
1592    if let Some(texs_arr) = root.get(KEY_TEXTURES).and_then(Value::as_array) {
1593        for (tex_idx, tex_val) in texs_arr.iter().enumerate() {
1594            let color_space: TextureColorSpace = tex_spaces
1595                .get(&(tex_idx as u32))
1596                .copied()
1597                .unwrap_or(TextureColorSpace::Srgb);
1598            let sampler: TextureSampler3D = tex_val
1599                .get(KEY_SAMPLER)
1600                .and_then(Value::as_u64)
1601                .and_then(|s_idx: u64| samplers.get(s_idx as usize).copied())
1602                .unwrap_or_default();
1603            let tex_name: String = tex_val
1604                .get(KEY_NAME)
1605                .and_then(Value::as_str)
1606                .map(str::to_string)
1607                .unwrap_or_else(|| format!("texture_{tex_idx}"));
1608            let mut decoded_tex: Texture2D3D = if let Some(src_idx) =
1609                tex_val.get(KEY_SOURCE).and_then(Value::as_u64)
1610                && let Some((img_name, img_bytes)) = raw_images.get(src_idx as usize)
1611                && !img_bytes.is_empty()
1612            {
1613                let label: &str = if tex_val.get(KEY_NAME).is_some() {
1614                    &tex_name
1615                } else {
1616                    img_name
1617                };
1618                Texture2D3D::from_encoded_bytes(label, img_bytes, color_space, true)?
1619            } else {
1620                Texture2D3D::from_rgba8(
1621                    &tex_name,
1622                    1,
1623                    1,
1624                    vec![255, 255, 255, 255],
1625                    color_space,
1626                    false,
1627                )?
1628            };
1629            decoded_tex.set_sampler(sampler);
1630            textures.push(decoded_tex);
1631        }
1632    }
1633    let mut meshes: Vec<Mesh3D> = Vec::new();
1634    let mut gltf_mesh_prim_ranges: Vec<(usize, usize)> = Vec::new();
1635    if let Some(meshes_arr) = root.get(KEY_MESHES).and_then(Value::as_array) {
1636        for (mesh_idx, mesh_val) in meshes_arr.iter().enumerate() {
1637            let first_prim_idx: usize = meshes.len();
1638            let mesh_name: String = mesh_val
1639                .get(KEY_NAME)
1640                .and_then(Value::as_str)
1641                .map(str::to_string)
1642                .unwrap_or_else(|| format!("{scene_name}_mesh_{mesh_idx}"));
1643            let target_names: Vec<String> = mesh_val
1644                .get(KEY_EXTRAS)
1645                .and_then(|ext: &Value| ext.get(KEY_TARGET_NAMES))
1646                .and_then(Value::as_array)
1647                .map(|arr: &Vec<Value>| {
1648                    arr.iter()
1649                        .filter_map(|item: &Value| item.as_str().map(str::to_string))
1650                        .collect()
1651                })
1652                .unwrap_or_default();
1653            let Some(prims) = mesh_val.get(KEY_PRIMITIVES).and_then(Value::as_array) else {
1654                gltf_mesh_prim_ranges.push((first_prim_idx, 0));
1655                continue;
1656            };
1657            for (prim_idx, prim) in prims.iter().enumerate() {
1658                let prim_name: String = if prims.len() == 1 {
1659                    mesh_name.clone()
1660                } else {
1661                    format!("{mesh_name}_prim_{prim_idx}")
1662                };
1663                let mat_opt: Option<u32> = prim
1664                    .get(KEY_MATERIAL)
1665                    .and_then(Value::as_u64)
1666                    .map(|idx: u64| idx as u32);
1667                let legacy_mat: PbrMaterial = mat_opt
1668                    .and_then(|idx: u32| materials.get(idx as usize))
1669                    .or_else(|| materials.first())
1670                    .map(PrincipledMaterial3D::to_legacy_pbr)
1671                    .unwrap_or_default();
1672                if let Some(attrs) = prim.get(KEY_ATTRIBUTES).and_then(Value::as_object) {
1673                    let Some(pos_acc_idx) = attrs.get(ATTR_POSITION).and_then(Value::as_u64) else {
1674                        continue;
1675                    };
1676                    let (pos_floats, vert_count, pos_comps): (Vec<f32>, usize, usize) =
1677                        decode_accessor_f32(&root, &buffers, &meshopt_views, pos_acc_idx as usize)?;
1678                    if pos_comps < 3 || vert_count == 0 {
1679                        continue;
1680                    }
1681                    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(vert_count);
1682                    for v_idx in 0..vert_count {
1683                        let base: usize = v_idx * pos_comps;
1684                        vertices.push(Vertex3D::new(
1685                            Vec3::new(pos_floats[base], pos_floats[base + 1], pos_floats[base + 2]),
1686                            Vec3::new(0.0, 1.0, 0.0),
1687                        ));
1688                    }
1689                    let has_normals: bool = if let Some(n_acc) =
1690                        attrs.get(ATTR_NORMAL).and_then(Value::as_u64)
1691                    {
1692                        let (n_floats, n_count, n_comps): (Vec<f32>, usize, usize) =
1693                            decode_accessor_f32(&root, &buffers, &meshopt_views, n_acc as usize)?;
1694                        if n_comps >= 3 && n_count >= vert_count {
1695                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1696                            {
1697                                let base: usize = v_idx * n_comps;
1698                                vertex.set_normal(
1699                                    Vec3::new(
1700                                        n_floats[base],
1701                                        n_floats[base + 1],
1702                                        n_floats[base + 2],
1703                                    )
1704                                    .normalize(),
1705                                );
1706                            }
1707                            true
1708                        } else {
1709                            false
1710                        }
1711                    } else {
1712                        false
1713                    };
1714                    let has_tangents: bool = if let Some(t_acc) =
1715                        attrs.get(ATTR_TANGENT).and_then(Value::as_u64)
1716                    {
1717                        let (t_floats, t_count, t_comps): (Vec<f32>, usize, usize) =
1718                            decode_accessor_f32(&root, &buffers, &meshopt_views, t_acc as usize)?;
1719                        if t_comps >= 4 && t_count >= vert_count {
1720                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1721                            {
1722                                let base: usize = v_idx * t_comps;
1723                                vertex.set_tangent([
1724                                    t_floats[base],
1725                                    t_floats[base + 1],
1726                                    t_floats[base + 2],
1727                                    t_floats[base + 3],
1728                                ]);
1729                                let next_flags: u32 = vertex.get_flags() | 4;
1730                                vertex.set_flags(next_flags);
1731                            }
1732                            true
1733                        } else {
1734                            false
1735                        }
1736                    } else {
1737                        false
1738                    };
1739                    if let Some(uv0_acc) = attrs.get(ATTR_TEXCOORD_0).and_then(Value::as_u64) {
1740                        let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
1741                            decode_accessor_f32(&root, &buffers, &meshopt_views, uv0_acc as usize)?;
1742                        if uv_comps >= 2 && uv_count >= vert_count {
1743                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1744                            {
1745                                let base: usize = v_idx * uv_comps;
1746                                vertex.set_uv0([uv_floats[base], uv_floats[base + 1]]);
1747                                let next_flags: u32 = vertex.get_flags() | 1;
1748                                vertex.set_flags(next_flags);
1749                            }
1750                        }
1751                    }
1752                    if let Some(uv1_acc) = attrs.get(ATTR_TEXCOORD_1).and_then(Value::as_u64) {
1753                        let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
1754                            decode_accessor_f32(&root, &buffers, &meshopt_views, uv1_acc as usize)?;
1755                        if uv_comps >= 2 && uv_count >= vert_count {
1756                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1757                            {
1758                                let base: usize = v_idx * uv_comps;
1759                                vertex.set_uv1([uv_floats[base], uv_floats[base + 1]]);
1760                                let next_flags: u32 = vertex.get_flags() | 2;
1761                                vertex.set_flags(next_flags);
1762                            }
1763                        }
1764                    }
1765                    if let Some(col_acc) = attrs.get(ATTR_COLOR_0).and_then(Value::as_u64) {
1766                        let (c_floats, c_count, c_comps): (Vec<f32>, usize, usize) =
1767                            decode_accessor_f32(&root, &buffers, &meshopt_views, col_acc as usize)?;
1768                        if c_comps >= 3 && c_count >= vert_count {
1769                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1770                            {
1771                                let base: usize = v_idx * c_comps;
1772                                let r_u8: u8 =
1773                                    (c_floats[base].clamp(0.0, 1.0) * 255.0).round() as u8;
1774                                let g_u8: u8 =
1775                                    (c_floats[base + 1].clamp(0.0, 1.0) * 255.0).round() as u8;
1776                                let b_u8: u8 =
1777                                    (c_floats[base + 2].clamp(0.0, 1.0) * 255.0).round() as u8;
1778                                let a_u8: u8 = if c_comps >= 4 {
1779                                    (c_floats[base + 3].clamp(0.0, 1.0) * 255.0).round() as u8
1780                                } else {
1781                                    255
1782                                };
1783                                vertex.set_color0([r_u8, g_u8, b_u8, a_u8]);
1784                                let next_flags: u32 = vertex.get_flags() | 8;
1785                                vertex.set_flags(next_flags);
1786                            }
1787                        }
1788                    }
1789                    let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
1790                    if let Some(j0_acc) = attrs.get(ATTR_JOINTS_0).and_then(Value::as_u64)
1791                        && let Some(w0_acc) = attrs.get(ATTR_WEIGHTS_0).and_then(Value::as_u64)
1792                    {
1793                        let (j0_vals, j0_cnt, j0_c): (Vec<u32>, usize, usize) =
1794                            decode_accessor_u32(&root, &buffers, &meshopt_views, j0_acc as usize)?;
1795                        let (w0_vals, w0_cnt, w0_c): (Vec<f32>, usize, usize) =
1796                            decode_accessor_f32(&root, &buffers, &meshopt_views, w0_acc as usize)?;
1797                        let j1_data: Option<(Vec<u32>, usize, usize)> = attrs
1798                            .get(ATTR_JOINTS_1)
1799                            .and_then(Value::as_u64)
1800                            .and_then(|id: u64| {
1801                                decode_accessor_u32(&root, &buffers, &meshopt_views, id as usize)
1802                                    .ok()
1803                            });
1804                        let w1_data: Option<(Vec<f32>, usize, usize)> = attrs
1805                            .get(ATTR_WEIGHTS_1)
1806                            .and_then(Value::as_u64)
1807                            .and_then(|id: u64| {
1808                                decode_accessor_f32(&root, &buffers, &meshopt_views, id as usize)
1809                                    .ok()
1810                            });
1811                        if j0_c >= 4 && w0_c >= 4 && j0_cnt >= vert_count && w0_cnt >= vert_count {
1812                            skin_influences.reserve(vert_count);
1813                            for v_idx in 0..vert_count {
1814                                let jb: usize = v_idx * j0_c;
1815                                let wb: usize = v_idx * w0_c;
1816                                let joints_0: [u16; 4] = [
1817                                    j0_vals[jb] as u16,
1818                                    j0_vals[jb + 1] as u16,
1819                                    j0_vals[jb + 2] as u16,
1820                                    j0_vals[jb + 3] as u16,
1821                                ];
1822                                let mut weights_0: [f32; 4] = [
1823                                    w0_vals[wb].max(0.0),
1824                                    w0_vals[wb + 1].max(0.0),
1825                                    w0_vals[wb + 2].max(0.0),
1826                                    w0_vals[wb + 3].max(0.0),
1827                                ];
1828                                let mut joints_1: [u16; 4] = [0u16; 4];
1829                                let mut weights_1: [f32; 4] = [0.0; 4];
1830                                if let (Some((j1v, j1cnt, j1c)), Some((w1v, w1cnt, w1c))) =
1831                                    (&j1_data, &w1_data)
1832                                    && *j1c >= 4
1833                                    && *w1c >= 4
1834                                    && *j1cnt >= vert_count
1835                                    && *w1cnt >= vert_count
1836                                {
1837                                    let j1b: usize = v_idx * (*j1c);
1838                                    let w1b: usize = v_idx * (*w1c);
1839                                    joints_1 = [
1840                                        j1v[j1b] as u16,
1841                                        j1v[j1b + 1] as u16,
1842                                        j1v[j1b + 2] as u16,
1843                                        j1v[j1b + 3] as u16,
1844                                    ];
1845                                    weights_1 = [
1846                                        w1v[w1b].max(0.0),
1847                                        w1v[w1b + 1].max(0.0),
1848                                        w1v[w1b + 2].max(0.0),
1849                                        w1v[w1b + 3].max(0.0),
1850                                    ];
1851                                }
1852                                let sum_w: f32 = weights_0[0]
1853                                    + weights_0[1]
1854                                    + weights_0[2]
1855                                    + weights_0[3]
1856                                    + weights_1[0]
1857                                    + weights_1[1]
1858                                    + weights_1[2]
1859                                    + weights_1[3];
1860                                if sum_w > 1e-6 {
1861                                    let inv_w: f32 = 1.0 / sum_w;
1862                                    for lane in 0..4usize {
1863                                        weights_0[lane] *= inv_w;
1864                                        weights_1[lane] *= inv_w;
1865                                    }
1866                                }
1867                                skin_influences.push(MeshSkinInfluence3D::new(
1868                                    joints_0, weights_0, joints_1, weights_1,
1869                                ));
1870                            }
1871                        }
1872                    }
1873                    let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
1874                    if let Some(targets_arr) = prim.get(KEY_TARGETS).and_then(Value::as_array) {
1875                        for (t_idx, target_val) in targets_arr.iter().enumerate() {
1876                            let target_name: String = target_names
1877                                .get(t_idx)
1878                                .cloned()
1879                                .unwrap_or_else(|| format!("shape_key_{t_idx}"));
1880                            let mut delta_positions: Vec<[f32; 3]> = Vec::new();
1881                            if let Some(dp_acc) =
1882                                target_val.get(ATTR_POSITION).and_then(Value::as_u64)
1883                            {
1884                                let (dp, cnt, comps): (Vec<f32>, usize, usize) =
1885                                    decode_accessor_f32(
1886                                        &root,
1887                                        &buffers,
1888                                        &meshopt_views,
1889                                        dp_acc as usize,
1890                                    )?;
1891                                if comps >= 3 {
1892                                    delta_positions.reserve(cnt);
1893                                    for i in 0..cnt {
1894                                        let b: usize = i * comps;
1895                                        delta_positions.push([dp[b], dp[b + 1], dp[b + 2]]);
1896                                    }
1897                                }
1898                            }
1899                            let mut delta_normals: Vec<[f32; 3]> = Vec::new();
1900                            if let Some(dn_acc) =
1901                                target_val.get(ATTR_NORMAL).and_then(Value::as_u64)
1902                            {
1903                                let (dn, cnt, comps): (Vec<f32>, usize, usize) =
1904                                    decode_accessor_f32(
1905                                        &root,
1906                                        &buffers,
1907                                        &meshopt_views,
1908                                        dn_acc as usize,
1909                                    )?;
1910                                if comps >= 3 {
1911                                    delta_normals.reserve(cnt);
1912                                    for i in 0..cnt {
1913                                        let b: usize = i * comps;
1914                                        delta_normals.push([dn[b], dn[b + 1], dn[b + 2]]);
1915                                    }
1916                                }
1917                            }
1918                            let mut delta_tangents: Vec<[f32; 3]> = Vec::new();
1919                            if let Some(dt_acc) =
1920                                target_val.get(ATTR_TANGENT).and_then(Value::as_u64)
1921                            {
1922                                let (dt, cnt, comps): (Vec<f32>, usize, usize) =
1923                                    decode_accessor_f32(
1924                                        &root,
1925                                        &buffers,
1926                                        &meshopt_views,
1927                                        dt_acc as usize,
1928                                    )?;
1929                                if comps >= 3 {
1930                                    delta_tangents.reserve(cnt);
1931                                    for i in 0..cnt {
1932                                        let b: usize = i * comps;
1933                                        delta_tangents.push([dt[b], dt[b + 1], dt[b + 2]]);
1934                                    }
1935                                }
1936                            }
1937                            morph_targets.push(MorphTarget3D {
1938                                name: target_name,
1939                                delta_positions,
1940                                delta_normals,
1941                                delta_tangents,
1942                            });
1943                        }
1944                    }
1945                    let raw_indices: Vec<u32> = if let Some(idx_acc) =
1946                        prim.get(KEY_INDICES).and_then(Value::as_u64)
1947                    {
1948                        let (vals, _, _): (Vec<u32>, usize, usize) =
1949                            decode_accessor_u32(&root, &buffers, &meshopt_views, idx_acc as usize)?;
1950                        vals
1951                    } else {
1952                        (0..(vert_count as u32)).collect()
1953                    };
1954                    let mode: u32 = prim
1955                        .get(KEY_MODE)
1956                        .and_then(Value::as_u64)
1957                        .unwrap_or(u64::from(GLTF_MODE_TRIANGLES))
1958                        as u32;
1959                    let tris: Vec<[u32; 3]> = assemble_primitive_triangles(&raw_indices, mode);
1960                    if !tris.is_empty() {
1961                        let mut built: Mesh3D =
1962                            Mesh3D::from_parts(prim_name, vertices, tris, legacy_mat);
1963                        if !has_normals {
1964                            built.compute_smooth_normals();
1965                        }
1966                        if !has_tangents {
1967                            built.compute_lengyel_tangents();
1968                        }
1969                        built.set_skin_influences(skin_influences);
1970                        built.set_morph_targets(morph_targets);
1971                        built.set_material_index(mat_opt);
1972                        meshes.push(built);
1973                    }
1974                } else {
1975                    let extras: &Value = prim.get(KEY_EXTRAS).unwrap_or(prim);
1976                    let pos_vals: Vec<f32> = extras
1977                        .get(KEY_LEGACY_POSITIONS)
1978                        .and_then(Value::as_array)
1979                        .map(|arr: &Vec<Value>| {
1980                            arr.iter()
1981                                .filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
1982                                .collect()
1983                        })
1984                        .unwrap_or_default();
1985                    let idx_vals: Vec<u32> = extras
1986                        .get(KEY_INDICES)
1987                        .and_then(Value::as_array)
1988                        .map(|arr: &Vec<Value>| {
1989                            arr.iter()
1990                                .filter_map(|item: &Value| item.as_u64().map(|val: u64| val as u32))
1991                                .collect()
1992                        })
1993                        .unwrap_or_default();
1994                    let raw_pts: Vec<Vec3> = pos_vals
1995                        .as_chunks::<3>()
1996                        .0
1997                        .iter()
1998                        .map(|chunk: &[f32; 3]| Vec3::new(chunk[0], chunk[1], chunk[2]))
1999                        .collect();
2000                    let mut verts: Vec<Vertex3D> = Vec::new();
2001                    let mut tris: Vec<[u32; 3]> = Vec::new();
2002                    for tri in idx_vals.as_chunks::<3>().0 {
2003                        let (i0, i1, i2): (usize, usize, usize) =
2004                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2005                        if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
2006                            let p0: Vec3 = raw_pts[i0];
2007                            let p1: Vec3 = raw_pts[i1];
2008                            let p2: Vec3 = raw_pts[i2];
2009                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
2010                            let base: u32 = verts.len() as u32;
2011                            verts.push(Vertex3D::new(p0, face_n));
2012                            verts.push(Vertex3D::new(p1, face_n));
2013                            verts.push(Vertex3D::new(p2, face_n));
2014                            tris.push([base, base + 1, base + 2]);
2015                        }
2016                    }
2017                    if !tris.is_empty() {
2018                        let mut built: Mesh3D =
2019                            Mesh3D::from_parts(prim_name, verts, tris, legacy_mat);
2020                        built.set_material_index(mat_opt);
2021                        meshes.push(built);
2022                    }
2023                }
2024            }
2025            gltf_mesh_prim_ranges
2026                .push((first_prim_idx, meshes.len().saturating_sub(first_prim_idx)));
2027        }
2028    }
2029    let mut skins: Vec<ImportedSkin3D> = Vec::new();
2030    if let Some(skins_arr) = root.get(KEY_SKINS).and_then(Value::as_array) {
2031        for (skin_idx, skin_val) in skins_arr.iter().enumerate() {
2032            let name: String = skin_val
2033                .get(KEY_NAME)
2034                .and_then(Value::as_str)
2035                .map(str::to_string)
2036                .unwrap_or_else(|| format!("skin_{skin_idx}"));
2037            let joints: Vec<u32> = skin_val
2038                .get(KEY_JOINTS)
2039                .and_then(Value::as_array)
2040                .map(|arr: &Vec<Value>| {
2041                    arr.iter()
2042                        .filter_map(|item: &Value| item.as_u64().map(|id: u64| id as u32))
2043                        .collect()
2044                })
2045                .unwrap_or_default();
2046            let skeleton_root: Option<u32> = skin_val
2047                .get(KEY_SKELETON)
2048                .and_then(Value::as_u64)
2049                .map(|id: u64| id as u32);
2050            let mut inverse_bind_matrices: Vec<Mat4> = Vec::with_capacity(joints.len());
2051            if let Some(ibm_acc) = skin_val.get(KEY_INV_BIND_MATRICES).and_then(Value::as_u64) {
2052                let (floats, count, comps): (Vec<f32>, usize, usize) =
2053                    decode_accessor_f32(&root, &buffers, &meshopt_views, ibm_acc as usize)?;
2054                if comps == 16 {
2055                    for idx in 0..count {
2056                        let base: usize = idx * 16;
2057                        let mut elems: [f32; 16] = [0.0; 16];
2058                        elems.copy_from_slice(&floats[base..(base + 16)]);
2059                        inverse_bind_matrices.push(Mat4::from_cols_array(elems));
2060                    }
2061                }
2062            }
2063            while inverse_bind_matrices.len() < joints.len() {
2064                inverse_bind_matrices.push(Mat4::identity());
2065            }
2066            skins.push(ImportedSkin3D {
2067                name,
2068                joints,
2069                skeleton_root,
2070                inverse_bind_matrices,
2071            });
2072        }
2073    }
2074    let mut animations: Vec<ImportedAnimationClip3D> = Vec::new();
2075    if let Some(anims_arr) = root.get(KEY_ANIMATIONS).and_then(Value::as_array) {
2076        for (anim_idx, anim_val) in anims_arr.iter().enumerate() {
2077            let name: String = anim_val
2078                .get(KEY_NAME)
2079                .and_then(Value::as_str)
2080                .map(str::to_string)
2081                .unwrap_or_else(|| format!("animation_{anim_idx}"));
2082            let mut duration_secs: f32 = 0.0;
2083            let mut parsed_samplers: Vec<ImportedAnimationSampler3D> = Vec::new();
2084            if let Some(samps_arr) = anim_val.get(KEY_SAMPLERS).and_then(Value::as_array) {
2085                for samp_val in samps_arr.iter() {
2086                    let Some(in_acc) = samp_val.get(KEY_INPUT).and_then(Value::as_u64) else {
2087                        parsed_samplers.push(ImportedAnimationSampler3D::default());
2088                        continue;
2089                    };
2090                    let Some(out_acc) = samp_val.get(KEY_OUTPUT).and_then(Value::as_u64) else {
2091                        parsed_samplers.push(ImportedAnimationSampler3D::default());
2092                        continue;
2093                    };
2094                    let (timestamps, t_cnt, _): (Vec<f32>, usize, usize) =
2095                        decode_accessor_f32(&root, &buffers, &meshopt_views, in_acc as usize)?;
2096                    let (values, v_cnt, v_comps): (Vec<f32>, usize, usize) =
2097                        decode_accessor_f32(&root, &buffers, &meshopt_views, out_acc as usize)?;
2098                    for &ts in timestamps.iter() {
2099                        if ts > duration_secs {
2100                            duration_secs = ts;
2101                        }
2102                    }
2103                    let interp: GltfInterpolationMode =
2104                        match samp_val.get(KEY_INTERPOLATION).and_then(Value::as_str) {
2105                            Some(INTERP_STEP) => GltfInterpolationMode::Step,
2106                            Some(INTERP_CUBICSPLINE) => GltfInterpolationMode::CubicSpline,
2107                            _ => GltfInterpolationMode::Linear,
2108                        };
2109                    let per_key_mult: usize = if interp == GltfInterpolationMode::CubicSpline {
2110                        3
2111                    } else {
2112                        1
2113                    };
2114                    let denom: usize = t_cnt.saturating_mul(per_key_mult).max(1);
2115                    let value_stride: usize = ((v_cnt * v_comps) / denom).max(1);
2116                    parsed_samplers.push(ImportedAnimationSampler3D {
2117                        timestamps,
2118                        values,
2119                        value_stride,
2120                        interpolation: interp,
2121                    });
2122                }
2123            }
2124            let mut parsed_channels: Vec<ImportedAnimationChannel3D> = Vec::new();
2125            if let Some(ch_arr) = anim_val.get(KEY_CHANNELS).and_then(Value::as_array) {
2126                for ch_val in ch_arr.iter() {
2127                    let Some(sampler_index) = ch_val.get(KEY_SAMPLER).and_then(Value::as_u64)
2128                    else {
2129                        continue;
2130                    };
2131                    let Some(target_obj) = ch_val.get(KEY_TARGET) else {
2132                        continue;
2133                    };
2134                    let Some(target_node) = target_obj.get(KEY_NODE).and_then(Value::as_u64) else {
2135                        continue;
2136                    };
2137                    let Some(path_str) = target_obj.get(KEY_PATH).and_then(Value::as_str) else {
2138                        continue;
2139                    };
2140                    let path: GltfAnimationPath = if path_str == KEY_TRANSLATION {
2141                        GltfAnimationPath::Translation
2142                    } else if path_str == KEY_ROTATION {
2143                        GltfAnimationPath::Rotation
2144                    } else if path_str == KEY_SCALE {
2145                        GltfAnimationPath::Scale
2146                    } else if path_str == KEY_WEIGHTS {
2147                        GltfAnimationPath::MorphWeights
2148                    } else {
2149                        continue;
2150                    };
2151                    parsed_channels.push(ImportedAnimationChannel3D::new(
2152                        target_node as u32,
2153                        path,
2154                        sampler_index as usize,
2155                    ));
2156                }
2157            }
2158            animations.push(ImportedAnimationClip3D {
2159                name,
2160                duration_secs,
2161                samplers: parsed_samplers,
2162                channels: parsed_channels,
2163            });
2164        }
2165    }
2166    let mut cameras: Vec<ImportedCamera3D> = Vec::new();
2167    if let Some(cams_arr) = root.get(KEY_CAMERAS).and_then(Value::as_array) {
2168        for (cam_idx, cam_val) in cams_arr.iter().enumerate() {
2169            let name: String = cam_val
2170                .get(KEY_NAME)
2171                .and_then(Value::as_str)
2172                .map(str::to_string)
2173                .unwrap_or_else(|| format!("camera_{cam_idx}"));
2174            if let Some(persp) = cam_val.get(KEY_PERSPECTIVE) {
2175                let yfov_rad: f32 =
2176                    persp.get(KEY_YFOV).and_then(Value::as_f64).unwrap_or(0.8) as f32;
2177                let aspect_ratio: Option<f32> = persp
2178                    .get(KEY_ASPECT_RATIO)
2179                    .and_then(Value::as_f64)
2180                    .map(|val: f64| val as f32);
2181                let znear: f32 = persp.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
2182                let zfar: Option<f32> = persp
2183                    .get(KEY_ZFAR)
2184                    .and_then(Value::as_f64)
2185                    .map(|val: f64| val as f32);
2186                cameras.push(ImportedCamera3D {
2187                    name,
2188                    projection: GltfCameraProjection::Perspective {
2189                        yfov_rad,
2190                        aspect_ratio,
2191                        znear,
2192                        zfar,
2193                    },
2194                });
2195            } else if let Some(ortho) = cam_val.get(KEY_ORTHOGRAPHIC) {
2196                let xmag: f32 = ortho.get(KEY_XMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
2197                let ymag: f32 = ortho.get(KEY_YMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
2198                let znear: f32 = ortho.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
2199                let zfar: f32 = ortho.get(KEY_ZFAR).and_then(Value::as_f64).unwrap_or(100.0) as f32;
2200                cameras.push(ImportedCamera3D {
2201                    name,
2202                    projection: GltfCameraProjection::Orthographic {
2203                        xmag,
2204                        ymag,
2205                        znear,
2206                        zfar,
2207                    },
2208                });
2209            }
2210        }
2211    }
2212    let mut lights: Vec<ImportedLight3D> = Vec::new();
2213    if let Some(lights_arr) = root
2214        .get(KEY_EXTENSIONS)
2215        .and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
2216        .and_then(|lp: &Value| lp.get(KEY_LIGHTS))
2217        .and_then(Value::as_array)
2218    {
2219        for (light_idx, light_val) in lights_arr.iter().enumerate() {
2220            let name: String = light_val
2221                .get(KEY_NAME)
2222                .and_then(Value::as_str)
2223                .map(str::to_string)
2224                .unwrap_or_else(|| format!("light_{light_idx}"));
2225            let color_arr: [f32; 3] = json_f32_3(light_val.get(KEY_COLOR), [1.0, 1.0, 1.0]);
2226            let intensity: f32 = light_val
2227                .get(KEY_INTENSITY)
2228                .and_then(Value::as_f64)
2229                .unwrap_or(1.0) as f32;
2230            let range: Option<f32> = light_val
2231                .get(KEY_RANGE)
2232                .and_then(Value::as_f64)
2233                .map(|val: f64| val as f32);
2234            let light_type: &str = light_val
2235                .get(KEY_TYPE)
2236                .and_then(Value::as_str)
2237                .unwrap_or(LIGHT_TYPE_POINT);
2238            let kind: GltfLightKind = if light_type == LIGHT_TYPE_DIRECTIONAL {
2239                GltfLightKind::Directional
2240            } else if light_type == LIGHT_TYPE_SPOT {
2241                let spot_obj: Option<&Value> = light_val.get(KEY_SPOT);
2242                let inner_cone_angle: f32 = spot_obj
2243                    .and_then(|s: &Value| s.get(KEY_INNER_CONE))
2244                    .and_then(Value::as_f64)
2245                    .unwrap_or(0.0) as f32;
2246                let outer_cone_angle: f32 = spot_obj
2247                    .and_then(|s: &Value| s.get(KEY_OUTER_CONE))
2248                    .and_then(Value::as_f64)
2249                    .map(|val: f64| val as f32)
2250                    .unwrap_or(FRAC_PI_2 * 0.5);
2251                GltfLightKind::Spot {
2252                    range,
2253                    inner_cone_angle,
2254                    outer_cone_angle,
2255                }
2256            } else if light_type == LIGHT_TYPE_AREA {
2257                GltfLightKind::Area {
2258                    width: 1.0,
2259                    height: 1.0,
2260                }
2261            } else {
2262                GltfLightKind::Point { range }
2263            };
2264            lights.push(ImportedLight3D {
2265                name,
2266                color: Vec3::from_array(color_arr),
2267                intensity,
2268                kind,
2269            });
2270        }
2271    }
2272    let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
2273    if let Some(nodes_arr) = root.get(KEY_NODES).and_then(Value::as_array) {
2274        let mut parent_of: Vec<Option<u32>> = vec![None; nodes_arr.len()];
2275        for (parent_idx, node_val) in nodes_arr.iter().enumerate() {
2276            if let Some(children) = node_val.get(KEY_CHILDREN).and_then(Value::as_array) {
2277                for child_val in children.iter() {
2278                    if let Some(child_idx) = child_val.as_u64() {
2279                        let c_usize: usize = child_idx as usize;
2280                        if c_usize < parent_of.len() {
2281                            parent_of[c_usize] = Some(parent_idx as u32);
2282                        }
2283                    }
2284                }
2285            }
2286        }
2287        let mut extra_prim_children: Vec<GltfExtraPrimChild> = Vec::new();
2288        for (node_idx, node_val) in nodes_arr.iter().enumerate() {
2289            let name: String = node_val
2290                .get(KEY_NAME)
2291                .and_then(Value::as_str)
2292                .map(str::to_string)
2293                .unwrap_or_else(|| format!("node_{node_idx}"));
2294            let mut node: SceneNode3D = SceneNode3D::from_name(&name, parent_of[node_idx]);
2295            if let Some(mat_arr) = node_val.get(KEY_MATRIX).and_then(Value::as_array)
2296                && mat_arr.len() == 16
2297            {
2298                let mut elems: [f32; 16] = [0.0; 16];
2299                for i in 0..16usize {
2300                    elems[i] = mat_arr[i].as_f64().unwrap_or(0.0) as f32;
2301                }
2302                let (tr, rot, sc): (Vec3, Quat, Vec3) =
2303                    Mat4::from_cols_array(elems).decompose_trs();
2304                node.set_local_translation(tr);
2305                node.set_local_rotation(rot);
2306                node.set_local_scale(sc);
2307            } else {
2308                let tr: [f32; 3] = json_f32_3(node_val.get(KEY_TRANSLATION), [0.0, 0.0, 0.0]);
2309                let rot: [f32; 4] = json_f32_4(node_val.get(KEY_ROTATION), [0.0, 0.0, 0.0, 1.0]);
2310                let sc: [f32; 3] = json_f32_3(node_val.get(KEY_SCALE), [1.0, 1.0, 1.0]);
2311                node.set_local_translation(Vec3::from_array(tr));
2312                node.set_local_rotation(Quat::from_array(rot).normalize());
2313                node.set_local_scale(Vec3::from_array(sc));
2314            }
2315            let mut extra_prims: Option<(usize, usize)> = None;
2316            if let Some(mesh_idx) = node_val.get(KEY_MESH).and_then(Value::as_u64)
2317                && let Some(&(first_prim, prim_count)) =
2318                    gltf_mesh_prim_ranges.get(mesh_idx as usize)
2319                && prim_count > 0
2320                && first_prim < meshes.len()
2321            {
2322                node.set_mesh_id(Some(first_prim as u32));
2323                if prim_count > 1 {
2324                    extra_prims = Some((first_prim + 1, prim_count - 1));
2325                }
2326            }
2327            if let Some(skin_idx) = node_val.get(KEY_SKIN).and_then(Value::as_u64) {
2328                node.set_skin_id(Some(skin_idx as u32));
2329            }
2330            if let Some(cam_idx) = node_val.get(KEY_CAMERA).and_then(Value::as_u64) {
2331                node.set_camera_id(Some(cam_idx as u32));
2332            }
2333            if let Some(light_idx) = node_val
2334                .get(KEY_EXTENSIONS)
2335                .and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
2336                .and_then(|lp: &Value| lp.get(KEY_LIGHT))
2337                .and_then(Value::as_u64)
2338            {
2339                node.set_light_id(Some(light_idx as u32));
2340            }
2341            if let Some(extras_obj) = node_val.get(KEY_EXTRAS) {
2342                let euv_obj: &Value = extras_obj.get("euv").unwrap_or(extras_obj);
2343                if let Some(colls) = euv_obj
2344                    .get(KEY_EUV_COLLECTIONS)
2345                    .or_else(|| extras_obj.get(KEY_EUV_COLLECTIONS))
2346                    .and_then(Value::as_array)
2347                {
2348                    let mut mask: u64 = 0;
2349                    for coll_val in colls.iter() {
2350                        if let Some(coll_name) = coll_val.as_str() {
2351                            mask |= scene_graph
2352                                .get_mut_collections()
2353                                .register_collection(coll_name);
2354                        }
2355                    }
2356                    if mask != 0 {
2357                        node.set_collection_mask(mask);
2358                    }
2359                }
2360                let mut tags: BlenderExtrasTags3D = BlenderExtrasTags3D::default();
2361                if let Some(col_str) = euv_obj.get(KEY_EUV_COLLIDER).and_then(Value::as_str) {
2362                    let shape: SceneColliderShape3D = if col_str == COLLIDER_SPHERE {
2363                        SceneColliderShape3D::Sphere
2364                    } else if col_str == COLLIDER_CONVEX || col_str == COLLIDER_CONVEX_HULL {
2365                        SceneColliderShape3D::ConvexHull
2366                    } else if col_str == COLLIDER_MESH {
2367                        SceneColliderShape3D::Mesh
2368                    } else if col_str == "box" {
2369                        SceneColliderShape3D::Box
2370                    } else {
2371                        SceneColliderShape3D::None
2372                    };
2373                    tags.set_collider(shape);
2374                }
2375                if let Some(buoy) = euv_obj.get(KEY_EUV_BUOYANCY).and_then(Value::as_f64) {
2376                    tags.set_buoyancy_density(buoy as f32);
2377                }
2378                if let Some(trig) = euv_obj.get(KEY_EUV_TRIGGER).and_then(Value::as_bool) {
2379                    tags.set_is_trigger(trig);
2380                }
2381                if let Some(cast) = euv_obj.get(KEY_EUV_CAST_SHADOWS).and_then(Value::as_bool) {
2382                    tags.set_cast_shadows(cast);
2383                }
2384                if let Ok(raw_json) = to_string(extras_obj) {
2385                    tags.set_custom_json(Some(raw_json));
2386                }
2387                node.set_extras(tags);
2388            }
2389            let node_skin: Option<u32> = node.try_get_skin_id();
2390            let node_col_mask: u64 = node.get_collection_mask();
2391            let node_extras: BlenderExtrasTags3D = node.get_extras().clone();
2392            let added_id: u32 = scene_graph.add_node(node);
2393            let mut node_weights: Vec<f32> = Vec::new();
2394            if let Some(weights_arr) = node_val.get(KEY_WEIGHTS).and_then(Value::as_array) {
2395                node_weights = weights_arr
2396                    .iter()
2397                    .filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
2398                    .collect();
2399                scene_graph.attach_morph_weights(added_id, &node_weights);
2400            }
2401            if let Some((start_p, extra_cnt)) = extra_prims {
2402                for offset in 0..extra_cnt {
2403                    let prim_mesh_id: u32 = (start_p + offset) as u32;
2404                    let child_name: String = format!("{name}_prim_{}", offset + 1);
2405                    extra_prim_children.push(GltfExtraPrimChild {
2406                        parent_id: added_id,
2407                        child_name,
2408                        prim_mesh_id,
2409                        skin_id: node_skin,
2410                        collection_mask: node_col_mask,
2411                        extras: node_extras.clone(),
2412                        morph_weights: node_weights.clone(),
2413                    });
2414                }
2415            }
2416        }
2417        for extra_child in extra_prim_children {
2418            let mut child: SceneNode3D =
2419                SceneNode3D::from_name(&extra_child.child_name, Some(extra_child.parent_id));
2420            child.set_mesh_id(Some(extra_child.prim_mesh_id));
2421            child.set_skin_id(extra_child.skin_id);
2422            child.set_collection_mask(extra_child.collection_mask);
2423            child.set_extras(extra_child.extras);
2424            let child_id: u32 = scene_graph.add_node(child);
2425            if !extra_child.morph_weights.is_empty() {
2426                scene_graph.attach_morph_weights(child_id, &extra_child.morph_weights);
2427            }
2428        }
2429        let _: usize = scene_graph.propagate_world_matrices();
2430    }
2431    Ok(ImportedScene3D {
2432        name: scene_name,
2433        generator,
2434        scene_graph,
2435        meshes,
2436        materials,
2437        textures,
2438        skins,
2439        animations,
2440        cameras,
2441        lights,
2442    })
2443}
2444
2445/// Parses a self-contained binary Khronos GLB v2 container (`.glb`) into an `ImportedScene3D`.
2446///
2447/// # Arguments
2448///
2449/// - `&[u8]` - Raw `.glb` file bytes.
2450///
2451/// # Returns
2452///
2453/// - `Result<ImportedScene3D, String>` - Fully imported scene bundle or validation error.
2454pub fn parse_glb_bytes(bytes: &[u8]) -> Result<ImportedScene3D, String> {
2455    if bytes.len() < 20 {
2456        return Err(ERR_GLB_INVALID.to_string());
2457    }
2458    let magic: u32 = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
2459    let version: u32 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
2460    let total_len: usize = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
2461    if magic != GLB_MAGIC || version != GLB_VERSION_2 || total_len > bytes.len() || total_len < 20 {
2462        return Err(ERR_GLB_INVALID.to_string());
2463    }
2464    let mut cursor: usize = 12;
2465    let mut json_slice: Option<&[u8]> = None;
2466    let mut bin_slice: Option<&[u8]> = None;
2467    while cursor + 8 <= total_len {
2468        let chunk_len: usize = u32::from_le_bytes([
2469            bytes[cursor],
2470            bytes[cursor + 1],
2471            bytes[cursor + 2],
2472            bytes[cursor + 3],
2473        ]) as usize;
2474        let chunk_type: u32 = u32::from_le_bytes([
2475            bytes[cursor + 4],
2476            bytes[cursor + 5],
2477            bytes[cursor + 6],
2478            bytes[cursor + 7],
2479        ]);
2480        let payload_start: usize = cursor + 8;
2481        let payload_end: usize = payload_start.saturating_add(chunk_len);
2482        if payload_end > total_len {
2483            return Err(ERR_GLB_INVALID.to_string());
2484        }
2485        if chunk_type == GLB_CHUNK_JSON && json_slice.is_none() {
2486            json_slice = Some(&bytes[payload_start..payload_end]);
2487        } else if chunk_type == GLB_CHUNK_BIN && bin_slice.is_none() {
2488            bin_slice = Some(&bytes[payload_start..payload_end]);
2489        }
2490        cursor = payload_end;
2491    }
2492    let raw_json: &[u8] = json_slice.ok_or_else(|| ERR_GLB_INVALID.to_string())?;
2493    let json_text: &str = from_utf8(raw_json)
2494        .ok()
2495        .ok_or_else(|| ERR_GLB_INVALID.to_string())?;
2496    parse_gltf_document(json_text, bin_slice, None)
2497}
2498
2499/// Parses either a binary `.glb` container or UTF-8 `.gltf` JSON byte slice with optional external URI resolver.
2500///
2501/// # Arguments
2502///
2503/// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
2504/// - `Option<&dyn GltfBufferResolver>` - Optional external buffer/image resolver for `.gltf`.
2505///
2506/// # Returns
2507///
2508/// - `Result<ImportedScene3D, String>` - Imported scene bundle or parse error.
2509pub fn parse_gltf_or_glb_bytes(
2510    bytes: &[u8],
2511    resolver: Option<&dyn GltfBufferResolver>,
2512) -> Result<ImportedScene3D, String> {
2513    if bytes.len() >= 4 && u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == GLB_MAGIC
2514    {
2515        return parse_glb_bytes(bytes);
2516    }
2517    let json_text: &str = from_utf8(bytes)
2518        .ok()
2519        .ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
2520    parse_gltf_document(json_text, None, resolver)
2521}