vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
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
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
use std::collections::HashSet;
use std::path::Path;
use vrm_spec::vrmc_vrm_1_0::{HumanBoneName, VRMC_VRM, VRMCVrmSchema};

use crate::constraint::{self, NodeConstraint};
use crate::diagnostic::{Diagnostic, LoadOptions, ValidationMode};
use crate::expressions::Expressions;
use crate::first_person::FirstPerson;
use crate::humanoid::{HumanBone, Humanoid};
use crate::image::AvatarImage;
use crate::instance::AvatarInstance;
use crate::look_at::LookAt;
use crate::material::{AvatarTexture, Material};
use crate::meta::AvatarMeta;
use crate::node::{self, AvatarNode};
use crate::primitive::RenderPrimitive;
use crate::skin::Skin;
use crate::spring_bone::SpringBone;
use crate::{ImageId, MaterialId, NodeId, PrimitiveId, SkinId, TextureId};
use vrm_spec::vrmc_spring_bone_1_0::{VRMC_SPRING_BONE, VrmcSpringBoneSchema};

/// A loaded VRM 1.0 avatar: the parsed VRM data (meta, humanoid, expressions,
/// look-at, first-person, spring bones, constraints) plus the renderable
/// glTF assets (nodes, primitives, materials, skins, images).
///
/// Load it with [`AvatarAsset::from_bytes`] / [`AvatarAsset::load`], or compose
/// it programmatically with [`crate::AvatarAssetBuilder`]. Drive a frame with
/// [`crate::AvatarRuntime`].
#[derive(Debug, Clone)]
pub struct AvatarAsset {
    meta: AvatarMeta,
    humanoid: Humanoid,
    expressions: Expressions,
    primitives: Vec<RenderPrimitive>,
    look_at: Option<LookAt>,
    pub(crate) images: Vec<AvatarImage>,
    pub(crate) materials: Vec<Material>,
    pub(crate) textures: Vec<AvatarTexture>,
    pub(crate) skins: Vec<Skin>,
    node_constraints: Vec<NodeConstraint>,
    spring_bone: SpringBone,
    pub(crate) first_person: FirstPerson,
    nodes: Vec<AvatarNode>,
    vrmc_vrm: Option<VRMCVrmSchema>,
}

impl AvatarAsset {
    pub(crate) fn new() -> Self {
        Self {
            meta: AvatarMeta::default(),
            humanoid: Humanoid::default(),
            expressions: Expressions::default(),
            primitives: Vec::new(),
            look_at: None,
            images: Vec::new(),
            materials: Vec::new(),
            textures: Vec::new(),
            skins: Vec::new(),
            node_constraints: Vec::new(),
            spring_bone: SpringBone::default(),
            first_person: FirstPerson::default(),
            nodes: Vec::new(),
            vrmc_vrm: None,
        }
    }

    /// Returns a reference to the [`AvatarMeta`].
    pub fn meta(&self) -> &AvatarMeta {
        &self.meta
    }

    /// Builder method that sets the [`AvatarMeta`].
    pub(crate) fn with_meta(mut self, meta: AvatarMeta) -> Self {
        self.meta = meta;
        self
    }

    /// Returns a reference to the [`Humanoid`].
    pub fn humanoid(&self) -> &Humanoid {
        &self.humanoid
    }

    /// Builder method that sets the [`Humanoid`].
    pub(crate) fn with_humanoid(mut self, humanoid: Humanoid) -> Self {
        self.humanoid = humanoid;
        self
    }

    /// Returns a reference to the [`Expressions`].
    pub fn expressions(&self) -> &Expressions {
        &self.expressions
    }

    /// Builder method that sets the [`Expressions`].
    pub(crate) fn with_expressions(mut self, expressions: Expressions) -> Self {
        self.expressions = expressions;
        self
    }

    /// Returns the list of [`RenderPrimitive`]s parsed from the model.
    pub fn primitives(&self) -> &[RenderPrimitive] {
        &self.primitives
    }

    /// Resolves a type-safe primitive identifier.
    pub fn primitive(&self, id: PrimitiveId) -> Option<&RenderPrimitive> {
        self.primitives.get(id.index())
    }

    /// Builder method that sets the primitive list.
    pub(crate) fn with_primitives(mut self, primitives: Vec<RenderPrimitive>) -> Self {
        self.primitives = primitives;
        self
    }

    /// Returns the [`LookAt`] configuration, if present.
    pub fn look_at(&self) -> Option<&LookAt> {
        self.look_at.as_ref()
    }

    /// Builder method that sets the [`LookAt`] configuration.
    pub(crate) fn with_look_at(mut self, look_at: LookAt) -> Self {
        self.look_at = Some(look_at);
        self
    }

    /// Returns the list of [`AvatarImage`]s parsed from the model.
    pub fn images(&self) -> &[AvatarImage] {
        &self.images
    }

    /// Resolves a type-safe image identifier.
    pub fn image(&self, id: ImageId) -> Option<&AvatarImage> {
        self.images.get(id.index())
    }

    /// Returns common glTF materials with optional MToon parameters.
    pub fn materials(&self) -> &[Material] {
        &self.materials
    }

    /// Resolves a type-safe material identifier.
    pub fn material(&self, id: MaterialId) -> Option<&Material> {
        self.materials.get(id.index())
    }

    /// Returns the glTF texture objects, kept separate from image data.
    pub fn textures(&self) -> &[AvatarTexture] {
        &self.textures
    }

    /// Resolves a type-safe texture identifier.
    pub fn texture(&self, id: TextureId) -> Option<&AvatarTexture> {
        self.textures.get(id.index())
    }

