polysmelt 0.14.0

Pure-Rust 3D asset interchange: glTF/GLB reading and writing, meshopt compression, and readers for common mesh formats, SketchUp included
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! The common form every reader produces: a glTF 2.0 document, its JSON and its buffers' bytes,
//! carrying whatever the source had (scene graph, animation, skins, morph targets, materials,
//! cameras, lights, names, extras).
//!
//! - [`Document::to_glb`] and [`Document::write_glb`] serialize it: every buffer goes into the
//!   GLB's binary chunk as it is, compression included. Nothing is decoded or repacked.
//! - [`Document::flatten`] derives the flat, posed triangle [`Mesh`] (for counting, previews or
//!   tools that want plain triangles), and [`Document::counts`] counts what it draws from the
//!   JSON alone.
//! - [`Document::decode`] rewrites it as plain glTF 2.0: meshopt and Draco decoded, quantized
//!   attributes as floats.
//! - [`Document::prune`] drops what a [`Keep`] doesn't keep (animations, skins, materials, ...);
//!   the loaders in [`formats`](crate::formats) apply it.
//!
//! The JSON's buffers have no `uri`: each has its bytes here, in memory, in a file the document
//! reads as needed (a GLB's binary chunk), or, for a meshopt fallback buffer, nowhere. Images
//! name a buffer view, or keep their `uri` when the file they name wasn't found.

use std::borrow::Cow;
use std::fmt;
#[cfg(feature = "fs")]
use std::fs::File;
use std::io::Write;
#[cfg(feature = "fs")]
use std::sync::Mutex;

use serde_json::{Map, Value, json};

use crate::gltf as container;
use crate::images::{Refs, Source};
use crate::material::{Full, Writer};
use crate::mesh::{Bone, Image, MAX_POINTS, MAX_TRIANGLES, Material, Mesh, Prim, TRIANGLE_CEILING};
use crate::num::usize_of;
use crate::{Context as _, Result};

pub use crate::keep::Keep;

/// A model as a glTF 2.0 document: its JSON, its buffers' bytes, and facts about the source.
pub struct Document<'a> {
    /// The glTF JSON. Its buffers have no `uri`; their bytes are held by the document (see
    /// [`Document::buffer`] and [`Document::push_buffer`]).
    pub json: Map<String, Value>,
    /// Buffer `i`'s bytes, for each of the JSON's buffers.
    pub(crate) buffers: Vec<Blob<'a>>,
    /// Facts worth recording about the source: `triangles`, and per format `points`, `lines`,
    /// `vertices`, `voxels`, `voxel_size`, `models`, `objects`, `colors`, `application`, and for
    /// motion capture `joints`, `channels`, `frames`, `frame_time` and `dropped_frames`.
    pub facts: Map<String, Value>,
    /// The images named but not read, by image index (see [`Document::images`]).
    pub(crate) refs: Refs,
    /// The most triangles [`Document::flatten`] draws (see [`Document::set_max_triangles`]).
    pub(crate) max_triangles: usize,
    /// Whether [`Document::flatten`] draws points and lines (see
    /// [`Document::set_lines_and_points`]).
    pub(crate) lines_and_points: bool,
    /// The most points and line segments [`Document::flatten`] draws (see
    /// [`Document::set_max_points`]).
    pub(crate) max_points: usize,
}

impl fmt::Debug for Document<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Document")
            .field("json", &self.json)
            .field("buffers", &self.buffers.iter().map(Blob::len).collect::<Vec<_>>())
            .field("facts", &self.facts)
            .finish()
    }
}

/// Which pose [`Document::flatten`] draws.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum Pose {
    /// The nodes' own transforms and morph weights.
    #[default]
    Rest,
    /// Animation `index` at `time` seconds: the channels it has override the rest pose; before
    /// its first key or after its last, the first or last value holds.
    Animation { index: usize, time: f32 },
    /// As `Rest`, but skinned meshes as their files store them: in the pose they were bound in,
    /// their vertices not moved by their joints, and the skeleton where the inverse bind matrices
    /// put it. Joints and weights still come with them, to pose with your own skinning. Quicker
    /// than `Rest` on skinned meshes, and the same wherever the nodes stand as they were bound.
    Bind,
}

/// What a document's default scene draws, every instance counted, as the JSON declares it:
/// indices aren't read, so triangles naming a missing vertex (which [`Document::flatten`] drops)
/// are counted.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    pub triangles: usize,
    pub points: usize,
    /// Line segments: a strip or loop of n points is n - 1 or n of them.
    pub lines: usize,
}

/// Where a buffer's bytes are.
pub(crate) enum Blob<'a> {
    /// In memory: borrowed from the input (a GLB's binary chunk, an asset), or owned.
    Bytes(Cow<'a, [u8]>),
    /// A stretch of a file, read as needed.
    #[cfg(feature = "fs")]
    #[cfg_attr(not(feature = "gltf"), allow(dead_code, reason = "only the glTF reader makes one"))]
    File(FileSpan),
    /// Typed arrays a reader built, laid end to end.
    Parts(Parts),
    /// A meshopt fallback buffer that isn't there: only its length. Views on it decode from
    /// their compressed data.
    #[cfg_attr(not(feature = "gltf"), allow(dead_code, reason = "only the glTF reader makes one"))]
    Missing(u64),
}

/// A stretch of a file: `len` bytes from `base`.
#[cfg(feature = "fs")]
pub(crate) struct FileSpan {
    file: Mutex<Cursor>,
    base: u64,
    len: u64,
}

/// A [`FileSpan`]'s file and what was last read ahead of it.
#[cfg(feature = "fs")]
struct Cursor {
    file: File,
    /// Where the file's cursor is relative to the span's base, to skip needless seeks.
    at: u64,
    /// Bytes read ahead from `ahead_at`: small reads (animation keys, a skin's matrices, little meshes' accessors), one
    /// after another through the file, come from here rather than each its own system call.
    ahead: Vec<u8>,
    ahead_at: u64,
}

/// How far a small read reads ahead.
#[cfg(feature = "fs")]
const AHEAD: usize = 64 * 1024;

#[cfg(feature = "fs")]
impl FileSpan {
    /// `len` bytes of `file` from `base`; its cursor is at `base + at`.
    #[cfg_attr(not(feature = "gltf"), allow(dead_code, reason = "only the glTF reader makes one"))]
    pub(crate) fn new(file: File, base: u64, len: u64, at: u64) -> Self {
        Self {
            file: Mutex::new(Cursor {
                file,
                at,
                ahead: Vec::new(),
                ahead_at: 0,
            }),
            base,
            len,
        }
    }

