draco-io 0.1.0

Rust IO helpers for Draco geometry compression formats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Document-preserving glTF Draco compression.
//!
//! [`compress_gltf_bytes`] takes a self-contained glTF or GLB document and
//! returns a copy whose triangle-mesh geometry is compressed with
//! `KHR_draco_mesh_compression`, while **everything else in the document is
//! carried through untouched**: materials, textures, images, samplers, cameras,
//! nodes, animations, skins, `extras`, and unknown extensions.
//!
//! This is the key difference from the `read meshes -> write fresh glTF` path,
//! which only models geometry and therefore drops materials and other content.
//! Here we mutate the original JSON document in place and only touch the parts
//! that change: the compressed primitives, their geometry accessors, the
//! buffer, and the buffer views.
//!
//! # What gets compressed
//!
//! A primitive is compressed only when it can be reproduced losslessly:
//!
//! - triangle list (`mode` 4 or absent), indexed or non-indexed (a fresh
//!   indices accessor is generated for the non-indexed case),
//! - not already Draco-compressed,
//! - its geometry accessors are not shared with any other primitive,
//! - decoding and re-encoding succeed and reproduce the exact attribute set.
//!
//! All standard attribute semantics are compressed, including `TANGENT`,
//! `JOINTS_n`, `WEIGHTS_n`, multiple `TEXCOORD_n`/`COLOR_n`, and custom `_*`
//! attributes: non-standard ones ride along inside the Draco stream as generic
//! attributes and are named by the extension's attribute map (the glTF semantic
//! lives in the map, not in the Draco attribute). Skinned and tangent-bearing
//! meshes are therefore compressed, not just preserved.
//!
//! Primitives that fall outside this scope — already Draco, sharing geometry
//! accessors, sparse accessors, or an attribute layout the encoder rejects —
//! are left uncompressed but fully preserved, along with the rest of the
//! document.
//!
//! Non-triangle primitives are likewise left uncompressed, and this is required
//! by the spec, not a limitation: `KHR_draco_mesh_compression` restricts the
//! primitive `mode` to `TRIANGLES` or `TRIANGLE_STRIP` ("Restrictions on
//! geometry type"), so point clouds (`POINTS`) and line modes cannot be
//! Draco-compressed in glTF at all. (Only `TRIANGLES` is compressed here;
//! `TRIANGLE_STRIP` is allowed by the spec but uncommon and left as-is.)

use std::collections::{BTreeSet, HashMap};
#[cfg(feature = "gltf-reader")]
use std::path::Path;

use serde_json::{Map, Value};

use crate::gltf_geometry::GltfError;
// The byte API parses + resolves buffers through the reader; the in-memory
// `compress_gltf_value` does not need it.
#[cfg(feature = "gltf-reader")]
use crate::gltf_reader::GltfReader;
use crate::gltf_writer::{encode_draco_mesh_with_info, QuantizationBits};

type Result<T> = std::result::Result<T, GltfError>;

const KHR_DRACO: &str = "KHR_draco_mesh_compression";
const MODE_TRIANGLES: u64 = 4;

// GLB container handling is only used by the byte API (reader feature).
#[cfg(feature = "gltf-reader")]
const GLB_MAGIC: u32 = 0x4654_6C67;
#[cfg(feature = "gltf-reader")]
const GLB_VERSION: u32 = 2;
#[cfg(feature = "gltf-reader")]
const GLB_CHUNK_JSON: u32 = 0x4E4F_534A;
#[cfg(feature = "gltf-reader")]
const GLB_CHUNK_BIN: u32 = 0x004E_4942;

#[cfg(feature = "gltf-reader")]
#[derive(Clone, Copy, PartialEq, Eq)]
enum Container {
    Glb,
    Gltf,
}

/// Compress the geometry of a self-contained glTF/GLB document with Draco,
/// preserving all other document content.
///
/// `input` may be GLB bytes or glTF JSON whose buffers/images are embedded as
/// data URIs (use [`compress_gltf_bytes_with_base_path`] for external files).
/// The output container matches the input (GLB in -> GLB out, glTF in -> glTF
/// out with an embedded buffer).
#[cfg(feature = "gltf-reader")]
pub fn compress_gltf_bytes(
    input: &[u8],
    quantization: Option<QuantizationBits>,
) -> Result<Vec<u8>> {
    compress_gltf_bytes_with_base_path(input, None, quantization)
}

