-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathbabylonFileLoader.ts
More file actions
1311 lines (1192 loc) · 67.3 KB
/
babylonFileLoader.ts
File metadata and controls
1311 lines (1192 loc) · 67.3 KB
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
import { Logger } from "../../Misc/logger";
import type { Nullable } from "../../types";
import { Camera } from "../../Cameras/camera";
import type { Scene } from "../../scene";
import { Vector3 } from "../../Maths/math.vector";
import { Color3, Color4 } from "../../Maths/math.color";
import { Mesh } from "../../Meshes/mesh";
import type { AbstractMesh } from "../../Meshes/abstractMesh";
import { Geometry } from "../../Meshes/geometry";
import type { Node } from "../../node";
import { TransformNode } from "../../Meshes/transformNode";
import { Material } from "../../Materials/material";
import { MultiMaterial } from "../../Materials/multiMaterial";
import { CubeTexture } from "../../Materials/Textures/cubeTexture";
import { HDRCubeTexture } from "../../Materials/Textures/hdrCubeTexture";
import { AnimationGroup } from "../../Animations/animationGroup";
import { Light } from "../../Lights/light";
import { SceneComponentConstants } from "../../sceneComponent";
import { RegisterSceneLoaderPlugin } from "../../Loading/sceneLoader";
import { SceneLoaderFlags } from "../sceneLoaderFlags";
import { Constants } from "../../Engines/constants";
import { AssetContainer } from "../../assetContainer";
import { ActionManager } from "../../Actions/actionManager";
import type { IParticleSystem } from "../../Particles/IParticleSystem";
import { Skeleton } from "../../Bones/skeleton";
import { MorphTargetManager } from "../../Morph/morphTargetManager";
import { CannonJSPlugin } from "../../Physics/v1/Plugins/cannonJSPlugin";
import { OimoJSPlugin } from "../../Physics/v1/Plugins/oimoJSPlugin";
import { AmmoJSPlugin } from "../../Physics/v1/Plugins/ammoJSPlugin";
import { ReflectionProbe } from "../../Probes/reflectionProbe";
import { GetClass } from "../../Misc/typeStore";
import { Tools } from "../../Misc/tools";
import { PostProcess } from "../../PostProcesses/postProcess";
import { SpriteManager } from "core/Sprites/spriteManager";
import { GetIndividualParser, Parse } from "./babylonFileParser.function";
import { Observable } from "../../Misc/observable";
import type { MorphTarget } from "../../Morph/morphTarget";
import "../../Physics/joinedPhysicsEngineComponent";
import "../../Helpers/sceneHelpers";
/** @internal */
// eslint-disable-next-line @typescript-eslint/naming-convention, no-var
export var _BabylonLoaderRegistered = true;
/**
* Helps setting up some configuration for the babylon file loader.
*/
export class BabylonFileLoaderConfiguration {
/**
* The loader does not allow injecting custom physics engine into the plugins.
* Unfortunately in ES6, we need to manually inject them into the plugin.
* So you could set this variable to your engine import to make it work.
*/
public static LoaderInjectedPhysicsEngine: any = undefined;
}
let TempIndexContainer: { [key: string]: Node } = {};
let TempMaterialIndexContainer: { [key: string]: Material } = {};
let TempMorphTargetIndexContainer: { [key: number]: MorphTarget } = {};
let TempMorphTargetManagerIndexContainer: { [key: string]: MorphTargetManager } = {};
let TempSkeletonIndexContainer: { [key: number]: Skeleton } = {};
const ParseMaterialByPredicate = (predicate: (parsedMaterial: any) => boolean, parsedData: any, scene: Scene, rootUrl: string) => {
if (!parsedData.materials) {
return null;
}
for (let index = 0, cache = parsedData.materials.length; index < cache; index++) {
const parsedMaterial = parsedData.materials[index];
if (predicate(parsedMaterial)) {
return { parsedMaterial, material: Material.Parse(parsedMaterial, scene, rootUrl) };
}
}
return null;
};
const IsDescendantOf = (mesh: any, names: Array<any>, hierarchyIds: Array<number>) => {
for (const i in names) {
if (mesh.name === names[i]) {
hierarchyIds.push(mesh.id);
return true;
}
}
if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) {
hierarchyIds.push(mesh.id);
return true;
}
return false;
};
// eslint-disable-next-line @typescript-eslint/naming-convention
const logOperation = (operation: string, producer: { file: string; name: string; version: string; exporter_version: string }) => {
return (
operation +
" of " +
(producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown")
);
};
const LoadDetailLevels = (scene: Scene, mesh: AbstractMesh) => {
const mastermesh: Mesh = mesh as Mesh;
// Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level.
// The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs.
if (mesh._waitingData.lods) {
if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {
const lodmeshes: string[] = mesh._waitingData.lods.ids;
const wasenabled: boolean = mastermesh.isEnabled(false);
if (mesh._waitingData.lods.distances) {
const distances: number[] = mesh._waitingData.lods.distances;
if (distances.length >= lodmeshes.length) {
const culling: number = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0;
mastermesh.setEnabled(false);
for (let index = 0; index < lodmeshes.length; index++) {
const lodid: string = lodmeshes[index];
const lodmesh: Mesh = scene.getMeshById(lodid) as Mesh;
if (lodmesh != null) {
mastermesh.addLODLevel(distances[index], lodmesh);
}
}
if (culling > 0) {
mastermesh.addLODLevel(culling, null);
}
if (wasenabled === true) {
mastermesh.setEnabled(true);
}
} else {
Tools.Warn("Invalid level of detail distances for " + mesh.name);
}
}
}
mesh._waitingData.lods = null;
}
};
const FindParent = (parentId: any, parentInstanceIndex: any, scene: Scene) => {
if (typeof parentId !== "number") {
const parentEntry = scene.getLastEntryById(parentId);
if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {
const instance = (parentEntry as Mesh).instances[parseInt(parentInstanceIndex)];
return instance;
}
return parentEntry;
}
const parent = TempIndexContainer[parentId];
if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {
const instance = (parent as Mesh).instances[parseInt(parentInstanceIndex)];
return instance;
}
return parent;
};
const FindMaterial = (materialId: any, scene: Scene) => {
if (typeof materialId !== "number") {
return scene.getLastMaterialById(materialId, true);
}
return TempMaterialIndexContainer[materialId];
};
/**
* @experimental
* Loads an AssetContainer from a serialized Babylon scene.
* @param scene The scene to load the asset container into.
* @param serializedScene The serialized scene data. This can be either a JSON string, or an object (e.g. from a call to JSON.parse).
* @param rootUrl The root URL for loading assets.
* @returns The loaded AssetContainer.
*/
export function LoadAssetContainerFromSerializedScene(scene: Scene, serializedScene: string | object, rootUrl: string): AssetContainer {
return LoadAssetContainer(scene, serializedScene, rootUrl);
}
const LoadAssetContainer = (scene: Scene, data: string | object, rootUrl: string, onError?: (message: string, exception?: any) => void, addToScene = false): AssetContainer => {
const container = new AssetContainer(scene);
// When loading into a container (not directly into the scene), suppress entity-added
// observables to prevent scene events during loading. Entities still get added to scene
// arrays (so the linking code can find them), but no events fire.
// They are removed from the scene at the end via container.removeAllFromScene().
let savedObservables: Record<string, Observable<any>> | undefined;
if (!addToScene) {
savedObservables = {
mesh: scene.onNewMeshAddedObservable,
transformNode: scene.onNewTransformNodeAddedObservable,
light: scene.onNewLightAddedObservable,
camera: scene.onNewCameraAddedObservable,
material: scene.onNewMaterialAddedObservable,
multiMaterial: scene.onNewMultiMaterialAddedObservable,
texture: scene.onNewTextureAddedObservable,
skeleton: scene.onNewSkeletonAddedObservable,
geometry: scene.onNewGeometryAddedObservable,
animationGroup: scene.onNewAnimationGroupAddedObservable,
particleSystem: scene.onNewParticleSystemAddedObservable,
};
scene.onNewMeshAddedObservable = new Observable();
scene.onNewTransformNodeAddedObservable = new Observable();
scene.onNewLightAddedObservable = new Observable();
scene.onNewCameraAddedObservable = new Observable();
scene.onNewMaterialAddedObservable = new Observable();
scene.onNewMultiMaterialAddedObservable = new Observable();
scene.onNewTextureAddedObservable = new Observable();
scene.onNewSkeletonAddedObservable = new Observable();
scene.onNewGeometryAddedObservable = new Observable();
scene.onNewAnimationGroupAddedObservable = new Observable();
scene.onNewParticleSystemAddedObservable = new Observable();
}
// Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
// when SceneLoader.debugLogging = true (default), or exception encountered.
// Everything stored in var log instead of writing separate lines to support only writing in exception,
// and avoid problems with multiple concurrent .babylon loads.
let log = "importScene has failed JSON parse";
try {
// eslint-disable-next-line no-var
var parsedData = typeof data === "object" ? data : JSON.parse(data);
log = "";
const fullDetails = SceneLoaderFlags.loggingLevel === Constants.SCENELOADER_DETAILED_LOGGING;
let index: number;
let cache: number;
// Environment texture
if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
// PBR needed for both HDR texture (gamma space) & a sky box
const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
const hdrSize: number = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128;
const hdrTexture = new HDRCubeTexture(
(parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture,
scene,
hdrSize,
true,
!isPBR,
undefined,
parsedData.environmentTexturePrefilterOnLoad
);
if (parsedData.environmentTextureRotationY) {
hdrTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = hdrTexture;
} else {
if (typeof parsedData.environmentTexture === "object") {
const environmentTexture = CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl);
scene.environmentTexture = environmentTexture;
} else if ((parsedData.environmentTexture as string).endsWith(".env")) {
const compressedTexture = new CubeTexture(
(parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture,
scene,
parsedData.environmentTextureForcedExtension
);
if (parsedData.environmentTextureRotationY) {
compressedTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = compressedTexture;
} else {
const cubeTexture = CubeTexture.CreateFromPrefilteredData(
(parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture,
scene,
parsedData.environmentTextureForcedExtension
);
if (parsedData.environmentTextureRotationY) {
cubeTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = cubeTexture;
}
}
if (parsedData.createDefaultSkybox === true) {
const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
}
container.environmentTexture = scene.environmentTexture;
}
// Environment Intensity
if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {
scene.environmentIntensity = parsedData.environmentIntensity;
}
// IBL Intensity
if (parsedData.iblIntensity !== undefined && parsedData.iblIntensity !== null) {
scene.iblIntensity = parsedData.iblIntensity;
}
// Lights
if (parsedData.lights !== undefined && parsedData.lights !== null) {
for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
const parsedLight = parsedData.lights[index];
const light = Light.Parse(parsedLight, scene);
if (light) {
TempIndexContainer[parsedLight.uniqueId] = light;
container.lights.push(light);
light._parentContainer = container;
log += index === 0 ? "\n\tLights:" : "";
log += "\n\t\t" + light.toString(fullDetails);
}
}
}
// Reflection probes
if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {
for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {
const parsedReflectionProbe = parsedData.reflectionProbes[index];
const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);
if (reflectionProbe) {
container.reflectionProbes.push(reflectionProbe);
reflectionProbe._parentContainer = container;
log += index === 0 ? "\n\tReflection Probes:" : "";
log += "\n\t\t" + reflectionProbe.toString(fullDetails);
}
}
}
// Animations
if (parsedData.animations !== undefined && parsedData.animations !== null) {
for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
const parsedAnimation = parsedData.animations[index];
const internalClass = GetClass("BABYLON.Animation");
if (internalClass) {
const animation = internalClass.Parse(parsedAnimation);
scene.animations.push(animation);
container.animations.push(animation);
log += index === 0 ? "\n\tAnimations:" : "";
log += "\n\t\t" + animation.toString(fullDetails);
}
}
}
// Materials
if (parsedData.materials !== undefined && parsedData.materials !== null) {
for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
const parsedMaterial = parsedData.materials[index];
const mat = Material.Parse(parsedMaterial, scene, rootUrl);
if (mat) {
TempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat;
container.materials.push(mat);
mat._parentContainer = container;
log += index === 0 ? "\n\tMaterials:" : "";
log += "\n\t\t" + mat.toString(fullDetails);
// Textures
const textures = mat.getActiveTextures();
for (const t of textures) {
if (container.textures.indexOf(t) == -1) {
container.textures.push(t);
t._parentContainer = container;
}
}
}
}
}
if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
const parsedMultiMaterial = parsedData.multiMaterials[index];
const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
TempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;
container.multiMaterials.push(mmat);
mmat._parentContainer = container;
log += index === 0 ? "\n\tMultiMaterials:" : "";
log += "\n\t\t" + mmat.toString(fullDetails);
// Textures
const textures = mmat.getActiveTextures();
for (const t of textures) {
if (container.textures.indexOf(t) == -1) {
container.textures.push(t);
t._parentContainer = container;
}
}
}
}
// Morph target managers
if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
for (const parsedManager of parsedData.morphTargetManagers) {
const manager = MorphTargetManager.Parse(parsedManager, scene);
TempMorphTargetManagerIndexContainer[parsedManager.id] = manager;
container.morphTargetManagers.push(manager);
manager._parentContainer = container;
// Morph targets - add to TempMorphTargetIndexContainer to later connect animations -> morph targets
for (let index = 0; index < parsedManager.targets.length; index++) {
const parsedTarget = parsedManager.targets[index];
if (parsedTarget.uniqueId !== undefined && parsedTarget.uniqueId !== null) {
const target = manager.getTarget(index);
TempMorphTargetIndexContainer[parsedTarget.uniqueId] = target;
}
}
}
}
// Skeletons
if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
const parsedSkeleton = parsedData.skeletons[index];
const skeleton = Skeleton.Parse(parsedSkeleton, scene);
if (parsedSkeleton.uniqueId !== undefined && parsedSkeleton.uniqueId !== null) {
TempSkeletonIndexContainer[parsedSkeleton.uniqueId] = skeleton;
}
container.skeletons.push(skeleton);
skeleton._parentContainer = container;
log += index === 0 ? "\n\tSkeletons:" : "";
log += "\n\t\t" + skeleton.toString(fullDetails);
// Bones - add to TempIndexContainer to later connect animations -> bones
for (let boneIndex = 0; boneIndex < parsedSkeleton.bones.length; boneIndex++) {
const parsedBone = parsedSkeleton.bones[boneIndex];
const bone = skeleton.bones[boneIndex]; // This was instantiated in Skeleton.Parse
TempIndexContainer[parsedBone.uniqueId] = bone;
}
}
}
// Geometries
const geometries = parsedData.geometries;
if (geometries !== undefined && geometries !== null) {
const addedGeometry = new Array<Nullable<Geometry>>();
// VertexData
const vertexData = geometries.vertexData;
if (vertexData !== undefined && vertexData !== null) {
for (index = 0, cache = vertexData.length; index < cache; index++) {
const parsedVertexData = vertexData[index];
addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
}
}
for (const g of addedGeometry) {
if (g) {
container.geometries.push(g);
g._parentContainer = container;
}
}
}
// Transform nodes
if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
const parsedTransformNode = parsedData.transformNodes[index];
const node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
TempIndexContainer[parsedTransformNode.uniqueId] = node;
container.transformNodes.push(node);
node._parentContainer = container;
}
}
// Meshes
if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
const parsedMesh = parsedData.meshes[index];
const mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
TempIndexContainer[parsedMesh.uniqueId] = mesh;
container.meshes.push(mesh);
mesh._parentContainer = container;
if (mesh.hasInstances) {
for (const instance of (mesh as Mesh).instances) {
container.meshes.push(instance);
instance._parentContainer = container;
}
}
// Load partProxies from GaussianSplattingMesh into AssetContainer
if (mesh.getClassName() === "GaussianSplattingMesh") {
const partProxies = (mesh as any)._partProxies as Map<number, AbstractMesh>;
if (partProxies.size) {
for (const partProxy of partProxies.values()) {
container.meshes.push(partProxy);
partProxy._parentContainer = container;
}
}
}
log += index === 0 ? "\n\tMeshes:" : "";
log += "\n\t\t" + mesh.toString(fullDetails);
}
}
// Cameras
if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
const parsedCamera = parsedData.cameras[index];
const camera = Camera.Parse(parsedCamera, scene);
TempIndexContainer[parsedCamera.uniqueId] = camera;
container.cameras.push(camera);
camera._parentContainer = container;
log += index === 0 ? "\n\tCameras:" : "";
log += "\n\t\t" + camera.toString(fullDetails);
}
}
// Postprocesses
if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) {
for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) {
const parsedPostProcess = parsedData.postProcesses[index];
const postProcess = PostProcess.Parse(parsedPostProcess, scene, rootUrl);
if (postProcess) {
container.postProcesses.push(postProcess);
postProcess._parentContainer = container;
log += index === 0 ? "\nPostprocesses:" : "";
log += "\n\t\t" + postProcess.toString();
}
}
}
// Animation Groups
if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null && parsedData.animationGroups.length) {
// Build the nodeMap only for scenes with animationGroups.
let nodeMap: Nullable<Map<Node["id"], Node>> = null;
// Helper to get nodes by id more efficiently, building the nodeMap only on first access.
const getNodeById = (id: Node["id"]) => {
if (!nodeMap) {
nodeMap = new Map<Node["id"], Node>();
// Nodes in scene does not change when parsing animationGroups, so it's safe to build a map.
// This follows the order of scene.getNodeById: mesh, transformNode, light, camera, bone
for (let index = 0; index < scene.meshes.length; index++) {
// This follows the behavior of scene.getXXXById, which picks the first match
if (!nodeMap.has(scene.meshes[index].id)) {
nodeMap.set(scene.meshes[index].id, scene.meshes[index]);
}
}
for (let index = 0; index < scene.transformNodes.length; index++) {
if (!nodeMap.has(scene.transformNodes[index].id)) {
nodeMap.set(scene.transformNodes[index].id, scene.transformNodes[index]);
}
}
for (let index = 0; index < scene.lights.length; index++) {
if (!nodeMap.has(scene.lights[index].id)) {
nodeMap.set(scene.lights[index].id, scene.lights[index]);
}
}
for (let index = 0; index < scene.cameras.length; index++) {
if (!nodeMap.has(scene.cameras[index].id)) {
nodeMap.set(scene.cameras[index].id, scene.cameras[index]);
}
}
for (let skeletonIndex = 0; skeletonIndex < scene.skeletons.length; skeletonIndex++) {
const skeleton = scene.skeletons[skeletonIndex];
for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
if (!nodeMap.has(skeleton.bones[boneIndex].id)) {
nodeMap.set(skeleton.bones[boneIndex].id, skeleton.bones[boneIndex]);
}
}
}
}
return nodeMap.get(id);
};
const targetLookup = (parsedTargetAnimation: any) => {
let target = null;
const isMorphTarget = parsedTargetAnimation.animation.property === "influence";
const uniqueId = parsedTargetAnimation.targetUniqueId;
// Attempt to find animation targets by uniqueId first (tracked in TempXXXIndexContainer).
if (uniqueId !== undefined && uniqueId !== null) {
target = isMorphTarget ? TempMorphTargetIndexContainer[uniqueId] : TempIndexContainer[uniqueId];
}
// Backwards compatibility: If no uniqueId is provided or no match is found,
// fall back to searching by id in the scene.
if (!target) {
const id = parsedTargetAnimation.targetId;
target = isMorphTarget ? scene.getMorphTargetById(id) : getNodeById(id);
}
return target;
};
for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
const parsedAnimationGroup = parsedData.animationGroups[index];
const animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene, targetLookup);
container.animationGroups.push(animationGroup);
animationGroup._parentContainer = container;
log += index === 0 ? "\n\tAnimationGroups:" : "";
log += "\n\t\t" + animationGroup.toString(fullDetails);
}
}
// Sprites
if (parsedData.spriteManagers) {
for (let index = 0, cache = parsedData.spriteManagers.length; index < cache; index++) {
const parsedSpriteManager = parsedData.spriteManagers[index];
const spriteManager = SpriteManager.Parse(parsedSpriteManager, scene, rootUrl);
container.spriteManagers.push(spriteManager);
spriteManager._parentContainer = container;
log += "\n\t\tSpriteManager " + spriteManager.name;
}
}
// Browsing all the graph to connect the dots
for (index = 0, cache = scene.cameras.length; index < cache; index++) {
const camera = scene.cameras[index];
if (camera._waitingParentId !== null) {
camera.parent = FindParent(camera._waitingParentId, camera._waitingParentInstanceIndex, scene);
camera._waitingParentId = null;
camera._waitingParentInstanceIndex = null;
}
}
for (index = 0, cache = scene.lights.length; index < cache; index++) {
const light = scene.lights[index];
if (light && light._waitingParentId !== null) {
light.parent = FindParent(light._waitingParentId, light._waitingParentInstanceIndex, scene);
light._waitingParentId = null;
light._waitingParentInstanceIndex = null;
}
}
// Connect parents & children and parse actions and lods
for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
const transformNode = scene.transformNodes[index];
if (transformNode._waitingParentId !== null) {
transformNode.parent = FindParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene);
transformNode._waitingParentId = null;
transformNode._waitingParentInstanceIndex = null;
}
}
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
const mesh = scene.meshes[index];
if (mesh._waitingParentId !== null) {
mesh.parent = FindParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene);
mesh._waitingParentId = null;
mesh._waitingParentInstanceIndex = null;
}
if (mesh._waitingData.lods) {
LoadDetailLevels(scene, mesh);
}
}
// link multimats with materials
for (const multimat of scene.multiMaterials) {
for (const subMaterial of multimat._waitingSubMaterialsUniqueIds) {
multimat.subMaterials.push(FindMaterial(subMaterial, scene));
}
multimat._waitingSubMaterialsUniqueIds = [];
}
// link meshes with materials
for (const mesh of scene.meshes) {
if (mesh._waitingMaterialId !== null) {
mesh.material = FindMaterial(mesh._waitingMaterialId, scene);
mesh._waitingMaterialId = null;
}
}
// link meshes with morph target managers
for (const mesh of scene.meshes) {
if (mesh._waitingMorphTargetManagerId !== null) {
mesh.morphTargetManager = TempMorphTargetManagerIndexContainer[mesh._waitingMorphTargetManagerId];
mesh._waitingMorphTargetManagerId = null;
}
}
// link meshes with skeletons
for (const mesh of scene.meshes) {
// First try to get it via uniqueId
if (mesh._waitingSkeletonUniqueId !== null) {
mesh.skeleton = TempSkeletonIndexContainer[mesh._waitingSkeletonUniqueId];
}
// If not possible or not found, try to get it from the scene (backwards compatibility)
if (mesh._waitingSkeletonId !== null && !mesh.skeleton) {
mesh.skeleton = scene.getLastSkeletonById(mesh._waitingSkeletonId);
}
mesh._waitingSkeletonId = null;
mesh._waitingSkeletonUniqueId = null;
}
// link bones to transform nodes
for (index = 0, cache = scene.skeletons.length; index < cache; index++) {
const skeleton = scene.skeletons[index];
if (skeleton._hasWaitingData) {
if (skeleton.bones != null) {
for (const bone of skeleton.bones) {
let linkTransformNode: Nullable<Node> = null;
// First try to get it via uniqueId
if (bone._waitingTransformNodeUniqueId !== null) {
linkTransformNode = TempIndexContainer[bone._waitingTransformNodeUniqueId];
}
// If not possible or not found, try to get it from the scene (backwards compatibility)
if (bone._waitingTransformNodeId !== null && !linkTransformNode) {
linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId);
}
if (linkTransformNode) {
bone.linkTransformNode(linkTransformNode as TransformNode);
}
bone._waitingTransformNodeId = null;
bone._waitingTransformNodeUniqueId = null;
}
}
skeleton._hasWaitingData = null;
}
}
// freeze world matrix application
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
const currentMesh = scene.meshes[index];
if (currentMesh._waitingData.freezeWorldMatrix) {
currentMesh.freezeWorldMatrix();
currentMesh._waitingData.freezeWorldMatrix = null;
} else {
currentMesh.computeWorldMatrix(true);
}
}
// Lights exclusions / inclusions
for (index = 0, cache = scene.lights.length; index < cache; index++) {
const light = scene.lights[index];
// Excluded check
if (light._excludedMeshesIds.length > 0) {
for (let excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
const excludedMesh = scene.getMeshById(light._excludedMeshesIds[excludedIndex]);
if (excludedMesh) {
light.excludedMeshes.push(excludedMesh);
}
}
light._excludedMeshesIds = [];
}
// Included check
if (light._includedOnlyMeshesIds.length > 0) {
for (let includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
const includedOnlyMesh = scene.getMeshById(light._includedOnlyMeshesIds[includedOnlyIndex]);
if (includedOnlyMesh) {
light.includedOnlyMeshes.push(includedOnlyMesh);
}
}
light._includedOnlyMeshesIds = [];
}
}
for (const g of scene.geometries) {
g._loadedUniqueId = "";
}
Parse(parsedData, scene, container, rootUrl);
// Actions (scene) Done last as it can access other objects.
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
const mesh = scene.meshes[index];
if (mesh._waitingData.actions) {
ActionManager.Parse(mesh._waitingData.actions, mesh, scene);
mesh._waitingData.actions = null;
}
}
if (parsedData.actions !== undefined && parsedData.actions !== null) {
ActionManager.Parse(parsedData.actions, null, scene);
}
} catch (err) {
const msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
} else {
Logger.Log(msg);
throw err;
}
} finally {
TempIndexContainer = {};
TempMaterialIndexContainer = {};
TempMorphTargetIndexContainer = {};
TempMorphTargetManagerIndexContainer = {};
TempSkeletonIndexContainer = {};
if (!addToScene) {
// Restore observables before removing from scene
if (savedObservables) {
scene.onNewMeshAddedObservable = savedObservables.mesh;
scene.onNewTransformNodeAddedObservable = savedObservables.transformNode;
scene.onNewLightAddedObservable = savedObservables.light;
scene.onNewCameraAddedObservable = savedObservables.camera;
scene.onNewMaterialAddedObservable = savedObservables.material;
scene.onNewMultiMaterialAddedObservable = savedObservables.multiMaterial;
scene.onNewTextureAddedObservable = savedObservables.texture;
scene.onNewSkeletonAddedObservable = savedObservables.skeleton;
scene.onNewGeometryAddedObservable = savedObservables.geometry;
scene.onNewAnimationGroupAddedObservable = savedObservables.animationGroup;
scene.onNewParticleSystemAddedObservable = savedObservables.particleSystem;
}
// Removes entities from scene arrays and moves them to the container
container.removeAllFromScene();
}
if (log !== null && SceneLoaderFlags.loggingLevel !== Constants.SCENELOADER_NO_LOGGING) {
Logger.Log(
logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (SceneLoaderFlags.loggingLevel !== Constants.SCENELOADER_MINIMAL_LOGGING ? log : "")
);
}
}
return container;
};
RegisterSceneLoaderPlugin({
name: "babylon.js",
extensions: ".babylon",
canDirectLoad: (data: string) => {
if (data.indexOf("babylon") !== -1) {
// We consider that the producer string is filled
return true;
}
return false;
},
importMesh: (
meshesNames: any,
scene: Scene,
data: any,
rootUrl: string,
meshes: AbstractMesh[],
particleSystems: IParticleSystem[],
skeletons: Skeleton[],
onError?: (message: string, exception?: any) => void
): boolean => {
// Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
// when SceneLoader.debugLogging = true (default), or exception encountered.
// Everything stored in var log instead of writing separate lines to support only writing in exception,
// and avoid problems with multiple concurrent .babylon loads.
let log = "importMesh has failed JSON parse";
try {
// eslint-disable-next-line no-var
var parsedData = JSON.parse(data);
log = "";
const fullDetails = SceneLoaderFlags.loggingLevel === Constants.SCENELOADER_DETAILED_LOGGING;
if (!meshesNames) {
meshesNames = null;
} else if (!Array.isArray(meshesNames)) {
meshesNames = [meshesNames];
}
const hierarchyIds: number[] = [];
const parsedIdToNodeMap = new Map<number, Node>();
// Transform nodes (the overall idea is to load all of them as this is super fast and then get rid of the ones we don't need)
const loadedTransformNodes = [];
if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
for (let index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
const parsedJSONTransformNode = parsedData.transformNodes[index];
const parsedTransformNode = TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl);
loadedTransformNodes.push(parsedTransformNode);
parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId!, parsedTransformNode);
parsedTransformNode._waitingParsedUniqueId = null;
}
}
if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
const loadedSkeletonsIds = [];
const loadedMaterialsIds: string[] = [];
const loadedMaterialsUniqueIds: string[] = [];
const loadedMorphTargetManagerIds: number[] = [];
for (let index = 0, cache = parsedData.meshes.length; index < cache; index++) {
const parsedMesh = parsedData.meshes[index];
if (meshesNames === null || IsDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
if (meshesNames !== null) {
// Remove found mesh name from list.
delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
}
//Geometry?
if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
//does the file contain geometries?
if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
//find the correct geometry and add it to the scene
let found: boolean = false;
const geoms = ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"];
for (const geometryType of geoms) {
if (!parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) {
continue;
}
const geom = parsedData.geometries[geometryType];
for (const parsedGeometryData of geom) {
if (parsedGeometryData.id === parsedMesh.geometryId) {
switch (geometryType) {
case "vertexData":
Geometry.Parse(parsedGeometryData, scene, rootUrl);
break;
}
found = true;
break;
}
}
if (found) {
break;
}
}
if (found === false) {
Logger.Warn("Geometry not found for mesh " + parsedMesh.id);
}
}
}
// Material ?
if (parsedMesh.materialUniqueId || parsedMesh.materialId) {
// if we have a unique ID, look up and store in loadedMaterialsUniqueIds, else use loadedMaterialsIds
const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds;
let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1;
if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
// Loads a submaterial of a multimaterial
const loadSubMaterial = (subMatId: string, predicate: (parsedMaterial: any) => boolean) => {
materialArray.push(subMatId);
const mat = ParseMaterialByPredicate(predicate, parsedData, scene, rootUrl);
if (mat && mat.material) {
TempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;
log += "\n\tMaterial " + mat.material.toString(fullDetails);
}
};
for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
if (
(parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId) ||
parsedMultiMaterial.id === parsedMesh.materialId
) {
if (parsedMultiMaterial.materialsUniqueIds) {
// if the materials inside the multimat are stored by unique id
for (const subMatId of parsedMultiMaterial.materialsUniqueIds) {
loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId);
}
} else {
// if the mats are stored by id instead
for (const subMatId of parsedMultiMaterial.materials) {
loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId);
}
}
materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id);
const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
TempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;
if (mmat) {
materialFound = true;
log += "\n\tMulti-Material " + mmat.toString(fullDetails);
}
break;
}
}
}
if (materialFound === false) {
materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId);
const mat = ParseMaterialByPredicate(
(parsedMaterial) =>
(parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId) || parsedMaterial.id === parsedMesh.materialId,
parsedData,
scene,
rootUrl
);
if (!mat || !mat.material) {
Logger.Warn("Material not found for mesh " + parsedMesh.id);
} else {
TempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;
log += "\n\tMaterial " + mat.material.toString(fullDetails);
}
}
}
// Skeleton ?
if (
parsedMesh.skeletonId !== null &&
parsedMesh.skeletonId !== undefined &&
parsedData.skeletonId !== -1 &&
parsedData.skeletons !== undefined &&
parsedData.skeletons !== null
) {
const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1;
if (!skeletonAlreadyLoaded) {
for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
const parsedSkeleton = parsedData.skeletons[skeletonIndex];
if (parsedSkeleton.id === parsedMesh.skeletonId) {
const skeleton = Skeleton.Parse(parsedSkeleton, scene);
loadedSkeletonsIds.push(parsedSkeleton.id);
if (parsedSkeleton.uniqueId !== undefined && parsedSkeleton.uniqueId !== null) {
TempSkeletonIndexContainer[parsedSkeleton.uniqueId] = skeleton;
}
skeletons.push(skeleton);
log += "\n\tSkeleton " + skeleton.toString(fullDetails);
}
}
}
}
// Morph target managers ?
if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
const morphTargetManagerAlreadyLoaded = loadedMorphTargetManagerIds.indexOf(parsedMesh.morphTargetManagerId) > -1;
if (!morphTargetManagerAlreadyLoaded) {
for (let morphTargetManagerIndex = 0; morphTargetManagerIndex < parsedData.morphTargetManagers.length; morphTargetManagerIndex++) {
const parsedManager = parsedData.morphTargetManagers[morphTargetManagerIndex];
if (parsedManager.id === parsedMesh.morphTargetManagerId) {
const morphTargetManager = MorphTargetManager.Parse(parsedManager, scene);