    /// Copies the bytes from `off` into `out`, which must lie within the span.
    fn read_at(&self, off: u64, out: &mut [u8]) -> Result<()> {
        let mut c = self.file.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        let end = off + out.len() as u64;
        if off >= c.ahead_at && end <= c.ahead_at + c.ahead.len() as u64 {
            let from = usize_of(off - c.ahead_at);
            out.copy_from_slice(&c.ahead[from..from + out.len()]);
            return Ok(());
        }
        if out.len() >= AHEAD / 2 {
            return self.read_file(&mut c, off, out);
        }
        let n = usize_of((self.len - off).min(AHEAD as u64));
        let mut ahead = std::mem::take(&mut c.ahead);
        ahead.resize(n, 0);
        c.ahead_at = 0;
        let read = self.read_file(&mut c, off, &mut ahead);
        if read.is_ok() {
            out.copy_from_slice(&ahead[..out.len()]);
            c.ahead_at = off;
        } else {
            ahead.clear();
        }
        c.ahead = ahead;
        read
    }

    fn read_file(&self, c: &mut Cursor, off: u64, out: &mut [u8]) -> Result<()> {
        use std::io::{Read, Seek, SeekFrom};
        if c.at != off {
            c.file.seek(SeekFrom::Start(self.base + off))?;
        }
        // Until the read succeeds, the cursor isn't known.
        c.at = u64::MAX;
        c.file.read_exact(out)?;
        c.at = off + out.len() as u64;
        Ok(())
    }
}

/// Typed arrays laid end to end, each at a 4-byte boundary, read as little-endian bytes in
/// place.
#[derive(Default)]
pub(crate) struct Parts {
    /// Each part and its offset.
    list: Vec<(u64, Part)>,
    len: u64,
}

/// One typed array of a [`Parts`].
pub(crate) enum Part {
    F32(Vec<f32>),
    U32(Vec<u32>),
    U16(Vec<u16>),
    Bytes(Vec<u8>),
}

#[allow(dead_code, reason = "readers use the part types their formats need")]
impl Part {
    /// Floats, stored as they are on a little-endian target (and byte-swapped once otherwise).
    pub(crate) fn f32(v: Vec<f32>) -> Self {
        if cfg!(target_endian = "little") {
            Part::F32(v)
        } else {
            Part::Bytes(v.iter().flat_map(|x| x.to_le_bytes()).collect())
        }
    }

    pub(crate) fn u32(v: Vec<u32>) -> Self {
        if cfg!(target_endian = "little") {
            Part::U32(v)
        } else {
            Part::Bytes(v.iter().flat_map(|x| x.to_le_bytes()).collect())
        }
    }

    pub(crate) fn u16(v: Vec<u16>) -> Self {
        if cfg!(target_endian = "little") {
            Part::U16(v)
        } else {
            Part::Bytes(v.iter().flat_map(|x| x.to_le_bytes()).collect())
        }
    }

    pub(crate) fn bytes(v: Vec<u8>) -> Self {
        Part::Bytes(v)
    }

    /// The part as a GLB stores it. Typed parts exist only on little-endian targets, where
    /// their memory is that.
    fn as_bytes(&self) -> &[u8] {
        match self {
            Part::F32(v) => bytemuck::cast_slice(v),
            Part::U32(v) => bytemuck::cast_slice(v),
            Part::U16(v) => bytemuck::cast_slice(v),
            Part::Bytes(v) => v,
        }
    }
}

impl Parts {
    /// Adds a part at the next 4-byte boundary; returns its offset and length.
    pub(crate) fn push(&mut self, part: Part) -> (u64, u64) {
        let at = self.len.next_multiple_of(4);
        let n = part.as_bytes().len() as u64;
        self.list.push((at, part));
        self.len = at + n;
        (at, n)
    }

    /// The part holding `off`, if any: its index.
    fn part_at(&self, off: u64) -> Option<usize> {
        let i = self.list.partition_point(|(at, _)| *at <= off).checked_sub(1)?;
        Some(i)
    }

    fn slice(&self, off: u64, len: u64) -> Option<&[u8]> {
        let (at, part) = &self.list[self.part_at(off)?];
        let bytes = part.as_bytes();
        let start = usize_of(off - at);
        bytes.get(start..start.checked_add(usize_of(len))?)
    }

    fn read_at(&self, off: u64, out: &mut [u8]) {
        out.fill(0);
        let end = off + out.len() as u64;
        let first = self.part_at(off).unwrap_or(0);
        for (at, part) in &self.list[first..] {
            if *at >= end {
                break;
            }
            let bytes = part.as_bytes();
            let (from, to) = (off.max(*at), end.min(at + bytes.len() as u64));
            if from < to {
                out[usize_of(from - off)..usize_of(to - off)]
                    .copy_from_slice(&bytes[usize_of(from - at)..usize_of(to - at)]);
            }
        }
    }

    fn write_to(&self, len: u64, w: &mut dyn Write) -> Result<()> {
        let mut pos = 0;
        for (at, part) in &self.list {
            if pos >= len {
                break;
            }
            write_zeros(w, (*at).min(len) - pos)?;
            let bytes = part.as_bytes();
            let take = usize_of((len - at).min(bytes.len() as u64));
            w.write_all(&bytes[..take])?;
            pos = at + take as u64;
        }
        write_zeros(w, len.saturating_sub(pos))
    }
}

fn write_zeros(w: &mut dyn Write, n: u64) -> Result<()> {
    use std::io::Read as _;
    std::io::copy(&mut std::io::repeat(0).take(n), w)?;
    Ok(())
}