/// Like [`compress_gltf_bytes`], but resolves external buffers/`.bin` files
/// relative to `base_path`.
#[cfg(feature = "gltf-reader")]
pub fn compress_gltf_bytes_with_base_path(
    input: &[u8],
    base_path: Option<&Path>,
    quantization: Option<QuantizationBits>,
) -> Result<Vec<u8>> {
    // Parse the full document as an opaque value we can mutate surgically.
    let is_glb = input.len() >= 4 && read_u32_le(&input[0..4]) == GLB_MAGIC;
    let (doc, container) = if is_glb {
        let (json_bytes, _) = split_glb(input)?;
        (serde_json::from_slice::<Value>(json_bytes)?, Container::Glb)
    } else {
        (serde_json::from_slice::<Value>(input)?, Container::Gltf)
    };

    // Reuse the reader (lenient: do not reject skins/animations/morph targets,
    // we only preserve them) for geometry decoding and resolved buffer bytes.
    let reader = GltfReader::from_bytes_lenient_with_base_path(input, base_path)?;
    let source_buffers: Vec<Vec<u8>> = reader.buffers().to_vec();

    let (doc, bin) = compress_gltf_value(doc, &source_buffers, quantization, |mesh, prim| {
        reader.decode_primitive_with_semantics(mesh, prim)
    })?;

    serialize(&doc, &bin, container)
}

/// The document-preserving compression core: transforms a parsed glTF document
/// (`doc`) in place, returning the mutated document plus the new single binary
/// blob. Geometry decoding is supplied by `decode`, so callers that already have
/// a parsed scene (e.g. a `gltf-rs` document) can compress without re-parsing
/// through the byte API.
///
/// `decode(mesh_index, primitive_index)` returns the primitive's geometry as a
/// [`draco_core::Mesh`] plus the `(glTF semantic, Draco attribute id)` mapping;
/// an `Err` marks the primitive as not compressible (it is preserved). `buffers`
/// holds the resolved bytes for each glTF buffer (used for repacking the
/// non-compressed buffer views).
///
/// The returned document's single buffer carries `byteLength` but no URI; the
/// caller embeds the returned `bin` (as a GLB BIN chunk or a data URI).
pub fn compress_gltf_value<F>(
    mut doc: Value,
    buffers: &[Vec<u8>],
    quantization: Option<QuantizationBits>,
    decode: F,
) -> Result<(Value, Vec<u8>)>
where
    F: Fn(usize, usize) -> Result<(draco_core::Mesh, Vec<(String, u32)>)>,
{
    if !doc.is_object() {
        return Err(GltfError::InvalidGltf("glTF root is not an object".into()));
    }
    let quant = quantization.unwrap_or_default();

    // Reference-count accessor usage across every primitive so we only mutate
    // accessors that belong exclusively to a single primitive we compress.
    let accessor_users = count_accessor_users(&doc);

    let plans = build_plans(&doc, &decode, &accessor_users, &quant)?;

    // Mutate accessors of compressed primitives: drop their buffer view and set
    // the count to the Draco-encoded value. Done before scanning for orphans so
    // the now-unreferenced geometry buffer views fall out naturally.
    apply_accessor_mutations(&mut doc, &plans)?;

    // Non-indexed primitives need a generated indices accessor (Draco glTF
    // primitives are indexed).
    add_generated_indices(&mut doc, &plans)?;

    // Repack the binary: keep only buffer views still referenced by the JSON,
    // append one Draco buffer view per compressed primitive, and reindex every
    // buffer-view reference in the document.
    let repack = repack_buffers(&mut doc, buffers, &plans)?;

    // Write the Draco extension onto each compressed primitive (after reindex,
    // so the freshly appended buffer-view indices are not remapped).
    for (i, plan) in plans.iter().enumerate() {
        let draco_bv = repack.draco_buffer_views[i];
        set_primitive_draco_extension(&mut doc, plan, draco_bv)?;
    }

    if !plans.is_empty() {
        ensure_extension_listed(&mut doc, "extensionsUsed");
        ensure_extension_listed(&mut doc, "extensionsRequired");
    }

    set_single_buffer(&mut doc, repack.bin.len());

    Ok((doc, repack.bin))
}