    /// Returns the initial (base) color for the given material attribute.
    ///
    /// Returns white `[1, 1, 1, 1]` when the material index is out of range or
    /// the material does not support `color_type`.
    pub fn base_color(
        &self,
        material_index: u32,
        color_type: crate::MaterialColorType,
    ) -> [f32; 4] {
        let Some(material) = self.materials.get(material_index as usize) else {
            return [1.0, 1.0, 1.0, 1.0];
        };

        match color_type {
            crate::MaterialColorType::Color => material.base_color_factor,
            crate::MaterialColorType::EmissionColor => [
                material.emissive_factor[0],
                material.emissive_factor[1],
                material.emissive_factor[2],
                1.0,
            ],
            crate::MaterialColorType::ShadeColor => material
                .mtoon()
                .map(|mtoon| mtoon.shade_color.extend(1.0).to_array())
                .unwrap_or([1.0; 4]),
            crate::MaterialColorType::MatcapColor => material
                .mtoon()
                .map(|mtoon| mtoon.matcap_factor.extend(1.0).to_array())
                .unwrap_or([1.0; 4]),
            crate::MaterialColorType::RimColor => material
                .mtoon()
                .map(|mtoon| mtoon.parametric_rim_color_factor.extend(1.0).to_array())
                .unwrap_or([1.0; 4]),
            crate::MaterialColorType::OutlineColor => material
                .mtoon()
                .map(|mtoon| mtoon.outline_color_factor.extend(1.0).to_array())
                .unwrap_or([1.0; 4]),
        }
    }

    /// Creates a mutable runtime state (expression weights, bone rotations,
    /// look-at target) detached from this avatar.
    pub fn instantiate(&self) -> AvatarInstance {
        AvatarInstance::new()
    }

    /// Returns the list of [`Skin`]s.
    pub fn skins(&self) -> &[Skin] {
        &self.skins
    }

    /// Resolves a type-safe skin identifier.
    pub fn skin(&self, id: SkinId) -> Option<&Skin> {
        self.skins.get(id.index())
    }

    #[cfg(test)]
    pub(crate) fn with_skins(mut self, skins: Vec<Skin>) -> Self {
        self.skins = skins;
        self
    }

    /// Returns the list of [`NodeConstraint`]s.
    pub fn node_constraints(&self) -> &[NodeConstraint] {
        &self.node_constraints
    }

    /// Builder method that sets the parsed node constraints.
    pub(crate) fn with_node_constraints(mut self, node_constraints: Vec<NodeConstraint>) -> Self {
        self.node_constraints = node_constraints;
        self
    }

    /// Returns the [`SpringBone`] configuration.
    pub fn spring_bone(&self) -> &SpringBone {
        &self.spring_bone
    }

    /// Builder method that sets the [`SpringBone`] data.
    pub(crate) fn with_spring_bone(mut self, spring_bone: SpringBone) -> Self {
        self.spring_bone = spring_bone;
        self
    }

    /// Returns the [`FirstPerson`] configuration.
    pub fn first_person(&self) -> &FirstPerson {
        &self.first_person
    }

    /// Returns the parsed node tree.
    pub fn nodes(&self) -> &[AvatarNode] {
        &self.nodes
    }

    /// Resolves a type-safe node identifier.
    pub fn node(&self, id: NodeId) -> Option<&AvatarNode> {
        self.nodes.get(id.index())
    }

    /// Builder method that sets the node tree.
    pub(crate) fn with_nodes(mut self, nodes: Vec<AvatarNode>) -> Self {
        self.nodes = nodes;
        self
    }

    /// Computes the world transform matrix of every node, applying the given bone rotations.
    pub fn compute_world_matrices(
        &self,
        bone_updates: &[crate::instance::BoneUpdate],
    ) -> Vec<glam::Mat4> {
        node::compute_world_matrices(&self.nodes, bone_updates)
    }

    /// Computes the joint matrices for `skin`, applying the given bone rotations.
    pub fn compute_joint_matrices(
        &self,
        skin: &Skin,
        bone_updates: &[crate::instance::BoneUpdate],
    ) -> Vec<glam::Mat4> {
        node::compute_joint_matrices(&self.nodes, skin, bone_updates)
    }

    /// Returns the raw [`VRMCVrmSchema`] this avatar was parsed from.
    pub fn vrmc_vrm(&self) -> Option<&VRMCVrmSchema> {
        self.vrmc_vrm.as_ref()
    }