impl Blob<'_> {
    pub(crate) fn len(&self) -> u64 {
        match self {
            Blob::Bytes(b) => b.len() as u64,
            #[cfg(feature = "fs")]
            Blob::File(f) => f.len,
            Blob::Parts(p) => p.len,
            Blob::Missing(n) => *n,
        }
    }

    /// `len` bytes from `off`, in place, when they are in memory in one piece.
    pub(crate) fn slice(&self, off: u64, len: u64) -> Option<&[u8]> {
        match self {
            Blob::Bytes(b) => b.get(usize_of(off)..usize_of(off.checked_add(len)?)),
            Blob::Parts(p) => p.slice(off, len),
            #[cfg(feature = "fs")]
            Blob::File(_) => None,
            Blob::Missing(_) => None,
        }
    }

    /// Copies the bytes from `off` into `out`.
    pub(crate) fn read_at(&self, off: u64, out: &mut [u8]) -> Result<()> {
        let end = off
            .checked_add(out.len() as u64)
            .filter(|&e| e <= self.len())
            .context("glTF data runs past the end of its buffer")?;
        match self {
            Blob::Bytes(b) => out.copy_from_slice(&b[usize_of(off)..usize_of(end)]),
            #[cfg(feature = "fs")]
            Blob::File(f) => f.read_at(off, out)?,
            Blob::Parts(p) => p.read_at(off, out),
            Blob::Missing(_) => bail!("glTF data is in a meshopt fallback buffer, which holds none"),
        }
        Ok(())
    }

    /// Writes the first `len` bytes.
    fn write_to(&self, len: u64, w: &mut dyn Write) -> Result<()> {
        ensure!(
            len <= self.len(),
            "glTF buffer holds {} bytes but declares {len}",
            self.len()
        );
        match self {
            Blob::Bytes(b) => w.write_all(&b[..usize_of(len)])?,
            #[cfg(feature = "fs")]
            Blob::File(f) => {
                let mut chunk = vec![0; usize_of(len.min(1 << 20))];
                let mut at = 0;
                while at < len {
                    let n = usize_of((len - at).min(chunk.len() as u64));
                    f.read_at(at, &mut chunk[..n])?;
                    w.write_all(&chunk[..n])?;
                    at += n as u64;
                }
            }
            Blob::Parts(p) => p.write_to(len, w)?,
            Blob::Missing(_) => bail!("a meshopt fallback buffer has no bytes to write"),
        }
        Ok(())
    }

    fn into_owned(self) -> Blob<'static> {
        match self {
            Blob::Bytes(b) => Blob::Bytes(Cow::Owned(b.into_owned())),
            #[cfg(feature = "fs")]
            Blob::File(f) => Blob::File(f),
            Blob::Parts(p) => Blob::Parts(p),
            Blob::Missing(n) => Blob::Missing(n),
        }
    }
}

fn list<'v>(obj: &'v Map<String, Value>, key: &str) -> &'v [Value] {
    obj.get(key).and_then(Value::as_array).map_or(&[], Vec::as_slice)
}