/// A primitive that will be compressed, with everything needed to rewrite it.
struct CompressPlan {
    mesh_idx: usize,
    prim_idx: usize,
    draco_bytes: Vec<u8>,
    /// `(glTF semantic, Draco attribute id)` for the extension's attribute map.
    semantic_to_id: Vec<(String, usize)>,
    /// Accessor index for each attribute.
    attribute_accessors: Vec<usize>,
    /// The source indices accessor, or `None` for a non-indexed primitive (a
    /// fresh indices accessor is generated, since Draco glTF primitives are
    /// always indexed).
    indices_accessor: Option<usize>,
    num_points: usize,
    num_indices: usize,
}

fn build_plans<F>(
    doc: &Value,
    decode: &F,
    accessor_users: &HashMap<usize, usize>,
    quant: &QuantizationBits,
) -> Result<Vec<CompressPlan>>
where
    F: Fn(usize, usize) -> Result<(draco_core::Mesh, Vec<(String, u32)>)>,
{
    let mut plans = Vec::new();
    let Some(meshes) = doc.get("meshes").and_then(Value::as_array) else {
        return Ok(plans);
    };

    for (mesh_idx, mesh) in meshes.iter().enumerate() {
        let Some(primitives) = mesh.get("primitives").and_then(Value::as_array) else {
            continue;
        };
        for (prim_idx, prim) in primitives.iter().enumerate() {
            if let Some(plan) =
                plan_for_primitive(prim, mesh_idx, prim_idx, decode, accessor_users, quant)?
            {
                plans.push(plan);
            }
        }
    }
    Ok(plans)
}

fn plan_for_primitive<F>(
    prim: &Value,
    mesh_idx: usize,
    prim_idx: usize,
    decode: &F,
    accessor_users: &HashMap<usize, usize>,
    quant: &QuantizationBits,
) -> Result<Option<CompressPlan>>
where
    F: Fn(usize, usize) -> Result<(draco_core::Mesh, Vec<(String, u32)>)>,
{
    // KHR_draco_mesh_compression restricts compressed primitives to TRIANGLES
    // or TRIANGLE_STRIP ("Restrictions on geometry type"), so point clouds
    // (POINTS) and line modes can never be Draco-compressed in glTF. We compress
    // the triangle list (mode 4 / default); everything else is preserved as-is.
    let mode = prim
        .get("mode")
        .and_then(Value::as_u64)
        .unwrap_or(MODE_TRIANGLES);
    if mode != MODE_TRIANGLES {
        return Ok(None);
    }
    // Skip primitives already using Draco.
    if prim
        .get("extensions")
        .and_then(|e| e.get(KHR_DRACO))
        .is_some()
    {
        return Ok(None);
    }
    // Indexed and non-indexed triangle lists are both supported. Non-indexed
    // primitives get a freshly generated indices accessor below, since Draco
    // glTF primitives are always indexed.
    let indices_accessor = prim
        .get("indices")
        .and_then(Value::as_u64)
        .map(|i| i as usize);

    // Collect attribute semantics + accessors; require a round-trippable set.
    let Some(attributes) = prim.get("attributes").and_then(Value::as_object) else {
        return Ok(None);
    };
    if attributes.is_empty() || !attributes.contains_key("POSITION") {
        return Ok(None);
    }
    let mut attribute_accessors = Vec::new();
    for accessor in attributes.values() {
        let Some(acc) = accessor.as_u64() else {
            return Ok(None);
        };
        attribute_accessors.push(acc as usize);
    }

    // All geometry accessors must be used by exactly this primitive, so that
    // dropping their buffer view / changing their count cannot corrupt another
    // primitive that shares them.
    let exclusive = |acc: usize| accessor_users.get(&acc).copied().unwrap_or(0) == 1;
    let indices_exclusive = indices_accessor.map(exclusive).unwrap_or(true);
    if !indices_exclusive || !attribute_accessors.iter().copied().all(exclusive) {
        return Ok(None);
    }

    // Decode geometry with the original glTF semantic names. An unsupported
    // attribute/layout means "leave this primitive uncompressed".
    let (mesh, semantic_to_uid) = match decode(mesh_idx, prim_idx) {
        Ok(out) => out,
        Err(_) => return Ok(None),
    };
    let (draco_bytes, info) = match encode_draco_mesh_with_info(&mesh, quant) {
        Ok(out) => out,
        Err(_) => return Ok(None),
    };

    // The decoded attribute set must match the source primitive exactly, so the
    // extension's attribute map is faithful (no dropped or renamed attribute).
    let produced: BTreeSet<&str> = semantic_to_uid.iter().map(|(s, _)| s.as_str()).collect();
    let original: BTreeSet<&str> = attributes.keys().map(String::as_str).collect();
    if produced != original {
        return Ok(None);
    }
    let semantic_to_id: Vec<(String, usize)> = semantic_to_uid
        .into_iter()
        .map(|(s, u)| (s, u as usize))
        .collect();

    Ok(Some(CompressPlan {
        mesh_idx,
        prim_idx,
        draco_bytes,
        semantic_to_id,
        attribute_accessors,
        indices_accessor,
        num_points: info.num_encoded_points,
        num_indices: info.num_encoded_faces * 3,
    }))
}