    /// Loads and parses a VRM avatar from a file path.
    ///
    /// Relative buffer and image URIs are resolved against the file's parent
    /// directory, including percent-encoded image paths.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, crate::LoadError> {
        Ok(Self::from_file_with_options(path, LoadOptions::default())?.asset)
    }

    /// Parses a VRM avatar from an in-memory byte slice.
    ///
    /// Images must be embedded in buffer views or PNG/JPEG data URIs. Use
    /// [`Self::from_file`] when the document contains external references.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, crate::LoadError> {
        Ok(Self::from_bytes_with_options(bytes, LoadOptions::default())?.asset)
    }

    /// Loads an avatar and returns any diagnostics produced by the selected
    /// validation mode. Relative buffer and image URIs are resolved against
    /// the file's parent directory.
    pub fn from_file_with_options<P: AsRef<Path>>(
        path: P,
        options: LoadOptions,
    ) -> Result<LoadOutcome, crate::LoadError> {
        let path_ref = path.as_ref();
        let bytes = std::fs::read(path_ref).map_err(|source| crate::LoadError::Io {
            path: path_ref.to_path_buf(),
            source,
        })?;
        Self::from_bytes_with_options_and_base(&bytes, options, path_ref.parent())
    }

    /// Parses an avatar and returns diagnostics for recoverable violations.
    /// Unresolved external buffer and image references are rejected.
    pub fn from_bytes_with_options(
        bytes: &[u8],
        options: LoadOptions,
    ) -> Result<LoadOutcome, crate::LoadError> {
        Self::from_bytes_with_options_and_base(bytes, options, None)
    }

    fn from_bytes_with_options_and_base(
        bytes: &[u8],
        options: LoadOptions,
        base: Option<&Path>,
    ) -> Result<LoadOutcome, crate::LoadError> {
        // gltf-json recursively validates node graphs. Reject cycles with an
        // iterative preflight first so hostile input cannot overflow the stack.
        let mut gltf = gltf::Gltf::from_slice_without_validation(bytes)?;
        validate_raw_node_graph(gltf.document.as_json())?;
        crate::image::validate_raw_sources(gltf.document.as_json())?;
        crate::primitive::validate_referenced_primitive_positions(gltf.document.as_json())?;
        validate_required_extensions(&gltf.document)?;
        validate_gltf_document(&gltf.document)?;
        let buffers = gltf::import_buffers(&gltf.document, base, gltf.blob.take())?;
        let doc = gltf.document;

        // VRM Features
        let schema = Self::parse_vrm_schema(&doc)?;
        let mut diagnostics = Vec::new();
        collect_optional_extension_diagnostics(&doc, options.validation, &mut diagnostics);
        collect_material_compatibility_diagnostics(&doc, &mut diagnostics);
        validate_vrm_semantics(&doc, &schema, options.validation, &mut diagnostics)?;
        let meta = AvatarMeta::load_meta(&schema.meta);
        let humanoid = Humanoid::load_humanoid(&schema.humanoid);
        let expressions = schema
            .expressions
            .as_ref()
            .map(Expressions::load_expressions)
            .unwrap_or_default();
        let look_at = schema.look_at.as_ref().map(LookAt::load_look_at);
        let first_person = schema
            .first_person
            .as_ref()
            .map(FirstPerson::load_first_person)
            .unwrap_or_default();

        // glTF Features
        let primitives = load_primitives(&doc, &buffers)?;
        let images = load_images(&doc, &buffers, base)?;
        crate::image::validate_thumbnail(
            &images,
            schema
                .meta
                .thumbnail_image
                .as_ref()
                .map(|index| index.value()),
        )?;
        let materials = load_materials(&doc)?;
        let textures = crate::material::load_textures(&doc);
        let skins = load_skins(&doc, &buffers)?;
        let node_constraints = load_constraints(&doc)?;
        let spring_bone = load_spring_bone(&doc, options.validation, &mut diagnostics)?;
        let nodes = node::load_nodes(&doc);

        let asset = Self {
            meta,
            humanoid,
            expressions,
            primitives,
            look_at,
            images,
            materials,
            textures,
            skins,
            node_constraints,
            spring_bone,
            first_person,
            nodes,
            vrmc_vrm: Some(schema),
        };
        Ok(LoadOutcome { asset, diagnostics })
    }

    fn parse_vrm_schema(doc: &gltf::Document) -> Result<VRMCVrmSchema, crate::LoadError> {
        match doc.extension_value(VRMC_VRM) {
            Some(value) => Ok(serde_json::from_value(value.to_owned())?),
            None if doc.extension_value("VRM").is_some() => {
                Err(crate::LoadError::UnsupportedVrmVersion)
            }
            None => Err(crate::LoadError::MissingVrmExtension),
        }
    }

    /// Loads a VRM 1.0 asset from a file using strict validation.
    ///
    /// Relative external buffers and images are resolved against the file's
    /// parent directory. Use [`Self::load_with_options`] to collect diagnostics
    /// from permissive validation.
    ///
    /// # Errors
    ///
    /// Returns [`crate::LoadError`] when the file cannot be read, its glTF or
    /// VRM data is invalid, an image cannot be decoded, or it requires an
    /// unsupported extension.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use vrm_runtime::AvatarAsset;
    ///
    /// let avatar = AvatarAsset::load("avatar.vrm")?;
    /// println!("{}", avatar.meta().name());
    /// # Ok::<(), vrm_runtime::LoadError>(())
    /// ```
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, crate::LoadError> {
        Self::from_file(path)
    }

    /// Loads a VRM asset from a file with explicit validation options.
    pub fn load_with_options<P: AsRef<Path>>(
        path: P,
        options: LoadOptions,
    ) -> Result<LoadOutcome, crate::LoadError> {
        Self::from_file_with_options(path, options)
    }

    /// Returns the feature set implemented by this crate version.
    pub const fn capabilities() -> crate::Capabilities {
        crate::Capabilities::current()
    }

    pub(crate) fn validate_programmatic(&self) -> Result<(), crate::BuildError> {
        let invalid = |message: String| crate::BuildError::InvalidAsset(message);

        if self.meta.name().trim().is_empty() {
            return Err(invalid("meta.name must not be empty".to_string()));
        }
        if self.meta.authors().is_empty()
            || self
                .meta
                .authors()
                .iter()
                .any(|author| author.trim().is_empty())
        {
            return Err(invalid(
                "meta.authors must contain at least one non-empty author".to_string(),
            ));
        }
        if self
            .meta
            .license_url()
            .is_none_or(|license| license.trim().is_empty())
        {
            return Err(invalid("meta.license_url must not be empty".to_string()));
        }
        if self
            .meta
            .references()
            .is_some_and(|references| references.is_empty())
        {
            return Err(invalid(
                "meta.references must contain at least one item when present".to_string(),
            ));
        }
        if let Some(look_at) = &self.look_at {
            look_at
                .validate_programmatic()
                .map_err(crate::BuildError::InvalidAsset)?;
        }

        for (position, node) in self.nodes.iter().enumerate() {
            if node.index as usize != position {
                return Err(invalid(format!(
                    "node storage position {position} does not match node index {}",
                    node.index
                )));
            }
            if !node.initial_translation.is_finite()
                || !node.initial_rotation.is_finite()
                || !node.initial_scale.is_finite()
            {
                return Err(invalid(format!(
                    "node {position} contains a non-finite transform"
                )));
            }
            if !is_positive_uniform_scale(node.initial_scale.to_array()) {
                return Err(invalid(format!(
                    "node {position} must use a positive uniform scale"
                )));
            }
            if node
                .parent
                .is_some_and(|parent| parent as usize >= self.nodes.len() || parent == node.index)
            {
                return Err(invalid(format!("node {position} has an invalid parent")));
            }
            let mut unique_children = HashSet::new();
            for &child in &node.children {
                if child as usize >= self.nodes.len()
                    || child == node.index
                    || !unique_children.insert(child)
                {
                    return Err(invalid(format!("node {position} has an invalid child")));
                }
                if self.nodes[child as usize].parent != Some(node.index) {
                    return Err(invalid(format!(
                        "node {position} and child {child} disagree about their relationship"
                    )));
                }
            }
            if let Some(parent) = node.parent
                && !self.nodes[parent as usize].children.contains(&node.index)
            {
                return Err(invalid(format!(
                    "node {position} and parent {parent} disagree about their relationship"
                )));
            }

            let mut ancestors = HashSet::new();
            let mut cursor = node.parent;
            while let Some(parent) = cursor {
                if !ancestors.insert(parent) {
                    return Err(invalid(format!(
                        "node hierarchy contains a cycle through node {parent}"
                    )));
                }
                cursor = self
                    .nodes
                    .get(parent as usize)
                    .and_then(|ancestor| ancestor.parent);
            }
        }

        let mut assigned_nodes = HashSet::new();
        for (bone, node) in self.humanoid.bones() {
            if node.0 as usize >= self.nodes.len() {
                return Err(invalid(format!(
                    "humanoid bone `{bone:?}` references missing node {}",
                    node.0
                )));
            }
            if !assigned_nodes.insert(node.0) {
                return Err(invalid(format!(
                    "node {} is assigned to more than one humanoid bone",
                    node.0
                )));
            }
        }

        for required in REQUIRED_HUMAN_BONES {
            let bone = HumanBone::from(required);
            if self.humanoid.bone(bone).is_none() {
                return Err(invalid(format!(
                    "humanoid bone `{}` is required",
                    human_bone_name(required)
                )));
            }
        }

        let node_parents = self
            .nodes
            .iter()
            .map(|node| node.parent.map(|parent| parent as usize))
            .collect::<Vec<_>>();
        let mapped_bones = self
            .humanoid
            .bones()
            .map(|(&bone, node)| (bone, node.0 as usize));
        if let Some(violation) = crate::humanoid::hierarchy_violations(mapped_bones, &node_parents)
            .into_iter()
            .next()
        {
            return Err(invalid(violation.message()));
        }

        for (skin_index, skin) in self.skins.iter().enumerate() {
            if skin.joints().len() != skin.inverse_bind_matrices().len() {
                return Err(invalid(format!(
                    "skin {skin_index} must have one inverse bind matrix per joint"
                )));
            }
            if skin
                .joints()
                .iter()
                .any(|&node| node as usize >= self.nodes.len())
                || skin.inverse_bind_matrices().iter().any(|matrix| {
                    matrix
                        .to_cols_array()
                        .iter()
                        .any(|component| !component.is_finite())
                })
            {
                return Err(invalid(format!(
                    "skin {skin_index} contains an invalid joint or matrix"
                )));
            }
        }

        for (texture_index, texture) in self.textures.iter().enumerate() {
            if texture.image_id().index() >= self.images.len() {
                return Err(invalid(format!(
                    "texture {texture_index} references a missing image"
                )));
            }
        }

        let validate_texture =
            |label: &str, texture: Option<&crate::TextureInfo>| -> Result<(), crate::BuildError> {
                if let Some(texture) = texture {
                    if texture.texture_id().index() >= self.textures.len() {
                        return Err(invalid(format!("{label} references a missing texture")));
                    }
                    let transform = texture.transform();
                    if !transform.rotation.is_finite()
                        || transform.offset.iter().any(|value| !value.is_finite())
                        || transform.scale.iter().any(|value| !value.is_finite())
                    {
                        return Err(invalid(format!("{label} has a non-finite UV transform")));
                    }
                }
                Ok(())
            };
        for (material_index, material) in self.materials.iter().enumerate() {
            validate_texture(
                &format!("material {material_index} base color texture"),
                material.base_color_texture(),
            )?;
            validate_texture(
                &format!("material {material_index} normal texture"),
                material.normal_texture().map(|normal| &normal.texture),
            )?;
            validate_texture(
                &format!("material {material_index} emissive texture"),
                material.emissive_texture(),
            )?;
            if let Some(mtoon) = material.mtoon() {
                for (name, texture) in [
                    ("shade multiply", mtoon.shade_multiply_texture.as_ref()),
                    ("shading shift", mtoon.shading_shift_texture.as_ref()),
                    ("matcap", mtoon.matcap_texture.as_ref()),
                    ("rim multiply", mtoon.rim_multiply_texture.as_ref()),
                    (
                        "outline width multiply",
                        mtoon.outline_width_multiply_texture.as_ref(),
                    ),
                    (
                        "UV animation mask",
                        mtoon.uv_animation_mask_texture.as_ref(),
                    ),
                ] {
                    validate_texture(
                        &format!("material {material_index} {name} texture"),
                        texture,
                    )?;
                }
            }
        }

        for (primitive_index, primitive) in self.primitives.iter().enumerate() {
            if primitive.node_index() as usize >= self.nodes.len() {
                return Err(invalid(format!(
                    "primitive {primitive_index} references a missing node"
                )));
            }
            if primitive
                .material_index()
                .is_some_and(|material| material >= self.materials.len())
                || primitive
                    .texture_index()
                    .is_some_and(|texture| texture >= self.textures.len())
                || primitive
                    .skin_index()
                    .is_some_and(|skin| skin >= self.skins.len())
            {
                return Err(invalid(format!(
                    "primitive {primitive_index} references a missing asset object"
                )));
            }
            if primitive
                .indices()
                .iter()
                .any(|&index| index as usize >= primitive.positions().len())
            {
                return Err(invalid(format!(
                    "primitive {primitive_index} contains an out-of-range vertex index"
                )));
            }
        }

        let mut expression_names = HashSet::new();
        for expression in self.expressions.iter() {
            if expression.name().is_empty() || !expression_names.insert(expression.name()) {
                return Err(invalid(
                    "expression names must be non-empty and unique".to_string(),
                ));
            }
            crate::expressions::validate_override_semantics(
                expression.name(),
                expression.override_blink(),
                expression.override_mouth(),
                expression.override_look_at(),
            )
            .map_err(invalid)?;
            for bind in expression.morph_target_binds() {
                let matching: Vec<_> = self
                    .primitives
                    .iter()
                    .filter(|primitive| primitive.node_index() == bind.node_index())
                    .collect();
                if matching.is_empty()
                    || matching.iter().any(|primitive| {
                        bind.target_index() as usize >= primitive.morph_targets().len()
                    })
                    || !bind.weight().is_finite()
                    || !(0.0..=1.0).contains(&bind.weight())
                {
                    return Err(invalid(format!(
                        "expression `{}` contains an invalid morph target bind",
                        expression.name()
                    )));
                }
            }
            for bind in expression.material_color_binds() {
                if bind.material_index as usize >= self.materials.len()
                    || bind.target_value.iter().any(|value| !value.is_finite())
                {
                    return Err(invalid(format!(
                        "expression `{}` contains an invalid material color bind",
                        expression.name()
                    )));
                }
            }
            for bind in expression.texture_transform_binds() {
                if bind.material_index as usize >= self.materials.len()
                    || bind.scale.iter().any(|value| !value.is_finite())
                    || bind.offset.iter().any(|value| !value.is_finite())
                {
                    return Err(invalid(format!(
                        "expression `{}` contains an invalid texture transform bind",
                        expression.name()
                    )));
                }
            }
        }

        for annotation in &self.first_person.mesh_annotations {
            if annotation.node_index as usize >= self.nodes.len()
                || !self
                    .primitives
                    .iter()
                    .any(|primitive| primitive.node_index() == annotation.node_index)
            {
                return Err(invalid(format!(
                    "first-person annotation references node {} without a mesh",
                    annotation.node_index
                )));
            }
        }

        constraint::validate_programmatic(&self.node_constraints, self.nodes.len())
            .map_err(invalid)?;
        crate::spring_bone::validate_programmatic(&self.nodes, &self.spring_bone)
            .map_err(invalid)?;

        Ok(())
    }
}