impl<'a> Document<'a> {
    /// A document that draws nothing: only the `asset` glTF requires.
    #[must_use]
    pub fn empty(facts: Map<String, Value>) -> Document<'static> {
        let Value::Object(json) = json!({ "asset": { "version": "2.0", "generator": "polysmelt" } }) else {
            unreachable!()
        };
        Document {
            json,
            buffers: Vec::new(),
            facts,
            refs: Refs::new(),
            max_triangles: MAX_TRIANGLES,
            lines_and_points: true,
            max_points: MAX_POINTS,
        }
    }

    /// The document with every borrowed buffer copied, so it outlives its input.
    #[must_use]
    pub fn into_owned(self) -> Document<'static> {
        Document {
            json: self.json,
            buffers: self.buffers.into_iter().map(Blob::into_owned).collect(),
            facts: self.facts,
            refs: self.refs,
            max_triangles: self.max_triangles,
            lines_and_points: self.lines_and_points,
            max_points: self.max_points,
        }
    }

    /// The most triangles [`Document::flatten`] draws before it refuses: the load's
    /// [`Keep::max_triangles`], or [`MAX_TRIANGLES`] for a document built otherwise.
    #[must_use]
    pub fn max_triangles(&self) -> usize {
        self.max_triangles
    }

    /// Sets the most triangles [`Document::flatten`] draws before it refuses, as
    /// [`Keep::max_triangles`] does for a load: values past [`TRIANGLE_CEILING`] are clamped.
    pub fn set_max_triangles(&mut self, n: usize) {
        self.max_triangles = n.min(TRIANGLE_CEILING);
    }

    /// Whether [`Document::flatten`] draws points and lines: the load's
    /// [`Keep::lines_and_points`], or `true` for a document built otherwise.
    #[must_use]
    pub fn lines_and_points(&self) -> bool {
        self.lines_and_points
    }

    /// Sets whether [`Document::flatten`] draws points and lines, as [`Keep::lines_and_points`]
    /// does for a load.
    pub fn set_lines_and_points(&mut self, on: bool) {
        self.lines_and_points = on;
    }

    /// The most points and line segments [`Document::flatten`] draws before it refuses: the
    /// load's [`Keep::max_points`], or [`MAX_POINTS`] for a document built otherwise.
    #[must_use]
    pub fn max_points(&self) -> usize {
        self.max_points
    }

    /// Sets the most points and line segments [`Document::flatten`] draws before it refuses, as
    /// [`Keep::max_points`] does for a load: values past [`TRIANGLE_CEILING`] are clamped.
    pub fn set_max_points(&mut self, n: usize) {
        self.max_points = n.min(TRIANGLE_CEILING);
    }

    /// Buffer `i`'s bytes, whole (borrowed when they are in memory in one piece).
    ///
    /// # Errors
    ///
    /// When buffer `i` doesn't exist, holds no bytes (a meshopt fallback buffer), or its file
    /// can't be read.
    pub fn buffer(&self, i: usize) -> Result<Cow<'_, [u8]>> {
        let b = self
            .buffers
            .get(i)
            .with_context(|| format!("glTF buffers[{i}] doesn't exist"))?;
        if let Some(s) = b.slice(0, b.len()) {
            return Ok(Cow::Borrowed(s));
        }
        let mut out = vec![0; usize_of(b.len())];
        b.read_at(0, &mut out)?;
        Ok(Cow::Owned(out))
    }

    /// Buffer view `i`'s bytes.
    pub(crate) fn view_bytes(&self, i: usize) -> Result<Cow<'_, [u8]>> {
        let v = list(&self.json, "bufferViews")
            .get(i)
            .with_context(|| format!("glTF bufferViews[{i}] doesn't exist"))?;
        let num = |k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0);
        let (offset, len) = (num("byteOffset"), num("byteLength"));
        let b = self
            .buffers
            .get(usize_of(num("buffer")))
            .context("glTF buffer view names a missing buffer")?;
        ensure!(
            offset.saturating_add(len) <= b.len(),
            "glTF buffer view runs past its buffer"
        );
        if let Some(s) = b.slice(offset, len) {
            return Ok(Cow::Borrowed(s));
        }
        let mut out = vec![0; usize_of(len)];
        b.read_at(offset, &mut out)?;
        Ok(Cow::Owned(out))
    }

    /// Adds a buffer holding `bytes`; returns its index.
    pub fn push_buffer(&mut self, bytes: Vec<u8>) -> usize {
        self.push_blob(Blob::Bytes(Cow::Owned(bytes)))
    }

    pub(crate) fn push_blob(&mut self, blob: Blob<'a>) -> usize {
        let buffers = self
            .json
            .entry("buffers")
            .or_insert_with(|| json!([]))
            .as_array_mut()
            .expect("glTF buffers is a list");
        buffers.push(json!({ "byteLength": blob.len() }));
        self.buffers.push(blob);
        self.buffers.len() - 1
    }

    /// Adds a buffer view of a whole buffer; returns its index.
    pub(crate) fn push_view(&mut self, view: Value) -> usize {
        let views = self
            .json
            .entry("bufferViews")
            .or_insert_with(|| json!([]))
            .as_array_mut()
            .expect("glTF bufferViews is a list");
        views.push(view);
        views.len() - 1
    }

    /// The document as a GLB.
    ///
    /// # Errors
    ///
    /// When a buffer holds fewer bytes than it declares, a buffer's file can't be read, or the
    /// GLB would be over 4 GiB.
    pub fn to_glb(&self) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        self.write_glb(&mut out)?;
        Ok(out)
    }

    /// Writes the document as a GLB: the JSON with every buffer's bytes in its binary chunk,
    /// each where its buffer views (and meshopt data) now point.
    ///
    /// # Errors
    ///
    /// As [`Document::to_glb`], and when writing fails.
    #[allow(
        clippy::cast_possible_truncation,
        reason = "each chunk is smaller than `total`, which is checked to fit"
    )]
    pub fn write_glb(&self, w: &mut dyn Write) -> Result<()> {
        let (json, layout, bin_len) = self.glb_json()?;
        let mut text = serde_json::to_vec(&Value::Object(json))?;
        text.resize(text.len().next_multiple_of(4), b' ');
        let padded = bin_len.map(|n| n.next_multiple_of(4));
        let total = 12 + 8 + text.len() as u64 + padded.map_or(0, |n| 8 + n);
        let total = u32::try_from(total).map_err(|_| invalid!("GLB would be over 4 GiB"))?;
        let mut head = Vec::with_capacity(28);
        head.extend_from_slice(b"glTF");
        head.extend_from_slice(&2u32.to_le_bytes());
        head.extend_from_slice(&total.to_le_bytes());
        head.extend_from_slice(&(text.len() as u32).to_le_bytes());
        head.extend_from_slice(b"JSON");
        w.write_all(&head)?;
        w.write_all(&text)?;
        if let Some(padded) = padded {
            w.write_all(&(padded as u32).to_le_bytes())?;
            w.write_all(b"BIN\0")?;
            let mut pos = 0;
            for (i, at, len) in layout {
                write_zeros(w, at - pos)?;
                self.buffers[i].write_to(len, w)?;
                pos = at + len;
            }
            write_zeros(w, padded - pos)?;
        }
        Ok(())
    }

    /// The GLB's JSON, where each buffer with bytes goes in the binary chunk (buffer, offset,
    /// length), and the binary chunk's length (`None` for none).
    #[allow(clippy::type_complexity, reason = "a private step of write_glb")]
    fn glb_json(&self) -> Result<(Map<String, Value>, Vec<(usize, u64, u64)>, Option<u64>)> {
        let mut json = self.json.clone();
        let buffers = list(&json, "buffers");
        ensure!(
            buffers.len() == self.buffers.len(),
            "glTF document lists {} buffers but holds {}",
            buffers.len(),
            self.buffers.len()
        );
        // Each buffer's new home: (buffer, offset). Buffers with bytes share the binary chunk;
        // missing fallbacks follow as buffers without data.
        let mut home = Vec::with_capacity(buffers.len());
        let mut layout = Vec::new();
        let mut placeholders = Vec::new();
        let mut bin_len = 0u64;
        for (i, (b, blob)) in buffers.iter().zip(&self.buffers).enumerate() {
            let declared = b.get("byteLength").and_then(Value::as_u64).unwrap_or(0);
            if let Blob::Missing(_) = blob {
                let mut p = b.as_object().cloned().unwrap_or_default();
                p.remove("uri");
                placeholders.push(Value::Object(p));
                home.push((placeholders.len(), 0));
                continue;
            }
            ensure!(
                blob.len() >= declared,
                "glTF buffer {i} holds {} bytes but declares {declared}",
                blob.len()
            );
            bin_len = bin_len.next_multiple_of(4);
            home.push((0, usize_of(bin_len)));
            layout.push((i, bin_len, declared));
            bin_len += declared;
        }
        let mut required = Vec::new();
        let views = json.get_mut("bufferViews").and_then(Value::as_array_mut);
        for (i, v) in views.into_iter().flatten().enumerate() {
            let v = v
                .as_object_mut()
                .with_context(|| format!("glTF buffer view {i} is not an object"))?;
            let (vb, _) = container::rehome(v, &home).with_context(|| format!("glTF buffer view {i}"))?;
            let exts = v.get_mut("extensions").and_then(Value::as_object_mut);
            for (name, ext) in exts.into_iter().flatten() {
                if !container::MESHOPT_EXTENSIONS.contains(&name.as_str()) {
                    continue;
                }
                let ext = ext.as_object_mut().context("bad meshopt extension")?;
                let (b, _) = container::rehome(ext, &home).with_context(|| format!("glTF buffer view {i}"))?;
                ensure!(
                    b == 0,
                    "glTF buffer view {i}: its compressed data is in a missing buffer"
                );
                if vb != 0 {
                    required.push(name.clone());
                }
            }
        }
        // Views on a missing fallback need the extension to be read at all.
        for name in required {
            container::require_extension(&mut json, &name);
        }
        let has_views = !list(&json, "bufferViews").is_empty();
        if layout.is_empty() && placeholders.is_empty() && !has_views {
            json.remove("buffers");
            return Ok((json, layout, None));
        }
        let mut buffers = vec![json!({ "byteLength": bin_len })];
        buffers.extend(placeholders);
        json.insert("buffers".into(), Value::Array(buffers));
        Ok((json, layout, Some(bin_len)))
    }

    /// The document for a mesh: one node drawing one mesh, a primitive per material (and one for
    /// the lines and one for the points of each, sharing its vertices),
    /// its arrays moved into the document's buffer without a copy. Skinned primitives, when the
    /// mesh has a skeleton, are a second mesh on a node with a skin: a node per bone, and
    /// inverse bind matrices that bind the vertices where they are, so the document draws as the
    /// mesh does and moves with its bones.
    #[must_use]
    pub fn from_mesh(mesh: Mesh, facts: Map<String, Value>) -> Document<'static> {
        let Mesh {
            prims,
            materials,
            images,
            skeleton,
        } = mesh;
        let images = images.into_iter().map(Source::Image).collect();
        let (skinned, rigid): (Vec<Prim>, Vec<Prim>) = if skeleton.is_empty() {
            (Vec::new(), prims)
        } else {
            prims.into_iter().partition(Prim::skinned)
        };
        let mut meshes = vec![(None, rigid)];
        if !skinned.is_empty() {
            meshes.push((None, skinned));
        }
        Self::from_named(meshes, &materials, images, None, facts, &skeleton)
    }

    /// The document for named meshes sharing `materials` and `images`: a node drawing each, in
    /// order, skipping those that draw nothing; `source` becomes the asset's
    /// `extras.source`. A mesh whose primitives are all skinned is bound to `skeleton`, when
    /// there is one.
    pub(crate) fn from_named(
        mut meshes: Vec<(Option<String>, Vec<Prim>)>,
        materials: &[Material],
        images: Vec<Source>,
        source: Option<Value>,
        facts: Map<String, Value>,
        skeleton: &[Bone],
    ) -> Document<'static> {
        let materials = texcoords(&mut meshes, materials);
        let mut b = Builder::default();
        let rig = (!skeleton.is_empty() && meshes.iter().any(|(_, p)| !p.is_empty() && p.iter().all(Prim::skinned)))
            .then(|| Rigging::new(skeleton, meshes.iter().flat_map(|(_, p)| p)));
        let (mut nodes, mut out) = (Vec::new(), Vec::new());
        let mut skinned_node = None;
        for (name, prims) in meshes {
            let skinned = !prims.is_empty() && prims.iter().all(Prim::skinned);
            b.joints = rig.as_ref().filter(|_| skinned).map(|r| (r.offset, r.joints.len()));
            let Some(mut mesh) = b.mesh(prims, materials.len()) else {
                continue;
            };
            let mut node = json!({ "mesh": out.len() });
            if let Some(name) = name {
                mesh["name"] = json!(name);
                node["name"] = json!(name);
            }
            if b.joints.is_some() {
                node["skin"] = json!(0);
                skinned_node = Some(nodes.len());
            }
            out.push(mesh);
            nodes.push(node);
        }
        b.joints = None;
        if out.is_empty() {
            return Document::empty(facts);
        }
        let mut json = Map::new();
        if let Some(source) = source {
            json.insert("asset".into(), json!({ "extras": { "source": source } }));
        }
        let mut scene: Vec<usize> = (0..nodes.len()).collect();
        if let (Some(rig), Some(_)) = (&rig, skinned_node) {
            scene.extend(rig.write(&mut b, &mut nodes, &mut json));
        }
        json.insert("scene".into(), json!(0));
        json.insert("scenes".into(), json!([{ "nodes": scene }]));
        json.insert("nodes".into(), Value::Array(nodes));
        json.insert("meshes".into(), Value::Array(out));
        b.materials(&materials, images, &mut json);
        b.finish(json, facts)
    }
}

