@babylonjs/loaders 5.0.0-rc.0 → 5.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/OBJ/index.d.ts +4 -4
  2. package/OBJ/index.js +4 -4
  3. package/OBJ/index.js.map +1 -1
  4. package/OBJ/mtlFileLoader.d.ts +41 -40
  5. package/OBJ/mtlFileLoader.js +232 -231
  6. package/OBJ/mtlFileLoader.js.map +1 -1
  7. package/OBJ/objFileLoader.d.ts +126 -133
  8. package/OBJ/objFileLoader.js +296 -300
  9. package/OBJ/objFileLoader.js.map +1 -1
  10. package/OBJ/objLoadingOptions.d.ts +43 -43
  11. package/OBJ/objLoadingOptions.js +1 -1
  12. package/OBJ/objLoadingOptions.js.map +1 -1
  13. package/OBJ/solidParser.d.ts +154 -153
  14. package/OBJ/solidParser.js +693 -699
  15. package/OBJ/solidParser.js.map +1 -1
  16. package/STL/index.d.ts +1 -1
  17. package/STL/index.js +1 -1
  18. package/STL/index.js.map +1 -1
  19. package/STL/stlFileLoader.d.ts +64 -71
  20. package/STL/stlFileLoader.js +233 -239
  21. package/STL/stlFileLoader.js.map +1 -1
  22. package/glTF/1.0/glTFBinaryExtension.d.ts +13 -13
  23. package/glTF/1.0/glTFBinaryExtension.js +60 -61
  24. package/glTF/1.0/glTFBinaryExtension.js.map +1 -1
  25. package/glTF/1.0/glTFLoader.d.ts +136 -106
  26. package/glTF/1.0/glTFLoader.js +1814 -1696
  27. package/glTF/1.0/glTFLoader.js.map +1 -1
  28. package/glTF/1.0/glTFLoaderInterfaces.d.ts +412 -412
  29. package/glTF/1.0/glTFLoaderInterfaces.js +95 -95
  30. package/glTF/1.0/glTFLoaderInterfaces.js.map +1 -1
  31. package/glTF/1.0/glTFLoaderUtils.d.ts +63 -62
  32. package/glTF/1.0/glTFLoaderUtils.js +250 -232
  33. package/glTF/1.0/glTFLoaderUtils.js.map +1 -1
  34. package/glTF/1.0/glTFMaterialsCommonExtension.d.ts +10 -10
  35. package/glTF/1.0/glTFMaterialsCommonExtension.js +129 -127
  36. package/glTF/1.0/glTFMaterialsCommonExtension.js.map +1 -1
  37. package/glTF/1.0/index.d.ts +5 -5
  38. package/glTF/1.0/index.js +5 -5
  39. package/glTF/1.0/index.js.map +1 -1
  40. package/glTF/2.0/Extensions/EXT_lights_image_based.d.ts +43 -36
  41. package/glTF/2.0/Extensions/EXT_lights_image_based.js +117 -110
  42. package/glTF/2.0/Extensions/EXT_lights_image_based.js.map +1 -1
  43. package/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.d.ts +36 -28
  44. package/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.js +88 -80
  45. package/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.js.map +1 -1
  46. package/glTF/2.0/Extensions/EXT_meshopt_compression.d.ts +34 -27
  47. package/glTF/2.0/Extensions/EXT_meshopt_compression.js +49 -42
  48. package/glTF/2.0/Extensions/EXT_meshopt_compression.js.map +1 -1
  49. package/glTF/2.0/Extensions/EXT_texture_webp.d.ts +29 -21
  50. package/glTF/2.0/Extensions/EXT_texture_webp.js +40 -32
  51. package/glTF/2.0/Extensions/EXT_texture_webp.js.map +1 -1
  52. package/glTF/2.0/Extensions/ExtrasAsMetadata.d.ts +50 -32
  53. package/glTF/2.0/Extensions/ExtrasAsMetadata.js +73 -55
  54. package/glTF/2.0/Extensions/ExtrasAsMetadata.js.map +1 -1
  55. package/glTF/2.0/Extensions/KHR_draco_mesh_compression.d.ts +39 -31
  56. package/glTF/2.0/Extensions/KHR_draco_mesh_compression.js +112 -101
  57. package/glTF/2.0/Extensions/KHR_draco_mesh_compression.js.map +1 -1
  58. package/glTF/2.0/Extensions/KHR_lights_punctual.d.ts +36 -28
  59. package/glTF/2.0/Extensions/KHR_lights_punctual.js +89 -81
  60. package/glTF/2.0/Extensions/KHR_lights_punctual.js.map +1 -1
  61. package/glTF/2.0/Extensions/KHR_materials_clearcoat.d.ts +39 -31
  62. package/glTF/2.0/Extensions/KHR_materials_clearcoat.js +94 -86
  63. package/glTF/2.0/Extensions/KHR_materials_clearcoat.js.map +1 -1
  64. package/glTF/2.0/Extensions/KHR_materials_emissive_strength.d.ts +38 -30
  65. package/glTF/2.0/Extensions/KHR_materials_emissive_strength.js +53 -45
  66. package/glTF/2.0/Extensions/KHR_materials_emissive_strength.js.map +1 -1
  67. package/glTF/2.0/Extensions/KHR_materials_ior.d.ts +42 -34
  68. package/glTF/2.0/Extensions/KHR_materials_ior.js +62 -54
  69. package/glTF/2.0/Extensions/KHR_materials_ior.js.map +1 -1
  70. package/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.d.ts +38 -30
  71. package/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.js +80 -72
  72. package/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.js.map +1 -1
  73. package/glTF/2.0/Extensions/KHR_materials_sheen.d.ts +39 -31
  74. package/glTF/2.0/Extensions/KHR_materials_sheen.js +84 -76
  75. package/glTF/2.0/Extensions/KHR_materials_sheen.js.map +1 -1
  76. package/glTF/2.0/Extensions/KHR_materials_specular.d.ts +38 -30
  77. package/glTF/2.0/Extensions/KHR_materials_specular.js +74 -66
  78. package/glTF/2.0/Extensions/KHR_materials_specular.js.map +1 -1
  79. package/glTF/2.0/Extensions/KHR_materials_translucency.d.ts +39 -31
  80. package/glTF/2.0/Extensions/KHR_materials_translucency.js +83 -76
  81. package/glTF/2.0/Extensions/KHR_materials_translucency.js.map +1 -1
  82. package/glTF/2.0/Extensions/KHR_materials_transmission.d.ts +38 -30
  83. package/glTF/2.0/Extensions/KHR_materials_transmission.js +288 -277
  84. package/glTF/2.0/Extensions/KHR_materials_transmission.js.map +1 -1
  85. package/glTF/2.0/Extensions/KHR_materials_unlit.d.ts +38 -30
  86. package/glTF/2.0/Extensions/KHR_materials_unlit.js +73 -65
  87. package/glTF/2.0/Extensions/KHR_materials_unlit.js.map +1 -1
  88. package/glTF/2.0/Extensions/KHR_materials_variants.d.ts +87 -76
  89. package/glTF/2.0/Extensions/KHR_materials_variants.js +254 -243
  90. package/glTF/2.0/Extensions/KHR_materials_variants.js.map +1 -1
  91. package/glTF/2.0/Extensions/KHR_materials_volume.d.ts +39 -31
  92. package/glTF/2.0/Extensions/KHR_materials_volume.js +85 -78
  93. package/glTF/2.0/Extensions/KHR_materials_volume.js.map +1 -1
  94. package/glTF/2.0/Extensions/KHR_mesh_quantization.d.ts +22 -19
  95. package/glTF/2.0/Extensions/KHR_mesh_quantization.js +23 -21
  96. package/glTF/2.0/Extensions/KHR_mesh_quantization.js.map +1 -1
  97. package/glTF/2.0/Extensions/KHR_texture_basisu.d.ts +29 -21
  98. package/glTF/2.0/Extensions/KHR_texture_basisu.js +40 -32
  99. package/glTF/2.0/Extensions/KHR_texture_basisu.js.map +1 -1
  100. package/glTF/2.0/Extensions/KHR_texture_transform.d.ts +33 -25
  101. package/glTF/2.0/Extensions/KHR_texture_transform.js +61 -53
  102. package/glTF/2.0/Extensions/KHR_texture_transform.js.map +1 -1
  103. package/glTF/2.0/Extensions/KHR_xmp_json_ld.d.ts +32 -29
  104. package/glTF/2.0/Extensions/KHR_xmp_json_ld.js +49 -46
  105. package/glTF/2.0/Extensions/KHR_xmp_json_ld.js.map +1 -1
  106. package/glTF/2.0/Extensions/MSFT_audio_emitter.d.ts +54 -38
  107. package/glTF/2.0/Extensions/MSFT_audio_emitter.js +240 -216
  108. package/glTF/2.0/Extensions/MSFT_audio_emitter.js.map +1 -1
  109. package/glTF/2.0/Extensions/MSFT_lod.d.ts +109 -75
  110. package/glTF/2.0/Extensions/MSFT_lod.js +369 -333
  111. package/glTF/2.0/Extensions/MSFT_lod.js.map +1 -1
  112. package/glTF/2.0/Extensions/MSFT_minecraftMesh.d.ts +14 -14
  113. package/glTF/2.0/Extensions/MSFT_minecraftMesh.js +36 -36
  114. package/glTF/2.0/Extensions/MSFT_minecraftMesh.js.map +1 -1
  115. package/glTF/2.0/Extensions/MSFT_sRGBFactors.d.ts +14 -14
  116. package/glTF/2.0/Extensions/MSFT_sRGBFactors.js +36 -36
  117. package/glTF/2.0/Extensions/MSFT_sRGBFactors.js.map +1 -1
  118. package/glTF/2.0/Extensions/index.d.ts +26 -26
  119. package/glTF/2.0/Extensions/index.js +26 -26
  120. package/glTF/2.0/Extensions/index.js.map +1 -1
  121. package/glTF/2.0/glTFLoader.d.ts +406 -357
  122. package/glTF/2.0/glTFLoader.js +2366 -2266
  123. package/glTF/2.0/glTFLoader.js.map +1 -1
  124. package/glTF/2.0/glTFLoaderExtension.d.ts +152 -152
  125. package/glTF/2.0/glTFLoaderExtension.js +1 -1
  126. package/glTF/2.0/glTFLoaderExtension.js.map +1 -1
  127. package/glTF/2.0/glTFLoaderInterfaces.d.ts +211 -209
  128. package/glTF/2.0/glTFLoaderInterfaces.js +1 -1
  129. package/glTF/2.0/glTFLoaderInterfaces.js.map +1 -1
  130. package/glTF/2.0/index.d.ts +4 -4
  131. package/glTF/2.0/index.js +5 -4
  132. package/glTF/2.0/index.js.map +1 -1
  133. package/glTF/glTFFileLoader.d.ts +433 -373
  134. package/glTF/glTFFileLoader.js +927 -870
  135. package/glTF/glTFFileLoader.js.map +1 -1
  136. package/glTF/glTFValidation.d.ts +29 -29
  137. package/glTF/glTFValidation.js +123 -121
  138. package/glTF/glTFValidation.js.map +1 -1
  139. package/glTF/index.d.ts +5 -5
  140. package/glTF/index.js +6 -5
  141. package/glTF/index.js.map +1 -1
  142. package/index.d.ts +3 -3
  143. package/index.js +4 -3
  144. package/index.js.map +1 -1
  145. package/legacy/legacy-glTF.d.ts +2 -2
  146. package/legacy/legacy-glTF.js +18 -18
  147. package/legacy/legacy-glTF.js.map +1 -1
  148. package/legacy/legacy-glTF1.d.ts +2 -2
  149. package/legacy/legacy-glTF1.js +15 -14
  150. package/legacy/legacy-glTF1.js.map +1 -1
  151. package/legacy/legacy-glTF1FileLoader.d.ts +2 -2
  152. package/legacy/legacy-glTF1FileLoader.js +3 -2
  153. package/legacy/legacy-glTF1FileLoader.js.map +1 -1
  154. package/legacy/legacy-glTF2.d.ts +2 -2
  155. package/legacy/legacy-glTF2.js +33 -32
  156. package/legacy/legacy-glTF2.js.map +1 -1
  157. package/legacy/legacy-glTF2FileLoader.d.ts +2 -2
  158. package/legacy/legacy-glTF2FileLoader.js +3 -2
  159. package/legacy/legacy-glTF2FileLoader.js.map +1 -1
  160. package/legacy/legacy-glTFFileLoader.d.ts +3 -3
  161. package/legacy/legacy-glTFFileLoader.js +4 -3
  162. package/legacy/legacy-glTFFileLoader.js.map +1 -1
  163. package/legacy/legacy-objFileLoader.d.ts +1 -1
  164. package/legacy/legacy-objFileLoader.js +13 -12
  165. package/legacy/legacy-objFileLoader.js.map +1 -1
  166. package/legacy/legacy-stlFileLoader.d.ts +1 -1
  167. package/legacy/legacy-stlFileLoader.js +13 -12
  168. package/legacy/legacy-stlFileLoader.js.map +1 -1
  169. package/legacy/legacy.d.ts +6 -6
  170. package/legacy/legacy.js +8 -6
  171. package/legacy/legacy.js.map +1 -1
  172. package/package.json +23 -198
  173. package/readme.md +2 -2