/// Counts, for each accessor index, how many primitives reference it (via
/// attributes or indices) across the whole document.
fn count_accessor_users(doc: &Value) -> HashMap<usize, usize> {
    let mut users: HashMap<usize, usize> = HashMap::new();
    let Some(meshes) = doc.get("meshes").and_then(Value::as_array) else {
        return users;
    };
    for mesh in meshes {
        let Some(primitives) = mesh.get("primitives").and_then(Value::as_array) else {
            continue;
        };
        for prim in primitives {
            if let Some(attrs) = prim.get("attributes").and_then(Value::as_object) {
                for accessor in attrs.values() {
                    if let Some(a) = accessor.as_u64() {
                        *users.entry(a as usize).or_default() += 1;
                    }
                }
            }
            if let Some(a) = prim.get("indices").and_then(Value::as_u64) {
                *users.entry(a as usize).or_default() += 1;
            }
        }
    }
    users
}

fn apply_accessor_mutations(doc: &mut Value, plans: &[CompressPlan]) -> Result<()> {
    let accessors = doc
        .get_mut("accessors")
        .and_then(Value::as_array_mut)
        .ok_or_else(|| GltfError::InvalidGltf("missing accessors array".into()))?;

    for plan in plans {
        for &acc in &plan.attribute_accessors {
            strip_geometry_accessor(accessors, acc, plan.num_points)?;
        }
        if let Some(indices) = plan.indices_accessor {
            strip_geometry_accessor(accessors, indices, plan.num_indices)?;
        }
    }
    Ok(())
}

/// For each non-indexed plan, append a fresh `SCALAR`/`UNSIGNED_INT` indices
/// accessor (no buffer view — the indices live in the Draco stream) and point
/// the primitive at it. Appending keeps existing accessor indices stable, and
/// the new accessor has no buffer view so it does not affect buffer repacking.
fn add_generated_indices(doc: &mut Value, plans: &[CompressPlan]) -> Result<()> {
    for plan in plans {
        if plan.indices_accessor.is_some() {
            continue;
        }
        let accessors = doc
            .get_mut("accessors")
            .and_then(Value::as_array_mut)
            .ok_or_else(|| GltfError::InvalidGltf("missing accessors array".into()))?;
        let new_idx = accessors.len();
        accessors.push(serde_json::json!({
            "componentType": 5125u64, // UNSIGNED_INT
            "count": plan.num_indices as u64,
            "type": "SCALAR",
        }));
        let prim = primitive_mut(doc, plan)?;
        prim.insert("indices".into(), Value::from(new_idx as u64));
    }
    Ok(())
}