/// The glTF materials for `materials`, their textures reading the coordinate sets as each primitive using them
/// numbers its sets (the color texture's first, then the others that are there, in order). A material with a
/// texture on another set ([`Sampling::uv_set`](crate::mesh::Sampling::uv_set)) gets a copy for each numbering
/// the primitives give it, and the primitives are pointed at theirs.
fn texcoords(meshes: &mut [(Option<String>, Vec<Prim>)], materials: &[Material]) -> Vec<Full> {
    let mut out: Vec<Full> = materials.iter().map(Full::from).collect();
    let last = materials.len().saturating_sub(1);
    // The other sets each material's textures read, in order.
    let sets: Vec<Vec<usize>> = materials
        .iter()
        .map(|m| {
            let used = std::cell::RefCell::new(Vec::new());
            Full::of(m, |s| {
                used.borrow_mut().extend(s);
                Some(0)
            });
            let mut used = used.into_inner();
            used.sort_unstable();
            used.dedup();
            used
        })
        .collect();
    // (material, the numbers its sets get, the material written for them).
    let mut copies: Vec<(usize, Vec<Option<u32>>, usize)> = Vec::new();
    for p in meshes.iter_mut().flat_map(|(_, p)| p) {
        let i = p.material.min(last);
        let Some(want) = sets.get(i).filter(|s| !s.is_empty()) else {
            continue;
        };
        let n = p.positions.len();
        let first = u32::from(p.uvs.len() == n);
        let numbers: Vec<Option<u32>> = want
            .iter()
            .map(|&s| {
                p.uv_sets.get(s).filter(|v| v.len() == n)?;
                let before = p.uv_sets[..s].iter().filter(|v| v.len() == n).count();
                Some(first + u32::try_from(before).ok()?)
            })
            .collect();
        if let Some(c) = copies.iter().find(|c| c.0 == i && c.1 == numbers) {
            p.material = c.2;
            continue;
        }
        let full = Full::of(&materials[i], |s| match s {
            None => Some(0),
            Some(s) => want.iter().position(|&w| w == s).and_then(|k| numbers[k]),
        });
        let slot = if copies.iter().any(|c| c.0 == i) {
            out.push(full);
            out.len() - 1
        } else {
            out[i] = full;
            i
        };
        copies.push((i, numbers, slot));
        p.material = slot;
    }
    out
}

/// A skeleton as a skin's joints: the bones, after a root above them all when they have
/// several roots or some vertex is bound to none (glTF wants a skin's joints to share a root,
/// and every skinned vertex weighted).
struct Rigging<'s> {
    skeleton: &'s [Bone],
    /// 1 when a root comes first, 0 otherwise: what's added to a bone's index for its joint.
    offset: u32,
    /// Each joint's world transform, as written: decomposed into TRS and composed back, so the
    /// inverse bind matrices match what a reader composes, whatever shear was dropped.
    joints: Vec<crate::flatten::M4>,
    /// Each joint's local TRS.
    locals: Vec<([f64; 3], [f64; 4], [f64; 3])>,
}