fn validate_raw_node_graph(root: &gltf::json::Root) -> Result<(), crate::LoadError> {
    let node_count = root.nodes.len();
    let mut indegree = vec![0usize; node_count];
    let mut children = vec![Vec::new(); node_count];

    for (parent, node) in root.nodes.iter().enumerate() {
        for child in node.children.as_deref().unwrap_or_default() {
            let child = child.value();
            if child >= node_count {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "/nodes/{parent}/children references missing node {child}"
                )));
            }
            indegree[child] += 1;
            if indegree[child] > 1 {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "node {child} has more than one parent"
                )));
            }
            children[parent].push(child);
        }
    }

    let mut roots: std::collections::VecDeque<_> = indegree
        .iter()
        .enumerate()
        .filter_map(|(index, &degree)| (degree == 0).then_some(index))
        .collect();
    let mut visited = 0usize;
    while let Some(parent) = roots.pop_front() {
        visited += 1;
        for &child in &children[parent] {
            indegree[child] -= 1;
            if indegree[child] == 0 {
                roots.push_back(child);
            }
        }
    }
    if visited != node_count {
        return Err(crate::LoadError::InvalidVrm(
            "node hierarchy contains a cycle".to_string(),
        ));
    }
    Ok(())
}

/// An avatar plus warnings emitted by permissive validation.
#[derive(Debug)]
pub struct LoadOutcome {
    /// The validated immutable avatar asset.
    pub asset: AvatarAsset,
    /// Recoverable issues reported while loading in permissive mode.
    pub diagnostics: Vec<Diagnostic>,
}