/// Mutable access to a plan's primitive JSON object.
fn primitive_mut<'a>(
    doc: &'a mut Value,
    plan: &CompressPlan,
) -> Result<&'a mut Map<String, Value>> {
    doc.get_mut("meshes")
        .and_then(Value::as_array_mut)
        .and_then(|m| m.get_mut(plan.mesh_idx))
        .and_then(|m| m.get_mut("primitives"))
        .and_then(Value::as_array_mut)
        .and_then(|p| p.get_mut(plan.prim_idx))
        .and_then(Value::as_object_mut)
        .ok_or_else(|| GltfError::InvalidGltf("primitive vanished during rewrite".into()))
}

/// Removes an accessor's buffer view (its data now lives in Draco) and sets the
/// count to the Draco-encoded element count. Other fields (type, componentType,
/// min/max, normalized) are preserved.
fn strip_geometry_accessor(accessors: &mut [Value], idx: usize, count: usize) -> Result<()> {
    let accessor = accessors
        .get_mut(idx)
        .and_then(Value::as_object_mut)
        .ok_or_else(|| GltfError::InvalidGltf(format!("accessor {} out of range", idx)))?;
    accessor.remove("bufferView");
    accessor.remove("byteOffset");
    accessor.insert("count".into(), Value::from(count));
    Ok(())
}

struct Repack {
    bin: Vec<u8>,
    /// New buffer-view index for each plan's Draco stream, in plan order.
    draco_buffer_views: Vec<usize>,
}

fn repack_buffers(
    doc: &mut Value,
    source_buffers: &[Vec<u8>],
    plans: &[CompressPlan],
) -> Result<Repack> {
    let old_views: Vec<Value> = doc
        .get("bufferViews")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();

    // Which buffer views are still referenced anywhere in the JSON (accessors,
    // images, surviving Draco extensions, and any unknown extension)? Scanning
    // by key name covers known and unknown referrers uniformly.
    let mut referenced = BTreeSet::new();
    collect_buffer_view_refs(doc, &mut referenced);

    // Build the new binary: kept views (remapped), then one view per Draco blob.
    let mut bin: Vec<u8> = Vec::new();
    let mut new_views: Vec<Value> = Vec::new();
    let mut remap: HashMap<usize, usize> = HashMap::new();

    for &old_idx in &referenced {
        let view = old_views
            .get(old_idx)
            .and_then(Value::as_object)
            .ok_or_else(|| GltfError::InvalidGltf(format!("buffer view {} invalid", old_idx)))?;
        let bytes = buffer_view_bytes(view, source_buffers)?;
        align_to_4(&mut bin);
        let offset = bin.len();
        bin.extend_from_slice(bytes);

        let mut new_view = view.clone();
        new_view.insert("buffer".into(), Value::from(0u64));
        new_view.insert("byteOffset".into(), Value::from(offset as u64));
        new_view.insert("byteLength".into(), Value::from(bytes.len() as u64));
        let new_idx = new_views.len();
        new_views.push(Value::Object(new_view));
        remap.insert(old_idx, new_idx);
    }

    // Reindex every buffer-view reference in the document to the kept set.
    remap_buffer_view_refs(doc, &remap);

    // Append the Draco buffer views (not present in the JSON yet, so they are
    // intentionally added after the remap pass).
    let mut draco_buffer_views = Vec::with_capacity(plans.len());
    for plan in plans {
        align_to_4(&mut bin);
        let offset = bin.len();
        bin.extend_from_slice(&plan.draco_bytes);
        let new_idx = new_views.len();
        new_views.push(serde_json::json!({
            "buffer": 0,
            "byteOffset": offset as u64,
            "byteLength": plan.draco_bytes.len() as u64,
        }));
        draco_buffer_views.push(new_idx);
    }

    if new_views.is_empty() {
        doc.as_object_mut().unwrap().remove("bufferViews");
    } else {
        doc.as_object_mut()
            .unwrap()
            .insert("bufferViews".into(), Value::Array(new_views));
    }

    Ok(Repack {
        bin,
        draco_buffer_views,
    })
}