impl<'s> Rigging<'s> {
    fn new<'p>(skeleton: &'s [Bone], prims: impl Iterator<Item = &'p Prim>) -> Self {
        use crate::flatten::{IDENTITY, affine_inverse, decompose, mul, trs};
        let roots = skeleton.iter().filter(|b| b.parent.is_none()).count();
        let unbound = || {
            prims.filter(|p| p.skinned()).any(|p| {
                p.skin_weights
                    .iter()
                    .any(|w| w.iter().sum::<f32>().partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater))
            })
        };
        let offset = u32::from(roots > 1 || unbound());
        let world = |b: &Bone| b.matrix.map(f64::from);
        let mut joints = Vec::with_capacity(skeleton.len() + 1);
        let mut locals = Vec::with_capacity(skeleton.len() + 1);
        if offset == 1 {
            joints.push(IDENTITY);
            locals.push(([0.0; 3], [0.0, 0.0, 0.0, 1.0], [1.0; 3]));
        }
        for (i, b) in skeleton.iter().enumerate() {
            // A bone's parent comes before it; one that doesn't is taken as a root.
            let parent = b.parent.filter(|&p| p < i);
            let local = match parent {
                Some(p) => affine_inverse(&world(&skeleton[p])).map_or_else(|| world(b), |inv| mul(&inv, &world(b))),
                None => world(b),
            };
            let (t, q, s) = decompose(&local);
            let above = match parent {
                Some(p) => joints[p + offset as usize],
                None => IDENTITY,
            };
            joints.push(mul(&above, &trs(t, q, s)));
            locals.push((t, q, s));
        }
        Self {
            skeleton,
            offset,
            joints,
            locals,
        }
    }

    /// Adds a node per joint after `nodes`, the skin, and its inverse bind matrices; gives the
    /// root joints' nodes, for the scene.
    fn write(&self, b: &mut Builder, nodes: &mut Vec<Value>, json: &mut Map<String, Value>) -> Vec<usize> {
        use crate::flatten::{IDENTITY, affine_inverse};
        let first = nodes.len();
        let offset = self.offset as usize;
        let mut roots = Vec::new();
        let mut children = vec![Vec::new(); self.joints.len()];
        for (i, bone) in self.skeleton.iter().enumerate() {
            match bone.parent.filter(|&p| p < i) {
                Some(p) => children[p + offset].push(first + i + offset),
                None if offset == 1 => children[0].push(first + i + offset),
                None => roots.push(first + i),
            }
        }
        if offset == 1 {
            roots.push(first);
        }
        for (j, ((t, q, s), kids)) in self.locals.iter().zip(&children).enumerate() {
            let mut node = Map::new();
            let name = match j.checked_sub(offset) {
                Some(i) => self.skeleton[i].name.clone(),
                None => Some("Skeleton".to_owned()),
            };
            if let Some(name) = name {
                node.insert("name".into(), json!(name));
            }
            if !kids.is_empty() {
                node.insert("children".into(), json!(kids));
            }
            let f = |v: &[f64]| v.iter().map(|&x| crate::num::f32_of(x)).collect::<Vec<f32>>();
            if t.iter().any(|&x| x != 0.0) {
                node.insert("translation".into(), json!(f(t)));
            }
            if q[..3].iter().any(|&x| x != 0.0) {
                node.insert("rotation".into(), json!(f(q)));
            }
            // Written as f32, a scale that rounds to 1 is the default.
            if f(s) != [1.0; 3] {
                node.insert("scale".into(), json!(f(s)));
            }
            nodes.push(Value::Object(node));
        }
        let ibm: Vec<f32> = self
            .joints
            .iter()
            .flat_map(|m| affine_inverse(m).unwrap_or(IDENTITY).map(crate::num::f32_of))
            .collect();
        let n = self.joints.len();
        let ibm = b.accessor(Part::f32(ibm), 5126, n, "MAT4", None);
        json.insert(
            "skins".into(),
            json!([{ "joints": (first..first + n).collect::<Vec<_>>(), "inverseBindMatrices": ibm }]),
        );
        roots
    }
}

/// A skinned primitive's `JOINTS_0` and `WEIGHTS_0`, flattened: each bone index moved up by
/// `offset` (past the root a skin may have first), weights summing to 1 in single precision,
/// and a vertex no bone moves bound to the root, joint 0. A slot with no weight names joint 0,
/// as glTF's validator wants.
fn skin_attributes(joints: &[[u32; 4]], weights: &[[f32; 4]], offset: u32, count: usize) -> (Vec<u32>, Vec<f32>) {
    let mut js = Vec::with_capacity(joints.len() * 4);
    let mut ws = Vec::with_capacity(weights.len() * 4);
    let last = u32::try_from(count.saturating_sub(1)).unwrap_or(u32::MAX);
    for (j, w) in joints.iter().zip(weights) {
        let mut w = w.map(|x| if x > 0.0 && x.is_finite() { x } else { 0.0 });
        let mut j = j.map(|x| x.saturating_add(offset).min(last));
        let sum: f32 = w.iter().sum();
        if sum > 0.0 {
            w = w.map(|x| x / sum);
            // What rounding left over goes to the strongest.
            let top = (0..4).fold(0, |a, k| if w[k] > w[a] { k } else { a });
            w[top] += 1.0 - w.iter().sum::<f32>();
        } else {
            (j, w) = ([0; 4], [1.0, 0.0, 0.0, 0.0]);
        }
        for k in 0..4 {
            if w[k] == 0.0 {
                j[k] = 0;
            }
        }
        js.extend_from_slice(&j);
        ws.extend_from_slice(&w);
    }
    (js, ws)
}

/// Builds a document's one buffer from typed arrays, with a view and an accessor for each.
#[derive(Default)]
pub(crate) struct Builder {
    pub parts: Parts,
    pub views: Vec<Value>,
    pub accessors: Vec<Value>,
    /// The images named but not read, by image index.
    pub refs: Refs,
    /// While writing skinned primitives: what's added to a bone's index for its joint, and how
    /// many joints the skin has.
    pub joints: Option<(u32, usize)>,
}