fn validate_required_extensions(doc: &gltf::Document) -> Result<(), crate::LoadError> {
    crate::extension_declarations::validate(doc.as_json()).map_err(crate::LoadError::InvalidVrm)?;
    for extension in doc.extensions_required() {
        if !SUPPORTED_EXTENSIONS.contains(&extension) {
            return Err(crate::LoadError::UnsupportedRequiredExtension(
                extension.to_string(),
            ));
        }
    }
    Ok(())
}

/// Runs glTF's structural validation while letting this crate validate the
/// VRM ecosystem extensions that the upstream glTF crate does not know about.
fn validate_gltf_document(doc: &gltf::Document) -> Result<(), crate::LoadError> {
    let mut root = doc.as_json().clone();
    root.extensions_required
        .retain(|extension| !SUPPORTED_EXTENSIONS.contains(&extension.as_str()));
    gltf::Document::from_json(root)?;
    Ok(())
}

const SUPPORTED_EXTENSIONS: &[&str] = &[
    "VRMC_vrm",
    "VRMC_materials_mtoon",
    "VRMC_materials_hdr_emissiveMultiplier",
    "VRMC_node_constraint",
    "VRMC_springBone",
    "VRMC_springBone_extended_collider",
    "KHR_materials_unlit",
    "KHR_materials_emissive_strength",
    "KHR_texture_transform",
];

