-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
loader.rs
2684 lines (2496 loc) · 102 KB
/
loader.rs
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
use crate::{
vertex_attributes::convert_attribute, Gltf, GltfAssetLabel, GltfExtras, GltfMaterialExtras,
GltfMaterialName, GltfMeshExtras, GltfNode, GltfSceneExtras, GltfSkin,
};
use alloc::collections::VecDeque;
use bevy_asset::{
io::Reader, AssetLoadError, AssetLoader, Handle, LoadContext, ReadAssetBytesError,
};
use bevy_color::{Color, LinearRgba};
use bevy_core_pipeline::prelude::Camera3d;
use bevy_ecs::{
entity::{Entity, EntityHashMap},
name::Name,
world::World,
};
use bevy_hierarchy::{BuildChildren, ChildBuild, WorldChildBuilder};
use bevy_image::{
CompressedImageFormats, Image, ImageAddressMode, ImageFilterMode, ImageLoaderSettings,
ImageSampler, ImageSamplerDescriptor, ImageType, TextureError,
};
use bevy_math::{Affine2, Mat4, Vec3};
use bevy_pbr::{
DirectionalLight, MeshMaterial3d, PointLight, SpotLight, StandardMaterial, UvChannel,
MAX_JOINTS,
};
use bevy_render::{
alpha::AlphaMode,
camera::{Camera, OrthographicProjection, PerspectiveProjection, Projection, ScalingMode},
mesh::{
morph::{MeshMorphWeights, MorphAttributes, MorphTargetImage, MorphWeights},
skinning::{SkinnedMesh, SkinnedMeshInverseBindposes},
Indices, Mesh, Mesh3d, MeshVertexAttribute, VertexAttributeValues,
},
primitives::Aabb,
render_asset::RenderAssetUsages,
render_resource::{Face, PrimitiveTopology},
view::Visibility,
};
use bevy_scene::Scene;
#[cfg(not(target_arch = "wasm32"))]
use bevy_tasks::IoTaskPool;
use bevy_transform::components::Transform;
use bevy_utils::{HashMap, HashSet};
use gltf::{
accessor::Iter,
image::Source,
json,
mesh::{util::ReadIndices, Mode},
texture::{Info, MagFilter, MinFilter, TextureTransform, WrappingMode},
Document, Material, Node, Primitive, Semantic,
};
use serde::{Deserialize, Serialize};
use serde_json::{value, Value};
use std::{
io::Error,
path::{Path, PathBuf},
};
use thiserror::Error;
use tracing::{error, info_span, warn};
#[cfg(feature = "bevy_animation")]
use {
bevy_animation::{prelude::*, AnimationTarget, AnimationTargetId},
smallvec::SmallVec,
};
/// An error that occurs when loading a glTF file.
#[derive(Error, Debug)]
pub enum GltfError {
/// Unsupported primitive mode.
#[error("unsupported primitive mode")]
UnsupportedPrimitive {
/// The primitive mode.
mode: Mode,
},
/// Invalid glTF file.
#[error("invalid glTF file: {0}")]
Gltf(#[from] gltf::Error),
/// Binary blob is missing.
#[error("binary blob is missing")]
MissingBlob,
/// Decoding the base64 mesh data failed.
#[error("failed to decode base64 mesh data")]
Base64Decode(#[from] base64::DecodeError),
/// Unsupported buffer format.
#[error("unsupported buffer format")]
BufferFormatUnsupported,
/// Invalid image mime type.
#[error("invalid image mime type: {0}")]
#[from(ignore)]
InvalidImageMimeType(String),
/// Error when loading a texture. Might be due to a disabled image file format feature.
#[error("You may need to add the feature for the file format: {0}")]
ImageError(#[from] TextureError),
/// Failed to read bytes from an asset path.
#[error("failed to read bytes from an asset path: {0}")]
ReadAssetBytesError(#[from] ReadAssetBytesError),
/// Failed to load asset from an asset path.
#[error("failed to load asset from an asset path: {0}")]
AssetLoadError(#[from] AssetLoadError),
/// Missing sampler for an animation.
#[error("Missing sampler for animation {0}")]
#[from(ignore)]
MissingAnimationSampler(usize),
/// Failed to generate tangents.
#[error("failed to generate tangents: {0}")]
GenerateTangentsError(#[from] bevy_render::mesh::GenerateTangentsError),
/// Failed to generate morph targets.
#[error("failed to generate morph targets: {0}")]
MorphTarget(#[from] bevy_render::mesh::morph::MorphBuildError),
/// Circular children in Nodes
#[error("GLTF model must be a tree, found cycle instead at node indices: {0:?}")]
#[from(ignore)]
CircularChildren(String),
/// Failed to load a file.
#[error("failed to load file: {0}")]
Io(#[from] Error),
}
/// Loads glTF files with all of their data as their corresponding bevy representations.
pub struct GltfLoader {
/// List of compressed image formats handled by the loader.
pub supported_compressed_formats: CompressedImageFormats,
/// Custom vertex attributes that will be recognized when loading a glTF file.
///
/// Keys must be the attribute names as found in the glTF data, which must start with an underscore.
/// See [this section of the glTF specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
/// for additional details on custom attributes.
pub custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>,
}
/// Specifies optional settings for processing gltfs at load time. By default, all recognized contents of
/// the gltf will be loaded.
///
/// # Example
///
/// To load a gltf but exclude the cameras, replace a call to `asset_server.load("my.gltf")` with
/// ```no_run
/// # use bevy_asset::{AssetServer, Handle};
/// # use bevy_gltf::*;
/// # let asset_server: AssetServer = panic!();
/// let gltf_handle: Handle<Gltf> = asset_server.load_with_settings(
/// "my.gltf",
/// |s: &mut GltfLoaderSettings| {
/// s.load_cameras = false;
/// }
/// );
/// ```
#[derive(Serialize, Deserialize)]
pub struct GltfLoaderSettings {
/// If empty, the gltf mesh nodes will be skipped.
///
/// Otherwise, nodes will be loaded and retained in RAM/VRAM according to the active flags.
pub load_meshes: RenderAssetUsages,
/// If empty, the gltf materials will be skipped.
///
/// Otherwise, materials will be loaded and retained in RAM/VRAM according to the active flags.
pub load_materials: RenderAssetUsages,
/// If true, the loader will spawn cameras for gltf camera nodes.
pub load_cameras: bool,
/// If true, the loader will spawn lights for gltf light nodes.
pub load_lights: bool,
/// If true, the loader will include the root of the gltf root node.
pub include_source: bool,
}
impl Default for GltfLoaderSettings {
fn default() -> Self {
Self {
load_meshes: RenderAssetUsages::default(),
load_materials: RenderAssetUsages::default(),
load_cameras: true,
load_lights: true,
include_source: false,
}
}
}
impl AssetLoader for GltfLoader {
type Asset = Gltf;
type Settings = GltfLoaderSettings;
type Error = GltfError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &GltfLoaderSettings,
load_context: &mut LoadContext<'_>,
) -> Result<Gltf, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
load_gltf(self, &bytes, load_context, settings).await
}
fn extensions(&self) -> &[&str] {
&["gltf", "glb"]
}
}
/// Loads an entire glTF file.
async fn load_gltf<'a, 'b, 'c>(
loader: &GltfLoader,
bytes: &'a [u8],
load_context: &'b mut LoadContext<'c>,
settings: &'b GltfLoaderSettings,
) -> Result<Gltf, GltfError> {
let gltf = gltf::Gltf::from_slice(bytes)?;
let file_name = load_context
.asset_path()
.path()
.to_str()
.ok_or(GltfError::Gltf(gltf::Error::Io(Error::new(
std::io::ErrorKind::InvalidInput,
"Gltf file name invalid",
))))?
.to_string();
let buffer_data = load_buffers(&gltf, load_context).await?;
let mut linear_textures = <HashSet<_>>::default();
for material in gltf.materials() {
if let Some(texture) = material.normal_texture() {
linear_textures.insert(texture.texture().index());
}
if let Some(texture) = material.occlusion_texture() {
linear_textures.insert(texture.texture().index());
}
if let Some(texture) = material
.pbr_metallic_roughness()
.metallic_roughness_texture()
{
linear_textures.insert(texture.texture().index());
}
if let Some(texture_index) = material_extension_texture_index(
&material,
"KHR_materials_anisotropy",
"anisotropyTexture",
) {
linear_textures.insert(texture_index);
}
// None of the clearcoat maps should be loaded as sRGB.
#[cfg(feature = "pbr_multi_layer_material_textures")]
for texture_field_name in [
"clearcoatTexture",
"clearcoatRoughnessTexture",
"clearcoatNormalTexture",
] {
if let Some(texture_index) = material_extension_texture_index(
&material,
"KHR_materials_clearcoat",
texture_field_name,
) {
linear_textures.insert(texture_index);
}
}
}
#[cfg(feature = "bevy_animation")]
let paths = {
let mut paths = HashMap::<usize, (usize, Vec<Name>)>::default();
for scene in gltf.scenes() {
for node in scene.nodes() {
let root_index = node.index();
paths_recur(node, &[], &mut paths, root_index, &mut HashSet::default());
}
}
paths
};
#[cfg(feature = "bevy_animation")]
let (animations, named_animations, animation_roots) = {
use bevy_animation::{animated_field, animation_curves::*, gltf_curves::*, VariableCurve};
use bevy_math::{
curve::{ConstantCurve, Interval, UnevenSampleAutoCurve},
Quat, Vec4,
};
use gltf::animation::util::ReadOutputs;
let mut animations = vec![];
let mut named_animations = <HashMap<_, _>>::default();
let mut animation_roots = <HashSet<_>>::default();
for animation in gltf.animations() {
let mut animation_clip = AnimationClip::default();
for channel in animation.channels() {
let node = channel.target().node();
let interpolation = channel.sampler().interpolation();
let reader = channel.reader(|buffer| Some(&buffer_data[buffer.index()]));
let keyframe_timestamps: Vec<f32> = if let Some(inputs) = reader.read_inputs() {
match inputs {
Iter::Standard(times) => times.collect(),
Iter::Sparse(_) => {
warn!("Sparse accessor not supported for animation sampler input");
continue;
}
}
} else {
warn!("Animations without a sampler input are not supported");
return Err(GltfError::MissingAnimationSampler(animation.index()));
};
if keyframe_timestamps.is_empty() {
warn!("Tried to load animation with no keyframe timestamps");
continue;
}
let maybe_curve: Option<VariableCurve> = if let Some(outputs) =
reader.read_outputs()
{
match outputs {
ReadOutputs::Translations(tr) => {
let translation_property = animated_field!(Transform::translation);
let translations: Vec<Vec3> = tr.map(Vec3::from).collect();
if keyframe_timestamps.len() == 1 {
Some(VariableCurve::new(AnimatableCurve::new(
translation_property,
ConstantCurve::new(Interval::EVERYWHERE, translations[0]),
)))
} else {
match interpolation {
gltf::animation::Interpolation::Linear => {
UnevenSampleAutoCurve::new(
keyframe_timestamps.into_iter().zip(translations),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
translation_property,
curve,
))
})
}
gltf::animation::Interpolation::Step => {
SteppedKeyframeCurve::new(
keyframe_timestamps.into_iter().zip(translations),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
translation_property,
curve,
))
})
}
gltf::animation::Interpolation::CubicSpline => {
CubicKeyframeCurve::new(keyframe_timestamps, translations)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
translation_property,
curve,
))
})
}
}
}
}
ReadOutputs::Rotations(rots) => {
let rotation_property = animated_field!(Transform::rotation);
let rotations: Vec<Quat> =
rots.into_f32().map(Quat::from_array).collect();
if keyframe_timestamps.len() == 1 {
Some(VariableCurve::new(AnimatableCurve::new(
rotation_property,
ConstantCurve::new(Interval::EVERYWHERE, rotations[0]),
)))
} else {
match interpolation {
gltf::animation::Interpolation::Linear => {
UnevenSampleAutoCurve::new(
keyframe_timestamps.into_iter().zip(rotations),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
rotation_property,
curve,
))
})
}
gltf::animation::Interpolation::Step => {
SteppedKeyframeCurve::new(
keyframe_timestamps.into_iter().zip(rotations),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
rotation_property,
curve,
))
})
}
gltf::animation::Interpolation::CubicSpline => {
CubicRotationCurve::new(
keyframe_timestamps,
rotations.into_iter().map(Vec4::from),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
rotation_property,
curve,
))
})
}
}
}
}
ReadOutputs::Scales(scale) => {
let scale_property = animated_field!(Transform::scale);
let scales: Vec<Vec3> = scale.map(Vec3::from).collect();
if keyframe_timestamps.len() == 1 {
Some(VariableCurve::new(AnimatableCurve::new(
scale_property,
ConstantCurve::new(Interval::EVERYWHERE, scales[0]),
)))
} else {
match interpolation {
gltf::animation::Interpolation::Linear => {
UnevenSampleAutoCurve::new(
keyframe_timestamps.into_iter().zip(scales),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
scale_property,
curve,
))
})
}
gltf::animation::Interpolation::Step => {
SteppedKeyframeCurve::new(
keyframe_timestamps.into_iter().zip(scales),
)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
scale_property,
curve,
))
})
}
gltf::animation::Interpolation::CubicSpline => {
CubicKeyframeCurve::new(keyframe_timestamps, scales)
.ok()
.map(|curve| {
VariableCurve::new(AnimatableCurve::new(
scale_property,
curve,
))
})
}
}
}
}
ReadOutputs::MorphTargetWeights(weights) => {
let weights: Vec<f32> = weights.into_f32().collect();
if keyframe_timestamps.len() == 1 {
#[allow(clippy::unnecessary_map_on_constructor)]
Some(ConstantCurve::new(Interval::EVERYWHERE, weights))
.map(WeightsCurve)
.map(VariableCurve::new)
} else {
match interpolation {
gltf::animation::Interpolation::Linear => {
WideLinearKeyframeCurve::new(keyframe_timestamps, weights)
.ok()
.map(WeightsCurve)
.map(VariableCurve::new)
}
gltf::animation::Interpolation::Step => {
WideSteppedKeyframeCurve::new(keyframe_timestamps, weights)
.ok()
.map(WeightsCurve)
.map(VariableCurve::new)
}
gltf::animation::Interpolation::CubicSpline => {
WideCubicKeyframeCurve::new(keyframe_timestamps, weights)
.ok()
.map(WeightsCurve)
.map(VariableCurve::new)
}
}
}
}
}
} else {
warn!("Animations without a sampler output are not supported");
return Err(GltfError::MissingAnimationSampler(animation.index()));
};
let Some(curve) = maybe_curve else {
warn!(
"Invalid keyframe data for node {}; curve could not be constructed",
node.index()
);
continue;
};
if let Some((root_index, path)) = paths.get(&node.index()) {
animation_roots.insert(*root_index);
animation_clip.add_variable_curve_to_target(
AnimationTargetId::from_names(path.iter()),
curve,
);
} else {
warn!(
"Animation ignored for node {}: part of its hierarchy is missing a name",
node.index()
);
}
}
let handle = load_context.add_labeled_asset(
GltfAssetLabel::Animation(animation.index()).to_string(),
animation_clip,
);
if let Some(name) = animation.name() {
named_animations.insert(name.into(), handle.clone());
}
animations.push(handle);
}
(animations, named_animations, animation_roots)
};
// TODO: use the threaded impl on wasm once wasm thread pool doesn't deadlock on it
// See https://github.com/bevyengine/bevy/issues/1924 for more details
// The taskpool use is also avoided when there is only one texture for performance reasons and
// to avoid https://github.com/bevyengine/bevy/pull/2725
// PERF: could this be a Vec instead? Are gltf texture indices dense?
fn process_loaded_texture(
load_context: &mut LoadContext,
handles: &mut Vec<Handle<Image>>,
texture: ImageOrPath,
) {
let handle = match texture {
ImageOrPath::Image { label, image } => {
load_context.add_labeled_asset(label.to_string(), image)
}
ImageOrPath::Path {
path,
is_srgb,
sampler_descriptor,
} => load_context
.loader()
.with_settings(move |settings: &mut ImageLoaderSettings| {
settings.is_srgb = is_srgb;
settings.sampler = ImageSampler::Descriptor(sampler_descriptor.clone());
})
.load(path),
};
handles.push(handle);
}
// We collect handles to ensure loaded images from paths are not unloaded before they are used elsewhere
// in the loader. This prevents "reloads", but it also prevents dropping the is_srgb context on reload.
//
// In theory we could store a mapping between texture.index() and handle to use
// later in the loader when looking up handles for materials. However this would mean
// that the material's load context would no longer track those images as dependencies.
let mut _texture_handles = Vec::new();
if gltf.textures().len() == 1 || cfg!(target_arch = "wasm32") {
for texture in gltf.textures() {
let parent_path = load_context.path().parent().unwrap();
let image = load_image(
texture,
&buffer_data,
&linear_textures,
parent_path,
loader.supported_compressed_formats,
settings.load_materials,
)
.await?;
process_loaded_texture(load_context, &mut _texture_handles, image);
}
} else {
#[cfg(not(target_arch = "wasm32"))]
IoTaskPool::get()
.scope(|scope| {
gltf.textures().for_each(|gltf_texture| {
let parent_path = load_context.path().parent().unwrap();
let linear_textures = &linear_textures;
let buffer_data = &buffer_data;
scope.spawn(async move {
load_image(
gltf_texture,
buffer_data,
linear_textures,
parent_path,
loader.supported_compressed_formats,
settings.load_materials,
)
.await
});
});
})
.into_iter()
.for_each(|result| match result {
Ok(image) => {
process_loaded_texture(load_context, &mut _texture_handles, image);
}
Err(err) => {
warn!("Error loading glTF texture: {}", err);
}
});
}
let mut materials = vec![];
let mut named_materials = <HashMap<_, _>>::default();
// Only include materials in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_materials flag
if !settings.load_materials.is_empty() {
// NOTE: materials must be loaded after textures because image load() calls will happen before load_with_settings, preventing is_srgb from being set properly
for material in gltf.materials() {
let handle = load_material(&material, load_context, &gltf.document, false);
if let Some(name) = material.name() {
named_materials.insert(name.into(), handle.clone());
}
materials.push(handle);
}
}
let mut meshes = vec![];
let mut named_meshes = <HashMap<_, _>>::default();
let mut meshes_on_skinned_nodes = <HashSet<_>>::default();
let mut meshes_on_non_skinned_nodes = <HashSet<_>>::default();
for gltf_node in gltf.nodes() {
if gltf_node.skin().is_some() {
if let Some(mesh) = gltf_node.mesh() {
meshes_on_skinned_nodes.insert(mesh.index());
}
} else if let Some(mesh) = gltf_node.mesh() {
meshes_on_non_skinned_nodes.insert(mesh.index());
}
}
for gltf_mesh in gltf.meshes() {
let mut primitives = vec![];
for primitive in gltf_mesh.primitives() {
let primitive_label = GltfAssetLabel::Primitive {
mesh: gltf_mesh.index(),
primitive: primitive.index(),
};
let primitive_topology = get_primitive_topology(primitive.mode())?;
let mut mesh = Mesh::new(primitive_topology, settings.load_meshes);
// Read vertex attributes
for (semantic, accessor) in primitive.attributes() {
if [Semantic::Joints(0), Semantic::Weights(0)].contains(&semantic) {
if !meshes_on_skinned_nodes.contains(&gltf_mesh.index()) {
warn!(
"Ignoring attribute {:?} for skinned mesh {} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)",
semantic,
primitive_label
);
continue;
} else if meshes_on_non_skinned_nodes.contains(&gltf_mesh.index()) {
error!("Skinned mesh {} used on both skinned and non skin nodes, this is likely to cause an error (NODE_SKINNED_MESH_WITHOUT_SKIN)", primitive_label);
}
}
match convert_attribute(
semantic,
accessor,
&buffer_data,
&loader.custom_vertex_attributes,
) {
Ok((attribute, values)) => mesh.insert_attribute(attribute, values),
Err(err) => warn!("{}", err),
}
}
// Read vertex indices
let reader = primitive.reader(|buffer| Some(buffer_data[buffer.index()].as_slice()));
if let Some(indices) = reader.read_indices() {
mesh.insert_indices(match indices {
ReadIndices::U8(is) => Indices::U16(is.map(|x| x as u16).collect()),
ReadIndices::U16(is) => Indices::U16(is.collect()),
ReadIndices::U32(is) => Indices::U32(is.collect()),
});
};
{
let morph_target_reader = reader.read_morph_targets();
if morph_target_reader.len() != 0 {
let morph_targets_label = GltfAssetLabel::MorphTarget {
mesh: gltf_mesh.index(),
primitive: primitive.index(),
};
let morph_target_image = MorphTargetImage::new(
morph_target_reader.map(PrimitiveMorphAttributesIter),
mesh.count_vertices(),
RenderAssetUsages::default(),
)?;
let handle = load_context
.add_labeled_asset(morph_targets_label.to_string(), morph_target_image.0);
mesh.set_morph_targets(handle);
let extras = gltf_mesh.extras().as_ref();
if let Some(names) = extras.and_then(|extras| {
serde_json::from_str::<MorphTargetNames>(extras.get()).ok()
}) {
mesh.set_morph_target_names(names.target_names);
}
}
}
if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_none()
&& matches!(mesh.primitive_topology(), PrimitiveTopology::TriangleList)
{
tracing::debug!("Automatically calculating missing vertex normals for geometry.");
let vertex_count_before = mesh.count_vertices();
mesh.duplicate_vertices();
mesh.compute_flat_normals();
let vertex_count_after = mesh.count_vertices();
if vertex_count_before != vertex_count_after {
tracing::debug!("Missing vertex normals in indexed geometry, computing them as flat. Vertex count increased from {} to {}", vertex_count_before, vertex_count_after);
} else {
tracing::debug!(
"Missing vertex normals in indexed geometry, computing them as flat."
);
}
}
if let Some(vertex_attribute) = reader
.read_tangents()
.map(|v| VertexAttributeValues::Float32x4(v.collect()))
{
mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, vertex_attribute);
} else if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_some()
&& material_needs_tangents(&primitive.material())
{
tracing::debug!(
"Missing vertex tangents for {}, computing them using the mikktspace algorithm. Consider using a tool such as Blender to pre-compute the tangents.", file_name
);
let generate_tangents_span = info_span!("generate_tangents", name = file_name);
generate_tangents_span.in_scope(|| {
if let Err(err) = mesh.generate_tangents() {
warn!(
"Failed to generate vertex tangents using the mikktspace algorithm: {}",
err
);
}
});
}
let mesh_handle = load_context.add_labeled_asset(primitive_label.to_string(), mesh);
primitives.push(super::GltfPrimitive::new(
&gltf_mesh,
&primitive,
mesh_handle,
primitive
.material()
.index()
.and_then(|i| materials.get(i).cloned()),
get_gltf_extras(primitive.extras()),
get_gltf_extras(primitive.material().extras()),
));
}
let mesh =
super::GltfMesh::new(&gltf_mesh, primitives, get_gltf_extras(gltf_mesh.extras()));
let handle = load_context.add_labeled_asset(mesh.asset_label().to_string(), mesh);
if let Some(name) = gltf_mesh.name() {
named_meshes.insert(name.into(), handle.clone());
}
meshes.push(handle);
}
let skinned_mesh_inverse_bindposes: Vec<_> = gltf
.skins()
.map(|gltf_skin| {
let reader = gltf_skin.reader(|buffer| Some(&buffer_data[buffer.index()]));
let local_to_bone_bind_matrices: Vec<Mat4> = reader
.read_inverse_bind_matrices()
.unwrap()
.map(|mat| Mat4::from_cols_array_2d(&mat))
.collect();
load_context.add_labeled_asset(
inverse_bind_matrices_label(&gltf_skin),
SkinnedMeshInverseBindposes::from(local_to_bone_bind_matrices),
)
})
.collect();
let mut nodes = HashMap::<usize, Handle<GltfNode>>::default();
let mut named_nodes = <HashMap<_, _>>::default();
let mut skins = vec![];
let mut named_skins = <HashMap<_, _>>::default();
for node in GltfTreeIterator::try_new(&gltf)? {
let skin = node.skin().map(|skin| {
let joints = skin
.joints()
.map(|joint| nodes.get(&joint.index()).unwrap().clone())
.collect();
let gltf_skin = GltfSkin::new(
&skin,
joints,
skinned_mesh_inverse_bindposes[skin.index()].clone(),
get_gltf_extras(skin.extras()),
);
let handle = load_context.add_labeled_asset(skin_label(&skin), gltf_skin);
skins.push(handle.clone());
if let Some(name) = skin.name() {
named_skins.insert(name.into(), handle.clone());
}
handle
});
let children = node
.children()
.map(|child| nodes.get(&child.index()).unwrap().clone())
.collect();
let mesh = node
.mesh()
.map(|mesh| mesh.index())
.and_then(|i| meshes.get(i).cloned());
let gltf_node = GltfNode::new(
&node,
children,
mesh,
node_transform(&node),
skin,
get_gltf_extras(node.extras()),
);
#[cfg(feature = "bevy_animation")]
let gltf_node = gltf_node.with_animation_root(animation_roots.contains(&node.index()));
let handle = load_context.add_labeled_asset(gltf_node.asset_label().to_string(), gltf_node);
nodes.insert(node.index(), handle.clone());
if let Some(name) = node.name() {
named_nodes.insert(name.into(), handle);
}
}
let mut nodes_to_sort = nodes.into_iter().collect::<Vec<_>>();
nodes_to_sort.sort_by_key(|(i, _)| *i);
let nodes = nodes_to_sort
.into_iter()
.map(|(_, resolved)| resolved)
.collect();
let mut scenes = vec![];
let mut named_scenes = <HashMap<_, _>>::default();
let mut active_camera_found = false;
for scene in gltf.scenes() {
let mut err = None;
let mut world = World::default();
let mut node_index_to_entity_map = <HashMap<_, _>>::default();
let mut entity_to_skin_index_map = EntityHashMap::default();
let mut scene_load_context = load_context.begin_labeled_asset();
let world_root_id = world
.spawn((Transform::default(), Visibility::default()))
.with_children(|parent| {
for node in scene.nodes() {
let result = load_node(
&node,
parent,
load_context,
&mut scene_load_context,
settings,
&mut node_index_to_entity_map,
&mut entity_to_skin_index_map,
&mut active_camera_found,
&Transform::default(),
#[cfg(feature = "bevy_animation")]
&animation_roots,
#[cfg(feature = "bevy_animation")]
None,
&gltf.document,
);
if result.is_err() {
err = Some(result);
return;
}
}
})
.id();
if let Some(extras) = scene.extras().as_ref() {
world.entity_mut(world_root_id).insert(GltfSceneExtras {
value: extras.get().to_string(),
});
}
if let Some(Err(err)) = err {
return Err(err);
}
#[cfg(feature = "bevy_animation")]
{
// for each node root in a scene, check if it's the root of an animation
// if it is, add the AnimationPlayer component
for node in scene.nodes() {
if animation_roots.contains(&node.index()) {
world
.entity_mut(*node_index_to_entity_map.get(&node.index()).unwrap())
.insert(AnimationPlayer::default());
}
}
}
for (&entity, &skin_index) in &entity_to_skin_index_map {
let mut entity = world.entity_mut(entity);
let skin = gltf.skins().nth(skin_index).unwrap();
let joint_entities: Vec<_> = skin
.joints()
.map(|node| node_index_to_entity_map[&node.index()])
.collect();
entity.insert(SkinnedMesh {
inverse_bindposes: skinned_mesh_inverse_bindposes[skin_index].clone(),
joints: joint_entities,
});
}
let loaded_scene = scene_load_context.finish(Scene::new(world));
let scene_handle = load_context.add_loaded_labeled_asset(scene_label(&scene), loaded_scene);
if let Some(name) = scene.name() {
named_scenes.insert(name.into(), scene_handle.clone());
}
scenes.push(scene_handle);
}
Ok(Gltf {
default_scene: gltf
.default_scene()
.and_then(|scene| scenes.get(scene.index()))
.cloned(),
scenes,
named_scenes,
meshes,
named_meshes,
skins,
named_skins,
materials,
named_materials,
nodes,
named_nodes,
#[cfg(feature = "bevy_animation")]
animations,
#[cfg(feature = "bevy_animation")]
named_animations,
source: if settings.include_source {
Some(gltf)
} else {
None
},
})
}
fn get_gltf_extras(extras: &json::Extras) -> Option<GltfExtras> {
extras.as_ref().map(|extras| GltfExtras {
value: extras.get().to_string(),
})
}
/// Calculate the transform of gLTF node.
///
/// This should be used instead of calling [`gltf::scene::Transform::matrix()`]
/// on [`Node::transform()`] directly because it uses optimized glam types and
/// if `libm` feature of `bevy_math` crate is enabled also handles cross
/// platform determinism properly.
fn node_transform(node: &Node) -> Transform {
match node.transform() {
gltf::scene::Transform::Matrix { matrix } => {
Transform::from_matrix(Mat4::from_cols_array_2d(&matrix))
}
gltf::scene::Transform::Decomposed {
translation,
rotation,
scale,
} => Transform {
translation: Vec3::from(translation),
rotation: bevy_math::Quat::from_array(rotation),
scale: Vec3::from(scale),
},
}
}
fn node_name(node: &Node) -> Name {
let name = node
.name()
.map(ToString::to_string)
.unwrap_or_else(|| format!("GltfNode{}", node.index()));
Name::new(name)
}
#[cfg(feature = "bevy_animation")]
fn paths_recur(
node: Node,
current_path: &[Name],
paths: &mut HashMap<usize, (usize, Vec<Name>)>,
root_index: usize,