impl Builder {
    /// A primitive's JSON (attributes and indices, no material) for its triangles, its arrays
    /// moved into the buffer; `None` when it has no triangles. Its lines and points are left
    /// out: [`Builder::primitives`] writes them too.
    #[cfg_attr(
        not(any(feature = "fbx", feature = "obj", feature = "ply", feature = "usd")),
        allow(dead_code, reason = "only readers that build primitives one at a time use it")
    )]
    pub(crate) fn primitive(&mut self, mut p: Prim) -> Option<Value> {
        if p.indices.is_empty() {
            return None;
        }
        p.lines = Vec::new();
        p.points = Vec::new();
        self.primitives(p).pop()
    }

    /// The JSON of a primitive's triangles, lines (mode 1) and points (mode 0), those it has, in
    /// that order, on one set of vertex attributes they share, and no material: its arrays moved
    /// into the buffer. Empty when it draws nothing.
    pub(crate) fn primitives(&mut self, mut p: Prim) -> Vec<Value> {
        if p.is_empty() {
            return Vec::new();
        }
        let n = p.positions.len();
        let draws: [(u64, Vec<u32>); 3] = [
            (4, std::mem::take(&mut p.indices)),
            (1, std::mem::take(&mut p.lines)),
            (0, std::mem::take(&mut p.points)),
        ];
        let pos = self.positions(p.positions);
        let mut attributes = json!({ "POSITION": pos });
        // Without normals, glTF clients shade flat.
        let has_normals = p.normals.len() == n;
        if has_normals {
            let a = self.accessor(Part::f32(p.normals.into_flattened()), 5126, n, "VEC3", Some(34962));
            attributes["NORMAL"] = json!(a);
        }
        // The index accessors next, as the buffer has always had them: (mode, accessor), an
        // accessor for all but points on every vertex in order (a point cloud), which need none.
        let draws: Vec<(u64, Option<usize>)> = draws
            .into_iter()
            .filter(|(_, idx)| !idx.is_empty())
            .map(|(mode, idx)| {
                let all = mode == 0 && idx.len() == n && idx.iter().enumerate().all(|(k, &i)| i as usize == k);
                (mode, (!all).then(|| self.indices(idx, n)))
            })
            .collect();
        // glTF wants tangents only beside normals, and unit length with a w of ±1.
        if has_normals && p.tangents.len() == n {
            let t: Vec<f32> = p
                .tangents
                .iter()
                .flat_map(|t| {
                    let len = (t[0] * t[0] + t[1] * t[1] + t[2] * t[2]).sqrt();
                    let w = if t[3] < 0.0 { -1.0 } else { 1.0 };
                    if len > 0.0 && len.is_finite() {
                        [t[0] / len, t[1] / len, t[2] / len, w]
                    } else {
                        [1.0, 0.0, 0.0, w]
                    }
                })
                .collect();
            let a = self.accessor(Part::f32(t), 5126, n, "VEC4", Some(34962));
            attributes["TANGENT"] = json!(a);
        }
        // Sets are numbered from 0 with no gaps, as glTF requires: the color texture's
        // coordinates first, which is the set the materials written here read, then the others
        // in order.
        let uvs = std::iter::once(p.uvs).chain(p.uv_sets).filter(|s| s.len() == n);
        for (k, set) in uvs.enumerate() {
            let a = self.accessor(Part::f32(set.into_flattened()), 5126, n, "VEC2", Some(34962));
            attributes[format!("TEXCOORD_{k}")] = json!(a);
        }
        let colors = std::iter::once(p.colors).chain(p.color_sets).filter(|s| s.len() == n);
        for (k, set) in colors.enumerate() {
            let mut colors = set.into_flattened();
            for c in &mut colors {
                *c = c.clamp(0.0, 1.0);
            }
            let a = self.accessor(Part::f32(colors), 5126, n, "VEC4", Some(34962));
            attributes[format!("COLOR_{k}")] = json!(a);
        }
        if let Some((offset, count)) = self.joints
            && p.skin_joints.len() == n
            && p.skin_weights.len() == n
        {
            let (joints, weights) = skin_attributes(&p.skin_joints, &p.skin_weights, offset, count);
            let j = if count <= 256 {
                let b = joints.iter().map(|&j| u8::try_from(j).unwrap_or(0)).collect();
                self.accessor(Part::bytes(b), 5121, n, "VEC4", Some(34962))
            } else {
                let b = joints.iter().map(|&j| u16::try_from(j).unwrap_or(0)).collect();
                self.accessor(Part::u16(b), 5123, n, "VEC4", Some(34962))
            };
            let w = self.accessor(Part::f32(weights), 5126, n, "VEC4", Some(34962));
            attributes["JOINTS_0"] = json!(j);
            attributes["WEIGHTS_0"] = json!(w);
        }
        let mut out = Vec::new();
        for (mode, indices) in draws {
            let mut prim = json!({ "attributes": attributes.clone() });
            if let Some(i) = indices {
                prim["indices"] = json!(i);
            }
            if mode != 4 {
                prim["mode"] = json!(mode);
            }
            out.push(prim);
        }
        out
    }

    /// An index accessor for `idx`, on `n` vertices.
    fn indices(&mut self, idx: Vec<u32>, n: usize) -> usize {
        let count = idx.len();
        // Two bytes an index when they'll do: under 65535 vertices, as glTF keeps the largest
        // value of each type for restarting strips.
        let narrow = (n < usize::from(u16::MAX))
            .then(|| idx.iter().map(|&i| u16::try_from(i).ok()).collect::<Option<Vec<u16>>>())
            .flatten();
        match narrow {
            Some(v) => self.accessor(Part::u16(v), 5123, count, "SCALAR", Some(34963)),
            None => self.accessor(Part::u32(idx), 5125, count, "SCALAR", Some(34963)),
        }
    }

    /// A mesh of `prims` (their triangles, lines and points), each using its material (the last
    /// of `materials` when out of range); `None` when none draws anything.
    pub(crate) fn mesh(&mut self, prims: Vec<Prim>, materials: usize) -> Option<Value> {
        let last = materials.saturating_sub(1);
        let mut primitives = Vec::new();
        for p in prims {
            let material = p.material.min(last);
            for mut prim in self.primitives(p) {
                prim["material"] = json!(material);
                primitives.push(prim);
            }
        }
        (!primitives.is_empty()).then(|| json!({ "primitives": primitives }))
    }

    /// A `VEC3` float accessor with the `min` and `max` glTF requires of positions (and of
    /// morph targets' position deltas).
    pub(crate) fn positions(&mut self, v: Vec<[f32; 3]>) -> usize {
        let (mut min, mut max) = ([f32::MAX; 3], [f32::MIN; 3]);
        for p in &v {
            for k in 0..3 {
                min[k] = min[k].min(p[k]);
                max[k] = max[k].max(p[k]);
            }
        }
        if v.is_empty() {
            (min, max) = ([0.0; 3], [0.0; 3]);
        }
        let n = v.len();
        let a = self.accessor(Part::f32(v.into_flattened()), 5126, n, "VEC3", Some(34962));
        self.accessors[a]["min"] = json!(min);
        self.accessors[a]["max"] = json!(max);
        a
    }

    /// A float accessor of `kind` (`SCALAR`, `VEC3`, `VEC4`, `MAT4`) with no target, for skins
    /// and animations; `bounds` adds the `min` and `max` an animation's times need.
    #[cfg(any(
        feature = "fbx",
        feature = "usd",
        feature = "vox",
        feature = "3ds",
        feature = "bvh",
        feature = "dae"
    ))]
    pub(crate) fn floats(&mut self, v: Vec<f32>, kind: &str, bounds: bool) -> usize {
        let width = match kind {
            "VEC2" => 2,
            "VEC3" => 3,
            "VEC4" => 4,
            "MAT4" => 16,
            _ => 1,
        };
        let count = v.len() / width;
        let range = bounds.then(|| {
            let mut min = vec![f32::MAX; width];
            let mut max = vec![f32::MIN; width];
            for e in v.chunks_exact(width) {
                for k in 0..width {
                    min[k] = min[k].min(e[k]);
                    max[k] = max[k].max(e[k]);
                }
            }
            (min, max)
        });
        let a = self.accessor(Part::f32(v), 5126, count, kind, None);
        if let Some((min, max)) = range {
            self.accessors[a]["min"] = json!(min);
            self.accessors[a]["max"] = json!(max);
        }
        a
    }

    /// Adds `materials` and `images` to `json`, with the textures and samplers they use (texture `i` is image
    /// `i`, repeating, and more for other wraps) and the extensions they use added to `extensionsUsed`. Nothing is
    /// added for an empty list.
    pub(crate) fn materials<M: Into<Full>>(
        &mut self,
        materials: impl IntoIterator<Item = M>,
        images: Vec<Source>,
        json: &mut Map<String, Value>,
    ) {
        let mut w = Writer::new(images.len());
        let materials: Vec<Value> = materials.into_iter().map(|m| w.material(&m.into())).collect();
        let images: Vec<Value> = images
            .into_iter()
            .enumerate()
            .map(|(i, s)| match s {
                Source::Image(Image { bytes, mime }) => {
                    let v = self.view(Part::bytes(bytes), None);
                    json!({ "bufferView": v, "mimeType": mime })
                }
                Source::Ref(r, uri) => {
                    self.refs.insert(i, r);
                    json!({ "uri": uri })
                }
            })
            .collect();
        let (textures, samplers, used) = w.finish();
        if !materials.is_empty() {
            json.insert("materials".into(), json!(materials));
        }
        if !used.is_empty() {
            let list = json.entry("extensionsUsed").or_insert_with(|| json!([]));
            if let Some(list) = list.as_array_mut() {
                for e in used {
                    if !list.iter().any(|v| v == e) {
                        list.push(json!(e));
                    }
                }
            }
        }
        if !images.is_empty() {
            json.insert("samplers".into(), json!(samplers));
            json.insert("textures".into(), json!(textures));
            json.insert("images".into(), json!(images));
        }
    }

    /// The document: `json` (scenes, nodes, meshes and the rest) with the asset, the accessors,
    /// the views and the one buffer they're on.
    pub(crate) fn finish(self, mut json: Map<String, Value>, facts: Map<String, Value>) -> Document<'static> {
        let asset = json.entry("asset").or_insert_with(|| json!({}));
        asset["version"] = json!("2.0");
        if asset.get("generator").is_none() {
            asset["generator"] = json!("polysmelt");
        }
        let mut buffers = Vec::new();
        if !self.views.is_empty() {
            json.insert("accessors".into(), Value::Array(self.accessors));
            json.insert("bufferViews".into(), Value::Array(self.views));
            json.insert("buffers".into(), json!([{ "byteLength": self.parts.len }]));
            buffers.push(Blob::Parts(self.parts));
        }
        Document {
            json,
            buffers,
            facts,
            refs: self.refs,
            max_triangles: MAX_TRIANGLES,
            lines_and_points: true,
            max_points: MAX_POINTS,
        }
    }

    /// A buffer view of `part`; returns its index.
    pub(crate) fn view(&mut self, part: Part, target: Option<u32>) -> usize {
        let (at, len) = self.parts.push(part);
        let mut v = json!({ "buffer": 0, "byteOffset": at, "byteLength": len });
        if let Some(t) = target {
            v["target"] = json!(t);
        }
        self.views.push(v);
        self.views.len() - 1
    }

    /// An accessor of `count` elements of `kind` over a view of `part`; returns its index.
    pub(crate) fn accessor(&mut self, part: Part, ctype: u32, count: usize, kind: &str, target: Option<u32>) -> usize {
        let v = self.view(part, target);
        self.accessors
            .push(json!({ "bufferView": v, "componentType": ctype, "count": count, "type": kind }));
        self.accessors.len() - 1
    }
}