fn collect_optional_extension_diagnostics(
    doc: &gltf::Document,
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if validation != ValidationMode::Permissive {
        return;
    }
    let required: HashSet<_> = doc.extensions_required().collect();
    for extension in doc.extensions_used() {
        if !SUPPORTED_EXTENSIONS.contains(&extension) && !required.contains(extension) {
            diagnostics.push(Diagnostic::warning(
                "VRM_UNSUPPORTED_OPTIONAL_EXTENSION",
                "/extensionsUsed",
                format!(
                    "optional extension `{extension}` is not interpreted; its fallback data is used"
                ),
            ));
        }
    }
}

fn collect_material_compatibility_diagnostics(
    doc: &gltf::Document,
    diagnostics: &mut Vec<Diagnostic>,
) {
    const LEGACY: &str = "VRMC_materials_hdr_emissiveMultiplier";
    const KHR: &str = "KHR_materials_emissive_strength";

    for material in doc.materials() {
        if material.extension_value(LEGACY).is_none() {
            continue;
        }
        let index = material.index().unwrap_or(0);
        diagnostics.push(Diagnostic::warning(
            "VRM_DEPRECATED_HDR_EMISSIVE_MULTIPLIER",
            format!("/materials/{index}/extensions/{LEGACY}"),
            format!("`{LEGACY}` is archived; prefer `{KHR}` for new assets"),
        ));
        if material.emissive_strength().is_some() {
            diagnostics.push(Diagnostic::warning(
                "VRM_EMISSIVE_STRENGTH_PRECEDENCE",
                format!("/materials/{index}/extensions"),
                format!("both emissive strength extensions are present; `{KHR}` takes precedence"),
            ));
        }
    }
}

/// Human bones that VRM 1.0 requires to be present on every humanoid.
const REQUIRED_HUMAN_BONES: [HumanBoneName; 15] = [
    HumanBoneName::Hips,
    HumanBoneName::Spine,
    HumanBoneName::Head,
    HumanBoneName::LeftUpperLeg,
    HumanBoneName::LeftLowerLeg,
    HumanBoneName::LeftFoot,
    HumanBoneName::RightUpperLeg,
    HumanBoneName::RightLowerLeg,
    HumanBoneName::RightFoot,
    HumanBoneName::LeftUpperArm,
    HumanBoneName::LeftLowerArm,
    HumanBoneName::LeftHand,
    HumanBoneName::RightUpperArm,
    HumanBoneName::RightLowerArm,
    HumanBoneName::RightHand,
];

/// Rejects VRMC_vrm documents that deserialize cleanly but violate VRM 1.0
/// semantic requirements, including metadata cardinalities, all-node scale,
/// humanoid mappings, and extension references.
fn validate_vrm_semantics(
    doc: &gltf::Document,
    schema: &VRMCVrmSchema,
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
) -> Result<(), crate::LoadError> {
    let node_count = doc.nodes().count();
    if schema.spec_version != "1.0" {
        return Err(crate::LoadError::InvalidVrm(format!(
            "unsupported VRMC_vrm specVersion `{}` (expected 1.0)",
            schema.spec_version
        )));
    }

    let bones = &schema.humanoid.human_bones.0;
    let mut assigned_nodes: HashSet<usize> = HashSet::new();

    for &required in &REQUIRED_HUMAN_BONES {
        let bone = bones
            .get(&required)
            .and_then(|entry| entry.as_ref())
            .ok_or_else(|| {
                crate::LoadError::InvalidVrm(format!(
                    "humanoid bone `{}` is required but missing",
                    human_bone_name(required)
                ))
            })?;
        let node_index = bone.node.map(|index| index.value()).ok_or_else(|| {
            crate::LoadError::InvalidVrm(format!(
                "humanoid bone `{}` has no node assignment",
                human_bone_name(required)
            ))
        })?;
        if node_index >= node_count {
            return Err(crate::LoadError::InvalidVrm(format!(
                "humanoid bone `{}` references missing node {}",
                human_bone_name(required),
                node_index
            )));
        }
        if !assigned_nodes.insert(node_index) {
            return Err(crate::LoadError::InvalidVrm(format!(
                "node {} is assigned to more than one humanoid bone",
                node_index
            )));
        }
    }

    if schema.meta.name.trim().is_empty() {
        semantic_violation(
            validation,
            diagnostics,
            "VRM_META_NAME_EMPTY",
            "/extensions/VRMC_vrm/meta/name",
            "meta.name must not be empty",
        )?;
    }
    if schema.meta.authors.is_empty()
        || schema
            .meta
            .authors
            .iter()
            .any(|author| author.trim().is_empty())
    {
        semantic_violation(
            validation,
            diagnostics,
            "VRM_META_AUTHORS_INVALID",
            "/extensions/VRMC_vrm/meta/authors",
            "meta.authors must contain at least one non-empty author",
        )?;
    }
    if schema.meta.references.as_ref().is_some_and(Vec::is_empty) {
        semantic_violation(
            validation,
            diagnostics,
            "VRM_META_REFERENCES_EMPTY",
            "/extensions/VRMC_vrm/meta/references",
            "meta.references must contain at least one item when present",
        )?;
    }

    if let Some(look_at) = &schema.look_at {
        crate::look_at::validate_schema(look_at).map_err(crate::LoadError::InvalidVrm)?;
    }

    for (name, entry) in bones {
        if REQUIRED_HUMAN_BONES.contains(name) {
            continue;
        }
        let bone = entry.as_ref().ok_or_else(|| {
            crate::LoadError::InvalidVrm(format!(
                "humanoid bone `{}` must be an object containing `node`",
                human_bone_name(*name)
            ))
        })?;
        let node_index = bone.node.map(|index| index.value()).ok_or_else(|| {
            crate::LoadError::InvalidVrm(format!(
                "humanoid bone `{}` must contain `node`",
                human_bone_name(*name)
            ))
        })?;
        if node_index >= node_count {
            return Err(crate::LoadError::InvalidVrm(format!(
                "humanoid bone `{}` references missing node {}",
                human_bone_name(*name),
                node_index
            )));
        }
        if !assigned_nodes.insert(node_index) {
            return Err(crate::LoadError::InvalidVrm(format!(
                "node {} is assigned to more than one humanoid bone",
                node_index
            )));
        }
    }

    validate_node_transforms(doc, validation, diagnostics)?;
    validate_humanoid_hierarchy(doc, &schema.humanoid.human_bones, validation, diagnostics)?;
    validate_vrm_references(doc, schema)?;

    Ok(())
}