@@ -1,1697 +1,1815 @@
1
- import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType } from "./glTFLoaderInterfaces.js";
2
- import { Quaternion, Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js";
3
- import { Color3 } from '@babylonjs/core/Maths/math.color.js';
4
- import { Tools } from "@babylonjs/core/Misc/tools.js";
5
- import { Camera } from "@babylonjs/core/Cameras/camera.js";
6
- import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera.js";
7
- import { Animation } from "@babylonjs/core/Animations/animation.js";
8
- import { Bone } from "@babylonjs/core/Bones/bone.js";
9
- import { Skeleton } from "@babylonjs/core/Bones/skeleton.js";
10
- import { Effect } from "@babylonjs/core/Materials/effect.js";
11
- import { Material } from "@babylonjs/core/Materials/material.js";
12
- import { MultiMaterial } from "@babylonjs/core/Materials/multiMaterial.js";
13
- import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js";
14
- import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial.js";
15
- import { Texture } from "@babylonjs/core/Materials/Textures/texture.js";
16
- import { VertexData } from "@babylonjs/core/Meshes/mesh.vertexData.js";
17
- import { VertexBuffer } from "@babylonjs/core/Buffers/buffer.js";
18
- import { Geometry } from "@babylonjs/core/Meshes/geometry.js";
19
- import { SubMesh } from "@babylonjs/core/Meshes/subMesh.js";
20
- import { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js";
21
- import { Mesh } from "@babylonjs/core/Meshes/mesh.js";
22
- import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
23
- import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js";
24
- import { PointLight } from "@babylonjs/core/Lights/pointLight.js";
25
- import { SpotLight } from "@babylonjs/core/Lights/spotLight.js";
26
- import { GLTFUtils } from "./glTFLoaderUtils.js";
27
- import { GLTFFileLoader } from "../glTFFileLoader.js";
28
- import { Constants } from '@babylonjs/core/Engines/constants.js';
29
- /**
30
- * Tokenizer. Used for shaders compatibility
31
- * Automatically map world, view, projection, worldViewProjection, attributes and so on
32
- */
33
- var ETokenType;
34
- (function (ETokenType) {
35
- ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
36
- ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
37
- ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
38
- })(ETokenType || (ETokenType = {}));
39
- var Tokenizer = /** @class */ (function () {
40
- function Tokenizer(toParse) {
41
- this._pos = 0;
42
- this.currentToken = ETokenType.UNKNOWN;
43
- this.currentIdentifier = "";
44
- this.currentString = "";
45
- this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
46
- this._toParse = toParse;
47
- this._maxPos = toParse.length;
48
- }
49
- Tokenizer.prototype.getNextToken = function () {
50
- if (this.isEnd()) {
51
- return ETokenType.END_OF_INPUT;
52
- }
53
- this.currentString = this.read();
54
- this.currentToken = ETokenType.UNKNOWN;
55
- if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
56
- this.currentToken = ETokenType.IDENTIFIER;
57
- this.currentIdentifier = this.currentString;
58
- while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
59
- this.currentIdentifier += this.currentString;
60
- this.forward();
61
- }
62
- }
63
- return this.currentToken;
64
- };
65
- Tokenizer.prototype.peek = function () {
66
- return this._toParse[this._pos];
67
- };
68
- Tokenizer.prototype.read = function () {
69
- return this._toParse[this._pos++];
70
- };
71
- Tokenizer.prototype.forward = function () {
72
- this._pos++;
73
- };
74
- Tokenizer.prototype.isEnd = function () {
75
- return this._pos >= this._maxPos;
76
- };
77
- return Tokenizer;
78
- }());
79
- /**
80
- * Values
81
- */
82
- var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
83
- var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
84
- var glTFAnimationPaths = ["translation", "rotation", "scale"];
85
- var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
86
- /**
87
- * Parse
88
- */
89
- var parseBuffers = function (parsedBuffers, gltfRuntime) {
90
- for (var buf in parsedBuffers) {
91
- var parsedBuffer = parsedBuffers[buf];
92
- gltfRuntime.buffers[buf] = parsedBuffer;
93
- gltfRuntime.buffersCount++;
94
- }
95
- };
96
- var parseShaders = function (parsedShaders, gltfRuntime) {
97
- for (var sha in parsedShaders) {
98
- var parsedShader = parsedShaders[sha];
99
- gltfRuntime.shaders[sha] = parsedShader;
100
- gltfRuntime.shaderscount++;
101
- }
102
- };
103
- var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
104
- for (var object in parsedObjects) {
105
- var parsedObject = parsedObjects[object];
106
- gltfRuntime[runtimeProperty][object] = parsedObject;
107
- }
108
- };
109
- /**
110
- * Utils
111
- */
112
- var normalizeUVs = function (buffer) {
113
- if (!buffer) {
114
- return;
115
- }
116
- for (var i = 0; i < buffer.length / 2; i++) {
117
- buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
118
- }
119
- };
120
- var getAttribute = function (attributeParameter) {
121
- if (attributeParameter.semantic === "NORMAL") {
122
- return "normal";
123
- }
124
- else if (attributeParameter.semantic === "POSITION") {
125
- return "position";
126
- }
127
- else if (attributeParameter.semantic === "JOINT") {
128
- return "matricesIndices";
129
- }
130
- else if (attributeParameter.semantic === "WEIGHT") {
131
- return "matricesWeights";
132
- }
133
- else if (attributeParameter.semantic === "COLOR") {
134
- return "color";
135
- }
136
- else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
137
- var channel = Number(attributeParameter.semantic.split("_")[1]);
138
- return "uv" + (channel === 0 ? "" : channel + 1);
139
- }
140
- return null;
141
- };
142
- /**
143
- * Loads and creates animations
144
- */
145
- var loadAnimations = function (gltfRuntime) {
146
- for (var anim in gltfRuntime.animations) {
147
- var animation = gltfRuntime.animations[anim];
148
- if (!animation.channels || !animation.samplers) {
149
- continue;
150
- }
151
- var lastAnimation = null;
152
- for (var i = 0; i < animation.channels.length; i++) {
153
- // Get parameters and load buffers
154
- var channel = animation.channels[i];
155
- var sampler = animation.samplers[channel.sampler];
156
- if (!sampler) {
157
- continue;
158
- }
159
- var inputData = null;
160
- var outputData = null;
161
- if (animation.parameters) {
162
- inputData = animation.parameters[sampler.input];
163
- outputData = animation.parameters[sampler.output];
164
- }
165
- else {
166
- inputData = sampler.input;
167
- outputData = sampler.output;
168
- }
169
- var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
170
- var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
171
- var targetId = channel.target.id;
172
- var targetNode = gltfRuntime.scene.getNodeById(targetId);
173
- if (targetNode === null) {
174
- targetNode = gltfRuntime.scene.getNodeByName(targetId);
175
- }
176
- if (targetNode === null) {
177
- Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to");
178
- continue;
179
- }
180
- var isBone = targetNode instanceof Bone;
181
- // Get target path (position, rotation or scaling)
182
- var targetPath = channel.target.path;
183
- var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
184
- if (targetPathIndex !== -1) {
185
- targetPath = babylonAnimationPaths[targetPathIndex];
186
- }
187
- // Determine animation type
188
- var animationType = Animation.ANIMATIONTYPE_MATRIX;
189
- if (!isBone) {
190
- if (targetPath === "rotationQuaternion") {
191
- animationType = Animation.ANIMATIONTYPE_QUATERNION;
192
- targetNode.rotationQuaternion = new Quaternion();
193
- }
194
- else {
195
- animationType = Animation.ANIMATIONTYPE_VECTOR3;
196
- }
197
- }
198
- // Create animation and key frames
199
- var babylonAnimation = null;
200
- var keys = [];
201
- var arrayOffset = 0;
202
- var modifyKey = false;
203
- if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
204
- babylonAnimation = lastAnimation;
205
- modifyKey = true;
206
- }
207
- if (!modifyKey) {
208
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
209
- babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
210
- gltfRuntime.scene._blockEntityCollection = false;
211
- }
212
- // For each frame
213
- for (var j = 0; j < bufferInput.length; j++) {
214
- var value = null;
215
- if (targetPath === "rotationQuaternion") { // VEC4
216
- value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
217
- arrayOffset += 4;
218
- }
219
- else { // Position and scaling are VEC3
220
- value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
221
- arrayOffset += 3;
222
- }
223
- if (isBone) {
224
- var bone = targetNode;
225
- var translation = Vector3.Zero();
226
- var rotationQuaternion = new Quaternion();
227
- var scaling = Vector3.Zero();
228
- // Warning on decompose
229
- var mat = bone.getBaseMatrix();
230
- if (modifyKey && lastAnimation) {
231
- mat = lastAnimation.getKeys()[j].value;
232
- }
233
- mat.decompose(scaling, rotationQuaternion, translation);
234
- if (targetPath === "position") {
235
- translation = value;
236
- }
237
- else if (targetPath === "rotationQuaternion") {
238
- rotationQuaternion = value;
239
- }
240
- else {
241
- scaling = value;
242
- }
243
- value = Matrix.Compose(scaling, rotationQuaternion, translation);
244
- }
245
- if (!modifyKey) {
246
- keys.push({
247
- frame: bufferInput[j],
248
- value: value
249
- });
250
- }
251
- else if (lastAnimation) {
252
- lastAnimation.getKeys()[j].value = value;
253
- }
254
- }
255
- // Finish
256
- if (!modifyKey && babylonAnimation) {
257
- babylonAnimation.setKeys(keys);
258
- targetNode.animations.push(babylonAnimation);
259
- }
260
- lastAnimation = babylonAnimation;
261
- gltfRuntime.scene.stopAnimation(targetNode);
262
- gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
263
- }
264
- }
265
- };
266
- /**
267
- * Returns the bones transformation matrix
268
- */
269
- var configureBoneTransformation = function (node) {
270
- var mat = null;
271
- if (node.translation || node.rotation || node.scale) {
272
- var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
273
- var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
274
- var position = Vector3.FromArray(node.translation || [0, 0, 0]);
275
- mat = Matrix.Compose(scale, rotation, position);
276
- }
277
- else {
278
- mat = Matrix.FromArray(node.matrix);
279
- }
280
- return mat;
281
- };
282
- /**
283
- * Returns the parent bone
284
- */
285
- var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
286
- // Try to find
287
- for (var i = 0; i < newSkeleton.bones.length; i++) {
288
- if (newSkeleton.bones[i].name === jointName) {
289
- return newSkeleton.bones[i];
290
- }
291
- }
292
- // Not found, search in gltf nodes
293
- var nodes = gltfRuntime.nodes;
294
- for (var nde in nodes) {
295
- var node = nodes[nde];
296
- if (!node.jointName) {
297
- continue;
298
- }
299
- var children = node.children;
300
- for (var i = 0; i < children.length; i++) {
301
- var child = gltfRuntime.nodes[children[i]];
302
- if (!child.jointName) {
303
- continue;
304
- }
305
- if (child.jointName === jointName) {
306
- var mat = configureBoneTransformation(node);
307
- var bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
308
- bone.id = nde;
309
- return bone;
310
- }
311
- }
312
- }
313
- return null;
314
- };
315
- /**
316
- * Returns the appropriate root node
317
- */
318
- var getNodeToRoot = function (nodesToRoot, id) {
319
- for (var i = 0; i < nodesToRoot.length; i++) {
320
- var nodeToRoot = nodesToRoot[i];
321
- for (var j = 0; j < nodeToRoot.node.children.length; j++) {
322
- var child = nodeToRoot.node.children[j];
323
- if (child === id) {
324
- return nodeToRoot.bone;
325
- }
326
- }
327
- }
328
- return null;
329
- };
330
- /**
331
- * Returns the node with the joint name
332
- */
333
- var getJointNode = function (gltfRuntime, jointName) {
334
- var nodes = gltfRuntime.nodes;
335
- var node = nodes[jointName];
336
- if (node) {
337
- return {
338
- node: node,
339
- id: jointName
340
- };
341
- }
342
- for (var nde in nodes) {
343
- node = nodes[nde];
344
- if (node.jointName === jointName) {
345
- return {
346
- node: node,
347
- id: nde
348
- };
349
- }
350
- }
351
- return null;
352
- };
353
- /**
354
- * Checks if a nodes is in joints
355
- */
356
- var nodeIsInJoints = function (skins, id) {
357
- for (var i = 0; i < skins.jointNames.length; i++) {
358
- if (skins.jointNames[i] === id) {
359
- return true;
360
- }
361
- }
362
- return false;
363
- };
364
- /**
365
- * Fills the nodes to root for bones and builds hierarchy
366
- */
367
- var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
368
- // Creates nodes for root
369
- for (var nde in gltfRuntime.nodes) {
370
- var node = gltfRuntime.nodes[nde];
371
- var id = nde;
372
- if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
373
- continue;
374
- }
375
- // Create node to root bone
376
- var mat = configureBoneTransformation(node);
377
- var bone = new Bone(node.name || "", newSkeleton, null, mat);
378
- bone.id = id;
379
- nodesToRoot.push({ bone: bone, node: node, id: id });
380
- }
381
- // Parenting
382
- for (var i = 0; i < nodesToRoot.length; i++) {
383
- var nodeToRoot = nodesToRoot[i];
384
- var children = nodeToRoot.node.children;
385
- for (var j = 0; j < children.length; j++) {
386
- var child = null;
387
- for (var k = 0; k < nodesToRoot.length; k++) {
388
- if (nodesToRoot[k].id === children[j]) {
389
- child = nodesToRoot[k];
390
- break;
391
- }
392
- }
393
- if (child) {
394
- child.bone._parent = nodeToRoot.bone;
395
- nodeToRoot.bone.children.push(child.bone);
396
- }
397
- }
398
- }
399
- };
400
- /**
401
- * Imports a skeleton
402
- */
403
- var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
404
- if (!newSkeleton) {
405
- newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
406
- }
407
- if (!skins.babylonSkeleton) {
408
- return newSkeleton;
409
- }
410
- // Find the root bones
411
- var nodesToRoot = [];
412
- var nodesToRootToAdd = [];
413
- getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
414
- newSkeleton.bones = [];
415
- // Joints
416
- for (var i = 0; i < skins.jointNames.length; i++) {
417
- var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
418
- if (!jointNode) {
419
- continue;
420
- }
421
- var node = jointNode.node;
422
- if (!node) {
423
- Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
424
- continue;
425
- }
426
- var id = jointNode.id;
427
- // Optimize, if the bone already exists...
428
- var existingBone = gltfRuntime.scene.getBoneById(id);
429
- if (existingBone) {
430
- newSkeleton.bones.push(existingBone);
431
- continue;
432
- }
433
- // Search for parent bone
434
- var foundBone = false;
435
- var parentBone = null;
436
- for (var j = 0; j < i; j++) {
437
- var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
438
- if (!jointNode_1) {
439
- continue;
440
- }
441
- var joint = jointNode_1.node;
442
- if (!joint) {
443
- Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
444
- continue;
445
- }
446
- var children = joint.children;
447
- if (!children) {
448
- continue;
449
- }
450
- foundBone = false;
451
- for (var k = 0; k < children.length; k++) {
452
- if (children[k] === id) {
453
- parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
454
- foundBone = true;
455
- break;
456
- }
457
- }
458
- if (foundBone) {
459
- break;
460
- }
461
- }
462
- // Create bone
463
- var mat = configureBoneTransformation(node);
464
- if (!parentBone && nodesToRoot.length > 0) {
465
- parentBone = getNodeToRoot(nodesToRoot, id);
466
- if (parentBone) {
467
- if (nodesToRootToAdd.indexOf(parentBone) === -1) {
468
- nodesToRootToAdd.push(parentBone);
469
- }
470
- }
471
- }
472
- var bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
473
- bone.id = id;
474
- }
475
- // Polish
476
- var bones = newSkeleton.bones;
477
- newSkeleton.bones = [];
478
- for (var i = 0; i < skins.jointNames.length; i++) {
479
- var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
480
- if (!jointNode) {
481
- continue;
482
- }
483
- for (var j = 0; j < bones.length; j++) {
484
- if (bones[j].id === jointNode.id) {
485
- newSkeleton.bones.push(bones[j]);
486
- break;
487
- }
488
- }
489
- }
490
- newSkeleton.prepare();
491
- // Finish
492
- for (var i = 0; i < nodesToRootToAdd.length; i++) {
493
- newSkeleton.bones.push(nodesToRootToAdd[i]);
494
- }
495
- return newSkeleton;
496
- };
497
- /**
498
- * Imports a mesh and its geometries
499
- */
500
- var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
501
- if (!newMesh) {
502
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
503
- newMesh = new Mesh(node.name || "", gltfRuntime.scene);
504
- newMesh._parentContainer = gltfRuntime.assetContainer;
505
- gltfRuntime.scene._blockEntityCollection = false;
506
- newMesh.id = id;
507
- }
508
- if (!node.babylonNode) {
509
- return newMesh;
510
- }
511
- var subMaterials = [];
512
- var vertexData = null;
513
- var verticesStarts = new Array();
514
- var verticesCounts = new Array();
515
- var indexStarts = new Array();
516
- var indexCounts = new Array();
517
- for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
518
- var meshId = meshes[meshIndex];
519
- var mesh = gltfRuntime.meshes[meshId];
520
- if (!mesh) {
521
- continue;
522
- }
523
- // Positions, normals and UVs
524
- for (var i = 0; i < mesh.primitives.length; i++) {
525
- // Temporary vertex data
526
- var tempVertexData = new VertexData();
527
- var primitive = mesh.primitives[i];
528
- if (primitive.mode !== 4) {
529
- // continue;
530
- }
531
- var attributes = primitive.attributes;
532
- var accessor = null;
533
- var buffer = null;
534
- // Set positions, normal and uvs
535
- for (var semantic in attributes) {
536
- // Link accessor and buffer view
537
- accessor = gltfRuntime.accessors[attributes[semantic]];
538
- buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
539
- if (semantic === "NORMAL") {
540
- tempVertexData.normals = new Float32Array(buffer.length);
541
- tempVertexData.normals.set(buffer);
542
- }
543
- else if (semantic === "POSITION") {
544
- if (GLTFFileLoader.HomogeneousCoordinates) {
545
- tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
546
- for (var j = 0; j < buffer.length; j += 4) {
547
- tempVertexData.positions[j] = buffer[j];
548
- tempVertexData.positions[j + 1] = buffer[j + 1];
549
- tempVertexData.positions[j + 2] = buffer[j + 2];
550
- }
551
- }
552
- else {
553
- tempVertexData.positions = new Float32Array(buffer.length);
554
- tempVertexData.positions.set(buffer);
555
- }
556
- verticesCounts.push(tempVertexData.positions.length);
557
- }
558
- else if (semantic.indexOf("TEXCOORD_") !== -1) {
559
- var channel = Number(semantic.split("_")[1]);
560
- var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
561
- var uvs = new Float32Array(buffer.length);
562
- uvs.set(buffer);
563
- normalizeUVs(uvs);
564
- tempVertexData.set(uvs, uvKind);
565
- }
566
- else if (semantic === "JOINT") {
567
- tempVertexData.matricesIndices = new Float32Array(buffer.length);
568
- tempVertexData.matricesIndices.set(buffer);
569
- }
570
- else if (semantic === "WEIGHT") {
571
- tempVertexData.matricesWeights = new Float32Array(buffer.length);
572
- tempVertexData.matricesWeights.set(buffer);
573
- }
574
- else if (semantic === "COLOR") {
575
- tempVertexData.colors = new Float32Array(buffer.length);
576
- tempVertexData.colors.set(buffer);
577
- }
578
- }
579
- // Indices
580
- accessor = gltfRuntime.accessors[primitive.indices];
581
- if (accessor) {
582
- buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
583
- tempVertexData.indices = new Int32Array(buffer.length);
584
- tempVertexData.indices.set(buffer);
585
- indexCounts.push(tempVertexData.indices.length);
586
- }
587
- else {
588
- // Set indices on the fly
589
- var indices = [];
590
- for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
591
- indices.push(j);
592
- }
593
- tempVertexData.indices = new Int32Array(indices);
594
- indexCounts.push(tempVertexData.indices.length);
595
- }
596
- if (!vertexData) {
597
- vertexData = tempVertexData;
598
- }
599
- else {
600
- vertexData.merge(tempVertexData);
601
- }
602
- // Sub material
603
- var material_1 = gltfRuntime.scene.getMaterialById(primitive.material);
604
- subMaterials.push(material_1 === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
605
- // Update vertices start and index start
606
- verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
607
- indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
608
- }
609
- }
610
- var material;
611
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
612
- if (subMaterials.length > 1) {
613
- material = new MultiMaterial("multimat" + id, gltfRuntime.scene);
614
- material.subMaterials = subMaterials;
615
- }
616
- else {
617
- material = new StandardMaterial("multimat" + id, gltfRuntime.scene);
618
- }
619
- if (subMaterials.length === 1) {
620
- material = subMaterials[0];
621
- }
622
- material._parentContainer = gltfRuntime.assetContainer;
623
- if (!newMesh.material) {
624
- newMesh.material = material;
625
- }
626
- // Apply geometry
627
- new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
628
- newMesh.computeWorldMatrix(true);
629
- gltfRuntime.scene._blockEntityCollection = false;
630
- // Apply submeshes
631
- newMesh.subMeshes = [];
632
- var index = 0;
633
- for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
634
- var meshId = meshes[meshIndex];
635
- var mesh = gltfRuntime.meshes[meshId];
636
- if (!mesh) {
637
- continue;
638
- }
639
- for (var i = 0; i < mesh.primitives.length; i++) {
640
- if (mesh.primitives[i].mode !== 4) {
641
- //continue;
642
- }
643
- SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
644
- index++;
645
- }
646
- }
647
- // Finish
648
- return newMesh;
649
- };
650
- /**
651
- * Configure node transformation from position, rotation and scaling
652
- */
653
- var configureNode = function (newNode, position, rotation, scaling) {
654
- if (newNode.position) {
655
- newNode.position = position;
656
- }
657
- if (newNode.rotationQuaternion || newNode.rotation) {
658
- newNode.rotationQuaternion = rotation;
659
- }
660
- if (newNode.scaling) {
661
- newNode.scaling = scaling;
662
- }
663
- };
664
- /**
665
- * Configures node from transformation matrix
666
- */
667
- var configureNodeFromMatrix = function (newNode, node, parent) {
668
- if (node.matrix) {
669
- var position = new Vector3(0, 0, 0);
670
- var rotation = new Quaternion();
671
- var scaling = new Vector3(0, 0, 0);
672
- var mat = Matrix.FromArray(node.matrix);
673
- mat.decompose(scaling, rotation, position);
674
- configureNode(newNode, position, rotation, scaling);
675
- }
676
- else if (node.translation && node.rotation && node.scale) {
677
- configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
678
- }
679
- newNode.computeWorldMatrix(true);
680
- };
681
- /**
682
- * Imports a node
683
- */
684
- var importNode = function (gltfRuntime, node, id, parent) {
685
- var lastNode = null;
686
- if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
687
- if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
688
- return null;
689
- }
690
- }
691
- // Meshes
692
- if (node.skin) {
693
- if (node.meshes) {
694
- var skin = gltfRuntime.skins[node.skin];
695
- var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
696
- newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);
697
- if (newMesh.skeleton === null) {
698
- newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
699
- if (!skin.babylonSkeleton) {
700
- skin.babylonSkeleton = newMesh.skeleton;
701
- }
702
- }
703
- lastNode = newMesh;
704
- }
705
- }
706
- else if (node.meshes) {
707
- /**
708
- * Improve meshes property
709
- */
710
- var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
711
- lastNode = newMesh;
712
- }
713
- // Lights
714
- else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
715
- var light = gltfRuntime.lights[node.light];
716
- if (light) {
717
- if (light.type === "ambient") {
718
- var ambienLight = light[light.type];
719
- var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
720
- hemiLight.name = node.name || "";
721
- if (ambienLight.color) {
722
- hemiLight.diffuse = Color3.FromArray(ambienLight.color);
723
- }
724
- lastNode = hemiLight;
725
- }
726
- else if (light.type === "directional") {
727
- var directionalLight = light[light.type];
728
- var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
729
- dirLight.name = node.name || "";
730
- if (directionalLight.color) {
731
- dirLight.diffuse = Color3.FromArray(directionalLight.color);
732
- }
733
- lastNode = dirLight;
734
- }
735
- else if (light.type === "point") {
736
- var pointLight = light[light.type];
737
- var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
738
- ptLight.name = node.name || "";
739
- if (pointLight.color) {
740
- ptLight.diffuse = Color3.FromArray(pointLight.color);
741
- }
742
- lastNode = ptLight;
743
- }
744
- else if (light.type === "spot") {
745
- var spotLight = light[light.type];
746
- var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
747
- spLight.name = node.name || "";
748
- if (spotLight.color) {
749
- spLight.diffuse = Color3.FromArray(spotLight.color);
750
- }
751
- if (spotLight.fallOfAngle) {
752
- spLight.angle = spotLight.fallOfAngle;
753
- }
754
- if (spotLight.fallOffExponent) {
755
- spLight.exponent = spotLight.fallOffExponent;
756
- }
757
- lastNode = spLight;
758
- }
759
- }
760
- }
761
- // Cameras
762
- else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
763
- var camera = gltfRuntime.cameras[node.camera];
764
- if (camera) {
765
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
766
- if (camera.type === "orthographic") {
767
- var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
768
- orthoCamera.name = node.name || "";
769
- orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
770
- orthoCamera.attachControl();
771
- lastNode = orthoCamera;
772
- orthoCamera._parentContainer = gltfRuntime.assetContainer;
773
- }
774
- else if (camera.type === "perspective") {
775
- var perspectiveCamera = camera[camera.type];
776
- var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
777
- persCamera.name = node.name || "";
778
- persCamera.attachControl();
779
- if (!perspectiveCamera.aspectRatio) {
780
- perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
781
- }
782
- if (perspectiveCamera.znear && perspectiveCamera.zfar) {
783
- persCamera.maxZ = perspectiveCamera.zfar;
784
- persCamera.minZ = perspectiveCamera.znear;
785
- }
786
- lastNode = persCamera;
787
- persCamera._parentContainer = gltfRuntime.assetContainer;
788
- }
789
- gltfRuntime.scene._blockEntityCollection = false;
790
- }
791
- }
792
- // Empty node
793
- if (!node.jointName) {
794
- if (node.babylonNode) {
795
- return node.babylonNode;
796
- }
797
- else if (lastNode === null) {
798
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
799
- var dummy = new Mesh(node.name || "", gltfRuntime.scene);
800
- dummy._parentContainer = gltfRuntime.assetContainer;
801
- gltfRuntime.scene._blockEntityCollection = false;
802
- node.babylonNode = dummy;
803
- lastNode = dummy;
804
- }
805
- }
806
- if (lastNode !== null) {
807
- if (node.matrix && lastNode instanceof Mesh) {
808
- configureNodeFromMatrix(lastNode, node, parent);
809
- }
810
- else {
811
- var translation = node.translation || [0, 0, 0];
812
- var rotation = node.rotation || [0, 0, 0, 1];
813
- var scale = node.scale || [1, 1, 1];
814
- configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
815
- }
816
- lastNode.updateCache(true);
817
- node.babylonNode = lastNode;
818
- }
819
- return lastNode;
820
- };
821
- /**
822
- * Traverses nodes and creates them
823
- */
824
- var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
825
- if (meshIncluded === void 0) { meshIncluded = false; }
826
- var node = gltfRuntime.nodes[id];
827
- var newNode = null;
828
- if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
829
- if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
830
- meshIncluded = true;
831
- }
832
- else {
833
- meshIncluded = false;
834
- }
835
- }
836
- else {
837
- meshIncluded = true;
838
- }
839
- if (!node.jointName && meshIncluded) {
840
- newNode = importNode(gltfRuntime, node, id, parent);
841
- if (newNode !== null) {
842
- newNode.id = id;
843
- newNode.parent = parent;
844
- }
845
- }
846
- if (node.children) {
847
- for (var i = 0; i < node.children.length; i++) {
848
- traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
849
- }
850
- }
851
- };
852
- /**
853
- * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
854
- */
855
- var postLoad = function (gltfRuntime) {
856
- // Nodes
857
- var currentScene = gltfRuntime.currentScene;
858
- if (currentScene) {
859
- for (var i = 0; i < currentScene.nodes.length; i++) {
860
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
861
- }
862
- }
863
- else {
864
- for (var thing in gltfRuntime.scenes) {
865
- currentScene = gltfRuntime.scenes[thing];
866
- for (var i = 0; i < currentScene.nodes.length; i++) {
867
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
868
- }
869
- }
870
- }
871
- // Set animations
872
- loadAnimations(gltfRuntime);
873
- for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
874
- var skeleton = gltfRuntime.scene.skeletons[i];
875
- gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
876
- }
877
- };
878
- /**
879
- * onBind shaderrs callback to set uniforms and matrices
880
- */
881
- var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
882
- var materialValues = material.values || technique.parameters;
883
- for (var unif in unTreatedUniforms) {
884
- var uniform = unTreatedUniforms[unif];
885
- var type = uniform.type;
886
- if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
887
- if (uniform.semantic && !uniform.source && !uniform.node) {
888
- GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
889
- }
890
- else if (uniform.semantic && (uniform.source || uniform.node)) {
891
- var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
892
- if (source === null) {
893
- source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || "");
894
- }
895
- if (source === null) {
896
- continue;
897
- }
898
- GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
899
- }
900
- }
901
- else {
902
- var value = materialValues[technique.uniforms[unif]];
903
- if (!value) {
904
- continue;
905
- }
906
- if (type === EParameterType.SAMPLER_2D) {
907
- var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
908
- if (texture === null || texture === undefined) {
909
- continue;
910
- }
911
- shaderMaterial.getEffect().setTexture(unif, texture);
912
- }
913
- else {
914
- GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
915
- }
916
- }
917
- }
918
- onSuccess(shaderMaterial);
919
- };
920
- /**
921
- * Prepare uniforms to send the only one time
922
- * Loads the appropriate textures
923
- */
924
- var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
925
- var materialValues = material.values || technique.parameters;
926
- var techniqueUniforms = technique.uniforms;
927
- /**
928
- * Prepare values here (not matrices)
929
- */
930
- for (var unif in unTreatedUniforms) {
931
- var uniform = unTreatedUniforms[unif];
932
- var type = uniform.type;
933
- var value = materialValues[techniqueUniforms[unif]];
934
- if (value === undefined) {
935
- // In case the value is the same for all materials
936
- value = uniform.value;
937
- }
938
- if (!value) {
939
- continue;
940
- }
941
- var onLoadTexture = function (uniformName) {
942
- return function (texture) {
943
- if (uniform.value && uniformName) {
944
- // Static uniform
945
- shaderMaterial.setTexture(uniformName, texture);
946
- delete unTreatedUniforms[uniformName];
947
- }
948
- };
949
- };
950
- // Texture (sampler2D)
951
- if (type === EParameterType.SAMPLER_2D) {
952
- GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
953
- }
954
- // Others
955
- else {
956
- if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
957
- // Static uniform
958
- delete unTreatedUniforms[unif];
959
- }
960
- }
961
- }
962
- };
963
- /**
964
- * Shader compilation failed
965
- */
966
- var onShaderCompileError = function (program, shaderMaterial, onError) {
967
- return function (effect, error) {
968
- shaderMaterial.dispose(true);
969
- onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
970
- };
971
- };
972
- /**
973
- * Shader compilation success
974
- */
975
- var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
976
- return function (_) {
977
- prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
978
- shaderMaterial.onBind = function (mesh) {
979
- onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
980
- };
981
- };
982
- };
983
- /**
984
- * Returns the appropriate uniform if already handled by babylon
985
- */
986
- var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
987
- for (var unif in technique.uniforms) {
988
- var uniform = technique.uniforms[unif];
989
- var uniformParameter = technique.parameters[uniform];
990
- if (tokenizer.currentIdentifier === unif) {
991
- if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
992
- var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
993
- if (transformIndex !== -1) {
994
- delete unTreatedUniforms[unif];
995
- return babylonTransforms[transformIndex];
996
- }
997
- }
998
- }
999
- }
1000
- return tokenizer.currentIdentifier;
1001
- };
1002
- /**
1003
- * All shaders loaded. Create materials one by one
1004
- */
1005
- var importMaterials = function (gltfRuntime) {
1006
- // Create materials
1007
- for (var mat in gltfRuntime.materials) {
1008
- GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
1009
- }
1010
- };
1011
- /**
1012
- * Implementation of the base glTF spec
1013
- * @hidden
1014
- */
1015
- var GLTFLoaderBase = /** @class */ (function () {
1016
- function GLTFLoaderBase() {
1017
- }
1018
- GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
1019
- var gltfRuntime = {
1020
- extensions: {},
1021
- accessors: {},
1022
- buffers: {},
1023
- bufferViews: {},
1024
- meshes: {},
1025
- lights: {},
1026
- cameras: {},
1027
- nodes: {},
1028
- images: {},
1029
- textures: {},
1030
- shaders: {},
1031
- programs: {},
1032
- samplers: {},
1033
- techniques: {},
1034
- materials: {},
1035
- animations: {},
1036
- skins: {},
1037
- extensionsUsed: [],
1038
- scenes: {},
1039
- buffersCount: 0,
1040
- shaderscount: 0,
1041
- scene: scene,
1042
- rootUrl: rootUrl,
1043
- loadedBufferCount: 0,
1044
- loadedBufferViews: {},
1045
- loadedShaderCount: 0,
1046
- importOnlyMeshes: false,
1047
- dummyNodes: [],
1048
- assetContainer: null
1049
- };
1050
- // Parse
1051
- if (parsedData.extensions) {
1052
- parseObject(parsedData.extensions, "extensions", gltfRuntime);
1053
- }
1054
- if (parsedData.extensionsUsed) {
1055
- parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
1056
- }
1057
- if (parsedData.buffers) {
1058
- parseBuffers(parsedData.buffers, gltfRuntime);
1059
- }
1060
- if (parsedData.bufferViews) {
1061
- parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
1062
- }
1063
- if (parsedData.accessors) {
1064
- parseObject(parsedData.accessors, "accessors", gltfRuntime);
1065
- }
1066
- if (parsedData.meshes) {
1067
- parseObject(parsedData.meshes, "meshes", gltfRuntime);
1068
- }
1069
- if (parsedData.lights) {
1070
- parseObject(parsedData.lights, "lights", gltfRuntime);
1071
- }
1072
- if (parsedData.cameras) {
1073
- parseObject(parsedData.cameras, "cameras", gltfRuntime);
1074
- }
1075
- if (parsedData.nodes) {
1076
- parseObject(parsedData.nodes, "nodes", gltfRuntime);
1077
- }
1078
- if (parsedData.images) {
1079
- parseObject(parsedData.images, "images", gltfRuntime);
1080
- }
1081
- if (parsedData.textures) {
1082
- parseObject(parsedData.textures, "textures", gltfRuntime);
1083
- }
1084
- if (parsedData.shaders) {
1085
- parseShaders(parsedData.shaders, gltfRuntime);
1086
- }
1087
- if (parsedData.programs) {
1088
- parseObject(parsedData.programs, "programs", gltfRuntime);
1089
- }
1090
- if (parsedData.samplers) {
1091
- parseObject(parsedData.samplers, "samplers", gltfRuntime);
1092
- }
1093
- if (parsedData.techniques) {
1094
- parseObject(parsedData.techniques, "techniques", gltfRuntime);
1095
- }
1096
- if (parsedData.materials) {
1097
- parseObject(parsedData.materials, "materials", gltfRuntime);
1098
- }
1099
- if (parsedData.animations) {
1100
- parseObject(parsedData.animations, "animations", gltfRuntime);
1101
- }
1102
- if (parsedData.skins) {
1103
- parseObject(parsedData.skins, "skins", gltfRuntime);
1104
- }
1105
- if (parsedData.scenes) {
1106
- gltfRuntime.scenes = parsedData.scenes;
1107
- }
1108
- if (parsedData.scene && parsedData.scenes) {
1109
- gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
1110
- }
1111
- return gltfRuntime;
1112
- };
1113
- GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1114
- var buffer = gltfRuntime.buffers[id];
1115
- if (Tools.IsBase64(buffer.uri)) {
1116
- setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))); });
1117
- }
1118
- else {
1119
- Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
1120
- if (request) {
1121
- onError(request.status + " " + request.statusText);
1122
- }
1123
- });
1124
- }
1125
- };
1126
- GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1127
- var texture = gltfRuntime.textures[id];
1128
- if (!texture || !texture.source) {
1129
- onError("");
1130
- return;
1131
- }
1132
- if (texture.babylonTexture) {
1133
- onSuccess(null);
1134
- return;
1135
- }
1136
- var source = gltfRuntime.images[texture.source];
1137
- if (Tools.IsBase64(source.uri)) {
1138
- setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))); });
1139
- }
1140
- else {
1141
- Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
1142
- if (request) {
1143
- onError(request.status + " " + request.statusText);
1144
- }
1145
- });
1146
- }
1147
- };
1148
- GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1149
- var texture = gltfRuntime.textures[id];
1150
- if (texture.babylonTexture) {
1151
- onSuccess(texture.babylonTexture);
1152
- return;
1153
- }
1154
- var sampler = gltfRuntime.samplers[texture.sampler];
1155
- var createMipMaps = (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
1156
- (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
1157
- (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
1158
- (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
1159
- var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
1160
- var blob = buffer == null ? new Blob() : new Blob([buffer]);
1161
- var blobURL = URL.createObjectURL(blob);
1162
- var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
1163
- var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
1164
- if (sampler.wrapS !== undefined) {
1165
- newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
1166
- }
1167
- if (sampler.wrapT !== undefined) {
1168
- newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
1169
- }
1170
- newTexture.name = id;
1171
- texture.babylonTexture = newTexture;
1172
- onSuccess(newTexture);
1173
- };
1174
- GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1175
- var shader = gltfRuntime.shaders[id];
1176
- if (Tools.IsBase64(shader.uri)) {
1177
- var shaderString = atob(shader.uri.split(",")[1]);
1178
- if (onSuccess) {
1179
- onSuccess(shaderString);
1180
- }
1181
- }
1182
- else {
1183
- Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
1184
- if (request && onError) {
1185
- onError(request.status + " " + request.statusText);
1186
- }
1187
- });
1188
- }
1189
- };
1190
- GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1191
- var material = gltfRuntime.materials[id];
1192
- if (!material.technique) {
1193
- if (onError) {
1194
- onError("No technique found.");
1195
- }
1196
- return;
1197
- }
1198
- var technique = gltfRuntime.techniques[material.technique];
1199
- if (!technique) {
1200
- gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
1201
- var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
1202
- defaultMaterial._parentContainer = gltfRuntime.assetContainer;
1203
- gltfRuntime.scene._blockEntityCollection = false;
1204
- defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
1205
- defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1206
- onSuccess(defaultMaterial);
1207
- return;
1208
- }
1209
- var program = gltfRuntime.programs[technique.program];
1210
- var states = technique.states;
1211
- var vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"];
1212
- var pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
1213
- var newVertexShader = "";
1214
- var newPixelShader = "";
1215
- var vertexTokenizer = new Tokenizer(vertexShader);
1216
- var pixelTokenizer = new Tokenizer(pixelShader);
1217
- var unTreatedUniforms = {};
1218
- var uniforms = [];
1219
- var attributes = [];
1220
- var samplers = [];
1221
- // Fill uniform, sampler2D and attributes
1222
- for (var unif in technique.uniforms) {
1223
- var uniform = technique.uniforms[unif];
1224
- var uniformParameter = technique.parameters[uniform];
1225
- unTreatedUniforms[unif] = uniformParameter;
1226
- if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
1227
- var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1228
- if (transformIndex !== -1) {
1229
- uniforms.push(babylonTransforms[transformIndex]);
1230
- delete unTreatedUniforms[unif];
1231
- }
1232
- else {
1233
- uniforms.push(unif);
1234
- }
1235
- }
1236
- else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
1237
- samplers.push(unif);
1238
- }
1239
- else {
1240
- uniforms.push(unif);
1241
- }
1242
- }
1243
- for (var attr in technique.attributes) {
1244
- var attribute = technique.attributes[attr];
1245
- var attributeParameter = technique.parameters[attribute];
1246
- if (attributeParameter.semantic) {
1247
- var name_1 = getAttribute(attributeParameter);
1248
- if (name_1) {
1249
- attributes.push(name_1);
1250
- }
1251
- }
1252
- }
1253
- // Configure vertex shader
1254
- while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
1255
- var tokenType = vertexTokenizer.currentToken;
1256
- if (tokenType !== ETokenType.IDENTIFIER) {
1257
- newVertexShader += vertexTokenizer.currentString;
1258
- continue;
1259
- }
1260
- var foundAttribute = false;
1261
- for (var attr in technique.attributes) {
1262
- var attribute = technique.attributes[attr];
1263
- var attributeParameter = technique.parameters[attribute];
1264
- if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
1265
- newVertexShader += getAttribute(attributeParameter);
1266
- foundAttribute = true;
1267
- break;
1268
- }
1269
- }
1270
- if (foundAttribute) {
1271
- continue;
1272
- }
1273
- newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
1274
- }
1275
- // Configure pixel shader
1276
- while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
1277
- var tokenType = pixelTokenizer.currentToken;
1278
- if (tokenType !== ETokenType.IDENTIFIER) {
1279
- newPixelShader += pixelTokenizer.currentString;
1280
- continue;
1281
- }
1282
- newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
1283
- }
1284
- // Create shader material
1285
- var shaderPath = {
1286
- vertex: program.vertexShader + id,
1287
- fragment: program.fragmentShader + id
1288
- };
1289
- var options = {
1290
- attributes: attributes,
1291
- uniforms: uniforms,
1292
- samplers: samplers,
1293
- needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
1294
- };
1295
- Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
1296
- Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
1297
- var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
1298
- shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
1299
- shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
1300
- shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1301
- if (states && states.functions) {
1302
- var functions = states.functions;
1303
- if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
1304
- shaderMaterial.backFaceCulling = false;
1305
- }
1306
- var blendFunc = functions.blendFuncSeparate;
1307
- if (blendFunc) {
1308
- if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
1309
- shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;
1310
- }
1311
- else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
1312
- shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;
1313
- }
1314
- else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
1315
- shaderMaterial.alphaMode = Constants.ALPHA_ADD;
1316
- }
1317
- else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
1318
- shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;
1319
- }
1320
- else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
1321
- shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;
1322
- }
1323
- else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
1324
- shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;
1325
- }
1326
- }
1327
- }
1328
- };
1329
- return GLTFLoaderBase;
1330
- }());
1331
- export { GLTFLoaderBase };
1332
- /**
1333
- * glTF V1 Loader
1334
- * @hidden
1335
- */
1336
- var GLTFLoader = /** @class */ (function () {
1337
- function GLTFLoader() {
1338
- }
1339
- GLTFLoader.RegisterExtension = function (extension) {
1340
- if (GLTFLoader.Extensions[extension.name]) {
1341
- Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
1342
- return;
1343
- }
1344
- GLTFLoader.Extensions[extension.name] = extension;
1345
- };
1346
- GLTFLoader.prototype.dispose = function () {
1347
- // do nothing
1348
- };
1349
- GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {
1350
- var _this = this;
1351
- scene.useRightHandedSystem = true;
1352
- GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1353
- gltfRuntime.assetContainer = assetContainer;
1354
- gltfRuntime.importOnlyMeshes = true;
1355
- if (meshesNames === "") {
1356
- gltfRuntime.importMeshesNames = [];
1357
- }
1358
- else if (typeof meshesNames === "string") {
1359
- gltfRuntime.importMeshesNames = [meshesNames];
1360
- }
1361
- else if (meshesNames && !(meshesNames instanceof Array)) {
1362
- gltfRuntime.importMeshesNames = [meshesNames];
1363
- }
1364
- else {
1365
- gltfRuntime.importMeshesNames = [];
1366
- Tools.Warn("Argument meshesNames must be of type string or string[]");
1367
- }
1368
- // Create nodes
1369
- _this._createNodes(gltfRuntime);
1370
- var meshes = new Array();
1371
- var skeletons = new Array();
1372
- // Fill arrays of meshes and skeletons
1373
- for (var nde in gltfRuntime.nodes) {
1374
- var node = gltfRuntime.nodes[nde];
1375
- if (node.babylonNode instanceof AbstractMesh) {
1376
- meshes.push(node.babylonNode);
1377
- }
1378
- }
1379
- for (var skl in gltfRuntime.skins) {
1380
- var skin = gltfRuntime.skins[skl];
1381
- if (skin.babylonSkeleton instanceof Skeleton) {
1382
- skeletons.push(skin.babylonSkeleton);
1383
- }
1384
- }
1385
- // Load buffers, shaders, materials, etc.
1386
- _this._loadBuffersAsync(gltfRuntime, function () {
1387
- _this._loadShadersAsync(gltfRuntime, function () {
1388
- importMaterials(gltfRuntime);
1389
- postLoad(gltfRuntime);
1390
- if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
1391
- onSuccess(meshes, skeletons);
1392
- }
1393
- });
1394
- }, onProgress);
1395
- if (GLTFFileLoader.IncrementalLoading && onSuccess) {
1396
- onSuccess(meshes, skeletons);
1397
- }
1398
- }, onError);
1399
- return true;
1400
- };
1401
- /**
1402
- * Imports one or more meshes from a loaded gltf file and adds them to the scene
1403
- * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
1404
- * @param scene the scene the meshes should be added to
1405
- * @param assetContainer defines the asset container to use (can be null)
1406
- * @param data gltf data containing information of the meshes in a loaded file
1407
- * @param rootUrl root url to load from
1408
- * @param onProgress event that fires when loading progress has occured
1409
- * @returns a promise containg the loaded meshes, particles, skeletons and animations
1410
- */
1411
- GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, assetContainer, data, rootUrl, onProgress) {
1412
- var _this = this;
1413
- return new Promise(function (resolve, reject) {
1414
- _this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, function (meshes, skeletons) {
1415
- resolve({
1416
- meshes: meshes,
1417
- particleSystems: [],
1418
- skeletons: skeletons,
1419
- animationGroups: [],
1420
- lights: [],
1421
- transformNodes: [],
1422
- geometries: []
1423
- });
1424
- }, onProgress, function (message) {
1425
- reject(new Error(message));
1426
- });
1427
- });
1428
- };
1429
- GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
1430
- var _this = this;
1431
- scene.useRightHandedSystem = true;
1432
- GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1433
- // Load runtime extensios
1434
- GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
1435
- // Create nodes
1436
- _this._createNodes(gltfRuntime);
1437
- // Load buffers, shaders, materials, etc.
1438
- _this._loadBuffersAsync(gltfRuntime, function () {
1439
- _this._loadShadersAsync(gltfRuntime, function () {
1440
- importMaterials(gltfRuntime);
1441
- postLoad(gltfRuntime);
1442
- if (!GLTFFileLoader.IncrementalLoading) {
1443
- onSuccess();
1444
- }
1445
- });
1446
- });
1447
- if (GLTFFileLoader.IncrementalLoading) {
1448
- onSuccess();
1449
- }
1450
- }, onError);
1451
- }, onError);
1452
- };
1453
- /**
1454
- * Imports all objects from a loaded gltf file and adds them to the scene
1455
- * @param scene the scene the objects should be added to
1456
- * @param data gltf data containing information of the meshes in a loaded file
1457
- * @param rootUrl root url to load from
1458
- * @param onProgress event that fires when loading progress has occured
1459
- * @returns a promise which completes when objects have been loaded to the scene
1460
- */
1461
- GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
1462
- var _this = this;
1463
- return new Promise(function (resolve, reject) {
1464
- _this._loadAsync(scene, data, rootUrl, function () {
1465
- resolve();
1466
- }, onProgress, function (message) {
1467
- reject(new Error(message));
1468
- });
1469
- });
1470
- };
1471
- GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
1472
- var hasShaders = false;
1473
- var processShader = function (sha, shader) {
1474
- GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
1475
- if (shaderString instanceof ArrayBuffer) {
1476
- return;
1477
- }
1478
- gltfRuntime.loadedShaderCount++;
1479
- if (shaderString) {
1480
- Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
1481
- }
1482
- if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
1483
- onload();
1484
- }
1485
- }, function () {
1486
- Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
1487
- });
1488
- };
1489
- for (var sha in gltfRuntime.shaders) {
1490
- hasShaders = true;
1491
- var shader = gltfRuntime.shaders[sha];
1492
- if (shader) {
1493
- processShader.bind(this, sha, shader)();
1494
- }
1495
- else {
1496
- Tools.Error("No shader named: " + sha);
1497
- }
1498
- }
1499
- if (!hasShaders) {
1500
- onload();
1501
- }
1502
- };
1503
- GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
1504
- var hasBuffers = false;
1505
- var processBuffer = function (buf, buffer) {
1506
- GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
1507
- gltfRuntime.loadedBufferCount++;
1508
- if (bufferView) {
1509
- if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
1510
- Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
1511
- }
1512
- gltfRuntime.loadedBufferViews[buf] = bufferView;
1513
- }
1514
- if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
1515
- onLoad();
1516
- }
1517
- }, function () {
1518
- Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
1519
- });
1520
- };
1521
- for (var buf in gltfRuntime.buffers) {
1522
- hasBuffers = true;
1523
- var buffer = gltfRuntime.buffers[buf];
1524
- if (buffer) {
1525
- processBuffer.bind(this, buf, buffer)();
1526
- }
1527
- else {
1528
- Tools.Error("No buffer named: " + buf);
1529
- }
1530
- }
1531
- if (!hasBuffers) {
1532
- onLoad();
1533
- }
1534
- };
1535
- GLTFLoader.prototype._createNodes = function (gltfRuntime) {
1536
- var currentScene = gltfRuntime.currentScene;
1537
- if (currentScene) {
1538
- // Only one scene even if multiple scenes are defined
1539
- for (var i = 0; i < currentScene.nodes.length; i++) {
1540
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1541
- }
1542
- }
1543
- else {
1544
- // Load all scenes
1545
- for (var thing in gltfRuntime.scenes) {
1546
- currentScene = gltfRuntime.scenes[thing];
1547
- for (var i = 0; i < currentScene.nodes.length; i++) {
1548
- traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1549
- }
1550
- }
1551
- }
1552
- };
1553
- GLTFLoader.Extensions = {};
1554
- return GLTFLoader;
1555
- }());
1556
- export { GLTFLoader };
1557
- /** @hidden */
1558
- var GLTFLoaderExtension = /** @class */ (function () {
1559
- function GLTFLoaderExtension(name) {
1560
- this._name = name;
1561
- }
1562
- Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
1563
- get: function () {
1564
- return this._name;
1565
- },
1566
- enumerable: false,
1567
- configurable: true
1568
- });
1569
- /**
1570
- * Defines an override for loading the runtime
1571
- * Return true to stop further extensions from loading the runtime
1572
- */
1573
- GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1574
- return false;
1575
- };
1576
- /**
1577
- * Defines an onverride for creating gltf runtime
1578
- * Return true to stop further extensions from creating the runtime
1579
- */
1580
- GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1581
- return false;
1582
- };
1583
- /**
1584
- * Defines an override for loading buffers
1585
- * Return true to stop further extensions from loading this buffer
1586
- */
1587
- GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1588
- return false;
1589
- };
1590
- /**
1591
- * Defines an override for loading texture buffers
1592
- * Return true to stop further extensions from loading this texture data
1593
- */
1594
- GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1595
- return false;
1596
- };
1597
- /**
1598
- * Defines an override for creating textures
1599
- * Return true to stop further extensions from loading this texture
1600
- */
1601
- GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1602
- return false;
1603
- };
1604
- /**
1605
- * Defines an override for loading shader strings
1606
- * Return true to stop further extensions from loading this shader data
1607
- */
1608
- GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1609
- return false;
1610
- };
1611
- /**
1612
- * Defines an override for loading materials
1613
- * Return true to stop further extensions from loading this material
1614
- */
1615
- GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1616
- return false;
1617
- };
1618
- // ---------
1619
- // Utilities
1620
- // ---------
1621
- GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1622
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1623
- return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
1624
- }, function () {
1625
- setTimeout(function () {
1626
- if (!onSuccess) {
1627
- return;
1628
- }
1629
- onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
1630
- });
1631
- });
1632
- };
1633
- GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1634
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1635
- return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
1636
- }, function () {
1637
- setTimeout(function () {
1638
- onSuccess();
1639
- });
1640
- });
1641
- };
1642
- GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1643
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1644
- return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1645
- }, function () {
1646
- GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1647
- });
1648
- };
1649
- GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
1650
- GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
1651
- if (buffer) {
1652
- GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1653
- }
1654
- }, onError);
1655
- };
1656
- GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1657
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1658
- return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1659
- }, function () {
1660
- GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1661
- });
1662
- };
1663
- GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1664
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1665
- return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1666
- }, function () {
1667
- GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1668
- });
1669
- };
1670
- GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1671
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1672
- return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1673
- }, function () {
1674
- GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1675
- });
1676
- };
1677
- GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1678
- GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
1679
- return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1680
- }, function () {
1681
- GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1682
- });
1683
- };
1684
- GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
1685
- for (var extensionName in GLTFLoader.Extensions) {
1686
- var loaderExtension = GLTFLoader.Extensions[extensionName];
1687
- if (func(loaderExtension)) {
1688
- return;
1689
- }
1690
- }
1691
- defaultFunc();
1692
- };
1693
- return GLTFLoaderExtension;
1694
- }());
1695
- export { GLTFLoaderExtension };
1696
- GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
1
+ import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType } from "./glTFLoaderInterfaces";
2
+ import { Quaternion, Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js";
3
+ import { Color3 } from "@babylonjs/core/Maths/math.color.js";
4
+ import { Tools } from "@babylonjs/core/Misc/tools.js";
5
+ import { Camera } from "@babylonjs/core/Cameras/camera.js";
6
+ import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera.js";
7
+ import { Animation } from "@babylonjs/core/Animations/animation.js";
8
+ import { Bone } from "@babylonjs/core/Bones/bone.js";
9
+ import { Skeleton } from "@babylonjs/core/Bones/skeleton.js";
10
+ import { Effect } from "@babylonjs/core/Materials/effect.js";
11
+ import { Material } from "@babylonjs/core/Materials/material.js";
12
+ import { MultiMaterial } from "@babylonjs/core/Materials/multiMaterial.js";
13
+ import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js";
14
+ import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial.js";
15
+ import { Texture } from "@babylonjs/core/Materials/Textures/texture.js";
16
+ import { VertexData } from "@babylonjs/core/Meshes/mesh.vertexData.js";
17
+ import { VertexBuffer } from "@babylonjs/core/Buffers/buffer.js";
18
+ import { Geometry } from "@babylonjs/core/Meshes/geometry.js";
19
+ import { SubMesh } from "@babylonjs/core/Meshes/subMesh.js";
20
+ import { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js";
21
+ import { Mesh } from "@babylonjs/core/Meshes/mesh.js";
22
+ import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js";
23
+ import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js";
24
+ import { PointLight } from "@babylonjs/core/Lights/pointLight.js";
25
+ import { SpotLight } from "@babylonjs/core/Lights/spotLight.js";
26
+ import { GLTFUtils } from "./glTFLoaderUtils";
27
+ import { GLTFFileLoader } from "../glTFFileLoader";
28
+ import { Constants } from "@babylonjs/core/Engines/constants.js";
29
+ /**
30
+ * Tokenizer. Used for shaders compatibility
31
+ * Automatically map world, view, projection, worldViewProjection, attributes and so on
32
+ */
33
+ var ETokenType;
34
+ (function (ETokenType) {
35
+ ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
36
+ ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
37
+ ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
38
+ })(ETokenType || (ETokenType = {}));
39
+ var Tokenizer = /** @class */ (function () {
40
+ function Tokenizer(toParse) {
41
+ this._pos = 0;
42
+ this.currentToken = ETokenType.UNKNOWN;
43
+ this.currentIdentifier = "";
44
+ this.currentString = "";
45
+ this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
46
+ this._toParse = toParse;
47
+ this._maxPos = toParse.length;
48
+ }
49
+ Tokenizer.prototype.getNextToken = function () {
50
+ if (this.isEnd()) {
51
+ return ETokenType.END_OF_INPUT;
52
+ }
53
+ this.currentString = this.read();
54
+ this.currentToken = ETokenType.UNKNOWN;
55
+ if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
56
+ this.currentToken = ETokenType.IDENTIFIER;
57
+ this.currentIdentifier = this.currentString;
58
+ while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === "_")) {
59
+ this.currentIdentifier += this.currentString;
60
+ this.forward();
61
+ }
62
+ }
63
+ return this.currentToken;
64
+ };
65
+ Tokenizer.prototype.peek = function () {
66
+ return this._toParse[this._pos];
67
+ };
68
+ Tokenizer.prototype.read = function () {
69
+ return this._toParse[this._pos++];
70
+ };
71
+ Tokenizer.prototype.forward = function () {
72
+ this._pos++;
73
+ };
74
+ Tokenizer.prototype.isEnd = function () {
75
+ return this._pos >= this._maxPos;
76
+ };
77
+ return Tokenizer;
78
+ }());
79
+ /**
80
+ * Values
81
+ */
82
+ var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
83
+ var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
84
+ var glTFAnimationPaths = ["translation", "rotation", "scale"];
85
+ var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
86
+ /**
87
+ * Parse
88
+ * @param parsedBuffers
89
+ * @param gltfRuntime
90
+ */
91
+ var parseBuffers = function (parsedBuffers, gltfRuntime) {
92
+ for (var buf in parsedBuffers) {
93
+ var parsedBuffer = parsedBuffers[buf];
94
+ gltfRuntime.buffers[buf] = parsedBuffer;
95
+ gltfRuntime.buffersCount++;
96
+ }
97
+ };
98
+ var parseShaders = function (parsedShaders, gltfRuntime) {
99
+ for (var sha in parsedShaders) {
100
+ var parsedShader = parsedShaders[sha];
101
+ gltfRuntime.shaders[sha] = parsedShader;
102
+ gltfRuntime.shaderscount++;
103
+ }
104
+ };
105
+ var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
106
+ for (var object in parsedObjects) {
107
+ var parsedObject = parsedObjects[object];
108
+ gltfRuntime[runtimeProperty][object] = parsedObject;
109
+ }
110
+ };
111
+ /**
112
+ * Utils
113
+ * @param buffer
114
+ */
115
+ var normalizeUVs = function (buffer) {
116
+ if (!buffer) {
117
+ return;
118
+ }
119
+ for (var i = 0; i < buffer.length / 2; i++) {
120
+ buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
121
+ }
122
+ };
123
+ var getAttribute = function (attributeParameter) {
124
+ if (attributeParameter.semantic === "NORMAL") {
125
+ return "normal";
126
+ }
127
+ else if (attributeParameter.semantic === "POSITION") {
128
+ return "position";
129
+ }
130
+ else if (attributeParameter.semantic === "JOINT") {
131
+ return "matricesIndices";
132
+ }
133
+ else if (attributeParameter.semantic === "WEIGHT") {
134
+ return "matricesWeights";
135
+ }
136
+ else if (attributeParameter.semantic === "COLOR") {
137
+ return "color";
138
+ }
139
+ else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
140
+ var channel = Number(attributeParameter.semantic.split("_")[1]);
141
+ return "uv" + (channel === 0 ? "" : channel + 1);
142
+ }
143
+ return null;
144
+ };
145
+ /**
146
+ * Loads and creates animations
147
+ * @param gltfRuntime
148
+ */
149
+ var loadAnimations = function (gltfRuntime) {
150
+ for (var anim in gltfRuntime.animations) {
151
+ var animation = gltfRuntime.animations[anim];
152
+ if (!animation.channels || !animation.samplers) {
153
+ continue;
154
+ }
155
+ var lastAnimation = null;
156
+ for (var i = 0; i < animation.channels.length; i++) {
157
+ // Get parameters and load buffers
158
+ var channel = animation.channels[i];
159
+ var sampler = animation.samplers[channel.sampler];
160
+ if (!sampler) {
161
+ continue;
162
+ }
163
+ var inputData = null;
164
+ var outputData = null;
165
+ if (animation.parameters) {
166
+ inputData = animation.parameters[sampler.input];
167
+ outputData = animation.parameters[sampler.output];
168
+ }
169
+ else {
170
+ inputData = sampler.input;
171
+ outputData = sampler.output;
172
+ }
173
+ var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
174
+ var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
175
+ var targetId = channel.target.id;
176
+ var targetNode = gltfRuntime.scene.getNodeById(targetId);
177
+ if (targetNode === null) {
178
+ targetNode = gltfRuntime.scene.getNodeByName(targetId);
179
+ }
180
+ if (targetNode === null) {
181
+ Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetId + " to attach to");
182
+ continue;
183
+ }
184
+ var isBone = targetNode instanceof Bone;
185
+ // Get target path (position, rotation or scaling)
186
+ var targetPath = channel.target.path;
187
+ var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
188
+ if (targetPathIndex !== -1) {
189
+ targetPath = babylonAnimationPaths[targetPathIndex];
190
+ }
191
+ // Determine animation type
192
+ var animationType = Animation.ANIMATIONTYPE_MATRIX;
193
+ if (!isBone) {
194
+ if (targetPath === "rotationQuaternion") {
195
+ animationType = Animation.ANIMATIONTYPE_QUATERNION;
196
+ targetNode.rotationQuaternion = new Quaternion();
197
+ }
198
+ else {
199
+ animationType = Animation.ANIMATIONTYPE_VECTOR3;
200
+ }
201
+ }
202
+ // Create animation and key frames
203
+ var babylonAnimation = null;
204
+ var keys = [];
205
+ var arrayOffset = 0;
206
+ var modifyKey = false;
207
+ if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
208
+ babylonAnimation = lastAnimation;
209
+ modifyKey = true;
210
+ }
211
+ if (!modifyKey) {
212
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
213
+ babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
214
+ gltfRuntime.scene._blockEntityCollection = false;
215
+ }
216
+ // For each frame
217
+ for (var j = 0; j < bufferInput.length; j++) {
218
+ var value = null;
219
+ if (targetPath === "rotationQuaternion") {
220
+ // VEC4
221
+ value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
222
+ arrayOffset += 4;
223
+ }
224
+ else {
225
+ // Position and scaling are VEC3
226
+ value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
227
+ arrayOffset += 3;
228
+ }
229
+ if (isBone) {
230
+ var bone = targetNode;
231
+ var translation = Vector3.Zero();
232
+ var rotationQuaternion = new Quaternion();
233
+ var scaling = Vector3.Zero();
234
+ // Warning on decompose
235
+ var mat = bone.getBaseMatrix();
236
+ if (modifyKey && lastAnimation) {
237
+ mat = lastAnimation.getKeys()[j].value;
238
+ }
239
+ mat.decompose(scaling, rotationQuaternion, translation);
240
+ if (targetPath === "position") {
241
+ translation = value;
242
+ }
243
+ else if (targetPath === "rotationQuaternion") {
244
+ rotationQuaternion = value;
245
+ }
246
+ else {
247
+ scaling = value;
248
+ }
249
+ value = Matrix.Compose(scaling, rotationQuaternion, translation);
250
+ }
251
+ if (!modifyKey) {
252
+ keys.push({
253
+ frame: bufferInput[j],
254
+ value: value,
255
+ });
256
+ }
257
+ else if (lastAnimation) {
258
+ lastAnimation.getKeys()[j].value = value;
259
+ }
260
+ }
261
+ // Finish
262
+ if (!modifyKey && babylonAnimation) {
263
+ babylonAnimation.setKeys(keys);
264
+ targetNode.animations.push(babylonAnimation);
265
+ }
266
+ lastAnimation = babylonAnimation;
267
+ gltfRuntime.scene.stopAnimation(targetNode);
268
+ gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
269
+ }
270
+ }
271
+ };
272
+ /**
273
+ * Returns the bones transformation matrix
274
+ * @param node
275
+ */
276
+ var configureBoneTransformation = function (node) {
277
+ var mat = null;
278
+ if (node.translation || node.rotation || node.scale) {
279
+ var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
280
+ var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
281
+ var position = Vector3.FromArray(node.translation || [0, 0, 0]);
282
+ mat = Matrix.Compose(scale, rotation, position);
283
+ }
284
+ else {
285
+ mat = Matrix.FromArray(node.matrix);
286
+ }
287
+ return mat;
288
+ };
289
+ /**
290
+ * Returns the parent bone
291
+ * @param gltfRuntime
292
+ * @param skins
293
+ * @param jointName
294
+ * @param newSkeleton
295
+ */
296
+ var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
297
+ // Try to find
298
+ for (var i = 0; i < newSkeleton.bones.length; i++) {
299
+ if (newSkeleton.bones[i].name === jointName) {
300
+ return newSkeleton.bones[i];
301
+ }
302
+ }
303
+ // Not found, search in gltf nodes
304
+ var nodes = gltfRuntime.nodes;
305
+ for (var nde in nodes) {
306
+ var node = nodes[nde];
307
+ if (!node.jointName) {
308
+ continue;
309
+ }
310
+ var children = node.children;
311
+ for (var i = 0; i < children.length; i++) {
312
+ var child = gltfRuntime.nodes[children[i]];
313
+ if (!child.jointName) {
314
+ continue;
315
+ }
316
+ if (child.jointName === jointName) {
317
+ var mat = configureBoneTransformation(node);
318
+ var bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
319
+ bone.id = nde;
320
+ return bone;
321
+ }
322
+ }
323
+ }
324
+ return null;
325
+ };
326
+ /**
327
+ * Returns the appropriate root node
328
+ * @param nodesToRoot
329
+ * @param id
330
+ */
331
+ var getNodeToRoot = function (nodesToRoot, id) {
332
+ for (var i = 0; i < nodesToRoot.length; i++) {
333
+ var nodeToRoot = nodesToRoot[i];
334
+ for (var j = 0; j < nodeToRoot.node.children.length; j++) {
335
+ var child = nodeToRoot.node.children[j];
336
+ if (child === id) {
337
+ return nodeToRoot.bone;
338
+ }
339
+ }
340
+ }
341
+ return null;
342
+ };
343
+ /**
344
+ * Returns the node with the joint name
345
+ * @param gltfRuntime
346
+ * @param jointName
347
+ */
348
+ var getJointNode = function (gltfRuntime, jointName) {
349
+ var nodes = gltfRuntime.nodes;
350
+ var node = nodes[jointName];
351
+ if (node) {
352
+ return {
353
+ node: node,
354
+ id: jointName,
355
+ };
356
+ }
357
+ for (var nde in nodes) {
358
+ node = nodes[nde];
359
+ if (node.jointName === jointName) {
360
+ return {
361
+ node: node,
362
+ id: nde,
363
+ };
364
+ }
365
+ }
366
+ return null;
367
+ };
368
+ /**
369
+ * Checks if a nodes is in joints
370
+ * @param skins
371
+ * @param id
372
+ */
373
+ var nodeIsInJoints = function (skins, id) {
374
+ for (var i = 0; i < skins.jointNames.length; i++) {
375
+ if (skins.jointNames[i] === id) {
376
+ return true;
377
+ }
378
+ }
379
+ return false;
380
+ };
381
+ /**
382
+ * Fills the nodes to root for bones and builds hierarchy
383
+ * @param gltfRuntime
384
+ * @param newSkeleton
385
+ * @param skins
386
+ * @param nodesToRoot
387
+ */
388
+ var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
389
+ // Creates nodes for root
390
+ for (var nde in gltfRuntime.nodes) {
391
+ var node = gltfRuntime.nodes[nde];
392
+ var id = nde;
393
+ if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
394
+ continue;
395
+ }
396
+ // Create node to root bone
397
+ var mat = configureBoneTransformation(node);
398
+ var bone = new Bone(node.name || "", newSkeleton, null, mat);
399
+ bone.id = id;
400
+ nodesToRoot.push({ bone: bone, node: node, id: id });
401
+ }
402
+ // Parenting
403
+ for (var i = 0; i < nodesToRoot.length; i++) {
404
+ var nodeToRoot = nodesToRoot[i];
405
+ var children = nodeToRoot.node.children;
406
+ for (var j = 0; j < children.length; j++) {
407
+ var child = null;
408
+ for (var k = 0; k < nodesToRoot.length; k++) {
409
+ if (nodesToRoot[k].id === children[j]) {
410
+ child = nodesToRoot[k];
411
+ break;
412
+ }
413
+ }
414
+ if (child) {
415
+ child.bone._parent = nodeToRoot.bone;
416
+ nodeToRoot.bone.children.push(child.bone);
417
+ }
418
+ }
419
+ }
420
+ };
421
+ /**
422
+ * Imports a skeleton
423
+ * @param gltfRuntime
424
+ * @param skins
425
+ * @param mesh
426
+ * @param newSkeleton
427
+ */
428
+ var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton) {
429
+ if (!newSkeleton) {
430
+ newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
431
+ }
432
+ if (!skins.babylonSkeleton) {
433
+ return newSkeleton;
434
+ }
435
+ // Find the root bones
436
+ var nodesToRoot = [];
437
+ var nodesToRootToAdd = [];
438
+ getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
439
+ newSkeleton.bones = [];
440
+ // Joints
441
+ for (var i = 0; i < skins.jointNames.length; i++) {
442
+ var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
443
+ if (!jointNode) {
444
+ continue;
445
+ }
446
+ var node = jointNode.node;
447
+ if (!node) {
448
+ Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
449
+ continue;
450
+ }
451
+ var id = jointNode.id;
452
+ // Optimize, if the bone already exists...
453
+ var existingBone = gltfRuntime.scene.getBoneById(id);
454
+ if (existingBone) {
455
+ newSkeleton.bones.push(existingBone);
456
+ continue;
457
+ }
458
+ // Search for parent bone
459
+ var foundBone = false;
460
+ var parentBone = null;
461
+ for (var j = 0; j < i; j++) {
462
+ var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
463
+ if (!jointNode_1) {
464
+ continue;
465
+ }
466
+ var joint = jointNode_1.node;
467
+ if (!joint) {
468
+ Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
469
+ continue;
470
+ }
471
+ var children = joint.children;
472
+ if (!children) {
473
+ continue;
474
+ }
475
+ foundBone = false;
476
+ for (var k = 0; k < children.length; k++) {
477
+ if (children[k] === id) {
478
+ parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
479
+ foundBone = true;
480
+ break;
481
+ }
482
+ }
483
+ if (foundBone) {
484
+ break;
485
+ }
486
+ }
487
+ // Create bone
488
+ var mat = configureBoneTransformation(node);
489
+ if (!parentBone && nodesToRoot.length > 0) {
490
+ parentBone = getNodeToRoot(nodesToRoot, id);
491
+ if (parentBone) {
492
+ if (nodesToRootToAdd.indexOf(parentBone) === -1) {
493
+ nodesToRootToAdd.push(parentBone);
494
+ }
495
+ }
496
+ }
497
+ var bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
498
+ bone.id = id;
499
+ }
500
+ // Polish
501
+ var bones = newSkeleton.bones;
502
+ newSkeleton.bones = [];
503
+ for (var i = 0; i < skins.jointNames.length; i++) {
504
+ var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
505
+ if (!jointNode) {
506
+ continue;
507
+ }
508
+ for (var j = 0; j < bones.length; j++) {
509
+ if (bones[j].id === jointNode.id) {
510
+ newSkeleton.bones.push(bones[j]);
511
+ break;
512
+ }
513
+ }
514
+ }
515
+ newSkeleton.prepare();
516
+ // Finish
517
+ for (var i = 0; i < nodesToRootToAdd.length; i++) {
518
+ newSkeleton.bones.push(nodesToRootToAdd[i]);
519
+ }
520
+ return newSkeleton;
521
+ };
522
+ /**
523
+ * Imports a mesh and its geometries
524
+ * @param gltfRuntime
525
+ * @param node
526
+ * @param meshes
527
+ * @param id
528
+ * @param newMesh
529
+ */
530
+ var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
531
+ if (!newMesh) {
532
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
533
+ newMesh = new Mesh(node.name || "", gltfRuntime.scene);
534
+ newMesh._parentContainer = gltfRuntime.assetContainer;
535
+ gltfRuntime.scene._blockEntityCollection = false;
536
+ newMesh.id = id;
537
+ }
538
+ if (!node.babylonNode) {
539
+ return newMesh;
540
+ }
541
+ var subMaterials = [];
542
+ var vertexData = null;
543
+ var verticesStarts = new Array();
544
+ var verticesCounts = new Array();
545
+ var indexStarts = new Array();
546
+ var indexCounts = new Array();
547
+ for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
548
+ var meshId = meshes[meshIndex];
549
+ var mesh = gltfRuntime.meshes[meshId];
550
+ if (!mesh) {
551
+ continue;
552
+ }
553
+ // Positions, normals and UVs
554
+ for (var i = 0; i < mesh.primitives.length; i++) {
555
+ // Temporary vertex data
556
+ var tempVertexData = new VertexData();
557
+ var primitive = mesh.primitives[i];
558
+ if (primitive.mode !== 4) {
559
+ // continue;
560
+ }
561
+ var attributes = primitive.attributes;
562
+ var accessor = null;
563
+ var buffer = null;
564
+ // Set positions, normal and uvs
565
+ for (var semantic in attributes) {
566
+ // Link accessor and buffer view
567
+ accessor = gltfRuntime.accessors[attributes[semantic]];
568
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
569
+ if (semantic === "NORMAL") {
570
+ tempVertexData.normals = new Float32Array(buffer.length);
571
+ tempVertexData.normals.set(buffer);
572
+ }
573
+ else if (semantic === "POSITION") {
574
+ if (GLTFFileLoader.HomogeneousCoordinates) {
575
+ tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
576
+ for (var j = 0; j < buffer.length; j += 4) {
577
+ tempVertexData.positions[j] = buffer[j];
578
+ tempVertexData.positions[j + 1] = buffer[j + 1];
579
+ tempVertexData.positions[j + 2] = buffer[j + 2];
580
+ }
581
+ }
582
+ else {
583
+ tempVertexData.positions = new Float32Array(buffer.length);
584
+ tempVertexData.positions.set(buffer);
585
+ }
586
+ verticesCounts.push(tempVertexData.positions.length);
587
+ }
588
+ else if (semantic.indexOf("TEXCOORD_") !== -1) {
589
+ var channel = Number(semantic.split("_")[1]);
590
+ var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : channel + 1);
591
+ var uvs = new Float32Array(buffer.length);
592
+ uvs.set(buffer);
593
+ normalizeUVs(uvs);
594
+ tempVertexData.set(uvs, uvKind);
595
+ }
596
+ else if (semantic === "JOINT") {
597
+ tempVertexData.matricesIndices = new Float32Array(buffer.length);
598
+ tempVertexData.matricesIndices.set(buffer);
599
+ }
600
+ else if (semantic === "WEIGHT") {
601
+ tempVertexData.matricesWeights = new Float32Array(buffer.length);
602
+ tempVertexData.matricesWeights.set(buffer);
603
+ }
604
+ else if (semantic === "COLOR") {
605
+ tempVertexData.colors = new Float32Array(buffer.length);
606
+ tempVertexData.colors.set(buffer);
607
+ }
608
+ }
609
+ // Indices
610
+ accessor = gltfRuntime.accessors[primitive.indices];
611
+ if (accessor) {
612
+ buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
613
+ tempVertexData.indices = new Int32Array(buffer.length);
614
+ tempVertexData.indices.set(buffer);
615
+ indexCounts.push(tempVertexData.indices.length);
616
+ }
617
+ else {
618
+ // Set indices on the fly
619
+ var indices = [];
620
+ for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
621
+ indices.push(j);
622
+ }
623
+ tempVertexData.indices = new Int32Array(indices);
624
+ indexCounts.push(tempVertexData.indices.length);
625
+ }
626
+ if (!vertexData) {
627
+ vertexData = tempVertexData;
628
+ }
629
+ else {
630
+ vertexData.merge(tempVertexData);
631
+ }
632
+ // Sub material
633
+ var material_1 = gltfRuntime.scene.getMaterialById(primitive.material);
634
+ subMaterials.push(material_1 === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
635
+ // Update vertices start and index start
636
+ verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
637
+ indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
638
+ }
639
+ }
640
+ var material;
641
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
642
+ if (subMaterials.length > 1) {
643
+ material = new MultiMaterial("multimat" + id, gltfRuntime.scene);
644
+ material.subMaterials = subMaterials;
645
+ }
646
+ else {
647
+ material = new StandardMaterial("multimat" + id, gltfRuntime.scene);
648
+ }
649
+ if (subMaterials.length === 1) {
650
+ material = subMaterials[0];
651
+ }
652
+ material._parentContainer = gltfRuntime.assetContainer;
653
+ if (!newMesh.material) {
654
+ newMesh.material = material;
655
+ }
656
+ // Apply geometry
657
+ new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
658
+ newMesh.computeWorldMatrix(true);
659
+ gltfRuntime.scene._blockEntityCollection = false;
660
+ // Apply submeshes
661
+ newMesh.subMeshes = [];
662
+ var index = 0;
663
+ for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
664
+ var meshId = meshes[meshIndex];
665
+ var mesh = gltfRuntime.meshes[meshId];
666
+ if (!mesh) {
667
+ continue;
668
+ }
669
+ for (var i = 0; i < mesh.primitives.length; i++) {
670
+ if (mesh.primitives[i].mode !== 4) {
671
+ //continue;
672
+ }
673
+ SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
674
+ index++;
675
+ }
676
+ }
677
+ // Finish
678
+ return newMesh;
679
+ };
680
+ /**
681
+ * Configure node transformation from position, rotation and scaling
682
+ * @param newNode
683
+ * @param position
684
+ * @param rotation
685
+ * @param scaling
686
+ */
687
+ var configureNode = function (newNode, position, rotation, scaling) {
688
+ if (newNode.position) {
689
+ newNode.position = position;
690
+ }
691
+ if (newNode.rotationQuaternion || newNode.rotation) {
692
+ newNode.rotationQuaternion = rotation;
693
+ }
694
+ if (newNode.scaling) {
695
+ newNode.scaling = scaling;
696
+ }
697
+ };
698
+ /**
699
+ * Configures node from transformation matrix
700
+ * @param newNode
701
+ * @param node
702
+ */
703
+ var configureNodeFromMatrix = function (newNode, node) {
704
+ if (node.matrix) {
705
+ var position = new Vector3(0, 0, 0);
706
+ var rotation = new Quaternion();
707
+ var scaling = new Vector3(0, 0, 0);
708
+ var mat = Matrix.FromArray(node.matrix);
709
+ mat.decompose(scaling, rotation, position);
710
+ configureNode(newNode, position, rotation, scaling);
711
+ }
712
+ else if (node.translation && node.rotation && node.scale) {
713
+ configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
714
+ }
715
+ newNode.computeWorldMatrix(true);
716
+ };
717
+ /**
718
+ * Imports a node
719
+ * @param gltfRuntime
720
+ * @param node
721
+ * @param id
722
+ */
723
+ var importNode = function (gltfRuntime, node, id) {
724
+ var lastNode = null;
725
+ if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
726
+ if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
727
+ return null;
728
+ }
729
+ }
730
+ // Meshes
731
+ if (node.skin) {
732
+ if (node.meshes) {
733
+ var skin = gltfRuntime.skins[node.skin];
734
+ var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
735
+ newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);
736
+ if (newMesh.skeleton === null) {
737
+ newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
738
+ if (!skin.babylonSkeleton) {
739
+ skin.babylonSkeleton = newMesh.skeleton;
740
+ }
741
+ }
742
+ lastNode = newMesh;
743
+ }
744
+ }
745
+ else if (node.meshes) {
746
+ /**
747
+ * Improve meshes property
748
+ */
749
+ var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
750
+ lastNode = newMesh;
751
+ }
752
+ // Lights
753
+ else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
754
+ var light = gltfRuntime.lights[node.light];
755
+ if (light) {
756
+ if (light.type === "ambient") {
757
+ var ambienLight = light[light.type];
758
+ var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
759
+ hemiLight.name = node.name || "";
760
+ if (ambienLight.color) {
761
+ hemiLight.diffuse = Color3.FromArray(ambienLight.color);
762
+ }
763
+ lastNode = hemiLight;
764
+ }
765
+ else if (light.type === "directional") {
766
+ var directionalLight = light[light.type];
767
+ var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
768
+ dirLight.name = node.name || "";
769
+ if (directionalLight.color) {
770
+ dirLight.diffuse = Color3.FromArray(directionalLight.color);
771
+ }
772
+ lastNode = dirLight;
773
+ }
774
+ else if (light.type === "point") {
775
+ var pointLight = light[light.type];
776
+ var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
777
+ ptLight.name = node.name || "";
778
+ if (pointLight.color) {
779
+ ptLight.diffuse = Color3.FromArray(pointLight.color);
780
+ }
781
+ lastNode = ptLight;
782
+ }
783
+ else if (light.type === "spot") {
784
+ var spotLight = light[light.type];
785
+ var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
786
+ spLight.name = node.name || "";
787
+ if (spotLight.color) {
788
+ spLight.diffuse = Color3.FromArray(spotLight.color);
789
+ }
790
+ if (spotLight.fallOfAngle) {
791
+ spLight.angle = spotLight.fallOfAngle;
792
+ }
793
+ if (spotLight.fallOffExponent) {
794
+ spLight.exponent = spotLight.fallOffExponent;
795
+ }
796
+ lastNode = spLight;
797
+ }
798
+ }
799
+ }
800
+ // Cameras
801
+ else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
802
+ var camera = gltfRuntime.cameras[node.camera];
803
+ if (camera) {
804
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
805
+ if (camera.type === "orthographic") {
806
+ var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
807
+ orthoCamera.name = node.name || "";
808
+ orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
809
+ orthoCamera.attachControl();
810
+ lastNode = orthoCamera;
811
+ orthoCamera._parentContainer = gltfRuntime.assetContainer;
812
+ }
813
+ else if (camera.type === "perspective") {
814
+ var perspectiveCamera = camera[camera.type];
815
+ var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);
816
+ persCamera.name = node.name || "";
817
+ persCamera.attachControl();
818
+ if (!perspectiveCamera.aspectRatio) {
819
+ perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
820
+ }
821
+ if (perspectiveCamera.znear && perspectiveCamera.zfar) {
822
+ persCamera.maxZ = perspectiveCamera.zfar;
823
+ persCamera.minZ = perspectiveCamera.znear;
824
+ }
825
+ lastNode = persCamera;
826
+ persCamera._parentContainer = gltfRuntime.assetContainer;
827
+ }
828
+ gltfRuntime.scene._blockEntityCollection = false;
829
+ }
830
+ }
831
+ // Empty node
832
+ if (!node.jointName) {
833
+ if (node.babylonNode) {
834
+ return node.babylonNode;
835
+ }
836
+ else if (lastNode === null) {
837
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
838
+ var dummy = new Mesh(node.name || "", gltfRuntime.scene);
839
+ dummy._parentContainer = gltfRuntime.assetContainer;
840
+ gltfRuntime.scene._blockEntityCollection = false;
841
+ node.babylonNode = dummy;
842
+ lastNode = dummy;
843
+ }
844
+ }
845
+ if (lastNode !== null) {
846
+ if (node.matrix && lastNode instanceof Mesh) {
847
+ configureNodeFromMatrix(lastNode, node);
848
+ }
849
+ else {
850
+ var translation = node.translation || [0, 0, 0];
851
+ var rotation = node.rotation || [0, 0, 0, 1];
852
+ var scale = node.scale || [1, 1, 1];
853
+ configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
854
+ }
855
+ lastNode.updateCache(true);
856
+ node.babylonNode = lastNode;
857
+ }
858
+ return lastNode;
859
+ };
860
+ /**
861
+ * Traverses nodes and creates them
862
+ * @param gltfRuntime
863
+ * @param id
864
+ * @param parent
865
+ * @param meshIncluded
866
+ */
867
+ var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
868
+ if (meshIncluded === void 0) { meshIncluded = false; }
869
+ var node = gltfRuntime.nodes[id];
870
+ var newNode = null;
871
+ if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
872
+ if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
873
+ meshIncluded = true;
874
+ }
875
+ else {
876
+ meshIncluded = false;
877
+ }
878
+ }
879
+ else {
880
+ meshIncluded = true;
881
+ }
882
+ if (!node.jointName && meshIncluded) {
883
+ newNode = importNode(gltfRuntime, node, id);
884
+ if (newNode !== null) {
885
+ newNode.id = id;
886
+ newNode.parent = parent;
887
+ }
888
+ }
889
+ if (node.children) {
890
+ for (var i = 0; i < node.children.length; i++) {
891
+ traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
892
+ }
893
+ }
894
+ };
895
+ /**
896
+ * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
897
+ * @param gltfRuntime
898
+ */
899
+ var postLoad = function (gltfRuntime) {
900
+ // Nodes
901
+ var currentScene = gltfRuntime.currentScene;
902
+ if (currentScene) {
903
+ for (var i = 0; i < currentScene.nodes.length; i++) {
904
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
905
+ }
906
+ }
907
+ else {
908
+ for (var thing in gltfRuntime.scenes) {
909
+ currentScene = gltfRuntime.scenes[thing];
910
+ for (var i = 0; i < currentScene.nodes.length; i++) {
911
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
912
+ }
913
+ }
914
+ }
915
+ // Set animations
916
+ loadAnimations(gltfRuntime);
917
+ for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
918
+ var skeleton = gltfRuntime.scene.skeletons[i];
919
+ gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
920
+ }
921
+ };
922
+ /**
923
+ * onBind shaderrs callback to set uniforms and matrices
924
+ * @param mesh
925
+ * @param gltfRuntime
926
+ * @param unTreatedUniforms
927
+ * @param shaderMaterial
928
+ * @param technique
929
+ * @param material
930
+ * @param onSuccess
931
+ */
932
+ var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
933
+ var materialValues = material.values || technique.parameters;
934
+ for (var unif in unTreatedUniforms) {
935
+ var uniform = unTreatedUniforms[unif];
936
+ var type = uniform.type;
937
+ if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
938
+ if (uniform.semantic && !uniform.source && !uniform.node) {
939
+ GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
940
+ }
941
+ else if (uniform.semantic && (uniform.source || uniform.node)) {
942
+ var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
943
+ if (source === null) {
944
+ source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || "");
945
+ }
946
+ if (source === null) {
947
+ continue;
948
+ }
949
+ GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
950
+ }
951
+ }
952
+ else {
953
+ var value = materialValues[technique.uniforms[unif]];
954
+ if (!value) {
955
+ continue;
956
+ }
957
+ if (type === EParameterType.SAMPLER_2D) {
958
+ var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
959
+ if (texture === null || texture === undefined) {
960
+ continue;
961
+ }
962
+ shaderMaterial.getEffect().setTexture(unif, texture);
963
+ }
964
+ else {
965
+ GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
966
+ }
967
+ }
968
+ }
969
+ onSuccess(shaderMaterial);
970
+ };
971
+ /**
972
+ * Prepare uniforms to send the only one time
973
+ * Loads the appropriate textures
974
+ * @param gltfRuntime
975
+ * @param shaderMaterial
976
+ * @param technique
977
+ * @param material
978
+ */
979
+ var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
980
+ var materialValues = material.values || technique.parameters;
981
+ var techniqueUniforms = technique.uniforms;
982
+ var _loop_1 = function (unif) {
983
+ var uniform = unTreatedUniforms[unif];
984
+ var type = uniform.type;
985
+ var value = materialValues[techniqueUniforms[unif]];
986
+ if (value === undefined) {
987
+ // In case the value is the same for all materials
988
+ value = uniform.value;
989
+ }
990
+ if (!value) {
991
+ return "continue";
992
+ }
993
+ var onLoadTexture = function (uniformName) {
994
+ return function (texture) {
995
+ if (uniform.value && uniformName) {
996
+ // Static uniform
997
+ shaderMaterial.setTexture(uniformName, texture);
998
+ delete unTreatedUniforms[uniformName];
999
+ }
1000
+ };
1001
+ };
1002
+ // Texture (sampler2D)
1003
+ if (type === EParameterType.SAMPLER_2D) {
1004
+ GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
1005
+ }
1006
+ // Others
1007
+ else {
1008
+ if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
1009
+ // Static uniform
1010
+ delete unTreatedUniforms[unif];
1011
+ }
1012
+ }
1013
+ };
1014
+ /**
1015
+ * Prepare values here (not matrices)
1016
+ */
1017
+ for (var unif in unTreatedUniforms) {
1018
+ _loop_1(unif);
1019
+ }
1020
+ };
1021
+ /**
1022
+ * Shader compilation failed
1023
+ * @param program
1024
+ * @param shaderMaterial
1025
+ * @param onError
1026
+ */
1027
+ var onShaderCompileError = function (program, shaderMaterial, onError) {
1028
+ return function (effect, error) {
1029
+ shaderMaterial.dispose(true);
1030
+ onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
1031
+ };
1032
+ };
1033
+ /**
1034
+ * Shader compilation success
1035
+ * @param gltfRuntime
1036
+ * @param shaderMaterial
1037
+ * @param technique
1038
+ * @param material
1039
+ * @param unTreatedUniforms
1040
+ * @param onSuccess
1041
+ */
1042
+ var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
1043
+ return function (_) {
1044
+ prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
1045
+ shaderMaterial.onBind = function (mesh) {
1046
+ onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
1047
+ };
1048
+ };
1049
+ };
1050
+ /**
1051
+ * Returns the appropriate uniform if already handled by babylon
1052
+ * @param tokenizer
1053
+ * @param technique
1054
+ */
1055
+ var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
1056
+ for (var unif in technique.uniforms) {
1057
+ var uniform = technique.uniforms[unif];
1058
+ var uniformParameter = technique.parameters[uniform];
1059
+ if (tokenizer.currentIdentifier === unif) {
1060
+ if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
1061
+ var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1062
+ if (transformIndex !== -1) {
1063
+ delete unTreatedUniforms[unif];
1064
+ return babylonTransforms[transformIndex];
1065
+ }
1066
+ }
1067
+ }
1068
+ }
1069
+ return tokenizer.currentIdentifier;
1070
+ };
1071
+ /**
1072
+ * All shaders loaded. Create materials one by one
1073
+ * @param gltfRuntime
1074
+ */
1075
+ var importMaterials = function (gltfRuntime) {
1076
+ // Create materials
1077
+ for (var mat in gltfRuntime.materials) {
1078
+ GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function () { }, function () { });
1079
+ }
1080
+ };
1081
+ /**
1082
+ * Implementation of the base glTF spec
1083
+ * @hidden
1084
+ */
1085
+ var GLTFLoaderBase = /** @class */ (function () {
1086
+ function GLTFLoaderBase() {
1087
+ }
1088
+ GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
1089
+ var gltfRuntime = {
1090
+ extensions: {},
1091
+ accessors: {},
1092
+ buffers: {},
1093
+ bufferViews: {},
1094
+ meshes: {},
1095
+ lights: {},
1096
+ cameras: {},
1097
+ nodes: {},
1098
+ images: {},
1099
+ textures: {},
1100
+ shaders: {},
1101
+ programs: {},
1102
+ samplers: {},
1103
+ techniques: {},
1104
+ materials: {},
1105
+ animations: {},
1106
+ skins: {},
1107
+ extensionsUsed: [],
1108
+ scenes: {},
1109
+ buffersCount: 0,
1110
+ shaderscount: 0,
1111
+ scene: scene,
1112
+ rootUrl: rootUrl,
1113
+ loadedBufferCount: 0,
1114
+ loadedBufferViews: {},
1115
+ loadedShaderCount: 0,
1116
+ importOnlyMeshes: false,
1117
+ dummyNodes: [],
1118
+ assetContainer: null,
1119
+ };
1120
+ // Parse
1121
+ if (parsedData.extensions) {
1122
+ parseObject(parsedData.extensions, "extensions", gltfRuntime);
1123
+ }
1124
+ if (parsedData.extensionsUsed) {
1125
+ parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
1126
+ }
1127
+ if (parsedData.buffers) {
1128
+ parseBuffers(parsedData.buffers, gltfRuntime);
1129
+ }
1130
+ if (parsedData.bufferViews) {
1131
+ parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
1132
+ }
1133
+ if (parsedData.accessors) {
1134
+ parseObject(parsedData.accessors, "accessors", gltfRuntime);
1135
+ }
1136
+ if (parsedData.meshes) {
1137
+ parseObject(parsedData.meshes, "meshes", gltfRuntime);
1138
+ }
1139
+ if (parsedData.lights) {
1140
+ parseObject(parsedData.lights, "lights", gltfRuntime);
1141
+ }
1142
+ if (parsedData.cameras) {
1143
+ parseObject(parsedData.cameras, "cameras", gltfRuntime);
1144
+ }
1145
+ if (parsedData.nodes) {
1146
+ parseObject(parsedData.nodes, "nodes", gltfRuntime);
1147
+ }
1148
+ if (parsedData.images) {
1149
+ parseObject(parsedData.images, "images", gltfRuntime);
1150
+ }
1151
+ if (parsedData.textures) {
1152
+ parseObject(parsedData.textures, "textures", gltfRuntime);
1153
+ }
1154
+ if (parsedData.shaders) {
1155
+ parseShaders(parsedData.shaders, gltfRuntime);
1156
+ }
1157
+ if (parsedData.programs) {
1158
+ parseObject(parsedData.programs, "programs", gltfRuntime);
1159
+ }
1160
+ if (parsedData.samplers) {
1161
+ parseObject(parsedData.samplers, "samplers", gltfRuntime);
1162
+ }
1163
+ if (parsedData.techniques) {
1164
+ parseObject(parsedData.techniques, "techniques", gltfRuntime);
1165
+ }
1166
+ if (parsedData.materials) {
1167
+ parseObject(parsedData.materials, "materials", gltfRuntime);
1168
+ }
1169
+ if (parsedData.animations) {
1170
+ parseObject(parsedData.animations, "animations", gltfRuntime);
1171
+ }
1172
+ if (parsedData.skins) {
1173
+ parseObject(parsedData.skins, "skins", gltfRuntime);
1174
+ }
1175
+ if (parsedData.scenes) {
1176
+ gltfRuntime.scenes = parsedData.scenes;
1177
+ }
1178
+ if (parsedData.scene && parsedData.scenes) {
1179
+ gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
1180
+ }
1181
+ return gltfRuntime;
1182
+ };
1183
+ GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1184
+ var buffer = gltfRuntime.buffers[id];
1185
+ if (Tools.IsBase64(buffer.uri)) {
1186
+ setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))); });
1187
+ }
1188
+ else {
1189
+ Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
1190
+ if (request) {
1191
+ onError(request.status + " " + request.statusText);
1192
+ }
1193
+ });
1194
+ }
1195
+ };
1196
+ GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1197
+ var texture = gltfRuntime.textures[id];
1198
+ if (!texture || !texture.source) {
1199
+ onError("");
1200
+ return;
1201
+ }
1202
+ if (texture.babylonTexture) {
1203
+ onSuccess(null);
1204
+ return;
1205
+ }
1206
+ var source = gltfRuntime.images[texture.source];
1207
+ if (Tools.IsBase64(source.uri)) {
1208
+ setTimeout(function () { return onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))); });
1209
+ }
1210
+ else {
1211
+ Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
1212
+ if (request) {
1213
+ onError(request.status + " " + request.statusText);
1214
+ }
1215
+ });
1216
+ }
1217
+ };
1218
+ GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess) {
1219
+ var texture = gltfRuntime.textures[id];
1220
+ if (texture.babylonTexture) {
1221
+ onSuccess(texture.babylonTexture);
1222
+ return;
1223
+ }
1224
+ var sampler = gltfRuntime.samplers[texture.sampler];
1225
+ var createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||
1226
+ sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||
1227
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||
1228
+ sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;
1229
+ var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
1230
+ var blob = buffer == null ? new Blob() : new Blob([buffer]);
1231
+ var blobURL = URL.createObjectURL(blob);
1232
+ var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
1233
+ var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
1234
+ if (sampler.wrapS !== undefined) {
1235
+ newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
1236
+ }
1237
+ if (sampler.wrapT !== undefined) {
1238
+ newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
1239
+ }
1240
+ newTexture.name = id;
1241
+ texture.babylonTexture = newTexture;
1242
+ onSuccess(newTexture);
1243
+ };
1244
+ GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1245
+ var shader = gltfRuntime.shaders[id];
1246
+ if (Tools.IsBase64(shader.uri)) {
1247
+ var shaderString = atob(shader.uri.split(",")[1]);
1248
+ if (onSuccess) {
1249
+ onSuccess(shaderString);
1250
+ }
1251
+ }
1252
+ else {
1253
+ Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
1254
+ if (request && onError) {
1255
+ onError(request.status + " " + request.statusText);
1256
+ }
1257
+ });
1258
+ }
1259
+ };
1260
+ GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1261
+ var material = gltfRuntime.materials[id];
1262
+ if (!material.technique) {
1263
+ if (onError) {
1264
+ onError("No technique found.");
1265
+ }
1266
+ return;
1267
+ }
1268
+ var technique = gltfRuntime.techniques[material.technique];
1269
+ if (!technique) {
1270
+ gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;
1271
+ var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
1272
+ defaultMaterial._parentContainer = gltfRuntime.assetContainer;
1273
+ gltfRuntime.scene._blockEntityCollection = false;
1274
+ defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
1275
+ defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1276
+ onSuccess(defaultMaterial);
1277
+ return;
1278
+ }
1279
+ var program = gltfRuntime.programs[technique.program];
1280
+ var states = technique.states;
1281
+ var vertexShader = Effect.ShadersStore[program.vertexShader + "VertexShader"];
1282
+ var pixelShader = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
1283
+ var newVertexShader = "";
1284
+ var newPixelShader = "";
1285
+ var vertexTokenizer = new Tokenizer(vertexShader);
1286
+ var pixelTokenizer = new Tokenizer(pixelShader);
1287
+ var unTreatedUniforms = {};
1288
+ var uniforms = [];
1289
+ var attributes = [];
1290
+ var samplers = [];
1291
+ // Fill uniform, sampler2D and attributes
1292
+ for (var unif in technique.uniforms) {
1293
+ var uniform = technique.uniforms[unif];
1294
+ var uniformParameter = technique.parameters[uniform];
1295
+ unTreatedUniforms[unif] = uniformParameter;
1296
+ if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
1297
+ var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
1298
+ if (transformIndex !== -1) {
1299
+ uniforms.push(babylonTransforms[transformIndex]);
1300
+ delete unTreatedUniforms[unif];
1301
+ }
1302
+ else {
1303
+ uniforms.push(unif);
1304
+ }
1305
+ }
1306
+ else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
1307
+ samplers.push(unif);
1308
+ }
1309
+ else {
1310
+ uniforms.push(unif);
1311
+ }
1312
+ }
1313
+ for (var attr in technique.attributes) {
1314
+ var attribute = technique.attributes[attr];
1315
+ var attributeParameter = technique.parameters[attribute];
1316
+ if (attributeParameter.semantic) {
1317
+ var name_1 = getAttribute(attributeParameter);
1318
+ if (name_1) {
1319
+ attributes.push(name_1);
1320
+ }
1321
+ }
1322
+ }
1323
+ // Configure vertex shader
1324
+ while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
1325
+ var tokenType = vertexTokenizer.currentToken;
1326
+ if (tokenType !== ETokenType.IDENTIFIER) {
1327
+ newVertexShader += vertexTokenizer.currentString;
1328
+ continue;
1329
+ }
1330
+ var foundAttribute = false;
1331
+ for (var attr in technique.attributes) {
1332
+ var attribute = technique.attributes[attr];
1333
+ var attributeParameter = technique.parameters[attribute];
1334
+ if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
1335
+ newVertexShader += getAttribute(attributeParameter);
1336
+ foundAttribute = true;
1337
+ break;
1338
+ }
1339
+ }
1340
+ if (foundAttribute) {
1341
+ continue;
1342
+ }
1343
+ newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
1344
+ }
1345
+ // Configure pixel shader
1346
+ while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
1347
+ var tokenType = pixelTokenizer.currentToken;
1348
+ if (tokenType !== ETokenType.IDENTIFIER) {
1349
+ newPixelShader += pixelTokenizer.currentString;
1350
+ continue;
1351
+ }
1352
+ newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
1353
+ }
1354
+ // Create shader material
1355
+ var shaderPath = {
1356
+ vertex: program.vertexShader + id,
1357
+ fragment: program.fragmentShader + id,
1358
+ };
1359
+ var options = {
1360
+ attributes: attributes,
1361
+ uniforms: uniforms,
1362
+ samplers: samplers,
1363
+ needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,
1364
+ };
1365
+ Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
1366
+ Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
1367
+ var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
1368
+ shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
1369
+ shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
1370
+ shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
1371
+ if (states && states.functions) {
1372
+ var functions = states.functions;
1373
+ if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
1374
+ shaderMaterial.backFaceCulling = false;
1375
+ }
1376
+ var blendFunc = functions.blendFuncSeparate;
1377
+ if (blendFunc) {
1378
+ if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1379
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&
1380
+ blendFunc[2] === EBlendingFunction.ONE &&
1381
+ blendFunc[3] === EBlendingFunction.ONE) {
1382
+ shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;
1383
+ }
1384
+ else if (blendFunc[0] === EBlendingFunction.ONE &&
1385
+ blendFunc[1] === EBlendingFunction.ONE &&
1386
+ blendFunc[2] === EBlendingFunction.ZERO &&
1387
+ blendFunc[3] === EBlendingFunction.ONE) {
1388
+ shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;
1389
+ }
1390
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1391
+ blendFunc[1] === EBlendingFunction.ONE &&
1392
+ blendFunc[2] === EBlendingFunction.ZERO &&
1393
+ blendFunc[3] === EBlendingFunction.ONE) {
1394
+ shaderMaterial.alphaMode = Constants.ALPHA_ADD;
1395
+ }
1396
+ else if (blendFunc[0] === EBlendingFunction.ZERO &&
1397
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1398
+ blendFunc[2] === EBlendingFunction.ONE &&
1399
+ blendFunc[3] === EBlendingFunction.ONE) {
1400
+ shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;
1401
+ }
1402
+ else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&
1403
+ blendFunc[1] === EBlendingFunction.ZERO &&
1404
+ blendFunc[2] === EBlendingFunction.ONE &&
1405
+ blendFunc[3] === EBlendingFunction.ONE) {
1406
+ shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;
1407
+ }
1408
+ else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&
1409
+ blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&
1410
+ blendFunc[2] === EBlendingFunction.ONE &&
1411
+ blendFunc[3] === EBlendingFunction.ONE) {
1412
+ shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;
1413
+ }
1414
+ }
1415
+ }
1416
+ };
1417
+ return GLTFLoaderBase;
1418
+ }());
1419
+ export { GLTFLoaderBase };
1420
+ /**
1421
+ * glTF V1 Loader
1422
+ * @hidden
1423
+ */
1424
+ var GLTFLoader = /** @class */ (function () {
1425
+ function GLTFLoader() {
1426
+ }
1427
+ GLTFLoader.RegisterExtension = function (extension) {
1428
+ if (GLTFLoader.Extensions[extension.name]) {
1429
+ Tools.Error('Tool with the same name "' + extension.name + '" already exists');
1430
+ return;
1431
+ }
1432
+ GLTFLoader.Extensions[extension.name] = extension;
1433
+ };
1434
+ GLTFLoader.prototype.dispose = function () {
1435
+ // do nothing
1436
+ };
1437
+ GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {
1438
+ var _this = this;
1439
+ scene.useRightHandedSystem = true;
1440
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1441
+ gltfRuntime.assetContainer = assetContainer;
1442
+ gltfRuntime.importOnlyMeshes = true;
1443
+ if (meshesNames === "") {
1444
+ gltfRuntime.importMeshesNames = [];
1445
+ }
1446
+ else if (typeof meshesNames === "string") {
1447
+ gltfRuntime.importMeshesNames = [meshesNames];
1448
+ }
1449
+ else if (meshesNames && !(meshesNames instanceof Array)) {
1450
+ gltfRuntime.importMeshesNames = [meshesNames];
1451
+ }
1452
+ else {
1453
+ gltfRuntime.importMeshesNames = [];
1454
+ Tools.Warn("Argument meshesNames must be of type string or string[]");
1455
+ }
1456
+ // Create nodes
1457
+ _this._createNodes(gltfRuntime);
1458
+ var meshes = new Array();
1459
+ var skeletons = new Array();
1460
+ // Fill arrays of meshes and skeletons
1461
+ for (var nde in gltfRuntime.nodes) {
1462
+ var node = gltfRuntime.nodes[nde];
1463
+ if (node.babylonNode instanceof AbstractMesh) {
1464
+ meshes.push(node.babylonNode);
1465
+ }
1466
+ }
1467
+ for (var skl in gltfRuntime.skins) {
1468
+ var skin = gltfRuntime.skins[skl];
1469
+ if (skin.babylonSkeleton instanceof Skeleton) {
1470
+ skeletons.push(skin.babylonSkeleton);
1471
+ }
1472
+ }
1473
+ // Load buffers, shaders, materials, etc.
1474
+ _this._loadBuffersAsync(gltfRuntime, function () {
1475
+ _this._loadShadersAsync(gltfRuntime, function () {
1476
+ importMaterials(gltfRuntime);
1477
+ postLoad(gltfRuntime);
1478
+ if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
1479
+ onSuccess(meshes, skeletons);
1480
+ }
1481
+ });
1482
+ });
1483
+ if (GLTFFileLoader.IncrementalLoading && onSuccess) {
1484
+ onSuccess(meshes, skeletons);
1485
+ }
1486
+ }, onError);
1487
+ return true;
1488
+ };
1489
+ /**
1490
+ * Imports one or more meshes from a loaded gltf file and adds them to the scene
1491
+ * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
1492
+ * @param scene the scene the meshes should be added to
1493
+ * @param assetContainer defines the asset container to use (can be null)
1494
+ * @param data gltf data containing information of the meshes in a loaded file
1495
+ * @param rootUrl root url to load from
1496
+ * @param onProgress event that fires when loading progress has occured
1497
+ * @returns a promise containg the loaded meshes, particles, skeletons and animations
1498
+ */
1499
+ GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, assetContainer, data, rootUrl, onProgress) {
1500
+ var _this = this;
1501
+ return new Promise(function (resolve, reject) {
1502
+ _this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, function (meshes, skeletons) {
1503
+ resolve({
1504
+ meshes: meshes,
1505
+ particleSystems: [],
1506
+ skeletons: skeletons,
1507
+ animationGroups: [],
1508
+ lights: [],
1509
+ transformNodes: [],
1510
+ geometries: [],
1511
+ });
1512
+ }, onProgress, function (message) {
1513
+ reject(new Error(message));
1514
+ });
1515
+ });
1516
+ };
1517
+ GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
1518
+ var _this = this;
1519
+ scene.useRightHandedSystem = true;
1520
+ GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
1521
+ // Load runtime extensios
1522
+ GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
1523
+ // Create nodes
1524
+ _this._createNodes(gltfRuntime);
1525
+ // Load buffers, shaders, materials, etc.
1526
+ _this._loadBuffersAsync(gltfRuntime, function () {
1527
+ _this._loadShadersAsync(gltfRuntime, function () {
1528
+ importMaterials(gltfRuntime);
1529
+ postLoad(gltfRuntime);
1530
+ if (!GLTFFileLoader.IncrementalLoading) {
1531
+ onSuccess();
1532
+ }
1533
+ });
1534
+ });
1535
+ if (GLTFFileLoader.IncrementalLoading) {
1536
+ onSuccess();
1537
+ }
1538
+ }, onError);
1539
+ }, onError);
1540
+ };
1541
+ /**
1542
+ * Imports all objects from a loaded gltf file and adds them to the scene
1543
+ * @param scene the scene the objects should be added to
1544
+ * @param data gltf data containing information of the meshes in a loaded file
1545
+ * @param rootUrl root url to load from
1546
+ * @param onProgress event that fires when loading progress has occured
1547
+ * @returns a promise which completes when objects have been loaded to the scene
1548
+ */
1549
+ GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
1550
+ var _this = this;
1551
+ return new Promise(function (resolve, reject) {
1552
+ _this._loadAsync(scene, data, rootUrl, function () {
1553
+ resolve();
1554
+ }, onProgress, function (message) {
1555
+ reject(new Error(message));
1556
+ });
1557
+ });
1558
+ };
1559
+ GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
1560
+ var hasShaders = false;
1561
+ var processShader = function (sha, shader) {
1562
+ GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
1563
+ if (shaderString instanceof ArrayBuffer) {
1564
+ return;
1565
+ }
1566
+ gltfRuntime.loadedShaderCount++;
1567
+ if (shaderString) {
1568
+ Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
1569
+ }
1570
+ if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
1571
+ onload();
1572
+ }
1573
+ }, function () {
1574
+ Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
1575
+ });
1576
+ };
1577
+ for (var sha in gltfRuntime.shaders) {
1578
+ hasShaders = true;
1579
+ var shader = gltfRuntime.shaders[sha];
1580
+ if (shader) {
1581
+ processShader.bind(this, sha, shader)();
1582
+ }
1583
+ else {
1584
+ Tools.Error("No shader named: " + sha);
1585
+ }
1586
+ }
1587
+ if (!hasShaders) {
1588
+ onload();
1589
+ }
1590
+ };
1591
+ GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad) {
1592
+ var hasBuffers = false;
1593
+ var processBuffer = function (buf, buffer) {
1594
+ GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
1595
+ gltfRuntime.loadedBufferCount++;
1596
+ if (bufferView) {
1597
+ if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
1598
+ Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
1599
+ }
1600
+ gltfRuntime.loadedBufferViews[buf] = bufferView;
1601
+ }
1602
+ if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
1603
+ onLoad();
1604
+ }
1605
+ }, function () {
1606
+ Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
1607
+ });
1608
+ };
1609
+ for (var buf in gltfRuntime.buffers) {
1610
+ hasBuffers = true;
1611
+ var buffer = gltfRuntime.buffers[buf];
1612
+ if (buffer) {
1613
+ processBuffer.bind(this, buf, buffer)();
1614
+ }
1615
+ else {
1616
+ Tools.Error("No buffer named: " + buf);
1617
+ }
1618
+ }
1619
+ if (!hasBuffers) {
1620
+ onLoad();
1621
+ }
1622
+ };
1623
+ GLTFLoader.prototype._createNodes = function (gltfRuntime) {
1624
+ var currentScene = gltfRuntime.currentScene;
1625
+ if (currentScene) {
1626
+ // Only one scene even if multiple scenes are defined
1627
+ for (var i = 0; i < currentScene.nodes.length; i++) {
1628
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1629
+ }
1630
+ }
1631
+ else {
1632
+ // Load all scenes
1633
+ for (var thing in gltfRuntime.scenes) {
1634
+ currentScene = gltfRuntime.scenes[thing];
1635
+ for (var i = 0; i < currentScene.nodes.length; i++) {
1636
+ traverseNodes(gltfRuntime, currentScene.nodes[i], null);
1637
+ }
1638
+ }
1639
+ }
1640
+ };
1641
+ GLTFLoader.Extensions = {};
1642
+ return GLTFLoader;
1643
+ }());
1644
+ export { GLTFLoader };
1645
+ /** @hidden */
1646
+ var GLTFLoaderExtension = /** @class */ (function () {
1647
+ function GLTFLoaderExtension(name) {
1648
+ this._name = name;
1649
+ }
1650
+ Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
1651
+ get: function () {
1652
+ return this._name;
1653
+ },
1654
+ enumerable: false,
1655
+ configurable: true
1656
+ });
1657
+ /**
1658
+ * Defines an override for loading the runtime
1659
+ * Return true to stop further extensions from loading the runtime
1660
+ * @param scene
1661
+ * @param data
1662
+ * @param rootUrl
1663
+ * @param onSuccess
1664
+ * @param onError
1665
+ */
1666
+ GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1667
+ return false;
1668
+ };
1669
+ /**
1670
+ * Defines an onverride for creating gltf runtime
1671
+ * Return true to stop further extensions from creating the runtime
1672
+ * @param gltfRuntime
1673
+ * @param onSuccess
1674
+ * @param onError
1675
+ */
1676
+ GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1677
+ return false;
1678
+ };
1679
+ /**
1680
+ * Defines an override for loading buffers
1681
+ * Return true to stop further extensions from loading this buffer
1682
+ * @param gltfRuntime
1683
+ * @param id
1684
+ * @param onSuccess
1685
+ * @param onError
1686
+ * @param onProgress
1687
+ */
1688
+ GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1689
+ return false;
1690
+ };
1691
+ /**
1692
+ * Defines an override for loading texture buffers
1693
+ * Return true to stop further extensions from loading this texture data
1694
+ * @param gltfRuntime
1695
+ * @param id
1696
+ * @param onSuccess
1697
+ * @param onError
1698
+ */
1699
+ GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1700
+ return false;
1701
+ };
1702
+ /**
1703
+ * Defines an override for creating textures
1704
+ * Return true to stop further extensions from loading this texture
1705
+ * @param gltfRuntime
1706
+ * @param id
1707
+ * @param buffer
1708
+ * @param onSuccess
1709
+ * @param onError
1710
+ */
1711
+ GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1712
+ return false;
1713
+ };
1714
+ /**
1715
+ * Defines an override for loading shader strings
1716
+ * Return true to stop further extensions from loading this shader data
1717
+ * @param gltfRuntime
1718
+ * @param id
1719
+ * @param onSuccess
1720
+ * @param onError
1721
+ */
1722
+ GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1723
+ return false;
1724
+ };
1725
+ /**
1726
+ * Defines an override for loading materials
1727
+ * Return true to stop further extensions from loading this material
1728
+ * @param gltfRuntime
1729
+ * @param id
1730
+ * @param onSuccess
1731
+ * @param onError
1732
+ */
1733
+ GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1734
+ return false;
1735
+ };
1736
+ // ---------
1737
+ // Utilities
1738
+ // ---------
1739
+ GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
1740
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1741
+ return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
1742
+ }, function () {
1743
+ setTimeout(function () {
1744
+ if (!onSuccess) {
1745
+ return;
1746
+ }
1747
+ onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
1748
+ });
1749
+ });
1750
+ };
1751
+ GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
1752
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1753
+ return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
1754
+ }, function () {
1755
+ setTimeout(function () {
1756
+ onSuccess();
1757
+ });
1758
+ });
1759
+ };
1760
+ GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
1761
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1762
+ return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1763
+ }, function () {
1764
+ GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
1765
+ });
1766
+ };
1767
+ GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
1768
+ GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
1769
+ if (buffer) {
1770
+ GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1771
+ }
1772
+ }, onError);
1773
+ };
1774
+ GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
1775
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1776
+ return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1777
+ }, function () {
1778
+ GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
1779
+ });
1780
+ };
1781
+ GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
1782
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1783
+ return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1784
+ }, function () {
1785
+ GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
1786
+ });
1787
+ };
1788
+ GLTFLoaderExtension._LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
1789
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1790
+ return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1791
+ }, function () {
1792
+ GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
1793
+ });
1794
+ };
1795
+ GLTFLoaderExtension._CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
1796
+ GLTFLoaderExtension._ApplyExtensions(function (loaderExtension) {
1797
+ return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
1798
+ }, function () {
1799
+ GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);
1800
+ });
1801
+ };
1802
+ GLTFLoaderExtension._ApplyExtensions = function (func, defaultFunc) {
1803
+ for (var extensionName in GLTFLoader.Extensions) {
1804
+ var loaderExtension = GLTFLoader.Extensions[extensionName];
1805
+ if (func(loaderExtension)) {
1806
+ return;
1807
+ }
1808
+ }
1809
+ defaultFunc();
1810
+ };
1811
+ return GLTFLoaderExtension;
1812
+ }());
1813
+ export { GLTFLoaderExtension };
1814
+ GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
1697
1815
  //# sourceMappingURL=glTFLoader.js.map