#[cfg(all(test, feature = "fs"))]
mod tests {
    use std::io::Write as _;

    use super::{AHEAD, FileSpan};

    #[test]
    fn a_file_span_reads_what_the_file_holds_however_it_is_read() {
        let bytes: Vec<u8> = (0..3 * AHEAD + 77)
            .map(|i| (i * 7 + i / 251).to_le_bytes()[0])
            .collect();
        let mut file = tempfile::tempfile().unwrap();
        file.write_all(b"head").unwrap();
        file.write_all(&bytes).unwrap();
        let span = FileSpan::new(file, 4, bytes.len() as u64, u64::MAX);
        let len = bytes.len();
        // Forward in small steps, backward, across the read-ahead's end, big reads, the very end.
        let mut reads: Vec<(usize, usize)> = (0..200).map(|k| (k * 997 % len, 1 + k % 300)).collect();
        reads.extend([
            (AHEAD - 3, 10),
            (5, AHEAD),
            (0, len),
            (len - 1, 1),
            (len - 40, 40),
            (100, 0),
            (AHEAD, 2),
        ]);
        reads.extend((0..50).rev().map(|k| (k * 3989, 64)));
        for (off, n) in reads {
            let n = n.min(len - off);
            let mut out = vec![0; n];
            span.read_at(off as u64, &mut out).unwrap();
            assert_eq!(out, bytes[off..off + n], "{n} bytes at {off}");
        }
    }
}