fn validate_node_transforms(
    doc: &gltf::Document,
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
) -> Result<(), crate::LoadError> {
    for node in doc.nodes() {
        let (_, _, scale) = node.transform().decomposed();
        if !is_positive_uniform_scale(scale) {
            let path = format!("/nodes/{}/scale", node.index());
            match validation {
                ValidationMode::Strict => {
                    return Err(crate::LoadError::InvalidVrm(format!(
                        "{path}: every node scale must be positive and uniform"
                    )));
                }
                ValidationMode::Permissive => diagnostics.push(Diagnostic::warning(
                    "VRM_NODE_SCALE_INVALID",
                    path,
                    "every node scale must be positive and uniform",
                )),
            }
        }
    }
    Ok(())
}

fn is_positive_uniform_scale(scale: [f32; 3]) -> bool {
    let max_scale = scale.iter().copied().fold(0.0_f32, f32::max);
    let uniform_tolerance = max_scale * 2.0e-3;
    scale.iter().all(|value| value.is_finite() && *value > 0.0)
        && (scale[0] - scale[1]).abs() <= uniform_tolerance
        && (scale[1] - scale[2]).abs() <= uniform_tolerance
}

fn validate_humanoid_hierarchy(
    doc: &gltf::Document,
    bones: &vrm_spec::vrmc_vrm_1_0::HumanBones,
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
) -> Result<(), crate::LoadError> {
    let mut parents = vec![None; doc.nodes().count()];
    for node in doc.nodes() {
        for child in node.children() {
            parents[child.index()] = Some(node.index());
        }
    }
    let mapped_bones = bones.0.iter().filter_map(|(name, entry)| {
        entry
            .as_ref()
            .and_then(|bone| bone.node.map(|node| (HumanBone::from(*name), node.value())))
    });
    for violation in crate::humanoid::hierarchy_violations(mapped_bones, &parents) {
        let bone_name = violation.bone().spec_name();
        let message = violation.message();
        match validation {
            ValidationMode::Strict => return Err(crate::LoadError::InvalidVrm(message)),
            ValidationMode::Permissive => diagnostics.push(Diagnostic::warning(
                "VRM_HUMANOID_HIERARCHY_INVALID",
                format!("/extensions/VRMC_vrm/humanoid/humanBones/{bone_name}"),
                message,
            )),
        }
    }
    Ok(())
}

fn validate_vrm_references(
    doc: &gltf::Document,
    schema: &VRMCVrmSchema,
) -> Result<(), crate::LoadError> {
    if let Some(thumbnail) = schema.meta.thumbnail_image.as_ref()
        && thumbnail.value() >= doc.images().count()
    {
        return Err(crate::LoadError::InvalidVrm(format!(
            "/extensions/VRMC_vrm/meta/thumbnailImage references missing image {}",
            thumbnail.value()
        )));
    }

    if let Some(first_person) = &schema.first_person {
        if first_person
            .mesh_annotations
            .as_ref()
            .is_some_and(Vec::is_empty)
        {
            return Err(crate::LoadError::InvalidVrm(
                "/extensions/VRMC_vrm/firstPerson/meshAnnotations must contain at least one item when present"
                    .to_string(),
            ));
        }
        for (index, annotation) in first_person
            .mesh_annotations
            .as_deref()
            .unwrap_or_default()
            .iter()
            .enumerate()
        {
            let node = annotation.node.as_ref().ok_or_else(|| {
                crate::LoadError::InvalidVrm(format!(
                    "/extensions/VRMC_vrm/firstPerson/meshAnnotations/{index}/node is required"
                ))
            })?;
            let node_index = node.value();
            if node_index >= doc.nodes().count()
                || doc
                    .nodes()
                    .nth(node_index)
                    .and_then(|node| node.mesh())
                    .is_none()
            {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "/extensions/VRMC_vrm/firstPerson/meshAnnotations/{index}/node must reference a node with a mesh"
                )));
            }
        }
    }

    let validate_expression = |name: &str,
                               location: String,
                               expression: &vrm_spec::vrmc_vrm_1_0::Expression|
     -> Result<(), crate::LoadError> {
        crate::expressions::validate_override_semantics(
            name,
            expression
                .override_blink
                .map(crate::ExpressionOverrideType::from)
                .unwrap_or_default(),
            expression
                .override_mouth
                .map(crate::ExpressionOverrideType::from)
                .unwrap_or_default(),
            expression
                .override_look_at
                .map(crate::ExpressionOverrideType::from)
                .unwrap_or_default(),
        )
        .map_err(|message| crate::LoadError::InvalidVrm(format!("{location}: {message}")))?;

        for (name, empty) in [
            (
                "morphTargetBinds",
                expression
                    .morph_target_binds
                    .as_ref()
                    .is_some_and(Vec::is_empty),
            ),
            (
                "materialColorBinds",
                expression
                    .material_color_binds
                    .as_ref()
                    .is_some_and(Vec::is_empty),
            ),
            (
                "textureTransformBinds",
                expression
                    .texture_transform_binds
                    .as_ref()
                    .is_some_and(Vec::is_empty),
            ),
        ] {
            if empty {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/{name} must contain at least one item when present"
                )));
            }
        }

        for (index, bind) in expression
            .morph_target_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .enumerate()
        {
            let node_index = bind.node.value();
            let Some(mesh) = doc.nodes().nth(node_index).and_then(|node| node.mesh()) else {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/morphTargetBinds/{index}/node must reference a node with a mesh"
                )));
            };
            if mesh
                .primitives()
                .any(|primitive| bind.index >= primitive.morph_targets().count())
            {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/morphTargetBinds/{index}/index is out of range"
                )));
            }
            if !bind.weight.is_finite() || !(0.0..=1.0).contains(&bind.weight) {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/morphTargetBinds/{index}/weight must be in 0..=1"
                )));
            }
        }
        for (index, bind) in expression
            .material_color_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .enumerate()
        {
            if bind.material.value() >= doc.materials().count()
                || bind.target_value.len() != 4
                || bind
                    .target_value
                    .iter()
                    .any(|&value| !is_representable_f32(value))
            {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/materialColorBinds/{index} has an invalid material or targetValue"
                )));
            }
        }
        for (index, bind) in expression
            .texture_transform_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .enumerate()
        {
            let valid_vector = |value: Option<&Vec<f64>>| {
                value.is_none_or(|value| {
                    value.len() == 2
                        && value
                            .iter()
                            .all(|&component| is_representable_f32(component))
                })
            };
            if bind.material.value() >= doc.materials().count()
                || !valid_vector(bind.scale.as_ref())
                || !valid_vector(bind.offset.as_ref())
            {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "{location}/textureTransformBinds/{index} is invalid"
                )));
            }
        }
        Ok(())
    };

    if let Some(expressions) = &schema.expressions {
        if let Some(preset) = &expressions.preset {
            for (name, expression) in &preset.0 {
                let name = crate::expressions::preset_expression_name(name);
                validate_expression(
                    name,
                    format!("/extensions/VRMC_vrm/expressions/preset/{name}"),
                    expression,
                )?;
            }
        }
        if let Some(custom) = &expressions.custom {
            for (name, expression) in custom {
                if crate::expressions::is_preset_expression_name(name) {
                    return Err(crate::LoadError::InvalidVrm(format!(
                        "/extensions/VRMC_vrm/expressions/custom/{name} conflicts with a preset expression name"
                    )));
                }
                validate_expression(
                    name,
                    format!("/extensions/VRMC_vrm/expressions/custom/{name}"),
                    expression,
                )?;
            }
        }
    }
    Ok(())
}