fn buffer_view_bytes<'a>(view: &Map<String, Value>, buffers: &'a [Vec<u8>]) -> Result<&'a [u8]> {
    let buffer_idx = view
        .get("buffer")
        .and_then(Value::as_u64)
        .ok_or_else(|| GltfError::InvalidGltf("buffer view missing buffer index".into()))?
        as usize;
    let offset = view.get("byteOffset").and_then(Value::as_u64).unwrap_or(0) as usize;
    let length = view
        .get("byteLength")
        .and_then(Value::as_u64)
        .ok_or_else(|| GltfError::InvalidGltf("buffer view missing byteLength".into()))?
        as usize;
    let buffer = buffers
        .get(buffer_idx)
        .ok_or_else(|| GltfError::InvalidGltf(format!("buffer {} not resolved", buffer_idx)))?;
    let end = offset
        .checked_add(length)
        .filter(|&e| e <= buffer.len())
        .ok_or_else(|| GltfError::InvalidGltf("buffer view out of range".into()))?;
    Ok(&buffer[offset..end])
}

/// Recursively collect every integer found under a `"bufferView"` key.
fn collect_buffer_view_refs(value: &Value, out: &mut BTreeSet<usize>) {
    match value {
        Value::Object(map) => {
            for (key, child) in map {
                if let Some(idx) = child.as_u64().filter(|_| key == "bufferView") {
                    out.insert(idx as usize);
                }
                collect_buffer_view_refs(child, out);
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_buffer_view_refs(item, out);
            }
        }
        _ => {}
    }
}

/// Recursively remap every integer under a `"bufferView"` key using `remap`.
fn remap_buffer_view_refs(value: &mut Value, remap: &HashMap<usize, usize>) {
    match value {
        Value::Object(map) => {
            for (key, child) in map.iter_mut() {
                if let Some(old) = child.as_u64().filter(|_| key == "bufferView") {
                    if let Some(&new) = remap.get(&(old as usize)) {
                        *child = Value::from(new as u64);
                    }
                }
                remap_buffer_view_refs(child, remap);
            }
        }
        Value::Array(items) => {
            for item in items {
                remap_buffer_view_refs(item, remap);
            }
        }
        _ => {}
    }
}

fn set_primitive_draco_extension(
    doc: &mut Value,
    plan: &CompressPlan,
    draco_buffer_view: usize,
) -> Result<()> {
    let prim = primitive_mut(doc, plan)?;

    let mut attributes = Map::new();
    for (semantic, id) in &plan.semantic_to_id {
        attributes.insert(semantic.clone(), Value::from(*id as u64));
    }
    let draco = serde_json::json!({
        "bufferView": draco_buffer_view as u64,
        "attributes": Value::Object(attributes),
    });

    let extensions = prim
        .entry("extensions")
        .or_insert_with(|| Value::Object(Map::new()));
    if !extensions.is_object() {
        return Err(GltfError::InvalidGltf(
            "primitive.extensions is not an object".into(),
        ));
    }
    extensions
        .as_object_mut()
        .unwrap()
        .insert(KHR_DRACO.into(), draco);
    Ok(())
}

/// Adds `KHR_draco_mesh_compression` to a root string array (creating it if
/// absent) without duplicating it.
fn ensure_extension_listed(doc: &mut Value, key: &str) {
    let root = doc.as_object_mut().unwrap();
    let list = root.entry(key).or_insert_with(|| Value::Array(Vec::new()));
    let Some(arr) = list.as_array_mut() else {
        return;
    };
    if !arr.iter().any(|v| v.as_str() == Some(KHR_DRACO)) {
        arr.push(Value::from(KHR_DRACO));
    }
}

/// Collapses the document to a single buffer of `bin_len` bytes (carrying
/// `byteLength` but no URI). The caller embeds the bytes: `serialize` fills a
/// data URI for glTF output, or writes a GLB BIN chunk.
fn set_single_buffer(doc: &mut Value, bin_len: usize) {
    let root = doc.as_object_mut().unwrap();
    if bin_len == 0 {
        root.remove("buffers");
        return;
    }
    let mut buffer = Map::new();
    buffer.insert("byteLength".into(), Value::from(bin_len as u64));
    root.insert("buffers".into(), Value::Array(vec![Value::Object(buffer)]));
}