fn is_representable_f32(value: f64) -> bool {
    value.is_finite() && (value as f32).is_finite()
}

fn semantic_violation(
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
    code: &'static str,
    path: &'static str,
    message: &'static str,
) -> Result<(), crate::LoadError> {
    match validation {
        ValidationMode::Strict => Err(crate::LoadError::InvalidVrm(format!("{path}: {message}"))),
        ValidationMode::Permissive => {
            diagnostics.push(Diagnostic::warning(code, path, message));
            Ok(())
        }
    }
}

/// Serde name of a [`HumanBoneName`] variant, e.g. `Hips` -> `hips`.
fn human_bone_name(name: HumanBoneName) -> String {
    serde_json::to_value(name)
        .ok()
        .and_then(|value| value.as_str().map(str::to_owned))
        .unwrap_or_else(|| format!("{name:?}"))
}

fn load_primitives(
    doc: &gltf::Document,
    buffers: &[gltf::buffer::Data],
) -> Result<Vec<RenderPrimitive>, crate::LoadError> {
    crate::primitive::load_primitives(doc, buffers)
}

fn load_images(
    doc: &gltf::Document,
    buffers: &[gltf::buffer::Data],
    base: Option<&Path>,
) -> Result<Vec<AvatarImage>, crate::LoadError> {
    crate::image::load_images(doc, buffers, base)
}

fn load_materials(doc: &gltf::Document) -> Result<Vec<Material>, crate::LoadError> {
    crate::material::load_materials(doc)
}

fn load_skins(
    doc: &gltf::Document,
    buffers: &[gltf::buffer::Data],
) -> Result<Vec<Skin>, crate::LoadError> {
    crate::skin::load_skins(doc, buffers)
}

fn load_constraints(doc: &gltf::Document) -> Result<Vec<NodeConstraint>, crate::LoadError> {
    constraint::load_constraints(doc)
}

fn load_spring_bone(
    doc: &gltf::Document,
    validation: ValidationMode,
    diagnostics: &mut Vec<Diagnostic>,
) -> Result<SpringBone, crate::LoadError> {
    let Some(value) = doc.extension_value(VRMC_SPRING_BONE) else {
        return Ok(SpringBone::default());
    };
    let schema =
        serde_json::from_value::<VrmcSpringBoneSchema>(value.to_owned()).map_err(|source| {
            crate::LoadError::InvalidExtension {
                extension: VRMC_SPRING_BONE,
                location: "/extensions/VRMC_springBone".to_string(),
                source,
            }
        })?;
    let normalized = crate::spring_bone::validate_schema_with_plane_normalization(
        doc,
        &schema,
        validation == ValidationMode::Permissive,
    )?;
    if normalized {
        diagnostics.push(Diagnostic::warning(
            "VRM_SPRING_COLLIDER_PLANE_NORMAL_NORMALIZED",
            "/extensions/VRMC_springBone/colliders/*/extensions/VRMC_springBone_extended_collider/shape/plane/normal",
            "a finite extended plane collider normal was normalized in permissive mode",
        ));
    }
    let mut spring_bone = SpringBone::load_spring_bone(&schema);
    crate::spring_bone::sort_springs_by_ancestry(doc, &mut spring_bone);
    Ok(spring_bone)
}