#[cfg(feature = "gltf-reader")]
fn serialize(doc: &Value, bin: &[u8], container: Container) -> Result<Vec<u8>> {
    match container {
        Container::Gltf => {
            // Re-emit with the buffer's data URI carrying the real bytes.
            let mut doc = doc.clone();
            if !bin.is_empty() {
                let uri = format!(
                    "data:application/octet-stream;base64,{}",
                    base64_encode(bin)
                );
                if let Some(buffers) = doc.get_mut("buffers").and_then(Value::as_array_mut) {
                    if let Some(buffer) = buffers.get_mut(0).and_then(Value::as_object_mut) {
                        buffer.insert("uri".into(), Value::from(uri));
                    }
                }
            }
            Ok(serde_json::to_vec(&doc)?)
        }
        Container::Glb => build_glb(doc, bin),
    }
}

#[cfg(feature = "gltf-reader")]
fn build_glb(doc: &Value, bin: &[u8]) -> Result<Vec<u8>> {
    let mut json = serde_json::to_vec(doc)?;
    while !json.len().is_multiple_of(4) {
        json.push(b' ');
    }
    let mut bin_padded = bin.to_vec();
    while !bin_padded.len().is_multiple_of(4) {
        bin_padded.push(0);
    }

    let has_bin = !bin_padded.is_empty();
    let mut total = 12 + 8 + json.len();
    if has_bin {
        total += 8 + bin_padded.len();
    }

    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(&GLB_MAGIC.to_le_bytes());
    out.extend_from_slice(&GLB_VERSION.to_le_bytes());
    out.extend_from_slice(&(total as u32).to_le_bytes());

    out.extend_from_slice(&(json.len() as u32).to_le_bytes());
    out.extend_from_slice(&GLB_CHUNK_JSON.to_le_bytes());
    out.extend_from_slice(&json);

    if has_bin {
        out.extend_from_slice(&(bin_padded.len() as u32).to_le_bytes());
        out.extend_from_slice(&GLB_CHUNK_BIN.to_le_bytes());
        out.extend_from_slice(&bin_padded);
    }

    Ok(out)
}

/// Returns the GLB JSON chunk bytes and optional BIN chunk bytes.
#[cfg(feature = "gltf-reader")]
fn split_glb(data: &[u8]) -> Result<(&[u8], Option<&[u8]>)> {
    if data.len() < 12 {
        return Err(GltfError::InvalidGlb(
            "file too small for GLB header".into(),
        ));
    }
    if read_u32_le(&data[0..4]) != GLB_MAGIC {
        return Err(GltfError::InvalidGlb("bad GLB magic".into()));
    }
    let total = read_u32_le(&data[8..12]) as usize;
    if total > data.len() {
        return Err(GltfError::InvalidGlb("GLB length exceeds data".into()));
    }

    let mut json: Option<&[u8]> = None;
    let mut bin: Option<&[u8]> = None;
    let mut pos = 12;
    while pos + 8 <= total {
        let len = read_u32_le(&data[pos..pos + 4]) as usize;
        let kind = read_u32_le(&data[pos + 4..pos + 8]);
        let start = pos + 8;
        let end = start
            .checked_add(len)
            .filter(|&e| e <= total)
            .ok_or_else(|| GltfError::InvalidGlb("GLB chunk out of range".into()))?;
        match kind {
            GLB_CHUNK_JSON => json = Some(&data[start..end]),
            GLB_CHUNK_BIN => bin = Some(&data[start..end]),
            _ => {}
        }
        pos = end;
    }
    let json = json.ok_or_else(|| GltfError::InvalidGlb("GLB has no JSON chunk".into()))?;
    Ok((json, bin))
}

#[cfg(feature = "gltf-reader")]
fn read_u32_le(bytes: &[u8]) -> u32 {
    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
}

fn align_to_4(buf: &mut Vec<u8>) {
    while !buf.len().is_multiple_of(4) {
        buf.push(0);
    }
}

#[cfg(feature = "gltf-reader")]
fn base64_encode(data: &[u8]) -> String {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = *chunk.get(1).unwrap_or(&0) as u32;
        let b2 = *chunk.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(TABLE[(n >> 18) as usize & 0x3F] as char);
        out.push(TABLE[(n >> 12) as usize & 0x3F] as char);
        out.push(if chunk.len() > 1 {
            TABLE[(n >> 6) as usize & 0x3F] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            TABLE[n as usize & 0x3F] as char
        } else {
            '='
        });
    }
    out
}